xref: /titanic_50/usr/src/uts/common/inet/tcp/tcp.c (revision 9a7670889e9c36ec355371e6b02f2d9084f040dc)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 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 const char tcp_version[] = "%Z%%M%	%I%	%E% SMI";
30 
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/sdt.h>
49 #include <sys/vtrace.h>
50 #include <sys/kmem.h>
51 #include <sys/ethernet.h>
52 #include <sys/cpuvar.h>
53 #include <sys/dlpi.h>
54 #include <sys/multidata.h>
55 #include <sys/multidata_impl.h>
56 #include <sys/pattr.h>
57 #include <sys/policy.h>
58 #include <sys/priv.h>
59 #include <sys/zone.h>
60 
61 #include <sys/errno.h>
62 #include <sys/signal.h>
63 #include <sys/socket.h>
64 #include <sys/sockio.h>
65 #include <sys/isa_defs.h>
66 #include <sys/md5.h>
67 #include <sys/random.h>
68 #include <netinet/in.h>
69 #include <netinet/tcp.h>
70 #include <netinet/ip6.h>
71 #include <netinet/icmp6.h>
72 #include <net/if.h>
73 #include <net/route.h>
74 #include <inet/ipsec_impl.h>
75 
76 #include <inet/common.h>
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip_ndp.h>
81 #include <inet/mi.h>
82 #include <inet/mib2.h>
83 #include <inet/nd.h>
84 #include <inet/optcom.h>
85 #include <inet/snmpcom.h>
86 #include <inet/kstatcom.h>
87 #include <inet/tcp.h>
88 #include <inet/tcp_impl.h>
89 #include <net/pfkeyv2.h>
90 #include <inet/ipsec_info.h>
91 #include <inet/ipdrop.h>
92 #include <inet/tcp_trace.h>
93 
94 #include <inet/ipclassifier.h>
95 #include <inet/ip_ire.h>
96 #include <inet/ip_ftable.h>
97 #include <inet/ip_if.h>
98 #include <inet/ipp_common.h>
99 #include <inet/ip_netinfo.h>
100 #include <sys/squeue.h>
101 #include <inet/kssl/ksslapi.h>
102 #include <sys/tsol/label.h>
103 #include <sys/tsol/tnet.h>
104 #include <sys/sdt.h>
105 #include <rpc/pmap_prot.h>
106 
107 /*
108  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
109  *
110  * (Read the detailed design doc in PSARC case directory)
111  *
112  * The entire tcp state is contained in tcp_t and conn_t structure
113  * which are allocated in tandem using ipcl_conn_create() and passing
114  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
115  * the references on the tcp_t. The tcp_t structure is never compressed
116  * and packets always land on the correct TCP perimeter from the time
117  * eager is created till the time tcp_t dies (as such the old mentat
118  * TCP global queue is not used for detached state and no IPSEC checking
119  * is required). The global queue is still allocated to send out resets
120  * for connection which have no listeners and IP directly calls
121  * tcp_xmit_listeners_reset() which does any policy check.
122  *
123  * Protection and Synchronisation mechanism:
124  *
125  * The tcp data structure does not use any kind of lock for protecting
126  * its state but instead uses 'squeues' for mutual exclusion from various
127  * read and write side threads. To access a tcp member, the thread should
128  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
129  * squeue_fill). Since the squeues allow a direct function call, caller
130  * can pass any tcp function having prototype of edesc_t as argument
131  * (different from traditional STREAMs model where packets come in only
132  * designated entry points). The list of functions that can be directly
133  * called via squeue are listed before the usual function prototype.
134  *
135  * Referencing:
136  *
137  * TCP is MT-Hot and we use a reference based scheme to make sure that the
138  * tcp structure doesn't disappear when its needed. When the application
139  * creates an outgoing connection or accepts an incoming connection, we
140  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
141  * The IP reference is just a symbolic reference since ip_tcpclose()
142  * looks at tcp structure after tcp_close_output() returns which could
143  * have dropped the last TCP reference. So as long as the connection is
144  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
145  * conn_t. The classifier puts its own reference when the connection is
146  * inserted in listen or connected hash. Anytime a thread needs to enter
147  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
148  * on write side or by doing a classify on read side and then puts a
149  * reference on the conn before doing squeue_enter/tryenter/fill. For
150  * read side, the classifier itself puts the reference under fanout lock
151  * to make sure that tcp can't disappear before it gets processed. The
152  * squeue will drop this reference automatically so the called function
153  * doesn't have to do a DEC_REF.
154  *
155  * Opening a new connection:
156  *
157  * The outgoing connection open is pretty simple. ip_tcpopen() does the
158  * work in creating the conn/tcp structure and initializing it. The
159  * squeue assignment is done based on the CPU the application
160  * is running on. So for outbound connections, processing is always done
161  * on application CPU which might be different from the incoming CPU
162  * being interrupted by the NIC. An optimal way would be to figure out
163  * the NIC <-> CPU binding at listen time, and assign the outgoing
164  * connection to the squeue attached to the CPU that will be interrupted
165  * for incoming packets (we know the NIC based on the bind IP address).
166  * This might seem like a problem if more data is going out but the
167  * fact is that in most cases the transmit is ACK driven transmit where
168  * the outgoing data normally sits on TCP's xmit queue waiting to be
169  * transmitted.
170  *
171  * Accepting a connection:
172  *
173  * This is a more interesting case because of various races involved in
174  * establishing a eager in its own perimeter. Read the meta comment on
175  * top of tcp_conn_request(). But briefly, the squeue is picked by
176  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
177  *
178  * Closing a connection:
179  *
180  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
181  * via squeue to do the close and mark the tcp as detached if the connection
182  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
183  * reference but tcp_close() drop IP's reference always. So if tcp was
184  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
185  * and 1 because it is in classifier's connected hash. This is the condition
186  * we use to determine that its OK to clean up the tcp outside of squeue
187  * when time wait expires (check the ref under fanout and conn_lock and
188  * if it is 2, remove it from fanout hash and kill it).
189  *
190  * Although close just drops the necessary references and marks the
191  * tcp_detached state, tcp_close needs to know the tcp_detached has been
192  * set (under squeue) before letting the STREAM go away (because a
193  * inbound packet might attempt to go up the STREAM while the close
194  * has happened and tcp_detached is not set). So a special lock and
195  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
196  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
197  * tcp_detached.
198  *
199  * Special provisions and fast paths:
200  *
201  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
202  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
203  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
204  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
205  * check to send packets directly to tcp_rput_data via squeue. Everyone
206  * else comes through tcp_input() on the read side.
207  *
208  * We also make special provisions for sockfs by marking tcp_issocket
209  * whenever we have only sockfs on top of TCP. This allows us to skip
210  * putting the tcp in acceptor hash since a sockfs listener can never
211  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
212  * since eager has already been allocated and the accept now happens
213  * on acceptor STREAM. There is a big blob of comment on top of
214  * tcp_conn_request explaining the new accept. When socket is POP'd,
215  * sockfs sends us an ioctl to mark the fact and we go back to old
216  * behaviour. Once tcp_issocket is unset, its never set for the
217  * life of that connection.
218  *
219  * IPsec notes :
220  *
221  * Since a packet is always executed on the correct TCP perimeter
222  * all IPsec processing is defered to IP including checking new
223  * connections and setting IPSEC policies for new connection. The
224  * only exception is tcp_xmit_listeners_reset() which is called
225  * directly from IP and needs to policy check to see if TH_RST
226  * can be sent out.
227  *
228  * PFHooks notes :
229  *
230  * For mdt case, one meta buffer contains multiple packets. Mblks for every
231  * packet are assembled and passed to the hooks. When packets are blocked,
232  * or boundary of any packet is changed, the mdt processing is stopped, and
233  * packets of the meta buffer are send to the IP path one by one.
234  */
235 
236 extern major_t TCP6_MAJ;
237 
238 /*
239  * Values for squeue switch:
240  * 1: squeue_enter_nodrain
241  * 2: squeue_enter
242  * 3: squeue_fill
243  */
244 int tcp_squeue_close = 2;
245 int tcp_squeue_wput = 2;
246 
247 squeue_func_t tcp_squeue_close_proc;
248 squeue_func_t tcp_squeue_wput_proc;
249 
250 /*
251  * This controls how tiny a write must be before we try to copy it
252  * into the the mblk on the tail of the transmit queue.  Not much
253  * speedup is observed for values larger than sixteen.  Zero will
254  * disable the optimisation.
255  */
256 int tcp_tx_pull_len = 16;
257 
258 /*
259  * TCP Statistics.
260  *
261  * How TCP statistics work.
262  *
263  * There are two types of statistics invoked by two macros.
264  *
265  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
266  * supposed to be used in non MT-hot paths of the code.
267  *
268  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
269  * supposed to be used for DEBUG purposes and may be used on a hot path.
270  *
271  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
272  * (use "kstat tcp" to get them).
273  *
274  * There is also additional debugging facility that marks tcp_clean_death()
275  * instances and saves them in tcp_t structure. It is triggered by
276  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
277  * tcp_clean_death() calls that counts the number of times each tag was hit. It
278  * is triggered by TCP_CLD_COUNTERS define.
279  *
280  * How to add new counters.
281  *
282  * 1) Add a field in the tcp_stat structure describing your counter.
283  * 2) Add a line in tcp_statistics with the name of the counter.
284  *
285  *    IMPORTANT!! - make sure that both are in sync !!
286  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
287  *
288  * Please avoid using private counters which are not kstat-exported.
289  *
290  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
291  * in tcp_t structure.
292  *
293  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
294  */
295 
296 #ifndef TCP_DEBUG_COUNTER
297 #ifdef DEBUG
298 #define	TCP_DEBUG_COUNTER 1
299 #else
300 #define	TCP_DEBUG_COUNTER 0
301 #endif
302 #endif
303 
304 #define	TCP_CLD_COUNTERS 0
305 
306 #define	TCP_TAG_CLEAN_DEATH 1
307 #define	TCP_MAX_CLEAN_DEATH_TAG 32
308 
309 #ifdef lint
310 static int _lint_dummy_;
311 #endif
312 
313 #if TCP_CLD_COUNTERS
314 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
315 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
316 #elif defined(lint)
317 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
318 #else
319 #define	TCP_CLD_STAT(x)
320 #endif
321 
322 #if TCP_DEBUG_COUNTER
323 #define	TCP_DBGSTAT(x) atomic_add_64(&(tcp_statistics.x.value.ui64), 1)
324 #elif defined(lint)
325 #define	TCP_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
326 #else
327 #define	TCP_DBGSTAT(x)
328 #endif
329 
330 tcp_stat_t tcp_statistics = {
331 	{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
332 	{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
333 	{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
334 	{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
335 	{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
336 	{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
337 	{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
338 	{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
339 	{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
340 	{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
341 	{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
342 	{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
343 	{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
344 	{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
345 	{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
346 	{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
347 	{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
348 	{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
349 	{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
350 	{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
351 	{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
352 	{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
353 	{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
354 	{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
355 	{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
356 	{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
357 	{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
358 	{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
359 	{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
360 	{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
361 	{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
362 	{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
363 	{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
364 	{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
365 	{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
366 	{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
367 	{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
368 	{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
369 	{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
370 	{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
371 	{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
372 	{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
373 	{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
374 	{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
375 	{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
376 	{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
377 	{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
378 	{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
379 	{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
380 	{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
381 	{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
382 	{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
383 	{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
384 	{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
385 	{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
386 	{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
387 	{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
388 	{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
389 	{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
390 	{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
391 	{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
392 	{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
393 	{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
394 	{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
395 	{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
396 	{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
397 	{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
398 	{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
399 	{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
400 	{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
401 	{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
402 	{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
403 	{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
404 	{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
405 	{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
406 	{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
407 	{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
408 	{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
409 	{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
410 	{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
411 	{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
412 	{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
413 	{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
414 	{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
415 	{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
416 	{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
417 	{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
418 	{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
419 	{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
420 	{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
421 	{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
422 	{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
423 	{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
424 	{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
425 };
426 
427 static kstat_t *tcp_kstat;
428 
429 /*
430  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
431  * tcp write side.
432  */
433 #define	CALL_IP_WPUT(connp, q, mp) {					\
434 	ASSERT(((q)->q_flag & QREADR) == 0);				\
435 	TCP_DBGSTAT(tcp_ip_output);					\
436 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
437 }
438 
439 /* Macros for timestamp comparisons */
440 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
441 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
442 
443 /*
444  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
445  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
446  * by adding three components: a time component which grows by 1 every 4096
447  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
448  * a per-connection component which grows by 125000 for every new connection;
449  * and an "extra" component that grows by a random amount centered
450  * approximately on 64000.  This causes the the ISS generator to cycle every
451  * 4.89 hours if no TCP connections are made, and faster if connections are
452  * made.
453  *
454  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
455  * components: a time component which grows by 250000 every second; and
456  * a per-connection component which grows by 125000 for every new connections.
457  *
458  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
459  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
460  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
461  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
462  * password.
463  */
464 #define	ISS_INCR	250000
465 #define	ISS_NSEC_SHT	12
466 
467 static uint32_t tcp_iss_incr_extra;	/* Incremented for each connection */
468 static kmutex_t tcp_iss_key_lock;
469 static MD5_CTX tcp_iss_key;
470 static sin_t	sin_null;	/* Zero address for quick clears */
471 static sin6_t	sin6_null;	/* Zero address for quick clears */
472 
473 /* Packet dropper for TCP IPsec policy drops. */
474 static ipdropper_t tcp_dropper;
475 
476 /*
477  * This implementation follows the 4.3BSD interpretation of the urgent
478  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
479  * incompatible changes in protocols like telnet and rlogin.
480  */
481 #define	TCP_OLD_URP_INTERPRETATION	1
482 
483 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
484 	(TCP_IS_DETACHED(tcp) && \
485 	    (!(tcp)->tcp_hard_binding))
486 
487 /*
488  * TCP reassembly macros.  We hide starting and ending sequence numbers in
489  * b_next and b_prev of messages on the reassembly queue.  The messages are
490  * chained using b_cont.  These macros are used in tcp_reass() so we don't
491  * have to see the ugly casts and assignments.
492  */
493 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
494 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
495 					(mblk_t *)(uintptr_t)(u))
496 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
497 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
498 					(mblk_t *)(uintptr_t)(u))
499 
500 /*
501  * Implementation of TCP Timers.
502  * =============================
503  *
504  * INTERFACE:
505  *
506  * There are two basic functions dealing with tcp timers:
507  *
508  *	timeout_id_t	tcp_timeout(connp, func, time)
509  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
510  *	TCP_TIMER_RESTART(tcp, intvl)
511  *
512  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
513  * after 'time' ticks passed. The function called by timeout() must adhere to
514  * the same restrictions as a driver soft interrupt handler - it must not sleep
515  * or call other functions that might sleep. The value returned is the opaque
516  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
517  * cancel the request. The call to tcp_timeout() may fail in which case it
518  * returns zero. This is different from the timeout(9F) function which never
519  * fails.
520  *
521  * The call-back function 'func' always receives 'connp' as its single
522  * argument. It is always executed in the squeue corresponding to the tcp
523  * structure. The tcp structure is guaranteed to be present at the time the
524  * call-back is called.
525  *
526  * NOTE: The call-back function 'func' is never called if tcp is in
527  * 	the TCPS_CLOSED state.
528  *
529  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
530  * request. locks acquired by the call-back routine should not be held across
531  * the call to tcp_timeout_cancel() or a deadlock may result.
532  *
533  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
534  * Otherwise, it returns an integer value greater than or equal to 0. In
535  * particular, if the call-back function is already placed on the squeue, it can
536  * not be canceled.
537  *
538  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
539  * 	within squeue context corresponding to the tcp instance. Since the
540  *	call-back is also called via the same squeue, there are no race
541  *	conditions described in untimeout(9F) manual page since all calls are
542  *	strictly serialized.
543  *
544  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
545  *	stored in tcp_timer_tid and starts a new one using
546  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
547  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
548  *	field.
549  *
550  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
551  *	call-back may still be called, so it is possible tcp_timer() will be
552  *	called several times. This should not be a problem since tcp_timer()
553  *	should always check the tcp instance state.
554  *
555  *
556  * IMPLEMENTATION:
557  *
558  * TCP timers are implemented using three-stage process. The call to
559  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
560  * when the timer expires. The tcp_timer_callback() arranges the call of the
561  * tcp_timer_handler() function via squeue corresponding to the tcp
562  * instance. The tcp_timer_handler() calls actual requested timeout call-back
563  * and passes tcp instance as an argument to it. Information is passed between
564  * stages using the tcp_timer_t structure which contains the connp pointer, the
565  * tcp call-back to call and the timeout id returned by the timeout(9F).
566  *
567  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
568  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
569  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
570  * returns the pointer to this mblk.
571  *
572  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
573  * looks like a normal mblk without actual dblk attached to it.
574  *
575  * To optimize performance each tcp instance holds a small cache of timer
576  * mblocks. In the current implementation it caches up to two timer mblocks per
577  * tcp instance. The cache is preserved over tcp frees and is only freed when
578  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
579  * timer processing happens on a corresponding squeue, the cache manipulation
580  * does not require any locks. Experiments show that majority of timer mblocks
581  * allocations are satisfied from the tcp cache and do not involve kmem calls.
582  *
583  * The tcp_timeout() places a refhold on the connp instance which guarantees
584  * that it will be present at the time the call-back function fires. The
585  * tcp_timer_handler() drops the reference after calling the call-back, so the
586  * call-back function does not need to manipulate the references explicitly.
587  */
588 
589 typedef struct tcp_timer_s {
590 	conn_t	*connp;
591 	void 	(*tcpt_proc)(void *);
592 	timeout_id_t   tcpt_tid;
593 } tcp_timer_t;
594 
595 static kmem_cache_t *tcp_timercache;
596 kmem_cache_t	*tcp_sack_info_cache;
597 kmem_cache_t	*tcp_iphc_cache;
598 
599 /*
600  * For scalability, we must not run a timer for every TCP connection
601  * in TIME_WAIT state.  To see why, consider (for time wait interval of
602  * 4 minutes):
603  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
604  *
605  * This list is ordered by time, so you need only delete from the head
606  * until you get to entries which aren't old enough to delete yet.
607  * The list consists of only the detached TIME_WAIT connections.
608  *
609  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
610  * becomes detached TIME_WAIT (either by changing the state and already
611  * being detached or the other way around). This means that the TIME_WAIT
612  * state can be extended (up to doubled) if the connection doesn't become
613  * detached for a long time.
614  *
615  * The list manipulations (including tcp_time_wait_next/prev)
616  * are protected by the tcp_time_wait_lock. The content of the
617  * detached TIME_WAIT connections is protected by the normal perimeters.
618  */
619 
620 typedef struct tcp_squeue_priv_s {
621 	kmutex_t	tcp_time_wait_lock;
622 				/* Protects the next 3 globals */
623 	timeout_id_t	tcp_time_wait_tid;
624 	tcp_t		*tcp_time_wait_head;
625 	tcp_t		*tcp_time_wait_tail;
626 	tcp_t		*tcp_free_list;
627 	uint_t		tcp_free_list_cnt;
628 } tcp_squeue_priv_t;
629 
630 /*
631  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
632  * Running it every 5 seconds seems to give the best results.
633  */
634 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
635 
636 /*
637  * To prevent memory hog, limit the number of entries in tcp_free_list
638  * to 1% of available memory / number of cpus
639  */
640 uint_t tcp_free_list_max_cnt = 0;
641 
642 #define	TCP_XMIT_LOWATER	4096
643 #define	TCP_XMIT_HIWATER	49152
644 #define	TCP_RECV_LOWATER	2048
645 #define	TCP_RECV_HIWATER	49152
646 
647 /*
648  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
649  */
650 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
651 
652 #define	TIDUSZ	4096	/* transport interface data unit size */
653 
654 /*
655  * Bind hash list size and has function.  It has to be a power of 2 for
656  * hashing.
657  */
658 #define	TCP_BIND_FANOUT_SIZE	512
659 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
660 /*
661  * Size of listen and acceptor hash list.  It has to be a power of 2 for
662  * hashing.
663  */
664 #define	TCP_FANOUT_SIZE		256
665 
666 #ifdef	_ILP32
667 #define	TCP_ACCEPTOR_HASH(accid)					\
668 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
669 #else
670 #define	TCP_ACCEPTOR_HASH(accid)					\
671 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
672 #endif	/* _ILP32 */
673 
674 #define	IP_ADDR_CACHE_SIZE	2048
675 #define	IP_ADDR_CACHE_HASH(faddr)					\
676 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
677 
678 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
679 #define	TCP_HSP_HASH_SIZE 256
680 
681 #define	TCP_HSP_HASH(addr)					\
682 	(((addr>>24) ^ (addr >>16) ^			\
683 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
684 
685 /*
686  * TCP options struct returned from tcp_parse_options.
687  */
688 typedef struct tcp_opt_s {
689 	uint32_t	tcp_opt_mss;
690 	uint32_t	tcp_opt_wscale;
691 	uint32_t	tcp_opt_ts_val;
692 	uint32_t	tcp_opt_ts_ecr;
693 	tcp_t		*tcp;
694 } tcp_opt_t;
695 
696 /*
697  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
698  */
699 
700 #ifdef _BIG_ENDIAN
701 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
702 	(TCPOPT_TSTAMP << 8) | 10)
703 #else
704 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
705 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
706 #endif
707 
708 /*
709  * Flags returned from tcp_parse_options.
710  */
711 #define	TCP_OPT_MSS_PRESENT	1
712 #define	TCP_OPT_WSCALE_PRESENT	2
713 #define	TCP_OPT_TSTAMP_PRESENT	4
714 #define	TCP_OPT_SACK_OK_PRESENT	8
715 #define	TCP_OPT_SACK_PRESENT	16
716 
717 /* TCP option length */
718 #define	TCPOPT_NOP_LEN		1
719 #define	TCPOPT_MAXSEG_LEN	4
720 #define	TCPOPT_WS_LEN		3
721 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
722 #define	TCPOPT_TSTAMP_LEN	10
723 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
724 #define	TCPOPT_SACK_OK_LEN	2
725 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
726 #define	TCPOPT_REAL_SACK_LEN	4
727 #define	TCPOPT_MAX_SACK_LEN	36
728 #define	TCPOPT_HEADER_LEN	2
729 
730 /* TCP cwnd burst factor. */
731 #define	TCP_CWND_INFINITE	65535
732 #define	TCP_CWND_SS		3
733 #define	TCP_CWND_NORMAL		5
734 
735 /* Maximum TCP initial cwin (start/restart). */
736 #define	TCP_MAX_INIT_CWND	8
737 
738 /*
739  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
740  * either tcp_slow_start_initial or tcp_slow_start_after idle
741  * depending on the caller.  If the upper layer has not used the
742  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
743  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
744  * If the upper layer has changed set the tcp_init_cwnd, just use
745  * it to calculate the tcp_cwnd.
746  */
747 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
748 {									\
749 	if ((tcp)->tcp_init_cwnd == 0) {				\
750 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
751 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
752 	} else {							\
753 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
754 	}								\
755 	tcp->tcp_cwnd_cnt = 0;						\
756 }
757 
758 /* TCP Timer control structure */
759 typedef struct tcpt_s {
760 	pfv_t	tcpt_pfv;	/* The routine we are to call */
761 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
762 } tcpt_t;
763 
764 /* Host Specific Parameter structure */
765 typedef struct tcp_hsp {
766 	struct tcp_hsp	*tcp_hsp_next;
767 	in6_addr_t	tcp_hsp_addr_v6;
768 	in6_addr_t	tcp_hsp_subnet_v6;
769 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
770 	int32_t		tcp_hsp_sendspace;
771 	int32_t		tcp_hsp_recvspace;
772 	int32_t		tcp_hsp_tstamp;
773 } tcp_hsp_t;
774 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
775 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
776 
777 /*
778  * Functions called directly via squeue having a prototype of edesc_t.
779  */
780 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
781 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
782 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
783 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
784 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
785 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
786 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
787 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
788 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
789 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
790 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
791 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
792 
793 
794 /* Prototype for TCP functions */
795 static void	tcp_random_init(void);
796 int		tcp_random(void);
797 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
798 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
799 		    tcp_t *eager);
800 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
801 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
802     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
803     boolean_t user_specified);
804 static void	tcp_closei_local(tcp_t *tcp);
805 static void	tcp_close_detached(tcp_t *tcp);
806 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
807 			mblk_t *idmp, mblk_t **defermp);
808 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
809 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
810 		    in_port_t dstport, uint_t srcid);
811 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
812 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
813 		    uint32_t scope_id);
814 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
815 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
816 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
817 static char	*tcp_display(tcp_t *tcp, char *, char);
818 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
819 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
820 static void	tcp_eager_unlink(tcp_t *tcp);
821 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
822 		    int unixerr);
823 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
824 		    int tlierr, int unixerr);
825 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
826 		    cred_t *cr);
827 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
828 		    char *value, caddr_t cp, cred_t *cr);
829 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
830 		    char *value, caddr_t cp, cred_t *cr);
831 static int	tcp_tpistate(tcp_t *tcp);
832 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
833     int caller_holds_lock);
834 static void	tcp_bind_hash_remove(tcp_t *tcp);
835 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id);
836 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
837 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
838 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
839 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
840 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
841 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
842 static int	tcp_header_init_ipv4(tcp_t *tcp);
843 static int	tcp_header_init_ipv6(tcp_t *tcp);
844 int		tcp_init(tcp_t *tcp, queue_t *q);
845 static int	tcp_init_values(tcp_t *tcp);
846 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
847 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
848 		    t_scalar_t addr_length);
849 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
850 static void	tcp_ip_notify(tcp_t *tcp);
851 static mblk_t	*tcp_ire_mp(mblk_t *mp);
852 static void	tcp_iss_init(tcp_t *tcp);
853 static void	tcp_keepalive_killer(void *arg);
854 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
855 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
856 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
857 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
858 static boolean_t tcp_allow_connopt_set(int level, int name);
859 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
860 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
861 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
862 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
863 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
864 		    mblk_t *mblk);
865 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
866 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
867 		    uchar_t *ptr, uint_t len);
868 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
869 static boolean_t tcp_param_register(tcpparam_t *tcppa, int cnt);
870 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
871 		    caddr_t cp, cred_t *cr);
872 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
873 		    caddr_t cp, cred_t *cr);
874 static void	tcp_iss_key_init(uint8_t *phrase, int len);
875 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
876 		    caddr_t cp, cred_t *cr);
877 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
878 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
879 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
880 static void	tcp_reinit(tcp_t *tcp);
881 static void	tcp_reinit_values(tcp_t *tcp);
882 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
883 		    tcp_t *thisstream, cred_t *cr);
884 
885 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
886 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
887 static boolean_t tcp_send_rst_chk(void);
888 static void	tcp_ss_rexmit(tcp_t *tcp);
889 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
890 static void	tcp_process_options(tcp_t *, tcph_t *);
891 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
892 static void	tcp_rsrv(queue_t *q);
893 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
894 static int	tcp_snmp_state(tcp_t *tcp);
895 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
896 		    cred_t *cr);
897 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
898 		    cred_t *cr);
899 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
900 		    cred_t *cr);
901 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
902 		    cred_t *cr);
903 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
904 		    cred_t *cr);
905 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
906 		    caddr_t cp, cred_t *cr);
907 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
908 		    caddr_t cp, cred_t *cr);
909 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
910 		    cred_t *cr);
911 static void	tcp_timer(void *arg);
912 static void	tcp_timer_callback(void *);
913 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
914     boolean_t random);
915 static in_port_t tcp_get_next_priv_port(const tcp_t *);
916 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
917 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
918 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
919 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
920 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
921 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
922 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
923 		    const int num_sack_blk, int *usable, uint_t *snxt,
924 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
925 		    const int mdt_thres);
926 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
927 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
928 		    const int num_sack_blk, int *usable, uint_t *snxt,
929 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
930 		    const int mdt_thres);
931 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
932 		    int num_sack_blk);
933 static void	tcp_wsrv(queue_t *q);
934 static int	tcp_xmit_end(tcp_t *tcp);
935 static void	tcp_ack_timer(void *arg);
936 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
937 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
938 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
939 		    zoneid_t zoneid);
940 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
941 		    uint32_t ack, int ctl);
942 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr);
943 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr);
944 static int	setmaxps(queue_t *q, int maxpsz);
945 static void	tcp_set_rto(tcp_t *, time_t);
946 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
947 		    boolean_t, boolean_t);
948 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
949 		    boolean_t ipsec_mctl);
950 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
951 		    char *opt, int optlen);
952 static int	tcp_build_hdrs(queue_t *, tcp_t *);
953 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
954 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
955 		    tcph_t *tcph);
956 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
957 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
958 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
959 boolean_t	tcp_reserved_port_check(in_port_t);
960 static tcp_t	*tcp_alloc_temp_tcp(in_port_t);
961 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
962 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
963 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
964 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
965 		    const boolean_t, const uint32_t, const uint32_t,
966 		    const uint32_t, const uint32_t);
967 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
968 		    const uint_t, const uint_t, boolean_t *);
969 static mblk_t	*tcp_lso_info_mp(mblk_t *);
970 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
971 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
972 extern mblk_t	*tcp_timermp_alloc(int);
973 extern void	tcp_timermp_free(tcp_t *);
974 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
975 static void	tcp_stop_lingering(tcp_t *tcp);
976 static void	tcp_close_linger_timeout(void *arg);
977 void		tcp_ddi_init(void);
978 void		tcp_ddi_destroy(void);
979 static void	tcp_kstat_init(void);
980 static void	tcp_kstat_fini(void);
981 static int	tcp_kstat_update(kstat_t *kp, int rw);
982 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
983 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
984 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
985 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
986 			tcph_t *tcph, mblk_t *idmp);
987 static squeue_func_t tcp_squeue_switch(int);
988 
989 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
990 static int	tcp_close(queue_t *, int);
991 static int	tcpclose_accept(queue_t *);
992 static int	tcp_modclose(queue_t *);
993 static void	tcp_wput_mod(queue_t *, mblk_t *);
994 
995 static void	tcp_squeue_add(squeue_t *);
996 static boolean_t tcp_zcopy_check(tcp_t *);
997 static void	tcp_zcopy_notify(tcp_t *);
998 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
999 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
1000 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
1001 
1002 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
1003 
1004 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
1005 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
1006 
1007 /*
1008  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
1009  *
1010  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
1011  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
1012  * (defined in tcp.h) needs to be filled in and passed into the kernel
1013  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
1014  * structure contains the four-tuple of a TCP connection and a range of TCP
1015  * states (specified by ac_start and ac_end). The use of wildcard addresses
1016  * and ports is allowed. Connections with a matching four tuple and a state
1017  * within the specified range will be aborted. The valid states for the
1018  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
1019  * inclusive.
1020  *
1021  * An application which has its connection aborted by this ioctl will receive
1022  * an error that is dependent on the connection state at the time of the abort.
1023  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1024  * though a RST packet has been received.  If the connection state is equal to
1025  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1026  * and all resources associated with the connection will be freed.
1027  */
1028 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1029 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1030 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1031 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *);
1032 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1033 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1034     boolean_t);
1035 
1036 static struct module_info tcp_rinfo =  {
1037 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1038 };
1039 
1040 static struct module_info tcp_winfo =  {
1041 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1042 };
1043 
1044 /*
1045  * Entry points for TCP as a module. It only allows SNMP requests
1046  * to pass through.
1047  */
1048 struct qinit tcp_mod_rinit = {
1049 	(pfi_t)putnext, NULL, tcp_open, ip_snmpmod_close, NULL, &tcp_rinfo,
1050 };
1051 
1052 struct qinit tcp_mod_winit = {
1053 	(pfi_t)ip_snmpmod_wput, NULL, tcp_open, ip_snmpmod_close, NULL,
1054 	&tcp_rinfo
1055 };
1056 
1057 /*
1058  * Entry points for TCP as a device. The normal case which supports
1059  * the TCP functionality.
1060  */
1061 struct qinit tcp_rinit = {
1062 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
1063 };
1064 
1065 struct qinit tcp_winit = {
1066 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1067 };
1068 
1069 /* Initial entry point for TCP in socket mode. */
1070 struct qinit tcp_sock_winit = {
1071 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1072 };
1073 
1074 /*
1075  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1076  * an accept. Avoid allocating data structures since eager has already
1077  * been created.
1078  */
1079 struct qinit tcp_acceptor_rinit = {
1080 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1081 };
1082 
1083 struct qinit tcp_acceptor_winit = {
1084 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1085 };
1086 
1087 /*
1088  * Entry points for TCP loopback (read side only)
1089  */
1090 struct qinit tcp_loopback_rinit = {
1091 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_open, tcp_close, (pfi_t)0,
1092 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1093 };
1094 
1095 struct streamtab tcpinfo = {
1096 	&tcp_rinit, &tcp_winit
1097 };
1098 
1099 extern squeue_func_t tcp_squeue_wput_proc;
1100 extern squeue_func_t tcp_squeue_timer_proc;
1101 
1102 /* Protected by tcp_g_q_lock */
1103 static queue_t	*tcp_g_q;	/* Default queue used during detached closes */
1104 kmutex_t tcp_g_q_lock;
1105 
1106 /* Protected by tcp_hsp_lock */
1107 /*
1108  * XXX The host param mechanism should go away and instead we should use
1109  * the metrics associated with the routes to determine the default sndspace
1110  * and rcvspace.
1111  */
1112 static tcp_hsp_t	**tcp_hsp_hash;	/* Hash table for HSPs */
1113 krwlock_t tcp_hsp_lock;
1114 
1115 /*
1116  * Extra privileged ports. In host byte order.
1117  * Protected by tcp_epriv_port_lock.
1118  */
1119 #define	TCP_NUM_EPRIV_PORTS	64
1120 static int	tcp_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
1121 static uint16_t	tcp_g_epriv_ports[TCP_NUM_EPRIV_PORTS] = { 2049, 4045 };
1122 kmutex_t tcp_epriv_port_lock;
1123 
1124 /*
1125  * The smallest anonymous port in the privileged port range which TCP
1126  * looks for free port.  Use in the option TCP_ANONPRIVBIND.
1127  */
1128 static in_port_t tcp_min_anonpriv_port = 512;
1129 
1130 /* Only modified during _init and _fini thus no locking is needed. */
1131 static caddr_t	tcp_g_nd;	/* Head of 'named dispatch' variable list */
1132 
1133 /* Hint not protected by any lock */
1134 static uint_t	tcp_next_port_to_try;
1135 
1136 
1137 /* TCP bind hash list - all tcp_t with state >= BOUND. */
1138 tf_t	tcp_bind_fanout[TCP_BIND_FANOUT_SIZE];
1139 
1140 /* TCP queue hash list - all tcp_t in case they will be an acceptor. */
1141 static tf_t	tcp_acceptor_fanout[TCP_FANOUT_SIZE];
1142 
1143 /*
1144  * TCP has a private interface for other kernel modules to reserve a
1145  * port range for them to use.  Once reserved, TCP will not use any ports
1146  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1147  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1148  * has to be verified.
1149  *
1150  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1151  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1152  * range is [port a, port b] inclusive.  And each port range is between
1153  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1154  *
1155  * Note that the default anonymous port range starts from 32768.  There is
1156  * no port "collision" between that and the reserved port range.  If there
1157  * is port collision (because the default smallest anonymous port is lowered
1158  * or some apps specifically bind to ports in the reserved port range), the
1159  * system may not be able to reserve a port range even there are enough
1160  * unbound ports as a reserved port range contains consecutive ports .
1161  */
1162 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1163 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1164 #define	TCP_SMALLEST_RESERVED_PORT		10240
1165 #define	TCP_LARGEST_RESERVED_PORT		20480
1166 
1167 /* Structure to represent those reserved port ranges. */
1168 typedef struct tcp_rport_s {
1169 	in_port_t	lo_port;
1170 	in_port_t	hi_port;
1171 	tcp_t		**temp_tcp_array;
1172 } tcp_rport_t;
1173 
1174 /* The reserved port array. */
1175 static tcp_rport_t tcp_reserved_port[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
1176 
1177 /* Locks to protect the tcp_reserved_ports array. */
1178 static krwlock_t tcp_reserved_port_lock;
1179 
1180 /* The number of ranges in the array. */
1181 uint32_t tcp_reserved_port_array_size = 0;
1182 
1183 /*
1184  * MIB-2 stuff for SNMP
1185  * Note: tcpInErrs {tcp 15} is accumulated in ip.c
1186  */
1187 mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */
1188 kstat_t		*tcp_mibkp;	/* kstat exporting tcp_mib data */
1189 
1190 boolean_t tcp_icmp_source_quench = B_FALSE;
1191 /*
1192  * Following assumes TPI alignment requirements stay along 32 bit
1193  * boundaries
1194  */
1195 #define	ROUNDUP32(x) \
1196 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1197 
1198 /* Template for response to info request. */
1199 static struct T_info_ack tcp_g_t_info_ack = {
1200 	T_INFO_ACK,		/* PRIM_type */
1201 	0,			/* TSDU_size */
1202 	T_INFINITE,		/* ETSDU_size */
1203 	T_INVALID,		/* CDATA_size */
1204 	T_INVALID,		/* DDATA_size */
1205 	sizeof (sin_t),		/* ADDR_size */
1206 	0,			/* OPT_size - not initialized here */
1207 	TIDUSZ,			/* TIDU_size */
1208 	T_COTS_ORD,		/* SERV_type */
1209 	TCPS_IDLE,		/* CURRENT_state */
1210 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1211 };
1212 
1213 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1214 	T_INFO_ACK,		/* PRIM_type */
1215 	0,			/* TSDU_size */
1216 	T_INFINITE,		/* ETSDU_size */
1217 	T_INVALID,		/* CDATA_size */
1218 	T_INVALID,		/* DDATA_size */
1219 	sizeof (sin6_t),	/* ADDR_size */
1220 	0,			/* OPT_size - not initialized here */
1221 	TIDUSZ,		/* TIDU_size */
1222 	T_COTS_ORD,		/* SERV_type */
1223 	TCPS_IDLE,		/* CURRENT_state */
1224 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1225 };
1226 
1227 #define	MS	1L
1228 #define	SECONDS	(1000 * MS)
1229 #define	MINUTES	(60 * SECONDS)
1230 #define	HOURS	(60 * MINUTES)
1231 #define	DAYS	(24 * HOURS)
1232 
1233 #define	PARAM_MAX (~(uint32_t)0)
1234 
1235 /* Max size IP datagram is 64k - 1 */
1236 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1237 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1238 /* Max of the above */
1239 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1240 
1241 /* Largest TCP port number */
1242 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1243 
1244 /*
1245  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1246  * layer header.  It has to be a multiple of 4.
1247  */
1248 static tcpparam_t tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1249 #define	tcp_wroff_xtra	tcp_wroff_xtra_param.tcp_param_val
1250 
1251 /*
1252  * All of these are alterable, within the min/max values given, at run time.
1253  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1254  * per the TCP spec.
1255  */
1256 /* BEGIN CSTYLED */
1257 tcpparam_t	tcp_param_arr[] = {
1258  /*min		max		value		name */
1259  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1260  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1261  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1262  { 1,		1024,		1,		"tcp_conn_req_min" },
1263  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1264  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1265  { 0,		10,		0,		"tcp_debug" },
1266  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1267  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1268  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1269  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1270  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1271  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1272  { 1,		255,		64,		"tcp_ipv4_ttl"},
1273  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1274  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1275  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1276  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1277  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1278  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1279  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1280  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1281  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1282  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1283  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1284  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1285  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1286  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1287  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1288  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1289  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1290  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1291  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1292  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1293  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1294  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1295  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1296  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1297 /*
1298  * Question:  What default value should I set for tcp_strong_iss?
1299  */
1300  { 0,		2,		1,		"tcp_strong_iss"},
1301  { 0,		65536,		20,		"tcp_rtt_updates"},
1302  { 0,		1,		1,		"tcp_wscale_always"},
1303  { 0,		1,		0,		"tcp_tstamp_always"},
1304  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1305  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1306  { 0,		16,		2,		"tcp_deferred_acks_max"},
1307  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1308  { 1,		4,		4,		"tcp_slow_start_initial"},
1309  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1310  { 0,		2,		2,		"tcp_sack_permitted"},
1311  { 0,		1,		0,		"tcp_trace"},
1312  { 0,		1,		1,		"tcp_compression_enabled"},
1313  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1314  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1315  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1316  { 0,		1,		0,		"tcp_rev_src_routes"},
1317  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1318  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1319  { 0,		16,		8,		"tcp_local_dacks_max"},
1320  { 0,		2,		1,		"tcp_ecn_permitted"},
1321  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1322  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1323  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1324  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1325  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1326 };
1327 /* END CSTYLED */
1328 
1329 /*
1330  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1331  * each header fragment in the header buffer.  Each parameter value has
1332  * to be a multiple of 4 (32-bit aligned).
1333  */
1334 static tcpparam_t tcp_mdt_head_param = { 32, 256, 32, "tcp_mdt_hdr_head_min" };
1335 static tcpparam_t tcp_mdt_tail_param = { 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1336 #define	tcp_mdt_hdr_head_min	tcp_mdt_head_param.tcp_param_val
1337 #define	tcp_mdt_hdr_tail_min	tcp_mdt_tail_param.tcp_param_val
1338 
1339 /*
1340  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1341  * the maximum number of payload buffers associated per Multidata.
1342  */
1343 static tcpparam_t tcp_mdt_max_pbufs_param =
1344 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1345 #define	tcp_mdt_max_pbufs	tcp_mdt_max_pbufs_param.tcp_param_val
1346 
1347 /* Round up the value to the nearest mss. */
1348 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1349 
1350 /*
1351  * Set ECN capable transport (ECT) code point in IP header.
1352  *
1353  * Note that there are 2 ECT code points '01' and '10', which are called
1354  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1355  * point ECT(0) for TCP as described in RFC 2481.
1356  */
1357 #define	SET_ECT(tcp, iph) \
1358 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1359 		/* We need to clear the code point first. */ \
1360 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1361 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1362 	} else { \
1363 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1364 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1365 	}
1366 
1367 /*
1368  * The format argument to pass to tcp_display().
1369  * DISP_PORT_ONLY means that the returned string has only port info.
1370  * DISP_ADDR_AND_PORT means that the returned string also contains the
1371  * remote and local IP address.
1372  */
1373 #define	DISP_PORT_ONLY		1
1374 #define	DISP_ADDR_AND_PORT	2
1375 
1376 /*
1377  * This controls the rate some ndd info report functions can be used
1378  * by non-privileged users.  It stores the last time such info is
1379  * requested.  When those report functions are called again, this
1380  * is checked with the current time and compare with the ndd param
1381  * tcp_ndd_get_info_interval.
1382  */
1383 static clock_t tcp_last_ndd_get_info_time = 0;
1384 #define	NDD_TOO_QUICK_MSG \
1385 	"ndd get info rate too high for non-privileged users, try again " \
1386 	"later.\n"
1387 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1388 
1389 #define	IS_VMLOANED_MBLK(mp) \
1390 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1391 
1392 /*
1393  * These two variables control the rate for TCP to generate RSTs in
1394  * response to segments not belonging to any connections.  We limit
1395  * TCP to sent out tcp_rst_sent_rate (ndd param) number of RSTs in
1396  * each 1 second interval.  This is to protect TCP against DoS attack.
1397  */
1398 static clock_t tcp_last_rst_intrvl;
1399 static uint32_t tcp_rst_cnt;
1400 
1401 /* The number of RST not sent because of the rate limit. */
1402 static uint32_t tcp_rst_unsent;
1403 
1404 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1405 boolean_t tcp_mdt_chain = B_TRUE;
1406 
1407 /*
1408  * MDT threshold in the form of effective send MSS multiplier; we take
1409  * the MDT path if the amount of unsent data exceeds the threshold value
1410  * (default threshold is 1*SMSS).
1411  */
1412 uint_t tcp_mdt_smss_threshold = 1;
1413 
1414 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1415 
1416 /*
1417  * Forces all connections to obey the value of the tcp_maxpsz_multiplier
1418  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1419  * determined dynamically during tcp_adapt_ire(), which is the default.
1420  */
1421 boolean_t tcp_static_maxpsz = B_FALSE;
1422 
1423 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1424 uint32_t tcp_random_anon_port = 1;
1425 
1426 /*
1427  * To reach to an eager in Q0 which can be dropped due to an incoming
1428  * new SYN request when Q0 is full, a new doubly linked list is
1429  * introduced. This list allows to select an eager from Q0 in O(1) time.
1430  * This is needed to avoid spending too much time walking through the
1431  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1432  * this new list has to be a member of Q0.
1433  * This list is headed by listener's tcp_t. When the list is empty,
1434  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1435  * of listener's tcp_t point to listener's tcp_t itself.
1436  *
1437  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1438  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1439  * These macros do not affect the eager's membership to Q0.
1440  */
1441 
1442 
1443 #define	MAKE_DROPPABLE(listener, eager)					\
1444 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1445 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1446 		    = (eager);						\
1447 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1448 		(eager)->tcp_eager_next_drop_q0 =			\
1449 		    (listener)->tcp_eager_next_drop_q0;			\
1450 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1451 	}
1452 
1453 #define	MAKE_UNDROPPABLE(eager)						\
1454 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1455 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1456 		    = (eager)->tcp_eager_prev_drop_q0;			\
1457 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1458 		    = (eager)->tcp_eager_next_drop_q0;			\
1459 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1460 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1461 	}
1462 
1463 /*
1464  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1465  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1466  * data, TCP will not respond with an ACK.  RFC 793 requires that
1467  * TCP responds with an ACK for such a bogus ACK.  By not following
1468  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1469  * an attacker successfully spoofs an acceptable segment to our
1470  * peer; or when our peer is "confused."
1471  */
1472 uint32_t tcp_drop_ack_unsent_cnt = 10;
1473 
1474 /*
1475  * Hook functions to enable cluster networking
1476  * On non-clustered systems these vectors must always be NULL.
1477  */
1478 
1479 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1480 			    uint8_t *laddrp, in_port_t lport) = NULL;
1481 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1482 			    uint8_t *laddrp, in_port_t lport) = NULL;
1483 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1484 			    uint8_t *laddrp, in_port_t lport,
1485 			    uint8_t *faddrp, in_port_t fport) = NULL;
1486 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1487 			    uint8_t *laddrp, in_port_t lport,
1488 			    uint8_t *faddrp, in_port_t fport) = NULL;
1489 
1490 /*
1491  * The following are defined in ip.c
1492  */
1493 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1494 				uint8_t *laddrp);
1495 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1496 				uint8_t *laddrp, uint8_t *faddrp);
1497 
1498 #define	CL_INET_CONNECT(tcp)		{			\
1499 	if (cl_inet_connect != NULL) {				\
1500 		/*						\
1501 		 * Running in cluster mode - register active connection	\
1502 		 * information						\
1503 		 */							\
1504 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1505 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1506 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1507 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1508 				    (in_port_t)(tcp)->tcp_lport,	\
1509 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1510 				    (in_port_t)(tcp)->tcp_fport);	\
1511 			}						\
1512 		} else {						\
1513 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1514 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1515 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1516 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1517 				    (in_port_t)(tcp)->tcp_lport,	\
1518 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1519 				    (in_port_t)(tcp)->tcp_fport);	\
1520 			}						\
1521 		}							\
1522 	}								\
1523 }
1524 
1525 #define	CL_INET_DISCONNECT(tcp)	{				\
1526 	if (cl_inet_disconnect != NULL) {				\
1527 		/*							\
1528 		 * Running in cluster mode - deregister active		\
1529 		 * connection information				\
1530 		 */							\
1531 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1532 			if ((tcp)->tcp_ip_src != 0) {			\
1533 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1534 				    AF_INET,				\
1535 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1536 				    (in_port_t)(tcp)->tcp_lport,	\
1537 				    (uint8_t *)				\
1538 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1539 				    (in_port_t)(tcp)->tcp_fport);	\
1540 			}						\
1541 		} else {						\
1542 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1543 			    &(tcp)->tcp_ip_src_v6)) {			\
1544 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1545 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1546 				    (in_port_t)(tcp)->tcp_lport,	\
1547 				    (uint8_t *)				\
1548 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1549 				    (in_port_t)(tcp)->tcp_fport);	\
1550 			}						\
1551 		}							\
1552 	}								\
1553 }
1554 
1555 /*
1556  * Cluster networking hook for traversing current connection list.
1557  * This routine is used to extract the current list of live connections
1558  * which must continue to to be dispatched to this node.
1559  */
1560 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1561 
1562 /*
1563  * Figure out the value of window scale opton.  Note that the rwnd is
1564  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1565  * We cannot find the scale value and then do a round up of tcp_rwnd
1566  * because the scale value may not be correct after that.
1567  *
1568  * Set the compiler flag to make this function inline.
1569  */
1570 static void
1571 tcp_set_ws_value(tcp_t *tcp)
1572 {
1573 	int i;
1574 	uint32_t rwnd = tcp->tcp_rwnd;
1575 
1576 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1577 	    i++, rwnd >>= 1)
1578 		;
1579 	tcp->tcp_rcv_ws = i;
1580 }
1581 
1582 /*
1583  * Remove a connection from the list of detached TIME_WAIT connections.
1584  * It returns B_FALSE if it can't remove the connection from the list
1585  * as the connection has already been removed from the list due to an
1586  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1587  */
1588 static boolean_t
1589 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1590 {
1591 	boolean_t	locked = B_FALSE;
1592 
1593 	if (tcp_time_wait == NULL) {
1594 		tcp_time_wait = *((tcp_squeue_priv_t **)
1595 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1596 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1597 		locked = B_TRUE;
1598 	}
1599 
1600 	if (tcp->tcp_time_wait_expire == 0) {
1601 		ASSERT(tcp->tcp_time_wait_next == NULL);
1602 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1603 		if (locked)
1604 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1605 		return (B_FALSE);
1606 	}
1607 	ASSERT(TCP_IS_DETACHED(tcp));
1608 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1609 
1610 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1611 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1612 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1613 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1614 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1615 			    NULL;
1616 		} else {
1617 			tcp_time_wait->tcp_time_wait_tail = NULL;
1618 		}
1619 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1620 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1621 		ASSERT(tcp->tcp_time_wait_next == NULL);
1622 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1623 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1624 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1625 	} else {
1626 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1627 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1628 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1629 		    tcp->tcp_time_wait_next;
1630 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1631 		    tcp->tcp_time_wait_prev;
1632 	}
1633 	tcp->tcp_time_wait_next = NULL;
1634 	tcp->tcp_time_wait_prev = NULL;
1635 	tcp->tcp_time_wait_expire = 0;
1636 
1637 	if (locked)
1638 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1639 	return (B_TRUE);
1640 }
1641 
1642 /*
1643  * Add a connection to the list of detached TIME_WAIT connections
1644  * and set its time to expire.
1645  */
1646 static void
1647 tcp_time_wait_append(tcp_t *tcp)
1648 {
1649 	tcp_squeue_priv_t *tcp_time_wait =
1650 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1651 		SQPRIVATE_TCP));
1652 
1653 	tcp_timers_stop(tcp);
1654 
1655 	/* Freed above */
1656 	ASSERT(tcp->tcp_timer_tid == 0);
1657 	ASSERT(tcp->tcp_ack_tid == 0);
1658 
1659 	/* must have happened at the time of detaching the tcp */
1660 	ASSERT(tcp->tcp_ptpahn == NULL);
1661 	ASSERT(tcp->tcp_flow_stopped == 0);
1662 	ASSERT(tcp->tcp_time_wait_next == NULL);
1663 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1664 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1665 	ASSERT(tcp->tcp_listener == NULL);
1666 
1667 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1668 	/*
1669 	 * The value computed below in tcp->tcp_time_wait_expire may
1670 	 * appear negative or wrap around. That is ok since our
1671 	 * interest is only in the difference between the current lbolt
1672 	 * value and tcp->tcp_time_wait_expire. But the value should not
1673 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1674 	 * The corresponding comparison in tcp_time_wait_collector() uses
1675 	 * modular arithmetic.
1676 	 */
1677 	tcp->tcp_time_wait_expire +=
1678 	    drv_usectohz(tcp_time_wait_interval * 1000);
1679 	if (tcp->tcp_time_wait_expire == 0)
1680 		tcp->tcp_time_wait_expire = 1;
1681 
1682 	ASSERT(TCP_IS_DETACHED(tcp));
1683 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1684 	ASSERT(tcp->tcp_time_wait_next == NULL);
1685 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1686 	TCP_DBGSTAT(tcp_time_wait);
1687 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1688 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1689 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1690 		tcp_time_wait->tcp_time_wait_head = tcp;
1691 	} else {
1692 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1693 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1694 		    TCPS_TIME_WAIT);
1695 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1696 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1697 	}
1698 	tcp_time_wait->tcp_time_wait_tail = tcp;
1699 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1700 }
1701 
1702 /* ARGSUSED */
1703 void
1704 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1705 {
1706 	conn_t	*connp = (conn_t *)arg;
1707 	tcp_t	*tcp = connp->conn_tcp;
1708 
1709 	ASSERT(tcp != NULL);
1710 	if (tcp->tcp_state == TCPS_CLOSED) {
1711 		return;
1712 	}
1713 
1714 	ASSERT((tcp->tcp_family == AF_INET &&
1715 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1716 	    (tcp->tcp_family == AF_INET6 &&
1717 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1718 	    tcp->tcp_ipversion == IPV6_VERSION)));
1719 	ASSERT(!tcp->tcp_listener);
1720 
1721 	TCP_STAT(tcp_time_wait_reap);
1722 	ASSERT(TCP_IS_DETACHED(tcp));
1723 
1724 	/*
1725 	 * Because they have no upstream client to rebind or tcp_close()
1726 	 * them later, we axe the connection here and now.
1727 	 */
1728 	tcp_close_detached(tcp);
1729 }
1730 
1731 void
1732 tcp_cleanup(tcp_t *tcp)
1733 {
1734 	mblk_t		*mp;
1735 	char		*tcp_iphc;
1736 	int		tcp_iphc_len;
1737 	int		tcp_hdr_grown;
1738 	tcp_sack_info_t	*tcp_sack_info;
1739 	conn_t		*connp = tcp->tcp_connp;
1740 
1741 	tcp_bind_hash_remove(tcp);
1742 	tcp_free(tcp);
1743 
1744 	/* Release any SSL context */
1745 	if (tcp->tcp_kssl_ent != NULL) {
1746 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1747 		tcp->tcp_kssl_ent = NULL;
1748 	}
1749 
1750 	if (tcp->tcp_kssl_ctx != NULL) {
1751 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1752 		tcp->tcp_kssl_ctx = NULL;
1753 	}
1754 	tcp->tcp_kssl_pending = B_FALSE;
1755 
1756 	conn_delete_ire(connp, NULL);
1757 	if (connp->conn_flags & IPCL_TCPCONN) {
1758 		if (connp->conn_latch != NULL)
1759 			IPLATCH_REFRELE(connp->conn_latch);
1760 		if (connp->conn_policy != NULL)
1761 			IPPH_REFRELE(connp->conn_policy);
1762 	}
1763 
1764 	/*
1765 	 * Since we will bzero the entire structure, we need to
1766 	 * remove it and reinsert it in global hash list. We
1767 	 * know the walkers can't get to this conn because we
1768 	 * had set CONDEMNED flag earlier and checked reference
1769 	 * under conn_lock so walker won't pick it and when we
1770 	 * go the ipcl_globalhash_remove() below, no walker
1771 	 * can get to it.
1772 	 */
1773 	ipcl_globalhash_remove(connp);
1774 
1775 	/* Save some state */
1776 	mp = tcp->tcp_timercache;
1777 
1778 	tcp_sack_info = tcp->tcp_sack_info;
1779 	tcp_iphc = tcp->tcp_iphc;
1780 	tcp_iphc_len = tcp->tcp_iphc_len;
1781 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1782 
1783 	if (connp->conn_cred != NULL)
1784 		crfree(connp->conn_cred);
1785 	if (connp->conn_peercred != NULL)
1786 		crfree(connp->conn_peercred);
1787 	bzero(connp, sizeof (conn_t));
1788 	bzero(tcp, sizeof (tcp_t));
1789 
1790 	/* restore the state */
1791 	tcp->tcp_timercache = mp;
1792 
1793 	tcp->tcp_sack_info = tcp_sack_info;
1794 	tcp->tcp_iphc = tcp_iphc;
1795 	tcp->tcp_iphc_len = tcp_iphc_len;
1796 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1797 
1798 
1799 	tcp->tcp_connp = connp;
1800 
1801 	connp->conn_tcp = tcp;
1802 	connp->conn_flags = IPCL_TCPCONN;
1803 	connp->conn_state_flags = CONN_INCIPIENT;
1804 	connp->conn_ulp = IPPROTO_TCP;
1805 	connp->conn_ref = 1;
1806 
1807 	ipcl_globalhash_insert(connp);
1808 }
1809 
1810 /*
1811  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1812  * is done forwards from the head.
1813  */
1814 /* ARGSUSED */
1815 void
1816 tcp_time_wait_collector(void *arg)
1817 {
1818 	tcp_t *tcp;
1819 	clock_t now;
1820 	mblk_t *mp;
1821 	conn_t *connp;
1822 	kmutex_t *lock;
1823 	boolean_t removed;
1824 
1825 	squeue_t *sqp = (squeue_t *)arg;
1826 	tcp_squeue_priv_t *tcp_time_wait =
1827 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1828 
1829 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1830 	tcp_time_wait->tcp_time_wait_tid = 0;
1831 
1832 	if (tcp_time_wait->tcp_free_list != NULL &&
1833 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1834 		TCP_STAT(tcp_freelist_cleanup);
1835 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1836 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1837 			CONN_DEC_REF(tcp->tcp_connp);
1838 		}
1839 		tcp_time_wait->tcp_free_list_cnt = 0;
1840 	}
1841 
1842 	/*
1843 	 * In order to reap time waits reliably, we should use a
1844 	 * source of time that is not adjustable by the user -- hence
1845 	 * the call to ddi_get_lbolt().
1846 	 */
1847 	now = ddi_get_lbolt();
1848 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1849 		/*
1850 		 * Compare times using modular arithmetic, since
1851 		 * lbolt can wrapover.
1852 		 */
1853 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1854 			break;
1855 		}
1856 
1857 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1858 		ASSERT(removed);
1859 
1860 		connp = tcp->tcp_connp;
1861 		ASSERT(connp->conn_fanout != NULL);
1862 		lock = &connp->conn_fanout->connf_lock;
1863 		/*
1864 		 * This is essentially a TW reclaim fast path optimization for
1865 		 * performance where the timewait collector checks under the
1866 		 * fanout lock (so that no one else can get access to the
1867 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1868 		 * the classifier hash list. If ref count is indeed 2, we can
1869 		 * just remove the conn under the fanout lock and avoid
1870 		 * cleaning up the conn under the squeue, provided that
1871 		 * clustering callbacks are not enabled. If clustering is
1872 		 * enabled, we need to make the clustering callback before
1873 		 * setting the CONDEMNED flag and after dropping all locks and
1874 		 * so we forego this optimization and fall back to the slow
1875 		 * path. Also please see the comments in tcp_closei_local
1876 		 * regarding the refcnt logic.
1877 		 *
1878 		 * Since we are holding the tcp_time_wait_lock, its better
1879 		 * not to block on the fanout_lock because other connections
1880 		 * can't add themselves to time_wait list. So we do a
1881 		 * tryenter instead of mutex_enter.
1882 		 */
1883 		if (mutex_tryenter(lock)) {
1884 			mutex_enter(&connp->conn_lock);
1885 			if ((connp->conn_ref == 2) &&
1886 			    (cl_inet_disconnect == NULL)) {
1887 				ipcl_hash_remove_locked(connp,
1888 				    connp->conn_fanout);
1889 				/*
1890 				 * Set the CONDEMNED flag now itself so that
1891 				 * the refcnt cannot increase due to any
1892 				 * walker. But we have still not cleaned up
1893 				 * conn_ire_cache. This is still ok since
1894 				 * we are going to clean it up in tcp_cleanup
1895 				 * immediately and any interface unplumb
1896 				 * thread will wait till the ire is blown away
1897 				 */
1898 				connp->conn_state_flags |= CONN_CONDEMNED;
1899 				mutex_exit(lock);
1900 				mutex_exit(&connp->conn_lock);
1901 				if (tcp_time_wait->tcp_free_list_cnt <
1902 				    tcp_free_list_max_cnt) {
1903 					/* Add to head of tcp_free_list */
1904 					mutex_exit(
1905 					    &tcp_time_wait->tcp_time_wait_lock);
1906 					tcp_cleanup(tcp);
1907 					mutex_enter(
1908 					    &tcp_time_wait->tcp_time_wait_lock);
1909 					tcp->tcp_time_wait_next =
1910 					    tcp_time_wait->tcp_free_list;
1911 					tcp_time_wait->tcp_free_list = tcp;
1912 					tcp_time_wait->tcp_free_list_cnt++;
1913 					continue;
1914 				} else {
1915 					/* Do not add to tcp_free_list */
1916 					mutex_exit(
1917 					    &tcp_time_wait->tcp_time_wait_lock);
1918 					tcp_bind_hash_remove(tcp);
1919 					conn_delete_ire(tcp->tcp_connp, NULL);
1920 					CONN_DEC_REF(tcp->tcp_connp);
1921 				}
1922 			} else {
1923 				CONN_INC_REF_LOCKED(connp);
1924 				mutex_exit(lock);
1925 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1926 				mutex_exit(&connp->conn_lock);
1927 				/*
1928 				 * We can reuse the closemp here since conn has
1929 				 * detached (otherwise we wouldn't even be in
1930 				 * time_wait list). tcp_closemp_used can safely
1931 				 * be changed without taking a lock as no other
1932 				 * thread can concurrently access it at this
1933 				 * point in the connection lifecycle. We
1934 				 * increment tcp_closemp_used to record any
1935 				 * attempt to reuse tcp_closemp while it is
1936 				 * still in use.
1937 				 */
1938 
1939 				if (tcp->tcp_closemp.b_prev == NULL)
1940 					tcp->tcp_closemp_used = 1;
1941 				else
1942 					tcp->tcp_closemp_used++;
1943 
1944 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1945 				mp = &tcp->tcp_closemp;
1946 				squeue_fill(connp->conn_sqp, mp,
1947 				    tcp_timewait_output, connp,
1948 				    SQTAG_TCP_TIMEWAIT);
1949 			}
1950 		} else {
1951 			mutex_enter(&connp->conn_lock);
1952 			CONN_INC_REF_LOCKED(connp);
1953 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1954 			mutex_exit(&connp->conn_lock);
1955 			/*
1956 			 * We can reuse the closemp here since conn has
1957 			 * detached (otherwise we wouldn't even be in
1958 			 * time_wait list). tcp_closemp_used can safely
1959 			 * be changed without taking a lock as no other
1960 			 * thread can concurrently access it at this
1961 			 * point in the connection lifecycle. We
1962 			 * increment tcp_closemp_used to record any
1963 			 * attempt to reuse tcp_closemp while it is
1964 			 * still in use.
1965 			 */
1966 
1967 			if (tcp->tcp_closemp.b_prev == NULL)
1968 				tcp->tcp_closemp_used = 1;
1969 			else
1970 				tcp->tcp_closemp_used++;
1971 
1972 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1973 			mp = &tcp->tcp_closemp;
1974 			squeue_fill(connp->conn_sqp, mp,
1975 			    tcp_timewait_output, connp, 0);
1976 		}
1977 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1978 	}
1979 
1980 	if (tcp_time_wait->tcp_free_list != NULL)
1981 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1982 
1983 	tcp_time_wait->tcp_time_wait_tid =
1984 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1985 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1986 }
1987 
1988 /*
1989  * Reply to a clients T_CONN_RES TPI message. This function
1990  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1991  * on the acceptor STREAM and processed in tcp_wput_accept().
1992  * Read the block comment on top of tcp_conn_request().
1993  */
1994 static void
1995 tcp_accept(tcp_t *listener, mblk_t *mp)
1996 {
1997 	tcp_t	*acceptor;
1998 	tcp_t	*eager;
1999 	tcp_t   *tcp;
2000 	struct T_conn_res	*tcr;
2001 	t_uscalar_t	acceptor_id;
2002 	t_scalar_t	seqnum;
2003 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
2004 	mblk_t	*ok_mp;
2005 	mblk_t	*mp1;
2006 
2007 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
2008 		tcp_err_ack(listener, mp, TPROTO, 0);
2009 		return;
2010 	}
2011 	tcr = (struct T_conn_res *)mp->b_rptr;
2012 
2013 	/*
2014 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
2015 	 * read side queue of the streams device underneath us i.e. the
2016 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
2017 	 * look it up in the queue_hash.  Under LP64 it sends down the
2018 	 * minor_t of the accepting endpoint.
2019 	 *
2020 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
2021 	 * fanout hash lock is held.
2022 	 * This prevents any thread from entering the acceptor queue from
2023 	 * below (since it has not been hard bound yet i.e. any inbound
2024 	 * packets will arrive on the listener or default tcp queue and
2025 	 * go through tcp_lookup).
2026 	 * The CONN_INC_REF will prevent the acceptor from closing.
2027 	 *
2028 	 * XXX It is still possible for a tli application to send down data
2029 	 * on the accepting stream while another thread calls t_accept.
2030 	 * This should not be a problem for well-behaved applications since
2031 	 * the T_OK_ACK is sent after the queue swapping is completed.
2032 	 *
2033 	 * If the accepting fd is the same as the listening fd, avoid
2034 	 * queue hash lookup since that will return an eager listener in a
2035 	 * already established state.
2036 	 */
2037 	acceptor_id = tcr->ACCEPTOR_id;
2038 	mutex_enter(&listener->tcp_eager_lock);
2039 	if (listener->tcp_acceptor_id == acceptor_id) {
2040 		eager = listener->tcp_eager_next_q;
2041 		/* only count how many T_CONN_INDs so don't count q0 */
2042 		if ((listener->tcp_conn_req_cnt_q != 1) ||
2043 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
2044 			mutex_exit(&listener->tcp_eager_lock);
2045 			tcp_err_ack(listener, mp, TBADF, 0);
2046 			return;
2047 		}
2048 		if (listener->tcp_conn_req_cnt_q0 != 0) {
2049 			/* Throw away all the eagers on q0. */
2050 			tcp_eager_cleanup(listener, 1);
2051 		}
2052 		if (listener->tcp_syn_defense) {
2053 			listener->tcp_syn_defense = B_FALSE;
2054 			if (listener->tcp_ip_addr_cache != NULL) {
2055 				kmem_free(listener->tcp_ip_addr_cache,
2056 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
2057 				listener->tcp_ip_addr_cache = NULL;
2058 			}
2059 		}
2060 		/*
2061 		 * Transfer tcp_conn_req_max to the eager so that when
2062 		 * a disconnect occurs we can revert the endpoint to the
2063 		 * listen state.
2064 		 */
2065 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2066 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2067 		/*
2068 		 * Get a reference on the acceptor just like the
2069 		 * tcp_acceptor_hash_lookup below.
2070 		 */
2071 		acceptor = listener;
2072 		CONN_INC_REF(acceptor->tcp_connp);
2073 	} else {
2074 		acceptor = tcp_acceptor_hash_lookup(acceptor_id);
2075 		if (acceptor == NULL) {
2076 			if (listener->tcp_debug) {
2077 				(void) strlog(TCP_MOD_ID, 0, 1,
2078 				    SL_ERROR|SL_TRACE,
2079 				    "tcp_accept: did not find acceptor 0x%x\n",
2080 				    acceptor_id);
2081 			}
2082 			mutex_exit(&listener->tcp_eager_lock);
2083 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2084 			return;
2085 		}
2086 		/*
2087 		 * Verify acceptor state. The acceptable states for an acceptor
2088 		 * include TCPS_IDLE and TCPS_BOUND.
2089 		 */
2090 		switch (acceptor->tcp_state) {
2091 		case TCPS_IDLE:
2092 			/* FALLTHRU */
2093 		case TCPS_BOUND:
2094 			break;
2095 		default:
2096 			CONN_DEC_REF(acceptor->tcp_connp);
2097 			mutex_exit(&listener->tcp_eager_lock);
2098 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2099 			return;
2100 		}
2101 	}
2102 
2103 	/* The listener must be in TCPS_LISTEN */
2104 	if (listener->tcp_state != TCPS_LISTEN) {
2105 		CONN_DEC_REF(acceptor->tcp_connp);
2106 		mutex_exit(&listener->tcp_eager_lock);
2107 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2108 		return;
2109 	}
2110 
2111 	/*
2112 	 * Rendezvous with an eager connection request packet hanging off
2113 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2114 	 * tcp structure when the connection packet arrived in
2115 	 * tcp_conn_request().
2116 	 */
2117 	seqnum = tcr->SEQ_number;
2118 	eager = listener;
2119 	do {
2120 		eager = eager->tcp_eager_next_q;
2121 		if (eager == NULL) {
2122 			CONN_DEC_REF(acceptor->tcp_connp);
2123 			mutex_exit(&listener->tcp_eager_lock);
2124 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2125 			return;
2126 		}
2127 	} while (eager->tcp_conn_req_seqnum != seqnum);
2128 	mutex_exit(&listener->tcp_eager_lock);
2129 
2130 	/*
2131 	 * At this point, both acceptor and listener have 2 ref
2132 	 * that they begin with. Acceptor has one additional ref
2133 	 * we placed in lookup while listener has 3 additional
2134 	 * ref for being behind the squeue (tcp_accept() is
2135 	 * done on listener's squeue); being in classifier hash;
2136 	 * and eager's ref on listener.
2137 	 */
2138 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2139 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2140 
2141 	/*
2142 	 * The eager at this point is set in its own squeue and
2143 	 * could easily have been killed (tcp_accept_finish will
2144 	 * deal with that) because of a TH_RST so we can only
2145 	 * ASSERT for a single ref.
2146 	 */
2147 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2148 
2149 	/* Pre allocate the stroptions mblk also */
2150 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2151 	if (opt_mp == NULL) {
2152 		CONN_DEC_REF(acceptor->tcp_connp);
2153 		CONN_DEC_REF(eager->tcp_connp);
2154 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2155 		return;
2156 	}
2157 	DB_TYPE(opt_mp) = M_SETOPTS;
2158 	opt_mp->b_wptr += sizeof (struct stroptions);
2159 
2160 	/*
2161 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2162 	 * from listener to acceptor. The message is chained on opt_mp
2163 	 * which will be sent onto eager's squeue.
2164 	 */
2165 	if (listener->tcp_bound_if != 0) {
2166 		/* allocate optmgmt req */
2167 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2168 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2169 		    sizeof (int));
2170 		if (mp1 != NULL)
2171 			linkb(opt_mp, mp1);
2172 	}
2173 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2174 		uint_t on = 1;
2175 
2176 		/* allocate optmgmt req */
2177 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2178 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2179 		if (mp1 != NULL)
2180 			linkb(opt_mp, mp1);
2181 	}
2182 
2183 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2184 	if ((mp1 = copymsg(mp)) == NULL) {
2185 		CONN_DEC_REF(acceptor->tcp_connp);
2186 		CONN_DEC_REF(eager->tcp_connp);
2187 		freemsg(opt_mp);
2188 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2189 		return;
2190 	}
2191 
2192 	tcr = (struct T_conn_res *)mp1->b_rptr;
2193 
2194 	/*
2195 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2196 	 * which allocates a larger mblk and appends the new
2197 	 * local address to the ok_ack.  The address is copied by
2198 	 * soaccept() for getsockname().
2199 	 */
2200 	{
2201 		int extra;
2202 
2203 		extra = (eager->tcp_family == AF_INET) ?
2204 		    sizeof (sin_t) : sizeof (sin6_t);
2205 
2206 		/*
2207 		 * Try to re-use mp, if possible.  Otherwise, allocate
2208 		 * an mblk and return it as ok_mp.  In any case, mp
2209 		 * is no longer usable upon return.
2210 		 */
2211 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2212 			CONN_DEC_REF(acceptor->tcp_connp);
2213 			CONN_DEC_REF(eager->tcp_connp);
2214 			freemsg(opt_mp);
2215 			/* Original mp has been freed by now, so use mp1 */
2216 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2217 			return;
2218 		}
2219 
2220 		mp = NULL;	/* We should never use mp after this point */
2221 
2222 		switch (extra) {
2223 		case sizeof (sin_t): {
2224 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2225 
2226 				ok_mp->b_wptr += extra;
2227 				sin->sin_family = AF_INET;
2228 				sin->sin_port = eager->tcp_lport;
2229 				sin->sin_addr.s_addr =
2230 				    eager->tcp_ipha->ipha_src;
2231 				break;
2232 			}
2233 		case sizeof (sin6_t): {
2234 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2235 
2236 				ok_mp->b_wptr += extra;
2237 				sin6->sin6_family = AF_INET6;
2238 				sin6->sin6_port = eager->tcp_lport;
2239 				if (eager->tcp_ipversion == IPV4_VERSION) {
2240 					sin6->sin6_flowinfo = 0;
2241 					IN6_IPADDR_TO_V4MAPPED(
2242 					    eager->tcp_ipha->ipha_src,
2243 					    &sin6->sin6_addr);
2244 				} else {
2245 					ASSERT(eager->tcp_ip6h != NULL);
2246 					sin6->sin6_flowinfo =
2247 					    eager->tcp_ip6h->ip6_vcf &
2248 					    ~IPV6_VERS_AND_FLOW_MASK;
2249 					sin6->sin6_addr =
2250 					    eager->tcp_ip6h->ip6_src;
2251 				}
2252 				break;
2253 			}
2254 		default:
2255 			break;
2256 		}
2257 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2258 	}
2259 
2260 	/*
2261 	 * If there are no options we know that the T_CONN_RES will
2262 	 * succeed. However, we can't send the T_OK_ACK upstream until
2263 	 * the tcp_accept_swap is done since it would be dangerous to
2264 	 * let the application start using the new fd prior to the swap.
2265 	 */
2266 	tcp_accept_swap(listener, acceptor, eager);
2267 
2268 	/*
2269 	 * tcp_accept_swap unlinks eager from listener but does not drop
2270 	 * the eager's reference on the listener.
2271 	 */
2272 	ASSERT(eager->tcp_listener == NULL);
2273 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2274 
2275 	/*
2276 	 * The eager is now associated with its own queue. Insert in
2277 	 * the hash so that the connection can be reused for a future
2278 	 * T_CONN_RES.
2279 	 */
2280 	tcp_acceptor_hash_insert(acceptor_id, eager);
2281 
2282 	/*
2283 	 * We now do the processing of options with T_CONN_RES.
2284 	 * We delay till now since we wanted to have queue to pass to
2285 	 * option processing routines that points back to the right
2286 	 * instance structure which does not happen until after
2287 	 * tcp_accept_swap().
2288 	 *
2289 	 * Note:
2290 	 * The sanity of the logic here assumes that whatever options
2291 	 * are appropriate to inherit from listner=>eager are done
2292 	 * before this point, and whatever were to be overridden (or not)
2293 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2294 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2295 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2296 	 * This may not be true at this point in time but can be fixed
2297 	 * independently. This option processing code starts with
2298 	 * the instantiated acceptor instance and the final queue at
2299 	 * this point.
2300 	 */
2301 
2302 	if (tcr->OPT_length != 0) {
2303 		/* Options to process */
2304 		int t_error = 0;
2305 		int sys_error = 0;
2306 		int do_disconnect = 0;
2307 
2308 		if (tcp_conprim_opt_process(eager, mp1,
2309 		    &do_disconnect, &t_error, &sys_error) < 0) {
2310 			eager->tcp_accept_error = 1;
2311 			if (do_disconnect) {
2312 				/*
2313 				 * An option failed which does not allow
2314 				 * connection to be accepted.
2315 				 *
2316 				 * We allow T_CONN_RES to succeed and
2317 				 * put a T_DISCON_IND on the eager queue.
2318 				 */
2319 				ASSERT(t_error == 0 && sys_error == 0);
2320 				eager->tcp_send_discon_ind = 1;
2321 			} else {
2322 				ASSERT(t_error != 0);
2323 				freemsg(ok_mp);
2324 				/*
2325 				 * Original mp was either freed or set
2326 				 * to ok_mp above, so use mp1 instead.
2327 				 */
2328 				tcp_err_ack(listener, mp1, t_error, sys_error);
2329 				goto finish;
2330 			}
2331 		}
2332 		/*
2333 		 * Most likely success in setting options (except if
2334 		 * eager->tcp_send_discon_ind set).
2335 		 * mp1 option buffer represented by OPT_length/offset
2336 		 * potentially modified and contains results of setting
2337 		 * options at this point
2338 		 */
2339 	}
2340 
2341 	/* We no longer need mp1, since all options processing has passed */
2342 	freemsg(mp1);
2343 
2344 	putnext(listener->tcp_rq, ok_mp);
2345 
2346 	mutex_enter(&listener->tcp_eager_lock);
2347 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2348 		tcp_t	*tail;
2349 		mblk_t	*conn_ind;
2350 
2351 		/*
2352 		 * This path should not be executed if listener and
2353 		 * acceptor streams are the same.
2354 		 */
2355 		ASSERT(listener != acceptor);
2356 
2357 		tcp = listener->tcp_eager_prev_q0;
2358 		/*
2359 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2360 		 * deferred T_conn_ind queue. We need to get to the head of
2361 		 * the queue in order to send up T_conn_ind the same order as
2362 		 * how the 3WHS is completed.
2363 		 */
2364 		while (tcp != listener) {
2365 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2366 				break;
2367 			else
2368 				tcp = tcp->tcp_eager_prev_q0;
2369 		}
2370 		ASSERT(tcp != listener);
2371 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2372 		ASSERT(conn_ind != NULL);
2373 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2374 
2375 		/* Move from q0 to q */
2376 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2377 		listener->tcp_conn_req_cnt_q0--;
2378 		listener->tcp_conn_req_cnt_q++;
2379 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2380 		    tcp->tcp_eager_prev_q0;
2381 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2382 		    tcp->tcp_eager_next_q0;
2383 		tcp->tcp_eager_prev_q0 = NULL;
2384 		tcp->tcp_eager_next_q0 = NULL;
2385 		tcp->tcp_conn_def_q0 = B_FALSE;
2386 
2387 		/* Make sure the tcp isn't in the list of droppables */
2388 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2389 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2390 
2391 		/*
2392 		 * Insert at end of the queue because sockfs sends
2393 		 * down T_CONN_RES in chronological order. Leaving
2394 		 * the older conn indications at front of the queue
2395 		 * helps reducing search time.
2396 		 */
2397 		tail = listener->tcp_eager_last_q;
2398 		if (tail != NULL)
2399 			tail->tcp_eager_next_q = tcp;
2400 		else
2401 			listener->tcp_eager_next_q = tcp;
2402 		listener->tcp_eager_last_q = tcp;
2403 		tcp->tcp_eager_next_q = NULL;
2404 		mutex_exit(&listener->tcp_eager_lock);
2405 		putnext(tcp->tcp_rq, conn_ind);
2406 	} else {
2407 		mutex_exit(&listener->tcp_eager_lock);
2408 	}
2409 
2410 	/*
2411 	 * Done with the acceptor - free it
2412 	 *
2413 	 * Note: from this point on, no access to listener should be made
2414 	 * as listener can be equal to acceptor.
2415 	 */
2416 finish:
2417 	ASSERT(acceptor->tcp_detached);
2418 	acceptor->tcp_rq = tcp_g_q;
2419 	acceptor->tcp_wq = WR(tcp_g_q);
2420 	(void) tcp_clean_death(acceptor, 0, 2);
2421 	CONN_DEC_REF(acceptor->tcp_connp);
2422 
2423 	/*
2424 	 * In case we already received a FIN we have to make tcp_rput send
2425 	 * the ordrel_ind. This will also send up a window update if the window
2426 	 * has opened up.
2427 	 *
2428 	 * In the normal case of a successful connection acceptance
2429 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2430 	 * indication that this was just accepted. This tells tcp_rput to
2431 	 * pass up any data queued in tcp_rcv_list.
2432 	 *
2433 	 * In the fringe case where options sent with T_CONN_RES failed and
2434 	 * we required, we would be indicating a T_DISCON_IND to blow
2435 	 * away this connection.
2436 	 */
2437 
2438 	/*
2439 	 * XXX: we currently have a problem if XTI application closes the
2440 	 * acceptor stream in between. This problem exists in on10-gate also
2441 	 * and is well know but nothing can be done short of major rewrite
2442 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2443 	 * eager same squeue as listener (we can distinguish non socket
2444 	 * listeners at the time of handling a SYN in tcp_conn_request)
2445 	 * and do most of the work that tcp_accept_finish does here itself
2446 	 * and then get behind the acceptor squeue to access the acceptor
2447 	 * queue.
2448 	 */
2449 	/*
2450 	 * We already have a ref on tcp so no need to do one before squeue_fill
2451 	 */
2452 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2453 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2454 }
2455 
2456 /*
2457  * Swap information between the eager and acceptor for a TLI/XTI client.
2458  * The sockfs accept is done on the acceptor stream and control goes
2459  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2460  * called. In either case, both the eager and listener are in their own
2461  * perimeter (squeue) and the code has to deal with potential race.
2462  *
2463  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2464  */
2465 static void
2466 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2467 {
2468 	conn_t	*econnp, *aconnp;
2469 
2470 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2471 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2472 	ASSERT(!eager->tcp_hard_bound);
2473 	ASSERT(!TCP_IS_SOCKET(acceptor));
2474 	ASSERT(!TCP_IS_SOCKET(eager));
2475 	ASSERT(!TCP_IS_SOCKET(listener));
2476 
2477 	acceptor->tcp_detached = B_TRUE;
2478 	/*
2479 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2480 	 * the acceptor id.
2481 	 */
2482 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2483 
2484 	/* remove eager from listen list... */
2485 	mutex_enter(&listener->tcp_eager_lock);
2486 	tcp_eager_unlink(eager);
2487 	ASSERT(eager->tcp_eager_next_q == NULL &&
2488 	    eager->tcp_eager_last_q == NULL);
2489 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2490 	    eager->tcp_eager_prev_q0 == NULL);
2491 	mutex_exit(&listener->tcp_eager_lock);
2492 	eager->tcp_rq = acceptor->tcp_rq;
2493 	eager->tcp_wq = acceptor->tcp_wq;
2494 
2495 	econnp = eager->tcp_connp;
2496 	aconnp = acceptor->tcp_connp;
2497 
2498 	eager->tcp_rq->q_ptr = econnp;
2499 	eager->tcp_wq->q_ptr = econnp;
2500 
2501 	/*
2502 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2503 	 * which might be a different squeue from our peer TCP instance.
2504 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2505 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2506 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2507 	 * above reach global visibility prior to the clearing of tcp_detached.
2508 	 */
2509 	membar_producer();
2510 	eager->tcp_detached = B_FALSE;
2511 
2512 	ASSERT(eager->tcp_ack_tid == 0);
2513 
2514 	econnp->conn_dev = aconnp->conn_dev;
2515 	if (eager->tcp_cred != NULL)
2516 		crfree(eager->tcp_cred);
2517 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2518 	aconnp->conn_cred = NULL;
2519 
2520 	econnp->conn_zoneid = aconnp->conn_zoneid;
2521 	econnp->conn_allzones = aconnp->conn_allzones;
2522 
2523 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2524 	aconnp->conn_mac_exempt = B_FALSE;
2525 
2526 	ASSERT(aconnp->conn_peercred == NULL);
2527 
2528 	/* Do the IPC initialization */
2529 	CONN_INC_REF(econnp);
2530 
2531 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2532 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2533 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2534 	econnp->conn_ulp = aconnp->conn_ulp;
2535 
2536 	/* Done with old IPC. Drop its ref on its connp */
2537 	CONN_DEC_REF(aconnp);
2538 }
2539 
2540 
2541 /*
2542  * Adapt to the information, such as rtt and rtt_sd, provided from the
2543  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2544  *
2545  * Checks for multicast and broadcast destination address.
2546  * Returns zero on failure; non-zero if ok.
2547  *
2548  * Note that the MSS calculation here is based on the info given in
2549  * the IRE.  We do not do any calculation based on TCP options.  They
2550  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2551  * knows which options to use.
2552  *
2553  * Note on how TCP gets its parameters for a connection.
2554  *
2555  * When a tcp_t structure is allocated, it gets all the default parameters.
2556  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2557  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2558  * default.  But if there is an associated tcp_host_param, it will override
2559  * the metrics.
2560  *
2561  * An incoming SYN with a multicast or broadcast destination address, is dropped
2562  * in 1 of 2 places.
2563  *
2564  * 1. If the packet was received over the wire it is dropped in
2565  * ip_rput_process_broadcast()
2566  *
2567  * 2. If the packet was received through internal IP loopback, i.e. the packet
2568  * was generated and received on the same machine, it is dropped in
2569  * ip_wput_local()
2570  *
2571  * An incoming SYN with a multicast or broadcast source address is always
2572  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2573  * reject an attempt to connect to a broadcast or multicast (destination)
2574  * address.
2575  */
2576 static int
2577 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2578 {
2579 	tcp_hsp_t	*hsp;
2580 	ire_t		*ire;
2581 	ire_t		*sire = NULL;
2582 	iulp_t		*ire_uinfo = NULL;
2583 	uint32_t	mss_max;
2584 	uint32_t	mss;
2585 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2586 	conn_t		*connp = tcp->tcp_connp;
2587 	boolean_t	ire_cacheable = B_FALSE;
2588 	zoneid_t	zoneid = connp->conn_zoneid;
2589 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2590 			    MATCH_IRE_SECATTR;
2591 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2592 	ill_t		*ill = NULL;
2593 	boolean_t	incoming = (ire_mp == NULL);
2594 
2595 	ASSERT(connp->conn_ire_cache == NULL);
2596 
2597 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2598 
2599 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2600 			BUMP_MIB(&ip_mib, ipIfStatsInDiscards);
2601 			return (0);
2602 		}
2603 		/*
2604 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2605 		 * for the destination with the nexthop as gateway.
2606 		 * ire_ctable_lookup() is used because this particular
2607 		 * ire, if it exists, will be marked private.
2608 		 * If that is not available, use the interface ire
2609 		 * for the nexthop.
2610 		 *
2611 		 * TSol: tcp_update_label will detect label mismatches based
2612 		 * only on the destination's label, but that would not
2613 		 * detect label mismatches based on the security attributes
2614 		 * of routes or next hop gateway. Hence we need to pass the
2615 		 * label to ire_ftable_lookup below in order to locate the
2616 		 * right prefix (and/or) ire cache. Similarly we also need
2617 		 * pass the label to the ire_cache_lookup below to locate
2618 		 * the right ire that also matches on the label.
2619 		 */
2620 		if (tcp->tcp_connp->conn_nexthop_set) {
2621 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2622 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2623 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2624 			if (ire == NULL) {
2625 				ire = ire_ftable_lookup(
2626 				    tcp->tcp_connp->conn_nexthop_v4,
2627 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2628 				    tsl, match_flags);
2629 				if (ire == NULL)
2630 					return (0);
2631 			} else {
2632 				ire_uinfo = &ire->ire_uinfo;
2633 			}
2634 		} else {
2635 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2636 			    zoneid, tsl);
2637 			if (ire != NULL) {
2638 				ire_cacheable = B_TRUE;
2639 				ire_uinfo = (ire_mp != NULL) ?
2640 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2641 				    &ire->ire_uinfo;
2642 
2643 			} else {
2644 				if (ire_mp == NULL) {
2645 					ire = ire_ftable_lookup(
2646 					    tcp->tcp_connp->conn_rem,
2647 					    0, 0, 0, NULL, &sire, zoneid, 0,
2648 					    tsl, (MATCH_IRE_RECURSIVE |
2649 					    MATCH_IRE_DEFAULT));
2650 					if (ire == NULL)
2651 						return (0);
2652 					ire_uinfo = (sire != NULL) ?
2653 					    &sire->ire_uinfo :
2654 					    &ire->ire_uinfo;
2655 				} else {
2656 					ire = (ire_t *)ire_mp->b_rptr;
2657 					ire_uinfo =
2658 					    &((ire_t *)
2659 					    ire_mp->b_rptr)->ire_uinfo;
2660 				}
2661 			}
2662 		}
2663 		ASSERT(ire != NULL);
2664 
2665 		if ((ire->ire_src_addr == INADDR_ANY) ||
2666 		    (ire->ire_type & IRE_BROADCAST)) {
2667 			/*
2668 			 * ire->ire_mp is non null when ire_mp passed in is used
2669 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2670 			 */
2671 			if (ire->ire_mp == NULL)
2672 				ire_refrele(ire);
2673 			if (sire != NULL)
2674 				ire_refrele(sire);
2675 			return (0);
2676 		}
2677 
2678 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2679 			ipaddr_t src_addr;
2680 
2681 			/*
2682 			 * ip_bind_connected() has stored the correct source
2683 			 * address in conn_src.
2684 			 */
2685 			src_addr = tcp->tcp_connp->conn_src;
2686 			tcp->tcp_ipha->ipha_src = src_addr;
2687 			/*
2688 			 * Copy of the src addr. in tcp_t is needed
2689 			 * for the lookup funcs.
2690 			 */
2691 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2692 		}
2693 		/*
2694 		 * Set the fragment bit so that IP will tell us if the MTU
2695 		 * should change. IP tells us the latest setting of
2696 		 * ip_path_mtu_discovery through ire_frag_flag.
2697 		 */
2698 		if (ip_path_mtu_discovery) {
2699 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2700 			    htons(IPH_DF);
2701 		}
2702 		/*
2703 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2704 		 * for IP_NEXTHOP. No cache ire has been found for the
2705 		 * destination and we are working with the nexthop's
2706 		 * interface ire. Since we need to forward all packets
2707 		 * to the nexthop first, we "blindly" set tcp_localnet
2708 		 * to false, eventhough the destination may also be
2709 		 * onlink.
2710 		 */
2711 		if (ire_uinfo == NULL)
2712 			tcp->tcp_localnet = 0;
2713 		else
2714 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2715 	} else {
2716 		/*
2717 		 * For incoming connection ire_mp = NULL
2718 		 * For outgoing connection ire_mp != NULL
2719 		 * Technically we should check conn_incoming_ill
2720 		 * when ire_mp is NULL and conn_outgoing_ill when
2721 		 * ire_mp is non-NULL. But this is performance
2722 		 * critical path and for IPV*_BOUND_IF, outgoing
2723 		 * and incoming ill are always set to the same value.
2724 		 */
2725 		ill_t	*dst_ill = NULL;
2726 		ipif_t  *dst_ipif = NULL;
2727 
2728 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2729 
2730 		if (connp->conn_outgoing_ill != NULL) {
2731 			/* Outgoing or incoming path */
2732 			int   err;
2733 
2734 			dst_ill = conn_get_held_ill(connp,
2735 			    &connp->conn_outgoing_ill, &err);
2736 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2737 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2738 				return (0);
2739 			}
2740 			match_flags |= MATCH_IRE_ILL;
2741 			dst_ipif = dst_ill->ill_ipif;
2742 		}
2743 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2744 		    0, 0, dst_ipif, zoneid, tsl, match_flags);
2745 
2746 		if (ire != NULL) {
2747 			ire_cacheable = B_TRUE;
2748 			ire_uinfo = (ire_mp != NULL) ?
2749 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2750 			    &ire->ire_uinfo;
2751 		} else {
2752 			if (ire_mp == NULL) {
2753 				ire = ire_ftable_lookup_v6(
2754 				    &tcp->tcp_connp->conn_remv6,
2755 				    0, 0, 0, dst_ipif, &sire, zoneid,
2756 				    0, tsl, match_flags);
2757 				if (ire == NULL) {
2758 					if (dst_ill != NULL)
2759 						ill_refrele(dst_ill);
2760 					return (0);
2761 				}
2762 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2763 				    &ire->ire_uinfo;
2764 			} else {
2765 				ire = (ire_t *)ire_mp->b_rptr;
2766 				ire_uinfo =
2767 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2768 			}
2769 		}
2770 		if (dst_ill != NULL)
2771 			ill_refrele(dst_ill);
2772 
2773 		ASSERT(ire != NULL);
2774 		ASSERT(ire_uinfo != NULL);
2775 
2776 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2777 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2778 			/*
2779 			 * ire->ire_mp is non null when ire_mp passed in is used
2780 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2781 			 */
2782 			if (ire->ire_mp == NULL)
2783 				ire_refrele(ire);
2784 			if (sire != NULL)
2785 				ire_refrele(sire);
2786 			return (0);
2787 		}
2788 
2789 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2790 			in6_addr_t	src_addr;
2791 
2792 			/*
2793 			 * ip_bind_connected_v6() has stored the correct source
2794 			 * address per IPv6 addr. selection policy in
2795 			 * conn_src_v6.
2796 			 */
2797 			src_addr = tcp->tcp_connp->conn_srcv6;
2798 
2799 			tcp->tcp_ip6h->ip6_src = src_addr;
2800 			/*
2801 			 * Copy of the src addr. in tcp_t is needed
2802 			 * for the lookup funcs.
2803 			 */
2804 			tcp->tcp_ip_src_v6 = src_addr;
2805 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2806 			    &connp->conn_srcv6));
2807 		}
2808 		tcp->tcp_localnet =
2809 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2810 	}
2811 
2812 	/*
2813 	 * This allows applications to fail quickly when connections are made
2814 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2815 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2816 	 */
2817 	if ((ire->ire_flags & RTF_REJECT) &&
2818 	    (ire->ire_flags & RTF_PRIVATE))
2819 		goto error;
2820 
2821 	/*
2822 	 * Make use of the cached rtt and rtt_sd values to calculate the
2823 	 * initial RTO.  Note that they are already initialized in
2824 	 * tcp_init_values().
2825 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2826 	 * IP_NEXTHOP, but instead are using the interface ire for the
2827 	 * nexthop, then we do not use the ire_uinfo from that ire to
2828 	 * do any initializations.
2829 	 */
2830 	if (ire_uinfo != NULL) {
2831 		if (ire_uinfo->iulp_rtt != 0) {
2832 			clock_t	rto;
2833 
2834 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2835 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2836 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2837 			    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
2838 
2839 			if (rto > tcp_rexmit_interval_max) {
2840 				tcp->tcp_rto = tcp_rexmit_interval_max;
2841 			} else if (rto < tcp_rexmit_interval_min) {
2842 				tcp->tcp_rto = tcp_rexmit_interval_min;
2843 			} else {
2844 				tcp->tcp_rto = rto;
2845 			}
2846 		}
2847 		if (ire_uinfo->iulp_ssthresh != 0)
2848 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2849 		else
2850 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2851 		if (ire_uinfo->iulp_spipe > 0) {
2852 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2853 			    tcp_max_buf);
2854 			if (tcp_snd_lowat_fraction != 0)
2855 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2856 				    tcp_snd_lowat_fraction;
2857 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2858 		}
2859 		/*
2860 		 * Note that up till now, acceptor always inherits receive
2861 		 * window from the listener.  But if there is a metrics
2862 		 * associated with a host, we should use that instead of
2863 		 * inheriting it from listener. Thus we need to pass this
2864 		 * info back to the caller.
2865 		 */
2866 		if (ire_uinfo->iulp_rpipe > 0) {
2867 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
2868 		}
2869 
2870 		if (ire_uinfo->iulp_rtomax > 0) {
2871 			tcp->tcp_second_timer_threshold =
2872 			    ire_uinfo->iulp_rtomax;
2873 		}
2874 
2875 		/*
2876 		 * Use the metric option settings, iulp_tstamp_ok and
2877 		 * iulp_wscale_ok, only for active open. What this means
2878 		 * is that if the other side uses timestamp or window
2879 		 * scale option, TCP will also use those options. That
2880 		 * is for passive open.  If the application sets a
2881 		 * large window, window scale is enabled regardless of
2882 		 * the value in iulp_wscale_ok.  This is the behavior
2883 		 * since 2.6.  So we keep it.
2884 		 * The only case left in passive open processing is the
2885 		 * check for SACK.
2886 		 * For ECN, it should probably be like SACK.  But the
2887 		 * current value is binary, so we treat it like the other
2888 		 * cases.  The metric only controls active open.For passive
2889 		 * open, the ndd param, tcp_ecn_permitted, controls the
2890 		 * behavior.
2891 		 */
2892 		if (!tcp_detached) {
2893 			/*
2894 			 * The if check means that the following can only
2895 			 * be turned on by the metrics only IRE, but not off.
2896 			 */
2897 			if (ire_uinfo->iulp_tstamp_ok)
2898 				tcp->tcp_snd_ts_ok = B_TRUE;
2899 			if (ire_uinfo->iulp_wscale_ok)
2900 				tcp->tcp_snd_ws_ok = B_TRUE;
2901 			if (ire_uinfo->iulp_sack == 2)
2902 				tcp->tcp_snd_sack_ok = B_TRUE;
2903 			if (ire_uinfo->iulp_ecn_ok)
2904 				tcp->tcp_ecn_ok = B_TRUE;
2905 		} else {
2906 			/*
2907 			 * Passive open.
2908 			 *
2909 			 * As above, the if check means that SACK can only be
2910 			 * turned on by the metric only IRE.
2911 			 */
2912 			if (ire_uinfo->iulp_sack > 0) {
2913 				tcp->tcp_snd_sack_ok = B_TRUE;
2914 			}
2915 		}
2916 	}
2917 
2918 
2919 	/*
2920 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2921 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2922 	 * length of all those options exceeds 28 bytes.  But because
2923 	 * of the tcp_mss_min check below, we may not have a problem if
2924 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2925 	 * the negative problem still exists.  And the check defeats PMTUd.
2926 	 * In fact, if PMTUd finds that the MSS should be smaller than
2927 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2928 	 * value.
2929 	 *
2930 	 * We do not deal with that now.  All those problems related to
2931 	 * PMTUd will be fixed later.
2932 	 */
2933 	ASSERT(ire->ire_max_frag != 0);
2934 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2935 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2936 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2937 			mss = MIN(mss, IPV6_MIN_MTU);
2938 		}
2939 	}
2940 
2941 	/* Sanity check for MSS value. */
2942 	if (tcp->tcp_ipversion == IPV4_VERSION)
2943 		mss_max = tcp_mss_max_ipv4;
2944 	else
2945 		mss_max = tcp_mss_max_ipv6;
2946 
2947 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2948 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2949 		/*
2950 		 * After receiving an ICMPv6 "packet too big" message with a
2951 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2952 		 * will insert a 8-byte fragment header in every packet; we
2953 		 * reduce the MSS by that amount here.
2954 		 */
2955 		mss -= sizeof (ip6_frag_t);
2956 	}
2957 
2958 	if (tcp->tcp_ipsec_overhead == 0)
2959 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2960 
2961 	mss -= tcp->tcp_ipsec_overhead;
2962 
2963 	if (mss < tcp_mss_min)
2964 		mss = tcp_mss_min;
2965 	if (mss > mss_max)
2966 		mss = mss_max;
2967 
2968 	/* Note that this is the maximum MSS, excluding all options. */
2969 	tcp->tcp_mss = mss;
2970 
2971 	/*
2972 	 * Initialize the ISS here now that we have the full connection ID.
2973 	 * The RFC 1948 method of initial sequence number generation requires
2974 	 * knowledge of the full connection ID before setting the ISS.
2975 	 */
2976 
2977 	tcp_iss_init(tcp);
2978 
2979 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2980 		tcp->tcp_loopback = B_TRUE;
2981 
2982 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2983 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
2984 	} else {
2985 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
2986 	}
2987 
2988 	if (hsp != NULL) {
2989 		/* Only modify if we're going to make them bigger */
2990 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2991 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2992 			if (tcp_snd_lowat_fraction != 0)
2993 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2994 					tcp_snd_lowat_fraction;
2995 		}
2996 
2997 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2998 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2999 		}
3000 
3001 		/* Copy timestamp flag only for active open */
3002 		if (!tcp_detached)
3003 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
3004 	}
3005 
3006 	if (sire != NULL)
3007 		IRE_REFRELE(sire);
3008 
3009 	/*
3010 	 * If we got an IRE_CACHE and an ILL, go through their properties;
3011 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
3012 	 */
3013 	if (tcp->tcp_loopback ||
3014 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
3015 		/*
3016 		 * For incoming, see if this tcp may be MDT-capable.  For
3017 		 * outgoing, this process has been taken care of through
3018 		 * tcp_rput_other.
3019 		 */
3020 		tcp_ire_ill_check(tcp, ire, ill, incoming);
3021 		tcp->tcp_ire_ill_check_done = B_TRUE;
3022 	}
3023 
3024 	mutex_enter(&connp->conn_lock);
3025 	/*
3026 	 * Make sure that conn is not marked incipient
3027 	 * for incoming connections. A blind
3028 	 * removal of incipient flag is cheaper than
3029 	 * check and removal.
3030 	 */
3031 	connp->conn_state_flags &= ~CONN_INCIPIENT;
3032 
3033 	/* Must not cache forwarding table routes. */
3034 	if (ire_cacheable) {
3035 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
3036 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3037 			connp->conn_ire_cache = ire;
3038 			IRE_UNTRACE_REF(ire);
3039 			rw_exit(&ire->ire_bucket->irb_lock);
3040 			mutex_exit(&connp->conn_lock);
3041 			return (1);
3042 		}
3043 		rw_exit(&ire->ire_bucket->irb_lock);
3044 	}
3045 	mutex_exit(&connp->conn_lock);
3046 
3047 	if (ire->ire_mp == NULL)
3048 		ire_refrele(ire);
3049 	return (1);
3050 
3051 error:
3052 	if (ire->ire_mp == NULL)
3053 		ire_refrele(ire);
3054 	if (sire != NULL)
3055 		ire_refrele(sire);
3056 	return (0);
3057 }
3058 
3059 /*
3060  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
3061  * O_T_BIND_REQ/T_BIND_REQ message.
3062  */
3063 static void
3064 tcp_bind(tcp_t *tcp, mblk_t *mp)
3065 {
3066 	sin_t	*sin;
3067 	sin6_t	*sin6;
3068 	mblk_t	*mp1;
3069 	in_port_t requested_port;
3070 	in_port_t allocated_port;
3071 	struct T_bind_req *tbr;
3072 	boolean_t	bind_to_req_port_only;
3073 	boolean_t	backlog_update = B_FALSE;
3074 	boolean_t	user_specified;
3075 	in6_addr_t	v6addr;
3076 	ipaddr_t	v4addr;
3077 	uint_t	origipversion;
3078 	int	err;
3079 	queue_t *q = tcp->tcp_wq;
3080 	conn_t	*connp;
3081 	mlp_type_t addrtype, mlptype;
3082 	zone_t	*zone;
3083 	cred_t	*cr;
3084 	in_port_t mlp_port;
3085 
3086 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3087 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3088 		if (tcp->tcp_debug) {
3089 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3090 			    "tcp_bind: bad req, len %u",
3091 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3092 		}
3093 		tcp_err_ack(tcp, mp, TPROTO, 0);
3094 		return;
3095 	}
3096 	/* Make sure the largest address fits */
3097 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3098 	if (mp1 == NULL) {
3099 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3100 		return;
3101 	}
3102 	mp = mp1;
3103 	tbr = (struct T_bind_req *)mp->b_rptr;
3104 	if (tcp->tcp_state >= TCPS_BOUND) {
3105 		if ((tcp->tcp_state == TCPS_BOUND ||
3106 		    tcp->tcp_state == TCPS_LISTEN) &&
3107 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3108 		    tbr->CONIND_number > 0) {
3109 			/*
3110 			 * Handle listen() increasing CONIND_number.
3111 			 * This is more "liberal" then what the TPI spec
3112 			 * requires but is needed to avoid a t_unbind
3113 			 * when handling listen() since the port number
3114 			 * might be "stolen" between the unbind and bind.
3115 			 */
3116 			backlog_update = B_TRUE;
3117 			goto do_bind;
3118 		}
3119 		if (tcp->tcp_debug) {
3120 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3121 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3122 		}
3123 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3124 		return;
3125 	}
3126 	origipversion = tcp->tcp_ipversion;
3127 
3128 	switch (tbr->ADDR_length) {
3129 	case 0:			/* request for a generic port */
3130 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3131 		if (tcp->tcp_family == AF_INET) {
3132 			tbr->ADDR_length = sizeof (sin_t);
3133 			sin = (sin_t *)&tbr[1];
3134 			*sin = sin_null;
3135 			sin->sin_family = AF_INET;
3136 			mp->b_wptr = (uchar_t *)&sin[1];
3137 			tcp->tcp_ipversion = IPV4_VERSION;
3138 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3139 		} else {
3140 			ASSERT(tcp->tcp_family == AF_INET6);
3141 			tbr->ADDR_length = sizeof (sin6_t);
3142 			sin6 = (sin6_t *)&tbr[1];
3143 			*sin6 = sin6_null;
3144 			sin6->sin6_family = AF_INET6;
3145 			mp->b_wptr = (uchar_t *)&sin6[1];
3146 			tcp->tcp_ipversion = IPV6_VERSION;
3147 			V6_SET_ZERO(v6addr);
3148 		}
3149 		requested_port = 0;
3150 		break;
3151 
3152 	case sizeof (sin_t):	/* Complete IPv4 address */
3153 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3154 		    sizeof (sin_t));
3155 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3156 			if (tcp->tcp_debug) {
3157 				(void) strlog(TCP_MOD_ID, 0, 1,
3158 				    SL_ERROR|SL_TRACE,
3159 				    "tcp_bind: bad address parameter, "
3160 				    "offset %d, len %d",
3161 				    tbr->ADDR_offset, tbr->ADDR_length);
3162 			}
3163 			tcp_err_ack(tcp, mp, TPROTO, 0);
3164 			return;
3165 		}
3166 		/*
3167 		 * With sockets sockfs will accept bogus sin_family in
3168 		 * bind() and replace it with the family used in the socket
3169 		 * call.
3170 		 */
3171 		if (sin->sin_family != AF_INET ||
3172 		    tcp->tcp_family != AF_INET) {
3173 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3174 			return;
3175 		}
3176 		requested_port = ntohs(sin->sin_port);
3177 		tcp->tcp_ipversion = IPV4_VERSION;
3178 		v4addr = sin->sin_addr.s_addr;
3179 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3180 		break;
3181 
3182 	case sizeof (sin6_t): /* Complete IPv6 address */
3183 		sin6 = (sin6_t *)mi_offset_param(mp,
3184 		    tbr->ADDR_offset, sizeof (sin6_t));
3185 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3186 			if (tcp->tcp_debug) {
3187 				(void) strlog(TCP_MOD_ID, 0, 1,
3188 				    SL_ERROR|SL_TRACE,
3189 				    "tcp_bind: bad IPv6 address parameter, "
3190 				    "offset %d, len %d", tbr->ADDR_offset,
3191 				    tbr->ADDR_length);
3192 			}
3193 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3194 			return;
3195 		}
3196 		if (sin6->sin6_family != AF_INET6 ||
3197 		    tcp->tcp_family != AF_INET6) {
3198 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3199 			return;
3200 		}
3201 		requested_port = ntohs(sin6->sin6_port);
3202 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3203 		    IPV4_VERSION : IPV6_VERSION;
3204 		v6addr = sin6->sin6_addr;
3205 		break;
3206 
3207 	default:
3208 		if (tcp->tcp_debug) {
3209 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3210 			    "tcp_bind: bad address length, %d",
3211 			    tbr->ADDR_length);
3212 		}
3213 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3214 		return;
3215 	}
3216 	tcp->tcp_bound_source_v6 = v6addr;
3217 
3218 	/* Check for change in ipversion */
3219 	if (origipversion != tcp->tcp_ipversion) {
3220 		ASSERT(tcp->tcp_family == AF_INET6);
3221 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3222 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3223 		if (err) {
3224 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3225 			return;
3226 		}
3227 	}
3228 
3229 	/*
3230 	 * Initialize family specific fields. Copy of the src addr.
3231 	 * in tcp_t is needed for the lookup funcs.
3232 	 */
3233 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3234 		tcp->tcp_ip6h->ip6_src = v6addr;
3235 	} else {
3236 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3237 	}
3238 	tcp->tcp_ip_src_v6 = v6addr;
3239 
3240 	/*
3241 	 * For O_T_BIND_REQ:
3242 	 * Verify that the target port/addr is available, or choose
3243 	 * another.
3244 	 * For  T_BIND_REQ:
3245 	 * Verify that the target port/addr is available or fail.
3246 	 * In both cases when it succeeds the tcp is inserted in the
3247 	 * bind hash table. This ensures that the operation is atomic
3248 	 * under the lock on the hash bucket.
3249 	 */
3250 	bind_to_req_port_only = requested_port != 0 &&
3251 	    tbr->PRIM_type != O_T_BIND_REQ;
3252 	/*
3253 	 * Get a valid port (within the anonymous range and should not
3254 	 * be a privileged one) to use if the user has not given a port.
3255 	 * If multiple threads are here, they may all start with
3256 	 * with the same initial port. But, it should be fine as long as
3257 	 * tcp_bindi will ensure that no two threads will be assigned
3258 	 * the same port.
3259 	 *
3260 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3261 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3262 	 * unless TCP_ANONPRIVBIND option is set.
3263 	 */
3264 	mlptype = mlptSingle;
3265 	mlp_port = requested_port;
3266 	if (requested_port == 0) {
3267 		requested_port = tcp->tcp_anon_priv_bind ?
3268 		    tcp_get_next_priv_port(tcp) :
3269 		    tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
3270 		if (requested_port == 0) {
3271 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3272 			return;
3273 		}
3274 		user_specified = B_FALSE;
3275 
3276 		/*
3277 		 * If the user went through one of the RPC interfaces to create
3278 		 * this socket and RPC is MLP in this zone, then give him an
3279 		 * anonymous MLP.
3280 		 */
3281 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3282 		connp = tcp->tcp_connp;
3283 		if (connp->conn_anon_mlp && is_system_labeled()) {
3284 			zone = crgetzone(cr);
3285 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3286 			    IPV6_VERSION, &v6addr);
3287 			if (addrtype == mlptSingle) {
3288 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3289 				return;
3290 			}
3291 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3292 			    PMAPPORT, addrtype);
3293 			mlp_port = PMAPPORT;
3294 		}
3295 	} else {
3296 		int i;
3297 		boolean_t priv = B_FALSE;
3298 
3299 		/*
3300 		 * If the requested_port is in the well-known privileged range,
3301 		 * verify that the stream was opened by a privileged user.
3302 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3303 		 * but instead the code relies on:
3304 		 * - the fact that the address of the array and its size never
3305 		 *   changes
3306 		 * - the atomic assignment of the elements of the array
3307 		 */
3308 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3309 		if (requested_port < tcp_smallest_nonpriv_port) {
3310 			priv = B_TRUE;
3311 		} else {
3312 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3313 				if (requested_port ==
3314 				    tcp_g_epriv_ports[i]) {
3315 					priv = B_TRUE;
3316 					break;
3317 				}
3318 			}
3319 		}
3320 		if (priv) {
3321 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3322 				if (tcp->tcp_debug) {
3323 					(void) strlog(TCP_MOD_ID, 0, 1,
3324 					    SL_ERROR|SL_TRACE,
3325 					    "tcp_bind: no priv for port %d",
3326 					    requested_port);
3327 				}
3328 				tcp_err_ack(tcp, mp, TACCES, 0);
3329 				return;
3330 			}
3331 		}
3332 		user_specified = B_TRUE;
3333 
3334 		connp = tcp->tcp_connp;
3335 		if (is_system_labeled()) {
3336 			zone = crgetzone(cr);
3337 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3338 			    IPV6_VERSION, &v6addr);
3339 			if (addrtype == mlptSingle) {
3340 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3341 				return;
3342 			}
3343 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3344 			    requested_port, addrtype);
3345 		}
3346 	}
3347 
3348 	if (mlptype != mlptSingle) {
3349 		if (secpolicy_net_bindmlp(cr) != 0) {
3350 			if (tcp->tcp_debug) {
3351 				(void) strlog(TCP_MOD_ID, 0, 1,
3352 				    SL_ERROR|SL_TRACE,
3353 				    "tcp_bind: no priv for multilevel port %d",
3354 				    requested_port);
3355 			}
3356 			tcp_err_ack(tcp, mp, TACCES, 0);
3357 			return;
3358 		}
3359 
3360 		/*
3361 		 * If we're specifically binding a shared IP address and the
3362 		 * port is MLP on shared addresses, then check to see if this
3363 		 * zone actually owns the MLP.  Reject if not.
3364 		 */
3365 		if (mlptype == mlptShared && addrtype == mlptShared) {
3366 			zoneid_t mlpzone;
3367 
3368 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3369 			    htons(mlp_port));
3370 			if (connp->conn_zoneid != mlpzone) {
3371 				if (tcp->tcp_debug) {
3372 					(void) strlog(TCP_MOD_ID, 0, 1,
3373 					    SL_ERROR|SL_TRACE,
3374 					    "tcp_bind: attempt to bind port "
3375 					    "%d on shared addr in zone %d "
3376 					    "(should be %d)",
3377 					    mlp_port, connp->conn_zoneid,
3378 					    mlpzone);
3379 				}
3380 				tcp_err_ack(tcp, mp, TACCES, 0);
3381 				return;
3382 			}
3383 		}
3384 
3385 		if (!user_specified) {
3386 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3387 			    requested_port, B_TRUE);
3388 			if (err != 0) {
3389 				if (tcp->tcp_debug) {
3390 					(void) strlog(TCP_MOD_ID, 0, 1,
3391 					    SL_ERROR|SL_TRACE,
3392 					    "tcp_bind: cannot establish anon "
3393 					    "MLP for port %d",
3394 					    requested_port);
3395 				}
3396 				tcp_err_ack(tcp, mp, TSYSERR, err);
3397 				return;
3398 			}
3399 			connp->conn_anon_port = B_TRUE;
3400 		}
3401 		connp->conn_mlp_type = mlptype;
3402 	}
3403 
3404 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3405 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3406 
3407 	if (allocated_port == 0) {
3408 		connp->conn_mlp_type = mlptSingle;
3409 		if (connp->conn_anon_port) {
3410 			connp->conn_anon_port = B_FALSE;
3411 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3412 			    requested_port, B_FALSE);
3413 		}
3414 		if (bind_to_req_port_only) {
3415 			if (tcp->tcp_debug) {
3416 				(void) strlog(TCP_MOD_ID, 0, 1,
3417 				    SL_ERROR|SL_TRACE,
3418 				    "tcp_bind: requested addr busy");
3419 			}
3420 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3421 		} else {
3422 			/* If we are out of ports, fail the bind. */
3423 			if (tcp->tcp_debug) {
3424 				(void) strlog(TCP_MOD_ID, 0, 1,
3425 				    SL_ERROR|SL_TRACE,
3426 				    "tcp_bind: out of ports?");
3427 			}
3428 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3429 		}
3430 		return;
3431 	}
3432 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3433 do_bind:
3434 	if (!backlog_update) {
3435 		if (tcp->tcp_family == AF_INET)
3436 			sin->sin_port = htons(allocated_port);
3437 		else
3438 			sin6->sin6_port = htons(allocated_port);
3439 	}
3440 	if (tcp->tcp_family == AF_INET) {
3441 		if (tbr->CONIND_number != 0) {
3442 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3443 			    sizeof (sin_t));
3444 		} else {
3445 			/* Just verify the local IP address */
3446 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3447 		}
3448 	} else {
3449 		if (tbr->CONIND_number != 0) {
3450 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3451 			    sizeof (sin6_t));
3452 		} else {
3453 			/* Just verify the local IP address */
3454 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3455 			    IPV6_ADDR_LEN);
3456 		}
3457 	}
3458 	if (mp1 == NULL) {
3459 		if (connp->conn_anon_port) {
3460 			connp->conn_anon_port = B_FALSE;
3461 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3462 			    requested_port, B_FALSE);
3463 		}
3464 		connp->conn_mlp_type = mlptSingle;
3465 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3466 		return;
3467 	}
3468 
3469 	tbr->PRIM_type = T_BIND_ACK;
3470 	mp->b_datap->db_type = M_PCPROTO;
3471 
3472 	/* Chain in the reply mp for tcp_rput() */
3473 	mp1->b_cont = mp;
3474 	mp = mp1;
3475 
3476 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3477 	if (tcp->tcp_conn_req_max) {
3478 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
3479 			tcp->tcp_conn_req_max = tcp_conn_req_min;
3480 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
3481 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
3482 		/*
3483 		 * If this is a listener, do not reset the eager list
3484 		 * and other stuffs.  Note that we don't check if the
3485 		 * existing eager list meets the new tcp_conn_req_max
3486 		 * requirement.
3487 		 */
3488 		if (tcp->tcp_state != TCPS_LISTEN) {
3489 			tcp->tcp_state = TCPS_LISTEN;
3490 			/* Initialize the chain. Don't need the eager_lock */
3491 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3492 			tcp->tcp_eager_next_drop_q0 = tcp;
3493 			tcp->tcp_eager_prev_drop_q0 = tcp;
3494 			tcp->tcp_second_ctimer_threshold =
3495 			    tcp_ip_abort_linterval;
3496 		}
3497 	}
3498 
3499 	/*
3500 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3501 	 * processing continues in tcp_rput_other().
3502 	 */
3503 	if (tcp->tcp_family == AF_INET6) {
3504 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3505 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3506 	} else {
3507 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3508 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3509 	}
3510 	/*
3511 	 * If the bind cannot complete immediately
3512 	 * IP will arrange to call tcp_rput_other
3513 	 * when the bind completes.
3514 	 */
3515 	if (mp != NULL) {
3516 		tcp_rput_other(tcp, mp);
3517 	} else {
3518 		/*
3519 		 * Bind will be resumed later. Need to ensure
3520 		 * that conn doesn't disappear when that happens.
3521 		 * This will be decremented in ip_resume_tcp_bind().
3522 		 */
3523 		CONN_INC_REF(tcp->tcp_connp);
3524 	}
3525 }
3526 
3527 
3528 /*
3529  * If the "bind_to_req_port_only" parameter is set, if the requested port
3530  * number is available, return it, If not return 0
3531  *
3532  * If "bind_to_req_port_only" parameter is not set and
3533  * If the requested port number is available, return it.  If not, return
3534  * the first anonymous port we happen across.  If no anonymous ports are
3535  * available, return 0. addr is the requested local address, if any.
3536  *
3537  * In either case, when succeeding update the tcp_t to record the port number
3538  * and insert it in the bind hash table.
3539  *
3540  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3541  * without setting SO_REUSEADDR. This is needed so that they
3542  * can be viewed as two independent transport protocols.
3543  */
3544 static in_port_t
3545 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3546     int reuseaddr, boolean_t quick_connect,
3547     boolean_t bind_to_req_port_only, boolean_t user_specified)
3548 {
3549 	/* number of times we have run around the loop */
3550 	int count = 0;
3551 	/* maximum number of times to run around the loop */
3552 	int loopmax;
3553 	conn_t *connp = tcp->tcp_connp;
3554 	zoneid_t zoneid = connp->conn_zoneid;
3555 
3556 	/*
3557 	 * Lookup for free addresses is done in a loop and "loopmax"
3558 	 * influences how long we spin in the loop
3559 	 */
3560 	if (bind_to_req_port_only) {
3561 		/*
3562 		 * If the requested port is busy, don't bother to look
3563 		 * for a new one. Setting loop maximum count to 1 has
3564 		 * that effect.
3565 		 */
3566 		loopmax = 1;
3567 	} else {
3568 		/*
3569 		 * If the requested port is busy, look for a free one
3570 		 * in the anonymous port range.
3571 		 * Set loopmax appropriately so that one does not look
3572 		 * forever in the case all of the anonymous ports are in use.
3573 		 */
3574 		if (tcp->tcp_anon_priv_bind) {
3575 			/*
3576 			 * loopmax =
3577 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3578 			 */
3579 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
3580 		} else {
3581 			loopmax = (tcp_largest_anon_port -
3582 			    tcp_smallest_anon_port + 1);
3583 		}
3584 	}
3585 	do {
3586 		uint16_t	lport;
3587 		tf_t		*tbf;
3588 		tcp_t		*ltcp;
3589 		conn_t		*lconnp;
3590 
3591 		lport = htons(port);
3592 
3593 		/*
3594 		 * Ensure that the tcp_t is not currently in the bind hash.
3595 		 * Hold the lock on the hash bucket to ensure that
3596 		 * the duplicate check plus the insertion is an atomic
3597 		 * operation.
3598 		 *
3599 		 * This function does an inline lookup on the bind hash list
3600 		 * Make sure that we access only members of tcp_t
3601 		 * and that we don't look at tcp_tcp, since we are not
3602 		 * doing a CONN_INC_REF.
3603 		 */
3604 		tcp_bind_hash_remove(tcp);
3605 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
3606 		mutex_enter(&tbf->tf_lock);
3607 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3608 		    ltcp = ltcp->tcp_bind_hash) {
3609 			boolean_t not_socket;
3610 			boolean_t exclbind;
3611 
3612 			if (lport != ltcp->tcp_lport)
3613 				continue;
3614 
3615 			lconnp = ltcp->tcp_connp;
3616 
3617 			/*
3618 			 * On a labeled system, we must treat bindings to ports
3619 			 * on shared IP addresses by sockets with MAC exemption
3620 			 * privilege as being in all zones, as there's
3621 			 * otherwise no way to identify the right receiver.
3622 			 */
3623 			if (!IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) &&
3624 			    !lconnp->conn_mac_exempt &&
3625 			    !connp->conn_mac_exempt)
3626 				continue;
3627 
3628 			/*
3629 			 * If TCP_EXCLBIND is set for either the bound or
3630 			 * binding endpoint, the semantics of bind
3631 			 * is changed according to the following.
3632 			 *
3633 			 * spec = specified address (v4 or v6)
3634 			 * unspec = unspecified address (v4 or v6)
3635 			 * A = specified addresses are different for endpoints
3636 			 *
3637 			 * bound	bind to		allowed
3638 			 * -------------------------------------
3639 			 * unspec	unspec		no
3640 			 * unspec	spec		no
3641 			 * spec		unspec		no
3642 			 * spec		spec		yes if A
3643 			 *
3644 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3645 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3646 			 *
3647 			 * Note:
3648 			 *
3649 			 * 1. Because of TLI semantics, an endpoint can go
3650 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3651 			 * TCPS_BOUND, depending on whether it is originally
3652 			 * a listener or not.  That is why we need to check
3653 			 * for states greater than or equal to TCPS_BOUND
3654 			 * here.
3655 			 *
3656 			 * 2. Ideally, we should only check for state equals
3657 			 * to TCPS_LISTEN. And the following check should be
3658 			 * added.
3659 			 *
3660 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3661 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3662 			 *		...
3663 			 * }
3664 			 *
3665 			 * The semantics will be changed to this.  If the
3666 			 * endpoint on the list is in state not equal to
3667 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3668 			 * set, let the bind succeed.
3669 			 *
3670 			 * Because of (1), we cannot do that for TLI
3671 			 * endpoints.  But we can do that for socket endpoints.
3672 			 * If in future, we can change this going back
3673 			 * semantics, we can use the above check for TLI also.
3674 			 */
3675 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3676 			    TCP_IS_SOCKET(tcp));
3677 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3678 
3679 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3680 			    (exclbind && (not_socket ||
3681 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3682 				if (V6_OR_V4_INADDR_ANY(
3683 				    ltcp->tcp_bound_source_v6) ||
3684 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3685 				    IN6_ARE_ADDR_EQUAL(laddr,
3686 				    &ltcp->tcp_bound_source_v6)) {
3687 					break;
3688 				}
3689 				continue;
3690 			}
3691 
3692 			/*
3693 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3694 			 * have disjoint port number spaces, if *_EXCLBIND
3695 			 * is not set and only if the application binds to a
3696 			 * specific port. We use the same autoassigned port
3697 			 * number space for IPv4 and IPv6 sockets.
3698 			 */
3699 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3700 			    bind_to_req_port_only)
3701 				continue;
3702 
3703 			/*
3704 			 * Ideally, we should make sure that the source
3705 			 * address, remote address, and remote port in the
3706 			 * four tuple for this tcp-connection is unique.
3707 			 * However, trying to find out the local source
3708 			 * address would require too much code duplication
3709 			 * with IP, since IP needs needs to have that code
3710 			 * to support userland TCP implementations.
3711 			 */
3712 			if (quick_connect &&
3713 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3714 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3715 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3716 				    &ltcp->tcp_remote_v6)))
3717 				continue;
3718 
3719 			if (!reuseaddr) {
3720 				/*
3721 				 * No socket option SO_REUSEADDR.
3722 				 * If existing port is bound to
3723 				 * a non-wildcard IP address
3724 				 * and the requesting stream is
3725 				 * bound to a distinct
3726 				 * different IP addresses
3727 				 * (non-wildcard, also), keep
3728 				 * going.
3729 				 */
3730 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3731 				    !V6_OR_V4_INADDR_ANY(
3732 				    ltcp->tcp_bound_source_v6) &&
3733 				    !IN6_ARE_ADDR_EQUAL(laddr,
3734 					&ltcp->tcp_bound_source_v6))
3735 					continue;
3736 				if (ltcp->tcp_state >= TCPS_BOUND) {
3737 					/*
3738 					 * This port is being used and
3739 					 * its state is >= TCPS_BOUND,
3740 					 * so we can't bind to it.
3741 					 */
3742 					break;
3743 				}
3744 			} else {
3745 				/*
3746 				 * socket option SO_REUSEADDR is set on the
3747 				 * binding tcp_t.
3748 				 *
3749 				 * If two streams are bound to
3750 				 * same IP address or both addr
3751 				 * and bound source are wildcards
3752 				 * (INADDR_ANY), we want to stop
3753 				 * searching.
3754 				 * We have found a match of IP source
3755 				 * address and source port, which is
3756 				 * refused regardless of the
3757 				 * SO_REUSEADDR setting, so we break.
3758 				 */
3759 				if (IN6_ARE_ADDR_EQUAL(laddr,
3760 				    &ltcp->tcp_bound_source_v6) &&
3761 				    (ltcp->tcp_state == TCPS_LISTEN ||
3762 					ltcp->tcp_state == TCPS_BOUND))
3763 					break;
3764 			}
3765 		}
3766 		if (ltcp != NULL) {
3767 			/* The port number is busy */
3768 			mutex_exit(&tbf->tf_lock);
3769 		} else {
3770 			/*
3771 			 * This port is ours. Insert in fanout and mark as
3772 			 * bound to prevent others from getting the port
3773 			 * number.
3774 			 */
3775 			tcp->tcp_state = TCPS_BOUND;
3776 			tcp->tcp_lport = htons(port);
3777 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3778 
3779 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
3780 			    tcp->tcp_lport)] == tbf);
3781 			tcp_bind_hash_insert(tbf, tcp, 1);
3782 
3783 			mutex_exit(&tbf->tf_lock);
3784 
3785 			/*
3786 			 * We don't want tcp_next_port_to_try to "inherit"
3787 			 * a port number supplied by the user in a bind.
3788 			 */
3789 			if (user_specified)
3790 				return (port);
3791 
3792 			/*
3793 			 * This is the only place where tcp_next_port_to_try
3794 			 * is updated. After the update, it may or may not
3795 			 * be in the valid range.
3796 			 */
3797 			if (!tcp->tcp_anon_priv_bind)
3798 				tcp_next_port_to_try = port + 1;
3799 			return (port);
3800 		}
3801 
3802 		if (tcp->tcp_anon_priv_bind) {
3803 			port = tcp_get_next_priv_port(tcp);
3804 		} else {
3805 			if (count == 0 && user_specified) {
3806 				/*
3807 				 * We may have to return an anonymous port. So
3808 				 * get one to start with.
3809 				 */
3810 				port =
3811 				    tcp_update_next_port(tcp_next_port_to_try,
3812 					tcp, B_TRUE);
3813 				user_specified = B_FALSE;
3814 			} else {
3815 				port = tcp_update_next_port(port + 1, tcp,
3816 				    B_FALSE);
3817 			}
3818 		}
3819 		if (port == 0)
3820 			break;
3821 
3822 		/*
3823 		 * Don't let this loop run forever in the case where
3824 		 * all of the anonymous ports are in use.
3825 		 */
3826 	} while (++count < loopmax);
3827 	return (0);
3828 }
3829 
3830 /*
3831  * tcp_clean_death / tcp_close_detached must not be called more than once
3832  * on a tcp. Thus every function that potentially calls tcp_clean_death
3833  * must check for the tcp state before calling tcp_clean_death.
3834  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3835  * tcp_timer_handler, all check for the tcp state.
3836  */
3837 /* ARGSUSED */
3838 void
3839 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3840 {
3841 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3842 
3843 	freemsg(mp);
3844 	if (tcp->tcp_state > TCPS_BOUND)
3845 	    (void) tcp_clean_death(((conn_t *)arg)->conn_tcp, ETIMEDOUT, 5);
3846 }
3847 
3848 /*
3849  * We are dying for some reason.  Try to do it gracefully.  (May be called
3850  * as writer.)
3851  *
3852  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3853  * done by a service procedure).
3854  * TBD - Should the return value distinguish between the tcp_t being
3855  * freed and it being reinitialized?
3856  */
3857 static int
3858 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3859 {
3860 	mblk_t	*mp;
3861 	queue_t	*q;
3862 
3863 	TCP_CLD_STAT(tag);
3864 
3865 #if TCP_TAG_CLEAN_DEATH
3866 	tcp->tcp_cleandeathtag = tag;
3867 #endif
3868 
3869 	if (tcp->tcp_fused)
3870 		tcp_unfuse(tcp);
3871 
3872 	if (tcp->tcp_linger_tid != 0 &&
3873 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3874 		tcp_stop_lingering(tcp);
3875 	}
3876 
3877 	ASSERT(tcp != NULL);
3878 	ASSERT((tcp->tcp_family == AF_INET &&
3879 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3880 	    (tcp->tcp_family == AF_INET6 &&
3881 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3882 	    tcp->tcp_ipversion == IPV6_VERSION)));
3883 
3884 	if (TCP_IS_DETACHED(tcp)) {
3885 		if (tcp->tcp_hard_binding) {
3886 			/*
3887 			 * Its an eager that we are dealing with. We close the
3888 			 * eager but in case a conn_ind has already gone to the
3889 			 * listener, let tcp_accept_finish() send a discon_ind
3890 			 * to the listener and drop the last reference. If the
3891 			 * listener doesn't even know about the eager i.e. the
3892 			 * conn_ind hasn't gone up, blow away the eager and drop
3893 			 * the last reference as well. If the conn_ind has gone
3894 			 * up, state should be BOUND. tcp_accept_finish
3895 			 * will figure out that the connection has received a
3896 			 * RST and will send a DISCON_IND to the application.
3897 			 */
3898 			tcp_closei_local(tcp);
3899 			if (!tcp->tcp_tconnind_started) {
3900 				CONN_DEC_REF(tcp->tcp_connp);
3901 			} else {
3902 				tcp->tcp_state = TCPS_BOUND;
3903 			}
3904 		} else {
3905 			tcp_close_detached(tcp);
3906 		}
3907 		return (0);
3908 	}
3909 
3910 	TCP_STAT(tcp_clean_death_nondetached);
3911 
3912 	/*
3913 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3914 	 * is run) postpone cleaning up the endpoint until service routine
3915 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3916 	 * client_errno since tcp_close uses the client_errno field.
3917 	 */
3918 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3919 		if (err != 0)
3920 			tcp->tcp_client_errno = err;
3921 
3922 		tcp->tcp_deferred_clean_death = B_TRUE;
3923 		return (-1);
3924 	}
3925 
3926 	q = tcp->tcp_rq;
3927 
3928 	/* Trash all inbound data */
3929 	flushq(q, FLUSHALL);
3930 
3931 	/*
3932 	 * If we are at least part way open and there is error
3933 	 * (err==0 implies no error)
3934 	 * notify our client by a T_DISCON_IND.
3935 	 */
3936 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3937 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3938 		    !TCP_IS_SOCKET(tcp)) {
3939 			/*
3940 			 * Send M_FLUSH according to TPI. Because sockets will
3941 			 * (and must) ignore FLUSHR we do that only for TPI
3942 			 * endpoints and sockets in STREAMS mode.
3943 			 */
3944 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3945 		}
3946 		if (tcp->tcp_debug) {
3947 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3948 			    "tcp_clean_death: discon err %d", err);
3949 		}
3950 		mp = mi_tpi_discon_ind(NULL, err, 0);
3951 		if (mp != NULL) {
3952 			putnext(q, mp);
3953 		} else {
3954 			if (tcp->tcp_debug) {
3955 				(void) strlog(TCP_MOD_ID, 0, 1,
3956 				    SL_ERROR|SL_TRACE,
3957 				    "tcp_clean_death, sending M_ERROR");
3958 			}
3959 			(void) putnextctl1(q, M_ERROR, EPROTO);
3960 		}
3961 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3962 			/* SYN_SENT or SYN_RCVD */
3963 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3964 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3965 			/* ESTABLISHED or CLOSE_WAIT */
3966 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3967 		}
3968 	}
3969 
3970 	tcp_reinit(tcp);
3971 	return (-1);
3972 }
3973 
3974 /*
3975  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3976  * to expire, stop the wait and finish the close.
3977  */
3978 static void
3979 tcp_stop_lingering(tcp_t *tcp)
3980 {
3981 	clock_t	delta = 0;
3982 
3983 	tcp->tcp_linger_tid = 0;
3984 	if (tcp->tcp_state > TCPS_LISTEN) {
3985 		tcp_acceptor_hash_remove(tcp);
3986 		mutex_enter(&tcp->tcp_non_sq_lock);
3987 		if (tcp->tcp_flow_stopped) {
3988 			tcp_clrqfull(tcp);
3989 		}
3990 		mutex_exit(&tcp->tcp_non_sq_lock);
3991 
3992 		if (tcp->tcp_timer_tid != 0) {
3993 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3994 			tcp->tcp_timer_tid = 0;
3995 		}
3996 		/*
3997 		 * Need to cancel those timers which will not be used when
3998 		 * TCP is detached.  This has to be done before the tcp_wq
3999 		 * is set to the global queue.
4000 		 */
4001 		tcp_timers_stop(tcp);
4002 
4003 
4004 		tcp->tcp_detached = B_TRUE;
4005 		tcp->tcp_rq = tcp_g_q;
4006 		tcp->tcp_wq = WR(tcp_g_q);
4007 
4008 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4009 			tcp_time_wait_append(tcp);
4010 			TCP_DBGSTAT(tcp_detach_time_wait);
4011 			goto finish;
4012 		}
4013 
4014 		/*
4015 		 * If delta is zero the timer event wasn't executed and was
4016 		 * successfully canceled. In this case we need to restart it
4017 		 * with the minimal delta possible.
4018 		 */
4019 		if (delta >= 0) {
4020 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4021 			    delta ? delta : 1);
4022 		}
4023 	} else {
4024 		tcp_closei_local(tcp);
4025 		CONN_DEC_REF(tcp->tcp_connp);
4026 	}
4027 finish:
4028 	/* Signal closing thread that it can complete close */
4029 	mutex_enter(&tcp->tcp_closelock);
4030 	tcp->tcp_detached = B_TRUE;
4031 	tcp->tcp_rq = tcp_g_q;
4032 	tcp->tcp_wq = WR(tcp_g_q);
4033 	tcp->tcp_closed = 1;
4034 	cv_signal(&tcp->tcp_closecv);
4035 	mutex_exit(&tcp->tcp_closelock);
4036 }
4037 
4038 /*
4039  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
4040  * expires.
4041  */
4042 static void
4043 tcp_close_linger_timeout(void *arg)
4044 {
4045 	conn_t	*connp = (conn_t *)arg;
4046 	tcp_t 	*tcp = connp->conn_tcp;
4047 
4048 	tcp->tcp_client_errno = ETIMEDOUT;
4049 	tcp_stop_lingering(tcp);
4050 }
4051 
4052 static int
4053 tcp_close(queue_t *q, int flags)
4054 {
4055 	conn_t		*connp = Q_TO_CONN(q);
4056 	tcp_t		*tcp = connp->conn_tcp;
4057 	mblk_t 		*mp = &tcp->tcp_closemp;
4058 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4059 	boolean_t	linger_interrupted = B_FALSE;
4060 	mblk_t		*bp;
4061 
4062 	ASSERT(WR(q)->q_next == NULL);
4063 	ASSERT(connp->conn_ref >= 2);
4064 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
4065 
4066 	/*
4067 	 * We are being closed as /dev/tcp or /dev/tcp6.
4068 	 *
4069 	 * Mark the conn as closing. ill_pending_mp_add will not
4070 	 * add any mp to the pending mp list, after this conn has
4071 	 * started closing. Same for sq_pending_mp_add
4072 	 */
4073 	mutex_enter(&connp->conn_lock);
4074 	connp->conn_state_flags |= CONN_CLOSING;
4075 	if (connp->conn_oper_pending_ill != NULL)
4076 		conn_ioctl_cleanup_reqd = B_TRUE;
4077 	CONN_INC_REF_LOCKED(connp);
4078 	mutex_exit(&connp->conn_lock);
4079 	tcp->tcp_closeflags = (uint8_t)flags;
4080 	ASSERT(connp->conn_ref >= 3);
4081 
4082 	/*
4083 	 * tcp_closemp_used is used below without any protection of a lock
4084 	 * as we don't expect any one else to use it concurrently at this
4085 	 * point otherwise it would be a major defect, though we do
4086 	 * increment tcp_closemp_used to record any attempt to reuse
4087 	 * tcp_closemp while it is still in use. This would help debugging.
4088 	 */
4089 
4090 	if (mp->b_prev == NULL) {
4091 		tcp->tcp_closemp_used = 1;
4092 	} else {
4093 		tcp->tcp_closemp_used++;
4094 		ASSERT(mp->b_prev == NULL);
4095 	}
4096 
4097 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
4098 
4099 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
4100 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
4101 
4102 	mutex_enter(&tcp->tcp_closelock);
4103 	while (!tcp->tcp_closed) {
4104 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
4105 			/*
4106 			 * We got interrupted. Check if we are lingering,
4107 			 * if yes, post a message to stop and wait until
4108 			 * tcp_closed is set. If we aren't lingering,
4109 			 * just go back around.
4110 			 */
4111 			if (tcp->tcp_linger &&
4112 			    tcp->tcp_lingertime > 0 &&
4113 			    !linger_interrupted) {
4114 				mutex_exit(&tcp->tcp_closelock);
4115 				/* Entering squeue, bump ref count. */
4116 				CONN_INC_REF(connp);
4117 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
4118 				squeue_enter(connp->conn_sqp, bp,
4119 				    tcp_linger_interrupted, connp,
4120 				    SQTAG_IP_TCP_CLOSE);
4121 				linger_interrupted = B_TRUE;
4122 				mutex_enter(&tcp->tcp_closelock);
4123 			}
4124 		}
4125 	}
4126 	mutex_exit(&tcp->tcp_closelock);
4127 
4128 	/*
4129 	 * In the case of listener streams that have eagers in the q or q0
4130 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4131 	 * tcp_wq of the eagers point to our queues. By waiting for the
4132 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4133 	 * up their queue pointers and also dropped their references to us.
4134 	 */
4135 	if (tcp->tcp_wait_for_eagers) {
4136 		mutex_enter(&connp->conn_lock);
4137 		while (connp->conn_ref != 1) {
4138 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4139 		}
4140 		mutex_exit(&connp->conn_lock);
4141 	}
4142 	/*
4143 	 * ioctl cleanup. The mp is queued in the
4144 	 * ill_pending_mp or in the sq_pending_mp.
4145 	 */
4146 	if (conn_ioctl_cleanup_reqd)
4147 		conn_ioctl_cleanup(connp);
4148 
4149 	qprocsoff(q);
4150 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4151 
4152 	tcp->tcp_cpid = -1;
4153 
4154 	/*
4155 	 * Drop IP's reference on the conn. This is the last reference
4156 	 * on the connp if the state was less than established. If the
4157 	 * connection has gone into timewait state, then we will have
4158 	 * one ref for the TCP and one more ref (total of two) for the
4159 	 * classifier connected hash list (a timewait connections stays
4160 	 * in connected hash till closed).
4161 	 *
4162 	 * We can't assert the references because there might be other
4163 	 * transient reference places because of some walkers or queued
4164 	 * packets in squeue for the timewait state.
4165 	 */
4166 	CONN_DEC_REF(connp);
4167 	q->q_ptr = WR(q)->q_ptr = NULL;
4168 	return (0);
4169 }
4170 
4171 static int
4172 tcpclose_accept(queue_t *q)
4173 {
4174 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4175 
4176 	/*
4177 	 * We had opened an acceptor STREAM for sockfs which is
4178 	 * now being closed due to some error.
4179 	 */
4180 	qprocsoff(q);
4181 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
4182 	q->q_ptr = WR(q)->q_ptr = NULL;
4183 	return (0);
4184 }
4185 
4186 /*
4187  * Called by tcp_close() routine via squeue when lingering is
4188  * interrupted by a signal.
4189  */
4190 
4191 /* ARGSUSED */
4192 static void
4193 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
4194 {
4195 	conn_t	*connp = (conn_t *)arg;
4196 	tcp_t	*tcp = connp->conn_tcp;
4197 
4198 	freeb(mp);
4199 	if (tcp->tcp_linger_tid != 0 &&
4200 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4201 		tcp_stop_lingering(tcp);
4202 		tcp->tcp_client_errno = EINTR;
4203 	}
4204 }
4205 
4206 /*
4207  * Called by streams close routine via squeues when our client blows off her
4208  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4209  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4210  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4211  * acked.
4212  *
4213  * NOTE: tcp_close potentially returns error when lingering.
4214  * However, the stream head currently does not pass these errors
4215  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4216  * errors to the application (from tsleep()) and not errors
4217  * like ECONNRESET caused by receiving a reset packet.
4218  */
4219 
4220 /* ARGSUSED */
4221 static void
4222 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4223 {
4224 	char	*msg;
4225 	conn_t	*connp = (conn_t *)arg;
4226 	tcp_t	*tcp = connp->conn_tcp;
4227 	clock_t	delta = 0;
4228 
4229 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4230 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4231 
4232 	/* Cancel any pending timeout */
4233 	if (tcp->tcp_ordrelid != 0) {
4234 		if (tcp->tcp_timeout) {
4235 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4236 		}
4237 		tcp->tcp_ordrelid = 0;
4238 		tcp->tcp_timeout = B_FALSE;
4239 	}
4240 
4241 	mutex_enter(&tcp->tcp_eager_lock);
4242 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4243 		/* Cleanup for listener */
4244 		tcp_eager_cleanup(tcp, 0);
4245 		tcp->tcp_wait_for_eagers = 1;
4246 	}
4247 	mutex_exit(&tcp->tcp_eager_lock);
4248 
4249 	connp->conn_mdt_ok = B_FALSE;
4250 	tcp->tcp_mdt = B_FALSE;
4251 
4252 	connp->conn_lso_ok = B_FALSE;
4253 	tcp->tcp_lso = B_FALSE;
4254 
4255 	msg = NULL;
4256 	switch (tcp->tcp_state) {
4257 	case TCPS_CLOSED:
4258 	case TCPS_IDLE:
4259 	case TCPS_BOUND:
4260 	case TCPS_LISTEN:
4261 		break;
4262 	case TCPS_SYN_SENT:
4263 		msg = "tcp_close, during connect";
4264 		break;
4265 	case TCPS_SYN_RCVD:
4266 		/*
4267 		 * Close during the connect 3-way handshake
4268 		 * but here there may or may not be pending data
4269 		 * already on queue. Process almost same as in
4270 		 * the ESTABLISHED state.
4271 		 */
4272 		/* FALLTHRU */
4273 	default:
4274 		if (tcp->tcp_fused)
4275 			tcp_unfuse(tcp);
4276 
4277 		/*
4278 		 * If SO_LINGER has set a zero linger time, abort the
4279 		 * connection with a reset.
4280 		 */
4281 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4282 			msg = "tcp_close, zero lingertime";
4283 			break;
4284 		}
4285 
4286 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4287 		/*
4288 		 * Abort connection if there is unread data queued.
4289 		 */
4290 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4291 			msg = "tcp_close, unread data";
4292 			break;
4293 		}
4294 		/*
4295 		 * tcp_hard_bound is now cleared thus all packets go through
4296 		 * tcp_lookup. This fact is used by tcp_detach below.
4297 		 *
4298 		 * We have done a qwait() above which could have possibly
4299 		 * drained more messages in turn causing transition to a
4300 		 * different state. Check whether we have to do the rest
4301 		 * of the processing or not.
4302 		 */
4303 		if (tcp->tcp_state <= TCPS_LISTEN)
4304 			break;
4305 
4306 		/*
4307 		 * Transmit the FIN before detaching the tcp_t.
4308 		 * After tcp_detach returns this queue/perimeter
4309 		 * no longer owns the tcp_t thus others can modify it.
4310 		 */
4311 		(void) tcp_xmit_end(tcp);
4312 
4313 		/*
4314 		 * If lingering on close then wait until the fin is acked,
4315 		 * the SO_LINGER time passes, or a reset is sent/received.
4316 		 */
4317 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4318 		    !(tcp->tcp_fin_acked) &&
4319 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4320 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4321 				tcp->tcp_client_errno = EWOULDBLOCK;
4322 			} else if (tcp->tcp_client_errno == 0) {
4323 
4324 				ASSERT(tcp->tcp_linger_tid == 0);
4325 
4326 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4327 				    tcp_close_linger_timeout,
4328 				    tcp->tcp_lingertime * hz);
4329 
4330 				/* tcp_close_linger_timeout will finish close */
4331 				if (tcp->tcp_linger_tid == 0)
4332 					tcp->tcp_client_errno = ENOSR;
4333 				else
4334 					return;
4335 			}
4336 
4337 			/*
4338 			 * Check if we need to detach or just close
4339 			 * the instance.
4340 			 */
4341 			if (tcp->tcp_state <= TCPS_LISTEN)
4342 				break;
4343 		}
4344 
4345 		/*
4346 		 * Make sure that no other thread will access the tcp_rq of
4347 		 * this instance (through lookups etc.) as tcp_rq will go
4348 		 * away shortly.
4349 		 */
4350 		tcp_acceptor_hash_remove(tcp);
4351 
4352 		mutex_enter(&tcp->tcp_non_sq_lock);
4353 		if (tcp->tcp_flow_stopped) {
4354 			tcp_clrqfull(tcp);
4355 		}
4356 		mutex_exit(&tcp->tcp_non_sq_lock);
4357 
4358 		if (tcp->tcp_timer_tid != 0) {
4359 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4360 			tcp->tcp_timer_tid = 0;
4361 		}
4362 		/*
4363 		 * Need to cancel those timers which will not be used when
4364 		 * TCP is detached.  This has to be done before the tcp_wq
4365 		 * is set to the global queue.
4366 		 */
4367 		tcp_timers_stop(tcp);
4368 
4369 		tcp->tcp_detached = B_TRUE;
4370 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4371 			tcp_time_wait_append(tcp);
4372 			TCP_DBGSTAT(tcp_detach_time_wait);
4373 			ASSERT(connp->conn_ref >= 3);
4374 			goto finish;
4375 		}
4376 
4377 		/*
4378 		 * If delta is zero the timer event wasn't executed and was
4379 		 * successfully canceled. In this case we need to restart it
4380 		 * with the minimal delta possible.
4381 		 */
4382 		if (delta >= 0)
4383 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4384 			    delta ? delta : 1);
4385 
4386 		ASSERT(connp->conn_ref >= 3);
4387 		goto finish;
4388 	}
4389 
4390 	/* Detach did not complete. Still need to remove q from stream. */
4391 	if (msg) {
4392 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4393 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4394 			BUMP_MIB(&tcp_mib, tcpEstabResets);
4395 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4396 		    tcp->tcp_state == TCPS_SYN_RCVD)
4397 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
4398 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4399 	}
4400 
4401 	tcp_closei_local(tcp);
4402 	CONN_DEC_REF(connp);
4403 	ASSERT(connp->conn_ref >= 2);
4404 
4405 finish:
4406 	/*
4407 	 * Although packets are always processed on the correct
4408 	 * tcp's perimeter and access is serialized via squeue's,
4409 	 * IP still needs a queue when sending packets in time_wait
4410 	 * state so use WR(tcp_g_q) till ip_output() can be
4411 	 * changed to deal with just connp. For read side, we
4412 	 * could have set tcp_rq to NULL but there are some cases
4413 	 * in tcp_rput_data() from early days of this code which
4414 	 * do a putnext without checking if tcp is closed. Those
4415 	 * need to be identified before both tcp_rq and tcp_wq
4416 	 * can be set to NULL and tcp_q_q can disappear forever.
4417 	 */
4418 	mutex_enter(&tcp->tcp_closelock);
4419 	/*
4420 	 * Don't change the queues in the case of a listener that has
4421 	 * eagers in its q or q0. It could surprise the eagers.
4422 	 * Instead wait for the eagers outside the squeue.
4423 	 */
4424 	if (!tcp->tcp_wait_for_eagers) {
4425 		tcp->tcp_detached = B_TRUE;
4426 		tcp->tcp_rq = tcp_g_q;
4427 		tcp->tcp_wq = WR(tcp_g_q);
4428 	}
4429 
4430 	/* Signal tcp_close() to finish closing. */
4431 	tcp->tcp_closed = 1;
4432 	cv_signal(&tcp->tcp_closecv);
4433 	mutex_exit(&tcp->tcp_closelock);
4434 }
4435 
4436 
4437 /*
4438  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4439  * Some stream heads get upset if they see these later on as anything but NULL.
4440  */
4441 static void
4442 tcp_close_mpp(mblk_t **mpp)
4443 {
4444 	mblk_t	*mp;
4445 
4446 	if ((mp = *mpp) != NULL) {
4447 		do {
4448 			mp->b_next = NULL;
4449 			mp->b_prev = NULL;
4450 		} while ((mp = mp->b_cont) != NULL);
4451 
4452 		mp = *mpp;
4453 		*mpp = NULL;
4454 		freemsg(mp);
4455 	}
4456 }
4457 
4458 /* Do detached close. */
4459 static void
4460 tcp_close_detached(tcp_t *tcp)
4461 {
4462 	if (tcp->tcp_fused)
4463 		tcp_unfuse(tcp);
4464 
4465 	/*
4466 	 * Clustering code serializes TCP disconnect callbacks and
4467 	 * cluster tcp list walks by blocking a TCP disconnect callback
4468 	 * if a cluster tcp list walk is in progress. This ensures
4469 	 * accurate accounting of TCPs in the cluster code even though
4470 	 * the TCP list walk itself is not atomic.
4471 	 */
4472 	tcp_closei_local(tcp);
4473 	CONN_DEC_REF(tcp->tcp_connp);
4474 }
4475 
4476 /*
4477  * Stop all TCP timers, and free the timer mblks if requested.
4478  */
4479 void
4480 tcp_timers_stop(tcp_t *tcp)
4481 {
4482 	if (tcp->tcp_timer_tid != 0) {
4483 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4484 		tcp->tcp_timer_tid = 0;
4485 	}
4486 	if (tcp->tcp_ka_tid != 0) {
4487 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4488 		tcp->tcp_ka_tid = 0;
4489 	}
4490 	if (tcp->tcp_ack_tid != 0) {
4491 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4492 		tcp->tcp_ack_tid = 0;
4493 	}
4494 	if (tcp->tcp_push_tid != 0) {
4495 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4496 		tcp->tcp_push_tid = 0;
4497 	}
4498 }
4499 
4500 /*
4501  * The tcp_t is going away. Remove it from all lists and set it
4502  * to TCPS_CLOSED. The freeing up of memory is deferred until
4503  * tcp_inactive. This is needed since a thread in tcp_rput might have
4504  * done a CONN_INC_REF on this structure before it was removed from the
4505  * hashes.
4506  */
4507 static void
4508 tcp_closei_local(tcp_t *tcp)
4509 {
4510 	ire_t 	*ire;
4511 	conn_t	*connp = tcp->tcp_connp;
4512 
4513 	if (!TCP_IS_SOCKET(tcp))
4514 		tcp_acceptor_hash_remove(tcp);
4515 
4516 	UPDATE_MIB(&tcp_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4517 	tcp->tcp_ibsegs = 0;
4518 	UPDATE_MIB(&tcp_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4519 	tcp->tcp_obsegs = 0;
4520 
4521 	/*
4522 	 * If we are an eager connection hanging off a listener that
4523 	 * hasn't formally accepted the connection yet, get off his
4524 	 * list and blow off any data that we have accumulated.
4525 	 */
4526 	if (tcp->tcp_listener != NULL) {
4527 		tcp_t	*listener = tcp->tcp_listener;
4528 		mutex_enter(&listener->tcp_eager_lock);
4529 		/*
4530 		 * tcp_tconnind_started == B_TRUE means that the
4531 		 * conn_ind has already gone to listener. At
4532 		 * this point, eager will be closed but we
4533 		 * leave it in listeners eager list so that
4534 		 * if listener decides to close without doing
4535 		 * accept, we can clean this up. In tcp_wput_accept
4536 		 * we take care of the case of accept on closed
4537 		 * eager.
4538 		 */
4539 		if (!tcp->tcp_tconnind_started) {
4540 			tcp_eager_unlink(tcp);
4541 			mutex_exit(&listener->tcp_eager_lock);
4542 			/*
4543 			 * We don't want to have any pointers to the
4544 			 * listener queue, after we have released our
4545 			 * reference on the listener
4546 			 */
4547 			tcp->tcp_rq = tcp_g_q;
4548 			tcp->tcp_wq = WR(tcp_g_q);
4549 			CONN_DEC_REF(listener->tcp_connp);
4550 		} else {
4551 			mutex_exit(&listener->tcp_eager_lock);
4552 		}
4553 	}
4554 
4555 	/* Stop all the timers */
4556 	tcp_timers_stop(tcp);
4557 
4558 	if (tcp->tcp_state == TCPS_LISTEN) {
4559 		if (tcp->tcp_ip_addr_cache) {
4560 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4561 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4562 			tcp->tcp_ip_addr_cache = NULL;
4563 		}
4564 	}
4565 	mutex_enter(&tcp->tcp_non_sq_lock);
4566 	if (tcp->tcp_flow_stopped)
4567 		tcp_clrqfull(tcp);
4568 	mutex_exit(&tcp->tcp_non_sq_lock);
4569 
4570 	tcp_bind_hash_remove(tcp);
4571 	/*
4572 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4573 	 * is trying to remove this tcp from the time wait list, we will
4574 	 * block in tcp_time_wait_remove while trying to acquire the
4575 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4576 	 * requires the ipcl_hash_remove to be ordered after the
4577 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4578 	 */
4579 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4580 		(void) tcp_time_wait_remove(tcp, NULL);
4581 	CL_INET_DISCONNECT(tcp);
4582 	ipcl_hash_remove(connp);
4583 
4584 	/*
4585 	 * Delete the cached ire in conn_ire_cache and also mark
4586 	 * the conn as CONDEMNED
4587 	 */
4588 	mutex_enter(&connp->conn_lock);
4589 	connp->conn_state_flags |= CONN_CONDEMNED;
4590 	ire = connp->conn_ire_cache;
4591 	connp->conn_ire_cache = NULL;
4592 	mutex_exit(&connp->conn_lock);
4593 	if (ire != NULL)
4594 		IRE_REFRELE_NOTR(ire);
4595 
4596 	/* Need to cleanup any pending ioctls */
4597 	ASSERT(tcp->tcp_time_wait_next == NULL);
4598 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4599 	ASSERT(tcp->tcp_time_wait_expire == 0);
4600 	tcp->tcp_state = TCPS_CLOSED;
4601 
4602 	/* Release any SSL context */
4603 	if (tcp->tcp_kssl_ent != NULL) {
4604 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4605 		tcp->tcp_kssl_ent = NULL;
4606 	}
4607 	if (tcp->tcp_kssl_ctx != NULL) {
4608 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4609 		tcp->tcp_kssl_ctx = NULL;
4610 	}
4611 	tcp->tcp_kssl_pending = B_FALSE;
4612 }
4613 
4614 /*
4615  * tcp is dying (called from ipcl_conn_destroy and error cases).
4616  * Free the tcp_t in either case.
4617  */
4618 void
4619 tcp_free(tcp_t *tcp)
4620 {
4621 	mblk_t	*mp;
4622 	ip6_pkt_t	*ipp;
4623 
4624 	ASSERT(tcp != NULL);
4625 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4626 
4627 	tcp->tcp_rq = NULL;
4628 	tcp->tcp_wq = NULL;
4629 
4630 	tcp_close_mpp(&tcp->tcp_xmit_head);
4631 	tcp_close_mpp(&tcp->tcp_reass_head);
4632 	if (tcp->tcp_rcv_list != NULL) {
4633 		/* Free b_next chain */
4634 		tcp_close_mpp(&tcp->tcp_rcv_list);
4635 	}
4636 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4637 		freemsg(mp);
4638 	}
4639 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4640 		freemsg(mp);
4641 	}
4642 
4643 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4644 		freeb(tcp->tcp_fused_sigurg_mp);
4645 		tcp->tcp_fused_sigurg_mp = NULL;
4646 	}
4647 
4648 	if (tcp->tcp_sack_info != NULL) {
4649 		if (tcp->tcp_notsack_list != NULL) {
4650 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4651 		}
4652 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4653 	}
4654 
4655 	if (tcp->tcp_hopopts != NULL) {
4656 		mi_free(tcp->tcp_hopopts);
4657 		tcp->tcp_hopopts = NULL;
4658 		tcp->tcp_hopoptslen = 0;
4659 	}
4660 	ASSERT(tcp->tcp_hopoptslen == 0);
4661 	if (tcp->tcp_dstopts != NULL) {
4662 		mi_free(tcp->tcp_dstopts);
4663 		tcp->tcp_dstopts = NULL;
4664 		tcp->tcp_dstoptslen = 0;
4665 	}
4666 	ASSERT(tcp->tcp_dstoptslen == 0);
4667 	if (tcp->tcp_rtdstopts != NULL) {
4668 		mi_free(tcp->tcp_rtdstopts);
4669 		tcp->tcp_rtdstopts = NULL;
4670 		tcp->tcp_rtdstoptslen = 0;
4671 	}
4672 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4673 	if (tcp->tcp_rthdr != NULL) {
4674 		mi_free(tcp->tcp_rthdr);
4675 		tcp->tcp_rthdr = NULL;
4676 		tcp->tcp_rthdrlen = 0;
4677 	}
4678 	ASSERT(tcp->tcp_rthdrlen == 0);
4679 
4680 	ipp = &tcp->tcp_sticky_ipp;
4681 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4682 	    IPPF_RTHDR))
4683 		ip6_pkt_free(ipp);
4684 
4685 	/*
4686 	 * Free memory associated with the tcp/ip header template.
4687 	 */
4688 
4689 	if (tcp->tcp_iphc != NULL)
4690 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4691 
4692 	/*
4693 	 * Following is really a blowing away a union.
4694 	 * It happens to have exactly two members of identical size
4695 	 * the following code is enough.
4696 	 */
4697 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4698 
4699 	if (tcp->tcp_tracebuf != NULL) {
4700 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4701 		tcp->tcp_tracebuf = NULL;
4702 	}
4703 }
4704 
4705 
4706 /*
4707  * Put a connection confirmation message upstream built from the
4708  * address information within 'iph' and 'tcph'.  Report our success or failure.
4709  */
4710 static boolean_t
4711 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4712     mblk_t **defermp)
4713 {
4714 	sin_t	sin;
4715 	sin6_t	sin6;
4716 	mblk_t	*mp;
4717 	char	*optp = NULL;
4718 	int	optlen = 0;
4719 	cred_t	*cr;
4720 
4721 	if (defermp != NULL)
4722 		*defermp = NULL;
4723 
4724 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4725 		/*
4726 		 * Return in T_CONN_CON results of option negotiation through
4727 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4728 		 * negotiation, then what is received from remote end needs
4729 		 * to be taken into account but there is no such thing (yet?)
4730 		 * in our TCP/IP.
4731 		 * Note: We do not use mi_offset_param() here as
4732 		 * tcp_opts_conn_req contents do not directly come from
4733 		 * an application and are either generated in kernel or
4734 		 * from user input that was already verified.
4735 		 */
4736 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4737 		optp = (char *)(mp->b_rptr +
4738 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4739 		optlen = (int)
4740 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4741 	}
4742 
4743 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4744 		ipha_t *ipha = (ipha_t *)iphdr;
4745 
4746 		/* packet is IPv4 */
4747 		if (tcp->tcp_family == AF_INET) {
4748 			sin = sin_null;
4749 			sin.sin_addr.s_addr = ipha->ipha_src;
4750 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4751 			sin.sin_family = AF_INET;
4752 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4753 			    (int)sizeof (sin_t), optp, optlen);
4754 		} else {
4755 			sin6 = sin6_null;
4756 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4757 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4758 			sin6.sin6_family = AF_INET6;
4759 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4760 			    (int)sizeof (sin6_t), optp, optlen);
4761 
4762 		}
4763 	} else {
4764 		ip6_t	*ip6h = (ip6_t *)iphdr;
4765 
4766 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4767 		ASSERT(tcp->tcp_family == AF_INET6);
4768 		sin6 = sin6_null;
4769 		sin6.sin6_addr = ip6h->ip6_src;
4770 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4771 		sin6.sin6_family = AF_INET6;
4772 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4773 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4774 		    (int)sizeof (sin6_t), optp, optlen);
4775 	}
4776 
4777 	if (!mp)
4778 		return (B_FALSE);
4779 
4780 	if ((cr = DB_CRED(idmp)) != NULL) {
4781 		mblk_setcred(mp, cr);
4782 		DB_CPID(mp) = DB_CPID(idmp);
4783 	}
4784 
4785 	if (defermp == NULL)
4786 		putnext(tcp->tcp_rq, mp);
4787 	else
4788 		*defermp = mp;
4789 
4790 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4791 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4792 	return (B_TRUE);
4793 }
4794 
4795 /*
4796  * Defense for the SYN attack -
4797  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4798  *    one from the list of droppable eagers. This list is a subset of q0.
4799  *    see comments before the definition of MAKE_DROPPABLE().
4800  * 2. Don't drop a SYN request before its first timeout. This gives every
4801  *    request at least til the first timeout to complete its 3-way handshake.
4802  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4803  *    requests currently on the queue that has timed out. This will be used
4804  *    as an indicator of whether an attack is under way, so that appropriate
4805  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4806  *    either when eager goes into ESTABLISHED, or gets freed up.)
4807  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4808  *    # of timeout drops back to <= q0len/32 => SYN alert off
4809  */
4810 static boolean_t
4811 tcp_drop_q0(tcp_t *tcp)
4812 {
4813 	tcp_t	*eager;
4814 	mblk_t	*mp;
4815 
4816 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4817 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4818 
4819 	/* Pick oldest eager from the list of droppable eagers */
4820 	eager = tcp->tcp_eager_prev_drop_q0;
4821 
4822 	/* If list is empty. return B_FALSE */
4823 	if (eager == tcp) {
4824 		return (B_FALSE);
4825 	}
4826 
4827 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4828 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4829 		return (B_FALSE);
4830 
4831 	/*
4832 	 * Take this eager out from the list of droppable eagers since we are
4833 	 * going to drop it.
4834 	 */
4835 	MAKE_UNDROPPABLE(eager);
4836 
4837 	if (tcp->tcp_debug) {
4838 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4839 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4840 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
4841 		    tcp->tcp_conn_req_cnt_q0,
4842 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4843 	}
4844 
4845 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
4846 
4847 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4848 	CONN_INC_REF(eager->tcp_connp);
4849 
4850 	/* Mark the IRE created for this SYN request temporary */
4851 	tcp_ip_ire_mark_advice(eager);
4852 	squeue_fill(eager->tcp_connp->conn_sqp, mp,
4853 	    tcp_clean_death_wrapper, eager->tcp_connp, SQTAG_TCP_DROP_Q0);
4854 
4855 	return (B_TRUE);
4856 }
4857 
4858 int
4859 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4860     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4861 {
4862 	tcp_t 		*ltcp = lconnp->conn_tcp;
4863 	tcp_t		*tcp = connp->conn_tcp;
4864 	mblk_t		*tpi_mp;
4865 	ipha_t		*ipha;
4866 	ip6_t		*ip6h;
4867 	sin6_t 		sin6;
4868 	in6_addr_t 	v6dst;
4869 	int		err;
4870 	int		ifindex = 0;
4871 	cred_t		*cr;
4872 
4873 	if (ipvers == IPV4_VERSION) {
4874 		ipha = (ipha_t *)mp->b_rptr;
4875 
4876 		connp->conn_send = ip_output;
4877 		connp->conn_recv = tcp_input;
4878 
4879 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4880 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4881 
4882 		sin6 = sin6_null;
4883 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4884 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4885 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4886 		sin6.sin6_family = AF_INET6;
4887 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4888 		    lconnp->conn_zoneid);
4889 		if (tcp->tcp_recvdstaddr) {
4890 			sin6_t	sin6d;
4891 
4892 			sin6d = sin6_null;
4893 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4894 			    &sin6d.sin6_addr);
4895 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4896 			sin6d.sin6_family = AF_INET;
4897 			tpi_mp = mi_tpi_extconn_ind(NULL,
4898 			    (char *)&sin6d, sizeof (sin6_t),
4899 			    (char *)&tcp,
4900 			    (t_scalar_t)sizeof (intptr_t),
4901 			    (char *)&sin6d, sizeof (sin6_t),
4902 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4903 		} else {
4904 			tpi_mp = mi_tpi_conn_ind(NULL,
4905 			    (char *)&sin6, sizeof (sin6_t),
4906 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4907 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4908 		}
4909 	} else {
4910 		ip6h = (ip6_t *)mp->b_rptr;
4911 
4912 		connp->conn_send = ip_output_v6;
4913 		connp->conn_recv = tcp_input;
4914 
4915 		connp->conn_srcv6 = ip6h->ip6_dst;
4916 		connp->conn_remv6 = ip6h->ip6_src;
4917 
4918 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4919 		ifindex = (int)DB_CKSUMSTUFF(mp);
4920 		DB_CKSUMSTUFF(mp) = 0;
4921 
4922 		sin6 = sin6_null;
4923 		sin6.sin6_addr = ip6h->ip6_src;
4924 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4925 		sin6.sin6_family = AF_INET6;
4926 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4927 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4928 		    lconnp->conn_zoneid);
4929 
4930 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4931 			/* Pass up the scope_id of remote addr */
4932 			sin6.sin6_scope_id = ifindex;
4933 		} else {
4934 			sin6.sin6_scope_id = 0;
4935 		}
4936 		if (tcp->tcp_recvdstaddr) {
4937 			sin6_t	sin6d;
4938 
4939 			sin6d = sin6_null;
4940 			sin6.sin6_addr = ip6h->ip6_dst;
4941 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4942 			sin6d.sin6_family = AF_INET;
4943 			tpi_mp = mi_tpi_extconn_ind(NULL,
4944 			    (char *)&sin6d, sizeof (sin6_t),
4945 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4946 			    (char *)&sin6d, sizeof (sin6_t),
4947 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4948 		} else {
4949 			tpi_mp = mi_tpi_conn_ind(NULL,
4950 			    (char *)&sin6, sizeof (sin6_t),
4951 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4952 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4953 		}
4954 	}
4955 
4956 	if (tpi_mp == NULL)
4957 		return (ENOMEM);
4958 
4959 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4960 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4961 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4962 	connp->conn_fully_bound = B_FALSE;
4963 
4964 	if (tcp_trace)
4965 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4966 
4967 	/* Inherit information from the "parent" */
4968 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4969 	tcp->tcp_family = ltcp->tcp_family;
4970 	tcp->tcp_wq = ltcp->tcp_wq;
4971 	tcp->tcp_rq = ltcp->tcp_rq;
4972 	tcp->tcp_mss = tcp_mss_def_ipv6;
4973 	tcp->tcp_detached = B_TRUE;
4974 	if ((err = tcp_init_values(tcp)) != 0) {
4975 		freemsg(tpi_mp);
4976 		return (err);
4977 	}
4978 
4979 	if (ipvers == IPV4_VERSION) {
4980 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4981 			freemsg(tpi_mp);
4982 			return (err);
4983 		}
4984 		ASSERT(tcp->tcp_ipha != NULL);
4985 	} else {
4986 		/* ifindex must be already set */
4987 		ASSERT(ifindex != 0);
4988 
4989 		if (ltcp->tcp_bound_if != 0) {
4990 			/*
4991 			 * Set newtcp's bound_if equal to
4992 			 * listener's value. If ifindex is
4993 			 * not the same as ltcp->tcp_bound_if,
4994 			 * it must be a packet for the ipmp group
4995 			 * of interfaces
4996 			 */
4997 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4998 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4999 			tcp->tcp_bound_if = ifindex;
5000 		}
5001 
5002 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
5003 		tcp->tcp_recvifindex = 0;
5004 		tcp->tcp_recvhops = 0xffffffffU;
5005 		ASSERT(tcp->tcp_ip6h != NULL);
5006 	}
5007 
5008 	tcp->tcp_lport = ltcp->tcp_lport;
5009 
5010 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
5011 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
5012 			/*
5013 			 * Listener had options of some sort; eager inherits.
5014 			 * Free up the eager template and allocate one
5015 			 * of the right size.
5016 			 */
5017 			if (tcp->tcp_hdr_grown) {
5018 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
5019 			} else {
5020 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
5021 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
5022 			}
5023 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
5024 			    KM_NOSLEEP);
5025 			if (tcp->tcp_iphc == NULL) {
5026 				tcp->tcp_iphc_len = 0;
5027 				freemsg(tpi_mp);
5028 				return (ENOMEM);
5029 			}
5030 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
5031 			tcp->tcp_hdr_grown = B_TRUE;
5032 		}
5033 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5034 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5035 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5036 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
5037 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
5038 
5039 		/*
5040 		 * Copy the IP+TCP header template from listener to eager
5041 		 */
5042 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5043 		if (tcp->tcp_ipversion == IPV6_VERSION) {
5044 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
5045 			    IPPROTO_RAW) {
5046 				tcp->tcp_ip6h =
5047 				    (ip6_t *)(tcp->tcp_iphc +
5048 					sizeof (ip6i_t));
5049 			} else {
5050 				tcp->tcp_ip6h =
5051 				    (ip6_t *)(tcp->tcp_iphc);
5052 			}
5053 			tcp->tcp_ipha = NULL;
5054 		} else {
5055 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5056 			tcp->tcp_ip6h = NULL;
5057 		}
5058 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5059 		    tcp->tcp_ip_hdr_len);
5060 	} else {
5061 		/*
5062 		 * only valid case when ipversion of listener and
5063 		 * eager differ is when listener is IPv6 and
5064 		 * eager is IPv4.
5065 		 * Eager header template has been initialized to the
5066 		 * maximum v4 header sizes, which includes space for
5067 		 * TCP and IP options.
5068 		 */
5069 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5070 		    (tcp->tcp_ipversion == IPV4_VERSION));
5071 		ASSERT(tcp->tcp_iphc_len >=
5072 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5073 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5074 		/* copy IP header fields individually */
5075 		tcp->tcp_ipha->ipha_ttl =
5076 		    ltcp->tcp_ip6h->ip6_hops;
5077 		bcopy(ltcp->tcp_tcph->th_lport,
5078 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5079 	}
5080 
5081 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5082 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5083 	    sizeof (in_port_t));
5084 
5085 	if (ltcp->tcp_lport == 0) {
5086 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5087 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5088 		    sizeof (in_port_t));
5089 	}
5090 
5091 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5092 		ASSERT(ipha != NULL);
5093 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5094 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5095 
5096 		/* Source routing option copyover (reverse it) */
5097 		if (tcp_rev_src_routes)
5098 			tcp_opt_reverse(tcp, ipha);
5099 	} else {
5100 		ASSERT(ip6h != NULL);
5101 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5102 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5103 	}
5104 
5105 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5106 	ASSERT(!tcp->tcp_tconnind_started);
5107 	/*
5108 	 * If the SYN contains a credential, it's a loopback packet; attach
5109 	 * the credential to the TPI message.
5110 	 */
5111 	if ((cr = DB_CRED(idmp)) != NULL) {
5112 		mblk_setcred(tpi_mp, cr);
5113 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5114 	}
5115 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5116 
5117 	/* Inherit the listener's SSL protection state */
5118 
5119 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5120 		kssl_hold_ent(tcp->tcp_kssl_ent);
5121 		tcp->tcp_kssl_pending = B_TRUE;
5122 	}
5123 
5124 	return (0);
5125 }
5126 
5127 
5128 int
5129 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5130     tcph_t *tcph, mblk_t *idmp)
5131 {
5132 	tcp_t 		*ltcp = lconnp->conn_tcp;
5133 	tcp_t		*tcp = connp->conn_tcp;
5134 	sin_t		sin;
5135 	mblk_t		*tpi_mp = NULL;
5136 	int		err;
5137 	cred_t		*cr;
5138 
5139 	sin = sin_null;
5140 	sin.sin_addr.s_addr = ipha->ipha_src;
5141 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5142 	sin.sin_family = AF_INET;
5143 	if (ltcp->tcp_recvdstaddr) {
5144 		sin_t	sind;
5145 
5146 		sind = sin_null;
5147 		sind.sin_addr.s_addr = ipha->ipha_dst;
5148 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5149 		sind.sin_family = AF_INET;
5150 		tpi_mp = mi_tpi_extconn_ind(NULL,
5151 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5152 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5153 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5154 	} else {
5155 		tpi_mp = mi_tpi_conn_ind(NULL,
5156 		    (char *)&sin, sizeof (sin_t),
5157 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5158 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5159 	}
5160 
5161 	if (tpi_mp == NULL) {
5162 		return (ENOMEM);
5163 	}
5164 
5165 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5166 	connp->conn_send = ip_output;
5167 	connp->conn_recv = tcp_input;
5168 	connp->conn_fully_bound = B_FALSE;
5169 
5170 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5171 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5172 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5173 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5174 
5175 	if (tcp_trace) {
5176 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5177 	}
5178 
5179 	/* Inherit information from the "parent" */
5180 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5181 	tcp->tcp_family = ltcp->tcp_family;
5182 	tcp->tcp_wq = ltcp->tcp_wq;
5183 	tcp->tcp_rq = ltcp->tcp_rq;
5184 	tcp->tcp_mss = tcp_mss_def_ipv4;
5185 	tcp->tcp_detached = B_TRUE;
5186 	if ((err = tcp_init_values(tcp)) != 0) {
5187 		freemsg(tpi_mp);
5188 		return (err);
5189 	}
5190 
5191 	/*
5192 	 * Let's make sure that eager tcp template has enough space to
5193 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5194 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5195 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5196 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5197 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5198 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5199 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5200 	 */
5201 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5202 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5203 
5204 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5205 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5206 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5207 	tcp->tcp_ttl = ltcp->tcp_ttl;
5208 	tcp->tcp_tos = ltcp->tcp_tos;
5209 
5210 	/* Copy the IP+TCP header template from listener to eager */
5211 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5212 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5213 	tcp->tcp_ip6h = NULL;
5214 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5215 	    tcp->tcp_ip_hdr_len);
5216 
5217 	/* Initialize the IP addresses and Ports */
5218 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5219 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5220 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5221 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5222 
5223 	/* Source routing option copyover (reverse it) */
5224 	if (tcp_rev_src_routes)
5225 		tcp_opt_reverse(tcp, ipha);
5226 
5227 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5228 	ASSERT(!tcp->tcp_tconnind_started);
5229 
5230 	/*
5231 	 * If the SYN contains a credential, it's a loopback packet; attach
5232 	 * the credential to the TPI message.
5233 	 */
5234 	if ((cr = DB_CRED(idmp)) != NULL) {
5235 		mblk_setcred(tpi_mp, cr);
5236 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5237 	}
5238 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5239 
5240 	/* Inherit the listener's SSL protection state */
5241 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5242 		kssl_hold_ent(tcp->tcp_kssl_ent);
5243 		tcp->tcp_kssl_pending = B_TRUE;
5244 	}
5245 
5246 	return (0);
5247 }
5248 
5249 /*
5250  * sets up conn for ipsec.
5251  * if the first mblk is M_CTL it is consumed and mpp is updated.
5252  * in case of error mpp is freed.
5253  */
5254 conn_t *
5255 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5256 {
5257 	conn_t 		*connp = tcp->tcp_connp;
5258 	conn_t 		*econnp;
5259 	squeue_t 	*new_sqp;
5260 	mblk_t 		*first_mp = *mpp;
5261 	mblk_t		*mp = *mpp;
5262 	boolean_t	mctl_present = B_FALSE;
5263 	uint_t		ipvers;
5264 
5265 	econnp = tcp_get_conn(sqp);
5266 	if (econnp == NULL) {
5267 		freemsg(first_mp);
5268 		return (NULL);
5269 	}
5270 	if (DB_TYPE(mp) == M_CTL) {
5271 		if (mp->b_cont == NULL ||
5272 		    mp->b_cont->b_datap->db_type != M_DATA) {
5273 			freemsg(first_mp);
5274 			return (NULL);
5275 		}
5276 		mp = mp->b_cont;
5277 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5278 			freemsg(first_mp);
5279 			return (NULL);
5280 		}
5281 
5282 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5283 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5284 		mctl_present = B_TRUE;
5285 	} else {
5286 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5287 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5288 	}
5289 
5290 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5291 	DB_CKSUMSTART(mp) = 0;
5292 
5293 	ASSERT(OK_32PTR(mp->b_rptr));
5294 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5295 	if (ipvers == IPV4_VERSION) {
5296 		uint16_t  	*up;
5297 		uint32_t	ports;
5298 		ipha_t		*ipha;
5299 
5300 		ipha = (ipha_t *)mp->b_rptr;
5301 		up = (uint16_t *)((uchar_t *)ipha +
5302 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5303 		ports = *(uint32_t *)up;
5304 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5305 		    ipha->ipha_dst, ipha->ipha_src, ports);
5306 	} else {
5307 		uint16_t  	*up;
5308 		uint32_t	ports;
5309 		uint16_t	ip_hdr_len;
5310 		uint8_t		*nexthdrp;
5311 		ip6_t 		*ip6h;
5312 		tcph_t		*tcph;
5313 
5314 		ip6h = (ip6_t *)mp->b_rptr;
5315 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5316 			ip_hdr_len = IPV6_HDR_LEN;
5317 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5318 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5319 			CONN_DEC_REF(econnp);
5320 			freemsg(first_mp);
5321 			return (NULL);
5322 		}
5323 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5324 		up = (uint16_t *)tcph->th_lport;
5325 		ports = *(uint32_t *)up;
5326 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5327 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5328 	}
5329 
5330 	/*
5331 	 * The caller already ensured that there is a sqp present.
5332 	 */
5333 	econnp->conn_sqp = new_sqp;
5334 
5335 	if (connp->conn_policy != NULL) {
5336 		ipsec_in_t *ii;
5337 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5338 		ASSERT(ii->ipsec_in_policy == NULL);
5339 		IPPH_REFHOLD(connp->conn_policy);
5340 		ii->ipsec_in_policy = connp->conn_policy;
5341 
5342 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5343 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5344 			CONN_DEC_REF(econnp);
5345 			freemsg(first_mp);
5346 			return (NULL);
5347 		}
5348 	}
5349 
5350 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5351 		CONN_DEC_REF(econnp);
5352 		freemsg(first_mp);
5353 		return (NULL);
5354 	}
5355 
5356 	/*
5357 	 * If we know we have some policy, pass the "IPSEC"
5358 	 * options size TCP uses this adjust the MSS.
5359 	 */
5360 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5361 	if (mctl_present) {
5362 		freeb(first_mp);
5363 		*mpp = mp;
5364 	}
5365 
5366 	return (econnp);
5367 }
5368 
5369 /*
5370  * tcp_get_conn/tcp_free_conn
5371  *
5372  * tcp_get_conn is used to get a clean tcp connection structure.
5373  * It tries to reuse the connections put on the freelist by the
5374  * time_wait_collector failing which it goes to kmem_cache. This
5375  * way has two benefits compared to just allocating from and
5376  * freeing to kmem_cache.
5377  * 1) The time_wait_collector can free (which includes the cleanup)
5378  * outside the squeue. So when the interrupt comes, we have a clean
5379  * connection sitting in the freelist. Obviously, this buys us
5380  * performance.
5381  *
5382  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5383  * has multiple disadvantages - tying up the squeue during alloc, and the
5384  * fact that IPSec policy initialization has to happen here which
5385  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5386  * But allocating the conn/tcp in IP land is also not the best since
5387  * we can't check the 'q' and 'q0' which are protected by squeue and
5388  * blindly allocate memory which might have to be freed here if we are
5389  * not allowed to accept the connection. By using the freelist and
5390  * putting the conn/tcp back in freelist, we don't pay a penalty for
5391  * allocating memory without checking 'q/q0' and freeing it if we can't
5392  * accept the connection.
5393  *
5394  * Care should be taken to put the conn back in the same squeue's freelist
5395  * from which it was allocated. Best results are obtained if conn is
5396  * allocated from listener's squeue and freed to the same. Time wait
5397  * collector will free up the freelist is the connection ends up sitting
5398  * there for too long.
5399  */
5400 void *
5401 tcp_get_conn(void *arg)
5402 {
5403 	tcp_t			*tcp = NULL;
5404 	conn_t			*connp = NULL;
5405 	squeue_t		*sqp = (squeue_t *)arg;
5406 	tcp_squeue_priv_t 	*tcp_time_wait;
5407 
5408 	tcp_time_wait =
5409 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5410 
5411 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5412 	tcp = tcp_time_wait->tcp_free_list;
5413 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5414 	if (tcp != NULL) {
5415 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5416 		tcp_time_wait->tcp_free_list_cnt--;
5417 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5418 		tcp->tcp_time_wait_next = NULL;
5419 		connp = tcp->tcp_connp;
5420 		connp->conn_flags |= IPCL_REUSED;
5421 		return ((void *)connp);
5422 	}
5423 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5424 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
5425 		return (NULL);
5426 	return ((void *)connp);
5427 }
5428 
5429 /*
5430  * Update the cached label for the given tcp_t.  This should be called once per
5431  * connection, and before any packets are sent or tcp_process_options is
5432  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5433  */
5434 static boolean_t
5435 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5436 {
5437 	conn_t *connp = tcp->tcp_connp;
5438 
5439 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5440 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5441 		int added;
5442 
5443 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5444 		    connp->conn_mac_exempt) != 0)
5445 			return (B_FALSE);
5446 
5447 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5448 		if (added == -1)
5449 			return (B_FALSE);
5450 		tcp->tcp_hdr_len += added;
5451 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5452 		tcp->tcp_ip_hdr_len += added;
5453 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5454 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5455 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5456 			    tcp->tcp_hdr_len);
5457 			if (added == -1)
5458 				return (B_FALSE);
5459 			tcp->tcp_hdr_len += added;
5460 			tcp->tcp_tcph = (tcph_t *)
5461 			    ((uchar_t *)tcp->tcp_tcph + added);
5462 			tcp->tcp_ip_hdr_len += added;
5463 		}
5464 	} else {
5465 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5466 
5467 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5468 		    connp->conn_mac_exempt) != 0)
5469 			return (B_FALSE);
5470 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5471 		    &tcp->tcp_label_len, optbuf) != 0)
5472 			return (B_FALSE);
5473 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5474 			return (B_FALSE);
5475 	}
5476 
5477 	connp->conn_ulp_labeled = 1;
5478 
5479 	return (B_TRUE);
5480 }
5481 
5482 /* BEGIN CSTYLED */
5483 /*
5484  *
5485  * The sockfs ACCEPT path:
5486  * =======================
5487  *
5488  * The eager is now established in its own perimeter as soon as SYN is
5489  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5490  * completes the accept processing on the acceptor STREAM. The sending
5491  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5492  * listener but a TLI/XTI listener completes the accept processing
5493  * on the listener perimeter.
5494  *
5495  * Common control flow for 3 way handshake:
5496  * ----------------------------------------
5497  *
5498  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5499  *					-> tcp_conn_request()
5500  *
5501  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5502  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5503  *
5504  * Sockfs ACCEPT Path:
5505  * -------------------
5506  *
5507  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5508  * as STREAM entry point)
5509  *
5510  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5511  *
5512  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5513  * association (we are not behind eager's squeue but sockfs is protecting us
5514  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5515  * is changed to point at tcp_wput().
5516  *
5517  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5518  * listener (done on listener's perimeter).
5519  *
5520  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5521  * accept.
5522  *
5523  * TLI/XTI client ACCEPT path:
5524  * ---------------------------
5525  *
5526  * soaccept() sends T_CONN_RES on the listener STREAM.
5527  *
5528  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5529  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5530  *
5531  * Locks:
5532  * ======
5533  *
5534  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5535  * and listeners->tcp_eager_next_q.
5536  *
5537  * Referencing:
5538  * ============
5539  *
5540  * 1) We start out in tcp_conn_request by eager placing a ref on
5541  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5542  *
5543  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5544  * doing so we place a ref on the eager. This ref is finally dropped at the
5545  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5546  * reference is dropped by the squeue framework.
5547  *
5548  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5549  *
5550  * The reference must be released by the same entity that added the reference
5551  * In the above scheme, the eager is the entity that adds and releases the
5552  * references. Note that tcp_accept_finish executes in the squeue of the eager
5553  * (albeit after it is attached to the acceptor stream). Though 1. executes
5554  * in the listener's squeue, the eager is nascent at this point and the
5555  * reference can be considered to have been added on behalf of the eager.
5556  *
5557  * Eager getting a Reset or listener closing:
5558  * ==========================================
5559  *
5560  * Once the listener and eager are linked, the listener never does the unlink.
5561  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5562  * a message on all eager perimeter. The eager then does the unlink, clears
5563  * any pointers to the listener's queue and drops the reference to the
5564  * listener. The listener waits in tcp_close outside the squeue until its
5565  * refcount has dropped to 1. This ensures that the listener has waited for
5566  * all eagers to clear their association with the listener.
5567  *
5568  * Similarly, if eager decides to go away, it can unlink itself and close.
5569  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5570  * the reference to eager is still valid because of the extra ref we put
5571  * in tcp_send_conn_ind.
5572  *
5573  * Listener can always locate the eager under the protection
5574  * of the listener->tcp_eager_lock, and then do a refhold
5575  * on the eager during the accept processing.
5576  *
5577  * The acceptor stream accesses the eager in the accept processing
5578  * based on the ref placed on eager before sending T_conn_ind.
5579  * The only entity that can negate this refhold is a listener close
5580  * which is mutually exclusive with an active acceptor stream.
5581  *
5582  * Eager's reference on the listener
5583  * ===================================
5584  *
5585  * If the accept happens (even on a closed eager) the eager drops its
5586  * reference on the listener at the start of tcp_accept_finish. If the
5587  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5588  * the reference is dropped in tcp_closei_local. If the listener closes,
5589  * the reference is dropped in tcp_eager_kill. In all cases the reference
5590  * is dropped while executing in the eager's context (squeue).
5591  */
5592 /* END CSTYLED */
5593 
5594 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5595 
5596 /*
5597  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5598  * tcp_rput_data will not see any SYN packets.
5599  */
5600 /* ARGSUSED */
5601 void
5602 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5603 {
5604 	tcph_t		*tcph;
5605 	uint32_t	seg_seq;
5606 	tcp_t		*eager;
5607 	uint_t		ipvers;
5608 	ipha_t		*ipha;
5609 	ip6_t		*ip6h;
5610 	int		err;
5611 	conn_t		*econnp = NULL;
5612 	squeue_t	*new_sqp;
5613 	mblk_t		*mp1;
5614 	uint_t 		ip_hdr_len;
5615 	conn_t		*connp = (conn_t *)arg;
5616 	tcp_t		*tcp = connp->conn_tcp;
5617 	ire_t		*ire;
5618 	cred_t		*credp;
5619 
5620 	if (tcp->tcp_state != TCPS_LISTEN)
5621 		goto error2;
5622 
5623 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5624 
5625 	mutex_enter(&tcp->tcp_eager_lock);
5626 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5627 		mutex_exit(&tcp->tcp_eager_lock);
5628 		TCP_STAT(tcp_listendrop);
5629 		BUMP_MIB(&tcp_mib, tcpListenDrop);
5630 		if (tcp->tcp_debug) {
5631 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5632 			    "tcp_conn_request: listen backlog (max=%d) "
5633 			    "overflow (%d pending) on %s",
5634 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5635 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5636 		}
5637 		goto error2;
5638 	}
5639 
5640 	if (tcp->tcp_conn_req_cnt_q0 >=
5641 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
5642 		/*
5643 		 * Q0 is full. Drop a pending half-open req from the queue
5644 		 * to make room for the new SYN req. Also mark the time we
5645 		 * drop a SYN.
5646 		 *
5647 		 * A more aggressive defense against SYN attack will
5648 		 * be to set the "tcp_syn_defense" flag now.
5649 		 */
5650 		TCP_STAT(tcp_listendropq0);
5651 		tcp->tcp_last_rcv_lbolt = lbolt64;
5652 		if (!tcp_drop_q0(tcp)) {
5653 			mutex_exit(&tcp->tcp_eager_lock);
5654 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
5655 			if (tcp->tcp_debug) {
5656 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5657 				    "tcp_conn_request: listen half-open queue "
5658 				    "(max=%d) full (%d pending) on %s",
5659 				    tcp_conn_req_max_q0,
5660 				    tcp->tcp_conn_req_cnt_q0,
5661 				    tcp_display(tcp, NULL,
5662 				    DISP_PORT_ONLY));
5663 			}
5664 			goto error2;
5665 		}
5666 	}
5667 	mutex_exit(&tcp->tcp_eager_lock);
5668 
5669 	/*
5670 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5671 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5672 	 * link local address.  If IPSec is enabled, db_struioflag has
5673 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5674 	 * otherwise an error case if neither of them is set.
5675 	 */
5676 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5677 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5678 		DB_CKSUMSTART(mp) = 0;
5679 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5680 		econnp = (conn_t *)tcp_get_conn(arg2);
5681 		if (econnp == NULL)
5682 			goto error2;
5683 		econnp->conn_sqp = new_sqp;
5684 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5685 		/*
5686 		 * mp is updated in tcp_get_ipsec_conn().
5687 		 */
5688 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5689 		if (econnp == NULL) {
5690 			/*
5691 			 * mp freed by tcp_get_ipsec_conn.
5692 			 */
5693 			return;
5694 		}
5695 	} else {
5696 		goto error2;
5697 	}
5698 
5699 	ASSERT(DB_TYPE(mp) == M_DATA);
5700 
5701 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5702 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5703 	ASSERT(OK_32PTR(mp->b_rptr));
5704 	if (ipvers == IPV4_VERSION) {
5705 		ipha = (ipha_t *)mp->b_rptr;
5706 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5707 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5708 	} else {
5709 		ip6h = (ip6_t *)mp->b_rptr;
5710 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5711 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5712 	}
5713 
5714 	if (tcp->tcp_family == AF_INET) {
5715 		ASSERT(ipvers == IPV4_VERSION);
5716 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5717 	} else {
5718 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5719 	}
5720 
5721 	if (err)
5722 		goto error3;
5723 
5724 	eager = econnp->conn_tcp;
5725 
5726 	/* Inherit various TCP parameters from the listener */
5727 	eager->tcp_naglim = tcp->tcp_naglim;
5728 	eager->tcp_first_timer_threshold =
5729 	    tcp->tcp_first_timer_threshold;
5730 	eager->tcp_second_timer_threshold =
5731 	    tcp->tcp_second_timer_threshold;
5732 
5733 	eager->tcp_first_ctimer_threshold =
5734 	    tcp->tcp_first_ctimer_threshold;
5735 	eager->tcp_second_ctimer_threshold =
5736 	    tcp->tcp_second_ctimer_threshold;
5737 
5738 	/*
5739 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5740 	 * If it does not, the eager's receive window will be set to the
5741 	 * listener's receive window later in this function.
5742 	 */
5743 	eager->tcp_rwnd = 0;
5744 
5745 	/*
5746 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5747 	 * calling tcp_process_options() where tcp_mss_set() is called
5748 	 * to set the initial cwnd.
5749 	 */
5750 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5751 
5752 	/*
5753 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5754 	 * zone id before the accept is completed in tcp_wput_accept().
5755 	 */
5756 	econnp->conn_zoneid = connp->conn_zoneid;
5757 	econnp->conn_allzones = connp->conn_allzones;
5758 
5759 	/* Copy nexthop information from listener to eager */
5760 	if (connp->conn_nexthop_set) {
5761 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5762 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5763 	}
5764 
5765 	/*
5766 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5767 	 * eager is accepted
5768 	 */
5769 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5770 	crhold(credp);
5771 
5772 	/*
5773 	 * If the caller has the process-wide flag set, then default to MAC
5774 	 * exempt mode.  This allows read-down to unlabeled hosts.
5775 	 */
5776 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5777 		econnp->conn_mac_exempt = B_TRUE;
5778 
5779 	if (is_system_labeled()) {
5780 		cred_t *cr;
5781 
5782 		if (connp->conn_mlp_type != mlptSingle) {
5783 			cr = econnp->conn_peercred = DB_CRED(mp);
5784 			if (cr != NULL)
5785 				crhold(cr);
5786 			else
5787 				cr = econnp->conn_cred;
5788 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5789 			    econnp, cred_t *, cr)
5790 		} else {
5791 			cr = econnp->conn_cred;
5792 			DTRACE_PROBE2(syn_accept, conn_t *,
5793 			    econnp, cred_t *, cr)
5794 		}
5795 
5796 		if (!tcp_update_label(eager, cr)) {
5797 			DTRACE_PROBE3(
5798 			    tx__ip__log__error__connrequest__tcp,
5799 			    char *, "eager connp(1) label on SYN mp(2) failed",
5800 			    conn_t *, econnp, mblk_t *, mp);
5801 			goto error3;
5802 		}
5803 	}
5804 
5805 	eager->tcp_hard_binding = B_TRUE;
5806 
5807 	tcp_bind_hash_insert(&tcp_bind_fanout[
5808 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5809 
5810 	CL_INET_CONNECT(eager);
5811 
5812 	/*
5813 	 * No need to check for multicast destination since ip will only pass
5814 	 * up multicasts to those that have expressed interest
5815 	 * TODO: what about rejecting broadcasts?
5816 	 * Also check that source is not a multicast or broadcast address.
5817 	 */
5818 	eager->tcp_state = TCPS_SYN_RCVD;
5819 
5820 
5821 	/*
5822 	 * There should be no ire in the mp as we are being called after
5823 	 * receiving the SYN.
5824 	 */
5825 	ASSERT(tcp_ire_mp(mp) == NULL);
5826 
5827 	/*
5828 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5829 	 */
5830 
5831 	if (tcp_adapt_ire(eager, NULL) == 0) {
5832 		/* Undo the bind_hash_insert */
5833 		tcp_bind_hash_remove(eager);
5834 		goto error3;
5835 	}
5836 
5837 	/* Process all TCP options. */
5838 	tcp_process_options(eager, tcph);
5839 
5840 	/* Is the other end ECN capable? */
5841 	if (tcp_ecn_permitted >= 1 &&
5842 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5843 		eager->tcp_ecn_ok = B_TRUE;
5844 	}
5845 
5846 	/*
5847 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5848 	 * window size changed via SO_RCVBUF option.  First round up the
5849 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5850 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5851 	 * setting.
5852 	 *
5853 	 * Note if there is a rpipe metric associated with the remote host,
5854 	 * we should not inherit receive window size from listener.
5855 	 */
5856 	eager->tcp_rwnd = MSS_ROUNDUP(
5857 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5858 	    eager->tcp_rwnd), eager->tcp_mss);
5859 	if (eager->tcp_snd_ws_ok)
5860 		tcp_set_ws_value(eager);
5861 	/*
5862 	 * Note that this is the only place tcp_rwnd_set() is called for
5863 	 * accepting a connection.  We need to call it here instead of
5864 	 * after the 3-way handshake because we need to tell the other
5865 	 * side our rwnd in the SYN-ACK segment.
5866 	 */
5867 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5868 
5869 	/*
5870 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5871 	 * via soaccept()->soinheritoptions() which essentially applies
5872 	 * all the listener options to the new STREAM. The options that we
5873 	 * need to take care of are:
5874 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5875 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5876 	 * SO_SNDBUF, SO_RCVBUF.
5877 	 *
5878 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5879 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5880 	 *		tcp_maxpsz_set() gets called later from
5881 	 *		tcp_accept_finish(), the option takes effect.
5882 	 *
5883 	 */
5884 	/* Set the TCP options */
5885 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5886 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5887 	eager->tcp_oobinline = tcp->tcp_oobinline;
5888 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5889 	eager->tcp_broadcast = tcp->tcp_broadcast;
5890 	eager->tcp_useloopback = tcp->tcp_useloopback;
5891 	eager->tcp_dontroute = tcp->tcp_dontroute;
5892 	eager->tcp_linger = tcp->tcp_linger;
5893 	eager->tcp_lingertime = tcp->tcp_lingertime;
5894 	if (tcp->tcp_ka_enabled)
5895 		eager->tcp_ka_enabled = 1;
5896 
5897 	/* Set the IP options */
5898 	econnp->conn_broadcast = connp->conn_broadcast;
5899 	econnp->conn_loopback = connp->conn_loopback;
5900 	econnp->conn_dontroute = connp->conn_dontroute;
5901 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5902 
5903 	/* Put a ref on the listener for the eager. */
5904 	CONN_INC_REF(connp);
5905 	mutex_enter(&tcp->tcp_eager_lock);
5906 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5907 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5908 	tcp->tcp_eager_next_q0 = eager;
5909 	eager->tcp_eager_prev_q0 = tcp;
5910 
5911 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5912 	eager->tcp_listener = tcp;
5913 	eager->tcp_saved_listener = tcp;
5914 
5915 	/*
5916 	 * Tag this detached tcp vector for later retrieval
5917 	 * by our listener client in tcp_accept().
5918 	 */
5919 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5920 	tcp->tcp_conn_req_cnt_q0++;
5921 	if (++tcp->tcp_conn_req_seqnum == -1) {
5922 		/*
5923 		 * -1 is "special" and defined in TPI as something
5924 		 * that should never be used in T_CONN_IND
5925 		 */
5926 		++tcp->tcp_conn_req_seqnum;
5927 	}
5928 	mutex_exit(&tcp->tcp_eager_lock);
5929 
5930 	if (tcp->tcp_syn_defense) {
5931 		/* Don't drop the SYN that comes from a good IP source */
5932 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5933 		if (addr_cache != NULL && eager->tcp_remote ==
5934 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5935 			eager->tcp_dontdrop = B_TRUE;
5936 		}
5937 	}
5938 
5939 	/*
5940 	 * We need to insert the eager in its own perimeter but as soon
5941 	 * as we do that, we expose the eager to the classifier and
5942 	 * should not touch any field outside the eager's perimeter.
5943 	 * So do all the work necessary before inserting the eager
5944 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5945 	 * will succeed but undo everything if it fails.
5946 	 */
5947 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5948 	eager->tcp_irs = seg_seq;
5949 	eager->tcp_rack = seg_seq;
5950 	eager->tcp_rnxt = seg_seq + 1;
5951 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5952 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
5953 	eager->tcp_state = TCPS_SYN_RCVD;
5954 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5955 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5956 	if (mp1 == NULL)
5957 		goto error1;
5958 	DB_CPID(mp1) = tcp->tcp_cpid;
5959 	eager->tcp_cpid = tcp->tcp_cpid;
5960 	eager->tcp_open_time = lbolt64;
5961 
5962 	/*
5963 	 * We need to start the rto timer. In normal case, we start
5964 	 * the timer after sending the packet on the wire (or at
5965 	 * least believing that packet was sent by waiting for
5966 	 * CALL_IP_WPUT() to return). Since this is the first packet
5967 	 * being sent on the wire for the eager, our initial tcp_rto
5968 	 * is at least tcp_rexmit_interval_min which is a fairly
5969 	 * large value to allow the algorithm to adjust slowly to large
5970 	 * fluctuations of RTT during first few transmissions.
5971 	 *
5972 	 * Starting the timer first and then sending the packet in this
5973 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5974 	 * is of the order of several 100ms and starting the timer
5975 	 * first and then sending the packet will result in difference
5976 	 * of few micro seconds.
5977 	 *
5978 	 * Without this optimization, we are forced to hold the fanout
5979 	 * lock across the ipcl_bind_insert() and sending the packet
5980 	 * so that we don't race against an incoming packet (maybe RST)
5981 	 * for this eager.
5982 	 */
5983 
5984 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5985 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5986 
5987 
5988 	/*
5989 	 * Insert the eager in its own perimeter now. We are ready to deal
5990 	 * with any packets on eager.
5991 	 */
5992 	if (eager->tcp_ipversion == IPV4_VERSION) {
5993 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5994 			goto error;
5995 		}
5996 	} else {
5997 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5998 			goto error;
5999 		}
6000 	}
6001 
6002 	/* mark conn as fully-bound */
6003 	econnp->conn_fully_bound = B_TRUE;
6004 
6005 	/* Send the SYN-ACK */
6006 	tcp_send_data(eager, eager->tcp_wq, mp1);
6007 	freemsg(mp);
6008 
6009 	return;
6010 error:
6011 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
6012 	freemsg(mp1);
6013 error1:
6014 	/* Undo what we did above */
6015 	mutex_enter(&tcp->tcp_eager_lock);
6016 	tcp_eager_unlink(eager);
6017 	mutex_exit(&tcp->tcp_eager_lock);
6018 	/* Drop eager's reference on the listener */
6019 	CONN_DEC_REF(connp);
6020 
6021 	/*
6022 	 * Delete the cached ire in conn_ire_cache and also mark
6023 	 * the conn as CONDEMNED
6024 	 */
6025 	mutex_enter(&econnp->conn_lock);
6026 	econnp->conn_state_flags |= CONN_CONDEMNED;
6027 	ire = econnp->conn_ire_cache;
6028 	econnp->conn_ire_cache = NULL;
6029 	mutex_exit(&econnp->conn_lock);
6030 	if (ire != NULL)
6031 		IRE_REFRELE_NOTR(ire);
6032 
6033 	/*
6034 	 * tcp_accept_comm inserts the eager to the bind_hash
6035 	 * we need to remove it from the hash if ipcl_conn_insert
6036 	 * fails.
6037 	 */
6038 	tcp_bind_hash_remove(eager);
6039 	/* Drop the eager ref placed in tcp_open_detached */
6040 	CONN_DEC_REF(econnp);
6041 
6042 	/*
6043 	 * If a connection already exists, send the mp to that connections so
6044 	 * that it can be appropriately dealt with.
6045 	 */
6046 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
6047 		if (!IPCL_IS_CONNECTED(econnp)) {
6048 			/*
6049 			 * Something bad happened. ipcl_conn_insert()
6050 			 * failed because a connection already existed
6051 			 * in connected hash but we can't find it
6052 			 * anymore (someone blew it away). Just
6053 			 * free this message and hopefully remote
6054 			 * will retransmit at which time the SYN can be
6055 			 * treated as a new connection or dealth with
6056 			 * a TH_RST if a connection already exists.
6057 			 */
6058 			CONN_DEC_REF(econnp);
6059 			freemsg(mp);
6060 		} else {
6061 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
6062 			    econnp, SQTAG_TCP_CONN_REQ);
6063 		}
6064 	} else {
6065 		/* Nobody wants this packet */
6066 		freemsg(mp);
6067 	}
6068 	return;
6069 error2:
6070 	freemsg(mp);
6071 	return;
6072 error3:
6073 	CONN_DEC_REF(econnp);
6074 	freemsg(mp);
6075 }
6076 
6077 /*
6078  * In an ideal case of vertical partition in NUMA architecture, its
6079  * beneficial to have the listener and all the incoming connections
6080  * tied to the same squeue. The other constraint is that incoming
6081  * connections should be tied to the squeue attached to interrupted
6082  * CPU for obvious locality reason so this leaves the listener to
6083  * be tied to the same squeue. Our only problem is that when listener
6084  * is binding, the CPU that will get interrupted by the NIC whose
6085  * IP address the listener is binding to is not even known. So
6086  * the code below allows us to change that binding at the time the
6087  * CPU is interrupted by virtue of incoming connection's squeue.
6088  *
6089  * This is usefull only in case of a listener bound to a specific IP
6090  * address. For other kind of listeners, they get bound the
6091  * very first time and there is no attempt to rebind them.
6092  */
6093 void
6094 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6095 {
6096 	conn_t		*connp = (conn_t *)arg;
6097 	squeue_t	*sqp = (squeue_t *)arg2;
6098 	squeue_t	*new_sqp;
6099 	uint32_t	conn_flags;
6100 
6101 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6102 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
6103 	} else {
6104 		goto done;
6105 	}
6106 
6107 	if (connp->conn_fanout == NULL)
6108 		goto done;
6109 
6110 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6111 		mutex_enter(&connp->conn_fanout->connf_lock);
6112 		mutex_enter(&connp->conn_lock);
6113 		/*
6114 		 * No one from read or write side can access us now
6115 		 * except for already queued packets on this squeue.
6116 		 * But since we haven't changed the squeue yet, they
6117 		 * can't execute. If they are processed after we have
6118 		 * changed the squeue, they are sent back to the
6119 		 * correct squeue down below.
6120 		 * But a listner close can race with processing of
6121 		 * incoming SYN. If incoming SYN processing changes
6122 		 * the squeue then the listener close which is waiting
6123 		 * to enter the squeue would operate on the wrong
6124 		 * squeue. Hence we don't change the squeue here unless
6125 		 * the refcount is exactly the minimum refcount. The
6126 		 * minimum refcount of 4 is counted as - 1 each for
6127 		 * TCP and IP, 1 for being in the classifier hash, and
6128 		 * 1 for the mblk being processed.
6129 		 */
6130 
6131 		if (connp->conn_ref != 4 ||
6132 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
6133 			mutex_exit(&connp->conn_lock);
6134 			mutex_exit(&connp->conn_fanout->connf_lock);
6135 			goto done;
6136 		}
6137 		if (connp->conn_sqp != new_sqp) {
6138 			while (connp->conn_sqp != new_sqp)
6139 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6140 		}
6141 
6142 		do {
6143 			conn_flags = connp->conn_flags;
6144 			conn_flags |= IPCL_FULLY_BOUND;
6145 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6146 			    conn_flags);
6147 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6148 
6149 		mutex_exit(&connp->conn_fanout->connf_lock);
6150 		mutex_exit(&connp->conn_lock);
6151 	}
6152 
6153 done:
6154 	if (connp->conn_sqp != sqp) {
6155 		CONN_INC_REF(connp);
6156 		squeue_fill(connp->conn_sqp, mp,
6157 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6158 	} else {
6159 		tcp_conn_request(connp, mp, sqp);
6160 	}
6161 }
6162 
6163 /*
6164  * Successful connect request processing begins when our client passes
6165  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6166  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6167  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6168  *   upstream <- tcp_rput()                <- IP
6169  * After various error checks are completed, tcp_connect() lays
6170  * the target address and port into the composite header template,
6171  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6172  * request followed by an IRE request, and passes the three mblk message
6173  * down to IP looking like this:
6174  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6175  * Processing continues in tcp_rput() when we receive the following message:
6176  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6177  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6178  * to fire off the connection request, and then passes the T_OK_ACK mblk
6179  * upstream that we filled in below.  There are, of course, numerous
6180  * error conditions along the way which truncate the processing described
6181  * above.
6182  */
6183 static void
6184 tcp_connect(tcp_t *tcp, mblk_t *mp)
6185 {
6186 	sin_t		*sin;
6187 	sin6_t		*sin6;
6188 	queue_t		*q = tcp->tcp_wq;
6189 	struct T_conn_req	*tcr;
6190 	ipaddr_t	*dstaddrp;
6191 	in_port_t	dstport;
6192 	uint_t		srcid;
6193 
6194 	tcr = (struct T_conn_req *)mp->b_rptr;
6195 
6196 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6197 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6198 		tcp_err_ack(tcp, mp, TPROTO, 0);
6199 		return;
6200 	}
6201 
6202 	/*
6203 	 * Determine packet type based on type of address passed in
6204 	 * the request should contain an IPv4 or IPv6 address.
6205 	 * Make sure that address family matches the type of
6206 	 * family of the the address passed down
6207 	 */
6208 	switch (tcr->DEST_length) {
6209 	default:
6210 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6211 		return;
6212 
6213 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6214 		/*
6215 		 * XXX: The check for valid DEST_length was not there
6216 		 * in earlier releases and some buggy
6217 		 * TLI apps (e.g Sybase) got away with not feeding
6218 		 * in sin_zero part of address.
6219 		 * We allow that bug to keep those buggy apps humming.
6220 		 * Test suites require the check on DEST_length.
6221 		 * We construct a new mblk with valid DEST_length
6222 		 * free the original so the rest of the code does
6223 		 * not have to keep track of this special shorter
6224 		 * length address case.
6225 		 */
6226 		mblk_t *nmp;
6227 		struct T_conn_req *ntcr;
6228 		sin_t *nsin;
6229 
6230 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6231 		    tcr->OPT_length, BPRI_HI);
6232 		if (nmp == NULL) {
6233 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6234 			return;
6235 		}
6236 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6237 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6238 		ntcr->PRIM_type = T_CONN_REQ;
6239 		ntcr->DEST_length = sizeof (sin_t);
6240 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6241 
6242 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6243 		*nsin = sin_null;
6244 		/* Get pointer to shorter address to copy from original mp */
6245 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6246 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6247 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6248 			freemsg(nmp);
6249 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6250 			return;
6251 		}
6252 		nsin->sin_family = sin->sin_family;
6253 		nsin->sin_port = sin->sin_port;
6254 		nsin->sin_addr = sin->sin_addr;
6255 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6256 		nmp->b_wptr = (uchar_t *)&nsin[1];
6257 		if (tcr->OPT_length != 0) {
6258 			ntcr->OPT_length = tcr->OPT_length;
6259 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6260 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6261 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6262 			    tcr->OPT_length);
6263 			nmp->b_wptr += tcr->OPT_length;
6264 		}
6265 		freemsg(mp);	/* original mp freed */
6266 		mp = nmp;	/* re-initialize original variables */
6267 		tcr = ntcr;
6268 	}
6269 	/* FALLTHRU */
6270 
6271 	case sizeof (sin_t):
6272 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6273 		    sizeof (sin_t));
6274 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6275 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6276 			return;
6277 		}
6278 		if (tcp->tcp_family != AF_INET ||
6279 		    sin->sin_family != AF_INET) {
6280 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6281 			return;
6282 		}
6283 		if (sin->sin_port == 0) {
6284 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6285 			return;
6286 		}
6287 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6288 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6289 			return;
6290 		}
6291 
6292 		break;
6293 
6294 	case sizeof (sin6_t):
6295 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6296 		    sizeof (sin6_t));
6297 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6298 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6299 			return;
6300 		}
6301 		if (tcp->tcp_family != AF_INET6 ||
6302 		    sin6->sin6_family != AF_INET6) {
6303 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6304 			return;
6305 		}
6306 		if (sin6->sin6_port == 0) {
6307 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6308 			return;
6309 		}
6310 		break;
6311 	}
6312 	/*
6313 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6314 	 * should key on their sequence number and cut them loose.
6315 	 */
6316 
6317 	/*
6318 	 * If options passed in, feed it for verification and handling
6319 	 */
6320 	if (tcr->OPT_length != 0) {
6321 		mblk_t	*ok_mp;
6322 		mblk_t	*discon_mp;
6323 		mblk_t  *conn_opts_mp;
6324 		int t_error, sys_error, do_disconnect;
6325 
6326 		conn_opts_mp = NULL;
6327 
6328 		if (tcp_conprim_opt_process(tcp, mp,
6329 			&do_disconnect, &t_error, &sys_error) < 0) {
6330 			if (do_disconnect) {
6331 				ASSERT(t_error == 0 && sys_error == 0);
6332 				discon_mp = mi_tpi_discon_ind(NULL,
6333 				    ECONNREFUSED, 0);
6334 				if (!discon_mp) {
6335 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6336 					    TSYSERR, ENOMEM);
6337 					return;
6338 				}
6339 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6340 				if (!ok_mp) {
6341 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6342 					    TSYSERR, ENOMEM);
6343 					return;
6344 				}
6345 				qreply(q, ok_mp);
6346 				qreply(q, discon_mp); /* no flush! */
6347 			} else {
6348 				ASSERT(t_error != 0);
6349 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6350 				    sys_error);
6351 			}
6352 			return;
6353 		}
6354 		/*
6355 		 * Success in setting options, the mp option buffer represented
6356 		 * by OPT_length/offset has been potentially modified and
6357 		 * contains results of option processing. We copy it in
6358 		 * another mp to save it for potentially influencing returning
6359 		 * it in T_CONN_CONN.
6360 		 */
6361 		if (tcr->OPT_length != 0) { /* there are resulting options */
6362 			conn_opts_mp = copyb(mp);
6363 			if (!conn_opts_mp) {
6364 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6365 				    TSYSERR, ENOMEM);
6366 				return;
6367 			}
6368 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6369 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6370 			/*
6371 			 * Note:
6372 			 * These resulting option negotiation can include any
6373 			 * end-to-end negotiation options but there no such
6374 			 * thing (yet?) in our TCP/IP.
6375 			 */
6376 		}
6377 	}
6378 
6379 	/*
6380 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6381 	 * make sure that the template IP header in the tcp structure is an
6382 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6383 	 * need to this before we call tcp_bindi() so that the port lookup
6384 	 * code will look for ports in the correct port space (IPv4 and
6385 	 * IPv6 have separate port spaces).
6386 	 */
6387 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6388 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6389 		int err = 0;
6390 
6391 		err = tcp_header_init_ipv4(tcp);
6392 		if (err != 0) {
6393 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6394 			goto connect_failed;
6395 		}
6396 		if (tcp->tcp_lport != 0)
6397 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6398 	}
6399 
6400 	switch (tcp->tcp_state) {
6401 	case TCPS_IDLE:
6402 		/*
6403 		 * We support quick connect, refer to comments in
6404 		 * tcp_connect_*()
6405 		 */
6406 		/* FALLTHRU */
6407 	case TCPS_BOUND:
6408 	case TCPS_LISTEN:
6409 		if (tcp->tcp_family == AF_INET6) {
6410 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6411 				tcp_connect_ipv6(tcp, mp,
6412 				    &sin6->sin6_addr,
6413 				    sin6->sin6_port, sin6->sin6_flowinfo,
6414 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6415 				return;
6416 			}
6417 			/*
6418 			 * Destination adress is mapped IPv6 address.
6419 			 * Source bound address should be unspecified or
6420 			 * IPv6 mapped address as well.
6421 			 */
6422 			if (!IN6_IS_ADDR_UNSPECIFIED(
6423 			    &tcp->tcp_bound_source_v6) &&
6424 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6425 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6426 				    EADDRNOTAVAIL);
6427 				break;
6428 			}
6429 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6430 			dstport = sin6->sin6_port;
6431 			srcid = sin6->__sin6_src_id;
6432 		} else {
6433 			dstaddrp = &sin->sin_addr.s_addr;
6434 			dstport = sin->sin_port;
6435 			srcid = 0;
6436 		}
6437 
6438 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6439 		return;
6440 	default:
6441 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6442 		break;
6443 	}
6444 	/*
6445 	 * Note: Code below is the "failure" case
6446 	 */
6447 	/* return error ack and blow away saved option results if any */
6448 connect_failed:
6449 	if (mp != NULL)
6450 		putnext(tcp->tcp_rq, mp);
6451 	else {
6452 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6453 		    TSYSERR, ENOMEM);
6454 	}
6455 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6456 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6457 }
6458 
6459 /*
6460  * Handle connect to IPv4 destinations, including connections for AF_INET6
6461  * sockets connecting to IPv4 mapped IPv6 destinations.
6462  */
6463 static void
6464 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6465     uint_t srcid)
6466 {
6467 	tcph_t	*tcph;
6468 	mblk_t	*mp1;
6469 	ipaddr_t dstaddr = *dstaddrp;
6470 	int32_t	oldstate;
6471 	uint16_t lport;
6472 
6473 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6474 
6475 	/* Check for attempt to connect to INADDR_ANY */
6476 	if (dstaddr == INADDR_ANY)  {
6477 		/*
6478 		 * SunOS 4.x and 4.3 BSD allow an application
6479 		 * to connect a TCP socket to INADDR_ANY.
6480 		 * When they do this, the kernel picks the
6481 		 * address of one interface and uses it
6482 		 * instead.  The kernel usually ends up
6483 		 * picking the address of the loopback
6484 		 * interface.  This is an undocumented feature.
6485 		 * However, we provide the same thing here
6486 		 * in order to have source and binary
6487 		 * compatibility with SunOS 4.x.
6488 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6489 		 * generate the T_CONN_CON.
6490 		 */
6491 		dstaddr = htonl(INADDR_LOOPBACK);
6492 		*dstaddrp = dstaddr;
6493 	}
6494 
6495 	/* Handle __sin6_src_id if socket not bound to an IP address */
6496 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6497 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6498 		    tcp->tcp_connp->conn_zoneid);
6499 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6500 		    tcp->tcp_ipha->ipha_src);
6501 	}
6502 
6503 	/*
6504 	 * Don't let an endpoint connect to itself.  Note that
6505 	 * the test here does not catch the case where the
6506 	 * source IP addr was left unspecified by the user. In
6507 	 * this case, the source addr is set in tcp_adapt_ire()
6508 	 * using the reply to the T_BIND message that we send
6509 	 * down to IP here and the check is repeated in tcp_rput_other.
6510 	 */
6511 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6512 	    dstport == tcp->tcp_lport) {
6513 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6514 		goto failed;
6515 	}
6516 
6517 	tcp->tcp_ipha->ipha_dst = dstaddr;
6518 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6519 
6520 	/*
6521 	 * Massage a source route if any putting the first hop
6522 	 * in iph_dst. Compute a starting value for the checksum which
6523 	 * takes into account that the original iph_dst should be
6524 	 * included in the checksum but that ip will include the
6525 	 * first hop in the source route in the tcp checksum.
6526 	 */
6527 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
6528 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6529 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6530 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6531 	if ((int)tcp->tcp_sum < 0)
6532 		tcp->tcp_sum--;
6533 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6534 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6535 	    (tcp->tcp_sum >> 16));
6536 	tcph = tcp->tcp_tcph;
6537 	*(uint16_t *)tcph->th_fport = dstport;
6538 	tcp->tcp_fport = dstport;
6539 
6540 	oldstate = tcp->tcp_state;
6541 	/*
6542 	 * At this point the remote destination address and remote port fields
6543 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6544 	 * have to see which state tcp was in so we can take apropriate action.
6545 	 */
6546 	if (oldstate == TCPS_IDLE) {
6547 		/*
6548 		 * We support a quick connect capability here, allowing
6549 		 * clients to transition directly from IDLE to SYN_SENT
6550 		 * tcp_bindi will pick an unused port, insert the connection
6551 		 * in the bind hash and transition to BOUND state.
6552 		 */
6553 		lport = tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
6554 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6555 		    B_FALSE, B_FALSE);
6556 		if (lport == 0) {
6557 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6558 			goto failed;
6559 		}
6560 	}
6561 	tcp->tcp_state = TCPS_SYN_SENT;
6562 
6563 	/*
6564 	 * TODO: allow data with connect requests
6565 	 * by unlinking M_DATA trailers here and
6566 	 * linking them in behind the T_OK_ACK mblk.
6567 	 * The tcp_rput() bind ack handler would then
6568 	 * feed them to tcp_wput_data() rather than call
6569 	 * tcp_timer().
6570 	 */
6571 	mp = mi_tpi_ok_ack_alloc(mp);
6572 	if (!mp) {
6573 		tcp->tcp_state = oldstate;
6574 		goto failed;
6575 	}
6576 	if (tcp->tcp_family == AF_INET) {
6577 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6578 		    sizeof (ipa_conn_t));
6579 	} else {
6580 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6581 		    sizeof (ipa6_conn_t));
6582 	}
6583 	if (mp1) {
6584 		/* Hang onto the T_OK_ACK for later. */
6585 		linkb(mp1, mp);
6586 		mblk_setcred(mp1, tcp->tcp_cred);
6587 		if (tcp->tcp_family == AF_INET)
6588 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6589 		else {
6590 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6591 			    &tcp->tcp_sticky_ipp);
6592 		}
6593 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6594 		tcp->tcp_active_open = 1;
6595 		/*
6596 		 * If the bind cannot complete immediately
6597 		 * IP will arrange to call tcp_rput_other
6598 		 * when the bind completes.
6599 		 */
6600 		if (mp1 != NULL)
6601 			tcp_rput_other(tcp, mp1);
6602 		return;
6603 	}
6604 	/* Error case */
6605 	tcp->tcp_state = oldstate;
6606 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6607 
6608 failed:
6609 	/* return error ack and blow away saved option results if any */
6610 	if (mp != NULL)
6611 		putnext(tcp->tcp_rq, mp);
6612 	else {
6613 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6614 		    TSYSERR, ENOMEM);
6615 	}
6616 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6617 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6618 
6619 }
6620 
6621 /*
6622  * Handle connect to IPv6 destinations.
6623  */
6624 static void
6625 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6626     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6627 {
6628 	tcph_t	*tcph;
6629 	mblk_t	*mp1;
6630 	ip6_rthdr_t *rth;
6631 	int32_t  oldstate;
6632 	uint16_t lport;
6633 
6634 	ASSERT(tcp->tcp_family == AF_INET6);
6635 
6636 	/*
6637 	 * If we're here, it means that the destination address is a native
6638 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6639 	 * reason why it might not be IPv6 is if the socket was bound to an
6640 	 * IPv4-mapped IPv6 address.
6641 	 */
6642 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6643 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6644 		goto failed;
6645 	}
6646 
6647 	/*
6648 	 * Interpret a zero destination to mean loopback.
6649 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6650 	 * generate the T_CONN_CON.
6651 	 */
6652 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6653 		*dstaddrp = ipv6_loopback;
6654 	}
6655 
6656 	/* Handle __sin6_src_id if socket not bound to an IP address */
6657 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6658 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6659 		    tcp->tcp_connp->conn_zoneid);
6660 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6661 	}
6662 
6663 	/*
6664 	 * Take care of the scope_id now and add ip6i_t
6665 	 * if ip6i_t is not already allocated through TCP
6666 	 * sticky options. At this point tcp_ip6h does not
6667 	 * have dst info, thus use dstaddrp.
6668 	 */
6669 	if (scope_id != 0 &&
6670 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6671 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6672 		ip6i_t  *ip6i;
6673 
6674 		ipp->ipp_ifindex = scope_id;
6675 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6676 
6677 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6678 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6679 			/* Already allocated */
6680 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6681 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6682 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6683 		} else {
6684 			int reterr;
6685 
6686 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6687 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6688 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6689 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6690 			if (reterr != 0)
6691 				goto failed;
6692 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6693 		}
6694 	}
6695 
6696 	/*
6697 	 * Don't let an endpoint connect to itself.  Note that
6698 	 * the test here does not catch the case where the
6699 	 * source IP addr was left unspecified by the user. In
6700 	 * this case, the source addr is set in tcp_adapt_ire()
6701 	 * using the reply to the T_BIND message that we send
6702 	 * down to IP here and the check is repeated in tcp_rput_other.
6703 	 */
6704 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6705 	    (dstport == tcp->tcp_lport)) {
6706 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6707 		goto failed;
6708 	}
6709 
6710 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6711 	tcp->tcp_remote_v6 = *dstaddrp;
6712 	tcp->tcp_ip6h->ip6_vcf =
6713 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6714 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6715 
6716 
6717 	/*
6718 	 * Massage a routing header (if present) putting the first hop
6719 	 * in ip6_dst. Compute a starting value for the checksum which
6720 	 * takes into account that the original ip6_dst should be
6721 	 * included in the checksum but that ip will include the
6722 	 * first hop in the source route in the tcp checksum.
6723 	 */
6724 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6725 	if (rth != NULL) {
6726 
6727 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
6728 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6729 		    (tcp->tcp_sum >> 16));
6730 	} else {
6731 		tcp->tcp_sum = 0;
6732 	}
6733 
6734 	tcph = tcp->tcp_tcph;
6735 	*(uint16_t *)tcph->th_fport = dstport;
6736 	tcp->tcp_fport = dstport;
6737 
6738 	oldstate = tcp->tcp_state;
6739 	/*
6740 	 * At this point the remote destination address and remote port fields
6741 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6742 	 * have to see which state tcp was in so we can take apropriate action.
6743 	 */
6744 	if (oldstate == TCPS_IDLE) {
6745 		/*
6746 		 * We support a quick connect capability here, allowing
6747 		 * clients to transition directly from IDLE to SYN_SENT
6748 		 * tcp_bindi will pick an unused port, insert the connection
6749 		 * in the bind hash and transition to BOUND state.
6750 		 */
6751 		lport = tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
6752 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6753 		    B_FALSE, B_FALSE);
6754 		if (lport == 0) {
6755 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6756 			goto failed;
6757 		}
6758 	}
6759 	tcp->tcp_state = TCPS_SYN_SENT;
6760 	/*
6761 	 * TODO: allow data with connect requests
6762 	 * by unlinking M_DATA trailers here and
6763 	 * linking them in behind the T_OK_ACK mblk.
6764 	 * The tcp_rput() bind ack handler would then
6765 	 * feed them to tcp_wput_data() rather than call
6766 	 * tcp_timer().
6767 	 */
6768 	mp = mi_tpi_ok_ack_alloc(mp);
6769 	if (!mp) {
6770 		tcp->tcp_state = oldstate;
6771 		goto failed;
6772 	}
6773 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6774 	if (mp1) {
6775 		/* Hang onto the T_OK_ACK for later. */
6776 		linkb(mp1, mp);
6777 		mblk_setcred(mp1, tcp->tcp_cred);
6778 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6779 		    &tcp->tcp_sticky_ipp);
6780 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6781 		tcp->tcp_active_open = 1;
6782 		/* ip_bind_v6() may return ACK or ERROR */
6783 		if (mp1 != NULL)
6784 			tcp_rput_other(tcp, mp1);
6785 		return;
6786 	}
6787 	/* Error case */
6788 	tcp->tcp_state = oldstate;
6789 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6790 
6791 failed:
6792 	/* return error ack and blow away saved option results if any */
6793 	if (mp != NULL)
6794 		putnext(tcp->tcp_rq, mp);
6795 	else {
6796 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6797 		    TSYSERR, ENOMEM);
6798 	}
6799 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6800 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6801 }
6802 
6803 /*
6804  * We need a stream q for detached closing tcp connections
6805  * to use.  Our client hereby indicates that this q is the
6806  * one to use.
6807  */
6808 static void
6809 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6810 {
6811 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6812 	queue_t	*q = tcp->tcp_wq;
6813 
6814 	mp->b_datap->db_type = M_IOCACK;
6815 	iocp->ioc_count = 0;
6816 	mutex_enter(&tcp_g_q_lock);
6817 	if (tcp_g_q != NULL) {
6818 		mutex_exit(&tcp_g_q_lock);
6819 		iocp->ioc_error = EALREADY;
6820 	} else {
6821 		mblk_t *mp1;
6822 
6823 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6824 		if (mp1 == NULL) {
6825 			mutex_exit(&tcp_g_q_lock);
6826 			iocp->ioc_error = ENOMEM;
6827 		} else {
6828 			tcp_g_q = tcp->tcp_rq;
6829 			mutex_exit(&tcp_g_q_lock);
6830 			iocp->ioc_error = 0;
6831 			iocp->ioc_rval = 0;
6832 			/*
6833 			 * We are passing tcp_sticky_ipp as NULL
6834 			 * as it is not useful for tcp_default queue
6835 			 */
6836 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6837 			if (mp1 != NULL)
6838 				tcp_rput_other(tcp, mp1);
6839 		}
6840 	}
6841 	qreply(q, mp);
6842 }
6843 
6844 /*
6845  * Our client hereby directs us to reject the connection request
6846  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6847  * of sending the appropriate RST, not an ICMP error.
6848  */
6849 static void
6850 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6851 {
6852 	tcp_t	*ltcp = NULL;
6853 	t_scalar_t seqnum;
6854 	conn_t	*connp;
6855 
6856 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6857 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6858 		tcp_err_ack(tcp, mp, TPROTO, 0);
6859 		return;
6860 	}
6861 
6862 	/*
6863 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6864 	 * when the stream is in BOUND state. Do not send a reset,
6865 	 * since the destination IP address is not valid, and it can
6866 	 * be the initialized value of all zeros (broadcast address).
6867 	 *
6868 	 * If TCP has sent down a bind request to IP and has not
6869 	 * received the reply, reject the request.  Otherwise, TCP
6870 	 * will be confused.
6871 	 */
6872 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6873 		if (tcp->tcp_debug) {
6874 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6875 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6876 		}
6877 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6878 		return;
6879 	}
6880 
6881 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6882 
6883 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6884 
6885 		/*
6886 		 * According to TPI, for non-listeners, ignore seqnum
6887 		 * and disconnect.
6888 		 * Following interpretation of -1 seqnum is historical
6889 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6890 		 * a valid seqnum should not be -1).
6891 		 *
6892 		 *	-1 means disconnect everything
6893 		 *	regardless even on a listener.
6894 		 */
6895 
6896 		int old_state = tcp->tcp_state;
6897 
6898 		/*
6899 		 * The connection can't be on the tcp_time_wait_head list
6900 		 * since it is not detached.
6901 		 */
6902 		ASSERT(tcp->tcp_time_wait_next == NULL);
6903 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6904 		ASSERT(tcp->tcp_time_wait_expire == 0);
6905 		ltcp = NULL;
6906 		/*
6907 		 * If it used to be a listener, check to make sure no one else
6908 		 * has taken the port before switching back to LISTEN state.
6909 		 */
6910 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6911 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6912 			    tcp->tcp_ipha->ipha_src,
6913 			    tcp->tcp_connp->conn_zoneid);
6914 			if (connp != NULL)
6915 				ltcp = connp->conn_tcp;
6916 		} else {
6917 			/* Allow tcp_bound_if listeners? */
6918 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6919 			    &tcp->tcp_ip6h->ip6_src, 0,
6920 			    tcp->tcp_connp->conn_zoneid);
6921 			if (connp != NULL)
6922 				ltcp = connp->conn_tcp;
6923 		}
6924 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6925 			tcp->tcp_state = TCPS_LISTEN;
6926 		} else if (old_state > TCPS_BOUND) {
6927 			tcp->tcp_conn_req_max = 0;
6928 			tcp->tcp_state = TCPS_BOUND;
6929 		}
6930 		if (ltcp != NULL)
6931 			CONN_DEC_REF(ltcp->tcp_connp);
6932 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6933 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
6934 		} else if (old_state == TCPS_ESTABLISHED ||
6935 		    old_state == TCPS_CLOSE_WAIT) {
6936 			BUMP_MIB(&tcp_mib, tcpEstabResets);
6937 		}
6938 
6939 		if (tcp->tcp_fused)
6940 			tcp_unfuse(tcp);
6941 
6942 		mutex_enter(&tcp->tcp_eager_lock);
6943 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6944 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6945 			tcp_eager_cleanup(tcp, 0);
6946 		}
6947 		mutex_exit(&tcp->tcp_eager_lock);
6948 
6949 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6950 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6951 
6952 		tcp_reinit(tcp);
6953 
6954 		if (old_state >= TCPS_ESTABLISHED) {
6955 			/* Send M_FLUSH according to TPI */
6956 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6957 		}
6958 		mp = mi_tpi_ok_ack_alloc(mp);
6959 		if (mp)
6960 			putnext(tcp->tcp_rq, mp);
6961 		return;
6962 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6963 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6964 		return;
6965 	}
6966 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6967 		/* Send M_FLUSH according to TPI */
6968 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6969 	}
6970 	mp = mi_tpi_ok_ack_alloc(mp);
6971 	if (mp)
6972 		putnext(tcp->tcp_rq, mp);
6973 }
6974 
6975 /*
6976  * Diagnostic routine used to return a string associated with the tcp state.
6977  * Note that if the caller does not supply a buffer, it will use an internal
6978  * static string.  This means that if multiple threads call this function at
6979  * the same time, output can be corrupted...  Note also that this function
6980  * does not check the size of the supplied buffer.  The caller has to make
6981  * sure that it is big enough.
6982  */
6983 static char *
6984 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6985 {
6986 	char		buf1[30];
6987 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6988 	char		*buf;
6989 	char		*cp;
6990 	in6_addr_t	local, remote;
6991 	char		local_addrbuf[INET6_ADDRSTRLEN];
6992 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6993 
6994 	if (sup_buf != NULL)
6995 		buf = sup_buf;
6996 	else
6997 		buf = priv_buf;
6998 
6999 	if (tcp == NULL)
7000 		return ("NULL_TCP");
7001 	switch (tcp->tcp_state) {
7002 	case TCPS_CLOSED:
7003 		cp = "TCP_CLOSED";
7004 		break;
7005 	case TCPS_IDLE:
7006 		cp = "TCP_IDLE";
7007 		break;
7008 	case TCPS_BOUND:
7009 		cp = "TCP_BOUND";
7010 		break;
7011 	case TCPS_LISTEN:
7012 		cp = "TCP_LISTEN";
7013 		break;
7014 	case TCPS_SYN_SENT:
7015 		cp = "TCP_SYN_SENT";
7016 		break;
7017 	case TCPS_SYN_RCVD:
7018 		cp = "TCP_SYN_RCVD";
7019 		break;
7020 	case TCPS_ESTABLISHED:
7021 		cp = "TCP_ESTABLISHED";
7022 		break;
7023 	case TCPS_CLOSE_WAIT:
7024 		cp = "TCP_CLOSE_WAIT";
7025 		break;
7026 	case TCPS_FIN_WAIT_1:
7027 		cp = "TCP_FIN_WAIT_1";
7028 		break;
7029 	case TCPS_CLOSING:
7030 		cp = "TCP_CLOSING";
7031 		break;
7032 	case TCPS_LAST_ACK:
7033 		cp = "TCP_LAST_ACK";
7034 		break;
7035 	case TCPS_FIN_WAIT_2:
7036 		cp = "TCP_FIN_WAIT_2";
7037 		break;
7038 	case TCPS_TIME_WAIT:
7039 		cp = "TCP_TIME_WAIT";
7040 		break;
7041 	default:
7042 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7043 		cp = buf1;
7044 		break;
7045 	}
7046 	switch (format) {
7047 	case DISP_ADDR_AND_PORT:
7048 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7049 			/*
7050 			 * Note that we use the remote address in the tcp_b
7051 			 * structure.  This means that it will print out
7052 			 * the real destination address, not the next hop's
7053 			 * address if source routing is used.
7054 			 */
7055 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7056 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7057 
7058 		} else {
7059 			local = tcp->tcp_ip_src_v6;
7060 			remote = tcp->tcp_remote_v6;
7061 		}
7062 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7063 		    sizeof (local_addrbuf));
7064 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7065 		    sizeof (remote_addrbuf));
7066 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7067 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7068 		    ntohs(tcp->tcp_fport), cp);
7069 		break;
7070 	case DISP_PORT_ONLY:
7071 	default:
7072 		(void) mi_sprintf(buf, "[%u, %u] %s",
7073 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7074 		break;
7075 	}
7076 
7077 	return (buf);
7078 }
7079 
7080 /*
7081  * Called via squeue to get on to eager's perimeter to send a
7082  * TH_RST. The listener wants the eager to disappear either
7083  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
7084  * being called.
7085  */
7086 /* ARGSUSED */
7087 void
7088 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7089 {
7090 	conn_t	*econnp = (conn_t *)arg;
7091 	tcp_t	*eager = econnp->conn_tcp;
7092 	tcp_t	*listener = eager->tcp_listener;
7093 
7094 	/*
7095 	 * We could be called because listener is closing. Since
7096 	 * the eager is using listener's queue's, its not safe.
7097 	 * Better use the default queue just to send the TH_RST
7098 	 * out.
7099 	 */
7100 	eager->tcp_rq = tcp_g_q;
7101 	eager->tcp_wq = WR(tcp_g_q);
7102 
7103 	if (eager->tcp_state > TCPS_LISTEN) {
7104 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7105 		    eager, eager->tcp_snxt, 0, TH_RST);
7106 	}
7107 
7108 	/* We are here because listener wants this eager gone */
7109 	if (listener != NULL) {
7110 		mutex_enter(&listener->tcp_eager_lock);
7111 		tcp_eager_unlink(eager);
7112 		if (eager->tcp_tconnind_started) {
7113 			/*
7114 			 * The eager has sent a conn_ind up to the
7115 			 * listener but listener decides to close
7116 			 * instead. We need to drop the extra ref
7117 			 * placed on eager in tcp_rput_data() before
7118 			 * sending the conn_ind to listener.
7119 			 */
7120 			CONN_DEC_REF(econnp);
7121 		}
7122 		mutex_exit(&listener->tcp_eager_lock);
7123 		CONN_DEC_REF(listener->tcp_connp);
7124 	}
7125 
7126 	if (eager->tcp_state > TCPS_BOUND)
7127 		tcp_close_detached(eager);
7128 }
7129 
7130 /*
7131  * Reset any eager connection hanging off this listener marked
7132  * with 'seqnum' and then reclaim it's resources.
7133  */
7134 static boolean_t
7135 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7136 {
7137 	tcp_t	*eager;
7138 	mblk_t 	*mp;
7139 
7140 	TCP_STAT(tcp_eager_blowoff_calls);
7141 	eager = listener;
7142 	mutex_enter(&listener->tcp_eager_lock);
7143 	do {
7144 		eager = eager->tcp_eager_next_q;
7145 		if (eager == NULL) {
7146 			mutex_exit(&listener->tcp_eager_lock);
7147 			return (B_FALSE);
7148 		}
7149 	} while (eager->tcp_conn_req_seqnum != seqnum);
7150 
7151 	if (eager->tcp_closemp_used > 0) {
7152 		mutex_exit(&listener->tcp_eager_lock);
7153 		return (B_TRUE);
7154 	}
7155 	eager->tcp_closemp_used = 1;
7156 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7157 	CONN_INC_REF(eager->tcp_connp);
7158 	mutex_exit(&listener->tcp_eager_lock);
7159 	mp = &eager->tcp_closemp;
7160 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7161 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7162 	return (B_TRUE);
7163 }
7164 
7165 /*
7166  * Reset any eager connection hanging off this listener
7167  * and then reclaim it's resources.
7168  */
7169 static void
7170 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7171 {
7172 	tcp_t	*eager;
7173 	mblk_t	*mp;
7174 
7175 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7176 
7177 	if (!q0_only) {
7178 		/* First cleanup q */
7179 		TCP_STAT(tcp_eager_blowoff_q);
7180 		eager = listener->tcp_eager_next_q;
7181 		while (eager != NULL) {
7182 			if (eager->tcp_closemp_used == 0) {
7183 				eager->tcp_closemp_used = 1;
7184 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7185 				CONN_INC_REF(eager->tcp_connp);
7186 				mp = &eager->tcp_closemp;
7187 				squeue_fill(eager->tcp_connp->conn_sqp, mp,
7188 				    tcp_eager_kill, eager->tcp_connp,
7189 				    SQTAG_TCP_EAGER_CLEANUP);
7190 			}
7191 			eager = eager->tcp_eager_next_q;
7192 		}
7193 	}
7194 	/* Then cleanup q0 */
7195 	TCP_STAT(tcp_eager_blowoff_q0);
7196 	eager = listener->tcp_eager_next_q0;
7197 	while (eager != listener) {
7198 		if (eager->tcp_closemp_used == 0) {
7199 			eager->tcp_closemp_used = 1;
7200 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7201 			CONN_INC_REF(eager->tcp_connp);
7202 			mp = &eager->tcp_closemp;
7203 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7204 			    tcp_eager_kill, eager->tcp_connp,
7205 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
7206 		}
7207 		eager = eager->tcp_eager_next_q0;
7208 	}
7209 }
7210 
7211 /*
7212  * If we are an eager connection hanging off a listener that hasn't
7213  * formally accepted the connection yet, get off his list and blow off
7214  * any data that we have accumulated.
7215  */
7216 static void
7217 tcp_eager_unlink(tcp_t *tcp)
7218 {
7219 	tcp_t	*listener = tcp->tcp_listener;
7220 
7221 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7222 	ASSERT(listener != NULL);
7223 	if (tcp->tcp_eager_next_q0 != NULL) {
7224 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7225 
7226 		/* Remove the eager tcp from q0 */
7227 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7228 		    tcp->tcp_eager_prev_q0;
7229 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7230 		    tcp->tcp_eager_next_q0;
7231 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7232 		listener->tcp_conn_req_cnt_q0--;
7233 
7234 		tcp->tcp_eager_next_q0 = NULL;
7235 		tcp->tcp_eager_prev_q0 = NULL;
7236 
7237 		/*
7238 		 * Take the eager out, if it is in the list of droppable
7239 		 * eagers.
7240 		 */
7241 		MAKE_UNDROPPABLE(tcp);
7242 
7243 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7244 			/* we have timed out before */
7245 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7246 			listener->tcp_syn_rcvd_timeout--;
7247 		}
7248 	} else {
7249 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7250 		tcp_t	*prev = NULL;
7251 
7252 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7253 			if (tcpp[0] == tcp) {
7254 				if (listener->tcp_eager_last_q == tcp) {
7255 					/*
7256 					 * If we are unlinking the last
7257 					 * element on the list, adjust
7258 					 * tail pointer. Set tail pointer
7259 					 * to nil when list is empty.
7260 					 */
7261 					ASSERT(tcp->tcp_eager_next_q == NULL);
7262 					if (listener->tcp_eager_last_q ==
7263 					    listener->tcp_eager_next_q) {
7264 						listener->tcp_eager_last_q =
7265 						NULL;
7266 					} else {
7267 						/*
7268 						 * We won't get here if there
7269 						 * is only one eager in the
7270 						 * list.
7271 						 */
7272 						ASSERT(prev != NULL);
7273 						listener->tcp_eager_last_q =
7274 						    prev;
7275 					}
7276 				}
7277 				tcpp[0] = tcp->tcp_eager_next_q;
7278 				tcp->tcp_eager_next_q = NULL;
7279 				tcp->tcp_eager_last_q = NULL;
7280 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7281 				listener->tcp_conn_req_cnt_q--;
7282 				break;
7283 			}
7284 			prev = tcpp[0];
7285 		}
7286 	}
7287 	tcp->tcp_listener = NULL;
7288 }
7289 
7290 /* Shorthand to generate and send TPI error acks to our client */
7291 static void
7292 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7293 {
7294 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7295 		putnext(tcp->tcp_rq, mp);
7296 }
7297 
7298 /* Shorthand to generate and send TPI error acks to our client */
7299 static void
7300 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7301     int t_error, int sys_error)
7302 {
7303 	struct T_error_ack	*teackp;
7304 
7305 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7306 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7307 		teackp = (struct T_error_ack *)mp->b_rptr;
7308 		teackp->ERROR_prim = primitive;
7309 		teackp->TLI_error = t_error;
7310 		teackp->UNIX_error = sys_error;
7311 		putnext(tcp->tcp_rq, mp);
7312 	}
7313 }
7314 
7315 /*
7316  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7317  * but instead the code relies on:
7318  * - the fact that the address of the array and its size never changes
7319  * - the atomic assignment of the elements of the array
7320  */
7321 /* ARGSUSED */
7322 static int
7323 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7324 {
7325 	int i;
7326 
7327 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7328 		if (tcp_g_epriv_ports[i] != 0)
7329 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
7330 	}
7331 	return (0);
7332 }
7333 
7334 /*
7335  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7336  * threads from changing it at the same time.
7337  */
7338 /* ARGSUSED */
7339 static int
7340 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7341     cred_t *cr)
7342 {
7343 	long	new_value;
7344 	int	i;
7345 
7346 	/*
7347 	 * Fail the request if the new value does not lie within the
7348 	 * port number limits.
7349 	 */
7350 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7351 	    new_value <= 0 || new_value >= 65536) {
7352 		return (EINVAL);
7353 	}
7354 
7355 	mutex_enter(&tcp_epriv_port_lock);
7356 	/* Check if the value is already in the list */
7357 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7358 		if (new_value == tcp_g_epriv_ports[i]) {
7359 			mutex_exit(&tcp_epriv_port_lock);
7360 			return (EEXIST);
7361 		}
7362 	}
7363 	/* Find an empty slot */
7364 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7365 		if (tcp_g_epriv_ports[i] == 0)
7366 			break;
7367 	}
7368 	if (i == tcp_g_num_epriv_ports) {
7369 		mutex_exit(&tcp_epriv_port_lock);
7370 		return (EOVERFLOW);
7371 	}
7372 	/* Set the new value */
7373 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
7374 	mutex_exit(&tcp_epriv_port_lock);
7375 	return (0);
7376 }
7377 
7378 /*
7379  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7380  * threads from changing it at the same time.
7381  */
7382 /* ARGSUSED */
7383 static int
7384 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7385     cred_t *cr)
7386 {
7387 	long	new_value;
7388 	int	i;
7389 
7390 	/*
7391 	 * Fail the request if the new value does not lie within the
7392 	 * port number limits.
7393 	 */
7394 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7395 	    new_value >= 65536) {
7396 		return (EINVAL);
7397 	}
7398 
7399 	mutex_enter(&tcp_epriv_port_lock);
7400 	/* Check that the value is already in the list */
7401 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7402 		if (tcp_g_epriv_ports[i] == new_value)
7403 			break;
7404 	}
7405 	if (i == tcp_g_num_epriv_ports) {
7406 		mutex_exit(&tcp_epriv_port_lock);
7407 		return (ESRCH);
7408 	}
7409 	/* Clear the value */
7410 	tcp_g_epriv_ports[i] = 0;
7411 	mutex_exit(&tcp_epriv_port_lock);
7412 	return (0);
7413 }
7414 
7415 /* Return the TPI/TLI equivalent of our current tcp_state */
7416 static int
7417 tcp_tpistate(tcp_t *tcp)
7418 {
7419 	switch (tcp->tcp_state) {
7420 	case TCPS_IDLE:
7421 		return (TS_UNBND);
7422 	case TCPS_LISTEN:
7423 		/*
7424 		 * Return whether there are outstanding T_CONN_IND waiting
7425 		 * for the matching T_CONN_RES. Therefore don't count q0.
7426 		 */
7427 		if (tcp->tcp_conn_req_cnt_q > 0)
7428 			return (TS_WRES_CIND);
7429 		else
7430 			return (TS_IDLE);
7431 	case TCPS_BOUND:
7432 		return (TS_IDLE);
7433 	case TCPS_SYN_SENT:
7434 		return (TS_WCON_CREQ);
7435 	case TCPS_SYN_RCVD:
7436 		/*
7437 		 * Note: assumption: this has to the active open SYN_RCVD.
7438 		 * The passive instance is detached in SYN_RCVD stage of
7439 		 * incoming connection processing so we cannot get request
7440 		 * for T_info_ack on it.
7441 		 */
7442 		return (TS_WACK_CRES);
7443 	case TCPS_ESTABLISHED:
7444 		return (TS_DATA_XFER);
7445 	case TCPS_CLOSE_WAIT:
7446 		return (TS_WREQ_ORDREL);
7447 	case TCPS_FIN_WAIT_1:
7448 		return (TS_WIND_ORDREL);
7449 	case TCPS_FIN_WAIT_2:
7450 		return (TS_WIND_ORDREL);
7451 
7452 	case TCPS_CLOSING:
7453 	case TCPS_LAST_ACK:
7454 	case TCPS_TIME_WAIT:
7455 	case TCPS_CLOSED:
7456 		/*
7457 		 * Following TS_WACK_DREQ7 is a rendition of "not
7458 		 * yet TS_IDLE" TPI state. There is no best match to any
7459 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7460 		 * choose a value chosen that will map to TLI/XTI level
7461 		 * state of TSTATECHNG (state is process of changing) which
7462 		 * captures what this dummy state represents.
7463 		 */
7464 		return (TS_WACK_DREQ7);
7465 	default:
7466 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7467 		    tcp->tcp_state, tcp_display(tcp, NULL,
7468 		    DISP_PORT_ONLY));
7469 		return (TS_UNBND);
7470 	}
7471 }
7472 
7473 static void
7474 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7475 {
7476 	if (tcp->tcp_family == AF_INET6)
7477 		*tia = tcp_g_t_info_ack_v6;
7478 	else
7479 		*tia = tcp_g_t_info_ack;
7480 	tia->CURRENT_state = tcp_tpistate(tcp);
7481 	tia->OPT_size = tcp_max_optsize;
7482 	if (tcp->tcp_mss == 0) {
7483 		/* Not yet set - tcp_open does not set mss */
7484 		if (tcp->tcp_ipversion == IPV4_VERSION)
7485 			tia->TIDU_size = tcp_mss_def_ipv4;
7486 		else
7487 			tia->TIDU_size = tcp_mss_def_ipv6;
7488 	} else {
7489 		tia->TIDU_size = tcp->tcp_mss;
7490 	}
7491 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7492 }
7493 
7494 /*
7495  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7496  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7497  * tcp_g_t_info_ack.  The current state of the stream is copied from
7498  * tcp_state.
7499  */
7500 static void
7501 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7502 {
7503 	t_uscalar_t		cap_bits1;
7504 	struct T_capability_ack	*tcap;
7505 
7506 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7507 		freemsg(mp);
7508 		return;
7509 	}
7510 
7511 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7512 
7513 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7514 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7515 	if (mp == NULL)
7516 		return;
7517 
7518 	tcap = (struct T_capability_ack *)mp->b_rptr;
7519 	tcap->CAP_bits1 = 0;
7520 
7521 	if (cap_bits1 & TC1_INFO) {
7522 		tcp_copy_info(&tcap->INFO_ack, tcp);
7523 		tcap->CAP_bits1 |= TC1_INFO;
7524 	}
7525 
7526 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7527 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7528 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7529 	}
7530 
7531 	putnext(tcp->tcp_rq, mp);
7532 }
7533 
7534 /*
7535  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7536  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7537  * The current state of the stream is copied from tcp_state.
7538  */
7539 static void
7540 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7541 {
7542 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7543 	    T_INFO_ACK);
7544 	if (!mp) {
7545 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7546 		return;
7547 	}
7548 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7549 	putnext(tcp->tcp_rq, mp);
7550 }
7551 
7552 /* Respond to the TPI addr request */
7553 static void
7554 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7555 {
7556 	sin_t	*sin;
7557 	mblk_t	*ackmp;
7558 	struct T_addr_ack *taa;
7559 
7560 	/* Make it large enough for worst case */
7561 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7562 	    2 * sizeof (sin6_t), 1);
7563 	if (ackmp == NULL) {
7564 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7565 		return;
7566 	}
7567 
7568 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7569 		tcp_addr_req_ipv6(tcp, ackmp);
7570 		return;
7571 	}
7572 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7573 
7574 	bzero(taa, sizeof (struct T_addr_ack));
7575 	ackmp->b_wptr = (uchar_t *)&taa[1];
7576 
7577 	taa->PRIM_type = T_ADDR_ACK;
7578 	ackmp->b_datap->db_type = M_PCPROTO;
7579 
7580 	/*
7581 	 * Note: Following code assumes 32 bit alignment of basic
7582 	 * data structures like sin_t and struct T_addr_ack.
7583 	 */
7584 	if (tcp->tcp_state >= TCPS_BOUND) {
7585 		/*
7586 		 * Fill in local address
7587 		 */
7588 		taa->LOCADDR_length = sizeof (sin_t);
7589 		taa->LOCADDR_offset = sizeof (*taa);
7590 
7591 		sin = (sin_t *)&taa[1];
7592 
7593 		/* Fill zeroes and then intialize non-zero fields */
7594 		*sin = sin_null;
7595 
7596 		sin->sin_family = AF_INET;
7597 
7598 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7599 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7600 
7601 		ackmp->b_wptr = (uchar_t *)&sin[1];
7602 
7603 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7604 			/*
7605 			 * Fill in Remote address
7606 			 */
7607 			taa->REMADDR_length = sizeof (sin_t);
7608 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7609 						taa->LOCADDR_length);
7610 
7611 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7612 			*sin = sin_null;
7613 			sin->sin_family = AF_INET;
7614 			sin->sin_addr.s_addr = tcp->tcp_remote;
7615 			sin->sin_port = tcp->tcp_fport;
7616 
7617 			ackmp->b_wptr = (uchar_t *)&sin[1];
7618 		}
7619 	}
7620 	putnext(tcp->tcp_rq, ackmp);
7621 }
7622 
7623 /* Assumes that tcp_addr_req gets enough space and alignment */
7624 static void
7625 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7626 {
7627 	sin6_t	*sin6;
7628 	struct T_addr_ack *taa;
7629 
7630 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7631 	ASSERT(OK_32PTR(ackmp->b_rptr));
7632 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7633 	    2 * sizeof (sin6_t));
7634 
7635 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7636 
7637 	bzero(taa, sizeof (struct T_addr_ack));
7638 	ackmp->b_wptr = (uchar_t *)&taa[1];
7639 
7640 	taa->PRIM_type = T_ADDR_ACK;
7641 	ackmp->b_datap->db_type = M_PCPROTO;
7642 
7643 	/*
7644 	 * Note: Following code assumes 32 bit alignment of basic
7645 	 * data structures like sin6_t and struct T_addr_ack.
7646 	 */
7647 	if (tcp->tcp_state >= TCPS_BOUND) {
7648 		/*
7649 		 * Fill in local address
7650 		 */
7651 		taa->LOCADDR_length = sizeof (sin6_t);
7652 		taa->LOCADDR_offset = sizeof (*taa);
7653 
7654 		sin6 = (sin6_t *)&taa[1];
7655 		*sin6 = sin6_null;
7656 
7657 		sin6->sin6_family = AF_INET6;
7658 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7659 		sin6->sin6_port = tcp->tcp_lport;
7660 
7661 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7662 
7663 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7664 			/*
7665 			 * Fill in Remote address
7666 			 */
7667 			taa->REMADDR_length = sizeof (sin6_t);
7668 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7669 						taa->LOCADDR_length);
7670 
7671 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7672 			*sin6 = sin6_null;
7673 			sin6->sin6_family = AF_INET6;
7674 			sin6->sin6_flowinfo =
7675 			    tcp->tcp_ip6h->ip6_vcf &
7676 			    ~IPV6_VERS_AND_FLOW_MASK;
7677 			sin6->sin6_addr = tcp->tcp_remote_v6;
7678 			sin6->sin6_port = tcp->tcp_fport;
7679 
7680 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7681 		}
7682 	}
7683 	putnext(tcp->tcp_rq, ackmp);
7684 }
7685 
7686 /*
7687  * Handle reinitialization of a tcp structure.
7688  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7689  */
7690 static void
7691 tcp_reinit(tcp_t *tcp)
7692 {
7693 	mblk_t	*mp;
7694 	int 	err;
7695 
7696 	TCP_STAT(tcp_reinit_calls);
7697 
7698 	/* tcp_reinit should never be called for detached tcp_t's */
7699 	ASSERT(tcp->tcp_listener == NULL);
7700 	ASSERT((tcp->tcp_family == AF_INET &&
7701 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7702 	    (tcp->tcp_family == AF_INET6 &&
7703 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7704 	    tcp->tcp_ipversion == IPV6_VERSION)));
7705 
7706 	/* Cancel outstanding timers */
7707 	tcp_timers_stop(tcp);
7708 
7709 	/*
7710 	 * Reset everything in the state vector, after updating global
7711 	 * MIB data from instance counters.
7712 	 */
7713 	UPDATE_MIB(&tcp_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7714 	tcp->tcp_ibsegs = 0;
7715 	UPDATE_MIB(&tcp_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7716 	tcp->tcp_obsegs = 0;
7717 
7718 	tcp_close_mpp(&tcp->tcp_xmit_head);
7719 	if (tcp->tcp_snd_zcopy_aware)
7720 		tcp_zcopy_notify(tcp);
7721 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7722 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7723 	mutex_enter(&tcp->tcp_non_sq_lock);
7724 	if (tcp->tcp_flow_stopped &&
7725 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7726 		tcp_clrqfull(tcp);
7727 	}
7728 	mutex_exit(&tcp->tcp_non_sq_lock);
7729 	tcp_close_mpp(&tcp->tcp_reass_head);
7730 	tcp->tcp_reass_tail = NULL;
7731 	if (tcp->tcp_rcv_list != NULL) {
7732 		/* Free b_next chain */
7733 		tcp_close_mpp(&tcp->tcp_rcv_list);
7734 		tcp->tcp_rcv_last_head = NULL;
7735 		tcp->tcp_rcv_last_tail = NULL;
7736 		tcp->tcp_rcv_cnt = 0;
7737 	}
7738 	tcp->tcp_rcv_last_tail = NULL;
7739 
7740 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7741 		freemsg(mp);
7742 		tcp->tcp_urp_mp = NULL;
7743 	}
7744 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7745 		freemsg(mp);
7746 		tcp->tcp_urp_mark_mp = NULL;
7747 	}
7748 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7749 		freeb(tcp->tcp_fused_sigurg_mp);
7750 		tcp->tcp_fused_sigurg_mp = NULL;
7751 	}
7752 
7753 	/*
7754 	 * Following is a union with two members which are
7755 	 * identical types and size so the following cleanup
7756 	 * is enough.
7757 	 */
7758 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7759 
7760 	CL_INET_DISCONNECT(tcp);
7761 
7762 	/*
7763 	 * The connection can't be on the tcp_time_wait_head list
7764 	 * since it is not detached.
7765 	 */
7766 	ASSERT(tcp->tcp_time_wait_next == NULL);
7767 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7768 	ASSERT(tcp->tcp_time_wait_expire == 0);
7769 
7770 	if (tcp->tcp_kssl_pending) {
7771 		tcp->tcp_kssl_pending = B_FALSE;
7772 
7773 		/* Don't reset if the initialized by bind. */
7774 		if (tcp->tcp_kssl_ent != NULL) {
7775 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7776 			    KSSL_NO_PROXY);
7777 		}
7778 	}
7779 	if (tcp->tcp_kssl_ctx != NULL) {
7780 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7781 		tcp->tcp_kssl_ctx = NULL;
7782 	}
7783 
7784 	/*
7785 	 * Reset/preserve other values
7786 	 */
7787 	tcp_reinit_values(tcp);
7788 	ipcl_hash_remove(tcp->tcp_connp);
7789 	conn_delete_ire(tcp->tcp_connp, NULL);
7790 
7791 	if (tcp->tcp_conn_req_max != 0) {
7792 		/*
7793 		 * This is the case when a TLI program uses the same
7794 		 * transport end point to accept a connection.  This
7795 		 * makes the TCP both a listener and acceptor.  When
7796 		 * this connection is closed, we need to set the state
7797 		 * back to TCPS_LISTEN.  Make sure that the eager list
7798 		 * is reinitialized.
7799 		 *
7800 		 * Note that this stream is still bound to the four
7801 		 * tuples of the previous connection in IP.  If a new
7802 		 * SYN with different foreign address comes in, IP will
7803 		 * not find it and will send it to the global queue.  In
7804 		 * the global queue, TCP will do a tcp_lookup_listener()
7805 		 * to find this stream.  This works because this stream
7806 		 * is only removed from connected hash.
7807 		 *
7808 		 */
7809 		tcp->tcp_state = TCPS_LISTEN;
7810 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7811 		tcp->tcp_eager_next_drop_q0 = tcp;
7812 		tcp->tcp_eager_prev_drop_q0 = tcp;
7813 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7814 		if (tcp->tcp_family == AF_INET6) {
7815 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7816 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7817 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7818 		} else {
7819 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7820 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7821 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7822 		}
7823 	} else {
7824 		tcp->tcp_state = TCPS_BOUND;
7825 	}
7826 
7827 	/*
7828 	 * Initialize to default values
7829 	 * Can't fail since enough header template space already allocated
7830 	 * at open().
7831 	 */
7832 	err = tcp_init_values(tcp);
7833 	ASSERT(err == 0);
7834 	/* Restore state in tcp_tcph */
7835 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7836 	if (tcp->tcp_ipversion == IPV4_VERSION)
7837 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7838 	else
7839 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7840 	/*
7841 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7842 	 * since the lookup funcs can only lookup on tcp_t
7843 	 */
7844 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7845 
7846 	ASSERT(tcp->tcp_ptpbhn != NULL);
7847 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
7848 	tcp->tcp_rwnd = tcp_recv_hiwat;
7849 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7850 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
7851 }
7852 
7853 /*
7854  * Force values to zero that need be zero.
7855  * Do not touch values asociated with the BOUND or LISTEN state
7856  * since the connection will end up in that state after the reinit.
7857  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7858  * structure!
7859  */
7860 static void
7861 tcp_reinit_values(tcp)
7862 	tcp_t *tcp;
7863 {
7864 #ifndef	lint
7865 #define	DONTCARE(x)
7866 #define	PRESERVE(x)
7867 #else
7868 #define	DONTCARE(x)	((x) = (x))
7869 #define	PRESERVE(x)	((x) = (x))
7870 #endif	/* lint */
7871 
7872 	PRESERVE(tcp->tcp_bind_hash);
7873 	PRESERVE(tcp->tcp_ptpbhn);
7874 	PRESERVE(tcp->tcp_acceptor_hash);
7875 	PRESERVE(tcp->tcp_ptpahn);
7876 
7877 	/* Should be ASSERT NULL on these with new code! */
7878 	ASSERT(tcp->tcp_time_wait_next == NULL);
7879 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7880 	ASSERT(tcp->tcp_time_wait_expire == 0);
7881 	PRESERVE(tcp->tcp_state);
7882 	PRESERVE(tcp->tcp_rq);
7883 	PRESERVE(tcp->tcp_wq);
7884 
7885 	ASSERT(tcp->tcp_xmit_head == NULL);
7886 	ASSERT(tcp->tcp_xmit_last == NULL);
7887 	ASSERT(tcp->tcp_unsent == 0);
7888 	ASSERT(tcp->tcp_xmit_tail == NULL);
7889 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7890 
7891 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7892 	tcp->tcp_suna = 0;			/* Displayed in mib */
7893 	tcp->tcp_swnd = 0;
7894 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7895 
7896 	ASSERT(tcp->tcp_ibsegs == 0);
7897 	ASSERT(tcp->tcp_obsegs == 0);
7898 
7899 	if (tcp->tcp_iphc != NULL) {
7900 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7901 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7902 	}
7903 
7904 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7905 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7906 	DONTCARE(tcp->tcp_ipha);
7907 	DONTCARE(tcp->tcp_ip6h);
7908 	DONTCARE(tcp->tcp_ip_hdr_len);
7909 	DONTCARE(tcp->tcp_tcph);
7910 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7911 	tcp->tcp_valid_bits = 0;
7912 
7913 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7914 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7915 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7916 	tcp->tcp_last_rcv_lbolt = 0;
7917 
7918 	tcp->tcp_init_cwnd = 0;
7919 
7920 	tcp->tcp_urp_last_valid = 0;
7921 	tcp->tcp_hard_binding = 0;
7922 	tcp->tcp_hard_bound = 0;
7923 	PRESERVE(tcp->tcp_cred);
7924 	PRESERVE(tcp->tcp_cpid);
7925 	PRESERVE(tcp->tcp_open_time);
7926 	PRESERVE(tcp->tcp_exclbind);
7927 
7928 	tcp->tcp_fin_acked = 0;
7929 	tcp->tcp_fin_rcvd = 0;
7930 	tcp->tcp_fin_sent = 0;
7931 	tcp->tcp_ordrel_done = 0;
7932 
7933 	tcp->tcp_debug = 0;
7934 	tcp->tcp_dontroute = 0;
7935 	tcp->tcp_broadcast = 0;
7936 
7937 	tcp->tcp_useloopback = 0;
7938 	tcp->tcp_reuseaddr = 0;
7939 	tcp->tcp_oobinline = 0;
7940 	tcp->tcp_dgram_errind = 0;
7941 
7942 	tcp->tcp_detached = 0;
7943 	tcp->tcp_bind_pending = 0;
7944 	tcp->tcp_unbind_pending = 0;
7945 	tcp->tcp_deferred_clean_death = 0;
7946 
7947 	tcp->tcp_snd_ws_ok = B_FALSE;
7948 	tcp->tcp_snd_ts_ok = B_FALSE;
7949 	tcp->tcp_linger = 0;
7950 	tcp->tcp_ka_enabled = 0;
7951 	tcp->tcp_zero_win_probe = 0;
7952 
7953 	tcp->tcp_loopback = 0;
7954 	tcp->tcp_localnet = 0;
7955 	tcp->tcp_syn_defense = 0;
7956 	tcp->tcp_set_timer = 0;
7957 
7958 	tcp->tcp_active_open = 0;
7959 	ASSERT(tcp->tcp_timeout == B_FALSE);
7960 	tcp->tcp_rexmit = B_FALSE;
7961 	tcp->tcp_xmit_zc_clean = B_FALSE;
7962 
7963 	tcp->tcp_snd_sack_ok = B_FALSE;
7964 	PRESERVE(tcp->tcp_recvdstaddr);
7965 	tcp->tcp_hwcksum = B_FALSE;
7966 
7967 	tcp->tcp_ire_ill_check_done = B_FALSE;
7968 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7969 
7970 	tcp->tcp_mdt = B_FALSE;
7971 	tcp->tcp_mdt_hdr_head = 0;
7972 	tcp->tcp_mdt_hdr_tail = 0;
7973 
7974 	tcp->tcp_conn_def_q0 = 0;
7975 	tcp->tcp_ip_forward_progress = B_FALSE;
7976 	tcp->tcp_anon_priv_bind = 0;
7977 	tcp->tcp_ecn_ok = B_FALSE;
7978 
7979 	tcp->tcp_cwr = B_FALSE;
7980 	tcp->tcp_ecn_echo_on = B_FALSE;
7981 
7982 	if (tcp->tcp_sack_info != NULL) {
7983 		if (tcp->tcp_notsack_list != NULL) {
7984 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7985 		}
7986 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7987 		tcp->tcp_sack_info = NULL;
7988 	}
7989 
7990 	tcp->tcp_rcv_ws = 0;
7991 	tcp->tcp_snd_ws = 0;
7992 	tcp->tcp_ts_recent = 0;
7993 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7994 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7995 	tcp->tcp_if_mtu = 0;
7996 
7997 	ASSERT(tcp->tcp_reass_head == NULL);
7998 	ASSERT(tcp->tcp_reass_tail == NULL);
7999 
8000 	tcp->tcp_cwnd_cnt = 0;
8001 
8002 	ASSERT(tcp->tcp_rcv_list == NULL);
8003 	ASSERT(tcp->tcp_rcv_last_head == NULL);
8004 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
8005 	ASSERT(tcp->tcp_rcv_cnt == 0);
8006 
8007 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
8008 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
8009 	tcp->tcp_csuna = 0;
8010 
8011 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8012 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8013 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8014 	tcp->tcp_rtt_update = 0;
8015 
8016 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8017 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8018 
8019 	tcp->tcp_rack = 0;			/* Displayed in mib */
8020 	tcp->tcp_rack_cnt = 0;
8021 	tcp->tcp_rack_cur_max = 0;
8022 	tcp->tcp_rack_abs_max = 0;
8023 
8024 	tcp->tcp_max_swnd = 0;
8025 
8026 	ASSERT(tcp->tcp_listener == NULL);
8027 
8028 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8029 
8030 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8031 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8032 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8033 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8034 
8035 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8036 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8037 	PRESERVE(tcp->tcp_conn_req_max);
8038 	PRESERVE(tcp->tcp_conn_req_seqnum);
8039 
8040 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8041 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8042 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8043 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8044 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8045 
8046 	tcp->tcp_lingertime = 0;
8047 
8048 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8049 	ASSERT(tcp->tcp_urp_mp == NULL);
8050 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8051 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8052 
8053 	ASSERT(tcp->tcp_eager_next_q == NULL);
8054 	ASSERT(tcp->tcp_eager_last_q == NULL);
8055 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8056 	    tcp->tcp_eager_prev_q0 == NULL) ||
8057 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8058 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8059 
8060 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
8061 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
8062 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
8063 
8064 	tcp->tcp_client_errno = 0;
8065 
8066 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8067 
8068 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8069 
8070 	PRESERVE(tcp->tcp_bound_source_v6);
8071 	tcp->tcp_last_sent_len = 0;
8072 	tcp->tcp_dupack_cnt = 0;
8073 
8074 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8075 	PRESERVE(tcp->tcp_lport);
8076 
8077 	PRESERVE(tcp->tcp_acceptor_lockp);
8078 
8079 	ASSERT(tcp->tcp_ordrelid == 0);
8080 	PRESERVE(tcp->tcp_acceptor_id);
8081 	DONTCARE(tcp->tcp_ipsec_overhead);
8082 
8083 	/*
8084 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
8085 	 * in tcp structure and now tracing), Re-initialize all
8086 	 * members of tcp_traceinfo.
8087 	 */
8088 	if (tcp->tcp_tracebuf != NULL) {
8089 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
8090 	}
8091 
8092 	PRESERVE(tcp->tcp_family);
8093 	if (tcp->tcp_family == AF_INET6) {
8094 		tcp->tcp_ipversion = IPV6_VERSION;
8095 		tcp->tcp_mss = tcp_mss_def_ipv6;
8096 	} else {
8097 		tcp->tcp_ipversion = IPV4_VERSION;
8098 		tcp->tcp_mss = tcp_mss_def_ipv4;
8099 	}
8100 
8101 	tcp->tcp_bound_if = 0;
8102 	tcp->tcp_ipv6_recvancillary = 0;
8103 	tcp->tcp_recvifindex = 0;
8104 	tcp->tcp_recvhops = 0;
8105 	tcp->tcp_closed = 0;
8106 	tcp->tcp_cleandeathtag = 0;
8107 	if (tcp->tcp_hopopts != NULL) {
8108 		mi_free(tcp->tcp_hopopts);
8109 		tcp->tcp_hopopts = NULL;
8110 		tcp->tcp_hopoptslen = 0;
8111 	}
8112 	ASSERT(tcp->tcp_hopoptslen == 0);
8113 	if (tcp->tcp_dstopts != NULL) {
8114 		mi_free(tcp->tcp_dstopts);
8115 		tcp->tcp_dstopts = NULL;
8116 		tcp->tcp_dstoptslen = 0;
8117 	}
8118 	ASSERT(tcp->tcp_dstoptslen == 0);
8119 	if (tcp->tcp_rtdstopts != NULL) {
8120 		mi_free(tcp->tcp_rtdstopts);
8121 		tcp->tcp_rtdstopts = NULL;
8122 		tcp->tcp_rtdstoptslen = 0;
8123 	}
8124 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8125 	if (tcp->tcp_rthdr != NULL) {
8126 		mi_free(tcp->tcp_rthdr);
8127 		tcp->tcp_rthdr = NULL;
8128 		tcp->tcp_rthdrlen = 0;
8129 	}
8130 	ASSERT(tcp->tcp_rthdrlen == 0);
8131 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8132 
8133 	/* Reset fusion-related fields */
8134 	tcp->tcp_fused = B_FALSE;
8135 	tcp->tcp_unfusable = B_FALSE;
8136 	tcp->tcp_fused_sigurg = B_FALSE;
8137 	tcp->tcp_direct_sockfs = B_FALSE;
8138 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8139 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8140 	tcp->tcp_loopback_peer = NULL;
8141 	tcp->tcp_fuse_rcv_hiwater = 0;
8142 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8143 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8144 
8145 	tcp->tcp_lso = B_FALSE;
8146 
8147 	tcp->tcp_in_ack_unsent = 0;
8148 	tcp->tcp_cork = B_FALSE;
8149 	tcp->tcp_tconnind_started = B_FALSE;
8150 
8151 	PRESERVE(tcp->tcp_squeue_bytes);
8152 
8153 	ASSERT(tcp->tcp_kssl_ctx == NULL);
8154 	ASSERT(!tcp->tcp_kssl_pending);
8155 	PRESERVE(tcp->tcp_kssl_ent);
8156 
8157 	tcp->tcp_closemp_used = 0;
8158 
8159 #ifdef DEBUG
8160 	DONTCARE(tcp->tcmp_stk[0]);
8161 #endif
8162 
8163 
8164 #undef	DONTCARE
8165 #undef	PRESERVE
8166 }
8167 
8168 /*
8169  * Allocate necessary resources and initialize state vector.
8170  * Guaranteed not to fail so that when an error is returned,
8171  * the caller doesn't need to do any additional cleanup.
8172  */
8173 int
8174 tcp_init(tcp_t *tcp, queue_t *q)
8175 {
8176 	int	err;
8177 
8178 	tcp->tcp_rq = q;
8179 	tcp->tcp_wq = WR(q);
8180 	tcp->tcp_state = TCPS_IDLE;
8181 	if ((err = tcp_init_values(tcp)) != 0)
8182 		tcp_timers_stop(tcp);
8183 	return (err);
8184 }
8185 
8186 static int
8187 tcp_init_values(tcp_t *tcp)
8188 {
8189 	int	err;
8190 
8191 	ASSERT((tcp->tcp_family == AF_INET &&
8192 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8193 	    (tcp->tcp_family == AF_INET6 &&
8194 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8195 	    tcp->tcp_ipversion == IPV6_VERSION)));
8196 
8197 	/*
8198 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8199 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8200 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8201 	 * during first few transmissions of a connection as seen in slow
8202 	 * links.
8203 	 */
8204 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
8205 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
8206 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8207 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8208 	    tcp_conn_grace_period;
8209 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
8210 		tcp->tcp_rto = tcp_rexmit_interval_min;
8211 	tcp->tcp_timer_backoff = 0;
8212 	tcp->tcp_ms_we_have_waited = 0;
8213 	tcp->tcp_last_recv_time = lbolt;
8214 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
8215 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
8216 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8217 
8218 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
8219 
8220 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
8221 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
8222 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
8223 	/*
8224 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8225 	 * passive open.
8226 	 */
8227 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
8228 
8229 	tcp->tcp_naglim = tcp_naglim_def;
8230 
8231 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8232 
8233 	tcp->tcp_mdt_hdr_head = 0;
8234 	tcp->tcp_mdt_hdr_tail = 0;
8235 
8236 	/* Reset fusion-related fields */
8237 	tcp->tcp_fused = B_FALSE;
8238 	tcp->tcp_unfusable = B_FALSE;
8239 	tcp->tcp_fused_sigurg = B_FALSE;
8240 	tcp->tcp_direct_sockfs = B_FALSE;
8241 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8242 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8243 	tcp->tcp_loopback_peer = NULL;
8244 	tcp->tcp_fuse_rcv_hiwater = 0;
8245 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8246 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8247 
8248 	/* Initialize the header template */
8249 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8250 		err = tcp_header_init_ipv4(tcp);
8251 	} else {
8252 		err = tcp_header_init_ipv6(tcp);
8253 	}
8254 	if (err)
8255 		return (err);
8256 
8257 	/*
8258 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8259 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8260 	 */
8261 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8262 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
8263 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
8264 
8265 	tcp->tcp_cork = B_FALSE;
8266 	/*
8267 	 * Init the tcp_debug option.  This value determines whether TCP
8268 	 * calls strlog() to print out debug messages.  Doing this
8269 	 * initialization here means that this value is not inherited thru
8270 	 * tcp_reinit().
8271 	 */
8272 	tcp->tcp_debug = tcp_dbg;
8273 
8274 	tcp->tcp_ka_interval = tcp_keepalive_interval;
8275 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
8276 
8277 	return (0);
8278 }
8279 
8280 /*
8281  * Initialize the IPv4 header. Loses any record of any IP options.
8282  */
8283 static int
8284 tcp_header_init_ipv4(tcp_t *tcp)
8285 {
8286 	tcph_t		*tcph;
8287 	uint32_t	sum;
8288 	conn_t		*connp;
8289 
8290 	/*
8291 	 * This is a simple initialization. If there's
8292 	 * already a template, it should never be too small,
8293 	 * so reuse it.  Otherwise, allocate space for the new one.
8294 	 */
8295 	if (tcp->tcp_iphc == NULL) {
8296 		ASSERT(tcp->tcp_iphc_len == 0);
8297 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8298 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8299 		if (tcp->tcp_iphc == NULL) {
8300 			tcp->tcp_iphc_len = 0;
8301 			return (ENOMEM);
8302 		}
8303 	}
8304 
8305 	/* options are gone; may need a new label */
8306 	connp = tcp->tcp_connp;
8307 	connp->conn_mlp_type = mlptSingle;
8308 	connp->conn_ulp_labeled = !is_system_labeled();
8309 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8310 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8311 	tcp->tcp_ip6h = NULL;
8312 	tcp->tcp_ipversion = IPV4_VERSION;
8313 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8314 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8315 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8316 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8317 	tcp->tcp_ipha->ipha_version_and_hdr_length
8318 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8319 	tcp->tcp_ipha->ipha_ident = 0;
8320 
8321 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
8322 	tcp->tcp_tos = 0;
8323 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8324 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
8325 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8326 
8327 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8328 	tcp->tcp_tcph = tcph;
8329 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8330 	/*
8331 	 * IP wants our header length in the checksum field to
8332 	 * allow it to perform a single pseudo-header+checksum
8333 	 * calculation on behalf of TCP.
8334 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8335 	 */
8336 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8337 	sum = (sum >> 16) + (sum & 0xFFFF);
8338 	U16_TO_ABE16(sum, tcph->th_sum);
8339 	return (0);
8340 }
8341 
8342 /*
8343  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8344  */
8345 static int
8346 tcp_header_init_ipv6(tcp_t *tcp)
8347 {
8348 	tcph_t	*tcph;
8349 	uint32_t	sum;
8350 	conn_t	*connp;
8351 
8352 	/*
8353 	 * This is a simple initialization. If there's
8354 	 * already a template, it should never be too small,
8355 	 * so reuse it. Otherwise, allocate space for the new one.
8356 	 * Ensure that there is enough space to "downgrade" the tcp_t
8357 	 * to an IPv4 tcp_t. This requires having space for a full load
8358 	 * of IPv4 options, as well as a full load of TCP options
8359 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8360 	 * than a v6 header and a TCP header with a full load of TCP options
8361 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8362 	 * We want to avoid reallocation in the "downgraded" case when
8363 	 * processing outbound IPv4 options.
8364 	 */
8365 	if (tcp->tcp_iphc == NULL) {
8366 		ASSERT(tcp->tcp_iphc_len == 0);
8367 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8368 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8369 		if (tcp->tcp_iphc == NULL) {
8370 			tcp->tcp_iphc_len = 0;
8371 			return (ENOMEM);
8372 		}
8373 	}
8374 
8375 	/* options are gone; may need a new label */
8376 	connp = tcp->tcp_connp;
8377 	connp->conn_mlp_type = mlptSingle;
8378 	connp->conn_ulp_labeled = !is_system_labeled();
8379 
8380 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8381 	tcp->tcp_ipversion = IPV6_VERSION;
8382 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8383 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8384 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8385 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8386 	tcp->tcp_ipha = NULL;
8387 
8388 	/* Initialize the header template */
8389 
8390 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8391 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8392 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8393 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
8394 
8395 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8396 	tcp->tcp_tcph = tcph;
8397 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8398 	/*
8399 	 * IP wants our header length in the checksum field to
8400 	 * allow it to perform a single psuedo-header+checksum
8401 	 * calculation on behalf of TCP.
8402 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8403 	 */
8404 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8405 	sum = (sum >> 16) + (sum & 0xFFFF);
8406 	U16_TO_ABE16(sum, tcph->th_sum);
8407 	return (0);
8408 }
8409 
8410 /* At minimum we need 8 bytes in the TCP header for the lookup */
8411 #define	ICMP_MIN_TCP_HDR	8
8412 
8413 /*
8414  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8415  * passed up by IP. The message is always received on the correct tcp_t.
8416  * Assumes that IP has pulled up everything up to and including the ICMP header.
8417  */
8418 void
8419 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8420 {
8421 	icmph_t *icmph;
8422 	ipha_t	*ipha;
8423 	int	iph_hdr_length;
8424 	tcph_t	*tcph;
8425 	boolean_t ipsec_mctl = B_FALSE;
8426 	boolean_t secure;
8427 	mblk_t *first_mp = mp;
8428 	uint32_t new_mss;
8429 	uint32_t ratio;
8430 	size_t mp_size = MBLKL(mp);
8431 	uint32_t seg_seq;
8432 
8433 	/* Assume IP provides aligned packets - otherwise toss */
8434 	if (!OK_32PTR(mp->b_rptr)) {
8435 		freemsg(mp);
8436 		return;
8437 	}
8438 
8439 	/*
8440 	 * Since ICMP errors are normal data marked with M_CTL when sent
8441 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8442 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8443 	 */
8444 	if ((mp_size == sizeof (ipsec_info_t)) &&
8445 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8446 		ASSERT(mp->b_cont != NULL);
8447 		mp = mp->b_cont;
8448 		/* IP should have done this */
8449 		ASSERT(OK_32PTR(mp->b_rptr));
8450 		mp_size = MBLKL(mp);
8451 		ipsec_mctl = B_TRUE;
8452 	}
8453 
8454 	/*
8455 	 * Verify that we have a complete outer IP header. If not, drop it.
8456 	 */
8457 	if (mp_size < sizeof (ipha_t)) {
8458 noticmpv4:
8459 		freemsg(first_mp);
8460 		return;
8461 	}
8462 
8463 	ipha = (ipha_t *)mp->b_rptr;
8464 	/*
8465 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8466 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8467 	 */
8468 	switch (IPH_HDR_VERSION(ipha)) {
8469 	case IPV6_VERSION:
8470 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8471 		return;
8472 	case IPV4_VERSION:
8473 		break;
8474 	default:
8475 		goto noticmpv4;
8476 	}
8477 
8478 	/* Skip past the outer IP and ICMP headers */
8479 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8480 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8481 	/*
8482 	 * If we don't have the correct outer IP header length or if the ULP
8483 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8484 	 * send it upstream.
8485 	 */
8486 	if (iph_hdr_length < sizeof (ipha_t) ||
8487 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8488 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8489 		goto noticmpv4;
8490 	}
8491 	ipha = (ipha_t *)&icmph[1];
8492 
8493 	/* Skip past the inner IP and find the ULP header */
8494 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8495 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8496 	/*
8497 	 * If we don't have the correct inner IP header length or if the ULP
8498 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8499 	 * bytes of TCP header, drop it.
8500 	 */
8501 	if (iph_hdr_length < sizeof (ipha_t) ||
8502 	    ipha->ipha_protocol != IPPROTO_TCP ||
8503 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8504 		goto noticmpv4;
8505 	}
8506 
8507 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8508 		if (ipsec_mctl) {
8509 			secure = ipsec_in_is_secure(first_mp);
8510 		} else {
8511 			secure = B_FALSE;
8512 		}
8513 		if (secure) {
8514 			/*
8515 			 * If we are willing to accept this in clear
8516 			 * we don't have to verify policy.
8517 			 */
8518 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8519 				if (!tcp_check_policy(tcp, first_mp,
8520 				    ipha, NULL, secure, ipsec_mctl)) {
8521 					/*
8522 					 * tcp_check_policy called
8523 					 * ip_drop_packet() on failure.
8524 					 */
8525 					return;
8526 				}
8527 			}
8528 		}
8529 	} else if (ipsec_mctl) {
8530 		/*
8531 		 * This is a hard_bound connection. IP has already
8532 		 * verified policy. We don't have to do it again.
8533 		 */
8534 		freeb(first_mp);
8535 		first_mp = mp;
8536 		ipsec_mctl = B_FALSE;
8537 	}
8538 
8539 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8540 	/*
8541 	 * TCP SHOULD check that the TCP sequence number contained in
8542 	 * payload of the ICMP error message is within the range
8543 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8544 	 */
8545 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8546 		/*
8547 		 * If the ICMP message is bogus, should we kill the
8548 		 * connection, or should we just drop the bogus ICMP
8549 		 * message? It would probably make more sense to just
8550 		 * drop the message so that if this one managed to get
8551 		 * in, the real connection should not suffer.
8552 		 */
8553 		goto noticmpv4;
8554 	}
8555 
8556 	switch (icmph->icmph_type) {
8557 	case ICMP_DEST_UNREACHABLE:
8558 		switch (icmph->icmph_code) {
8559 		case ICMP_FRAGMENTATION_NEEDED:
8560 			/*
8561 			 * Reduce the MSS based on the new MTU.  This will
8562 			 * eliminate any fragmentation locally.
8563 			 * N.B.  There may well be some funny side-effects on
8564 			 * the local send policy and the remote receive policy.
8565 			 * Pending further research, we provide
8566 			 * tcp_ignore_path_mtu just in case this proves
8567 			 * disastrous somewhere.
8568 			 *
8569 			 * After updating the MSS, retransmit part of the
8570 			 * dropped segment using the new mss by calling
8571 			 * tcp_wput_data().  Need to adjust all those
8572 			 * params to make sure tcp_wput_data() work properly.
8573 			 */
8574 			if (tcp_ignore_path_mtu)
8575 				break;
8576 
8577 			/*
8578 			 * Decrease the MSS by time stamp options
8579 			 * IP options and IPSEC options. tcp_hdr_len
8580 			 * includes time stamp option and IP option
8581 			 * length.
8582 			 */
8583 
8584 			new_mss = ntohs(icmph->icmph_du_mtu) -
8585 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8586 
8587 			/*
8588 			 * Only update the MSS if the new one is
8589 			 * smaller than the previous one.  This is
8590 			 * to avoid problems when getting multiple
8591 			 * ICMP errors for the same MTU.
8592 			 */
8593 			if (new_mss >= tcp->tcp_mss)
8594 				break;
8595 
8596 			/*
8597 			 * Stop doing PMTU if new_mss is less than 68
8598 			 * or less than tcp_mss_min.
8599 			 * The value 68 comes from rfc 1191.
8600 			 */
8601 			if (new_mss < MAX(68, tcp_mss_min))
8602 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8603 				    0;
8604 
8605 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8606 			ASSERT(ratio >= 1);
8607 			tcp_mss_set(tcp, new_mss);
8608 
8609 			/*
8610 			 * Make sure we have something to
8611 			 * send.
8612 			 */
8613 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8614 			    (tcp->tcp_xmit_head != NULL)) {
8615 				/*
8616 				 * Shrink tcp_cwnd in
8617 				 * proportion to the old MSS/new MSS.
8618 				 */
8619 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8620 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8621 				    (tcp->tcp_unsent == 0)) {
8622 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8623 				} else {
8624 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8625 				}
8626 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8627 				tcp->tcp_rexmit = B_TRUE;
8628 				tcp->tcp_dupack_cnt = 0;
8629 				tcp->tcp_snd_burst = TCP_CWND_SS;
8630 				tcp_ss_rexmit(tcp);
8631 			}
8632 			break;
8633 		case ICMP_PORT_UNREACHABLE:
8634 		case ICMP_PROTOCOL_UNREACHABLE:
8635 			switch (tcp->tcp_state) {
8636 			case TCPS_SYN_SENT:
8637 			case TCPS_SYN_RCVD:
8638 				/*
8639 				 * ICMP can snipe away incipient
8640 				 * TCP connections as long as
8641 				 * seq number is same as initial
8642 				 * send seq number.
8643 				 */
8644 				if (seg_seq == tcp->tcp_iss) {
8645 					(void) tcp_clean_death(tcp,
8646 					    ECONNREFUSED, 6);
8647 				}
8648 				break;
8649 			}
8650 			break;
8651 		case ICMP_HOST_UNREACHABLE:
8652 		case ICMP_NET_UNREACHABLE:
8653 			/* Record the error in case we finally time out. */
8654 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8655 				tcp->tcp_client_errno = EHOSTUNREACH;
8656 			else
8657 				tcp->tcp_client_errno = ENETUNREACH;
8658 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8659 				if (tcp->tcp_listener != NULL &&
8660 				    tcp->tcp_listener->tcp_syn_defense) {
8661 					/*
8662 					 * Ditch the half-open connection if we
8663 					 * suspect a SYN attack is under way.
8664 					 */
8665 					tcp_ip_ire_mark_advice(tcp);
8666 					(void) tcp_clean_death(tcp,
8667 					    tcp->tcp_client_errno, 7);
8668 				}
8669 			}
8670 			break;
8671 		default:
8672 			break;
8673 		}
8674 		break;
8675 	case ICMP_SOURCE_QUENCH: {
8676 		/*
8677 		 * use a global boolean to control
8678 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8679 		 * The default is false.
8680 		 */
8681 		if (tcp_icmp_source_quench) {
8682 			/*
8683 			 * Reduce the sending rate as if we got a
8684 			 * retransmit timeout
8685 			 */
8686 			uint32_t npkt;
8687 
8688 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8689 			    tcp->tcp_mss;
8690 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8691 			tcp->tcp_cwnd = tcp->tcp_mss;
8692 			tcp->tcp_cwnd_cnt = 0;
8693 		}
8694 		break;
8695 	}
8696 	}
8697 	freemsg(first_mp);
8698 }
8699 
8700 /*
8701  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8702  * error messages passed up by IP.
8703  * Assumes that IP has pulled up all the extension headers as well
8704  * as the ICMPv6 header.
8705  */
8706 static void
8707 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8708 {
8709 	icmp6_t *icmp6;
8710 	ip6_t	*ip6h;
8711 	uint16_t	iph_hdr_length;
8712 	tcpha_t	*tcpha;
8713 	uint8_t	*nexthdrp;
8714 	uint32_t new_mss;
8715 	uint32_t ratio;
8716 	boolean_t secure;
8717 	mblk_t *first_mp = mp;
8718 	size_t mp_size;
8719 	uint32_t seg_seq;
8720 
8721 	/*
8722 	 * The caller has determined if this is an IPSEC_IN packet and
8723 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8724 	 */
8725 	if (ipsec_mctl)
8726 		mp = mp->b_cont;
8727 
8728 	mp_size = MBLKL(mp);
8729 
8730 	/*
8731 	 * Verify that we have a complete IP header. If not, send it upstream.
8732 	 */
8733 	if (mp_size < sizeof (ip6_t)) {
8734 noticmpv6:
8735 		freemsg(first_mp);
8736 		return;
8737 	}
8738 
8739 	/*
8740 	 * Verify this is an ICMPV6 packet, else send it upstream.
8741 	 */
8742 	ip6h = (ip6_t *)mp->b_rptr;
8743 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8744 		iph_hdr_length = IPV6_HDR_LEN;
8745 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8746 	    &nexthdrp) ||
8747 	    *nexthdrp != IPPROTO_ICMPV6) {
8748 		goto noticmpv6;
8749 	}
8750 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8751 	ip6h = (ip6_t *)&icmp6[1];
8752 	/*
8753 	 * Verify if we have a complete ICMP and inner IP header.
8754 	 */
8755 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8756 		goto noticmpv6;
8757 
8758 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8759 		goto noticmpv6;
8760 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8761 	/*
8762 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8763 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8764 	 * packet.
8765 	 */
8766 	if ((*nexthdrp != IPPROTO_TCP) ||
8767 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8768 		goto noticmpv6;
8769 	}
8770 
8771 	/*
8772 	 * ICMP errors come on the right queue or come on
8773 	 * listener/global queue for detached connections and
8774 	 * get switched to the right queue. If it comes on the
8775 	 * right queue, policy check has already been done by IP
8776 	 * and thus free the first_mp without verifying the policy.
8777 	 * If it has come for a non-hard bound connection, we need
8778 	 * to verify policy as IP may not have done it.
8779 	 */
8780 	if (!tcp->tcp_hard_bound) {
8781 		if (ipsec_mctl) {
8782 			secure = ipsec_in_is_secure(first_mp);
8783 		} else {
8784 			secure = B_FALSE;
8785 		}
8786 		if (secure) {
8787 			/*
8788 			 * If we are willing to accept this in clear
8789 			 * we don't have to verify policy.
8790 			 */
8791 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8792 				if (!tcp_check_policy(tcp, first_mp,
8793 				    NULL, ip6h, secure, ipsec_mctl)) {
8794 					/*
8795 					 * tcp_check_policy called
8796 					 * ip_drop_packet() on failure.
8797 					 */
8798 					return;
8799 				}
8800 			}
8801 		}
8802 	} else if (ipsec_mctl) {
8803 		/*
8804 		 * This is a hard_bound connection. IP has already
8805 		 * verified policy. We don't have to do it again.
8806 		 */
8807 		freeb(first_mp);
8808 		first_mp = mp;
8809 		ipsec_mctl = B_FALSE;
8810 	}
8811 
8812 	seg_seq = ntohl(tcpha->tha_seq);
8813 	/*
8814 	 * TCP SHOULD check that the TCP sequence number contained in
8815 	 * payload of the ICMP error message is within the range
8816 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8817 	 */
8818 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8819 		/*
8820 		 * If the ICMP message is bogus, should we kill the
8821 		 * connection, or should we just drop the bogus ICMP
8822 		 * message? It would probably make more sense to just
8823 		 * drop the message so that if this one managed to get
8824 		 * in, the real connection should not suffer.
8825 		 */
8826 		goto noticmpv6;
8827 	}
8828 
8829 	switch (icmp6->icmp6_type) {
8830 	case ICMP6_PACKET_TOO_BIG:
8831 		/*
8832 		 * Reduce the MSS based on the new MTU.  This will
8833 		 * eliminate any fragmentation locally.
8834 		 * N.B.  There may well be some funny side-effects on
8835 		 * the local send policy and the remote receive policy.
8836 		 * Pending further research, we provide
8837 		 * tcp_ignore_path_mtu just in case this proves
8838 		 * disastrous somewhere.
8839 		 *
8840 		 * After updating the MSS, retransmit part of the
8841 		 * dropped segment using the new mss by calling
8842 		 * tcp_wput_data().  Need to adjust all those
8843 		 * params to make sure tcp_wput_data() work properly.
8844 		 */
8845 		if (tcp_ignore_path_mtu)
8846 			break;
8847 
8848 		/*
8849 		 * Decrease the MSS by time stamp options
8850 		 * IP options and IPSEC options. tcp_hdr_len
8851 		 * includes time stamp option and IP option
8852 		 * length.
8853 		 */
8854 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8855 			    tcp->tcp_ipsec_overhead;
8856 
8857 		/*
8858 		 * Only update the MSS if the new one is
8859 		 * smaller than the previous one.  This is
8860 		 * to avoid problems when getting multiple
8861 		 * ICMP errors for the same MTU.
8862 		 */
8863 		if (new_mss >= tcp->tcp_mss)
8864 			break;
8865 
8866 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8867 		ASSERT(ratio >= 1);
8868 		tcp_mss_set(tcp, new_mss);
8869 
8870 		/*
8871 		 * Make sure we have something to
8872 		 * send.
8873 		 */
8874 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8875 		    (tcp->tcp_xmit_head != NULL)) {
8876 			/*
8877 			 * Shrink tcp_cwnd in
8878 			 * proportion to the old MSS/new MSS.
8879 			 */
8880 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8881 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8882 			    (tcp->tcp_unsent == 0)) {
8883 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8884 			} else {
8885 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8886 			}
8887 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8888 			tcp->tcp_rexmit = B_TRUE;
8889 			tcp->tcp_dupack_cnt = 0;
8890 			tcp->tcp_snd_burst = TCP_CWND_SS;
8891 			tcp_ss_rexmit(tcp);
8892 		}
8893 		break;
8894 
8895 	case ICMP6_DST_UNREACH:
8896 		switch (icmp6->icmp6_code) {
8897 		case ICMP6_DST_UNREACH_NOPORT:
8898 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8899 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8900 			    (seg_seq == tcp->tcp_iss)) {
8901 				(void) tcp_clean_death(tcp,
8902 				    ECONNREFUSED, 8);
8903 			}
8904 			break;
8905 
8906 		case ICMP6_DST_UNREACH_ADMIN:
8907 		case ICMP6_DST_UNREACH_NOROUTE:
8908 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8909 		case ICMP6_DST_UNREACH_ADDR:
8910 			/* Record the error in case we finally time out. */
8911 			tcp->tcp_client_errno = EHOSTUNREACH;
8912 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8913 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8914 			    (seg_seq == tcp->tcp_iss)) {
8915 				if (tcp->tcp_listener != NULL &&
8916 				    tcp->tcp_listener->tcp_syn_defense) {
8917 					/*
8918 					 * Ditch the half-open connection if we
8919 					 * suspect a SYN attack is under way.
8920 					 */
8921 					tcp_ip_ire_mark_advice(tcp);
8922 					(void) tcp_clean_death(tcp,
8923 					    tcp->tcp_client_errno, 9);
8924 				}
8925 			}
8926 
8927 
8928 			break;
8929 		default:
8930 			break;
8931 		}
8932 		break;
8933 
8934 	case ICMP6_PARAM_PROB:
8935 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8936 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8937 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8938 		    (uchar_t *)nexthdrp) {
8939 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8940 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8941 				(void) tcp_clean_death(tcp,
8942 				    ECONNREFUSED, 10);
8943 			}
8944 			break;
8945 		}
8946 		break;
8947 
8948 	case ICMP6_TIME_EXCEEDED:
8949 	default:
8950 		break;
8951 	}
8952 	freemsg(first_mp);
8953 }
8954 
8955 /*
8956  * IP recognizes seven kinds of bind requests:
8957  *
8958  * - A zero-length address binds only to the protocol number.
8959  *
8960  * - A 4-byte address is treated as a request to
8961  * validate that the address is a valid local IPv4
8962  * address, appropriate for an application to bind to.
8963  * IP does the verification, but does not make any note
8964  * of the address at this time.
8965  *
8966  * - A 16-byte address contains is treated as a request
8967  * to validate a local IPv6 address, as the 4-byte
8968  * address case above.
8969  *
8970  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8971  * use it for the inbound fanout of packets.
8972  *
8973  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8974  * use it for the inbound fanout of packets.
8975  *
8976  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8977  * information consisting of local and remote addresses
8978  * and ports.  In this case, the addresses are both
8979  * validated as appropriate for this operation, and, if
8980  * so, the information is retained for use in the
8981  * inbound fanout.
8982  *
8983  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8984  * fanout information, like the 12-byte case above.
8985  *
8986  * IP will also fill in the IRE request mblk with information
8987  * regarding our peer.  In all cases, we notify IP of our protocol
8988  * type by appending a single protocol byte to the bind request.
8989  */
8990 static mblk_t *
8991 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8992 {
8993 	char	*cp;
8994 	mblk_t	*mp;
8995 	struct T_bind_req *tbr;
8996 	ipa_conn_t	*ac;
8997 	ipa6_conn_t	*ac6;
8998 	sin_t		*sin;
8999 	sin6_t		*sin6;
9000 
9001 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
9002 	ASSERT((tcp->tcp_family == AF_INET &&
9003 	    tcp->tcp_ipversion == IPV4_VERSION) ||
9004 	    (tcp->tcp_family == AF_INET6 &&
9005 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9006 	    tcp->tcp_ipversion == IPV6_VERSION)));
9007 
9008 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9009 	if (!mp)
9010 		return (mp);
9011 	mp->b_datap->db_type = M_PROTO;
9012 	tbr = (struct T_bind_req *)mp->b_rptr;
9013 	tbr->PRIM_type = bind_prim;
9014 	tbr->ADDR_offset = sizeof (*tbr);
9015 	tbr->CONIND_number = 0;
9016 	tbr->ADDR_length = addr_length;
9017 	cp = (char *)&tbr[1];
9018 	switch (addr_length) {
9019 	case sizeof (ipa_conn_t):
9020 		ASSERT(tcp->tcp_family == AF_INET);
9021 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9022 
9023 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9024 		if (mp->b_cont == NULL) {
9025 			freemsg(mp);
9026 			return (NULL);
9027 		}
9028 		mp->b_cont->b_wptr += sizeof (ire_t);
9029 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9030 
9031 		/* cp known to be 32 bit aligned */
9032 		ac = (ipa_conn_t *)cp;
9033 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9034 		ac->ac_faddr = tcp->tcp_remote;
9035 		ac->ac_fport = tcp->tcp_fport;
9036 		ac->ac_lport = tcp->tcp_lport;
9037 		tcp->tcp_hard_binding = 1;
9038 		break;
9039 
9040 	case sizeof (ipa6_conn_t):
9041 		ASSERT(tcp->tcp_family == AF_INET6);
9042 
9043 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9044 		if (mp->b_cont == NULL) {
9045 			freemsg(mp);
9046 			return (NULL);
9047 		}
9048 		mp->b_cont->b_wptr += sizeof (ire_t);
9049 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9050 
9051 		/* cp known to be 32 bit aligned */
9052 		ac6 = (ipa6_conn_t *)cp;
9053 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9054 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9055 			    &ac6->ac6_laddr);
9056 		} else {
9057 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9058 		}
9059 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9060 		ac6->ac6_fport = tcp->tcp_fport;
9061 		ac6->ac6_lport = tcp->tcp_lport;
9062 		tcp->tcp_hard_binding = 1;
9063 		break;
9064 
9065 	case sizeof (sin_t):
9066 		/*
9067 		 * NOTE: IPV6_ADDR_LEN also has same size.
9068 		 * Use family to discriminate.
9069 		 */
9070 		if (tcp->tcp_family == AF_INET) {
9071 			sin = (sin_t *)cp;
9072 
9073 			*sin = sin_null;
9074 			sin->sin_family = AF_INET;
9075 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9076 			sin->sin_port = tcp->tcp_lport;
9077 			break;
9078 		} else {
9079 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9080 		}
9081 		break;
9082 
9083 	case sizeof (sin6_t):
9084 		ASSERT(tcp->tcp_family == AF_INET6);
9085 		sin6 = (sin6_t *)cp;
9086 
9087 		*sin6 = sin6_null;
9088 		sin6->sin6_family = AF_INET6;
9089 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9090 		sin6->sin6_port = tcp->tcp_lport;
9091 		break;
9092 
9093 	case IP_ADDR_LEN:
9094 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9095 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9096 		break;
9097 
9098 	}
9099 	/* Add protocol number to end */
9100 	cp[addr_length] = (char)IPPROTO_TCP;
9101 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9102 	return (mp);
9103 }
9104 
9105 /*
9106  * Notify IP that we are having trouble with this connection.  IP should
9107  * blow the IRE away and start over.
9108  */
9109 static void
9110 tcp_ip_notify(tcp_t *tcp)
9111 {
9112 	struct iocblk	*iocp;
9113 	ipid_t	*ipid;
9114 	mblk_t	*mp;
9115 
9116 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9117 	if (tcp->tcp_ipversion == IPV6_VERSION)
9118 		return;
9119 
9120 	mp = mkiocb(IP_IOCTL);
9121 	if (mp == NULL)
9122 		return;
9123 
9124 	iocp = (struct iocblk *)mp->b_rptr;
9125 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9126 
9127 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9128 	if (!mp->b_cont) {
9129 		freeb(mp);
9130 		return;
9131 	}
9132 
9133 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9134 	mp->b_cont->b_wptr += iocp->ioc_count;
9135 	bzero(ipid, sizeof (*ipid));
9136 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9137 	ipid->ipid_ire_type = IRE_CACHE;
9138 	ipid->ipid_addr_offset = sizeof (ipid_t);
9139 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9140 	/*
9141 	 * Note: in the case of source routing we want to blow away the
9142 	 * route to the first source route hop.
9143 	 */
9144 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9145 	    sizeof (tcp->tcp_ipha->ipha_dst));
9146 
9147 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9148 }
9149 
9150 /* Unlink and return any mblk that looks like it contains an ire */
9151 static mblk_t *
9152 tcp_ire_mp(mblk_t *mp)
9153 {
9154 	mblk_t	*prev_mp;
9155 
9156 	for (;;) {
9157 		prev_mp = mp;
9158 		mp = mp->b_cont;
9159 		if (mp == NULL)
9160 			break;
9161 		switch (DB_TYPE(mp)) {
9162 		case IRE_DB_TYPE:
9163 		case IRE_DB_REQ_TYPE:
9164 			if (prev_mp != NULL)
9165 				prev_mp->b_cont = mp->b_cont;
9166 			mp->b_cont = NULL;
9167 			return (mp);
9168 		default:
9169 			break;
9170 		}
9171 	}
9172 	return (mp);
9173 }
9174 
9175 /*
9176  * Timer callback routine for keepalive probe.  We do a fake resend of
9177  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9178  * check to see if we have heard anything from the other end for the last
9179  * RTO period.  If we have, set the timer to expire for another
9180  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9181  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9182  * the timeout if we have not heard from the other side.  If for more than
9183  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9184  * kill the connection unless the keepalive abort threshold is 0.  In
9185  * that case, we will probe "forever."
9186  */
9187 static void
9188 tcp_keepalive_killer(void *arg)
9189 {
9190 	mblk_t	*mp;
9191 	conn_t	*connp = (conn_t *)arg;
9192 	tcp_t  	*tcp = connp->conn_tcp;
9193 	int32_t	firetime;
9194 	int32_t	idletime;
9195 	int32_t	ka_intrvl;
9196 
9197 	tcp->tcp_ka_tid = 0;
9198 
9199 	if (tcp->tcp_fused)
9200 		return;
9201 
9202 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
9203 	ka_intrvl = tcp->tcp_ka_interval;
9204 
9205 	/*
9206 	 * Keepalive probe should only be sent if the application has not
9207 	 * done a close on the connection.
9208 	 */
9209 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9210 		return;
9211 	}
9212 	/* Timer fired too early, restart it. */
9213 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9214 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9215 		    MSEC_TO_TICK(ka_intrvl));
9216 		return;
9217 	}
9218 
9219 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9220 	/*
9221 	 * If we have not heard from the other side for a long
9222 	 * time, kill the connection unless the keepalive abort
9223 	 * threshold is 0.  In that case, we will probe "forever."
9224 	 */
9225 	if (tcp->tcp_ka_abort_thres != 0 &&
9226 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9227 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
9228 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9229 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9230 		return;
9231 	}
9232 
9233 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9234 	    idletime >= ka_intrvl) {
9235 		/* Fake resend of last ACKed byte. */
9236 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9237 
9238 		if (mp1 != NULL) {
9239 			*mp1->b_wptr++ = '\0';
9240 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9241 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9242 			freeb(mp1);
9243 			/*
9244 			 * if allocation failed, fall through to start the
9245 			 * timer back.
9246 			 */
9247 			if (mp != NULL) {
9248 				TCP_RECORD_TRACE(tcp, mp,
9249 				    TCP_TRACE_SEND_PKT);
9250 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9251 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
9252 				if (tcp->tcp_ka_last_intrvl != 0) {
9253 					/*
9254 					 * We should probe again at least
9255 					 * in ka_intrvl, but not more than
9256 					 * tcp_rexmit_interval_max.
9257 					 */
9258 					firetime = MIN(ka_intrvl - 1,
9259 					    tcp->tcp_ka_last_intrvl << 1);
9260 					if (firetime > tcp_rexmit_interval_max)
9261 						firetime =
9262 						    tcp_rexmit_interval_max;
9263 				} else {
9264 					firetime = tcp->tcp_rto;
9265 				}
9266 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9267 				    tcp_keepalive_killer,
9268 				    MSEC_TO_TICK(firetime));
9269 				tcp->tcp_ka_last_intrvl = firetime;
9270 				return;
9271 			}
9272 		}
9273 	} else {
9274 		tcp->tcp_ka_last_intrvl = 0;
9275 	}
9276 
9277 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9278 	if ((firetime = ka_intrvl - idletime) < 0) {
9279 		firetime = ka_intrvl;
9280 	}
9281 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9282 	    MSEC_TO_TICK(firetime));
9283 }
9284 
9285 int
9286 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9287 {
9288 	queue_t	*q = tcp->tcp_rq;
9289 	int32_t	mss = tcp->tcp_mss;
9290 	int	maxpsz;
9291 
9292 	if (TCP_IS_DETACHED(tcp))
9293 		return (mss);
9294 
9295 	if (tcp->tcp_fused) {
9296 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9297 		mss = INFPSZ;
9298 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
9299 		/*
9300 		 * Set the sd_qn_maxpsz according to the socket send buffer
9301 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9302 		 * instruct the stream head to copyin user data into contiguous
9303 		 * kernel-allocated buffers without breaking it up into smaller
9304 		 * chunks.  We round up the buffer size to the nearest SMSS.
9305 		 */
9306 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9307 		if (tcp->tcp_kssl_ctx == NULL)
9308 			mss = INFPSZ;
9309 		else
9310 			mss = SSL3_MAX_RECORD_LEN;
9311 	} else {
9312 		/*
9313 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9314 		 * (and a multiple of the mss).  This instructs the stream
9315 		 * head to break down larger than SMSS writes into SMSS-
9316 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9317 		 */
9318 		maxpsz = tcp->tcp_maxpsz * mss;
9319 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9320 			maxpsz = tcp->tcp_xmit_hiwater/2;
9321 			/* Round up to nearest mss */
9322 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9323 		}
9324 	}
9325 	(void) setmaxps(q, maxpsz);
9326 	tcp->tcp_wq->q_maxpsz = maxpsz;
9327 
9328 	if (set_maxblk)
9329 		(void) mi_set_sth_maxblk(q, mss);
9330 
9331 	return (mss);
9332 }
9333 
9334 /*
9335  * Extract option values from a tcp header.  We put any found values into the
9336  * tcpopt struct and return a bitmask saying which options were found.
9337  */
9338 static int
9339 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9340 {
9341 	uchar_t		*endp;
9342 	int		len;
9343 	uint32_t	mss;
9344 	uchar_t		*up = (uchar_t *)tcph;
9345 	int		found = 0;
9346 	int32_t		sack_len;
9347 	tcp_seq		sack_begin, sack_end;
9348 	tcp_t		*tcp;
9349 
9350 	endp = up + TCP_HDR_LENGTH(tcph);
9351 	up += TCP_MIN_HEADER_LENGTH;
9352 	while (up < endp) {
9353 		len = endp - up;
9354 		switch (*up) {
9355 		case TCPOPT_EOL:
9356 			break;
9357 
9358 		case TCPOPT_NOP:
9359 			up++;
9360 			continue;
9361 
9362 		case TCPOPT_MAXSEG:
9363 			if (len < TCPOPT_MAXSEG_LEN ||
9364 			    up[1] != TCPOPT_MAXSEG_LEN)
9365 				break;
9366 
9367 			mss = BE16_TO_U16(up+2);
9368 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9369 			tcpopt->tcp_opt_mss = mss;
9370 			found |= TCP_OPT_MSS_PRESENT;
9371 
9372 			up += TCPOPT_MAXSEG_LEN;
9373 			continue;
9374 
9375 		case TCPOPT_WSCALE:
9376 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9377 				break;
9378 
9379 			if (up[2] > TCP_MAX_WINSHIFT)
9380 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9381 			else
9382 				tcpopt->tcp_opt_wscale = up[2];
9383 			found |= TCP_OPT_WSCALE_PRESENT;
9384 
9385 			up += TCPOPT_WS_LEN;
9386 			continue;
9387 
9388 		case TCPOPT_SACK_PERMITTED:
9389 			if (len < TCPOPT_SACK_OK_LEN ||
9390 			    up[1] != TCPOPT_SACK_OK_LEN)
9391 				break;
9392 			found |= TCP_OPT_SACK_OK_PRESENT;
9393 			up += TCPOPT_SACK_OK_LEN;
9394 			continue;
9395 
9396 		case TCPOPT_SACK:
9397 			if (len <= 2 || up[1] <= 2 || len < up[1])
9398 				break;
9399 
9400 			/* If TCP is not interested in SACK blks... */
9401 			if ((tcp = tcpopt->tcp) == NULL) {
9402 				up += up[1];
9403 				continue;
9404 			}
9405 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9406 			up += TCPOPT_HEADER_LEN;
9407 
9408 			/*
9409 			 * If the list is empty, allocate one and assume
9410 			 * nothing is sack'ed.
9411 			 */
9412 			ASSERT(tcp->tcp_sack_info != NULL);
9413 			if (tcp->tcp_notsack_list == NULL) {
9414 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9415 				    tcp->tcp_suna, tcp->tcp_snxt,
9416 				    &(tcp->tcp_num_notsack_blk),
9417 				    &(tcp->tcp_cnt_notsack_list));
9418 
9419 				/*
9420 				 * Make sure tcp_notsack_list is not NULL.
9421 				 * This happens when kmem_alloc(KM_NOSLEEP)
9422 				 * returns NULL.
9423 				 */
9424 				if (tcp->tcp_notsack_list == NULL) {
9425 					up += sack_len;
9426 					continue;
9427 				}
9428 				tcp->tcp_fack = tcp->tcp_suna;
9429 			}
9430 
9431 			while (sack_len > 0) {
9432 				if (up + 8 > endp) {
9433 					up = endp;
9434 					break;
9435 				}
9436 				sack_begin = BE32_TO_U32(up);
9437 				up += 4;
9438 				sack_end = BE32_TO_U32(up);
9439 				up += 4;
9440 				sack_len -= 8;
9441 				/*
9442 				 * Bounds checking.  Make sure the SACK
9443 				 * info is within tcp_suna and tcp_snxt.
9444 				 * If this SACK blk is out of bound, ignore
9445 				 * it but continue to parse the following
9446 				 * blks.
9447 				 */
9448 				if (SEQ_LEQ(sack_end, sack_begin) ||
9449 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9450 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9451 					continue;
9452 				}
9453 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9454 				    sack_begin, sack_end,
9455 				    &(tcp->tcp_num_notsack_blk),
9456 				    &(tcp->tcp_cnt_notsack_list));
9457 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9458 					tcp->tcp_fack = sack_end;
9459 				}
9460 			}
9461 			found |= TCP_OPT_SACK_PRESENT;
9462 			continue;
9463 
9464 		case TCPOPT_TSTAMP:
9465 			if (len < TCPOPT_TSTAMP_LEN ||
9466 			    up[1] != TCPOPT_TSTAMP_LEN)
9467 				break;
9468 
9469 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9470 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9471 
9472 			found |= TCP_OPT_TSTAMP_PRESENT;
9473 
9474 			up += TCPOPT_TSTAMP_LEN;
9475 			continue;
9476 
9477 		default:
9478 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9479 				break;
9480 			up += up[1];
9481 			continue;
9482 		}
9483 		break;
9484 	}
9485 	return (found);
9486 }
9487 
9488 /*
9489  * Set the mss associated with a particular tcp based on its current value,
9490  * and a new one passed in. Observe minimums and maximums, and reset
9491  * other state variables that we want to view as multiples of mss.
9492  *
9493  * This function is called in various places mainly because
9494  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
9495  *    other side's SYN/SYN-ACK packet arrives.
9496  * 2) PMTUd may get us a new MSS.
9497  * 3) If the other side stops sending us timestamp option, we need to
9498  *    increase the MSS size to use the extra bytes available.
9499  */
9500 static void
9501 tcp_mss_set(tcp_t *tcp, uint32_t mss)
9502 {
9503 	uint32_t	mss_max;
9504 
9505 	if (tcp->tcp_ipversion == IPV4_VERSION)
9506 		mss_max = tcp_mss_max_ipv4;
9507 	else
9508 		mss_max = tcp_mss_max_ipv6;
9509 
9510 	if (mss < tcp_mss_min)
9511 		mss = tcp_mss_min;
9512 	if (mss > mss_max)
9513 		mss = mss_max;
9514 	/*
9515 	 * Unless naglim has been set by our client to
9516 	 * a non-mss value, force naglim to track mss.
9517 	 * This can help to aggregate small writes.
9518 	 */
9519 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9520 		tcp->tcp_naglim = mss;
9521 	/*
9522 	 * TCP should be able to buffer at least 4 MSS data for obvious
9523 	 * performance reason.
9524 	 */
9525 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9526 		tcp->tcp_xmit_hiwater = mss << 2;
9527 
9528 	/*
9529 	 * Check if we need to apply the tcp_init_cwnd here.  If
9530 	 * it is set and the MSS gets bigger (should not happen
9531 	 * normally), we need to adjust the resulting tcp_cwnd properly.
9532 	 * The new tcp_cwnd should not get bigger.
9533 	 */
9534 	if (tcp->tcp_init_cwnd == 0) {
9535 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
9536 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
9537 	} else {
9538 		if (tcp->tcp_mss < mss) {
9539 			tcp->tcp_cwnd = MAX(1,
9540 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
9541 		} else {
9542 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
9543 		}
9544 	}
9545 	tcp->tcp_mss = mss;
9546 	tcp->tcp_cwnd_cnt = 0;
9547 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9548 }
9549 
9550 static int
9551 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9552 {
9553 	tcp_t		*tcp = NULL;
9554 	conn_t		*connp;
9555 	int		err;
9556 	dev_t		conn_dev;
9557 	zoneid_t	zoneid = getzoneid();
9558 
9559 	/*
9560 	 * Special case for install: miniroot needs to be able to access files
9561 	 * via NFS as though it were always in the global zone.
9562 	 */
9563 	if (credp == kcred && nfs_global_client_only != 0)
9564 		zoneid = GLOBAL_ZONEID;
9565 
9566 	if (q->q_ptr != NULL)
9567 		return (0);
9568 
9569 	if (sflag == MODOPEN) {
9570 		/*
9571 		 * This is a special case. The purpose of a modopen
9572 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
9573 		 * through for MIB browsers. Everything else is failed.
9574 		 */
9575 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9576 
9577 		if (connp == NULL)
9578 			return (ENOMEM);
9579 
9580 		connp->conn_flags |= IPCL_TCPMOD;
9581 		connp->conn_cred = credp;
9582 		connp->conn_zoneid = zoneid;
9583 		q->q_ptr = WR(q)->q_ptr = connp;
9584 		crhold(credp);
9585 		q->q_qinfo = &tcp_mod_rinit;
9586 		WR(q)->q_qinfo = &tcp_mod_winit;
9587 		qprocson(q);
9588 		return (0);
9589 	}
9590 
9591 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
9592 		return (EBUSY);
9593 
9594 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9595 
9596 	if (flag & SO_ACCEPTOR) {
9597 		q->q_qinfo = &tcp_acceptor_rinit;
9598 		q->q_ptr = (void *)conn_dev;
9599 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9600 		WR(q)->q_ptr = (void *)conn_dev;
9601 		qprocson(q);
9602 		return (0);
9603 	}
9604 
9605 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9606 	if (connp == NULL) {
9607 		inet_minor_free(ip_minor_arena, conn_dev);
9608 		q->q_ptr = NULL;
9609 		return (ENOSR);
9610 	}
9611 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9612 	tcp = connp->conn_tcp;
9613 
9614 	q->q_ptr = WR(q)->q_ptr = connp;
9615 	if (getmajor(*devp) == TCP6_MAJ) {
9616 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9617 		connp->conn_send = ip_output_v6;
9618 		connp->conn_af_isv6 = B_TRUE;
9619 		connp->conn_pkt_isv6 = B_TRUE;
9620 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9621 		tcp->tcp_ipversion = IPV6_VERSION;
9622 		tcp->tcp_family = AF_INET6;
9623 		tcp->tcp_mss = tcp_mss_def_ipv6;
9624 	} else {
9625 		connp->conn_flags |= IPCL_TCP4;
9626 		connp->conn_send = ip_output;
9627 		connp->conn_af_isv6 = B_FALSE;
9628 		connp->conn_pkt_isv6 = B_FALSE;
9629 		tcp->tcp_ipversion = IPV4_VERSION;
9630 		tcp->tcp_family = AF_INET;
9631 		tcp->tcp_mss = tcp_mss_def_ipv4;
9632 	}
9633 
9634 	/*
9635 	 * TCP keeps a copy of cred for cache locality reasons but
9636 	 * we put a reference only once. If connp->conn_cred
9637 	 * becomes invalid, tcp_cred should also be set to NULL.
9638 	 */
9639 	tcp->tcp_cred = connp->conn_cred = credp;
9640 	crhold(connp->conn_cred);
9641 	tcp->tcp_cpid = curproc->p_pid;
9642 	tcp->tcp_open_time = lbolt64;
9643 	connp->conn_zoneid = zoneid;
9644 	connp->conn_mlp_type = mlptSingle;
9645 	connp->conn_ulp_labeled = !is_system_labeled();
9646 
9647 	/*
9648 	 * If the caller has the process-wide flag set, then default to MAC
9649 	 * exempt mode.  This allows read-down to unlabeled hosts.
9650 	 */
9651 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9652 		connp->conn_mac_exempt = B_TRUE;
9653 
9654 	connp->conn_dev = conn_dev;
9655 
9656 	ASSERT(q->q_qinfo == &tcp_rinit);
9657 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9658 
9659 	if (flag & SO_SOCKSTR) {
9660 		/*
9661 		 * No need to insert a socket in tcp acceptor hash.
9662 		 * If it was a socket acceptor stream, we dealt with
9663 		 * it above. A socket listener can never accept a
9664 		 * connection and doesn't need acceptor_id.
9665 		 */
9666 		connp->conn_flags |= IPCL_SOCKET;
9667 		tcp->tcp_issocket = 1;
9668 		WR(q)->q_qinfo = &tcp_sock_winit;
9669 	} else {
9670 #ifdef	_ILP32
9671 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9672 #else
9673 		tcp->tcp_acceptor_id = conn_dev;
9674 #endif	/* _ILP32 */
9675 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9676 	}
9677 
9678 	if (tcp_trace)
9679 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9680 
9681 	err = tcp_init(tcp, q);
9682 	if (err != 0) {
9683 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9684 		tcp_acceptor_hash_remove(tcp);
9685 		CONN_DEC_REF(connp);
9686 		q->q_ptr = WR(q)->q_ptr = NULL;
9687 		return (err);
9688 	}
9689 
9690 	RD(q)->q_hiwat = tcp_recv_hiwat;
9691 	tcp->tcp_rwnd = tcp_recv_hiwat;
9692 
9693 	/* Non-zero default values */
9694 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9695 	/*
9696 	 * Put the ref for TCP. Ref for IP was already put
9697 	 * by ipcl_conn_create. Also Make the conn_t globally
9698 	 * visible to walkers
9699 	 */
9700 	mutex_enter(&connp->conn_lock);
9701 	CONN_INC_REF_LOCKED(connp);
9702 	ASSERT(connp->conn_ref == 2);
9703 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9704 	mutex_exit(&connp->conn_lock);
9705 
9706 	qprocson(q);
9707 	return (0);
9708 }
9709 
9710 /*
9711  * Some TCP options can be "set" by requesting them in the option
9712  * buffer. This is needed for XTI feature test though we do not
9713  * allow it in general. We interpret that this mechanism is more
9714  * applicable to OSI protocols and need not be allowed in general.
9715  * This routine filters out options for which it is not allowed (most)
9716  * and lets through those (few) for which it is. [ The XTI interface
9717  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9718  * ever implemented will have to be allowed here ].
9719  */
9720 static boolean_t
9721 tcp_allow_connopt_set(int level, int name)
9722 {
9723 
9724 	switch (level) {
9725 	case IPPROTO_TCP:
9726 		switch (name) {
9727 		case TCP_NODELAY:
9728 			return (B_TRUE);
9729 		default:
9730 			return (B_FALSE);
9731 		}
9732 		/*NOTREACHED*/
9733 	default:
9734 		return (B_FALSE);
9735 	}
9736 	/*NOTREACHED*/
9737 }
9738 
9739 /*
9740  * This routine gets default values of certain options whose default
9741  * values are maintained by protocol specific code
9742  */
9743 /* ARGSUSED */
9744 int
9745 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9746 {
9747 	int32_t	*i1 = (int32_t *)ptr;
9748 
9749 	switch (level) {
9750 	case IPPROTO_TCP:
9751 		switch (name) {
9752 		case TCP_NOTIFY_THRESHOLD:
9753 			*i1 = tcp_ip_notify_interval;
9754 			break;
9755 		case TCP_ABORT_THRESHOLD:
9756 			*i1 = tcp_ip_abort_interval;
9757 			break;
9758 		case TCP_CONN_NOTIFY_THRESHOLD:
9759 			*i1 = tcp_ip_notify_cinterval;
9760 			break;
9761 		case TCP_CONN_ABORT_THRESHOLD:
9762 			*i1 = tcp_ip_abort_cinterval;
9763 			break;
9764 		default:
9765 			return (-1);
9766 		}
9767 		break;
9768 	case IPPROTO_IP:
9769 		switch (name) {
9770 		case IP_TTL:
9771 			*i1 = tcp_ipv4_ttl;
9772 			break;
9773 		default:
9774 			return (-1);
9775 		}
9776 		break;
9777 	case IPPROTO_IPV6:
9778 		switch (name) {
9779 		case IPV6_UNICAST_HOPS:
9780 			*i1 = tcp_ipv6_hoplimit;
9781 			break;
9782 		default:
9783 			return (-1);
9784 		}
9785 		break;
9786 	default:
9787 		return (-1);
9788 	}
9789 	return (sizeof (int));
9790 }
9791 
9792 
9793 /*
9794  * TCP routine to get the values of options.
9795  */
9796 int
9797 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9798 {
9799 	int		*i1 = (int *)ptr;
9800 	conn_t		*connp = Q_TO_CONN(q);
9801 	tcp_t		*tcp = connp->conn_tcp;
9802 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9803 
9804 	switch (level) {
9805 	case SOL_SOCKET:
9806 		switch (name) {
9807 		case SO_LINGER:	{
9808 			struct linger *lgr = (struct linger *)ptr;
9809 
9810 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9811 			lgr->l_linger = tcp->tcp_lingertime;
9812 			}
9813 			return (sizeof (struct linger));
9814 		case SO_DEBUG:
9815 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9816 			break;
9817 		case SO_KEEPALIVE:
9818 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9819 			break;
9820 		case SO_DONTROUTE:
9821 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9822 			break;
9823 		case SO_USELOOPBACK:
9824 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9825 			break;
9826 		case SO_BROADCAST:
9827 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9828 			break;
9829 		case SO_REUSEADDR:
9830 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9831 			break;
9832 		case SO_OOBINLINE:
9833 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9834 			break;
9835 		case SO_DGRAM_ERRIND:
9836 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9837 			break;
9838 		case SO_TYPE:
9839 			*i1 = SOCK_STREAM;
9840 			break;
9841 		case SO_SNDBUF:
9842 			*i1 = tcp->tcp_xmit_hiwater;
9843 			break;
9844 		case SO_RCVBUF:
9845 			*i1 = RD(q)->q_hiwat;
9846 			break;
9847 		case SO_SND_COPYAVOID:
9848 			*i1 = tcp->tcp_snd_zcopy_on ?
9849 			    SO_SND_COPYAVOID : 0;
9850 			break;
9851 		case SO_ALLZONES:
9852 			*i1 = connp->conn_allzones ? 1 : 0;
9853 			break;
9854 		case SO_ANON_MLP:
9855 			*i1 = connp->conn_anon_mlp;
9856 			break;
9857 		case SO_MAC_EXEMPT:
9858 			*i1 = connp->conn_mac_exempt;
9859 			break;
9860 		case SO_EXCLBIND:
9861 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9862 			break;
9863 		case SO_PROTOTYPE:
9864 			*i1 = IPPROTO_TCP;
9865 			break;
9866 		case SO_DOMAIN:
9867 			*i1 = tcp->tcp_family;
9868 			break;
9869 		default:
9870 			return (-1);
9871 		}
9872 		break;
9873 	case IPPROTO_TCP:
9874 		switch (name) {
9875 		case TCP_NODELAY:
9876 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9877 			break;
9878 		case TCP_MAXSEG:
9879 			*i1 = tcp->tcp_mss;
9880 			break;
9881 		case TCP_NOTIFY_THRESHOLD:
9882 			*i1 = (int)tcp->tcp_first_timer_threshold;
9883 			break;
9884 		case TCP_ABORT_THRESHOLD:
9885 			*i1 = tcp->tcp_second_timer_threshold;
9886 			break;
9887 		case TCP_CONN_NOTIFY_THRESHOLD:
9888 			*i1 = tcp->tcp_first_ctimer_threshold;
9889 			break;
9890 		case TCP_CONN_ABORT_THRESHOLD:
9891 			*i1 = tcp->tcp_second_ctimer_threshold;
9892 			break;
9893 		case TCP_RECVDSTADDR:
9894 			*i1 = tcp->tcp_recvdstaddr;
9895 			break;
9896 		case TCP_ANONPRIVBIND:
9897 			*i1 = tcp->tcp_anon_priv_bind;
9898 			break;
9899 		case TCP_EXCLBIND:
9900 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9901 			break;
9902 		case TCP_INIT_CWND:
9903 			*i1 = tcp->tcp_init_cwnd;
9904 			break;
9905 		case TCP_KEEPALIVE_THRESHOLD:
9906 			*i1 = tcp->tcp_ka_interval;
9907 			break;
9908 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9909 			*i1 = tcp->tcp_ka_abort_thres;
9910 			break;
9911 		case TCP_CORK:
9912 			*i1 = tcp->tcp_cork;
9913 			break;
9914 		default:
9915 			return (-1);
9916 		}
9917 		break;
9918 	case IPPROTO_IP:
9919 		if (tcp->tcp_family != AF_INET)
9920 			return (-1);
9921 		switch (name) {
9922 		case IP_OPTIONS:
9923 		case T_IP_OPTIONS: {
9924 			/*
9925 			 * This is compatible with BSD in that in only return
9926 			 * the reverse source route with the final destination
9927 			 * as the last entry. The first 4 bytes of the option
9928 			 * will contain the final destination.
9929 			 */
9930 			int	opt_len;
9931 
9932 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9933 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9934 			ASSERT(opt_len >= 0);
9935 			/* Caller ensures enough space */
9936 			if (opt_len > 0) {
9937 				/*
9938 				 * TODO: Do we have to handle getsockopt on an
9939 				 * initiator as well?
9940 				 */
9941 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9942 			}
9943 			return (0);
9944 			}
9945 		case IP_TOS:
9946 		case T_IP_TOS:
9947 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9948 			break;
9949 		case IP_TTL:
9950 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9951 			break;
9952 		case IP_NEXTHOP:
9953 			/* Handled at IP level */
9954 			return (-EINVAL);
9955 		default:
9956 			return (-1);
9957 		}
9958 		break;
9959 	case IPPROTO_IPV6:
9960 		/*
9961 		 * IPPROTO_IPV6 options are only supported for sockets
9962 		 * that are using IPv6 on the wire.
9963 		 */
9964 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9965 			return (-1);
9966 		}
9967 		switch (name) {
9968 		case IPV6_UNICAST_HOPS:
9969 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9970 			break;	/* goto sizeof (int) option return */
9971 		case IPV6_BOUND_IF:
9972 			/* Zero if not set */
9973 			*i1 = tcp->tcp_bound_if;
9974 			break;	/* goto sizeof (int) option return */
9975 		case IPV6_RECVPKTINFO:
9976 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9977 				*i1 = 1;
9978 			else
9979 				*i1 = 0;
9980 			break;	/* goto sizeof (int) option return */
9981 		case IPV6_RECVTCLASS:
9982 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9983 				*i1 = 1;
9984 			else
9985 				*i1 = 0;
9986 			break;	/* goto sizeof (int) option return */
9987 		case IPV6_RECVHOPLIMIT:
9988 			if (tcp->tcp_ipv6_recvancillary &
9989 			    TCP_IPV6_RECVHOPLIMIT)
9990 				*i1 = 1;
9991 			else
9992 				*i1 = 0;
9993 			break;	/* goto sizeof (int) option return */
9994 		case IPV6_RECVHOPOPTS:
9995 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9996 				*i1 = 1;
9997 			else
9998 				*i1 = 0;
9999 			break;	/* goto sizeof (int) option return */
10000 		case IPV6_RECVDSTOPTS:
10001 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10002 				*i1 = 1;
10003 			else
10004 				*i1 = 0;
10005 			break;	/* goto sizeof (int) option return */
10006 		case _OLD_IPV6_RECVDSTOPTS:
10007 			if (tcp->tcp_ipv6_recvancillary &
10008 			    TCP_OLD_IPV6_RECVDSTOPTS)
10009 				*i1 = 1;
10010 			else
10011 				*i1 = 0;
10012 			break;	/* goto sizeof (int) option return */
10013 		case IPV6_RECVRTHDR:
10014 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10015 				*i1 = 1;
10016 			else
10017 				*i1 = 0;
10018 			break;	/* goto sizeof (int) option return */
10019 		case IPV6_RECVRTHDRDSTOPTS:
10020 			if (tcp->tcp_ipv6_recvancillary &
10021 			    TCP_IPV6_RECVRTDSTOPTS)
10022 				*i1 = 1;
10023 			else
10024 				*i1 = 0;
10025 			break;	/* goto sizeof (int) option return */
10026 		case IPV6_PKTINFO: {
10027 			/* XXX assumes that caller has room for max size! */
10028 			struct in6_pktinfo *pkti;
10029 
10030 			pkti = (struct in6_pktinfo *)ptr;
10031 			if (ipp->ipp_fields & IPPF_IFINDEX)
10032 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10033 			else
10034 				pkti->ipi6_ifindex = 0;
10035 			if (ipp->ipp_fields & IPPF_ADDR)
10036 				pkti->ipi6_addr = ipp->ipp_addr;
10037 			else
10038 				pkti->ipi6_addr = ipv6_all_zeros;
10039 			return (sizeof (struct in6_pktinfo));
10040 		}
10041 		case IPV6_TCLASS:
10042 			if (ipp->ipp_fields & IPPF_TCLASS)
10043 				*i1 = ipp->ipp_tclass;
10044 			else
10045 				*i1 = IPV6_FLOW_TCLASS(
10046 				    IPV6_DEFAULT_VERS_AND_FLOW);
10047 			break;	/* goto sizeof (int) option return */
10048 		case IPV6_NEXTHOP: {
10049 			sin6_t *sin6 = (sin6_t *)ptr;
10050 
10051 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10052 				return (0);
10053 			*sin6 = sin6_null;
10054 			sin6->sin6_family = AF_INET6;
10055 			sin6->sin6_addr = ipp->ipp_nexthop;
10056 			return (sizeof (sin6_t));
10057 		}
10058 		case IPV6_HOPOPTS:
10059 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10060 				return (0);
10061 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
10062 				return (0);
10063 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
10064 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
10065 			if (tcp->tcp_label_len > 0) {
10066 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
10067 				ptr[1] = (ipp->ipp_hopoptslen -
10068 				    tcp->tcp_label_len + 7) / 8 - 1;
10069 			}
10070 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
10071 		case IPV6_RTHDRDSTOPTS:
10072 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10073 				return (0);
10074 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10075 			return (ipp->ipp_rtdstoptslen);
10076 		case IPV6_RTHDR:
10077 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10078 				return (0);
10079 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10080 			return (ipp->ipp_rthdrlen);
10081 		case IPV6_DSTOPTS:
10082 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10083 				return (0);
10084 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10085 			return (ipp->ipp_dstoptslen);
10086 		case IPV6_SRC_PREFERENCES:
10087 			return (ip6_get_src_preferences(connp,
10088 			    (uint32_t *)ptr));
10089 		case IPV6_PATHMTU: {
10090 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10091 
10092 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10093 				return (-1);
10094 
10095 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10096 				connp->conn_fport, mtuinfo));
10097 		}
10098 		default:
10099 			return (-1);
10100 		}
10101 		break;
10102 	default:
10103 		return (-1);
10104 	}
10105 	return (sizeof (int));
10106 }
10107 
10108 /*
10109  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10110  * Parameters are assumed to be verified by the caller.
10111  */
10112 /* ARGSUSED */
10113 int
10114 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10115     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10116     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10117 {
10118 	conn_t	*connp = Q_TO_CONN(q);
10119 	tcp_t	*tcp = connp->conn_tcp;
10120 	int	*i1 = (int *)invalp;
10121 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10122 	boolean_t checkonly;
10123 	int	reterr;
10124 
10125 	switch (optset_context) {
10126 	case SETFN_OPTCOM_CHECKONLY:
10127 		checkonly = B_TRUE;
10128 		/*
10129 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10130 		 * inlen != 0 implies value supplied and
10131 		 * 	we have to "pretend" to set it.
10132 		 * inlen == 0 implies that there is no
10133 		 * 	value part in T_CHECK request and just validation
10134 		 * done elsewhere should be enough, we just return here.
10135 		 */
10136 		if (inlen == 0) {
10137 			*outlenp = 0;
10138 			return (0);
10139 		}
10140 		break;
10141 	case SETFN_OPTCOM_NEGOTIATE:
10142 		checkonly = B_FALSE;
10143 		break;
10144 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10145 	case SETFN_CONN_NEGOTIATE:
10146 		checkonly = B_FALSE;
10147 		/*
10148 		 * Negotiating local and "association-related" options
10149 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10150 		 * primitives is allowed by XTI, but we choose
10151 		 * to not implement this style negotiation for Internet
10152 		 * protocols (We interpret it is a must for OSI world but
10153 		 * optional for Internet protocols) for all options.
10154 		 * [ Will do only for the few options that enable test
10155 		 * suites that our XTI implementation of this feature
10156 		 * works for transports that do allow it ]
10157 		 */
10158 		if (!tcp_allow_connopt_set(level, name)) {
10159 			*outlenp = 0;
10160 			return (EINVAL);
10161 		}
10162 		break;
10163 	default:
10164 		/*
10165 		 * We should never get here
10166 		 */
10167 		*outlenp = 0;
10168 		return (EINVAL);
10169 	}
10170 
10171 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10172 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10173 
10174 	/*
10175 	 * For TCP, we should have no ancillary data sent down
10176 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10177 	 * has to be zero.
10178 	 */
10179 	ASSERT(thisdg_attrs == NULL);
10180 
10181 	/*
10182 	 * For fixed length options, no sanity check
10183 	 * of passed in length is done. It is assumed *_optcom_req()
10184 	 * routines do the right thing.
10185 	 */
10186 
10187 	switch (level) {
10188 	case SOL_SOCKET:
10189 		switch (name) {
10190 		case SO_LINGER: {
10191 			struct linger *lgr = (struct linger *)invalp;
10192 
10193 			if (!checkonly) {
10194 				if (lgr->l_onoff) {
10195 					tcp->tcp_linger = 1;
10196 					tcp->tcp_lingertime = lgr->l_linger;
10197 				} else {
10198 					tcp->tcp_linger = 0;
10199 					tcp->tcp_lingertime = 0;
10200 				}
10201 				/* struct copy */
10202 				*(struct linger *)outvalp = *lgr;
10203 			} else {
10204 				if (!lgr->l_onoff) {
10205 				    ((struct linger *)outvalp)->l_onoff = 0;
10206 				    ((struct linger *)outvalp)->l_linger = 0;
10207 				} else {
10208 				    /* struct copy */
10209 				    *(struct linger *)outvalp = *lgr;
10210 				}
10211 			}
10212 			*outlenp = sizeof (struct linger);
10213 			return (0);
10214 		}
10215 		case SO_DEBUG:
10216 			if (!checkonly)
10217 				tcp->tcp_debug = onoff;
10218 			break;
10219 		case SO_KEEPALIVE:
10220 			if (checkonly) {
10221 				/* T_CHECK case */
10222 				break;
10223 			}
10224 
10225 			if (!onoff) {
10226 				if (tcp->tcp_ka_enabled) {
10227 					if (tcp->tcp_ka_tid != 0) {
10228 						(void) TCP_TIMER_CANCEL(tcp,
10229 						    tcp->tcp_ka_tid);
10230 						tcp->tcp_ka_tid = 0;
10231 					}
10232 					tcp->tcp_ka_enabled = 0;
10233 				}
10234 				break;
10235 			}
10236 			if (!tcp->tcp_ka_enabled) {
10237 				/* Crank up the keepalive timer */
10238 				tcp->tcp_ka_last_intrvl = 0;
10239 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10240 				    tcp_keepalive_killer,
10241 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10242 				tcp->tcp_ka_enabled = 1;
10243 			}
10244 			break;
10245 		case SO_DONTROUTE:
10246 			/*
10247 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10248 			 * only of interest to IP.  We track them here only so
10249 			 * that we can report their current value.
10250 			 */
10251 			if (!checkonly) {
10252 				tcp->tcp_dontroute = onoff;
10253 				tcp->tcp_connp->conn_dontroute = onoff;
10254 			}
10255 			break;
10256 		case SO_USELOOPBACK:
10257 			if (!checkonly) {
10258 				tcp->tcp_useloopback = onoff;
10259 				tcp->tcp_connp->conn_loopback = onoff;
10260 			}
10261 			break;
10262 		case SO_BROADCAST:
10263 			if (!checkonly) {
10264 				tcp->tcp_broadcast = onoff;
10265 				tcp->tcp_connp->conn_broadcast = onoff;
10266 			}
10267 			break;
10268 		case SO_REUSEADDR:
10269 			if (!checkonly) {
10270 				tcp->tcp_reuseaddr = onoff;
10271 				tcp->tcp_connp->conn_reuseaddr = onoff;
10272 			}
10273 			break;
10274 		case SO_OOBINLINE:
10275 			if (!checkonly)
10276 				tcp->tcp_oobinline = onoff;
10277 			break;
10278 		case SO_DGRAM_ERRIND:
10279 			if (!checkonly)
10280 				tcp->tcp_dgram_errind = onoff;
10281 			break;
10282 		case SO_SNDBUF: {
10283 			if (*i1 > tcp_max_buf) {
10284 				*outlenp = 0;
10285 				return (ENOBUFS);
10286 			}
10287 			if (checkonly)
10288 				break;
10289 
10290 			tcp->tcp_xmit_hiwater = *i1;
10291 			if (tcp_snd_lowat_fraction != 0)
10292 				tcp->tcp_xmit_lowater =
10293 				    tcp->tcp_xmit_hiwater /
10294 				    tcp_snd_lowat_fraction;
10295 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10296 			/*
10297 			 * If we are flow-controlled, recheck the condition.
10298 			 * There are apps that increase SO_SNDBUF size when
10299 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10300 			 * control condition to be lifted right away.
10301 			 */
10302 			mutex_enter(&tcp->tcp_non_sq_lock);
10303 			if (tcp->tcp_flow_stopped &&
10304 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10305 				tcp_clrqfull(tcp);
10306 			}
10307 			mutex_exit(&tcp->tcp_non_sq_lock);
10308 			break;
10309 		}
10310 		case SO_RCVBUF:
10311 			if (*i1 > tcp_max_buf) {
10312 				*outlenp = 0;
10313 				return (ENOBUFS);
10314 			}
10315 			/* Silently ignore zero */
10316 			if (!checkonly && *i1 != 0) {
10317 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10318 				(void) tcp_rwnd_set(tcp, *i1);
10319 			}
10320 			/*
10321 			 * XXX should we return the rwnd here
10322 			 * and tcp_opt_get ?
10323 			 */
10324 			break;
10325 		case SO_SND_COPYAVOID:
10326 			if (!checkonly) {
10327 				/* we only allow enable at most once for now */
10328 				if (tcp->tcp_loopback ||
10329 				    (!tcp->tcp_snd_zcopy_aware &&
10330 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10331 					*outlenp = 0;
10332 					return (EOPNOTSUPP);
10333 				}
10334 				tcp->tcp_snd_zcopy_aware = 1;
10335 			}
10336 			break;
10337 		case SO_ALLZONES:
10338 			/* Handled at the IP level */
10339 			return (-EINVAL);
10340 		case SO_ANON_MLP:
10341 			if (!checkonly) {
10342 				mutex_enter(&connp->conn_lock);
10343 				connp->conn_anon_mlp = onoff;
10344 				mutex_exit(&connp->conn_lock);
10345 			}
10346 			break;
10347 		case SO_MAC_EXEMPT:
10348 			if (secpolicy_net_mac_aware(cr) != 0 ||
10349 			    IPCL_IS_BOUND(connp))
10350 				return (EACCES);
10351 			if (!checkonly) {
10352 				mutex_enter(&connp->conn_lock);
10353 				connp->conn_mac_exempt = onoff;
10354 				mutex_exit(&connp->conn_lock);
10355 			}
10356 			break;
10357 		case SO_EXCLBIND:
10358 			if (!checkonly)
10359 				tcp->tcp_exclbind = onoff;
10360 			break;
10361 		default:
10362 			*outlenp = 0;
10363 			return (EINVAL);
10364 		}
10365 		break;
10366 	case IPPROTO_TCP:
10367 		switch (name) {
10368 		case TCP_NODELAY:
10369 			if (!checkonly)
10370 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10371 			break;
10372 		case TCP_NOTIFY_THRESHOLD:
10373 			if (!checkonly)
10374 				tcp->tcp_first_timer_threshold = *i1;
10375 			break;
10376 		case TCP_ABORT_THRESHOLD:
10377 			if (!checkonly)
10378 				tcp->tcp_second_timer_threshold = *i1;
10379 			break;
10380 		case TCP_CONN_NOTIFY_THRESHOLD:
10381 			if (!checkonly)
10382 				tcp->tcp_first_ctimer_threshold = *i1;
10383 			break;
10384 		case TCP_CONN_ABORT_THRESHOLD:
10385 			if (!checkonly)
10386 				tcp->tcp_second_ctimer_threshold = *i1;
10387 			break;
10388 		case TCP_RECVDSTADDR:
10389 			if (tcp->tcp_state > TCPS_LISTEN)
10390 				return (EOPNOTSUPP);
10391 			if (!checkonly)
10392 				tcp->tcp_recvdstaddr = onoff;
10393 			break;
10394 		case TCP_ANONPRIVBIND:
10395 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
10396 				*outlenp = 0;
10397 				return (reterr);
10398 			}
10399 			if (!checkonly) {
10400 				tcp->tcp_anon_priv_bind = onoff;
10401 			}
10402 			break;
10403 		case TCP_EXCLBIND:
10404 			if (!checkonly)
10405 				tcp->tcp_exclbind = onoff;
10406 			break;	/* goto sizeof (int) option return */
10407 		case TCP_INIT_CWND: {
10408 			uint32_t init_cwnd = *((uint32_t *)invalp);
10409 
10410 			if (checkonly)
10411 				break;
10412 
10413 			/*
10414 			 * Only allow socket with network configuration
10415 			 * privilege to set the initial cwnd to be larger
10416 			 * than allowed by RFC 3390.
10417 			 */
10418 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10419 				tcp->tcp_init_cwnd = init_cwnd;
10420 				break;
10421 			}
10422 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
10423 				*outlenp = 0;
10424 				return (reterr);
10425 			}
10426 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10427 				*outlenp = 0;
10428 				return (EINVAL);
10429 			}
10430 			tcp->tcp_init_cwnd = init_cwnd;
10431 			break;
10432 		}
10433 		case TCP_KEEPALIVE_THRESHOLD:
10434 			if (checkonly)
10435 				break;
10436 
10437 			if (*i1 < tcp_keepalive_interval_low ||
10438 			    *i1 > tcp_keepalive_interval_high) {
10439 				*outlenp = 0;
10440 				return (EINVAL);
10441 			}
10442 			if (*i1 != tcp->tcp_ka_interval) {
10443 				tcp->tcp_ka_interval = *i1;
10444 				/*
10445 				 * Check if we need to restart the
10446 				 * keepalive timer.
10447 				 */
10448 				if (tcp->tcp_ka_tid != 0) {
10449 					ASSERT(tcp->tcp_ka_enabled);
10450 					(void) TCP_TIMER_CANCEL(tcp,
10451 					    tcp->tcp_ka_tid);
10452 					tcp->tcp_ka_last_intrvl = 0;
10453 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10454 					    tcp_keepalive_killer,
10455 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10456 				}
10457 			}
10458 			break;
10459 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10460 			if (!checkonly) {
10461 				if (*i1 < tcp_keepalive_abort_interval_low ||
10462 				    *i1 > tcp_keepalive_abort_interval_high) {
10463 					*outlenp = 0;
10464 					return (EINVAL);
10465 				}
10466 				tcp->tcp_ka_abort_thres = *i1;
10467 			}
10468 			break;
10469 		case TCP_CORK:
10470 			if (!checkonly) {
10471 				/*
10472 				 * if tcp->tcp_cork was set and is now
10473 				 * being unset, we have to make sure that
10474 				 * the remaining data gets sent out. Also
10475 				 * unset tcp->tcp_cork so that tcp_wput_data()
10476 				 * can send data even if it is less than mss
10477 				 */
10478 				if (tcp->tcp_cork && onoff == 0 &&
10479 				    tcp->tcp_unsent > 0) {
10480 					tcp->tcp_cork = B_FALSE;
10481 					tcp_wput_data(tcp, NULL, B_FALSE);
10482 				}
10483 				tcp->tcp_cork = onoff;
10484 			}
10485 			break;
10486 		default:
10487 			*outlenp = 0;
10488 			return (EINVAL);
10489 		}
10490 		break;
10491 	case IPPROTO_IP:
10492 		if (tcp->tcp_family != AF_INET) {
10493 			*outlenp = 0;
10494 			return (ENOPROTOOPT);
10495 		}
10496 		switch (name) {
10497 		case IP_OPTIONS:
10498 		case T_IP_OPTIONS:
10499 			reterr = tcp_opt_set_header(tcp, checkonly,
10500 			    invalp, inlen);
10501 			if (reterr) {
10502 				*outlenp = 0;
10503 				return (reterr);
10504 			}
10505 			/* OK return - copy input buffer into output buffer */
10506 			if (invalp != outvalp) {
10507 				/* don't trust bcopy for identical src/dst */
10508 				bcopy(invalp, outvalp, inlen);
10509 			}
10510 			*outlenp = inlen;
10511 			return (0);
10512 		case IP_TOS:
10513 		case T_IP_TOS:
10514 			if (!checkonly) {
10515 				tcp->tcp_ipha->ipha_type_of_service =
10516 				    (uchar_t)*i1;
10517 				tcp->tcp_tos = (uchar_t)*i1;
10518 			}
10519 			break;
10520 		case IP_TTL:
10521 			if (!checkonly) {
10522 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10523 				tcp->tcp_ttl = (uchar_t)*i1;
10524 			}
10525 			break;
10526 		case IP_BOUND_IF:
10527 		case IP_NEXTHOP:
10528 			/* Handled at the IP level */
10529 			return (-EINVAL);
10530 		case IP_SEC_OPT:
10531 			/*
10532 			 * We should not allow policy setting after
10533 			 * we start listening for connections.
10534 			 */
10535 			if (tcp->tcp_state == TCPS_LISTEN) {
10536 				return (EINVAL);
10537 			} else {
10538 				/* Handled at the IP level */
10539 				return (-EINVAL);
10540 			}
10541 		default:
10542 			*outlenp = 0;
10543 			return (EINVAL);
10544 		}
10545 		break;
10546 	case IPPROTO_IPV6: {
10547 		ip6_pkt_t		*ipp;
10548 
10549 		/*
10550 		 * IPPROTO_IPV6 options are only supported for sockets
10551 		 * that are using IPv6 on the wire.
10552 		 */
10553 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10554 			*outlenp = 0;
10555 			return (ENOPROTOOPT);
10556 		}
10557 		/*
10558 		 * Only sticky options; no ancillary data
10559 		 */
10560 		ASSERT(thisdg_attrs == NULL);
10561 		ipp = &tcp->tcp_sticky_ipp;
10562 
10563 		switch (name) {
10564 		case IPV6_UNICAST_HOPS:
10565 			/* -1 means use default */
10566 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10567 				*outlenp = 0;
10568 				return (EINVAL);
10569 			}
10570 			if (!checkonly) {
10571 				if (*i1 == -1) {
10572 					tcp->tcp_ip6h->ip6_hops =
10573 					    ipp->ipp_unicast_hops =
10574 					    (uint8_t)tcp_ipv6_hoplimit;
10575 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10576 					/* Pass modified value to IP. */
10577 					*i1 = tcp->tcp_ip6h->ip6_hops;
10578 				} else {
10579 					tcp->tcp_ip6h->ip6_hops =
10580 					    ipp->ipp_unicast_hops =
10581 					    (uint8_t)*i1;
10582 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10583 				}
10584 				reterr = tcp_build_hdrs(q, tcp);
10585 				if (reterr != 0)
10586 					return (reterr);
10587 			}
10588 			break;
10589 		case IPV6_BOUND_IF:
10590 			if (!checkonly) {
10591 				int error = 0;
10592 
10593 				tcp->tcp_bound_if = *i1;
10594 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10595 				    B_TRUE, checkonly, level, name, mblk);
10596 				if (error != 0) {
10597 					*outlenp = 0;
10598 					return (error);
10599 				}
10600 			}
10601 			break;
10602 		/*
10603 		 * Set boolean switches for ancillary data delivery
10604 		 */
10605 		case IPV6_RECVPKTINFO:
10606 			if (!checkonly) {
10607 				if (onoff)
10608 					tcp->tcp_ipv6_recvancillary |=
10609 					    TCP_IPV6_RECVPKTINFO;
10610 				else
10611 					tcp->tcp_ipv6_recvancillary &=
10612 					    ~TCP_IPV6_RECVPKTINFO;
10613 				/* Force it to be sent up with the next msg */
10614 				tcp->tcp_recvifindex = 0;
10615 			}
10616 			break;
10617 		case IPV6_RECVTCLASS:
10618 			if (!checkonly) {
10619 				if (onoff)
10620 					tcp->tcp_ipv6_recvancillary |=
10621 					    TCP_IPV6_RECVTCLASS;
10622 				else
10623 					tcp->tcp_ipv6_recvancillary &=
10624 					    ~TCP_IPV6_RECVTCLASS;
10625 			}
10626 			break;
10627 		case IPV6_RECVHOPLIMIT:
10628 			if (!checkonly) {
10629 				if (onoff)
10630 					tcp->tcp_ipv6_recvancillary |=
10631 					    TCP_IPV6_RECVHOPLIMIT;
10632 				else
10633 					tcp->tcp_ipv6_recvancillary &=
10634 					    ~TCP_IPV6_RECVHOPLIMIT;
10635 				/* Force it to be sent up with the next msg */
10636 				tcp->tcp_recvhops = 0xffffffffU;
10637 			}
10638 			break;
10639 		case IPV6_RECVHOPOPTS:
10640 			if (!checkonly) {
10641 				if (onoff)
10642 					tcp->tcp_ipv6_recvancillary |=
10643 					    TCP_IPV6_RECVHOPOPTS;
10644 				else
10645 					tcp->tcp_ipv6_recvancillary &=
10646 					    ~TCP_IPV6_RECVHOPOPTS;
10647 			}
10648 			break;
10649 		case IPV6_RECVDSTOPTS:
10650 			if (!checkonly) {
10651 				if (onoff)
10652 					tcp->tcp_ipv6_recvancillary |=
10653 					    TCP_IPV6_RECVDSTOPTS;
10654 				else
10655 					tcp->tcp_ipv6_recvancillary &=
10656 					    ~TCP_IPV6_RECVDSTOPTS;
10657 			}
10658 			break;
10659 		case _OLD_IPV6_RECVDSTOPTS:
10660 			if (!checkonly) {
10661 				if (onoff)
10662 					tcp->tcp_ipv6_recvancillary |=
10663 					    TCP_OLD_IPV6_RECVDSTOPTS;
10664 				else
10665 					tcp->tcp_ipv6_recvancillary &=
10666 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10667 			}
10668 			break;
10669 		case IPV6_RECVRTHDR:
10670 			if (!checkonly) {
10671 				if (onoff)
10672 					tcp->tcp_ipv6_recvancillary |=
10673 					    TCP_IPV6_RECVRTHDR;
10674 				else
10675 					tcp->tcp_ipv6_recvancillary &=
10676 					    ~TCP_IPV6_RECVRTHDR;
10677 			}
10678 			break;
10679 		case IPV6_RECVRTHDRDSTOPTS:
10680 			if (!checkonly) {
10681 				if (onoff)
10682 					tcp->tcp_ipv6_recvancillary |=
10683 					    TCP_IPV6_RECVRTDSTOPTS;
10684 				else
10685 					tcp->tcp_ipv6_recvancillary &=
10686 					    ~TCP_IPV6_RECVRTDSTOPTS;
10687 			}
10688 			break;
10689 		case IPV6_PKTINFO:
10690 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10691 				return (EINVAL);
10692 			if (checkonly)
10693 				break;
10694 
10695 			if (inlen == 0) {
10696 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10697 			} else {
10698 				struct in6_pktinfo *pkti;
10699 
10700 				pkti = (struct in6_pktinfo *)invalp;
10701 				/*
10702 				 * RFC 3542 states that ipi6_addr must be
10703 				 * the unspecified address when setting the
10704 				 * IPV6_PKTINFO sticky socket option on a
10705 				 * TCP socket.
10706 				 */
10707 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10708 					return (EINVAL);
10709 				/*
10710 				 * ip6_set_pktinfo() validates the source
10711 				 * address and interface index.
10712 				 */
10713 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10714 				    pkti, mblk);
10715 				if (reterr != 0)
10716 					return (reterr);
10717 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10718 				ipp->ipp_addr = pkti->ipi6_addr;
10719 				if (ipp->ipp_ifindex != 0)
10720 					ipp->ipp_fields |= IPPF_IFINDEX;
10721 				else
10722 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10723 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10724 					ipp->ipp_fields |= IPPF_ADDR;
10725 				else
10726 					ipp->ipp_fields &= ~IPPF_ADDR;
10727 			}
10728 			reterr = tcp_build_hdrs(q, tcp);
10729 			if (reterr != 0)
10730 				return (reterr);
10731 			break;
10732 		case IPV6_TCLASS:
10733 			if (inlen != 0 && inlen != sizeof (int))
10734 				return (EINVAL);
10735 			if (checkonly)
10736 				break;
10737 
10738 			if (inlen == 0) {
10739 				ipp->ipp_fields &= ~IPPF_TCLASS;
10740 			} else {
10741 				if (*i1 > 255 || *i1 < -1)
10742 					return (EINVAL);
10743 				if (*i1 == -1) {
10744 					ipp->ipp_tclass = 0;
10745 					*i1 = 0;
10746 				} else {
10747 					ipp->ipp_tclass = *i1;
10748 				}
10749 				ipp->ipp_fields |= IPPF_TCLASS;
10750 			}
10751 			reterr = tcp_build_hdrs(q, tcp);
10752 			if (reterr != 0)
10753 				return (reterr);
10754 			break;
10755 		case IPV6_NEXTHOP:
10756 			/*
10757 			 * IP will verify that the nexthop is reachable
10758 			 * and fail for sticky options.
10759 			 */
10760 			if (inlen != 0 && inlen != sizeof (sin6_t))
10761 				return (EINVAL);
10762 			if (checkonly)
10763 				break;
10764 
10765 			if (inlen == 0) {
10766 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10767 			} else {
10768 				sin6_t *sin6 = (sin6_t *)invalp;
10769 
10770 				if (sin6->sin6_family != AF_INET6)
10771 					return (EAFNOSUPPORT);
10772 				if (IN6_IS_ADDR_V4MAPPED(
10773 				    &sin6->sin6_addr))
10774 					return (EADDRNOTAVAIL);
10775 				ipp->ipp_nexthop = sin6->sin6_addr;
10776 				if (!IN6_IS_ADDR_UNSPECIFIED(
10777 				    &ipp->ipp_nexthop))
10778 					ipp->ipp_fields |= IPPF_NEXTHOP;
10779 				else
10780 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10781 			}
10782 			reterr = tcp_build_hdrs(q, tcp);
10783 			if (reterr != 0)
10784 				return (reterr);
10785 			break;
10786 		case IPV6_HOPOPTS: {
10787 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10788 
10789 			/*
10790 			 * Sanity checks - minimum size, size a multiple of
10791 			 * eight bytes, and matching size passed in.
10792 			 */
10793 			if (inlen != 0 &&
10794 			    inlen != (8 * (hopts->ip6h_len + 1)))
10795 				return (EINVAL);
10796 
10797 			if (checkonly)
10798 				break;
10799 
10800 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10801 			    (uchar_t **)&ipp->ipp_hopopts,
10802 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10803 			if (reterr != 0)
10804 				return (reterr);
10805 			if (ipp->ipp_hopoptslen == 0)
10806 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10807 			else
10808 				ipp->ipp_fields |= IPPF_HOPOPTS;
10809 			reterr = tcp_build_hdrs(q, tcp);
10810 			if (reterr != 0)
10811 				return (reterr);
10812 			break;
10813 		}
10814 		case IPV6_RTHDRDSTOPTS: {
10815 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10816 
10817 			/*
10818 			 * Sanity checks - minimum size, size a multiple of
10819 			 * eight bytes, and matching size passed in.
10820 			 */
10821 			if (inlen != 0 &&
10822 			    inlen != (8 * (dopts->ip6d_len + 1)))
10823 				return (EINVAL);
10824 
10825 			if (checkonly)
10826 				break;
10827 
10828 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10829 			    (uchar_t **)&ipp->ipp_rtdstopts,
10830 			    &ipp->ipp_rtdstoptslen, 0);
10831 			if (reterr != 0)
10832 				return (reterr);
10833 			if (ipp->ipp_rtdstoptslen == 0)
10834 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10835 			else
10836 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10837 			reterr = tcp_build_hdrs(q, tcp);
10838 			if (reterr != 0)
10839 				return (reterr);
10840 			break;
10841 		}
10842 		case IPV6_DSTOPTS: {
10843 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10844 
10845 			/*
10846 			 * Sanity checks - minimum size, size a multiple of
10847 			 * eight bytes, and matching size passed in.
10848 			 */
10849 			if (inlen != 0 &&
10850 			    inlen != (8 * (dopts->ip6d_len + 1)))
10851 				return (EINVAL);
10852 
10853 			if (checkonly)
10854 				break;
10855 
10856 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10857 			    (uchar_t **)&ipp->ipp_dstopts,
10858 			    &ipp->ipp_dstoptslen, 0);
10859 			if (reterr != 0)
10860 				return (reterr);
10861 			if (ipp->ipp_dstoptslen == 0)
10862 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10863 			else
10864 				ipp->ipp_fields |= IPPF_DSTOPTS;
10865 			reterr = tcp_build_hdrs(q, tcp);
10866 			if (reterr != 0)
10867 				return (reterr);
10868 			break;
10869 		}
10870 		case IPV6_RTHDR: {
10871 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10872 
10873 			/*
10874 			 * Sanity checks - minimum size, size a multiple of
10875 			 * eight bytes, and matching size passed in.
10876 			 */
10877 			if (inlen != 0 &&
10878 			    inlen != (8 * (rt->ip6r_len + 1)))
10879 				return (EINVAL);
10880 
10881 			if (checkonly)
10882 				break;
10883 
10884 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10885 			    (uchar_t **)&ipp->ipp_rthdr,
10886 			    &ipp->ipp_rthdrlen, 0);
10887 			if (reterr != 0)
10888 				return (reterr);
10889 			if (ipp->ipp_rthdrlen == 0)
10890 				ipp->ipp_fields &= ~IPPF_RTHDR;
10891 			else
10892 				ipp->ipp_fields |= IPPF_RTHDR;
10893 			reterr = tcp_build_hdrs(q, tcp);
10894 			if (reterr != 0)
10895 				return (reterr);
10896 			break;
10897 		}
10898 		case IPV6_V6ONLY:
10899 			if (!checkonly)
10900 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10901 			break;
10902 		case IPV6_USE_MIN_MTU:
10903 			if (inlen != sizeof (int))
10904 				return (EINVAL);
10905 
10906 			if (*i1 < -1 || *i1 > 1)
10907 				return (EINVAL);
10908 
10909 			if (checkonly)
10910 				break;
10911 
10912 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10913 			ipp->ipp_use_min_mtu = *i1;
10914 			break;
10915 		case IPV6_BOUND_PIF:
10916 			/* Handled at the IP level */
10917 			return (-EINVAL);
10918 		case IPV6_SEC_OPT:
10919 			/*
10920 			 * We should not allow policy setting after
10921 			 * we start listening for connections.
10922 			 */
10923 			if (tcp->tcp_state == TCPS_LISTEN) {
10924 				return (EINVAL);
10925 			} else {
10926 				/* Handled at the IP level */
10927 				return (-EINVAL);
10928 			}
10929 		case IPV6_SRC_PREFERENCES:
10930 			if (inlen != sizeof (uint32_t))
10931 				return (EINVAL);
10932 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10933 			    *(uint32_t *)invalp);
10934 			if (reterr != 0) {
10935 				*outlenp = 0;
10936 				return (reterr);
10937 			}
10938 			break;
10939 		default:
10940 			*outlenp = 0;
10941 			return (EINVAL);
10942 		}
10943 		break;
10944 	}		/* end IPPROTO_IPV6 */
10945 	default:
10946 		*outlenp = 0;
10947 		return (EINVAL);
10948 	}
10949 	/*
10950 	 * Common case of OK return with outval same as inval
10951 	 */
10952 	if (invalp != outvalp) {
10953 		/* don't trust bcopy for identical src/dst */
10954 		(void) bcopy(invalp, outvalp, inlen);
10955 	}
10956 	*outlenp = inlen;
10957 	return (0);
10958 }
10959 
10960 /*
10961  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10962  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10963  * headers, and the maximum size tcp header (to avoid reallocation
10964  * on the fly for additional tcp options).
10965  * Returns failure if can't allocate memory.
10966  */
10967 static int
10968 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
10969 {
10970 	char	*hdrs;
10971 	uint_t	hdrs_len;
10972 	ip6i_t	*ip6i;
10973 	char	buf[TCP_MAX_HDR_LENGTH];
10974 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10975 	in6_addr_t src, dst;
10976 
10977 	/*
10978 	 * save the existing tcp header and source/dest IP addresses
10979 	 */
10980 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10981 	src = tcp->tcp_ip6h->ip6_src;
10982 	dst = tcp->tcp_ip6h->ip6_dst;
10983 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10984 	ASSERT(hdrs_len != 0);
10985 	if (hdrs_len > tcp->tcp_iphc_len) {
10986 		/* Need to reallocate */
10987 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10988 		if (hdrs == NULL)
10989 			return (ENOMEM);
10990 		if (tcp->tcp_iphc != NULL) {
10991 			if (tcp->tcp_hdr_grown) {
10992 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10993 			} else {
10994 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10995 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10996 			}
10997 			tcp->tcp_iphc_len = 0;
10998 		}
10999 		ASSERT(tcp->tcp_iphc_len == 0);
11000 		tcp->tcp_iphc = hdrs;
11001 		tcp->tcp_iphc_len = hdrs_len;
11002 		tcp->tcp_hdr_grown = B_TRUE;
11003 	}
11004 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11005 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11006 
11007 	/* Set header fields not in ipp */
11008 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11009 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11010 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11011 	} else {
11012 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11013 	}
11014 	/*
11015 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11016 	 *
11017 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11018 	 */
11019 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11020 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11021 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11022 
11023 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11024 
11025 	tcp->tcp_ip6h->ip6_src = src;
11026 	tcp->tcp_ip6h->ip6_dst = dst;
11027 
11028 	/*
11029 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11030 	 * the default value for TCP.
11031 	 */
11032 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11033 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
11034 
11035 	/*
11036 	 * If we're setting extension headers after a connection
11037 	 * has been established, and if we have a routing header
11038 	 * among the extension headers, call ip_massage_options_v6 to
11039 	 * manipulate the routing header/ip6_dst set the checksum
11040 	 * difference in the tcp header template.
11041 	 * (This happens in tcp_connect_ipv6 if the routing header
11042 	 * is set prior to the connect.)
11043 	 * Set the tcp_sum to zero first in case we've cleared a
11044 	 * routing header or don't have one at all.
11045 	 */
11046 	tcp->tcp_sum = 0;
11047 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11048 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11049 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11050 		    (uint8_t *)tcp->tcp_tcph);
11051 		if (rth != NULL) {
11052 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11053 			    rth);
11054 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11055 			    (tcp->tcp_sum >> 16));
11056 		}
11057 	}
11058 
11059 	/* Try to get everything in a single mblk */
11060 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
11061 	return (0);
11062 }
11063 
11064 /*
11065  * Transfer any source route option from ipha to buf/dst in reversed form.
11066  */
11067 static int
11068 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11069 {
11070 	ipoptp_t	opts;
11071 	uchar_t		*opt;
11072 	uint8_t		optval;
11073 	uint8_t		optlen;
11074 	uint32_t	len = 0;
11075 
11076 	for (optval = ipoptp_first(&opts, ipha);
11077 	    optval != IPOPT_EOL;
11078 	    optval = ipoptp_next(&opts)) {
11079 		opt = opts.ipoptp_cur;
11080 		optlen = opts.ipoptp_len;
11081 		switch (optval) {
11082 			int	off1, off2;
11083 		case IPOPT_SSRR:
11084 		case IPOPT_LSRR:
11085 
11086 			/* Reverse source route */
11087 			/*
11088 			 * First entry should be the next to last one in the
11089 			 * current source route (the last entry is our
11090 			 * address.)
11091 			 * The last entry should be the final destination.
11092 			 */
11093 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11094 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11095 			off1 = IPOPT_MINOFF_SR - 1;
11096 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11097 			if (off2 < 0) {
11098 				/* No entries in source route */
11099 				break;
11100 			}
11101 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11102 			/*
11103 			 * Note: use src since ipha has not had its src
11104 			 * and dst reversed (it is in the state it was
11105 			 * received.
11106 			 */
11107 			bcopy(&ipha->ipha_src, buf + off2,
11108 			    IP_ADDR_LEN);
11109 			off2 -= IP_ADDR_LEN;
11110 
11111 			while (off2 > 0) {
11112 				bcopy(opt + off2, buf + off1,
11113 				    IP_ADDR_LEN);
11114 				off1 += IP_ADDR_LEN;
11115 				off2 -= IP_ADDR_LEN;
11116 			}
11117 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11118 			buf += optlen;
11119 			len += optlen;
11120 			break;
11121 		}
11122 	}
11123 done:
11124 	/* Pad the resulting options */
11125 	while (len & 0x3) {
11126 		*buf++ = IPOPT_EOL;
11127 		len++;
11128 	}
11129 	return (len);
11130 }
11131 
11132 
11133 /*
11134  * Extract and revert a source route from ipha (if any)
11135  * and then update the relevant fields in both tcp_t and the standard header.
11136  */
11137 static void
11138 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11139 {
11140 	char	buf[TCP_MAX_HDR_LENGTH];
11141 	uint_t	tcph_len;
11142 	int	len;
11143 
11144 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11145 	len = IPH_HDR_LENGTH(ipha);
11146 	if (len == IP_SIMPLE_HDR_LENGTH)
11147 		/* Nothing to do */
11148 		return;
11149 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11150 	    (len & 0x3))
11151 		return;
11152 
11153 	tcph_len = tcp->tcp_tcp_hdr_len;
11154 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11155 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11156 		(tcp->tcp_ipha->ipha_dst & 0xffff);
11157 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11158 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11159 	len += IP_SIMPLE_HDR_LENGTH;
11160 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11161 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11162 	if ((int)tcp->tcp_sum < 0)
11163 		tcp->tcp_sum--;
11164 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11165 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11166 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11167 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11168 	tcp->tcp_ip_hdr_len = len;
11169 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11170 	    (IP_VERSION << 4) | (len >> 2);
11171 	len += tcph_len;
11172 	tcp->tcp_hdr_len = len;
11173 }
11174 
11175 /*
11176  * Copy the standard header into its new location,
11177  * lay in the new options and then update the relevant
11178  * fields in both tcp_t and the standard header.
11179  */
11180 static int
11181 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11182 {
11183 	uint_t	tcph_len;
11184 	uint8_t	*ip_optp;
11185 	tcph_t	*new_tcph;
11186 
11187 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11188 		return (EINVAL);
11189 
11190 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11191 		return (EINVAL);
11192 
11193 	if (checkonly) {
11194 		/*
11195 		 * do not really set, just pretend to - T_CHECK
11196 		 */
11197 		return (0);
11198 	}
11199 
11200 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11201 	if (tcp->tcp_label_len > 0) {
11202 		int padlen;
11203 		uint8_t opt;
11204 
11205 		/* convert list termination to no-ops */
11206 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11207 		ip_optp += ip_optp[IPOPT_OLEN];
11208 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11209 		while (--padlen >= 0)
11210 			*ip_optp++ = opt;
11211 	}
11212 	tcph_len = tcp->tcp_tcp_hdr_len;
11213 	new_tcph = (tcph_t *)(ip_optp + len);
11214 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11215 	tcp->tcp_tcph = new_tcph;
11216 	bcopy(ptr, ip_optp, len);
11217 
11218 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11219 
11220 	tcp->tcp_ip_hdr_len = len;
11221 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11222 	    (IP_VERSION << 4) | (len >> 2);
11223 	tcp->tcp_hdr_len = len + tcph_len;
11224 	if (!TCP_IS_DETACHED(tcp)) {
11225 		/* Always allocate room for all options. */
11226 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11227 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
11228 	}
11229 	return (0);
11230 }
11231 
11232 /* Get callback routine passed to nd_load by tcp_param_register */
11233 /* ARGSUSED */
11234 static int
11235 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11236 {
11237 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11238 
11239 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11240 	return (0);
11241 }
11242 
11243 /*
11244  * Walk through the param array specified registering each element with the
11245  * named dispatch handler.
11246  */
11247 static boolean_t
11248 tcp_param_register(tcpparam_t *tcppa, int cnt)
11249 {
11250 	for (; cnt-- > 0; tcppa++) {
11251 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11252 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
11253 			    tcp_param_get, tcp_param_set,
11254 			    (caddr_t)tcppa)) {
11255 				nd_free(&tcp_g_nd);
11256 				return (B_FALSE);
11257 			}
11258 		}
11259 	}
11260 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
11261 	    tcp_param_get, tcp_param_set_aligned,
11262 	    (caddr_t)&tcp_wroff_xtra_param)) {
11263 		nd_free(&tcp_g_nd);
11264 		return (B_FALSE);
11265 	}
11266 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
11267 	    tcp_param_get, tcp_param_set_aligned,
11268 	    (caddr_t)&tcp_mdt_head_param)) {
11269 		nd_free(&tcp_g_nd);
11270 		return (B_FALSE);
11271 	}
11272 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
11273 	    tcp_param_get, tcp_param_set_aligned,
11274 	    (caddr_t)&tcp_mdt_tail_param)) {
11275 		nd_free(&tcp_g_nd);
11276 		return (B_FALSE);
11277 	}
11278 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
11279 	    tcp_param_get, tcp_param_set,
11280 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
11281 		nd_free(&tcp_g_nd);
11282 		return (B_FALSE);
11283 	}
11284 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
11285 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11286 		nd_free(&tcp_g_nd);
11287 		return (B_FALSE);
11288 	}
11289 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
11290 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11291 		nd_free(&tcp_g_nd);
11292 		return (B_FALSE);
11293 	}
11294 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
11295 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11296 		nd_free(&tcp_g_nd);
11297 		return (B_FALSE);
11298 	}
11299 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
11300 	    NULL)) {
11301 		nd_free(&tcp_g_nd);
11302 		return (B_FALSE);
11303 	}
11304 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
11305 	    NULL, NULL)) {
11306 		nd_free(&tcp_g_nd);
11307 		return (B_FALSE);
11308 	}
11309 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
11310 	    NULL, NULL)) {
11311 		nd_free(&tcp_g_nd);
11312 		return (B_FALSE);
11313 	}
11314 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
11315 	    NULL, NULL)) {
11316 		nd_free(&tcp_g_nd);
11317 		return (B_FALSE);
11318 	}
11319 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
11320 	    NULL, NULL)) {
11321 		nd_free(&tcp_g_nd);
11322 		return (B_FALSE);
11323 	}
11324 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
11325 	    tcp_host_param_set, NULL)) {
11326 		nd_free(&tcp_g_nd);
11327 		return (B_FALSE);
11328 	}
11329 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
11330 	    tcp_host_param_set_ipv6, NULL)) {
11331 		nd_free(&tcp_g_nd);
11332 		return (B_FALSE);
11333 	}
11334 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
11335 	    NULL)) {
11336 		nd_free(&tcp_g_nd);
11337 		return (B_FALSE);
11338 	}
11339 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
11340 	    tcp_reserved_port_list, NULL, NULL)) {
11341 		nd_free(&tcp_g_nd);
11342 		return (B_FALSE);
11343 	}
11344 	/*
11345 	 * Dummy ndd variables - only to convey obsolescence information
11346 	 * through printing of their name (no get or set routines)
11347 	 * XXX Remove in future releases ?
11348 	 */
11349 	if (!nd_load(&tcp_g_nd,
11350 	    "tcp_close_wait_interval(obsoleted - "
11351 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11352 		nd_free(&tcp_g_nd);
11353 		return (B_FALSE);
11354 	}
11355 	return (B_TRUE);
11356 }
11357 
11358 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11359 /* ARGSUSED */
11360 static int
11361 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11362     cred_t *cr)
11363 {
11364 	long new_value;
11365 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11366 
11367 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11368 	    new_value < tcppa->tcp_param_min ||
11369 	    new_value > tcppa->tcp_param_max) {
11370 		return (EINVAL);
11371 	}
11372 	/*
11373 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11374 	 * round it up.  For future 64 bit requirement, we actually make it
11375 	 * a multiple of 8.
11376 	 */
11377 	if (new_value & 0x7) {
11378 		new_value = (new_value & ~0x7) + 0x8;
11379 	}
11380 	tcppa->tcp_param_val = new_value;
11381 	return (0);
11382 }
11383 
11384 /* Set callback routine passed to nd_load by tcp_param_register */
11385 /* ARGSUSED */
11386 static int
11387 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11388 {
11389 	long	new_value;
11390 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11391 
11392 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11393 	    new_value < tcppa->tcp_param_min ||
11394 	    new_value > tcppa->tcp_param_max) {
11395 		return (EINVAL);
11396 	}
11397 	tcppa->tcp_param_val = new_value;
11398 	return (0);
11399 }
11400 
11401 /*
11402  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11403  * is filled, return as much as we can.  The message passed in may be
11404  * multi-part, chained using b_cont.  "start" is the starting sequence
11405  * number for this piece.
11406  */
11407 static mblk_t *
11408 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11409 {
11410 	uint32_t	end;
11411 	mblk_t		*mp1;
11412 	mblk_t		*mp2;
11413 	mblk_t		*next_mp;
11414 	uint32_t	u1;
11415 
11416 	/* Walk through all the new pieces. */
11417 	do {
11418 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11419 		    (uintptr_t)INT_MAX);
11420 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11421 		next_mp = mp->b_cont;
11422 		if (start == end) {
11423 			/* Empty.  Blast it. */
11424 			freeb(mp);
11425 			continue;
11426 		}
11427 		mp->b_cont = NULL;
11428 		TCP_REASS_SET_SEQ(mp, start);
11429 		TCP_REASS_SET_END(mp, end);
11430 		mp1 = tcp->tcp_reass_tail;
11431 		if (!mp1) {
11432 			tcp->tcp_reass_tail = mp;
11433 			tcp->tcp_reass_head = mp;
11434 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11435 			UPDATE_MIB(&tcp_mib,
11436 			    tcpInDataUnorderBytes, end - start);
11437 			continue;
11438 		}
11439 		/* New stuff completely beyond tail? */
11440 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11441 			/* Link it on end. */
11442 			mp1->b_cont = mp;
11443 			tcp->tcp_reass_tail = mp;
11444 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11445 			UPDATE_MIB(&tcp_mib,
11446 			    tcpInDataUnorderBytes, end - start);
11447 			continue;
11448 		}
11449 		mp1 = tcp->tcp_reass_head;
11450 		u1 = TCP_REASS_SEQ(mp1);
11451 		/* New stuff at the front? */
11452 		if (SEQ_LT(start, u1)) {
11453 			/* Yes... Check for overlap. */
11454 			mp->b_cont = mp1;
11455 			tcp->tcp_reass_head = mp;
11456 			tcp_reass_elim_overlap(tcp, mp);
11457 			continue;
11458 		}
11459 		/*
11460 		 * The new piece fits somewhere between the head and tail.
11461 		 * We find our slot, where mp1 precedes us and mp2 trails.
11462 		 */
11463 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11464 			u1 = TCP_REASS_SEQ(mp2);
11465 			if (SEQ_LEQ(start, u1))
11466 				break;
11467 		}
11468 		/* Link ourselves in */
11469 		mp->b_cont = mp2;
11470 		mp1->b_cont = mp;
11471 
11472 		/* Trim overlap with following mblk(s) first */
11473 		tcp_reass_elim_overlap(tcp, mp);
11474 
11475 		/* Trim overlap with preceding mblk */
11476 		tcp_reass_elim_overlap(tcp, mp1);
11477 
11478 	} while (start = end, mp = next_mp);
11479 	mp1 = tcp->tcp_reass_head;
11480 	/* Anything ready to go? */
11481 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11482 		return (NULL);
11483 	/* Eat what we can off the queue */
11484 	for (;;) {
11485 		mp = mp1->b_cont;
11486 		end = TCP_REASS_END(mp1);
11487 		TCP_REASS_SET_SEQ(mp1, 0);
11488 		TCP_REASS_SET_END(mp1, 0);
11489 		if (!mp) {
11490 			tcp->tcp_reass_tail = NULL;
11491 			break;
11492 		}
11493 		if (end != TCP_REASS_SEQ(mp)) {
11494 			mp1->b_cont = NULL;
11495 			break;
11496 		}
11497 		mp1 = mp;
11498 	}
11499 	mp1 = tcp->tcp_reass_head;
11500 	tcp->tcp_reass_head = mp;
11501 	return (mp1);
11502 }
11503 
11504 /* Eliminate any overlap that mp may have over later mblks */
11505 static void
11506 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11507 {
11508 	uint32_t	end;
11509 	mblk_t		*mp1;
11510 	uint32_t	u1;
11511 
11512 	end = TCP_REASS_END(mp);
11513 	while ((mp1 = mp->b_cont) != NULL) {
11514 		u1 = TCP_REASS_SEQ(mp1);
11515 		if (!SEQ_GT(end, u1))
11516 			break;
11517 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11518 			mp->b_wptr -= end - u1;
11519 			TCP_REASS_SET_END(mp, u1);
11520 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
11521 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
11522 			break;
11523 		}
11524 		mp->b_cont = mp1->b_cont;
11525 		TCP_REASS_SET_SEQ(mp1, 0);
11526 		TCP_REASS_SET_END(mp1, 0);
11527 		freeb(mp1);
11528 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
11529 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
11530 	}
11531 	if (!mp1)
11532 		tcp->tcp_reass_tail = mp;
11533 }
11534 
11535 /*
11536  * Send up all messages queued on tcp_rcv_list.
11537  */
11538 static uint_t
11539 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11540 {
11541 	mblk_t *mp;
11542 	uint_t ret = 0;
11543 	uint_t thwin;
11544 #ifdef DEBUG
11545 	uint_t cnt = 0;
11546 #endif
11547 	/* Can't drain on an eager connection */
11548 	if (tcp->tcp_listener != NULL)
11549 		return (ret);
11550 
11551 	/*
11552 	 * Handle two cases here: we are currently fused or we were
11553 	 * previously fused and have some urgent data to be delivered
11554 	 * upstream.  The latter happens because we either ran out of
11555 	 * memory or were detached and therefore sending the SIGURG was
11556 	 * deferred until this point.  In either case we pass control
11557 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11558 	 * some work.
11559 	 */
11560 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11561 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11562 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11563 		    &tcp->tcp_fused_sigurg_mp))
11564 			return (ret);
11565 	}
11566 
11567 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11568 		tcp->tcp_rcv_list = mp->b_next;
11569 		mp->b_next = NULL;
11570 #ifdef DEBUG
11571 		cnt += msgdsize(mp);
11572 #endif
11573 		/* Does this need SSL processing first? */
11574 		if ((tcp->tcp_kssl_ctx  != NULL) && (DB_TYPE(mp) == M_DATA)) {
11575 			tcp_kssl_input(tcp, mp);
11576 			continue;
11577 		}
11578 		putnext(q, mp);
11579 	}
11580 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11581 	tcp->tcp_rcv_last_head = NULL;
11582 	tcp->tcp_rcv_last_tail = NULL;
11583 	tcp->tcp_rcv_cnt = 0;
11584 
11585 	/* Learn the latest rwnd information that we sent to the other side. */
11586 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11587 	    << tcp->tcp_rcv_ws;
11588 	/* This is peer's calculated send window (our receive window). */
11589 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11590 	/*
11591 	 * Increase the receive window to max.  But we need to do receiver
11592 	 * SWS avoidance.  This means that we need to check the increase of
11593 	 * of receive window is at least 1 MSS.
11594 	 */
11595 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11596 		/*
11597 		 * If the window that the other side knows is less than max
11598 		 * deferred acks segments, send an update immediately.
11599 		 */
11600 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11601 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11602 			ret = TH_ACK_NEEDED;
11603 		}
11604 		tcp->tcp_rwnd = q->q_hiwat;
11605 	}
11606 	/* No need for the push timer now. */
11607 	if (tcp->tcp_push_tid != 0) {
11608 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11609 		tcp->tcp_push_tid = 0;
11610 	}
11611 	return (ret);
11612 }
11613 
11614 /*
11615  * Queue data on tcp_rcv_list which is a b_next chain.
11616  * tcp_rcv_last_head/tail is the last element of this chain.
11617  * Each element of the chain is a b_cont chain.
11618  *
11619  * M_DATA messages are added to the current element.
11620  * Other messages are added as new (b_next) elements.
11621  */
11622 void
11623 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11624 {
11625 	ASSERT(seg_len == msgdsize(mp));
11626 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11627 
11628 	if (tcp->tcp_rcv_list == NULL) {
11629 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11630 		tcp->tcp_rcv_list = mp;
11631 		tcp->tcp_rcv_last_head = mp;
11632 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11633 		tcp->tcp_rcv_last_tail->b_cont = mp;
11634 	} else {
11635 		tcp->tcp_rcv_last_head->b_next = mp;
11636 		tcp->tcp_rcv_last_head = mp;
11637 	}
11638 
11639 	while (mp->b_cont)
11640 		mp = mp->b_cont;
11641 
11642 	tcp->tcp_rcv_last_tail = mp;
11643 	tcp->tcp_rcv_cnt += seg_len;
11644 	tcp->tcp_rwnd -= seg_len;
11645 }
11646 
11647 /*
11648  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11649  *
11650  * This is the default entry function into TCP on the read side. TCP is
11651  * always entered via squeue i.e. using squeue's for mutual exclusion.
11652  * When classifier does a lookup to find the tcp, it also puts a reference
11653  * on the conn structure associated so the tcp is guaranteed to exist
11654  * when we come here. We still need to check the state because it might
11655  * as well has been closed. The squeue processing function i.e. squeue_enter,
11656  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11657  * CONN_DEC_REF.
11658  *
11659  * Apart from the default entry point, IP also sends packets directly to
11660  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11661  * connections.
11662  */
11663 void
11664 tcp_input(void *arg, mblk_t *mp, void *arg2)
11665 {
11666 	conn_t	*connp = (conn_t *)arg;
11667 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11668 
11669 	/* arg2 is the sqp */
11670 	ASSERT(arg2 != NULL);
11671 	ASSERT(mp != NULL);
11672 
11673 	/*
11674 	 * Don't accept any input on a closed tcp as this TCP logically does
11675 	 * not exist on the system. Don't proceed further with this TCP.
11676 	 * For eg. this packet could trigger another close of this tcp
11677 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11678 	 * tcp_clean_death / tcp_closei_local must be called at most once
11679 	 * on a TCP. In this case we need to refeed the packet into the
11680 	 * classifier and figure out where the packet should go. Need to
11681 	 * preserve the recv_ill somehow. Until we figure that out, for
11682 	 * now just drop the packet if we can't classify the packet.
11683 	 */
11684 	if (tcp->tcp_state == TCPS_CLOSED ||
11685 	    tcp->tcp_state == TCPS_BOUND) {
11686 		conn_t	*new_connp;
11687 
11688 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11689 		if (new_connp != NULL) {
11690 			tcp_reinput(new_connp, mp, arg2);
11691 			return;
11692 		}
11693 		/* We failed to classify. For now just drop the packet */
11694 		freemsg(mp);
11695 		return;
11696 	}
11697 
11698 	if (DB_TYPE(mp) == M_DATA)
11699 		tcp_rput_data(connp, mp, arg2);
11700 	else
11701 		tcp_rput_common(tcp, mp);
11702 }
11703 
11704 /*
11705  * The read side put procedure.
11706  * The packets passed up by ip are assume to be aligned according to
11707  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11708  */
11709 static void
11710 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11711 {
11712 	/*
11713 	 * tcp_rput_data() does not expect M_CTL except for the case
11714 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11715 	 * type. Need to make sure that any other M_CTLs don't make
11716 	 * it to tcp_rput_data since it is not expecting any and doesn't
11717 	 * check for it.
11718 	 */
11719 	if (DB_TYPE(mp) == M_CTL) {
11720 		switch (*(uint32_t *)(mp->b_rptr)) {
11721 		case TCP_IOC_ABORT_CONN:
11722 			/*
11723 			 * Handle connection abort request.
11724 			 */
11725 			tcp_ioctl_abort_handler(tcp, mp);
11726 			return;
11727 		case IPSEC_IN:
11728 			/*
11729 			 * Only secure icmp arrive in TCP and they
11730 			 * don't go through data path.
11731 			 */
11732 			tcp_icmp_error(tcp, mp);
11733 			return;
11734 		case IN_PKTINFO:
11735 			/*
11736 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11737 			 * sockets that are receiving IPv4 traffic. tcp
11738 			 */
11739 			ASSERT(tcp->tcp_family == AF_INET6);
11740 			ASSERT(tcp->tcp_ipv6_recvancillary &
11741 			    TCP_IPV6_RECVPKTINFO);
11742 			tcp_rput_data(tcp->tcp_connp, mp,
11743 			    tcp->tcp_connp->conn_sqp);
11744 			return;
11745 		case MDT_IOC_INFO_UPDATE:
11746 			/*
11747 			 * Handle Multidata information update; the
11748 			 * following routine will free the message.
11749 			 */
11750 			if (tcp->tcp_connp->conn_mdt_ok) {
11751 				tcp_mdt_update(tcp,
11752 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11753 				    B_FALSE);
11754 			}
11755 			freemsg(mp);
11756 			return;
11757 		case LSO_IOC_INFO_UPDATE:
11758 			/*
11759 			 * Handle LSO information update; the following
11760 			 * routine will free the message.
11761 			 */
11762 			if (tcp->tcp_connp->conn_lso_ok) {
11763 				tcp_lso_update(tcp,
11764 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11765 			}
11766 			freemsg(mp);
11767 			return;
11768 		default:
11769 			/*
11770 			 * tcp_icmp_err() will process the M_CTL packets.
11771 			 * Non-ICMP packets, if any, will be discarded in
11772 			 * tcp_icmp_err(). We will process the ICMP packet
11773 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11774 			 * incoming ICMP packet may result in changing
11775 			 * the tcp_mss, which we would need if we have
11776 			 * packets to retransmit.
11777 			 */
11778 			tcp_icmp_error(tcp, mp);
11779 			return;
11780 		}
11781 	}
11782 
11783 	/* No point processing the message if tcp is already closed */
11784 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11785 		freemsg(mp);
11786 		return;
11787 	}
11788 
11789 	tcp_rput_other(tcp, mp);
11790 }
11791 
11792 
11793 /* The minimum of smoothed mean deviation in RTO calculation. */
11794 #define	TCP_SD_MIN	400
11795 
11796 /*
11797  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11798  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11799  * are the same as those in Appendix A.2 of that paper.
11800  *
11801  * m = new measurement
11802  * sa = smoothed RTT average (8 * average estimates).
11803  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11804  */
11805 static void
11806 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11807 {
11808 	long m = TICK_TO_MSEC(rtt);
11809 	clock_t sa = tcp->tcp_rtt_sa;
11810 	clock_t sv = tcp->tcp_rtt_sd;
11811 	clock_t rto;
11812 
11813 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
11814 	tcp->tcp_rtt_update++;
11815 
11816 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11817 	if (sa != 0) {
11818 		/*
11819 		 * Update average estimator:
11820 		 *	new rtt = 7/8 old rtt + 1/8 Error
11821 		 */
11822 
11823 		/* m is now Error in estimate. */
11824 		m -= sa >> 3;
11825 		if ((sa += m) <= 0) {
11826 			/*
11827 			 * Don't allow the smoothed average to be negative.
11828 			 * We use 0 to denote reinitialization of the
11829 			 * variables.
11830 			 */
11831 			sa = 1;
11832 		}
11833 
11834 		/*
11835 		 * Update deviation estimator:
11836 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11837 		 */
11838 		if (m < 0)
11839 			m = -m;
11840 		m -= sv >> 2;
11841 		sv += m;
11842 	} else {
11843 		/*
11844 		 * This follows BSD's implementation.  So the reinitialized
11845 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11846 		 * link is bandwidth dominated, doubling the window size
11847 		 * during slow start means doubling the RTT.  We want to be
11848 		 * more conservative when we reinitialize our estimates.  3
11849 		 * is just a convenient number.
11850 		 */
11851 		sa = m << 3;
11852 		sv = m << 1;
11853 	}
11854 	if (sv < TCP_SD_MIN) {
11855 		/*
11856 		 * We do not know that if sa captures the delay ACK
11857 		 * effect as in a long train of segments, a receiver
11858 		 * does not delay its ACKs.  So set the minimum of sv
11859 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11860 		 * of BSD DATO.  That means the minimum of mean
11861 		 * deviation is 100 ms.
11862 		 *
11863 		 */
11864 		sv = TCP_SD_MIN;
11865 	}
11866 	tcp->tcp_rtt_sa = sa;
11867 	tcp->tcp_rtt_sd = sv;
11868 	/*
11869 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11870 	 *
11871 	 * Add tcp_rexmit_interval extra in case of extreme environment
11872 	 * where the algorithm fails to work.  The default value of
11873 	 * tcp_rexmit_interval_extra should be 0.
11874 	 *
11875 	 * As we use a finer grained clock than BSD and update
11876 	 * RTO for every ACKs, add in another .25 of RTT to the
11877 	 * deviation of RTO to accomodate burstiness of 1/4 of
11878 	 * window size.
11879 	 */
11880 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
11881 
11882 	if (rto > tcp_rexmit_interval_max) {
11883 		tcp->tcp_rto = tcp_rexmit_interval_max;
11884 	} else if (rto < tcp_rexmit_interval_min) {
11885 		tcp->tcp_rto = tcp_rexmit_interval_min;
11886 	} else {
11887 		tcp->tcp_rto = rto;
11888 	}
11889 
11890 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11891 	tcp->tcp_timer_backoff = 0;
11892 }
11893 
11894 /*
11895  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11896  * send queue which starts at the given seq. no.
11897  *
11898  * Parameters:
11899  *	tcp_t *tcp: the tcp instance pointer.
11900  *	uint32_t seq: the starting seq. no of the requested segment.
11901  *	int32_t *off: after the execution, *off will be the offset to
11902  *		the returned mblk which points to the requested seq no.
11903  *		It is the caller's responsibility to send in a non-null off.
11904  *
11905  * Return:
11906  *	A mblk_t pointer pointing to the requested segment in send queue.
11907  */
11908 static mblk_t *
11909 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11910 {
11911 	int32_t	cnt;
11912 	mblk_t	*mp;
11913 
11914 	/* Defensive coding.  Make sure we don't send incorrect data. */
11915 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
11916 		return (NULL);
11917 
11918 	cnt = seq - tcp->tcp_suna;
11919 	mp = tcp->tcp_xmit_head;
11920 	while (cnt > 0 && mp != NULL) {
11921 		cnt -= mp->b_wptr - mp->b_rptr;
11922 		if (cnt < 0) {
11923 			cnt += mp->b_wptr - mp->b_rptr;
11924 			break;
11925 		}
11926 		mp = mp->b_cont;
11927 	}
11928 	ASSERT(mp != NULL);
11929 	*off = cnt;
11930 	return (mp);
11931 }
11932 
11933 /*
11934  * This function handles all retransmissions if SACK is enabled for this
11935  * connection.  First it calculates how many segments can be retransmitted
11936  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11937  * segments.  A segment is eligible if sack_cnt for that segment is greater
11938  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11939  * all eligible segments, it checks to see if TCP can send some new segments
11940  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11941  *
11942  * Parameters:
11943  *	tcp_t *tcp: the tcp structure of the connection.
11944  *	uint_t *flags: in return, appropriate value will be set for
11945  *	tcp_rput_data().
11946  */
11947 static void
11948 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11949 {
11950 	notsack_blk_t	*notsack_blk;
11951 	int32_t		usable_swnd;
11952 	int32_t		mss;
11953 	uint32_t	seg_len;
11954 	mblk_t		*xmit_mp;
11955 
11956 	ASSERT(tcp->tcp_sack_info != NULL);
11957 	ASSERT(tcp->tcp_notsack_list != NULL);
11958 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11959 
11960 	/* Defensive coding in case there is a bug... */
11961 	if (tcp->tcp_notsack_list == NULL) {
11962 		return;
11963 	}
11964 	notsack_blk = tcp->tcp_notsack_list;
11965 	mss = tcp->tcp_mss;
11966 
11967 	/*
11968 	 * Limit the num of outstanding data in the network to be
11969 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11970 	 */
11971 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11972 
11973 	/* At least retransmit 1 MSS of data. */
11974 	if (usable_swnd <= 0) {
11975 		usable_swnd = mss;
11976 	}
11977 
11978 	/* Make sure no new RTT samples will be taken. */
11979 	tcp->tcp_csuna = tcp->tcp_snxt;
11980 
11981 	notsack_blk = tcp->tcp_notsack_list;
11982 	while (usable_swnd > 0) {
11983 		mblk_t		*snxt_mp, *tmp_mp;
11984 		tcp_seq		begin = tcp->tcp_sack_snxt;
11985 		tcp_seq		end;
11986 		int32_t		off;
11987 
11988 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11989 			if (SEQ_GT(notsack_blk->end, begin) &&
11990 			    (notsack_blk->sack_cnt >=
11991 			    tcp_dupack_fast_retransmit)) {
11992 				end = notsack_blk->end;
11993 				if (SEQ_LT(begin, notsack_blk->begin)) {
11994 					begin = notsack_blk->begin;
11995 				}
11996 				break;
11997 			}
11998 		}
11999 		/*
12000 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12001 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12002 		 * set to tcp_cwnd_ssthresh.
12003 		 */
12004 		if (notsack_blk == NULL) {
12005 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12006 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12007 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12008 				ASSERT(tcp->tcp_cwnd > 0);
12009 				return;
12010 			} else {
12011 				usable_swnd = usable_swnd / mss;
12012 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12013 				    MAX(usable_swnd * mss, mss);
12014 				*flags |= TH_XMIT_NEEDED;
12015 				return;
12016 			}
12017 		}
12018 
12019 		/*
12020 		 * Note that we may send more than usable_swnd allows here
12021 		 * because of round off, but no more than 1 MSS of data.
12022 		 */
12023 		seg_len = end - begin;
12024 		if (seg_len > mss)
12025 			seg_len = mss;
12026 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12027 		ASSERT(snxt_mp != NULL);
12028 		/* This should not happen.  Defensive coding again... */
12029 		if (snxt_mp == NULL) {
12030 			return;
12031 		}
12032 
12033 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12034 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12035 		if (xmit_mp == NULL)
12036 			return;
12037 
12038 		usable_swnd -= seg_len;
12039 		tcp->tcp_pipe += seg_len;
12040 		tcp->tcp_sack_snxt = begin + seg_len;
12041 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
12042 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12043 
12044 		/*
12045 		 * Update the send timestamp to avoid false retransmission.
12046 		 */
12047 		snxt_mp->b_prev = (mblk_t *)lbolt;
12048 
12049 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
12050 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
12051 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
12052 		/*
12053 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12054 		 * This happens when new data sent during fast recovery is
12055 		 * also lost.  If TCP retransmits those new data, it needs
12056 		 * to extend SACK recover phase to avoid starting another
12057 		 * fast retransmit/recovery unnecessarily.
12058 		 */
12059 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12060 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12061 		}
12062 	}
12063 }
12064 
12065 /*
12066  * This function handles policy checking at TCP level for non-hard_bound/
12067  * detached connections.
12068  */
12069 static boolean_t
12070 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12071     boolean_t secure, boolean_t mctl_present)
12072 {
12073 	ipsec_latch_t *ipl = NULL;
12074 	ipsec_action_t *act = NULL;
12075 	mblk_t *data_mp;
12076 	ipsec_in_t *ii;
12077 	const char *reason;
12078 	kstat_named_t *counter;
12079 
12080 	ASSERT(mctl_present || !secure);
12081 
12082 	ASSERT((ipha == NULL && ip6h != NULL) ||
12083 	    (ip6h == NULL && ipha != NULL));
12084 
12085 	/*
12086 	 * We don't necessarily have an ipsec_in_act action to verify
12087 	 * policy because of assymetrical policy where we have only
12088 	 * outbound policy and no inbound policy (possible with global
12089 	 * policy).
12090 	 */
12091 	if (!secure) {
12092 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12093 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12094 			return (B_TRUE);
12095 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12096 		    "tcp_check_policy", ipha, ip6h, secure);
12097 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12098 		    &ipdrops_tcp_clear, &tcp_dropper);
12099 		return (B_FALSE);
12100 	}
12101 
12102 	/*
12103 	 * We have a secure packet.
12104 	 */
12105 	if (act == NULL) {
12106 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12107 		    "tcp_check_policy", ipha, ip6h, secure);
12108 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12109 		    &ipdrops_tcp_secure, &tcp_dropper);
12110 		return (B_FALSE);
12111 	}
12112 
12113 	/*
12114 	 * XXX This whole routine is currently incorrect.  ipl should
12115 	 * be set to the latch pointer, but is currently not set, so
12116 	 * we initialize it to NULL to avoid picking up random garbage.
12117 	 */
12118 	if (ipl == NULL)
12119 		return (B_TRUE);
12120 
12121 	data_mp = first_mp->b_cont;
12122 
12123 	ii = (ipsec_in_t *)first_mp->b_rptr;
12124 
12125 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12126 	    &counter, tcp->tcp_connp)) {
12127 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
12128 		return (B_TRUE);
12129 	}
12130 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12131 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12132 	    reason);
12133 	BUMP_MIB(&ip_mib, ipsecInFailed);
12134 
12135 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
12136 	return (B_FALSE);
12137 }
12138 
12139 /*
12140  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12141  * retransmission after a timeout.
12142  *
12143  * To limit the number of duplicate segments, we limit the number of segment
12144  * to be sent in one time to tcp_snd_burst, the burst variable.
12145  */
12146 static void
12147 tcp_ss_rexmit(tcp_t *tcp)
12148 {
12149 	uint32_t	snxt;
12150 	uint32_t	smax;
12151 	int32_t		win;
12152 	int32_t		mss;
12153 	int32_t		off;
12154 	int32_t		burst = tcp->tcp_snd_burst;
12155 	mblk_t		*snxt_mp;
12156 
12157 	/*
12158 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12159 	 * all unack'ed segments.
12160 	 */
12161 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12162 		smax = tcp->tcp_rexmit_max;
12163 		snxt = tcp->tcp_rexmit_nxt;
12164 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12165 			snxt = tcp->tcp_suna;
12166 		}
12167 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12168 		win -= snxt - tcp->tcp_suna;
12169 		mss = tcp->tcp_mss;
12170 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12171 
12172 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12173 		    (burst > 0) && (snxt_mp != NULL)) {
12174 			mblk_t	*xmit_mp;
12175 			mblk_t	*old_snxt_mp = snxt_mp;
12176 			uint32_t cnt = mss;
12177 
12178 			if (win < cnt) {
12179 				cnt = win;
12180 			}
12181 			if (SEQ_GT(snxt + cnt, smax)) {
12182 				cnt = smax - snxt;
12183 			}
12184 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12185 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12186 			if (xmit_mp == NULL)
12187 				return;
12188 
12189 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12190 
12191 			snxt += cnt;
12192 			win -= cnt;
12193 			/*
12194 			 * Update the send timestamp to avoid false
12195 			 * retransmission.
12196 			 */
12197 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12198 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
12199 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
12200 
12201 			tcp->tcp_rexmit_nxt = snxt;
12202 			burst--;
12203 		}
12204 		/*
12205 		 * If we have transmitted all we have at the time
12206 		 * we started the retranmission, we can leave
12207 		 * the rest of the job to tcp_wput_data().  But we
12208 		 * need to check the send window first.  If the
12209 		 * win is not 0, go on with tcp_wput_data().
12210 		 */
12211 		if (SEQ_LT(snxt, smax) || win == 0) {
12212 			return;
12213 		}
12214 	}
12215 	/* Only call tcp_wput_data() if there is data to be sent. */
12216 	if (tcp->tcp_unsent) {
12217 		tcp_wput_data(tcp, NULL, B_FALSE);
12218 	}
12219 }
12220 
12221 /*
12222  * Process all TCP option in SYN segment.  Note that this function should
12223  * be called after tcp_adapt_ire() is called so that the necessary info
12224  * from IRE is already set in the tcp structure.
12225  *
12226  * This function sets up the correct tcp_mss value according to the
12227  * MSS option value and our header size.  It also sets up the window scale
12228  * and timestamp values, and initialize SACK info blocks.  But it does not
12229  * change receive window size after setting the tcp_mss value.  The caller
12230  * should do the appropriate change.
12231  */
12232 void
12233 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12234 {
12235 	int options;
12236 	tcp_opt_t tcpopt;
12237 	uint32_t mss_max;
12238 	char *tmp_tcph;
12239 
12240 	tcpopt.tcp = NULL;
12241 	options = tcp_parse_options(tcph, &tcpopt);
12242 
12243 	/*
12244 	 * Process MSS option.  Note that MSS option value does not account
12245 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12246 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12247 	 * IPv6.
12248 	 */
12249 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12250 		if (tcp->tcp_ipversion == IPV4_VERSION)
12251 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
12252 		else
12253 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
12254 	} else {
12255 		if (tcp->tcp_ipversion == IPV4_VERSION)
12256 			mss_max = tcp_mss_max_ipv4;
12257 		else
12258 			mss_max = tcp_mss_max_ipv6;
12259 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
12260 			tcpopt.tcp_opt_mss = tcp_mss_min;
12261 		else if (tcpopt.tcp_opt_mss > mss_max)
12262 			tcpopt.tcp_opt_mss = mss_max;
12263 	}
12264 
12265 	/* Process Window Scale option. */
12266 	if (options & TCP_OPT_WSCALE_PRESENT) {
12267 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12268 		tcp->tcp_snd_ws_ok = B_TRUE;
12269 	} else {
12270 		tcp->tcp_snd_ws = B_FALSE;
12271 		tcp->tcp_snd_ws_ok = B_FALSE;
12272 		tcp->tcp_rcv_ws = B_FALSE;
12273 	}
12274 
12275 	/* Process Timestamp option. */
12276 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12277 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12278 		tmp_tcph = (char *)tcp->tcp_tcph;
12279 
12280 		tcp->tcp_snd_ts_ok = B_TRUE;
12281 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12282 		tcp->tcp_last_rcv_lbolt = lbolt64;
12283 		ASSERT(OK_32PTR(tmp_tcph));
12284 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12285 
12286 		/* Fill in our template header with basic timestamp option. */
12287 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12288 		tmp_tcph[0] = TCPOPT_NOP;
12289 		tmp_tcph[1] = TCPOPT_NOP;
12290 		tmp_tcph[2] = TCPOPT_TSTAMP;
12291 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12292 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12293 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12294 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12295 	} else {
12296 		tcp->tcp_snd_ts_ok = B_FALSE;
12297 	}
12298 
12299 	/*
12300 	 * Process SACK options.  If SACK is enabled for this connection,
12301 	 * then allocate the SACK info structure.  Note the following ways
12302 	 * when tcp_snd_sack_ok is set to true.
12303 	 *
12304 	 * For active connection: in tcp_adapt_ire() called in
12305 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12306 	 * is checked.
12307 	 *
12308 	 * For passive connection: in tcp_adapt_ire() called in
12309 	 * tcp_accept_comm().
12310 	 *
12311 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12312 	 * That check makes sure that if we did not send a SACK OK option,
12313 	 * we will not enable SACK for this connection even though the other
12314 	 * side sends us SACK OK option.  For active connection, the SACK
12315 	 * info structure has already been allocated.  So we need to free
12316 	 * it if SACK is disabled.
12317 	 */
12318 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12319 	    (tcp->tcp_snd_sack_ok ||
12320 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12321 		/* This should be true only in the passive case. */
12322 		if (tcp->tcp_sack_info == NULL) {
12323 			ASSERT(TCP_IS_DETACHED(tcp));
12324 			tcp->tcp_sack_info =
12325 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12326 		}
12327 		if (tcp->tcp_sack_info == NULL) {
12328 			tcp->tcp_snd_sack_ok = B_FALSE;
12329 		} else {
12330 			tcp->tcp_snd_sack_ok = B_TRUE;
12331 			if (tcp->tcp_snd_ts_ok) {
12332 				tcp->tcp_max_sack_blk = 3;
12333 			} else {
12334 				tcp->tcp_max_sack_blk = 4;
12335 			}
12336 		}
12337 	} else {
12338 		/*
12339 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12340 		 * no SACK info will be used for this
12341 		 * connection.  This assumes that SACK usage
12342 		 * permission is negotiated.  This may need
12343 		 * to be changed once this is clarified.
12344 		 */
12345 		if (tcp->tcp_sack_info != NULL) {
12346 			ASSERT(tcp->tcp_notsack_list == NULL);
12347 			kmem_cache_free(tcp_sack_info_cache,
12348 			    tcp->tcp_sack_info);
12349 			tcp->tcp_sack_info = NULL;
12350 		}
12351 		tcp->tcp_snd_sack_ok = B_FALSE;
12352 	}
12353 
12354 	/*
12355 	 * Now we know the exact TCP/IP header length, subtract
12356 	 * that from tcp_mss to get our side's MSS.
12357 	 */
12358 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12359 	/*
12360 	 * Here we assume that the other side's header size will be equal to
12361 	 * our header size.  We calculate the real MSS accordingly.  Need to
12362 	 * take into additional stuffs IPsec puts in.
12363 	 *
12364 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12365 	 */
12366 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12367 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12368 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12369 
12370 	/*
12371 	 * Set MSS to the smaller one of both ends of the connection.
12372 	 * We should not have called tcp_mss_set() before, but our
12373 	 * side of the MSS should have been set to a proper value
12374 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12375 	 * STREAM head parameters properly.
12376 	 *
12377 	 * If we have a larger-than-16-bit window but the other side
12378 	 * didn't want to do window scale, tcp_rwnd_set() will take
12379 	 * care of that.
12380 	 */
12381 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
12382 }
12383 
12384 /*
12385  * Sends the T_CONN_IND to the listener. The caller calls this
12386  * functions via squeue to get inside the listener's perimeter
12387  * once the 3 way hand shake is done a T_CONN_IND needs to be
12388  * sent. As an optimization, the caller can call this directly
12389  * if listener's perimeter is same as eager's.
12390  */
12391 /* ARGSUSED */
12392 void
12393 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12394 {
12395 	conn_t			*lconnp = (conn_t *)arg;
12396 	tcp_t			*listener = lconnp->conn_tcp;
12397 	tcp_t			*tcp;
12398 	struct T_conn_ind	*conn_ind;
12399 	ipaddr_t 		*addr_cache;
12400 	boolean_t		need_send_conn_ind = B_FALSE;
12401 
12402 	/* retrieve the eager */
12403 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12404 	ASSERT(conn_ind->OPT_offset != 0 &&
12405 	    conn_ind->OPT_length == sizeof (intptr_t));
12406 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12407 		conn_ind->OPT_length);
12408 
12409 	/*
12410 	 * TLI/XTI applications will get confused by
12411 	 * sending eager as an option since it violates
12412 	 * the option semantics. So remove the eager as
12413 	 * option since TLI/XTI app doesn't need it anyway.
12414 	 */
12415 	if (!TCP_IS_SOCKET(listener)) {
12416 		conn_ind->OPT_length = 0;
12417 		conn_ind->OPT_offset = 0;
12418 	}
12419 	if (listener->tcp_state == TCPS_CLOSED ||
12420 	    TCP_IS_DETACHED(listener)) {
12421 		/*
12422 		 * If listener has closed, it would have caused a
12423 		 * a cleanup/blowoff to happen for the eager. We
12424 		 * just need to return.
12425 		 */
12426 		freemsg(mp);
12427 		return;
12428 	}
12429 
12430 
12431 	/*
12432 	 * if the conn_req_q is full defer passing up the
12433 	 * T_CONN_IND until space is availabe after t_accept()
12434 	 * processing
12435 	 */
12436 	mutex_enter(&listener->tcp_eager_lock);
12437 
12438 	/*
12439 	 * Take the eager out, if it is in the list of droppable eagers
12440 	 * as we are here because the 3W handshake is over.
12441 	 */
12442 	MAKE_UNDROPPABLE(tcp);
12443 
12444 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12445 		tcp_t *tail;
12446 
12447 		/*
12448 		 * The eager already has an extra ref put in tcp_rput_data
12449 		 * so that it stays till accept comes back even though it
12450 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12451 		 */
12452 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12453 		listener->tcp_conn_req_cnt_q0--;
12454 		listener->tcp_conn_req_cnt_q++;
12455 
12456 		/* Move from SYN_RCVD to ESTABLISHED list  */
12457 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12458 		    tcp->tcp_eager_prev_q0;
12459 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12460 		    tcp->tcp_eager_next_q0;
12461 		tcp->tcp_eager_prev_q0 = NULL;
12462 		tcp->tcp_eager_next_q0 = NULL;
12463 
12464 		/*
12465 		 * Insert at end of the queue because sockfs
12466 		 * sends down T_CONN_RES in chronological
12467 		 * order. Leaving the older conn indications
12468 		 * at front of the queue helps reducing search
12469 		 * time.
12470 		 */
12471 		tail = listener->tcp_eager_last_q;
12472 		if (tail != NULL)
12473 			tail->tcp_eager_next_q = tcp;
12474 		else
12475 			listener->tcp_eager_next_q = tcp;
12476 		listener->tcp_eager_last_q = tcp;
12477 		tcp->tcp_eager_next_q = NULL;
12478 		/*
12479 		 * Delay sending up the T_conn_ind until we are
12480 		 * done with the eager. Once we have have sent up
12481 		 * the T_conn_ind, the accept can potentially complete
12482 		 * any time and release the refhold we have on the eager.
12483 		 */
12484 		need_send_conn_ind = B_TRUE;
12485 	} else {
12486 		/*
12487 		 * Defer connection on q0 and set deferred
12488 		 * connection bit true
12489 		 */
12490 		tcp->tcp_conn_def_q0 = B_TRUE;
12491 
12492 		/* take tcp out of q0 ... */
12493 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12494 		    tcp->tcp_eager_next_q0;
12495 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12496 		    tcp->tcp_eager_prev_q0;
12497 
12498 		/* ... and place it at the end of q0 */
12499 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12500 		tcp->tcp_eager_next_q0 = listener;
12501 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12502 		listener->tcp_eager_prev_q0 = tcp;
12503 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12504 	}
12505 
12506 	/* we have timed out before */
12507 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12508 		tcp->tcp_syn_rcvd_timeout = 0;
12509 		listener->tcp_syn_rcvd_timeout--;
12510 		if (listener->tcp_syn_defense &&
12511 		    listener->tcp_syn_rcvd_timeout <=
12512 		    (tcp_conn_req_max_q0 >> 5) &&
12513 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12514 			listener->tcp_last_rcv_lbolt)) {
12515 			/*
12516 			 * Turn off the defense mode if we
12517 			 * believe the SYN attack is over.
12518 			 */
12519 			listener->tcp_syn_defense = B_FALSE;
12520 			if (listener->tcp_ip_addr_cache) {
12521 				kmem_free((void *)listener->tcp_ip_addr_cache,
12522 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12523 				listener->tcp_ip_addr_cache = NULL;
12524 			}
12525 		}
12526 	}
12527 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12528 	if (addr_cache != NULL) {
12529 		/*
12530 		 * We have finished a 3-way handshake with this
12531 		 * remote host. This proves the IP addr is good.
12532 		 * Cache it!
12533 		 */
12534 		addr_cache[IP_ADDR_CACHE_HASH(
12535 			tcp->tcp_remote)] = tcp->tcp_remote;
12536 	}
12537 	mutex_exit(&listener->tcp_eager_lock);
12538 	if (need_send_conn_ind)
12539 		putnext(listener->tcp_rq, mp);
12540 }
12541 
12542 mblk_t *
12543 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12544     uint_t *ifindexp, ip6_pkt_t *ippp)
12545 {
12546 	ip_pktinfo_t	*pinfo;
12547 	ip6_t		*ip6h;
12548 	uchar_t		*rptr;
12549 	mblk_t		*first_mp = mp;
12550 	boolean_t	mctl_present = B_FALSE;
12551 	uint_t 		ifindex = 0;
12552 	ip6_pkt_t	ipp;
12553 	uint_t		ipvers;
12554 	uint_t		ip_hdr_len;
12555 
12556 	rptr = mp->b_rptr;
12557 	ASSERT(OK_32PTR(rptr));
12558 	ASSERT(tcp != NULL);
12559 	ipp.ipp_fields = 0;
12560 
12561 	switch DB_TYPE(mp) {
12562 	case M_CTL:
12563 		mp = mp->b_cont;
12564 		if (mp == NULL) {
12565 			freemsg(first_mp);
12566 			return (NULL);
12567 		}
12568 		if (DB_TYPE(mp) != M_DATA) {
12569 			freemsg(first_mp);
12570 			return (NULL);
12571 		}
12572 		mctl_present = B_TRUE;
12573 		break;
12574 	case M_DATA:
12575 		break;
12576 	default:
12577 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12578 		freemsg(mp);
12579 		return (NULL);
12580 	}
12581 	ipvers = IPH_HDR_VERSION(rptr);
12582 	if (ipvers == IPV4_VERSION) {
12583 		if (tcp == NULL) {
12584 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12585 			goto done;
12586 		}
12587 
12588 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12589 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12590 
12591 		/*
12592 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12593 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12594 		 */
12595 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12596 		    mctl_present) {
12597 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12598 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12599 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12600 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12601 				ipp.ipp_fields |= IPPF_IFINDEX;
12602 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12603 				ifindex = pinfo->ip_pkt_ifindex;
12604 			}
12605 			freeb(first_mp);
12606 			mctl_present = B_FALSE;
12607 		}
12608 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12609 	} else {
12610 		ip6h = (ip6_t *)rptr;
12611 
12612 		ASSERT(ipvers == IPV6_VERSION);
12613 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12614 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12615 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12616 
12617 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12618 			uint8_t	nexthdrp;
12619 
12620 			/* Look for ifindex information */
12621 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12622 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12623 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12624 					BUMP_MIB(&ip_mib, tcpInErrs);
12625 					freemsg(first_mp);
12626 					return (NULL);
12627 				}
12628 
12629 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12630 					ASSERT(ip6i->ip6i_ifindex != 0);
12631 					ipp.ipp_fields |= IPPF_IFINDEX;
12632 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12633 					ifindex = ip6i->ip6i_ifindex;
12634 				}
12635 				rptr = (uchar_t *)&ip6i[1];
12636 				mp->b_rptr = rptr;
12637 				if (rptr == mp->b_wptr) {
12638 					mblk_t *mp1;
12639 					mp1 = mp->b_cont;
12640 					freeb(mp);
12641 					mp = mp1;
12642 					rptr = mp->b_rptr;
12643 				}
12644 				if (MBLKL(mp) < IPV6_HDR_LEN +
12645 				    sizeof (tcph_t)) {
12646 					BUMP_MIB(&ip_mib, tcpInErrs);
12647 					freemsg(first_mp);
12648 					return (NULL);
12649 				}
12650 				ip6h = (ip6_t *)rptr;
12651 			}
12652 
12653 			/*
12654 			 * Find any potentially interesting extension headers
12655 			 * as well as the length of the IPv6 + extension
12656 			 * headers.
12657 			 */
12658 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12659 			/* Verify if this is a TCP packet */
12660 			if (nexthdrp != IPPROTO_TCP) {
12661 				BUMP_MIB(&ip_mib, tcpInErrs);
12662 				freemsg(first_mp);
12663 				return (NULL);
12664 			}
12665 		} else {
12666 			ip_hdr_len = IPV6_HDR_LEN;
12667 		}
12668 	}
12669 
12670 done:
12671 	if (ipversp != NULL)
12672 		*ipversp = ipvers;
12673 	if (ip_hdr_lenp != NULL)
12674 		*ip_hdr_lenp = ip_hdr_len;
12675 	if (ippp != NULL)
12676 		*ippp = ipp;
12677 	if (ifindexp != NULL)
12678 		*ifindexp = ifindex;
12679 	if (mctl_present) {
12680 		freeb(first_mp);
12681 	}
12682 	return (mp);
12683 }
12684 
12685 /*
12686  * Handle M_DATA messages from IP. Its called directly from IP via
12687  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12688  * in this path.
12689  *
12690  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12691  * v4 and v6), we are called through tcp_input() and a M_CTL can
12692  * be present for options but tcp_find_pktinfo() deals with it. We
12693  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12694  *
12695  * The first argument is always the connp/tcp to which the mp belongs.
12696  * There are no exceptions to this rule. The caller has already put
12697  * a reference on this connp/tcp and once tcp_rput_data() returns,
12698  * the squeue will do the refrele.
12699  *
12700  * The TH_SYN for the listener directly go to tcp_conn_request via
12701  * squeue.
12702  *
12703  * sqp: NULL = recursive, sqp != NULL means called from squeue
12704  */
12705 void
12706 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12707 {
12708 	int32_t		bytes_acked;
12709 	int32_t		gap;
12710 	mblk_t		*mp1;
12711 	uint_t		flags;
12712 	uint32_t	new_swnd = 0;
12713 	uchar_t		*iphdr;
12714 	uchar_t		*rptr;
12715 	int32_t		rgap;
12716 	uint32_t	seg_ack;
12717 	int		seg_len;
12718 	uint_t		ip_hdr_len;
12719 	uint32_t	seg_seq;
12720 	tcph_t		*tcph;
12721 	int		urp;
12722 	tcp_opt_t	tcpopt;
12723 	uint_t		ipvers;
12724 	ip6_pkt_t	ipp;
12725 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12726 	uint32_t	cwnd;
12727 	uint32_t	add;
12728 	int		npkt;
12729 	int		mss;
12730 	conn_t		*connp = (conn_t *)arg;
12731 	squeue_t	*sqp = (squeue_t *)arg2;
12732 	tcp_t		*tcp = connp->conn_tcp;
12733 
12734 	/*
12735 	 * RST from fused tcp loopback peer should trigger an unfuse.
12736 	 */
12737 	if (tcp->tcp_fused) {
12738 		TCP_STAT(tcp_fusion_aborted);
12739 		tcp_unfuse(tcp);
12740 	}
12741 
12742 	iphdr = mp->b_rptr;
12743 	rptr = mp->b_rptr;
12744 	ASSERT(OK_32PTR(rptr));
12745 
12746 	/*
12747 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12748 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12749 	 * necessary information.
12750 	 */
12751 	if (IPCL_IS_TCP4(connp)) {
12752 		ipvers = IPV4_VERSION;
12753 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12754 	} else {
12755 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12756 		    NULL, &ipp);
12757 		if (mp == NULL) {
12758 			TCP_STAT(tcp_rput_v6_error);
12759 			return;
12760 		}
12761 		iphdr = mp->b_rptr;
12762 		rptr = mp->b_rptr;
12763 	}
12764 	ASSERT(DB_TYPE(mp) == M_DATA);
12765 
12766 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12767 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12768 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12769 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12770 	seg_len = (int)(mp->b_wptr - rptr) -
12771 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12772 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12773 		do {
12774 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12775 			    (uintptr_t)INT_MAX);
12776 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12777 		} while ((mp1 = mp1->b_cont) != NULL &&
12778 		    mp1->b_datap->db_type == M_DATA);
12779 	}
12780 
12781 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12782 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12783 		    seg_len, tcph);
12784 		return;
12785 	}
12786 
12787 	if (sqp != NULL) {
12788 		/*
12789 		 * This is the correct place to update tcp_last_recv_time. Note
12790 		 * that it is also updated for tcp structure that belongs to
12791 		 * global and listener queues which do not really need updating.
12792 		 * But that should not cause any harm.  And it is updated for
12793 		 * all kinds of incoming segments, not only for data segments.
12794 		 */
12795 		tcp->tcp_last_recv_time = lbolt;
12796 	}
12797 
12798 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12799 
12800 	BUMP_LOCAL(tcp->tcp_ibsegs);
12801 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12802 
12803 	if ((flags & TH_URG) && sqp != NULL) {
12804 		/*
12805 		 * TCP can't handle urgent pointers that arrive before
12806 		 * the connection has been accept()ed since it can't
12807 		 * buffer OOB data.  Discard segment if this happens.
12808 		 *
12809 		 * Nor can it reassemble urgent pointers, so discard
12810 		 * if it's not the next segment expected.
12811 		 *
12812 		 * Otherwise, collapse chain into one mblk (discard if
12813 		 * that fails).  This makes sure the headers, retransmitted
12814 		 * data, and new data all are in the same mblk.
12815 		 */
12816 		ASSERT(mp != NULL);
12817 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
12818 			freemsg(mp);
12819 			return;
12820 		}
12821 		/* Update pointers into message */
12822 		iphdr = rptr = mp->b_rptr;
12823 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12824 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12825 			/*
12826 			 * Since we can't handle any data with this urgent
12827 			 * pointer that is out of sequence, we expunge
12828 			 * the data.  This allows us to still register
12829 			 * the urgent mark and generate the M_PCSIG,
12830 			 * which we can do.
12831 			 */
12832 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12833 			seg_len = 0;
12834 		}
12835 	}
12836 
12837 	switch (tcp->tcp_state) {
12838 	case TCPS_SYN_SENT:
12839 		if (flags & TH_ACK) {
12840 			/*
12841 			 * Note that our stack cannot send data before a
12842 			 * connection is established, therefore the
12843 			 * following check is valid.  Otherwise, it has
12844 			 * to be changed.
12845 			 */
12846 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12847 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12848 				freemsg(mp);
12849 				if (flags & TH_RST)
12850 					return;
12851 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12852 				    tcp, seg_ack, 0, TH_RST);
12853 				return;
12854 			}
12855 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12856 		}
12857 		if (flags & TH_RST) {
12858 			freemsg(mp);
12859 			if (flags & TH_ACK)
12860 				(void) tcp_clean_death(tcp,
12861 				    ECONNREFUSED, 13);
12862 			return;
12863 		}
12864 		if (!(flags & TH_SYN)) {
12865 			freemsg(mp);
12866 			return;
12867 		}
12868 
12869 		/* Process all TCP options. */
12870 		tcp_process_options(tcp, tcph);
12871 		/*
12872 		 * The following changes our rwnd to be a multiple of the
12873 		 * MIN(peer MSS, our MSS) for performance reason.
12874 		 */
12875 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12876 		    tcp->tcp_mss));
12877 
12878 		/* Is the other end ECN capable? */
12879 		if (tcp->tcp_ecn_ok) {
12880 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12881 				tcp->tcp_ecn_ok = B_FALSE;
12882 			}
12883 		}
12884 		/*
12885 		 * Clear ECN flags because it may interfere with later
12886 		 * processing.
12887 		 */
12888 		flags &= ~(TH_ECE|TH_CWR);
12889 
12890 		tcp->tcp_irs = seg_seq;
12891 		tcp->tcp_rack = seg_seq;
12892 		tcp->tcp_rnxt = seg_seq + 1;
12893 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12894 		if (!TCP_IS_DETACHED(tcp)) {
12895 			/* Allocate room for SACK options if needed. */
12896 			if (tcp->tcp_snd_sack_ok) {
12897 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12898 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
12899 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12900 			} else {
12901 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12902 				    tcp->tcp_hdr_len +
12903 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12904 			}
12905 		}
12906 		if (flags & TH_ACK) {
12907 			/*
12908 			 * If we can't get the confirmation upstream, pretend
12909 			 * we didn't even see this one.
12910 			 *
12911 			 * XXX: how can we pretend we didn't see it if we
12912 			 * have updated rnxt et. al.
12913 			 *
12914 			 * For loopback we defer sending up the T_CONN_CON
12915 			 * until after some checks below.
12916 			 */
12917 			mp1 = NULL;
12918 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12919 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12920 				freemsg(mp);
12921 				return;
12922 			}
12923 			/* SYN was acked - making progress */
12924 			if (tcp->tcp_ipversion == IPV6_VERSION)
12925 				tcp->tcp_ip_forward_progress = B_TRUE;
12926 
12927 			/* One for the SYN */
12928 			tcp->tcp_suna = tcp->tcp_iss + 1;
12929 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12930 			tcp->tcp_state = TCPS_ESTABLISHED;
12931 
12932 			/*
12933 			 * If SYN was retransmitted, need to reset all
12934 			 * retransmission info.  This is because this
12935 			 * segment will be treated as a dup ACK.
12936 			 */
12937 			if (tcp->tcp_rexmit) {
12938 				tcp->tcp_rexmit = B_FALSE;
12939 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12940 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12941 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12942 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12943 				tcp->tcp_ms_we_have_waited = 0;
12944 
12945 				/*
12946 				 * Set tcp_cwnd back to 1 MSS, per
12947 				 * recommendation from
12948 				 * draft-floyd-incr-init-win-01.txt,
12949 				 * Increasing TCP's Initial Window.
12950 				 */
12951 				tcp->tcp_cwnd = tcp->tcp_mss;
12952 			}
12953 
12954 			tcp->tcp_swl1 = seg_seq;
12955 			tcp->tcp_swl2 = seg_ack;
12956 
12957 			new_swnd = BE16_TO_U16(tcph->th_win);
12958 			tcp->tcp_swnd = new_swnd;
12959 			if (new_swnd > tcp->tcp_max_swnd)
12960 				tcp->tcp_max_swnd = new_swnd;
12961 
12962 			/*
12963 			 * Always send the three-way handshake ack immediately
12964 			 * in order to make the connection complete as soon as
12965 			 * possible on the accepting host.
12966 			 */
12967 			flags |= TH_ACK_NEEDED;
12968 
12969 			/*
12970 			 * Special case for loopback.  At this point we have
12971 			 * received SYN-ACK from the remote endpoint.  In
12972 			 * order to ensure that both endpoints reach the
12973 			 * fused state prior to any data exchange, the final
12974 			 * ACK needs to be sent before we indicate T_CONN_CON
12975 			 * to the module upstream.
12976 			 */
12977 			if (tcp->tcp_loopback) {
12978 				mblk_t *ack_mp;
12979 
12980 				ASSERT(!tcp->tcp_unfusable);
12981 				ASSERT(mp1 != NULL);
12982 				/*
12983 				 * For loopback, we always get a pure SYN-ACK
12984 				 * and only need to send back the final ACK
12985 				 * with no data (this is because the other
12986 				 * tcp is ours and we don't do T/TCP).  This
12987 				 * final ACK triggers the passive side to
12988 				 * perform fusion in ESTABLISHED state.
12989 				 */
12990 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12991 					if (tcp->tcp_ack_tid != 0) {
12992 						(void) TCP_TIMER_CANCEL(tcp,
12993 						    tcp->tcp_ack_tid);
12994 						tcp->tcp_ack_tid = 0;
12995 					}
12996 					TCP_RECORD_TRACE(tcp, ack_mp,
12997 					    TCP_TRACE_SEND_PKT);
12998 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
12999 					BUMP_LOCAL(tcp->tcp_obsegs);
13000 					BUMP_MIB(&tcp_mib, tcpOutAck);
13001 
13002 					/* Send up T_CONN_CON */
13003 					putnext(tcp->tcp_rq, mp1);
13004 
13005 					freemsg(mp);
13006 					return;
13007 				}
13008 				/*
13009 				 * Forget fusion; we need to handle more
13010 				 * complex cases below.  Send the deferred
13011 				 * T_CONN_CON message upstream and proceed
13012 				 * as usual.  Mark this tcp as not capable
13013 				 * of fusion.
13014 				 */
13015 				TCP_STAT(tcp_fusion_unfusable);
13016 				tcp->tcp_unfusable = B_TRUE;
13017 				putnext(tcp->tcp_rq, mp1);
13018 			}
13019 
13020 			/*
13021 			 * Check to see if there is data to be sent.  If
13022 			 * yes, set the transmit flag.  Then check to see
13023 			 * if received data processing needs to be done.
13024 			 * If not, go straight to xmit_check.  This short
13025 			 * cut is OK as we don't support T/TCP.
13026 			 */
13027 			if (tcp->tcp_unsent)
13028 				flags |= TH_XMIT_NEEDED;
13029 
13030 			if (seg_len == 0 && !(flags & TH_URG)) {
13031 				freemsg(mp);
13032 				goto xmit_check;
13033 			}
13034 
13035 			flags &= ~TH_SYN;
13036 			seg_seq++;
13037 			break;
13038 		}
13039 		tcp->tcp_state = TCPS_SYN_RCVD;
13040 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13041 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13042 		if (mp1) {
13043 			DB_CPID(mp1) = tcp->tcp_cpid;
13044 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
13045 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13046 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13047 		}
13048 		freemsg(mp);
13049 		return;
13050 	case TCPS_SYN_RCVD:
13051 		if (flags & TH_ACK) {
13052 			/*
13053 			 * In this state, a SYN|ACK packet is either bogus
13054 			 * because the other side must be ACKing our SYN which
13055 			 * indicates it has seen the ACK for their SYN and
13056 			 * shouldn't retransmit it or we're crossing SYNs
13057 			 * on active open.
13058 			 */
13059 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13060 				freemsg(mp);
13061 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13062 				    tcp, seg_ack, 0, TH_RST);
13063 				return;
13064 			}
13065 			/*
13066 			 * NOTE: RFC 793 pg. 72 says this should be
13067 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13068 			 * but that would mean we have an ack that ignored
13069 			 * our SYN.
13070 			 */
13071 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13072 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13073 				freemsg(mp);
13074 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13075 				    tcp, seg_ack, 0, TH_RST);
13076 				return;
13077 			}
13078 		}
13079 		break;
13080 	case TCPS_LISTEN:
13081 		/*
13082 		 * Only a TLI listener can come through this path when a
13083 		 * acceptor is going back to be a listener and a packet
13084 		 * for the acceptor hits the classifier. For a socket
13085 		 * listener, this can never happen because a listener
13086 		 * can never accept connection on itself and hence a
13087 		 * socket acceptor can not go back to being a listener.
13088 		 */
13089 		ASSERT(!TCP_IS_SOCKET(tcp));
13090 		/*FALLTHRU*/
13091 	case TCPS_CLOSED:
13092 	case TCPS_BOUND: {
13093 		conn_t	*new_connp;
13094 
13095 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
13096 		if (new_connp != NULL) {
13097 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13098 			return;
13099 		}
13100 		/* We failed to classify. For now just drop the packet */
13101 		freemsg(mp);
13102 		return;
13103 	}
13104 	case TCPS_IDLE:
13105 		/*
13106 		 * Handle the case where the tcp_clean_death() has happened
13107 		 * on a connection (application hasn't closed yet) but a packet
13108 		 * was already queued on squeue before tcp_clean_death()
13109 		 * was processed. Calling tcp_clean_death() twice on same
13110 		 * connection can result in weird behaviour.
13111 		 */
13112 		freemsg(mp);
13113 		return;
13114 	default:
13115 		break;
13116 	}
13117 
13118 	/*
13119 	 * Already on the correct queue/perimeter.
13120 	 * If this is a detached connection and not an eager
13121 	 * connection hanging off a listener then new data
13122 	 * (past the FIN) will cause a reset.
13123 	 * We do a special check here where it
13124 	 * is out of the main line, rather than check
13125 	 * if we are detached every time we see new
13126 	 * data down below.
13127 	 */
13128 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13129 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13130 		BUMP_MIB(&tcp_mib, tcpInClosed);
13131 		TCP_RECORD_TRACE(tcp,
13132 		    mp, TCP_TRACE_RECV_PKT);
13133 
13134 		freemsg(mp);
13135 		/*
13136 		 * This could be an SSL closure alert. We're detached so just
13137 		 * acknowledge it this last time.
13138 		 */
13139 		if (tcp->tcp_kssl_ctx != NULL) {
13140 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13141 			tcp->tcp_kssl_ctx = NULL;
13142 
13143 			tcp->tcp_rnxt += seg_len;
13144 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13145 			flags |= TH_ACK_NEEDED;
13146 			goto ack_check;
13147 		}
13148 
13149 		tcp_xmit_ctl("new data when detached", tcp,
13150 		    tcp->tcp_snxt, 0, TH_RST);
13151 		(void) tcp_clean_death(tcp, EPROTO, 12);
13152 		return;
13153 	}
13154 
13155 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13156 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13157 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13158 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13159 	mss = tcp->tcp_mss;
13160 
13161 	if (tcp->tcp_snd_ts_ok) {
13162 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13163 			/*
13164 			 * This segment is not acceptable.
13165 			 * Drop it and send back an ACK.
13166 			 */
13167 			freemsg(mp);
13168 			flags |= TH_ACK_NEEDED;
13169 			goto ack_check;
13170 		}
13171 	} else if (tcp->tcp_snd_sack_ok) {
13172 		ASSERT(tcp->tcp_sack_info != NULL);
13173 		tcpopt.tcp = tcp;
13174 		/*
13175 		 * SACK info in already updated in tcp_parse_options.  Ignore
13176 		 * all other TCP options...
13177 		 */
13178 		(void) tcp_parse_options(tcph, &tcpopt);
13179 	}
13180 try_again:;
13181 	gap = seg_seq - tcp->tcp_rnxt;
13182 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13183 	/*
13184 	 * gap is the amount of sequence space between what we expect to see
13185 	 * and what we got for seg_seq.  A positive value for gap means
13186 	 * something got lost.  A negative value means we got some old stuff.
13187 	 */
13188 	if (gap < 0) {
13189 		/* Old stuff present.  Is the SYN in there? */
13190 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13191 		    (seg_len != 0)) {
13192 			flags &= ~TH_SYN;
13193 			seg_seq++;
13194 			urp--;
13195 			/* Recompute the gaps after noting the SYN. */
13196 			goto try_again;
13197 		}
13198 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
13199 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
13200 		    (seg_len > -gap ? -gap : seg_len));
13201 		/* Remove the old stuff from seg_len. */
13202 		seg_len += gap;
13203 		/*
13204 		 * Anything left?
13205 		 * Make sure to check for unack'd FIN when rest of data
13206 		 * has been previously ack'd.
13207 		 */
13208 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13209 			/*
13210 			 * Resets are only valid if they lie within our offered
13211 			 * window.  If the RST bit is set, we just ignore this
13212 			 * segment.
13213 			 */
13214 			if (flags & TH_RST) {
13215 				freemsg(mp);
13216 				return;
13217 			}
13218 
13219 			/*
13220 			 * The arriving of dup data packets indicate that we
13221 			 * may have postponed an ack for too long, or the other
13222 			 * side's RTT estimate is out of shape. Start acking
13223 			 * more often.
13224 			 */
13225 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13226 			    tcp->tcp_rack_cnt >= 1 &&
13227 			    tcp->tcp_rack_abs_max > 2) {
13228 				tcp->tcp_rack_abs_max--;
13229 			}
13230 			tcp->tcp_rack_cur_max = 1;
13231 
13232 			/*
13233 			 * This segment is "unacceptable".  None of its
13234 			 * sequence space lies within our advertized window.
13235 			 *
13236 			 * Adjust seg_len to the original value for tracing.
13237 			 */
13238 			seg_len -= gap;
13239 			if (tcp->tcp_debug) {
13240 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13241 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13242 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13243 				    "seg_len %d, rnxt %u, snxt %u, %s",
13244 				    gap, rgap, flags, seg_seq, seg_ack,
13245 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13246 				    tcp_display(tcp, NULL,
13247 				    DISP_ADDR_AND_PORT));
13248 			}
13249 
13250 			/*
13251 			 * Arrange to send an ACK in response to the
13252 			 * unacceptable segment per RFC 793 page 69. There
13253 			 * is only one small difference between ours and the
13254 			 * acceptability test in the RFC - we accept ACK-only
13255 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13256 			 * will be generated.
13257 			 *
13258 			 * Note that we have to ACK an ACK-only packet at least
13259 			 * for stacks that send 0-length keep-alives with
13260 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13261 			 * section 4.2.3.6. As long as we don't ever generate
13262 			 * an unacceptable packet in response to an incoming
13263 			 * packet that is unacceptable, it should not cause
13264 			 * "ACK wars".
13265 			 */
13266 			flags |=  TH_ACK_NEEDED;
13267 
13268 			/*
13269 			 * Continue processing this segment in order to use the
13270 			 * ACK information it contains, but skip all other
13271 			 * sequence-number processing.	Processing the ACK
13272 			 * information is necessary in order to
13273 			 * re-synchronize connections that may have lost
13274 			 * synchronization.
13275 			 *
13276 			 * We clear seg_len and flag fields related to
13277 			 * sequence number processing as they are not
13278 			 * to be trusted for an unacceptable segment.
13279 			 */
13280 			seg_len = 0;
13281 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13282 			goto process_ack;
13283 		}
13284 
13285 		/* Fix seg_seq, and chew the gap off the front. */
13286 		seg_seq = tcp->tcp_rnxt;
13287 		urp += gap;
13288 		do {
13289 			mblk_t	*mp2;
13290 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13291 			    (uintptr_t)UINT_MAX);
13292 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13293 			if (gap > 0) {
13294 				mp->b_rptr = mp->b_wptr - gap;
13295 				break;
13296 			}
13297 			mp2 = mp;
13298 			mp = mp->b_cont;
13299 			freeb(mp2);
13300 		} while (gap < 0);
13301 		/*
13302 		 * If the urgent data has already been acknowledged, we
13303 		 * should ignore TH_URG below
13304 		 */
13305 		if (urp < 0)
13306 			flags &= ~TH_URG;
13307 	}
13308 	/*
13309 	 * rgap is the amount of stuff received out of window.  A negative
13310 	 * value is the amount out of window.
13311 	 */
13312 	if (rgap < 0) {
13313 		mblk_t	*mp2;
13314 
13315 		if (tcp->tcp_rwnd == 0) {
13316 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
13317 		} else {
13318 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
13319 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
13320 		}
13321 
13322 		/*
13323 		 * seg_len does not include the FIN, so if more than
13324 		 * just the FIN is out of window, we act like we don't
13325 		 * see it.  (If just the FIN is out of window, rgap
13326 		 * will be zero and we will go ahead and acknowledge
13327 		 * the FIN.)
13328 		 */
13329 		flags &= ~TH_FIN;
13330 
13331 		/* Fix seg_len and make sure there is something left. */
13332 		seg_len += rgap;
13333 		if (seg_len <= 0) {
13334 			/*
13335 			 * Resets are only valid if they lie within our offered
13336 			 * window.  If the RST bit is set, we just ignore this
13337 			 * segment.
13338 			 */
13339 			if (flags & TH_RST) {
13340 				freemsg(mp);
13341 				return;
13342 			}
13343 
13344 			/* Per RFC 793, we need to send back an ACK. */
13345 			flags |= TH_ACK_NEEDED;
13346 
13347 			/*
13348 			 * Send SIGURG as soon as possible i.e. even
13349 			 * if the TH_URG was delivered in a window probe
13350 			 * packet (which will be unacceptable).
13351 			 *
13352 			 * We generate a signal if none has been generated
13353 			 * for this connection or if this is a new urgent
13354 			 * byte. Also send a zero-length "unmarked" message
13355 			 * to inform SIOCATMARK that this is not the mark.
13356 			 *
13357 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13358 			 * is sent up. This plus the check for old data
13359 			 * (gap >= 0) handles the wraparound of the sequence
13360 			 * number space without having to always track the
13361 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13362 			 * this max in its rcv_up variable).
13363 			 *
13364 			 * This prevents duplicate SIGURGS due to a "late"
13365 			 * zero-window probe when the T_EXDATA_IND has already
13366 			 * been sent up.
13367 			 */
13368 			if ((flags & TH_URG) &&
13369 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13370 			    tcp->tcp_urp_last))) {
13371 				mp1 = allocb(0, BPRI_MED);
13372 				if (mp1 == NULL) {
13373 					freemsg(mp);
13374 					return;
13375 				}
13376 				if (!TCP_IS_DETACHED(tcp) &&
13377 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13378 				    SIGURG)) {
13379 					/* Try again on the rexmit. */
13380 					freemsg(mp1);
13381 					freemsg(mp);
13382 					return;
13383 				}
13384 				/*
13385 				 * If the next byte would be the mark
13386 				 * then mark with MARKNEXT else mark
13387 				 * with NOTMARKNEXT.
13388 				 */
13389 				if (gap == 0 && urp == 0)
13390 					mp1->b_flag |= MSGMARKNEXT;
13391 				else
13392 					mp1->b_flag |= MSGNOTMARKNEXT;
13393 				freemsg(tcp->tcp_urp_mark_mp);
13394 				tcp->tcp_urp_mark_mp = mp1;
13395 				flags |= TH_SEND_URP_MARK;
13396 				tcp->tcp_urp_last_valid = B_TRUE;
13397 				tcp->tcp_urp_last = urp + seg_seq;
13398 			}
13399 			/*
13400 			 * If this is a zero window probe, continue to
13401 			 * process the ACK part.  But we need to set seg_len
13402 			 * to 0 to avoid data processing.  Otherwise just
13403 			 * drop the segment and send back an ACK.
13404 			 */
13405 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13406 				flags &= ~(TH_SYN | TH_URG);
13407 				seg_len = 0;
13408 				goto process_ack;
13409 			} else {
13410 				freemsg(mp);
13411 				goto ack_check;
13412 			}
13413 		}
13414 		/* Pitch out of window stuff off the end. */
13415 		rgap = seg_len;
13416 		mp2 = mp;
13417 		do {
13418 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13419 			    (uintptr_t)INT_MAX);
13420 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13421 			if (rgap < 0) {
13422 				mp2->b_wptr += rgap;
13423 				if ((mp1 = mp2->b_cont) != NULL) {
13424 					mp2->b_cont = NULL;
13425 					freemsg(mp1);
13426 				}
13427 				break;
13428 			}
13429 		} while ((mp2 = mp2->b_cont) != NULL);
13430 	}
13431 ok:;
13432 	/*
13433 	 * TCP should check ECN info for segments inside the window only.
13434 	 * Therefore the check should be done here.
13435 	 */
13436 	if (tcp->tcp_ecn_ok) {
13437 		if (flags & TH_CWR) {
13438 			tcp->tcp_ecn_echo_on = B_FALSE;
13439 		}
13440 		/*
13441 		 * Note that both ECN_CE and CWR can be set in the
13442 		 * same segment.  In this case, we once again turn
13443 		 * on ECN_ECHO.
13444 		 */
13445 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13446 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13447 
13448 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13449 				tcp->tcp_ecn_echo_on = B_TRUE;
13450 			}
13451 		} else {
13452 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13453 
13454 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13455 			    htonl(IPH_ECN_CE << 20)) {
13456 				tcp->tcp_ecn_echo_on = B_TRUE;
13457 			}
13458 		}
13459 	}
13460 
13461 	/*
13462 	 * Check whether we can update tcp_ts_recent.  This test is
13463 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13464 	 * Extensions for High Performance: An Update", Internet Draft.
13465 	 */
13466 	if (tcp->tcp_snd_ts_ok &&
13467 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13468 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13469 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13470 		tcp->tcp_last_rcv_lbolt = lbolt64;
13471 	}
13472 
13473 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13474 		/*
13475 		 * FIN in an out of order segment.  We record this in
13476 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13477 		 * Clear the FIN so that any check on FIN flag will fail.
13478 		 * Remember that FIN also counts in the sequence number
13479 		 * space.  So we need to ack out of order FIN only segments.
13480 		 */
13481 		if (flags & TH_FIN) {
13482 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13483 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13484 			flags &= ~TH_FIN;
13485 			flags |= TH_ACK_NEEDED;
13486 		}
13487 		if (seg_len > 0) {
13488 			/* Fill in the SACK blk list. */
13489 			if (tcp->tcp_snd_sack_ok) {
13490 				ASSERT(tcp->tcp_sack_info != NULL);
13491 				tcp_sack_insert(tcp->tcp_sack_list,
13492 				    seg_seq, seg_seq + seg_len,
13493 				    &(tcp->tcp_num_sack_blk));
13494 			}
13495 
13496 			/*
13497 			 * Attempt reassembly and see if we have something
13498 			 * ready to go.
13499 			 */
13500 			mp = tcp_reass(tcp, mp, seg_seq);
13501 			/* Always ack out of order packets */
13502 			flags |= TH_ACK_NEEDED | TH_PUSH;
13503 			if (mp) {
13504 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13505 				    (uintptr_t)INT_MAX);
13506 				seg_len = mp->b_cont ? msgdsize(mp) :
13507 					(int)(mp->b_wptr - mp->b_rptr);
13508 				seg_seq = tcp->tcp_rnxt;
13509 				/*
13510 				 * A gap is filled and the seq num and len
13511 				 * of the gap match that of a previously
13512 				 * received FIN, put the FIN flag back in.
13513 				 */
13514 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13515 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13516 					flags |= TH_FIN;
13517 					tcp->tcp_valid_bits &=
13518 					    ~TCP_OFO_FIN_VALID;
13519 				}
13520 			} else {
13521 				/*
13522 				 * Keep going even with NULL mp.
13523 				 * There may be a useful ACK or something else
13524 				 * we don't want to miss.
13525 				 *
13526 				 * But TCP should not perform fast retransmit
13527 				 * because of the ack number.  TCP uses
13528 				 * seg_len == 0 to determine if it is a pure
13529 				 * ACK.  And this is not a pure ACK.
13530 				 */
13531 				seg_len = 0;
13532 				ofo_seg = B_TRUE;
13533 			}
13534 		}
13535 	} else if (seg_len > 0) {
13536 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
13537 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
13538 		/*
13539 		 * If an out of order FIN was received before, and the seq
13540 		 * num and len of the new segment match that of the FIN,
13541 		 * put the FIN flag back in.
13542 		 */
13543 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13544 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13545 			flags |= TH_FIN;
13546 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13547 		}
13548 	}
13549 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13550 	if (flags & TH_RST) {
13551 		freemsg(mp);
13552 		switch (tcp->tcp_state) {
13553 		case TCPS_SYN_RCVD:
13554 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13555 			break;
13556 		case TCPS_ESTABLISHED:
13557 		case TCPS_FIN_WAIT_1:
13558 		case TCPS_FIN_WAIT_2:
13559 		case TCPS_CLOSE_WAIT:
13560 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13561 			break;
13562 		case TCPS_CLOSING:
13563 		case TCPS_LAST_ACK:
13564 			(void) tcp_clean_death(tcp, 0, 16);
13565 			break;
13566 		default:
13567 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13568 			(void) tcp_clean_death(tcp, ENXIO, 17);
13569 			break;
13570 		}
13571 		return;
13572 	}
13573 	if (flags & TH_SYN) {
13574 		/*
13575 		 * See RFC 793, Page 71
13576 		 *
13577 		 * The seq number must be in the window as it should
13578 		 * be "fixed" above.  If it is outside window, it should
13579 		 * be already rejected.  Note that we allow seg_seq to be
13580 		 * rnxt + rwnd because we want to accept 0 window probe.
13581 		 */
13582 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13583 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13584 		freemsg(mp);
13585 		/*
13586 		 * If the ACK flag is not set, just use our snxt as the
13587 		 * seq number of the RST segment.
13588 		 */
13589 		if (!(flags & TH_ACK)) {
13590 			seg_ack = tcp->tcp_snxt;
13591 		}
13592 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13593 		    TH_RST|TH_ACK);
13594 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13595 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13596 		return;
13597 	}
13598 	/*
13599 	 * urp could be -1 when the urp field in the packet is 0
13600 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13601 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13602 	 */
13603 	if (flags & TH_URG && urp >= 0) {
13604 		if (!tcp->tcp_urp_last_valid ||
13605 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13606 			/*
13607 			 * If we haven't generated the signal yet for this
13608 			 * urgent pointer value, do it now.  Also, send up a
13609 			 * zero-length M_DATA indicating whether or not this is
13610 			 * the mark. The latter is not needed when a
13611 			 * T_EXDATA_IND is sent up. However, if there are
13612 			 * allocation failures this code relies on the sender
13613 			 * retransmitting and the socket code for determining
13614 			 * the mark should not block waiting for the peer to
13615 			 * transmit. Thus, for simplicity we always send up the
13616 			 * mark indication.
13617 			 */
13618 			mp1 = allocb(0, BPRI_MED);
13619 			if (mp1 == NULL) {
13620 				freemsg(mp);
13621 				return;
13622 			}
13623 			if (!TCP_IS_DETACHED(tcp) &&
13624 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13625 				/* Try again on the rexmit. */
13626 				freemsg(mp1);
13627 				freemsg(mp);
13628 				return;
13629 			}
13630 			/*
13631 			 * Mark with NOTMARKNEXT for now.
13632 			 * The code below will change this to MARKNEXT
13633 			 * if we are at the mark.
13634 			 *
13635 			 * If there are allocation failures (e.g. in dupmsg
13636 			 * below) the next time tcp_rput_data sees the urgent
13637 			 * segment it will send up the MSG*MARKNEXT message.
13638 			 */
13639 			mp1->b_flag |= MSGNOTMARKNEXT;
13640 			freemsg(tcp->tcp_urp_mark_mp);
13641 			tcp->tcp_urp_mark_mp = mp1;
13642 			flags |= TH_SEND_URP_MARK;
13643 #ifdef DEBUG
13644 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13645 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13646 			    "last %x, %s",
13647 			    seg_seq, urp, tcp->tcp_urp_last,
13648 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13649 #endif /* DEBUG */
13650 			tcp->tcp_urp_last_valid = B_TRUE;
13651 			tcp->tcp_urp_last = urp + seg_seq;
13652 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13653 			/*
13654 			 * An allocation failure prevented the previous
13655 			 * tcp_rput_data from sending up the allocated
13656 			 * MSG*MARKNEXT message - send it up this time
13657 			 * around.
13658 			 */
13659 			flags |= TH_SEND_URP_MARK;
13660 		}
13661 
13662 		/*
13663 		 * If the urgent byte is in this segment, make sure that it is
13664 		 * all by itself.  This makes it much easier to deal with the
13665 		 * possibility of an allocation failure on the T_exdata_ind.
13666 		 * Note that seg_len is the number of bytes in the segment, and
13667 		 * urp is the offset into the segment of the urgent byte.
13668 		 * urp < seg_len means that the urgent byte is in this segment.
13669 		 */
13670 		if (urp < seg_len) {
13671 			if (seg_len != 1) {
13672 				uint32_t  tmp_rnxt;
13673 				/*
13674 				 * Break it up and feed it back in.
13675 				 * Re-attach the IP header.
13676 				 */
13677 				mp->b_rptr = iphdr;
13678 				if (urp > 0) {
13679 					/*
13680 					 * There is stuff before the urgent
13681 					 * byte.
13682 					 */
13683 					mp1 = dupmsg(mp);
13684 					if (!mp1) {
13685 						/*
13686 						 * Trim from urgent byte on.
13687 						 * The rest will come back.
13688 						 */
13689 						(void) adjmsg(mp,
13690 						    urp - seg_len);
13691 						tcp_rput_data(connp,
13692 						    mp, NULL);
13693 						return;
13694 					}
13695 					(void) adjmsg(mp1, urp - seg_len);
13696 					/* Feed this piece back in. */
13697 					tmp_rnxt = tcp->tcp_rnxt;
13698 					tcp_rput_data(connp, mp1, NULL);
13699 					/*
13700 					 * If the data passed back in was not
13701 					 * processed (ie: bad ACK) sending
13702 					 * the remainder back in will cause a
13703 					 * loop. In this case, drop the
13704 					 * packet and let the sender try
13705 					 * sending a good packet.
13706 					 */
13707 					if (tmp_rnxt == tcp->tcp_rnxt) {
13708 						freemsg(mp);
13709 						return;
13710 					}
13711 				}
13712 				if (urp != seg_len - 1) {
13713 					uint32_t  tmp_rnxt;
13714 					/*
13715 					 * There is stuff after the urgent
13716 					 * byte.
13717 					 */
13718 					mp1 = dupmsg(mp);
13719 					if (!mp1) {
13720 						/*
13721 						 * Trim everything beyond the
13722 						 * urgent byte.  The rest will
13723 						 * come back.
13724 						 */
13725 						(void) adjmsg(mp,
13726 						    urp + 1 - seg_len);
13727 						tcp_rput_data(connp,
13728 						    mp, NULL);
13729 						return;
13730 					}
13731 					(void) adjmsg(mp1, urp + 1 - seg_len);
13732 					tmp_rnxt = tcp->tcp_rnxt;
13733 					tcp_rput_data(connp, mp1, NULL);
13734 					/*
13735 					 * If the data passed back in was not
13736 					 * processed (ie: bad ACK) sending
13737 					 * the remainder back in will cause a
13738 					 * loop. In this case, drop the
13739 					 * packet and let the sender try
13740 					 * sending a good packet.
13741 					 */
13742 					if (tmp_rnxt == tcp->tcp_rnxt) {
13743 						freemsg(mp);
13744 						return;
13745 					}
13746 				}
13747 				tcp_rput_data(connp, mp, NULL);
13748 				return;
13749 			}
13750 			/*
13751 			 * This segment contains only the urgent byte.  We
13752 			 * have to allocate the T_exdata_ind, if we can.
13753 			 */
13754 			if (!tcp->tcp_urp_mp) {
13755 				struct T_exdata_ind *tei;
13756 				mp1 = allocb(sizeof (struct T_exdata_ind),
13757 				    BPRI_MED);
13758 				if (!mp1) {
13759 					/*
13760 					 * Sigh... It'll be back.
13761 					 * Generate any MSG*MARK message now.
13762 					 */
13763 					freemsg(mp);
13764 					seg_len = 0;
13765 					if (flags & TH_SEND_URP_MARK) {
13766 
13767 
13768 						ASSERT(tcp->tcp_urp_mark_mp);
13769 						tcp->tcp_urp_mark_mp->b_flag &=
13770 							~MSGNOTMARKNEXT;
13771 						tcp->tcp_urp_mark_mp->b_flag |=
13772 							MSGMARKNEXT;
13773 					}
13774 					goto ack_check;
13775 				}
13776 				mp1->b_datap->db_type = M_PROTO;
13777 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13778 				tei->PRIM_type = T_EXDATA_IND;
13779 				tei->MORE_flag = 0;
13780 				mp1->b_wptr = (uchar_t *)&tei[1];
13781 				tcp->tcp_urp_mp = mp1;
13782 #ifdef DEBUG
13783 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13784 				    "tcp_rput: allocated exdata_ind %s",
13785 				    tcp_display(tcp, NULL,
13786 				    DISP_PORT_ONLY));
13787 #endif /* DEBUG */
13788 				/*
13789 				 * There is no need to send a separate MSG*MARK
13790 				 * message since the T_EXDATA_IND will be sent
13791 				 * now.
13792 				 */
13793 				flags &= ~TH_SEND_URP_MARK;
13794 				freemsg(tcp->tcp_urp_mark_mp);
13795 				tcp->tcp_urp_mark_mp = NULL;
13796 			}
13797 			/*
13798 			 * Now we are all set.  On the next putnext upstream,
13799 			 * tcp_urp_mp will be non-NULL and will get prepended
13800 			 * to what has to be this piece containing the urgent
13801 			 * byte.  If for any reason we abort this segment below,
13802 			 * if it comes back, we will have this ready, or it
13803 			 * will get blown off in close.
13804 			 */
13805 		} else if (urp == seg_len) {
13806 			/*
13807 			 * The urgent byte is the next byte after this sequence
13808 			 * number. If there is data it is marked with
13809 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13810 			 * since it is not needed. Otherwise, if the code
13811 			 * above just allocated a zero-length tcp_urp_mark_mp
13812 			 * message, that message is tagged with MSGMARKNEXT.
13813 			 * Sending up these MSGMARKNEXT messages makes
13814 			 * SIOCATMARK work correctly even though
13815 			 * the T_EXDATA_IND will not be sent up until the
13816 			 * urgent byte arrives.
13817 			 */
13818 			if (seg_len != 0) {
13819 				flags |= TH_MARKNEXT_NEEDED;
13820 				freemsg(tcp->tcp_urp_mark_mp);
13821 				tcp->tcp_urp_mark_mp = NULL;
13822 				flags &= ~TH_SEND_URP_MARK;
13823 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13824 				flags |= TH_SEND_URP_MARK;
13825 				tcp->tcp_urp_mark_mp->b_flag &=
13826 					~MSGNOTMARKNEXT;
13827 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13828 			}
13829 #ifdef DEBUG
13830 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13831 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13832 			    seg_len, flags,
13833 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13834 #endif /* DEBUG */
13835 		} else {
13836 			/* Data left until we hit mark */
13837 #ifdef DEBUG
13838 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13839 			    "tcp_rput: URP %d bytes left, %s",
13840 			    urp - seg_len, tcp_display(tcp, NULL,
13841 			    DISP_PORT_ONLY));
13842 #endif /* DEBUG */
13843 		}
13844 	}
13845 
13846 process_ack:
13847 	if (!(flags & TH_ACK)) {
13848 		freemsg(mp);
13849 		goto xmit_check;
13850 	}
13851 	}
13852 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13853 
13854 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13855 		tcp->tcp_ip_forward_progress = B_TRUE;
13856 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13857 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13858 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13859 			/* 3-way handshake complete - pass up the T_CONN_IND */
13860 			tcp_t	*listener = tcp->tcp_listener;
13861 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13862 
13863 			tcp->tcp_tconnind_started = B_TRUE;
13864 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13865 			/*
13866 			 * We are here means eager is fine but it can
13867 			 * get a TH_RST at any point between now and till
13868 			 * accept completes and disappear. We need to
13869 			 * ensure that reference to eager is valid after
13870 			 * we get out of eager's perimeter. So we do
13871 			 * an extra refhold.
13872 			 */
13873 			CONN_INC_REF(connp);
13874 
13875 			/*
13876 			 * The listener also exists because of the refhold
13877 			 * done in tcp_conn_request. Its possible that it
13878 			 * might have closed. We will check that once we
13879 			 * get inside listeners context.
13880 			 */
13881 			CONN_INC_REF(listener->tcp_connp);
13882 			if (listener->tcp_connp->conn_sqp ==
13883 			    connp->conn_sqp) {
13884 				tcp_send_conn_ind(listener->tcp_connp, mp,
13885 				    listener->tcp_connp->conn_sqp);
13886 				CONN_DEC_REF(listener->tcp_connp);
13887 			} else if (!tcp->tcp_loopback) {
13888 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
13889 				    tcp_send_conn_ind,
13890 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
13891 			} else {
13892 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
13893 				    tcp_send_conn_ind, listener->tcp_connp,
13894 				    SQTAG_TCP_CONN_IND);
13895 			}
13896 		}
13897 
13898 		if (tcp->tcp_active_open) {
13899 			/*
13900 			 * We are seeing the final ack in the three way
13901 			 * hand shake of a active open'ed connection
13902 			 * so we must send up a T_CONN_CON
13903 			 */
13904 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13905 				freemsg(mp);
13906 				return;
13907 			}
13908 			/*
13909 			 * Don't fuse the loopback endpoints for
13910 			 * simultaneous active opens.
13911 			 */
13912 			if (tcp->tcp_loopback) {
13913 				TCP_STAT(tcp_fusion_unfusable);
13914 				tcp->tcp_unfusable = B_TRUE;
13915 			}
13916 		}
13917 
13918 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
13919 		bytes_acked--;
13920 		/* SYN was acked - making progress */
13921 		if (tcp->tcp_ipversion == IPV6_VERSION)
13922 			tcp->tcp_ip_forward_progress = B_TRUE;
13923 
13924 		/*
13925 		 * If SYN was retransmitted, need to reset all
13926 		 * retransmission info as this segment will be
13927 		 * treated as a dup ACK.
13928 		 */
13929 		if (tcp->tcp_rexmit) {
13930 			tcp->tcp_rexmit = B_FALSE;
13931 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13932 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
13933 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13934 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13935 			tcp->tcp_ms_we_have_waited = 0;
13936 			tcp->tcp_cwnd = mss;
13937 		}
13938 
13939 		/*
13940 		 * We set the send window to zero here.
13941 		 * This is needed if there is data to be
13942 		 * processed already on the queue.
13943 		 * Later (at swnd_update label), the
13944 		 * "new_swnd > tcp_swnd" condition is satisfied
13945 		 * the XMIT_NEEDED flag is set in the current
13946 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
13947 		 * called if there is already data on queue in
13948 		 * this state.
13949 		 */
13950 		tcp->tcp_swnd = 0;
13951 
13952 		if (new_swnd > tcp->tcp_max_swnd)
13953 			tcp->tcp_max_swnd = new_swnd;
13954 		tcp->tcp_swl1 = seg_seq;
13955 		tcp->tcp_swl2 = seg_ack;
13956 		tcp->tcp_state = TCPS_ESTABLISHED;
13957 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13958 
13959 		/* Fuse when both sides are in ESTABLISHED state */
13960 		if (tcp->tcp_loopback && do_tcp_fusion)
13961 			tcp_fuse(tcp, iphdr, tcph);
13962 
13963 	}
13964 	/* This code follows 4.4BSD-Lite2 mostly. */
13965 	if (bytes_acked < 0)
13966 		goto est;
13967 
13968 	/*
13969 	 * If TCP is ECN capable and the congestion experience bit is
13970 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
13971 	 * done once per window (or more loosely, per RTT).
13972 	 */
13973 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
13974 		tcp->tcp_cwr = B_FALSE;
13975 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
13976 		if (!tcp->tcp_cwr) {
13977 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
13978 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
13979 			tcp->tcp_cwnd = npkt * mss;
13980 			/*
13981 			 * If the cwnd is 0, use the timer to clock out
13982 			 * new segments.  This is required by the ECN spec.
13983 			 */
13984 			if (npkt == 0) {
13985 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13986 				/*
13987 				 * This makes sure that when the ACK comes
13988 				 * back, we will increase tcp_cwnd by 1 MSS.
13989 				 */
13990 				tcp->tcp_cwnd_cnt = 0;
13991 			}
13992 			tcp->tcp_cwr = B_TRUE;
13993 			/*
13994 			 * This marks the end of the current window of in
13995 			 * flight data.  That is why we don't use
13996 			 * tcp_suna + tcp_swnd.  Only data in flight can
13997 			 * provide ECN info.
13998 			 */
13999 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14000 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14001 		}
14002 	}
14003 
14004 	mp1 = tcp->tcp_xmit_head;
14005 	if (bytes_acked == 0) {
14006 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14007 			int dupack_cnt;
14008 
14009 			BUMP_MIB(&tcp_mib, tcpInDupAck);
14010 			/*
14011 			 * Fast retransmit.  When we have seen exactly three
14012 			 * identical ACKs while we have unacked data
14013 			 * outstanding we take it as a hint that our peer
14014 			 * dropped something.
14015 			 *
14016 			 * If TCP is retransmitting, don't do fast retransmit.
14017 			 */
14018 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14019 			    ! tcp->tcp_rexmit) {
14020 				/* Do Limited Transmit */
14021 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14022 				    tcp_dupack_fast_retransmit) {
14023 					/*
14024 					 * RFC 3042
14025 					 *
14026 					 * What we need to do is temporarily
14027 					 * increase tcp_cwnd so that new
14028 					 * data can be sent if it is allowed
14029 					 * by the receive window (tcp_rwnd).
14030 					 * tcp_wput_data() will take care of
14031 					 * the rest.
14032 					 *
14033 					 * If the connection is SACK capable,
14034 					 * only do limited xmit when there
14035 					 * is SACK info.
14036 					 *
14037 					 * Note how tcp_cwnd is incremented.
14038 					 * The first dup ACK will increase
14039 					 * it by 1 MSS.  The second dup ACK
14040 					 * will increase it by 2 MSS.  This
14041 					 * means that only 1 new segment will
14042 					 * be sent for each dup ACK.
14043 					 */
14044 					if (tcp->tcp_unsent > 0 &&
14045 					    (!tcp->tcp_snd_sack_ok ||
14046 					    (tcp->tcp_snd_sack_ok &&
14047 					    tcp->tcp_notsack_list != NULL))) {
14048 						tcp->tcp_cwnd += mss <<
14049 						    (tcp->tcp_dupack_cnt - 1);
14050 						flags |= TH_LIMIT_XMIT;
14051 					}
14052 				} else if (dupack_cnt ==
14053 				    tcp_dupack_fast_retransmit) {
14054 
14055 				/*
14056 				 * If we have reduced tcp_ssthresh
14057 				 * because of ECN, do not reduce it again
14058 				 * unless it is already one window of data
14059 				 * away.  After one window of data, tcp_cwr
14060 				 * should then be cleared.  Note that
14061 				 * for non ECN capable connection, tcp_cwr
14062 				 * should always be false.
14063 				 *
14064 				 * Adjust cwnd since the duplicate
14065 				 * ack indicates that a packet was
14066 				 * dropped (due to congestion.)
14067 				 */
14068 				if (!tcp->tcp_cwr) {
14069 					npkt = ((tcp->tcp_snxt -
14070 					    tcp->tcp_suna) >> 1) / mss;
14071 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14072 					    mss;
14073 					tcp->tcp_cwnd = (npkt +
14074 					    tcp->tcp_dupack_cnt) * mss;
14075 				}
14076 				if (tcp->tcp_ecn_ok) {
14077 					tcp->tcp_cwr = B_TRUE;
14078 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14079 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14080 				}
14081 
14082 				/*
14083 				 * We do Hoe's algorithm.  Refer to her
14084 				 * paper "Improving the Start-up Behavior
14085 				 * of a Congestion Control Scheme for TCP,"
14086 				 * appeared in SIGCOMM'96.
14087 				 *
14088 				 * Save highest seq no we have sent so far.
14089 				 * Be careful about the invisible FIN byte.
14090 				 */
14091 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14092 				    (tcp->tcp_unsent == 0)) {
14093 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14094 				} else {
14095 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14096 				}
14097 
14098 				/*
14099 				 * Do not allow bursty traffic during.
14100 				 * fast recovery.  Refer to Fall and Floyd's
14101 				 * paper "Simulation-based Comparisons of
14102 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14103 				 * This is a best current practise.
14104 				 */
14105 				tcp->tcp_snd_burst = TCP_CWND_SS;
14106 
14107 				/*
14108 				 * For SACK:
14109 				 * Calculate tcp_pipe, which is the
14110 				 * estimated number of bytes in
14111 				 * network.
14112 				 *
14113 				 * tcp_fack is the highest sack'ed seq num
14114 				 * TCP has received.
14115 				 *
14116 				 * tcp_pipe is explained in the above quoted
14117 				 * Fall and Floyd's paper.  tcp_fack is
14118 				 * explained in Mathis and Mahdavi's
14119 				 * "Forward Acknowledgment: Refining TCP
14120 				 * Congestion Control" in SIGCOMM '96.
14121 				 */
14122 				if (tcp->tcp_snd_sack_ok) {
14123 					ASSERT(tcp->tcp_sack_info != NULL);
14124 					if (tcp->tcp_notsack_list != NULL) {
14125 						tcp->tcp_pipe = tcp->tcp_snxt -
14126 						    tcp->tcp_fack;
14127 						tcp->tcp_sack_snxt = seg_ack;
14128 						flags |= TH_NEED_SACK_REXMIT;
14129 					} else {
14130 						/*
14131 						 * Always initialize tcp_pipe
14132 						 * even though we don't have
14133 						 * any SACK info.  If later
14134 						 * we get SACK info and
14135 						 * tcp_pipe is not initialized,
14136 						 * funny things will happen.
14137 						 */
14138 						tcp->tcp_pipe =
14139 						    tcp->tcp_cwnd_ssthresh;
14140 					}
14141 				} else {
14142 					flags |= TH_REXMIT_NEEDED;
14143 				} /* tcp_snd_sack_ok */
14144 
14145 				} else {
14146 					/*
14147 					 * Here we perform congestion
14148 					 * avoidance, but NOT slow start.
14149 					 * This is known as the Fast
14150 					 * Recovery Algorithm.
14151 					 */
14152 					if (tcp->tcp_snd_sack_ok &&
14153 					    tcp->tcp_notsack_list != NULL) {
14154 						flags |= TH_NEED_SACK_REXMIT;
14155 						tcp->tcp_pipe -= mss;
14156 						if (tcp->tcp_pipe < 0)
14157 							tcp->tcp_pipe = 0;
14158 					} else {
14159 					/*
14160 					 * We know that one more packet has
14161 					 * left the pipe thus we can update
14162 					 * cwnd.
14163 					 */
14164 					cwnd = tcp->tcp_cwnd + mss;
14165 					if (cwnd > tcp->tcp_cwnd_max)
14166 						cwnd = tcp->tcp_cwnd_max;
14167 					tcp->tcp_cwnd = cwnd;
14168 					if (tcp->tcp_unsent > 0)
14169 						flags |= TH_XMIT_NEEDED;
14170 					}
14171 				}
14172 			}
14173 		} else if (tcp->tcp_zero_win_probe) {
14174 			/*
14175 			 * If the window has opened, need to arrange
14176 			 * to send additional data.
14177 			 */
14178 			if (new_swnd != 0) {
14179 				/* tcp_suna != tcp_snxt */
14180 				/* Packet contains a window update */
14181 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
14182 				tcp->tcp_zero_win_probe = 0;
14183 				tcp->tcp_timer_backoff = 0;
14184 				tcp->tcp_ms_we_have_waited = 0;
14185 
14186 				/*
14187 				 * Transmit starting with tcp_suna since
14188 				 * the one byte probe is not ack'ed.
14189 				 * If TCP has sent more than one identical
14190 				 * probe, tcp_rexmit will be set.  That means
14191 				 * tcp_ss_rexmit() will send out the one
14192 				 * byte along with new data.  Otherwise,
14193 				 * fake the retransmission.
14194 				 */
14195 				flags |= TH_XMIT_NEEDED;
14196 				if (!tcp->tcp_rexmit) {
14197 					tcp->tcp_rexmit = B_TRUE;
14198 					tcp->tcp_dupack_cnt = 0;
14199 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14200 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14201 				}
14202 			}
14203 		}
14204 		goto swnd_update;
14205 	}
14206 
14207 	/*
14208 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14209 	 * If the ACK value acks something that we have not yet sent, it might
14210 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14211 	 * other side.
14212 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14213 	 * state is handled above, so we can always just drop the segment and
14214 	 * send an ACK here.
14215 	 *
14216 	 * Should we send ACKs in response to ACK only segments?
14217 	 */
14218 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14219 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
14220 		/* drop the received segment */
14221 		freemsg(mp);
14222 
14223 		/*
14224 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14225 		 * greater than 0, check if the number of such
14226 		 * bogus ACks is greater than that count.  If yes,
14227 		 * don't send back any ACK.  This prevents TCP from
14228 		 * getting into an ACK storm if somehow an attacker
14229 		 * successfully spoofs an acceptable segment to our
14230 		 * peer.
14231 		 */
14232 		if (tcp_drop_ack_unsent_cnt > 0 &&
14233 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14234 			TCP_STAT(tcp_in_ack_unsent_drop);
14235 			return;
14236 		}
14237 		mp = tcp_ack_mp(tcp);
14238 		if (mp != NULL) {
14239 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
14240 			BUMP_LOCAL(tcp->tcp_obsegs);
14241 			BUMP_MIB(&tcp_mib, tcpOutAck);
14242 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14243 		}
14244 		return;
14245 	}
14246 
14247 	/*
14248 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14249 	 * blocks that are covered by this ACK.
14250 	 */
14251 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14252 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14253 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14254 	}
14255 
14256 	/*
14257 	 * If we got an ACK after fast retransmit, check to see
14258 	 * if it is a partial ACK.  If it is not and the congestion
14259 	 * window was inflated to account for the other side's
14260 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14261 	 */
14262 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
14263 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14264 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14265 			tcp->tcp_dupack_cnt = 0;
14266 			/*
14267 			 * Restore the orig tcp_cwnd_ssthresh after
14268 			 * fast retransmit phase.
14269 			 */
14270 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14271 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14272 			}
14273 			tcp->tcp_rexmit_max = seg_ack;
14274 			tcp->tcp_cwnd_cnt = 0;
14275 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14276 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14277 
14278 			/*
14279 			 * Remove all notsack info to avoid confusion with
14280 			 * the next fast retrasnmit/recovery phase.
14281 			 */
14282 			if (tcp->tcp_snd_sack_ok &&
14283 			    tcp->tcp_notsack_list != NULL) {
14284 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14285 			}
14286 		} else {
14287 			if (tcp->tcp_snd_sack_ok &&
14288 			    tcp->tcp_notsack_list != NULL) {
14289 				flags |= TH_NEED_SACK_REXMIT;
14290 				tcp->tcp_pipe -= mss;
14291 				if (tcp->tcp_pipe < 0)
14292 					tcp->tcp_pipe = 0;
14293 			} else {
14294 				/*
14295 				 * Hoe's algorithm:
14296 				 *
14297 				 * Retransmit the unack'ed segment and
14298 				 * restart fast recovery.  Note that we
14299 				 * need to scale back tcp_cwnd to the
14300 				 * original value when we started fast
14301 				 * recovery.  This is to prevent overly
14302 				 * aggressive behaviour in sending new
14303 				 * segments.
14304 				 */
14305 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14306 					tcp_dupack_fast_retransmit * mss;
14307 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14308 				flags |= TH_REXMIT_NEEDED;
14309 			}
14310 		}
14311 	} else {
14312 		tcp->tcp_dupack_cnt = 0;
14313 		if (tcp->tcp_rexmit) {
14314 			/*
14315 			 * TCP is retranmitting.  If the ACK ack's all
14316 			 * outstanding data, update tcp_rexmit_max and
14317 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14318 			 * to the correct value.
14319 			 *
14320 			 * Note that SEQ_LEQ() is used.  This is to avoid
14321 			 * unnecessary fast retransmit caused by dup ACKs
14322 			 * received when TCP does slow start retransmission
14323 			 * after a time out.  During this phase, TCP may
14324 			 * send out segments which are already received.
14325 			 * This causes dup ACKs to be sent back.
14326 			 */
14327 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14328 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14329 					tcp->tcp_rexmit_nxt = seg_ack;
14330 				}
14331 				if (seg_ack != tcp->tcp_rexmit_max) {
14332 					flags |= TH_XMIT_NEEDED;
14333 				}
14334 			} else {
14335 				tcp->tcp_rexmit = B_FALSE;
14336 				tcp->tcp_xmit_zc_clean = B_FALSE;
14337 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14338 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14339 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14340 			}
14341 			tcp->tcp_ms_we_have_waited = 0;
14342 		}
14343 	}
14344 
14345 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
14346 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
14347 	tcp->tcp_suna = seg_ack;
14348 	if (tcp->tcp_zero_win_probe != 0) {
14349 		tcp->tcp_zero_win_probe = 0;
14350 		tcp->tcp_timer_backoff = 0;
14351 	}
14352 
14353 	/*
14354 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14355 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14356 	 * will not reach here.
14357 	 */
14358 	if (mp1 == NULL) {
14359 		goto fin_acked;
14360 	}
14361 
14362 	/*
14363 	 * Update the congestion window.
14364 	 *
14365 	 * If TCP is not ECN capable or TCP is ECN capable but the
14366 	 * congestion experience bit is not set, increase the tcp_cwnd as
14367 	 * usual.
14368 	 */
14369 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14370 		cwnd = tcp->tcp_cwnd;
14371 		add = mss;
14372 
14373 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14374 			/*
14375 			 * This is to prevent an increase of less than 1 MSS of
14376 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14377 			 * may send out tinygrams in order to preserve mblk
14378 			 * boundaries.
14379 			 *
14380 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14381 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14382 			 * increased by 1 MSS for every RTTs.
14383 			 */
14384 			if (tcp->tcp_cwnd_cnt <= 0) {
14385 				tcp->tcp_cwnd_cnt = cwnd + add;
14386 			} else {
14387 				tcp->tcp_cwnd_cnt -= add;
14388 				add = 0;
14389 			}
14390 		}
14391 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14392 	}
14393 
14394 	/* See if the latest urgent data has been acknowledged */
14395 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14396 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14397 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14398 
14399 	/* Can we update the RTT estimates? */
14400 	if (tcp->tcp_snd_ts_ok) {
14401 		/* Ignore zero timestamp echo-reply. */
14402 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14403 			tcp_set_rto(tcp, (int32_t)lbolt -
14404 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14405 		}
14406 
14407 		/* If needed, restart the timer. */
14408 		if (tcp->tcp_set_timer == 1) {
14409 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14410 			tcp->tcp_set_timer = 0;
14411 		}
14412 		/*
14413 		 * Update tcp_csuna in case the other side stops sending
14414 		 * us timestamps.
14415 		 */
14416 		tcp->tcp_csuna = tcp->tcp_snxt;
14417 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14418 		/*
14419 		 * An ACK sequence we haven't seen before, so get the RTT
14420 		 * and update the RTO. But first check if the timestamp is
14421 		 * valid to use.
14422 		 */
14423 		if ((mp1->b_next != NULL) &&
14424 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14425 			tcp_set_rto(tcp, (int32_t)lbolt -
14426 			    (int32_t)(intptr_t)mp1->b_prev);
14427 		else
14428 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14429 
14430 		/* Remeber the last sequence to be ACKed */
14431 		tcp->tcp_csuna = seg_ack;
14432 		if (tcp->tcp_set_timer == 1) {
14433 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14434 			tcp->tcp_set_timer = 0;
14435 		}
14436 	} else {
14437 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14438 	}
14439 
14440 	/* Eat acknowledged bytes off the xmit queue. */
14441 	for (;;) {
14442 		mblk_t	*mp2;
14443 		uchar_t	*wptr;
14444 
14445 		wptr = mp1->b_wptr;
14446 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14447 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14448 		if (bytes_acked < 0) {
14449 			mp1->b_rptr = wptr + bytes_acked;
14450 			/*
14451 			 * Set a new timestamp if all the bytes timed by the
14452 			 * old timestamp have been ack'ed.
14453 			 */
14454 			if (SEQ_GT(seg_ack,
14455 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14456 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14457 				mp1->b_next = NULL;
14458 			}
14459 			break;
14460 		}
14461 		mp1->b_next = NULL;
14462 		mp1->b_prev = NULL;
14463 		mp2 = mp1;
14464 		mp1 = mp1->b_cont;
14465 
14466 		/*
14467 		 * This notification is required for some zero-copy
14468 		 * clients to maintain a copy semantic. After the data
14469 		 * is ack'ed, client is safe to modify or reuse the buffer.
14470 		 */
14471 		if (tcp->tcp_snd_zcopy_aware &&
14472 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14473 			tcp_zcopy_notify(tcp);
14474 		freeb(mp2);
14475 		if (bytes_acked == 0) {
14476 			if (mp1 == NULL) {
14477 				/* Everything is ack'ed, clear the tail. */
14478 				tcp->tcp_xmit_tail = NULL;
14479 				/*
14480 				 * Cancel the timer unless we are still
14481 				 * waiting for an ACK for the FIN packet.
14482 				 */
14483 				if (tcp->tcp_timer_tid != 0 &&
14484 				    tcp->tcp_snxt == tcp->tcp_suna) {
14485 					(void) TCP_TIMER_CANCEL(tcp,
14486 					    tcp->tcp_timer_tid);
14487 					tcp->tcp_timer_tid = 0;
14488 				}
14489 				goto pre_swnd_update;
14490 			}
14491 			if (mp2 != tcp->tcp_xmit_tail)
14492 				break;
14493 			tcp->tcp_xmit_tail = mp1;
14494 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14495 			    (uintptr_t)INT_MAX);
14496 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14497 			    mp1->b_rptr);
14498 			break;
14499 		}
14500 		if (mp1 == NULL) {
14501 			/*
14502 			 * More was acked but there is nothing more
14503 			 * outstanding.  This means that the FIN was
14504 			 * just acked or that we're talking to a clown.
14505 			 */
14506 fin_acked:
14507 			ASSERT(tcp->tcp_fin_sent);
14508 			tcp->tcp_xmit_tail = NULL;
14509 			if (tcp->tcp_fin_sent) {
14510 				/* FIN was acked - making progress */
14511 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14512 				    !tcp->tcp_fin_acked)
14513 					tcp->tcp_ip_forward_progress = B_TRUE;
14514 				tcp->tcp_fin_acked = B_TRUE;
14515 				if (tcp->tcp_linger_tid != 0 &&
14516 				    TCP_TIMER_CANCEL(tcp,
14517 					tcp->tcp_linger_tid) >= 0) {
14518 					tcp_stop_lingering(tcp);
14519 				}
14520 			} else {
14521 				/*
14522 				 * We should never get here because
14523 				 * we have already checked that the
14524 				 * number of bytes ack'ed should be
14525 				 * smaller than or equal to what we
14526 				 * have sent so far (it is the
14527 				 * acceptability check of the ACK).
14528 				 * We can only get here if the send
14529 				 * queue is corrupted.
14530 				 *
14531 				 * Terminate the connection and
14532 				 * panic the system.  It is better
14533 				 * for us to panic instead of
14534 				 * continuing to avoid other disaster.
14535 				 */
14536 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14537 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14538 				panic("Memory corruption "
14539 				    "detected for connection %s.",
14540 				    tcp_display(tcp, NULL,
14541 					DISP_ADDR_AND_PORT));
14542 				/*NOTREACHED*/
14543 			}
14544 			goto pre_swnd_update;
14545 		}
14546 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14547 	}
14548 	if (tcp->tcp_unsent) {
14549 		flags |= TH_XMIT_NEEDED;
14550 	}
14551 pre_swnd_update:
14552 	tcp->tcp_xmit_head = mp1;
14553 swnd_update:
14554 	/*
14555 	 * The following check is different from most other implementations.
14556 	 * For bi-directional transfer, when segments are dropped, the
14557 	 * "normal" check will not accept a window update in those
14558 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14559 	 * segments which are outside receiver's window.  As TCP accepts
14560 	 * the ack in those retransmitted segments, if the window update in
14561 	 * the same segment is not accepted, TCP will incorrectly calculates
14562 	 * that it can send more segments.  This can create a deadlock
14563 	 * with the receiver if its window becomes zero.
14564 	 */
14565 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14566 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14567 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14568 		/*
14569 		 * The criteria for update is:
14570 		 *
14571 		 * 1. the segment acknowledges some data.  Or
14572 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14573 		 * 3. the segment is not old and the advertised window is
14574 		 * larger than the previous advertised window.
14575 		 */
14576 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14577 			flags |= TH_XMIT_NEEDED;
14578 		tcp->tcp_swnd = new_swnd;
14579 		if (new_swnd > tcp->tcp_max_swnd)
14580 			tcp->tcp_max_swnd = new_swnd;
14581 		tcp->tcp_swl1 = seg_seq;
14582 		tcp->tcp_swl2 = seg_ack;
14583 	}
14584 est:
14585 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14586 
14587 		switch (tcp->tcp_state) {
14588 		case TCPS_FIN_WAIT_1:
14589 			if (tcp->tcp_fin_acked) {
14590 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14591 				/*
14592 				 * We implement the non-standard BSD/SunOS
14593 				 * FIN_WAIT_2 flushing algorithm.
14594 				 * If there is no user attached to this
14595 				 * TCP endpoint, then this TCP struct
14596 				 * could hang around forever in FIN_WAIT_2
14597 				 * state if the peer forgets to send us
14598 				 * a FIN.  To prevent this, we wait only
14599 				 * 2*MSL (a convenient time value) for
14600 				 * the FIN to arrive.  If it doesn't show up,
14601 				 * we flush the TCP endpoint.  This algorithm,
14602 				 * though a violation of RFC-793, has worked
14603 				 * for over 10 years in BSD systems.
14604 				 * Note: SunOS 4.x waits 675 seconds before
14605 				 * flushing the FIN_WAIT_2 connection.
14606 				 */
14607 				TCP_TIMER_RESTART(tcp,
14608 				    tcp_fin_wait_2_flush_interval);
14609 			}
14610 			break;
14611 		case TCPS_FIN_WAIT_2:
14612 			break;	/* Shutdown hook? */
14613 		case TCPS_LAST_ACK:
14614 			freemsg(mp);
14615 			if (tcp->tcp_fin_acked) {
14616 				(void) tcp_clean_death(tcp, 0, 19);
14617 				return;
14618 			}
14619 			goto xmit_check;
14620 		case TCPS_CLOSING:
14621 			if (tcp->tcp_fin_acked) {
14622 				tcp->tcp_state = TCPS_TIME_WAIT;
14623 				/*
14624 				 * Unconditionally clear the exclusive binding
14625 				 * bit so this TIME-WAIT connection won't
14626 				 * interfere with new ones.
14627 				 */
14628 				tcp->tcp_exclbind = 0;
14629 				if (!TCP_IS_DETACHED(tcp)) {
14630 					TCP_TIMER_RESTART(tcp,
14631 					    tcp_time_wait_interval);
14632 				} else {
14633 					tcp_time_wait_append(tcp);
14634 					TCP_DBGSTAT(tcp_rput_time_wait);
14635 				}
14636 			}
14637 			/*FALLTHRU*/
14638 		case TCPS_CLOSE_WAIT:
14639 			freemsg(mp);
14640 			goto xmit_check;
14641 		default:
14642 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14643 			break;
14644 		}
14645 	}
14646 	if (flags & TH_FIN) {
14647 		/* Make sure we ack the fin */
14648 		flags |= TH_ACK_NEEDED;
14649 		if (!tcp->tcp_fin_rcvd) {
14650 			tcp->tcp_fin_rcvd = B_TRUE;
14651 			tcp->tcp_rnxt++;
14652 			tcph = tcp->tcp_tcph;
14653 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14654 
14655 			/*
14656 			 * Generate the ordrel_ind at the end unless we
14657 			 * are an eager guy.
14658 			 * In the eager case tcp_rsrv will do this when run
14659 			 * after tcp_accept is done.
14660 			 */
14661 			if (tcp->tcp_listener == NULL &&
14662 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14663 				flags |= TH_ORDREL_NEEDED;
14664 			switch (tcp->tcp_state) {
14665 			case TCPS_SYN_RCVD:
14666 			case TCPS_ESTABLISHED:
14667 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14668 				/* Keepalive? */
14669 				break;
14670 			case TCPS_FIN_WAIT_1:
14671 				if (!tcp->tcp_fin_acked) {
14672 					tcp->tcp_state = TCPS_CLOSING;
14673 					break;
14674 				}
14675 				/* FALLTHRU */
14676 			case TCPS_FIN_WAIT_2:
14677 				tcp->tcp_state = TCPS_TIME_WAIT;
14678 				/*
14679 				 * Unconditionally clear the exclusive binding
14680 				 * bit so this TIME-WAIT connection won't
14681 				 * interfere with new ones.
14682 				 */
14683 				tcp->tcp_exclbind = 0;
14684 				if (!TCP_IS_DETACHED(tcp)) {
14685 					TCP_TIMER_RESTART(tcp,
14686 					    tcp_time_wait_interval);
14687 				} else {
14688 					tcp_time_wait_append(tcp);
14689 					TCP_DBGSTAT(tcp_rput_time_wait);
14690 				}
14691 				if (seg_len) {
14692 					/*
14693 					 * implies data piggybacked on FIN.
14694 					 * break to handle data.
14695 					 */
14696 					break;
14697 				}
14698 				freemsg(mp);
14699 				goto ack_check;
14700 			}
14701 		}
14702 	}
14703 	if (mp == NULL)
14704 		goto xmit_check;
14705 	if (seg_len == 0) {
14706 		freemsg(mp);
14707 		goto xmit_check;
14708 	}
14709 	if (mp->b_rptr == mp->b_wptr) {
14710 		/*
14711 		 * The header has been consumed, so we remove the
14712 		 * zero-length mblk here.
14713 		 */
14714 		mp1 = mp;
14715 		mp = mp->b_cont;
14716 		freeb(mp1);
14717 	}
14718 	tcph = tcp->tcp_tcph;
14719 	tcp->tcp_rack_cnt++;
14720 	{
14721 		uint32_t cur_max;
14722 
14723 		cur_max = tcp->tcp_rack_cur_max;
14724 		if (tcp->tcp_rack_cnt >= cur_max) {
14725 			/*
14726 			 * We have more unacked data than we should - send
14727 			 * an ACK now.
14728 			 */
14729 			flags |= TH_ACK_NEEDED;
14730 			cur_max++;
14731 			if (cur_max > tcp->tcp_rack_abs_max)
14732 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14733 			else
14734 				tcp->tcp_rack_cur_max = cur_max;
14735 		} else if (TCP_IS_DETACHED(tcp)) {
14736 			/* We don't have an ACK timer for detached TCP. */
14737 			flags |= TH_ACK_NEEDED;
14738 		} else if (seg_len < mss) {
14739 			/*
14740 			 * If we get a segment that is less than an mss, and we
14741 			 * already have unacknowledged data, and the amount
14742 			 * unacknowledged is not a multiple of mss, then we
14743 			 * better generate an ACK now.  Otherwise, this may be
14744 			 * the tail piece of a transaction, and we would rather
14745 			 * wait for the response.
14746 			 */
14747 			uint32_t udif;
14748 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14749 			    (uintptr_t)INT_MAX);
14750 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14751 			if (udif && (udif % mss))
14752 				flags |= TH_ACK_NEEDED;
14753 			else
14754 				flags |= TH_ACK_TIMER_NEEDED;
14755 		} else {
14756 			/* Start delayed ack timer */
14757 			flags |= TH_ACK_TIMER_NEEDED;
14758 		}
14759 	}
14760 	tcp->tcp_rnxt += seg_len;
14761 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14762 
14763 	/* Update SACK list */
14764 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14765 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14766 		    &(tcp->tcp_num_sack_blk));
14767 	}
14768 
14769 	if (tcp->tcp_urp_mp) {
14770 		tcp->tcp_urp_mp->b_cont = mp;
14771 		mp = tcp->tcp_urp_mp;
14772 		tcp->tcp_urp_mp = NULL;
14773 		/* Ready for a new signal. */
14774 		tcp->tcp_urp_last_valid = B_FALSE;
14775 #ifdef DEBUG
14776 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14777 		    "tcp_rput: sending exdata_ind %s",
14778 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14779 #endif /* DEBUG */
14780 	}
14781 
14782 	/*
14783 	 * Check for ancillary data changes compared to last segment.
14784 	 */
14785 	if (tcp->tcp_ipv6_recvancillary != 0) {
14786 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14787 		if (mp == NULL)
14788 			return;
14789 	}
14790 
14791 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14792 		/*
14793 		 * Side queue inbound data until the accept happens.
14794 		 * tcp_accept/tcp_rput drains this when the accept happens.
14795 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14796 		 * T_EXDATA_IND) it is queued on b_next.
14797 		 * XXX Make urgent data use this. Requires:
14798 		 *	Removing tcp_listener check for TH_URG
14799 		 *	Making M_PCPROTO and MARK messages skip the eager case
14800 		 */
14801 
14802 		if (tcp->tcp_kssl_pending) {
14803 			tcp_kssl_input(tcp, mp);
14804 		} else {
14805 			tcp_rcv_enqueue(tcp, mp, seg_len);
14806 		}
14807 	} else {
14808 		if (mp->b_datap->db_type != M_DATA ||
14809 		    (flags & TH_MARKNEXT_NEEDED)) {
14810 			if (tcp->tcp_rcv_list != NULL) {
14811 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14812 			}
14813 			ASSERT(tcp->tcp_rcv_list == NULL ||
14814 			    tcp->tcp_fused_sigurg);
14815 			if (flags & TH_MARKNEXT_NEEDED) {
14816 #ifdef DEBUG
14817 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14818 				    "tcp_rput: sending MSGMARKNEXT %s",
14819 				    tcp_display(tcp, NULL,
14820 				    DISP_PORT_ONLY));
14821 #endif /* DEBUG */
14822 				mp->b_flag |= MSGMARKNEXT;
14823 				flags &= ~TH_MARKNEXT_NEEDED;
14824 			}
14825 
14826 			/* Does this need SSL processing first? */
14827 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14828 			    (DB_TYPE(mp) == M_DATA)) {
14829 				tcp_kssl_input(tcp, mp);
14830 			} else {
14831 				putnext(tcp->tcp_rq, mp);
14832 				if (!canputnext(tcp->tcp_rq))
14833 					tcp->tcp_rwnd -= seg_len;
14834 			}
14835 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14836 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
14837 			if (tcp->tcp_rcv_list != NULL) {
14838 				/*
14839 				 * Enqueue the new segment first and then
14840 				 * call tcp_rcv_drain() to send all data
14841 				 * up.  The other way to do this is to
14842 				 * send all queued data up and then call
14843 				 * putnext() to send the new segment up.
14844 				 * This way can remove the else part later
14845 				 * on.
14846 				 *
14847 				 * We don't this to avoid one more call to
14848 				 * canputnext() as tcp_rcv_drain() needs to
14849 				 * call canputnext().
14850 				 */
14851 				tcp_rcv_enqueue(tcp, mp, seg_len);
14852 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14853 			} else {
14854 				/* Does this need SSL processing first? */
14855 				if ((tcp->tcp_kssl_ctx  != NULL) &&
14856 				    (DB_TYPE(mp) == M_DATA)) {
14857 					tcp_kssl_input(tcp, mp);
14858 				} else {
14859 					putnext(tcp->tcp_rq, mp);
14860 					if (!canputnext(tcp->tcp_rq))
14861 						tcp->tcp_rwnd -= seg_len;
14862 				}
14863 			}
14864 		} else {
14865 			/*
14866 			 * Enqueue all packets when processing an mblk
14867 			 * from the co queue and also enqueue normal packets.
14868 			 */
14869 			tcp_rcv_enqueue(tcp, mp, seg_len);
14870 		}
14871 		/*
14872 		 * Make sure the timer is running if we have data waiting
14873 		 * for a push bit. This provides resiliency against
14874 		 * implementations that do not correctly generate push bits.
14875 		 */
14876 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
14877 			/*
14878 			 * The connection may be closed at this point, so don't
14879 			 * do anything for a detached tcp.
14880 			 */
14881 			if (!TCP_IS_DETACHED(tcp))
14882 				tcp->tcp_push_tid = TCP_TIMER(tcp,
14883 				    tcp_push_timer,
14884 				    MSEC_TO_TICK(tcp_push_timer_interval));
14885 		}
14886 	}
14887 xmit_check:
14888 	/* Is there anything left to do? */
14889 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14890 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
14891 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
14892 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14893 		goto done;
14894 
14895 	/* Any transmit work to do and a non-zero window? */
14896 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
14897 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
14898 		if (flags & TH_REXMIT_NEEDED) {
14899 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
14900 
14901 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
14902 			if (snd_size > mss)
14903 				snd_size = mss;
14904 			if (snd_size > tcp->tcp_swnd)
14905 				snd_size = tcp->tcp_swnd;
14906 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
14907 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
14908 			    B_TRUE);
14909 
14910 			if (mp1 != NULL) {
14911 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14912 				tcp->tcp_csuna = tcp->tcp_snxt;
14913 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
14914 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
14915 				TCP_RECORD_TRACE(tcp, mp1,
14916 				    TCP_TRACE_SEND_PKT);
14917 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
14918 			}
14919 		}
14920 		if (flags & TH_NEED_SACK_REXMIT) {
14921 			tcp_sack_rxmit(tcp, &flags);
14922 		}
14923 		/*
14924 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
14925 		 * out new segment.  Note that tcp_rexmit should not be
14926 		 * set, otherwise TH_LIMIT_XMIT should not be set.
14927 		 */
14928 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
14929 			if (!tcp->tcp_rexmit) {
14930 				tcp_wput_data(tcp, NULL, B_FALSE);
14931 			} else {
14932 				tcp_ss_rexmit(tcp);
14933 			}
14934 		}
14935 		/*
14936 		 * Adjust tcp_cwnd back to normal value after sending
14937 		 * new data segments.
14938 		 */
14939 		if (flags & TH_LIMIT_XMIT) {
14940 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
14941 			/*
14942 			 * This will restart the timer.  Restarting the
14943 			 * timer is used to avoid a timeout before the
14944 			 * limited transmitted segment's ACK gets back.
14945 			 */
14946 			if (tcp->tcp_xmit_head != NULL)
14947 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14948 		}
14949 
14950 		/* Anything more to do? */
14951 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
14952 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14953 			goto done;
14954 	}
14955 ack_check:
14956 	if (flags & TH_SEND_URP_MARK) {
14957 		ASSERT(tcp->tcp_urp_mark_mp);
14958 		/*
14959 		 * Send up any queued data and then send the mark message
14960 		 */
14961 		if (tcp->tcp_rcv_list != NULL) {
14962 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14963 		}
14964 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14965 
14966 		mp1 = tcp->tcp_urp_mark_mp;
14967 		tcp->tcp_urp_mark_mp = NULL;
14968 #ifdef DEBUG
14969 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14970 		    "tcp_rput: sending zero-length %s %s",
14971 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
14972 		    "MSGNOTMARKNEXT"),
14973 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14974 #endif /* DEBUG */
14975 		putnext(tcp->tcp_rq, mp1);
14976 		flags &= ~TH_SEND_URP_MARK;
14977 	}
14978 	if (flags & TH_ACK_NEEDED) {
14979 		/*
14980 		 * Time to send an ack for some reason.
14981 		 */
14982 		mp1 = tcp_ack_mp(tcp);
14983 
14984 		if (mp1 != NULL) {
14985 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
14986 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
14987 			BUMP_LOCAL(tcp->tcp_obsegs);
14988 			BUMP_MIB(&tcp_mib, tcpOutAck);
14989 		}
14990 		if (tcp->tcp_ack_tid != 0) {
14991 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
14992 			tcp->tcp_ack_tid = 0;
14993 		}
14994 	}
14995 	if (flags & TH_ACK_TIMER_NEEDED) {
14996 		/*
14997 		 * Arrange for deferred ACK or push wait timeout.
14998 		 * Start timer if it is not already running.
14999 		 */
15000 		if (tcp->tcp_ack_tid == 0) {
15001 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15002 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15003 			    (clock_t)tcp_local_dack_interval :
15004 			    (clock_t)tcp_deferred_ack_interval));
15005 		}
15006 	}
15007 	if (flags & TH_ORDREL_NEEDED) {
15008 		/*
15009 		 * Send up the ordrel_ind unless we are an eager guy.
15010 		 * In the eager case tcp_rsrv will do this when run
15011 		 * after tcp_accept is done.
15012 		 */
15013 		ASSERT(tcp->tcp_listener == NULL);
15014 		if (tcp->tcp_rcv_list != NULL) {
15015 			/*
15016 			 * Push any mblk(s) enqueued from co processing.
15017 			 */
15018 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15019 		}
15020 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15021 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
15022 			tcp->tcp_ordrel_done = B_TRUE;
15023 			putnext(tcp->tcp_rq, mp1);
15024 			if (tcp->tcp_deferred_clean_death) {
15025 				/*
15026 				 * tcp_clean_death was deferred
15027 				 * for T_ORDREL_IND - do it now
15028 				 */
15029 				(void) tcp_clean_death(tcp,
15030 				    tcp->tcp_client_errno, 20);
15031 				tcp->tcp_deferred_clean_death =	B_FALSE;
15032 			}
15033 		} else {
15034 			/*
15035 			 * Run the orderly release in the
15036 			 * service routine.
15037 			 */
15038 			qenable(tcp->tcp_rq);
15039 			/*
15040 			 * Caveat(XXX): The machine may be so
15041 			 * overloaded that tcp_rsrv() is not scheduled
15042 			 * until after the endpoint has transitioned
15043 			 * to TCPS_TIME_WAIT
15044 			 * and tcp_time_wait_interval expires. Then
15045 			 * tcp_timer() will blow away state in tcp_t
15046 			 * and T_ORDREL_IND will never be delivered
15047 			 * upstream. Unlikely but potentially
15048 			 * a problem.
15049 			 */
15050 		}
15051 	}
15052 done:
15053 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15054 }
15055 
15056 /*
15057  * This function does PAWS protection check. Returns B_TRUE if the
15058  * segment passes the PAWS test, else returns B_FALSE.
15059  */
15060 boolean_t
15061 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15062 {
15063 	uint8_t	flags;
15064 	int	options;
15065 	uint8_t *up;
15066 
15067 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15068 	/*
15069 	 * If timestamp option is aligned nicely, get values inline,
15070 	 * otherwise call general routine to parse.  Only do that
15071 	 * if timestamp is the only option.
15072 	 */
15073 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15074 	    TCPOPT_REAL_TS_LEN &&
15075 	    OK_32PTR((up = ((uint8_t *)tcph) +
15076 	    TCP_MIN_HEADER_LENGTH)) &&
15077 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15078 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15079 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15080 
15081 		options = TCP_OPT_TSTAMP_PRESENT;
15082 	} else {
15083 		if (tcp->tcp_snd_sack_ok) {
15084 			tcpoptp->tcp = tcp;
15085 		} else {
15086 			tcpoptp->tcp = NULL;
15087 		}
15088 		options = tcp_parse_options(tcph, tcpoptp);
15089 	}
15090 
15091 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15092 		/*
15093 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15094 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15095 		 */
15096 		if ((flags & TH_RST) == 0 &&
15097 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15098 		    tcp->tcp_ts_recent)) {
15099 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15100 			    PAWS_TIMEOUT)) {
15101 				/* This segment is not acceptable. */
15102 				return (B_FALSE);
15103 			} else {
15104 				/*
15105 				 * Connection has been idle for
15106 				 * too long.  Reset the timestamp
15107 				 * and assume the segment is valid.
15108 				 */
15109 				tcp->tcp_ts_recent =
15110 				    tcpoptp->tcp_opt_ts_val;
15111 			}
15112 		}
15113 	} else {
15114 		/*
15115 		 * If we don't get a timestamp on every packet, we
15116 		 * figure we can't really trust 'em, so we stop sending
15117 		 * and parsing them.
15118 		 */
15119 		tcp->tcp_snd_ts_ok = B_FALSE;
15120 
15121 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15122 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15123 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15124 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
15125 		if (tcp->tcp_snd_sack_ok) {
15126 			ASSERT(tcp->tcp_sack_info != NULL);
15127 			tcp->tcp_max_sack_blk = 4;
15128 		}
15129 	}
15130 	return (B_TRUE);
15131 }
15132 
15133 /*
15134  * Attach ancillary data to a received TCP segments for the
15135  * ancillary pieces requested by the application that are
15136  * different than they were in the previous data segment.
15137  *
15138  * Save the "current" values once memory allocation is ok so that
15139  * when memory allocation fails we can just wait for the next data segment.
15140  */
15141 static mblk_t *
15142 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15143 {
15144 	struct T_optdata_ind *todi;
15145 	int optlen;
15146 	uchar_t *optptr;
15147 	struct T_opthdr *toh;
15148 	uint_t addflag;	/* Which pieces to add */
15149 	mblk_t *mp1;
15150 
15151 	optlen = 0;
15152 	addflag = 0;
15153 	/* If app asked for pktinfo and the index has changed ... */
15154 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15155 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15156 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15157 		optlen += sizeof (struct T_opthdr) +
15158 		    sizeof (struct in6_pktinfo);
15159 		addflag |= TCP_IPV6_RECVPKTINFO;
15160 	}
15161 	/* If app asked for hoplimit and it has changed ... */
15162 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15163 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15164 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15165 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15166 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15167 	}
15168 	/* If app asked for tclass and it has changed ... */
15169 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15170 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15171 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15172 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15173 		addflag |= TCP_IPV6_RECVTCLASS;
15174 	}
15175 	/*
15176 	 * If app asked for hopbyhop headers and it has changed ...
15177 	 * For security labels, note that (1) security labels can't change on
15178 	 * a connected socket at all, (2) we're connected to at most one peer,
15179 	 * (3) if anything changes, then it must be some other extra option.
15180 	 */
15181 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15182 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15183 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15184 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15185 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15186 		    tcp->tcp_label_len;
15187 		addflag |= TCP_IPV6_RECVHOPOPTS;
15188 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15189 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15190 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15191 			return (mp);
15192 	}
15193 	/* If app asked for dst headers before routing headers ... */
15194 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15195 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15196 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
15197 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15198 		optlen += sizeof (struct T_opthdr) +
15199 		    ipp->ipp_rtdstoptslen;
15200 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15201 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15202 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15203 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15204 			return (mp);
15205 	}
15206 	/* If app asked for routing headers and it has changed ... */
15207 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15208 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15209 	    (ipp->ipp_fields & IPPF_RTHDR),
15210 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15211 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15212 		addflag |= TCP_IPV6_RECVRTHDR;
15213 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15214 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15215 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15216 			return (mp);
15217 	}
15218 	/* If app asked for dest headers and it has changed ... */
15219 	if ((tcp->tcp_ipv6_recvancillary &
15220 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15221 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15222 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15223 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15224 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15225 		addflag |= TCP_IPV6_RECVDSTOPTS;
15226 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15227 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15228 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15229 			return (mp);
15230 	}
15231 
15232 	if (optlen == 0) {
15233 		/* Nothing to add */
15234 		return (mp);
15235 	}
15236 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15237 	if (mp1 == NULL) {
15238 		/*
15239 		 * Defer sending ancillary data until the next TCP segment
15240 		 * arrives.
15241 		 */
15242 		return (mp);
15243 	}
15244 	mp1->b_cont = mp;
15245 	mp = mp1;
15246 	mp->b_wptr += sizeof (*todi) + optlen;
15247 	mp->b_datap->db_type = M_PROTO;
15248 	todi = (struct T_optdata_ind *)mp->b_rptr;
15249 	todi->PRIM_type = T_OPTDATA_IND;
15250 	todi->DATA_flag = 1;	/* MORE data */
15251 	todi->OPT_length = optlen;
15252 	todi->OPT_offset = sizeof (*todi);
15253 	optptr = (uchar_t *)&todi[1];
15254 	/*
15255 	 * If app asked for pktinfo and the index has changed ...
15256 	 * Note that the local address never changes for the connection.
15257 	 */
15258 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15259 		struct in6_pktinfo *pkti;
15260 
15261 		toh = (struct T_opthdr *)optptr;
15262 		toh->level = IPPROTO_IPV6;
15263 		toh->name = IPV6_PKTINFO;
15264 		toh->len = sizeof (*toh) + sizeof (*pkti);
15265 		toh->status = 0;
15266 		optptr += sizeof (*toh);
15267 		pkti = (struct in6_pktinfo *)optptr;
15268 		if (tcp->tcp_ipversion == IPV6_VERSION)
15269 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15270 		else
15271 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15272 			    &pkti->ipi6_addr);
15273 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15274 		optptr += sizeof (*pkti);
15275 		ASSERT(OK_32PTR(optptr));
15276 		/* Save as "last" value */
15277 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15278 	}
15279 	/* If app asked for hoplimit and it has changed ... */
15280 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15281 		toh = (struct T_opthdr *)optptr;
15282 		toh->level = IPPROTO_IPV6;
15283 		toh->name = IPV6_HOPLIMIT;
15284 		toh->len = sizeof (*toh) + sizeof (uint_t);
15285 		toh->status = 0;
15286 		optptr += sizeof (*toh);
15287 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15288 		optptr += sizeof (uint_t);
15289 		ASSERT(OK_32PTR(optptr));
15290 		/* Save as "last" value */
15291 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15292 	}
15293 	/* If app asked for tclass and it has changed ... */
15294 	if (addflag & TCP_IPV6_RECVTCLASS) {
15295 		toh = (struct T_opthdr *)optptr;
15296 		toh->level = IPPROTO_IPV6;
15297 		toh->name = IPV6_TCLASS;
15298 		toh->len = sizeof (*toh) + sizeof (uint_t);
15299 		toh->status = 0;
15300 		optptr += sizeof (*toh);
15301 		*(uint_t *)optptr = ipp->ipp_tclass;
15302 		optptr += sizeof (uint_t);
15303 		ASSERT(OK_32PTR(optptr));
15304 		/* Save as "last" value */
15305 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15306 	}
15307 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15308 		toh = (struct T_opthdr *)optptr;
15309 		toh->level = IPPROTO_IPV6;
15310 		toh->name = IPV6_HOPOPTS;
15311 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15312 		    tcp->tcp_label_len;
15313 		toh->status = 0;
15314 		optptr += sizeof (*toh);
15315 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15316 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15317 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15318 		ASSERT(OK_32PTR(optptr));
15319 		/* Save as last value */
15320 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15321 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15322 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15323 	}
15324 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15325 		toh = (struct T_opthdr *)optptr;
15326 		toh->level = IPPROTO_IPV6;
15327 		toh->name = IPV6_RTHDRDSTOPTS;
15328 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15329 		toh->status = 0;
15330 		optptr += sizeof (*toh);
15331 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15332 		optptr += ipp->ipp_rtdstoptslen;
15333 		ASSERT(OK_32PTR(optptr));
15334 		/* Save as last value */
15335 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15336 		    &tcp->tcp_rtdstoptslen,
15337 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15338 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15339 	}
15340 	if (addflag & TCP_IPV6_RECVRTHDR) {
15341 		toh = (struct T_opthdr *)optptr;
15342 		toh->level = IPPROTO_IPV6;
15343 		toh->name = IPV6_RTHDR;
15344 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15345 		toh->status = 0;
15346 		optptr += sizeof (*toh);
15347 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15348 		optptr += ipp->ipp_rthdrlen;
15349 		ASSERT(OK_32PTR(optptr));
15350 		/* Save as last value */
15351 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15352 		    (ipp->ipp_fields & IPPF_RTHDR),
15353 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15354 	}
15355 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15356 		toh = (struct T_opthdr *)optptr;
15357 		toh->level = IPPROTO_IPV6;
15358 		toh->name = IPV6_DSTOPTS;
15359 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15360 		toh->status = 0;
15361 		optptr += sizeof (*toh);
15362 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15363 		optptr += ipp->ipp_dstoptslen;
15364 		ASSERT(OK_32PTR(optptr));
15365 		/* Save as last value */
15366 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15367 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15368 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15369 	}
15370 	ASSERT(optptr == mp->b_wptr);
15371 	return (mp);
15372 }
15373 
15374 
15375 /*
15376  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15377  * or a "bad" IRE detected by tcp_adapt_ire.
15378  * We can't tell if the failure was due to the laddr or the faddr
15379  * thus we clear out all addresses and ports.
15380  */
15381 static void
15382 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15383 {
15384 	queue_t	*q = tcp->tcp_rq;
15385 	tcph_t	*tcph;
15386 	struct T_error_ack *tea;
15387 	conn_t	*connp = tcp->tcp_connp;
15388 
15389 
15390 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15391 
15392 	if (mp->b_cont) {
15393 		freemsg(mp->b_cont);
15394 		mp->b_cont = NULL;
15395 	}
15396 	tea = (struct T_error_ack *)mp->b_rptr;
15397 	switch (tea->PRIM_type) {
15398 	case T_BIND_ACK:
15399 		/*
15400 		 * Need to unbind with classifier since we were just told that
15401 		 * our bind succeeded.
15402 		 */
15403 		tcp->tcp_hard_bound = B_FALSE;
15404 		tcp->tcp_hard_binding = B_FALSE;
15405 
15406 		ipcl_hash_remove(connp);
15407 		/* Reuse the mblk if possible */
15408 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15409 			sizeof (*tea));
15410 		mp->b_rptr = mp->b_datap->db_base;
15411 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15412 		tea = (struct T_error_ack *)mp->b_rptr;
15413 		tea->PRIM_type = T_ERROR_ACK;
15414 		tea->TLI_error = TSYSERR;
15415 		tea->UNIX_error = error;
15416 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15417 			tea->ERROR_prim = T_CONN_REQ;
15418 		} else {
15419 			tea->ERROR_prim = O_T_BIND_REQ;
15420 		}
15421 		break;
15422 
15423 	case T_ERROR_ACK:
15424 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15425 			tea->ERROR_prim = T_CONN_REQ;
15426 		break;
15427 	default:
15428 		panic("tcp_bind_failed: unexpected TPI type");
15429 		/*NOTREACHED*/
15430 	}
15431 
15432 	tcp->tcp_state = TCPS_IDLE;
15433 	if (tcp->tcp_ipversion == IPV4_VERSION)
15434 		tcp->tcp_ipha->ipha_src = 0;
15435 	else
15436 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15437 	/*
15438 	 * Copy of the src addr. in tcp_t is needed since
15439 	 * the lookup funcs. can only look at tcp_t
15440 	 */
15441 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15442 
15443 	tcph = tcp->tcp_tcph;
15444 	tcph->th_lport[0] = 0;
15445 	tcph->th_lport[1] = 0;
15446 	tcp_bind_hash_remove(tcp);
15447 	bzero(&connp->u_port, sizeof (connp->u_port));
15448 	/* blow away saved option results if any */
15449 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15450 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15451 
15452 	conn_delete_ire(tcp->tcp_connp, NULL);
15453 	putnext(q, mp);
15454 }
15455 
15456 /*
15457  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15458  * messages.
15459  */
15460 void
15461 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15462 {
15463 	mblk_t	*mp1;
15464 	uchar_t	*rptr = mp->b_rptr;
15465 	queue_t	*q = tcp->tcp_rq;
15466 	struct T_error_ack *tea;
15467 	uint32_t mss;
15468 	mblk_t *syn_mp;
15469 	mblk_t *mdti;
15470 	mblk_t *lsoi;
15471 	int	retval;
15472 	mblk_t *ire_mp;
15473 
15474 	switch (mp->b_datap->db_type) {
15475 	case M_PROTO:
15476 	case M_PCPROTO:
15477 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15478 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15479 			break;
15480 		tea = (struct T_error_ack *)rptr;
15481 		switch (tea->PRIM_type) {
15482 		case T_BIND_ACK:
15483 			/*
15484 			 * Adapt Multidata information, if any.  The
15485 			 * following tcp_mdt_update routine will free
15486 			 * the message.
15487 			 */
15488 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15489 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15490 				    b_rptr)->mdt_capab, B_TRUE);
15491 				freemsg(mdti);
15492 			}
15493 
15494 			/*
15495 			 * Check to update LSO information with tcp, and
15496 			 * tcp_lso_update routine will free the message.
15497 			 */
15498 			if ((lsoi = tcp_lso_info_mp(mp)) != NULL) {
15499 				tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
15500 				    b_rptr)->lso_capab);
15501 				freemsg(lsoi);
15502 			}
15503 
15504 			/* Get the IRE, if we had requested for it */
15505 			ire_mp = tcp_ire_mp(mp);
15506 
15507 			if (tcp->tcp_hard_binding) {
15508 				tcp->tcp_hard_binding = B_FALSE;
15509 				tcp->tcp_hard_bound = B_TRUE;
15510 				CL_INET_CONNECT(tcp);
15511 			} else {
15512 				if (ire_mp != NULL)
15513 					freeb(ire_mp);
15514 				goto after_syn_sent;
15515 			}
15516 
15517 			retval = tcp_adapt_ire(tcp, ire_mp);
15518 			if (ire_mp != NULL)
15519 				freeb(ire_mp);
15520 			if (retval == 0) {
15521 				tcp_bind_failed(tcp, mp,
15522 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15523 				    ENETUNREACH : EADDRNOTAVAIL));
15524 				return;
15525 			}
15526 			/*
15527 			 * Don't let an endpoint connect to itself.
15528 			 * Also checked in tcp_connect() but that
15529 			 * check can't handle the case when the
15530 			 * local IP address is INADDR_ANY.
15531 			 */
15532 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15533 				if ((tcp->tcp_ipha->ipha_dst ==
15534 				    tcp->tcp_ipha->ipha_src) &&
15535 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15536 				    tcp->tcp_tcph->th_fport))) {
15537 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15538 					return;
15539 				}
15540 			} else {
15541 				if (IN6_ARE_ADDR_EQUAL(
15542 				    &tcp->tcp_ip6h->ip6_dst,
15543 				    &tcp->tcp_ip6h->ip6_src) &&
15544 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15545 				    tcp->tcp_tcph->th_fport))) {
15546 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15547 					return;
15548 				}
15549 			}
15550 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15551 			/*
15552 			 * This should not be possible!  Just for
15553 			 * defensive coding...
15554 			 */
15555 			if (tcp->tcp_state != TCPS_SYN_SENT)
15556 				goto after_syn_sent;
15557 
15558 			if (is_system_labeled() &&
15559 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
15560 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
15561 				return;
15562 			}
15563 
15564 			ASSERT(q == tcp->tcp_rq);
15565 			/*
15566 			 * tcp_adapt_ire() does not adjust
15567 			 * for TCP/IP header length.
15568 			 */
15569 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15570 
15571 			/*
15572 			 * Just make sure our rwnd is at
15573 			 * least tcp_recv_hiwat_mss * MSS
15574 			 * large, and round up to the nearest
15575 			 * MSS.
15576 			 *
15577 			 * We do the round up here because
15578 			 * we need to get the interface
15579 			 * MTU first before we can do the
15580 			 * round up.
15581 			 */
15582 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15583 			    tcp_recv_hiwat_minmss * mss);
15584 			q->q_hiwat = tcp->tcp_rwnd;
15585 			tcp_set_ws_value(tcp);
15586 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15587 			    tcp->tcp_tcph->th_win);
15588 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
15589 				tcp->tcp_snd_ws_ok = B_TRUE;
15590 
15591 			/*
15592 			 * Set tcp_snd_ts_ok to true
15593 			 * so that tcp_xmit_mp will
15594 			 * include the timestamp
15595 			 * option in the SYN segment.
15596 			 */
15597 			if (tcp_tstamp_always ||
15598 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
15599 				tcp->tcp_snd_ts_ok = B_TRUE;
15600 			}
15601 
15602 			/*
15603 			 * tcp_snd_sack_ok can be set in
15604 			 * tcp_adapt_ire() if the sack metric
15605 			 * is set.  So check it here also.
15606 			 */
15607 			if (tcp_sack_permitted == 2 ||
15608 			    tcp->tcp_snd_sack_ok) {
15609 				if (tcp->tcp_sack_info == NULL) {
15610 					tcp->tcp_sack_info =
15611 					kmem_cache_alloc(tcp_sack_info_cache,
15612 					    KM_SLEEP);
15613 				}
15614 				tcp->tcp_snd_sack_ok = B_TRUE;
15615 			}
15616 
15617 			/*
15618 			 * Should we use ECN?  Note that the current
15619 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15620 			 * is 1.  The reason for doing this is that there
15621 			 * are equipments out there that will drop ECN
15622 			 * enabled IP packets.  Setting it to 1 avoids
15623 			 * compatibility problems.
15624 			 */
15625 			if (tcp_ecn_permitted == 2)
15626 				tcp->tcp_ecn_ok = B_TRUE;
15627 
15628 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15629 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15630 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15631 			if (syn_mp) {
15632 				cred_t *cr;
15633 				pid_t pid;
15634 
15635 				/*
15636 				 * Obtain the credential from the
15637 				 * thread calling connect(); the credential
15638 				 * lives on in the second mblk which
15639 				 * originated from T_CONN_REQ and is echoed
15640 				 * with the T_BIND_ACK from ip.  If none
15641 				 * can be found, default to the creator
15642 				 * of the socket.
15643 				 */
15644 				if (mp->b_cont == NULL ||
15645 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15646 					cr = tcp->tcp_cred;
15647 					pid = tcp->tcp_cpid;
15648 				} else {
15649 					pid = DB_CPID(mp->b_cont);
15650 				}
15651 
15652 				TCP_RECORD_TRACE(tcp, syn_mp,
15653 				    TCP_TRACE_SEND_PKT);
15654 				mblk_setcred(syn_mp, cr);
15655 				DB_CPID(syn_mp) = pid;
15656 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15657 			}
15658 		after_syn_sent:
15659 			/*
15660 			 * A trailer mblk indicates a waiting client upstream.
15661 			 * We complete here the processing begun in
15662 			 * either tcp_bind() or tcp_connect() by passing
15663 			 * upstream the reply message they supplied.
15664 			 */
15665 			mp1 = mp;
15666 			mp = mp->b_cont;
15667 			freeb(mp1);
15668 			if (mp)
15669 				break;
15670 			return;
15671 		case T_ERROR_ACK:
15672 			if (tcp->tcp_debug) {
15673 				(void) strlog(TCP_MOD_ID, 0, 1,
15674 				    SL_TRACE|SL_ERROR,
15675 				    "tcp_rput_other: case T_ERROR_ACK, "
15676 				    "ERROR_prim == %d",
15677 				    tea->ERROR_prim);
15678 			}
15679 			switch (tea->ERROR_prim) {
15680 			case O_T_BIND_REQ:
15681 			case T_BIND_REQ:
15682 				tcp_bind_failed(tcp, mp,
15683 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15684 				    ENETUNREACH : EADDRNOTAVAIL));
15685 				return;
15686 			case T_UNBIND_REQ:
15687 				tcp->tcp_hard_binding = B_FALSE;
15688 				tcp->tcp_hard_bound = B_FALSE;
15689 				if (mp->b_cont) {
15690 					freemsg(mp->b_cont);
15691 					mp->b_cont = NULL;
15692 				}
15693 				if (tcp->tcp_unbind_pending)
15694 					tcp->tcp_unbind_pending = 0;
15695 				else {
15696 					/* From tcp_ip_unbind() - free */
15697 					freemsg(mp);
15698 					return;
15699 				}
15700 				break;
15701 			case T_SVR4_OPTMGMT_REQ:
15702 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15703 					/* T_OPTMGMT_REQ generated by TCP */
15704 					printf("T_SVR4_OPTMGMT_REQ failed "
15705 					    "%d/%d - dropped (cnt %d)\n",
15706 					    tea->TLI_error, tea->UNIX_error,
15707 					    tcp->tcp_drop_opt_ack_cnt);
15708 					freemsg(mp);
15709 					tcp->tcp_drop_opt_ack_cnt--;
15710 					return;
15711 				}
15712 				break;
15713 			}
15714 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15715 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15716 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15717 				    "- dropped (cnt %d)\n",
15718 				    tea->TLI_error, tea->UNIX_error,
15719 				    tcp->tcp_drop_opt_ack_cnt);
15720 				freemsg(mp);
15721 				tcp->tcp_drop_opt_ack_cnt--;
15722 				return;
15723 			}
15724 			break;
15725 		case T_OPTMGMT_ACK:
15726 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15727 				/* T_OPTMGMT_REQ generated by TCP */
15728 				freemsg(mp);
15729 				tcp->tcp_drop_opt_ack_cnt--;
15730 				return;
15731 			}
15732 			break;
15733 		default:
15734 			break;
15735 		}
15736 		break;
15737 	case M_FLUSH:
15738 		if (*rptr & FLUSHR)
15739 			flushq(q, FLUSHDATA);
15740 		break;
15741 	default:
15742 		/* M_CTL will be directly sent to tcp_icmp_error() */
15743 		ASSERT(DB_TYPE(mp) != M_CTL);
15744 		break;
15745 	}
15746 	/*
15747 	 * Make sure we set this bit before sending the ACK for
15748 	 * bind. Otherwise accept could possibly run and free
15749 	 * this tcp struct.
15750 	 */
15751 	putnext(q, mp);
15752 }
15753 
15754 /*
15755  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15756  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15757  * tcp_rsrv() try again.
15758  */
15759 static void
15760 tcp_ordrel_kick(void *arg)
15761 {
15762 	conn_t 	*connp = (conn_t *)arg;
15763 	tcp_t	*tcp = connp->conn_tcp;
15764 
15765 	tcp->tcp_ordrelid = 0;
15766 	tcp->tcp_timeout = B_FALSE;
15767 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15768 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15769 		qenable(tcp->tcp_rq);
15770 	}
15771 }
15772 
15773 /* ARGSUSED */
15774 static void
15775 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15776 {
15777 	conn_t	*connp = (conn_t *)arg;
15778 	tcp_t	*tcp = connp->conn_tcp;
15779 	queue_t	*q = tcp->tcp_rq;
15780 	uint_t	thwin;
15781 
15782 	freeb(mp);
15783 
15784 	TCP_STAT(tcp_rsrv_calls);
15785 
15786 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15787 		return;
15788 	}
15789 
15790 	if (tcp->tcp_fused) {
15791 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15792 
15793 		ASSERT(tcp->tcp_fused);
15794 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15795 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15796 		ASSERT(!TCP_IS_DETACHED(tcp));
15797 		ASSERT(tcp->tcp_connp->conn_sqp ==
15798 		    peer_tcp->tcp_connp->conn_sqp);
15799 
15800 		/*
15801 		 * Normally we would not get backenabled in synchronous
15802 		 * streams mode, but in case this happens, we need to plug
15803 		 * synchronous streams during our drain to prevent a race
15804 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15805 		 */
15806 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15807 		if (tcp->tcp_rcv_list != NULL)
15808 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15809 
15810 		tcp_clrqfull(peer_tcp);
15811 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15812 		TCP_STAT(tcp_fusion_backenabled);
15813 		return;
15814 	}
15815 
15816 	if (canputnext(q)) {
15817 		tcp->tcp_rwnd = q->q_hiwat;
15818 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15819 		    << tcp->tcp_rcv_ws;
15820 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15821 		/*
15822 		 * Send back a window update immediately if TCP is above
15823 		 * ESTABLISHED state and the increase of the rcv window
15824 		 * that the other side knows is at least 1 MSS after flow
15825 		 * control is lifted.
15826 		 */
15827 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15828 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15829 			tcp_xmit_ctl(NULL, tcp,
15830 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15831 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15832 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
15833 		}
15834 	}
15835 	/* Handle a failure to allocate a T_ORDREL_IND here */
15836 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15837 		ASSERT(tcp->tcp_listener == NULL);
15838 		if (tcp->tcp_rcv_list != NULL) {
15839 			(void) tcp_rcv_drain(q, tcp);
15840 		}
15841 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15842 		mp = mi_tpi_ordrel_ind();
15843 		if (mp) {
15844 			tcp->tcp_ordrel_done = B_TRUE;
15845 			putnext(q, mp);
15846 			if (tcp->tcp_deferred_clean_death) {
15847 				/*
15848 				 * tcp_clean_death was deferred for
15849 				 * T_ORDREL_IND - do it now
15850 				 */
15851 				tcp->tcp_deferred_clean_death = B_FALSE;
15852 				(void) tcp_clean_death(tcp,
15853 				    tcp->tcp_client_errno, 22);
15854 			}
15855 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15856 			/*
15857 			 * If there isn't already a timer running
15858 			 * start one.  Use a 4 second
15859 			 * timer as a fallback since it can't fail.
15860 			 */
15861 			tcp->tcp_timeout = B_TRUE;
15862 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15863 			    MSEC_TO_TICK(4000));
15864 		}
15865 	}
15866 }
15867 
15868 /*
15869  * The read side service routine is called mostly when we get back-enabled as a
15870  * result of flow control relief.  Since we don't actually queue anything in
15871  * TCP, we have no data to send out of here.  What we do is clear the receive
15872  * window, and send out a window update.
15873  * This routine is also called to drive an orderly release message upstream
15874  * if the attempt in tcp_rput failed.
15875  */
15876 static void
15877 tcp_rsrv(queue_t *q)
15878 {
15879 	conn_t *connp = Q_TO_CONN(q);
15880 	tcp_t	*tcp = connp->conn_tcp;
15881 	mblk_t	*mp;
15882 
15883 	/* No code does a putq on the read side */
15884 	ASSERT(q->q_first == NULL);
15885 
15886 	/* Nothing to do for the default queue */
15887 	if (q == tcp_g_q) {
15888 		return;
15889 	}
15890 
15891 	mp = allocb(0, BPRI_HI);
15892 	if (mp == NULL) {
15893 		/*
15894 		 * We are under memory pressure. Return for now and we
15895 		 * we will be called again later.
15896 		 */
15897 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15898 			/*
15899 			 * If there isn't already a timer running
15900 			 * start one.  Use a 4 second
15901 			 * timer as a fallback since it can't fail.
15902 			 */
15903 			tcp->tcp_timeout = B_TRUE;
15904 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15905 			    MSEC_TO_TICK(4000));
15906 		}
15907 		return;
15908 	}
15909 	CONN_INC_REF(connp);
15910 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15911 	    SQTAG_TCP_RSRV);
15912 }
15913 
15914 /*
15915  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15916  * We do not allow the receive window to shrink.  After setting rwnd,
15917  * set the flow control hiwat of the stream.
15918  *
15919  * This function is called in 2 cases:
15920  *
15921  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15922  *    connection (passive open) and in tcp_rput_data() for active connect.
15923  *    This is called after tcp_mss_set() when the desired MSS value is known.
15924  *    This makes sure that our window size is a mutiple of the other side's
15925  *    MSS.
15926  * 2) Handling SO_RCVBUF option.
15927  *
15928  * It is ASSUMED that the requested size is a multiple of the current MSS.
15929  *
15930  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15931  * user requests so.
15932  */
15933 static int
15934 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15935 {
15936 	uint32_t	mss = tcp->tcp_mss;
15937 	uint32_t	old_max_rwnd;
15938 	uint32_t	max_transmittable_rwnd;
15939 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15940 
15941 	if (tcp->tcp_fused) {
15942 		size_t sth_hiwat;
15943 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15944 
15945 		ASSERT(peer_tcp != NULL);
15946 		/*
15947 		 * Record the stream head's high water mark for
15948 		 * this endpoint; this is used for flow-control
15949 		 * purposes in tcp_fuse_output().
15950 		 */
15951 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15952 		if (!tcp_detached)
15953 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
15954 
15955 		/*
15956 		 * In the fusion case, the maxpsz stream head value of
15957 		 * our peer is set according to its send buffer size
15958 		 * and our receive buffer size; since the latter may
15959 		 * have changed we need to update the peer's maxpsz.
15960 		 */
15961 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15962 		return (rwnd);
15963 	}
15964 
15965 	if (tcp_detached)
15966 		old_max_rwnd = tcp->tcp_rwnd;
15967 	else
15968 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
15969 
15970 	/*
15971 	 * Insist on a receive window that is at least
15972 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15973 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15974 	 * and delayed acknowledgement.
15975 	 */
15976 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
15977 
15978 	/*
15979 	 * If window size info has already been exchanged, TCP should not
15980 	 * shrink the window.  Shrinking window is doable if done carefully.
15981 	 * We may add that support later.  But so far there is not a real
15982 	 * need to do that.
15983 	 */
15984 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15985 		/* MSS may have changed, do a round up again. */
15986 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15987 	}
15988 
15989 	/*
15990 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15991 	 * can be applied even before the window scale option is decided.
15992 	 */
15993 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15994 	if (rwnd > max_transmittable_rwnd) {
15995 		rwnd = max_transmittable_rwnd -
15996 		    (max_transmittable_rwnd % mss);
15997 		if (rwnd < mss)
15998 			rwnd = max_transmittable_rwnd;
15999 		/*
16000 		 * If we're over the limit we may have to back down tcp_rwnd.
16001 		 * The increment below won't work for us. So we set all three
16002 		 * here and the increment below will have no effect.
16003 		 */
16004 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16005 	}
16006 	if (tcp->tcp_localnet) {
16007 		tcp->tcp_rack_abs_max =
16008 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
16009 	} else {
16010 		/*
16011 		 * For a remote host on a different subnet (through a router),
16012 		 * we ack every other packet to be conforming to RFC1122.
16013 		 * tcp_deferred_acks_max is default to 2.
16014 		 */
16015 		tcp->tcp_rack_abs_max =
16016 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
16017 	}
16018 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16019 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16020 	else
16021 		tcp->tcp_rack_cur_max = 0;
16022 	/*
16023 	 * Increment the current rwnd by the amount the maximum grew (we
16024 	 * can not overwrite it since we might be in the middle of a
16025 	 * connection.)
16026 	 */
16027 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16028 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16029 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16030 		tcp->tcp_cwnd_max = rwnd;
16031 
16032 	if (tcp_detached)
16033 		return (rwnd);
16034 	/*
16035 	 * We set the maximum receive window into rq->q_hiwat.
16036 	 * This is not actually used for flow control.
16037 	 */
16038 	tcp->tcp_rq->q_hiwat = rwnd;
16039 	/*
16040 	 * Set the Stream head high water mark. This doesn't have to be
16041 	 * here, since we are simply using default values, but we would
16042 	 * prefer to choose these values algorithmically, with a likely
16043 	 * relationship to rwnd.
16044 	 */
16045 	(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd, tcp_sth_rcv_hiwat));
16046 	return (rwnd);
16047 }
16048 
16049 /*
16050  * Return SNMP stuff in buffer in mpdata.
16051  */
16052 int
16053 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16054 {
16055 	mblk_t			*mpdata;
16056 	mblk_t			*mp_conn_ctl = NULL;
16057 	mblk_t			*mp_conn_tail;
16058 	mblk_t			*mp_attr_ctl = NULL;
16059 	mblk_t			*mp_attr_tail;
16060 	mblk_t			*mp6_conn_ctl = NULL;
16061 	mblk_t			*mp6_conn_tail;
16062 	mblk_t			*mp6_attr_ctl = NULL;
16063 	mblk_t			*mp6_attr_tail;
16064 	struct opthdr		*optp;
16065 	mib2_tcpConnEntry_t	tce;
16066 	mib2_tcp6ConnEntry_t	tce6;
16067 	mib2_transportMLPEntry_t mlp;
16068 	connf_t			*connfp;
16069 	conn_t			*connp;
16070 	int			i;
16071 	boolean_t 		ispriv;
16072 	zoneid_t 		zoneid;
16073 	int			v4_conn_idx;
16074 	int			v6_conn_idx;
16075 
16076 	if (mpctl == NULL ||
16077 	    (mpdata = mpctl->b_cont) == NULL ||
16078 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16079 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16080 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16081 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16082 		freemsg(mp_conn_ctl);
16083 		freemsg(mp_attr_ctl);
16084 		freemsg(mp6_conn_ctl);
16085 		freemsg(mp6_attr_ctl);
16086 		return (0);
16087 	}
16088 
16089 	/* build table of connections -- need count in fixed part */
16090 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
16091 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
16092 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
16093 	SET_MIB(tcp_mib.tcpMaxConn, -1);
16094 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
16095 
16096 	ispriv =
16097 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16098 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16099 
16100 	v4_conn_idx = v6_conn_idx = 0;
16101 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16102 
16103 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16104 
16105 		connfp = &ipcl_globalhash_fanout[i];
16106 
16107 		connp = NULL;
16108 
16109 		while ((connp =
16110 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16111 			tcp_t *tcp;
16112 			boolean_t needattr;
16113 
16114 			if (connp->conn_zoneid != zoneid)
16115 				continue;	/* not in this zone */
16116 
16117 			tcp = connp->conn_tcp;
16118 			UPDATE_MIB(&tcp_mib, tcpHCInSegs, tcp->tcp_ibsegs);
16119 			tcp->tcp_ibsegs = 0;
16120 			UPDATE_MIB(&tcp_mib, tcpHCOutSegs, tcp->tcp_obsegs);
16121 			tcp->tcp_obsegs = 0;
16122 
16123 			tce6.tcp6ConnState = tce.tcpConnState =
16124 			    tcp_snmp_state(tcp);
16125 			if (tce.tcpConnState == MIB2_TCP_established ||
16126 			    tce.tcpConnState == MIB2_TCP_closeWait)
16127 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
16128 
16129 			needattr = B_FALSE;
16130 			bzero(&mlp, sizeof (mlp));
16131 			if (connp->conn_mlp_type != mlptSingle) {
16132 				if (connp->conn_mlp_type == mlptShared ||
16133 				    connp->conn_mlp_type == mlptBoth)
16134 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16135 				if (connp->conn_mlp_type == mlptPrivate ||
16136 				    connp->conn_mlp_type == mlptBoth)
16137 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16138 				needattr = B_TRUE;
16139 			}
16140 			if (connp->conn_peercred != NULL) {
16141 				ts_label_t *tsl;
16142 
16143 				tsl = crgetlabel(connp->conn_peercred);
16144 				mlp.tme_doi = label2doi(tsl);
16145 				mlp.tme_label = *label2bslabel(tsl);
16146 				needattr = B_TRUE;
16147 			}
16148 
16149 			/* Create a message to report on IPv6 entries */
16150 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16151 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16152 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16153 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16154 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16155 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16156 			/* Don't want just anybody seeing these... */
16157 			if (ispriv) {
16158 				tce6.tcp6ConnEntryInfo.ce_snxt =
16159 				    tcp->tcp_snxt;
16160 				tce6.tcp6ConnEntryInfo.ce_suna =
16161 				    tcp->tcp_suna;
16162 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16163 				    tcp->tcp_rnxt;
16164 				tce6.tcp6ConnEntryInfo.ce_rack =
16165 				    tcp->tcp_rack;
16166 			} else {
16167 				/*
16168 				 * Netstat, unfortunately, uses this to
16169 				 * get send/receive queue sizes.  How to fix?
16170 				 * Why not compute the difference only?
16171 				 */
16172 				tce6.tcp6ConnEntryInfo.ce_snxt =
16173 				    tcp->tcp_snxt - tcp->tcp_suna;
16174 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16175 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16176 				    tcp->tcp_rnxt - tcp->tcp_rack;
16177 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16178 			}
16179 
16180 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16181 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16182 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16183 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16184 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16185 
16186 			tce6.tcp6ConnCreationProcess =
16187 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16188 			    tcp->tcp_cpid;
16189 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16190 
16191 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16192 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16193 
16194 			mlp.tme_connidx = v6_conn_idx++;
16195 			if (needattr)
16196 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16197 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16198 			}
16199 			/*
16200 			 * Create an IPv4 table entry for IPv4 entries and also
16201 			 * for IPv6 entries which are bound to in6addr_any
16202 			 * but don't have IPV6_V6ONLY set.
16203 			 * (i.e. anything an IPv4 peer could connect to)
16204 			 */
16205 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16206 			    (tcp->tcp_state <= TCPS_LISTEN &&
16207 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16208 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16209 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16210 					tce.tcpConnRemAddress = INADDR_ANY;
16211 					tce.tcpConnLocalAddress = INADDR_ANY;
16212 				} else {
16213 					tce.tcpConnRemAddress =
16214 					    tcp->tcp_remote;
16215 					tce.tcpConnLocalAddress =
16216 					    tcp->tcp_ip_src;
16217 				}
16218 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16219 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16220 				/* Don't want just anybody seeing these... */
16221 				if (ispriv) {
16222 					tce.tcpConnEntryInfo.ce_snxt =
16223 					    tcp->tcp_snxt;
16224 					tce.tcpConnEntryInfo.ce_suna =
16225 					    tcp->tcp_suna;
16226 					tce.tcpConnEntryInfo.ce_rnxt =
16227 					    tcp->tcp_rnxt;
16228 					tce.tcpConnEntryInfo.ce_rack =
16229 					    tcp->tcp_rack;
16230 				} else {
16231 					/*
16232 					 * Netstat, unfortunately, uses this to
16233 					 * get send/receive queue sizes.  How
16234 					 * to fix?
16235 					 * Why not compute the difference only?
16236 					 */
16237 					tce.tcpConnEntryInfo.ce_snxt =
16238 					    tcp->tcp_snxt - tcp->tcp_suna;
16239 					tce.tcpConnEntryInfo.ce_suna = 0;
16240 					tce.tcpConnEntryInfo.ce_rnxt =
16241 					    tcp->tcp_rnxt - tcp->tcp_rack;
16242 					tce.tcpConnEntryInfo.ce_rack = 0;
16243 				}
16244 
16245 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16246 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16247 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16248 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16249 				tce.tcpConnEntryInfo.ce_state =
16250 				    tcp->tcp_state;
16251 
16252 				tce.tcpConnCreationProcess =
16253 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16254 				    tcp->tcp_cpid;
16255 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16256 
16257 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16258 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16259 
16260 				mlp.tme_connidx = v4_conn_idx++;
16261 				if (needattr)
16262 					(void) snmp_append_data2(
16263 					    mp_attr_ctl->b_cont,
16264 					    &mp_attr_tail, (char *)&mlp,
16265 					    sizeof (mlp));
16266 			}
16267 		}
16268 	}
16269 
16270 	/* fixed length structure for IPv4 and IPv6 counters */
16271 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16272 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
16273 	/* synchronize 32- and 64-bit counters */
16274 	SYNC32_MIB(&tcp_mib, tcpInSegs, tcpHCInSegs);
16275 	SYNC32_MIB(&tcp_mib, tcpOutSegs, tcpHCOutSegs);
16276 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16277 	optp->level = MIB2_TCP;
16278 	optp->name = 0;
16279 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
16280 	optp->len = msgdsize(mpdata);
16281 	qreply(q, mpctl);
16282 
16283 	/* table of connections... */
16284 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16285 	    sizeof (struct T_optmgmt_ack)];
16286 	optp->level = MIB2_TCP;
16287 	optp->name = MIB2_TCP_CONN;
16288 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16289 	qreply(q, mp_conn_ctl);
16290 
16291 	/* table of MLP attributes... */
16292 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16293 	    sizeof (struct T_optmgmt_ack)];
16294 	optp->level = MIB2_TCP;
16295 	optp->name = EXPER_XPORT_MLP;
16296 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16297 	if (optp->len == 0)
16298 		freemsg(mp_attr_ctl);
16299 	else
16300 		qreply(q, mp_attr_ctl);
16301 
16302 	/* table of IPv6 connections... */
16303 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16304 	    sizeof (struct T_optmgmt_ack)];
16305 	optp->level = MIB2_TCP6;
16306 	optp->name = MIB2_TCP6_CONN;
16307 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16308 	qreply(q, mp6_conn_ctl);
16309 
16310 	/* table of IPv6 MLP attributes... */
16311 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16312 	    sizeof (struct T_optmgmt_ack)];
16313 	optp->level = MIB2_TCP6;
16314 	optp->name = EXPER_XPORT_MLP;
16315 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16316 	if (optp->len == 0)
16317 		freemsg(mp6_attr_ctl);
16318 	else
16319 		qreply(q, mp6_attr_ctl);
16320 	return (1);
16321 }
16322 
16323 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16324 /* ARGSUSED */
16325 int
16326 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16327 {
16328 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16329 
16330 	switch (level) {
16331 	case MIB2_TCP:
16332 		switch (name) {
16333 		case 13:
16334 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16335 				return (0);
16336 			/* TODO: delete entry defined by tce */
16337 			return (1);
16338 		default:
16339 			return (0);
16340 		}
16341 	default:
16342 		return (1);
16343 	}
16344 }
16345 
16346 /* Translate TCP state to MIB2 TCP state. */
16347 static int
16348 tcp_snmp_state(tcp_t *tcp)
16349 {
16350 	if (tcp == NULL)
16351 		return (0);
16352 
16353 	switch (tcp->tcp_state) {
16354 	case TCPS_CLOSED:
16355 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16356 	case TCPS_BOUND:
16357 		return (MIB2_TCP_closed);
16358 	case TCPS_LISTEN:
16359 		return (MIB2_TCP_listen);
16360 	case TCPS_SYN_SENT:
16361 		return (MIB2_TCP_synSent);
16362 	case TCPS_SYN_RCVD:
16363 		return (MIB2_TCP_synReceived);
16364 	case TCPS_ESTABLISHED:
16365 		return (MIB2_TCP_established);
16366 	case TCPS_CLOSE_WAIT:
16367 		return (MIB2_TCP_closeWait);
16368 	case TCPS_FIN_WAIT_1:
16369 		return (MIB2_TCP_finWait1);
16370 	case TCPS_CLOSING:
16371 		return (MIB2_TCP_closing);
16372 	case TCPS_LAST_ACK:
16373 		return (MIB2_TCP_lastAck);
16374 	case TCPS_FIN_WAIT_2:
16375 		return (MIB2_TCP_finWait2);
16376 	case TCPS_TIME_WAIT:
16377 		return (MIB2_TCP_timeWait);
16378 	default:
16379 		return (0);
16380 	}
16381 }
16382 
16383 static char tcp_report_header[] =
16384 	"TCP     " MI_COL_HDRPAD_STR
16385 	"zone dest            snxt     suna     "
16386 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16387 	"recent   [lport,fport] state";
16388 
16389 /*
16390  * TCP status report triggered via the Named Dispatch mechanism.
16391  */
16392 /* ARGSUSED */
16393 static void
16394 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16395     cred_t *cr)
16396 {
16397 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16398 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
16399 	char cflag;
16400 	in6_addr_t	v6dst;
16401 	char buf[80];
16402 	uint_t print_len, buf_len;
16403 
16404 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16405 	if (buf_len <= 0)
16406 		return;
16407 
16408 	if (hashval >= 0)
16409 		(void) sprintf(hash, "%03d ", hashval);
16410 	else
16411 		hash[0] = '\0';
16412 
16413 	/*
16414 	 * Note that we use the remote address in the tcp_b  structure.
16415 	 * This means that it will print out the real destination address,
16416 	 * not the next hop's address if source routing is used.  This
16417 	 * avoid the confusion on the output because user may not
16418 	 * know that source routing is used for a connection.
16419 	 */
16420 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16421 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16422 	} else {
16423 		v6dst = tcp->tcp_remote_v6;
16424 	}
16425 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16426 	/*
16427 	 * the ispriv checks are so that normal users cannot determine
16428 	 * sequence number information using NDD.
16429 	 */
16430 
16431 	if (TCP_IS_DETACHED(tcp))
16432 		cflag = '*';
16433 	else
16434 		cflag = ' ';
16435 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16436 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16437 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16438 	    hash,
16439 	    (void *)tcp,
16440 	    tcp->tcp_connp->conn_zoneid,
16441 	    addrbuf,
16442 	    (ispriv) ? tcp->tcp_snxt : 0,
16443 	    (ispriv) ? tcp->tcp_suna : 0,
16444 	    tcp->tcp_swnd,
16445 	    (ispriv) ? tcp->tcp_rnxt : 0,
16446 	    (ispriv) ? tcp->tcp_rack : 0,
16447 	    tcp->tcp_rwnd,
16448 	    tcp->tcp_rto,
16449 	    tcp->tcp_mss,
16450 	    tcp->tcp_snd_ws_ok,
16451 	    tcp->tcp_snd_ws,
16452 	    tcp->tcp_rcv_ws,
16453 	    tcp->tcp_snd_ts_ok,
16454 	    tcp->tcp_ts_recent,
16455 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16456 	if (print_len < buf_len) {
16457 		((mblk_t *)mp)->b_wptr += print_len;
16458 	} else {
16459 		((mblk_t *)mp)->b_wptr += buf_len;
16460 	}
16461 }
16462 
16463 /*
16464  * TCP status report (for listeners only) triggered via the Named Dispatch
16465  * mechanism.
16466  */
16467 /* ARGSUSED */
16468 static void
16469 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16470 {
16471 	char addrbuf[INET6_ADDRSTRLEN];
16472 	in6_addr_t	v6dst;
16473 	uint_t print_len, buf_len;
16474 
16475 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16476 	if (buf_len <= 0)
16477 		return;
16478 
16479 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16480 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16481 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16482 	} else {
16483 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16484 		    addrbuf, sizeof (addrbuf));
16485 	}
16486 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16487 	    "%03d "
16488 	    MI_COL_PTRFMT_STR
16489 	    "%d %s %05u %08u %d/%d/%d%c\n",
16490 	    hashval, (void *)tcp,
16491 	    tcp->tcp_connp->conn_zoneid,
16492 	    addrbuf,
16493 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16494 	    tcp->tcp_conn_req_seqnum,
16495 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16496 	    tcp->tcp_conn_req_max,
16497 	    tcp->tcp_syn_defense ? '*' : ' ');
16498 	if (print_len < buf_len) {
16499 		((mblk_t *)mp)->b_wptr += print_len;
16500 	} else {
16501 		((mblk_t *)mp)->b_wptr += buf_len;
16502 	}
16503 }
16504 
16505 /* TCP status report triggered via the Named Dispatch mechanism. */
16506 /* ARGSUSED */
16507 static int
16508 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16509 {
16510 	tcp_t	*tcp;
16511 	int	i;
16512 	conn_t	*connp;
16513 	connf_t	*connfp;
16514 	zoneid_t zoneid;
16515 
16516 	/*
16517 	 * Because of the ndd constraint, at most we can have 64K buffer
16518 	 * to put in all TCP info.  So to be more efficient, just
16519 	 * allocate a 64K buffer here, assuming we need that large buffer.
16520 	 * This may be a problem as any user can read tcp_status.  Therefore
16521 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16522 	 * This should be OK as normal users should not do this too often.
16523 	 */
16524 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16525 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16526 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16527 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16528 			return (0);
16529 		}
16530 	}
16531 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16532 		/* The following may work even if we cannot get a large buf. */
16533 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16534 		return (0);
16535 	}
16536 
16537 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16538 
16539 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16540 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16541 
16542 		connfp = &ipcl_globalhash_fanout[i];
16543 
16544 		connp = NULL;
16545 
16546 		while ((connp =
16547 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16548 			tcp = connp->conn_tcp;
16549 			if (zoneid != GLOBAL_ZONEID &&
16550 			    zoneid != connp->conn_zoneid)
16551 				continue;
16552 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16553 			    cr);
16554 		}
16555 
16556 	}
16557 
16558 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16559 	return (0);
16560 }
16561 
16562 /* TCP status report triggered via the Named Dispatch mechanism. */
16563 /* ARGSUSED */
16564 static int
16565 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16566 {
16567 	tf_t	*tbf;
16568 	tcp_t	*tcp;
16569 	int	i;
16570 	zoneid_t zoneid;
16571 
16572 	/* Refer to comments in tcp_status_report(). */
16573 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16574 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16575 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16576 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16577 			return (0);
16578 		}
16579 	}
16580 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16581 		/* The following may work even if we cannot get a large buf. */
16582 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16583 		return (0);
16584 	}
16585 
16586 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16587 
16588 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16589 
16590 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
16591 		tbf = &tcp_bind_fanout[i];
16592 		mutex_enter(&tbf->tf_lock);
16593 		for (tcp = tbf->tf_tcp; tcp != NULL;
16594 		    tcp = tcp->tcp_bind_hash) {
16595 			if (zoneid != GLOBAL_ZONEID &&
16596 			    zoneid != tcp->tcp_connp->conn_zoneid)
16597 				continue;
16598 			CONN_INC_REF(tcp->tcp_connp);
16599 			tcp_report_item(mp->b_cont, tcp, i,
16600 			    Q_TO_TCP(q), cr);
16601 			CONN_DEC_REF(tcp->tcp_connp);
16602 		}
16603 		mutex_exit(&tbf->tf_lock);
16604 	}
16605 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16606 	return (0);
16607 }
16608 
16609 /* TCP status report triggered via the Named Dispatch mechanism. */
16610 /* ARGSUSED */
16611 static int
16612 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16613 {
16614 	connf_t	*connfp;
16615 	conn_t	*connp;
16616 	tcp_t	*tcp;
16617 	int	i;
16618 	zoneid_t zoneid;
16619 
16620 	/* Refer to comments in tcp_status_report(). */
16621 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16622 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16623 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16624 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16625 			return (0);
16626 		}
16627 	}
16628 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16629 		/* The following may work even if we cannot get a large buf. */
16630 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16631 		return (0);
16632 	}
16633 
16634 	(void) mi_mpprintf(mp,
16635 	    "    TCP    " MI_COL_HDRPAD_STR
16636 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16637 
16638 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16639 
16640 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
16641 		connfp =  &ipcl_bind_fanout[i];
16642 		connp = NULL;
16643 		while ((connp =
16644 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16645 			tcp = connp->conn_tcp;
16646 			if (zoneid != GLOBAL_ZONEID &&
16647 			    zoneid != connp->conn_zoneid)
16648 				continue;
16649 			tcp_report_listener(mp->b_cont, tcp, i);
16650 		}
16651 	}
16652 
16653 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16654 	return (0);
16655 }
16656 
16657 /* TCP status report triggered via the Named Dispatch mechanism. */
16658 /* ARGSUSED */
16659 static int
16660 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16661 {
16662 	connf_t	*connfp;
16663 	conn_t	*connp;
16664 	tcp_t	*tcp;
16665 	int	i;
16666 	zoneid_t zoneid;
16667 
16668 	/* Refer to comments in tcp_status_report(). */
16669 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16670 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16671 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16672 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16673 			return (0);
16674 		}
16675 	}
16676 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16677 		/* The following may work even if we cannot get a large buf. */
16678 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16679 		return (0);
16680 	}
16681 
16682 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16683 	    ipcl_conn_fanout_size);
16684 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16685 
16686 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16687 
16688 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
16689 		connfp =  &ipcl_conn_fanout[i];
16690 		connp = NULL;
16691 		while ((connp =
16692 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16693 			tcp = connp->conn_tcp;
16694 			if (zoneid != GLOBAL_ZONEID &&
16695 			    zoneid != connp->conn_zoneid)
16696 				continue;
16697 			tcp_report_item(mp->b_cont, tcp, i,
16698 			    Q_TO_TCP(q), cr);
16699 		}
16700 	}
16701 
16702 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16703 	return (0);
16704 }
16705 
16706 /* TCP status report triggered via the Named Dispatch mechanism. */
16707 /* ARGSUSED */
16708 static int
16709 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16710 {
16711 	tf_t	*tf;
16712 	tcp_t	*tcp;
16713 	int	i;
16714 	zoneid_t zoneid;
16715 
16716 	/* Refer to comments in tcp_status_report(). */
16717 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16718 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16719 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16720 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16721 			return (0);
16722 		}
16723 	}
16724 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16725 		/* The following may work even if we cannot get a large buf. */
16726 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16727 		return (0);
16728 	}
16729 
16730 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16731 
16732 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16733 
16734 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16735 		tf = &tcp_acceptor_fanout[i];
16736 		mutex_enter(&tf->tf_lock);
16737 		for (tcp = tf->tf_tcp; tcp != NULL;
16738 		    tcp = tcp->tcp_acceptor_hash) {
16739 			if (zoneid != GLOBAL_ZONEID &&
16740 			    zoneid != tcp->tcp_connp->conn_zoneid)
16741 				continue;
16742 			tcp_report_item(mp->b_cont, tcp, i,
16743 			    Q_TO_TCP(q), cr);
16744 		}
16745 		mutex_exit(&tf->tf_lock);
16746 	}
16747 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16748 	return (0);
16749 }
16750 
16751 /*
16752  * tcp_timer is the timer service routine.  It handles the retransmission,
16753  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16754  * from the state of the tcp instance what kind of action needs to be done
16755  * at the time it is called.
16756  */
16757 static void
16758 tcp_timer(void *arg)
16759 {
16760 	mblk_t		*mp;
16761 	clock_t		first_threshold;
16762 	clock_t		second_threshold;
16763 	clock_t		ms;
16764 	uint32_t	mss;
16765 	conn_t		*connp = (conn_t *)arg;
16766 	tcp_t		*tcp = connp->conn_tcp;
16767 
16768 	tcp->tcp_timer_tid = 0;
16769 
16770 	if (tcp->tcp_fused)
16771 		return;
16772 
16773 	first_threshold =  tcp->tcp_first_timer_threshold;
16774 	second_threshold = tcp->tcp_second_timer_threshold;
16775 	switch (tcp->tcp_state) {
16776 	case TCPS_IDLE:
16777 	case TCPS_BOUND:
16778 	case TCPS_LISTEN:
16779 		return;
16780 	case TCPS_SYN_RCVD: {
16781 		tcp_t	*listener = tcp->tcp_listener;
16782 
16783 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16784 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16785 			/* it's our first timeout */
16786 			tcp->tcp_syn_rcvd_timeout = 1;
16787 			mutex_enter(&listener->tcp_eager_lock);
16788 			listener->tcp_syn_rcvd_timeout++;
16789 			if (!tcp->tcp_dontdrop && tcp->tcp_closemp_used == 0) {
16790 				/*
16791 				 * Make this eager available for drop if we
16792 				 * need to drop one to accomodate a new
16793 				 * incoming SYN request.
16794 				 */
16795 				MAKE_DROPPABLE(listener, tcp);
16796 			}
16797 			if (!listener->tcp_syn_defense &&
16798 			    (listener->tcp_syn_rcvd_timeout >
16799 			    (tcp_conn_req_max_q0 >> 2)) &&
16800 			    (tcp_conn_req_max_q0 > 200)) {
16801 				/* We may be under attack. Put on a defense. */
16802 				listener->tcp_syn_defense = B_TRUE;
16803 				cmn_err(CE_WARN, "High TCP connect timeout "
16804 				    "rate! System (port %d) may be under a "
16805 				    "SYN flood attack!",
16806 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16807 
16808 				listener->tcp_ip_addr_cache = kmem_zalloc(
16809 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16810 				    KM_NOSLEEP);
16811 			}
16812 			mutex_exit(&listener->tcp_eager_lock);
16813 		} else if (listener != NULL) {
16814 			mutex_enter(&listener->tcp_eager_lock);
16815 			tcp->tcp_syn_rcvd_timeout++;
16816 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16817 			    tcp->tcp_closemp_used == 0) {
16818 				/*
16819 				 * This is our second timeout. Put the tcp in
16820 				 * the list of droppable eagers to allow it to
16821 				 * be dropped, if needed. We don't check
16822 				 * whether tcp_dontdrop is set or not to
16823 				 * protect ourselve from a SYN attack where a
16824 				 * remote host can spoof itself as one of the
16825 				 * good IP source and continue to hold
16826 				 * resources too long.
16827 				 */
16828 				MAKE_DROPPABLE(listener, tcp);
16829 			}
16830 			mutex_exit(&listener->tcp_eager_lock);
16831 		}
16832 	}
16833 		/* FALLTHRU */
16834 	case TCPS_SYN_SENT:
16835 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16836 		second_threshold = tcp->tcp_second_ctimer_threshold;
16837 		break;
16838 	case TCPS_ESTABLISHED:
16839 	case TCPS_FIN_WAIT_1:
16840 	case TCPS_CLOSING:
16841 	case TCPS_CLOSE_WAIT:
16842 	case TCPS_LAST_ACK:
16843 		/* If we have data to rexmit */
16844 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16845 			clock_t	time_to_wait;
16846 
16847 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16848 			if (!tcp->tcp_xmit_head)
16849 				break;
16850 			time_to_wait = lbolt -
16851 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16852 			time_to_wait = tcp->tcp_rto -
16853 			    TICK_TO_MSEC(time_to_wait);
16854 			/*
16855 			 * If the timer fires too early, 1 clock tick earlier,
16856 			 * restart the timer.
16857 			 */
16858 			if (time_to_wait > msec_per_tick) {
16859 				TCP_STAT(tcp_timer_fire_early);
16860 				TCP_TIMER_RESTART(tcp, time_to_wait);
16861 				return;
16862 			}
16863 			/*
16864 			 * When we probe zero windows, we force the swnd open.
16865 			 * If our peer acks with a closed window swnd will be
16866 			 * set to zero by tcp_rput(). As long as we are
16867 			 * receiving acks tcp_rput will
16868 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16869 			 * first and second interval actions.  NOTE: the timer
16870 			 * interval is allowed to continue its exponential
16871 			 * backoff.
16872 			 */
16873 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16874 				if (tcp->tcp_debug) {
16875 					(void) strlog(TCP_MOD_ID, 0, 1,
16876 					    SL_TRACE, "tcp_timer: zero win");
16877 				}
16878 			} else {
16879 				/*
16880 				 * After retransmission, we need to do
16881 				 * slow start.  Set the ssthresh to one
16882 				 * half of current effective window and
16883 				 * cwnd to one MSS.  Also reset
16884 				 * tcp_cwnd_cnt.
16885 				 *
16886 				 * Note that if tcp_ssthresh is reduced because
16887 				 * of ECN, do not reduce it again unless it is
16888 				 * already one window of data away (tcp_cwr
16889 				 * should then be cleared) or this is a
16890 				 * timeout for a retransmitted segment.
16891 				 */
16892 				uint32_t npkt;
16893 
16894 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16895 					npkt = ((tcp->tcp_timer_backoff ?
16896 					    tcp->tcp_cwnd_ssthresh :
16897 					    tcp->tcp_snxt -
16898 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16899 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16900 					    tcp->tcp_mss;
16901 				}
16902 				tcp->tcp_cwnd = tcp->tcp_mss;
16903 				tcp->tcp_cwnd_cnt = 0;
16904 				if (tcp->tcp_ecn_ok) {
16905 					tcp->tcp_cwr = B_TRUE;
16906 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16907 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16908 				}
16909 			}
16910 			break;
16911 		}
16912 		/*
16913 		 * We have something to send yet we cannot send.  The
16914 		 * reason can be:
16915 		 *
16916 		 * 1. Zero send window: we need to do zero window probe.
16917 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16918 		 * segments.
16919 		 * 3. SWS avoidance: receiver may have shrunk window,
16920 		 * reset our knowledge.
16921 		 *
16922 		 * Note that condition 2 can happen with either 1 or
16923 		 * 3.  But 1 and 3 are exclusive.
16924 		 */
16925 		if (tcp->tcp_unsent != 0) {
16926 			if (tcp->tcp_cwnd == 0) {
16927 				/*
16928 				 * Set tcp_cwnd to 1 MSS so that a
16929 				 * new segment can be sent out.  We
16930 				 * are "clocking out" new data when
16931 				 * the network is really congested.
16932 				 */
16933 				ASSERT(tcp->tcp_ecn_ok);
16934 				tcp->tcp_cwnd = tcp->tcp_mss;
16935 			}
16936 			if (tcp->tcp_swnd == 0) {
16937 				/* Extend window for zero window probe */
16938 				tcp->tcp_swnd++;
16939 				tcp->tcp_zero_win_probe = B_TRUE;
16940 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
16941 			} else {
16942 				/*
16943 				 * Handle timeout from sender SWS avoidance.
16944 				 * Reset our knowledge of the max send window
16945 				 * since the receiver might have reduced its
16946 				 * receive buffer.  Avoid setting tcp_max_swnd
16947 				 * to one since that will essentially disable
16948 				 * the SWS checks.
16949 				 *
16950 				 * Note that since we don't have a SWS
16951 				 * state variable, if the timeout is set
16952 				 * for ECN but not for SWS, this
16953 				 * code will also be executed.  This is
16954 				 * fine as tcp_max_swnd is updated
16955 				 * constantly and it will not affect
16956 				 * anything.
16957 				 */
16958 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16959 			}
16960 			tcp_wput_data(tcp, NULL, B_FALSE);
16961 			return;
16962 		}
16963 		/* Is there a FIN that needs to be to re retransmitted? */
16964 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16965 		    !tcp->tcp_fin_acked)
16966 			break;
16967 		/* Nothing to do, return without restarting timer. */
16968 		TCP_STAT(tcp_timer_fire_miss);
16969 		return;
16970 	case TCPS_FIN_WAIT_2:
16971 		/*
16972 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16973 		 * We waited some time for for peer's FIN, but it hasn't
16974 		 * arrived.  We flush the connection now to avoid
16975 		 * case where the peer has rebooted.
16976 		 */
16977 		if (TCP_IS_DETACHED(tcp)) {
16978 			(void) tcp_clean_death(tcp, 0, 23);
16979 		} else {
16980 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
16981 		}
16982 		return;
16983 	case TCPS_TIME_WAIT:
16984 		(void) tcp_clean_death(tcp, 0, 24);
16985 		return;
16986 	default:
16987 		if (tcp->tcp_debug) {
16988 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16989 			    "tcp_timer: strange state (%d) %s",
16990 			    tcp->tcp_state, tcp_display(tcp, NULL,
16991 			    DISP_PORT_ONLY));
16992 		}
16993 		return;
16994 	}
16995 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16996 		/*
16997 		 * For zero window probe, we need to send indefinitely,
16998 		 * unless we have not heard from the other side for some
16999 		 * time...
17000 		 */
17001 		if ((tcp->tcp_zero_win_probe == 0) ||
17002 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17003 		    second_threshold)) {
17004 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
17005 			/*
17006 			 * If TCP is in SYN_RCVD state, send back a
17007 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17008 			 * should be zero in TCPS_SYN_RCVD state.
17009 			 */
17010 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17011 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17012 				    "in SYN_RCVD",
17013 				    tcp, tcp->tcp_snxt,
17014 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17015 			}
17016 			(void) tcp_clean_death(tcp,
17017 			    tcp->tcp_client_errno ?
17018 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17019 			return;
17020 		} else {
17021 			/*
17022 			 * Set tcp_ms_we_have_waited to second_threshold
17023 			 * so that in next timeout, we will do the above
17024 			 * check (lbolt - tcp_last_recv_time).  This is
17025 			 * also to avoid overflow.
17026 			 *
17027 			 * We don't need to decrement tcp_timer_backoff
17028 			 * to avoid overflow because it will be decremented
17029 			 * later if new timeout value is greater than
17030 			 * tcp_rexmit_interval_max.  In the case when
17031 			 * tcp_rexmit_interval_max is greater than
17032 			 * second_threshold, it means that we will wait
17033 			 * longer than second_threshold to send the next
17034 			 * window probe.
17035 			 */
17036 			tcp->tcp_ms_we_have_waited = second_threshold;
17037 		}
17038 	} else if (ms > first_threshold) {
17039 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17040 		    tcp->tcp_xmit_head != NULL) {
17041 			tcp->tcp_xmit_head =
17042 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17043 		}
17044 		/*
17045 		 * We have been retransmitting for too long...  The RTT
17046 		 * we calculated is probably incorrect.  Reinitialize it.
17047 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17048 		 * tcp_rtt_update so that we won't accidentally cache a
17049 		 * bad value.  But only do this if this is not a zero
17050 		 * window probe.
17051 		 */
17052 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17053 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17054 			    (tcp->tcp_rtt_sa >> 5);
17055 			tcp->tcp_rtt_sa = 0;
17056 			tcp_ip_notify(tcp);
17057 			tcp->tcp_rtt_update = 0;
17058 		}
17059 	}
17060 	tcp->tcp_timer_backoff++;
17061 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17062 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17063 	    tcp_rexmit_interval_min) {
17064 		/*
17065 		 * This means the original RTO is tcp_rexmit_interval_min.
17066 		 * So we will use tcp_rexmit_interval_min as the RTO value
17067 		 * and do the backoff.
17068 		 */
17069 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
17070 	} else {
17071 		ms <<= tcp->tcp_timer_backoff;
17072 	}
17073 	if (ms > tcp_rexmit_interval_max) {
17074 		ms = tcp_rexmit_interval_max;
17075 		/*
17076 		 * ms is at max, decrement tcp_timer_backoff to avoid
17077 		 * overflow.
17078 		 */
17079 		tcp->tcp_timer_backoff--;
17080 	}
17081 	tcp->tcp_ms_we_have_waited += ms;
17082 	if (tcp->tcp_zero_win_probe == 0) {
17083 		tcp->tcp_rto = ms;
17084 	}
17085 	TCP_TIMER_RESTART(tcp, ms);
17086 	/*
17087 	 * This is after a timeout and tcp_rto is backed off.  Set
17088 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17089 	 * restart the timer with a correct value.
17090 	 */
17091 	tcp->tcp_set_timer = 1;
17092 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17093 	if (mss > tcp->tcp_mss)
17094 		mss = tcp->tcp_mss;
17095 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17096 		mss = tcp->tcp_swnd;
17097 
17098 	if ((mp = tcp->tcp_xmit_head) != NULL)
17099 		mp->b_prev = (mblk_t *)lbolt;
17100 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17101 	    B_TRUE);
17102 
17103 	/*
17104 	 * When slow start after retransmission begins, start with
17105 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17106 	 * start phase.  tcp_snd_burst controls how many segments
17107 	 * can be sent because of an ack.
17108 	 */
17109 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17110 	tcp->tcp_snd_burst = TCP_CWND_SS;
17111 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17112 	    (tcp->tcp_unsent == 0)) {
17113 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17114 	} else {
17115 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17116 	}
17117 	tcp->tcp_rexmit = B_TRUE;
17118 	tcp->tcp_dupack_cnt = 0;
17119 
17120 	/*
17121 	 * Remove all rexmit SACK blk to start from fresh.
17122 	 */
17123 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17124 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17125 		tcp->tcp_num_notsack_blk = 0;
17126 		tcp->tcp_cnt_notsack_list = 0;
17127 	}
17128 	if (mp == NULL) {
17129 		return;
17130 	}
17131 	/* Attach credentials to retransmitted initial SYNs. */
17132 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17133 		mblk_setcred(mp, tcp->tcp_cred);
17134 		DB_CPID(mp) = tcp->tcp_cpid;
17135 	}
17136 
17137 	tcp->tcp_csuna = tcp->tcp_snxt;
17138 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
17139 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
17140 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
17141 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17142 
17143 }
17144 
17145 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17146 static void
17147 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17148 {
17149 	conn_t	*connp;
17150 
17151 	switch (tcp->tcp_state) {
17152 	case TCPS_BOUND:
17153 	case TCPS_LISTEN:
17154 		break;
17155 	default:
17156 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17157 		return;
17158 	}
17159 
17160 	/*
17161 	 * Need to clean up all the eagers since after the unbind, segments
17162 	 * will no longer be delivered to this listener stream.
17163 	 */
17164 	mutex_enter(&tcp->tcp_eager_lock);
17165 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17166 		tcp_eager_cleanup(tcp, 0);
17167 	}
17168 	mutex_exit(&tcp->tcp_eager_lock);
17169 
17170 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17171 		tcp->tcp_ipha->ipha_src = 0;
17172 	} else {
17173 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17174 	}
17175 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17176 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17177 	tcp_bind_hash_remove(tcp);
17178 	tcp->tcp_state = TCPS_IDLE;
17179 	tcp->tcp_mdt = B_FALSE;
17180 	/* Send M_FLUSH according to TPI */
17181 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17182 	connp = tcp->tcp_connp;
17183 	connp->conn_mdt_ok = B_FALSE;
17184 	ipcl_hash_remove(connp);
17185 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17186 	mp = mi_tpi_ok_ack_alloc(mp);
17187 	putnext(tcp->tcp_rq, mp);
17188 }
17189 
17190 /*
17191  * Don't let port fall into the privileged range.
17192  * Since the extra privileged ports can be arbitrary we also
17193  * ensure that we exclude those from consideration.
17194  * tcp_g_epriv_ports is not sorted thus we loop over it until
17195  * there are no changes.
17196  *
17197  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17198  * but instead the code relies on:
17199  * - the fact that the address of the array and its size never changes
17200  * - the atomic assignment of the elements of the array
17201  *
17202  * Returns 0 if there are no more ports available.
17203  *
17204  * TS note: skip multilevel ports.
17205  */
17206 static in_port_t
17207 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17208 {
17209 	int i;
17210 	boolean_t restart = B_FALSE;
17211 
17212 	if (random && tcp_random_anon_port != 0) {
17213 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17214 		    sizeof (in_port_t));
17215 		/*
17216 		 * Unless changed by a sys admin, the smallest anon port
17217 		 * is 32768 and the largest anon port is 65535.  It is
17218 		 * very likely (50%) for the random port to be smaller
17219 		 * than the smallest anon port.  When that happens,
17220 		 * add port % (anon port range) to the smallest anon
17221 		 * port to get the random port.  It should fall into the
17222 		 * valid anon port range.
17223 		 */
17224 		if (port < tcp_smallest_anon_port) {
17225 			port = tcp_smallest_anon_port +
17226 			    port % (tcp_largest_anon_port -
17227 				tcp_smallest_anon_port);
17228 		}
17229 	}
17230 
17231 retry:
17232 	if (port < tcp_smallest_anon_port)
17233 		port = (in_port_t)tcp_smallest_anon_port;
17234 
17235 	if (port > tcp_largest_anon_port) {
17236 		if (restart)
17237 			return (0);
17238 		restart = B_TRUE;
17239 		port = (in_port_t)tcp_smallest_anon_port;
17240 	}
17241 
17242 	if (port < tcp_smallest_nonpriv_port)
17243 		port = (in_port_t)tcp_smallest_nonpriv_port;
17244 
17245 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
17246 		if (port == tcp_g_epriv_ports[i]) {
17247 			port++;
17248 			/*
17249 			 * Make sure whether the port is in the
17250 			 * valid range.
17251 			 */
17252 			goto retry;
17253 		}
17254 	}
17255 	if (is_system_labeled() &&
17256 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17257 	    IPPROTO_TCP, B_TRUE)) != 0) {
17258 		port = i;
17259 		goto retry;
17260 	}
17261 	return (port);
17262 }
17263 
17264 /*
17265  * Return the next anonymous port in the privileged port range for
17266  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17267  * downwards.  This is the same behavior as documented in the userland
17268  * library call rresvport(3N).
17269  *
17270  * TS note: skip multilevel ports.
17271  */
17272 static in_port_t
17273 tcp_get_next_priv_port(const tcp_t *tcp)
17274 {
17275 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17276 	in_port_t nextport;
17277 	boolean_t restart = B_FALSE;
17278 
17279 retry:
17280 	if (next_priv_port < tcp_min_anonpriv_port ||
17281 	    next_priv_port >= IPPORT_RESERVED) {
17282 		next_priv_port = IPPORT_RESERVED - 1;
17283 		if (restart)
17284 			return (0);
17285 		restart = B_TRUE;
17286 	}
17287 	if (is_system_labeled() &&
17288 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17289 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17290 		next_priv_port = nextport;
17291 		goto retry;
17292 	}
17293 	return (next_priv_port--);
17294 }
17295 
17296 /* The write side r/w procedure. */
17297 
17298 #if CCS_STATS
17299 struct {
17300 	struct {
17301 		int64_t count, bytes;
17302 	} tot, hit;
17303 } wrw_stats;
17304 #endif
17305 
17306 /*
17307  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17308  * messages.
17309  */
17310 /* ARGSUSED */
17311 static void
17312 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17313 {
17314 	conn_t	*connp = (conn_t *)arg;
17315 	tcp_t	*tcp = connp->conn_tcp;
17316 	queue_t	*q = tcp->tcp_wq;
17317 
17318 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17319 	/*
17320 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17321 	 * Once the close starts, streamhead and sockfs will not let any data
17322 	 * packets come down (close ensures that there are no threads using the
17323 	 * queue and no new threads will come down) but since qprocsoff()
17324 	 * hasn't happened yet, a M_FLUSH or some non data message might
17325 	 * get reflected back (in response to our own FLUSHRW) and get
17326 	 * processed after tcp_close() is done. The conn would still be valid
17327 	 * because a ref would have added but we need to check the state
17328 	 * before actually processing the packet.
17329 	 */
17330 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17331 		freemsg(mp);
17332 		return;
17333 	}
17334 
17335 	switch (DB_TYPE(mp)) {
17336 	case M_IOCDATA:
17337 		tcp_wput_iocdata(tcp, mp);
17338 		break;
17339 	case M_FLUSH:
17340 		tcp_wput_flush(tcp, mp);
17341 		break;
17342 	default:
17343 		CALL_IP_WPUT(connp, q, mp);
17344 		break;
17345 	}
17346 }
17347 
17348 /*
17349  * The TCP fast path write put procedure.
17350  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17351  */
17352 /* ARGSUSED */
17353 void
17354 tcp_output(void *arg, mblk_t *mp, void *arg2)
17355 {
17356 	int		len;
17357 	int		hdrlen;
17358 	int		plen;
17359 	mblk_t		*mp1;
17360 	uchar_t		*rptr;
17361 	uint32_t	snxt;
17362 	tcph_t		*tcph;
17363 	struct datab	*db;
17364 	uint32_t	suna;
17365 	uint32_t	mss;
17366 	ipaddr_t	*dst;
17367 	ipaddr_t	*src;
17368 	uint32_t	sum;
17369 	int		usable;
17370 	conn_t		*connp = (conn_t *)arg;
17371 	tcp_t		*tcp = connp->conn_tcp;
17372 	uint32_t	msize;
17373 
17374 	/*
17375 	 * Try and ASSERT the minimum possible references on the
17376 	 * conn early enough. Since we are executing on write side,
17377 	 * the connection is obviously not detached and that means
17378 	 * there is a ref each for TCP and IP. Since we are behind
17379 	 * the squeue, the minimum references needed are 3. If the
17380 	 * conn is in classifier hash list, there should be an
17381 	 * extra ref for that (we check both the possibilities).
17382 	 */
17383 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17384 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17385 
17386 	ASSERT(DB_TYPE(mp) == M_DATA);
17387 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17388 
17389 	mutex_enter(&tcp->tcp_non_sq_lock);
17390 	tcp->tcp_squeue_bytes -= msize;
17391 	mutex_exit(&tcp->tcp_non_sq_lock);
17392 
17393 	/* Bypass tcp protocol for fused tcp loopback */
17394 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17395 		return;
17396 
17397 	mss = tcp->tcp_mss;
17398 	if (tcp->tcp_xmit_zc_clean)
17399 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17400 
17401 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17402 	len = (int)(mp->b_wptr - mp->b_rptr);
17403 
17404 	/*
17405 	 * Criteria for fast path:
17406 	 *
17407 	 *   1. no unsent data
17408 	 *   2. single mblk in request
17409 	 *   3. connection established
17410 	 *   4. data in mblk
17411 	 *   5. len <= mss
17412 	 *   6. no tcp_valid bits
17413 	 */
17414 	if ((tcp->tcp_unsent != 0) ||
17415 	    (tcp->tcp_cork) ||
17416 	    (mp->b_cont != NULL) ||
17417 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17418 	    (len == 0) ||
17419 	    (len > mss) ||
17420 	    (tcp->tcp_valid_bits != 0)) {
17421 		tcp_wput_data(tcp, mp, B_FALSE);
17422 		return;
17423 	}
17424 
17425 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17426 	ASSERT(tcp->tcp_fin_sent == 0);
17427 
17428 	/* queue new packet onto retransmission queue */
17429 	if (tcp->tcp_xmit_head == NULL) {
17430 		tcp->tcp_xmit_head = mp;
17431 	} else {
17432 		tcp->tcp_xmit_last->b_cont = mp;
17433 	}
17434 	tcp->tcp_xmit_last = mp;
17435 	tcp->tcp_xmit_tail = mp;
17436 
17437 	/* find out how much we can send */
17438 	/* BEGIN CSTYLED */
17439 	/*
17440 	 *    un-acked           usable
17441 	 *  |--------------|-----------------|
17442 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17443 	 */
17444 	/* END CSTYLED */
17445 
17446 	/* start sending from tcp_snxt */
17447 	snxt = tcp->tcp_snxt;
17448 
17449 	/*
17450 	 * Check to see if this connection has been idled for some
17451 	 * time and no ACK is expected.  If it is, we need to slow
17452 	 * start again to get back the connection's "self-clock" as
17453 	 * described in VJ's paper.
17454 	 *
17455 	 * Refer to the comment in tcp_mss_set() for the calculation
17456 	 * of tcp_cwnd after idle.
17457 	 */
17458 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17459 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17460 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
17461 	}
17462 
17463 	usable = tcp->tcp_swnd;		/* tcp window size */
17464 	if (usable > tcp->tcp_cwnd)
17465 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17466 	usable -= snxt;		/* subtract stuff already sent */
17467 	suna = tcp->tcp_suna;
17468 	usable += suna;
17469 	/* usable can be < 0 if the congestion window is smaller */
17470 	if (len > usable) {
17471 		/* Can't send complete M_DATA in one shot */
17472 		goto slow;
17473 	}
17474 
17475 	mutex_enter(&tcp->tcp_non_sq_lock);
17476 	if (tcp->tcp_flow_stopped &&
17477 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17478 		tcp_clrqfull(tcp);
17479 	}
17480 	mutex_exit(&tcp->tcp_non_sq_lock);
17481 
17482 	/*
17483 	 * determine if anything to send (Nagle).
17484 	 *
17485 	 *   1. len < tcp_mss (i.e. small)
17486 	 *   2. unacknowledged data present
17487 	 *   3. len < nagle limit
17488 	 *   4. last packet sent < nagle limit (previous packet sent)
17489 	 */
17490 	if ((len < mss) && (snxt != suna) &&
17491 	    (len < (int)tcp->tcp_naglim) &&
17492 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17493 		/*
17494 		 * This was the first unsent packet and normally
17495 		 * mss < xmit_hiwater so there is no need to worry
17496 		 * about flow control. The next packet will go
17497 		 * through the flow control check in tcp_wput_data().
17498 		 */
17499 		/* leftover work from above */
17500 		tcp->tcp_unsent = len;
17501 		tcp->tcp_xmit_tail_unsent = len;
17502 
17503 		return;
17504 	}
17505 
17506 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17507 
17508 	if (snxt == suna) {
17509 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17510 	}
17511 
17512 	/* we have always sent something */
17513 	tcp->tcp_rack_cnt = 0;
17514 
17515 	tcp->tcp_snxt = snxt + len;
17516 	tcp->tcp_rack = tcp->tcp_rnxt;
17517 
17518 	if ((mp1 = dupb(mp)) == 0)
17519 		goto no_memory;
17520 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17521 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17522 
17523 	/* adjust tcp header information */
17524 	tcph = tcp->tcp_tcph;
17525 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17526 
17527 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17528 	sum = (sum >> 16) + (sum & 0xFFFF);
17529 	U16_TO_ABE16(sum, tcph->th_sum);
17530 
17531 	U32_TO_ABE32(snxt, tcph->th_seq);
17532 
17533 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
17534 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
17535 	BUMP_LOCAL(tcp->tcp_obsegs);
17536 
17537 	/* Update the latest receive window size in TCP header. */
17538 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17539 	    tcph->th_win);
17540 
17541 	tcp->tcp_last_sent_len = (ushort_t)len;
17542 
17543 	plen = len + tcp->tcp_hdr_len;
17544 
17545 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17546 		tcp->tcp_ipha->ipha_length = htons(plen);
17547 	} else {
17548 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17549 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17550 	}
17551 
17552 	/* see if we need to allocate a mblk for the headers */
17553 	hdrlen = tcp->tcp_hdr_len;
17554 	rptr = mp1->b_rptr - hdrlen;
17555 	db = mp1->b_datap;
17556 	if ((db->db_ref != 2) || rptr < db->db_base ||
17557 	    (!OK_32PTR(rptr))) {
17558 		/* NOTE: we assume allocb returns an OK_32PTR */
17559 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17560 		    tcp_wroff_xtra, BPRI_MED);
17561 		if (!mp) {
17562 			freemsg(mp1);
17563 			goto no_memory;
17564 		}
17565 		mp->b_cont = mp1;
17566 		mp1 = mp;
17567 		/* Leave room for Link Level header */
17568 		/* hdrlen = tcp->tcp_hdr_len; */
17569 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
17570 		mp1->b_wptr = &rptr[hdrlen];
17571 	}
17572 	mp1->b_rptr = rptr;
17573 
17574 	/* Fill in the timestamp option. */
17575 	if (tcp->tcp_snd_ts_ok) {
17576 		U32_TO_BE32((uint32_t)lbolt,
17577 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17578 		U32_TO_BE32(tcp->tcp_ts_recent,
17579 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17580 	} else {
17581 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17582 	}
17583 
17584 	/* copy header into outgoing packet */
17585 	dst = (ipaddr_t *)rptr;
17586 	src = (ipaddr_t *)tcp->tcp_iphc;
17587 	dst[0] = src[0];
17588 	dst[1] = src[1];
17589 	dst[2] = src[2];
17590 	dst[3] = src[3];
17591 	dst[4] = src[4];
17592 	dst[5] = src[5];
17593 	dst[6] = src[6];
17594 	dst[7] = src[7];
17595 	dst[8] = src[8];
17596 	dst[9] = src[9];
17597 	if (hdrlen -= 40) {
17598 		hdrlen >>= 2;
17599 		dst += 10;
17600 		src += 10;
17601 		do {
17602 			*dst++ = *src++;
17603 		} while (--hdrlen);
17604 	}
17605 
17606 	/*
17607 	 * Set the ECN info in the TCP header.  Note that this
17608 	 * is not the template header.
17609 	 */
17610 	if (tcp->tcp_ecn_ok) {
17611 		SET_ECT(tcp, rptr);
17612 
17613 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17614 		if (tcp->tcp_ecn_echo_on)
17615 			tcph->th_flags[0] |= TH_ECE;
17616 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17617 			tcph->th_flags[0] |= TH_CWR;
17618 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17619 		}
17620 	}
17621 
17622 	if (tcp->tcp_ip_forward_progress) {
17623 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17624 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17625 		tcp->tcp_ip_forward_progress = B_FALSE;
17626 	}
17627 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17628 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17629 	return;
17630 
17631 	/*
17632 	 * If we ran out of memory, we pretend to have sent the packet
17633 	 * and that it was lost on the wire.
17634 	 */
17635 no_memory:
17636 	return;
17637 
17638 slow:
17639 	/* leftover work from above */
17640 	tcp->tcp_unsent = len;
17641 	tcp->tcp_xmit_tail_unsent = len;
17642 	tcp_wput_data(tcp, NULL, B_FALSE);
17643 }
17644 
17645 /*
17646  * The function called through squeue to get behind eager's perimeter to
17647  * finish the accept processing.
17648  */
17649 /* ARGSUSED */
17650 void
17651 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17652 {
17653 	conn_t			*connp = (conn_t *)arg;
17654 	tcp_t			*tcp = connp->conn_tcp;
17655 	queue_t			*q = tcp->tcp_rq;
17656 	mblk_t			*mp1;
17657 	mblk_t			*stropt_mp = mp;
17658 	struct  stroptions	*stropt;
17659 	uint_t			thwin;
17660 
17661 	/*
17662 	 * Drop the eager's ref on the listener, that was placed when
17663 	 * this eager began life in tcp_conn_request.
17664 	 */
17665 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17666 
17667 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17668 		/*
17669 		 * Someone blewoff the eager before we could finish
17670 		 * the accept.
17671 		 *
17672 		 * The only reason eager exists it because we put in
17673 		 * a ref on it when conn ind went up. We need to send
17674 		 * a disconnect indication up while the last reference
17675 		 * on the eager will be dropped by the squeue when we
17676 		 * return.
17677 		 */
17678 		ASSERT(tcp->tcp_listener == NULL);
17679 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17680 			struct	T_discon_ind	*tdi;
17681 
17682 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17683 			/*
17684 			 * Let us reuse the incoming mblk to avoid memory
17685 			 * allocation failure problems. We know that the
17686 			 * size of the incoming mblk i.e. stroptions is greater
17687 			 * than sizeof T_discon_ind. So the reallocb below
17688 			 * can't fail.
17689 			 */
17690 			freemsg(mp->b_cont);
17691 			mp->b_cont = NULL;
17692 			ASSERT(DB_REF(mp) == 1);
17693 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17694 			    B_FALSE);
17695 			ASSERT(mp != NULL);
17696 			DB_TYPE(mp) = M_PROTO;
17697 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17698 			tdi = (struct T_discon_ind *)mp->b_rptr;
17699 			if (tcp->tcp_issocket) {
17700 				tdi->DISCON_reason = ECONNREFUSED;
17701 				tdi->SEQ_number = 0;
17702 			} else {
17703 				tdi->DISCON_reason = ENOPROTOOPT;
17704 				tdi->SEQ_number =
17705 				    tcp->tcp_conn_req_seqnum;
17706 			}
17707 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17708 			putnext(q, mp);
17709 		} else {
17710 			freemsg(mp);
17711 		}
17712 		if (tcp->tcp_hard_binding) {
17713 			tcp->tcp_hard_binding = B_FALSE;
17714 			tcp->tcp_hard_bound = B_TRUE;
17715 		}
17716 		tcp->tcp_detached = B_FALSE;
17717 		return;
17718 	}
17719 
17720 	mp1 = stropt_mp->b_cont;
17721 	stropt_mp->b_cont = NULL;
17722 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17723 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17724 
17725 	while (mp1 != NULL) {
17726 		mp = mp1;
17727 		mp1 = mp1->b_cont;
17728 		mp->b_cont = NULL;
17729 		tcp->tcp_drop_opt_ack_cnt++;
17730 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17731 	}
17732 	mp = NULL;
17733 
17734 	/*
17735 	 * For a loopback connection with tcp_direct_sockfs on, note that
17736 	 * we don't have to protect tcp_rcv_list yet because synchronous
17737 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17738 	 * possibly race with us.
17739 	 */
17740 
17741 	/*
17742 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17743 	 * properly.  This is the first time we know of the acceptor'
17744 	 * queue.  So we do it here.
17745 	 */
17746 	if (tcp->tcp_rcv_list == NULL) {
17747 		/*
17748 		 * Recv queue is empty, tcp_rwnd should not have changed.
17749 		 * That means it should be equal to the listener's tcp_rwnd.
17750 		 */
17751 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17752 	} else {
17753 #ifdef DEBUG
17754 		uint_t cnt = 0;
17755 
17756 		mp1 = tcp->tcp_rcv_list;
17757 		while ((mp = mp1) != NULL) {
17758 			mp1 = mp->b_next;
17759 			cnt += msgdsize(mp);
17760 		}
17761 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17762 #endif
17763 		/* There is some data, add them back to get the max. */
17764 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17765 	}
17766 
17767 	stropt->so_flags = SO_HIWAT;
17768 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
17769 
17770 	stropt->so_flags |= SO_MAXBLK;
17771 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17772 
17773 	/*
17774 	 * This is the first time we run on the correct
17775 	 * queue after tcp_accept. So fix all the q parameters
17776 	 * here.
17777 	 */
17778 	/* Allocate room for SACK options if needed. */
17779 	stropt->so_flags |= SO_WROFF;
17780 	if (tcp->tcp_fused) {
17781 		ASSERT(tcp->tcp_loopback);
17782 		ASSERT(tcp->tcp_loopback_peer != NULL);
17783 		/*
17784 		 * For fused tcp loopback, set the stream head's write
17785 		 * offset value to zero since we won't be needing any room
17786 		 * for TCP/IP headers.  This would also improve performance
17787 		 * since it would reduce the amount of work done by kmem.
17788 		 * Non-fused tcp loopback case is handled separately below.
17789 		 */
17790 		stropt->so_wroff = 0;
17791 		/*
17792 		 * Record the stream head's high water mark for this endpoint;
17793 		 * this is used for flow-control purposes in tcp_fuse_output().
17794 		 */
17795 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17796 		/*
17797 		 * Update the peer's transmit parameters according to
17798 		 * our recently calculated high water mark value.
17799 		 */
17800 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17801 	} else if (tcp->tcp_snd_sack_ok) {
17802 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17803 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17804 	} else {
17805 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17806 		    tcp_wroff_xtra);
17807 	}
17808 
17809 	/*
17810 	 * If this is endpoint is handling SSL, then reserve extra
17811 	 * offset and space at the end.
17812 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17813 	 * overriding the previous setting. The extra cost of signing and
17814 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17815 	 * instead of a single contiguous one by the stream head
17816 	 * largely outweighs the statistical reduction of ACKs, when
17817 	 * applicable. The peer will also save on decyption and verification
17818 	 * costs.
17819 	 */
17820 	if (tcp->tcp_kssl_ctx != NULL) {
17821 		stropt->so_wroff += SSL3_WROFFSET;
17822 
17823 		stropt->so_flags |= SO_TAIL;
17824 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
17825 
17826 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
17827 	}
17828 
17829 	/* Send the options up */
17830 	putnext(q, stropt_mp);
17831 
17832 	/*
17833 	 * Pass up any data and/or a fin that has been received.
17834 	 *
17835 	 * Adjust receive window in case it had decreased
17836 	 * (because there is data <=> tcp_rcv_list != NULL)
17837 	 * while the connection was detached. Note that
17838 	 * in case the eager was flow-controlled, w/o this
17839 	 * code, the rwnd may never open up again!
17840 	 */
17841 	if (tcp->tcp_rcv_list != NULL) {
17842 		/* We drain directly in case of fused tcp loopback */
17843 		if (!tcp->tcp_fused && canputnext(q)) {
17844 			tcp->tcp_rwnd = q->q_hiwat;
17845 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17846 			    << tcp->tcp_rcv_ws;
17847 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17848 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17849 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17850 				tcp_xmit_ctl(NULL,
17851 				    tcp, (tcp->tcp_swnd == 0) ?
17852 				    tcp->tcp_suna : tcp->tcp_snxt,
17853 				    tcp->tcp_rnxt, TH_ACK);
17854 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17855 			}
17856 
17857 		}
17858 		(void) tcp_rcv_drain(q, tcp);
17859 
17860 		/*
17861 		 * For fused tcp loopback, back-enable peer endpoint
17862 		 * if it's currently flow-controlled.
17863 		 */
17864 		if (tcp->tcp_fused) {
17865 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17866 
17867 			ASSERT(peer_tcp != NULL);
17868 			ASSERT(peer_tcp->tcp_fused);
17869 			/*
17870 			 * In order to change the peer's tcp_flow_stopped,
17871 			 * we need to take locks for both end points. The
17872 			 * highest address is taken first.
17873 			 */
17874 			if (peer_tcp > tcp) {
17875 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
17876 				mutex_enter(&tcp->tcp_non_sq_lock);
17877 			} else {
17878 				mutex_enter(&tcp->tcp_non_sq_lock);
17879 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
17880 			}
17881 			if (peer_tcp->tcp_flow_stopped) {
17882 				tcp_clrqfull(peer_tcp);
17883 				TCP_STAT(tcp_fusion_backenabled);
17884 			}
17885 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17886 			mutex_exit(&tcp->tcp_non_sq_lock);
17887 		}
17888 	}
17889 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17890 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17891 		mp = mi_tpi_ordrel_ind();
17892 		if (mp) {
17893 			tcp->tcp_ordrel_done = B_TRUE;
17894 			putnext(q, mp);
17895 			if (tcp->tcp_deferred_clean_death) {
17896 				/*
17897 				 * tcp_clean_death was deferred
17898 				 * for T_ORDREL_IND - do it now
17899 				 */
17900 				(void) tcp_clean_death(tcp,
17901 				    tcp->tcp_client_errno, 21);
17902 				tcp->tcp_deferred_clean_death = B_FALSE;
17903 			}
17904 		} else {
17905 			/*
17906 			 * Run the orderly release in the
17907 			 * service routine.
17908 			 */
17909 			qenable(q);
17910 		}
17911 	}
17912 	if (tcp->tcp_hard_binding) {
17913 		tcp->tcp_hard_binding = B_FALSE;
17914 		tcp->tcp_hard_bound = B_TRUE;
17915 	}
17916 
17917 	tcp->tcp_detached = B_FALSE;
17918 
17919 	/* We can enable synchronous streams now */
17920 	if (tcp->tcp_fused) {
17921 		tcp_fuse_syncstr_enable_pair(tcp);
17922 	}
17923 
17924 	if (tcp->tcp_ka_enabled) {
17925 		tcp->tcp_ka_last_intrvl = 0;
17926 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17927 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17928 	}
17929 
17930 	/*
17931 	 * At this point, eager is fully established and will
17932 	 * have the following references -
17933 	 *
17934 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17935 	 * 1 reference for the squeue which will be dropped by the squeue as
17936 	 *	soon as this function returns.
17937 	 * There will be 1 additonal reference for being in classifier
17938 	 *	hash list provided something bad hasn't happened.
17939 	 */
17940 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17941 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17942 }
17943 
17944 /*
17945  * The function called through squeue to get behind listener's perimeter to
17946  * send a deffered conn_ind.
17947  */
17948 /* ARGSUSED */
17949 void
17950 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17951 {
17952 	conn_t	*connp = (conn_t *)arg;
17953 	tcp_t *listener = connp->conn_tcp;
17954 
17955 	if (listener->tcp_state == TCPS_CLOSED ||
17956 	    TCP_IS_DETACHED(listener)) {
17957 		/*
17958 		 * If listener has closed, it would have caused a
17959 		 * a cleanup/blowoff to happen for the eager.
17960 		 */
17961 		tcp_t *tcp;
17962 		struct T_conn_ind	*conn_ind;
17963 
17964 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
17965 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17966 		    conn_ind->OPT_length);
17967 		/*
17968 		 * We need to drop the ref on eager that was put
17969 		 * tcp_rput_data() before trying to send the conn_ind
17970 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17971 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17972 		 * listener is closed so we drop the ref.
17973 		 */
17974 		CONN_DEC_REF(tcp->tcp_connp);
17975 		freemsg(mp);
17976 		return;
17977 	}
17978 	putnext(listener->tcp_rq, mp);
17979 }
17980 
17981 
17982 /*
17983  * This is the STREAMS entry point for T_CONN_RES coming down on
17984  * Acceptor STREAM when  sockfs listener does accept processing.
17985  * Read the block comment on top pf tcp_conn_request().
17986  */
17987 void
17988 tcp_wput_accept(queue_t *q, mblk_t *mp)
17989 {
17990 	queue_t *rq = RD(q);
17991 	struct T_conn_res *conn_res;
17992 	tcp_t *eager;
17993 	tcp_t *listener;
17994 	struct T_ok_ack *ok;
17995 	t_scalar_t PRIM_type;
17996 	mblk_t *opt_mp;
17997 	conn_t *econnp;
17998 
17999 	ASSERT(DB_TYPE(mp) == M_PROTO);
18000 
18001 	conn_res = (struct T_conn_res *)mp->b_rptr;
18002 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18003 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18004 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18005 		if (mp != NULL)
18006 			putnext(rq, mp);
18007 		return;
18008 	}
18009 	switch (conn_res->PRIM_type) {
18010 	case O_T_CONN_RES:
18011 	case T_CONN_RES:
18012 		/*
18013 		 * We pass up an err ack if allocb fails. This will
18014 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18015 		 * tcp_eager_blowoff to be called. sockfs will then call
18016 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18017 		 * we need to do the allocb up here because we have to
18018 		 * make sure rq->q_qinfo->qi_qclose still points to the
18019 		 * correct function (tcpclose_accept) in case allocb
18020 		 * fails.
18021 		 */
18022 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18023 		if (opt_mp == NULL) {
18024 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18025 			if (mp != NULL)
18026 				putnext(rq, mp);
18027 			return;
18028 		}
18029 
18030 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18031 		    &eager, conn_res->OPT_length);
18032 		PRIM_type = conn_res->PRIM_type;
18033 		mp->b_datap->db_type = M_PCPROTO;
18034 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18035 		ok = (struct T_ok_ack *)mp->b_rptr;
18036 		ok->PRIM_type = T_OK_ACK;
18037 		ok->CORRECT_prim = PRIM_type;
18038 		econnp = eager->tcp_connp;
18039 		econnp->conn_dev = (dev_t)q->q_ptr;
18040 		eager->tcp_rq = rq;
18041 		eager->tcp_wq = q;
18042 		rq->q_ptr = econnp;
18043 		rq->q_qinfo = &tcp_rinit;
18044 		q->q_ptr = econnp;
18045 		q->q_qinfo = &tcp_winit;
18046 		listener = eager->tcp_listener;
18047 		eager->tcp_issocket = B_TRUE;
18048 
18049 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18050 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18051 
18052 		/* Put the ref for IP */
18053 		CONN_INC_REF(econnp);
18054 
18055 		/*
18056 		 * We should have minimum of 3 references on the conn
18057 		 * at this point. One each for TCP and IP and one for
18058 		 * the T_conn_ind that was sent up when the 3-way handshake
18059 		 * completed. In the normal case we would also have another
18060 		 * reference (making a total of 4) for the conn being in the
18061 		 * classifier hash list. However the eager could have received
18062 		 * an RST subsequently and tcp_closei_local could have removed
18063 		 * the eager from the classifier hash list, hence we can't
18064 		 * assert that reference.
18065 		 */
18066 		ASSERT(econnp->conn_ref >= 3);
18067 
18068 		/*
18069 		 * Send the new local address also up to sockfs. There
18070 		 * should already be enough space in the mp that came
18071 		 * down from soaccept().
18072 		 */
18073 		if (eager->tcp_family == AF_INET) {
18074 			sin_t *sin;
18075 
18076 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18077 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18078 			sin = (sin_t *)mp->b_wptr;
18079 			mp->b_wptr += sizeof (sin_t);
18080 			sin->sin_family = AF_INET;
18081 			sin->sin_port = eager->tcp_lport;
18082 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18083 		} else {
18084 			sin6_t *sin6;
18085 
18086 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18087 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18088 			sin6 = (sin6_t *)mp->b_wptr;
18089 			mp->b_wptr += sizeof (sin6_t);
18090 			sin6->sin6_family = AF_INET6;
18091 			sin6->sin6_port = eager->tcp_lport;
18092 			if (eager->tcp_ipversion == IPV4_VERSION) {
18093 				sin6->sin6_flowinfo = 0;
18094 				IN6_IPADDR_TO_V4MAPPED(
18095 					eager->tcp_ipha->ipha_src,
18096 					    &sin6->sin6_addr);
18097 			} else {
18098 				ASSERT(eager->tcp_ip6h != NULL);
18099 				sin6->sin6_flowinfo =
18100 				    eager->tcp_ip6h->ip6_vcf &
18101 				    ~IPV6_VERS_AND_FLOW_MASK;
18102 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18103 			}
18104 			sin6->sin6_scope_id = 0;
18105 			sin6->__sin6_src_id = 0;
18106 		}
18107 
18108 		putnext(rq, mp);
18109 
18110 		opt_mp->b_datap->db_type = M_SETOPTS;
18111 		opt_mp->b_wptr += sizeof (struct stroptions);
18112 
18113 		/*
18114 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18115 		 * from listener to acceptor. The message is chained on the
18116 		 * bind_mp which tcp_rput_other will send down to IP.
18117 		 */
18118 		if (listener->tcp_bound_if != 0) {
18119 			/* allocate optmgmt req */
18120 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18121 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18122 			    sizeof (int));
18123 			if (mp != NULL)
18124 				linkb(opt_mp, mp);
18125 		}
18126 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18127 			uint_t on = 1;
18128 
18129 			/* allocate optmgmt req */
18130 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18131 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18132 			if (mp != NULL)
18133 				linkb(opt_mp, mp);
18134 		}
18135 
18136 
18137 		mutex_enter(&listener->tcp_eager_lock);
18138 
18139 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18140 
18141 			tcp_t *tail;
18142 			tcp_t *tcp;
18143 			mblk_t *mp1;
18144 
18145 			tcp = listener->tcp_eager_prev_q0;
18146 			/*
18147 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18148 			 * deferred T_conn_ind queue. We need to get to the head
18149 			 * of the queue in order to send up T_conn_ind the same
18150 			 * order as how the 3WHS is completed.
18151 			 */
18152 			while (tcp != listener) {
18153 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18154 				    !tcp->tcp_kssl_pending)
18155 					break;
18156 				else
18157 					tcp = tcp->tcp_eager_prev_q0;
18158 			}
18159 			/* None of the pending eagers can be sent up now */
18160 			if (tcp == listener)
18161 				goto no_more_eagers;
18162 
18163 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18164 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18165 			/* Move from q0 to q */
18166 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18167 			listener->tcp_conn_req_cnt_q0--;
18168 			listener->tcp_conn_req_cnt_q++;
18169 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18170 			    tcp->tcp_eager_prev_q0;
18171 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18172 			    tcp->tcp_eager_next_q0;
18173 			tcp->tcp_eager_prev_q0 = NULL;
18174 			tcp->tcp_eager_next_q0 = NULL;
18175 			tcp->tcp_conn_def_q0 = B_FALSE;
18176 
18177 			/* Make sure the tcp isn't in the list of droppables */
18178 			ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18179 			    tcp->tcp_eager_prev_drop_q0 == NULL);
18180 
18181 			/*
18182 			 * Insert at end of the queue because sockfs sends
18183 			 * down T_CONN_RES in chronological order. Leaving
18184 			 * the older conn indications at front of the queue
18185 			 * helps reducing search time.
18186 			 */
18187 			tail = listener->tcp_eager_last_q;
18188 			if (tail != NULL) {
18189 				tail->tcp_eager_next_q = tcp;
18190 			} else {
18191 				listener->tcp_eager_next_q = tcp;
18192 			}
18193 			listener->tcp_eager_last_q = tcp;
18194 			tcp->tcp_eager_next_q = NULL;
18195 
18196 			/* Need to get inside the listener perimeter */
18197 			CONN_INC_REF(listener->tcp_connp);
18198 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18199 			    tcp_send_pending, listener->tcp_connp,
18200 			    SQTAG_TCP_SEND_PENDING);
18201 		}
18202 no_more_eagers:
18203 		tcp_eager_unlink(eager);
18204 		mutex_exit(&listener->tcp_eager_lock);
18205 
18206 		/*
18207 		 * At this point, the eager is detached from the listener
18208 		 * but we still have an extra refs on eager (apart from the
18209 		 * usual tcp references). The ref was placed in tcp_rput_data
18210 		 * before sending the conn_ind in tcp_send_conn_ind.
18211 		 * The ref will be dropped in tcp_accept_finish().
18212 		 */
18213 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18214 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18215 		return;
18216 	default:
18217 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18218 		if (mp != NULL)
18219 			putnext(rq, mp);
18220 		return;
18221 	}
18222 }
18223 
18224 void
18225 tcp_wput(queue_t *q, mblk_t *mp)
18226 {
18227 	conn_t	*connp = Q_TO_CONN(q);
18228 	tcp_t	*tcp;
18229 	void (*output_proc)();
18230 	t_scalar_t type;
18231 	uchar_t *rptr;
18232 	struct iocblk	*iocp;
18233 	uint32_t	msize;
18234 
18235 	ASSERT(connp->conn_ref >= 2);
18236 
18237 	switch (DB_TYPE(mp)) {
18238 	case M_DATA:
18239 		tcp = connp->conn_tcp;
18240 		ASSERT(tcp != NULL);
18241 
18242 		msize = msgdsize(mp);
18243 
18244 		mutex_enter(&tcp->tcp_non_sq_lock);
18245 		tcp->tcp_squeue_bytes += msize;
18246 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18247 			tcp_setqfull(tcp);
18248 		}
18249 		mutex_exit(&tcp->tcp_non_sq_lock);
18250 
18251 		CONN_INC_REF(connp);
18252 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18253 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18254 		return;
18255 	case M_PROTO:
18256 	case M_PCPROTO:
18257 		/*
18258 		 * if it is a snmp message, don't get behind the squeue
18259 		 */
18260 		tcp = connp->conn_tcp;
18261 		rptr = mp->b_rptr;
18262 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18263 			type = ((union T_primitives *)rptr)->type;
18264 		} else {
18265 			if (tcp->tcp_debug) {
18266 				(void) strlog(TCP_MOD_ID, 0, 1,
18267 				    SL_ERROR|SL_TRACE,
18268 				    "tcp_wput_proto, dropping one...");
18269 			}
18270 			freemsg(mp);
18271 			return;
18272 		}
18273 		if (type == T_SVR4_OPTMGMT_REQ) {
18274 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18275 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
18276 			    cr)) {
18277 				/*
18278 				 * This was a SNMP request
18279 				 */
18280 				return;
18281 			} else {
18282 				output_proc = tcp_wput_proto;
18283 			}
18284 		} else {
18285 			output_proc = tcp_wput_proto;
18286 		}
18287 		break;
18288 	case M_IOCTL:
18289 		/*
18290 		 * Most ioctls can be processed right away without going via
18291 		 * squeues - process them right here. Those that do require
18292 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18293 		 * are processed by tcp_wput_ioctl().
18294 		 */
18295 		iocp = (struct iocblk *)mp->b_rptr;
18296 		tcp = connp->conn_tcp;
18297 
18298 		switch (iocp->ioc_cmd) {
18299 		case TCP_IOC_ABORT_CONN:
18300 			tcp_ioctl_abort_conn(q, mp);
18301 			return;
18302 		case TI_GETPEERNAME:
18303 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
18304 				iocp->ioc_error = ENOTCONN;
18305 				iocp->ioc_count = 0;
18306 				mp->b_datap->db_type = M_IOCACK;
18307 				qreply(q, mp);
18308 				return;
18309 			}
18310 			/* FALLTHRU */
18311 		case TI_GETMYNAME:
18312 			mi_copyin(q, mp, NULL,
18313 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18314 			return;
18315 		case ND_SET:
18316 			/* nd_getset does the necessary checks */
18317 		case ND_GET:
18318 			if (!nd_getset(q, tcp_g_nd, mp)) {
18319 				CALL_IP_WPUT(connp, q, mp);
18320 				return;
18321 			}
18322 			qreply(q, mp);
18323 			return;
18324 		case TCP_IOC_DEFAULT_Q:
18325 			/*
18326 			 * Wants to be the default wq. Check the credentials
18327 			 * first, the rest is executed via squeue.
18328 			 */
18329 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
18330 				iocp->ioc_error = EPERM;
18331 				iocp->ioc_count = 0;
18332 				mp->b_datap->db_type = M_IOCACK;
18333 				qreply(q, mp);
18334 				return;
18335 			}
18336 			output_proc = tcp_wput_ioctl;
18337 			break;
18338 		default:
18339 			output_proc = tcp_wput_ioctl;
18340 			break;
18341 		}
18342 		break;
18343 	default:
18344 		output_proc = tcp_wput_nondata;
18345 		break;
18346 	}
18347 
18348 	CONN_INC_REF(connp);
18349 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18350 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18351 }
18352 
18353 /*
18354  * Initial STREAMS write side put() procedure for sockets. It tries to
18355  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18356  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18357  * are handled by tcp_wput() as usual.
18358  *
18359  * All further messages will also be handled by tcp_wput() because we cannot
18360  * be sure that the above short cut is safe later.
18361  */
18362 static void
18363 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18364 {
18365 	conn_t			*connp = Q_TO_CONN(wq);
18366 	tcp_t			*tcp = connp->conn_tcp;
18367 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18368 
18369 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18370 	wq->q_qinfo = &tcp_winit;
18371 
18372 	ASSERT(IPCL_IS_TCP(connp));
18373 	ASSERT(TCP_IS_SOCKET(tcp));
18374 
18375 	if (DB_TYPE(mp) == M_PCPROTO &&
18376 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18377 	    car->PRIM_type == T_CAPABILITY_REQ) {
18378 		tcp_capability_req(tcp, mp);
18379 		return;
18380 	}
18381 
18382 	tcp_wput(wq, mp);
18383 }
18384 
18385 static boolean_t
18386 tcp_zcopy_check(tcp_t *tcp)
18387 {
18388 	conn_t	*connp = tcp->tcp_connp;
18389 	ire_t	*ire;
18390 	boolean_t	zc_enabled = B_FALSE;
18391 
18392 	if (do_tcpzcopy == 2)
18393 		zc_enabled = B_TRUE;
18394 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18395 	    IPCL_IS_CONNECTED(connp) &&
18396 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18397 	    connp->conn_dontroute == 0 &&
18398 	    !connp->conn_nexthop_set &&
18399 	    connp->conn_xmit_if_ill == NULL &&
18400 	    connp->conn_nofailover_ill == NULL &&
18401 	    do_tcpzcopy == 1) {
18402 		/*
18403 		 * the checks above  closely resemble the fast path checks
18404 		 * in tcp_send_data().
18405 		 */
18406 		mutex_enter(&connp->conn_lock);
18407 		ire = connp->conn_ire_cache;
18408 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18409 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18410 			IRE_REFHOLD(ire);
18411 			if (ire->ire_stq != NULL) {
18412 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18413 
18414 				zc_enabled = ill && (ill->ill_capabilities &
18415 				    ILL_CAPAB_ZEROCOPY) &&
18416 				    (ill->ill_zerocopy_capab->
18417 				    ill_zerocopy_flags != 0);
18418 			}
18419 			IRE_REFRELE(ire);
18420 		}
18421 		mutex_exit(&connp->conn_lock);
18422 	}
18423 	tcp->tcp_snd_zcopy_on = zc_enabled;
18424 	if (!TCP_IS_DETACHED(tcp)) {
18425 		if (zc_enabled) {
18426 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18427 			TCP_STAT(tcp_zcopy_on);
18428 		} else {
18429 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18430 			TCP_STAT(tcp_zcopy_off);
18431 		}
18432 	}
18433 	return (zc_enabled);
18434 }
18435 
18436 static mblk_t *
18437 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18438 {
18439 	if (do_tcpzcopy == 2)
18440 		return (bp);
18441 	else if (tcp->tcp_snd_zcopy_on) {
18442 		tcp->tcp_snd_zcopy_on = B_FALSE;
18443 		if (!TCP_IS_DETACHED(tcp)) {
18444 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18445 			TCP_STAT(tcp_zcopy_disable);
18446 		}
18447 	}
18448 	return (tcp_zcopy_backoff(tcp, bp, 0));
18449 }
18450 
18451 /*
18452  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18453  * the original desballoca'ed segmapped mblk.
18454  */
18455 static mblk_t *
18456 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18457 {
18458 	mblk_t *head, *tail, *nbp;
18459 	if (IS_VMLOANED_MBLK(bp)) {
18460 		TCP_STAT(tcp_zcopy_backoff);
18461 		if ((head = copyb(bp)) == NULL) {
18462 			/* fail to backoff; leave it for the next backoff */
18463 			tcp->tcp_xmit_zc_clean = B_FALSE;
18464 			return (bp);
18465 		}
18466 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18467 			if (fix_xmitlist)
18468 				tcp_zcopy_notify(tcp);
18469 			else
18470 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18471 		}
18472 		nbp = bp->b_cont;
18473 		if (fix_xmitlist) {
18474 			head->b_prev = bp->b_prev;
18475 			head->b_next = bp->b_next;
18476 			if (tcp->tcp_xmit_tail == bp)
18477 				tcp->tcp_xmit_tail = head;
18478 		}
18479 		bp->b_next = NULL;
18480 		bp->b_prev = NULL;
18481 		freeb(bp);
18482 	} else {
18483 		head = bp;
18484 		nbp = bp->b_cont;
18485 	}
18486 	tail = head;
18487 	while (nbp) {
18488 		if (IS_VMLOANED_MBLK(nbp)) {
18489 			TCP_STAT(tcp_zcopy_backoff);
18490 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18491 				tcp->tcp_xmit_zc_clean = B_FALSE;
18492 				tail->b_cont = nbp;
18493 				return (head);
18494 			}
18495 			tail = tail->b_cont;
18496 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18497 				if (fix_xmitlist)
18498 					tcp_zcopy_notify(tcp);
18499 				else
18500 					tail->b_datap->db_struioflag |=
18501 					    STRUIO_ZCNOTIFY;
18502 			}
18503 			bp = nbp;
18504 			nbp = nbp->b_cont;
18505 			if (fix_xmitlist) {
18506 				tail->b_prev = bp->b_prev;
18507 				tail->b_next = bp->b_next;
18508 				if (tcp->tcp_xmit_tail == bp)
18509 					tcp->tcp_xmit_tail = tail;
18510 			}
18511 			bp->b_next = NULL;
18512 			bp->b_prev = NULL;
18513 			freeb(bp);
18514 		} else {
18515 			tail->b_cont = nbp;
18516 			tail = nbp;
18517 			nbp = nbp->b_cont;
18518 		}
18519 	}
18520 	if (fix_xmitlist) {
18521 		tcp->tcp_xmit_last = tail;
18522 		tcp->tcp_xmit_zc_clean = B_TRUE;
18523 	}
18524 	return (head);
18525 }
18526 
18527 static void
18528 tcp_zcopy_notify(tcp_t *tcp)
18529 {
18530 	struct stdata	*stp;
18531 
18532 	if (tcp->tcp_detached)
18533 		return;
18534 	stp = STREAM(tcp->tcp_rq);
18535 	mutex_enter(&stp->sd_lock);
18536 	stp->sd_flag |= STZCNOTIFY;
18537 	cv_broadcast(&stp->sd_zcopy_wait);
18538 	mutex_exit(&stp->sd_lock);
18539 }
18540 
18541 static boolean_t
18542 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18543 {
18544 	ire_t *ire;
18545 	conn_t *connp = tcp->tcp_connp;
18546 
18547 
18548 	mutex_enter(&connp->conn_lock);
18549 	ire = connp->conn_ire_cache;
18550 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18551 
18552 	if ((ire != NULL) &&
18553 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18554 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18555 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18556 		IRE_REFHOLD(ire);
18557 		mutex_exit(&connp->conn_lock);
18558 	} else {
18559 		boolean_t cached = B_FALSE;
18560 		ts_label_t *tsl;
18561 
18562 		/* force a recheck later on */
18563 		tcp->tcp_ire_ill_check_done = B_FALSE;
18564 
18565 		TCP_DBGSTAT(tcp_ire_null1);
18566 		connp->conn_ire_cache = NULL;
18567 		mutex_exit(&connp->conn_lock);
18568 
18569 		if (ire != NULL)
18570 			IRE_REFRELE_NOTR(ire);
18571 
18572 		tsl = crgetlabel(CONN_CRED(connp));
18573 		ire = (dst ? ire_cache_lookup(*dst, connp->conn_zoneid, tsl) :
18574 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18575 		    connp->conn_zoneid, tsl));
18576 
18577 		if (ire == NULL) {
18578 			TCP_STAT(tcp_ire_null);
18579 			return (B_FALSE);
18580 		}
18581 
18582 		IRE_REFHOLD_NOTR(ire);
18583 		/*
18584 		 * Since we are inside the squeue, there cannot be another
18585 		 * thread in TCP trying to set the conn_ire_cache now.  The
18586 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18587 		 * unplumb thread has not yet started cleaning up the conns.
18588 		 * Hence we don't need to grab the conn lock.
18589 		 */
18590 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
18591 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18592 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18593 				connp->conn_ire_cache = ire;
18594 				cached = B_TRUE;
18595 			}
18596 			rw_exit(&ire->ire_bucket->irb_lock);
18597 		}
18598 
18599 		/*
18600 		 * We can continue to use the ire but since it was
18601 		 * not cached, we should drop the extra reference.
18602 		 */
18603 		if (!cached)
18604 			IRE_REFRELE_NOTR(ire);
18605 
18606 		/*
18607 		 * Rampart note: no need to select a new label here, since
18608 		 * labels are not allowed to change during the life of a TCP
18609 		 * connection.
18610 		 */
18611 	}
18612 
18613 	*irep = ire;
18614 
18615 	return (B_TRUE);
18616 }
18617 
18618 /*
18619  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18620  *
18621  * 0 = success;
18622  * 1 = failed to find ire and ill.
18623  */
18624 static boolean_t
18625 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18626 {
18627 	ipha_t		*ipha;
18628 	ipaddr_t	dst;
18629 	ire_t		*ire;
18630 	ill_t		*ill;
18631 	conn_t		*connp = tcp->tcp_connp;
18632 	mblk_t		*ire_fp_mp;
18633 
18634 	if (mp != NULL)
18635 		ipha = (ipha_t *)mp->b_rptr;
18636 	else
18637 		ipha = tcp->tcp_ipha;
18638 	dst = ipha->ipha_dst;
18639 
18640 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18641 		return (B_FALSE);
18642 
18643 	if ((ire->ire_flags & RTF_MULTIRT) ||
18644 	    (ire->ire_stq == NULL) ||
18645 	    (ire->ire_nce == NULL) ||
18646 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18647 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18648 		MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18649 		TCP_STAT(tcp_ip_ire_send);
18650 		IRE_REFRELE(ire);
18651 		return (B_FALSE);
18652 	}
18653 
18654 	ill = ire_to_ill(ire);
18655 	if (connp->conn_outgoing_ill != NULL) {
18656 		ill_t *conn_outgoing_ill = NULL;
18657 		/*
18658 		 * Choose a good ill in the group to send the packets on.
18659 		 */
18660 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18661 		ill = ire_to_ill(ire);
18662 	}
18663 	ASSERT(ill != NULL);
18664 
18665 	if (!tcp->tcp_ire_ill_check_done) {
18666 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18667 		tcp->tcp_ire_ill_check_done = B_TRUE;
18668 	}
18669 
18670 	*irep = ire;
18671 	*illp = ill;
18672 
18673 	return (B_TRUE);
18674 }
18675 
18676 static void
18677 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18678 {
18679 	ipha_t		*ipha;
18680 	ipaddr_t	src;
18681 	ipaddr_t	dst;
18682 	uint32_t	cksum;
18683 	ire_t		*ire;
18684 	uint16_t	*up;
18685 	ill_t		*ill;
18686 	conn_t		*connp = tcp->tcp_connp;
18687 	uint32_t	hcksum_txflags = 0;
18688 	mblk_t		*ire_fp_mp;
18689 	uint_t		ire_fp_mp_len;
18690 
18691 	ASSERT(DB_TYPE(mp) == M_DATA);
18692 
18693 	if (DB_CRED(mp) == NULL)
18694 		mblk_setcred(mp, CONN_CRED(connp));
18695 
18696 	ipha = (ipha_t *)mp->b_rptr;
18697 	src = ipha->ipha_src;
18698 	dst = ipha->ipha_dst;
18699 
18700 	/*
18701 	 * Drop off fast path for IPv6 and also if options are present or
18702 	 * we need to resolve a TS label.
18703 	 */
18704 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18705 	    !IPCL_IS_CONNECTED(connp) ||
18706 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18707 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18708 	    !connp->conn_ulp_labeled ||
18709 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18710 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18711 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
18712 		if (tcp->tcp_snd_zcopy_aware)
18713 			mp = tcp_zcopy_disable(tcp, mp);
18714 		TCP_STAT(tcp_ip_send);
18715 		CALL_IP_WPUT(connp, q, mp);
18716 		return;
18717 	}
18718 
18719 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18720 		if (tcp->tcp_snd_zcopy_aware)
18721 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18722 		CALL_IP_WPUT(connp, q, mp);
18723 		return;
18724 	}
18725 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18726 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18727 
18728 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18729 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18730 #ifndef _BIG_ENDIAN
18731 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18732 #endif
18733 
18734 	/*
18735 	 * Check to see if we need to re-enable LSO/MDT for this connection
18736 	 * because it was previously disabled due to changes in the ill;
18737 	 * note that by doing it here, this re-enabling only applies when
18738 	 * the packet is not dispatched through CALL_IP_WPUT().
18739 	 *
18740 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18741 	 * case, since that's how we ended up here.  For IPv6, we do the
18742 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18743 	 */
18744 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18745 		/*
18746 		 * Restore LSO for this connection, so that next time around
18747 		 * it is eligible to go through tcp_lsosend() path again.
18748 		 */
18749 		TCP_STAT(tcp_lso_enabled);
18750 		tcp->tcp_lso = B_TRUE;
18751 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18752 		    "interface %s\n", (void *)connp, ill->ill_name));
18753 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18754 		/*
18755 		 * Restore MDT for this connection, so that next time around
18756 		 * it is eligible to go through tcp_multisend() path again.
18757 		 */
18758 		TCP_STAT(tcp_mdt_conn_resumed1);
18759 		tcp->tcp_mdt = B_TRUE;
18760 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18761 		    "interface %s\n", (void *)connp, ill->ill_name));
18762 	}
18763 
18764 	if (tcp->tcp_snd_zcopy_aware) {
18765 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18766 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18767 			mp = tcp_zcopy_disable(tcp, mp);
18768 		/*
18769 		 * we shouldn't need to reset ipha as the mp containing
18770 		 * ipha should never be a zero-copy mp.
18771 		 */
18772 	}
18773 
18774 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18775 		ASSERT(ill->ill_hcksum_capab != NULL);
18776 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18777 	}
18778 
18779 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18780 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18781 
18782 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18783 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18784 
18785 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18786 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18787 
18788 	/* Software checksum? */
18789 	if (DB_CKSUMFLAGS(mp) == 0) {
18790 		TCP_STAT(tcp_out_sw_cksum);
18791 		TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
18792 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18793 	}
18794 
18795 	ipha->ipha_fragment_offset_and_flags |=
18796 	    (uint32_t)htons(ire->ire_frag_flag);
18797 
18798 	/* Calculate IP header checksum if hardware isn't capable */
18799 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18800 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18801 		    ((uint16_t *)ipha)[4]);
18802 	}
18803 
18804 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18805 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18806 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18807 
18808 	UPDATE_OB_PKT_COUNT(ire);
18809 	ire->ire_last_used_time = lbolt;
18810 
18811 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18812 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18813 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18814 	    ntohs(ipha->ipha_length));
18815 
18816 	if (ILL_DLS_CAPABLE(ill)) {
18817 		/*
18818 		 * Send the packet directly to DLD, where it may be queued
18819 		 * depending on the availability of transmit resources at
18820 		 * the media layer.
18821 		 */
18822 		IP_DLS_ILL_TX(ill, ipha, mp);
18823 	} else {
18824 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
18825 		DTRACE_PROBE4(ip4__physical__out__start,
18826 		    ill_t *, NULL, ill_t *, out_ill,
18827 		    ipha_t *, ipha, mblk_t *, mp);
18828 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
18829 		    NULL, out_ill, ipha, mp, mp);
18830 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18831 		if (mp != NULL)
18832 			putnext(ire->ire_stq, mp);
18833 	}
18834 	IRE_REFRELE(ire);
18835 }
18836 
18837 /*
18838  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18839  * if the receiver shrinks the window, i.e. moves the right window to the
18840  * left, the we should not send new data, but should retransmit normally the
18841  * old unacked data between suna and suna + swnd. We might has sent data
18842  * that is now outside the new window, pretend that we didn't send  it.
18843  */
18844 static void
18845 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18846 {
18847 	uint32_t	snxt = tcp->tcp_snxt;
18848 	mblk_t		*xmit_tail;
18849 	int32_t		offset;
18850 
18851 	ASSERT(shrunk_count > 0);
18852 
18853 	/* Pretend we didn't send the data outside the window */
18854 	snxt -= shrunk_count;
18855 
18856 	/* Get the mblk and the offset in it per the shrunk window */
18857 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18858 
18859 	ASSERT(xmit_tail != NULL);
18860 
18861 	/* Reset all the values per the now shrunk window */
18862 	tcp->tcp_snxt = snxt;
18863 	tcp->tcp_xmit_tail = xmit_tail;
18864 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18865 	    offset;
18866 	tcp->tcp_unsent += shrunk_count;
18867 
18868 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18869 		/*
18870 		 * Make sure the timer is running so that we will probe a zero
18871 		 * window.
18872 		 */
18873 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18874 }
18875 
18876 
18877 /*
18878  * The TCP normal data output path.
18879  * NOTE: the logic of the fast path is duplicated from this function.
18880  */
18881 static void
18882 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18883 {
18884 	int		len;
18885 	mblk_t		*local_time;
18886 	mblk_t		*mp1;
18887 	uint32_t	snxt;
18888 	int		tail_unsent;
18889 	int		tcpstate;
18890 	int		usable = 0;
18891 	mblk_t		*xmit_tail;
18892 	queue_t		*q = tcp->tcp_wq;
18893 	int32_t		mss;
18894 	int32_t		num_sack_blk = 0;
18895 	int32_t		tcp_hdr_len;
18896 	int32_t		tcp_tcp_hdr_len;
18897 	int		mdt_thres;
18898 	int		rc;
18899 
18900 	tcpstate = tcp->tcp_state;
18901 	if (mp == NULL) {
18902 		/*
18903 		 * tcp_wput_data() with NULL mp should only be called when
18904 		 * there is unsent data.
18905 		 */
18906 		ASSERT(tcp->tcp_unsent > 0);
18907 		/* Really tacky... but we need this for detached closes. */
18908 		len = tcp->tcp_unsent;
18909 		goto data_null;
18910 	}
18911 
18912 #if CCS_STATS
18913 	wrw_stats.tot.count++;
18914 	wrw_stats.tot.bytes += msgdsize(mp);
18915 #endif
18916 	ASSERT(mp->b_datap->db_type == M_DATA);
18917 	/*
18918 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18919 	 * or before a connection attempt has begun.
18920 	 */
18921 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18922 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18923 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18924 #ifdef DEBUG
18925 			cmn_err(CE_WARN,
18926 			    "tcp_wput_data: data after ordrel, %s",
18927 			    tcp_display(tcp, NULL,
18928 			    DISP_ADDR_AND_PORT));
18929 #else
18930 			if (tcp->tcp_debug) {
18931 				(void) strlog(TCP_MOD_ID, 0, 1,
18932 				    SL_TRACE|SL_ERROR,
18933 				    "tcp_wput_data: data after ordrel, %s\n",
18934 				    tcp_display(tcp, NULL,
18935 				    DISP_ADDR_AND_PORT));
18936 			}
18937 #endif /* DEBUG */
18938 		}
18939 		if (tcp->tcp_snd_zcopy_aware &&
18940 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18941 			tcp_zcopy_notify(tcp);
18942 		freemsg(mp);
18943 		mutex_enter(&tcp->tcp_non_sq_lock);
18944 		if (tcp->tcp_flow_stopped &&
18945 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18946 			tcp_clrqfull(tcp);
18947 		}
18948 		mutex_exit(&tcp->tcp_non_sq_lock);
18949 		return;
18950 	}
18951 
18952 	/* Strip empties */
18953 	for (;;) {
18954 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18955 		    (uintptr_t)INT_MAX);
18956 		len = (int)(mp->b_wptr - mp->b_rptr);
18957 		if (len > 0)
18958 			break;
18959 		mp1 = mp;
18960 		mp = mp->b_cont;
18961 		freeb(mp1);
18962 		if (!mp) {
18963 			return;
18964 		}
18965 	}
18966 
18967 	/* If we are the first on the list ... */
18968 	if (tcp->tcp_xmit_head == NULL) {
18969 		tcp->tcp_xmit_head = mp;
18970 		tcp->tcp_xmit_tail = mp;
18971 		tcp->tcp_xmit_tail_unsent = len;
18972 	} else {
18973 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18974 		struct datab *dp;
18975 
18976 		mp1 = tcp->tcp_xmit_last;
18977 		if (len < tcp_tx_pull_len &&
18978 		    (dp = mp1->b_datap)->db_ref == 1 &&
18979 		    dp->db_lim - mp1->b_wptr >= len) {
18980 			ASSERT(len > 0);
18981 			ASSERT(!mp1->b_cont);
18982 			if (len == 1) {
18983 				*mp1->b_wptr++ = *mp->b_rptr;
18984 			} else {
18985 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18986 				mp1->b_wptr += len;
18987 			}
18988 			if (mp1 == tcp->tcp_xmit_tail)
18989 				tcp->tcp_xmit_tail_unsent += len;
18990 			mp1->b_cont = mp->b_cont;
18991 			if (tcp->tcp_snd_zcopy_aware &&
18992 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18993 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18994 			freeb(mp);
18995 			mp = mp1;
18996 		} else {
18997 			tcp->tcp_xmit_last->b_cont = mp;
18998 		}
18999 		len += tcp->tcp_unsent;
19000 	}
19001 
19002 	/* Tack on however many more positive length mblks we have */
19003 	if ((mp1 = mp->b_cont) != NULL) {
19004 		do {
19005 			int tlen;
19006 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19007 			    (uintptr_t)INT_MAX);
19008 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19009 			if (tlen <= 0) {
19010 				mp->b_cont = mp1->b_cont;
19011 				freeb(mp1);
19012 			} else {
19013 				len += tlen;
19014 				mp = mp1;
19015 			}
19016 		} while ((mp1 = mp->b_cont) != NULL);
19017 	}
19018 	tcp->tcp_xmit_last = mp;
19019 	tcp->tcp_unsent = len;
19020 
19021 	if (urgent)
19022 		usable = 1;
19023 
19024 data_null:
19025 	snxt = tcp->tcp_snxt;
19026 	xmit_tail = tcp->tcp_xmit_tail;
19027 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19028 
19029 	/*
19030 	 * Note that tcp_mss has been adjusted to take into account the
19031 	 * timestamp option if applicable.  Because SACK options do not
19032 	 * appear in every TCP segments and they are of variable lengths,
19033 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19034 	 * the actual segment length when we need to send a segment which
19035 	 * includes SACK options.
19036 	 */
19037 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19038 		int32_t	opt_len;
19039 
19040 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19041 		    tcp->tcp_num_sack_blk);
19042 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19043 		    2 + TCPOPT_HEADER_LEN;
19044 		mss = tcp->tcp_mss - opt_len;
19045 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19046 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19047 	} else {
19048 		mss = tcp->tcp_mss;
19049 		tcp_hdr_len = tcp->tcp_hdr_len;
19050 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19051 	}
19052 
19053 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19054 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19055 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
19056 	}
19057 	if (tcpstate == TCPS_SYN_RCVD) {
19058 		/*
19059 		 * The three-way connection establishment handshake is not
19060 		 * complete yet. We want to queue the data for transmission
19061 		 * after entering ESTABLISHED state (RFC793). A jump to
19062 		 * "done" label effectively leaves data on the queue.
19063 		 */
19064 		goto done;
19065 	} else {
19066 		int usable_r;
19067 
19068 		/*
19069 		 * In the special case when cwnd is zero, which can only
19070 		 * happen if the connection is ECN capable, return now.
19071 		 * New segments is sent using tcp_timer().  The timer
19072 		 * is set in tcp_rput_data().
19073 		 */
19074 		if (tcp->tcp_cwnd == 0) {
19075 			/*
19076 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19077 			 * finished.
19078 			 */
19079 			ASSERT(tcp->tcp_ecn_ok ||
19080 			    tcp->tcp_state < TCPS_ESTABLISHED);
19081 			return;
19082 		}
19083 
19084 		/* NOTE: trouble if xmitting while SYN not acked? */
19085 		usable_r = snxt - tcp->tcp_suna;
19086 		usable_r = tcp->tcp_swnd - usable_r;
19087 
19088 		/*
19089 		 * Check if the receiver has shrunk the window.  If
19090 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19091 		 * cannot be set as there is unsent data, so FIN cannot
19092 		 * be sent out.  Otherwise, we need to take into account
19093 		 * of FIN as it consumes an "invisible" sequence number.
19094 		 */
19095 		ASSERT(tcp->tcp_fin_sent == 0);
19096 		if (usable_r < 0) {
19097 			/*
19098 			 * The receiver has shrunk the window and we have sent
19099 			 * -usable_r date beyond the window, re-adjust.
19100 			 *
19101 			 * If TCP window scaling is enabled, there can be
19102 			 * round down error as the advertised receive window
19103 			 * is actually right shifted n bits.  This means that
19104 			 * the lower n bits info is wiped out.  It will look
19105 			 * like the window is shrunk.  Do a check here to
19106 			 * see if the shrunk amount is actually within the
19107 			 * error in window calculation.  If it is, just
19108 			 * return.  Note that this check is inside the
19109 			 * shrunk window check.  This makes sure that even
19110 			 * though tcp_process_shrunk_swnd() is not called,
19111 			 * we will stop further processing.
19112 			 */
19113 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19114 				tcp_process_shrunk_swnd(tcp, -usable_r);
19115 			}
19116 			return;
19117 		}
19118 
19119 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19120 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19121 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19122 
19123 		/* usable = MIN(usable, unsent) */
19124 		if (usable_r > len)
19125 			usable_r = len;
19126 
19127 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19128 		if (usable_r > 0) {
19129 			usable = usable_r;
19130 		} else {
19131 			/* Bypass all other unnecessary processing. */
19132 			goto done;
19133 		}
19134 	}
19135 
19136 	local_time = (mblk_t *)lbolt;
19137 
19138 	/*
19139 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19140 	 * BSD.  This is more in line with the true intent of Nagle.
19141 	 *
19142 	 * The conditions are:
19143 	 * 1. The amount of unsent data (or amount of data which can be
19144 	 *    sent, whichever is smaller) is less than Nagle limit.
19145 	 * 2. The last sent size is also less than Nagle limit.
19146 	 * 3. There is unack'ed data.
19147 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19148 	 *    Nagle algorithm.  This reduces the probability that urgent
19149 	 *    bytes get "merged" together.
19150 	 * 5. The app has not closed the connection.  This eliminates the
19151 	 *    wait time of the receiving side waiting for the last piece of
19152 	 *    (small) data.
19153 	 *
19154 	 * If all are satisified, exit without sending anything.  Note
19155 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19156 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19157 	 * 4095).
19158 	 */
19159 	if (usable < (int)tcp->tcp_naglim &&
19160 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19161 	    snxt != tcp->tcp_suna &&
19162 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19163 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19164 		goto done;
19165 	}
19166 
19167 	if (tcp->tcp_cork) {
19168 		/*
19169 		 * if the tcp->tcp_cork option is set, then we have to force
19170 		 * TCP not to send partial segment (smaller than MSS bytes).
19171 		 * We are calculating the usable now based on full mss and
19172 		 * will save the rest of remaining data for later.
19173 		 */
19174 		if (usable < mss)
19175 			goto done;
19176 		usable = (usable / mss) * mss;
19177 	}
19178 
19179 	/* Update the latest receive window size in TCP header. */
19180 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19181 	    tcp->tcp_tcph->th_win);
19182 
19183 	/*
19184 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19185 	 *
19186 	 * 1. Simple TCP/IP{v4,v6} (no options).
19187 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19188 	 * 3. If the TCP connection is in ESTABLISHED state.
19189 	 * 4. The TCP is not detached.
19190 	 *
19191 	 * If any of the above conditions have changed during the
19192 	 * connection, stop using LSO/MDT and restore the stream head
19193 	 * parameters accordingly.
19194 	 */
19195 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19196 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19197 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19198 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19199 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19200 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19201 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19202 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19203 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
19204 		if (tcp->tcp_lso) {
19205 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19206 			tcp->tcp_lso = B_FALSE;
19207 		} else {
19208 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19209 			tcp->tcp_mdt = B_FALSE;
19210 		}
19211 
19212 		/* Anything other than detached is considered pathological */
19213 		if (!TCP_IS_DETACHED(tcp)) {
19214 			if (tcp->tcp_lso)
19215 				TCP_STAT(tcp_lso_disabled);
19216 			else
19217 				TCP_STAT(tcp_mdt_conn_halted1);
19218 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19219 		}
19220 	}
19221 
19222 	/* Use MDT if sendable amount is greater than the threshold */
19223 	if (tcp->tcp_mdt &&
19224 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19225 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19226 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19227 	    (tcp->tcp_valid_bits == 0 ||
19228 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19229 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19230 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19231 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19232 		    local_time, mdt_thres);
19233 	} else {
19234 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19235 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19236 		    local_time, INT_MAX);
19237 	}
19238 
19239 	/* Pretend that all we were trying to send really got sent */
19240 	if (rc < 0 && tail_unsent < 0) {
19241 		do {
19242 			xmit_tail = xmit_tail->b_cont;
19243 			xmit_tail->b_prev = local_time;
19244 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19245 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19246 			tail_unsent += (int)(xmit_tail->b_wptr -
19247 			    xmit_tail->b_rptr);
19248 		} while (tail_unsent < 0);
19249 	}
19250 done:;
19251 	tcp->tcp_xmit_tail = xmit_tail;
19252 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19253 	len = tcp->tcp_snxt - snxt;
19254 	if (len) {
19255 		/*
19256 		 * If new data was sent, need to update the notsack
19257 		 * list, which is, afterall, data blocks that have
19258 		 * not been sack'ed by the receiver.  New data is
19259 		 * not sack'ed.
19260 		 */
19261 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19262 			/* len is a negative value. */
19263 			tcp->tcp_pipe -= len;
19264 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19265 			    tcp->tcp_snxt, snxt,
19266 			    &(tcp->tcp_num_notsack_blk),
19267 			    &(tcp->tcp_cnt_notsack_list));
19268 		}
19269 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19270 		tcp->tcp_rack = tcp->tcp_rnxt;
19271 		tcp->tcp_rack_cnt = 0;
19272 		if ((snxt + len) == tcp->tcp_suna) {
19273 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19274 		}
19275 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19276 		/*
19277 		 * Didn't send anything. Make sure the timer is running
19278 		 * so that we will probe a zero window.
19279 		 */
19280 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19281 	}
19282 	/* Note that len is the amount we just sent but with a negative sign */
19283 	tcp->tcp_unsent += len;
19284 	mutex_enter(&tcp->tcp_non_sq_lock);
19285 	if (tcp->tcp_flow_stopped) {
19286 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19287 			tcp_clrqfull(tcp);
19288 		}
19289 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19290 		tcp_setqfull(tcp);
19291 	}
19292 	mutex_exit(&tcp->tcp_non_sq_lock);
19293 }
19294 
19295 /*
19296  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19297  * outgoing TCP header with the template header, as well as other
19298  * options such as time-stamp, ECN and/or SACK.
19299  */
19300 static void
19301 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19302 {
19303 	tcph_t *tcp_tmpl, *tcp_h;
19304 	uint32_t *dst, *src;
19305 	int hdrlen;
19306 
19307 	ASSERT(OK_32PTR(rptr));
19308 
19309 	/* Template header */
19310 	tcp_tmpl = tcp->tcp_tcph;
19311 
19312 	/* Header of outgoing packet */
19313 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19314 
19315 	/* dst and src are opaque 32-bit fields, used for copying */
19316 	dst = (uint32_t *)rptr;
19317 	src = (uint32_t *)tcp->tcp_iphc;
19318 	hdrlen = tcp->tcp_hdr_len;
19319 
19320 	/* Fill time-stamp option if needed */
19321 	if (tcp->tcp_snd_ts_ok) {
19322 		U32_TO_BE32((uint32_t)now,
19323 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19324 		U32_TO_BE32(tcp->tcp_ts_recent,
19325 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19326 	} else {
19327 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19328 	}
19329 
19330 	/*
19331 	 * Copy the template header; is this really more efficient than
19332 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19333 	 * but perhaps not for other scenarios.
19334 	 */
19335 	dst[0] = src[0];
19336 	dst[1] = src[1];
19337 	dst[2] = src[2];
19338 	dst[3] = src[3];
19339 	dst[4] = src[4];
19340 	dst[5] = src[5];
19341 	dst[6] = src[6];
19342 	dst[7] = src[7];
19343 	dst[8] = src[8];
19344 	dst[9] = src[9];
19345 	if (hdrlen -= 40) {
19346 		hdrlen >>= 2;
19347 		dst += 10;
19348 		src += 10;
19349 		do {
19350 			*dst++ = *src++;
19351 		} while (--hdrlen);
19352 	}
19353 
19354 	/*
19355 	 * Set the ECN info in the TCP header if it is not a zero
19356 	 * window probe.  Zero window probe is only sent in
19357 	 * tcp_wput_data() and tcp_timer().
19358 	 */
19359 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19360 		SET_ECT(tcp, rptr);
19361 
19362 		if (tcp->tcp_ecn_echo_on)
19363 			tcp_h->th_flags[0] |= TH_ECE;
19364 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19365 			tcp_h->th_flags[0] |= TH_CWR;
19366 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19367 		}
19368 	}
19369 
19370 	/* Fill in SACK options */
19371 	if (num_sack_blk > 0) {
19372 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19373 		sack_blk_t *tmp;
19374 		int32_t	i;
19375 
19376 		wptr[0] = TCPOPT_NOP;
19377 		wptr[1] = TCPOPT_NOP;
19378 		wptr[2] = TCPOPT_SACK;
19379 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19380 		    sizeof (sack_blk_t);
19381 		wptr += TCPOPT_REAL_SACK_LEN;
19382 
19383 		tmp = tcp->tcp_sack_list;
19384 		for (i = 0; i < num_sack_blk; i++) {
19385 			U32_TO_BE32(tmp[i].begin, wptr);
19386 			wptr += sizeof (tcp_seq);
19387 			U32_TO_BE32(tmp[i].end, wptr);
19388 			wptr += sizeof (tcp_seq);
19389 		}
19390 		tcp_h->th_offset_and_rsrvd[0] +=
19391 		    ((num_sack_blk * 2 + 1) << 4);
19392 	}
19393 }
19394 
19395 /*
19396  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19397  * the destination address and SAP attribute, and if necessary, the
19398  * hardware checksum offload attribute to a Multidata message.
19399  */
19400 static int
19401 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19402     const uint32_t start, const uint32_t stuff, const uint32_t end,
19403     const uint32_t flags)
19404 {
19405 	/* Add global destination address & SAP attribute */
19406 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19407 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19408 		    "destination address+SAP\n"));
19409 
19410 		if (dlmp != NULL)
19411 			TCP_STAT(tcp_mdt_allocfail);
19412 		return (-1);
19413 	}
19414 
19415 	/* Add global hwcksum attribute */
19416 	if (hwcksum &&
19417 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19418 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19419 		    "checksum attribute\n"));
19420 
19421 		TCP_STAT(tcp_mdt_allocfail);
19422 		return (-1);
19423 	}
19424 
19425 	return (0);
19426 }
19427 
19428 /*
19429  * Smaller and private version of pdescinfo_t used specifically for TCP,
19430  * which allows for only two payload spans per packet.
19431  */
19432 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19433 
19434 /*
19435  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19436  * scheme, and returns one the following:
19437  *
19438  * -1 = failed allocation.
19439  *  0 = success; burst count reached, or usable send window is too small,
19440  *      and that we'd rather wait until later before sending again.
19441  */
19442 static int
19443 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19444     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19445     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19446     const int mdt_thres)
19447 {
19448 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19449 	multidata_t	*mmd;
19450 	uint_t		obsegs, obbytes, hdr_frag_sz;
19451 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19452 	int		num_burst_seg, max_pld;
19453 	pdesc_t		*pkt;
19454 	tcp_pdescinfo_t	tcp_pkt_info;
19455 	pdescinfo_t	*pkt_info;
19456 	int		pbuf_idx, pbuf_idx_nxt;
19457 	int		seg_len, len, spill, af;
19458 	boolean_t	add_buffer, zcopy, clusterwide;
19459 	boolean_t	buf_trunked = B_FALSE;
19460 	boolean_t	rconfirm = B_FALSE;
19461 	boolean_t	done = B_FALSE;
19462 	uint32_t	cksum;
19463 	uint32_t	hwcksum_flags;
19464 	ire_t		*ire = NULL;
19465 	ill_t		*ill;
19466 	ipha_t		*ipha;
19467 	ip6_t		*ip6h;
19468 	ipaddr_t	src, dst;
19469 	ill_zerocopy_capab_t *zc_cap = NULL;
19470 	uint16_t	*up;
19471 	int		err;
19472 	conn_t		*connp;
19473 	mblk_t		*mp, *mp1, *fw_mp_head = NULL;
19474 	uchar_t		*pld_start;
19475 
19476 #ifdef	_BIG_ENDIAN
19477 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19478 #else
19479 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19480 #endif
19481 
19482 #define	PREP_NEW_MULTIDATA() {			\
19483 	mmd = NULL;				\
19484 	md_mp = md_hbuf = NULL;			\
19485 	cur_hdr_off = 0;			\
19486 	max_pld = tcp->tcp_mdt_max_pld;		\
19487 	pbuf_idx = pbuf_idx_nxt = -1;		\
19488 	add_buffer = B_TRUE;			\
19489 	zcopy = B_FALSE;			\
19490 }
19491 
19492 #define	PREP_NEW_PBUF() {			\
19493 	md_pbuf = md_pbuf_nxt = NULL;		\
19494 	pbuf_idx = pbuf_idx_nxt = -1;		\
19495 	cur_pld_off = 0;			\
19496 	first_snxt = *snxt;			\
19497 	ASSERT(*tail_unsent > 0);		\
19498 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19499 }
19500 
19501 	ASSERT(mdt_thres >= mss);
19502 	ASSERT(*usable > 0 && *usable > mdt_thres);
19503 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19504 	ASSERT(!TCP_IS_DETACHED(tcp));
19505 	ASSERT(tcp->tcp_valid_bits == 0 ||
19506 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19507 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19508 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19509 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19510 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19511 
19512 	connp = tcp->tcp_connp;
19513 	ASSERT(connp != NULL);
19514 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19515 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19516 
19517 	/*
19518 	 * Note that tcp will only declare at most 2 payload spans per
19519 	 * packet, which is much lower than the maximum allowable number
19520 	 * of packet spans per Multidata.  For this reason, we use the
19521 	 * privately declared and smaller descriptor info structure, in
19522 	 * order to save some stack space.
19523 	 */
19524 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19525 
19526 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19527 	if (af == AF_INET) {
19528 		dst = tcp->tcp_ipha->ipha_dst;
19529 		src = tcp->tcp_ipha->ipha_src;
19530 		ASSERT(!CLASSD(dst));
19531 	}
19532 	ASSERT(af == AF_INET ||
19533 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19534 
19535 	obsegs = obbytes = 0;
19536 	num_burst_seg = tcp->tcp_snd_burst;
19537 	md_mp_head = NULL;
19538 	PREP_NEW_MULTIDATA();
19539 
19540 	/*
19541 	 * Before we go on further, make sure there is an IRE that we can
19542 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19543 	 * in proceeding any further, and we should just hand everything
19544 	 * off to the legacy path.
19545 	 */
19546 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19547 		goto legacy_send_no_md;
19548 
19549 	ASSERT(ire != NULL);
19550 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19551 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19552 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19553 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19554 	/*
19555 	 * If we do support loopback for MDT (which requires modifications
19556 	 * to the receiving paths), the following assertions should go away,
19557 	 * and we would be sending the Multidata to loopback conn later on.
19558 	 */
19559 	ASSERT(!IRE_IS_LOCAL(ire));
19560 	ASSERT(ire->ire_stq != NULL);
19561 
19562 	ill = ire_to_ill(ire);
19563 	ASSERT(ill != NULL);
19564 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19565 
19566 	if (!tcp->tcp_ire_ill_check_done) {
19567 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19568 		tcp->tcp_ire_ill_check_done = B_TRUE;
19569 	}
19570 
19571 	/*
19572 	 * If the underlying interface conditions have changed, or if the
19573 	 * new interface does not support MDT, go back to legacy path.
19574 	 */
19575 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19576 		/* don't go through this path anymore for this connection */
19577 		TCP_STAT(tcp_mdt_conn_halted2);
19578 		tcp->tcp_mdt = B_FALSE;
19579 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19580 		    "interface %s\n", (void *)connp, ill->ill_name));
19581 		/* IRE will be released prior to returning */
19582 		goto legacy_send_no_md;
19583 	}
19584 
19585 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19586 		zc_cap = ill->ill_zerocopy_capab;
19587 
19588 	/*
19589 	 * Check if we can take tcp fast-path. Note that "incomplete"
19590 	 * ire's (where the link-layer for next hop is not resolved
19591 	 * or where the fast-path header in nce_fp_mp is not available
19592 	 * yet) are sent down the legacy (slow) path.
19593 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19594 	 */
19595 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19596 		/* IRE will be released prior to returning */
19597 		goto legacy_send_no_md;
19598 	}
19599 
19600 	/* go to legacy path if interface doesn't support zerocopy */
19601 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19602 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19603 		/* IRE will be released prior to returning */
19604 		goto legacy_send_no_md;
19605 	}
19606 
19607 	/* does the interface support hardware checksum offload? */
19608 	hwcksum_flags = 0;
19609 	if (ILL_HCKSUM_CAPABLE(ill) &&
19610 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19611 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19612 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19613 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19614 		    HCKSUM_IPHDRCKSUM)
19615 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19616 
19617 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19618 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19619 			hwcksum_flags |= HCK_FULLCKSUM;
19620 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19621 		    HCKSUM_INET_PARTIAL)
19622 			hwcksum_flags |= HCK_PARTIALCKSUM;
19623 	}
19624 
19625 	/*
19626 	 * Each header fragment consists of the leading extra space,
19627 	 * followed by the TCP/IP header, and the trailing extra space.
19628 	 * We make sure that each header fragment begins on a 32-bit
19629 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19630 	 * aligned in tcp_mdt_update).
19631 	 */
19632 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19633 	    tcp->tcp_mdt_hdr_tail), 4);
19634 
19635 	/* are we starting from the beginning of data block? */
19636 	if (*tail_unsent == 0) {
19637 		*xmit_tail = (*xmit_tail)->b_cont;
19638 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19639 		*tail_unsent = (int)MBLKL(*xmit_tail);
19640 	}
19641 
19642 	/*
19643 	 * Here we create one or more Multidata messages, each made up of
19644 	 * one header buffer and up to N payload buffers.  This entire
19645 	 * operation is done within two loops:
19646 	 *
19647 	 * The outer loop mostly deals with creating the Multidata message,
19648 	 * as well as the header buffer that gets added to it.  It also
19649 	 * links the Multidata messages together such that all of them can
19650 	 * be sent down to the lower layer in a single putnext call; this
19651 	 * linking behavior depends on the tcp_mdt_chain tunable.
19652 	 *
19653 	 * The inner loop takes an existing Multidata message, and adds
19654 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19655 	 * packetizes those buffers by filling up the corresponding header
19656 	 * buffer fragments with the proper IP and TCP headers, and by
19657 	 * describing the layout of each packet in the packet descriptors
19658 	 * that get added to the Multidata.
19659 	 */
19660 	do {
19661 		/*
19662 		 * If usable send window is too small, or data blocks in
19663 		 * transmit list are smaller than our threshold (i.e. app
19664 		 * performs large writes followed by small ones), we hand
19665 		 * off the control over to the legacy path.  Note that we'll
19666 		 * get back the control once it encounters a large block.
19667 		 */
19668 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19669 		    (*xmit_tail)->b_cont != NULL &&
19670 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19671 			/* send down what we've got so far */
19672 			if (md_mp_head != NULL) {
19673 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19674 				    obsegs, obbytes, &rconfirm);
19675 			}
19676 			/*
19677 			 * Pass control over to tcp_send(), but tell it to
19678 			 * return to us once a large-size transmission is
19679 			 * possible.
19680 			 */
19681 			TCP_STAT(tcp_mdt_legacy_small);
19682 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19683 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19684 			    tail_unsent, xmit_tail, local_time,
19685 			    mdt_thres)) <= 0) {
19686 				/* burst count reached, or alloc failed */
19687 				IRE_REFRELE(ire);
19688 				return (err);
19689 			}
19690 
19691 			/* tcp_send() may have sent everything, so check */
19692 			if (*usable <= 0) {
19693 				IRE_REFRELE(ire);
19694 				return (0);
19695 			}
19696 
19697 			TCP_STAT(tcp_mdt_legacy_ret);
19698 			/*
19699 			 * We may have delivered the Multidata, so make sure
19700 			 * to re-initialize before the next round.
19701 			 */
19702 			md_mp_head = NULL;
19703 			obsegs = obbytes = 0;
19704 			num_burst_seg = tcp->tcp_snd_burst;
19705 			PREP_NEW_MULTIDATA();
19706 
19707 			/* are we starting from the beginning of data block? */
19708 			if (*tail_unsent == 0) {
19709 				*xmit_tail = (*xmit_tail)->b_cont;
19710 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19711 				    (uintptr_t)INT_MAX);
19712 				*tail_unsent = (int)MBLKL(*xmit_tail);
19713 			}
19714 		}
19715 
19716 		/*
19717 		 * max_pld limits the number of mblks in tcp's transmit
19718 		 * queue that can be added to a Multidata message.  Once
19719 		 * this counter reaches zero, no more additional mblks
19720 		 * can be added to it.  What happens afterwards depends
19721 		 * on whether or not we are set to chain the Multidata
19722 		 * messages.  If we are to link them together, reset
19723 		 * max_pld to its original value (tcp_mdt_max_pld) and
19724 		 * prepare to create a new Multidata message which will
19725 		 * get linked to md_mp_head.  Else, leave it alone and
19726 		 * let the inner loop break on its own.
19727 		 */
19728 		if (tcp_mdt_chain && max_pld == 0)
19729 			PREP_NEW_MULTIDATA();
19730 
19731 		/* adding a payload buffer; re-initialize values */
19732 		if (add_buffer)
19733 			PREP_NEW_PBUF();
19734 
19735 		/*
19736 		 * If we don't have a Multidata, either because we just
19737 		 * (re)entered this outer loop, or after we branched off
19738 		 * to tcp_send above, setup the Multidata and header
19739 		 * buffer to be used.
19740 		 */
19741 		if (md_mp == NULL) {
19742 			int md_hbuflen;
19743 			uint32_t start, stuff;
19744 
19745 			/*
19746 			 * Calculate Multidata header buffer size large enough
19747 			 * to hold all of the headers that can possibly be
19748 			 * sent at this moment.  We'd rather over-estimate
19749 			 * the size than running out of space; this is okay
19750 			 * since this buffer is small anyway.
19751 			 */
19752 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19753 
19754 			/*
19755 			 * Start and stuff offset for partial hardware
19756 			 * checksum offload; these are currently for IPv4.
19757 			 * For full checksum offload, they are set to zero.
19758 			 */
19759 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19760 				if (af == AF_INET) {
19761 					start = IP_SIMPLE_HDR_LENGTH;
19762 					stuff = IP_SIMPLE_HDR_LENGTH +
19763 					    TCP_CHECKSUM_OFFSET;
19764 				} else {
19765 					start = IPV6_HDR_LEN;
19766 					stuff = IPV6_HDR_LEN +
19767 					    TCP_CHECKSUM_OFFSET;
19768 				}
19769 			} else {
19770 				start = stuff = 0;
19771 			}
19772 
19773 			/*
19774 			 * Create the header buffer, Multidata, as well as
19775 			 * any necessary attributes (destination address,
19776 			 * SAP and hardware checksum offload) that should
19777 			 * be associated with the Multidata message.
19778 			 */
19779 			ASSERT(cur_hdr_off == 0);
19780 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19781 			    ((md_hbuf->b_wptr += md_hbuflen),
19782 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19783 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19784 			    /* fastpath mblk */
19785 			    ire->ire_nce->nce_res_mp,
19786 			    /* hardware checksum enabled */
19787 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19788 			    /* hardware checksum offsets */
19789 			    start, stuff, 0,
19790 			    /* hardware checksum flag */
19791 			    hwcksum_flags) != 0)) {
19792 legacy_send:
19793 				if (md_mp != NULL) {
19794 					/* Unlink message from the chain */
19795 					if (md_mp_head != NULL) {
19796 						err = (intptr_t)rmvb(md_mp_head,
19797 						    md_mp);
19798 						/*
19799 						 * We can't assert that rmvb
19800 						 * did not return -1, since we
19801 						 * may get here before linkb
19802 						 * happens.  We do, however,
19803 						 * check if we just removed the
19804 						 * only element in the list.
19805 						 */
19806 						if (err == 0)
19807 							md_mp_head = NULL;
19808 					}
19809 					/* md_hbuf gets freed automatically */
19810 					TCP_STAT(tcp_mdt_discarded);
19811 					freeb(md_mp);
19812 				} else {
19813 					/* Either allocb or mmd_alloc failed */
19814 					TCP_STAT(tcp_mdt_allocfail);
19815 					if (md_hbuf != NULL)
19816 						freeb(md_hbuf);
19817 				}
19818 
19819 				/* send down what we've got so far */
19820 				if (md_mp_head != NULL) {
19821 					tcp_multisend_data(tcp, ire, ill,
19822 					    md_mp_head, obsegs, obbytes,
19823 					    &rconfirm);
19824 				}
19825 legacy_send_no_md:
19826 				if (ire != NULL)
19827 					IRE_REFRELE(ire);
19828 				/*
19829 				 * Too bad; let the legacy path handle this.
19830 				 * We specify INT_MAX for the threshold, since
19831 				 * we gave up with the Multidata processings
19832 				 * and let the old path have it all.
19833 				 */
19834 				TCP_STAT(tcp_mdt_legacy_all);
19835 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19836 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19837 				    snxt, tail_unsent, xmit_tail, local_time,
19838 				    INT_MAX));
19839 			}
19840 
19841 			/* link to any existing ones, if applicable */
19842 			TCP_STAT(tcp_mdt_allocd);
19843 			if (md_mp_head == NULL) {
19844 				md_mp_head = md_mp;
19845 			} else if (tcp_mdt_chain) {
19846 				TCP_STAT(tcp_mdt_linked);
19847 				linkb(md_mp_head, md_mp);
19848 			}
19849 		}
19850 
19851 		ASSERT(md_mp_head != NULL);
19852 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19853 		ASSERT(md_mp != NULL && mmd != NULL);
19854 		ASSERT(md_hbuf != NULL);
19855 
19856 		/*
19857 		 * Packetize the transmittable portion of the data block;
19858 		 * each data block is essentially added to the Multidata
19859 		 * as a payload buffer.  We also deal with adding more
19860 		 * than one payload buffers, which happens when the remaining
19861 		 * packetized portion of the current payload buffer is less
19862 		 * than MSS, while the next data block in transmit queue
19863 		 * has enough data to make up for one.  This "spillover"
19864 		 * case essentially creates a split-packet, where portions
19865 		 * of the packet's payload fragments may span across two
19866 		 * virtually discontiguous address blocks.
19867 		 */
19868 		seg_len = mss;
19869 		do {
19870 			len = seg_len;
19871 
19872 			ASSERT(len > 0);
19873 			ASSERT(max_pld >= 0);
19874 			ASSERT(!add_buffer || cur_pld_off == 0);
19875 
19876 			/*
19877 			 * First time around for this payload buffer; note
19878 			 * in the case of a spillover, the following has
19879 			 * been done prior to adding the split-packet
19880 			 * descriptor to Multidata, and we don't want to
19881 			 * repeat the process.
19882 			 */
19883 			if (add_buffer) {
19884 				ASSERT(mmd != NULL);
19885 				ASSERT(md_pbuf == NULL);
19886 				ASSERT(md_pbuf_nxt == NULL);
19887 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19888 
19889 				/*
19890 				 * Have we reached the limit?  We'd get to
19891 				 * this case when we're not chaining the
19892 				 * Multidata messages together, and since
19893 				 * we're done, terminate this loop.
19894 				 */
19895 				if (max_pld == 0)
19896 					break; /* done */
19897 
19898 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19899 					TCP_STAT(tcp_mdt_allocfail);
19900 					goto legacy_send; /* out_of_mem */
19901 				}
19902 
19903 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19904 				    zc_cap != NULL) {
19905 					if (!ip_md_zcopy_attr(mmd, NULL,
19906 					    zc_cap->ill_zerocopy_flags)) {
19907 						freeb(md_pbuf);
19908 						TCP_STAT(tcp_mdt_allocfail);
19909 						/* out_of_mem */
19910 						goto legacy_send;
19911 					}
19912 					zcopy = B_TRUE;
19913 				}
19914 
19915 				md_pbuf->b_rptr += base_pld_off;
19916 
19917 				/*
19918 				 * Add a payload buffer to the Multidata; this
19919 				 * operation must not fail, or otherwise our
19920 				 * logic in this routine is broken.  There
19921 				 * is no memory allocation done by the
19922 				 * routine, so any returned failure simply
19923 				 * tells us that we've done something wrong.
19924 				 *
19925 				 * A failure tells us that either we're adding
19926 				 * the same payload buffer more than once, or
19927 				 * we're trying to add more buffers than
19928 				 * allowed (max_pld calculation is wrong).
19929 				 * None of the above cases should happen, and
19930 				 * we panic because either there's horrible
19931 				 * heap corruption, and/or programming mistake.
19932 				 */
19933 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19934 				if (pbuf_idx < 0) {
19935 					cmn_err(CE_PANIC, "tcp_multisend: "
19936 					    "payload buffer logic error "
19937 					    "detected for tcp %p mmd %p "
19938 					    "pbuf %p (%d)\n",
19939 					    (void *)tcp, (void *)mmd,
19940 					    (void *)md_pbuf, pbuf_idx);
19941 				}
19942 
19943 				ASSERT(max_pld > 0);
19944 				--max_pld;
19945 				add_buffer = B_FALSE;
19946 			}
19947 
19948 			ASSERT(md_mp_head != NULL);
19949 			ASSERT(md_pbuf != NULL);
19950 			ASSERT(md_pbuf_nxt == NULL);
19951 			ASSERT(pbuf_idx != -1);
19952 			ASSERT(pbuf_idx_nxt == -1);
19953 			ASSERT(*usable > 0);
19954 
19955 			/*
19956 			 * We spillover to the next payload buffer only
19957 			 * if all of the following is true:
19958 			 *
19959 			 *   1. There is not enough data on the current
19960 			 *	payload buffer to make up `len',
19961 			 *   2. We are allowed to send `len',
19962 			 *   3. The next payload buffer length is large
19963 			 *	enough to accomodate `spill'.
19964 			 */
19965 			if ((spill = len - *tail_unsent) > 0 &&
19966 			    *usable >= len &&
19967 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19968 			    max_pld > 0) {
19969 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19970 				if (md_pbuf_nxt == NULL) {
19971 					TCP_STAT(tcp_mdt_allocfail);
19972 					goto legacy_send; /* out_of_mem */
19973 				}
19974 
19975 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19976 				    zc_cap != NULL) {
19977 					if (!ip_md_zcopy_attr(mmd, NULL,
19978 					    zc_cap->ill_zerocopy_flags)) {
19979 						freeb(md_pbuf_nxt);
19980 						TCP_STAT(tcp_mdt_allocfail);
19981 						/* out_of_mem */
19982 						goto legacy_send;
19983 					}
19984 					zcopy = B_TRUE;
19985 				}
19986 
19987 				/*
19988 				 * See comments above on the first call to
19989 				 * mmd_addpldbuf for explanation on the panic.
19990 				 */
19991 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19992 				if (pbuf_idx_nxt < 0) {
19993 					panic("tcp_multisend: "
19994 					    "next payload buffer logic error "
19995 					    "detected for tcp %p mmd %p "
19996 					    "pbuf %p (%d)\n",
19997 					    (void *)tcp, (void *)mmd,
19998 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19999 				}
20000 
20001 				ASSERT(max_pld > 0);
20002 				--max_pld;
20003 			} else if (spill > 0) {
20004 				/*
20005 				 * If there's a spillover, but the following
20006 				 * xmit_tail couldn't give us enough octets
20007 				 * to reach "len", then stop the current
20008 				 * Multidata creation and let the legacy
20009 				 * tcp_send() path take over.  We don't want
20010 				 * to send the tiny segment as part of this
20011 				 * Multidata for performance reasons; instead,
20012 				 * we let the legacy path deal with grouping
20013 				 * it with the subsequent small mblks.
20014 				 */
20015 				if (*usable >= len &&
20016 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20017 					max_pld = 0;
20018 					break;	/* done */
20019 				}
20020 
20021 				/*
20022 				 * We can't spillover, and we are near
20023 				 * the end of the current payload buffer,
20024 				 * so send what's left.
20025 				 */
20026 				ASSERT(*tail_unsent > 0);
20027 				len = *tail_unsent;
20028 			}
20029 
20030 			/* tail_unsent is negated if there is a spillover */
20031 			*tail_unsent -= len;
20032 			*usable -= len;
20033 			ASSERT(*usable >= 0);
20034 
20035 			if (*usable < mss)
20036 				seg_len = *usable;
20037 			/*
20038 			 * Sender SWS avoidance; see comments in tcp_send();
20039 			 * everything else is the same, except that we only
20040 			 * do this here if there is no more data to be sent
20041 			 * following the current xmit_tail.  We don't check
20042 			 * for 1-byte urgent data because we shouldn't get
20043 			 * here if TCP_URG_VALID is set.
20044 			 */
20045 			if (*usable > 0 && *usable < mss &&
20046 			    ((md_pbuf_nxt == NULL &&
20047 			    (*xmit_tail)->b_cont == NULL) ||
20048 			    (md_pbuf_nxt != NULL &&
20049 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20050 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20051 			    (tcp->tcp_unsent -
20052 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20053 			    !tcp->tcp_zero_win_probe) {
20054 				if ((*snxt + len) == tcp->tcp_snxt &&
20055 				    (*snxt + len) == tcp->tcp_suna) {
20056 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20057 				}
20058 				done = B_TRUE;
20059 			}
20060 
20061 			/*
20062 			 * Prime pump for IP's checksumming on our behalf;
20063 			 * include the adjustment for a source route if any.
20064 			 * Do this only for software/partial hardware checksum
20065 			 * offload, as this field gets zeroed out later for
20066 			 * the full hardware checksum offload case.
20067 			 */
20068 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20069 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20070 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20071 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20072 			}
20073 
20074 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20075 			*snxt += len;
20076 
20077 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20078 			/*
20079 			 * We set the PUSH bit only if TCP has no more buffered
20080 			 * data to be transmitted (or if sender SWS avoidance
20081 			 * takes place), as opposed to setting it for every
20082 			 * last packet in the burst.
20083 			 */
20084 			if (done ||
20085 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20086 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20087 
20088 			/*
20089 			 * Set FIN bit if this is our last segment; snxt
20090 			 * already includes its length, and it will not
20091 			 * be adjusted after this point.
20092 			 */
20093 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20094 			    *snxt == tcp->tcp_fss) {
20095 				if (!tcp->tcp_fin_acked) {
20096 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20097 					BUMP_MIB(&tcp_mib, tcpOutControl);
20098 				}
20099 				if (!tcp->tcp_fin_sent) {
20100 					tcp->tcp_fin_sent = B_TRUE;
20101 					/*
20102 					 * tcp state must be ESTABLISHED
20103 					 * in order for us to get here in
20104 					 * the first place.
20105 					 */
20106 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20107 
20108 					/*
20109 					 * Upon returning from this routine,
20110 					 * tcp_wput_data() will set tcp_snxt
20111 					 * to be equal to snxt + tcp_fin_sent.
20112 					 * This is essentially the same as
20113 					 * setting it to tcp_fss + 1.
20114 					 */
20115 				}
20116 			}
20117 
20118 			tcp->tcp_last_sent_len = (ushort_t)len;
20119 
20120 			len += tcp_hdr_len;
20121 			if (tcp->tcp_ipversion == IPV4_VERSION)
20122 				tcp->tcp_ipha->ipha_length = htons(len);
20123 			else
20124 				tcp->tcp_ip6h->ip6_plen = htons(len -
20125 				    ((char *)&tcp->tcp_ip6h[1] -
20126 				    tcp->tcp_iphc));
20127 
20128 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20129 
20130 			/* setup header fragment */
20131 			PDESC_HDR_ADD(pkt_info,
20132 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20133 			    tcp->tcp_mdt_hdr_head,		/* head room */
20134 			    tcp_hdr_len,			/* len */
20135 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20136 
20137 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20138 			    hdr_frag_sz);
20139 			ASSERT(MBLKIN(md_hbuf,
20140 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20141 			    PDESC_HDRSIZE(pkt_info)));
20142 
20143 			/* setup first payload fragment */
20144 			PDESC_PLD_INIT(pkt_info);
20145 			PDESC_PLD_SPAN_ADD(pkt_info,
20146 			    pbuf_idx,				/* index */
20147 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20148 			    tcp->tcp_last_sent_len);		/* len */
20149 
20150 			/* create a split-packet in case of a spillover */
20151 			if (md_pbuf_nxt != NULL) {
20152 				ASSERT(spill > 0);
20153 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20154 				ASSERT(!add_buffer);
20155 
20156 				md_pbuf = md_pbuf_nxt;
20157 				md_pbuf_nxt = NULL;
20158 				pbuf_idx = pbuf_idx_nxt;
20159 				pbuf_idx_nxt = -1;
20160 				cur_pld_off = spill;
20161 
20162 				/* trim out first payload fragment */
20163 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20164 
20165 				/* setup second payload fragment */
20166 				PDESC_PLD_SPAN_ADD(pkt_info,
20167 				    pbuf_idx,			/* index */
20168 				    md_pbuf->b_rptr,		/* start */
20169 				    spill);			/* len */
20170 
20171 				if ((*xmit_tail)->b_next == NULL) {
20172 					/*
20173 					 * Store the lbolt used for RTT
20174 					 * estimation. We can only record one
20175 					 * timestamp per mblk so we do it when
20176 					 * we reach the end of the payload
20177 					 * buffer.  Also we only take a new
20178 					 * timestamp sample when the previous
20179 					 * timed data from the same mblk has
20180 					 * been ack'ed.
20181 					 */
20182 					(*xmit_tail)->b_prev = local_time;
20183 					(*xmit_tail)->b_next =
20184 					    (mblk_t *)(uintptr_t)first_snxt;
20185 				}
20186 
20187 				first_snxt = *snxt - spill;
20188 
20189 				/*
20190 				 * Advance xmit_tail; usable could be 0 by
20191 				 * the time we got here, but we made sure
20192 				 * above that we would only spillover to
20193 				 * the next data block if usable includes
20194 				 * the spilled-over amount prior to the
20195 				 * subtraction.  Therefore, we are sure
20196 				 * that xmit_tail->b_cont can't be NULL.
20197 				 */
20198 				ASSERT((*xmit_tail)->b_cont != NULL);
20199 				*xmit_tail = (*xmit_tail)->b_cont;
20200 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20201 				    (uintptr_t)INT_MAX);
20202 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20203 			} else {
20204 				cur_pld_off += tcp->tcp_last_sent_len;
20205 			}
20206 
20207 			/*
20208 			 * Fill in the header using the template header, and
20209 			 * add options such as time-stamp, ECN and/or SACK,
20210 			 * as needed.
20211 			 */
20212 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20213 			    (clock_t)local_time, num_sack_blk);
20214 
20215 			/* take care of some IP header businesses */
20216 			if (af == AF_INET) {
20217 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20218 
20219 				ASSERT(OK_32PTR((uchar_t *)ipha));
20220 				ASSERT(PDESC_HDRL(pkt_info) >=
20221 				    IP_SIMPLE_HDR_LENGTH);
20222 				ASSERT(ipha->ipha_version_and_hdr_length ==
20223 				    IP_SIMPLE_HDR_VERSION);
20224 
20225 				/*
20226 				 * Assign ident value for current packet; see
20227 				 * related comments in ip_wput_ire() about the
20228 				 * contract private interface with clustering
20229 				 * group.
20230 				 */
20231 				clusterwide = B_FALSE;
20232 				if (cl_inet_ipident != NULL) {
20233 					ASSERT(cl_inet_isclusterwide != NULL);
20234 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20235 					    AF_INET,
20236 					    (uint8_t *)(uintptr_t)src)) {
20237 						ipha->ipha_ident =
20238 						    (*cl_inet_ipident)
20239 						    (IPPROTO_IP, AF_INET,
20240 						    (uint8_t *)(uintptr_t)src,
20241 						    (uint8_t *)(uintptr_t)dst);
20242 						clusterwide = B_TRUE;
20243 					}
20244 				}
20245 
20246 				if (!clusterwide) {
20247 					ipha->ipha_ident = (uint16_t)
20248 					    atomic_add_32_nv(
20249 						&ire->ire_ident, 1);
20250 				}
20251 #ifndef _BIG_ENDIAN
20252 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20253 				    (ipha->ipha_ident >> 8);
20254 #endif
20255 			} else {
20256 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20257 
20258 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20259 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20260 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20261 				ASSERT(PDESC_HDRL(pkt_info) >=
20262 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20263 				    TCP_CHECKSUM_SIZE));
20264 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20265 
20266 				if (tcp->tcp_ip_forward_progress) {
20267 					rconfirm = B_TRUE;
20268 					tcp->tcp_ip_forward_progress = B_FALSE;
20269 				}
20270 			}
20271 
20272 			/* at least one payload span, and at most two */
20273 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20274 
20275 			/* add the packet descriptor to Multidata */
20276 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20277 			    KM_NOSLEEP)) == NULL) {
20278 				/*
20279 				 * Any failure other than ENOMEM indicates
20280 				 * that we have passed in invalid pkt_info
20281 				 * or parameters to mmd_addpdesc, which must
20282 				 * not happen.
20283 				 *
20284 				 * EINVAL is a result of failure on boundary
20285 				 * checks against the pkt_info contents.  It
20286 				 * should not happen, and we panic because
20287 				 * either there's horrible heap corruption,
20288 				 * and/or programming mistake.
20289 				 */
20290 				if (err != ENOMEM) {
20291 					cmn_err(CE_PANIC, "tcp_multisend: "
20292 					    "pdesc logic error detected for "
20293 					    "tcp %p mmd %p pinfo %p (%d)\n",
20294 					    (void *)tcp, (void *)mmd,
20295 					    (void *)pkt_info, err);
20296 				}
20297 				TCP_STAT(tcp_mdt_addpdescfail);
20298 				goto legacy_send; /* out_of_mem */
20299 			}
20300 			ASSERT(pkt != NULL);
20301 
20302 			/* calculate IP header and TCP checksums */
20303 			if (af == AF_INET) {
20304 				/* calculate pseudo-header checksum */
20305 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20306 				    (src >> 16) + (src & 0xFFFF);
20307 
20308 				/* offset for TCP header checksum */
20309 				up = IPH_TCPH_CHECKSUMP(ipha,
20310 				    IP_SIMPLE_HDR_LENGTH);
20311 			} else {
20312 				up = (uint16_t *)&ip6h->ip6_src;
20313 
20314 				/* calculate pseudo-header checksum */
20315 				cksum = up[0] + up[1] + up[2] + up[3] +
20316 				    up[4] + up[5] + up[6] + up[7] +
20317 				    up[8] + up[9] + up[10] + up[11] +
20318 				    up[12] + up[13] + up[14] + up[15];
20319 
20320 				/* Fold the initial sum */
20321 				cksum = (cksum & 0xffff) + (cksum >> 16);
20322 
20323 				up = (uint16_t *)(((uchar_t *)ip6h) +
20324 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20325 			}
20326 
20327 			if (hwcksum_flags & HCK_FULLCKSUM) {
20328 				/* clear checksum field for hardware */
20329 				*up = 0;
20330 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20331 				uint32_t sum;
20332 
20333 				/* pseudo-header checksumming */
20334 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20335 				sum = (sum & 0xFFFF) + (sum >> 16);
20336 				*up = (sum & 0xFFFF) + (sum >> 16);
20337 			} else {
20338 				/* software checksumming */
20339 				TCP_STAT(tcp_out_sw_cksum);
20340 				TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
20341 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20342 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20343 				    cksum + IP_TCP_CSUM_COMP);
20344 				if (*up == 0)
20345 					*up = 0xFFFF;
20346 			}
20347 
20348 			/* IPv4 header checksum */
20349 			if (af == AF_INET) {
20350 				ipha->ipha_fragment_offset_and_flags |=
20351 				    (uint32_t)htons(ire->ire_frag_flag);
20352 
20353 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20354 					ipha->ipha_hdr_checksum = 0;
20355 				} else {
20356 					IP_HDR_CKSUM(ipha, cksum,
20357 					    ((uint32_t *)ipha)[0],
20358 					    ((uint16_t *)ipha)[4]);
20359 				}
20360 			}
20361 
20362 			if (af == AF_INET && HOOKS4_INTERESTED_PHYSICAL_OUT||
20363 			    af == AF_INET6 && HOOKS6_INTERESTED_PHYSICAL_OUT) {
20364 				/* build header(IP/TCP) mblk for this segment */
20365 				if ((mp = dupb(md_hbuf)) == NULL)
20366 					goto legacy_send;
20367 
20368 				mp->b_rptr = pkt_info->hdr_rptr;
20369 				mp->b_wptr = pkt_info->hdr_wptr;
20370 
20371 				/* build payload mblk for this segment */
20372 				if ((mp1 = dupb(*xmit_tail)) == NULL) {
20373 					freemsg(mp);
20374 					goto legacy_send;
20375 				}
20376 				mp1->b_wptr = md_pbuf->b_rptr + cur_pld_off;
20377 				mp1->b_rptr = mp1->b_wptr -
20378 				    tcp->tcp_last_sent_len;
20379 				linkb(mp, mp1);
20380 
20381 				pld_start = mp1->b_rptr;
20382 
20383 				if (af == AF_INET) {
20384 					DTRACE_PROBE4(
20385 					    ip4__physical__out__start,
20386 					    ill_t *, NULL,
20387 					    ill_t *, ill,
20388 					    ipha_t *, ipha,
20389 					    mblk_t *, mp);
20390 					FW_HOOKS(ip4_physical_out_event,
20391 					    ipv4firewall_physical_out,
20392 					    NULL, ill, ipha, mp, mp);
20393 					DTRACE_PROBE1(
20394 					    ip4__physical__out__end,
20395 					    mblk_t *, mp);
20396 				} else {
20397 					DTRACE_PROBE4(
20398 					    ip6__physical__out_start,
20399 					    ill_t *, NULL,
20400 					    ill_t *, ill,
20401 					    ip6_t *, ip6h,
20402 					    mblk_t *, mp);
20403 					FW_HOOKS6(ip6_physical_out_event,
20404 					    ipv6firewall_physical_out,
20405 					    NULL, ill, ip6h, mp, mp);
20406 					DTRACE_PROBE1(
20407 					    ip6__physical__out__end,
20408 					    mblk_t *, mp);
20409 				}
20410 
20411 				if (buf_trunked && mp != NULL) {
20412 					/*
20413 					 * Need to pass it to normal path.
20414 					 */
20415 					CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20416 				} else if (mp == NULL ||
20417 				    mp->b_rptr != pkt_info->hdr_rptr ||
20418 				    mp->b_wptr != pkt_info->hdr_wptr ||
20419 				    (mp1 = mp->b_cont) == NULL ||
20420 				    mp1->b_rptr != pld_start ||
20421 				    mp1->b_wptr != pld_start +
20422 				    tcp->tcp_last_sent_len ||
20423 				    mp1->b_cont != NULL) {
20424 					/*
20425 					 * Need to pass all packets of this
20426 					 * buffer to normal path, either when
20427 					 * packet is blocked, or when boundary
20428 					 * of header buffer or payload buffer
20429 					 * has been changed by FW_HOOKS[6].
20430 					 */
20431 					buf_trunked = B_TRUE;
20432 					if (md_mp_head != NULL) {
20433 						err = (intptr_t)rmvb(md_mp_head,
20434 						    md_mp);
20435 						if (err == 0)
20436 							md_mp_head = NULL;
20437 					}
20438 
20439 					/* send down what we've got so far */
20440 					if (md_mp_head != NULL) {
20441 						tcp_multisend_data(tcp, ire,
20442 						    ill, md_mp_head, obsegs,
20443 						    obbytes, &rconfirm);
20444 					}
20445 					md_mp_head = NULL;
20446 
20447 					if (mp != NULL)
20448 						CALL_IP_WPUT(tcp->tcp_connp,
20449 						    q, mp);
20450 
20451 					mp1 = fw_mp_head;
20452 					do {
20453 						mp = mp1;
20454 						mp1 = mp1->b_next;
20455 						mp->b_next = NULL;
20456 						mp->b_prev = NULL;
20457 						CALL_IP_WPUT(tcp->tcp_connp,
20458 						    q, mp);
20459 					} while (mp1 != NULL);
20460 
20461 					fw_mp_head = NULL;
20462 				} else {
20463 					if (fw_mp_head == NULL)
20464 						fw_mp_head = mp;
20465 					else
20466 						fw_mp_head->b_prev->b_next = mp;
20467 					fw_mp_head->b_prev = mp;
20468 				}
20469 			}
20470 
20471 			/* advance header offset */
20472 			cur_hdr_off += hdr_frag_sz;
20473 
20474 			obbytes += tcp->tcp_last_sent_len;
20475 			++obsegs;
20476 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20477 		    *tail_unsent > 0);
20478 
20479 		if ((*xmit_tail)->b_next == NULL) {
20480 			/*
20481 			 * Store the lbolt used for RTT estimation. We can only
20482 			 * record one timestamp per mblk so we do it when we
20483 			 * reach the end of the payload buffer. Also we only
20484 			 * take a new timestamp sample when the previous timed
20485 			 * data from the same mblk has been ack'ed.
20486 			 */
20487 			(*xmit_tail)->b_prev = local_time;
20488 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20489 		}
20490 
20491 		ASSERT(*tail_unsent >= 0);
20492 		if (*tail_unsent > 0) {
20493 			/*
20494 			 * We got here because we broke out of the above
20495 			 * loop due to of one of the following cases:
20496 			 *
20497 			 *   1. len < adjusted MSS (i.e. small),
20498 			 *   2. Sender SWS avoidance,
20499 			 *   3. max_pld is zero.
20500 			 *
20501 			 * We are done for this Multidata, so trim our
20502 			 * last payload buffer (if any) accordingly.
20503 			 */
20504 			if (md_pbuf != NULL)
20505 				md_pbuf->b_wptr -= *tail_unsent;
20506 		} else if (*usable > 0) {
20507 			*xmit_tail = (*xmit_tail)->b_cont;
20508 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20509 			    (uintptr_t)INT_MAX);
20510 			*tail_unsent = (int)MBLKL(*xmit_tail);
20511 			add_buffer = B_TRUE;
20512 		}
20513 
20514 		while (fw_mp_head) {
20515 			mp = fw_mp_head;
20516 			fw_mp_head = fw_mp_head->b_next;
20517 			mp->b_prev = mp->b_next = NULL;
20518 			freemsg(mp);
20519 		}
20520 		if (buf_trunked) {
20521 			TCP_STAT(tcp_mdt_discarded);
20522 			freeb(md_mp);
20523 			buf_trunked = B_FALSE;
20524 		}
20525 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20526 	    (tcp_mdt_chain || max_pld > 0));
20527 
20528 	if (md_mp_head != NULL) {
20529 		/* send everything down */
20530 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20531 		    &rconfirm);
20532 	}
20533 
20534 #undef PREP_NEW_MULTIDATA
20535 #undef PREP_NEW_PBUF
20536 #undef IPVER
20537 
20538 	IRE_REFRELE(ire);
20539 	return (0);
20540 }
20541 
20542 /*
20543  * A wrapper function for sending one or more Multidata messages down to
20544  * the module below ip; this routine does not release the reference of the
20545  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20546  */
20547 static void
20548 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20549     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20550 {
20551 	uint64_t delta;
20552 	nce_t *nce;
20553 
20554 	ASSERT(ire != NULL && ill != NULL);
20555 	ASSERT(ire->ire_stq != NULL);
20556 	ASSERT(md_mp_head != NULL);
20557 	ASSERT(rconfirm != NULL);
20558 
20559 	/* adjust MIBs and IRE timestamp */
20560 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20561 	tcp->tcp_obsegs += obsegs;
20562 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
20563 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
20564 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
20565 
20566 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20567 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
20568 	} else {
20569 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
20570 	}
20571 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20572 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20573 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20574 
20575 	ire->ire_ob_pkt_count += obsegs;
20576 	if (ire->ire_ipif != NULL)
20577 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20578 	ire->ire_last_used_time = lbolt;
20579 
20580 	/* send it down */
20581 	putnext(ire->ire_stq, md_mp_head);
20582 
20583 	/* we're done for TCP/IPv4 */
20584 	if (tcp->tcp_ipversion == IPV4_VERSION)
20585 		return;
20586 
20587 	nce = ire->ire_nce;
20588 
20589 	ASSERT(nce != NULL);
20590 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20591 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20592 
20593 	/* reachability confirmation? */
20594 	if (*rconfirm) {
20595 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20596 		if (nce->nce_state != ND_REACHABLE) {
20597 			mutex_enter(&nce->nce_lock);
20598 			nce->nce_state = ND_REACHABLE;
20599 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20600 			mutex_exit(&nce->nce_lock);
20601 			(void) untimeout(nce->nce_timeout_id);
20602 			if (ip_debug > 2) {
20603 				/* ip1dbg */
20604 				pr_addr_dbg("tcp_multisend_data: state "
20605 				    "for %s changed to REACHABLE\n",
20606 				    AF_INET6, &ire->ire_addr_v6);
20607 			}
20608 		}
20609 		/* reset transport reachability confirmation */
20610 		*rconfirm = B_FALSE;
20611 	}
20612 
20613 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20614 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20615 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20616 
20617 	if (delta > (uint64_t)ill->ill_reachable_time) {
20618 		mutex_enter(&nce->nce_lock);
20619 		switch (nce->nce_state) {
20620 		case ND_REACHABLE:
20621 		case ND_STALE:
20622 			/*
20623 			 * ND_REACHABLE is identical to ND_STALE in this
20624 			 * specific case. If reachable time has expired for
20625 			 * this neighbor (delta is greater than reachable
20626 			 * time), conceptually, the neighbor cache is no
20627 			 * longer in REACHABLE state, but already in STALE
20628 			 * state.  So the correct transition here is to
20629 			 * ND_DELAY.
20630 			 */
20631 			nce->nce_state = ND_DELAY;
20632 			mutex_exit(&nce->nce_lock);
20633 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
20634 			if (ip_debug > 3) {
20635 				/* ip2dbg */
20636 				pr_addr_dbg("tcp_multisend_data: state "
20637 				    "for %s changed to DELAY\n",
20638 				    AF_INET6, &ire->ire_addr_v6);
20639 			}
20640 			break;
20641 		case ND_DELAY:
20642 		case ND_PROBE:
20643 			mutex_exit(&nce->nce_lock);
20644 			/* Timers have already started */
20645 			break;
20646 		case ND_UNREACHABLE:
20647 			/*
20648 			 * ndp timer has detected that this nce is
20649 			 * unreachable and initiated deleting this nce
20650 			 * and all its associated IREs. This is a race
20651 			 * where we found the ire before it was deleted
20652 			 * and have just sent out a packet using this
20653 			 * unreachable nce.
20654 			 */
20655 			mutex_exit(&nce->nce_lock);
20656 			break;
20657 		default:
20658 			ASSERT(0);
20659 		}
20660 	}
20661 }
20662 
20663 /*
20664  * Derived from tcp_send_data().
20665  */
20666 static void
20667 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20668     int num_lso_seg)
20669 {
20670 	ipha_t		*ipha;
20671 	mblk_t		*ire_fp_mp;
20672 	uint_t		ire_fp_mp_len;
20673 	uint32_t	hcksum_txflags = 0;
20674 	ipaddr_t	src;
20675 	ipaddr_t	dst;
20676 	uint32_t	cksum;
20677 	uint16_t	*up;
20678 
20679 	ASSERT(DB_TYPE(mp) == M_DATA);
20680 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20681 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20682 	ASSERT(tcp->tcp_connp != NULL);
20683 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20684 
20685 	ipha = (ipha_t *)mp->b_rptr;
20686 	src = ipha->ipha_src;
20687 	dst = ipha->ipha_dst;
20688 
20689 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20690 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20691 	    num_lso_seg);
20692 #ifndef _BIG_ENDIAN
20693 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20694 #endif
20695 	if (tcp->tcp_snd_zcopy_aware) {
20696 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20697 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20698 			mp = tcp_zcopy_disable(tcp, mp);
20699 	}
20700 
20701 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20702 		ASSERT(ill->ill_hcksum_capab != NULL);
20703 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20704 	}
20705 
20706 	/*
20707 	 * Since the TCP checksum should be recalculated by h/w, we can just
20708 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20709 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20710 	 * The partial pseudo-header excludes TCP length, that was calculated
20711 	 * in tcp_send(), so to zero *up before further processing.
20712 	 */
20713 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20714 
20715 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20716 	*up = 0;
20717 
20718 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20719 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20720 
20721 	/*
20722 	 * Append LSO flag to DB_LSOFLAGS(mp) and set the mss to DB_LSOMSS(mp).
20723 	 */
20724 	DB_LSOFLAGS(mp) |= HW_LSO;
20725 	DB_LSOMSS(mp) = mss;
20726 
20727 	ipha->ipha_fragment_offset_and_flags |=
20728 	    (uint32_t)htons(ire->ire_frag_flag);
20729 
20730 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20731 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20732 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20733 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20734 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20735 
20736 	UPDATE_OB_PKT_COUNT(ire);
20737 	ire->ire_last_used_time = lbolt;
20738 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20739 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20740 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20741 	    ntohs(ipha->ipha_length));
20742 
20743 	if (ILL_DLS_CAPABLE(ill)) {
20744 		/*
20745 		 * Send the packet directly to DLD, where it may be queued
20746 		 * depending on the availability of transmit resources at
20747 		 * the media layer.
20748 		 */
20749 		IP_DLS_ILL_TX(ill, ipha, mp);
20750 	} else {
20751 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
20752 		DTRACE_PROBE4(ip4__physical__out__start,
20753 		    ill_t *, NULL, ill_t *, out_ill,
20754 		    ipha_t *, ipha, mblk_t *, mp);
20755 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
20756 		    NULL, out_ill, ipha, mp, mp);
20757 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20758 		if (mp != NULL)
20759 			putnext(ire->ire_stq, mp);
20760 	}
20761 }
20762 
20763 /*
20764  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20765  * scheme, and returns one of the following:
20766  *
20767  * -1 = failed allocation.
20768  *  0 = success; burst count reached, or usable send window is too small,
20769  *      and that we'd rather wait until later before sending again.
20770  *  1 = success; we are called from tcp_multisend(), and both usable send
20771  *      window and tail_unsent are greater than the MDT threshold, and thus
20772  *      Multidata Transmit should be used instead.
20773  */
20774 static int
20775 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20776     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20777     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20778     const int mdt_thres)
20779 {
20780 	int num_burst_seg = tcp->tcp_snd_burst;
20781 	ire_t		*ire = NULL;
20782 	ill_t		*ill = NULL;
20783 	mblk_t		*ire_fp_mp = NULL;
20784 	uint_t		ire_fp_mp_len = 0;
20785 	int		num_lso_seg = 1;
20786 	uint_t		lso_usable;
20787 	boolean_t	do_lso_send = B_FALSE;
20788 
20789 	/*
20790 	 * Check LSO capability before any further work. And the similar check
20791 	 * need to be done in for(;;) loop.
20792 	 * LSO will be deployed when therer is more than one mss of available
20793 	 * data and a burst transmission is allowed.
20794 	 */
20795 	if (tcp->tcp_lso &&
20796 	    (tcp->tcp_valid_bits == 0 ||
20797 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20798 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20799 		/*
20800 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20801 		 */
20802 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
20803 			/*
20804 			 * Enable LSO with this transmission.
20805 			 * Since IRE has been hold in
20806 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
20807 			 * should be called before return.
20808 			 */
20809 			do_lso_send = B_TRUE;
20810 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
20811 			ire_fp_mp_len = MBLKL(ire_fp_mp);
20812 			/* Round up to multiple of 4 */
20813 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
20814 		} else {
20815 			do_lso_send = B_FALSE;
20816 			ill = NULL;
20817 		}
20818 	}
20819 
20820 	for (;;) {
20821 		struct datab	*db;
20822 		tcph_t		*tcph;
20823 		uint32_t	sum;
20824 		mblk_t		*mp, *mp1;
20825 		uchar_t		*rptr;
20826 		int		len;
20827 
20828 		/*
20829 		 * If we're called by tcp_multisend(), and the amount of
20830 		 * sendable data as well as the size of current xmit_tail
20831 		 * is beyond the MDT threshold, return to the caller and
20832 		 * let the large data transmit be done using MDT.
20833 		 */
20834 		if (*usable > 0 && *usable > mdt_thres &&
20835 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20836 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20837 			ASSERT(tcp->tcp_mdt);
20838 			return (1);	/* success; do large send */
20839 		}
20840 
20841 		if (num_burst_seg == 0)
20842 			break;		/* success; burst count reached */
20843 
20844 		/*
20845 		 * Calculate the maximum payload length we can send in *one*
20846 		 * time.
20847 		 */
20848 		if (do_lso_send) {
20849 			/*
20850 			 * Check whether need to do LSO any more.
20851 			 */
20852 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20853 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
20854 				lso_usable = MIN(lso_usable,
20855 				    num_burst_seg * mss);
20856 
20857 				num_lso_seg = lso_usable / mss;
20858 				if (lso_usable % mss) {
20859 					num_lso_seg++;
20860 					tcp->tcp_last_sent_len = (ushort_t)
20861 					    (lso_usable % mss);
20862 				} else {
20863 					tcp->tcp_last_sent_len = (ushort_t)mss;
20864 				}
20865 			} else {
20866 				do_lso_send = B_FALSE;
20867 				num_lso_seg = 1;
20868 				lso_usable = mss;
20869 			}
20870 		}
20871 
20872 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
20873 
20874 		/*
20875 		 * Adjust num_burst_seg here.
20876 		 */
20877 		num_burst_seg -= num_lso_seg;
20878 
20879 		len = mss;
20880 		if (len > *usable) {
20881 			ASSERT(do_lso_send == B_FALSE);
20882 
20883 			len = *usable;
20884 			if (len <= 0) {
20885 				/* Terminate the loop */
20886 				break;	/* success; too small */
20887 			}
20888 			/*
20889 			 * Sender silly-window avoidance.
20890 			 * Ignore this if we are going to send a
20891 			 * zero window probe out.
20892 			 *
20893 			 * TODO: force data into microscopic window?
20894 			 *	==> (!pushed || (unsent > usable))
20895 			 */
20896 			if (len < (tcp->tcp_max_swnd >> 1) &&
20897 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20898 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20899 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20900 				/*
20901 				 * If the retransmit timer is not running
20902 				 * we start it so that we will retransmit
20903 				 * in the case when the the receiver has
20904 				 * decremented the window.
20905 				 */
20906 				if (*snxt == tcp->tcp_snxt &&
20907 				    *snxt == tcp->tcp_suna) {
20908 					/*
20909 					 * We are not supposed to send
20910 					 * anything.  So let's wait a little
20911 					 * bit longer before breaking SWS
20912 					 * avoidance.
20913 					 *
20914 					 * What should the value be?
20915 					 * Suggestion: MAX(init rexmit time,
20916 					 * tcp->tcp_rto)
20917 					 */
20918 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20919 				}
20920 				break;	/* success; too small */
20921 			}
20922 		}
20923 
20924 		tcph = tcp->tcp_tcph;
20925 
20926 		/*
20927 		 * The reason to adjust len here is that we need to set flags
20928 		 * and calculate checksum.
20929 		 */
20930 		if (do_lso_send)
20931 			len = lso_usable;
20932 
20933 		*usable -= len; /* Approximate - can be adjusted later */
20934 		if (*usable > 0)
20935 			tcph->th_flags[0] = TH_ACK;
20936 		else
20937 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20938 
20939 		/*
20940 		 * Prime pump for IP's checksumming on our behalf
20941 		 * Include the adjustment for a source route if any.
20942 		 */
20943 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20944 		sum = (sum >> 16) + (sum & 0xFFFF);
20945 		U16_TO_ABE16(sum, tcph->th_sum);
20946 
20947 		U32_TO_ABE32(*snxt, tcph->th_seq);
20948 
20949 		/*
20950 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20951 		 * set.  For the case when TCP_FSS_VALID is the only valid
20952 		 * bit (normal active close), branch off only when we think
20953 		 * that the FIN flag needs to be set.  Note for this case,
20954 		 * that (snxt + len) may not reflect the actual seg_len,
20955 		 * as len may be further reduced in tcp_xmit_mp().  If len
20956 		 * gets modified, we will end up here again.
20957 		 */
20958 		if (tcp->tcp_valid_bits != 0 &&
20959 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20960 		    ((*snxt + len) == tcp->tcp_fss))) {
20961 			uchar_t		*prev_rptr;
20962 			uint32_t	prev_snxt = tcp->tcp_snxt;
20963 
20964 			if (*tail_unsent == 0) {
20965 				ASSERT((*xmit_tail)->b_cont != NULL);
20966 				*xmit_tail = (*xmit_tail)->b_cont;
20967 				prev_rptr = (*xmit_tail)->b_rptr;
20968 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20969 				    (*xmit_tail)->b_rptr);
20970 			} else {
20971 				prev_rptr = (*xmit_tail)->b_rptr;
20972 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20973 				    *tail_unsent;
20974 			}
20975 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20976 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20977 			/* Restore tcp_snxt so we get amount sent right. */
20978 			tcp->tcp_snxt = prev_snxt;
20979 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20980 				/*
20981 				 * If the previous timestamp is still in use,
20982 				 * don't stomp on it.
20983 				 */
20984 				if ((*xmit_tail)->b_next == NULL) {
20985 					(*xmit_tail)->b_prev = local_time;
20986 					(*xmit_tail)->b_next =
20987 					    (mblk_t *)(uintptr_t)(*snxt);
20988 				}
20989 			} else
20990 				(*xmit_tail)->b_rptr = prev_rptr;
20991 
20992 			if (mp == NULL) {
20993 				if (ire != NULL)
20994 					IRE_REFRELE(ire);
20995 				return (-1);
20996 			}
20997 			mp1 = mp->b_cont;
20998 
20999 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21000 				tcp->tcp_last_sent_len = (ushort_t)len;
21001 			while (mp1->b_cont) {
21002 				*xmit_tail = (*xmit_tail)->b_cont;
21003 				(*xmit_tail)->b_prev = local_time;
21004 				(*xmit_tail)->b_next =
21005 				    (mblk_t *)(uintptr_t)(*snxt);
21006 				mp1 = mp1->b_cont;
21007 			}
21008 			*snxt += len;
21009 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21010 			BUMP_LOCAL(tcp->tcp_obsegs);
21011 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
21012 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
21013 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21014 			tcp_send_data(tcp, q, mp);
21015 			continue;
21016 		}
21017 
21018 		*snxt += len;	/* Adjust later if we don't send all of len */
21019 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
21020 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
21021 
21022 		if (*tail_unsent) {
21023 			/* Are the bytes above us in flight? */
21024 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21025 			if (rptr != (*xmit_tail)->b_rptr) {
21026 				*tail_unsent -= len;
21027 				if (len <= mss) /* LSO is unusable */
21028 					tcp->tcp_last_sent_len = (ushort_t)len;
21029 				len += tcp_hdr_len;
21030 				if (tcp->tcp_ipversion == IPV4_VERSION)
21031 					tcp->tcp_ipha->ipha_length = htons(len);
21032 				else
21033 					tcp->tcp_ip6h->ip6_plen =
21034 					    htons(len -
21035 					    ((char *)&tcp->tcp_ip6h[1] -
21036 					    tcp->tcp_iphc));
21037 				mp = dupb(*xmit_tail);
21038 				if (mp == NULL) {
21039 					if (ire != NULL)
21040 						IRE_REFRELE(ire);
21041 					return (-1);	/* out_of_mem */
21042 				}
21043 				mp->b_rptr = rptr;
21044 				/*
21045 				 * If the old timestamp is no longer in use,
21046 				 * sample a new timestamp now.
21047 				 */
21048 				if ((*xmit_tail)->b_next == NULL) {
21049 					(*xmit_tail)->b_prev = local_time;
21050 					(*xmit_tail)->b_next =
21051 					    (mblk_t *)(uintptr_t)(*snxt-len);
21052 				}
21053 				goto must_alloc;
21054 			}
21055 		} else {
21056 			*xmit_tail = (*xmit_tail)->b_cont;
21057 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21058 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21059 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21060 			    (*xmit_tail)->b_rptr);
21061 		}
21062 
21063 		(*xmit_tail)->b_prev = local_time;
21064 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21065 
21066 		*tail_unsent -= len;
21067 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21068 			tcp->tcp_last_sent_len = (ushort_t)len;
21069 
21070 		len += tcp_hdr_len;
21071 		if (tcp->tcp_ipversion == IPV4_VERSION)
21072 			tcp->tcp_ipha->ipha_length = htons(len);
21073 		else
21074 			tcp->tcp_ip6h->ip6_plen = htons(len -
21075 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21076 
21077 		mp = dupb(*xmit_tail);
21078 		if (mp == NULL) {
21079 			if (ire != NULL)
21080 				IRE_REFRELE(ire);
21081 			return (-1);	/* out_of_mem */
21082 		}
21083 
21084 		len = tcp_hdr_len;
21085 		/*
21086 		 * There are four reasons to allocate a new hdr mblk:
21087 		 *  1) The bytes above us are in use by another packet
21088 		 *  2) We don't have good alignment
21089 		 *  3) The mblk is being shared
21090 		 *  4) We don't have enough room for a header
21091 		 */
21092 		rptr = mp->b_rptr - len;
21093 		if (!OK_32PTR(rptr) ||
21094 		    ((db = mp->b_datap), db->db_ref != 2) ||
21095 		    rptr < db->db_base + ire_fp_mp_len) {
21096 			/* NOTE: we assume allocb returns an OK_32PTR */
21097 
21098 		must_alloc:;
21099 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21100 			    tcp_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21101 			if (mp1 == NULL) {
21102 				freemsg(mp);
21103 				if (ire != NULL)
21104 					IRE_REFRELE(ire);
21105 				return (-1);	/* out_of_mem */
21106 			}
21107 			mp1->b_cont = mp;
21108 			mp = mp1;
21109 			/* Leave room for Link Level header */
21110 			len = tcp_hdr_len;
21111 			rptr = &mp->b_rptr[tcp_wroff_xtra + ire_fp_mp_len];
21112 			mp->b_wptr = &rptr[len];
21113 		}
21114 
21115 		/*
21116 		 * Fill in the header using the template header, and add
21117 		 * options such as time-stamp, ECN and/or SACK, as needed.
21118 		 */
21119 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21120 
21121 		mp->b_rptr = rptr;
21122 
21123 		if (*tail_unsent) {
21124 			int spill = *tail_unsent;
21125 
21126 			mp1 = mp->b_cont;
21127 			if (mp1 == NULL)
21128 				mp1 = mp;
21129 
21130 			/*
21131 			 * If we're a little short, tack on more mblks until
21132 			 * there is no more spillover.
21133 			 */
21134 			while (spill < 0) {
21135 				mblk_t *nmp;
21136 				int nmpsz;
21137 
21138 				nmp = (*xmit_tail)->b_cont;
21139 				nmpsz = MBLKL(nmp);
21140 
21141 				/*
21142 				 * Excess data in mblk; can we split it?
21143 				 * If MDT is enabled for the connection,
21144 				 * keep on splitting as this is a transient
21145 				 * send path.
21146 				 */
21147 				if (!do_lso_send && !tcp->tcp_mdt &&
21148 				    (spill + nmpsz > 0)) {
21149 					/*
21150 					 * Don't split if stream head was
21151 					 * told to break up larger writes
21152 					 * into smaller ones.
21153 					 */
21154 					if (tcp->tcp_maxpsz > 0)
21155 						break;
21156 
21157 					/*
21158 					 * Next mblk is less than SMSS/2
21159 					 * rounded up to nearest 64-byte;
21160 					 * let it get sent as part of the
21161 					 * next segment.
21162 					 */
21163 					if (tcp->tcp_localnet &&
21164 					    !tcp->tcp_cork &&
21165 					    (nmpsz < roundup((mss >> 1), 64)))
21166 						break;
21167 				}
21168 
21169 				*xmit_tail = nmp;
21170 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21171 				/* Stash for rtt use later */
21172 				(*xmit_tail)->b_prev = local_time;
21173 				(*xmit_tail)->b_next =
21174 				    (mblk_t *)(uintptr_t)(*snxt - len);
21175 				mp1->b_cont = dupb(*xmit_tail);
21176 				mp1 = mp1->b_cont;
21177 
21178 				spill += nmpsz;
21179 				if (mp1 == NULL) {
21180 					*tail_unsent = spill;
21181 					freemsg(mp);
21182 					if (ire != NULL)
21183 						IRE_REFRELE(ire);
21184 					return (-1);	/* out_of_mem */
21185 				}
21186 			}
21187 
21188 			/* Trim back any surplus on the last mblk */
21189 			if (spill >= 0) {
21190 				mp1->b_wptr -= spill;
21191 				*tail_unsent = spill;
21192 			} else {
21193 				/*
21194 				 * We did not send everything we could in
21195 				 * order to remain within the b_cont limit.
21196 				 */
21197 				*usable -= spill;
21198 				*snxt += spill;
21199 				tcp->tcp_last_sent_len += spill;
21200 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
21201 				/*
21202 				 * Adjust the checksum
21203 				 */
21204 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21205 				sum += spill;
21206 				sum = (sum >> 16) + (sum & 0xFFFF);
21207 				U16_TO_ABE16(sum, tcph->th_sum);
21208 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21209 					sum = ntohs(
21210 					    ((ipha_t *)rptr)->ipha_length) +
21211 					    spill;
21212 					((ipha_t *)rptr)->ipha_length =
21213 					    htons(sum);
21214 				} else {
21215 					sum = ntohs(
21216 					    ((ip6_t *)rptr)->ip6_plen) +
21217 					    spill;
21218 					((ip6_t *)rptr)->ip6_plen =
21219 					    htons(sum);
21220 				}
21221 				*tail_unsent = 0;
21222 			}
21223 		}
21224 		if (tcp->tcp_ip_forward_progress) {
21225 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21226 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21227 			tcp->tcp_ip_forward_progress = B_FALSE;
21228 		}
21229 
21230 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21231 		if (do_lso_send) {
21232 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21233 			    num_lso_seg);
21234 			tcp->tcp_obsegs += num_lso_seg;
21235 
21236 			TCP_STAT(tcp_lso_times);
21237 			TCP_STAT_UPDATE(tcp_lso_pkt_out, num_lso_seg);
21238 		} else {
21239 			tcp_send_data(tcp, q, mp);
21240 			BUMP_LOCAL(tcp->tcp_obsegs);
21241 		}
21242 	}
21243 
21244 	if (ire != NULL)
21245 		IRE_REFRELE(ire);
21246 	return (0);
21247 }
21248 
21249 /* Unlink and return any mblk that looks like it contains a MDT info */
21250 static mblk_t *
21251 tcp_mdt_info_mp(mblk_t *mp)
21252 {
21253 	mblk_t	*prev_mp;
21254 
21255 	for (;;) {
21256 		prev_mp = mp;
21257 		/* no more to process? */
21258 		if ((mp = mp->b_cont) == NULL)
21259 			break;
21260 
21261 		switch (DB_TYPE(mp)) {
21262 		case M_CTL:
21263 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21264 				continue;
21265 			ASSERT(prev_mp != NULL);
21266 			prev_mp->b_cont = mp->b_cont;
21267 			mp->b_cont = NULL;
21268 			return (mp);
21269 		default:
21270 			break;
21271 		}
21272 	}
21273 	return (mp);
21274 }
21275 
21276 /* MDT info update routine, called when IP notifies us about MDT */
21277 static void
21278 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21279 {
21280 	boolean_t prev_state;
21281 
21282 	/*
21283 	 * IP is telling us to abort MDT on this connection?  We know
21284 	 * this because the capability is only turned off when IP
21285 	 * encounters some pathological cases, e.g. link-layer change
21286 	 * where the new driver doesn't support MDT, or in situation
21287 	 * where MDT usage on the link-layer has been switched off.
21288 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21289 	 * if the link-layer doesn't support MDT, and if it does, it
21290 	 * will indicate that the feature is to be turned on.
21291 	 */
21292 	prev_state = tcp->tcp_mdt;
21293 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21294 	if (!tcp->tcp_mdt && !first) {
21295 		TCP_STAT(tcp_mdt_conn_halted3);
21296 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21297 		    (void *)tcp->tcp_connp));
21298 	}
21299 
21300 	/*
21301 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21302 	 * so disable MDT otherwise.  The checks are done here
21303 	 * and in tcp_wput_data().
21304 	 */
21305 	if (tcp->tcp_mdt &&
21306 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21307 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21308 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21309 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21310 		tcp->tcp_mdt = B_FALSE;
21311 
21312 	if (tcp->tcp_mdt) {
21313 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21314 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21315 			    "version (%d), expected version is %d",
21316 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21317 			tcp->tcp_mdt = B_FALSE;
21318 			return;
21319 		}
21320 
21321 		/*
21322 		 * We need the driver to be able to handle at least three
21323 		 * spans per packet in order for tcp MDT to be utilized.
21324 		 * The first is for the header portion, while the rest are
21325 		 * needed to handle a packet that straddles across two
21326 		 * virtually non-contiguous buffers; a typical tcp packet
21327 		 * therefore consists of only two spans.  Note that we take
21328 		 * a zero as "don't care".
21329 		 */
21330 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21331 		    mdt_capab->ill_mdt_span_limit < 3) {
21332 			tcp->tcp_mdt = B_FALSE;
21333 			return;
21334 		}
21335 
21336 		/* a zero means driver wants default value */
21337 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21338 		    tcp_mdt_max_pbufs);
21339 		if (tcp->tcp_mdt_max_pld == 0)
21340 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
21341 
21342 		/* ensure 32-bit alignment */
21343 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
21344 		    mdt_capab->ill_mdt_hdr_head), 4);
21345 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
21346 		    mdt_capab->ill_mdt_hdr_tail), 4);
21347 
21348 		if (!first && !prev_state) {
21349 			TCP_STAT(tcp_mdt_conn_resumed2);
21350 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21351 			    (void *)tcp->tcp_connp));
21352 		}
21353 	}
21354 }
21355 
21356 /* Unlink and return any mblk that looks like it contains a LSO info */
21357 static mblk_t *
21358 tcp_lso_info_mp(mblk_t *mp)
21359 {
21360 	mblk_t	*prev_mp;
21361 
21362 	for (;;) {
21363 		prev_mp = mp;
21364 		/* no more to process? */
21365 		if ((mp = mp->b_cont) == NULL)
21366 			break;
21367 
21368 		switch (DB_TYPE(mp)) {
21369 		case M_CTL:
21370 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21371 				continue;
21372 			ASSERT(prev_mp != NULL);
21373 			prev_mp->b_cont = mp->b_cont;
21374 			mp->b_cont = NULL;
21375 			return (mp);
21376 		default:
21377 			break;
21378 		}
21379 	}
21380 
21381 	return (mp);
21382 }
21383 
21384 /* LSO info update routine, called when IP notifies us about LSO */
21385 static void
21386 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21387 {
21388 	/*
21389 	 * IP is telling us to abort LSO on this connection?  We know
21390 	 * this because the capability is only turned off when IP
21391 	 * encounters some pathological cases, e.g. link-layer change
21392 	 * where the new NIC/driver doesn't support LSO, or in situation
21393 	 * where LSO usage on the link-layer has been switched off.
21394 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21395 	 * if the link-layer doesn't support LSO, and if it does, it
21396 	 * will indicate that the feature is to be turned on.
21397 	 */
21398 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21399 	TCP_STAT(tcp_lso_enabled);
21400 
21401 	/*
21402 	 * We currently only support LSO on simple TCP/IPv4,
21403 	 * so disable LSO otherwise.  The checks are done here
21404 	 * and in tcp_wput_data().
21405 	 */
21406 	if (tcp->tcp_lso &&
21407 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21408 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21409 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21410 		tcp->tcp_lso = B_FALSE;
21411 		TCP_STAT(tcp_lso_disabled);
21412 	} else {
21413 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21414 		    lso_capab->ill_lso_max);
21415 	}
21416 }
21417 
21418 static void
21419 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21420 {
21421 	conn_t *connp = tcp->tcp_connp;
21422 
21423 	ASSERT(ire != NULL);
21424 
21425 	/*
21426 	 * We may be in the fastpath here, and although we essentially do
21427 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21428 	 * we try to keep things as brief as possible.  After all, these
21429 	 * are only best-effort checks, and we do more thorough ones prior
21430 	 * to calling tcp_send()/tcp_multisend().
21431 	 */
21432 	if ((ip_lso_outbound || ip_multidata_outbound) && check_lso_mdt &&
21433 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21434 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21435 	    !(ire->ire_flags & RTF_MULTIRT) &&
21436 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
21437 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21438 		if (ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21439 			/* Cache the result */
21440 			connp->conn_lso_ok = B_TRUE;
21441 
21442 			ASSERT(ill->ill_lso_capab != NULL);
21443 			if (!ill->ill_lso_capab->ill_lso_on) {
21444 				ill->ill_lso_capab->ill_lso_on = 1;
21445 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21446 				    "LSO for interface %s\n", (void *)connp,
21447 				    ill->ill_name));
21448 			}
21449 			tcp_lso_update(tcp, ill->ill_lso_capab);
21450 		} else if (ip_multidata_outbound && ILL_MDT_CAPABLE(ill)) {
21451 			/* Cache the result */
21452 			connp->conn_mdt_ok = B_TRUE;
21453 
21454 			ASSERT(ill->ill_mdt_capab != NULL);
21455 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21456 				ill->ill_mdt_capab->ill_mdt_on = 1;
21457 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21458 				    "MDT for interface %s\n", (void *)connp,
21459 				    ill->ill_name));
21460 			}
21461 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21462 		}
21463 	}
21464 
21465 	/*
21466 	 * The goal is to reduce the number of generated tcp segments by
21467 	 * setting the maxpsz multiplier to 0; this will have an affect on
21468 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21469 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21470 	 * of outbound segments and incoming ACKs, thus allowing for better
21471 	 * network and system performance.  In contrast the legacy behavior
21472 	 * may result in sending less than SMSS size, because the last mblk
21473 	 * for some packets may have more data than needed to make up SMSS,
21474 	 * and the legacy code refused to "split" it.
21475 	 *
21476 	 * We apply the new behavior on following situations:
21477 	 *
21478 	 *   1) Loopback connections,
21479 	 *   2) Connections in which the remote peer is not on local subnet,
21480 	 *   3) Local subnet connections over the bge interface (see below).
21481 	 *
21482 	 * Ideally, we would like this behavior to apply for interfaces other
21483 	 * than bge.  However, doing so would negatively impact drivers which
21484 	 * perform dynamic mapping and unmapping of DMA resources, which are
21485 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21486 	 * packet will be generated by tcp).  The bge driver does not suffer
21487 	 * from this, as it copies the mblks into pre-mapped buffers, and
21488 	 * therefore does not require more I/O resources than before.
21489 	 *
21490 	 * Otherwise, this behavior is present on all network interfaces when
21491 	 * the destination endpoint is non-local, since reducing the number
21492 	 * of packets in general is good for the network.
21493 	 *
21494 	 * TODO We need to remove this hard-coded conditional for bge once
21495 	 *	a better "self-tuning" mechanism, or a way to comprehend
21496 	 *	the driver transmit strategy is devised.  Until the solution
21497 	 *	is found and well understood, we live with this hack.
21498 	 */
21499 	if (!tcp_static_maxpsz &&
21500 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21501 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21502 		/* override the default value */
21503 		tcp->tcp_maxpsz = 0;
21504 
21505 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21506 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21507 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21508 	}
21509 
21510 	/* set the stream head parameters accordingly */
21511 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21512 }
21513 
21514 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21515 static void
21516 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21517 {
21518 	uchar_t	fval = *mp->b_rptr;
21519 	mblk_t	*tail;
21520 	queue_t	*q = tcp->tcp_wq;
21521 
21522 	/* TODO: How should flush interact with urgent data? */
21523 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21524 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21525 		/*
21526 		 * Flush only data that has not yet been put on the wire.  If
21527 		 * we flush data that we have already transmitted, life, as we
21528 		 * know it, may come to an end.
21529 		 */
21530 		tail = tcp->tcp_xmit_tail;
21531 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21532 		tcp->tcp_xmit_tail_unsent = 0;
21533 		tcp->tcp_unsent = 0;
21534 		if (tail->b_wptr != tail->b_rptr)
21535 			tail = tail->b_cont;
21536 		if (tail) {
21537 			mblk_t **excess = &tcp->tcp_xmit_head;
21538 			for (;;) {
21539 				mblk_t *mp1 = *excess;
21540 				if (mp1 == tail)
21541 					break;
21542 				tcp->tcp_xmit_tail = mp1;
21543 				tcp->tcp_xmit_last = mp1;
21544 				excess = &mp1->b_cont;
21545 			}
21546 			*excess = NULL;
21547 			tcp_close_mpp(&tail);
21548 			if (tcp->tcp_snd_zcopy_aware)
21549 				tcp_zcopy_notify(tcp);
21550 		}
21551 		/*
21552 		 * We have no unsent data, so unsent must be less than
21553 		 * tcp_xmit_lowater, so re-enable flow.
21554 		 */
21555 		mutex_enter(&tcp->tcp_non_sq_lock);
21556 		if (tcp->tcp_flow_stopped) {
21557 			tcp_clrqfull(tcp);
21558 		}
21559 		mutex_exit(&tcp->tcp_non_sq_lock);
21560 	}
21561 	/*
21562 	 * TODO: you can't just flush these, you have to increase rwnd for one
21563 	 * thing.  For another, how should urgent data interact?
21564 	 */
21565 	if (fval & FLUSHR) {
21566 		*mp->b_rptr = fval & ~FLUSHW;
21567 		/* XXX */
21568 		qreply(q, mp);
21569 		return;
21570 	}
21571 	freemsg(mp);
21572 }
21573 
21574 /*
21575  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21576  * messages.
21577  */
21578 static void
21579 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21580 {
21581 	mblk_t	*mp1;
21582 	STRUCT_HANDLE(strbuf, sb);
21583 	uint16_t port;
21584 	queue_t 	*q = tcp->tcp_wq;
21585 	in6_addr_t	v6addr;
21586 	ipaddr_t	v4addr;
21587 	uint32_t	flowinfo = 0;
21588 	int		addrlen;
21589 
21590 	/* Make sure it is one of ours. */
21591 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21592 	case TI_GETMYNAME:
21593 	case TI_GETPEERNAME:
21594 		break;
21595 	default:
21596 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21597 		return;
21598 	}
21599 	switch (mi_copy_state(q, mp, &mp1)) {
21600 	case -1:
21601 		return;
21602 	case MI_COPY_CASE(MI_COPY_IN, 1):
21603 		break;
21604 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21605 		/* Copy out the strbuf. */
21606 		mi_copyout(q, mp);
21607 		return;
21608 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21609 		/* All done. */
21610 		mi_copy_done(q, mp, 0);
21611 		return;
21612 	default:
21613 		mi_copy_done(q, mp, EPROTO);
21614 		return;
21615 	}
21616 	/* Check alignment of the strbuf */
21617 	if (!OK_32PTR(mp1->b_rptr)) {
21618 		mi_copy_done(q, mp, EINVAL);
21619 		return;
21620 	}
21621 
21622 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
21623 	    (void *)mp1->b_rptr);
21624 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21625 
21626 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21627 		mi_copy_done(q, mp, EINVAL);
21628 		return;
21629 	}
21630 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21631 	case TI_GETMYNAME:
21632 		if (tcp->tcp_family == AF_INET) {
21633 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21634 				v4addr = tcp->tcp_ipha->ipha_src;
21635 			} else {
21636 				/* can't return an address in this case */
21637 				v4addr = 0;
21638 			}
21639 		} else {
21640 			/* tcp->tcp_family == AF_INET6 */
21641 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21642 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
21643 				    &v6addr);
21644 			} else {
21645 				v6addr = tcp->tcp_ip6h->ip6_src;
21646 			}
21647 		}
21648 		port = tcp->tcp_lport;
21649 		break;
21650 	case TI_GETPEERNAME:
21651 		if (tcp->tcp_family == AF_INET) {
21652 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21653 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
21654 				    v4addr);
21655 			} else {
21656 				/* can't return an address in this case */
21657 				v4addr = 0;
21658 			}
21659 		} else {
21660 			/* tcp->tcp_family == AF_INET6) */
21661 			v6addr = tcp->tcp_remote_v6;
21662 			if (tcp->tcp_ipversion == IPV6_VERSION) {
21663 				/*
21664 				 * No flowinfo if tcp->tcp_ipversion is v4.
21665 				 *
21666 				 * flowinfo was already initialized to zero
21667 				 * where it was declared above, so only
21668 				 * set it if ipversion is v6.
21669 				 */
21670 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
21671 				    ~IPV6_VERS_AND_FLOW_MASK;
21672 			}
21673 		}
21674 		port = tcp->tcp_fport;
21675 		break;
21676 	default:
21677 		mi_copy_done(q, mp, EPROTO);
21678 		return;
21679 	}
21680 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21681 	if (!mp1)
21682 		return;
21683 
21684 	if (tcp->tcp_family == AF_INET) {
21685 		sin_t *sin;
21686 
21687 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
21688 		sin = (sin_t *)mp1->b_rptr;
21689 		mp1->b_wptr = (uchar_t *)&sin[1];
21690 		*sin = sin_null;
21691 		sin->sin_family = AF_INET;
21692 		sin->sin_addr.s_addr = v4addr;
21693 		sin->sin_port = port;
21694 	} else {
21695 		/* tcp->tcp_family == AF_INET6 */
21696 		sin6_t *sin6;
21697 
21698 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
21699 		sin6 = (sin6_t *)mp1->b_rptr;
21700 		mp1->b_wptr = (uchar_t *)&sin6[1];
21701 		*sin6 = sin6_null;
21702 		sin6->sin6_family = AF_INET6;
21703 		sin6->sin6_flowinfo = flowinfo;
21704 		sin6->sin6_addr = v6addr;
21705 		sin6->sin6_port = port;
21706 	}
21707 	/* Copy out the address */
21708 	mi_copyout(q, mp);
21709 }
21710 
21711 /*
21712  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21713  * messages.
21714  */
21715 /* ARGSUSED */
21716 static void
21717 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21718 {
21719 	conn_t 	*connp = (conn_t *)arg;
21720 	tcp_t	*tcp = connp->conn_tcp;
21721 	queue_t	*q = tcp->tcp_wq;
21722 	struct iocblk	*iocp;
21723 
21724 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21725 	/*
21726 	 * Try and ASSERT the minimum possible references on the
21727 	 * conn early enough. Since we are executing on write side,
21728 	 * the connection is obviously not detached and that means
21729 	 * there is a ref each for TCP and IP. Since we are behind
21730 	 * the squeue, the minimum references needed are 3. If the
21731 	 * conn is in classifier hash list, there should be an
21732 	 * extra ref for that (we check both the possibilities).
21733 	 */
21734 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21735 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21736 
21737 	iocp = (struct iocblk *)mp->b_rptr;
21738 	switch (iocp->ioc_cmd) {
21739 	case TCP_IOC_DEFAULT_Q:
21740 		/* Wants to be the default wq. */
21741 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
21742 			iocp->ioc_error = EPERM;
21743 			iocp->ioc_count = 0;
21744 			mp->b_datap->db_type = M_IOCACK;
21745 			qreply(q, mp);
21746 			return;
21747 		}
21748 		tcp_def_q_set(tcp, mp);
21749 		return;
21750 	case _SIOCSOCKFALLBACK:
21751 		/*
21752 		 * Either sockmod is about to be popped and the socket
21753 		 * would now be treated as a plain stream, or a module
21754 		 * is about to be pushed so we could no longer use read-
21755 		 * side synchronous streams for fused loopback tcp.
21756 		 * Drain any queued data and disable direct sockfs
21757 		 * interface from now on.
21758 		 */
21759 		if (!tcp->tcp_issocket) {
21760 			DB_TYPE(mp) = M_IOCNAK;
21761 			iocp->ioc_error = EINVAL;
21762 		} else {
21763 #ifdef	_ILP32
21764 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
21765 #else
21766 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21767 #endif
21768 			/*
21769 			 * Insert this socket into the acceptor hash.
21770 			 * We might need it for T_CONN_RES message
21771 			 */
21772 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21773 
21774 			if (tcp->tcp_fused) {
21775 				/*
21776 				 * This is a fused loopback tcp; disable
21777 				 * read-side synchronous streams interface
21778 				 * and drain any queued data.  It is okay
21779 				 * to do this for non-synchronous streams
21780 				 * fused tcp as well.
21781 				 */
21782 				tcp_fuse_disable_pair(tcp, B_FALSE);
21783 			}
21784 			tcp->tcp_issocket = B_FALSE;
21785 			TCP_STAT(tcp_sock_fallback);
21786 
21787 			DB_TYPE(mp) = M_IOCACK;
21788 			iocp->ioc_error = 0;
21789 		}
21790 		iocp->ioc_count = 0;
21791 		iocp->ioc_rval = 0;
21792 		qreply(q, mp);
21793 		return;
21794 	}
21795 	CALL_IP_WPUT(connp, q, mp);
21796 }
21797 
21798 /*
21799  * This routine is called by tcp_wput() to handle all TPI requests.
21800  */
21801 /* ARGSUSED */
21802 static void
21803 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21804 {
21805 	conn_t 	*connp = (conn_t *)arg;
21806 	tcp_t	*tcp = connp->conn_tcp;
21807 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21808 	uchar_t *rptr;
21809 	t_scalar_t type;
21810 	int len;
21811 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
21812 
21813 	/*
21814 	 * Try and ASSERT the minimum possible references on the
21815 	 * conn early enough. Since we are executing on write side,
21816 	 * the connection is obviously not detached and that means
21817 	 * there is a ref each for TCP and IP. Since we are behind
21818 	 * the squeue, the minimum references needed are 3. If the
21819 	 * conn is in classifier hash list, there should be an
21820 	 * extra ref for that (we check both the possibilities).
21821 	 */
21822 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21823 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21824 
21825 	rptr = mp->b_rptr;
21826 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21827 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21828 		type = ((union T_primitives *)rptr)->type;
21829 		if (type == T_EXDATA_REQ) {
21830 			uint32_t msize = msgdsize(mp->b_cont);
21831 
21832 			len = msize - 1;
21833 			if (len < 0) {
21834 				freemsg(mp);
21835 				return;
21836 			}
21837 			/*
21838 			 * Try to force urgent data out on the wire.
21839 			 * Even if we have unsent data this will
21840 			 * at least send the urgent flag.
21841 			 * XXX does not handle more flag correctly.
21842 			 */
21843 			len += tcp->tcp_unsent;
21844 			len += tcp->tcp_snxt;
21845 			tcp->tcp_urg = len;
21846 			tcp->tcp_valid_bits |= TCP_URG_VALID;
21847 
21848 			/* Bypass tcp protocol for fused tcp loopback */
21849 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
21850 				return;
21851 		} else if (type != T_DATA_REQ) {
21852 			goto non_urgent_data;
21853 		}
21854 		/* TODO: options, flags, ... from user */
21855 		/* Set length to zero for reclamation below */
21856 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21857 		freeb(mp);
21858 		return;
21859 	} else {
21860 		if (tcp->tcp_debug) {
21861 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21862 			    "tcp_wput_proto, dropping one...");
21863 		}
21864 		freemsg(mp);
21865 		return;
21866 	}
21867 
21868 non_urgent_data:
21869 
21870 	switch ((int)tprim->type) {
21871 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21872 		/*
21873 		 * save the kssl_ent_t from the next block, and convert this
21874 		 * back to a normal bind_req.
21875 		 */
21876 		if (mp->b_cont != NULL) {
21877 		    ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21878 
21879 			if (tcp->tcp_kssl_ent != NULL) {
21880 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21881 				    KSSL_NO_PROXY);
21882 				tcp->tcp_kssl_ent = NULL;
21883 			}
21884 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21885 			    sizeof (kssl_ent_t));
21886 			kssl_hold_ent(tcp->tcp_kssl_ent);
21887 			freemsg(mp->b_cont);
21888 			mp->b_cont = NULL;
21889 		}
21890 		tprim->type = T_BIND_REQ;
21891 
21892 	/* FALLTHROUGH */
21893 	case O_T_BIND_REQ:	/* bind request */
21894 	case T_BIND_REQ:	/* new semantics bind request */
21895 		tcp_bind(tcp, mp);
21896 		break;
21897 	case T_UNBIND_REQ:	/* unbind request */
21898 		tcp_unbind(tcp, mp);
21899 		break;
21900 	case O_T_CONN_RES:	/* old connection response XXX */
21901 	case T_CONN_RES:	/* connection response */
21902 		tcp_accept(tcp, mp);
21903 		break;
21904 	case T_CONN_REQ:	/* connection request */
21905 		tcp_connect(tcp, mp);
21906 		break;
21907 	case T_DISCON_REQ:	/* disconnect request */
21908 		tcp_disconnect(tcp, mp);
21909 		break;
21910 	case T_CAPABILITY_REQ:
21911 		tcp_capability_req(tcp, mp);	/* capability request */
21912 		break;
21913 	case T_INFO_REQ:	/* information request */
21914 		tcp_info_req(tcp, mp);
21915 		break;
21916 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21917 		/* Only IP is allowed to return meaningful value */
21918 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21919 		break;
21920 	case T_OPTMGMT_REQ:
21921 		/*
21922 		 * Note:  no support for snmpcom_req() through new
21923 		 * T_OPTMGMT_REQ. See comments in ip.c
21924 		 */
21925 		/* Only IP is allowed to return meaningful value */
21926 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21927 		break;
21928 
21929 	case T_UNITDATA_REQ:	/* unitdata request */
21930 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21931 		break;
21932 	case T_ORDREL_REQ:	/* orderly release req */
21933 		freemsg(mp);
21934 
21935 		if (tcp->tcp_fused)
21936 			tcp_unfuse(tcp);
21937 
21938 		if (tcp_xmit_end(tcp) != 0) {
21939 			/*
21940 			 * We were crossing FINs and got a reset from
21941 			 * the other side. Just ignore it.
21942 			 */
21943 			if (tcp->tcp_debug) {
21944 				(void) strlog(TCP_MOD_ID, 0, 1,
21945 				    SL_ERROR|SL_TRACE,
21946 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21947 				    "state %s",
21948 				    tcp_display(tcp, NULL,
21949 				    DISP_ADDR_AND_PORT));
21950 			}
21951 		}
21952 		break;
21953 	case T_ADDR_REQ:
21954 		tcp_addr_req(tcp, mp);
21955 		break;
21956 	default:
21957 		if (tcp->tcp_debug) {
21958 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21959 			    "tcp_wput_proto, bogus TPI msg, type %d",
21960 			    tprim->type);
21961 		}
21962 		/*
21963 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21964 		 * to recover.
21965 		 */
21966 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21967 		break;
21968 	}
21969 }
21970 
21971 /*
21972  * The TCP write service routine should never be called...
21973  */
21974 /* ARGSUSED */
21975 static void
21976 tcp_wsrv(queue_t *q)
21977 {
21978 	TCP_STAT(tcp_wsrv_called);
21979 }
21980 
21981 /* Non overlapping byte exchanger */
21982 static void
21983 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21984 {
21985 	uchar_t	uch;
21986 
21987 	while (len-- > 0) {
21988 		uch = a[len];
21989 		a[len] = b[len];
21990 		b[len] = uch;
21991 	}
21992 }
21993 
21994 /*
21995  * Send out a control packet on the tcp connection specified.  This routine
21996  * is typically called where we need a simple ACK or RST generated.
21997  */
21998 static void
21999 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22000 {
22001 	uchar_t		*rptr;
22002 	tcph_t		*tcph;
22003 	ipha_t		*ipha = NULL;
22004 	ip6_t		*ip6h = NULL;
22005 	uint32_t	sum;
22006 	int		tcp_hdr_len;
22007 	int		tcp_ip_hdr_len;
22008 	mblk_t		*mp;
22009 
22010 	/*
22011 	 * Save sum for use in source route later.
22012 	 */
22013 	ASSERT(tcp != NULL);
22014 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22015 	tcp_hdr_len = tcp->tcp_hdr_len;
22016 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22017 
22018 	/* If a text string is passed in with the request, pass it to strlog. */
22019 	if (str != NULL && tcp->tcp_debug) {
22020 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22021 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22022 		    str, seq, ack, ctl);
22023 	}
22024 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
22025 	    BPRI_MED);
22026 	if (mp == NULL) {
22027 		return;
22028 	}
22029 	rptr = &mp->b_rptr[tcp_wroff_xtra];
22030 	mp->b_rptr = rptr;
22031 	mp->b_wptr = &rptr[tcp_hdr_len];
22032 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22033 
22034 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22035 		ipha = (ipha_t *)rptr;
22036 		ipha->ipha_length = htons(tcp_hdr_len);
22037 	} else {
22038 		ip6h = (ip6_t *)rptr;
22039 		ASSERT(tcp != NULL);
22040 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22041 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22042 	}
22043 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22044 	tcph->th_flags[0] = (uint8_t)ctl;
22045 	if (ctl & TH_RST) {
22046 		BUMP_MIB(&tcp_mib, tcpOutRsts);
22047 		BUMP_MIB(&tcp_mib, tcpOutControl);
22048 		/*
22049 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22050 		 */
22051 		if (tcp->tcp_snd_ts_ok &&
22052 		    tcp->tcp_state > TCPS_SYN_SENT) {
22053 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22054 			*(mp->b_wptr) = TCPOPT_EOL;
22055 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22056 				ipha->ipha_length = htons(tcp_hdr_len -
22057 				    TCPOPT_REAL_TS_LEN);
22058 			} else {
22059 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22060 				    TCPOPT_REAL_TS_LEN);
22061 			}
22062 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22063 			sum -= TCPOPT_REAL_TS_LEN;
22064 		}
22065 	}
22066 	if (ctl & TH_ACK) {
22067 		if (tcp->tcp_snd_ts_ok) {
22068 			U32_TO_BE32(lbolt,
22069 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22070 			U32_TO_BE32(tcp->tcp_ts_recent,
22071 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22072 		}
22073 
22074 		/* Update the latest receive window size in TCP header. */
22075 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22076 		    tcph->th_win);
22077 		tcp->tcp_rack = ack;
22078 		tcp->tcp_rack_cnt = 0;
22079 		BUMP_MIB(&tcp_mib, tcpOutAck);
22080 	}
22081 	BUMP_LOCAL(tcp->tcp_obsegs);
22082 	U32_TO_BE32(seq, tcph->th_seq);
22083 	U32_TO_BE32(ack, tcph->th_ack);
22084 	/*
22085 	 * Include the adjustment for a source route if any.
22086 	 */
22087 	sum = (sum >> 16) + (sum & 0xFFFF);
22088 	U16_TO_BE16(sum, tcph->th_sum);
22089 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22090 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22091 }
22092 
22093 /*
22094  * If this routine returns B_TRUE, TCP can generate a RST in response
22095  * to a segment.  If it returns B_FALSE, TCP should not respond.
22096  */
22097 static boolean_t
22098 tcp_send_rst_chk(void)
22099 {
22100 	clock_t	now;
22101 
22102 	/*
22103 	 * TCP needs to protect itself from generating too many RSTs.
22104 	 * This can be a DoS attack by sending us random segments
22105 	 * soliciting RSTs.
22106 	 *
22107 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22108 	 * in each 1 second interval.  In this way, TCP still generate
22109 	 * RSTs in normal cases but when under attack, the impact is
22110 	 * limited.
22111 	 */
22112 	if (tcp_rst_sent_rate_enabled != 0) {
22113 		now = lbolt;
22114 		/* lbolt can wrap around. */
22115 		if ((tcp_last_rst_intrvl > now) ||
22116 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
22117 			tcp_last_rst_intrvl = now;
22118 			tcp_rst_cnt = 1;
22119 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
22120 			return (B_FALSE);
22121 		}
22122 	}
22123 	return (B_TRUE);
22124 }
22125 
22126 /*
22127  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22128  */
22129 static void
22130 tcp_ip_ire_mark_advice(tcp_t *tcp)
22131 {
22132 	mblk_t *mp;
22133 	ipic_t *ipic;
22134 
22135 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22136 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22137 		    &ipic);
22138 	} else {
22139 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22140 		    &ipic);
22141 	}
22142 	if (mp == NULL)
22143 		return;
22144 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22145 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22146 }
22147 
22148 /*
22149  * Return an IP advice ioctl mblk and set ipic to be the pointer
22150  * to the advice structure.
22151  */
22152 static mblk_t *
22153 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22154 {
22155 	struct iocblk *ioc;
22156 	mblk_t *mp, *mp1;
22157 
22158 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22159 	if (mp == NULL)
22160 		return (NULL);
22161 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22162 	*ipic = (ipic_t *)mp->b_rptr;
22163 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22164 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22165 
22166 	bcopy(addr, *ipic + 1, addr_len);
22167 
22168 	(*ipic)->ipic_addr_length = addr_len;
22169 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22170 
22171 	mp1 = mkiocb(IP_IOCTL);
22172 	if (mp1 == NULL) {
22173 		freemsg(mp);
22174 		return (NULL);
22175 	}
22176 	mp1->b_cont = mp;
22177 	ioc = (struct iocblk *)mp1->b_rptr;
22178 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22179 
22180 	return (mp1);
22181 }
22182 
22183 /*
22184  * Generate a reset based on an inbound packet for which there is no active
22185  * tcp state that we can find.
22186  *
22187  * IPSEC NOTE : Try to send the reply with the same protection as it came
22188  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22189  * the packet will go out at the same level of protection as it came in by
22190  * converting the IPSEC_IN to IPSEC_OUT.
22191  */
22192 static void
22193 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22194     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid)
22195 {
22196 	ipha_t		*ipha = NULL;
22197 	ip6_t		*ip6h = NULL;
22198 	ushort_t	len;
22199 	tcph_t		*tcph;
22200 	int		i;
22201 	mblk_t		*ipsec_mp;
22202 	boolean_t	mctl_present;
22203 	ipic_t		*ipic;
22204 	ipaddr_t	v4addr;
22205 	in6_addr_t	v6addr;
22206 	int		addr_len;
22207 	void		*addr;
22208 	queue_t		*q = tcp_g_q;
22209 	tcp_t		*tcp = Q_TO_TCP(q);
22210 	cred_t		*cr;
22211 	mblk_t		*nmp;
22212 
22213 	if (!tcp_send_rst_chk()) {
22214 		tcp_rst_unsent++;
22215 		freemsg(mp);
22216 		return;
22217 	}
22218 
22219 	if (mp->b_datap->db_type == M_CTL) {
22220 		ipsec_mp = mp;
22221 		mp = mp->b_cont;
22222 		mctl_present = B_TRUE;
22223 	} else {
22224 		ipsec_mp = mp;
22225 		mctl_present = B_FALSE;
22226 	}
22227 
22228 	if (str && q && tcp_dbg) {
22229 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22230 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22231 		    "flags 0x%x",
22232 		    str, seq, ack, ctl);
22233 	}
22234 	if (mp->b_datap->db_ref != 1) {
22235 		mblk_t *mp1 = copyb(mp);
22236 		freemsg(mp);
22237 		mp = mp1;
22238 		if (!mp) {
22239 			if (mctl_present)
22240 				freeb(ipsec_mp);
22241 			return;
22242 		} else {
22243 			if (mctl_present) {
22244 				ipsec_mp->b_cont = mp;
22245 			} else {
22246 				ipsec_mp = mp;
22247 			}
22248 		}
22249 	} else if (mp->b_cont) {
22250 		freemsg(mp->b_cont);
22251 		mp->b_cont = NULL;
22252 	}
22253 	/*
22254 	 * We skip reversing source route here.
22255 	 * (for now we replace all IP options with EOL)
22256 	 */
22257 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22258 		ipha = (ipha_t *)mp->b_rptr;
22259 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22260 			mp->b_rptr[i] = IPOPT_EOL;
22261 		/*
22262 		 * Make sure that src address isn't flagrantly invalid.
22263 		 * Not all broadcast address checking for the src address
22264 		 * is possible, since we don't know the netmask of the src
22265 		 * addr.  No check for destination address is done, since
22266 		 * IP will not pass up a packet with a broadcast dest
22267 		 * address to TCP.  Similar checks are done below for IPv6.
22268 		 */
22269 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22270 		    CLASSD(ipha->ipha_src)) {
22271 			freemsg(ipsec_mp);
22272 			BUMP_MIB(&ip_mib, ipIfStatsInDiscards);
22273 			return;
22274 		}
22275 	} else {
22276 		ip6h = (ip6_t *)mp->b_rptr;
22277 
22278 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22279 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22280 			freemsg(ipsec_mp);
22281 			BUMP_MIB(&ip6_mib, ipIfStatsInDiscards);
22282 			return;
22283 		}
22284 
22285 		/* Remove any extension headers assuming partial overlay */
22286 		if (ip_hdr_len > IPV6_HDR_LEN) {
22287 			uint8_t *to;
22288 
22289 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22290 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22291 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22292 			ip_hdr_len = IPV6_HDR_LEN;
22293 			ip6h = (ip6_t *)mp->b_rptr;
22294 			ip6h->ip6_nxt = IPPROTO_TCP;
22295 		}
22296 	}
22297 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22298 	if (tcph->th_flags[0] & TH_RST) {
22299 		freemsg(ipsec_mp);
22300 		return;
22301 	}
22302 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22303 	len = ip_hdr_len + sizeof (tcph_t);
22304 	mp->b_wptr = &mp->b_rptr[len];
22305 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22306 		ipha->ipha_length = htons(len);
22307 		/* Swap addresses */
22308 		v4addr = ipha->ipha_src;
22309 		ipha->ipha_src = ipha->ipha_dst;
22310 		ipha->ipha_dst = v4addr;
22311 		ipha->ipha_ident = 0;
22312 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
22313 		addr_len = IP_ADDR_LEN;
22314 		addr = &v4addr;
22315 	} else {
22316 		/* No ip6i_t in this case */
22317 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22318 		/* Swap addresses */
22319 		v6addr = ip6h->ip6_src;
22320 		ip6h->ip6_src = ip6h->ip6_dst;
22321 		ip6h->ip6_dst = v6addr;
22322 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
22323 		addr_len = IPV6_ADDR_LEN;
22324 		addr = &v6addr;
22325 	}
22326 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22327 	U32_TO_BE32(ack, tcph->th_ack);
22328 	U32_TO_BE32(seq, tcph->th_seq);
22329 	U16_TO_BE16(0, tcph->th_win);
22330 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22331 	tcph->th_flags[0] = (uint8_t)ctl;
22332 	if (ctl & TH_RST) {
22333 		BUMP_MIB(&tcp_mib, tcpOutRsts);
22334 		BUMP_MIB(&tcp_mib, tcpOutControl);
22335 	}
22336 
22337 	/* IP trusts us to set up labels when required. */
22338 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22339 	    crgetlabel(cr) != NULL) {
22340 		int err, adjust;
22341 
22342 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22343 			err = tsol_check_label(cr, &mp, &adjust,
22344 			    tcp->tcp_connp->conn_mac_exempt);
22345 		else
22346 			err = tsol_check_label_v6(cr, &mp, &adjust,
22347 			    tcp->tcp_connp->conn_mac_exempt);
22348 		if (mctl_present)
22349 			ipsec_mp->b_cont = mp;
22350 		else
22351 			ipsec_mp = mp;
22352 		if (err != 0) {
22353 			freemsg(ipsec_mp);
22354 			return;
22355 		}
22356 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22357 			ipha = (ipha_t *)mp->b_rptr;
22358 			adjust += ntohs(ipha->ipha_length);
22359 			ipha->ipha_length = htons(adjust);
22360 		} else {
22361 			ip6h = (ip6_t *)mp->b_rptr;
22362 		}
22363 	}
22364 
22365 	if (mctl_present) {
22366 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22367 
22368 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22369 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22370 			return;
22371 		}
22372 	}
22373 	if (zoneid == ALL_ZONES)
22374 		zoneid = GLOBAL_ZONEID;
22375 
22376 	/* Add the zoneid so ip_output routes it properly */
22377 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid)) == NULL) {
22378 		freemsg(ipsec_mp);
22379 		return;
22380 	}
22381 	ipsec_mp = nmp;
22382 
22383 	/*
22384 	 * NOTE:  one might consider tracing a TCP packet here, but
22385 	 * this function has no active TCP state and no tcp structure
22386 	 * that has a trace buffer.  If we traced here, we would have
22387 	 * to keep a local trace buffer in tcp_record_trace().
22388 	 *
22389 	 * TSol note: The mblk that contains the incoming packet was
22390 	 * reused by tcp_xmit_listener_reset, so it already contains
22391 	 * the right credentials and we don't need to call mblk_setcred.
22392 	 * Also the conn's cred is not right since it is associated
22393 	 * with tcp_g_q.
22394 	 */
22395 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22396 
22397 	/*
22398 	 * Tell IP to mark the IRE used for this destination temporary.
22399 	 * This way, we can limit our exposure to DoS attack because IP
22400 	 * creates an IRE for each destination.  If there are too many,
22401 	 * the time to do any routing lookup will be extremely long.  And
22402 	 * the lookup can be in interrupt context.
22403 	 *
22404 	 * Note that in normal circumstances, this marking should not
22405 	 * affect anything.  It would be nice if only 1 message is
22406 	 * needed to inform IP that the IRE created for this RST should
22407 	 * not be added to the cache table.  But there is currently
22408 	 * not such communication mechanism between TCP and IP.  So
22409 	 * the best we can do now is to send the advice ioctl to IP
22410 	 * to mark the IRE temporary.
22411 	 */
22412 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22413 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22414 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22415 	}
22416 }
22417 
22418 /*
22419  * Initiate closedown sequence on an active connection.  (May be called as
22420  * writer.)  Return value zero for OK return, non-zero for error return.
22421  */
22422 static int
22423 tcp_xmit_end(tcp_t *tcp)
22424 {
22425 	ipic_t	*ipic;
22426 	mblk_t	*mp;
22427 
22428 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22429 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22430 		/*
22431 		 * Invalid state, only states TCPS_SYN_RCVD,
22432 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22433 		 */
22434 		return (-1);
22435 	}
22436 
22437 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22438 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22439 	/*
22440 	 * If there is nothing more unsent, send the FIN now.
22441 	 * Otherwise, it will go out with the last segment.
22442 	 */
22443 	if (tcp->tcp_unsent == 0) {
22444 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22445 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22446 
22447 		if (mp) {
22448 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22449 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22450 		} else {
22451 			/*
22452 			 * Couldn't allocate msg.  Pretend we got it out.
22453 			 * Wait for rexmit timeout.
22454 			 */
22455 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22456 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22457 		}
22458 
22459 		/*
22460 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22461 		 * changed.
22462 		 */
22463 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22464 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22465 		}
22466 	} else {
22467 		/*
22468 		 * If tcp->tcp_cork is set, then the data will not get sent,
22469 		 * so we have to check that and unset it first.
22470 		 */
22471 		if (tcp->tcp_cork)
22472 			tcp->tcp_cork = B_FALSE;
22473 		tcp_wput_data(tcp, NULL, B_FALSE);
22474 	}
22475 
22476 	/*
22477 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22478 	 * is 0, don't update the cache.
22479 	 */
22480 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
22481 		return (0);
22482 
22483 	/*
22484 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22485 	 * different from the destination.
22486 	 */
22487 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22488 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22489 			return (0);
22490 		}
22491 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22492 		    &ipic);
22493 	} else {
22494 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22495 		    &tcp->tcp_ip6h->ip6_dst))) {
22496 			return (0);
22497 		}
22498 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22499 		    &ipic);
22500 	}
22501 
22502 	/* Record route attributes in the IRE for use by future connections. */
22503 	if (mp == NULL)
22504 		return (0);
22505 
22506 	/*
22507 	 * We do not have a good algorithm to update ssthresh at this time.
22508 	 * So don't do any update.
22509 	 */
22510 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22511 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22512 
22513 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22514 	return (0);
22515 }
22516 
22517 /*
22518  * Generate a "no listener here" RST in response to an "unknown" segment.
22519  * Note that we are reusing the incoming mp to construct the outgoing
22520  * RST.
22521  */
22522 void
22523 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid)
22524 {
22525 	uchar_t		*rptr;
22526 	uint32_t	seg_len;
22527 	tcph_t		*tcph;
22528 	uint32_t	seg_seq;
22529 	uint32_t	seg_ack;
22530 	uint_t		flags;
22531 	mblk_t		*ipsec_mp;
22532 	ipha_t 		*ipha;
22533 	ip6_t 		*ip6h;
22534 	boolean_t	mctl_present = B_FALSE;
22535 	boolean_t	check = B_TRUE;
22536 	boolean_t	policy_present;
22537 
22538 	TCP_STAT(tcp_no_listener);
22539 
22540 	ipsec_mp = mp;
22541 
22542 	if (mp->b_datap->db_type == M_CTL) {
22543 		ipsec_in_t *ii;
22544 
22545 		mctl_present = B_TRUE;
22546 		mp = mp->b_cont;
22547 
22548 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22549 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22550 		if (ii->ipsec_in_dont_check) {
22551 			check = B_FALSE;
22552 			if (!ii->ipsec_in_secure) {
22553 				freeb(ipsec_mp);
22554 				mctl_present = B_FALSE;
22555 				ipsec_mp = mp;
22556 			}
22557 		}
22558 	}
22559 
22560 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22561 		policy_present = ipsec_inbound_v4_policy_present;
22562 		ipha = (ipha_t *)mp->b_rptr;
22563 		ip6h = NULL;
22564 	} else {
22565 		policy_present = ipsec_inbound_v6_policy_present;
22566 		ipha = NULL;
22567 		ip6h = (ip6_t *)mp->b_rptr;
22568 	}
22569 
22570 	if (check && policy_present) {
22571 		/*
22572 		 * The conn_t parameter is NULL because we already know
22573 		 * nobody's home.
22574 		 */
22575 		ipsec_mp = ipsec_check_global_policy(
22576 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
22577 		if (ipsec_mp == NULL)
22578 			return;
22579 	}
22580 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22581 		DTRACE_PROBE2(
22582 		    tx__ip__log__error__nolistener__tcp,
22583 		    char *, "Could not reply with RST to mp(1)",
22584 		    mblk_t *, mp);
22585 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22586 		freemsg(ipsec_mp);
22587 		return;
22588 	}
22589 
22590 	rptr = mp->b_rptr;
22591 
22592 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22593 	seg_seq = BE32_TO_U32(tcph->th_seq);
22594 	seg_ack = BE32_TO_U32(tcph->th_ack);
22595 	flags = tcph->th_flags[0];
22596 
22597 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22598 	if (flags & TH_RST) {
22599 		freemsg(ipsec_mp);
22600 	} else if (flags & TH_ACK) {
22601 		tcp_xmit_early_reset("no tcp, reset",
22602 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid);
22603 	} else {
22604 		if (flags & TH_SYN) {
22605 			seg_len++;
22606 		} else {
22607 			/*
22608 			 * Here we violate the RFC.  Note that a normal
22609 			 * TCP will never send a segment without the ACK
22610 			 * flag, except for RST or SYN segment.  This
22611 			 * segment is neither.  Just drop it on the
22612 			 * floor.
22613 			 */
22614 			freemsg(ipsec_mp);
22615 			tcp_rst_unsent++;
22616 			return;
22617 		}
22618 
22619 		tcp_xmit_early_reset("no tcp, reset/ack",
22620 		    ipsec_mp, 0, seg_seq + seg_len,
22621 		    TH_RST | TH_ACK, ip_hdr_len, zoneid);
22622 	}
22623 }
22624 
22625 /*
22626  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22627  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22628  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22629  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22630  * otherwise it will dup partial mblks.)
22631  * Otherwise, an appropriate ACK packet will be generated.  This
22632  * routine is not usually called to send new data for the first time.  It
22633  * is mostly called out of the timer for retransmits, and to generate ACKs.
22634  *
22635  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22636  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22637  * of the original mblk chain will be returned in *offset and *end_mp.
22638  */
22639 mblk_t *
22640 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22641     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22642     boolean_t rexmit)
22643 {
22644 	int	data_length;
22645 	int32_t	off = 0;
22646 	uint_t	flags;
22647 	mblk_t	*mp1;
22648 	mblk_t	*mp2;
22649 	uchar_t	*rptr;
22650 	tcph_t	*tcph;
22651 	int32_t	num_sack_blk = 0;
22652 	int32_t	sack_opt_len = 0;
22653 
22654 	/* Allocate for our maximum TCP header + link-level */
22655 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
22656 	    BPRI_MED);
22657 	if (!mp1)
22658 		return (NULL);
22659 	data_length = 0;
22660 
22661 	/*
22662 	 * Note that tcp_mss has been adjusted to take into account the
22663 	 * timestamp option if applicable.  Because SACK options do not
22664 	 * appear in every TCP segments and they are of variable lengths,
22665 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22666 	 * the actual segment length when we need to send a segment which
22667 	 * includes SACK options.
22668 	 */
22669 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22670 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22671 		    tcp->tcp_num_sack_blk);
22672 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22673 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22674 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22675 			max_to_send -= sack_opt_len;
22676 	}
22677 
22678 	if (offset != NULL) {
22679 		off = *offset;
22680 		/* We use offset as an indicator that end_mp is not NULL. */
22681 		*end_mp = NULL;
22682 	}
22683 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22684 		/* This could be faster with cooperation from downstream */
22685 		if (mp2 != mp1 && !sendall &&
22686 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22687 		    max_to_send)
22688 			/*
22689 			 * Don't send the next mblk since the whole mblk
22690 			 * does not fit.
22691 			 */
22692 			break;
22693 		mp2->b_cont = dupb(mp);
22694 		mp2 = mp2->b_cont;
22695 		if (!mp2) {
22696 			freemsg(mp1);
22697 			return (NULL);
22698 		}
22699 		mp2->b_rptr += off;
22700 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22701 		    (uintptr_t)INT_MAX);
22702 
22703 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22704 		if (data_length > max_to_send) {
22705 			mp2->b_wptr -= data_length - max_to_send;
22706 			data_length = max_to_send;
22707 			off = mp2->b_wptr - mp->b_rptr;
22708 			break;
22709 		} else {
22710 			off = 0;
22711 		}
22712 	}
22713 	if (offset != NULL) {
22714 		*offset = off;
22715 		*end_mp = mp;
22716 	}
22717 	if (seg_len != NULL) {
22718 		*seg_len = data_length;
22719 	}
22720 
22721 	/* Update the latest receive window size in TCP header. */
22722 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22723 	    tcp->tcp_tcph->th_win);
22724 
22725 	rptr = mp1->b_rptr + tcp_wroff_xtra;
22726 	mp1->b_rptr = rptr;
22727 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22728 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22729 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22730 	U32_TO_ABE32(seq, tcph->th_seq);
22731 
22732 	/*
22733 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22734 	 * that this function was called from tcp_wput_data. Thus, when called
22735 	 * to retransmit data the setting of the PUSH bit may appear some
22736 	 * what random in that it might get set when it should not. This
22737 	 * should not pose any performance issues.
22738 	 */
22739 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22740 	    tcp->tcp_unsent == data_length)) {
22741 		flags = TH_ACK | TH_PUSH;
22742 	} else {
22743 		flags = TH_ACK;
22744 	}
22745 
22746 	if (tcp->tcp_ecn_ok) {
22747 		if (tcp->tcp_ecn_echo_on)
22748 			flags |= TH_ECE;
22749 
22750 		/*
22751 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22752 		 * There is no TCP flow control for non-data segments, and
22753 		 * only data segment is transmitted reliably.
22754 		 */
22755 		if (data_length > 0 && !rexmit) {
22756 			SET_ECT(tcp, rptr);
22757 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22758 				flags |= TH_CWR;
22759 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22760 			}
22761 		}
22762 	}
22763 
22764 	if (tcp->tcp_valid_bits) {
22765 		uint32_t u1;
22766 
22767 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22768 		    seq == tcp->tcp_iss) {
22769 			uchar_t	*wptr;
22770 
22771 			/*
22772 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22773 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22774 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22775 			 * our SYN is not ack'ed but the app closes this
22776 			 * TCP connection.
22777 			 */
22778 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22779 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22780 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22781 
22782 			/*
22783 			 * Tack on the MSS option.  It is always needed
22784 			 * for both active and passive open.
22785 			 *
22786 			 * MSS option value should be interface MTU - MIN
22787 			 * TCP/IP header according to RFC 793 as it means
22788 			 * the maximum segment size TCP can receive.  But
22789 			 * to get around some broken middle boxes/end hosts
22790 			 * out there, we allow the option value to be the
22791 			 * same as the MSS option size on the peer side.
22792 			 * In this way, the other side will not send
22793 			 * anything larger than they can receive.
22794 			 *
22795 			 * Note that for SYN_SENT state, the ndd param
22796 			 * tcp_use_smss_as_mss_opt has no effect as we
22797 			 * don't know the peer's MSS option value. So
22798 			 * the only case we need to take care of is in
22799 			 * SYN_RCVD state, which is done later.
22800 			 */
22801 			wptr = mp1->b_wptr;
22802 			wptr[0] = TCPOPT_MAXSEG;
22803 			wptr[1] = TCPOPT_MAXSEG_LEN;
22804 			wptr += 2;
22805 			u1 = tcp->tcp_if_mtu -
22806 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22807 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22808 			    TCP_MIN_HEADER_LENGTH;
22809 			U16_TO_BE16(u1, wptr);
22810 			mp1->b_wptr = wptr + 2;
22811 			/* Update the offset to cover the additional word */
22812 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22813 
22814 			/*
22815 			 * Note that the following way of filling in
22816 			 * TCP options are not optimal.  Some NOPs can
22817 			 * be saved.  But there is no need at this time
22818 			 * to optimize it.  When it is needed, we will
22819 			 * do it.
22820 			 */
22821 			switch (tcp->tcp_state) {
22822 			case TCPS_SYN_SENT:
22823 				flags = TH_SYN;
22824 
22825 				if (tcp->tcp_snd_ts_ok) {
22826 					uint32_t llbolt = (uint32_t)lbolt;
22827 
22828 					wptr = mp1->b_wptr;
22829 					wptr[0] = TCPOPT_NOP;
22830 					wptr[1] = TCPOPT_NOP;
22831 					wptr[2] = TCPOPT_TSTAMP;
22832 					wptr[3] = TCPOPT_TSTAMP_LEN;
22833 					wptr += 4;
22834 					U32_TO_BE32(llbolt, wptr);
22835 					wptr += 4;
22836 					ASSERT(tcp->tcp_ts_recent == 0);
22837 					U32_TO_BE32(0L, wptr);
22838 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22839 					tcph->th_offset_and_rsrvd[0] +=
22840 					    (3 << 4);
22841 				}
22842 
22843 				/*
22844 				 * Set up all the bits to tell other side
22845 				 * we are ECN capable.
22846 				 */
22847 				if (tcp->tcp_ecn_ok) {
22848 					flags |= (TH_ECE | TH_CWR);
22849 				}
22850 				break;
22851 			case TCPS_SYN_RCVD:
22852 				flags |= TH_SYN;
22853 
22854 				/*
22855 				 * Reset the MSS option value to be SMSS
22856 				 * We should probably add back the bytes
22857 				 * for timestamp option and IPsec.  We
22858 				 * don't do that as this is a workaround
22859 				 * for broken middle boxes/end hosts, it
22860 				 * is better for us to be more cautious.
22861 				 * They may not take these things into
22862 				 * account in their SMSS calculation.  Thus
22863 				 * the peer's calculated SMSS may be smaller
22864 				 * than what it can be.  This should be OK.
22865 				 */
22866 				if (tcp_use_smss_as_mss_opt) {
22867 					u1 = tcp->tcp_mss;
22868 					U16_TO_BE16(u1, wptr);
22869 				}
22870 
22871 				/*
22872 				 * If the other side is ECN capable, reply
22873 				 * that we are also ECN capable.
22874 				 */
22875 				if (tcp->tcp_ecn_ok)
22876 					flags |= TH_ECE;
22877 				break;
22878 			default:
22879 				/*
22880 				 * The above ASSERT() makes sure that this
22881 				 * must be FIN-WAIT-1 state.  Our SYN has
22882 				 * not been ack'ed so retransmit it.
22883 				 */
22884 				flags |= TH_SYN;
22885 				break;
22886 			}
22887 
22888 			if (tcp->tcp_snd_ws_ok) {
22889 				wptr = mp1->b_wptr;
22890 				wptr[0] =  TCPOPT_NOP;
22891 				wptr[1] =  TCPOPT_WSCALE;
22892 				wptr[2] =  TCPOPT_WS_LEN;
22893 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22894 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22895 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22896 			}
22897 
22898 			if (tcp->tcp_snd_sack_ok) {
22899 				wptr = mp1->b_wptr;
22900 				wptr[0] = TCPOPT_NOP;
22901 				wptr[1] = TCPOPT_NOP;
22902 				wptr[2] = TCPOPT_SACK_PERMITTED;
22903 				wptr[3] = TCPOPT_SACK_OK_LEN;
22904 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22905 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22906 			}
22907 
22908 			/* allocb() of adequate mblk assures space */
22909 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22910 			    (uintptr_t)INT_MAX);
22911 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22912 			/*
22913 			 * Get IP set to checksum on our behalf
22914 			 * Include the adjustment for a source route if any.
22915 			 */
22916 			u1 += tcp->tcp_sum;
22917 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22918 			U16_TO_BE16(u1, tcph->th_sum);
22919 			BUMP_MIB(&tcp_mib, tcpOutControl);
22920 		}
22921 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22922 		    (seq + data_length) == tcp->tcp_fss) {
22923 			if (!tcp->tcp_fin_acked) {
22924 				flags |= TH_FIN;
22925 				BUMP_MIB(&tcp_mib, tcpOutControl);
22926 			}
22927 			if (!tcp->tcp_fin_sent) {
22928 				tcp->tcp_fin_sent = B_TRUE;
22929 				switch (tcp->tcp_state) {
22930 				case TCPS_SYN_RCVD:
22931 				case TCPS_ESTABLISHED:
22932 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22933 					break;
22934 				case TCPS_CLOSE_WAIT:
22935 					tcp->tcp_state = TCPS_LAST_ACK;
22936 					break;
22937 				}
22938 				if (tcp->tcp_suna == tcp->tcp_snxt)
22939 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22940 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22941 			}
22942 		}
22943 		/*
22944 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22945 		 * is smaller than seq, u1 will become a very huge value.
22946 		 * So the comparison will fail.  Also note that tcp_urp
22947 		 * should be positive, see RFC 793 page 17.
22948 		 */
22949 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22950 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22951 		    u1 < (uint32_t)(64 * 1024)) {
22952 			flags |= TH_URG;
22953 			BUMP_MIB(&tcp_mib, tcpOutUrg);
22954 			U32_TO_ABE16(u1, tcph->th_urp);
22955 		}
22956 	}
22957 	tcph->th_flags[0] = (uchar_t)flags;
22958 	tcp->tcp_rack = tcp->tcp_rnxt;
22959 	tcp->tcp_rack_cnt = 0;
22960 
22961 	if (tcp->tcp_snd_ts_ok) {
22962 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22963 			uint32_t llbolt = (uint32_t)lbolt;
22964 
22965 			U32_TO_BE32(llbolt,
22966 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22967 			U32_TO_BE32(tcp->tcp_ts_recent,
22968 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22969 		}
22970 	}
22971 
22972 	if (num_sack_blk > 0) {
22973 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22974 		sack_blk_t *tmp;
22975 		int32_t	i;
22976 
22977 		wptr[0] = TCPOPT_NOP;
22978 		wptr[1] = TCPOPT_NOP;
22979 		wptr[2] = TCPOPT_SACK;
22980 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22981 		    sizeof (sack_blk_t);
22982 		wptr += TCPOPT_REAL_SACK_LEN;
22983 
22984 		tmp = tcp->tcp_sack_list;
22985 		for (i = 0; i < num_sack_blk; i++) {
22986 			U32_TO_BE32(tmp[i].begin, wptr);
22987 			wptr += sizeof (tcp_seq);
22988 			U32_TO_BE32(tmp[i].end, wptr);
22989 			wptr += sizeof (tcp_seq);
22990 		}
22991 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22992 	}
22993 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22994 	data_length += (int)(mp1->b_wptr - rptr);
22995 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22996 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22997 	} else {
22998 		ip6_t *ip6 = (ip6_t *)(rptr +
22999 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23000 		    sizeof (ip6i_t) : 0));
23001 
23002 		ip6->ip6_plen = htons(data_length -
23003 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23004 	}
23005 
23006 	/*
23007 	 * Prime pump for IP
23008 	 * Include the adjustment for a source route if any.
23009 	 */
23010 	data_length -= tcp->tcp_ip_hdr_len;
23011 	data_length += tcp->tcp_sum;
23012 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23013 	U16_TO_ABE16(data_length, tcph->th_sum);
23014 	if (tcp->tcp_ip_forward_progress) {
23015 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23016 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23017 		tcp->tcp_ip_forward_progress = B_FALSE;
23018 	}
23019 	return (mp1);
23020 }
23021 
23022 /* This function handles the push timeout. */
23023 void
23024 tcp_push_timer(void *arg)
23025 {
23026 	conn_t	*connp = (conn_t *)arg;
23027 	tcp_t *tcp = connp->conn_tcp;
23028 
23029 	TCP_DBGSTAT(tcp_push_timer_cnt);
23030 
23031 	ASSERT(tcp->tcp_listener == NULL);
23032 
23033 	/*
23034 	 * We need to plug synchronous streams during our drain to prevent
23035 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23036 	 */
23037 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23038 	tcp->tcp_push_tid = 0;
23039 	if ((tcp->tcp_rcv_list != NULL) &&
23040 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
23041 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23042 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23043 }
23044 
23045 /*
23046  * This function handles delayed ACK timeout.
23047  */
23048 static void
23049 tcp_ack_timer(void *arg)
23050 {
23051 	conn_t	*connp = (conn_t *)arg;
23052 	tcp_t *tcp = connp->conn_tcp;
23053 	mblk_t *mp;
23054 
23055 	TCP_DBGSTAT(tcp_ack_timer_cnt);
23056 
23057 	tcp->tcp_ack_tid = 0;
23058 
23059 	if (tcp->tcp_fused)
23060 		return;
23061 
23062 	/*
23063 	 * Do not send ACK if there is no outstanding unack'ed data.
23064 	 */
23065 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23066 		return;
23067 	}
23068 
23069 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23070 		/*
23071 		 * Make sure we don't allow deferred ACKs to result in
23072 		 * timer-based ACKing.  If we have held off an ACK
23073 		 * when there was more than an mss here, and the timer
23074 		 * goes off, we have to worry about the possibility
23075 		 * that the sender isn't doing slow-start, or is out
23076 		 * of step with us for some other reason.  We fall
23077 		 * permanently back in the direction of
23078 		 * ACK-every-other-packet as suggested in RFC 1122.
23079 		 */
23080 		if (tcp->tcp_rack_abs_max > 2)
23081 			tcp->tcp_rack_abs_max--;
23082 		tcp->tcp_rack_cur_max = 2;
23083 	}
23084 	mp = tcp_ack_mp(tcp);
23085 
23086 	if (mp != NULL) {
23087 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
23088 		BUMP_LOCAL(tcp->tcp_obsegs);
23089 		BUMP_MIB(&tcp_mib, tcpOutAck);
23090 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
23091 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23092 	}
23093 }
23094 
23095 
23096 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23097 static mblk_t *
23098 tcp_ack_mp(tcp_t *tcp)
23099 {
23100 	uint32_t	seq_no;
23101 
23102 	/*
23103 	 * There are a few cases to be considered while setting the sequence no.
23104 	 * Essentially, we can come here while processing an unacceptable pkt
23105 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23106 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23107 	 * If we are here for a zero window probe, stick with suna. In all
23108 	 * other cases, we check if suna + swnd encompasses snxt and set
23109 	 * the sequence number to snxt, if so. If snxt falls outside the
23110 	 * window (the receiver probably shrunk its window), we will go with
23111 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23112 	 * receiver.
23113 	 */
23114 	if (tcp->tcp_zero_win_probe) {
23115 		seq_no = tcp->tcp_suna;
23116 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23117 		ASSERT(tcp->tcp_swnd == 0);
23118 		seq_no = tcp->tcp_snxt;
23119 	} else {
23120 		seq_no = SEQ_GT(tcp->tcp_snxt,
23121 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23122 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23123 	}
23124 
23125 	if (tcp->tcp_valid_bits) {
23126 		/*
23127 		 * For the complex case where we have to send some
23128 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23129 		 */
23130 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23131 		    NULL, B_FALSE));
23132 	} else {
23133 		/* Generate a simple ACK */
23134 		int	data_length;
23135 		uchar_t	*rptr;
23136 		tcph_t	*tcph;
23137 		mblk_t	*mp1;
23138 		int32_t	tcp_hdr_len;
23139 		int32_t	tcp_tcp_hdr_len;
23140 		int32_t	num_sack_blk = 0;
23141 		int32_t sack_opt_len;
23142 
23143 		/*
23144 		 * Allocate space for TCP + IP headers
23145 		 * and link-level header
23146 		 */
23147 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23148 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23149 			    tcp->tcp_num_sack_blk);
23150 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23151 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23152 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23153 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23154 		} else {
23155 			tcp_hdr_len = tcp->tcp_hdr_len;
23156 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23157 		}
23158 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
23159 		if (!mp1)
23160 			return (NULL);
23161 
23162 		/* Update the latest receive window size in TCP header. */
23163 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23164 		    tcp->tcp_tcph->th_win);
23165 		/* copy in prototype TCP + IP header */
23166 		rptr = mp1->b_rptr + tcp_wroff_xtra;
23167 		mp1->b_rptr = rptr;
23168 		mp1->b_wptr = rptr + tcp_hdr_len;
23169 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23170 
23171 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23172 
23173 		/* Set the TCP sequence number. */
23174 		U32_TO_ABE32(seq_no, tcph->th_seq);
23175 
23176 		/* Set up the TCP flag field. */
23177 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23178 		if (tcp->tcp_ecn_echo_on)
23179 			tcph->th_flags[0] |= TH_ECE;
23180 
23181 		tcp->tcp_rack = tcp->tcp_rnxt;
23182 		tcp->tcp_rack_cnt = 0;
23183 
23184 		/* fill in timestamp option if in use */
23185 		if (tcp->tcp_snd_ts_ok) {
23186 			uint32_t llbolt = (uint32_t)lbolt;
23187 
23188 			U32_TO_BE32(llbolt,
23189 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23190 			U32_TO_BE32(tcp->tcp_ts_recent,
23191 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23192 		}
23193 
23194 		/* Fill in SACK options */
23195 		if (num_sack_blk > 0) {
23196 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23197 			sack_blk_t *tmp;
23198 			int32_t	i;
23199 
23200 			wptr[0] = TCPOPT_NOP;
23201 			wptr[1] = TCPOPT_NOP;
23202 			wptr[2] = TCPOPT_SACK;
23203 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23204 			    sizeof (sack_blk_t);
23205 			wptr += TCPOPT_REAL_SACK_LEN;
23206 
23207 			tmp = tcp->tcp_sack_list;
23208 			for (i = 0; i < num_sack_blk; i++) {
23209 				U32_TO_BE32(tmp[i].begin, wptr);
23210 				wptr += sizeof (tcp_seq);
23211 				U32_TO_BE32(tmp[i].end, wptr);
23212 				wptr += sizeof (tcp_seq);
23213 			}
23214 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23215 			    << 4);
23216 		}
23217 
23218 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23219 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23220 		} else {
23221 			/* Check for ip6i_t header in sticky hdrs */
23222 			ip6_t *ip6 = (ip6_t *)(rptr +
23223 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23224 			    sizeof (ip6i_t) : 0));
23225 
23226 			ip6->ip6_plen = htons(tcp_hdr_len -
23227 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23228 		}
23229 
23230 		/*
23231 		 * Prime pump for checksum calculation in IP.  Include the
23232 		 * adjustment for a source route if any.
23233 		 */
23234 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23235 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23236 		U16_TO_ABE16(data_length, tcph->th_sum);
23237 
23238 		if (tcp->tcp_ip_forward_progress) {
23239 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23240 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23241 			tcp->tcp_ip_forward_progress = B_FALSE;
23242 		}
23243 		return (mp1);
23244 	}
23245 }
23246 
23247 /*
23248  * To create a temporary tcp structure for inserting into bind hash list.
23249  * The parameter is assumed to be in network byte order, ready for use.
23250  */
23251 /* ARGSUSED */
23252 static tcp_t *
23253 tcp_alloc_temp_tcp(in_port_t port)
23254 {
23255 	conn_t	*connp;
23256 	tcp_t	*tcp;
23257 
23258 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
23259 	if (connp == NULL)
23260 		return (NULL);
23261 
23262 	tcp = connp->conn_tcp;
23263 
23264 	/*
23265 	 * Only initialize the necessary info in those structures.  Note
23266 	 * that since INADDR_ANY is all 0, we do not need to set
23267 	 * tcp_bound_source to INADDR_ANY here.
23268 	 */
23269 	tcp->tcp_state = TCPS_BOUND;
23270 	tcp->tcp_lport = port;
23271 	tcp->tcp_exclbind = 1;
23272 	tcp->tcp_reserved_port = 1;
23273 
23274 	/* Just for place holding... */
23275 	tcp->tcp_ipversion = IPV4_VERSION;
23276 
23277 	return (tcp);
23278 }
23279 
23280 /*
23281  * To remove a port range specified by lo_port and hi_port from the
23282  * reserved port ranges.  This is one of the three public functions of
23283  * the reserved port interface.  Note that a port range has to be removed
23284  * as a whole.  Ports in a range cannot be removed individually.
23285  *
23286  * Params:
23287  *	in_port_t lo_port: the beginning port of the reserved port range to
23288  *		be deleted.
23289  *	in_port_t hi_port: the ending port of the reserved port range to
23290  *		be deleted.
23291  *
23292  * Return:
23293  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
23294  */
23295 boolean_t
23296 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
23297 {
23298 	int	i, j;
23299 	int	size;
23300 	tcp_t	**temp_tcp_array;
23301 	tcp_t	*tcp;
23302 
23303 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
23304 
23305 	/* First make sure that the port ranage is indeed reserved. */
23306 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
23307 		if (tcp_reserved_port[i].lo_port == lo_port) {
23308 			hi_port = tcp_reserved_port[i].hi_port;
23309 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
23310 			break;
23311 		}
23312 	}
23313 	if (i == tcp_reserved_port_array_size) {
23314 		rw_exit(&tcp_reserved_port_lock);
23315 		return (B_FALSE);
23316 	}
23317 
23318 	/*
23319 	 * Remove the range from the array.  This simple loop is possible
23320 	 * because port ranges are inserted in ascending order.
23321 	 */
23322 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
23323 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
23324 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
23325 		tcp_reserved_port[j].temp_tcp_array =
23326 		    tcp_reserved_port[j+1].temp_tcp_array;
23327 	}
23328 
23329 	/* Remove all the temporary tcp structures. */
23330 	size = hi_port - lo_port + 1;
23331 	while (size > 0) {
23332 		tcp = temp_tcp_array[size - 1];
23333 		ASSERT(tcp != NULL);
23334 		tcp_bind_hash_remove(tcp);
23335 		CONN_DEC_REF(tcp->tcp_connp);
23336 		size--;
23337 	}
23338 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
23339 	tcp_reserved_port_array_size--;
23340 	rw_exit(&tcp_reserved_port_lock);
23341 	return (B_TRUE);
23342 }
23343 
23344 /*
23345  * Macro to remove temporary tcp structure from the bind hash list.  The
23346  * first parameter is the list of tcp to be removed.  The second parameter
23347  * is the number of tcps in the array.
23348  */
23349 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
23350 { \
23351 	while ((num) > 0) { \
23352 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
23353 		tf_t *tbf; \
23354 		tcp_t *tcpnext; \
23355 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
23356 		mutex_enter(&tbf->tf_lock); \
23357 		tcpnext = tcp->tcp_bind_hash; \
23358 		if (tcpnext) { \
23359 			tcpnext->tcp_ptpbhn = \
23360 				tcp->tcp_ptpbhn; \
23361 		} \
23362 		*tcp->tcp_ptpbhn = tcpnext; \
23363 		mutex_exit(&tbf->tf_lock); \
23364 		kmem_free(tcp, sizeof (tcp_t)); \
23365 		(tcp_array)[(num) - 1] = NULL; \
23366 		(num)--; \
23367 	} \
23368 }
23369 
23370 /*
23371  * The public interface for other modules to call to reserve a port range
23372  * in TCP.  The caller passes in how large a port range it wants.  TCP
23373  * will try to find a range and return it via lo_port and hi_port.  This is
23374  * used by NCA's nca_conn_init.
23375  * NCA can only be used in the global zone so this only affects the global
23376  * zone's ports.
23377  *
23378  * Params:
23379  *	int size: the size of the port range to be reserved.
23380  *	in_port_t *lo_port (referenced): returns the beginning port of the
23381  *		reserved port range added.
23382  *	in_port_t *hi_port (referenced): returns the ending port of the
23383  *		reserved port range added.
23384  *
23385  * Return:
23386  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
23387  */
23388 boolean_t
23389 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
23390 {
23391 	tcp_t		*tcp;
23392 	tcp_t		*tmp_tcp;
23393 	tcp_t		**temp_tcp_array;
23394 	tf_t		*tbf;
23395 	in_port_t	net_port;
23396 	in_port_t	port;
23397 	int32_t		cur_size;
23398 	int		i, j;
23399 	boolean_t	used;
23400 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
23401 	zoneid_t	zoneid = GLOBAL_ZONEID;
23402 
23403 	/* Sanity check. */
23404 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
23405 		return (B_FALSE);
23406 	}
23407 
23408 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
23409 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
23410 		rw_exit(&tcp_reserved_port_lock);
23411 		return (B_FALSE);
23412 	}
23413 
23414 	/*
23415 	 * Find the starting port to try.  Since the port ranges are ordered
23416 	 * in the reserved port array, we can do a simple search here.
23417 	 */
23418 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
23419 	*hi_port = TCP_LARGEST_RESERVED_PORT;
23420 	for (i = 0; i < tcp_reserved_port_array_size;
23421 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
23422 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
23423 			*hi_port = tcp_reserved_port[i].lo_port - 1;
23424 			break;
23425 		}
23426 	}
23427 	/* No available port range. */
23428 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
23429 		rw_exit(&tcp_reserved_port_lock);
23430 		return (B_FALSE);
23431 	}
23432 
23433 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
23434 	if (temp_tcp_array == NULL) {
23435 		rw_exit(&tcp_reserved_port_lock);
23436 		return (B_FALSE);
23437 	}
23438 
23439 	/* Go thru the port range to see if some ports are already bound. */
23440 	for (port = *lo_port, cur_size = 0;
23441 	    cur_size < size && port <= *hi_port;
23442 	    cur_size++, port++) {
23443 		used = B_FALSE;
23444 		net_port = htons(port);
23445 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
23446 		mutex_enter(&tbf->tf_lock);
23447 		for (tcp = tbf->tf_tcp; tcp != NULL;
23448 		    tcp = tcp->tcp_bind_hash) {
23449 			if (IPCL_ZONE_MATCH(tcp->tcp_connp, zoneid) &&
23450 			    net_port == tcp->tcp_lport) {
23451 				/*
23452 				 * A port is already bound.  Search again
23453 				 * starting from port + 1.  Release all
23454 				 * temporary tcps.
23455 				 */
23456 				mutex_exit(&tbf->tf_lock);
23457 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
23458 				*lo_port = port + 1;
23459 				cur_size = -1;
23460 				used = B_TRUE;
23461 				break;
23462 			}
23463 		}
23464 		if (!used) {
23465 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
23466 				/*
23467 				 * Allocation failure.  Just fail the request.
23468 				 * Need to remove all those temporary tcp
23469 				 * structures.
23470 				 */
23471 				mutex_exit(&tbf->tf_lock);
23472 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
23473 				rw_exit(&tcp_reserved_port_lock);
23474 				kmem_free(temp_tcp_array,
23475 				    (hi_port - lo_port + 1) *
23476 				    sizeof (tcp_t *));
23477 				return (B_FALSE);
23478 			}
23479 			temp_tcp_array[cur_size] = tmp_tcp;
23480 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
23481 			mutex_exit(&tbf->tf_lock);
23482 		}
23483 	}
23484 
23485 	/*
23486 	 * The current range is not large enough.  We can actually do another
23487 	 * search if this search is done between 2 reserved port ranges.  But
23488 	 * for first release, we just stop here and return saying that no port
23489 	 * range is available.
23490 	 */
23491 	if (cur_size < size) {
23492 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
23493 		rw_exit(&tcp_reserved_port_lock);
23494 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
23495 		return (B_FALSE);
23496 	}
23497 	*hi_port = port - 1;
23498 
23499 	/*
23500 	 * Insert range into array in ascending order.  Since this function
23501 	 * must not be called often, we choose to use the simplest method.
23502 	 * The above array should not consume excessive stack space as
23503 	 * the size must be very small.  If in future releases, we find
23504 	 * that we should provide more reserved port ranges, this function
23505 	 * has to be modified to be more efficient.
23506 	 */
23507 	if (tcp_reserved_port_array_size == 0) {
23508 		tcp_reserved_port[0].lo_port = *lo_port;
23509 		tcp_reserved_port[0].hi_port = *hi_port;
23510 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
23511 	} else {
23512 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
23513 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
23514 				tmp_ports[j].lo_port = *lo_port;
23515 				tmp_ports[j].hi_port = *hi_port;
23516 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
23517 				j++;
23518 			}
23519 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
23520 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
23521 			tmp_ports[j].temp_tcp_array =
23522 			    tcp_reserved_port[i].temp_tcp_array;
23523 		}
23524 		if (j == i) {
23525 			tmp_ports[j].lo_port = *lo_port;
23526 			tmp_ports[j].hi_port = *hi_port;
23527 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
23528 		}
23529 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
23530 	}
23531 	tcp_reserved_port_array_size++;
23532 	rw_exit(&tcp_reserved_port_lock);
23533 	return (B_TRUE);
23534 }
23535 
23536 /*
23537  * Check to see if a port is in any reserved port range.
23538  *
23539  * Params:
23540  *	in_port_t port: the port to be verified.
23541  *
23542  * Return:
23543  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
23544  */
23545 boolean_t
23546 tcp_reserved_port_check(in_port_t port)
23547 {
23548 	int i;
23549 
23550 	rw_enter(&tcp_reserved_port_lock, RW_READER);
23551 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
23552 		if (port >= tcp_reserved_port[i].lo_port ||
23553 		    port <= tcp_reserved_port[i].hi_port) {
23554 			rw_exit(&tcp_reserved_port_lock);
23555 			return (B_TRUE);
23556 		}
23557 	}
23558 	rw_exit(&tcp_reserved_port_lock);
23559 	return (B_FALSE);
23560 }
23561 
23562 /*
23563  * To list all reserved port ranges.  This is the function to handle
23564  * ndd tcp_reserved_port_list.
23565  */
23566 /* ARGSUSED */
23567 static int
23568 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23569 {
23570 	int i;
23571 
23572 	rw_enter(&tcp_reserved_port_lock, RW_READER);
23573 	if (tcp_reserved_port_array_size > 0)
23574 		(void) mi_mpprintf(mp, "The following ports are reserved:");
23575 	else
23576 		(void) mi_mpprintf(mp, "No port is reserved.");
23577 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
23578 		(void) mi_mpprintf(mp, "%d-%d",
23579 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
23580 	}
23581 	rw_exit(&tcp_reserved_port_lock);
23582 	return (0);
23583 }
23584 
23585 /*
23586  * Hash list insertion routine for tcp_t structures.
23587  * Inserts entries with the ones bound to a specific IP address first
23588  * followed by those bound to INADDR_ANY.
23589  */
23590 static void
23591 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23592 {
23593 	tcp_t	**tcpp;
23594 	tcp_t	*tcpnext;
23595 
23596 	if (tcp->tcp_ptpbhn != NULL) {
23597 		ASSERT(!caller_holds_lock);
23598 		tcp_bind_hash_remove(tcp);
23599 	}
23600 	tcpp = &tbf->tf_tcp;
23601 	if (!caller_holds_lock) {
23602 		mutex_enter(&tbf->tf_lock);
23603 	} else {
23604 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23605 	}
23606 	tcpnext = tcpp[0];
23607 	if (tcpnext) {
23608 		/*
23609 		 * If the new tcp bound to the INADDR_ANY address
23610 		 * and the first one in the list is not bound to
23611 		 * INADDR_ANY we skip all entries until we find the
23612 		 * first one bound to INADDR_ANY.
23613 		 * This makes sure that applications binding to a
23614 		 * specific address get preference over those binding to
23615 		 * INADDR_ANY.
23616 		 */
23617 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23618 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23619 			while ((tcpnext = tcpp[0]) != NULL &&
23620 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23621 				tcpp = &(tcpnext->tcp_bind_hash);
23622 			if (tcpnext)
23623 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23624 		} else
23625 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23626 	}
23627 	tcp->tcp_bind_hash = tcpnext;
23628 	tcp->tcp_ptpbhn = tcpp;
23629 	tcpp[0] = tcp;
23630 	if (!caller_holds_lock)
23631 		mutex_exit(&tbf->tf_lock);
23632 }
23633 
23634 /*
23635  * Hash list removal routine for tcp_t structures.
23636  */
23637 static void
23638 tcp_bind_hash_remove(tcp_t *tcp)
23639 {
23640 	tcp_t	*tcpnext;
23641 	kmutex_t *lockp;
23642 
23643 	if (tcp->tcp_ptpbhn == NULL)
23644 		return;
23645 
23646 	/*
23647 	 * Extract the lock pointer in case there are concurrent
23648 	 * hash_remove's for this instance.
23649 	 */
23650 	ASSERT(tcp->tcp_lport != 0);
23651 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23652 
23653 	ASSERT(lockp != NULL);
23654 	mutex_enter(lockp);
23655 	if (tcp->tcp_ptpbhn) {
23656 		tcpnext = tcp->tcp_bind_hash;
23657 		if (tcpnext) {
23658 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23659 			tcp->tcp_bind_hash = NULL;
23660 		}
23661 		*tcp->tcp_ptpbhn = tcpnext;
23662 		tcp->tcp_ptpbhn = NULL;
23663 	}
23664 	mutex_exit(lockp);
23665 }
23666 
23667 
23668 /*
23669  * Hash list lookup routine for tcp_t structures.
23670  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23671  */
23672 static tcp_t *
23673 tcp_acceptor_hash_lookup(t_uscalar_t id)
23674 {
23675 	tf_t	*tf;
23676 	tcp_t	*tcp;
23677 
23678 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23679 	mutex_enter(&tf->tf_lock);
23680 	for (tcp = tf->tf_tcp; tcp != NULL;
23681 	    tcp = tcp->tcp_acceptor_hash) {
23682 		if (tcp->tcp_acceptor_id == id) {
23683 			CONN_INC_REF(tcp->tcp_connp);
23684 			mutex_exit(&tf->tf_lock);
23685 			return (tcp);
23686 		}
23687 	}
23688 	mutex_exit(&tf->tf_lock);
23689 	return (NULL);
23690 }
23691 
23692 
23693 /*
23694  * Hash list insertion routine for tcp_t structures.
23695  */
23696 void
23697 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23698 {
23699 	tf_t	*tf;
23700 	tcp_t	**tcpp;
23701 	tcp_t	*tcpnext;
23702 
23703 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23704 
23705 	if (tcp->tcp_ptpahn != NULL)
23706 		tcp_acceptor_hash_remove(tcp);
23707 	tcpp = &tf->tf_tcp;
23708 	mutex_enter(&tf->tf_lock);
23709 	tcpnext = tcpp[0];
23710 	if (tcpnext)
23711 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23712 	tcp->tcp_acceptor_hash = tcpnext;
23713 	tcp->tcp_ptpahn = tcpp;
23714 	tcpp[0] = tcp;
23715 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23716 	mutex_exit(&tf->tf_lock);
23717 }
23718 
23719 /*
23720  * Hash list removal routine for tcp_t structures.
23721  */
23722 static void
23723 tcp_acceptor_hash_remove(tcp_t *tcp)
23724 {
23725 	tcp_t	*tcpnext;
23726 	kmutex_t *lockp;
23727 
23728 	/*
23729 	 * Extract the lock pointer in case there are concurrent
23730 	 * hash_remove's for this instance.
23731 	 */
23732 	lockp = tcp->tcp_acceptor_lockp;
23733 
23734 	if (tcp->tcp_ptpahn == NULL)
23735 		return;
23736 
23737 	ASSERT(lockp != NULL);
23738 	mutex_enter(lockp);
23739 	if (tcp->tcp_ptpahn) {
23740 		tcpnext = tcp->tcp_acceptor_hash;
23741 		if (tcpnext) {
23742 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23743 			tcp->tcp_acceptor_hash = NULL;
23744 		}
23745 		*tcp->tcp_ptpahn = tcpnext;
23746 		tcp->tcp_ptpahn = NULL;
23747 	}
23748 	mutex_exit(lockp);
23749 	tcp->tcp_acceptor_lockp = NULL;
23750 }
23751 
23752 /* ARGSUSED */
23753 static int
23754 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
23755 {
23756 	int error = 0;
23757 	int retval;
23758 	char *end;
23759 
23760 	tcp_hsp_t *hsp;
23761 	tcp_hsp_t *hspprev;
23762 
23763 	ipaddr_t addr = 0;		/* Address we're looking for */
23764 	in6_addr_t v6addr;		/* Address we're looking for */
23765 	uint32_t hash;			/* Hash of that address */
23766 
23767 	/*
23768 	 * If the following variables are still zero after parsing the input
23769 	 * string, the user didn't specify them and we don't change them in
23770 	 * the HSP.
23771 	 */
23772 
23773 	ipaddr_t mask = 0;		/* Subnet mask */
23774 	in6_addr_t v6mask;
23775 	long sendspace = 0;		/* Send buffer size */
23776 	long recvspace = 0;		/* Receive buffer size */
23777 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
23778 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
23779 
23780 	rw_enter(&tcp_hsp_lock, RW_WRITER);
23781 
23782 	/* Parse and validate address */
23783 	if (af == AF_INET) {
23784 		retval = inet_pton(af, value, &addr);
23785 		if (retval == 1)
23786 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
23787 	} else if (af == AF_INET6) {
23788 		retval = inet_pton(af, value, &v6addr);
23789 	} else {
23790 		error = EINVAL;
23791 		goto done;
23792 	}
23793 	if (retval == 0) {
23794 		error = EINVAL;
23795 		goto done;
23796 	}
23797 
23798 	while ((*value) && *value != ' ')
23799 		value++;
23800 
23801 	/* Parse individual keywords, set variables if found */
23802 	while (*value) {
23803 		/* Skip leading blanks */
23804 
23805 		while (*value == ' ' || *value == '\t')
23806 			value++;
23807 
23808 		/* If at end of string, we're done */
23809 
23810 		if (!*value)
23811 			break;
23812 
23813 		/* We have a word, figure out what it is */
23814 
23815 		if (strncmp("mask", value, 4) == 0) {
23816 			value += 4;
23817 			while (*value == ' ' || *value == '\t')
23818 				value++;
23819 			/* Parse subnet mask */
23820 			if (af == AF_INET) {
23821 				retval = inet_pton(af, value, &mask);
23822 				if (retval == 1) {
23823 					V4MASK_TO_V6(mask, v6mask);
23824 				}
23825 			} else if (af == AF_INET6) {
23826 				retval = inet_pton(af, value, &v6mask);
23827 			}
23828 			if (retval != 1) {
23829 				error = EINVAL;
23830 				goto done;
23831 			}
23832 			while ((*value) && *value != ' ')
23833 				value++;
23834 		} else if (strncmp("sendspace", value, 9) == 0) {
23835 			value += 9;
23836 
23837 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
23838 			    sendspace < TCP_XMIT_HIWATER ||
23839 			    sendspace >= (1L<<30)) {
23840 				error = EINVAL;
23841 				goto done;
23842 			}
23843 			value = end;
23844 		} else if (strncmp("recvspace", value, 9) == 0) {
23845 			value += 9;
23846 
23847 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
23848 			    recvspace < TCP_RECV_HIWATER ||
23849 			    recvspace >= (1L<<30)) {
23850 				error = EINVAL;
23851 				goto done;
23852 			}
23853 			value = end;
23854 		} else if (strncmp("timestamp", value, 9) == 0) {
23855 			value += 9;
23856 
23857 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
23858 			    timestamp < 0 || timestamp > 1) {
23859 				error = EINVAL;
23860 				goto done;
23861 			}
23862 
23863 			/*
23864 			 * We increment timestamp so we know it's been set;
23865 			 * this is undone when we put it in the HSP
23866 			 */
23867 			timestamp++;
23868 			value = end;
23869 		} else if (strncmp("delete", value, 6) == 0) {
23870 			value += 6;
23871 			delete = B_TRUE;
23872 		} else {
23873 			error = EINVAL;
23874 			goto done;
23875 		}
23876 	}
23877 
23878 	/* Hash address for lookup */
23879 
23880 	hash = TCP_HSP_HASH(addr);
23881 
23882 	if (delete) {
23883 		/*
23884 		 * Note that deletes don't return an error if the thing
23885 		 * we're trying to delete isn't there.
23886 		 */
23887 		if (tcp_hsp_hash == NULL)
23888 			goto done;
23889 		hsp = tcp_hsp_hash[hash];
23890 
23891 		if (hsp) {
23892 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23893 			    &v6addr)) {
23894 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
23895 				mi_free((char *)hsp);
23896 			} else {
23897 				hspprev = hsp;
23898 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
23899 					if (IN6_ARE_ADDR_EQUAL(
23900 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
23901 						hspprev->tcp_hsp_next =
23902 						    hsp->tcp_hsp_next;
23903 						mi_free((char *)hsp);
23904 						break;
23905 					}
23906 					hspprev = hsp;
23907 				}
23908 			}
23909 		}
23910 	} else {
23911 		/*
23912 		 * We're adding/modifying an HSP.  If we haven't already done
23913 		 * so, allocate the hash table.
23914 		 */
23915 
23916 		if (!tcp_hsp_hash) {
23917 			tcp_hsp_hash = (tcp_hsp_t **)
23918 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
23919 			if (!tcp_hsp_hash) {
23920 				error = EINVAL;
23921 				goto done;
23922 			}
23923 		}
23924 
23925 		/* Get head of hash chain */
23926 
23927 		hsp = tcp_hsp_hash[hash];
23928 
23929 		/* Try to find pre-existing hsp on hash chain */
23930 		/* Doesn't handle CIDR prefixes. */
23931 		while (hsp) {
23932 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
23933 				break;
23934 			hsp = hsp->tcp_hsp_next;
23935 		}
23936 
23937 		/*
23938 		 * If we didn't, create one with default values and put it
23939 		 * at head of hash chain
23940 		 */
23941 
23942 		if (!hsp) {
23943 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
23944 			if (!hsp) {
23945 				error = EINVAL;
23946 				goto done;
23947 			}
23948 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
23949 			tcp_hsp_hash[hash] = hsp;
23950 		}
23951 
23952 		/* Set values that the user asked us to change */
23953 
23954 		hsp->tcp_hsp_addr_v6 = v6addr;
23955 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
23956 			hsp->tcp_hsp_vers = IPV4_VERSION;
23957 		else
23958 			hsp->tcp_hsp_vers = IPV6_VERSION;
23959 		hsp->tcp_hsp_subnet_v6 = v6mask;
23960 		if (sendspace > 0)
23961 			hsp->tcp_hsp_sendspace = sendspace;
23962 		if (recvspace > 0)
23963 			hsp->tcp_hsp_recvspace = recvspace;
23964 		if (timestamp > 0)
23965 			hsp->tcp_hsp_tstamp = timestamp - 1;
23966 	}
23967 
23968 done:
23969 	rw_exit(&tcp_hsp_lock);
23970 	return (error);
23971 }
23972 
23973 /* Set callback routine passed to nd_load by tcp_param_register. */
23974 /* ARGSUSED */
23975 static int
23976 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
23977 {
23978 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
23979 }
23980 /* ARGSUSED */
23981 static int
23982 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23983     cred_t *cr)
23984 {
23985 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
23986 }
23987 
23988 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
23989 /* ARGSUSED */
23990 static int
23991 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23992 {
23993 	tcp_hsp_t *hsp;
23994 	int i;
23995 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
23996 
23997 	rw_enter(&tcp_hsp_lock, RW_READER);
23998 	(void) mi_mpprintf(mp,
23999 	    "Hash HSP     " MI_COL_HDRPAD_STR
24000 	    "Address         Subnet Mask     Send       Receive    TStamp");
24001 	if (tcp_hsp_hash) {
24002 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
24003 			hsp = tcp_hsp_hash[i];
24004 			while (hsp) {
24005 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
24006 					(void) inet_ntop(AF_INET,
24007 					    &hsp->tcp_hsp_addr,
24008 					    addrbuf, sizeof (addrbuf));
24009 					(void) inet_ntop(AF_INET,
24010 					    &hsp->tcp_hsp_subnet,
24011 					    subnetbuf, sizeof (subnetbuf));
24012 				} else {
24013 					(void) inet_ntop(AF_INET6,
24014 					    &hsp->tcp_hsp_addr_v6,
24015 					    addrbuf, sizeof (addrbuf));
24016 					(void) inet_ntop(AF_INET6,
24017 					    &hsp->tcp_hsp_subnet_v6,
24018 					    subnetbuf, sizeof (subnetbuf));
24019 				}
24020 				(void) mi_mpprintf(mp,
24021 				    " %03d " MI_COL_PTRFMT_STR
24022 				    "%s %s %010d %010d      %d",
24023 				    i,
24024 				    (void *)hsp,
24025 				    addrbuf,
24026 				    subnetbuf,
24027 				    hsp->tcp_hsp_sendspace,
24028 				    hsp->tcp_hsp_recvspace,
24029 				    hsp->tcp_hsp_tstamp);
24030 
24031 				hsp = hsp->tcp_hsp_next;
24032 			}
24033 		}
24034 	}
24035 	rw_exit(&tcp_hsp_lock);
24036 	return (0);
24037 }
24038 
24039 
24040 /* Data for fast netmask macro used by tcp_hsp_lookup */
24041 
24042 static ipaddr_t netmasks[] = {
24043 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24044 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24045 };
24046 
24047 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24048 
24049 /*
24050  * XXX This routine should go away and instead we should use the metrics
24051  * associated with the routes to determine the default sndspace and rcvspace.
24052  */
24053 static tcp_hsp_t *
24054 tcp_hsp_lookup(ipaddr_t addr)
24055 {
24056 	tcp_hsp_t *hsp = NULL;
24057 
24058 	/* Quick check without acquiring the lock. */
24059 	if (tcp_hsp_hash == NULL)
24060 		return (NULL);
24061 
24062 	rw_enter(&tcp_hsp_lock, RW_READER);
24063 
24064 	/* This routine finds the best-matching HSP for address addr. */
24065 
24066 	if (tcp_hsp_hash) {
24067 		int i;
24068 		ipaddr_t srchaddr;
24069 		tcp_hsp_t *hsp_net;
24070 
24071 		/* We do three passes: host, network, and subnet. */
24072 
24073 		srchaddr = addr;
24074 
24075 		for (i = 1; i <= 3; i++) {
24076 			/* Look for exact match on srchaddr */
24077 
24078 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
24079 			while (hsp) {
24080 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24081 				    hsp->tcp_hsp_addr == srchaddr)
24082 					break;
24083 				hsp = hsp->tcp_hsp_next;
24084 			}
24085 			ASSERT(hsp == NULL ||
24086 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24087 
24088 			/*
24089 			 * If this is the first pass:
24090 			 *   If we found a match, great, return it.
24091 			 *   If not, search for the network on the second pass.
24092 			 */
24093 
24094 			if (i == 1)
24095 				if (hsp)
24096 					break;
24097 				else
24098 				{
24099 					srchaddr = addr & netmask(addr);
24100 					continue;
24101 				}
24102 
24103 			/*
24104 			 * If this is the second pass:
24105 			 *   If we found a match, but there's a subnet mask,
24106 			 *    save the match but try again using the subnet
24107 			 *    mask on the third pass.
24108 			 *   Otherwise, return whatever we found.
24109 			 */
24110 
24111 			if (i == 2) {
24112 				if (hsp && hsp->tcp_hsp_subnet) {
24113 					hsp_net = hsp;
24114 					srchaddr = addr & hsp->tcp_hsp_subnet;
24115 					continue;
24116 				} else {
24117 					break;
24118 				}
24119 			}
24120 
24121 			/*
24122 			 * This must be the third pass.  If we didn't find
24123 			 * anything, return the saved network HSP instead.
24124 			 */
24125 
24126 			if (!hsp)
24127 				hsp = hsp_net;
24128 		}
24129 	}
24130 
24131 	rw_exit(&tcp_hsp_lock);
24132 	return (hsp);
24133 }
24134 
24135 /*
24136  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24137  * match lookup.
24138  */
24139 static tcp_hsp_t *
24140 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
24141 {
24142 	tcp_hsp_t *hsp = NULL;
24143 
24144 	/* Quick check without acquiring the lock. */
24145 	if (tcp_hsp_hash == NULL)
24146 		return (NULL);
24147 
24148 	rw_enter(&tcp_hsp_lock, RW_READER);
24149 
24150 	/* This routine finds the best-matching HSP for address addr. */
24151 
24152 	if (tcp_hsp_hash) {
24153 		int i;
24154 		in6_addr_t v6srchaddr;
24155 		tcp_hsp_t *hsp_net;
24156 
24157 		/* We do three passes: host, network, and subnet. */
24158 
24159 		v6srchaddr = *v6addr;
24160 
24161 		for (i = 1; i <= 3; i++) {
24162 			/* Look for exact match on srchaddr */
24163 
24164 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
24165 			    V4_PART_OF_V6(v6srchaddr))];
24166 			while (hsp) {
24167 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24168 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24169 				    &v6srchaddr))
24170 					break;
24171 				hsp = hsp->tcp_hsp_next;
24172 			}
24173 
24174 			/*
24175 			 * If this is the first pass:
24176 			 *   If we found a match, great, return it.
24177 			 *   If not, search for the network on the second pass.
24178 			 */
24179 
24180 			if (i == 1)
24181 				if (hsp)
24182 					break;
24183 				else {
24184 					/* Assume a 64 bit mask */
24185 					v6srchaddr.s6_addr32[0] =
24186 					    v6addr->s6_addr32[0];
24187 					v6srchaddr.s6_addr32[1] =
24188 					    v6addr->s6_addr32[1];
24189 					v6srchaddr.s6_addr32[2] = 0;
24190 					v6srchaddr.s6_addr32[3] = 0;
24191 					continue;
24192 				}
24193 
24194 			/*
24195 			 * If this is the second pass:
24196 			 *   If we found a match, but there's a subnet mask,
24197 			 *    save the match but try again using the subnet
24198 			 *    mask on the third pass.
24199 			 *   Otherwise, return whatever we found.
24200 			 */
24201 
24202 			if (i == 2) {
24203 				ASSERT(hsp == NULL ||
24204 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24205 				if (hsp &&
24206 				    !IN6_IS_ADDR_UNSPECIFIED(
24207 				    &hsp->tcp_hsp_subnet_v6)) {
24208 					hsp_net = hsp;
24209 					V6_MASK_COPY(*v6addr,
24210 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24211 					continue;
24212 				} else {
24213 					break;
24214 				}
24215 			}
24216 
24217 			/*
24218 			 * This must be the third pass.  If we didn't find
24219 			 * anything, return the saved network HSP instead.
24220 			 */
24221 
24222 			if (!hsp)
24223 				hsp = hsp_net;
24224 		}
24225 	}
24226 
24227 	rw_exit(&tcp_hsp_lock);
24228 	return (hsp);
24229 }
24230 
24231 /*
24232  * Type three generator adapted from the random() function in 4.4 BSD:
24233  */
24234 
24235 /*
24236  * Copyright (c) 1983, 1993
24237  *	The Regents of the University of California.  All rights reserved.
24238  *
24239  * Redistribution and use in source and binary forms, with or without
24240  * modification, are permitted provided that the following conditions
24241  * are met:
24242  * 1. Redistributions of source code must retain the above copyright
24243  *    notice, this list of conditions and the following disclaimer.
24244  * 2. Redistributions in binary form must reproduce the above copyright
24245  *    notice, this list of conditions and the following disclaimer in the
24246  *    documentation and/or other materials provided with the distribution.
24247  * 3. All advertising materials mentioning features or use of this software
24248  *    must display the following acknowledgement:
24249  *	This product includes software developed by the University of
24250  *	California, Berkeley and its contributors.
24251  * 4. Neither the name of the University nor the names of its contributors
24252  *    may be used to endorse or promote products derived from this software
24253  *    without specific prior written permission.
24254  *
24255  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24256  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24257  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24258  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24259  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24260  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24261  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24262  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24263  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24264  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24265  * SUCH DAMAGE.
24266  */
24267 
24268 /* Type 3 -- x**31 + x**3 + 1 */
24269 #define	DEG_3		31
24270 #define	SEP_3		3
24271 
24272 
24273 /* Protected by tcp_random_lock */
24274 static int tcp_randtbl[DEG_3 + 1];
24275 
24276 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24277 static int *tcp_random_rptr = &tcp_randtbl[1];
24278 
24279 static int *tcp_random_state = &tcp_randtbl[1];
24280 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24281 
24282 kmutex_t tcp_random_lock;
24283 
24284 void
24285 tcp_random_init(void)
24286 {
24287 	int i;
24288 	hrtime_t hrt;
24289 	time_t wallclock;
24290 	uint64_t result;
24291 
24292 	/*
24293 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24294 	 * a longlong, which may contain resolution down to nanoseconds.
24295 	 * The current time will either be a 32-bit or a 64-bit quantity.
24296 	 * XOR the two together in a 64-bit result variable.
24297 	 * Convert the result to a 32-bit value by multiplying the high-order
24298 	 * 32-bits by the low-order 32-bits.
24299 	 */
24300 
24301 	hrt = gethrtime();
24302 	(void) drv_getparm(TIME, &wallclock);
24303 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24304 	mutex_enter(&tcp_random_lock);
24305 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24306 	    (result & 0xffffffff);
24307 
24308 	for (i = 1; i < DEG_3; i++)
24309 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24310 			+ 12345;
24311 	tcp_random_fptr = &tcp_random_state[SEP_3];
24312 	tcp_random_rptr = &tcp_random_state[0];
24313 	mutex_exit(&tcp_random_lock);
24314 	for (i = 0; i < 10 * DEG_3; i++)
24315 		(void) tcp_random();
24316 }
24317 
24318 /*
24319  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24320  * This range is selected to be approximately centered on TCP_ISS / 2,
24321  * and easy to compute. We get this value by generating a 32-bit random
24322  * number, selecting out the high-order 17 bits, and then adding one so
24323  * that we never return zero.
24324  */
24325 int
24326 tcp_random(void)
24327 {
24328 	int i;
24329 
24330 	mutex_enter(&tcp_random_lock);
24331 	*tcp_random_fptr += *tcp_random_rptr;
24332 
24333 	/*
24334 	 * The high-order bits are more random than the low-order bits,
24335 	 * so we select out the high-order 17 bits and add one so that
24336 	 * we never return zero.
24337 	 */
24338 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24339 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24340 		tcp_random_fptr = tcp_random_state;
24341 		++tcp_random_rptr;
24342 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24343 		tcp_random_rptr = tcp_random_state;
24344 
24345 	mutex_exit(&tcp_random_lock);
24346 	return (i);
24347 }
24348 
24349 /*
24350  * XXX This will go away when TPI is extended to send
24351  * info reqs to sockfs/timod .....
24352  * Given a queue, set the max packet size for the write
24353  * side of the queue below stream head.  This value is
24354  * cached on the stream head.
24355  * Returns 1 on success, 0 otherwise.
24356  */
24357 static int
24358 setmaxps(queue_t *q, int maxpsz)
24359 {
24360 	struct stdata	*stp;
24361 	queue_t		*wq;
24362 	stp = STREAM(q);
24363 
24364 	/*
24365 	 * At this point change of a queue parameter is not allowed
24366 	 * when a multiplexor is sitting on top.
24367 	 */
24368 	if (stp->sd_flag & STPLEX)
24369 		return (0);
24370 
24371 	claimstr(stp->sd_wrq);
24372 	wq = stp->sd_wrq->q_next;
24373 	ASSERT(wq != NULL);
24374 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
24375 	releasestr(stp->sd_wrq);
24376 	return (1);
24377 }
24378 
24379 static int
24380 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24381     int *t_errorp, int *sys_errorp)
24382 {
24383 	int error;
24384 	int is_absreq_failure;
24385 	t_scalar_t *opt_lenp;
24386 	t_scalar_t opt_offset;
24387 	int prim_type;
24388 	struct T_conn_req *tcreqp;
24389 	struct T_conn_res *tcresp;
24390 	cred_t *cr;
24391 
24392 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24393 
24394 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24395 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24396 	    prim_type == T_CONN_RES);
24397 
24398 	switch (prim_type) {
24399 	case T_CONN_REQ:
24400 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24401 		opt_offset = tcreqp->OPT_offset;
24402 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24403 		break;
24404 	case O_T_CONN_RES:
24405 	case T_CONN_RES:
24406 		tcresp = (struct T_conn_res *)mp->b_rptr;
24407 		opt_offset = tcresp->OPT_offset;
24408 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24409 		break;
24410 	}
24411 
24412 	*t_errorp = 0;
24413 	*sys_errorp = 0;
24414 	*do_disconnectp = 0;
24415 
24416 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24417 	    opt_offset, cr, &tcp_opt_obj,
24418 	    NULL, &is_absreq_failure);
24419 
24420 	switch (error) {
24421 	case  0:		/* no error */
24422 		ASSERT(is_absreq_failure == 0);
24423 		return (0);
24424 	case ENOPROTOOPT:
24425 		*t_errorp = TBADOPT;
24426 		break;
24427 	case EACCES:
24428 		*t_errorp = TACCES;
24429 		break;
24430 	default:
24431 		*t_errorp = TSYSERR; *sys_errorp = error;
24432 		break;
24433 	}
24434 	if (is_absreq_failure != 0) {
24435 		/*
24436 		 * The connection request should get the local ack
24437 		 * T_OK_ACK and then a T_DISCON_IND.
24438 		 */
24439 		*do_disconnectp = 1;
24440 	}
24441 	return (-1);
24442 }
24443 
24444 /*
24445  * Split this function out so that if the secret changes, I'm okay.
24446  *
24447  * Initialize the tcp_iss_cookie and tcp_iss_key.
24448  */
24449 
24450 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24451 
24452 static void
24453 tcp_iss_key_init(uint8_t *phrase, int len)
24454 {
24455 	struct {
24456 		int32_t current_time;
24457 		uint32_t randnum;
24458 		uint16_t pad;
24459 		uint8_t ether[6];
24460 		uint8_t passwd[PASSWD_SIZE];
24461 	} tcp_iss_cookie;
24462 	time_t t;
24463 
24464 	/*
24465 	 * Start with the current absolute time.
24466 	 */
24467 	(void) drv_getparm(TIME, &t);
24468 	tcp_iss_cookie.current_time = t;
24469 
24470 	/*
24471 	 * XXX - Need a more random number per RFC 1750, not this crap.
24472 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24473 	 */
24474 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24475 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24476 
24477 	/*
24478 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24479 	 * as a good template.
24480 	 */
24481 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24482 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24483 
24484 	/*
24485 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24486 	 */
24487 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24488 
24489 	/*
24490 	 * See 4010593 if this section becomes a problem again,
24491 	 * but the local ethernet address is useful here.
24492 	 */
24493 	(void) localetheraddr(NULL,
24494 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24495 
24496 	/*
24497 	 * Hash 'em all together.  The MD5Final is called per-connection.
24498 	 */
24499 	mutex_enter(&tcp_iss_key_lock);
24500 	MD5Init(&tcp_iss_key);
24501 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
24502 	    sizeof (tcp_iss_cookie));
24503 	mutex_exit(&tcp_iss_key_lock);
24504 }
24505 
24506 /*
24507  * Set the RFC 1948 pass phrase
24508  */
24509 /* ARGSUSED */
24510 static int
24511 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24512     cred_t *cr)
24513 {
24514 	/*
24515 	 * Basically, value contains a new pass phrase.  Pass it along!
24516 	 */
24517 	tcp_iss_key_init((uint8_t *)value, strlen(value));
24518 	return (0);
24519 }
24520 
24521 /* ARGSUSED */
24522 static int
24523 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24524 {
24525 	bzero(buf, sizeof (tcp_sack_info_t));
24526 	return (0);
24527 }
24528 
24529 /* ARGSUSED */
24530 static int
24531 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24532 {
24533 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24534 	return (0);
24535 }
24536 
24537 void
24538 tcp_ddi_init(void)
24539 {
24540 	int i;
24541 
24542 	/* Initialize locks */
24543 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
24544 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24545 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24546 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24547 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24548 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
24549 
24550 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
24551 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
24552 		    MUTEX_DEFAULT, NULL);
24553 	}
24554 
24555 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
24556 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
24557 		    MUTEX_DEFAULT, NULL);
24558 	}
24559 
24560 	/* TCP's IPsec code calls the packet dropper. */
24561 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
24562 
24563 	if (!tcp_g_nd) {
24564 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
24565 			nd_free(&tcp_g_nd);
24566 		}
24567 	}
24568 
24569 	/*
24570 	 * Note: To really walk the device tree you need the devinfo
24571 	 * pointer to your device which is only available after probe/attach.
24572 	 * The following is safe only because it uses ddi_root_node()
24573 	 */
24574 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24575 	    tcp_opt_obj.odb_opt_arr_cnt);
24576 
24577 	tcp_timercache = kmem_cache_create("tcp_timercache",
24578 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24579 	    NULL, NULL, NULL, NULL, NULL, 0);
24580 
24581 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24582 	    sizeof (tcp_sack_info_t), 0,
24583 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24584 
24585 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24586 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24587 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24588 
24589 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
24590 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
24591 
24592 	ip_squeue_init(tcp_squeue_add);
24593 
24594 	/* Initialize the random number generator */
24595 	tcp_random_init();
24596 
24597 	/*
24598 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24599 	 * by the boot scripts.
24600 	 *
24601 	 * Use NULL name, as the name is caught by the new lockstats.
24602 	 *
24603 	 * Initialize with some random, non-guessable string, like the global
24604 	 * T_INFO_ACK.
24605 	 */
24606 
24607 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24608 	    sizeof (tcp_g_t_info_ack));
24609 
24610 	if ((tcp_kstat = kstat_create(TCP_MOD_NAME, 0, "tcpstat",
24611 		"net", KSTAT_TYPE_NAMED,
24612 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
24613 		KSTAT_FLAG_VIRTUAL)) != NULL) {
24614 		tcp_kstat->ks_data = &tcp_statistics;
24615 		kstat_install(tcp_kstat);
24616 	}
24617 
24618 	tcp_kstat_init();
24619 }
24620 
24621 void
24622 tcp_ddi_destroy(void)
24623 {
24624 	int i;
24625 
24626 	nd_free(&tcp_g_nd);
24627 
24628 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
24629 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
24630 	}
24631 
24632 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
24633 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
24634 	}
24635 
24636 	mutex_destroy(&tcp_iss_key_lock);
24637 	rw_destroy(&tcp_hsp_lock);
24638 	mutex_destroy(&tcp_g_q_lock);
24639 	mutex_destroy(&tcp_random_lock);
24640 	mutex_destroy(&tcp_epriv_port_lock);
24641 	rw_destroy(&tcp_reserved_port_lock);
24642 
24643 	ip_drop_unregister(&tcp_dropper);
24644 
24645 	kmem_cache_destroy(tcp_timercache);
24646 	kmem_cache_destroy(tcp_sack_info_cache);
24647 	kmem_cache_destroy(tcp_iphc_cache);
24648 
24649 	tcp_kstat_fini();
24650 }
24651 
24652 /*
24653  * Generate ISS, taking into account NDD changes may happen halfway through.
24654  * (If the iss is not zero, set it.)
24655  */
24656 
24657 static void
24658 tcp_iss_init(tcp_t *tcp)
24659 {
24660 	MD5_CTX context;
24661 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24662 	uint32_t answer[4];
24663 
24664 	tcp_iss_incr_extra += (ISS_INCR >> 1);
24665 	tcp->tcp_iss = tcp_iss_incr_extra;
24666 	switch (tcp_strong_iss) {
24667 	case 2:
24668 		mutex_enter(&tcp_iss_key_lock);
24669 		context = tcp_iss_key;
24670 		mutex_exit(&tcp_iss_key_lock);
24671 		arg.ports = tcp->tcp_ports;
24672 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24673 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24674 			    &arg.src);
24675 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24676 			    &arg.dst);
24677 		} else {
24678 			arg.src = tcp->tcp_ip6h->ip6_src;
24679 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24680 		}
24681 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24682 		MD5Final((uchar_t *)answer, &context);
24683 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24684 		/*
24685 		 * Now that we've hashed into a unique per-connection sequence
24686 		 * space, add a random increment per strong_iss == 1.  So I
24687 		 * guess we'll have to...
24688 		 */
24689 		/* FALLTHRU */
24690 	case 1:
24691 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24692 		break;
24693 	default:
24694 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24695 		break;
24696 	}
24697 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24698 	tcp->tcp_fss = tcp->tcp_iss - 1;
24699 	tcp->tcp_suna = tcp->tcp_iss;
24700 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24701 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24702 	tcp->tcp_csuna = tcp->tcp_snxt;
24703 }
24704 
24705 /*
24706  * Exported routine for extracting active tcp connection status.
24707  *
24708  * This is used by the Solaris Cluster Networking software to
24709  * gather a list of connections that need to be forwarded to
24710  * specific nodes in the cluster when configuration changes occur.
24711  *
24712  * The callback is invoked for each tcp_t structure. Returning
24713  * non-zero from the callback routine terminates the search.
24714  */
24715 int
24716 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
24717 {
24718 	tcp_t *tcp;
24719 	cl_tcp_info_t	cl_tcpi;
24720 	connf_t	*connfp;
24721 	conn_t	*connp;
24722 	int	i;
24723 
24724 	ASSERT(callback != NULL);
24725 
24726 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24727 
24728 		connfp = &ipcl_globalhash_fanout[i];
24729 		connp = NULL;
24730 
24731 		while ((connp =
24732 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24733 
24734 			tcp = connp->conn_tcp;
24735 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24736 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24737 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24738 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24739 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24740 			/*
24741 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24742 			 * addresses. They are copied implicitly below as
24743 			 * mapped addresses.
24744 			 */
24745 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24746 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24747 				cl_tcpi.cl_tcpi_faddr =
24748 				    tcp->tcp_ipha->ipha_dst;
24749 			} else {
24750 				cl_tcpi.cl_tcpi_faddr_v6 =
24751 				    tcp->tcp_ip6h->ip6_dst;
24752 			}
24753 
24754 			/*
24755 			 * If the callback returns non-zero
24756 			 * we terminate the traversal.
24757 			 */
24758 			if ((*callback)(&cl_tcpi, arg) != 0) {
24759 				CONN_DEC_REF(tcp->tcp_connp);
24760 				return (1);
24761 			}
24762 		}
24763 	}
24764 
24765 	return (0);
24766 }
24767 
24768 /*
24769  * Macros used for accessing the different types of sockaddr
24770  * structures inside a tcp_ioc_abort_conn_t.
24771  */
24772 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24773 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24774 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24775 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24776 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24777 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24778 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24779 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24780 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24781 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24782 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24783 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24784 
24785 /*
24786  * Return the correct error code to mimic the behavior
24787  * of a connection reset.
24788  */
24789 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24790 		switch ((state)) {		\
24791 		case TCPS_SYN_SENT:		\
24792 		case TCPS_SYN_RCVD:		\
24793 			(err) = ECONNREFUSED;	\
24794 			break;			\
24795 		case TCPS_ESTABLISHED:		\
24796 		case TCPS_FIN_WAIT_1:		\
24797 		case TCPS_FIN_WAIT_2:		\
24798 		case TCPS_CLOSE_WAIT:		\
24799 			(err) = ECONNRESET;	\
24800 			break;			\
24801 		case TCPS_CLOSING:		\
24802 		case TCPS_LAST_ACK:		\
24803 		case TCPS_TIME_WAIT:		\
24804 			(err) = 0;		\
24805 			break;			\
24806 		default:			\
24807 			(err) = ENXIO;		\
24808 		}				\
24809 	}
24810 
24811 /*
24812  * Check if a tcp structure matches the info in acp.
24813  */
24814 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24815 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24816 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24817 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24818 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24819 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24820 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24821 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24822 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24823 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24824 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24825 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24826 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24827 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24828 	&(tcp)->tcp_ip_src_v6)) &&				\
24829 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24830 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24831 	&(tcp)->tcp_remote_v6)) &&				\
24832 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24833 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24834 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24835 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24836 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24837 	(acp)->ac_end >= (tcp)->tcp_state))
24838 
24839 #define	TCP_AC_MATCH(acp, tcp)					\
24840 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24841 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24842 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24843 
24844 /*
24845  * Build a message containing a tcp_ioc_abort_conn_t structure
24846  * which is filled in with information from acp and tp.
24847  */
24848 static mblk_t *
24849 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24850 {
24851 	mblk_t *mp;
24852 	tcp_ioc_abort_conn_t *tacp;
24853 
24854 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24855 	if (mp == NULL)
24856 		return (NULL);
24857 
24858 	mp->b_datap->db_type = M_CTL;
24859 
24860 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24861 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24862 		sizeof (uint32_t));
24863 
24864 	tacp->ac_start = acp->ac_start;
24865 	tacp->ac_end = acp->ac_end;
24866 	tacp->ac_zoneid = acp->ac_zoneid;
24867 
24868 	if (acp->ac_local.ss_family == AF_INET) {
24869 		tacp->ac_local.ss_family = AF_INET;
24870 		tacp->ac_remote.ss_family = AF_INET;
24871 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24872 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24873 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24874 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24875 	} else {
24876 		tacp->ac_local.ss_family = AF_INET6;
24877 		tacp->ac_remote.ss_family = AF_INET6;
24878 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24879 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24880 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24881 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24882 	}
24883 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24884 	return (mp);
24885 }
24886 
24887 /*
24888  * Print a tcp_ioc_abort_conn_t structure.
24889  */
24890 static void
24891 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24892 {
24893 	char lbuf[128];
24894 	char rbuf[128];
24895 	sa_family_t af;
24896 	in_port_t lport, rport;
24897 	ushort_t logflags;
24898 
24899 	af = acp->ac_local.ss_family;
24900 
24901 	if (af == AF_INET) {
24902 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24903 				lbuf, 128);
24904 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24905 				rbuf, 128);
24906 		lport = ntohs(TCP_AC_V4LPORT(acp));
24907 		rport = ntohs(TCP_AC_V4RPORT(acp));
24908 	} else {
24909 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24910 				lbuf, 128);
24911 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24912 				rbuf, 128);
24913 		lport = ntohs(TCP_AC_V6LPORT(acp));
24914 		rport = ntohs(TCP_AC_V6RPORT(acp));
24915 	}
24916 
24917 	logflags = SL_TRACE | SL_NOTE;
24918 	/*
24919 	 * Don't print this message to the console if the operation was done
24920 	 * to a non-global zone.
24921 	 */
24922 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24923 		logflags |= SL_CONSOLE;
24924 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24925 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24926 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24927 		acp->ac_start, acp->ac_end);
24928 }
24929 
24930 /*
24931  * Called inside tcp_rput when a message built using
24932  * tcp_ioctl_abort_build_msg is put into a queue.
24933  * Note that when we get here there is no wildcard in acp any more.
24934  */
24935 static void
24936 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24937 {
24938 	tcp_ioc_abort_conn_t *acp;
24939 
24940 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24941 	if (tcp->tcp_state <= acp->ac_end) {
24942 		/*
24943 		 * If we get here, we are already on the correct
24944 		 * squeue. This ioctl follows the following path
24945 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24946 		 * ->tcp_ioctl_abort->squeue_fill (if on a
24947 		 * different squeue)
24948 		 */
24949 		int errcode;
24950 
24951 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24952 		(void) tcp_clean_death(tcp, errcode, 26);
24953 	}
24954 	freemsg(mp);
24955 }
24956 
24957 /*
24958  * Abort all matching connections on a hash chain.
24959  */
24960 static int
24961 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24962     boolean_t exact)
24963 {
24964 	int nmatch, err = 0;
24965 	tcp_t *tcp;
24966 	MBLKP mp, last, listhead = NULL;
24967 	conn_t	*tconnp;
24968 	connf_t	*connfp = &ipcl_conn_fanout[index];
24969 
24970 startover:
24971 	nmatch = 0;
24972 
24973 	mutex_enter(&connfp->connf_lock);
24974 	for (tconnp = connfp->connf_head; tconnp != NULL;
24975 	    tconnp = tconnp->conn_next) {
24976 		tcp = tconnp->conn_tcp;
24977 		if (TCP_AC_MATCH(acp, tcp)) {
24978 			CONN_INC_REF(tcp->tcp_connp);
24979 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24980 			if (mp == NULL) {
24981 				err = ENOMEM;
24982 				CONN_DEC_REF(tcp->tcp_connp);
24983 				break;
24984 			}
24985 			mp->b_prev = (mblk_t *)tcp;
24986 
24987 			if (listhead == NULL) {
24988 				listhead = mp;
24989 				last = mp;
24990 			} else {
24991 				last->b_next = mp;
24992 				last = mp;
24993 			}
24994 			nmatch++;
24995 			if (exact)
24996 				break;
24997 		}
24998 
24999 		/* Avoid holding lock for too long. */
25000 		if (nmatch >= 500)
25001 			break;
25002 	}
25003 	mutex_exit(&connfp->connf_lock);
25004 
25005 	/* Pass mp into the correct tcp */
25006 	while ((mp = listhead) != NULL) {
25007 		listhead = listhead->b_next;
25008 		tcp = (tcp_t *)mp->b_prev;
25009 		mp->b_next = mp->b_prev = NULL;
25010 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
25011 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
25012 	}
25013 
25014 	*count += nmatch;
25015 	if (nmatch >= 500 && err == 0)
25016 		goto startover;
25017 	return (err);
25018 }
25019 
25020 /*
25021  * Abort all connections that matches the attributes specified in acp.
25022  */
25023 static int
25024 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
25025 {
25026 	sa_family_t af;
25027 	uint32_t  ports;
25028 	uint16_t *pports;
25029 	int err = 0, count = 0;
25030 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25031 	int index = -1;
25032 	ushort_t logflags;
25033 
25034 	af = acp->ac_local.ss_family;
25035 
25036 	if (af == AF_INET) {
25037 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25038 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25039 			pports = (uint16_t *)&ports;
25040 			pports[1] = TCP_AC_V4LPORT(acp);
25041 			pports[0] = TCP_AC_V4RPORT(acp);
25042 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25043 		}
25044 	} else {
25045 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25046 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25047 			pports = (uint16_t *)&ports;
25048 			pports[1] = TCP_AC_V6LPORT(acp);
25049 			pports[0] = TCP_AC_V6RPORT(acp);
25050 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25051 		}
25052 	}
25053 
25054 	/*
25055 	 * For cases where remote addr, local port, and remote port are non-
25056 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25057 	 */
25058 	if (index != -1) {
25059 		err = tcp_ioctl_abort_bucket(acp, index,
25060 			    &count, exact);
25061 	} else {
25062 		/*
25063 		 * loop through all entries for wildcard case
25064 		 */
25065 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
25066 			err = tcp_ioctl_abort_bucket(acp, index,
25067 			    &count, exact);
25068 			if (err != 0)
25069 				break;
25070 		}
25071 	}
25072 
25073 	logflags = SL_TRACE | SL_NOTE;
25074 	/*
25075 	 * Don't print this message to the console if the operation was done
25076 	 * to a non-global zone.
25077 	 */
25078 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25079 		logflags |= SL_CONSOLE;
25080 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25081 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25082 	if (err == 0 && count == 0)
25083 		err = ENOENT;
25084 	return (err);
25085 }
25086 
25087 /*
25088  * Process the TCP_IOC_ABORT_CONN ioctl request.
25089  */
25090 static void
25091 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25092 {
25093 	int	err;
25094 	IOCP    iocp;
25095 	MBLKP   mp1;
25096 	sa_family_t laf, raf;
25097 	tcp_ioc_abort_conn_t *acp;
25098 	zone_t *zptr;
25099 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
25100 
25101 	iocp = (IOCP)mp->b_rptr;
25102 
25103 	if ((mp1 = mp->b_cont) == NULL ||
25104 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25105 		err = EINVAL;
25106 		goto out;
25107 	}
25108 
25109 	/* check permissions */
25110 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
25111 		err = EPERM;
25112 		goto out;
25113 	}
25114 
25115 	if (mp1->b_cont != NULL) {
25116 		freemsg(mp1->b_cont);
25117 		mp1->b_cont = NULL;
25118 	}
25119 
25120 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25121 	laf = acp->ac_local.ss_family;
25122 	raf = acp->ac_remote.ss_family;
25123 
25124 	/* check that a zone with the supplied zoneid exists */
25125 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25126 		zptr = zone_find_by_id(zoneid);
25127 		if (zptr != NULL) {
25128 			zone_rele(zptr);
25129 		} else {
25130 			err = EINVAL;
25131 			goto out;
25132 		}
25133 	}
25134 
25135 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25136 	    acp->ac_start > acp->ac_end || laf != raf ||
25137 	    (laf != AF_INET && laf != AF_INET6)) {
25138 		err = EINVAL;
25139 		goto out;
25140 	}
25141 
25142 	tcp_ioctl_abort_dump(acp);
25143 	err = tcp_ioctl_abort(acp);
25144 
25145 out:
25146 	if (mp1 != NULL) {
25147 		freemsg(mp1);
25148 		mp->b_cont = NULL;
25149 	}
25150 
25151 	if (err != 0)
25152 		miocnak(q, mp, 0, err);
25153 	else
25154 		miocack(q, mp, 0, 0);
25155 }
25156 
25157 /*
25158  * tcp_time_wait_processing() handles processing of incoming packets when
25159  * the tcp is in the TIME_WAIT state.
25160  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25161  * on the time wait list.
25162  */
25163 void
25164 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25165     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25166 {
25167 	int32_t		bytes_acked;
25168 	int32_t		gap;
25169 	int32_t		rgap;
25170 	tcp_opt_t	tcpopt;
25171 	uint_t		flags;
25172 	uint32_t	new_swnd = 0;
25173 	conn_t		*connp;
25174 
25175 	BUMP_LOCAL(tcp->tcp_ibsegs);
25176 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
25177 
25178 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25179 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25180 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25181 	if (tcp->tcp_snd_ts_ok) {
25182 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25183 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25184 			    tcp->tcp_rnxt, TH_ACK);
25185 			goto done;
25186 		}
25187 	}
25188 	gap = seg_seq - tcp->tcp_rnxt;
25189 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25190 	if (gap < 0) {
25191 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
25192 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
25193 		    (seg_len > -gap ? -gap : seg_len));
25194 		seg_len += gap;
25195 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25196 			if (flags & TH_RST) {
25197 				goto done;
25198 			}
25199 			if ((flags & TH_FIN) && seg_len == -1) {
25200 				/*
25201 				 * When TCP receives a duplicate FIN in
25202 				 * TIME_WAIT state, restart the 2 MSL timer.
25203 				 * See page 73 in RFC 793. Make sure this TCP
25204 				 * is already on the TIME_WAIT list. If not,
25205 				 * just restart the timer.
25206 				 */
25207 				if (TCP_IS_DETACHED(tcp)) {
25208 					if (tcp_time_wait_remove(tcp, NULL) ==
25209 					    B_TRUE) {
25210 						tcp_time_wait_append(tcp);
25211 						TCP_DBGSTAT(tcp_rput_time_wait);
25212 					}
25213 				} else {
25214 					ASSERT(tcp != NULL);
25215 					TCP_TIMER_RESTART(tcp,
25216 					    tcp_time_wait_interval);
25217 				}
25218 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25219 				    tcp->tcp_rnxt, TH_ACK);
25220 				goto done;
25221 			}
25222 			flags |=  TH_ACK_NEEDED;
25223 			seg_len = 0;
25224 			goto process_ack;
25225 		}
25226 
25227 		/* Fix seg_seq, and chew the gap off the front. */
25228 		seg_seq = tcp->tcp_rnxt;
25229 	}
25230 
25231 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25232 		/*
25233 		 * Make sure that when we accept the connection, pick
25234 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25235 		 * old connection.
25236 		 *
25237 		 * The next ISS generated is equal to tcp_iss_incr_extra
25238 		 * + ISS_INCR/2 + other components depending on the
25239 		 * value of tcp_strong_iss.  We pre-calculate the new
25240 		 * ISS here and compare with tcp_snxt to determine if
25241 		 * we need to make adjustment to tcp_iss_incr_extra.
25242 		 *
25243 		 * The above calculation is ugly and is a
25244 		 * waste of CPU cycles...
25245 		 */
25246 		uint32_t new_iss = tcp_iss_incr_extra;
25247 		int32_t adj;
25248 
25249 		switch (tcp_strong_iss) {
25250 		case 2: {
25251 			/* Add time and MD5 components. */
25252 			uint32_t answer[4];
25253 			struct {
25254 				uint32_t ports;
25255 				in6_addr_t src;
25256 				in6_addr_t dst;
25257 			} arg;
25258 			MD5_CTX context;
25259 
25260 			mutex_enter(&tcp_iss_key_lock);
25261 			context = tcp_iss_key;
25262 			mutex_exit(&tcp_iss_key_lock);
25263 			arg.ports = tcp->tcp_ports;
25264 			/* We use MAPPED addresses in tcp_iss_init */
25265 			arg.src = tcp->tcp_ip_src_v6;
25266 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25267 				IN6_IPADDR_TO_V4MAPPED(
25268 					tcp->tcp_ipha->ipha_dst,
25269 					    &arg.dst);
25270 			} else {
25271 				arg.dst =
25272 				    tcp->tcp_ip6h->ip6_dst;
25273 			}
25274 			MD5Update(&context, (uchar_t *)&arg,
25275 			    sizeof (arg));
25276 			MD5Final((uchar_t *)answer, &context);
25277 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25278 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25279 			break;
25280 		}
25281 		case 1:
25282 			/* Add time component and min random (i.e. 1). */
25283 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25284 			break;
25285 		default:
25286 			/* Add only time component. */
25287 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25288 			break;
25289 		}
25290 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25291 			/*
25292 			 * New ISS not guaranteed to be ISS_INCR/2
25293 			 * ahead of the current tcp_snxt, so add the
25294 			 * difference to tcp_iss_incr_extra.
25295 			 */
25296 			tcp_iss_incr_extra += adj;
25297 		}
25298 		/*
25299 		 * If tcp_clean_death() can not perform the task now,
25300 		 * drop the SYN packet and let the other side re-xmit.
25301 		 * Otherwise pass the SYN packet back in, since the
25302 		 * old tcp state has been cleaned up or freed.
25303 		 */
25304 		if (tcp_clean_death(tcp, 0, 27) == -1)
25305 			goto done;
25306 		/*
25307 		 * We will come back to tcp_rput_data
25308 		 * on the global queue. Packets destined
25309 		 * for the global queue will be checked
25310 		 * with global policy. But the policy for
25311 		 * this packet has already been checked as
25312 		 * this was destined for the detached
25313 		 * connection. We need to bypass policy
25314 		 * check this time by attaching a dummy
25315 		 * ipsec_in with ipsec_in_dont_check set.
25316 		 */
25317 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
25318 		    NULL) {
25319 			TCP_STAT(tcp_time_wait_syn_success);
25320 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25321 			return;
25322 		}
25323 		goto done;
25324 	}
25325 
25326 	/*
25327 	 * rgap is the amount of stuff received out of window.  A negative
25328 	 * value is the amount out of window.
25329 	 */
25330 	if (rgap < 0) {
25331 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
25332 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
25333 		/* Fix seg_len and make sure there is something left. */
25334 		seg_len += rgap;
25335 		if (seg_len <= 0) {
25336 			if (flags & TH_RST) {
25337 				goto done;
25338 			}
25339 			flags |=  TH_ACK_NEEDED;
25340 			seg_len = 0;
25341 			goto process_ack;
25342 		}
25343 	}
25344 	/*
25345 	 * Check whether we can update tcp_ts_recent.  This test is
25346 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25347 	 * Extensions for High Performance: An Update", Internet Draft.
25348 	 */
25349 	if (tcp->tcp_snd_ts_ok &&
25350 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25351 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25352 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25353 		tcp->tcp_last_rcv_lbolt = lbolt64;
25354 	}
25355 
25356 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25357 		/* Always ack out of order packets */
25358 		flags |= TH_ACK_NEEDED;
25359 		seg_len = 0;
25360 	} else if (seg_len > 0) {
25361 		BUMP_MIB(&tcp_mib, tcpInClosed);
25362 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
25363 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
25364 	}
25365 	if (flags & TH_RST) {
25366 		(void) tcp_clean_death(tcp, 0, 28);
25367 		goto done;
25368 	}
25369 	if (flags & TH_SYN) {
25370 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25371 		    TH_RST|TH_ACK);
25372 		/*
25373 		 * Do not delete the TCP structure if it is in
25374 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25375 		 */
25376 		goto done;
25377 	}
25378 process_ack:
25379 	if (flags & TH_ACK) {
25380 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25381 		if (bytes_acked <= 0) {
25382 			if (bytes_acked == 0 && seg_len == 0 &&
25383 			    new_swnd == tcp->tcp_swnd)
25384 				BUMP_MIB(&tcp_mib, tcpInDupAck);
25385 		} else {
25386 			/* Acks something not sent */
25387 			flags |= TH_ACK_NEEDED;
25388 		}
25389 	}
25390 	if (flags & TH_ACK_NEEDED) {
25391 		/*
25392 		 * Time to send an ack for some reason.
25393 		 */
25394 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25395 		    tcp->tcp_rnxt, TH_ACK);
25396 	}
25397 done:
25398 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25399 		DB_CKSUMSTART(mp) = 0;
25400 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25401 		TCP_STAT(tcp_time_wait_syn_fail);
25402 	}
25403 	freemsg(mp);
25404 }
25405 
25406 /*
25407  * Allocate a T_SVR4_OPTMGMT_REQ.
25408  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
25409  * that tcp_rput_other can drop the acks.
25410  */
25411 static mblk_t *
25412 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
25413 {
25414 	mblk_t *mp;
25415 	struct T_optmgmt_req *tor;
25416 	struct opthdr *oh;
25417 	uint_t size;
25418 	char *optptr;
25419 
25420 	size = sizeof (*tor) + sizeof (*oh) + optlen;
25421 	mp = allocb(size, BPRI_MED);
25422 	if (mp == NULL)
25423 		return (NULL);
25424 
25425 	mp->b_wptr += size;
25426 	mp->b_datap->db_type = M_PROTO;
25427 	tor = (struct T_optmgmt_req *)mp->b_rptr;
25428 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
25429 	tor->MGMT_flags = T_NEGOTIATE;
25430 	tor->OPT_length = sizeof (*oh) + optlen;
25431 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
25432 
25433 	oh = (struct opthdr *)&tor[1];
25434 	oh->level = level;
25435 	oh->name = cmd;
25436 	oh->len = optlen;
25437 	if (optlen != 0) {
25438 		optptr = (char *)&oh[1];
25439 		bcopy(opt, optptr, optlen);
25440 	}
25441 	return (mp);
25442 }
25443 
25444 /*
25445  * TCP Timers Implementation.
25446  */
25447 timeout_id_t
25448 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25449 {
25450 	mblk_t *mp;
25451 	tcp_timer_t *tcpt;
25452 	tcp_t *tcp = connp->conn_tcp;
25453 
25454 	ASSERT(connp->conn_sqp != NULL);
25455 
25456 	TCP_DBGSTAT(tcp_timeout_calls);
25457 
25458 	if (tcp->tcp_timercache == NULL) {
25459 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25460 	} else {
25461 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
25462 		mp = tcp->tcp_timercache;
25463 		tcp->tcp_timercache = mp->b_next;
25464 		mp->b_next = NULL;
25465 		ASSERT(mp->b_wptr == NULL);
25466 	}
25467 
25468 	CONN_INC_REF(connp);
25469 	tcpt = (tcp_timer_t *)mp->b_rptr;
25470 	tcpt->connp = connp;
25471 	tcpt->tcpt_proc = f;
25472 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
25473 	return ((timeout_id_t)mp);
25474 }
25475 
25476 static void
25477 tcp_timer_callback(void *arg)
25478 {
25479 	mblk_t *mp = (mblk_t *)arg;
25480 	tcp_timer_t *tcpt;
25481 	conn_t	*connp;
25482 
25483 	tcpt = (tcp_timer_t *)mp->b_rptr;
25484 	connp = tcpt->connp;
25485 	squeue_fill(connp->conn_sqp, mp,
25486 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
25487 }
25488 
25489 static void
25490 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25491 {
25492 	tcp_timer_t *tcpt;
25493 	conn_t *connp = (conn_t *)arg;
25494 	tcp_t *tcp = connp->conn_tcp;
25495 
25496 	tcpt = (tcp_timer_t *)mp->b_rptr;
25497 	ASSERT(connp == tcpt->connp);
25498 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25499 
25500 	/*
25501 	 * If the TCP has reached the closed state, don't proceed any
25502 	 * further. This TCP logically does not exist on the system.
25503 	 * tcpt_proc could for example access queues, that have already
25504 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25505 	 */
25506 	if (tcp->tcp_state != TCPS_CLOSED) {
25507 		(*tcpt->tcpt_proc)(connp);
25508 	} else {
25509 		tcp->tcp_timer_tid = 0;
25510 	}
25511 	tcp_timer_free(connp->conn_tcp, mp);
25512 }
25513 
25514 /*
25515  * There is potential race with untimeout and the handler firing at the same
25516  * time. The mblock may be freed by the handler while we are trying to use
25517  * it. But since both should execute on the same squeue, this race should not
25518  * occur.
25519  */
25520 clock_t
25521 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25522 {
25523 	mblk_t	*mp = (mblk_t *)id;
25524 	tcp_timer_t *tcpt;
25525 	clock_t delta;
25526 
25527 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
25528 
25529 	if (mp == NULL)
25530 		return (-1);
25531 
25532 	tcpt = (tcp_timer_t *)mp->b_rptr;
25533 	ASSERT(tcpt->connp == connp);
25534 
25535 	delta = untimeout(tcpt->tcpt_tid);
25536 
25537 	if (delta >= 0) {
25538 		TCP_DBGSTAT(tcp_timeout_canceled);
25539 		tcp_timer_free(connp->conn_tcp, mp);
25540 		CONN_DEC_REF(connp);
25541 	}
25542 
25543 	return (delta);
25544 }
25545 
25546 /*
25547  * Allocate space for the timer event. The allocation looks like mblk, but it is
25548  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25549  *
25550  * Dealing with failures: If we can't allocate from the timer cache we try
25551  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25552  * points to b_rptr.
25553  * If we can't allocate anything using allocb_tryhard(), we perform a last
25554  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25555  * save the actual allocation size in b_datap.
25556  */
25557 mblk_t *
25558 tcp_timermp_alloc(int kmflags)
25559 {
25560 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25561 	    kmflags & ~KM_PANIC);
25562 
25563 	if (mp != NULL) {
25564 		mp->b_next = mp->b_prev = NULL;
25565 		mp->b_rptr = (uchar_t *)(&mp[1]);
25566 		mp->b_wptr = NULL;
25567 		mp->b_datap = NULL;
25568 		mp->b_queue = NULL;
25569 	} else if (kmflags & KM_PANIC) {
25570 		/*
25571 		 * Failed to allocate memory for the timer. Try allocating from
25572 		 * dblock caches.
25573 		 */
25574 		TCP_STAT(tcp_timermp_allocfail);
25575 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25576 		if (mp == NULL) {
25577 			size_t size = 0;
25578 			/*
25579 			 * Memory is really low. Try tryhard allocation.
25580 			 */
25581 			TCP_STAT(tcp_timermp_allocdblfail);
25582 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25583 			    sizeof (tcp_timer_t), &size, kmflags);
25584 			mp->b_rptr = (uchar_t *)(&mp[1]);
25585 			mp->b_next = mp->b_prev = NULL;
25586 			mp->b_wptr = (uchar_t *)-1;
25587 			mp->b_datap = (dblk_t *)size;
25588 			mp->b_queue = NULL;
25589 		}
25590 		ASSERT(mp->b_wptr != NULL);
25591 	}
25592 	TCP_DBGSTAT(tcp_timermp_alloced);
25593 
25594 	return (mp);
25595 }
25596 
25597 /*
25598  * Free per-tcp timer cache.
25599  * It can only contain entries from tcp_timercache.
25600  */
25601 void
25602 tcp_timermp_free(tcp_t *tcp)
25603 {
25604 	mblk_t *mp;
25605 
25606 	while ((mp = tcp->tcp_timercache) != NULL) {
25607 		ASSERT(mp->b_wptr == NULL);
25608 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25609 		kmem_cache_free(tcp_timercache, mp);
25610 	}
25611 }
25612 
25613 /*
25614  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25615  * events there already (currently at most two events are cached).
25616  * If the event is not allocated from the timer cache, free it right away.
25617  */
25618 static void
25619 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25620 {
25621 	mblk_t *mp1 = tcp->tcp_timercache;
25622 
25623 	if (mp->b_wptr != NULL) {
25624 		/*
25625 		 * This allocation is not from a timer cache, free it right
25626 		 * away.
25627 		 */
25628 		if (mp->b_wptr != (uchar_t *)-1)
25629 			freeb(mp);
25630 		else
25631 			kmem_free(mp, (size_t)mp->b_datap);
25632 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25633 		/* Cache this timer block for future allocations */
25634 		mp->b_rptr = (uchar_t *)(&mp[1]);
25635 		mp->b_next = mp1;
25636 		tcp->tcp_timercache = mp;
25637 	} else {
25638 		kmem_cache_free(tcp_timercache, mp);
25639 		TCP_DBGSTAT(tcp_timermp_freed);
25640 	}
25641 }
25642 
25643 /*
25644  * End of TCP Timers implementation.
25645  */
25646 
25647 /*
25648  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25649  * on the specified backing STREAMS q. Note, the caller may make the
25650  * decision to call based on the tcp_t.tcp_flow_stopped value which
25651  * when check outside the q's lock is only an advisory check ...
25652  */
25653 
25654 void
25655 tcp_setqfull(tcp_t *tcp)
25656 {
25657 	queue_t *q = tcp->tcp_wq;
25658 
25659 	if (!(q->q_flag & QFULL)) {
25660 		mutex_enter(QLOCK(q));
25661 		if (!(q->q_flag & QFULL)) {
25662 			/* still need to set QFULL */
25663 			q->q_flag |= QFULL;
25664 			tcp->tcp_flow_stopped = B_TRUE;
25665 			mutex_exit(QLOCK(q));
25666 			TCP_STAT(tcp_flwctl_on);
25667 		} else {
25668 			mutex_exit(QLOCK(q));
25669 		}
25670 	}
25671 }
25672 
25673 void
25674 tcp_clrqfull(tcp_t *tcp)
25675 {
25676 	queue_t *q = tcp->tcp_wq;
25677 
25678 	if (q->q_flag & QFULL) {
25679 		mutex_enter(QLOCK(q));
25680 		if (q->q_flag & QFULL) {
25681 			q->q_flag &= ~QFULL;
25682 			tcp->tcp_flow_stopped = B_FALSE;
25683 			mutex_exit(QLOCK(q));
25684 			if (q->q_flag & QWANTW)
25685 				qbackenable(q, 0);
25686 		} else {
25687 			mutex_exit(QLOCK(q));
25688 		}
25689 	}
25690 }
25691 
25692 /*
25693  * TCP Kstats implementation
25694  */
25695 static void
25696 tcp_kstat_init(void)
25697 {
25698 	tcp_named_kstat_t template = {
25699 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25700 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25701 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25702 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25703 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25704 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25705 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25706 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25707 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25708 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25709 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25710 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25711 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25712 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25713 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25714 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25715 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25716 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25717 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25718 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25719 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25720 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25721 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25722 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25723 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25724 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25725 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25726 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25727 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25728 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25729 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25730 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25731 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25732 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25733 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25734 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25735 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25736 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25737 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25738 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25739 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25740 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25741 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25742 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25743 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25744 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25745 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25746 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25747 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25748 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25749 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25750 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25751 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25752 	};
25753 
25754 	tcp_mibkp = kstat_create(TCP_MOD_NAME, 0, TCP_MOD_NAME,
25755 	    "mib2", KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0);
25756 
25757 	if (tcp_mibkp == NULL)
25758 		return;
25759 
25760 	template.rtoAlgorithm.value.ui32 = 4;
25761 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
25762 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
25763 	template.maxConn.value.i32 = -1;
25764 
25765 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
25766 
25767 	tcp_mibkp->ks_update = tcp_kstat_update;
25768 
25769 	kstat_install(tcp_mibkp);
25770 }
25771 
25772 static void
25773 tcp_kstat_fini(void)
25774 {
25775 
25776 	if (tcp_mibkp != NULL) {
25777 		kstat_delete(tcp_mibkp);
25778 		tcp_mibkp = NULL;
25779 	}
25780 }
25781 
25782 static int
25783 tcp_kstat_update(kstat_t *kp, int rw)
25784 {
25785 	tcp_named_kstat_t	*tcpkp;
25786 	tcp_t			*tcp;
25787 	connf_t			*connfp;
25788 	conn_t			*connp;
25789 	int 			i;
25790 
25791 	if (!kp || !kp->ks_data)
25792 		return (EIO);
25793 
25794 	if (rw == KSTAT_WRITE)
25795 		return (EACCES);
25796 
25797 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25798 
25799 	tcpkp->currEstab.value.ui32 = 0;
25800 
25801 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25802 		connfp = &ipcl_globalhash_fanout[i];
25803 		connp = NULL;
25804 		while ((connp =
25805 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25806 			tcp = connp->conn_tcp;
25807 			switch (tcp_snmp_state(tcp)) {
25808 			case MIB2_TCP_established:
25809 			case MIB2_TCP_closeWait:
25810 				tcpkp->currEstab.value.ui32++;
25811 				break;
25812 			}
25813 		}
25814 	}
25815 
25816 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
25817 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
25818 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
25819 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
25820 	tcpkp->inSegs.value.ui64 = tcp_mib.tcpHCInSegs;
25821 	tcpkp->outSegs.value.ui64 = tcp_mib.tcpHCOutSegs;
25822 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
25823 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
25824 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
25825 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
25826 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
25827 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
25828 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
25829 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
25830 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
25831 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
25832 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
25833 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
25834 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
25835 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
25836 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
25837 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
25838 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
25839 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
25840 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
25841 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
25842 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
25843 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
25844 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
25845 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
25846 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
25847 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
25848 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
25849 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
25850 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
25851 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
25852 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
25853 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
25854 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
25855 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
25856 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
25857 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
25858 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
25859 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
25860 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
25861 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
25862 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
25863 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
25864 
25865 	return (0);
25866 }
25867 
25868 void
25869 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25870 {
25871 	uint16_t	hdr_len;
25872 	ipha_t		*ipha;
25873 	uint8_t		*nexthdrp;
25874 	tcph_t		*tcph;
25875 
25876 	/* Already has an eager */
25877 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25878 		TCP_STAT(tcp_reinput_syn);
25879 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
25880 		    connp, SQTAG_TCP_REINPUT_EAGER);
25881 		return;
25882 	}
25883 
25884 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25885 	case IPV4_VERSION:
25886 		ipha = (ipha_t *)mp->b_rptr;
25887 		hdr_len = IPH_HDR_LENGTH(ipha);
25888 		break;
25889 	case IPV6_VERSION:
25890 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25891 		    &hdr_len, &nexthdrp)) {
25892 			CONN_DEC_REF(connp);
25893 			freemsg(mp);
25894 			return;
25895 		}
25896 		break;
25897 	}
25898 
25899 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25900 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25901 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25902 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25903 	}
25904 
25905 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
25906 	    SQTAG_TCP_REINPUT);
25907 }
25908 
25909 static squeue_func_t
25910 tcp_squeue_switch(int val)
25911 {
25912 	squeue_func_t rval = squeue_fill;
25913 
25914 	switch (val) {
25915 	case 1:
25916 		rval = squeue_enter_nodrain;
25917 		break;
25918 	case 2:
25919 		rval = squeue_enter;
25920 		break;
25921 	default:
25922 		break;
25923 	}
25924 	return (rval);
25925 }
25926 
25927 static void
25928 tcp_squeue_add(squeue_t *sqp)
25929 {
25930 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25931 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
25932 
25933 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25934 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
25935 	    sqp, TCP_TIME_WAIT_DELAY);
25936 	if (tcp_free_list_max_cnt == 0) {
25937 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25938 			max_ncpus : boot_max_ncpus);
25939 
25940 		/*
25941 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25942 		 */
25943 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25944 			(tcp_ncpus * sizeof (tcp_t) * 100);
25945 	}
25946 	tcp_time_wait->tcp_free_list_cnt = 0;
25947 }
25948