xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 60a3f738d56f92ae8b80e4b62a2331c6e1f2311f)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 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 };
422 
423 static kstat_t *tcp_kstat;
424 
425 /*
426  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
427  * tcp write side.
428  */
429 #define	CALL_IP_WPUT(connp, q, mp) {					\
430 	ASSERT(((q)->q_flag & QREADR) == 0);				\
431 	TCP_DBGSTAT(tcp_ip_output);					\
432 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
433 }
434 
435 /* Macros for timestamp comparisons */
436 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
437 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
438 
439 /*
440  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
441  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
442  * by adding three components: a time component which grows by 1 every 4096
443  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
444  * a per-connection component which grows by 125000 for every new connection;
445  * and an "extra" component that grows by a random amount centered
446  * approximately on 64000.  This causes the the ISS generator to cycle every
447  * 4.89 hours if no TCP connections are made, and faster if connections are
448  * made.
449  *
450  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
451  * components: a time component which grows by 250000 every second; and
452  * a per-connection component which grows by 125000 for every new connections.
453  *
454  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
455  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
456  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
457  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
458  * password.
459  */
460 #define	ISS_INCR	250000
461 #define	ISS_NSEC_SHT	12
462 
463 static uint32_t tcp_iss_incr_extra;	/* Incremented for each connection */
464 static kmutex_t tcp_iss_key_lock;
465 static MD5_CTX tcp_iss_key;
466 static sin_t	sin_null;	/* Zero address for quick clears */
467 static sin6_t	sin6_null;	/* Zero address for quick clears */
468 
469 /* Packet dropper for TCP IPsec policy drops. */
470 static ipdropper_t tcp_dropper;
471 
472 /*
473  * This implementation follows the 4.3BSD interpretation of the urgent
474  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
475  * incompatible changes in protocols like telnet and rlogin.
476  */
477 #define	TCP_OLD_URP_INTERPRETATION	1
478 
479 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
480 	(TCP_IS_DETACHED(tcp) && \
481 	    (!(tcp)->tcp_hard_binding))
482 
483 /*
484  * TCP reassembly macros.  We hide starting and ending sequence numbers in
485  * b_next and b_prev of messages on the reassembly queue.  The messages are
486  * chained using b_cont.  These macros are used in tcp_reass() so we don't
487  * have to see the ugly casts and assignments.
488  */
489 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
490 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
491 					(mblk_t *)(uintptr_t)(u))
492 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
493 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
494 					(mblk_t *)(uintptr_t)(u))
495 
496 /*
497  * Implementation of TCP Timers.
498  * =============================
499  *
500  * INTERFACE:
501  *
502  * There are two basic functions dealing with tcp timers:
503  *
504  *	timeout_id_t	tcp_timeout(connp, func, time)
505  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
506  *	TCP_TIMER_RESTART(tcp, intvl)
507  *
508  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
509  * after 'time' ticks passed. The function called by timeout() must adhere to
510  * the same restrictions as a driver soft interrupt handler - it must not sleep
511  * or call other functions that might sleep. The value returned is the opaque
512  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
513  * cancel the request. The call to tcp_timeout() may fail in which case it
514  * returns zero. This is different from the timeout(9F) function which never
515  * fails.
516  *
517  * The call-back function 'func' always receives 'connp' as its single
518  * argument. It is always executed in the squeue corresponding to the tcp
519  * structure. The tcp structure is guaranteed to be present at the time the
520  * call-back is called.
521  *
522  * NOTE: The call-back function 'func' is never called if tcp is in
523  * 	the TCPS_CLOSED state.
524  *
525  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
526  * request. locks acquired by the call-back routine should not be held across
527  * the call to tcp_timeout_cancel() or a deadlock may result.
528  *
529  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
530  * Otherwise, it returns an integer value greater than or equal to 0. In
531  * particular, if the call-back function is already placed on the squeue, it can
532  * not be canceled.
533  *
534  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
535  * 	within squeue context corresponding to the tcp instance. Since the
536  *	call-back is also called via the same squeue, there are no race
537  *	conditions described in untimeout(9F) manual page since all calls are
538  *	strictly serialized.
539  *
540  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
541  *	stored in tcp_timer_tid and starts a new one using
542  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
543  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
544  *	field.
545  *
546  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
547  *	call-back may still be called, so it is possible tcp_timer() will be
548  *	called several times. This should not be a problem since tcp_timer()
549  *	should always check the tcp instance state.
550  *
551  *
552  * IMPLEMENTATION:
553  *
554  * TCP timers are implemented using three-stage process. The call to
555  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
556  * when the timer expires. The tcp_timer_callback() arranges the call of the
557  * tcp_timer_handler() function via squeue corresponding to the tcp
558  * instance. The tcp_timer_handler() calls actual requested timeout call-back
559  * and passes tcp instance as an argument to it. Information is passed between
560  * stages using the tcp_timer_t structure which contains the connp pointer, the
561  * tcp call-back to call and the timeout id returned by the timeout(9F).
562  *
563  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
564  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
565  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
566  * returns the pointer to this mblk.
567  *
568  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
569  * looks like a normal mblk without actual dblk attached to it.
570  *
571  * To optimize performance each tcp instance holds a small cache of timer
572  * mblocks. In the current implementation it caches up to two timer mblocks per
573  * tcp instance. The cache is preserved over tcp frees and is only freed when
574  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
575  * timer processing happens on a corresponding squeue, the cache manipulation
576  * does not require any locks. Experiments show that majority of timer mblocks
577  * allocations are satisfied from the tcp cache and do not involve kmem calls.
578  *
579  * The tcp_timeout() places a refhold on the connp instance which guarantees
580  * that it will be present at the time the call-back function fires. The
581  * tcp_timer_handler() drops the reference after calling the call-back, so the
582  * call-back function does not need to manipulate the references explicitly.
583  */
584 
585 typedef struct tcp_timer_s {
586 	conn_t	*connp;
587 	void 	(*tcpt_proc)(void *);
588 	timeout_id_t   tcpt_tid;
589 } tcp_timer_t;
590 
591 static kmem_cache_t *tcp_timercache;
592 kmem_cache_t	*tcp_sack_info_cache;
593 kmem_cache_t	*tcp_iphc_cache;
594 
595 /*
596  * For scalability, we must not run a timer for every TCP connection
597  * in TIME_WAIT state.  To see why, consider (for time wait interval of
598  * 4 minutes):
599  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
600  *
601  * This list is ordered by time, so you need only delete from the head
602  * until you get to entries which aren't old enough to delete yet.
603  * The list consists of only the detached TIME_WAIT connections.
604  *
605  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
606  * becomes detached TIME_WAIT (either by changing the state and already
607  * being detached or the other way around). This means that the TIME_WAIT
608  * state can be extended (up to doubled) if the connection doesn't become
609  * detached for a long time.
610  *
611  * The list manipulations (including tcp_time_wait_next/prev)
612  * are protected by the tcp_time_wait_lock. The content of the
613  * detached TIME_WAIT connections is protected by the normal perimeters.
614  */
615 
616 typedef struct tcp_squeue_priv_s {
617 	kmutex_t	tcp_time_wait_lock;
618 				/* Protects the next 3 globals */
619 	timeout_id_t	tcp_time_wait_tid;
620 	tcp_t		*tcp_time_wait_head;
621 	tcp_t		*tcp_time_wait_tail;
622 	tcp_t		*tcp_free_list;
623 	uint_t		tcp_free_list_cnt;
624 } tcp_squeue_priv_t;
625 
626 /*
627  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
628  * Running it every 5 seconds seems to give the best results.
629  */
630 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
631 
632 /*
633  * To prevent memory hog, limit the number of entries in tcp_free_list
634  * to 1% of available memory / number of cpus
635  */
636 uint_t tcp_free_list_max_cnt = 0;
637 
638 #define	TCP_XMIT_LOWATER	4096
639 #define	TCP_XMIT_HIWATER	49152
640 #define	TCP_RECV_LOWATER	2048
641 #define	TCP_RECV_HIWATER	49152
642 
643 /*
644  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
645  */
646 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
647 
648 #define	TIDUSZ	4096	/* transport interface data unit size */
649 
650 /*
651  * Bind hash list size and has function.  It has to be a power of 2 for
652  * hashing.
653  */
654 #define	TCP_BIND_FANOUT_SIZE	512
655 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
656 /*
657  * Size of listen and acceptor hash list.  It has to be a power of 2 for
658  * hashing.
659  */
660 #define	TCP_FANOUT_SIZE		256
661 
662 #ifdef	_ILP32
663 #define	TCP_ACCEPTOR_HASH(accid)					\
664 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
665 #else
666 #define	TCP_ACCEPTOR_HASH(accid)					\
667 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
668 #endif	/* _ILP32 */
669 
670 #define	IP_ADDR_CACHE_SIZE	2048
671 #define	IP_ADDR_CACHE_HASH(faddr)					\
672 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
673 
674 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
675 #define	TCP_HSP_HASH_SIZE 256
676 
677 #define	TCP_HSP_HASH(addr)					\
678 	(((addr>>24) ^ (addr >>16) ^			\
679 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
680 
681 /*
682  * TCP options struct returned from tcp_parse_options.
683  */
684 typedef struct tcp_opt_s {
685 	uint32_t	tcp_opt_mss;
686 	uint32_t	tcp_opt_wscale;
687 	uint32_t	tcp_opt_ts_val;
688 	uint32_t	tcp_opt_ts_ecr;
689 	tcp_t		*tcp;
690 } tcp_opt_t;
691 
692 /*
693  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
694  */
695 
696 #ifdef _BIG_ENDIAN
697 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
698 	(TCPOPT_TSTAMP << 8) | 10)
699 #else
700 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
701 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
702 #endif
703 
704 /*
705  * Flags returned from tcp_parse_options.
706  */
707 #define	TCP_OPT_MSS_PRESENT	1
708 #define	TCP_OPT_WSCALE_PRESENT	2
709 #define	TCP_OPT_TSTAMP_PRESENT	4
710 #define	TCP_OPT_SACK_OK_PRESENT	8
711 #define	TCP_OPT_SACK_PRESENT	16
712 
713 /* TCP option length */
714 #define	TCPOPT_NOP_LEN		1
715 #define	TCPOPT_MAXSEG_LEN	4
716 #define	TCPOPT_WS_LEN		3
717 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
718 #define	TCPOPT_TSTAMP_LEN	10
719 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
720 #define	TCPOPT_SACK_OK_LEN	2
721 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
722 #define	TCPOPT_REAL_SACK_LEN	4
723 #define	TCPOPT_MAX_SACK_LEN	36
724 #define	TCPOPT_HEADER_LEN	2
725 
726 /* TCP cwnd burst factor. */
727 #define	TCP_CWND_INFINITE	65535
728 #define	TCP_CWND_SS		3
729 #define	TCP_CWND_NORMAL		5
730 
731 /* Maximum TCP initial cwin (start/restart). */
732 #define	TCP_MAX_INIT_CWND	8
733 
734 /*
735  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
736  * either tcp_slow_start_initial or tcp_slow_start_after idle
737  * depending on the caller.  If the upper layer has not used the
738  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
739  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
740  * If the upper layer has changed set the tcp_init_cwnd, just use
741  * it to calculate the tcp_cwnd.
742  */
743 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
744 {									\
745 	if ((tcp)->tcp_init_cwnd == 0) {				\
746 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
747 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
748 	} else {							\
749 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
750 	}								\
751 	tcp->tcp_cwnd_cnt = 0;						\
752 }
753 
754 /* TCP Timer control structure */
755 typedef struct tcpt_s {
756 	pfv_t	tcpt_pfv;	/* The routine we are to call */
757 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
758 } tcpt_t;
759 
760 /* Host Specific Parameter structure */
761 typedef struct tcp_hsp {
762 	struct tcp_hsp	*tcp_hsp_next;
763 	in6_addr_t	tcp_hsp_addr_v6;
764 	in6_addr_t	tcp_hsp_subnet_v6;
765 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
766 	int32_t		tcp_hsp_sendspace;
767 	int32_t		tcp_hsp_recvspace;
768 	int32_t		tcp_hsp_tstamp;
769 } tcp_hsp_t;
770 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
771 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
772 
773 /*
774  * Functions called directly via squeue having a prototype of edesc_t.
775  */
776 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
777 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
778 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
779 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
780 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
781 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
782 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
783 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
784 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
785 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
786 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
787 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
788 
789 
790 /* Prototype for TCP functions */
791 static void	tcp_random_init(void);
792 int		tcp_random(void);
793 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
794 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
795 		    tcp_t *eager);
796 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
797 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
798     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
799     boolean_t user_specified);
800 static void	tcp_closei_local(tcp_t *tcp);
801 static void	tcp_close_detached(tcp_t *tcp);
802 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
803 			mblk_t *idmp, mblk_t **defermp);
804 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
805 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
806 		    in_port_t dstport, uint_t srcid);
807 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
808 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
809 		    uint32_t scope_id);
810 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
811 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
812 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
813 static char	*tcp_display(tcp_t *tcp, char *, char);
814 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
815 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
816 static void	tcp_eager_unlink(tcp_t *tcp);
817 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
818 		    int unixerr);
819 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
820 		    int tlierr, int unixerr);
821 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
822 		    cred_t *cr);
823 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
824 		    char *value, caddr_t cp, cred_t *cr);
825 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
826 		    char *value, caddr_t cp, cred_t *cr);
827 static int	tcp_tpistate(tcp_t *tcp);
828 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
829     int caller_holds_lock);
830 static void	tcp_bind_hash_remove(tcp_t *tcp);
831 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id);
832 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
833 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
834 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
835 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
836 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
837 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
838 static int	tcp_header_init_ipv4(tcp_t *tcp);
839 static int	tcp_header_init_ipv6(tcp_t *tcp);
840 int		tcp_init(tcp_t *tcp, queue_t *q);
841 static int	tcp_init_values(tcp_t *tcp);
842 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
843 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
844 		    t_scalar_t addr_length);
845 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
846 static void	tcp_ip_notify(tcp_t *tcp);
847 static mblk_t	*tcp_ire_mp(mblk_t *mp);
848 static void	tcp_iss_init(tcp_t *tcp);
849 static void	tcp_keepalive_killer(void *arg);
850 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
851 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
852 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
853 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
854 static boolean_t tcp_allow_connopt_set(int level, int name);
855 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
856 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
857 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
858 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
859 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
860 		    mblk_t *mblk);
861 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
862 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
863 		    uchar_t *ptr, uint_t len);
864 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
865 static boolean_t tcp_param_register(tcpparam_t *tcppa, int cnt);
866 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
867 		    caddr_t cp, cred_t *cr);
868 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
869 		    caddr_t cp, cred_t *cr);
870 static void	tcp_iss_key_init(uint8_t *phrase, int len);
871 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
872 		    caddr_t cp, cred_t *cr);
873 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
874 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
875 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
876 static void	tcp_reinit(tcp_t *tcp);
877 static void	tcp_reinit_values(tcp_t *tcp);
878 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
879 		    tcp_t *thisstream, cred_t *cr);
880 
881 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
882 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
883 static boolean_t tcp_send_rst_chk(void);
884 static void	tcp_ss_rexmit(tcp_t *tcp);
885 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
886 static void	tcp_process_options(tcp_t *, tcph_t *);
887 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
888 static void	tcp_rsrv(queue_t *q);
889 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
890 static int	tcp_snmp_state(tcp_t *tcp);
891 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
892 		    cred_t *cr);
893 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
894 		    cred_t *cr);
895 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
896 		    cred_t *cr);
897 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
898 		    cred_t *cr);
899 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
900 		    cred_t *cr);
901 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
902 		    caddr_t cp, cred_t *cr);
903 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
904 		    caddr_t cp, cred_t *cr);
905 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
906 		    cred_t *cr);
907 static void	tcp_timer(void *arg);
908 static void	tcp_timer_callback(void *);
909 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
910     boolean_t random);
911 static in_port_t tcp_get_next_priv_port(const tcp_t *);
912 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
913 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
914 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
915 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
916 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
917 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
918 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
919 		    const int num_sack_blk, int *usable, uint_t *snxt,
920 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
921 		    const int mdt_thres);
922 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
923 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
924 		    const int num_sack_blk, int *usable, uint_t *snxt,
925 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
926 		    const int mdt_thres);
927 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
928 		    int num_sack_blk);
929 static void	tcp_wsrv(queue_t *q);
930 static int	tcp_xmit_end(tcp_t *tcp);
931 static void	tcp_ack_timer(void *arg);
932 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
933 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
934 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
935 		    zoneid_t zoneid);
936 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
937 		    uint32_t ack, int ctl);
938 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr);
939 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr);
940 static int	setmaxps(queue_t *q, int maxpsz);
941 static void	tcp_set_rto(tcp_t *, time_t);
942 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
943 		    boolean_t, boolean_t);
944 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
945 		    boolean_t ipsec_mctl);
946 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
947 		    char *opt, int optlen);
948 static int	tcp_build_hdrs(queue_t *, tcp_t *);
949 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
950 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
951 		    tcph_t *tcph);
952 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
953 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
954 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
955 boolean_t	tcp_reserved_port_check(in_port_t);
956 static tcp_t	*tcp_alloc_temp_tcp(in_port_t);
957 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
958 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
959 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
960 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
961 		    const boolean_t, const uint32_t, const uint32_t,
962 		    const uint32_t, const uint32_t);
963 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
964 		    const uint_t, const uint_t, boolean_t *);
965 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
966 extern mblk_t	*tcp_timermp_alloc(int);
967 extern void	tcp_timermp_free(tcp_t *);
968 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
969 static void	tcp_stop_lingering(tcp_t *tcp);
970 static void	tcp_close_linger_timeout(void *arg);
971 void		tcp_ddi_init(void);
972 void		tcp_ddi_destroy(void);
973 static void	tcp_kstat_init(void);
974 static void	tcp_kstat_fini(void);
975 static int	tcp_kstat_update(kstat_t *kp, int rw);
976 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
977 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
978 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
979 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
980 			tcph_t *tcph, mblk_t *idmp);
981 static squeue_func_t tcp_squeue_switch(int);
982 
983 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
984 static int	tcp_close(queue_t *, int);
985 static int	tcpclose_accept(queue_t *);
986 static int	tcp_modclose(queue_t *);
987 static void	tcp_wput_mod(queue_t *, mblk_t *);
988 
989 static void	tcp_squeue_add(squeue_t *);
990 static boolean_t tcp_zcopy_check(tcp_t *);
991 static void	tcp_zcopy_notify(tcp_t *);
992 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
993 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
994 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
995 
996 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
997 
998 /*
999  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
1000  *
1001  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
1002  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
1003  * (defined in tcp.h) needs to be filled in and passed into the kernel
1004  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
1005  * structure contains the four-tuple of a TCP connection and a range of TCP
1006  * states (specified by ac_start and ac_end). The use of wildcard addresses
1007  * and ports is allowed. Connections with a matching four tuple and a state
1008  * within the specified range will be aborted. The valid states for the
1009  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
1010  * inclusive.
1011  *
1012  * An application which has its connection aborted by this ioctl will receive
1013  * an error that is dependent on the connection state at the time of the abort.
1014  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1015  * though a RST packet has been received.  If the connection state is equal to
1016  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1017  * and all resources associated with the connection will be freed.
1018  */
1019 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1020 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1021 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1022 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *);
1023 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1024 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1025     boolean_t);
1026 
1027 static struct module_info tcp_rinfo =  {
1028 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1029 };
1030 
1031 static struct module_info tcp_winfo =  {
1032 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1033 };
1034 
1035 /*
1036  * Entry points for TCP as a module. It only allows SNMP requests
1037  * to pass through.
1038  */
1039 struct qinit tcp_mod_rinit = {
1040 	(pfi_t)putnext, NULL, tcp_open, ip_snmpmod_close, NULL, &tcp_rinfo,
1041 };
1042 
1043 struct qinit tcp_mod_winit = {
1044 	(pfi_t)ip_snmpmod_wput, NULL, tcp_open, ip_snmpmod_close, NULL,
1045 	&tcp_rinfo
1046 };
1047 
1048 /*
1049  * Entry points for TCP as a device. The normal case which supports
1050  * the TCP functionality.
1051  */
1052 struct qinit tcp_rinit = {
1053 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
1054 };
1055 
1056 struct qinit tcp_winit = {
1057 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1058 };
1059 
1060 /* Initial entry point for TCP in socket mode. */
1061 struct qinit tcp_sock_winit = {
1062 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1063 };
1064 
1065 /*
1066  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1067  * an accept. Avoid allocating data structures since eager has already
1068  * been created.
1069  */
1070 struct qinit tcp_acceptor_rinit = {
1071 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1072 };
1073 
1074 struct qinit tcp_acceptor_winit = {
1075 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1076 };
1077 
1078 /*
1079  * Entry points for TCP loopback (read side only)
1080  */
1081 struct qinit tcp_loopback_rinit = {
1082 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_open, tcp_close, (pfi_t)0,
1083 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1084 };
1085 
1086 struct streamtab tcpinfo = {
1087 	&tcp_rinit, &tcp_winit
1088 };
1089 
1090 extern squeue_func_t tcp_squeue_wput_proc;
1091 extern squeue_func_t tcp_squeue_timer_proc;
1092 
1093 /* Protected by tcp_g_q_lock */
1094 static queue_t	*tcp_g_q;	/* Default queue used during detached closes */
1095 kmutex_t tcp_g_q_lock;
1096 
1097 /* Protected by tcp_hsp_lock */
1098 /*
1099  * XXX The host param mechanism should go away and instead we should use
1100  * the metrics associated with the routes to determine the default sndspace
1101  * and rcvspace.
1102  */
1103 static tcp_hsp_t	**tcp_hsp_hash;	/* Hash table for HSPs */
1104 krwlock_t tcp_hsp_lock;
1105 
1106 /*
1107  * Extra privileged ports. In host byte order.
1108  * Protected by tcp_epriv_port_lock.
1109  */
1110 #define	TCP_NUM_EPRIV_PORTS	64
1111 static int	tcp_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
1112 static uint16_t	tcp_g_epriv_ports[TCP_NUM_EPRIV_PORTS] = { 2049, 4045 };
1113 kmutex_t tcp_epriv_port_lock;
1114 
1115 /*
1116  * The smallest anonymous port in the privileged port range which TCP
1117  * looks for free port.  Use in the option TCP_ANONPRIVBIND.
1118  */
1119 static in_port_t tcp_min_anonpriv_port = 512;
1120 
1121 /* Only modified during _init and _fini thus no locking is needed. */
1122 static caddr_t	tcp_g_nd;	/* Head of 'named dispatch' variable list */
1123 
1124 /* Hint not protected by any lock */
1125 static uint_t	tcp_next_port_to_try;
1126 
1127 
1128 /* TCP bind hash list - all tcp_t with state >= BOUND. */
1129 tf_t	tcp_bind_fanout[TCP_BIND_FANOUT_SIZE];
1130 
1131 /* TCP queue hash list - all tcp_t in case they will be an acceptor. */
1132 static tf_t	tcp_acceptor_fanout[TCP_FANOUT_SIZE];
1133 
1134 /*
1135  * TCP has a private interface for other kernel modules to reserve a
1136  * port range for them to use.  Once reserved, TCP will not use any ports
1137  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1138  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1139  * has to be verified.
1140  *
1141  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1142  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1143  * range is [port a, port b] inclusive.  And each port range is between
1144  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1145  *
1146  * Note that the default anonymous port range starts from 32768.  There is
1147  * no port "collision" between that and the reserved port range.  If there
1148  * is port collision (because the default smallest anonymous port is lowered
1149  * or some apps specifically bind to ports in the reserved port range), the
1150  * system may not be able to reserve a port range even there are enough
1151  * unbound ports as a reserved port range contains consecutive ports .
1152  */
1153 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1154 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1155 #define	TCP_SMALLEST_RESERVED_PORT		10240
1156 #define	TCP_LARGEST_RESERVED_PORT		20480
1157 
1158 /* Structure to represent those reserved port ranges. */
1159 typedef struct tcp_rport_s {
1160 	in_port_t	lo_port;
1161 	in_port_t	hi_port;
1162 	tcp_t		**temp_tcp_array;
1163 } tcp_rport_t;
1164 
1165 /* The reserved port array. */
1166 static tcp_rport_t tcp_reserved_port[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
1167 
1168 /* Locks to protect the tcp_reserved_ports array. */
1169 static krwlock_t tcp_reserved_port_lock;
1170 
1171 /* The number of ranges in the array. */
1172 uint32_t tcp_reserved_port_array_size = 0;
1173 
1174 /*
1175  * MIB-2 stuff for SNMP
1176  * Note: tcpInErrs {tcp 15} is accumulated in ip.c
1177  */
1178 mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */
1179 kstat_t		*tcp_mibkp;	/* kstat exporting tcp_mib data */
1180 
1181 boolean_t tcp_icmp_source_quench = B_FALSE;
1182 /*
1183  * Following assumes TPI alignment requirements stay along 32 bit
1184  * boundaries
1185  */
1186 #define	ROUNDUP32(x) \
1187 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1188 
1189 /* Template for response to info request. */
1190 static struct T_info_ack tcp_g_t_info_ack = {
1191 	T_INFO_ACK,		/* PRIM_type */
1192 	0,			/* TSDU_size */
1193 	T_INFINITE,		/* ETSDU_size */
1194 	T_INVALID,		/* CDATA_size */
1195 	T_INVALID,		/* DDATA_size */
1196 	sizeof (sin_t),		/* ADDR_size */
1197 	0,			/* OPT_size - not initialized here */
1198 	TIDUSZ,			/* TIDU_size */
1199 	T_COTS_ORD,		/* SERV_type */
1200 	TCPS_IDLE,		/* CURRENT_state */
1201 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1202 };
1203 
1204 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1205 	T_INFO_ACK,		/* PRIM_type */
1206 	0,			/* TSDU_size */
1207 	T_INFINITE,		/* ETSDU_size */
1208 	T_INVALID,		/* CDATA_size */
1209 	T_INVALID,		/* DDATA_size */
1210 	sizeof (sin6_t),	/* ADDR_size */
1211 	0,			/* OPT_size - not initialized here */
1212 	TIDUSZ,		/* TIDU_size */
1213 	T_COTS_ORD,		/* SERV_type */
1214 	TCPS_IDLE,		/* CURRENT_state */
1215 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1216 };
1217 
1218 #define	MS	1L
1219 #define	SECONDS	(1000 * MS)
1220 #define	MINUTES	(60 * SECONDS)
1221 #define	HOURS	(60 * MINUTES)
1222 #define	DAYS	(24 * HOURS)
1223 
1224 #define	PARAM_MAX (~(uint32_t)0)
1225 
1226 /* Max size IP datagram is 64k - 1 */
1227 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1228 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1229 /* Max of the above */
1230 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1231 
1232 /* Largest TCP port number */
1233 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1234 
1235 /*
1236  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1237  * layer header.  It has to be a multiple of 4.
1238  */
1239 static tcpparam_t tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1240 #define	tcp_wroff_xtra	tcp_wroff_xtra_param.tcp_param_val
1241 
1242 /*
1243  * All of these are alterable, within the min/max values given, at run time.
1244  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1245  * per the TCP spec.
1246  */
1247 /* BEGIN CSTYLED */
1248 tcpparam_t	tcp_param_arr[] = {
1249  /*min		max		value		name */
1250  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1251  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1252  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1253  { 1,		1024,		1,		"tcp_conn_req_min" },
1254  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1255  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1256  { 0,		10,		0,		"tcp_debug" },
1257  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1258  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1259  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1260  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1261  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1262  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1263  { 1,		255,		64,		"tcp_ipv4_ttl"},
1264  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1265  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1266  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1267  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1268  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1269  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1270  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1271  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1272  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1273  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1274  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1275  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1276  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1277  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1278  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1279  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1280  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1281  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1282  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1283  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1284  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1285  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1286  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1287  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1288 /*
1289  * Question:  What default value should I set for tcp_strong_iss?
1290  */
1291  { 0,		2,		1,		"tcp_strong_iss"},
1292  { 0,		65536,		20,		"tcp_rtt_updates"},
1293  { 0,		1,		1,		"tcp_wscale_always"},
1294  { 0,		1,		0,		"tcp_tstamp_always"},
1295  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1296  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1297  { 0,		16,		2,		"tcp_deferred_acks_max"},
1298  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1299  { 1,		4,		4,		"tcp_slow_start_initial"},
1300  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1301  { 0,		2,		2,		"tcp_sack_permitted"},
1302  { 0,		1,		0,		"tcp_trace"},
1303  { 0,		1,		1,		"tcp_compression_enabled"},
1304  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1305  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1306  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1307  { 0,		1,		0,		"tcp_rev_src_routes"},
1308  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1309  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1310  { 0,		16,		8,		"tcp_local_dacks_max"},
1311  { 0,		2,		1,		"tcp_ecn_permitted"},
1312  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1313  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1314  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1315  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1316  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1317 };
1318 /* END CSTYLED */
1319 
1320 /*
1321  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1322  * each header fragment in the header buffer.  Each parameter value has
1323  * to be a multiple of 4 (32-bit aligned).
1324  */
1325 static tcpparam_t tcp_mdt_head_param = { 32, 256, 32, "tcp_mdt_hdr_head_min" };
1326 static tcpparam_t tcp_mdt_tail_param = { 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1327 #define	tcp_mdt_hdr_head_min	tcp_mdt_head_param.tcp_param_val
1328 #define	tcp_mdt_hdr_tail_min	tcp_mdt_tail_param.tcp_param_val
1329 
1330 /*
1331  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1332  * the maximum number of payload buffers associated per Multidata.
1333  */
1334 static tcpparam_t tcp_mdt_max_pbufs_param =
1335 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1336 #define	tcp_mdt_max_pbufs	tcp_mdt_max_pbufs_param.tcp_param_val
1337 
1338 /* Round up the value to the nearest mss. */
1339 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1340 
1341 /*
1342  * Set ECN capable transport (ECT) code point in IP header.
1343  *
1344  * Note that there are 2 ECT code points '01' and '10', which are called
1345  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1346  * point ECT(0) for TCP as described in RFC 2481.
1347  */
1348 #define	SET_ECT(tcp, iph) \
1349 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1350 		/* We need to clear the code point first. */ \
1351 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1352 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1353 	} else { \
1354 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1355 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1356 	}
1357 
1358 /*
1359  * The format argument to pass to tcp_display().
1360  * DISP_PORT_ONLY means that the returned string has only port info.
1361  * DISP_ADDR_AND_PORT means that the returned string also contains the
1362  * remote and local IP address.
1363  */
1364 #define	DISP_PORT_ONLY		1
1365 #define	DISP_ADDR_AND_PORT	2
1366 
1367 /*
1368  * This controls the rate some ndd info report functions can be used
1369  * by non-privileged users.  It stores the last time such info is
1370  * requested.  When those report functions are called again, this
1371  * is checked with the current time and compare with the ndd param
1372  * tcp_ndd_get_info_interval.
1373  */
1374 static clock_t tcp_last_ndd_get_info_time = 0;
1375 #define	NDD_TOO_QUICK_MSG \
1376 	"ndd get info rate too high for non-privileged users, try again " \
1377 	"later.\n"
1378 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1379 
1380 #define	IS_VMLOANED_MBLK(mp) \
1381 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1382 
1383 /*
1384  * These two variables control the rate for TCP to generate RSTs in
1385  * response to segments not belonging to any connections.  We limit
1386  * TCP to sent out tcp_rst_sent_rate (ndd param) number of RSTs in
1387  * each 1 second interval.  This is to protect TCP against DoS attack.
1388  */
1389 static clock_t tcp_last_rst_intrvl;
1390 static uint32_t tcp_rst_cnt;
1391 
1392 /* The number of RST not sent because of the rate limit. */
1393 static uint32_t tcp_rst_unsent;
1394 
1395 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1396 boolean_t tcp_mdt_chain = B_TRUE;
1397 
1398 /*
1399  * MDT threshold in the form of effective send MSS multiplier; we take
1400  * the MDT path if the amount of unsent data exceeds the threshold value
1401  * (default threshold is 1*SMSS).
1402  */
1403 uint_t tcp_mdt_smss_threshold = 1;
1404 
1405 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1406 
1407 /*
1408  * Forces all connections to obey the value of the tcp_maxpsz_multiplier
1409  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1410  * determined dynamically during tcp_adapt_ire(), which is the default.
1411  */
1412 boolean_t tcp_static_maxpsz = B_FALSE;
1413 
1414 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1415 uint32_t tcp_random_anon_port = 1;
1416 
1417 /*
1418  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1419  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1420  * data, TCP will not respond with an ACK.  RFC 793 requires that
1421  * TCP responds with an ACK for such a bogus ACK.  By not following
1422  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1423  * an attacker successfully spoofs an acceptable segment to our
1424  * peer; or when our peer is "confused."
1425  */
1426 uint32_t tcp_drop_ack_unsent_cnt = 10;
1427 
1428 /*
1429  * Hook functions to enable cluster networking
1430  * On non-clustered systems these vectors must always be NULL.
1431  */
1432 
1433 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1434 			    uint8_t *laddrp, in_port_t lport) = NULL;
1435 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1436 			    uint8_t *laddrp, in_port_t lport) = NULL;
1437 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1438 			    uint8_t *laddrp, in_port_t lport,
1439 			    uint8_t *faddrp, in_port_t fport) = NULL;
1440 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1441 			    uint8_t *laddrp, in_port_t lport,
1442 			    uint8_t *faddrp, in_port_t fport) = NULL;
1443 
1444 /*
1445  * The following are defined in ip.c
1446  */
1447 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1448 				uint8_t *laddrp);
1449 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1450 				uint8_t *laddrp, uint8_t *faddrp);
1451 
1452 #define	CL_INET_CONNECT(tcp)		{			\
1453 	if (cl_inet_connect != NULL) {				\
1454 		/*						\
1455 		 * Running in cluster mode - register active connection	\
1456 		 * information						\
1457 		 */							\
1458 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1459 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1460 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1461 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1462 				    (in_port_t)(tcp)->tcp_lport,	\
1463 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1464 				    (in_port_t)(tcp)->tcp_fport);	\
1465 			}						\
1466 		} else {						\
1467 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1468 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1469 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1470 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1471 				    (in_port_t)(tcp)->tcp_lport,	\
1472 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1473 				    (in_port_t)(tcp)->tcp_fport);	\
1474 			}						\
1475 		}							\
1476 	}								\
1477 }
1478 
1479 #define	CL_INET_DISCONNECT(tcp)	{				\
1480 	if (cl_inet_disconnect != NULL) {				\
1481 		/*							\
1482 		 * Running in cluster mode - deregister active		\
1483 		 * connection information				\
1484 		 */							\
1485 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1486 			if ((tcp)->tcp_ip_src != 0) {			\
1487 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1488 				    AF_INET,				\
1489 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1490 				    (in_port_t)(tcp)->tcp_lport,	\
1491 				    (uint8_t *)				\
1492 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1493 				    (in_port_t)(tcp)->tcp_fport);	\
1494 			}						\
1495 		} else {						\
1496 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1497 			    &(tcp)->tcp_ip_src_v6)) {			\
1498 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1499 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1500 				    (in_port_t)(tcp)->tcp_lport,	\
1501 				    (uint8_t *)				\
1502 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1503 				    (in_port_t)(tcp)->tcp_fport);	\
1504 			}						\
1505 		}							\
1506 	}								\
1507 }
1508 
1509 /*
1510  * Cluster networking hook for traversing current connection list.
1511  * This routine is used to extract the current list of live connections
1512  * which must continue to to be dispatched to this node.
1513  */
1514 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1515 
1516 /*
1517  * Figure out the value of window scale opton.  Note that the rwnd is
1518  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1519  * We cannot find the scale value and then do a round up of tcp_rwnd
1520  * because the scale value may not be correct after that.
1521  *
1522  * Set the compiler flag to make this function inline.
1523  */
1524 static void
1525 tcp_set_ws_value(tcp_t *tcp)
1526 {
1527 	int i;
1528 	uint32_t rwnd = tcp->tcp_rwnd;
1529 
1530 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1531 	    i++, rwnd >>= 1)
1532 		;
1533 	tcp->tcp_rcv_ws = i;
1534 }
1535 
1536 /*
1537  * Remove a connection from the list of detached TIME_WAIT connections.
1538  */
1539 static void
1540 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1541 {
1542 	boolean_t	locked = B_FALSE;
1543 
1544 	if (tcp_time_wait == NULL) {
1545 		tcp_time_wait = *((tcp_squeue_priv_t **)
1546 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1547 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1548 		locked = B_TRUE;
1549 	}
1550 
1551 	if (tcp->tcp_time_wait_expire == 0) {
1552 		ASSERT(tcp->tcp_time_wait_next == NULL);
1553 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1554 		if (locked)
1555 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1556 		return;
1557 	}
1558 	ASSERT(TCP_IS_DETACHED(tcp));
1559 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1560 
1561 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1562 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1563 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1564 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1565 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1566 			    NULL;
1567 		} else {
1568 			tcp_time_wait->tcp_time_wait_tail = NULL;
1569 		}
1570 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1571 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1572 		ASSERT(tcp->tcp_time_wait_next == NULL);
1573 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1574 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1575 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1576 	} else {
1577 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1578 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1579 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1580 		    tcp->tcp_time_wait_next;
1581 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1582 		    tcp->tcp_time_wait_prev;
1583 	}
1584 	tcp->tcp_time_wait_next = NULL;
1585 	tcp->tcp_time_wait_prev = NULL;
1586 	tcp->tcp_time_wait_expire = 0;
1587 
1588 	if (locked)
1589 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1590 }
1591 
1592 /*
1593  * Add a connection to the list of detached TIME_WAIT connections
1594  * and set its time to expire.
1595  */
1596 static void
1597 tcp_time_wait_append(tcp_t *tcp)
1598 {
1599 	tcp_squeue_priv_t *tcp_time_wait =
1600 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1601 		SQPRIVATE_TCP));
1602 
1603 	tcp_timers_stop(tcp);
1604 
1605 	/* Freed above */
1606 	ASSERT(tcp->tcp_timer_tid == 0);
1607 	ASSERT(tcp->tcp_ack_tid == 0);
1608 
1609 	/* must have happened at the time of detaching the tcp */
1610 	ASSERT(tcp->tcp_ptpahn == NULL);
1611 	ASSERT(tcp->tcp_flow_stopped == 0);
1612 	ASSERT(tcp->tcp_time_wait_next == NULL);
1613 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1614 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1615 	ASSERT(tcp->tcp_listener == NULL);
1616 
1617 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1618 	/*
1619 	 * The value computed below in tcp->tcp_time_wait_expire may
1620 	 * appear negative or wrap around. That is ok since our
1621 	 * interest is only in the difference between the current lbolt
1622 	 * value and tcp->tcp_time_wait_expire. But the value should not
1623 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1624 	 * The corresponding comparison in tcp_time_wait_collector() uses
1625 	 * modular arithmetic.
1626 	 */
1627 	tcp->tcp_time_wait_expire +=
1628 	    drv_usectohz(tcp_time_wait_interval * 1000);
1629 	if (tcp->tcp_time_wait_expire == 0)
1630 		tcp->tcp_time_wait_expire = 1;
1631 
1632 	ASSERT(TCP_IS_DETACHED(tcp));
1633 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1634 	ASSERT(tcp->tcp_time_wait_next == NULL);
1635 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1636 	TCP_DBGSTAT(tcp_time_wait);
1637 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1638 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1639 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1640 		tcp_time_wait->tcp_time_wait_head = tcp;
1641 	} else {
1642 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1643 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1644 		    TCPS_TIME_WAIT);
1645 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1646 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1647 	}
1648 	tcp_time_wait->tcp_time_wait_tail = tcp;
1649 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1650 }
1651 
1652 /* ARGSUSED */
1653 void
1654 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1655 {
1656 	conn_t	*connp = (conn_t *)arg;
1657 	tcp_t	*tcp = connp->conn_tcp;
1658 
1659 	ASSERT(tcp != NULL);
1660 	if (tcp->tcp_state == TCPS_CLOSED) {
1661 		return;
1662 	}
1663 
1664 	ASSERT((tcp->tcp_family == AF_INET &&
1665 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1666 	    (tcp->tcp_family == AF_INET6 &&
1667 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1668 	    tcp->tcp_ipversion == IPV6_VERSION)));
1669 	ASSERT(!tcp->tcp_listener);
1670 
1671 	TCP_STAT(tcp_time_wait_reap);
1672 	ASSERT(TCP_IS_DETACHED(tcp));
1673 
1674 	/*
1675 	 * Because they have no upstream client to rebind or tcp_close()
1676 	 * them later, we axe the connection here and now.
1677 	 */
1678 	tcp_close_detached(tcp);
1679 }
1680 
1681 void
1682 tcp_cleanup(tcp_t *tcp)
1683 {
1684 	mblk_t		*mp;
1685 	char		*tcp_iphc;
1686 	int		tcp_iphc_len;
1687 	int		tcp_hdr_grown;
1688 	tcp_sack_info_t	*tcp_sack_info;
1689 	conn_t		*connp = tcp->tcp_connp;
1690 
1691 	tcp_bind_hash_remove(tcp);
1692 	tcp_free(tcp);
1693 
1694 	/* Release any SSL context */
1695 	if (tcp->tcp_kssl_ent != NULL) {
1696 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1697 		tcp->tcp_kssl_ent = NULL;
1698 	}
1699 
1700 	if (tcp->tcp_kssl_ctx != NULL) {
1701 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1702 		tcp->tcp_kssl_ctx = NULL;
1703 	}
1704 	tcp->tcp_kssl_pending = B_FALSE;
1705 
1706 	conn_delete_ire(connp, NULL);
1707 	if (connp->conn_flags & IPCL_TCPCONN) {
1708 		if (connp->conn_latch != NULL)
1709 			IPLATCH_REFRELE(connp->conn_latch);
1710 		if (connp->conn_policy != NULL)
1711 			IPPH_REFRELE(connp->conn_policy);
1712 	}
1713 
1714 	/*
1715 	 * Since we will bzero the entire structure, we need to
1716 	 * remove it and reinsert it in global hash list. We
1717 	 * know the walkers can't get to this conn because we
1718 	 * had set CONDEMNED flag earlier and checked reference
1719 	 * under conn_lock so walker won't pick it and when we
1720 	 * go the ipcl_globalhash_remove() below, no walker
1721 	 * can get to it.
1722 	 */
1723 	ipcl_globalhash_remove(connp);
1724 
1725 	/* Save some state */
1726 	mp = tcp->tcp_timercache;
1727 
1728 	tcp_sack_info = tcp->tcp_sack_info;
1729 	tcp_iphc = tcp->tcp_iphc;
1730 	tcp_iphc_len = tcp->tcp_iphc_len;
1731 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1732 
1733 	if (connp->conn_cred != NULL)
1734 		crfree(connp->conn_cred);
1735 	if (connp->conn_peercred != NULL)
1736 		crfree(connp->conn_peercred);
1737 	bzero(connp, sizeof (conn_t));
1738 	bzero(tcp, sizeof (tcp_t));
1739 
1740 	/* restore the state */
1741 	tcp->tcp_timercache = mp;
1742 
1743 	tcp->tcp_sack_info = tcp_sack_info;
1744 	tcp->tcp_iphc = tcp_iphc;
1745 	tcp->tcp_iphc_len = tcp_iphc_len;
1746 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1747 
1748 
1749 	tcp->tcp_connp = connp;
1750 
1751 	connp->conn_tcp = tcp;
1752 	connp->conn_flags = IPCL_TCPCONN;
1753 	connp->conn_state_flags = CONN_INCIPIENT;
1754 	connp->conn_ulp = IPPROTO_TCP;
1755 	connp->conn_ref = 1;
1756 
1757 	ipcl_globalhash_insert(connp);
1758 }
1759 
1760 /*
1761  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1762  * is done forwards from the head.
1763  */
1764 /* ARGSUSED */
1765 void
1766 tcp_time_wait_collector(void *arg)
1767 {
1768 	tcp_t *tcp;
1769 	clock_t now;
1770 	mblk_t *mp;
1771 	conn_t *connp;
1772 	kmutex_t *lock;
1773 
1774 	squeue_t *sqp = (squeue_t *)arg;
1775 	tcp_squeue_priv_t *tcp_time_wait =
1776 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1777 
1778 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1779 	tcp_time_wait->tcp_time_wait_tid = 0;
1780 
1781 	if (tcp_time_wait->tcp_free_list != NULL &&
1782 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1783 		TCP_STAT(tcp_freelist_cleanup);
1784 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1785 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1786 			CONN_DEC_REF(tcp->tcp_connp);
1787 		}
1788 		tcp_time_wait->tcp_free_list_cnt = 0;
1789 	}
1790 
1791 	/*
1792 	 * In order to reap time waits reliably, we should use a
1793 	 * source of time that is not adjustable by the user -- hence
1794 	 * the call to ddi_get_lbolt().
1795 	 */
1796 	now = ddi_get_lbolt();
1797 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1798 		/*
1799 		 * Compare times using modular arithmetic, since
1800 		 * lbolt can wrapover.
1801 		 */
1802 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1803 			break;
1804 		}
1805 
1806 		tcp_time_wait_remove(tcp, tcp_time_wait);
1807 
1808 		connp = tcp->tcp_connp;
1809 		ASSERT(connp->conn_fanout != NULL);
1810 		lock = &connp->conn_fanout->connf_lock;
1811 		/*
1812 		 * This is essentially a TW reclaim fast path optimization for
1813 		 * performance where the timewait collector checks under the
1814 		 * fanout lock (so that no one else can get access to the
1815 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1816 		 * the classifier hash list. If ref count is indeed 2, we can
1817 		 * just remove the conn under the fanout lock and avoid
1818 		 * cleaning up the conn under the squeue, provided that
1819 		 * clustering callbacks are not enabled. If clustering is
1820 		 * enabled, we need to make the clustering callback before
1821 		 * setting the CONDEMNED flag and after dropping all locks and
1822 		 * so we forego this optimization and fall back to the slow
1823 		 * path. Also please see the comments in tcp_closei_local
1824 		 * regarding the refcnt logic.
1825 		 *
1826 		 * Since we are holding the tcp_time_wait_lock, its better
1827 		 * not to block on the fanout_lock because other connections
1828 		 * can't add themselves to time_wait list. So we do a
1829 		 * tryenter instead of mutex_enter.
1830 		 */
1831 		if (mutex_tryenter(lock)) {
1832 			mutex_enter(&connp->conn_lock);
1833 			if ((connp->conn_ref == 2) &&
1834 			    (cl_inet_disconnect == NULL)) {
1835 				ipcl_hash_remove_locked(connp,
1836 				    connp->conn_fanout);
1837 				/*
1838 				 * Set the CONDEMNED flag now itself so that
1839 				 * the refcnt cannot increase due to any
1840 				 * walker. But we have still not cleaned up
1841 				 * conn_ire_cache. This is still ok since
1842 				 * we are going to clean it up in tcp_cleanup
1843 				 * immediately and any interface unplumb
1844 				 * thread will wait till the ire is blown away
1845 				 */
1846 				connp->conn_state_flags |= CONN_CONDEMNED;
1847 				mutex_exit(lock);
1848 				mutex_exit(&connp->conn_lock);
1849 				if (tcp_time_wait->tcp_free_list_cnt <
1850 				    tcp_free_list_max_cnt) {
1851 					/* Add to head of tcp_free_list */
1852 					mutex_exit(
1853 					    &tcp_time_wait->tcp_time_wait_lock);
1854 					tcp_cleanup(tcp);
1855 					mutex_enter(
1856 					    &tcp_time_wait->tcp_time_wait_lock);
1857 					tcp->tcp_time_wait_next =
1858 					    tcp_time_wait->tcp_free_list;
1859 					tcp_time_wait->tcp_free_list = tcp;
1860 					tcp_time_wait->tcp_free_list_cnt++;
1861 					continue;
1862 				} else {
1863 					/* Do not add to tcp_free_list */
1864 					mutex_exit(
1865 					    &tcp_time_wait->tcp_time_wait_lock);
1866 					tcp_bind_hash_remove(tcp);
1867 					conn_delete_ire(tcp->tcp_connp, NULL);
1868 					CONN_DEC_REF(tcp->tcp_connp);
1869 				}
1870 			} else {
1871 				CONN_INC_REF_LOCKED(connp);
1872 				mutex_exit(lock);
1873 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1874 				mutex_exit(&connp->conn_lock);
1875 				/*
1876 				 * We can reuse the closemp here since conn has
1877 				 * detached (otherwise we wouldn't even be in
1878 				 * time_wait list).
1879 				 */
1880 				mp = &tcp->tcp_closemp;
1881 				squeue_fill(connp->conn_sqp, mp,
1882 				    tcp_timewait_output, connp,
1883 				    SQTAG_TCP_TIMEWAIT);
1884 			}
1885 		} else {
1886 			mutex_enter(&connp->conn_lock);
1887 			CONN_INC_REF_LOCKED(connp);
1888 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1889 			mutex_exit(&connp->conn_lock);
1890 			/*
1891 			 * We can reuse the closemp here since conn has
1892 			 * detached (otherwise we wouldn't even be in
1893 			 * time_wait list).
1894 			 */
1895 			mp = &tcp->tcp_closemp;
1896 			squeue_fill(connp->conn_sqp, mp,
1897 			    tcp_timewait_output, connp, 0);
1898 		}
1899 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1900 	}
1901 
1902 	if (tcp_time_wait->tcp_free_list != NULL)
1903 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1904 
1905 	tcp_time_wait->tcp_time_wait_tid =
1906 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1907 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1908 }
1909 
1910 /*
1911  * Reply to a clients T_CONN_RES TPI message. This function
1912  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1913  * on the acceptor STREAM and processed in tcp_wput_accept().
1914  * Read the block comment on top of tcp_conn_request().
1915  */
1916 static void
1917 tcp_accept(tcp_t *listener, mblk_t *mp)
1918 {
1919 	tcp_t	*acceptor;
1920 	tcp_t	*eager;
1921 	tcp_t   *tcp;
1922 	struct T_conn_res	*tcr;
1923 	t_uscalar_t	acceptor_id;
1924 	t_scalar_t	seqnum;
1925 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1926 	mblk_t	*ok_mp;
1927 	mblk_t	*mp1;
1928 
1929 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1930 		tcp_err_ack(listener, mp, TPROTO, 0);
1931 		return;
1932 	}
1933 	tcr = (struct T_conn_res *)mp->b_rptr;
1934 
1935 	/*
1936 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1937 	 * read side queue of the streams device underneath us i.e. the
1938 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1939 	 * look it up in the queue_hash.  Under LP64 it sends down the
1940 	 * minor_t of the accepting endpoint.
1941 	 *
1942 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1943 	 * fanout hash lock is held.
1944 	 * This prevents any thread from entering the acceptor queue from
1945 	 * below (since it has not been hard bound yet i.e. any inbound
1946 	 * packets will arrive on the listener or default tcp queue and
1947 	 * go through tcp_lookup).
1948 	 * The CONN_INC_REF will prevent the acceptor from closing.
1949 	 *
1950 	 * XXX It is still possible for a tli application to send down data
1951 	 * on the accepting stream while another thread calls t_accept.
1952 	 * This should not be a problem for well-behaved applications since
1953 	 * the T_OK_ACK is sent after the queue swapping is completed.
1954 	 *
1955 	 * If the accepting fd is the same as the listening fd, avoid
1956 	 * queue hash lookup since that will return an eager listener in a
1957 	 * already established state.
1958 	 */
1959 	acceptor_id = tcr->ACCEPTOR_id;
1960 	mutex_enter(&listener->tcp_eager_lock);
1961 	if (listener->tcp_acceptor_id == acceptor_id) {
1962 		eager = listener->tcp_eager_next_q;
1963 		/* only count how many T_CONN_INDs so don't count q0 */
1964 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1965 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1966 			mutex_exit(&listener->tcp_eager_lock);
1967 			tcp_err_ack(listener, mp, TBADF, 0);
1968 			return;
1969 		}
1970 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1971 			/* Throw away all the eagers on q0. */
1972 			tcp_eager_cleanup(listener, 1);
1973 		}
1974 		if (listener->tcp_syn_defense) {
1975 			listener->tcp_syn_defense = B_FALSE;
1976 			if (listener->tcp_ip_addr_cache != NULL) {
1977 				kmem_free(listener->tcp_ip_addr_cache,
1978 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1979 				listener->tcp_ip_addr_cache = NULL;
1980 			}
1981 		}
1982 		/*
1983 		 * Transfer tcp_conn_req_max to the eager so that when
1984 		 * a disconnect occurs we can revert the endpoint to the
1985 		 * listen state.
1986 		 */
1987 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1988 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1989 		/*
1990 		 * Get a reference on the acceptor just like the
1991 		 * tcp_acceptor_hash_lookup below.
1992 		 */
1993 		acceptor = listener;
1994 		CONN_INC_REF(acceptor->tcp_connp);
1995 	} else {
1996 		acceptor = tcp_acceptor_hash_lookup(acceptor_id);
1997 		if (acceptor == NULL) {
1998 			if (listener->tcp_debug) {
1999 				(void) strlog(TCP_MOD_ID, 0, 1,
2000 				    SL_ERROR|SL_TRACE,
2001 				    "tcp_accept: did not find acceptor 0x%x\n",
2002 				    acceptor_id);
2003 			}
2004 			mutex_exit(&listener->tcp_eager_lock);
2005 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2006 			return;
2007 		}
2008 		/*
2009 		 * Verify acceptor state. The acceptable states for an acceptor
2010 		 * include TCPS_IDLE and TCPS_BOUND.
2011 		 */
2012 		switch (acceptor->tcp_state) {
2013 		case TCPS_IDLE:
2014 			/* FALLTHRU */
2015 		case TCPS_BOUND:
2016 			break;
2017 		default:
2018 			CONN_DEC_REF(acceptor->tcp_connp);
2019 			mutex_exit(&listener->tcp_eager_lock);
2020 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2021 			return;
2022 		}
2023 	}
2024 
2025 	/* The listener must be in TCPS_LISTEN */
2026 	if (listener->tcp_state != TCPS_LISTEN) {
2027 		CONN_DEC_REF(acceptor->tcp_connp);
2028 		mutex_exit(&listener->tcp_eager_lock);
2029 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2030 		return;
2031 	}
2032 
2033 	/*
2034 	 * Rendezvous with an eager connection request packet hanging off
2035 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2036 	 * tcp structure when the connection packet arrived in
2037 	 * tcp_conn_request().
2038 	 */
2039 	seqnum = tcr->SEQ_number;
2040 	eager = listener;
2041 	do {
2042 		eager = eager->tcp_eager_next_q;
2043 		if (eager == NULL) {
2044 			CONN_DEC_REF(acceptor->tcp_connp);
2045 			mutex_exit(&listener->tcp_eager_lock);
2046 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2047 			return;
2048 		}
2049 	} while (eager->tcp_conn_req_seqnum != seqnum);
2050 	mutex_exit(&listener->tcp_eager_lock);
2051 
2052 	/*
2053 	 * At this point, both acceptor and listener have 2 ref
2054 	 * that they begin with. Acceptor has one additional ref
2055 	 * we placed in lookup while listener has 3 additional
2056 	 * ref for being behind the squeue (tcp_accept() is
2057 	 * done on listener's squeue); being in classifier hash;
2058 	 * and eager's ref on listener.
2059 	 */
2060 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2061 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2062 
2063 	/*
2064 	 * The eager at this point is set in its own squeue and
2065 	 * could easily have been killed (tcp_accept_finish will
2066 	 * deal with that) because of a TH_RST so we can only
2067 	 * ASSERT for a single ref.
2068 	 */
2069 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2070 
2071 	/* Pre allocate the stroptions mblk also */
2072 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2073 	if (opt_mp == NULL) {
2074 		CONN_DEC_REF(acceptor->tcp_connp);
2075 		CONN_DEC_REF(eager->tcp_connp);
2076 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2077 		return;
2078 	}
2079 	DB_TYPE(opt_mp) = M_SETOPTS;
2080 	opt_mp->b_wptr += sizeof (struct stroptions);
2081 
2082 	/*
2083 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2084 	 * from listener to acceptor. The message is chained on opt_mp
2085 	 * which will be sent onto eager's squeue.
2086 	 */
2087 	if (listener->tcp_bound_if != 0) {
2088 		/* allocate optmgmt req */
2089 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2090 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2091 		    sizeof (int));
2092 		if (mp1 != NULL)
2093 			linkb(opt_mp, mp1);
2094 	}
2095 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2096 		uint_t on = 1;
2097 
2098 		/* allocate optmgmt req */
2099 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2100 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2101 		if (mp1 != NULL)
2102 			linkb(opt_mp, mp1);
2103 	}
2104 
2105 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2106 	if ((mp1 = copymsg(mp)) == NULL) {
2107 		CONN_DEC_REF(acceptor->tcp_connp);
2108 		CONN_DEC_REF(eager->tcp_connp);
2109 		freemsg(opt_mp);
2110 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2111 		return;
2112 	}
2113 
2114 	tcr = (struct T_conn_res *)mp1->b_rptr;
2115 
2116 	/*
2117 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2118 	 * which allocates a larger mblk and appends the new
2119 	 * local address to the ok_ack.  The address is copied by
2120 	 * soaccept() for getsockname().
2121 	 */
2122 	{
2123 		int extra;
2124 
2125 		extra = (eager->tcp_family == AF_INET) ?
2126 		    sizeof (sin_t) : sizeof (sin6_t);
2127 
2128 		/*
2129 		 * Try to re-use mp, if possible.  Otherwise, allocate
2130 		 * an mblk and return it as ok_mp.  In any case, mp
2131 		 * is no longer usable upon return.
2132 		 */
2133 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2134 			CONN_DEC_REF(acceptor->tcp_connp);
2135 			CONN_DEC_REF(eager->tcp_connp);
2136 			freemsg(opt_mp);
2137 			/* Original mp has been freed by now, so use mp1 */
2138 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2139 			return;
2140 		}
2141 
2142 		mp = NULL;	/* We should never use mp after this point */
2143 
2144 		switch (extra) {
2145 		case sizeof (sin_t): {
2146 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2147 
2148 				ok_mp->b_wptr += extra;
2149 				sin->sin_family = AF_INET;
2150 				sin->sin_port = eager->tcp_lport;
2151 				sin->sin_addr.s_addr =
2152 				    eager->tcp_ipha->ipha_src;
2153 				break;
2154 			}
2155 		case sizeof (sin6_t): {
2156 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2157 
2158 				ok_mp->b_wptr += extra;
2159 				sin6->sin6_family = AF_INET6;
2160 				sin6->sin6_port = eager->tcp_lport;
2161 				if (eager->tcp_ipversion == IPV4_VERSION) {
2162 					sin6->sin6_flowinfo = 0;
2163 					IN6_IPADDR_TO_V4MAPPED(
2164 					    eager->tcp_ipha->ipha_src,
2165 					    &sin6->sin6_addr);
2166 				} else {
2167 					ASSERT(eager->tcp_ip6h != NULL);
2168 					sin6->sin6_flowinfo =
2169 					    eager->tcp_ip6h->ip6_vcf &
2170 					    ~IPV6_VERS_AND_FLOW_MASK;
2171 					sin6->sin6_addr =
2172 					    eager->tcp_ip6h->ip6_src;
2173 				}
2174 				break;
2175 			}
2176 		default:
2177 			break;
2178 		}
2179 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2180 	}
2181 
2182 	/*
2183 	 * If there are no options we know that the T_CONN_RES will
2184 	 * succeed. However, we can't send the T_OK_ACK upstream until
2185 	 * the tcp_accept_swap is done since it would be dangerous to
2186 	 * let the application start using the new fd prior to the swap.
2187 	 */
2188 	tcp_accept_swap(listener, acceptor, eager);
2189 
2190 	/*
2191 	 * tcp_accept_swap unlinks eager from listener but does not drop
2192 	 * the eager's reference on the listener.
2193 	 */
2194 	ASSERT(eager->tcp_listener == NULL);
2195 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2196 
2197 	/*
2198 	 * The eager is now associated with its own queue. Insert in
2199 	 * the hash so that the connection can be reused for a future
2200 	 * T_CONN_RES.
2201 	 */
2202 	tcp_acceptor_hash_insert(acceptor_id, eager);
2203 
2204 	/*
2205 	 * We now do the processing of options with T_CONN_RES.
2206 	 * We delay till now since we wanted to have queue to pass to
2207 	 * option processing routines that points back to the right
2208 	 * instance structure which does not happen until after
2209 	 * tcp_accept_swap().
2210 	 *
2211 	 * Note:
2212 	 * The sanity of the logic here assumes that whatever options
2213 	 * are appropriate to inherit from listner=>eager are done
2214 	 * before this point, and whatever were to be overridden (or not)
2215 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2216 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2217 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2218 	 * This may not be true at this point in time but can be fixed
2219 	 * independently. This option processing code starts with
2220 	 * the instantiated acceptor instance and the final queue at
2221 	 * this point.
2222 	 */
2223 
2224 	if (tcr->OPT_length != 0) {
2225 		/* Options to process */
2226 		int t_error = 0;
2227 		int sys_error = 0;
2228 		int do_disconnect = 0;
2229 
2230 		if (tcp_conprim_opt_process(eager, mp1,
2231 		    &do_disconnect, &t_error, &sys_error) < 0) {
2232 			eager->tcp_accept_error = 1;
2233 			if (do_disconnect) {
2234 				/*
2235 				 * An option failed which does not allow
2236 				 * connection to be accepted.
2237 				 *
2238 				 * We allow T_CONN_RES to succeed and
2239 				 * put a T_DISCON_IND on the eager queue.
2240 				 */
2241 				ASSERT(t_error == 0 && sys_error == 0);
2242 				eager->tcp_send_discon_ind = 1;
2243 			} else {
2244 				ASSERT(t_error != 0);
2245 				freemsg(ok_mp);
2246 				/*
2247 				 * Original mp was either freed or set
2248 				 * to ok_mp above, so use mp1 instead.
2249 				 */
2250 				tcp_err_ack(listener, mp1, t_error, sys_error);
2251 				goto finish;
2252 			}
2253 		}
2254 		/*
2255 		 * Most likely success in setting options (except if
2256 		 * eager->tcp_send_discon_ind set).
2257 		 * mp1 option buffer represented by OPT_length/offset
2258 		 * potentially modified and contains results of setting
2259 		 * options at this point
2260 		 */
2261 	}
2262 
2263 	/* We no longer need mp1, since all options processing has passed */
2264 	freemsg(mp1);
2265 
2266 	putnext(listener->tcp_rq, ok_mp);
2267 
2268 	mutex_enter(&listener->tcp_eager_lock);
2269 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2270 		tcp_t	*tail;
2271 		mblk_t	*conn_ind;
2272 
2273 		/*
2274 		 * This path should not be executed if listener and
2275 		 * acceptor streams are the same.
2276 		 */
2277 		ASSERT(listener != acceptor);
2278 
2279 		tcp = listener->tcp_eager_prev_q0;
2280 		/*
2281 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2282 		 * deferred T_conn_ind queue. We need to get to the head of
2283 		 * the queue in order to send up T_conn_ind the same order as
2284 		 * how the 3WHS is completed.
2285 		 */
2286 		while (tcp != listener) {
2287 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2288 				break;
2289 			else
2290 				tcp = tcp->tcp_eager_prev_q0;
2291 		}
2292 		ASSERT(tcp != listener);
2293 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2294 		ASSERT(conn_ind != NULL);
2295 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2296 
2297 		/* Move from q0 to q */
2298 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2299 		listener->tcp_conn_req_cnt_q0--;
2300 		listener->tcp_conn_req_cnt_q++;
2301 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2302 		    tcp->tcp_eager_prev_q0;
2303 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2304 		    tcp->tcp_eager_next_q0;
2305 		tcp->tcp_eager_prev_q0 = NULL;
2306 		tcp->tcp_eager_next_q0 = NULL;
2307 		tcp->tcp_conn_def_q0 = B_FALSE;
2308 
2309 		/*
2310 		 * Insert at end of the queue because sockfs sends
2311 		 * down T_CONN_RES in chronological order. Leaving
2312 		 * the older conn indications at front of the queue
2313 		 * helps reducing search time.
2314 		 */
2315 		tail = listener->tcp_eager_last_q;
2316 		if (tail != NULL)
2317 			tail->tcp_eager_next_q = tcp;
2318 		else
2319 			listener->tcp_eager_next_q = tcp;
2320 		listener->tcp_eager_last_q = tcp;
2321 		tcp->tcp_eager_next_q = NULL;
2322 		mutex_exit(&listener->tcp_eager_lock);
2323 		putnext(tcp->tcp_rq, conn_ind);
2324 	} else {
2325 		mutex_exit(&listener->tcp_eager_lock);
2326 	}
2327 
2328 	/*
2329 	 * Done with the acceptor - free it
2330 	 *
2331 	 * Note: from this point on, no access to listener should be made
2332 	 * as listener can be equal to acceptor.
2333 	 */
2334 finish:
2335 	ASSERT(acceptor->tcp_detached);
2336 	acceptor->tcp_rq = tcp_g_q;
2337 	acceptor->tcp_wq = WR(tcp_g_q);
2338 	(void) tcp_clean_death(acceptor, 0, 2);
2339 	CONN_DEC_REF(acceptor->tcp_connp);
2340 
2341 	/*
2342 	 * In case we already received a FIN we have to make tcp_rput send
2343 	 * the ordrel_ind. This will also send up a window update if the window
2344 	 * has opened up.
2345 	 *
2346 	 * In the normal case of a successful connection acceptance
2347 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2348 	 * indication that this was just accepted. This tells tcp_rput to
2349 	 * pass up any data queued in tcp_rcv_list.
2350 	 *
2351 	 * In the fringe case where options sent with T_CONN_RES failed and
2352 	 * we required, we would be indicating a T_DISCON_IND to blow
2353 	 * away this connection.
2354 	 */
2355 
2356 	/*
2357 	 * XXX: we currently have a problem if XTI application closes the
2358 	 * acceptor stream in between. This problem exists in on10-gate also
2359 	 * and is well know but nothing can be done short of major rewrite
2360 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2361 	 * eager same squeue as listener (we can distinguish non socket
2362 	 * listeners at the time of handling a SYN in tcp_conn_request)
2363 	 * and do most of the work that tcp_accept_finish does here itself
2364 	 * and then get behind the acceptor squeue to access the acceptor
2365 	 * queue.
2366 	 */
2367 	/*
2368 	 * We already have a ref on tcp so no need to do one before squeue_fill
2369 	 */
2370 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2371 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2372 }
2373 
2374 /*
2375  * Swap information between the eager and acceptor for a TLI/XTI client.
2376  * The sockfs accept is done on the acceptor stream and control goes
2377  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2378  * called. In either case, both the eager and listener are in their own
2379  * perimeter (squeue) and the code has to deal with potential race.
2380  *
2381  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2382  */
2383 static void
2384 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2385 {
2386 	conn_t	*econnp, *aconnp;
2387 
2388 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2389 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2390 	ASSERT(!eager->tcp_hard_bound);
2391 	ASSERT(!TCP_IS_SOCKET(acceptor));
2392 	ASSERT(!TCP_IS_SOCKET(eager));
2393 	ASSERT(!TCP_IS_SOCKET(listener));
2394 
2395 	acceptor->tcp_detached = B_TRUE;
2396 	/*
2397 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2398 	 * the acceptor id.
2399 	 */
2400 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2401 
2402 	/* remove eager from listen list... */
2403 	mutex_enter(&listener->tcp_eager_lock);
2404 	tcp_eager_unlink(eager);
2405 	ASSERT(eager->tcp_eager_next_q == NULL &&
2406 	    eager->tcp_eager_last_q == NULL);
2407 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2408 	    eager->tcp_eager_prev_q0 == NULL);
2409 	mutex_exit(&listener->tcp_eager_lock);
2410 	eager->tcp_rq = acceptor->tcp_rq;
2411 	eager->tcp_wq = acceptor->tcp_wq;
2412 
2413 	econnp = eager->tcp_connp;
2414 	aconnp = acceptor->tcp_connp;
2415 
2416 	eager->tcp_rq->q_ptr = econnp;
2417 	eager->tcp_wq->q_ptr = econnp;
2418 
2419 	/*
2420 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2421 	 * which might be a different squeue from our peer TCP instance.
2422 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2423 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2424 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2425 	 * above reach global visibility prior to the clearing of tcp_detached.
2426 	 */
2427 	membar_producer();
2428 	eager->tcp_detached = B_FALSE;
2429 
2430 	ASSERT(eager->tcp_ack_tid == 0);
2431 
2432 	econnp->conn_dev = aconnp->conn_dev;
2433 	if (eager->tcp_cred != NULL)
2434 		crfree(eager->tcp_cred);
2435 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2436 	aconnp->conn_cred = NULL;
2437 
2438 	econnp->conn_zoneid = aconnp->conn_zoneid;
2439 	econnp->conn_allzones = aconnp->conn_allzones;
2440 
2441 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2442 	aconnp->conn_mac_exempt = B_FALSE;
2443 
2444 	ASSERT(aconnp->conn_peercred == NULL);
2445 
2446 	/* Do the IPC initialization */
2447 	CONN_INC_REF(econnp);
2448 
2449 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2450 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2451 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2452 	econnp->conn_ulp = aconnp->conn_ulp;
2453 
2454 	/* Done with old IPC. Drop its ref on its connp */
2455 	CONN_DEC_REF(aconnp);
2456 }
2457 
2458 
2459 /*
2460  * Adapt to the information, such as rtt and rtt_sd, provided from the
2461  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2462  *
2463  * Checks for multicast and broadcast destination address.
2464  * Returns zero on failure; non-zero if ok.
2465  *
2466  * Note that the MSS calculation here is based on the info given in
2467  * the IRE.  We do not do any calculation based on TCP options.  They
2468  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2469  * knows which options to use.
2470  *
2471  * Note on how TCP gets its parameters for a connection.
2472  *
2473  * When a tcp_t structure is allocated, it gets all the default parameters.
2474  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2475  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2476  * default.  But if there is an associated tcp_host_param, it will override
2477  * the metrics.
2478  *
2479  * An incoming SYN with a multicast or broadcast destination address, is dropped
2480  * in 1 of 2 places.
2481  *
2482  * 1. If the packet was received over the wire it is dropped in
2483  * ip_rput_process_broadcast()
2484  *
2485  * 2. If the packet was received through internal IP loopback, i.e. the packet
2486  * was generated and received on the same machine, it is dropped in
2487  * ip_wput_local()
2488  *
2489  * An incoming SYN with a multicast or broadcast source address is always
2490  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2491  * reject an attempt to connect to a broadcast or multicast (destination)
2492  * address.
2493  */
2494 static int
2495 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2496 {
2497 	tcp_hsp_t	*hsp;
2498 	ire_t		*ire;
2499 	ire_t		*sire = NULL;
2500 	iulp_t		*ire_uinfo = NULL;
2501 	uint32_t	mss_max;
2502 	uint32_t	mss;
2503 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2504 	conn_t		*connp = tcp->tcp_connp;
2505 	boolean_t	ire_cacheable = B_FALSE;
2506 	zoneid_t	zoneid = connp->conn_zoneid;
2507 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2508 			    MATCH_IRE_SECATTR;
2509 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2510 	ill_t		*ill = NULL;
2511 	boolean_t	incoming = (ire_mp == NULL);
2512 
2513 	ASSERT(connp->conn_ire_cache == NULL);
2514 
2515 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2516 
2517 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2518 			BUMP_MIB(&ip_mib, ipInDiscards);
2519 			return (0);
2520 		}
2521 		/*
2522 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2523 		 * for the destination with the nexthop as gateway.
2524 		 * ire_ctable_lookup() is used because this particular
2525 		 * ire, if it exists, will be marked private.
2526 		 * If that is not available, use the interface ire
2527 		 * for the nexthop.
2528 		 *
2529 		 * TSol: tcp_update_label will detect label mismatches based
2530 		 * only on the destination's label, but that would not
2531 		 * detect label mismatches based on the security attributes
2532 		 * of routes or next hop gateway. Hence we need to pass the
2533 		 * label to ire_ftable_lookup below in order to locate the
2534 		 * right prefix (and/or) ire cache. Similarly we also need
2535 		 * pass the label to the ire_cache_lookup below to locate
2536 		 * the right ire that also matches on the label.
2537 		 */
2538 		if (tcp->tcp_connp->conn_nexthop_set) {
2539 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2540 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2541 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2542 			if (ire == NULL) {
2543 				ire = ire_ftable_lookup(
2544 				    tcp->tcp_connp->conn_nexthop_v4,
2545 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2546 				    tsl, match_flags);
2547 				if (ire == NULL)
2548 					return (0);
2549 			} else {
2550 				ire_uinfo = &ire->ire_uinfo;
2551 			}
2552 		} else {
2553 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2554 			    zoneid, tsl);
2555 			if (ire != NULL) {
2556 				ire_cacheable = B_TRUE;
2557 				ire_uinfo = (ire_mp != NULL) ?
2558 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2559 				    &ire->ire_uinfo;
2560 
2561 			} else {
2562 				if (ire_mp == NULL) {
2563 					ire = ire_ftable_lookup(
2564 					    tcp->tcp_connp->conn_rem,
2565 					    0, 0, 0, NULL, &sire, zoneid, 0,
2566 					    tsl, (MATCH_IRE_RECURSIVE |
2567 					    MATCH_IRE_DEFAULT));
2568 					if (ire == NULL)
2569 						return (0);
2570 					ire_uinfo = (sire != NULL) ?
2571 					    &sire->ire_uinfo :
2572 					    &ire->ire_uinfo;
2573 				} else {
2574 					ire = (ire_t *)ire_mp->b_rptr;
2575 					ire_uinfo =
2576 					    &((ire_t *)
2577 					    ire_mp->b_rptr)->ire_uinfo;
2578 				}
2579 			}
2580 		}
2581 		ASSERT(ire != NULL);
2582 
2583 		if ((ire->ire_src_addr == INADDR_ANY) ||
2584 		    (ire->ire_type & IRE_BROADCAST)) {
2585 			/*
2586 			 * ire->ire_mp is non null when ire_mp passed in is used
2587 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2588 			 */
2589 			if (ire->ire_mp == NULL)
2590 				ire_refrele(ire);
2591 			if (sire != NULL)
2592 				ire_refrele(sire);
2593 			return (0);
2594 		}
2595 
2596 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2597 			ipaddr_t src_addr;
2598 
2599 			/*
2600 			 * ip_bind_connected() has stored the correct source
2601 			 * address in conn_src.
2602 			 */
2603 			src_addr = tcp->tcp_connp->conn_src;
2604 			tcp->tcp_ipha->ipha_src = src_addr;
2605 			/*
2606 			 * Copy of the src addr. in tcp_t is needed
2607 			 * for the lookup funcs.
2608 			 */
2609 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2610 		}
2611 		/*
2612 		 * Set the fragment bit so that IP will tell us if the MTU
2613 		 * should change. IP tells us the latest setting of
2614 		 * ip_path_mtu_discovery through ire_frag_flag.
2615 		 */
2616 		if (ip_path_mtu_discovery) {
2617 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2618 			    htons(IPH_DF);
2619 		}
2620 		/*
2621 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2622 		 * for IP_NEXTHOP. No cache ire has been found for the
2623 		 * destination and we are working with the nexthop's
2624 		 * interface ire. Since we need to forward all packets
2625 		 * to the nexthop first, we "blindly" set tcp_localnet
2626 		 * to false, eventhough the destination may also be
2627 		 * onlink.
2628 		 */
2629 		if (ire_uinfo == NULL)
2630 			tcp->tcp_localnet = 0;
2631 		else
2632 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2633 	} else {
2634 		/*
2635 		 * For incoming connection ire_mp = NULL
2636 		 * For outgoing connection ire_mp != NULL
2637 		 * Technically we should check conn_incoming_ill
2638 		 * when ire_mp is NULL and conn_outgoing_ill when
2639 		 * ire_mp is non-NULL. But this is performance
2640 		 * critical path and for IPV*_BOUND_IF, outgoing
2641 		 * and incoming ill are always set to the same value.
2642 		 */
2643 		ill_t	*dst_ill = NULL;
2644 		ipif_t  *dst_ipif = NULL;
2645 
2646 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2647 
2648 		if (connp->conn_outgoing_ill != NULL) {
2649 			/* Outgoing or incoming path */
2650 			int   err;
2651 
2652 			dst_ill = conn_get_held_ill(connp,
2653 			    &connp->conn_outgoing_ill, &err);
2654 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2655 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2656 				return (0);
2657 			}
2658 			match_flags |= MATCH_IRE_ILL;
2659 			dst_ipif = dst_ill->ill_ipif;
2660 		}
2661 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2662 		    0, 0, dst_ipif, zoneid, tsl, match_flags);
2663 
2664 		if (ire != NULL) {
2665 			ire_cacheable = B_TRUE;
2666 			ire_uinfo = (ire_mp != NULL) ?
2667 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2668 			    &ire->ire_uinfo;
2669 		} else {
2670 			if (ire_mp == NULL) {
2671 				ire = ire_ftable_lookup_v6(
2672 				    &tcp->tcp_connp->conn_remv6,
2673 				    0, 0, 0, dst_ipif, &sire, zoneid,
2674 				    0, tsl, match_flags);
2675 				if (ire == NULL) {
2676 					if (dst_ill != NULL)
2677 						ill_refrele(dst_ill);
2678 					return (0);
2679 				}
2680 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2681 				    &ire->ire_uinfo;
2682 			} else {
2683 				ire = (ire_t *)ire_mp->b_rptr;
2684 				ire_uinfo =
2685 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2686 			}
2687 		}
2688 		if (dst_ill != NULL)
2689 			ill_refrele(dst_ill);
2690 
2691 		ASSERT(ire != NULL);
2692 		ASSERT(ire_uinfo != NULL);
2693 
2694 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2695 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2696 			/*
2697 			 * ire->ire_mp is non null when ire_mp passed in is used
2698 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2699 			 */
2700 			if (ire->ire_mp == NULL)
2701 				ire_refrele(ire);
2702 			if (sire != NULL)
2703 				ire_refrele(sire);
2704 			return (0);
2705 		}
2706 
2707 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2708 			in6_addr_t	src_addr;
2709 
2710 			/*
2711 			 * ip_bind_connected_v6() has stored the correct source
2712 			 * address per IPv6 addr. selection policy in
2713 			 * conn_src_v6.
2714 			 */
2715 			src_addr = tcp->tcp_connp->conn_srcv6;
2716 
2717 			tcp->tcp_ip6h->ip6_src = src_addr;
2718 			/*
2719 			 * Copy of the src addr. in tcp_t is needed
2720 			 * for the lookup funcs.
2721 			 */
2722 			tcp->tcp_ip_src_v6 = src_addr;
2723 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2724 			    &connp->conn_srcv6));
2725 		}
2726 		tcp->tcp_localnet =
2727 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2728 	}
2729 
2730 	/*
2731 	 * This allows applications to fail quickly when connections are made
2732 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2733 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2734 	 */
2735 	if ((ire->ire_flags & RTF_REJECT) &&
2736 	    (ire->ire_flags & RTF_PRIVATE))
2737 		goto error;
2738 
2739 	/*
2740 	 * Make use of the cached rtt and rtt_sd values to calculate the
2741 	 * initial RTO.  Note that they are already initialized in
2742 	 * tcp_init_values().
2743 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2744 	 * IP_NEXTHOP, but instead are using the interface ire for the
2745 	 * nexthop, then we do not use the ire_uinfo from that ire to
2746 	 * do any initializations.
2747 	 */
2748 	if (ire_uinfo != NULL) {
2749 		if (ire_uinfo->iulp_rtt != 0) {
2750 			clock_t	rto;
2751 
2752 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2753 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2754 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2755 			    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
2756 
2757 			if (rto > tcp_rexmit_interval_max) {
2758 				tcp->tcp_rto = tcp_rexmit_interval_max;
2759 			} else if (rto < tcp_rexmit_interval_min) {
2760 				tcp->tcp_rto = tcp_rexmit_interval_min;
2761 			} else {
2762 				tcp->tcp_rto = rto;
2763 			}
2764 		}
2765 		if (ire_uinfo->iulp_ssthresh != 0)
2766 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2767 		else
2768 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2769 		if (ire_uinfo->iulp_spipe > 0) {
2770 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2771 			    tcp_max_buf);
2772 			if (tcp_snd_lowat_fraction != 0)
2773 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2774 				    tcp_snd_lowat_fraction;
2775 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2776 		}
2777 		/*
2778 		 * Note that up till now, acceptor always inherits receive
2779 		 * window from the listener.  But if there is a metrics
2780 		 * associated with a host, we should use that instead of
2781 		 * inheriting it from listener. Thus we need to pass this
2782 		 * info back to the caller.
2783 		 */
2784 		if (ire_uinfo->iulp_rpipe > 0) {
2785 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
2786 		}
2787 
2788 		if (ire_uinfo->iulp_rtomax > 0) {
2789 			tcp->tcp_second_timer_threshold =
2790 			    ire_uinfo->iulp_rtomax;
2791 		}
2792 
2793 		/*
2794 		 * Use the metric option settings, iulp_tstamp_ok and
2795 		 * iulp_wscale_ok, only for active open. What this means
2796 		 * is that if the other side uses timestamp or window
2797 		 * scale option, TCP will also use those options. That
2798 		 * is for passive open.  If the application sets a
2799 		 * large window, window scale is enabled regardless of
2800 		 * the value in iulp_wscale_ok.  This is the behavior
2801 		 * since 2.6.  So we keep it.
2802 		 * The only case left in passive open processing is the
2803 		 * check for SACK.
2804 		 * For ECN, it should probably be like SACK.  But the
2805 		 * current value is binary, so we treat it like the other
2806 		 * cases.  The metric only controls active open.For passive
2807 		 * open, the ndd param, tcp_ecn_permitted, controls the
2808 		 * behavior.
2809 		 */
2810 		if (!tcp_detached) {
2811 			/*
2812 			 * The if check means that the following can only
2813 			 * be turned on by the metrics only IRE, but not off.
2814 			 */
2815 			if (ire_uinfo->iulp_tstamp_ok)
2816 				tcp->tcp_snd_ts_ok = B_TRUE;
2817 			if (ire_uinfo->iulp_wscale_ok)
2818 				tcp->tcp_snd_ws_ok = B_TRUE;
2819 			if (ire_uinfo->iulp_sack == 2)
2820 				tcp->tcp_snd_sack_ok = B_TRUE;
2821 			if (ire_uinfo->iulp_ecn_ok)
2822 				tcp->tcp_ecn_ok = B_TRUE;
2823 		} else {
2824 			/*
2825 			 * Passive open.
2826 			 *
2827 			 * As above, the if check means that SACK can only be
2828 			 * turned on by the metric only IRE.
2829 			 */
2830 			if (ire_uinfo->iulp_sack > 0) {
2831 				tcp->tcp_snd_sack_ok = B_TRUE;
2832 			}
2833 		}
2834 	}
2835 
2836 
2837 	/*
2838 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2839 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2840 	 * length of all those options exceeds 28 bytes.  But because
2841 	 * of the tcp_mss_min check below, we may not have a problem if
2842 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2843 	 * the negative problem still exists.  And the check defeats PMTUd.
2844 	 * In fact, if PMTUd finds that the MSS should be smaller than
2845 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2846 	 * value.
2847 	 *
2848 	 * We do not deal with that now.  All those problems related to
2849 	 * PMTUd will be fixed later.
2850 	 */
2851 	ASSERT(ire->ire_max_frag != 0);
2852 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2853 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2854 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2855 			mss = MIN(mss, IPV6_MIN_MTU);
2856 		}
2857 	}
2858 
2859 	/* Sanity check for MSS value. */
2860 	if (tcp->tcp_ipversion == IPV4_VERSION)
2861 		mss_max = tcp_mss_max_ipv4;
2862 	else
2863 		mss_max = tcp_mss_max_ipv6;
2864 
2865 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2866 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2867 		/*
2868 		 * After receiving an ICMPv6 "packet too big" message with a
2869 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2870 		 * will insert a 8-byte fragment header in every packet; we
2871 		 * reduce the MSS by that amount here.
2872 		 */
2873 		mss -= sizeof (ip6_frag_t);
2874 	}
2875 
2876 	if (tcp->tcp_ipsec_overhead == 0)
2877 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2878 
2879 	mss -= tcp->tcp_ipsec_overhead;
2880 
2881 	if (mss < tcp_mss_min)
2882 		mss = tcp_mss_min;
2883 	if (mss > mss_max)
2884 		mss = mss_max;
2885 
2886 	/* Note that this is the maximum MSS, excluding all options. */
2887 	tcp->tcp_mss = mss;
2888 
2889 	/*
2890 	 * Initialize the ISS here now that we have the full connection ID.
2891 	 * The RFC 1948 method of initial sequence number generation requires
2892 	 * knowledge of the full connection ID before setting the ISS.
2893 	 */
2894 
2895 	tcp_iss_init(tcp);
2896 
2897 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2898 		tcp->tcp_loopback = B_TRUE;
2899 
2900 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2901 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
2902 	} else {
2903 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
2904 	}
2905 
2906 	if (hsp != NULL) {
2907 		/* Only modify if we're going to make them bigger */
2908 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2909 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2910 			if (tcp_snd_lowat_fraction != 0)
2911 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2912 					tcp_snd_lowat_fraction;
2913 		}
2914 
2915 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2916 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2917 		}
2918 
2919 		/* Copy timestamp flag only for active open */
2920 		if (!tcp_detached)
2921 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2922 	}
2923 
2924 	if (sire != NULL)
2925 		IRE_REFRELE(sire);
2926 
2927 	/*
2928 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2929 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2930 	 */
2931 	if (tcp->tcp_loopback ||
2932 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2933 		/*
2934 		 * For incoming, see if this tcp may be MDT-capable.  For
2935 		 * outgoing, this process has been taken care of through
2936 		 * tcp_rput_other.
2937 		 */
2938 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2939 		tcp->tcp_ire_ill_check_done = B_TRUE;
2940 	}
2941 
2942 	mutex_enter(&connp->conn_lock);
2943 	/*
2944 	 * Make sure that conn is not marked incipient
2945 	 * for incoming connections. A blind
2946 	 * removal of incipient flag is cheaper than
2947 	 * check and removal.
2948 	 */
2949 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2950 
2951 	/* Must not cache forwarding table routes. */
2952 	if (ire_cacheable) {
2953 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2954 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2955 			connp->conn_ire_cache = ire;
2956 			IRE_UNTRACE_REF(ire);
2957 			rw_exit(&ire->ire_bucket->irb_lock);
2958 			mutex_exit(&connp->conn_lock);
2959 			return (1);
2960 		}
2961 		rw_exit(&ire->ire_bucket->irb_lock);
2962 	}
2963 	mutex_exit(&connp->conn_lock);
2964 
2965 	if (ire->ire_mp == NULL)
2966 		ire_refrele(ire);
2967 	return (1);
2968 
2969 error:
2970 	if (ire->ire_mp == NULL)
2971 		ire_refrele(ire);
2972 	if (sire != NULL)
2973 		ire_refrele(sire);
2974 	return (0);
2975 }
2976 
2977 /*
2978  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2979  * O_T_BIND_REQ/T_BIND_REQ message.
2980  */
2981 static void
2982 tcp_bind(tcp_t *tcp, mblk_t *mp)
2983 {
2984 	sin_t	*sin;
2985 	sin6_t	*sin6;
2986 	mblk_t	*mp1;
2987 	in_port_t requested_port;
2988 	in_port_t allocated_port;
2989 	struct T_bind_req *tbr;
2990 	boolean_t	bind_to_req_port_only;
2991 	boolean_t	backlog_update = B_FALSE;
2992 	boolean_t	user_specified;
2993 	in6_addr_t	v6addr;
2994 	ipaddr_t	v4addr;
2995 	uint_t	origipversion;
2996 	int	err;
2997 	queue_t *q = tcp->tcp_wq;
2998 	conn_t	*connp;
2999 	mlp_type_t addrtype, mlptype;
3000 	zone_t	*zone;
3001 	cred_t	*cr;
3002 	in_port_t mlp_port;
3003 
3004 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3005 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3006 		if (tcp->tcp_debug) {
3007 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3008 			    "tcp_bind: bad req, len %u",
3009 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3010 		}
3011 		tcp_err_ack(tcp, mp, TPROTO, 0);
3012 		return;
3013 	}
3014 	/* Make sure the largest address fits */
3015 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3016 	if (mp1 == NULL) {
3017 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3018 		return;
3019 	}
3020 	mp = mp1;
3021 	tbr = (struct T_bind_req *)mp->b_rptr;
3022 	if (tcp->tcp_state >= TCPS_BOUND) {
3023 		if ((tcp->tcp_state == TCPS_BOUND ||
3024 		    tcp->tcp_state == TCPS_LISTEN) &&
3025 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3026 		    tbr->CONIND_number > 0) {
3027 			/*
3028 			 * Handle listen() increasing CONIND_number.
3029 			 * This is more "liberal" then what the TPI spec
3030 			 * requires but is needed to avoid a t_unbind
3031 			 * when handling listen() since the port number
3032 			 * might be "stolen" between the unbind and bind.
3033 			 */
3034 			backlog_update = B_TRUE;
3035 			goto do_bind;
3036 		}
3037 		if (tcp->tcp_debug) {
3038 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3039 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3040 		}
3041 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3042 		return;
3043 	}
3044 	origipversion = tcp->tcp_ipversion;
3045 
3046 	switch (tbr->ADDR_length) {
3047 	case 0:			/* request for a generic port */
3048 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3049 		if (tcp->tcp_family == AF_INET) {
3050 			tbr->ADDR_length = sizeof (sin_t);
3051 			sin = (sin_t *)&tbr[1];
3052 			*sin = sin_null;
3053 			sin->sin_family = AF_INET;
3054 			mp->b_wptr = (uchar_t *)&sin[1];
3055 			tcp->tcp_ipversion = IPV4_VERSION;
3056 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3057 		} else {
3058 			ASSERT(tcp->tcp_family == AF_INET6);
3059 			tbr->ADDR_length = sizeof (sin6_t);
3060 			sin6 = (sin6_t *)&tbr[1];
3061 			*sin6 = sin6_null;
3062 			sin6->sin6_family = AF_INET6;
3063 			mp->b_wptr = (uchar_t *)&sin6[1];
3064 			tcp->tcp_ipversion = IPV6_VERSION;
3065 			V6_SET_ZERO(v6addr);
3066 		}
3067 		requested_port = 0;
3068 		break;
3069 
3070 	case sizeof (sin_t):	/* Complete IPv4 address */
3071 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3072 		    sizeof (sin_t));
3073 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3074 			if (tcp->tcp_debug) {
3075 				(void) strlog(TCP_MOD_ID, 0, 1,
3076 				    SL_ERROR|SL_TRACE,
3077 				    "tcp_bind: bad address parameter, "
3078 				    "offset %d, len %d",
3079 				    tbr->ADDR_offset, tbr->ADDR_length);
3080 			}
3081 			tcp_err_ack(tcp, mp, TPROTO, 0);
3082 			return;
3083 		}
3084 		/*
3085 		 * With sockets sockfs will accept bogus sin_family in
3086 		 * bind() and replace it with the family used in the socket
3087 		 * call.
3088 		 */
3089 		if (sin->sin_family != AF_INET ||
3090 		    tcp->tcp_family != AF_INET) {
3091 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3092 			return;
3093 		}
3094 		requested_port = ntohs(sin->sin_port);
3095 		tcp->tcp_ipversion = IPV4_VERSION;
3096 		v4addr = sin->sin_addr.s_addr;
3097 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3098 		break;
3099 
3100 	case sizeof (sin6_t): /* Complete IPv6 address */
3101 		sin6 = (sin6_t *)mi_offset_param(mp,
3102 		    tbr->ADDR_offset, sizeof (sin6_t));
3103 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3104 			if (tcp->tcp_debug) {
3105 				(void) strlog(TCP_MOD_ID, 0, 1,
3106 				    SL_ERROR|SL_TRACE,
3107 				    "tcp_bind: bad IPv6 address parameter, "
3108 				    "offset %d, len %d", tbr->ADDR_offset,
3109 				    tbr->ADDR_length);
3110 			}
3111 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3112 			return;
3113 		}
3114 		if (sin6->sin6_family != AF_INET6 ||
3115 		    tcp->tcp_family != AF_INET6) {
3116 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3117 			return;
3118 		}
3119 		requested_port = ntohs(sin6->sin6_port);
3120 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3121 		    IPV4_VERSION : IPV6_VERSION;
3122 		v6addr = sin6->sin6_addr;
3123 		break;
3124 
3125 	default:
3126 		if (tcp->tcp_debug) {
3127 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3128 			    "tcp_bind: bad address length, %d",
3129 			    tbr->ADDR_length);
3130 		}
3131 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3132 		return;
3133 	}
3134 	tcp->tcp_bound_source_v6 = v6addr;
3135 
3136 	/* Check for change in ipversion */
3137 	if (origipversion != tcp->tcp_ipversion) {
3138 		ASSERT(tcp->tcp_family == AF_INET6);
3139 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3140 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3141 		if (err) {
3142 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3143 			return;
3144 		}
3145 	}
3146 
3147 	/*
3148 	 * Initialize family specific fields. Copy of the src addr.
3149 	 * in tcp_t is needed for the lookup funcs.
3150 	 */
3151 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3152 		tcp->tcp_ip6h->ip6_src = v6addr;
3153 	} else {
3154 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3155 	}
3156 	tcp->tcp_ip_src_v6 = v6addr;
3157 
3158 	/*
3159 	 * For O_T_BIND_REQ:
3160 	 * Verify that the target port/addr is available, or choose
3161 	 * another.
3162 	 * For  T_BIND_REQ:
3163 	 * Verify that the target port/addr is available or fail.
3164 	 * In both cases when it succeeds the tcp is inserted in the
3165 	 * bind hash table. This ensures that the operation is atomic
3166 	 * under the lock on the hash bucket.
3167 	 */
3168 	bind_to_req_port_only = requested_port != 0 &&
3169 	    tbr->PRIM_type != O_T_BIND_REQ;
3170 	/*
3171 	 * Get a valid port (within the anonymous range and should not
3172 	 * be a privileged one) to use if the user has not given a port.
3173 	 * If multiple threads are here, they may all start with
3174 	 * with the same initial port. But, it should be fine as long as
3175 	 * tcp_bindi will ensure that no two threads will be assigned
3176 	 * the same port.
3177 	 *
3178 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3179 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3180 	 * unless TCP_ANONPRIVBIND option is set.
3181 	 */
3182 	mlptype = mlptSingle;
3183 	mlp_port = requested_port;
3184 	if (requested_port == 0) {
3185 		requested_port = tcp->tcp_anon_priv_bind ?
3186 		    tcp_get_next_priv_port(tcp) :
3187 		    tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
3188 		if (requested_port == 0) {
3189 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3190 			return;
3191 		}
3192 		user_specified = B_FALSE;
3193 
3194 		/*
3195 		 * If the user went through one of the RPC interfaces to create
3196 		 * this socket and RPC is MLP in this zone, then give him an
3197 		 * anonymous MLP.
3198 		 */
3199 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3200 		connp = tcp->tcp_connp;
3201 		if (connp->conn_anon_mlp && is_system_labeled()) {
3202 			zone = crgetzone(cr);
3203 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3204 			    IPV6_VERSION, &v6addr);
3205 			if (addrtype == mlptSingle) {
3206 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3207 				return;
3208 			}
3209 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3210 			    PMAPPORT, addrtype);
3211 			mlp_port = PMAPPORT;
3212 		}
3213 	} else {
3214 		int i;
3215 		boolean_t priv = B_FALSE;
3216 
3217 		/*
3218 		 * If the requested_port is in the well-known privileged range,
3219 		 * verify that the stream was opened by a privileged user.
3220 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3221 		 * but instead the code relies on:
3222 		 * - the fact that the address of the array and its size never
3223 		 *   changes
3224 		 * - the atomic assignment of the elements of the array
3225 		 */
3226 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3227 		if (requested_port < tcp_smallest_nonpriv_port) {
3228 			priv = B_TRUE;
3229 		} else {
3230 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3231 				if (requested_port ==
3232 				    tcp_g_epriv_ports[i]) {
3233 					priv = B_TRUE;
3234 					break;
3235 				}
3236 			}
3237 		}
3238 		if (priv) {
3239 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3240 				if (tcp->tcp_debug) {
3241 					(void) strlog(TCP_MOD_ID, 0, 1,
3242 					    SL_ERROR|SL_TRACE,
3243 					    "tcp_bind: no priv for port %d",
3244 					    requested_port);
3245 				}
3246 				tcp_err_ack(tcp, mp, TACCES, 0);
3247 				return;
3248 			}
3249 		}
3250 		user_specified = B_TRUE;
3251 
3252 		connp = tcp->tcp_connp;
3253 		if (is_system_labeled()) {
3254 			zone = crgetzone(cr);
3255 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3256 			    IPV6_VERSION, &v6addr);
3257 			if (addrtype == mlptSingle) {
3258 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3259 				return;
3260 			}
3261 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3262 			    requested_port, addrtype);
3263 		}
3264 	}
3265 
3266 	if (mlptype != mlptSingle) {
3267 		if (secpolicy_net_bindmlp(cr) != 0) {
3268 			if (tcp->tcp_debug) {
3269 				(void) strlog(TCP_MOD_ID, 0, 1,
3270 				    SL_ERROR|SL_TRACE,
3271 				    "tcp_bind: no priv for multilevel port %d",
3272 				    requested_port);
3273 			}
3274 			tcp_err_ack(tcp, mp, TACCES, 0);
3275 			return;
3276 		}
3277 
3278 		/*
3279 		 * If we're specifically binding a shared IP address and the
3280 		 * port is MLP on shared addresses, then check to see if this
3281 		 * zone actually owns the MLP.  Reject if not.
3282 		 */
3283 		if (mlptype == mlptShared && addrtype == mlptShared) {
3284 			zoneid_t mlpzone;
3285 
3286 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3287 			    htons(mlp_port));
3288 			if (connp->conn_zoneid != mlpzone) {
3289 				if (tcp->tcp_debug) {
3290 					(void) strlog(TCP_MOD_ID, 0, 1,
3291 					    SL_ERROR|SL_TRACE,
3292 					    "tcp_bind: attempt to bind port "
3293 					    "%d on shared addr in zone %d "
3294 					    "(should be %d)",
3295 					    mlp_port, connp->conn_zoneid,
3296 					    mlpzone);
3297 				}
3298 				tcp_err_ack(tcp, mp, TACCES, 0);
3299 				return;
3300 			}
3301 		}
3302 
3303 		if (!user_specified) {
3304 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3305 			    requested_port, B_TRUE);
3306 			if (err != 0) {
3307 				if (tcp->tcp_debug) {
3308 					(void) strlog(TCP_MOD_ID, 0, 1,
3309 					    SL_ERROR|SL_TRACE,
3310 					    "tcp_bind: cannot establish anon "
3311 					    "MLP for port %d",
3312 					    requested_port);
3313 				}
3314 				tcp_err_ack(tcp, mp, TSYSERR, err);
3315 				return;
3316 			}
3317 			connp->conn_anon_port = B_TRUE;
3318 		}
3319 		connp->conn_mlp_type = mlptype;
3320 	}
3321 
3322 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3323 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3324 
3325 	if (allocated_port == 0) {
3326 		connp->conn_mlp_type = mlptSingle;
3327 		if (connp->conn_anon_port) {
3328 			connp->conn_anon_port = B_FALSE;
3329 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3330 			    requested_port, B_FALSE);
3331 		}
3332 		if (bind_to_req_port_only) {
3333 			if (tcp->tcp_debug) {
3334 				(void) strlog(TCP_MOD_ID, 0, 1,
3335 				    SL_ERROR|SL_TRACE,
3336 				    "tcp_bind: requested addr busy");
3337 			}
3338 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3339 		} else {
3340 			/* If we are out of ports, fail the bind. */
3341 			if (tcp->tcp_debug) {
3342 				(void) strlog(TCP_MOD_ID, 0, 1,
3343 				    SL_ERROR|SL_TRACE,
3344 				    "tcp_bind: out of ports?");
3345 			}
3346 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3347 		}
3348 		return;
3349 	}
3350 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3351 do_bind:
3352 	if (!backlog_update) {
3353 		if (tcp->tcp_family == AF_INET)
3354 			sin->sin_port = htons(allocated_port);
3355 		else
3356 			sin6->sin6_port = htons(allocated_port);
3357 	}
3358 	if (tcp->tcp_family == AF_INET) {
3359 		if (tbr->CONIND_number != 0) {
3360 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3361 			    sizeof (sin_t));
3362 		} else {
3363 			/* Just verify the local IP address */
3364 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3365 		}
3366 	} else {
3367 		if (tbr->CONIND_number != 0) {
3368 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3369 			    sizeof (sin6_t));
3370 		} else {
3371 			/* Just verify the local IP address */
3372 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3373 			    IPV6_ADDR_LEN);
3374 		}
3375 	}
3376 	if (mp1 == NULL) {
3377 		if (connp->conn_anon_port) {
3378 			connp->conn_anon_port = B_FALSE;
3379 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3380 			    requested_port, B_FALSE);
3381 		}
3382 		connp->conn_mlp_type = mlptSingle;
3383 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3384 		return;
3385 	}
3386 
3387 	tbr->PRIM_type = T_BIND_ACK;
3388 	mp->b_datap->db_type = M_PCPROTO;
3389 
3390 	/* Chain in the reply mp for tcp_rput() */
3391 	mp1->b_cont = mp;
3392 	mp = mp1;
3393 
3394 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3395 	if (tcp->tcp_conn_req_max) {
3396 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
3397 			tcp->tcp_conn_req_max = tcp_conn_req_min;
3398 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
3399 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
3400 		/*
3401 		 * If this is a listener, do not reset the eager list
3402 		 * and other stuffs.  Note that we don't check if the
3403 		 * existing eager list meets the new tcp_conn_req_max
3404 		 * requirement.
3405 		 */
3406 		if (tcp->tcp_state != TCPS_LISTEN) {
3407 			tcp->tcp_state = TCPS_LISTEN;
3408 			/* Initialize the chain. Don't need the eager_lock */
3409 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3410 			tcp->tcp_second_ctimer_threshold =
3411 			    tcp_ip_abort_linterval;
3412 		}
3413 	}
3414 
3415 	/*
3416 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3417 	 * processing continues in tcp_rput_other().
3418 	 */
3419 	if (tcp->tcp_family == AF_INET6) {
3420 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3421 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3422 	} else {
3423 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3424 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3425 	}
3426 	/*
3427 	 * If the bind cannot complete immediately
3428 	 * IP will arrange to call tcp_rput_other
3429 	 * when the bind completes.
3430 	 */
3431 	if (mp != NULL) {
3432 		tcp_rput_other(tcp, mp);
3433 	} else {
3434 		/*
3435 		 * Bind will be resumed later. Need to ensure
3436 		 * that conn doesn't disappear when that happens.
3437 		 * This will be decremented in ip_resume_tcp_bind().
3438 		 */
3439 		CONN_INC_REF(tcp->tcp_connp);
3440 	}
3441 }
3442 
3443 
3444 /*
3445  * If the "bind_to_req_port_only" parameter is set, if the requested port
3446  * number is available, return it, If not return 0
3447  *
3448  * If "bind_to_req_port_only" parameter is not set and
3449  * If the requested port number is available, return it.  If not, return
3450  * the first anonymous port we happen across.  If no anonymous ports are
3451  * available, return 0. addr is the requested local address, if any.
3452  *
3453  * In either case, when succeeding update the tcp_t to record the port number
3454  * and insert it in the bind hash table.
3455  *
3456  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3457  * without setting SO_REUSEADDR. This is needed so that they
3458  * can be viewed as two independent transport protocols.
3459  */
3460 static in_port_t
3461 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3462     int reuseaddr, boolean_t quick_connect,
3463     boolean_t bind_to_req_port_only, boolean_t user_specified)
3464 {
3465 	/* number of times we have run around the loop */
3466 	int count = 0;
3467 	/* maximum number of times to run around the loop */
3468 	int loopmax;
3469 	conn_t *connp = tcp->tcp_connp;
3470 	zoneid_t zoneid = connp->conn_zoneid;
3471 
3472 	/*
3473 	 * Lookup for free addresses is done in a loop and "loopmax"
3474 	 * influences how long we spin in the loop
3475 	 */
3476 	if (bind_to_req_port_only) {
3477 		/*
3478 		 * If the requested port is busy, don't bother to look
3479 		 * for a new one. Setting loop maximum count to 1 has
3480 		 * that effect.
3481 		 */
3482 		loopmax = 1;
3483 	} else {
3484 		/*
3485 		 * If the requested port is busy, look for a free one
3486 		 * in the anonymous port range.
3487 		 * Set loopmax appropriately so that one does not look
3488 		 * forever in the case all of the anonymous ports are in use.
3489 		 */
3490 		if (tcp->tcp_anon_priv_bind) {
3491 			/*
3492 			 * loopmax =
3493 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3494 			 */
3495 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
3496 		} else {
3497 			loopmax = (tcp_largest_anon_port -
3498 			    tcp_smallest_anon_port + 1);
3499 		}
3500 	}
3501 	do {
3502 		uint16_t	lport;
3503 		tf_t		*tbf;
3504 		tcp_t		*ltcp;
3505 		conn_t		*lconnp;
3506 
3507 		lport = htons(port);
3508 
3509 		/*
3510 		 * Ensure that the tcp_t is not currently in the bind hash.
3511 		 * Hold the lock on the hash bucket to ensure that
3512 		 * the duplicate check plus the insertion is an atomic
3513 		 * operation.
3514 		 *
3515 		 * This function does an inline lookup on the bind hash list
3516 		 * Make sure that we access only members of tcp_t
3517 		 * and that we don't look at tcp_tcp, since we are not
3518 		 * doing a CONN_INC_REF.
3519 		 */
3520 		tcp_bind_hash_remove(tcp);
3521 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
3522 		mutex_enter(&tbf->tf_lock);
3523 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3524 		    ltcp = ltcp->tcp_bind_hash) {
3525 			boolean_t not_socket;
3526 			boolean_t exclbind;
3527 
3528 			if (lport != ltcp->tcp_lport)
3529 				continue;
3530 
3531 			lconnp = ltcp->tcp_connp;
3532 
3533 			/*
3534 			 * On a labeled system, we must treat bindings to ports
3535 			 * on shared IP addresses by sockets with MAC exemption
3536 			 * privilege as being in all zones, as there's
3537 			 * otherwise no way to identify the right receiver.
3538 			 */
3539 			if (!IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) &&
3540 			    !lconnp->conn_mac_exempt &&
3541 			    !connp->conn_mac_exempt)
3542 				continue;
3543 
3544 			/*
3545 			 * If TCP_EXCLBIND is set for either the bound or
3546 			 * binding endpoint, the semantics of bind
3547 			 * is changed according to the following.
3548 			 *
3549 			 * spec = specified address (v4 or v6)
3550 			 * unspec = unspecified address (v4 or v6)
3551 			 * A = specified addresses are different for endpoints
3552 			 *
3553 			 * bound	bind to		allowed
3554 			 * -------------------------------------
3555 			 * unspec	unspec		no
3556 			 * unspec	spec		no
3557 			 * spec		unspec		no
3558 			 * spec		spec		yes if A
3559 			 *
3560 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3561 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3562 			 *
3563 			 * Note:
3564 			 *
3565 			 * 1. Because of TLI semantics, an endpoint can go
3566 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3567 			 * TCPS_BOUND, depending on whether it is originally
3568 			 * a listener or not.  That is why we need to check
3569 			 * for states greater than or equal to TCPS_BOUND
3570 			 * here.
3571 			 *
3572 			 * 2. Ideally, we should only check for state equals
3573 			 * to TCPS_LISTEN. And the following check should be
3574 			 * added.
3575 			 *
3576 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3577 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3578 			 *		...
3579 			 * }
3580 			 *
3581 			 * The semantics will be changed to this.  If the
3582 			 * endpoint on the list is in state not equal to
3583 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3584 			 * set, let the bind succeed.
3585 			 *
3586 			 * Because of (1), we cannot do that for TLI
3587 			 * endpoints.  But we can do that for socket endpoints.
3588 			 * If in future, we can change this going back
3589 			 * semantics, we can use the above check for TLI also.
3590 			 */
3591 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3592 			    TCP_IS_SOCKET(tcp));
3593 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3594 
3595 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3596 			    (exclbind && (not_socket ||
3597 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3598 				if (V6_OR_V4_INADDR_ANY(
3599 				    ltcp->tcp_bound_source_v6) ||
3600 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3601 				    IN6_ARE_ADDR_EQUAL(laddr,
3602 				    &ltcp->tcp_bound_source_v6)) {
3603 					break;
3604 				}
3605 				continue;
3606 			}
3607 
3608 			/*
3609 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3610 			 * have disjoint port number spaces, if *_EXCLBIND
3611 			 * is not set and only if the application binds to a
3612 			 * specific port. We use the same autoassigned port
3613 			 * number space for IPv4 and IPv6 sockets.
3614 			 */
3615 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3616 			    bind_to_req_port_only)
3617 				continue;
3618 
3619 			/*
3620 			 * Ideally, we should make sure that the source
3621 			 * address, remote address, and remote port in the
3622 			 * four tuple for this tcp-connection is unique.
3623 			 * However, trying to find out the local source
3624 			 * address would require too much code duplication
3625 			 * with IP, since IP needs needs to have that code
3626 			 * to support userland TCP implementations.
3627 			 */
3628 			if (quick_connect &&
3629 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3630 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3631 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3632 				    &ltcp->tcp_remote_v6)))
3633 				continue;
3634 
3635 			if (!reuseaddr) {
3636 				/*
3637 				 * No socket option SO_REUSEADDR.
3638 				 * If existing port is bound to
3639 				 * a non-wildcard IP address
3640 				 * and the requesting stream is
3641 				 * bound to a distinct
3642 				 * different IP addresses
3643 				 * (non-wildcard, also), keep
3644 				 * going.
3645 				 */
3646 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3647 				    !V6_OR_V4_INADDR_ANY(
3648 				    ltcp->tcp_bound_source_v6) &&
3649 				    !IN6_ARE_ADDR_EQUAL(laddr,
3650 					&ltcp->tcp_bound_source_v6))
3651 					continue;
3652 				if (ltcp->tcp_state >= TCPS_BOUND) {
3653 					/*
3654 					 * This port is being used and
3655 					 * its state is >= TCPS_BOUND,
3656 					 * so we can't bind to it.
3657 					 */
3658 					break;
3659 				}
3660 			} else {
3661 				/*
3662 				 * socket option SO_REUSEADDR is set on the
3663 				 * binding tcp_t.
3664 				 *
3665 				 * If two streams are bound to
3666 				 * same IP address or both addr
3667 				 * and bound source are wildcards
3668 				 * (INADDR_ANY), we want to stop
3669 				 * searching.
3670 				 * We have found a match of IP source
3671 				 * address and source port, which is
3672 				 * refused regardless of the
3673 				 * SO_REUSEADDR setting, so we break.
3674 				 */
3675 				if (IN6_ARE_ADDR_EQUAL(laddr,
3676 				    &ltcp->tcp_bound_source_v6) &&
3677 				    (ltcp->tcp_state == TCPS_LISTEN ||
3678 					ltcp->tcp_state == TCPS_BOUND))
3679 					break;
3680 			}
3681 		}
3682 		if (ltcp != NULL) {
3683 			/* The port number is busy */
3684 			mutex_exit(&tbf->tf_lock);
3685 		} else {
3686 			/*
3687 			 * This port is ours. Insert in fanout and mark as
3688 			 * bound to prevent others from getting the port
3689 			 * number.
3690 			 */
3691 			tcp->tcp_state = TCPS_BOUND;
3692 			tcp->tcp_lport = htons(port);
3693 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3694 
3695 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
3696 			    tcp->tcp_lport)] == tbf);
3697 			tcp_bind_hash_insert(tbf, tcp, 1);
3698 
3699 			mutex_exit(&tbf->tf_lock);
3700 
3701 			/*
3702 			 * We don't want tcp_next_port_to_try to "inherit"
3703 			 * a port number supplied by the user in a bind.
3704 			 */
3705 			if (user_specified)
3706 				return (port);
3707 
3708 			/*
3709 			 * This is the only place where tcp_next_port_to_try
3710 			 * is updated. After the update, it may or may not
3711 			 * be in the valid range.
3712 			 */
3713 			if (!tcp->tcp_anon_priv_bind)
3714 				tcp_next_port_to_try = port + 1;
3715 			return (port);
3716 		}
3717 
3718 		if (tcp->tcp_anon_priv_bind) {
3719 			port = tcp_get_next_priv_port(tcp);
3720 		} else {
3721 			if (count == 0 && user_specified) {
3722 				/*
3723 				 * We may have to return an anonymous port. So
3724 				 * get one to start with.
3725 				 */
3726 				port =
3727 				    tcp_update_next_port(tcp_next_port_to_try,
3728 					tcp, B_TRUE);
3729 				user_specified = B_FALSE;
3730 			} else {
3731 				port = tcp_update_next_port(port + 1, tcp,
3732 				    B_FALSE);
3733 			}
3734 		}
3735 		if (port == 0)
3736 			break;
3737 
3738 		/*
3739 		 * Don't let this loop run forever in the case where
3740 		 * all of the anonymous ports are in use.
3741 		 */
3742 	} while (++count < loopmax);
3743 	return (0);
3744 }
3745 
3746 /*
3747  * We are dying for some reason.  Try to do it gracefully.  (May be called
3748  * as writer.)
3749  *
3750  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3751  * done by a service procedure).
3752  * TBD - Should the return value distinguish between the tcp_t being
3753  * freed and it being reinitialized?
3754  */
3755 static int
3756 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3757 {
3758 	mblk_t	*mp;
3759 	queue_t	*q;
3760 
3761 	TCP_CLD_STAT(tag);
3762 
3763 #if TCP_TAG_CLEAN_DEATH
3764 	tcp->tcp_cleandeathtag = tag;
3765 #endif
3766 
3767 	if (tcp->tcp_fused)
3768 		tcp_unfuse(tcp);
3769 
3770 	if (tcp->tcp_linger_tid != 0 &&
3771 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3772 		tcp_stop_lingering(tcp);
3773 	}
3774 
3775 	ASSERT(tcp != NULL);
3776 	ASSERT((tcp->tcp_family == AF_INET &&
3777 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3778 	    (tcp->tcp_family == AF_INET6 &&
3779 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3780 	    tcp->tcp_ipversion == IPV6_VERSION)));
3781 
3782 	if (TCP_IS_DETACHED(tcp)) {
3783 		if (tcp->tcp_hard_binding) {
3784 			/*
3785 			 * Its an eager that we are dealing with. We close the
3786 			 * eager but in case a conn_ind has already gone to the
3787 			 * listener, let tcp_accept_finish() send a discon_ind
3788 			 * to the listener and drop the last reference. If the
3789 			 * listener doesn't even know about the eager i.e. the
3790 			 * conn_ind hasn't gone up, blow away the eager and drop
3791 			 * the last reference as well. If the conn_ind has gone
3792 			 * up, state should be BOUND. tcp_accept_finish
3793 			 * will figure out that the connection has received a
3794 			 * RST and will send a DISCON_IND to the application.
3795 			 */
3796 			tcp_closei_local(tcp);
3797 			if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
3798 				CONN_DEC_REF(tcp->tcp_connp);
3799 			} else {
3800 				tcp->tcp_state = TCPS_BOUND;
3801 			}
3802 		} else {
3803 			tcp_close_detached(tcp);
3804 		}
3805 		return (0);
3806 	}
3807 
3808 	TCP_STAT(tcp_clean_death_nondetached);
3809 
3810 	/*
3811 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3812 	 * is run) postpone cleaning up the endpoint until service routine
3813 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3814 	 * client_errno since tcp_close uses the client_errno field.
3815 	 */
3816 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3817 		if (err != 0)
3818 			tcp->tcp_client_errno = err;
3819 
3820 		tcp->tcp_deferred_clean_death = B_TRUE;
3821 		return (-1);
3822 	}
3823 
3824 	q = tcp->tcp_rq;
3825 
3826 	/* Trash all inbound data */
3827 	flushq(q, FLUSHALL);
3828 
3829 	/*
3830 	 * If we are at least part way open and there is error
3831 	 * (err==0 implies no error)
3832 	 * notify our client by a T_DISCON_IND.
3833 	 */
3834 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3835 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3836 		    !TCP_IS_SOCKET(tcp)) {
3837 			/*
3838 			 * Send M_FLUSH according to TPI. Because sockets will
3839 			 * (and must) ignore FLUSHR we do that only for TPI
3840 			 * endpoints and sockets in STREAMS mode.
3841 			 */
3842 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3843 		}
3844 		if (tcp->tcp_debug) {
3845 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3846 			    "tcp_clean_death: discon err %d", err);
3847 		}
3848 		mp = mi_tpi_discon_ind(NULL, err, 0);
3849 		if (mp != NULL) {
3850 			putnext(q, mp);
3851 		} else {
3852 			if (tcp->tcp_debug) {
3853 				(void) strlog(TCP_MOD_ID, 0, 1,
3854 				    SL_ERROR|SL_TRACE,
3855 				    "tcp_clean_death, sending M_ERROR");
3856 			}
3857 			(void) putnextctl1(q, M_ERROR, EPROTO);
3858 		}
3859 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3860 			/* SYN_SENT or SYN_RCVD */
3861 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3862 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3863 			/* ESTABLISHED or CLOSE_WAIT */
3864 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3865 		}
3866 	}
3867 
3868 	tcp_reinit(tcp);
3869 	return (-1);
3870 }
3871 
3872 /*
3873  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3874  * to expire, stop the wait and finish the close.
3875  */
3876 static void
3877 tcp_stop_lingering(tcp_t *tcp)
3878 {
3879 	clock_t	delta = 0;
3880 
3881 	tcp->tcp_linger_tid = 0;
3882 	if (tcp->tcp_state > TCPS_LISTEN) {
3883 		tcp_acceptor_hash_remove(tcp);
3884 		if (tcp->tcp_flow_stopped) {
3885 			tcp_clrqfull(tcp);
3886 		}
3887 
3888 		if (tcp->tcp_timer_tid != 0) {
3889 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3890 			tcp->tcp_timer_tid = 0;
3891 		}
3892 		/*
3893 		 * Need to cancel those timers which will not be used when
3894 		 * TCP is detached.  This has to be done before the tcp_wq
3895 		 * is set to the global queue.
3896 		 */
3897 		tcp_timers_stop(tcp);
3898 
3899 
3900 		tcp->tcp_detached = B_TRUE;
3901 		tcp->tcp_rq = tcp_g_q;
3902 		tcp->tcp_wq = WR(tcp_g_q);
3903 
3904 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3905 			tcp_time_wait_append(tcp);
3906 			TCP_DBGSTAT(tcp_detach_time_wait);
3907 			goto finish;
3908 		}
3909 
3910 		/*
3911 		 * If delta is zero the timer event wasn't executed and was
3912 		 * successfully canceled. In this case we need to restart it
3913 		 * with the minimal delta possible.
3914 		 */
3915 		if (delta >= 0) {
3916 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3917 			    delta ? delta : 1);
3918 		}
3919 	} else {
3920 		tcp_closei_local(tcp);
3921 		CONN_DEC_REF(tcp->tcp_connp);
3922 	}
3923 finish:
3924 	/* Signal closing thread that it can complete close */
3925 	mutex_enter(&tcp->tcp_closelock);
3926 	tcp->tcp_detached = B_TRUE;
3927 	tcp->tcp_rq = tcp_g_q;
3928 	tcp->tcp_wq = WR(tcp_g_q);
3929 	tcp->tcp_closed = 1;
3930 	cv_signal(&tcp->tcp_closecv);
3931 	mutex_exit(&tcp->tcp_closelock);
3932 }
3933 
3934 /*
3935  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3936  * expires.
3937  */
3938 static void
3939 tcp_close_linger_timeout(void *arg)
3940 {
3941 	conn_t	*connp = (conn_t *)arg;
3942 	tcp_t 	*tcp = connp->conn_tcp;
3943 
3944 	tcp->tcp_client_errno = ETIMEDOUT;
3945 	tcp_stop_lingering(tcp);
3946 }
3947 
3948 static int
3949 tcp_close(queue_t *q, int flags)
3950 {
3951 	conn_t		*connp = Q_TO_CONN(q);
3952 	tcp_t		*tcp = connp->conn_tcp;
3953 	mblk_t 		*mp = &tcp->tcp_closemp;
3954 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3955 	boolean_t	linger_interrupted = B_FALSE;
3956 	mblk_t		*bp;
3957 
3958 	ASSERT(WR(q)->q_next == NULL);
3959 	ASSERT(connp->conn_ref >= 2);
3960 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
3961 
3962 	/*
3963 	 * We are being closed as /dev/tcp or /dev/tcp6.
3964 	 *
3965 	 * Mark the conn as closing. ill_pending_mp_add will not
3966 	 * add any mp to the pending mp list, after this conn has
3967 	 * started closing. Same for sq_pending_mp_add
3968 	 */
3969 	mutex_enter(&connp->conn_lock);
3970 	connp->conn_state_flags |= CONN_CLOSING;
3971 	if (connp->conn_oper_pending_ill != NULL)
3972 		conn_ioctl_cleanup_reqd = B_TRUE;
3973 	CONN_INC_REF_LOCKED(connp);
3974 	mutex_exit(&connp->conn_lock);
3975 	tcp->tcp_closeflags = (uint8_t)flags;
3976 	ASSERT(connp->conn_ref >= 3);
3977 
3978 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
3979 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
3980 
3981 	mutex_enter(&tcp->tcp_closelock);
3982 	while (!tcp->tcp_closed) {
3983 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3984 			/*
3985 			 * We got interrupted. Check if we are lingering,
3986 			 * if yes, post a message to stop and wait until
3987 			 * tcp_closed is set. If we aren't lingering,
3988 			 * just go back around.
3989 			 */
3990 			if (tcp->tcp_linger &&
3991 			    tcp->tcp_lingertime > 0 &&
3992 			    !linger_interrupted) {
3993 				mutex_exit(&tcp->tcp_closelock);
3994 				/* Entering squeue, bump ref count. */
3995 				CONN_INC_REF(connp);
3996 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3997 				squeue_enter(connp->conn_sqp, bp,
3998 				    tcp_linger_interrupted, connp,
3999 				    SQTAG_IP_TCP_CLOSE);
4000 				linger_interrupted = B_TRUE;
4001 				mutex_enter(&tcp->tcp_closelock);
4002 			}
4003 		}
4004 	}
4005 	mutex_exit(&tcp->tcp_closelock);
4006 
4007 	/*
4008 	 * In the case of listener streams that have eagers in the q or q0
4009 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4010 	 * tcp_wq of the eagers point to our queues. By waiting for the
4011 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4012 	 * up their queue pointers and also dropped their references to us.
4013 	 */
4014 	if (tcp->tcp_wait_for_eagers) {
4015 		mutex_enter(&connp->conn_lock);
4016 		while (connp->conn_ref != 1) {
4017 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4018 		}
4019 		mutex_exit(&connp->conn_lock);
4020 	}
4021 	/*
4022 	 * ioctl cleanup. The mp is queued in the
4023 	 * ill_pending_mp or in the sq_pending_mp.
4024 	 */
4025 	if (conn_ioctl_cleanup_reqd)
4026 		conn_ioctl_cleanup(connp);
4027 
4028 	qprocsoff(q);
4029 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4030 
4031 	tcp->tcp_cpid = -1;
4032 
4033 	/*
4034 	 * Drop IP's reference on the conn. This is the last reference
4035 	 * on the connp if the state was less than established. If the
4036 	 * connection has gone into timewait state, then we will have
4037 	 * one ref for the TCP and one more ref (total of two) for the
4038 	 * classifier connected hash list (a timewait connections stays
4039 	 * in connected hash till closed).
4040 	 *
4041 	 * We can't assert the references because there might be other
4042 	 * transient reference places because of some walkers or queued
4043 	 * packets in squeue for the timewait state.
4044 	 */
4045 	CONN_DEC_REF(connp);
4046 	q->q_ptr = WR(q)->q_ptr = NULL;
4047 	return (0);
4048 }
4049 
4050 static int
4051 tcpclose_accept(queue_t *q)
4052 {
4053 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4054 
4055 	/*
4056 	 * We had opened an acceptor STREAM for sockfs which is
4057 	 * now being closed due to some error.
4058 	 */
4059 	qprocsoff(q);
4060 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
4061 	q->q_ptr = WR(q)->q_ptr = NULL;
4062 	return (0);
4063 }
4064 
4065 /*
4066  * Called by tcp_close() routine via squeue when lingering is
4067  * interrupted by a signal.
4068  */
4069 
4070 /* ARGSUSED */
4071 static void
4072 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
4073 {
4074 	conn_t	*connp = (conn_t *)arg;
4075 	tcp_t	*tcp = connp->conn_tcp;
4076 
4077 	freeb(mp);
4078 	if (tcp->tcp_linger_tid != 0 &&
4079 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4080 		tcp_stop_lingering(tcp);
4081 		tcp->tcp_client_errno = EINTR;
4082 	}
4083 }
4084 
4085 /*
4086  * Called by streams close routine via squeues when our client blows off her
4087  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4088  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4089  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4090  * acked.
4091  *
4092  * NOTE: tcp_close potentially returns error when lingering.
4093  * However, the stream head currently does not pass these errors
4094  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4095  * errors to the application (from tsleep()) and not errors
4096  * like ECONNRESET caused by receiving a reset packet.
4097  */
4098 
4099 /* ARGSUSED */
4100 static void
4101 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4102 {
4103 	char	*msg;
4104 	conn_t	*connp = (conn_t *)arg;
4105 	tcp_t	*tcp = connp->conn_tcp;
4106 	clock_t	delta = 0;
4107 
4108 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4109 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4110 
4111 	/* Cancel any pending timeout */
4112 	if (tcp->tcp_ordrelid != 0) {
4113 		if (tcp->tcp_timeout) {
4114 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4115 		}
4116 		tcp->tcp_ordrelid = 0;
4117 		tcp->tcp_timeout = B_FALSE;
4118 	}
4119 
4120 	mutex_enter(&tcp->tcp_eager_lock);
4121 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4122 		/* Cleanup for listener */
4123 		tcp_eager_cleanup(tcp, 0);
4124 		tcp->tcp_wait_for_eagers = 1;
4125 	}
4126 	mutex_exit(&tcp->tcp_eager_lock);
4127 
4128 	connp->conn_mdt_ok = B_FALSE;
4129 	tcp->tcp_mdt = B_FALSE;
4130 
4131 	msg = NULL;
4132 	switch (tcp->tcp_state) {
4133 	case TCPS_CLOSED:
4134 	case TCPS_IDLE:
4135 	case TCPS_BOUND:
4136 	case TCPS_LISTEN:
4137 		break;
4138 	case TCPS_SYN_SENT:
4139 		msg = "tcp_close, during connect";
4140 		break;
4141 	case TCPS_SYN_RCVD:
4142 		/*
4143 		 * Close during the connect 3-way handshake
4144 		 * but here there may or may not be pending data
4145 		 * already on queue. Process almost same as in
4146 		 * the ESTABLISHED state.
4147 		 */
4148 		/* FALLTHRU */
4149 	default:
4150 		if (tcp->tcp_fused)
4151 			tcp_unfuse(tcp);
4152 
4153 		/*
4154 		 * If SO_LINGER has set a zero linger time, abort the
4155 		 * connection with a reset.
4156 		 */
4157 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4158 			msg = "tcp_close, zero lingertime";
4159 			break;
4160 		}
4161 
4162 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4163 		/*
4164 		 * Abort connection if there is unread data queued.
4165 		 */
4166 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4167 			msg = "tcp_close, unread data";
4168 			break;
4169 		}
4170 		/*
4171 		 * tcp_hard_bound is now cleared thus all packets go through
4172 		 * tcp_lookup. This fact is used by tcp_detach below.
4173 		 *
4174 		 * We have done a qwait() above which could have possibly
4175 		 * drained more messages in turn causing transition to a
4176 		 * different state. Check whether we have to do the rest
4177 		 * of the processing or not.
4178 		 */
4179 		if (tcp->tcp_state <= TCPS_LISTEN)
4180 			break;
4181 
4182 		/*
4183 		 * Transmit the FIN before detaching the tcp_t.
4184 		 * After tcp_detach returns this queue/perimeter
4185 		 * no longer owns the tcp_t thus others can modify it.
4186 		 */
4187 		(void) tcp_xmit_end(tcp);
4188 
4189 		/*
4190 		 * If lingering on close then wait until the fin is acked,
4191 		 * the SO_LINGER time passes, or a reset is sent/received.
4192 		 */
4193 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4194 		    !(tcp->tcp_fin_acked) &&
4195 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4196 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4197 				tcp->tcp_client_errno = EWOULDBLOCK;
4198 			} else if (tcp->tcp_client_errno == 0) {
4199 
4200 				ASSERT(tcp->tcp_linger_tid == 0);
4201 
4202 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4203 				    tcp_close_linger_timeout,
4204 				    tcp->tcp_lingertime * hz);
4205 
4206 				/* tcp_close_linger_timeout will finish close */
4207 				if (tcp->tcp_linger_tid == 0)
4208 					tcp->tcp_client_errno = ENOSR;
4209 				else
4210 					return;
4211 			}
4212 
4213 			/*
4214 			 * Check if we need to detach or just close
4215 			 * the instance.
4216 			 */
4217 			if (tcp->tcp_state <= TCPS_LISTEN)
4218 				break;
4219 		}
4220 
4221 		/*
4222 		 * Make sure that no other thread will access the tcp_rq of
4223 		 * this instance (through lookups etc.) as tcp_rq will go
4224 		 * away shortly.
4225 		 */
4226 		tcp_acceptor_hash_remove(tcp);
4227 
4228 		if (tcp->tcp_flow_stopped) {
4229 			tcp_clrqfull(tcp);
4230 		}
4231 
4232 		if (tcp->tcp_timer_tid != 0) {
4233 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4234 			tcp->tcp_timer_tid = 0;
4235 		}
4236 		/*
4237 		 * Need to cancel those timers which will not be used when
4238 		 * TCP is detached.  This has to be done before the tcp_wq
4239 		 * is set to the global queue.
4240 		 */
4241 		tcp_timers_stop(tcp);
4242 
4243 		tcp->tcp_detached = B_TRUE;
4244 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4245 			tcp_time_wait_append(tcp);
4246 			TCP_DBGSTAT(tcp_detach_time_wait);
4247 			ASSERT(connp->conn_ref >= 3);
4248 			goto finish;
4249 		}
4250 
4251 		/*
4252 		 * If delta is zero the timer event wasn't executed and was
4253 		 * successfully canceled. In this case we need to restart it
4254 		 * with the minimal delta possible.
4255 		 */
4256 		if (delta >= 0)
4257 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4258 			    delta ? delta : 1);
4259 
4260 		ASSERT(connp->conn_ref >= 3);
4261 		goto finish;
4262 	}
4263 
4264 	/* Detach did not complete. Still need to remove q from stream. */
4265 	if (msg) {
4266 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4267 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4268 			BUMP_MIB(&tcp_mib, tcpEstabResets);
4269 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4270 		    tcp->tcp_state == TCPS_SYN_RCVD)
4271 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
4272 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4273 	}
4274 
4275 	tcp_closei_local(tcp);
4276 	CONN_DEC_REF(connp);
4277 	ASSERT(connp->conn_ref >= 2);
4278 
4279 finish:
4280 	/*
4281 	 * Although packets are always processed on the correct
4282 	 * tcp's perimeter and access is serialized via squeue's,
4283 	 * IP still needs a queue when sending packets in time_wait
4284 	 * state so use WR(tcp_g_q) till ip_output() can be
4285 	 * changed to deal with just connp. For read side, we
4286 	 * could have set tcp_rq to NULL but there are some cases
4287 	 * in tcp_rput_data() from early days of this code which
4288 	 * do a putnext without checking if tcp is closed. Those
4289 	 * need to be identified before both tcp_rq and tcp_wq
4290 	 * can be set to NULL and tcp_q_q can disappear forever.
4291 	 */
4292 	mutex_enter(&tcp->tcp_closelock);
4293 	/*
4294 	 * Don't change the queues in the case of a listener that has
4295 	 * eagers in its q or q0. It could surprise the eagers.
4296 	 * Instead wait for the eagers outside the squeue.
4297 	 */
4298 	if (!tcp->tcp_wait_for_eagers) {
4299 		tcp->tcp_detached = B_TRUE;
4300 		tcp->tcp_rq = tcp_g_q;
4301 		tcp->tcp_wq = WR(tcp_g_q);
4302 	}
4303 
4304 	/* Signal tcp_close() to finish closing. */
4305 	tcp->tcp_closed = 1;
4306 	cv_signal(&tcp->tcp_closecv);
4307 	mutex_exit(&tcp->tcp_closelock);
4308 }
4309 
4310 
4311 /*
4312  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4313  * Some stream heads get upset if they see these later on as anything but NULL.
4314  */
4315 static void
4316 tcp_close_mpp(mblk_t **mpp)
4317 {
4318 	mblk_t	*mp;
4319 
4320 	if ((mp = *mpp) != NULL) {
4321 		do {
4322 			mp->b_next = NULL;
4323 			mp->b_prev = NULL;
4324 		} while ((mp = mp->b_cont) != NULL);
4325 
4326 		mp = *mpp;
4327 		*mpp = NULL;
4328 		freemsg(mp);
4329 	}
4330 }
4331 
4332 /* Do detached close. */
4333 static void
4334 tcp_close_detached(tcp_t *tcp)
4335 {
4336 	if (tcp->tcp_fused)
4337 		tcp_unfuse(tcp);
4338 
4339 	/*
4340 	 * Clustering code serializes TCP disconnect callbacks and
4341 	 * cluster tcp list walks by blocking a TCP disconnect callback
4342 	 * if a cluster tcp list walk is in progress. This ensures
4343 	 * accurate accounting of TCPs in the cluster code even though
4344 	 * the TCP list walk itself is not atomic.
4345 	 */
4346 	tcp_closei_local(tcp);
4347 	CONN_DEC_REF(tcp->tcp_connp);
4348 }
4349 
4350 /*
4351  * Stop all TCP timers, and free the timer mblks if requested.
4352  */
4353 void
4354 tcp_timers_stop(tcp_t *tcp)
4355 {
4356 	if (tcp->tcp_timer_tid != 0) {
4357 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4358 		tcp->tcp_timer_tid = 0;
4359 	}
4360 	if (tcp->tcp_ka_tid != 0) {
4361 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4362 		tcp->tcp_ka_tid = 0;
4363 	}
4364 	if (tcp->tcp_ack_tid != 0) {
4365 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4366 		tcp->tcp_ack_tid = 0;
4367 	}
4368 	if (tcp->tcp_push_tid != 0) {
4369 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4370 		tcp->tcp_push_tid = 0;
4371 	}
4372 }
4373 
4374 /*
4375  * The tcp_t is going away. Remove it from all lists and set it
4376  * to TCPS_CLOSED. The freeing up of memory is deferred until
4377  * tcp_inactive. This is needed since a thread in tcp_rput might have
4378  * done a CONN_INC_REF on this structure before it was removed from the
4379  * hashes.
4380  */
4381 static void
4382 tcp_closei_local(tcp_t *tcp)
4383 {
4384 	ire_t 	*ire;
4385 	conn_t	*connp = tcp->tcp_connp;
4386 
4387 	if (!TCP_IS_SOCKET(tcp))
4388 		tcp_acceptor_hash_remove(tcp);
4389 
4390 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
4391 	tcp->tcp_ibsegs = 0;
4392 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
4393 	tcp->tcp_obsegs = 0;
4394 
4395 	/*
4396 	 * If we are an eager connection hanging off a listener that
4397 	 * hasn't formally accepted the connection yet, get off his
4398 	 * list and blow off any data that we have accumulated.
4399 	 */
4400 	if (tcp->tcp_listener != NULL) {
4401 		tcp_t	*listener = tcp->tcp_listener;
4402 		mutex_enter(&listener->tcp_eager_lock);
4403 		/*
4404 		 * tcp_eager_conn_ind == NULL means that the
4405 		 * conn_ind has already gone to listener. At
4406 		 * this point, eager will be closed but we
4407 		 * leave it in listeners eager list so that
4408 		 * if listener decides to close without doing
4409 		 * accept, we can clean this up. In tcp_wput_accept
4410 		 * we take case of the case of accept on closed
4411 		 * eager.
4412 		 */
4413 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4414 			tcp_eager_unlink(tcp);
4415 			mutex_exit(&listener->tcp_eager_lock);
4416 			/*
4417 			 * We don't want to have any pointers to the
4418 			 * listener queue, after we have released our
4419 			 * reference on the listener
4420 			 */
4421 			tcp->tcp_rq = tcp_g_q;
4422 			tcp->tcp_wq = WR(tcp_g_q);
4423 			CONN_DEC_REF(listener->tcp_connp);
4424 		} else {
4425 			mutex_exit(&listener->tcp_eager_lock);
4426 		}
4427 	}
4428 
4429 	/* Stop all the timers */
4430 	tcp_timers_stop(tcp);
4431 
4432 	if (tcp->tcp_state == TCPS_LISTEN) {
4433 		if (tcp->tcp_ip_addr_cache) {
4434 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4435 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4436 			tcp->tcp_ip_addr_cache = NULL;
4437 		}
4438 	}
4439 	if (tcp->tcp_flow_stopped)
4440 		tcp_clrqfull(tcp);
4441 
4442 	tcp_bind_hash_remove(tcp);
4443 	/*
4444 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4445 	 * is trying to remove this tcp from the time wait list, we will
4446 	 * block in tcp_time_wait_remove while trying to acquire the
4447 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4448 	 * requires the ipcl_hash_remove to be ordered after the
4449 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4450 	 */
4451 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4452 		tcp_time_wait_remove(tcp, NULL);
4453 	CL_INET_DISCONNECT(tcp);
4454 	ipcl_hash_remove(connp);
4455 
4456 	/*
4457 	 * Delete the cached ire in conn_ire_cache and also mark
4458 	 * the conn as CONDEMNED
4459 	 */
4460 	mutex_enter(&connp->conn_lock);
4461 	connp->conn_state_flags |= CONN_CONDEMNED;
4462 	ire = connp->conn_ire_cache;
4463 	connp->conn_ire_cache = NULL;
4464 	mutex_exit(&connp->conn_lock);
4465 	if (ire != NULL)
4466 		IRE_REFRELE_NOTR(ire);
4467 
4468 	/* Need to cleanup any pending ioctls */
4469 	ASSERT(tcp->tcp_time_wait_next == NULL);
4470 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4471 	ASSERT(tcp->tcp_time_wait_expire == 0);
4472 	tcp->tcp_state = TCPS_CLOSED;
4473 
4474 	/* Release any SSL context */
4475 	if (tcp->tcp_kssl_ent != NULL) {
4476 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4477 		tcp->tcp_kssl_ent = NULL;
4478 	}
4479 	if (tcp->tcp_kssl_ctx != NULL) {
4480 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4481 		tcp->tcp_kssl_ctx = NULL;
4482 	}
4483 	tcp->tcp_kssl_pending = B_FALSE;
4484 }
4485 
4486 /*
4487  * tcp is dying (called from ipcl_conn_destroy and error cases).
4488  * Free the tcp_t in either case.
4489  */
4490 void
4491 tcp_free(tcp_t *tcp)
4492 {
4493 	mblk_t	*mp;
4494 	ip6_pkt_t	*ipp;
4495 
4496 	ASSERT(tcp != NULL);
4497 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4498 
4499 	tcp->tcp_rq = NULL;
4500 	tcp->tcp_wq = NULL;
4501 
4502 	tcp_close_mpp(&tcp->tcp_xmit_head);
4503 	tcp_close_mpp(&tcp->tcp_reass_head);
4504 	if (tcp->tcp_rcv_list != NULL) {
4505 		/* Free b_next chain */
4506 		tcp_close_mpp(&tcp->tcp_rcv_list);
4507 	}
4508 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4509 		freemsg(mp);
4510 	}
4511 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4512 		freemsg(mp);
4513 	}
4514 
4515 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4516 		freeb(tcp->tcp_fused_sigurg_mp);
4517 		tcp->tcp_fused_sigurg_mp = NULL;
4518 	}
4519 
4520 	if (tcp->tcp_sack_info != NULL) {
4521 		if (tcp->tcp_notsack_list != NULL) {
4522 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4523 		}
4524 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4525 	}
4526 
4527 	if (tcp->tcp_hopopts != NULL) {
4528 		mi_free(tcp->tcp_hopopts);
4529 		tcp->tcp_hopopts = NULL;
4530 		tcp->tcp_hopoptslen = 0;
4531 	}
4532 	ASSERT(tcp->tcp_hopoptslen == 0);
4533 	if (tcp->tcp_dstopts != NULL) {
4534 		mi_free(tcp->tcp_dstopts);
4535 		tcp->tcp_dstopts = NULL;
4536 		tcp->tcp_dstoptslen = 0;
4537 	}
4538 	ASSERT(tcp->tcp_dstoptslen == 0);
4539 	if (tcp->tcp_rtdstopts != NULL) {
4540 		mi_free(tcp->tcp_rtdstopts);
4541 		tcp->tcp_rtdstopts = NULL;
4542 		tcp->tcp_rtdstoptslen = 0;
4543 	}
4544 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4545 	if (tcp->tcp_rthdr != NULL) {
4546 		mi_free(tcp->tcp_rthdr);
4547 		tcp->tcp_rthdr = NULL;
4548 		tcp->tcp_rthdrlen = 0;
4549 	}
4550 	ASSERT(tcp->tcp_rthdrlen == 0);
4551 
4552 	ipp = &tcp->tcp_sticky_ipp;
4553 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4554 	    IPPF_RTHDR))
4555 		ip6_pkt_free(ipp);
4556 
4557 	/*
4558 	 * Free memory associated with the tcp/ip header template.
4559 	 */
4560 
4561 	if (tcp->tcp_iphc != NULL)
4562 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4563 
4564 	/*
4565 	 * Following is really a blowing away a union.
4566 	 * It happens to have exactly two members of identical size
4567 	 * the following code is enough.
4568 	 */
4569 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4570 
4571 	if (tcp->tcp_tracebuf != NULL) {
4572 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4573 		tcp->tcp_tracebuf = NULL;
4574 	}
4575 }
4576 
4577 
4578 /*
4579  * Put a connection confirmation message upstream built from the
4580  * address information within 'iph' and 'tcph'.  Report our success or failure.
4581  */
4582 static boolean_t
4583 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4584     mblk_t **defermp)
4585 {
4586 	sin_t	sin;
4587 	sin6_t	sin6;
4588 	mblk_t	*mp;
4589 	char	*optp = NULL;
4590 	int	optlen = 0;
4591 	cred_t	*cr;
4592 
4593 	if (defermp != NULL)
4594 		*defermp = NULL;
4595 
4596 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4597 		/*
4598 		 * Return in T_CONN_CON results of option negotiation through
4599 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4600 		 * negotiation, then what is received from remote end needs
4601 		 * to be taken into account but there is no such thing (yet?)
4602 		 * in our TCP/IP.
4603 		 * Note: We do not use mi_offset_param() here as
4604 		 * tcp_opts_conn_req contents do not directly come from
4605 		 * an application and are either generated in kernel or
4606 		 * from user input that was already verified.
4607 		 */
4608 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4609 		optp = (char *)(mp->b_rptr +
4610 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4611 		optlen = (int)
4612 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4613 	}
4614 
4615 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4616 		ipha_t *ipha = (ipha_t *)iphdr;
4617 
4618 		/* packet is IPv4 */
4619 		if (tcp->tcp_family == AF_INET) {
4620 			sin = sin_null;
4621 			sin.sin_addr.s_addr = ipha->ipha_src;
4622 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4623 			sin.sin_family = AF_INET;
4624 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4625 			    (int)sizeof (sin_t), optp, optlen);
4626 		} else {
4627 			sin6 = sin6_null;
4628 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4629 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4630 			sin6.sin6_family = AF_INET6;
4631 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4632 			    (int)sizeof (sin6_t), optp, optlen);
4633 
4634 		}
4635 	} else {
4636 		ip6_t	*ip6h = (ip6_t *)iphdr;
4637 
4638 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4639 		ASSERT(tcp->tcp_family == AF_INET6);
4640 		sin6 = sin6_null;
4641 		sin6.sin6_addr = ip6h->ip6_src;
4642 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4643 		sin6.sin6_family = AF_INET6;
4644 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4645 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4646 		    (int)sizeof (sin6_t), optp, optlen);
4647 	}
4648 
4649 	if (!mp)
4650 		return (B_FALSE);
4651 
4652 	if ((cr = DB_CRED(idmp)) != NULL) {
4653 		mblk_setcred(mp, cr);
4654 		DB_CPID(mp) = DB_CPID(idmp);
4655 	}
4656 
4657 	if (defermp == NULL)
4658 		putnext(tcp->tcp_rq, mp);
4659 	else
4660 		*defermp = mp;
4661 
4662 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4663 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4664 	return (B_TRUE);
4665 }
4666 
4667 /*
4668  * Defense for the SYN attack -
4669  * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
4670  *    one that doesn't have the dontdrop bit set.
4671  * 2. Don't drop a SYN request before its first timeout. This gives every
4672  *    request at least til the first timeout to complete its 3-way handshake.
4673  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4674  *    requests currently on the queue that has timed out. This will be used
4675  *    as an indicator of whether an attack is under way, so that appropriate
4676  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4677  *    either when eager goes into ESTABLISHED, or gets freed up.)
4678  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4679  *    # of timeout drops back to <= q0len/32 => SYN alert off
4680  */
4681 static boolean_t
4682 tcp_drop_q0(tcp_t *tcp)
4683 {
4684 	tcp_t	*eager;
4685 
4686 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4687 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4688 	/*
4689 	 * New one is added after next_q0 so prev_q0 points to the oldest
4690 	 * Also do not drop any established connections that are deferred on
4691 	 * q0 due to q being full
4692 	 */
4693 
4694 	eager = tcp->tcp_eager_prev_q0;
4695 	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
4696 		eager = eager->tcp_eager_prev_q0;
4697 		if (eager == tcp) {
4698 			eager = tcp->tcp_eager_prev_q0;
4699 			break;
4700 		}
4701 	}
4702 	if (eager->tcp_syn_rcvd_timeout == 0)
4703 		return (B_FALSE);
4704 
4705 	if (tcp->tcp_debug) {
4706 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4707 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4708 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
4709 		    tcp->tcp_conn_req_cnt_q0,
4710 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4711 	}
4712 
4713 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
4714 
4715 	/*
4716 	 * need to do refhold here because the selected eager could
4717 	 * be removed by someone else if we release the eager lock.
4718 	 */
4719 	CONN_INC_REF(eager->tcp_connp);
4720 	mutex_exit(&tcp->tcp_eager_lock);
4721 
4722 	/* Mark the IRE created for this SYN request temporary */
4723 	tcp_ip_ire_mark_advice(eager);
4724 	(void) tcp_clean_death(eager, ETIMEDOUT, 5);
4725 	CONN_DEC_REF(eager->tcp_connp);
4726 
4727 	mutex_enter(&tcp->tcp_eager_lock);
4728 	return (B_TRUE);
4729 }
4730 
4731 int
4732 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4733     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4734 {
4735 	tcp_t 		*ltcp = lconnp->conn_tcp;
4736 	tcp_t		*tcp = connp->conn_tcp;
4737 	mblk_t		*tpi_mp;
4738 	ipha_t		*ipha;
4739 	ip6_t		*ip6h;
4740 	sin6_t 		sin6;
4741 	in6_addr_t 	v6dst;
4742 	int		err;
4743 	int		ifindex = 0;
4744 	cred_t		*cr;
4745 
4746 	if (ipvers == IPV4_VERSION) {
4747 		ipha = (ipha_t *)mp->b_rptr;
4748 
4749 		connp->conn_send = ip_output;
4750 		connp->conn_recv = tcp_input;
4751 
4752 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4753 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4754 
4755 		sin6 = sin6_null;
4756 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4757 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4758 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4759 		sin6.sin6_family = AF_INET6;
4760 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4761 		    lconnp->conn_zoneid);
4762 		if (tcp->tcp_recvdstaddr) {
4763 			sin6_t	sin6d;
4764 
4765 			sin6d = sin6_null;
4766 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4767 			    &sin6d.sin6_addr);
4768 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4769 			sin6d.sin6_family = AF_INET;
4770 			tpi_mp = mi_tpi_extconn_ind(NULL,
4771 			    (char *)&sin6d, sizeof (sin6_t),
4772 			    (char *)&tcp,
4773 			    (t_scalar_t)sizeof (intptr_t),
4774 			    (char *)&sin6d, sizeof (sin6_t),
4775 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4776 		} else {
4777 			tpi_mp = mi_tpi_conn_ind(NULL,
4778 			    (char *)&sin6, sizeof (sin6_t),
4779 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4780 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4781 		}
4782 	} else {
4783 		ip6h = (ip6_t *)mp->b_rptr;
4784 
4785 		connp->conn_send = ip_output_v6;
4786 		connp->conn_recv = tcp_input;
4787 
4788 		connp->conn_srcv6 = ip6h->ip6_dst;
4789 		connp->conn_remv6 = ip6h->ip6_src;
4790 
4791 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4792 		ifindex = (int)DB_CKSUMSTUFF(mp);
4793 		DB_CKSUMSTUFF(mp) = 0;
4794 
4795 		sin6 = sin6_null;
4796 		sin6.sin6_addr = ip6h->ip6_src;
4797 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4798 		sin6.sin6_family = AF_INET6;
4799 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4800 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4801 		    lconnp->conn_zoneid);
4802 
4803 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4804 			/* Pass up the scope_id of remote addr */
4805 			sin6.sin6_scope_id = ifindex;
4806 		} else {
4807 			sin6.sin6_scope_id = 0;
4808 		}
4809 		if (tcp->tcp_recvdstaddr) {
4810 			sin6_t	sin6d;
4811 
4812 			sin6d = sin6_null;
4813 			sin6.sin6_addr = ip6h->ip6_dst;
4814 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4815 			sin6d.sin6_family = AF_INET;
4816 			tpi_mp = mi_tpi_extconn_ind(NULL,
4817 			    (char *)&sin6d, sizeof (sin6_t),
4818 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4819 			    (char *)&sin6d, sizeof (sin6_t),
4820 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4821 		} else {
4822 			tpi_mp = mi_tpi_conn_ind(NULL,
4823 			    (char *)&sin6, sizeof (sin6_t),
4824 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4825 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4826 		}
4827 	}
4828 
4829 	if (tpi_mp == NULL)
4830 		return (ENOMEM);
4831 
4832 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4833 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4834 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4835 	connp->conn_fully_bound = B_FALSE;
4836 
4837 	if (tcp_trace)
4838 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4839 
4840 	/* Inherit information from the "parent" */
4841 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4842 	tcp->tcp_family = ltcp->tcp_family;
4843 	tcp->tcp_wq = ltcp->tcp_wq;
4844 	tcp->tcp_rq = ltcp->tcp_rq;
4845 	tcp->tcp_mss = tcp_mss_def_ipv6;
4846 	tcp->tcp_detached = B_TRUE;
4847 	if ((err = tcp_init_values(tcp)) != 0) {
4848 		freemsg(tpi_mp);
4849 		return (err);
4850 	}
4851 
4852 	if (ipvers == IPV4_VERSION) {
4853 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4854 			freemsg(tpi_mp);
4855 			return (err);
4856 		}
4857 		ASSERT(tcp->tcp_ipha != NULL);
4858 	} else {
4859 		/* ifindex must be already set */
4860 		ASSERT(ifindex != 0);
4861 
4862 		if (ltcp->tcp_bound_if != 0) {
4863 			/*
4864 			 * Set newtcp's bound_if equal to
4865 			 * listener's value. If ifindex is
4866 			 * not the same as ltcp->tcp_bound_if,
4867 			 * it must be a packet for the ipmp group
4868 			 * of interfaces
4869 			 */
4870 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4871 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4872 			tcp->tcp_bound_if = ifindex;
4873 		}
4874 
4875 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4876 		tcp->tcp_recvifindex = 0;
4877 		tcp->tcp_recvhops = 0xffffffffU;
4878 		ASSERT(tcp->tcp_ip6h != NULL);
4879 	}
4880 
4881 	tcp->tcp_lport = ltcp->tcp_lport;
4882 
4883 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4884 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4885 			/*
4886 			 * Listener had options of some sort; eager inherits.
4887 			 * Free up the eager template and allocate one
4888 			 * of the right size.
4889 			 */
4890 			if (tcp->tcp_hdr_grown) {
4891 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4892 			} else {
4893 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4894 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4895 			}
4896 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4897 			    KM_NOSLEEP);
4898 			if (tcp->tcp_iphc == NULL) {
4899 				tcp->tcp_iphc_len = 0;
4900 				freemsg(tpi_mp);
4901 				return (ENOMEM);
4902 			}
4903 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4904 			tcp->tcp_hdr_grown = B_TRUE;
4905 		}
4906 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4907 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4908 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4909 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4910 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4911 
4912 		/*
4913 		 * Copy the IP+TCP header template from listener to eager
4914 		 */
4915 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4916 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4917 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4918 			    IPPROTO_RAW) {
4919 				tcp->tcp_ip6h =
4920 				    (ip6_t *)(tcp->tcp_iphc +
4921 					sizeof (ip6i_t));
4922 			} else {
4923 				tcp->tcp_ip6h =
4924 				    (ip6_t *)(tcp->tcp_iphc);
4925 			}
4926 			tcp->tcp_ipha = NULL;
4927 		} else {
4928 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4929 			tcp->tcp_ip6h = NULL;
4930 		}
4931 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4932 		    tcp->tcp_ip_hdr_len);
4933 	} else {
4934 		/*
4935 		 * only valid case when ipversion of listener and
4936 		 * eager differ is when listener is IPv6 and
4937 		 * eager is IPv4.
4938 		 * Eager header template has been initialized to the
4939 		 * maximum v4 header sizes, which includes space for
4940 		 * TCP and IP options.
4941 		 */
4942 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4943 		    (tcp->tcp_ipversion == IPV4_VERSION));
4944 		ASSERT(tcp->tcp_iphc_len >=
4945 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4946 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4947 		/* copy IP header fields individually */
4948 		tcp->tcp_ipha->ipha_ttl =
4949 		    ltcp->tcp_ip6h->ip6_hops;
4950 		bcopy(ltcp->tcp_tcph->th_lport,
4951 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4952 	}
4953 
4954 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4955 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4956 	    sizeof (in_port_t));
4957 
4958 	if (ltcp->tcp_lport == 0) {
4959 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4960 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4961 		    sizeof (in_port_t));
4962 	}
4963 
4964 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4965 		ASSERT(ipha != NULL);
4966 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4967 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4968 
4969 		/* Source routing option copyover (reverse it) */
4970 		if (tcp_rev_src_routes)
4971 			tcp_opt_reverse(tcp, ipha);
4972 	} else {
4973 		ASSERT(ip6h != NULL);
4974 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4975 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4976 	}
4977 
4978 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4979 	/*
4980 	 * If the SYN contains a credential, it's a loopback packet; attach
4981 	 * the credential to the TPI message.
4982 	 */
4983 	if ((cr = DB_CRED(idmp)) != NULL) {
4984 		mblk_setcred(tpi_mp, cr);
4985 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4986 	}
4987 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4988 
4989 	/* Inherit the listener's SSL protection state */
4990 
4991 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4992 		kssl_hold_ent(tcp->tcp_kssl_ent);
4993 		tcp->tcp_kssl_pending = B_TRUE;
4994 	}
4995 
4996 	return (0);
4997 }
4998 
4999 
5000 int
5001 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5002     tcph_t *tcph, mblk_t *idmp)
5003 {
5004 	tcp_t 		*ltcp = lconnp->conn_tcp;
5005 	tcp_t		*tcp = connp->conn_tcp;
5006 	sin_t		sin;
5007 	mblk_t		*tpi_mp = NULL;
5008 	int		err;
5009 	cred_t		*cr;
5010 
5011 	sin = sin_null;
5012 	sin.sin_addr.s_addr = ipha->ipha_src;
5013 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5014 	sin.sin_family = AF_INET;
5015 	if (ltcp->tcp_recvdstaddr) {
5016 		sin_t	sind;
5017 
5018 		sind = sin_null;
5019 		sind.sin_addr.s_addr = ipha->ipha_dst;
5020 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5021 		sind.sin_family = AF_INET;
5022 		tpi_mp = mi_tpi_extconn_ind(NULL,
5023 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5024 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5025 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5026 	} else {
5027 		tpi_mp = mi_tpi_conn_ind(NULL,
5028 		    (char *)&sin, sizeof (sin_t),
5029 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5030 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5031 	}
5032 
5033 	if (tpi_mp == NULL) {
5034 		return (ENOMEM);
5035 	}
5036 
5037 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5038 	connp->conn_send = ip_output;
5039 	connp->conn_recv = tcp_input;
5040 	connp->conn_fully_bound = B_FALSE;
5041 
5042 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5043 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5044 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5045 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5046 
5047 	if (tcp_trace) {
5048 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5049 	}
5050 
5051 	/* Inherit information from the "parent" */
5052 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5053 	tcp->tcp_family = ltcp->tcp_family;
5054 	tcp->tcp_wq = ltcp->tcp_wq;
5055 	tcp->tcp_rq = ltcp->tcp_rq;
5056 	tcp->tcp_mss = tcp_mss_def_ipv4;
5057 	tcp->tcp_detached = B_TRUE;
5058 	if ((err = tcp_init_values(tcp)) != 0) {
5059 		freemsg(tpi_mp);
5060 		return (err);
5061 	}
5062 
5063 	/*
5064 	 * Let's make sure that eager tcp template has enough space to
5065 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5066 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5067 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5068 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5069 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5070 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5071 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5072 	 */
5073 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5074 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5075 
5076 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5077 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5078 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5079 	tcp->tcp_ttl = ltcp->tcp_ttl;
5080 	tcp->tcp_tos = ltcp->tcp_tos;
5081 
5082 	/* Copy the IP+TCP header template from listener to eager */
5083 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5084 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5085 	tcp->tcp_ip6h = NULL;
5086 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5087 	    tcp->tcp_ip_hdr_len);
5088 
5089 	/* Initialize the IP addresses and Ports */
5090 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5091 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5092 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5093 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5094 
5095 	/* Source routing option copyover (reverse it) */
5096 	if (tcp_rev_src_routes)
5097 		tcp_opt_reverse(tcp, ipha);
5098 
5099 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5100 
5101 	/*
5102 	 * If the SYN contains a credential, it's a loopback packet; attach
5103 	 * the credential to the TPI message.
5104 	 */
5105 	if ((cr = DB_CRED(idmp)) != NULL) {
5106 		mblk_setcred(tpi_mp, cr);
5107 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5108 	}
5109 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5110 
5111 	/* Inherit the listener's SSL protection state */
5112 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5113 		kssl_hold_ent(tcp->tcp_kssl_ent);
5114 		tcp->tcp_kssl_pending = B_TRUE;
5115 	}
5116 
5117 	return (0);
5118 }
5119 
5120 /*
5121  * sets up conn for ipsec.
5122  * if the first mblk is M_CTL it is consumed and mpp is updated.
5123  * in case of error mpp is freed.
5124  */
5125 conn_t *
5126 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5127 {
5128 	conn_t 		*connp = tcp->tcp_connp;
5129 	conn_t 		*econnp;
5130 	squeue_t 	*new_sqp;
5131 	mblk_t 		*first_mp = *mpp;
5132 	mblk_t		*mp = *mpp;
5133 	boolean_t	mctl_present = B_FALSE;
5134 	uint_t		ipvers;
5135 
5136 	econnp = tcp_get_conn(sqp);
5137 	if (econnp == NULL) {
5138 		freemsg(first_mp);
5139 		return (NULL);
5140 	}
5141 	if (DB_TYPE(mp) == M_CTL) {
5142 		if (mp->b_cont == NULL ||
5143 		    mp->b_cont->b_datap->db_type != M_DATA) {
5144 			freemsg(first_mp);
5145 			return (NULL);
5146 		}
5147 		mp = mp->b_cont;
5148 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5149 			freemsg(first_mp);
5150 			return (NULL);
5151 		}
5152 
5153 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5154 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5155 		mctl_present = B_TRUE;
5156 	} else {
5157 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5158 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5159 	}
5160 
5161 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5162 	DB_CKSUMSTART(mp) = 0;
5163 
5164 	ASSERT(OK_32PTR(mp->b_rptr));
5165 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5166 	if (ipvers == IPV4_VERSION) {
5167 		uint16_t  	*up;
5168 		uint32_t	ports;
5169 		ipha_t		*ipha;
5170 
5171 		ipha = (ipha_t *)mp->b_rptr;
5172 		up = (uint16_t *)((uchar_t *)ipha +
5173 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5174 		ports = *(uint32_t *)up;
5175 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5176 		    ipha->ipha_dst, ipha->ipha_src, ports);
5177 	} else {
5178 		uint16_t  	*up;
5179 		uint32_t	ports;
5180 		uint16_t	ip_hdr_len;
5181 		uint8_t		*nexthdrp;
5182 		ip6_t 		*ip6h;
5183 		tcph_t		*tcph;
5184 
5185 		ip6h = (ip6_t *)mp->b_rptr;
5186 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5187 			ip_hdr_len = IPV6_HDR_LEN;
5188 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5189 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5190 			CONN_DEC_REF(econnp);
5191 			freemsg(first_mp);
5192 			return (NULL);
5193 		}
5194 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5195 		up = (uint16_t *)tcph->th_lport;
5196 		ports = *(uint32_t *)up;
5197 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5198 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5199 	}
5200 
5201 	/*
5202 	 * The caller already ensured that there is a sqp present.
5203 	 */
5204 	econnp->conn_sqp = new_sqp;
5205 
5206 	if (connp->conn_policy != NULL) {
5207 		ipsec_in_t *ii;
5208 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5209 		ASSERT(ii->ipsec_in_policy == NULL);
5210 		IPPH_REFHOLD(connp->conn_policy);
5211 		ii->ipsec_in_policy = connp->conn_policy;
5212 
5213 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5214 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5215 			CONN_DEC_REF(econnp);
5216 			freemsg(first_mp);
5217 			return (NULL);
5218 		}
5219 	}
5220 
5221 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5222 		CONN_DEC_REF(econnp);
5223 		freemsg(first_mp);
5224 		return (NULL);
5225 	}
5226 
5227 	/*
5228 	 * If we know we have some policy, pass the "IPSEC"
5229 	 * options size TCP uses this adjust the MSS.
5230 	 */
5231 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5232 	if (mctl_present) {
5233 		freeb(first_mp);
5234 		*mpp = mp;
5235 	}
5236 
5237 	return (econnp);
5238 }
5239 
5240 /*
5241  * tcp_get_conn/tcp_free_conn
5242  *
5243  * tcp_get_conn is used to get a clean tcp connection structure.
5244  * It tries to reuse the connections put on the freelist by the
5245  * time_wait_collector failing which it goes to kmem_cache. This
5246  * way has two benefits compared to just allocating from and
5247  * freeing to kmem_cache.
5248  * 1) The time_wait_collector can free (which includes the cleanup)
5249  * outside the squeue. So when the interrupt comes, we have a clean
5250  * connection sitting in the freelist. Obviously, this buys us
5251  * performance.
5252  *
5253  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5254  * has multiple disadvantages - tying up the squeue during alloc, and the
5255  * fact that IPSec policy initialization has to happen here which
5256  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5257  * But allocating the conn/tcp in IP land is also not the best since
5258  * we can't check the 'q' and 'q0' which are protected by squeue and
5259  * blindly allocate memory which might have to be freed here if we are
5260  * not allowed to accept the connection. By using the freelist and
5261  * putting the conn/tcp back in freelist, we don't pay a penalty for
5262  * allocating memory without checking 'q/q0' and freeing it if we can't
5263  * accept the connection.
5264  *
5265  * Care should be taken to put the conn back in the same squeue's freelist
5266  * from which it was allocated. Best results are obtained if conn is
5267  * allocated from listener's squeue and freed to the same. Time wait
5268  * collector will free up the freelist is the connection ends up sitting
5269  * there for too long.
5270  */
5271 void *
5272 tcp_get_conn(void *arg)
5273 {
5274 	tcp_t			*tcp = NULL;
5275 	conn_t			*connp = NULL;
5276 	squeue_t		*sqp = (squeue_t *)arg;
5277 	tcp_squeue_priv_t 	*tcp_time_wait;
5278 
5279 	tcp_time_wait =
5280 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5281 
5282 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5283 	tcp = tcp_time_wait->tcp_free_list;
5284 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5285 	if (tcp != NULL) {
5286 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5287 		tcp_time_wait->tcp_free_list_cnt--;
5288 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5289 		tcp->tcp_time_wait_next = NULL;
5290 		connp = tcp->tcp_connp;
5291 		connp->conn_flags |= IPCL_REUSED;
5292 		return ((void *)connp);
5293 	}
5294 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5295 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
5296 		return (NULL);
5297 	return ((void *)connp);
5298 }
5299 
5300 /*
5301  * Update the cached label for the given tcp_t.  This should be called once per
5302  * connection, and before any packets are sent or tcp_process_options is
5303  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5304  */
5305 static boolean_t
5306 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5307 {
5308 	conn_t *connp = tcp->tcp_connp;
5309 
5310 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5311 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5312 		int added;
5313 
5314 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5315 		    connp->conn_mac_exempt) != 0)
5316 			return (B_FALSE);
5317 
5318 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5319 		if (added == -1)
5320 			return (B_FALSE);
5321 		tcp->tcp_hdr_len += added;
5322 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5323 		tcp->tcp_ip_hdr_len += added;
5324 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5325 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5326 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5327 			    tcp->tcp_hdr_len);
5328 			if (added == -1)
5329 				return (B_FALSE);
5330 			tcp->tcp_hdr_len += added;
5331 			tcp->tcp_tcph = (tcph_t *)
5332 			    ((uchar_t *)tcp->tcp_tcph + added);
5333 			tcp->tcp_ip_hdr_len += added;
5334 		}
5335 	} else {
5336 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5337 
5338 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5339 		    connp->conn_mac_exempt) != 0)
5340 			return (B_FALSE);
5341 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5342 		    &tcp->tcp_label_len, optbuf) != 0)
5343 			return (B_FALSE);
5344 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5345 			return (B_FALSE);
5346 	}
5347 
5348 	connp->conn_ulp_labeled = 1;
5349 
5350 	return (B_TRUE);
5351 }
5352 
5353 /* BEGIN CSTYLED */
5354 /*
5355  *
5356  * The sockfs ACCEPT path:
5357  * =======================
5358  *
5359  * The eager is now established in its own perimeter as soon as SYN is
5360  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5361  * completes the accept processing on the acceptor STREAM. The sending
5362  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5363  * listener but a TLI/XTI listener completes the accept processing
5364  * on the listener perimeter.
5365  *
5366  * Common control flow for 3 way handshake:
5367  * ----------------------------------------
5368  *
5369  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5370  *					-> tcp_conn_request()
5371  *
5372  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5373  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5374  *
5375  * Sockfs ACCEPT Path:
5376  * -------------------
5377  *
5378  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5379  * as STREAM entry point)
5380  *
5381  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5382  *
5383  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5384  * association (we are not behind eager's squeue but sockfs is protecting us
5385  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5386  * is changed to point at tcp_wput().
5387  *
5388  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5389  * listener (done on listener's perimeter).
5390  *
5391  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5392  * accept.
5393  *
5394  * TLI/XTI client ACCEPT path:
5395  * ---------------------------
5396  *
5397  * soaccept() sends T_CONN_RES on the listener STREAM.
5398  *
5399  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5400  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5401  *
5402  * Locks:
5403  * ======
5404  *
5405  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5406  * and listeners->tcp_eager_next_q.
5407  *
5408  * Referencing:
5409  * ============
5410  *
5411  * 1) We start out in tcp_conn_request by eager placing a ref on
5412  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5413  *
5414  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5415  * doing so we place a ref on the eager. This ref is finally dropped at the
5416  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5417  * reference is dropped by the squeue framework.
5418  *
5419  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5420  *
5421  * The reference must be released by the same entity that added the reference
5422  * In the above scheme, the eager is the entity that adds and releases the
5423  * references. Note that tcp_accept_finish executes in the squeue of the eager
5424  * (albeit after it is attached to the acceptor stream). Though 1. executes
5425  * in the listener's squeue, the eager is nascent at this point and the
5426  * reference can be considered to have been added on behalf of the eager.
5427  *
5428  * Eager getting a Reset or listener closing:
5429  * ==========================================
5430  *
5431  * Once the listener and eager are linked, the listener never does the unlink.
5432  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5433  * a message on all eager perimeter. The eager then does the unlink, clears
5434  * any pointers to the listener's queue and drops the reference to the
5435  * listener. The listener waits in tcp_close outside the squeue until its
5436  * refcount has dropped to 1. This ensures that the listener has waited for
5437  * all eagers to clear their association with the listener.
5438  *
5439  * Similarly, if eager decides to go away, it can unlink itself and close.
5440  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5441  * the reference to eager is still valid because of the extra ref we put
5442  * in tcp_send_conn_ind.
5443  *
5444  * Listener can always locate the eager under the protection
5445  * of the listener->tcp_eager_lock, and then do a refhold
5446  * on the eager during the accept processing.
5447  *
5448  * The acceptor stream accesses the eager in the accept processing
5449  * based on the ref placed on eager before sending T_conn_ind.
5450  * The only entity that can negate this refhold is a listener close
5451  * which is mutually exclusive with an active acceptor stream.
5452  *
5453  * Eager's reference on the listener
5454  * ===================================
5455  *
5456  * If the accept happens (even on a closed eager) the eager drops its
5457  * reference on the listener at the start of tcp_accept_finish. If the
5458  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5459  * the reference is dropped in tcp_closei_local. If the listener closes,
5460  * the reference is dropped in tcp_eager_kill. In all cases the reference
5461  * is dropped while executing in the eager's context (squeue).
5462  */
5463 /* END CSTYLED */
5464 
5465 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5466 
5467 /*
5468  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5469  * tcp_rput_data will not see any SYN packets.
5470  */
5471 /* ARGSUSED */
5472 void
5473 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5474 {
5475 	tcph_t		*tcph;
5476 	uint32_t	seg_seq;
5477 	tcp_t		*eager;
5478 	uint_t		ipvers;
5479 	ipha_t		*ipha;
5480 	ip6_t		*ip6h;
5481 	int		err;
5482 	conn_t		*econnp = NULL;
5483 	squeue_t	*new_sqp;
5484 	mblk_t		*mp1;
5485 	uint_t 		ip_hdr_len;
5486 	conn_t		*connp = (conn_t *)arg;
5487 	tcp_t		*tcp = connp->conn_tcp;
5488 	ire_t		*ire;
5489 	cred_t		*credp;
5490 
5491 	if (tcp->tcp_state != TCPS_LISTEN)
5492 		goto error2;
5493 
5494 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5495 
5496 	mutex_enter(&tcp->tcp_eager_lock);
5497 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5498 		mutex_exit(&tcp->tcp_eager_lock);
5499 		TCP_STAT(tcp_listendrop);
5500 		BUMP_MIB(&tcp_mib, tcpListenDrop);
5501 		if (tcp->tcp_debug) {
5502 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5503 			    "tcp_conn_request: listen backlog (max=%d) "
5504 			    "overflow (%d pending) on %s",
5505 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5506 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5507 		}
5508 		goto error2;
5509 	}
5510 
5511 	if (tcp->tcp_conn_req_cnt_q0 >=
5512 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
5513 		/*
5514 		 * Q0 is full. Drop a pending half-open req from the queue
5515 		 * to make room for the new SYN req. Also mark the time we
5516 		 * drop a SYN.
5517 		 *
5518 		 * A more aggressive defense against SYN attack will
5519 		 * be to set the "tcp_syn_defense" flag now.
5520 		 */
5521 		TCP_STAT(tcp_listendropq0);
5522 		tcp->tcp_last_rcv_lbolt = lbolt64;
5523 		if (!tcp_drop_q0(tcp)) {
5524 			mutex_exit(&tcp->tcp_eager_lock);
5525 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
5526 			if (tcp->tcp_debug) {
5527 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5528 				    "tcp_conn_request: listen half-open queue "
5529 				    "(max=%d) full (%d pending) on %s",
5530 				    tcp_conn_req_max_q0,
5531 				    tcp->tcp_conn_req_cnt_q0,
5532 				    tcp_display(tcp, NULL,
5533 				    DISP_PORT_ONLY));
5534 			}
5535 			goto error2;
5536 		}
5537 	}
5538 	mutex_exit(&tcp->tcp_eager_lock);
5539 
5540 	/*
5541 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5542 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5543 	 * link local address.  If IPSec is enabled, db_struioflag has
5544 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5545 	 * otherwise an error case if neither of them is set.
5546 	 */
5547 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5548 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5549 		DB_CKSUMSTART(mp) = 0;
5550 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5551 		econnp = (conn_t *)tcp_get_conn(arg2);
5552 		if (econnp == NULL)
5553 			goto error2;
5554 		econnp->conn_sqp = new_sqp;
5555 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5556 		/*
5557 		 * mp is updated in tcp_get_ipsec_conn().
5558 		 */
5559 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5560 		if (econnp == NULL) {
5561 			/*
5562 			 * mp freed by tcp_get_ipsec_conn.
5563 			 */
5564 			return;
5565 		}
5566 	} else {
5567 		goto error2;
5568 	}
5569 
5570 	ASSERT(DB_TYPE(mp) == M_DATA);
5571 
5572 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5573 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5574 	ASSERT(OK_32PTR(mp->b_rptr));
5575 	if (ipvers == IPV4_VERSION) {
5576 		ipha = (ipha_t *)mp->b_rptr;
5577 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5578 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5579 	} else {
5580 		ip6h = (ip6_t *)mp->b_rptr;
5581 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5582 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5583 	}
5584 
5585 	if (tcp->tcp_family == AF_INET) {
5586 		ASSERT(ipvers == IPV4_VERSION);
5587 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5588 	} else {
5589 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5590 	}
5591 
5592 	if (err)
5593 		goto error3;
5594 
5595 	eager = econnp->conn_tcp;
5596 
5597 	/* Inherit various TCP parameters from the listener */
5598 	eager->tcp_naglim = tcp->tcp_naglim;
5599 	eager->tcp_first_timer_threshold =
5600 	    tcp->tcp_first_timer_threshold;
5601 	eager->tcp_second_timer_threshold =
5602 	    tcp->tcp_second_timer_threshold;
5603 
5604 	eager->tcp_first_ctimer_threshold =
5605 	    tcp->tcp_first_ctimer_threshold;
5606 	eager->tcp_second_ctimer_threshold =
5607 	    tcp->tcp_second_ctimer_threshold;
5608 
5609 	/*
5610 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5611 	 * If it does not, the eager's receive window will be set to the
5612 	 * listener's receive window later in this function.
5613 	 */
5614 	eager->tcp_rwnd = 0;
5615 
5616 	/*
5617 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5618 	 * calling tcp_process_options() where tcp_mss_set() is called
5619 	 * to set the initial cwnd.
5620 	 */
5621 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5622 
5623 	/*
5624 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5625 	 * zone id before the accept is completed in tcp_wput_accept().
5626 	 */
5627 	econnp->conn_zoneid = connp->conn_zoneid;
5628 	econnp->conn_allzones = connp->conn_allzones;
5629 
5630 	/* Copy nexthop information from listener to eager */
5631 	if (connp->conn_nexthop_set) {
5632 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5633 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5634 	}
5635 
5636 	/*
5637 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5638 	 * eager is accepted
5639 	 */
5640 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5641 	crhold(credp);
5642 
5643 	/*
5644 	 * If the caller has the process-wide flag set, then default to MAC
5645 	 * exempt mode.  This allows read-down to unlabeled hosts.
5646 	 */
5647 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5648 		econnp->conn_mac_exempt = B_TRUE;
5649 
5650 	if (is_system_labeled()) {
5651 		cred_t *cr;
5652 
5653 		if (connp->conn_mlp_type != mlptSingle) {
5654 			cr = econnp->conn_peercred = DB_CRED(mp);
5655 			if (cr != NULL)
5656 				crhold(cr);
5657 			else
5658 				cr = econnp->conn_cred;
5659 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5660 			    econnp, cred_t *, cr)
5661 		} else {
5662 			cr = econnp->conn_cred;
5663 			DTRACE_PROBE2(syn_accept, conn_t *,
5664 			    econnp, cred_t *, cr)
5665 		}
5666 
5667 		if (!tcp_update_label(eager, cr)) {
5668 			DTRACE_PROBE3(
5669 			    tx__ip__log__error__connrequest__tcp,
5670 			    char *, "eager connp(1) label on SYN mp(2) failed",
5671 			    conn_t *, econnp, mblk_t *, mp);
5672 			goto error3;
5673 		}
5674 	}
5675 
5676 	eager->tcp_hard_binding = B_TRUE;
5677 
5678 	tcp_bind_hash_insert(&tcp_bind_fanout[
5679 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5680 
5681 	CL_INET_CONNECT(eager);
5682 
5683 	/*
5684 	 * No need to check for multicast destination since ip will only pass
5685 	 * up multicasts to those that have expressed interest
5686 	 * TODO: what about rejecting broadcasts?
5687 	 * Also check that source is not a multicast or broadcast address.
5688 	 */
5689 	eager->tcp_state = TCPS_SYN_RCVD;
5690 
5691 
5692 	/*
5693 	 * There should be no ire in the mp as we are being called after
5694 	 * receiving the SYN.
5695 	 */
5696 	ASSERT(tcp_ire_mp(mp) == NULL);
5697 
5698 	/*
5699 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5700 	 */
5701 
5702 	if (tcp_adapt_ire(eager, NULL) == 0) {
5703 		/* Undo the bind_hash_insert */
5704 		tcp_bind_hash_remove(eager);
5705 		goto error3;
5706 	}
5707 
5708 	/* Process all TCP options. */
5709 	tcp_process_options(eager, tcph);
5710 
5711 	/* Is the other end ECN capable? */
5712 	if (tcp_ecn_permitted >= 1 &&
5713 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5714 		eager->tcp_ecn_ok = B_TRUE;
5715 	}
5716 
5717 	/*
5718 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5719 	 * window size changed via SO_RCVBUF option.  First round up the
5720 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5721 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5722 	 * setting.
5723 	 *
5724 	 * Note if there is a rpipe metric associated with the remote host,
5725 	 * we should not inherit receive window size from listener.
5726 	 */
5727 	eager->tcp_rwnd = MSS_ROUNDUP(
5728 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5729 	    eager->tcp_rwnd), eager->tcp_mss);
5730 	if (eager->tcp_snd_ws_ok)
5731 		tcp_set_ws_value(eager);
5732 	/*
5733 	 * Note that this is the only place tcp_rwnd_set() is called for
5734 	 * accepting a connection.  We need to call it here instead of
5735 	 * after the 3-way handshake because we need to tell the other
5736 	 * side our rwnd in the SYN-ACK segment.
5737 	 */
5738 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5739 
5740 	/*
5741 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5742 	 * via soaccept()->soinheritoptions() which essentially applies
5743 	 * all the listener options to the new STREAM. The options that we
5744 	 * need to take care of are:
5745 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5746 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5747 	 * SO_SNDBUF, SO_RCVBUF.
5748 	 *
5749 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5750 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5751 	 *		tcp_maxpsz_set() gets called later from
5752 	 *		tcp_accept_finish(), the option takes effect.
5753 	 *
5754 	 */
5755 	/* Set the TCP options */
5756 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5757 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5758 	eager->tcp_oobinline = tcp->tcp_oobinline;
5759 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5760 	eager->tcp_broadcast = tcp->tcp_broadcast;
5761 	eager->tcp_useloopback = tcp->tcp_useloopback;
5762 	eager->tcp_dontroute = tcp->tcp_dontroute;
5763 	eager->tcp_linger = tcp->tcp_linger;
5764 	eager->tcp_lingertime = tcp->tcp_lingertime;
5765 	if (tcp->tcp_ka_enabled)
5766 		eager->tcp_ka_enabled = 1;
5767 
5768 	/* Set the IP options */
5769 	econnp->conn_broadcast = connp->conn_broadcast;
5770 	econnp->conn_loopback = connp->conn_loopback;
5771 	econnp->conn_dontroute = connp->conn_dontroute;
5772 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5773 
5774 	/* Put a ref on the listener for the eager. */
5775 	CONN_INC_REF(connp);
5776 	mutex_enter(&tcp->tcp_eager_lock);
5777 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5778 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5779 	tcp->tcp_eager_next_q0 = eager;
5780 	eager->tcp_eager_prev_q0 = tcp;
5781 
5782 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5783 	eager->tcp_listener = tcp;
5784 	eager->tcp_saved_listener = tcp;
5785 
5786 	/*
5787 	 * Tag this detached tcp vector for later retrieval
5788 	 * by our listener client in tcp_accept().
5789 	 */
5790 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5791 	tcp->tcp_conn_req_cnt_q0++;
5792 	if (++tcp->tcp_conn_req_seqnum == -1) {
5793 		/*
5794 		 * -1 is "special" and defined in TPI as something
5795 		 * that should never be used in T_CONN_IND
5796 		 */
5797 		++tcp->tcp_conn_req_seqnum;
5798 	}
5799 	mutex_exit(&tcp->tcp_eager_lock);
5800 
5801 	if (tcp->tcp_syn_defense) {
5802 		/* Don't drop the SYN that comes from a good IP source */
5803 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5804 		if (addr_cache != NULL && eager->tcp_remote ==
5805 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5806 			eager->tcp_dontdrop = B_TRUE;
5807 		}
5808 	}
5809 
5810 	/*
5811 	 * We need to insert the eager in its own perimeter but as soon
5812 	 * as we do that, we expose the eager to the classifier and
5813 	 * should not touch any field outside the eager's perimeter.
5814 	 * So do all the work necessary before inserting the eager
5815 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5816 	 * will succeed but undo everything if it fails.
5817 	 */
5818 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5819 	eager->tcp_irs = seg_seq;
5820 	eager->tcp_rack = seg_seq;
5821 	eager->tcp_rnxt = seg_seq + 1;
5822 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5823 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
5824 	eager->tcp_state = TCPS_SYN_RCVD;
5825 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5826 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5827 	if (mp1 == NULL)
5828 		goto error1;
5829 	DB_CPID(mp1) = tcp->tcp_cpid;
5830 
5831 	/*
5832 	 * We need to start the rto timer. In normal case, we start
5833 	 * the timer after sending the packet on the wire (or at
5834 	 * least believing that packet was sent by waiting for
5835 	 * CALL_IP_WPUT() to return). Since this is the first packet
5836 	 * being sent on the wire for the eager, our initial tcp_rto
5837 	 * is at least tcp_rexmit_interval_min which is a fairly
5838 	 * large value to allow the algorithm to adjust slowly to large
5839 	 * fluctuations of RTT during first few transmissions.
5840 	 *
5841 	 * Starting the timer first and then sending the packet in this
5842 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5843 	 * is of the order of several 100ms and starting the timer
5844 	 * first and then sending the packet will result in difference
5845 	 * of few micro seconds.
5846 	 *
5847 	 * Without this optimization, we are forced to hold the fanout
5848 	 * lock across the ipcl_bind_insert() and sending the packet
5849 	 * so that we don't race against an incoming packet (maybe RST)
5850 	 * for this eager.
5851 	 */
5852 
5853 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5854 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5855 
5856 
5857 	/*
5858 	 * Insert the eager in its own perimeter now. We are ready to deal
5859 	 * with any packets on eager.
5860 	 */
5861 	if (eager->tcp_ipversion == IPV4_VERSION) {
5862 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5863 			goto error;
5864 		}
5865 	} else {
5866 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5867 			goto error;
5868 		}
5869 	}
5870 
5871 	/* mark conn as fully-bound */
5872 	econnp->conn_fully_bound = B_TRUE;
5873 
5874 	/* Send the SYN-ACK */
5875 	tcp_send_data(eager, eager->tcp_wq, mp1);
5876 	freemsg(mp);
5877 
5878 	return;
5879 error:
5880 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
5881 	freemsg(mp1);
5882 error1:
5883 	/* Undo what we did above */
5884 	mutex_enter(&tcp->tcp_eager_lock);
5885 	tcp_eager_unlink(eager);
5886 	mutex_exit(&tcp->tcp_eager_lock);
5887 	/* Drop eager's reference on the listener */
5888 	CONN_DEC_REF(connp);
5889 
5890 	/*
5891 	 * Delete the cached ire in conn_ire_cache and also mark
5892 	 * the conn as CONDEMNED
5893 	 */
5894 	mutex_enter(&econnp->conn_lock);
5895 	econnp->conn_state_flags |= CONN_CONDEMNED;
5896 	ire = econnp->conn_ire_cache;
5897 	econnp->conn_ire_cache = NULL;
5898 	mutex_exit(&econnp->conn_lock);
5899 	if (ire != NULL)
5900 		IRE_REFRELE_NOTR(ire);
5901 
5902 	/*
5903 	 * tcp_accept_comm inserts the eager to the bind_hash
5904 	 * we need to remove it from the hash if ipcl_conn_insert
5905 	 * fails.
5906 	 */
5907 	tcp_bind_hash_remove(eager);
5908 	/* Drop the eager ref placed in tcp_open_detached */
5909 	CONN_DEC_REF(econnp);
5910 
5911 	/*
5912 	 * If a connection already exists, send the mp to that connections so
5913 	 * that it can be appropriately dealt with.
5914 	 */
5915 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
5916 		if (!IPCL_IS_CONNECTED(econnp)) {
5917 			/*
5918 			 * Something bad happened. ipcl_conn_insert()
5919 			 * failed because a connection already existed
5920 			 * in connected hash but we can't find it
5921 			 * anymore (someone blew it away). Just
5922 			 * free this message and hopefully remote
5923 			 * will retransmit at which time the SYN can be
5924 			 * treated as a new connection or dealth with
5925 			 * a TH_RST if a connection already exists.
5926 			 */
5927 			freemsg(mp);
5928 		} else {
5929 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
5930 			    econnp, SQTAG_TCP_CONN_REQ);
5931 		}
5932 	} else {
5933 		/* Nobody wants this packet */
5934 		freemsg(mp);
5935 	}
5936 	return;
5937 error2:
5938 	freemsg(mp);
5939 	return;
5940 error3:
5941 	CONN_DEC_REF(econnp);
5942 	freemsg(mp);
5943 }
5944 
5945 /*
5946  * In an ideal case of vertical partition in NUMA architecture, its
5947  * beneficial to have the listener and all the incoming connections
5948  * tied to the same squeue. The other constraint is that incoming
5949  * connections should be tied to the squeue attached to interrupted
5950  * CPU for obvious locality reason so this leaves the listener to
5951  * be tied to the same squeue. Our only problem is that when listener
5952  * is binding, the CPU that will get interrupted by the NIC whose
5953  * IP address the listener is binding to is not even known. So
5954  * the code below allows us to change that binding at the time the
5955  * CPU is interrupted by virtue of incoming connection's squeue.
5956  *
5957  * This is usefull only in case of a listener bound to a specific IP
5958  * address. For other kind of listeners, they get bound the
5959  * very first time and there is no attempt to rebind them.
5960  */
5961 void
5962 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5963 {
5964 	conn_t		*connp = (conn_t *)arg;
5965 	squeue_t	*sqp = (squeue_t *)arg2;
5966 	squeue_t	*new_sqp;
5967 	uint32_t	conn_flags;
5968 
5969 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5970 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5971 	} else {
5972 		goto done;
5973 	}
5974 
5975 	if (connp->conn_fanout == NULL)
5976 		goto done;
5977 
5978 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5979 		mutex_enter(&connp->conn_fanout->connf_lock);
5980 		mutex_enter(&connp->conn_lock);
5981 		/*
5982 		 * No one from read or write side can access us now
5983 		 * except for already queued packets on this squeue.
5984 		 * But since we haven't changed the squeue yet, they
5985 		 * can't execute. If they are processed after we have
5986 		 * changed the squeue, they are sent back to the
5987 		 * correct squeue down below.
5988 		 */
5989 		if (connp->conn_sqp != new_sqp) {
5990 			while (connp->conn_sqp != new_sqp)
5991 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5992 		}
5993 
5994 		do {
5995 			conn_flags = connp->conn_flags;
5996 			conn_flags |= IPCL_FULLY_BOUND;
5997 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5998 			    conn_flags);
5999 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6000 
6001 		mutex_exit(&connp->conn_fanout->connf_lock);
6002 		mutex_exit(&connp->conn_lock);
6003 	}
6004 
6005 done:
6006 	if (connp->conn_sqp != sqp) {
6007 		CONN_INC_REF(connp);
6008 		squeue_fill(connp->conn_sqp, mp,
6009 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6010 	} else {
6011 		tcp_conn_request(connp, mp, sqp);
6012 	}
6013 }
6014 
6015 /*
6016  * Successful connect request processing begins when our client passes
6017  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6018  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6019  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6020  *   upstream <- tcp_rput()                <- IP
6021  * After various error checks are completed, tcp_connect() lays
6022  * the target address and port into the composite header template,
6023  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6024  * request followed by an IRE request, and passes the three mblk message
6025  * down to IP looking like this:
6026  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6027  * Processing continues in tcp_rput() when we receive the following message:
6028  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6029  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6030  * to fire off the connection request, and then passes the T_OK_ACK mblk
6031  * upstream that we filled in below.  There are, of course, numerous
6032  * error conditions along the way which truncate the processing described
6033  * above.
6034  */
6035 static void
6036 tcp_connect(tcp_t *tcp, mblk_t *mp)
6037 {
6038 	sin_t		*sin;
6039 	sin6_t		*sin6;
6040 	queue_t		*q = tcp->tcp_wq;
6041 	struct T_conn_req	*tcr;
6042 	ipaddr_t	*dstaddrp;
6043 	in_port_t	dstport;
6044 	uint_t		srcid;
6045 
6046 	tcr = (struct T_conn_req *)mp->b_rptr;
6047 
6048 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6049 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6050 		tcp_err_ack(tcp, mp, TPROTO, 0);
6051 		return;
6052 	}
6053 
6054 	/*
6055 	 * Determine packet type based on type of address passed in
6056 	 * the request should contain an IPv4 or IPv6 address.
6057 	 * Make sure that address family matches the type of
6058 	 * family of the the address passed down
6059 	 */
6060 	switch (tcr->DEST_length) {
6061 	default:
6062 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6063 		return;
6064 
6065 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6066 		/*
6067 		 * XXX: The check for valid DEST_length was not there
6068 		 * in earlier releases and some buggy
6069 		 * TLI apps (e.g Sybase) got away with not feeding
6070 		 * in sin_zero part of address.
6071 		 * We allow that bug to keep those buggy apps humming.
6072 		 * Test suites require the check on DEST_length.
6073 		 * We construct a new mblk with valid DEST_length
6074 		 * free the original so the rest of the code does
6075 		 * not have to keep track of this special shorter
6076 		 * length address case.
6077 		 */
6078 		mblk_t *nmp;
6079 		struct T_conn_req *ntcr;
6080 		sin_t *nsin;
6081 
6082 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6083 		    tcr->OPT_length, BPRI_HI);
6084 		if (nmp == NULL) {
6085 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6086 			return;
6087 		}
6088 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6089 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6090 		ntcr->PRIM_type = T_CONN_REQ;
6091 		ntcr->DEST_length = sizeof (sin_t);
6092 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6093 
6094 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6095 		*nsin = sin_null;
6096 		/* Get pointer to shorter address to copy from original mp */
6097 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6098 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6099 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6100 			freemsg(nmp);
6101 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6102 			return;
6103 		}
6104 		nsin->sin_family = sin->sin_family;
6105 		nsin->sin_port = sin->sin_port;
6106 		nsin->sin_addr = sin->sin_addr;
6107 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6108 		nmp->b_wptr = (uchar_t *)&nsin[1];
6109 		if (tcr->OPT_length != 0) {
6110 			ntcr->OPT_length = tcr->OPT_length;
6111 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6112 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6113 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6114 			    tcr->OPT_length);
6115 			nmp->b_wptr += tcr->OPT_length;
6116 		}
6117 		freemsg(mp);	/* original mp freed */
6118 		mp = nmp;	/* re-initialize original variables */
6119 		tcr = ntcr;
6120 	}
6121 	/* FALLTHRU */
6122 
6123 	case sizeof (sin_t):
6124 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6125 		    sizeof (sin_t));
6126 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6127 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6128 			return;
6129 		}
6130 		if (tcp->tcp_family != AF_INET ||
6131 		    sin->sin_family != AF_INET) {
6132 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6133 			return;
6134 		}
6135 		if (sin->sin_port == 0) {
6136 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6137 			return;
6138 		}
6139 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6140 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6141 			return;
6142 		}
6143 
6144 		break;
6145 
6146 	case sizeof (sin6_t):
6147 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6148 		    sizeof (sin6_t));
6149 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6150 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6151 			return;
6152 		}
6153 		if (tcp->tcp_family != AF_INET6 ||
6154 		    sin6->sin6_family != AF_INET6) {
6155 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6156 			return;
6157 		}
6158 		if (sin6->sin6_port == 0) {
6159 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6160 			return;
6161 		}
6162 		break;
6163 	}
6164 	/*
6165 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6166 	 * should key on their sequence number and cut them loose.
6167 	 */
6168 
6169 	/*
6170 	 * If options passed in, feed it for verification and handling
6171 	 */
6172 	if (tcr->OPT_length != 0) {
6173 		mblk_t	*ok_mp;
6174 		mblk_t	*discon_mp;
6175 		mblk_t  *conn_opts_mp;
6176 		int t_error, sys_error, do_disconnect;
6177 
6178 		conn_opts_mp = NULL;
6179 
6180 		if (tcp_conprim_opt_process(tcp, mp,
6181 			&do_disconnect, &t_error, &sys_error) < 0) {
6182 			if (do_disconnect) {
6183 				ASSERT(t_error == 0 && sys_error == 0);
6184 				discon_mp = mi_tpi_discon_ind(NULL,
6185 				    ECONNREFUSED, 0);
6186 				if (!discon_mp) {
6187 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6188 					    TSYSERR, ENOMEM);
6189 					return;
6190 				}
6191 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6192 				if (!ok_mp) {
6193 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6194 					    TSYSERR, ENOMEM);
6195 					return;
6196 				}
6197 				qreply(q, ok_mp);
6198 				qreply(q, discon_mp); /* no flush! */
6199 			} else {
6200 				ASSERT(t_error != 0);
6201 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6202 				    sys_error);
6203 			}
6204 			return;
6205 		}
6206 		/*
6207 		 * Success in setting options, the mp option buffer represented
6208 		 * by OPT_length/offset has been potentially modified and
6209 		 * contains results of option processing. We copy it in
6210 		 * another mp to save it for potentially influencing returning
6211 		 * it in T_CONN_CONN.
6212 		 */
6213 		if (tcr->OPT_length != 0) { /* there are resulting options */
6214 			conn_opts_mp = copyb(mp);
6215 			if (!conn_opts_mp) {
6216 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6217 				    TSYSERR, ENOMEM);
6218 				return;
6219 			}
6220 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6221 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6222 			/*
6223 			 * Note:
6224 			 * These resulting option negotiation can include any
6225 			 * end-to-end negotiation options but there no such
6226 			 * thing (yet?) in our TCP/IP.
6227 			 */
6228 		}
6229 	}
6230 
6231 	/*
6232 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6233 	 * make sure that the template IP header in the tcp structure is an
6234 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6235 	 * need to this before we call tcp_bindi() so that the port lookup
6236 	 * code will look for ports in the correct port space (IPv4 and
6237 	 * IPv6 have separate port spaces).
6238 	 */
6239 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6240 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6241 		int err = 0;
6242 
6243 		err = tcp_header_init_ipv4(tcp);
6244 		if (err != 0) {
6245 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6246 			goto connect_failed;
6247 		}
6248 		if (tcp->tcp_lport != 0)
6249 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6250 	}
6251 
6252 	switch (tcp->tcp_state) {
6253 	case TCPS_IDLE:
6254 		/*
6255 		 * We support quick connect, refer to comments in
6256 		 * tcp_connect_*()
6257 		 */
6258 		/* FALLTHRU */
6259 	case TCPS_BOUND:
6260 	case TCPS_LISTEN:
6261 		if (tcp->tcp_family == AF_INET6) {
6262 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6263 				tcp_connect_ipv6(tcp, mp,
6264 				    &sin6->sin6_addr,
6265 				    sin6->sin6_port, sin6->sin6_flowinfo,
6266 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6267 				return;
6268 			}
6269 			/*
6270 			 * Destination adress is mapped IPv6 address.
6271 			 * Source bound address should be unspecified or
6272 			 * IPv6 mapped address as well.
6273 			 */
6274 			if (!IN6_IS_ADDR_UNSPECIFIED(
6275 			    &tcp->tcp_bound_source_v6) &&
6276 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6277 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6278 				    EADDRNOTAVAIL);
6279 				break;
6280 			}
6281 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6282 			dstport = sin6->sin6_port;
6283 			srcid = sin6->__sin6_src_id;
6284 		} else {
6285 			dstaddrp = &sin->sin_addr.s_addr;
6286 			dstport = sin->sin_port;
6287 			srcid = 0;
6288 		}
6289 
6290 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6291 		return;
6292 	default:
6293 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6294 		break;
6295 	}
6296 	/*
6297 	 * Note: Code below is the "failure" case
6298 	 */
6299 	/* return error ack and blow away saved option results if any */
6300 connect_failed:
6301 	if (mp != NULL)
6302 		putnext(tcp->tcp_rq, mp);
6303 	else {
6304 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6305 		    TSYSERR, ENOMEM);
6306 	}
6307 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6308 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6309 }
6310 
6311 /*
6312  * Handle connect to IPv4 destinations, including connections for AF_INET6
6313  * sockets connecting to IPv4 mapped IPv6 destinations.
6314  */
6315 static void
6316 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6317     uint_t srcid)
6318 {
6319 	tcph_t	*tcph;
6320 	mblk_t	*mp1;
6321 	ipaddr_t dstaddr = *dstaddrp;
6322 	int32_t	oldstate;
6323 	uint16_t lport;
6324 
6325 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6326 
6327 	/* Check for attempt to connect to INADDR_ANY */
6328 	if (dstaddr == INADDR_ANY)  {
6329 		/*
6330 		 * SunOS 4.x and 4.3 BSD allow an application
6331 		 * to connect a TCP socket to INADDR_ANY.
6332 		 * When they do this, the kernel picks the
6333 		 * address of one interface and uses it
6334 		 * instead.  The kernel usually ends up
6335 		 * picking the address of the loopback
6336 		 * interface.  This is an undocumented feature.
6337 		 * However, we provide the same thing here
6338 		 * in order to have source and binary
6339 		 * compatibility with SunOS 4.x.
6340 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6341 		 * generate the T_CONN_CON.
6342 		 */
6343 		dstaddr = htonl(INADDR_LOOPBACK);
6344 		*dstaddrp = dstaddr;
6345 	}
6346 
6347 	/* Handle __sin6_src_id if socket not bound to an IP address */
6348 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6349 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6350 		    tcp->tcp_connp->conn_zoneid);
6351 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6352 		    tcp->tcp_ipha->ipha_src);
6353 	}
6354 
6355 	/*
6356 	 * Don't let an endpoint connect to itself.  Note that
6357 	 * the test here does not catch the case where the
6358 	 * source IP addr was left unspecified by the user. In
6359 	 * this case, the source addr is set in tcp_adapt_ire()
6360 	 * using the reply to the T_BIND message that we send
6361 	 * down to IP here and the check is repeated in tcp_rput_other.
6362 	 */
6363 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6364 	    dstport == tcp->tcp_lport) {
6365 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6366 		goto failed;
6367 	}
6368 
6369 	tcp->tcp_ipha->ipha_dst = dstaddr;
6370 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6371 
6372 	/*
6373 	 * Massage a source route if any putting the first hop
6374 	 * in iph_dst. Compute a starting value for the checksum which
6375 	 * takes into account that the original iph_dst should be
6376 	 * included in the checksum but that ip will include the
6377 	 * first hop in the source route in the tcp checksum.
6378 	 */
6379 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
6380 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6381 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6382 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6383 	if ((int)tcp->tcp_sum < 0)
6384 		tcp->tcp_sum--;
6385 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6386 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6387 	    (tcp->tcp_sum >> 16));
6388 	tcph = tcp->tcp_tcph;
6389 	*(uint16_t *)tcph->th_fport = dstport;
6390 	tcp->tcp_fport = dstport;
6391 
6392 	oldstate = tcp->tcp_state;
6393 	/*
6394 	 * At this point the remote destination address and remote port fields
6395 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6396 	 * have to see which state tcp was in so we can take apropriate action.
6397 	 */
6398 	if (oldstate == TCPS_IDLE) {
6399 		/*
6400 		 * We support a quick connect capability here, allowing
6401 		 * clients to transition directly from IDLE to SYN_SENT
6402 		 * tcp_bindi will pick an unused port, insert the connection
6403 		 * in the bind hash and transition to BOUND state.
6404 		 */
6405 		lport = tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
6406 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6407 		    B_FALSE, B_FALSE);
6408 		if (lport == 0) {
6409 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6410 			goto failed;
6411 		}
6412 	}
6413 	tcp->tcp_state = TCPS_SYN_SENT;
6414 
6415 	/*
6416 	 * TODO: allow data with connect requests
6417 	 * by unlinking M_DATA trailers here and
6418 	 * linking them in behind the T_OK_ACK mblk.
6419 	 * The tcp_rput() bind ack handler would then
6420 	 * feed them to tcp_wput_data() rather than call
6421 	 * tcp_timer().
6422 	 */
6423 	mp = mi_tpi_ok_ack_alloc(mp);
6424 	if (!mp) {
6425 		tcp->tcp_state = oldstate;
6426 		goto failed;
6427 	}
6428 	if (tcp->tcp_family == AF_INET) {
6429 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6430 		    sizeof (ipa_conn_t));
6431 	} else {
6432 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6433 		    sizeof (ipa6_conn_t));
6434 	}
6435 	if (mp1) {
6436 		/* Hang onto the T_OK_ACK for later. */
6437 		linkb(mp1, mp);
6438 		mblk_setcred(mp1, tcp->tcp_cred);
6439 		if (tcp->tcp_family == AF_INET)
6440 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6441 		else {
6442 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6443 			    &tcp->tcp_sticky_ipp);
6444 		}
6445 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6446 		tcp->tcp_active_open = 1;
6447 		/*
6448 		 * If the bind cannot complete immediately
6449 		 * IP will arrange to call tcp_rput_other
6450 		 * when the bind completes.
6451 		 */
6452 		if (mp1 != NULL)
6453 			tcp_rput_other(tcp, mp1);
6454 		return;
6455 	}
6456 	/* Error case */
6457 	tcp->tcp_state = oldstate;
6458 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6459 
6460 failed:
6461 	/* return error ack and blow away saved option results if any */
6462 	if (mp != NULL)
6463 		putnext(tcp->tcp_rq, mp);
6464 	else {
6465 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6466 		    TSYSERR, ENOMEM);
6467 	}
6468 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6469 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6470 
6471 }
6472 
6473 /*
6474  * Handle connect to IPv6 destinations.
6475  */
6476 static void
6477 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6478     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6479 {
6480 	tcph_t	*tcph;
6481 	mblk_t	*mp1;
6482 	ip6_rthdr_t *rth;
6483 	int32_t  oldstate;
6484 	uint16_t lport;
6485 
6486 	ASSERT(tcp->tcp_family == AF_INET6);
6487 
6488 	/*
6489 	 * If we're here, it means that the destination address is a native
6490 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6491 	 * reason why it might not be IPv6 is if the socket was bound to an
6492 	 * IPv4-mapped IPv6 address.
6493 	 */
6494 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6495 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6496 		goto failed;
6497 	}
6498 
6499 	/*
6500 	 * Interpret a zero destination to mean loopback.
6501 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6502 	 * generate the T_CONN_CON.
6503 	 */
6504 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6505 		*dstaddrp = ipv6_loopback;
6506 	}
6507 
6508 	/* Handle __sin6_src_id if socket not bound to an IP address */
6509 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6510 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6511 		    tcp->tcp_connp->conn_zoneid);
6512 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6513 	}
6514 
6515 	/*
6516 	 * Take care of the scope_id now and add ip6i_t
6517 	 * if ip6i_t is not already allocated through TCP
6518 	 * sticky options. At this point tcp_ip6h does not
6519 	 * have dst info, thus use dstaddrp.
6520 	 */
6521 	if (scope_id != 0 &&
6522 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6523 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6524 		ip6i_t  *ip6i;
6525 
6526 		ipp->ipp_ifindex = scope_id;
6527 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6528 
6529 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6530 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6531 			/* Already allocated */
6532 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6533 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6534 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6535 		} else {
6536 			int reterr;
6537 
6538 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6539 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6540 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6541 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6542 			if (reterr != 0)
6543 				goto failed;
6544 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6545 		}
6546 	}
6547 
6548 	/*
6549 	 * Don't let an endpoint connect to itself.  Note that
6550 	 * the test here does not catch the case where the
6551 	 * source IP addr was left unspecified by the user. In
6552 	 * this case, the source addr is set in tcp_adapt_ire()
6553 	 * using the reply to the T_BIND message that we send
6554 	 * down to IP here and the check is repeated in tcp_rput_other.
6555 	 */
6556 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6557 	    (dstport == tcp->tcp_lport)) {
6558 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6559 		goto failed;
6560 	}
6561 
6562 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6563 	tcp->tcp_remote_v6 = *dstaddrp;
6564 	tcp->tcp_ip6h->ip6_vcf =
6565 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6566 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6567 
6568 
6569 	/*
6570 	 * Massage a routing header (if present) putting the first hop
6571 	 * in ip6_dst. Compute a starting value for the checksum which
6572 	 * takes into account that the original ip6_dst should be
6573 	 * included in the checksum but that ip will include the
6574 	 * first hop in the source route in the tcp checksum.
6575 	 */
6576 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6577 	if (rth != NULL) {
6578 
6579 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
6580 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6581 		    (tcp->tcp_sum >> 16));
6582 	} else {
6583 		tcp->tcp_sum = 0;
6584 	}
6585 
6586 	tcph = tcp->tcp_tcph;
6587 	*(uint16_t *)tcph->th_fport = dstport;
6588 	tcp->tcp_fport = dstport;
6589 
6590 	oldstate = tcp->tcp_state;
6591 	/*
6592 	 * At this point the remote destination address and remote port fields
6593 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6594 	 * have to see which state tcp was in so we can take apropriate action.
6595 	 */
6596 	if (oldstate == TCPS_IDLE) {
6597 		/*
6598 		 * We support a quick connect capability here, allowing
6599 		 * clients to transition directly from IDLE to SYN_SENT
6600 		 * tcp_bindi will pick an unused port, insert the connection
6601 		 * in the bind hash and transition to BOUND state.
6602 		 */
6603 		lport = tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
6604 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6605 		    B_FALSE, B_FALSE);
6606 		if (lport == 0) {
6607 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6608 			goto failed;
6609 		}
6610 	}
6611 	tcp->tcp_state = TCPS_SYN_SENT;
6612 	/*
6613 	 * TODO: allow data with connect requests
6614 	 * by unlinking M_DATA trailers here and
6615 	 * linking them in behind the T_OK_ACK mblk.
6616 	 * The tcp_rput() bind ack handler would then
6617 	 * feed them to tcp_wput_data() rather than call
6618 	 * tcp_timer().
6619 	 */
6620 	mp = mi_tpi_ok_ack_alloc(mp);
6621 	if (!mp) {
6622 		tcp->tcp_state = oldstate;
6623 		goto failed;
6624 	}
6625 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6626 	if (mp1) {
6627 		/* Hang onto the T_OK_ACK for later. */
6628 		linkb(mp1, mp);
6629 		mblk_setcred(mp1, tcp->tcp_cred);
6630 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6631 		    &tcp->tcp_sticky_ipp);
6632 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6633 		tcp->tcp_active_open = 1;
6634 		/* ip_bind_v6() may return ACK or ERROR */
6635 		if (mp1 != NULL)
6636 			tcp_rput_other(tcp, mp1);
6637 		return;
6638 	}
6639 	/* Error case */
6640 	tcp->tcp_state = oldstate;
6641 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6642 
6643 failed:
6644 	/* return error ack and blow away saved option results if any */
6645 	if (mp != NULL)
6646 		putnext(tcp->tcp_rq, mp);
6647 	else {
6648 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6649 		    TSYSERR, ENOMEM);
6650 	}
6651 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6652 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6653 }
6654 
6655 /*
6656  * We need a stream q for detached closing tcp connections
6657  * to use.  Our client hereby indicates that this q is the
6658  * one to use.
6659  */
6660 static void
6661 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6662 {
6663 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6664 	queue_t	*q = tcp->tcp_wq;
6665 
6666 	mp->b_datap->db_type = M_IOCACK;
6667 	iocp->ioc_count = 0;
6668 	mutex_enter(&tcp_g_q_lock);
6669 	if (tcp_g_q != NULL) {
6670 		mutex_exit(&tcp_g_q_lock);
6671 		iocp->ioc_error = EALREADY;
6672 	} else {
6673 		mblk_t *mp1;
6674 
6675 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6676 		if (mp1 == NULL) {
6677 			mutex_exit(&tcp_g_q_lock);
6678 			iocp->ioc_error = ENOMEM;
6679 		} else {
6680 			tcp_g_q = tcp->tcp_rq;
6681 			mutex_exit(&tcp_g_q_lock);
6682 			iocp->ioc_error = 0;
6683 			iocp->ioc_rval = 0;
6684 			/*
6685 			 * We are passing tcp_sticky_ipp as NULL
6686 			 * as it is not useful for tcp_default queue
6687 			 */
6688 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6689 			if (mp1 != NULL)
6690 				tcp_rput_other(tcp, mp1);
6691 		}
6692 	}
6693 	qreply(q, mp);
6694 }
6695 
6696 /*
6697  * Our client hereby directs us to reject the connection request
6698  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6699  * of sending the appropriate RST, not an ICMP error.
6700  */
6701 static void
6702 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6703 {
6704 	tcp_t	*ltcp = NULL;
6705 	t_scalar_t seqnum;
6706 	conn_t	*connp;
6707 
6708 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6709 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6710 		tcp_err_ack(tcp, mp, TPROTO, 0);
6711 		return;
6712 	}
6713 
6714 	/*
6715 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6716 	 * when the stream is in BOUND state. Do not send a reset,
6717 	 * since the destination IP address is not valid, and it can
6718 	 * be the initialized value of all zeros (broadcast address).
6719 	 *
6720 	 * If TCP has sent down a bind request to IP and has not
6721 	 * received the reply, reject the request.  Otherwise, TCP
6722 	 * will be confused.
6723 	 */
6724 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6725 		if (tcp->tcp_debug) {
6726 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6727 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6728 		}
6729 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6730 		return;
6731 	}
6732 
6733 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6734 
6735 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6736 
6737 		/*
6738 		 * According to TPI, for non-listeners, ignore seqnum
6739 		 * and disconnect.
6740 		 * Following interpretation of -1 seqnum is historical
6741 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6742 		 * a valid seqnum should not be -1).
6743 		 *
6744 		 *	-1 means disconnect everything
6745 		 *	regardless even on a listener.
6746 		 */
6747 
6748 		int old_state = tcp->tcp_state;
6749 
6750 		/*
6751 		 * The connection can't be on the tcp_time_wait_head list
6752 		 * since it is not detached.
6753 		 */
6754 		ASSERT(tcp->tcp_time_wait_next == NULL);
6755 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6756 		ASSERT(tcp->tcp_time_wait_expire == 0);
6757 		ltcp = NULL;
6758 		/*
6759 		 * If it used to be a listener, check to make sure no one else
6760 		 * has taken the port before switching back to LISTEN state.
6761 		 */
6762 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6763 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6764 			    tcp->tcp_ipha->ipha_src,
6765 			    tcp->tcp_connp->conn_zoneid);
6766 			if (connp != NULL)
6767 				ltcp = connp->conn_tcp;
6768 		} else {
6769 			/* Allow tcp_bound_if listeners? */
6770 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6771 			    &tcp->tcp_ip6h->ip6_src, 0,
6772 			    tcp->tcp_connp->conn_zoneid);
6773 			if (connp != NULL)
6774 				ltcp = connp->conn_tcp;
6775 		}
6776 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6777 			tcp->tcp_state = TCPS_LISTEN;
6778 		} else if (old_state > TCPS_BOUND) {
6779 			tcp->tcp_conn_req_max = 0;
6780 			tcp->tcp_state = TCPS_BOUND;
6781 		}
6782 		if (ltcp != NULL)
6783 			CONN_DEC_REF(ltcp->tcp_connp);
6784 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6785 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
6786 		} else if (old_state == TCPS_ESTABLISHED ||
6787 		    old_state == TCPS_CLOSE_WAIT) {
6788 			BUMP_MIB(&tcp_mib, tcpEstabResets);
6789 		}
6790 
6791 		if (tcp->tcp_fused)
6792 			tcp_unfuse(tcp);
6793 
6794 		mutex_enter(&tcp->tcp_eager_lock);
6795 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6796 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6797 			tcp_eager_cleanup(tcp, 0);
6798 		}
6799 		mutex_exit(&tcp->tcp_eager_lock);
6800 
6801 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6802 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6803 
6804 		tcp_reinit(tcp);
6805 
6806 		if (old_state >= TCPS_ESTABLISHED) {
6807 			/* Send M_FLUSH according to TPI */
6808 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6809 		}
6810 		mp = mi_tpi_ok_ack_alloc(mp);
6811 		if (mp)
6812 			putnext(tcp->tcp_rq, mp);
6813 		return;
6814 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6815 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6816 		return;
6817 	}
6818 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6819 		/* Send M_FLUSH according to TPI */
6820 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6821 	}
6822 	mp = mi_tpi_ok_ack_alloc(mp);
6823 	if (mp)
6824 		putnext(tcp->tcp_rq, mp);
6825 }
6826 
6827 /*
6828  * Diagnostic routine used to return a string associated with the tcp state.
6829  * Note that if the caller does not supply a buffer, it will use an internal
6830  * static string.  This means that if multiple threads call this function at
6831  * the same time, output can be corrupted...  Note also that this function
6832  * does not check the size of the supplied buffer.  The caller has to make
6833  * sure that it is big enough.
6834  */
6835 static char *
6836 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6837 {
6838 	char		buf1[30];
6839 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6840 	char		*buf;
6841 	char		*cp;
6842 	in6_addr_t	local, remote;
6843 	char		local_addrbuf[INET6_ADDRSTRLEN];
6844 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6845 
6846 	if (sup_buf != NULL)
6847 		buf = sup_buf;
6848 	else
6849 		buf = priv_buf;
6850 
6851 	if (tcp == NULL)
6852 		return ("NULL_TCP");
6853 	switch (tcp->tcp_state) {
6854 	case TCPS_CLOSED:
6855 		cp = "TCP_CLOSED";
6856 		break;
6857 	case TCPS_IDLE:
6858 		cp = "TCP_IDLE";
6859 		break;
6860 	case TCPS_BOUND:
6861 		cp = "TCP_BOUND";
6862 		break;
6863 	case TCPS_LISTEN:
6864 		cp = "TCP_LISTEN";
6865 		break;
6866 	case TCPS_SYN_SENT:
6867 		cp = "TCP_SYN_SENT";
6868 		break;
6869 	case TCPS_SYN_RCVD:
6870 		cp = "TCP_SYN_RCVD";
6871 		break;
6872 	case TCPS_ESTABLISHED:
6873 		cp = "TCP_ESTABLISHED";
6874 		break;
6875 	case TCPS_CLOSE_WAIT:
6876 		cp = "TCP_CLOSE_WAIT";
6877 		break;
6878 	case TCPS_FIN_WAIT_1:
6879 		cp = "TCP_FIN_WAIT_1";
6880 		break;
6881 	case TCPS_CLOSING:
6882 		cp = "TCP_CLOSING";
6883 		break;
6884 	case TCPS_LAST_ACK:
6885 		cp = "TCP_LAST_ACK";
6886 		break;
6887 	case TCPS_FIN_WAIT_2:
6888 		cp = "TCP_FIN_WAIT_2";
6889 		break;
6890 	case TCPS_TIME_WAIT:
6891 		cp = "TCP_TIME_WAIT";
6892 		break;
6893 	default:
6894 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6895 		cp = buf1;
6896 		break;
6897 	}
6898 	switch (format) {
6899 	case DISP_ADDR_AND_PORT:
6900 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6901 			/*
6902 			 * Note that we use the remote address in the tcp_b
6903 			 * structure.  This means that it will print out
6904 			 * the real destination address, not the next hop's
6905 			 * address if source routing is used.
6906 			 */
6907 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6908 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6909 
6910 		} else {
6911 			local = tcp->tcp_ip_src_v6;
6912 			remote = tcp->tcp_remote_v6;
6913 		}
6914 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6915 		    sizeof (local_addrbuf));
6916 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6917 		    sizeof (remote_addrbuf));
6918 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6919 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6920 		    ntohs(tcp->tcp_fport), cp);
6921 		break;
6922 	case DISP_PORT_ONLY:
6923 	default:
6924 		(void) mi_sprintf(buf, "[%u, %u] %s",
6925 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6926 		break;
6927 	}
6928 
6929 	return (buf);
6930 }
6931 
6932 /*
6933  * Called via squeue to get on to eager's perimeter to send a
6934  * TH_RST. The listener wants the eager to disappear either
6935  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
6936  * being called.
6937  */
6938 /* ARGSUSED */
6939 void
6940 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6941 {
6942 	conn_t	*econnp = (conn_t *)arg;
6943 	tcp_t	*eager = econnp->conn_tcp;
6944 	tcp_t	*listener = eager->tcp_listener;
6945 
6946 	/*
6947 	 * We could be called because listener is closing. Since
6948 	 * the eager is using listener's queue's, its not safe.
6949 	 * Better use the default queue just to send the TH_RST
6950 	 * out.
6951 	 */
6952 	eager->tcp_rq = tcp_g_q;
6953 	eager->tcp_wq = WR(tcp_g_q);
6954 
6955 	if (eager->tcp_state > TCPS_LISTEN) {
6956 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6957 		    eager, eager->tcp_snxt, 0, TH_RST);
6958 	}
6959 
6960 	/* We are here because listener wants this eager gone */
6961 	if (listener != NULL) {
6962 		mutex_enter(&listener->tcp_eager_lock);
6963 		tcp_eager_unlink(eager);
6964 		if (eager->tcp_conn.tcp_eager_conn_ind == NULL) {
6965 			/*
6966 			 * The eager has sent a conn_ind up to the
6967 			 * listener but listener decides to close
6968 			 * instead. We need to drop the extra ref
6969 			 * placed on eager in tcp_rput_data() before
6970 			 * sending the conn_ind to listener.
6971 			 */
6972 			CONN_DEC_REF(econnp);
6973 		}
6974 		mutex_exit(&listener->tcp_eager_lock);
6975 		CONN_DEC_REF(listener->tcp_connp);
6976 	}
6977 
6978 	if (eager->tcp_state > TCPS_BOUND)
6979 		tcp_close_detached(eager);
6980 }
6981 
6982 /*
6983  * Reset any eager connection hanging off this listener marked
6984  * with 'seqnum' and then reclaim it's resources.
6985  */
6986 static boolean_t
6987 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6988 {
6989 	tcp_t	*eager;
6990 	mblk_t 	*mp;
6991 
6992 	TCP_STAT(tcp_eager_blowoff_calls);
6993 	eager = listener;
6994 	mutex_enter(&listener->tcp_eager_lock);
6995 	do {
6996 		eager = eager->tcp_eager_next_q;
6997 		if (eager == NULL) {
6998 			mutex_exit(&listener->tcp_eager_lock);
6999 			return (B_FALSE);
7000 		}
7001 	} while (eager->tcp_conn_req_seqnum != seqnum);
7002 	CONN_INC_REF(eager->tcp_connp);
7003 	mutex_exit(&listener->tcp_eager_lock);
7004 	mp = &eager->tcp_closemp;
7005 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7006 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7007 	return (B_TRUE);
7008 }
7009 
7010 /*
7011  * Reset any eager connection hanging off this listener
7012  * and then reclaim it's resources.
7013  */
7014 static void
7015 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7016 {
7017 	tcp_t	*eager;
7018 	mblk_t	*mp;
7019 
7020 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7021 
7022 	if (!q0_only) {
7023 		/* First cleanup q */
7024 		TCP_STAT(tcp_eager_blowoff_q);
7025 		eager = listener->tcp_eager_next_q;
7026 		while (eager != NULL) {
7027 			CONN_INC_REF(eager->tcp_connp);
7028 			mp = &eager->tcp_closemp;
7029 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7030 			    tcp_eager_kill, eager->tcp_connp,
7031 			    SQTAG_TCP_EAGER_CLEANUP);
7032 			eager = eager->tcp_eager_next_q;
7033 		}
7034 	}
7035 	/* Then cleanup q0 */
7036 	TCP_STAT(tcp_eager_blowoff_q0);
7037 	eager = listener->tcp_eager_next_q0;
7038 	while (eager != listener) {
7039 		CONN_INC_REF(eager->tcp_connp);
7040 		mp = &eager->tcp_closemp;
7041 		squeue_fill(eager->tcp_connp->conn_sqp, mp,
7042 		    tcp_eager_kill, eager->tcp_connp,
7043 		    SQTAG_TCP_EAGER_CLEANUP_Q0);
7044 		eager = eager->tcp_eager_next_q0;
7045 	}
7046 }
7047 
7048 /*
7049  * If we are an eager connection hanging off a listener that hasn't
7050  * formally accepted the connection yet, get off his list and blow off
7051  * any data that we have accumulated.
7052  */
7053 static void
7054 tcp_eager_unlink(tcp_t *tcp)
7055 {
7056 	tcp_t	*listener = tcp->tcp_listener;
7057 
7058 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7059 	ASSERT(listener != NULL);
7060 	if (tcp->tcp_eager_next_q0 != NULL) {
7061 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7062 
7063 		/* Remove the eager tcp from q0 */
7064 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7065 		    tcp->tcp_eager_prev_q0;
7066 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7067 		    tcp->tcp_eager_next_q0;
7068 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7069 		listener->tcp_conn_req_cnt_q0--;
7070 
7071 		tcp->tcp_eager_next_q0 = NULL;
7072 		tcp->tcp_eager_prev_q0 = NULL;
7073 
7074 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7075 			/* we have timed out before */
7076 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7077 			listener->tcp_syn_rcvd_timeout--;
7078 		}
7079 	} else {
7080 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7081 		tcp_t	*prev = NULL;
7082 
7083 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7084 			if (tcpp[0] == tcp) {
7085 				if (listener->tcp_eager_last_q == tcp) {
7086 					/*
7087 					 * If we are unlinking the last
7088 					 * element on the list, adjust
7089 					 * tail pointer. Set tail pointer
7090 					 * to nil when list is empty.
7091 					 */
7092 					ASSERT(tcp->tcp_eager_next_q == NULL);
7093 					if (listener->tcp_eager_last_q ==
7094 					    listener->tcp_eager_next_q) {
7095 						listener->tcp_eager_last_q =
7096 						NULL;
7097 					} else {
7098 						/*
7099 						 * We won't get here if there
7100 						 * is only one eager in the
7101 						 * list.
7102 						 */
7103 						ASSERT(prev != NULL);
7104 						listener->tcp_eager_last_q =
7105 						    prev;
7106 					}
7107 				}
7108 				tcpp[0] = tcp->tcp_eager_next_q;
7109 				tcp->tcp_eager_next_q = NULL;
7110 				tcp->tcp_eager_last_q = NULL;
7111 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7112 				listener->tcp_conn_req_cnt_q--;
7113 				break;
7114 			}
7115 			prev = tcpp[0];
7116 		}
7117 	}
7118 	tcp->tcp_listener = NULL;
7119 }
7120 
7121 /* Shorthand to generate and send TPI error acks to our client */
7122 static void
7123 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7124 {
7125 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7126 		putnext(tcp->tcp_rq, mp);
7127 }
7128 
7129 /* Shorthand to generate and send TPI error acks to our client */
7130 static void
7131 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7132     int t_error, int sys_error)
7133 {
7134 	struct T_error_ack	*teackp;
7135 
7136 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7137 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7138 		teackp = (struct T_error_ack *)mp->b_rptr;
7139 		teackp->ERROR_prim = primitive;
7140 		teackp->TLI_error = t_error;
7141 		teackp->UNIX_error = sys_error;
7142 		putnext(tcp->tcp_rq, mp);
7143 	}
7144 }
7145 
7146 /*
7147  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7148  * but instead the code relies on:
7149  * - the fact that the address of the array and its size never changes
7150  * - the atomic assignment of the elements of the array
7151  */
7152 /* ARGSUSED */
7153 static int
7154 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7155 {
7156 	int i;
7157 
7158 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7159 		if (tcp_g_epriv_ports[i] != 0)
7160 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
7161 	}
7162 	return (0);
7163 }
7164 
7165 /*
7166  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7167  * threads from changing it at the same time.
7168  */
7169 /* ARGSUSED */
7170 static int
7171 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7172     cred_t *cr)
7173 {
7174 	long	new_value;
7175 	int	i;
7176 
7177 	/*
7178 	 * Fail the request if the new value does not lie within the
7179 	 * port number limits.
7180 	 */
7181 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7182 	    new_value <= 0 || new_value >= 65536) {
7183 		return (EINVAL);
7184 	}
7185 
7186 	mutex_enter(&tcp_epriv_port_lock);
7187 	/* Check if the value is already in the list */
7188 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7189 		if (new_value == tcp_g_epriv_ports[i]) {
7190 			mutex_exit(&tcp_epriv_port_lock);
7191 			return (EEXIST);
7192 		}
7193 	}
7194 	/* Find an empty slot */
7195 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7196 		if (tcp_g_epriv_ports[i] == 0)
7197 			break;
7198 	}
7199 	if (i == tcp_g_num_epriv_ports) {
7200 		mutex_exit(&tcp_epriv_port_lock);
7201 		return (EOVERFLOW);
7202 	}
7203 	/* Set the new value */
7204 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
7205 	mutex_exit(&tcp_epriv_port_lock);
7206 	return (0);
7207 }
7208 
7209 /*
7210  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7211  * threads from changing it at the same time.
7212  */
7213 /* ARGSUSED */
7214 static int
7215 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7216     cred_t *cr)
7217 {
7218 	long	new_value;
7219 	int	i;
7220 
7221 	/*
7222 	 * Fail the request if the new value does not lie within the
7223 	 * port number limits.
7224 	 */
7225 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7226 	    new_value >= 65536) {
7227 		return (EINVAL);
7228 	}
7229 
7230 	mutex_enter(&tcp_epriv_port_lock);
7231 	/* Check that the value is already in the list */
7232 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7233 		if (tcp_g_epriv_ports[i] == new_value)
7234 			break;
7235 	}
7236 	if (i == tcp_g_num_epriv_ports) {
7237 		mutex_exit(&tcp_epriv_port_lock);
7238 		return (ESRCH);
7239 	}
7240 	/* Clear the value */
7241 	tcp_g_epriv_ports[i] = 0;
7242 	mutex_exit(&tcp_epriv_port_lock);
7243 	return (0);
7244 }
7245 
7246 /* Return the TPI/TLI equivalent of our current tcp_state */
7247 static int
7248 tcp_tpistate(tcp_t *tcp)
7249 {
7250 	switch (tcp->tcp_state) {
7251 	case TCPS_IDLE:
7252 		return (TS_UNBND);
7253 	case TCPS_LISTEN:
7254 		/*
7255 		 * Return whether there are outstanding T_CONN_IND waiting
7256 		 * for the matching T_CONN_RES. Therefore don't count q0.
7257 		 */
7258 		if (tcp->tcp_conn_req_cnt_q > 0)
7259 			return (TS_WRES_CIND);
7260 		else
7261 			return (TS_IDLE);
7262 	case TCPS_BOUND:
7263 		return (TS_IDLE);
7264 	case TCPS_SYN_SENT:
7265 		return (TS_WCON_CREQ);
7266 	case TCPS_SYN_RCVD:
7267 		/*
7268 		 * Note: assumption: this has to the active open SYN_RCVD.
7269 		 * The passive instance is detached in SYN_RCVD stage of
7270 		 * incoming connection processing so we cannot get request
7271 		 * for T_info_ack on it.
7272 		 */
7273 		return (TS_WACK_CRES);
7274 	case TCPS_ESTABLISHED:
7275 		return (TS_DATA_XFER);
7276 	case TCPS_CLOSE_WAIT:
7277 		return (TS_WREQ_ORDREL);
7278 	case TCPS_FIN_WAIT_1:
7279 		return (TS_WIND_ORDREL);
7280 	case TCPS_FIN_WAIT_2:
7281 		return (TS_WIND_ORDREL);
7282 
7283 	case TCPS_CLOSING:
7284 	case TCPS_LAST_ACK:
7285 	case TCPS_TIME_WAIT:
7286 	case TCPS_CLOSED:
7287 		/*
7288 		 * Following TS_WACK_DREQ7 is a rendition of "not
7289 		 * yet TS_IDLE" TPI state. There is no best match to any
7290 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7291 		 * choose a value chosen that will map to TLI/XTI level
7292 		 * state of TSTATECHNG (state is process of changing) which
7293 		 * captures what this dummy state represents.
7294 		 */
7295 		return (TS_WACK_DREQ7);
7296 	default:
7297 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7298 		    tcp->tcp_state, tcp_display(tcp, NULL,
7299 		    DISP_PORT_ONLY));
7300 		return (TS_UNBND);
7301 	}
7302 }
7303 
7304 static void
7305 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7306 {
7307 	if (tcp->tcp_family == AF_INET6)
7308 		*tia = tcp_g_t_info_ack_v6;
7309 	else
7310 		*tia = tcp_g_t_info_ack;
7311 	tia->CURRENT_state = tcp_tpistate(tcp);
7312 	tia->OPT_size = tcp_max_optsize;
7313 	if (tcp->tcp_mss == 0) {
7314 		/* Not yet set - tcp_open does not set mss */
7315 		if (tcp->tcp_ipversion == IPV4_VERSION)
7316 			tia->TIDU_size = tcp_mss_def_ipv4;
7317 		else
7318 			tia->TIDU_size = tcp_mss_def_ipv6;
7319 	} else {
7320 		tia->TIDU_size = tcp->tcp_mss;
7321 	}
7322 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7323 }
7324 
7325 /*
7326  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7327  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7328  * tcp_g_t_info_ack.  The current state of the stream is copied from
7329  * tcp_state.
7330  */
7331 static void
7332 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7333 {
7334 	t_uscalar_t		cap_bits1;
7335 	struct T_capability_ack	*tcap;
7336 
7337 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7338 		freemsg(mp);
7339 		return;
7340 	}
7341 
7342 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7343 
7344 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7345 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7346 	if (mp == NULL)
7347 		return;
7348 
7349 	tcap = (struct T_capability_ack *)mp->b_rptr;
7350 	tcap->CAP_bits1 = 0;
7351 
7352 	if (cap_bits1 & TC1_INFO) {
7353 		tcp_copy_info(&tcap->INFO_ack, tcp);
7354 		tcap->CAP_bits1 |= TC1_INFO;
7355 	}
7356 
7357 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7358 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7359 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7360 	}
7361 
7362 	putnext(tcp->tcp_rq, mp);
7363 }
7364 
7365 /*
7366  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7367  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7368  * The current state of the stream is copied from tcp_state.
7369  */
7370 static void
7371 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7372 {
7373 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7374 	    T_INFO_ACK);
7375 	if (!mp) {
7376 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7377 		return;
7378 	}
7379 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7380 	putnext(tcp->tcp_rq, mp);
7381 }
7382 
7383 /* Respond to the TPI addr request */
7384 static void
7385 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7386 {
7387 	sin_t	*sin;
7388 	mblk_t	*ackmp;
7389 	struct T_addr_ack *taa;
7390 
7391 	/* Make it large enough for worst case */
7392 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7393 	    2 * sizeof (sin6_t), 1);
7394 	if (ackmp == NULL) {
7395 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7396 		return;
7397 	}
7398 
7399 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7400 		tcp_addr_req_ipv6(tcp, ackmp);
7401 		return;
7402 	}
7403 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7404 
7405 	bzero(taa, sizeof (struct T_addr_ack));
7406 	ackmp->b_wptr = (uchar_t *)&taa[1];
7407 
7408 	taa->PRIM_type = T_ADDR_ACK;
7409 	ackmp->b_datap->db_type = M_PCPROTO;
7410 
7411 	/*
7412 	 * Note: Following code assumes 32 bit alignment of basic
7413 	 * data structures like sin_t and struct T_addr_ack.
7414 	 */
7415 	if (tcp->tcp_state >= TCPS_BOUND) {
7416 		/*
7417 		 * Fill in local address
7418 		 */
7419 		taa->LOCADDR_length = sizeof (sin_t);
7420 		taa->LOCADDR_offset = sizeof (*taa);
7421 
7422 		sin = (sin_t *)&taa[1];
7423 
7424 		/* Fill zeroes and then intialize non-zero fields */
7425 		*sin = sin_null;
7426 
7427 		sin->sin_family = AF_INET;
7428 
7429 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7430 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7431 
7432 		ackmp->b_wptr = (uchar_t *)&sin[1];
7433 
7434 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7435 			/*
7436 			 * Fill in Remote address
7437 			 */
7438 			taa->REMADDR_length = sizeof (sin_t);
7439 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7440 						taa->LOCADDR_length);
7441 
7442 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7443 			*sin = sin_null;
7444 			sin->sin_family = AF_INET;
7445 			sin->sin_addr.s_addr = tcp->tcp_remote;
7446 			sin->sin_port = tcp->tcp_fport;
7447 
7448 			ackmp->b_wptr = (uchar_t *)&sin[1];
7449 		}
7450 	}
7451 	putnext(tcp->tcp_rq, ackmp);
7452 }
7453 
7454 /* Assumes that tcp_addr_req gets enough space and alignment */
7455 static void
7456 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7457 {
7458 	sin6_t	*sin6;
7459 	struct T_addr_ack *taa;
7460 
7461 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7462 	ASSERT(OK_32PTR(ackmp->b_rptr));
7463 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7464 	    2 * sizeof (sin6_t));
7465 
7466 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7467 
7468 	bzero(taa, sizeof (struct T_addr_ack));
7469 	ackmp->b_wptr = (uchar_t *)&taa[1];
7470 
7471 	taa->PRIM_type = T_ADDR_ACK;
7472 	ackmp->b_datap->db_type = M_PCPROTO;
7473 
7474 	/*
7475 	 * Note: Following code assumes 32 bit alignment of basic
7476 	 * data structures like sin6_t and struct T_addr_ack.
7477 	 */
7478 	if (tcp->tcp_state >= TCPS_BOUND) {
7479 		/*
7480 		 * Fill in local address
7481 		 */
7482 		taa->LOCADDR_length = sizeof (sin6_t);
7483 		taa->LOCADDR_offset = sizeof (*taa);
7484 
7485 		sin6 = (sin6_t *)&taa[1];
7486 		*sin6 = sin6_null;
7487 
7488 		sin6->sin6_family = AF_INET6;
7489 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7490 		sin6->sin6_port = tcp->tcp_lport;
7491 
7492 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7493 
7494 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7495 			/*
7496 			 * Fill in Remote address
7497 			 */
7498 			taa->REMADDR_length = sizeof (sin6_t);
7499 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7500 						taa->LOCADDR_length);
7501 
7502 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7503 			*sin6 = sin6_null;
7504 			sin6->sin6_family = AF_INET6;
7505 			sin6->sin6_flowinfo =
7506 			    tcp->tcp_ip6h->ip6_vcf &
7507 			    ~IPV6_VERS_AND_FLOW_MASK;
7508 			sin6->sin6_addr = tcp->tcp_remote_v6;
7509 			sin6->sin6_port = tcp->tcp_fport;
7510 
7511 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7512 		}
7513 	}
7514 	putnext(tcp->tcp_rq, ackmp);
7515 }
7516 
7517 /*
7518  * Handle reinitialization of a tcp structure.
7519  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7520  */
7521 static void
7522 tcp_reinit(tcp_t *tcp)
7523 {
7524 	mblk_t	*mp;
7525 	int 	err;
7526 
7527 	TCP_STAT(tcp_reinit_calls);
7528 
7529 	/* tcp_reinit should never be called for detached tcp_t's */
7530 	ASSERT(tcp->tcp_listener == NULL);
7531 	ASSERT((tcp->tcp_family == AF_INET &&
7532 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7533 	    (tcp->tcp_family == AF_INET6 &&
7534 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7535 	    tcp->tcp_ipversion == IPV6_VERSION)));
7536 
7537 	/* Cancel outstanding timers */
7538 	tcp_timers_stop(tcp);
7539 
7540 	/*
7541 	 * Reset everything in the state vector, after updating global
7542 	 * MIB data from instance counters.
7543 	 */
7544 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
7545 	tcp->tcp_ibsegs = 0;
7546 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
7547 	tcp->tcp_obsegs = 0;
7548 
7549 	tcp_close_mpp(&tcp->tcp_xmit_head);
7550 	if (tcp->tcp_snd_zcopy_aware)
7551 		tcp_zcopy_notify(tcp);
7552 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7553 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7554 	if (tcp->tcp_flow_stopped &&
7555 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7556 		tcp_clrqfull(tcp);
7557 	}
7558 	tcp_close_mpp(&tcp->tcp_reass_head);
7559 	tcp->tcp_reass_tail = NULL;
7560 	if (tcp->tcp_rcv_list != NULL) {
7561 		/* Free b_next chain */
7562 		tcp_close_mpp(&tcp->tcp_rcv_list);
7563 		tcp->tcp_rcv_last_head = NULL;
7564 		tcp->tcp_rcv_last_tail = NULL;
7565 		tcp->tcp_rcv_cnt = 0;
7566 	}
7567 	tcp->tcp_rcv_last_tail = NULL;
7568 
7569 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7570 		freemsg(mp);
7571 		tcp->tcp_urp_mp = NULL;
7572 	}
7573 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7574 		freemsg(mp);
7575 		tcp->tcp_urp_mark_mp = NULL;
7576 	}
7577 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7578 		freeb(tcp->tcp_fused_sigurg_mp);
7579 		tcp->tcp_fused_sigurg_mp = NULL;
7580 	}
7581 
7582 	/*
7583 	 * Following is a union with two members which are
7584 	 * identical types and size so the following cleanup
7585 	 * is enough.
7586 	 */
7587 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7588 
7589 	CL_INET_DISCONNECT(tcp);
7590 
7591 	/*
7592 	 * The connection can't be on the tcp_time_wait_head list
7593 	 * since it is not detached.
7594 	 */
7595 	ASSERT(tcp->tcp_time_wait_next == NULL);
7596 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7597 	ASSERT(tcp->tcp_time_wait_expire == 0);
7598 
7599 	if (tcp->tcp_kssl_pending) {
7600 		tcp->tcp_kssl_pending = B_FALSE;
7601 
7602 		/* Don't reset if the initialized by bind. */
7603 		if (tcp->tcp_kssl_ent != NULL) {
7604 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7605 			    KSSL_NO_PROXY);
7606 		}
7607 	}
7608 	if (tcp->tcp_kssl_ctx != NULL) {
7609 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7610 		tcp->tcp_kssl_ctx = NULL;
7611 	}
7612 
7613 	/*
7614 	 * Reset/preserve other values
7615 	 */
7616 	tcp_reinit_values(tcp);
7617 	ipcl_hash_remove(tcp->tcp_connp);
7618 	conn_delete_ire(tcp->tcp_connp, NULL);
7619 
7620 	if (tcp->tcp_conn_req_max != 0) {
7621 		/*
7622 		 * This is the case when a TLI program uses the same
7623 		 * transport end point to accept a connection.  This
7624 		 * makes the TCP both a listener and acceptor.  When
7625 		 * this connection is closed, we need to set the state
7626 		 * back to TCPS_LISTEN.  Make sure that the eager list
7627 		 * is reinitialized.
7628 		 *
7629 		 * Note that this stream is still bound to the four
7630 		 * tuples of the previous connection in IP.  If a new
7631 		 * SYN with different foreign address comes in, IP will
7632 		 * not find it and will send it to the global queue.  In
7633 		 * the global queue, TCP will do a tcp_lookup_listener()
7634 		 * to find this stream.  This works because this stream
7635 		 * is only removed from connected hash.
7636 		 *
7637 		 */
7638 		tcp->tcp_state = TCPS_LISTEN;
7639 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7640 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7641 		if (tcp->tcp_family == AF_INET6) {
7642 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7643 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7644 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7645 		} else {
7646 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7647 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7648 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7649 		}
7650 	} else {
7651 		tcp->tcp_state = TCPS_BOUND;
7652 	}
7653 
7654 	/*
7655 	 * Initialize to default values
7656 	 * Can't fail since enough header template space already allocated
7657 	 * at open().
7658 	 */
7659 	err = tcp_init_values(tcp);
7660 	ASSERT(err == 0);
7661 	/* Restore state in tcp_tcph */
7662 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7663 	if (tcp->tcp_ipversion == IPV4_VERSION)
7664 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7665 	else
7666 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7667 	/*
7668 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7669 	 * since the lookup funcs can only lookup on tcp_t
7670 	 */
7671 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7672 
7673 	ASSERT(tcp->tcp_ptpbhn != NULL);
7674 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
7675 	tcp->tcp_rwnd = tcp_recv_hiwat;
7676 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7677 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
7678 }
7679 
7680 /*
7681  * Force values to zero that need be zero.
7682  * Do not touch values asociated with the BOUND or LISTEN state
7683  * since the connection will end up in that state after the reinit.
7684  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7685  * structure!
7686  */
7687 static void
7688 tcp_reinit_values(tcp)
7689 	tcp_t *tcp;
7690 {
7691 #ifndef	lint
7692 #define	DONTCARE(x)
7693 #define	PRESERVE(x)
7694 #else
7695 #define	DONTCARE(x)	((x) = (x))
7696 #define	PRESERVE(x)	((x) = (x))
7697 #endif	/* lint */
7698 
7699 	PRESERVE(tcp->tcp_bind_hash);
7700 	PRESERVE(tcp->tcp_ptpbhn);
7701 	PRESERVE(tcp->tcp_acceptor_hash);
7702 	PRESERVE(tcp->tcp_ptpahn);
7703 
7704 	/* Should be ASSERT NULL on these with new code! */
7705 	ASSERT(tcp->tcp_time_wait_next == NULL);
7706 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7707 	ASSERT(tcp->tcp_time_wait_expire == 0);
7708 	PRESERVE(tcp->tcp_state);
7709 	PRESERVE(tcp->tcp_rq);
7710 	PRESERVE(tcp->tcp_wq);
7711 
7712 	ASSERT(tcp->tcp_xmit_head == NULL);
7713 	ASSERT(tcp->tcp_xmit_last == NULL);
7714 	ASSERT(tcp->tcp_unsent == 0);
7715 	ASSERT(tcp->tcp_xmit_tail == NULL);
7716 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7717 
7718 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7719 	tcp->tcp_suna = 0;			/* Displayed in mib */
7720 	tcp->tcp_swnd = 0;
7721 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7722 
7723 	ASSERT(tcp->tcp_ibsegs == 0);
7724 	ASSERT(tcp->tcp_obsegs == 0);
7725 
7726 	if (tcp->tcp_iphc != NULL) {
7727 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7728 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7729 	}
7730 
7731 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7732 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7733 	DONTCARE(tcp->tcp_ipha);
7734 	DONTCARE(tcp->tcp_ip6h);
7735 	DONTCARE(tcp->tcp_ip_hdr_len);
7736 	DONTCARE(tcp->tcp_tcph);
7737 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7738 	tcp->tcp_valid_bits = 0;
7739 
7740 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7741 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7742 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7743 	tcp->tcp_last_rcv_lbolt = 0;
7744 
7745 	tcp->tcp_init_cwnd = 0;
7746 
7747 	tcp->tcp_urp_last_valid = 0;
7748 	tcp->tcp_hard_binding = 0;
7749 	tcp->tcp_hard_bound = 0;
7750 	PRESERVE(tcp->tcp_cred);
7751 	PRESERVE(tcp->tcp_cpid);
7752 	PRESERVE(tcp->tcp_exclbind);
7753 
7754 	tcp->tcp_fin_acked = 0;
7755 	tcp->tcp_fin_rcvd = 0;
7756 	tcp->tcp_fin_sent = 0;
7757 	tcp->tcp_ordrel_done = 0;
7758 
7759 	tcp->tcp_debug = 0;
7760 	tcp->tcp_dontroute = 0;
7761 	tcp->tcp_broadcast = 0;
7762 
7763 	tcp->tcp_useloopback = 0;
7764 	tcp->tcp_reuseaddr = 0;
7765 	tcp->tcp_oobinline = 0;
7766 	tcp->tcp_dgram_errind = 0;
7767 
7768 	tcp->tcp_detached = 0;
7769 	tcp->tcp_bind_pending = 0;
7770 	tcp->tcp_unbind_pending = 0;
7771 	tcp->tcp_deferred_clean_death = 0;
7772 
7773 	tcp->tcp_snd_ws_ok = B_FALSE;
7774 	tcp->tcp_snd_ts_ok = B_FALSE;
7775 	tcp->tcp_linger = 0;
7776 	tcp->tcp_ka_enabled = 0;
7777 	tcp->tcp_zero_win_probe = 0;
7778 
7779 	tcp->tcp_loopback = 0;
7780 	tcp->tcp_localnet = 0;
7781 	tcp->tcp_syn_defense = 0;
7782 	tcp->tcp_set_timer = 0;
7783 
7784 	tcp->tcp_active_open = 0;
7785 	ASSERT(tcp->tcp_timeout == B_FALSE);
7786 	tcp->tcp_rexmit = B_FALSE;
7787 	tcp->tcp_xmit_zc_clean = B_FALSE;
7788 
7789 	tcp->tcp_snd_sack_ok = B_FALSE;
7790 	PRESERVE(tcp->tcp_recvdstaddr);
7791 	tcp->tcp_hwcksum = B_FALSE;
7792 
7793 	tcp->tcp_ire_ill_check_done = B_FALSE;
7794 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7795 
7796 	tcp->tcp_mdt = B_FALSE;
7797 	tcp->tcp_mdt_hdr_head = 0;
7798 	tcp->tcp_mdt_hdr_tail = 0;
7799 
7800 	tcp->tcp_conn_def_q0 = 0;
7801 	tcp->tcp_ip_forward_progress = B_FALSE;
7802 	tcp->tcp_anon_priv_bind = 0;
7803 	tcp->tcp_ecn_ok = B_FALSE;
7804 
7805 	tcp->tcp_cwr = B_FALSE;
7806 	tcp->tcp_ecn_echo_on = B_FALSE;
7807 
7808 	if (tcp->tcp_sack_info != NULL) {
7809 		if (tcp->tcp_notsack_list != NULL) {
7810 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7811 		}
7812 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7813 		tcp->tcp_sack_info = NULL;
7814 	}
7815 
7816 	tcp->tcp_rcv_ws = 0;
7817 	tcp->tcp_snd_ws = 0;
7818 	tcp->tcp_ts_recent = 0;
7819 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7820 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7821 	tcp->tcp_if_mtu = 0;
7822 
7823 	ASSERT(tcp->tcp_reass_head == NULL);
7824 	ASSERT(tcp->tcp_reass_tail == NULL);
7825 
7826 	tcp->tcp_cwnd_cnt = 0;
7827 
7828 	ASSERT(tcp->tcp_rcv_list == NULL);
7829 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7830 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7831 	ASSERT(tcp->tcp_rcv_cnt == 0);
7832 
7833 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7834 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7835 	tcp->tcp_csuna = 0;
7836 
7837 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7838 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7839 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7840 	tcp->tcp_rtt_update = 0;
7841 
7842 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7843 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7844 
7845 	tcp->tcp_rack = 0;			/* Displayed in mib */
7846 	tcp->tcp_rack_cnt = 0;
7847 	tcp->tcp_rack_cur_max = 0;
7848 	tcp->tcp_rack_abs_max = 0;
7849 
7850 	tcp->tcp_max_swnd = 0;
7851 
7852 	ASSERT(tcp->tcp_listener == NULL);
7853 
7854 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7855 
7856 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7857 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7858 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7859 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7860 
7861 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7862 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7863 	PRESERVE(tcp->tcp_conn_req_max);
7864 	PRESERVE(tcp->tcp_conn_req_seqnum);
7865 
7866 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7867 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7868 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7869 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7870 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7871 
7872 	tcp->tcp_lingertime = 0;
7873 
7874 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7875 	ASSERT(tcp->tcp_urp_mp == NULL);
7876 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7877 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7878 
7879 	ASSERT(tcp->tcp_eager_next_q == NULL);
7880 	ASSERT(tcp->tcp_eager_last_q == NULL);
7881 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7882 	    tcp->tcp_eager_prev_q0 == NULL) ||
7883 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7884 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7885 
7886 	tcp->tcp_client_errno = 0;
7887 
7888 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7889 
7890 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7891 
7892 	PRESERVE(tcp->tcp_bound_source_v6);
7893 	tcp->tcp_last_sent_len = 0;
7894 	tcp->tcp_dupack_cnt = 0;
7895 
7896 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7897 	PRESERVE(tcp->tcp_lport);
7898 
7899 	PRESERVE(tcp->tcp_acceptor_lockp);
7900 
7901 	ASSERT(tcp->tcp_ordrelid == 0);
7902 	PRESERVE(tcp->tcp_acceptor_id);
7903 	DONTCARE(tcp->tcp_ipsec_overhead);
7904 
7905 	/*
7906 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
7907 	 * in tcp structure and now tracing), Re-initialize all
7908 	 * members of tcp_traceinfo.
7909 	 */
7910 	if (tcp->tcp_tracebuf != NULL) {
7911 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
7912 	}
7913 
7914 	PRESERVE(tcp->tcp_family);
7915 	if (tcp->tcp_family == AF_INET6) {
7916 		tcp->tcp_ipversion = IPV6_VERSION;
7917 		tcp->tcp_mss = tcp_mss_def_ipv6;
7918 	} else {
7919 		tcp->tcp_ipversion = IPV4_VERSION;
7920 		tcp->tcp_mss = tcp_mss_def_ipv4;
7921 	}
7922 
7923 	tcp->tcp_bound_if = 0;
7924 	tcp->tcp_ipv6_recvancillary = 0;
7925 	tcp->tcp_recvifindex = 0;
7926 	tcp->tcp_recvhops = 0;
7927 	tcp->tcp_closed = 0;
7928 	tcp->tcp_cleandeathtag = 0;
7929 	if (tcp->tcp_hopopts != NULL) {
7930 		mi_free(tcp->tcp_hopopts);
7931 		tcp->tcp_hopopts = NULL;
7932 		tcp->tcp_hopoptslen = 0;
7933 	}
7934 	ASSERT(tcp->tcp_hopoptslen == 0);
7935 	if (tcp->tcp_dstopts != NULL) {
7936 		mi_free(tcp->tcp_dstopts);
7937 		tcp->tcp_dstopts = NULL;
7938 		tcp->tcp_dstoptslen = 0;
7939 	}
7940 	ASSERT(tcp->tcp_dstoptslen == 0);
7941 	if (tcp->tcp_rtdstopts != NULL) {
7942 		mi_free(tcp->tcp_rtdstopts);
7943 		tcp->tcp_rtdstopts = NULL;
7944 		tcp->tcp_rtdstoptslen = 0;
7945 	}
7946 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7947 	if (tcp->tcp_rthdr != NULL) {
7948 		mi_free(tcp->tcp_rthdr);
7949 		tcp->tcp_rthdr = NULL;
7950 		tcp->tcp_rthdrlen = 0;
7951 	}
7952 	ASSERT(tcp->tcp_rthdrlen == 0);
7953 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7954 
7955 	/* Reset fusion-related fields */
7956 	tcp->tcp_fused = B_FALSE;
7957 	tcp->tcp_unfusable = B_FALSE;
7958 	tcp->tcp_fused_sigurg = B_FALSE;
7959 	tcp->tcp_direct_sockfs = B_FALSE;
7960 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7961 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7962 	tcp->tcp_loopback_peer = NULL;
7963 	tcp->tcp_fuse_rcv_hiwater = 0;
7964 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7965 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7966 
7967 	tcp->tcp_in_ack_unsent = 0;
7968 	tcp->tcp_cork = B_FALSE;
7969 
7970 	PRESERVE(tcp->tcp_squeue_bytes);
7971 
7972 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7973 	ASSERT(!tcp->tcp_kssl_pending);
7974 	PRESERVE(tcp->tcp_kssl_ent);
7975 
7976 #undef	DONTCARE
7977 #undef	PRESERVE
7978 }
7979 
7980 /*
7981  * Allocate necessary resources and initialize state vector.
7982  * Guaranteed not to fail so that when an error is returned,
7983  * the caller doesn't need to do any additional cleanup.
7984  */
7985 int
7986 tcp_init(tcp_t *tcp, queue_t *q)
7987 {
7988 	int	err;
7989 
7990 	tcp->tcp_rq = q;
7991 	tcp->tcp_wq = WR(q);
7992 	tcp->tcp_state = TCPS_IDLE;
7993 	if ((err = tcp_init_values(tcp)) != 0)
7994 		tcp_timers_stop(tcp);
7995 	return (err);
7996 }
7997 
7998 static int
7999 tcp_init_values(tcp_t *tcp)
8000 {
8001 	int	err;
8002 
8003 	ASSERT((tcp->tcp_family == AF_INET &&
8004 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8005 	    (tcp->tcp_family == AF_INET6 &&
8006 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8007 	    tcp->tcp_ipversion == IPV6_VERSION)));
8008 
8009 	/*
8010 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8011 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8012 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8013 	 * during first few transmissions of a connection as seen in slow
8014 	 * links.
8015 	 */
8016 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
8017 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
8018 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8019 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8020 	    tcp_conn_grace_period;
8021 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
8022 		tcp->tcp_rto = tcp_rexmit_interval_min;
8023 	tcp->tcp_timer_backoff = 0;
8024 	tcp->tcp_ms_we_have_waited = 0;
8025 	tcp->tcp_last_recv_time = lbolt;
8026 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
8027 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
8028 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8029 
8030 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
8031 
8032 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
8033 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
8034 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
8035 	/*
8036 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8037 	 * passive open.
8038 	 */
8039 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
8040 
8041 	tcp->tcp_naglim = tcp_naglim_def;
8042 
8043 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8044 
8045 	tcp->tcp_mdt_hdr_head = 0;
8046 	tcp->tcp_mdt_hdr_tail = 0;
8047 
8048 	/* Reset fusion-related fields */
8049 	tcp->tcp_fused = B_FALSE;
8050 	tcp->tcp_unfusable = B_FALSE;
8051 	tcp->tcp_fused_sigurg = B_FALSE;
8052 	tcp->tcp_direct_sockfs = B_FALSE;
8053 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8054 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8055 	tcp->tcp_loopback_peer = NULL;
8056 	tcp->tcp_fuse_rcv_hiwater = 0;
8057 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8058 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8059 
8060 	/* Initialize the header template */
8061 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8062 		err = tcp_header_init_ipv4(tcp);
8063 	} else {
8064 		err = tcp_header_init_ipv6(tcp);
8065 	}
8066 	if (err)
8067 		return (err);
8068 
8069 	/*
8070 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8071 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8072 	 */
8073 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8074 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
8075 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
8076 
8077 	tcp->tcp_cork = B_FALSE;
8078 	/*
8079 	 * Init the tcp_debug option.  This value determines whether TCP
8080 	 * calls strlog() to print out debug messages.  Doing this
8081 	 * initialization here means that this value is not inherited thru
8082 	 * tcp_reinit().
8083 	 */
8084 	tcp->tcp_debug = tcp_dbg;
8085 
8086 	tcp->tcp_ka_interval = tcp_keepalive_interval;
8087 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
8088 
8089 	return (0);
8090 }
8091 
8092 /*
8093  * Initialize the IPv4 header. Loses any record of any IP options.
8094  */
8095 static int
8096 tcp_header_init_ipv4(tcp_t *tcp)
8097 {
8098 	tcph_t		*tcph;
8099 	uint32_t	sum;
8100 	conn_t		*connp;
8101 
8102 	/*
8103 	 * This is a simple initialization. If there's
8104 	 * already a template, it should never be too small,
8105 	 * so reuse it.  Otherwise, allocate space for the new one.
8106 	 */
8107 	if (tcp->tcp_iphc == NULL) {
8108 		ASSERT(tcp->tcp_iphc_len == 0);
8109 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8110 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8111 		if (tcp->tcp_iphc == NULL) {
8112 			tcp->tcp_iphc_len = 0;
8113 			return (ENOMEM);
8114 		}
8115 	}
8116 
8117 	/* options are gone; may need a new label */
8118 	connp = tcp->tcp_connp;
8119 	connp->conn_mlp_type = mlptSingle;
8120 	connp->conn_ulp_labeled = !is_system_labeled();
8121 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8122 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8123 	tcp->tcp_ip6h = NULL;
8124 	tcp->tcp_ipversion = IPV4_VERSION;
8125 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8126 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8127 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8128 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8129 	tcp->tcp_ipha->ipha_version_and_hdr_length
8130 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8131 	tcp->tcp_ipha->ipha_ident = 0;
8132 
8133 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
8134 	tcp->tcp_tos = 0;
8135 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8136 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
8137 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8138 
8139 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8140 	tcp->tcp_tcph = tcph;
8141 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8142 	/*
8143 	 * IP wants our header length in the checksum field to
8144 	 * allow it to perform a single pseudo-header+checksum
8145 	 * calculation on behalf of TCP.
8146 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8147 	 */
8148 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8149 	sum = (sum >> 16) + (sum & 0xFFFF);
8150 	U16_TO_ABE16(sum, tcph->th_sum);
8151 	return (0);
8152 }
8153 
8154 /*
8155  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8156  */
8157 static int
8158 tcp_header_init_ipv6(tcp_t *tcp)
8159 {
8160 	tcph_t	*tcph;
8161 	uint32_t	sum;
8162 	conn_t	*connp;
8163 
8164 	/*
8165 	 * This is a simple initialization. If there's
8166 	 * already a template, it should never be too small,
8167 	 * so reuse it. Otherwise, allocate space for the new one.
8168 	 * Ensure that there is enough space to "downgrade" the tcp_t
8169 	 * to an IPv4 tcp_t. This requires having space for a full load
8170 	 * of IPv4 options, as well as a full load of TCP options
8171 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8172 	 * than a v6 header and a TCP header with a full load of TCP options
8173 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8174 	 * We want to avoid reallocation in the "downgraded" case when
8175 	 * processing outbound IPv4 options.
8176 	 */
8177 	if (tcp->tcp_iphc == NULL) {
8178 		ASSERT(tcp->tcp_iphc_len == 0);
8179 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8180 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8181 		if (tcp->tcp_iphc == NULL) {
8182 			tcp->tcp_iphc_len = 0;
8183 			return (ENOMEM);
8184 		}
8185 	}
8186 
8187 	/* options are gone; may need a new label */
8188 	connp = tcp->tcp_connp;
8189 	connp->conn_mlp_type = mlptSingle;
8190 	connp->conn_ulp_labeled = !is_system_labeled();
8191 
8192 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8193 	tcp->tcp_ipversion = IPV6_VERSION;
8194 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8195 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8196 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8197 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8198 	tcp->tcp_ipha = NULL;
8199 
8200 	/* Initialize the header template */
8201 
8202 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8203 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8204 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8205 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
8206 
8207 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8208 	tcp->tcp_tcph = tcph;
8209 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8210 	/*
8211 	 * IP wants our header length in the checksum field to
8212 	 * allow it to perform a single psuedo-header+checksum
8213 	 * calculation on behalf of TCP.
8214 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8215 	 */
8216 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8217 	sum = (sum >> 16) + (sum & 0xFFFF);
8218 	U16_TO_ABE16(sum, tcph->th_sum);
8219 	return (0);
8220 }
8221 
8222 /* At minimum we need 4 bytes in the TCP header for the lookup */
8223 #define	ICMP_MIN_TCP_HDR	12
8224 
8225 /*
8226  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8227  * passed up by IP. The message is always received on the correct tcp_t.
8228  * Assumes that IP has pulled up everything up to and including the ICMP header.
8229  */
8230 void
8231 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8232 {
8233 	icmph_t *icmph;
8234 	ipha_t	*ipha;
8235 	int	iph_hdr_length;
8236 	tcph_t	*tcph;
8237 	boolean_t ipsec_mctl = B_FALSE;
8238 	boolean_t secure;
8239 	mblk_t *first_mp = mp;
8240 	uint32_t new_mss;
8241 	uint32_t ratio;
8242 	size_t mp_size = MBLKL(mp);
8243 	uint32_t seg_ack;
8244 	uint32_t seg_seq;
8245 
8246 	/* Assume IP provides aligned packets - otherwise toss */
8247 	if (!OK_32PTR(mp->b_rptr)) {
8248 		freemsg(mp);
8249 		return;
8250 	}
8251 
8252 	/*
8253 	 * Since ICMP errors are normal data marked with M_CTL when sent
8254 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8255 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8256 	 */
8257 	if ((mp_size == sizeof (ipsec_info_t)) &&
8258 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8259 		ASSERT(mp->b_cont != NULL);
8260 		mp = mp->b_cont;
8261 		/* IP should have done this */
8262 		ASSERT(OK_32PTR(mp->b_rptr));
8263 		mp_size = MBLKL(mp);
8264 		ipsec_mctl = B_TRUE;
8265 	}
8266 
8267 	/*
8268 	 * Verify that we have a complete outer IP header. If not, drop it.
8269 	 */
8270 	if (mp_size < sizeof (ipha_t)) {
8271 noticmpv4:
8272 		freemsg(first_mp);
8273 		return;
8274 	}
8275 
8276 	ipha = (ipha_t *)mp->b_rptr;
8277 	/*
8278 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8279 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8280 	 */
8281 	switch (IPH_HDR_VERSION(ipha)) {
8282 	case IPV6_VERSION:
8283 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8284 		return;
8285 	case IPV4_VERSION:
8286 		break;
8287 	default:
8288 		goto noticmpv4;
8289 	}
8290 
8291 	/* Skip past the outer IP and ICMP headers */
8292 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8293 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8294 	/*
8295 	 * If we don't have the correct outer IP header length or if the ULP
8296 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8297 	 * send it upstream.
8298 	 */
8299 	if (iph_hdr_length < sizeof (ipha_t) ||
8300 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8301 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8302 		goto noticmpv4;
8303 	}
8304 	ipha = (ipha_t *)&icmph[1];
8305 
8306 	/* Skip past the inner IP and find the ULP header */
8307 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8308 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8309 	/*
8310 	 * If we don't have the correct inner IP header length or if the ULP
8311 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8312 	 * bytes of TCP header, drop it.
8313 	 */
8314 	if (iph_hdr_length < sizeof (ipha_t) ||
8315 	    ipha->ipha_protocol != IPPROTO_TCP ||
8316 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8317 		goto noticmpv4;
8318 	}
8319 
8320 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8321 		if (ipsec_mctl) {
8322 			secure = ipsec_in_is_secure(first_mp);
8323 		} else {
8324 			secure = B_FALSE;
8325 		}
8326 		if (secure) {
8327 			/*
8328 			 * If we are willing to accept this in clear
8329 			 * we don't have to verify policy.
8330 			 */
8331 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8332 				if (!tcp_check_policy(tcp, first_mp,
8333 				    ipha, NULL, secure, ipsec_mctl)) {
8334 					/*
8335 					 * tcp_check_policy called
8336 					 * ip_drop_packet() on failure.
8337 					 */
8338 					return;
8339 				}
8340 			}
8341 		}
8342 	} else if (ipsec_mctl) {
8343 		/*
8344 		 * This is a hard_bound connection. IP has already
8345 		 * verified policy. We don't have to do it again.
8346 		 */
8347 		freeb(first_mp);
8348 		first_mp = mp;
8349 		ipsec_mctl = B_FALSE;
8350 	}
8351 
8352 	seg_ack = ABE32_TO_U32(tcph->th_ack);
8353 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8354 	/*
8355 	 * TCP SHOULD check that the TCP sequence number contained in
8356 	 * payload of the ICMP error message is within the range
8357 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8358 	 */
8359 	if (SEQ_LT(seg_seq, tcp->tcp_suna) ||
8360 		SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8361 		SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8362 		/*
8363 		 * If the ICMP message is bogus, should we kill the
8364 		 * connection, or should we just drop the bogus ICMP
8365 		 * message? It would probably make more sense to just
8366 		 * drop the message so that if this one managed to get
8367 		 * in, the real connection should not suffer.
8368 		 */
8369 		goto noticmpv4;
8370 	}
8371 
8372 	switch (icmph->icmph_type) {
8373 	case ICMP_DEST_UNREACHABLE:
8374 		switch (icmph->icmph_code) {
8375 		case ICMP_FRAGMENTATION_NEEDED:
8376 			/*
8377 			 * Reduce the MSS based on the new MTU.  This will
8378 			 * eliminate any fragmentation locally.
8379 			 * N.B.  There may well be some funny side-effects on
8380 			 * the local send policy and the remote receive policy.
8381 			 * Pending further research, we provide
8382 			 * tcp_ignore_path_mtu just in case this proves
8383 			 * disastrous somewhere.
8384 			 *
8385 			 * After updating the MSS, retransmit part of the
8386 			 * dropped segment using the new mss by calling
8387 			 * tcp_wput_data().  Need to adjust all those
8388 			 * params to make sure tcp_wput_data() work properly.
8389 			 */
8390 			if (tcp_ignore_path_mtu)
8391 				break;
8392 
8393 			/*
8394 			 * Decrease the MSS by time stamp options
8395 			 * IP options and IPSEC options. tcp_hdr_len
8396 			 * includes time stamp option and IP option
8397 			 * length.
8398 			 */
8399 
8400 			new_mss = ntohs(icmph->icmph_du_mtu) -
8401 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8402 
8403 			/*
8404 			 * Only update the MSS if the new one is
8405 			 * smaller than the previous one.  This is
8406 			 * to avoid problems when getting multiple
8407 			 * ICMP errors for the same MTU.
8408 			 */
8409 			if (new_mss >= tcp->tcp_mss)
8410 				break;
8411 
8412 			/*
8413 			 * Stop doing PMTU if new_mss is less than 68
8414 			 * or less than tcp_mss_min.
8415 			 * The value 68 comes from rfc 1191.
8416 			 */
8417 			if (new_mss < MAX(68, tcp_mss_min))
8418 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8419 				    0;
8420 
8421 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8422 			ASSERT(ratio >= 1);
8423 			tcp_mss_set(tcp, new_mss);
8424 
8425 			/*
8426 			 * Make sure we have something to
8427 			 * send.
8428 			 */
8429 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8430 			    (tcp->tcp_xmit_head != NULL)) {
8431 				/*
8432 				 * Shrink tcp_cwnd in
8433 				 * proportion to the old MSS/new MSS.
8434 				 */
8435 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8436 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8437 				    (tcp->tcp_unsent == 0)) {
8438 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8439 				} else {
8440 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8441 				}
8442 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8443 				tcp->tcp_rexmit = B_TRUE;
8444 				tcp->tcp_dupack_cnt = 0;
8445 				tcp->tcp_snd_burst = TCP_CWND_SS;
8446 				tcp_ss_rexmit(tcp);
8447 			}
8448 			break;
8449 		case ICMP_PORT_UNREACHABLE:
8450 		case ICMP_PROTOCOL_UNREACHABLE:
8451 			switch (tcp->tcp_state) {
8452 			case TCPS_SYN_SENT:
8453 			case TCPS_SYN_RCVD:
8454 				/*
8455 				 * ICMP can snipe away incipient
8456 				 * TCP connections as long as
8457 				 * seq number is same as initial
8458 				 * send seq number.
8459 				 */
8460 				if (seg_seq == tcp->tcp_iss) {
8461 					(void) tcp_clean_death(tcp,
8462 					    ECONNREFUSED, 6);
8463 				}
8464 				break;
8465 			}
8466 			break;
8467 		case ICMP_HOST_UNREACHABLE:
8468 		case ICMP_NET_UNREACHABLE:
8469 			/* Record the error in case we finally time out. */
8470 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8471 				tcp->tcp_client_errno = EHOSTUNREACH;
8472 			else
8473 				tcp->tcp_client_errno = ENETUNREACH;
8474 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8475 				if (tcp->tcp_listener != NULL &&
8476 				    tcp->tcp_listener->tcp_syn_defense) {
8477 					/*
8478 					 * Ditch the half-open connection if we
8479 					 * suspect a SYN attack is under way.
8480 					 */
8481 					tcp_ip_ire_mark_advice(tcp);
8482 					(void) tcp_clean_death(tcp,
8483 					    tcp->tcp_client_errno, 7);
8484 				}
8485 			}
8486 			break;
8487 		default:
8488 			break;
8489 		}
8490 		break;
8491 	case ICMP_SOURCE_QUENCH: {
8492 		/*
8493 		 * use a global boolean to control
8494 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8495 		 * The default is false.
8496 		 */
8497 		if (tcp_icmp_source_quench) {
8498 			/*
8499 			 * Reduce the sending rate as if we got a
8500 			 * retransmit timeout
8501 			 */
8502 			uint32_t npkt;
8503 
8504 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8505 			    tcp->tcp_mss;
8506 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8507 			tcp->tcp_cwnd = tcp->tcp_mss;
8508 			tcp->tcp_cwnd_cnt = 0;
8509 		}
8510 		break;
8511 	}
8512 	}
8513 	freemsg(first_mp);
8514 }
8515 
8516 /*
8517  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8518  * error messages passed up by IP.
8519  * Assumes that IP has pulled up all the extension headers as well
8520  * as the ICMPv6 header.
8521  */
8522 static void
8523 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8524 {
8525 	icmp6_t *icmp6;
8526 	ip6_t	*ip6h;
8527 	uint16_t	iph_hdr_length;
8528 	tcpha_t	*tcpha;
8529 	uint8_t	*nexthdrp;
8530 	uint32_t new_mss;
8531 	uint32_t ratio;
8532 	boolean_t secure;
8533 	mblk_t *first_mp = mp;
8534 	size_t mp_size;
8535 	uint32_t seg_ack;
8536 	uint32_t seg_seq;
8537 
8538 	/*
8539 	 * The caller has determined if this is an IPSEC_IN packet and
8540 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8541 	 */
8542 	if (ipsec_mctl)
8543 		mp = mp->b_cont;
8544 
8545 	mp_size = MBLKL(mp);
8546 
8547 	/*
8548 	 * Verify that we have a complete IP header. If not, send it upstream.
8549 	 */
8550 	if (mp_size < sizeof (ip6_t)) {
8551 noticmpv6:
8552 		freemsg(first_mp);
8553 		return;
8554 	}
8555 
8556 	/*
8557 	 * Verify this is an ICMPV6 packet, else send it upstream.
8558 	 */
8559 	ip6h = (ip6_t *)mp->b_rptr;
8560 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8561 		iph_hdr_length = IPV6_HDR_LEN;
8562 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8563 	    &nexthdrp) ||
8564 	    *nexthdrp != IPPROTO_ICMPV6) {
8565 		goto noticmpv6;
8566 	}
8567 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8568 	ip6h = (ip6_t *)&icmp6[1];
8569 	/*
8570 	 * Verify if we have a complete ICMP and inner IP header.
8571 	 */
8572 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8573 		goto noticmpv6;
8574 
8575 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8576 		goto noticmpv6;
8577 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8578 	/*
8579 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8580 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8581 	 * packet.
8582 	 */
8583 	if ((*nexthdrp != IPPROTO_TCP) ||
8584 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8585 		goto noticmpv6;
8586 	}
8587 
8588 	/*
8589 	 * ICMP errors come on the right queue or come on
8590 	 * listener/global queue for detached connections and
8591 	 * get switched to the right queue. If it comes on the
8592 	 * right queue, policy check has already been done by IP
8593 	 * and thus free the first_mp without verifying the policy.
8594 	 * If it has come for a non-hard bound connection, we need
8595 	 * to verify policy as IP may not have done it.
8596 	 */
8597 	if (!tcp->tcp_hard_bound) {
8598 		if (ipsec_mctl) {
8599 			secure = ipsec_in_is_secure(first_mp);
8600 		} else {
8601 			secure = B_FALSE;
8602 		}
8603 		if (secure) {
8604 			/*
8605 			 * If we are willing to accept this in clear
8606 			 * we don't have to verify policy.
8607 			 */
8608 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8609 				if (!tcp_check_policy(tcp, first_mp,
8610 				    NULL, ip6h, secure, ipsec_mctl)) {
8611 					/*
8612 					 * tcp_check_policy called
8613 					 * ip_drop_packet() on failure.
8614 					 */
8615 					return;
8616 				}
8617 			}
8618 		}
8619 	} else if (ipsec_mctl) {
8620 		/*
8621 		 * This is a hard_bound connection. IP has already
8622 		 * verified policy. We don't have to do it again.
8623 		 */
8624 		freeb(first_mp);
8625 		first_mp = mp;
8626 		ipsec_mctl = B_FALSE;
8627 	}
8628 
8629 	seg_ack = ntohl(tcpha->tha_ack);
8630 	seg_seq = ntohl(tcpha->tha_seq);
8631 	/*
8632 	 * TCP SHOULD check that the TCP sequence number contained in
8633 	 * payload of the ICMP error message is within the range
8634 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8635 	 */
8636 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8637 	    SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8638 		/*
8639 		 * If the ICMP message is bogus, should we kill the
8640 		 * connection, or should we just drop the bogus ICMP
8641 		 * message? It would probably make more sense to just
8642 		 * drop the message so that if this one managed to get
8643 		 * in, the real connection should not suffer.
8644 		 */
8645 		goto noticmpv6;
8646 	}
8647 
8648 	switch (icmp6->icmp6_type) {
8649 	case ICMP6_PACKET_TOO_BIG:
8650 		/*
8651 		 * Reduce the MSS based on the new MTU.  This will
8652 		 * eliminate any fragmentation locally.
8653 		 * N.B.  There may well be some funny side-effects on
8654 		 * the local send policy and the remote receive policy.
8655 		 * Pending further research, we provide
8656 		 * tcp_ignore_path_mtu just in case this proves
8657 		 * disastrous somewhere.
8658 		 *
8659 		 * After updating the MSS, retransmit part of the
8660 		 * dropped segment using the new mss by calling
8661 		 * tcp_wput_data().  Need to adjust all those
8662 		 * params to make sure tcp_wput_data() work properly.
8663 		 */
8664 		if (tcp_ignore_path_mtu)
8665 			break;
8666 
8667 		/*
8668 		 * Decrease the MSS by time stamp options
8669 		 * IP options and IPSEC options. tcp_hdr_len
8670 		 * includes time stamp option and IP option
8671 		 * length.
8672 		 */
8673 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8674 			    tcp->tcp_ipsec_overhead;
8675 
8676 		/*
8677 		 * Only update the MSS if the new one is
8678 		 * smaller than the previous one.  This is
8679 		 * to avoid problems when getting multiple
8680 		 * ICMP errors for the same MTU.
8681 		 */
8682 		if (new_mss >= tcp->tcp_mss)
8683 			break;
8684 
8685 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8686 		ASSERT(ratio >= 1);
8687 		tcp_mss_set(tcp, new_mss);
8688 
8689 		/*
8690 		 * Make sure we have something to
8691 		 * send.
8692 		 */
8693 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8694 		    (tcp->tcp_xmit_head != NULL)) {
8695 			/*
8696 			 * Shrink tcp_cwnd in
8697 			 * proportion to the old MSS/new MSS.
8698 			 */
8699 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8700 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8701 			    (tcp->tcp_unsent == 0)) {
8702 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8703 			} else {
8704 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8705 			}
8706 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8707 			tcp->tcp_rexmit = B_TRUE;
8708 			tcp->tcp_dupack_cnt = 0;
8709 			tcp->tcp_snd_burst = TCP_CWND_SS;
8710 			tcp_ss_rexmit(tcp);
8711 		}
8712 		break;
8713 
8714 	case ICMP6_DST_UNREACH:
8715 		switch (icmp6->icmp6_code) {
8716 		case ICMP6_DST_UNREACH_NOPORT:
8717 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8718 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8719 			    (seg_seq == tcp->tcp_iss)) {
8720 				(void) tcp_clean_death(tcp,
8721 				    ECONNREFUSED, 8);
8722 			}
8723 			break;
8724 
8725 		case ICMP6_DST_UNREACH_ADMIN:
8726 		case ICMP6_DST_UNREACH_NOROUTE:
8727 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8728 		case ICMP6_DST_UNREACH_ADDR:
8729 			/* Record the error in case we finally time out. */
8730 			tcp->tcp_client_errno = EHOSTUNREACH;
8731 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8732 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8733 			    (seg_seq == tcp->tcp_iss)) {
8734 				if (tcp->tcp_listener != NULL &&
8735 				    tcp->tcp_listener->tcp_syn_defense) {
8736 					/*
8737 					 * Ditch the half-open connection if we
8738 					 * suspect a SYN attack is under way.
8739 					 */
8740 					tcp_ip_ire_mark_advice(tcp);
8741 					(void) tcp_clean_death(tcp,
8742 					    tcp->tcp_client_errno, 9);
8743 				}
8744 			}
8745 
8746 
8747 			break;
8748 		default:
8749 			break;
8750 		}
8751 		break;
8752 
8753 	case ICMP6_PARAM_PROB:
8754 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8755 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8756 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8757 		    (uchar_t *)nexthdrp) {
8758 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8759 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8760 				(void) tcp_clean_death(tcp,
8761 				    ECONNREFUSED, 10);
8762 			}
8763 			break;
8764 		}
8765 		break;
8766 
8767 	case ICMP6_TIME_EXCEEDED:
8768 	default:
8769 		break;
8770 	}
8771 	freemsg(first_mp);
8772 }
8773 
8774 /*
8775  * IP recognizes seven kinds of bind requests:
8776  *
8777  * - A zero-length address binds only to the protocol number.
8778  *
8779  * - A 4-byte address is treated as a request to
8780  * validate that the address is a valid local IPv4
8781  * address, appropriate for an application to bind to.
8782  * IP does the verification, but does not make any note
8783  * of the address at this time.
8784  *
8785  * - A 16-byte address contains is treated as a request
8786  * to validate a local IPv6 address, as the 4-byte
8787  * address case above.
8788  *
8789  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8790  * use it for the inbound fanout of packets.
8791  *
8792  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8793  * use it for the inbound fanout of packets.
8794  *
8795  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8796  * information consisting of local and remote addresses
8797  * and ports.  In this case, the addresses are both
8798  * validated as appropriate for this operation, and, if
8799  * so, the information is retained for use in the
8800  * inbound fanout.
8801  *
8802  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8803  * fanout information, like the 12-byte case above.
8804  *
8805  * IP will also fill in the IRE request mblk with information
8806  * regarding our peer.  In all cases, we notify IP of our protocol
8807  * type by appending a single protocol byte to the bind request.
8808  */
8809 static mblk_t *
8810 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8811 {
8812 	char	*cp;
8813 	mblk_t	*mp;
8814 	struct T_bind_req *tbr;
8815 	ipa_conn_t	*ac;
8816 	ipa6_conn_t	*ac6;
8817 	sin_t		*sin;
8818 	sin6_t		*sin6;
8819 
8820 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
8821 	ASSERT((tcp->tcp_family == AF_INET &&
8822 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8823 	    (tcp->tcp_family == AF_INET6 &&
8824 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8825 	    tcp->tcp_ipversion == IPV6_VERSION)));
8826 
8827 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
8828 	if (!mp)
8829 		return (mp);
8830 	mp->b_datap->db_type = M_PROTO;
8831 	tbr = (struct T_bind_req *)mp->b_rptr;
8832 	tbr->PRIM_type = bind_prim;
8833 	tbr->ADDR_offset = sizeof (*tbr);
8834 	tbr->CONIND_number = 0;
8835 	tbr->ADDR_length = addr_length;
8836 	cp = (char *)&tbr[1];
8837 	switch (addr_length) {
8838 	case sizeof (ipa_conn_t):
8839 		ASSERT(tcp->tcp_family == AF_INET);
8840 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8841 
8842 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8843 		if (mp->b_cont == NULL) {
8844 			freemsg(mp);
8845 			return (NULL);
8846 		}
8847 		mp->b_cont->b_wptr += sizeof (ire_t);
8848 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8849 
8850 		/* cp known to be 32 bit aligned */
8851 		ac = (ipa_conn_t *)cp;
8852 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
8853 		ac->ac_faddr = tcp->tcp_remote;
8854 		ac->ac_fport = tcp->tcp_fport;
8855 		ac->ac_lport = tcp->tcp_lport;
8856 		tcp->tcp_hard_binding = 1;
8857 		break;
8858 
8859 	case sizeof (ipa6_conn_t):
8860 		ASSERT(tcp->tcp_family == AF_INET6);
8861 
8862 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8863 		if (mp->b_cont == NULL) {
8864 			freemsg(mp);
8865 			return (NULL);
8866 		}
8867 		mp->b_cont->b_wptr += sizeof (ire_t);
8868 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8869 
8870 		/* cp known to be 32 bit aligned */
8871 		ac6 = (ipa6_conn_t *)cp;
8872 		if (tcp->tcp_ipversion == IPV4_VERSION) {
8873 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
8874 			    &ac6->ac6_laddr);
8875 		} else {
8876 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
8877 		}
8878 		ac6->ac6_faddr = tcp->tcp_remote_v6;
8879 		ac6->ac6_fport = tcp->tcp_fport;
8880 		ac6->ac6_lport = tcp->tcp_lport;
8881 		tcp->tcp_hard_binding = 1;
8882 		break;
8883 
8884 	case sizeof (sin_t):
8885 		/*
8886 		 * NOTE: IPV6_ADDR_LEN also has same size.
8887 		 * Use family to discriminate.
8888 		 */
8889 		if (tcp->tcp_family == AF_INET) {
8890 			sin = (sin_t *)cp;
8891 
8892 			*sin = sin_null;
8893 			sin->sin_family = AF_INET;
8894 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
8895 			sin->sin_port = tcp->tcp_lport;
8896 			break;
8897 		} else {
8898 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
8899 		}
8900 		break;
8901 
8902 	case sizeof (sin6_t):
8903 		ASSERT(tcp->tcp_family == AF_INET6);
8904 		sin6 = (sin6_t *)cp;
8905 
8906 		*sin6 = sin6_null;
8907 		sin6->sin6_family = AF_INET6;
8908 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
8909 		sin6->sin6_port = tcp->tcp_lport;
8910 		break;
8911 
8912 	case IP_ADDR_LEN:
8913 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8914 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
8915 		break;
8916 
8917 	}
8918 	/* Add protocol number to end */
8919 	cp[addr_length] = (char)IPPROTO_TCP;
8920 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
8921 	return (mp);
8922 }
8923 
8924 /*
8925  * Notify IP that we are having trouble with this connection.  IP should
8926  * blow the IRE away and start over.
8927  */
8928 static void
8929 tcp_ip_notify(tcp_t *tcp)
8930 {
8931 	struct iocblk	*iocp;
8932 	ipid_t	*ipid;
8933 	mblk_t	*mp;
8934 
8935 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8936 	if (tcp->tcp_ipversion == IPV6_VERSION)
8937 		return;
8938 
8939 	mp = mkiocb(IP_IOCTL);
8940 	if (mp == NULL)
8941 		return;
8942 
8943 	iocp = (struct iocblk *)mp->b_rptr;
8944 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8945 
8946 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8947 	if (!mp->b_cont) {
8948 		freeb(mp);
8949 		return;
8950 	}
8951 
8952 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8953 	mp->b_cont->b_wptr += iocp->ioc_count;
8954 	bzero(ipid, sizeof (*ipid));
8955 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8956 	ipid->ipid_ire_type = IRE_CACHE;
8957 	ipid->ipid_addr_offset = sizeof (ipid_t);
8958 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8959 	/*
8960 	 * Note: in the case of source routing we want to blow away the
8961 	 * route to the first source route hop.
8962 	 */
8963 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8964 	    sizeof (tcp->tcp_ipha->ipha_dst));
8965 
8966 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8967 }
8968 
8969 /* Unlink and return any mblk that looks like it contains an ire */
8970 static mblk_t *
8971 tcp_ire_mp(mblk_t *mp)
8972 {
8973 	mblk_t	*prev_mp;
8974 
8975 	for (;;) {
8976 		prev_mp = mp;
8977 		mp = mp->b_cont;
8978 		if (mp == NULL)
8979 			break;
8980 		switch (DB_TYPE(mp)) {
8981 		case IRE_DB_TYPE:
8982 		case IRE_DB_REQ_TYPE:
8983 			if (prev_mp != NULL)
8984 				prev_mp->b_cont = mp->b_cont;
8985 			mp->b_cont = NULL;
8986 			return (mp);
8987 		default:
8988 			break;
8989 		}
8990 	}
8991 	return (mp);
8992 }
8993 
8994 /*
8995  * Timer callback routine for keepalive probe.  We do a fake resend of
8996  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8997  * check to see if we have heard anything from the other end for the last
8998  * RTO period.  If we have, set the timer to expire for another
8999  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9000  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9001  * the timeout if we have not heard from the other side.  If for more than
9002  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9003  * kill the connection unless the keepalive abort threshold is 0.  In
9004  * that case, we will probe "forever."
9005  */
9006 static void
9007 tcp_keepalive_killer(void *arg)
9008 {
9009 	mblk_t	*mp;
9010 	conn_t	*connp = (conn_t *)arg;
9011 	tcp_t  	*tcp = connp->conn_tcp;
9012 	int32_t	firetime;
9013 	int32_t	idletime;
9014 	int32_t	ka_intrvl;
9015 
9016 	tcp->tcp_ka_tid = 0;
9017 
9018 	if (tcp->tcp_fused)
9019 		return;
9020 
9021 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
9022 	ka_intrvl = tcp->tcp_ka_interval;
9023 
9024 	/*
9025 	 * Keepalive probe should only be sent if the application has not
9026 	 * done a close on the connection.
9027 	 */
9028 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9029 		return;
9030 	}
9031 	/* Timer fired too early, restart it. */
9032 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9033 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9034 		    MSEC_TO_TICK(ka_intrvl));
9035 		return;
9036 	}
9037 
9038 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9039 	/*
9040 	 * If we have not heard from the other side for a long
9041 	 * time, kill the connection unless the keepalive abort
9042 	 * threshold is 0.  In that case, we will probe "forever."
9043 	 */
9044 	if (tcp->tcp_ka_abort_thres != 0 &&
9045 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9046 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
9047 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9048 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9049 		return;
9050 	}
9051 
9052 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9053 	    idletime >= ka_intrvl) {
9054 		/* Fake resend of last ACKed byte. */
9055 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9056 
9057 		if (mp1 != NULL) {
9058 			*mp1->b_wptr++ = '\0';
9059 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9060 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9061 			freeb(mp1);
9062 			/*
9063 			 * if allocation failed, fall through to start the
9064 			 * timer back.
9065 			 */
9066 			if (mp != NULL) {
9067 				TCP_RECORD_TRACE(tcp, mp,
9068 				    TCP_TRACE_SEND_PKT);
9069 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9070 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
9071 				if (tcp->tcp_ka_last_intrvl != 0) {
9072 					/*
9073 					 * We should probe again at least
9074 					 * in ka_intrvl, but not more than
9075 					 * tcp_rexmit_interval_max.
9076 					 */
9077 					firetime = MIN(ka_intrvl - 1,
9078 					    tcp->tcp_ka_last_intrvl << 1);
9079 					if (firetime > tcp_rexmit_interval_max)
9080 						firetime =
9081 						    tcp_rexmit_interval_max;
9082 				} else {
9083 					firetime = tcp->tcp_rto;
9084 				}
9085 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9086 				    tcp_keepalive_killer,
9087 				    MSEC_TO_TICK(firetime));
9088 				tcp->tcp_ka_last_intrvl = firetime;
9089 				return;
9090 			}
9091 		}
9092 	} else {
9093 		tcp->tcp_ka_last_intrvl = 0;
9094 	}
9095 
9096 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9097 	if ((firetime = ka_intrvl - idletime) < 0) {
9098 		firetime = ka_intrvl;
9099 	}
9100 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9101 	    MSEC_TO_TICK(firetime));
9102 }
9103 
9104 int
9105 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9106 {
9107 	queue_t	*q = tcp->tcp_rq;
9108 	int32_t	mss = tcp->tcp_mss;
9109 	int	maxpsz;
9110 
9111 	if (TCP_IS_DETACHED(tcp))
9112 		return (mss);
9113 
9114 	if (tcp->tcp_fused) {
9115 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9116 		mss = INFPSZ;
9117 	} else if (tcp->tcp_mdt || tcp->tcp_maxpsz == 0) {
9118 		/*
9119 		 * Set the sd_qn_maxpsz according to the socket send buffer
9120 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9121 		 * instruct the stream head to copyin user data into contiguous
9122 		 * kernel-allocated buffers without breaking it up into smaller
9123 		 * chunks.  We round up the buffer size to the nearest SMSS.
9124 		 */
9125 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9126 		if (tcp->tcp_kssl_ctx == NULL)
9127 			mss = INFPSZ;
9128 		else
9129 			mss = SSL3_MAX_RECORD_LEN;
9130 	} else {
9131 		/*
9132 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9133 		 * (and a multiple of the mss).  This instructs the stream
9134 		 * head to break down larger than SMSS writes into SMSS-
9135 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9136 		 */
9137 		maxpsz = tcp->tcp_maxpsz * mss;
9138 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9139 			maxpsz = tcp->tcp_xmit_hiwater/2;
9140 			/* Round up to nearest mss */
9141 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9142 		}
9143 	}
9144 	(void) setmaxps(q, maxpsz);
9145 	tcp->tcp_wq->q_maxpsz = maxpsz;
9146 
9147 	if (set_maxblk)
9148 		(void) mi_set_sth_maxblk(q, mss);
9149 
9150 	return (mss);
9151 }
9152 
9153 /*
9154  * Extract option values from a tcp header.  We put any found values into the
9155  * tcpopt struct and return a bitmask saying which options were found.
9156  */
9157 static int
9158 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9159 {
9160 	uchar_t		*endp;
9161 	int		len;
9162 	uint32_t	mss;
9163 	uchar_t		*up = (uchar_t *)tcph;
9164 	int		found = 0;
9165 	int32_t		sack_len;
9166 	tcp_seq		sack_begin, sack_end;
9167 	tcp_t		*tcp;
9168 
9169 	endp = up + TCP_HDR_LENGTH(tcph);
9170 	up += TCP_MIN_HEADER_LENGTH;
9171 	while (up < endp) {
9172 		len = endp - up;
9173 		switch (*up) {
9174 		case TCPOPT_EOL:
9175 			break;
9176 
9177 		case TCPOPT_NOP:
9178 			up++;
9179 			continue;
9180 
9181 		case TCPOPT_MAXSEG:
9182 			if (len < TCPOPT_MAXSEG_LEN ||
9183 			    up[1] != TCPOPT_MAXSEG_LEN)
9184 				break;
9185 
9186 			mss = BE16_TO_U16(up+2);
9187 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9188 			tcpopt->tcp_opt_mss = mss;
9189 			found |= TCP_OPT_MSS_PRESENT;
9190 
9191 			up += TCPOPT_MAXSEG_LEN;
9192 			continue;
9193 
9194 		case TCPOPT_WSCALE:
9195 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9196 				break;
9197 
9198 			if (up[2] > TCP_MAX_WINSHIFT)
9199 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9200 			else
9201 				tcpopt->tcp_opt_wscale = up[2];
9202 			found |= TCP_OPT_WSCALE_PRESENT;
9203 
9204 			up += TCPOPT_WS_LEN;
9205 			continue;
9206 
9207 		case TCPOPT_SACK_PERMITTED:
9208 			if (len < TCPOPT_SACK_OK_LEN ||
9209 			    up[1] != TCPOPT_SACK_OK_LEN)
9210 				break;
9211 			found |= TCP_OPT_SACK_OK_PRESENT;
9212 			up += TCPOPT_SACK_OK_LEN;
9213 			continue;
9214 
9215 		case TCPOPT_SACK:
9216 			if (len <= 2 || up[1] <= 2 || len < up[1])
9217 				break;
9218 
9219 			/* If TCP is not interested in SACK blks... */
9220 			if ((tcp = tcpopt->tcp) == NULL) {
9221 				up += up[1];
9222 				continue;
9223 			}
9224 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9225 			up += TCPOPT_HEADER_LEN;
9226 
9227 			/*
9228 			 * If the list is empty, allocate one and assume
9229 			 * nothing is sack'ed.
9230 			 */
9231 			ASSERT(tcp->tcp_sack_info != NULL);
9232 			if (tcp->tcp_notsack_list == NULL) {
9233 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9234 				    tcp->tcp_suna, tcp->tcp_snxt,
9235 				    &(tcp->tcp_num_notsack_blk),
9236 				    &(tcp->tcp_cnt_notsack_list));
9237 
9238 				/*
9239 				 * Make sure tcp_notsack_list is not NULL.
9240 				 * This happens when kmem_alloc(KM_NOSLEEP)
9241 				 * returns NULL.
9242 				 */
9243 				if (tcp->tcp_notsack_list == NULL) {
9244 					up += sack_len;
9245 					continue;
9246 				}
9247 				tcp->tcp_fack = tcp->tcp_suna;
9248 			}
9249 
9250 			while (sack_len > 0) {
9251 				if (up + 8 > endp) {
9252 					up = endp;
9253 					break;
9254 				}
9255 				sack_begin = BE32_TO_U32(up);
9256 				up += 4;
9257 				sack_end = BE32_TO_U32(up);
9258 				up += 4;
9259 				sack_len -= 8;
9260 				/*
9261 				 * Bounds checking.  Make sure the SACK
9262 				 * info is within tcp_suna and tcp_snxt.
9263 				 * If this SACK blk is out of bound, ignore
9264 				 * it but continue to parse the following
9265 				 * blks.
9266 				 */
9267 				if (SEQ_LEQ(sack_end, sack_begin) ||
9268 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9269 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9270 					continue;
9271 				}
9272 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9273 				    sack_begin, sack_end,
9274 				    &(tcp->tcp_num_notsack_blk),
9275 				    &(tcp->tcp_cnt_notsack_list));
9276 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9277 					tcp->tcp_fack = sack_end;
9278 				}
9279 			}
9280 			found |= TCP_OPT_SACK_PRESENT;
9281 			continue;
9282 
9283 		case TCPOPT_TSTAMP:
9284 			if (len < TCPOPT_TSTAMP_LEN ||
9285 			    up[1] != TCPOPT_TSTAMP_LEN)
9286 				break;
9287 
9288 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9289 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9290 
9291 			found |= TCP_OPT_TSTAMP_PRESENT;
9292 
9293 			up += TCPOPT_TSTAMP_LEN;
9294 			continue;
9295 
9296 		default:
9297 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9298 				break;
9299 			up += up[1];
9300 			continue;
9301 		}
9302 		break;
9303 	}
9304 	return (found);
9305 }
9306 
9307 /*
9308  * Set the mss associated with a particular tcp based on its current value,
9309  * and a new one passed in. Observe minimums and maximums, and reset
9310  * other state variables that we want to view as multiples of mss.
9311  *
9312  * This function is called in various places mainly because
9313  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
9314  *    other side's SYN/SYN-ACK packet arrives.
9315  * 2) PMTUd may get us a new MSS.
9316  * 3) If the other side stops sending us timestamp option, we need to
9317  *    increase the MSS size to use the extra bytes available.
9318  */
9319 static void
9320 tcp_mss_set(tcp_t *tcp, uint32_t mss)
9321 {
9322 	uint32_t	mss_max;
9323 
9324 	if (tcp->tcp_ipversion == IPV4_VERSION)
9325 		mss_max = tcp_mss_max_ipv4;
9326 	else
9327 		mss_max = tcp_mss_max_ipv6;
9328 
9329 	if (mss < tcp_mss_min)
9330 		mss = tcp_mss_min;
9331 	if (mss > mss_max)
9332 		mss = mss_max;
9333 	/*
9334 	 * Unless naglim has been set by our client to
9335 	 * a non-mss value, force naglim to track mss.
9336 	 * This can help to aggregate small writes.
9337 	 */
9338 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9339 		tcp->tcp_naglim = mss;
9340 	/*
9341 	 * TCP should be able to buffer at least 4 MSS data for obvious
9342 	 * performance reason.
9343 	 */
9344 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9345 		tcp->tcp_xmit_hiwater = mss << 2;
9346 
9347 	/*
9348 	 * Check if we need to apply the tcp_init_cwnd here.  If
9349 	 * it is set and the MSS gets bigger (should not happen
9350 	 * normally), we need to adjust the resulting tcp_cwnd properly.
9351 	 * The new tcp_cwnd should not get bigger.
9352 	 */
9353 	if (tcp->tcp_init_cwnd == 0) {
9354 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
9355 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
9356 	} else {
9357 		if (tcp->tcp_mss < mss) {
9358 			tcp->tcp_cwnd = MAX(1,
9359 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
9360 		} else {
9361 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
9362 		}
9363 	}
9364 	tcp->tcp_mss = mss;
9365 	tcp->tcp_cwnd_cnt = 0;
9366 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9367 }
9368 
9369 static int
9370 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9371 {
9372 	tcp_t		*tcp = NULL;
9373 	conn_t		*connp;
9374 	int		err;
9375 	dev_t		conn_dev;
9376 	zoneid_t	zoneid = getzoneid();
9377 
9378 	/*
9379 	 * Special case for install: miniroot needs to be able to access files
9380 	 * via NFS as though it were always in the global zone.
9381 	 */
9382 	if (credp == kcred && nfs_global_client_only != 0)
9383 		zoneid = GLOBAL_ZONEID;
9384 
9385 	if (q->q_ptr != NULL)
9386 		return (0);
9387 
9388 	if (sflag == MODOPEN) {
9389 		/*
9390 		 * This is a special case. The purpose of a modopen
9391 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
9392 		 * through for MIB browsers. Everything else is failed.
9393 		 */
9394 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9395 
9396 		if (connp == NULL)
9397 			return (ENOMEM);
9398 
9399 		connp->conn_flags |= IPCL_TCPMOD;
9400 		connp->conn_cred = credp;
9401 		connp->conn_zoneid = zoneid;
9402 		q->q_ptr = WR(q)->q_ptr = connp;
9403 		crhold(credp);
9404 		q->q_qinfo = &tcp_mod_rinit;
9405 		WR(q)->q_qinfo = &tcp_mod_winit;
9406 		qprocson(q);
9407 		return (0);
9408 	}
9409 
9410 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
9411 		return (EBUSY);
9412 
9413 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9414 
9415 	if (flag & SO_ACCEPTOR) {
9416 		q->q_qinfo = &tcp_acceptor_rinit;
9417 		q->q_ptr = (void *)conn_dev;
9418 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9419 		WR(q)->q_ptr = (void *)conn_dev;
9420 		qprocson(q);
9421 		return (0);
9422 	}
9423 
9424 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9425 	if (connp == NULL) {
9426 		inet_minor_free(ip_minor_arena, conn_dev);
9427 		q->q_ptr = NULL;
9428 		return (ENOSR);
9429 	}
9430 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9431 	tcp = connp->conn_tcp;
9432 
9433 	q->q_ptr = WR(q)->q_ptr = connp;
9434 	if (getmajor(*devp) == TCP6_MAJ) {
9435 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9436 		connp->conn_send = ip_output_v6;
9437 		connp->conn_af_isv6 = B_TRUE;
9438 		connp->conn_pkt_isv6 = B_TRUE;
9439 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9440 		tcp->tcp_ipversion = IPV6_VERSION;
9441 		tcp->tcp_family = AF_INET6;
9442 		tcp->tcp_mss = tcp_mss_def_ipv6;
9443 	} else {
9444 		connp->conn_flags |= IPCL_TCP4;
9445 		connp->conn_send = ip_output;
9446 		connp->conn_af_isv6 = B_FALSE;
9447 		connp->conn_pkt_isv6 = B_FALSE;
9448 		tcp->tcp_ipversion = IPV4_VERSION;
9449 		tcp->tcp_family = AF_INET;
9450 		tcp->tcp_mss = tcp_mss_def_ipv4;
9451 	}
9452 
9453 	/*
9454 	 * TCP keeps a copy of cred for cache locality reasons but
9455 	 * we put a reference only once. If connp->conn_cred
9456 	 * becomes invalid, tcp_cred should also be set to NULL.
9457 	 */
9458 	tcp->tcp_cred = connp->conn_cred = credp;
9459 	crhold(connp->conn_cred);
9460 	tcp->tcp_cpid = curproc->p_pid;
9461 	connp->conn_zoneid = zoneid;
9462 	connp->conn_mlp_type = mlptSingle;
9463 	connp->conn_ulp_labeled = !is_system_labeled();
9464 
9465 	/*
9466 	 * If the caller has the process-wide flag set, then default to MAC
9467 	 * exempt mode.  This allows read-down to unlabeled hosts.
9468 	 */
9469 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9470 		connp->conn_mac_exempt = B_TRUE;
9471 
9472 	connp->conn_dev = conn_dev;
9473 
9474 	ASSERT(q->q_qinfo == &tcp_rinit);
9475 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9476 
9477 	if (flag & SO_SOCKSTR) {
9478 		/*
9479 		 * No need to insert a socket in tcp acceptor hash.
9480 		 * If it was a socket acceptor stream, we dealt with
9481 		 * it above. A socket listener can never accept a
9482 		 * connection and doesn't need acceptor_id.
9483 		 */
9484 		connp->conn_flags |= IPCL_SOCKET;
9485 		tcp->tcp_issocket = 1;
9486 		WR(q)->q_qinfo = &tcp_sock_winit;
9487 	} else {
9488 #ifdef	_ILP32
9489 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9490 #else
9491 		tcp->tcp_acceptor_id = conn_dev;
9492 #endif	/* _ILP32 */
9493 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9494 	}
9495 
9496 	if (tcp_trace)
9497 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9498 
9499 	err = tcp_init(tcp, q);
9500 	if (err != 0) {
9501 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9502 		tcp_acceptor_hash_remove(tcp);
9503 		CONN_DEC_REF(connp);
9504 		q->q_ptr = WR(q)->q_ptr = NULL;
9505 		return (err);
9506 	}
9507 
9508 	RD(q)->q_hiwat = tcp_recv_hiwat;
9509 	tcp->tcp_rwnd = tcp_recv_hiwat;
9510 
9511 	/* Non-zero default values */
9512 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9513 	/*
9514 	 * Put the ref for TCP. Ref for IP was already put
9515 	 * by ipcl_conn_create. Also Make the conn_t globally
9516 	 * visible to walkers
9517 	 */
9518 	mutex_enter(&connp->conn_lock);
9519 	CONN_INC_REF_LOCKED(connp);
9520 	ASSERT(connp->conn_ref == 2);
9521 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9522 	mutex_exit(&connp->conn_lock);
9523 
9524 	qprocson(q);
9525 	return (0);
9526 }
9527 
9528 /*
9529  * Some TCP options can be "set" by requesting them in the option
9530  * buffer. This is needed for XTI feature test though we do not
9531  * allow it in general. We interpret that this mechanism is more
9532  * applicable to OSI protocols and need not be allowed in general.
9533  * This routine filters out options for which it is not allowed (most)
9534  * and lets through those (few) for which it is. [ The XTI interface
9535  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9536  * ever implemented will have to be allowed here ].
9537  */
9538 static boolean_t
9539 tcp_allow_connopt_set(int level, int name)
9540 {
9541 
9542 	switch (level) {
9543 	case IPPROTO_TCP:
9544 		switch (name) {
9545 		case TCP_NODELAY:
9546 			return (B_TRUE);
9547 		default:
9548 			return (B_FALSE);
9549 		}
9550 		/*NOTREACHED*/
9551 	default:
9552 		return (B_FALSE);
9553 	}
9554 	/*NOTREACHED*/
9555 }
9556 
9557 /*
9558  * This routine gets default values of certain options whose default
9559  * values are maintained by protocol specific code
9560  */
9561 /* ARGSUSED */
9562 int
9563 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9564 {
9565 	int32_t	*i1 = (int32_t *)ptr;
9566 
9567 	switch (level) {
9568 	case IPPROTO_TCP:
9569 		switch (name) {
9570 		case TCP_NOTIFY_THRESHOLD:
9571 			*i1 = tcp_ip_notify_interval;
9572 			break;
9573 		case TCP_ABORT_THRESHOLD:
9574 			*i1 = tcp_ip_abort_interval;
9575 			break;
9576 		case TCP_CONN_NOTIFY_THRESHOLD:
9577 			*i1 = tcp_ip_notify_cinterval;
9578 			break;
9579 		case TCP_CONN_ABORT_THRESHOLD:
9580 			*i1 = tcp_ip_abort_cinterval;
9581 			break;
9582 		default:
9583 			return (-1);
9584 		}
9585 		break;
9586 	case IPPROTO_IP:
9587 		switch (name) {
9588 		case IP_TTL:
9589 			*i1 = tcp_ipv4_ttl;
9590 			break;
9591 		default:
9592 			return (-1);
9593 		}
9594 		break;
9595 	case IPPROTO_IPV6:
9596 		switch (name) {
9597 		case IPV6_UNICAST_HOPS:
9598 			*i1 = tcp_ipv6_hoplimit;
9599 			break;
9600 		default:
9601 			return (-1);
9602 		}
9603 		break;
9604 	default:
9605 		return (-1);
9606 	}
9607 	return (sizeof (int));
9608 }
9609 
9610 
9611 /*
9612  * TCP routine to get the values of options.
9613  */
9614 int
9615 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9616 {
9617 	int		*i1 = (int *)ptr;
9618 	conn_t		*connp = Q_TO_CONN(q);
9619 	tcp_t		*tcp = connp->conn_tcp;
9620 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9621 
9622 	switch (level) {
9623 	case SOL_SOCKET:
9624 		switch (name) {
9625 		case SO_LINGER:	{
9626 			struct linger *lgr = (struct linger *)ptr;
9627 
9628 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9629 			lgr->l_linger = tcp->tcp_lingertime;
9630 			}
9631 			return (sizeof (struct linger));
9632 		case SO_DEBUG:
9633 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9634 			break;
9635 		case SO_KEEPALIVE:
9636 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9637 			break;
9638 		case SO_DONTROUTE:
9639 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9640 			break;
9641 		case SO_USELOOPBACK:
9642 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9643 			break;
9644 		case SO_BROADCAST:
9645 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9646 			break;
9647 		case SO_REUSEADDR:
9648 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9649 			break;
9650 		case SO_OOBINLINE:
9651 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9652 			break;
9653 		case SO_DGRAM_ERRIND:
9654 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9655 			break;
9656 		case SO_TYPE:
9657 			*i1 = SOCK_STREAM;
9658 			break;
9659 		case SO_SNDBUF:
9660 			*i1 = tcp->tcp_xmit_hiwater;
9661 			break;
9662 		case SO_RCVBUF:
9663 			*i1 = RD(q)->q_hiwat;
9664 			break;
9665 		case SO_SND_COPYAVOID:
9666 			*i1 = tcp->tcp_snd_zcopy_on ?
9667 			    SO_SND_COPYAVOID : 0;
9668 			break;
9669 		case SO_ALLZONES:
9670 			*i1 = connp->conn_allzones ? 1 : 0;
9671 			break;
9672 		case SO_ANON_MLP:
9673 			*i1 = connp->conn_anon_mlp;
9674 			break;
9675 		case SO_MAC_EXEMPT:
9676 			*i1 = connp->conn_mac_exempt;
9677 			break;
9678 		case SO_EXCLBIND:
9679 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9680 			break;
9681 		default:
9682 			return (-1);
9683 		}
9684 		break;
9685 	case IPPROTO_TCP:
9686 		switch (name) {
9687 		case TCP_NODELAY:
9688 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9689 			break;
9690 		case TCP_MAXSEG:
9691 			*i1 = tcp->tcp_mss;
9692 			break;
9693 		case TCP_NOTIFY_THRESHOLD:
9694 			*i1 = (int)tcp->tcp_first_timer_threshold;
9695 			break;
9696 		case TCP_ABORT_THRESHOLD:
9697 			*i1 = tcp->tcp_second_timer_threshold;
9698 			break;
9699 		case TCP_CONN_NOTIFY_THRESHOLD:
9700 			*i1 = tcp->tcp_first_ctimer_threshold;
9701 			break;
9702 		case TCP_CONN_ABORT_THRESHOLD:
9703 			*i1 = tcp->tcp_second_ctimer_threshold;
9704 			break;
9705 		case TCP_RECVDSTADDR:
9706 			*i1 = tcp->tcp_recvdstaddr;
9707 			break;
9708 		case TCP_ANONPRIVBIND:
9709 			*i1 = tcp->tcp_anon_priv_bind;
9710 			break;
9711 		case TCP_EXCLBIND:
9712 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9713 			break;
9714 		case TCP_INIT_CWND:
9715 			*i1 = tcp->tcp_init_cwnd;
9716 			break;
9717 		case TCP_KEEPALIVE_THRESHOLD:
9718 			*i1 = tcp->tcp_ka_interval;
9719 			break;
9720 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9721 			*i1 = tcp->tcp_ka_abort_thres;
9722 			break;
9723 		case TCP_CORK:
9724 			*i1 = tcp->tcp_cork;
9725 			break;
9726 		default:
9727 			return (-1);
9728 		}
9729 		break;
9730 	case IPPROTO_IP:
9731 		if (tcp->tcp_family != AF_INET)
9732 			return (-1);
9733 		switch (name) {
9734 		case IP_OPTIONS:
9735 		case T_IP_OPTIONS: {
9736 			/*
9737 			 * This is compatible with BSD in that in only return
9738 			 * the reverse source route with the final destination
9739 			 * as the last entry. The first 4 bytes of the option
9740 			 * will contain the final destination.
9741 			 */
9742 			int	opt_len;
9743 
9744 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9745 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9746 			ASSERT(opt_len >= 0);
9747 			/* Caller ensures enough space */
9748 			if (opt_len > 0) {
9749 				/*
9750 				 * TODO: Do we have to handle getsockopt on an
9751 				 * initiator as well?
9752 				 */
9753 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9754 			}
9755 			return (0);
9756 			}
9757 		case IP_TOS:
9758 		case T_IP_TOS:
9759 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9760 			break;
9761 		case IP_TTL:
9762 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9763 			break;
9764 		case IP_NEXTHOP:
9765 			/* Handled at IP level */
9766 			return (-EINVAL);
9767 		default:
9768 			return (-1);
9769 		}
9770 		break;
9771 	case IPPROTO_IPV6:
9772 		/*
9773 		 * IPPROTO_IPV6 options are only supported for sockets
9774 		 * that are using IPv6 on the wire.
9775 		 */
9776 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9777 			return (-1);
9778 		}
9779 		switch (name) {
9780 		case IPV6_UNICAST_HOPS:
9781 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9782 			break;	/* goto sizeof (int) option return */
9783 		case IPV6_BOUND_IF:
9784 			/* Zero if not set */
9785 			*i1 = tcp->tcp_bound_if;
9786 			break;	/* goto sizeof (int) option return */
9787 		case IPV6_RECVPKTINFO:
9788 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9789 				*i1 = 1;
9790 			else
9791 				*i1 = 0;
9792 			break;	/* goto sizeof (int) option return */
9793 		case IPV6_RECVTCLASS:
9794 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9795 				*i1 = 1;
9796 			else
9797 				*i1 = 0;
9798 			break;	/* goto sizeof (int) option return */
9799 		case IPV6_RECVHOPLIMIT:
9800 			if (tcp->tcp_ipv6_recvancillary &
9801 			    TCP_IPV6_RECVHOPLIMIT)
9802 				*i1 = 1;
9803 			else
9804 				*i1 = 0;
9805 			break;	/* goto sizeof (int) option return */
9806 		case IPV6_RECVHOPOPTS:
9807 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9808 				*i1 = 1;
9809 			else
9810 				*i1 = 0;
9811 			break;	/* goto sizeof (int) option return */
9812 		case IPV6_RECVDSTOPTS:
9813 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9814 				*i1 = 1;
9815 			else
9816 				*i1 = 0;
9817 			break;	/* goto sizeof (int) option return */
9818 		case _OLD_IPV6_RECVDSTOPTS:
9819 			if (tcp->tcp_ipv6_recvancillary &
9820 			    TCP_OLD_IPV6_RECVDSTOPTS)
9821 				*i1 = 1;
9822 			else
9823 				*i1 = 0;
9824 			break;	/* goto sizeof (int) option return */
9825 		case IPV6_RECVRTHDR:
9826 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9827 				*i1 = 1;
9828 			else
9829 				*i1 = 0;
9830 			break;	/* goto sizeof (int) option return */
9831 		case IPV6_RECVRTHDRDSTOPTS:
9832 			if (tcp->tcp_ipv6_recvancillary &
9833 			    TCP_IPV6_RECVRTDSTOPTS)
9834 				*i1 = 1;
9835 			else
9836 				*i1 = 0;
9837 			break;	/* goto sizeof (int) option return */
9838 		case IPV6_PKTINFO: {
9839 			/* XXX assumes that caller has room for max size! */
9840 			struct in6_pktinfo *pkti;
9841 
9842 			pkti = (struct in6_pktinfo *)ptr;
9843 			if (ipp->ipp_fields & IPPF_IFINDEX)
9844 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9845 			else
9846 				pkti->ipi6_ifindex = 0;
9847 			if (ipp->ipp_fields & IPPF_ADDR)
9848 				pkti->ipi6_addr = ipp->ipp_addr;
9849 			else
9850 				pkti->ipi6_addr = ipv6_all_zeros;
9851 			return (sizeof (struct in6_pktinfo));
9852 		}
9853 		case IPV6_TCLASS:
9854 			if (ipp->ipp_fields & IPPF_TCLASS)
9855 				*i1 = ipp->ipp_tclass;
9856 			else
9857 				*i1 = IPV6_FLOW_TCLASS(
9858 				    IPV6_DEFAULT_VERS_AND_FLOW);
9859 			break;	/* goto sizeof (int) option return */
9860 		case IPV6_NEXTHOP: {
9861 			sin6_t *sin6 = (sin6_t *)ptr;
9862 
9863 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9864 				return (0);
9865 			*sin6 = sin6_null;
9866 			sin6->sin6_family = AF_INET6;
9867 			sin6->sin6_addr = ipp->ipp_nexthop;
9868 			return (sizeof (sin6_t));
9869 		}
9870 		case IPV6_HOPOPTS:
9871 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9872 				return (0);
9873 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9874 				return (0);
9875 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9876 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9877 			if (tcp->tcp_label_len > 0) {
9878 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9879 				ptr[1] = (ipp->ipp_hopoptslen -
9880 				    tcp->tcp_label_len + 7) / 8 - 1;
9881 			}
9882 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9883 		case IPV6_RTHDRDSTOPTS:
9884 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9885 				return (0);
9886 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9887 			return (ipp->ipp_rtdstoptslen);
9888 		case IPV6_RTHDR:
9889 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9890 				return (0);
9891 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9892 			return (ipp->ipp_rthdrlen);
9893 		case IPV6_DSTOPTS:
9894 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9895 				return (0);
9896 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9897 			return (ipp->ipp_dstoptslen);
9898 		case IPV6_SRC_PREFERENCES:
9899 			return (ip6_get_src_preferences(connp,
9900 			    (uint32_t *)ptr));
9901 		case IPV6_PATHMTU: {
9902 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9903 
9904 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9905 				return (-1);
9906 
9907 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9908 				connp->conn_fport, mtuinfo));
9909 		}
9910 		default:
9911 			return (-1);
9912 		}
9913 		break;
9914 	default:
9915 		return (-1);
9916 	}
9917 	return (sizeof (int));
9918 }
9919 
9920 /*
9921  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9922  * Parameters are assumed to be verified by the caller.
9923  */
9924 /* ARGSUSED */
9925 int
9926 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9927     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9928     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9929 {
9930 	conn_t	*connp = Q_TO_CONN(q);
9931 	tcp_t	*tcp = connp->conn_tcp;
9932 	int	*i1 = (int *)invalp;
9933 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9934 	boolean_t checkonly;
9935 	int	reterr;
9936 
9937 	switch (optset_context) {
9938 	case SETFN_OPTCOM_CHECKONLY:
9939 		checkonly = B_TRUE;
9940 		/*
9941 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9942 		 * inlen != 0 implies value supplied and
9943 		 * 	we have to "pretend" to set it.
9944 		 * inlen == 0 implies that there is no
9945 		 * 	value part in T_CHECK request and just validation
9946 		 * done elsewhere should be enough, we just return here.
9947 		 */
9948 		if (inlen == 0) {
9949 			*outlenp = 0;
9950 			return (0);
9951 		}
9952 		break;
9953 	case SETFN_OPTCOM_NEGOTIATE:
9954 		checkonly = B_FALSE;
9955 		break;
9956 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9957 	case SETFN_CONN_NEGOTIATE:
9958 		checkonly = B_FALSE;
9959 		/*
9960 		 * Negotiating local and "association-related" options
9961 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9962 		 * primitives is allowed by XTI, but we choose
9963 		 * to not implement this style negotiation for Internet
9964 		 * protocols (We interpret it is a must for OSI world but
9965 		 * optional for Internet protocols) for all options.
9966 		 * [ Will do only for the few options that enable test
9967 		 * suites that our XTI implementation of this feature
9968 		 * works for transports that do allow it ]
9969 		 */
9970 		if (!tcp_allow_connopt_set(level, name)) {
9971 			*outlenp = 0;
9972 			return (EINVAL);
9973 		}
9974 		break;
9975 	default:
9976 		/*
9977 		 * We should never get here
9978 		 */
9979 		*outlenp = 0;
9980 		return (EINVAL);
9981 	}
9982 
9983 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9984 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9985 
9986 	/*
9987 	 * For TCP, we should have no ancillary data sent down
9988 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9989 	 * has to be zero.
9990 	 */
9991 	ASSERT(thisdg_attrs == NULL);
9992 
9993 	/*
9994 	 * For fixed length options, no sanity check
9995 	 * of passed in length is done. It is assumed *_optcom_req()
9996 	 * routines do the right thing.
9997 	 */
9998 
9999 	switch (level) {
10000 	case SOL_SOCKET:
10001 		switch (name) {
10002 		case SO_LINGER: {
10003 			struct linger *lgr = (struct linger *)invalp;
10004 
10005 			if (!checkonly) {
10006 				if (lgr->l_onoff) {
10007 					tcp->tcp_linger = 1;
10008 					tcp->tcp_lingertime = lgr->l_linger;
10009 				} else {
10010 					tcp->tcp_linger = 0;
10011 					tcp->tcp_lingertime = 0;
10012 				}
10013 				/* struct copy */
10014 				*(struct linger *)outvalp = *lgr;
10015 			} else {
10016 				if (!lgr->l_onoff) {
10017 				    ((struct linger *)outvalp)->l_onoff = 0;
10018 				    ((struct linger *)outvalp)->l_linger = 0;
10019 				} else {
10020 				    /* struct copy */
10021 				    *(struct linger *)outvalp = *lgr;
10022 				}
10023 			}
10024 			*outlenp = sizeof (struct linger);
10025 			return (0);
10026 		}
10027 		case SO_DEBUG:
10028 			if (!checkonly)
10029 				tcp->tcp_debug = onoff;
10030 			break;
10031 		case SO_KEEPALIVE:
10032 			if (checkonly) {
10033 				/* T_CHECK case */
10034 				break;
10035 			}
10036 
10037 			if (!onoff) {
10038 				if (tcp->tcp_ka_enabled) {
10039 					if (tcp->tcp_ka_tid != 0) {
10040 						(void) TCP_TIMER_CANCEL(tcp,
10041 						    tcp->tcp_ka_tid);
10042 						tcp->tcp_ka_tid = 0;
10043 					}
10044 					tcp->tcp_ka_enabled = 0;
10045 				}
10046 				break;
10047 			}
10048 			if (!tcp->tcp_ka_enabled) {
10049 				/* Crank up the keepalive timer */
10050 				tcp->tcp_ka_last_intrvl = 0;
10051 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10052 				    tcp_keepalive_killer,
10053 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10054 				tcp->tcp_ka_enabled = 1;
10055 			}
10056 			break;
10057 		case SO_DONTROUTE:
10058 			/*
10059 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10060 			 * only of interest to IP.  We track them here only so
10061 			 * that we can report their current value.
10062 			 */
10063 			if (!checkonly) {
10064 				tcp->tcp_dontroute = onoff;
10065 				tcp->tcp_connp->conn_dontroute = onoff;
10066 			}
10067 			break;
10068 		case SO_USELOOPBACK:
10069 			if (!checkonly) {
10070 				tcp->tcp_useloopback = onoff;
10071 				tcp->tcp_connp->conn_loopback = onoff;
10072 			}
10073 			break;
10074 		case SO_BROADCAST:
10075 			if (!checkonly) {
10076 				tcp->tcp_broadcast = onoff;
10077 				tcp->tcp_connp->conn_broadcast = onoff;
10078 			}
10079 			break;
10080 		case SO_REUSEADDR:
10081 			if (!checkonly) {
10082 				tcp->tcp_reuseaddr = onoff;
10083 				tcp->tcp_connp->conn_reuseaddr = onoff;
10084 			}
10085 			break;
10086 		case SO_OOBINLINE:
10087 			if (!checkonly)
10088 				tcp->tcp_oobinline = onoff;
10089 			break;
10090 		case SO_DGRAM_ERRIND:
10091 			if (!checkonly)
10092 				tcp->tcp_dgram_errind = onoff;
10093 			break;
10094 		case SO_SNDBUF: {
10095 			tcp_t *peer_tcp;
10096 
10097 			if (*i1 > tcp_max_buf) {
10098 				*outlenp = 0;
10099 				return (ENOBUFS);
10100 			}
10101 			if (checkonly)
10102 				break;
10103 
10104 			tcp->tcp_xmit_hiwater = *i1;
10105 			if (tcp_snd_lowat_fraction != 0)
10106 				tcp->tcp_xmit_lowater =
10107 				    tcp->tcp_xmit_hiwater /
10108 				    tcp_snd_lowat_fraction;
10109 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10110 			/*
10111 			 * If we are flow-controlled, recheck the condition.
10112 			 * There are apps that increase SO_SNDBUF size when
10113 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10114 			 * control condition to be lifted right away.
10115 			 *
10116 			 * For the fused tcp loopback case, in order to avoid
10117 			 * a race with the peer's tcp_fuse_rrw() we need to
10118 			 * hold its fuse_lock while accessing tcp_flow_stopped.
10119 			 */
10120 			peer_tcp = tcp->tcp_loopback_peer;
10121 			ASSERT(!tcp->tcp_fused || peer_tcp != NULL);
10122 			if (tcp->tcp_fused)
10123 				mutex_enter(&peer_tcp->tcp_fuse_lock);
10124 
10125 			if (tcp->tcp_flow_stopped &&
10126 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10127 				tcp_clrqfull(tcp);
10128 			}
10129 			if (tcp->tcp_fused)
10130 				mutex_exit(&peer_tcp->tcp_fuse_lock);
10131 			break;
10132 		}
10133 		case SO_RCVBUF:
10134 			if (*i1 > tcp_max_buf) {
10135 				*outlenp = 0;
10136 				return (ENOBUFS);
10137 			}
10138 			/* Silently ignore zero */
10139 			if (!checkonly && *i1 != 0) {
10140 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10141 				(void) tcp_rwnd_set(tcp, *i1);
10142 			}
10143 			/*
10144 			 * XXX should we return the rwnd here
10145 			 * and tcp_opt_get ?
10146 			 */
10147 			break;
10148 		case SO_SND_COPYAVOID:
10149 			if (!checkonly) {
10150 				/* we only allow enable at most once for now */
10151 				if (tcp->tcp_loopback ||
10152 				    (!tcp->tcp_snd_zcopy_aware &&
10153 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10154 					*outlenp = 0;
10155 					return (EOPNOTSUPP);
10156 				}
10157 				tcp->tcp_snd_zcopy_aware = 1;
10158 			}
10159 			break;
10160 		case SO_ALLZONES:
10161 			/* Handled at the IP level */
10162 			return (-EINVAL);
10163 		case SO_ANON_MLP:
10164 			if (!checkonly) {
10165 				mutex_enter(&connp->conn_lock);
10166 				connp->conn_anon_mlp = onoff;
10167 				mutex_exit(&connp->conn_lock);
10168 			}
10169 			break;
10170 		case SO_MAC_EXEMPT:
10171 			if (secpolicy_net_mac_aware(cr) != 0 ||
10172 			    IPCL_IS_BOUND(connp))
10173 				return (EACCES);
10174 			if (!checkonly) {
10175 				mutex_enter(&connp->conn_lock);
10176 				connp->conn_mac_exempt = onoff;
10177 				mutex_exit(&connp->conn_lock);
10178 			}
10179 			break;
10180 		case SO_EXCLBIND:
10181 			if (!checkonly)
10182 				tcp->tcp_exclbind = onoff;
10183 			break;
10184 		default:
10185 			*outlenp = 0;
10186 			return (EINVAL);
10187 		}
10188 		break;
10189 	case IPPROTO_TCP:
10190 		switch (name) {
10191 		case TCP_NODELAY:
10192 			if (!checkonly)
10193 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10194 			break;
10195 		case TCP_NOTIFY_THRESHOLD:
10196 			if (!checkonly)
10197 				tcp->tcp_first_timer_threshold = *i1;
10198 			break;
10199 		case TCP_ABORT_THRESHOLD:
10200 			if (!checkonly)
10201 				tcp->tcp_second_timer_threshold = *i1;
10202 			break;
10203 		case TCP_CONN_NOTIFY_THRESHOLD:
10204 			if (!checkonly)
10205 				tcp->tcp_first_ctimer_threshold = *i1;
10206 			break;
10207 		case TCP_CONN_ABORT_THRESHOLD:
10208 			if (!checkonly)
10209 				tcp->tcp_second_ctimer_threshold = *i1;
10210 			break;
10211 		case TCP_RECVDSTADDR:
10212 			if (tcp->tcp_state > TCPS_LISTEN)
10213 				return (EOPNOTSUPP);
10214 			if (!checkonly)
10215 				tcp->tcp_recvdstaddr = onoff;
10216 			break;
10217 		case TCP_ANONPRIVBIND:
10218 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
10219 				*outlenp = 0;
10220 				return (reterr);
10221 			}
10222 			if (!checkonly) {
10223 				tcp->tcp_anon_priv_bind = onoff;
10224 			}
10225 			break;
10226 		case TCP_EXCLBIND:
10227 			if (!checkonly)
10228 				tcp->tcp_exclbind = onoff;
10229 			break;	/* goto sizeof (int) option return */
10230 		case TCP_INIT_CWND: {
10231 			uint32_t init_cwnd = *((uint32_t *)invalp);
10232 
10233 			if (checkonly)
10234 				break;
10235 
10236 			/*
10237 			 * Only allow socket with network configuration
10238 			 * privilege to set the initial cwnd to be larger
10239 			 * than allowed by RFC 3390.
10240 			 */
10241 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10242 				tcp->tcp_init_cwnd = init_cwnd;
10243 				break;
10244 			}
10245 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
10246 				*outlenp = 0;
10247 				return (reterr);
10248 			}
10249 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10250 				*outlenp = 0;
10251 				return (EINVAL);
10252 			}
10253 			tcp->tcp_init_cwnd = init_cwnd;
10254 			break;
10255 		}
10256 		case TCP_KEEPALIVE_THRESHOLD:
10257 			if (checkonly)
10258 				break;
10259 
10260 			if (*i1 < tcp_keepalive_interval_low ||
10261 			    *i1 > tcp_keepalive_interval_high) {
10262 				*outlenp = 0;
10263 				return (EINVAL);
10264 			}
10265 			if (*i1 != tcp->tcp_ka_interval) {
10266 				tcp->tcp_ka_interval = *i1;
10267 				/*
10268 				 * Check if we need to restart the
10269 				 * keepalive timer.
10270 				 */
10271 				if (tcp->tcp_ka_tid != 0) {
10272 					ASSERT(tcp->tcp_ka_enabled);
10273 					(void) TCP_TIMER_CANCEL(tcp,
10274 					    tcp->tcp_ka_tid);
10275 					tcp->tcp_ka_last_intrvl = 0;
10276 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10277 					    tcp_keepalive_killer,
10278 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10279 				}
10280 			}
10281 			break;
10282 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10283 			if (!checkonly) {
10284 				if (*i1 < tcp_keepalive_abort_interval_low ||
10285 				    *i1 > tcp_keepalive_abort_interval_high) {
10286 					*outlenp = 0;
10287 					return (EINVAL);
10288 				}
10289 				tcp->tcp_ka_abort_thres = *i1;
10290 			}
10291 			break;
10292 		case TCP_CORK:
10293 			if (!checkonly) {
10294 				/*
10295 				 * if tcp->tcp_cork was set and is now
10296 				 * being unset, we have to make sure that
10297 				 * the remaining data gets sent out. Also
10298 				 * unset tcp->tcp_cork so that tcp_wput_data()
10299 				 * can send data even if it is less than mss
10300 				 */
10301 				if (tcp->tcp_cork && onoff == 0 &&
10302 				    tcp->tcp_unsent > 0) {
10303 					tcp->tcp_cork = B_FALSE;
10304 					tcp_wput_data(tcp, NULL, B_FALSE);
10305 				}
10306 				tcp->tcp_cork = onoff;
10307 			}
10308 			break;
10309 		default:
10310 			*outlenp = 0;
10311 			return (EINVAL);
10312 		}
10313 		break;
10314 	case IPPROTO_IP:
10315 		if (tcp->tcp_family != AF_INET) {
10316 			*outlenp = 0;
10317 			return (ENOPROTOOPT);
10318 		}
10319 		switch (name) {
10320 		case IP_OPTIONS:
10321 		case T_IP_OPTIONS:
10322 			reterr = tcp_opt_set_header(tcp, checkonly,
10323 			    invalp, inlen);
10324 			if (reterr) {
10325 				*outlenp = 0;
10326 				return (reterr);
10327 			}
10328 			/* OK return - copy input buffer into output buffer */
10329 			if (invalp != outvalp) {
10330 				/* don't trust bcopy for identical src/dst */
10331 				bcopy(invalp, outvalp, inlen);
10332 			}
10333 			*outlenp = inlen;
10334 			return (0);
10335 		case IP_TOS:
10336 		case T_IP_TOS:
10337 			if (!checkonly) {
10338 				tcp->tcp_ipha->ipha_type_of_service =
10339 				    (uchar_t)*i1;
10340 				tcp->tcp_tos = (uchar_t)*i1;
10341 			}
10342 			break;
10343 		case IP_TTL:
10344 			if (!checkonly) {
10345 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10346 				tcp->tcp_ttl = (uchar_t)*i1;
10347 			}
10348 			break;
10349 		case IP_BOUND_IF:
10350 		case IP_NEXTHOP:
10351 			/* Handled at the IP level */
10352 			return (-EINVAL);
10353 		case IP_SEC_OPT:
10354 			/*
10355 			 * We should not allow policy setting after
10356 			 * we start listening for connections.
10357 			 */
10358 			if (tcp->tcp_state == TCPS_LISTEN) {
10359 				return (EINVAL);
10360 			} else {
10361 				/* Handled at the IP level */
10362 				return (-EINVAL);
10363 			}
10364 		default:
10365 			*outlenp = 0;
10366 			return (EINVAL);
10367 		}
10368 		break;
10369 	case IPPROTO_IPV6: {
10370 		ip6_pkt_t		*ipp;
10371 
10372 		/*
10373 		 * IPPROTO_IPV6 options are only supported for sockets
10374 		 * that are using IPv6 on the wire.
10375 		 */
10376 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10377 			*outlenp = 0;
10378 			return (ENOPROTOOPT);
10379 		}
10380 		/*
10381 		 * Only sticky options; no ancillary data
10382 		 */
10383 		ASSERT(thisdg_attrs == NULL);
10384 		ipp = &tcp->tcp_sticky_ipp;
10385 
10386 		switch (name) {
10387 		case IPV6_UNICAST_HOPS:
10388 			/* -1 means use default */
10389 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10390 				*outlenp = 0;
10391 				return (EINVAL);
10392 			}
10393 			if (!checkonly) {
10394 				if (*i1 == -1) {
10395 					tcp->tcp_ip6h->ip6_hops =
10396 					    ipp->ipp_unicast_hops =
10397 					    (uint8_t)tcp_ipv6_hoplimit;
10398 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10399 					/* Pass modified value to IP. */
10400 					*i1 = tcp->tcp_ip6h->ip6_hops;
10401 				} else {
10402 					tcp->tcp_ip6h->ip6_hops =
10403 					    ipp->ipp_unicast_hops =
10404 					    (uint8_t)*i1;
10405 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10406 				}
10407 				reterr = tcp_build_hdrs(q, tcp);
10408 				if (reterr != 0)
10409 					return (reterr);
10410 			}
10411 			break;
10412 		case IPV6_BOUND_IF:
10413 			if (!checkonly) {
10414 				int error = 0;
10415 
10416 				tcp->tcp_bound_if = *i1;
10417 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10418 				    B_TRUE, checkonly, level, name, mblk);
10419 				if (error != 0) {
10420 					*outlenp = 0;
10421 					return (error);
10422 				}
10423 			}
10424 			break;
10425 		/*
10426 		 * Set boolean switches for ancillary data delivery
10427 		 */
10428 		case IPV6_RECVPKTINFO:
10429 			if (!checkonly) {
10430 				if (onoff)
10431 					tcp->tcp_ipv6_recvancillary |=
10432 					    TCP_IPV6_RECVPKTINFO;
10433 				else
10434 					tcp->tcp_ipv6_recvancillary &=
10435 					    ~TCP_IPV6_RECVPKTINFO;
10436 				/* Force it to be sent up with the next msg */
10437 				tcp->tcp_recvifindex = 0;
10438 			}
10439 			break;
10440 		case IPV6_RECVTCLASS:
10441 			if (!checkonly) {
10442 				if (onoff)
10443 					tcp->tcp_ipv6_recvancillary |=
10444 					    TCP_IPV6_RECVTCLASS;
10445 				else
10446 					tcp->tcp_ipv6_recvancillary &=
10447 					    ~TCP_IPV6_RECVTCLASS;
10448 			}
10449 			break;
10450 		case IPV6_RECVHOPLIMIT:
10451 			if (!checkonly) {
10452 				if (onoff)
10453 					tcp->tcp_ipv6_recvancillary |=
10454 					    TCP_IPV6_RECVHOPLIMIT;
10455 				else
10456 					tcp->tcp_ipv6_recvancillary &=
10457 					    ~TCP_IPV6_RECVHOPLIMIT;
10458 				/* Force it to be sent up with the next msg */
10459 				tcp->tcp_recvhops = 0xffffffffU;
10460 			}
10461 			break;
10462 		case IPV6_RECVHOPOPTS:
10463 			if (!checkonly) {
10464 				if (onoff)
10465 					tcp->tcp_ipv6_recvancillary |=
10466 					    TCP_IPV6_RECVHOPOPTS;
10467 				else
10468 					tcp->tcp_ipv6_recvancillary &=
10469 					    ~TCP_IPV6_RECVHOPOPTS;
10470 			}
10471 			break;
10472 		case IPV6_RECVDSTOPTS:
10473 			if (!checkonly) {
10474 				if (onoff)
10475 					tcp->tcp_ipv6_recvancillary |=
10476 					    TCP_IPV6_RECVDSTOPTS;
10477 				else
10478 					tcp->tcp_ipv6_recvancillary &=
10479 					    ~TCP_IPV6_RECVDSTOPTS;
10480 			}
10481 			break;
10482 		case _OLD_IPV6_RECVDSTOPTS:
10483 			if (!checkonly) {
10484 				if (onoff)
10485 					tcp->tcp_ipv6_recvancillary |=
10486 					    TCP_OLD_IPV6_RECVDSTOPTS;
10487 				else
10488 					tcp->tcp_ipv6_recvancillary &=
10489 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10490 			}
10491 			break;
10492 		case IPV6_RECVRTHDR:
10493 			if (!checkonly) {
10494 				if (onoff)
10495 					tcp->tcp_ipv6_recvancillary |=
10496 					    TCP_IPV6_RECVRTHDR;
10497 				else
10498 					tcp->tcp_ipv6_recvancillary &=
10499 					    ~TCP_IPV6_RECVRTHDR;
10500 			}
10501 			break;
10502 		case IPV6_RECVRTHDRDSTOPTS:
10503 			if (!checkonly) {
10504 				if (onoff)
10505 					tcp->tcp_ipv6_recvancillary |=
10506 					    TCP_IPV6_RECVRTDSTOPTS;
10507 				else
10508 					tcp->tcp_ipv6_recvancillary &=
10509 					    ~TCP_IPV6_RECVRTDSTOPTS;
10510 			}
10511 			break;
10512 		case IPV6_PKTINFO:
10513 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10514 				return (EINVAL);
10515 			if (checkonly)
10516 				break;
10517 
10518 			if (inlen == 0) {
10519 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10520 			} else {
10521 				struct in6_pktinfo *pkti;
10522 
10523 				pkti = (struct in6_pktinfo *)invalp;
10524 				/*
10525 				 * RFC 3542 states that ipi6_addr must be
10526 				 * the unspecified address when setting the
10527 				 * IPV6_PKTINFO sticky socket option on a
10528 				 * TCP socket.
10529 				 */
10530 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10531 					return (EINVAL);
10532 				/*
10533 				 * ip6_set_pktinfo() validates the source
10534 				 * address and interface index.
10535 				 */
10536 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10537 				    pkti, mblk);
10538 				if (reterr != 0)
10539 					return (reterr);
10540 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10541 				ipp->ipp_addr = pkti->ipi6_addr;
10542 				if (ipp->ipp_ifindex != 0)
10543 					ipp->ipp_fields |= IPPF_IFINDEX;
10544 				else
10545 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10546 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10547 					ipp->ipp_fields |= IPPF_ADDR;
10548 				else
10549 					ipp->ipp_fields &= ~IPPF_ADDR;
10550 			}
10551 			reterr = tcp_build_hdrs(q, tcp);
10552 			if (reterr != 0)
10553 				return (reterr);
10554 			break;
10555 		case IPV6_TCLASS:
10556 			if (inlen != 0 && inlen != sizeof (int))
10557 				return (EINVAL);
10558 			if (checkonly)
10559 				break;
10560 
10561 			if (inlen == 0) {
10562 				ipp->ipp_fields &= ~IPPF_TCLASS;
10563 			} else {
10564 				if (*i1 > 255 || *i1 < -1)
10565 					return (EINVAL);
10566 				if (*i1 == -1) {
10567 					ipp->ipp_tclass = 0;
10568 					*i1 = 0;
10569 				} else {
10570 					ipp->ipp_tclass = *i1;
10571 				}
10572 				ipp->ipp_fields |= IPPF_TCLASS;
10573 			}
10574 			reterr = tcp_build_hdrs(q, tcp);
10575 			if (reterr != 0)
10576 				return (reterr);
10577 			break;
10578 		case IPV6_NEXTHOP:
10579 			/*
10580 			 * IP will verify that the nexthop is reachable
10581 			 * and fail for sticky options.
10582 			 */
10583 			if (inlen != 0 && inlen != sizeof (sin6_t))
10584 				return (EINVAL);
10585 			if (checkonly)
10586 				break;
10587 
10588 			if (inlen == 0) {
10589 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10590 			} else {
10591 				sin6_t *sin6 = (sin6_t *)invalp;
10592 
10593 				if (sin6->sin6_family != AF_INET6)
10594 					return (EAFNOSUPPORT);
10595 				if (IN6_IS_ADDR_V4MAPPED(
10596 				    &sin6->sin6_addr))
10597 					return (EADDRNOTAVAIL);
10598 				ipp->ipp_nexthop = sin6->sin6_addr;
10599 				if (!IN6_IS_ADDR_UNSPECIFIED(
10600 				    &ipp->ipp_nexthop))
10601 					ipp->ipp_fields |= IPPF_NEXTHOP;
10602 				else
10603 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10604 			}
10605 			reterr = tcp_build_hdrs(q, tcp);
10606 			if (reterr != 0)
10607 				return (reterr);
10608 			break;
10609 		case IPV6_HOPOPTS: {
10610 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10611 
10612 			/*
10613 			 * Sanity checks - minimum size, size a multiple of
10614 			 * eight bytes, and matching size passed in.
10615 			 */
10616 			if (inlen != 0 &&
10617 			    inlen != (8 * (hopts->ip6h_len + 1)))
10618 				return (EINVAL);
10619 
10620 			if (checkonly)
10621 				break;
10622 
10623 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10624 			    (uchar_t **)&ipp->ipp_hopopts,
10625 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10626 			if (reterr != 0)
10627 				return (reterr);
10628 			if (ipp->ipp_hopoptslen == 0)
10629 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10630 			else
10631 				ipp->ipp_fields |= IPPF_HOPOPTS;
10632 			reterr = tcp_build_hdrs(q, tcp);
10633 			if (reterr != 0)
10634 				return (reterr);
10635 			break;
10636 		}
10637 		case IPV6_RTHDRDSTOPTS: {
10638 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10639 
10640 			/*
10641 			 * Sanity checks - minimum size, size a multiple of
10642 			 * eight bytes, and matching size passed in.
10643 			 */
10644 			if (inlen != 0 &&
10645 			    inlen != (8 * (dopts->ip6d_len + 1)))
10646 				return (EINVAL);
10647 
10648 			if (checkonly)
10649 				break;
10650 
10651 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10652 			    (uchar_t **)&ipp->ipp_rtdstopts,
10653 			    &ipp->ipp_rtdstoptslen, 0);
10654 			if (reterr != 0)
10655 				return (reterr);
10656 			if (ipp->ipp_rtdstoptslen == 0)
10657 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10658 			else
10659 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10660 			reterr = tcp_build_hdrs(q, tcp);
10661 			if (reterr != 0)
10662 				return (reterr);
10663 			break;
10664 		}
10665 		case IPV6_DSTOPTS: {
10666 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10667 
10668 			/*
10669 			 * Sanity checks - minimum size, size a multiple of
10670 			 * eight bytes, and matching size passed in.
10671 			 */
10672 			if (inlen != 0 &&
10673 			    inlen != (8 * (dopts->ip6d_len + 1)))
10674 				return (EINVAL);
10675 
10676 			if (checkonly)
10677 				break;
10678 
10679 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10680 			    (uchar_t **)&ipp->ipp_dstopts,
10681 			    &ipp->ipp_dstoptslen, 0);
10682 			if (reterr != 0)
10683 				return (reterr);
10684 			if (ipp->ipp_dstoptslen == 0)
10685 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10686 			else
10687 				ipp->ipp_fields |= IPPF_DSTOPTS;
10688 			reterr = tcp_build_hdrs(q, tcp);
10689 			if (reterr != 0)
10690 				return (reterr);
10691 			break;
10692 		}
10693 		case IPV6_RTHDR: {
10694 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10695 
10696 			/*
10697 			 * Sanity checks - minimum size, size a multiple of
10698 			 * eight bytes, and matching size passed in.
10699 			 */
10700 			if (inlen != 0 &&
10701 			    inlen != (8 * (rt->ip6r_len + 1)))
10702 				return (EINVAL);
10703 
10704 			if (checkonly)
10705 				break;
10706 
10707 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10708 			    (uchar_t **)&ipp->ipp_rthdr,
10709 			    &ipp->ipp_rthdrlen, 0);
10710 			if (reterr != 0)
10711 				return (reterr);
10712 			if (ipp->ipp_rthdrlen == 0)
10713 				ipp->ipp_fields &= ~IPPF_RTHDR;
10714 			else
10715 				ipp->ipp_fields |= IPPF_RTHDR;
10716 			reterr = tcp_build_hdrs(q, tcp);
10717 			if (reterr != 0)
10718 				return (reterr);
10719 			break;
10720 		}
10721 		case IPV6_V6ONLY:
10722 			if (!checkonly)
10723 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10724 			break;
10725 		case IPV6_USE_MIN_MTU:
10726 			if (inlen != sizeof (int))
10727 				return (EINVAL);
10728 
10729 			if (*i1 < -1 || *i1 > 1)
10730 				return (EINVAL);
10731 
10732 			if (checkonly)
10733 				break;
10734 
10735 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10736 			ipp->ipp_use_min_mtu = *i1;
10737 			break;
10738 		case IPV6_BOUND_PIF:
10739 			/* Handled at the IP level */
10740 			return (-EINVAL);
10741 		case IPV6_SEC_OPT:
10742 			/*
10743 			 * We should not allow policy setting after
10744 			 * we start listening for connections.
10745 			 */
10746 			if (tcp->tcp_state == TCPS_LISTEN) {
10747 				return (EINVAL);
10748 			} else {
10749 				/* Handled at the IP level */
10750 				return (-EINVAL);
10751 			}
10752 		case IPV6_SRC_PREFERENCES:
10753 			if (inlen != sizeof (uint32_t))
10754 				return (EINVAL);
10755 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10756 			    *(uint32_t *)invalp);
10757 			if (reterr != 0) {
10758 				*outlenp = 0;
10759 				return (reterr);
10760 			}
10761 			break;
10762 		default:
10763 			*outlenp = 0;
10764 			return (EINVAL);
10765 		}
10766 		break;
10767 	}		/* end IPPROTO_IPV6 */
10768 	default:
10769 		*outlenp = 0;
10770 		return (EINVAL);
10771 	}
10772 	/*
10773 	 * Common case of OK return with outval same as inval
10774 	 */
10775 	if (invalp != outvalp) {
10776 		/* don't trust bcopy for identical src/dst */
10777 		(void) bcopy(invalp, outvalp, inlen);
10778 	}
10779 	*outlenp = inlen;
10780 	return (0);
10781 }
10782 
10783 /*
10784  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10785  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10786  * headers, and the maximum size tcp header (to avoid reallocation
10787  * on the fly for additional tcp options).
10788  * Returns failure if can't allocate memory.
10789  */
10790 static int
10791 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
10792 {
10793 	char	*hdrs;
10794 	uint_t	hdrs_len;
10795 	ip6i_t	*ip6i;
10796 	char	buf[TCP_MAX_HDR_LENGTH];
10797 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10798 	in6_addr_t src, dst;
10799 
10800 	/*
10801 	 * save the existing tcp header and source/dest IP addresses
10802 	 */
10803 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10804 	src = tcp->tcp_ip6h->ip6_src;
10805 	dst = tcp->tcp_ip6h->ip6_dst;
10806 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10807 	ASSERT(hdrs_len != 0);
10808 	if (hdrs_len > tcp->tcp_iphc_len) {
10809 		/* Need to reallocate */
10810 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10811 		if (hdrs == NULL)
10812 			return (ENOMEM);
10813 		if (tcp->tcp_iphc != NULL) {
10814 			if (tcp->tcp_hdr_grown) {
10815 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10816 			} else {
10817 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10818 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10819 			}
10820 			tcp->tcp_iphc_len = 0;
10821 		}
10822 		ASSERT(tcp->tcp_iphc_len == 0);
10823 		tcp->tcp_iphc = hdrs;
10824 		tcp->tcp_iphc_len = hdrs_len;
10825 		tcp->tcp_hdr_grown = B_TRUE;
10826 	}
10827 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10828 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10829 
10830 	/* Set header fields not in ipp */
10831 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10832 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10833 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10834 	} else {
10835 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10836 	}
10837 	/*
10838 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10839 	 *
10840 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10841 	 */
10842 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10843 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10844 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10845 
10846 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10847 
10848 	tcp->tcp_ip6h->ip6_src = src;
10849 	tcp->tcp_ip6h->ip6_dst = dst;
10850 
10851 	/*
10852 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10853 	 * the default value for TCP.
10854 	 */
10855 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10856 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
10857 
10858 	/*
10859 	 * If we're setting extension headers after a connection
10860 	 * has been established, and if we have a routing header
10861 	 * among the extension headers, call ip_massage_options_v6 to
10862 	 * manipulate the routing header/ip6_dst set the checksum
10863 	 * difference in the tcp header template.
10864 	 * (This happens in tcp_connect_ipv6 if the routing header
10865 	 * is set prior to the connect.)
10866 	 * Set the tcp_sum to zero first in case we've cleared a
10867 	 * routing header or don't have one at all.
10868 	 */
10869 	tcp->tcp_sum = 0;
10870 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10871 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10872 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10873 		    (uint8_t *)tcp->tcp_tcph);
10874 		if (rth != NULL) {
10875 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10876 			    rth);
10877 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10878 			    (tcp->tcp_sum >> 16));
10879 		}
10880 	}
10881 
10882 	/* Try to get everything in a single mblk */
10883 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
10884 	return (0);
10885 }
10886 
10887 /*
10888  * Transfer any source route option from ipha to buf/dst in reversed form.
10889  */
10890 static int
10891 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10892 {
10893 	ipoptp_t	opts;
10894 	uchar_t		*opt;
10895 	uint8_t		optval;
10896 	uint8_t		optlen;
10897 	uint32_t	len = 0;
10898 
10899 	for (optval = ipoptp_first(&opts, ipha);
10900 	    optval != IPOPT_EOL;
10901 	    optval = ipoptp_next(&opts)) {
10902 		opt = opts.ipoptp_cur;
10903 		optlen = opts.ipoptp_len;
10904 		switch (optval) {
10905 			int	off1, off2;
10906 		case IPOPT_SSRR:
10907 		case IPOPT_LSRR:
10908 
10909 			/* Reverse source route */
10910 			/*
10911 			 * First entry should be the next to last one in the
10912 			 * current source route (the last entry is our
10913 			 * address.)
10914 			 * The last entry should be the final destination.
10915 			 */
10916 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10917 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10918 			off1 = IPOPT_MINOFF_SR - 1;
10919 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10920 			if (off2 < 0) {
10921 				/* No entries in source route */
10922 				break;
10923 			}
10924 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10925 			/*
10926 			 * Note: use src since ipha has not had its src
10927 			 * and dst reversed (it is in the state it was
10928 			 * received.
10929 			 */
10930 			bcopy(&ipha->ipha_src, buf + off2,
10931 			    IP_ADDR_LEN);
10932 			off2 -= IP_ADDR_LEN;
10933 
10934 			while (off2 > 0) {
10935 				bcopy(opt + off2, buf + off1,
10936 				    IP_ADDR_LEN);
10937 				off1 += IP_ADDR_LEN;
10938 				off2 -= IP_ADDR_LEN;
10939 			}
10940 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10941 			buf += optlen;
10942 			len += optlen;
10943 			break;
10944 		}
10945 	}
10946 done:
10947 	/* Pad the resulting options */
10948 	while (len & 0x3) {
10949 		*buf++ = IPOPT_EOL;
10950 		len++;
10951 	}
10952 	return (len);
10953 }
10954 
10955 
10956 /*
10957  * Extract and revert a source route from ipha (if any)
10958  * and then update the relevant fields in both tcp_t and the standard header.
10959  */
10960 static void
10961 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
10962 {
10963 	char	buf[TCP_MAX_HDR_LENGTH];
10964 	uint_t	tcph_len;
10965 	int	len;
10966 
10967 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
10968 	len = IPH_HDR_LENGTH(ipha);
10969 	if (len == IP_SIMPLE_HDR_LENGTH)
10970 		/* Nothing to do */
10971 		return;
10972 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
10973 	    (len & 0x3))
10974 		return;
10975 
10976 	tcph_len = tcp->tcp_tcp_hdr_len;
10977 	bcopy(tcp->tcp_tcph, buf, tcph_len);
10978 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
10979 		(tcp->tcp_ipha->ipha_dst & 0xffff);
10980 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
10981 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
10982 	len += IP_SIMPLE_HDR_LENGTH;
10983 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
10984 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
10985 	if ((int)tcp->tcp_sum < 0)
10986 		tcp->tcp_sum--;
10987 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
10988 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
10989 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
10990 	bcopy(buf, tcp->tcp_tcph, tcph_len);
10991 	tcp->tcp_ip_hdr_len = len;
10992 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10993 	    (IP_VERSION << 4) | (len >> 2);
10994 	len += tcph_len;
10995 	tcp->tcp_hdr_len = len;
10996 }
10997 
10998 /*
10999  * Copy the standard header into its new location,
11000  * lay in the new options and then update the relevant
11001  * fields in both tcp_t and the standard header.
11002  */
11003 static int
11004 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11005 {
11006 	uint_t	tcph_len;
11007 	uint8_t	*ip_optp;
11008 	tcph_t	*new_tcph;
11009 
11010 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11011 		return (EINVAL);
11012 
11013 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11014 		return (EINVAL);
11015 
11016 	if (checkonly) {
11017 		/*
11018 		 * do not really set, just pretend to - T_CHECK
11019 		 */
11020 		return (0);
11021 	}
11022 
11023 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11024 	if (tcp->tcp_label_len > 0) {
11025 		int padlen;
11026 		uint8_t opt;
11027 
11028 		/* convert list termination to no-ops */
11029 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11030 		ip_optp += ip_optp[IPOPT_OLEN];
11031 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11032 		while (--padlen >= 0)
11033 			*ip_optp++ = opt;
11034 	}
11035 	tcph_len = tcp->tcp_tcp_hdr_len;
11036 	new_tcph = (tcph_t *)(ip_optp + len);
11037 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11038 	tcp->tcp_tcph = new_tcph;
11039 	bcopy(ptr, ip_optp, len);
11040 
11041 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11042 
11043 	tcp->tcp_ip_hdr_len = len;
11044 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11045 	    (IP_VERSION << 4) | (len >> 2);
11046 	tcp->tcp_hdr_len = len + tcph_len;
11047 	if (!TCP_IS_DETACHED(tcp)) {
11048 		/* Always allocate room for all options. */
11049 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11050 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
11051 	}
11052 	return (0);
11053 }
11054 
11055 /* Get callback routine passed to nd_load by tcp_param_register */
11056 /* ARGSUSED */
11057 static int
11058 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11059 {
11060 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11061 
11062 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11063 	return (0);
11064 }
11065 
11066 /*
11067  * Walk through the param array specified registering each element with the
11068  * named dispatch handler.
11069  */
11070 static boolean_t
11071 tcp_param_register(tcpparam_t *tcppa, int cnt)
11072 {
11073 	for (; cnt-- > 0; tcppa++) {
11074 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11075 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
11076 			    tcp_param_get, tcp_param_set,
11077 			    (caddr_t)tcppa)) {
11078 				nd_free(&tcp_g_nd);
11079 				return (B_FALSE);
11080 			}
11081 		}
11082 	}
11083 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
11084 	    tcp_param_get, tcp_param_set_aligned,
11085 	    (caddr_t)&tcp_wroff_xtra_param)) {
11086 		nd_free(&tcp_g_nd);
11087 		return (B_FALSE);
11088 	}
11089 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
11090 	    tcp_param_get, tcp_param_set_aligned,
11091 	    (caddr_t)&tcp_mdt_head_param)) {
11092 		nd_free(&tcp_g_nd);
11093 		return (B_FALSE);
11094 	}
11095 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
11096 	    tcp_param_get, tcp_param_set_aligned,
11097 	    (caddr_t)&tcp_mdt_tail_param)) {
11098 		nd_free(&tcp_g_nd);
11099 		return (B_FALSE);
11100 	}
11101 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
11102 	    tcp_param_get, tcp_param_set,
11103 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
11104 		nd_free(&tcp_g_nd);
11105 		return (B_FALSE);
11106 	}
11107 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
11108 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11109 		nd_free(&tcp_g_nd);
11110 		return (B_FALSE);
11111 	}
11112 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
11113 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11114 		nd_free(&tcp_g_nd);
11115 		return (B_FALSE);
11116 	}
11117 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
11118 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11119 		nd_free(&tcp_g_nd);
11120 		return (B_FALSE);
11121 	}
11122 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
11123 	    NULL)) {
11124 		nd_free(&tcp_g_nd);
11125 		return (B_FALSE);
11126 	}
11127 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
11128 	    NULL, NULL)) {
11129 		nd_free(&tcp_g_nd);
11130 		return (B_FALSE);
11131 	}
11132 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
11133 	    NULL, NULL)) {
11134 		nd_free(&tcp_g_nd);
11135 		return (B_FALSE);
11136 	}
11137 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
11138 	    NULL, NULL)) {
11139 		nd_free(&tcp_g_nd);
11140 		return (B_FALSE);
11141 	}
11142 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
11143 	    NULL, NULL)) {
11144 		nd_free(&tcp_g_nd);
11145 		return (B_FALSE);
11146 	}
11147 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
11148 	    tcp_host_param_set, NULL)) {
11149 		nd_free(&tcp_g_nd);
11150 		return (B_FALSE);
11151 	}
11152 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
11153 	    tcp_host_param_set_ipv6, NULL)) {
11154 		nd_free(&tcp_g_nd);
11155 		return (B_FALSE);
11156 	}
11157 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
11158 	    NULL)) {
11159 		nd_free(&tcp_g_nd);
11160 		return (B_FALSE);
11161 	}
11162 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
11163 	    tcp_reserved_port_list, NULL, NULL)) {
11164 		nd_free(&tcp_g_nd);
11165 		return (B_FALSE);
11166 	}
11167 	/*
11168 	 * Dummy ndd variables - only to convey obsolescence information
11169 	 * through printing of their name (no get or set routines)
11170 	 * XXX Remove in future releases ?
11171 	 */
11172 	if (!nd_load(&tcp_g_nd,
11173 	    "tcp_close_wait_interval(obsoleted - "
11174 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11175 		nd_free(&tcp_g_nd);
11176 		return (B_FALSE);
11177 	}
11178 	return (B_TRUE);
11179 }
11180 
11181 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11182 /* ARGSUSED */
11183 static int
11184 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11185     cred_t *cr)
11186 {
11187 	long new_value;
11188 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11189 
11190 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11191 	    new_value < tcppa->tcp_param_min ||
11192 	    new_value > tcppa->tcp_param_max) {
11193 		return (EINVAL);
11194 	}
11195 	/*
11196 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11197 	 * round it up.  For future 64 bit requirement, we actually make it
11198 	 * a multiple of 8.
11199 	 */
11200 	if (new_value & 0x7) {
11201 		new_value = (new_value & ~0x7) + 0x8;
11202 	}
11203 	tcppa->tcp_param_val = new_value;
11204 	return (0);
11205 }
11206 
11207 /* Set callback routine passed to nd_load by tcp_param_register */
11208 /* ARGSUSED */
11209 static int
11210 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11211 {
11212 	long	new_value;
11213 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11214 
11215 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11216 	    new_value < tcppa->tcp_param_min ||
11217 	    new_value > tcppa->tcp_param_max) {
11218 		return (EINVAL);
11219 	}
11220 	tcppa->tcp_param_val = new_value;
11221 	return (0);
11222 }
11223 
11224 /*
11225  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11226  * is filled, return as much as we can.  The message passed in may be
11227  * multi-part, chained using b_cont.  "start" is the starting sequence
11228  * number for this piece.
11229  */
11230 static mblk_t *
11231 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11232 {
11233 	uint32_t	end;
11234 	mblk_t		*mp1;
11235 	mblk_t		*mp2;
11236 	mblk_t		*next_mp;
11237 	uint32_t	u1;
11238 
11239 	/* Walk through all the new pieces. */
11240 	do {
11241 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11242 		    (uintptr_t)INT_MAX);
11243 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11244 		next_mp = mp->b_cont;
11245 		if (start == end) {
11246 			/* Empty.  Blast it. */
11247 			freeb(mp);
11248 			continue;
11249 		}
11250 		mp->b_cont = NULL;
11251 		TCP_REASS_SET_SEQ(mp, start);
11252 		TCP_REASS_SET_END(mp, end);
11253 		mp1 = tcp->tcp_reass_tail;
11254 		if (!mp1) {
11255 			tcp->tcp_reass_tail = mp;
11256 			tcp->tcp_reass_head = mp;
11257 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11258 			UPDATE_MIB(&tcp_mib,
11259 			    tcpInDataUnorderBytes, end - start);
11260 			continue;
11261 		}
11262 		/* New stuff completely beyond tail? */
11263 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11264 			/* Link it on end. */
11265 			mp1->b_cont = mp;
11266 			tcp->tcp_reass_tail = mp;
11267 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11268 			UPDATE_MIB(&tcp_mib,
11269 			    tcpInDataUnorderBytes, end - start);
11270 			continue;
11271 		}
11272 		mp1 = tcp->tcp_reass_head;
11273 		u1 = TCP_REASS_SEQ(mp1);
11274 		/* New stuff at the front? */
11275 		if (SEQ_LT(start, u1)) {
11276 			/* Yes... Check for overlap. */
11277 			mp->b_cont = mp1;
11278 			tcp->tcp_reass_head = mp;
11279 			tcp_reass_elim_overlap(tcp, mp);
11280 			continue;
11281 		}
11282 		/*
11283 		 * The new piece fits somewhere between the head and tail.
11284 		 * We find our slot, where mp1 precedes us and mp2 trails.
11285 		 */
11286 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11287 			u1 = TCP_REASS_SEQ(mp2);
11288 			if (SEQ_LEQ(start, u1))
11289 				break;
11290 		}
11291 		/* Link ourselves in */
11292 		mp->b_cont = mp2;
11293 		mp1->b_cont = mp;
11294 
11295 		/* Trim overlap with following mblk(s) first */
11296 		tcp_reass_elim_overlap(tcp, mp);
11297 
11298 		/* Trim overlap with preceding mblk */
11299 		tcp_reass_elim_overlap(tcp, mp1);
11300 
11301 	} while (start = end, mp = next_mp);
11302 	mp1 = tcp->tcp_reass_head;
11303 	/* Anything ready to go? */
11304 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11305 		return (NULL);
11306 	/* Eat what we can off the queue */
11307 	for (;;) {
11308 		mp = mp1->b_cont;
11309 		end = TCP_REASS_END(mp1);
11310 		TCP_REASS_SET_SEQ(mp1, 0);
11311 		TCP_REASS_SET_END(mp1, 0);
11312 		if (!mp) {
11313 			tcp->tcp_reass_tail = NULL;
11314 			break;
11315 		}
11316 		if (end != TCP_REASS_SEQ(mp)) {
11317 			mp1->b_cont = NULL;
11318 			break;
11319 		}
11320 		mp1 = mp;
11321 	}
11322 	mp1 = tcp->tcp_reass_head;
11323 	tcp->tcp_reass_head = mp;
11324 	return (mp1);
11325 }
11326 
11327 /* Eliminate any overlap that mp may have over later mblks */
11328 static void
11329 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11330 {
11331 	uint32_t	end;
11332 	mblk_t		*mp1;
11333 	uint32_t	u1;
11334 
11335 	end = TCP_REASS_END(mp);
11336 	while ((mp1 = mp->b_cont) != NULL) {
11337 		u1 = TCP_REASS_SEQ(mp1);
11338 		if (!SEQ_GT(end, u1))
11339 			break;
11340 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11341 			mp->b_wptr -= end - u1;
11342 			TCP_REASS_SET_END(mp, u1);
11343 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
11344 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
11345 			break;
11346 		}
11347 		mp->b_cont = mp1->b_cont;
11348 		TCP_REASS_SET_SEQ(mp1, 0);
11349 		TCP_REASS_SET_END(mp1, 0);
11350 		freeb(mp1);
11351 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
11352 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
11353 	}
11354 	if (!mp1)
11355 		tcp->tcp_reass_tail = mp;
11356 }
11357 
11358 /*
11359  * Send up all messages queued on tcp_rcv_list.
11360  */
11361 static uint_t
11362 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11363 {
11364 	mblk_t *mp;
11365 	uint_t ret = 0;
11366 	uint_t thwin;
11367 #ifdef DEBUG
11368 	uint_t cnt = 0;
11369 #endif
11370 	/* Can't drain on an eager connection */
11371 	if (tcp->tcp_listener != NULL)
11372 		return (ret);
11373 
11374 	/*
11375 	 * Handle two cases here: we are currently fused or we were
11376 	 * previously fused and have some urgent data to be delivered
11377 	 * upstream.  The latter happens because we either ran out of
11378 	 * memory or were detached and therefore sending the SIGURG was
11379 	 * deferred until this point.  In either case we pass control
11380 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11381 	 * some work.
11382 	 */
11383 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11384 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11385 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11386 		    &tcp->tcp_fused_sigurg_mp))
11387 			return (ret);
11388 	}
11389 
11390 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11391 		tcp->tcp_rcv_list = mp->b_next;
11392 		mp->b_next = NULL;
11393 #ifdef DEBUG
11394 		cnt += msgdsize(mp);
11395 #endif
11396 		/* Does this need SSL processing first? */
11397 		if ((tcp->tcp_kssl_ctx  != NULL) && (DB_TYPE(mp) == M_DATA)) {
11398 			tcp_kssl_input(tcp, mp);
11399 			continue;
11400 		}
11401 		putnext(q, mp);
11402 	}
11403 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11404 	tcp->tcp_rcv_last_head = NULL;
11405 	tcp->tcp_rcv_last_tail = NULL;
11406 	tcp->tcp_rcv_cnt = 0;
11407 
11408 	/* Learn the latest rwnd information that we sent to the other side. */
11409 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11410 	    << tcp->tcp_rcv_ws;
11411 	/* This is peer's calculated send window (our receive window). */
11412 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11413 	/*
11414 	 * Increase the receive window to max.  But we need to do receiver
11415 	 * SWS avoidance.  This means that we need to check the increase of
11416 	 * of receive window is at least 1 MSS.
11417 	 */
11418 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11419 		/*
11420 		 * If the window that the other side knows is less than max
11421 		 * deferred acks segments, send an update immediately.
11422 		 */
11423 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11424 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11425 			ret = TH_ACK_NEEDED;
11426 		}
11427 		tcp->tcp_rwnd = q->q_hiwat;
11428 	}
11429 	/* No need for the push timer now. */
11430 	if (tcp->tcp_push_tid != 0) {
11431 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11432 		tcp->tcp_push_tid = 0;
11433 	}
11434 	return (ret);
11435 }
11436 
11437 /*
11438  * Queue data on tcp_rcv_list which is a b_next chain.
11439  * tcp_rcv_last_head/tail is the last element of this chain.
11440  * Each element of the chain is a b_cont chain.
11441  *
11442  * M_DATA messages are added to the current element.
11443  * Other messages are added as new (b_next) elements.
11444  */
11445 void
11446 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11447 {
11448 	ASSERT(seg_len == msgdsize(mp));
11449 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11450 
11451 	if (tcp->tcp_rcv_list == NULL) {
11452 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11453 		tcp->tcp_rcv_list = mp;
11454 		tcp->tcp_rcv_last_head = mp;
11455 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11456 		tcp->tcp_rcv_last_tail->b_cont = mp;
11457 	} else {
11458 		tcp->tcp_rcv_last_head->b_next = mp;
11459 		tcp->tcp_rcv_last_head = mp;
11460 	}
11461 
11462 	while (mp->b_cont)
11463 		mp = mp->b_cont;
11464 
11465 	tcp->tcp_rcv_last_tail = mp;
11466 	tcp->tcp_rcv_cnt += seg_len;
11467 	tcp->tcp_rwnd -= seg_len;
11468 }
11469 
11470 /*
11471  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11472  *
11473  * This is the default entry function into TCP on the read side. TCP is
11474  * always entered via squeue i.e. using squeue's for mutual exclusion.
11475  * When classifier does a lookup to find the tcp, it also puts a reference
11476  * on the conn structure associated so the tcp is guaranteed to exist
11477  * when we come here. We still need to check the state because it might
11478  * as well has been closed. The squeue processing function i.e. squeue_enter,
11479  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11480  * CONN_DEC_REF.
11481  *
11482  * Apart from the default entry point, IP also sends packets directly to
11483  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11484  * connections.
11485  */
11486 void
11487 tcp_input(void *arg, mblk_t *mp, void *arg2)
11488 {
11489 	conn_t	*connp = (conn_t *)arg;
11490 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11491 
11492 	/* arg2 is the sqp */
11493 	ASSERT(arg2 != NULL);
11494 	ASSERT(mp != NULL);
11495 
11496 	/*
11497 	 * Don't accept any input on a closed tcp as this TCP logically does
11498 	 * not exist on the system. Don't proceed further with this TCP.
11499 	 * For eg. this packet could trigger another close of this tcp
11500 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11501 	 * tcp_clean_death / tcp_closei_local must be called at most once
11502 	 * on a TCP. In this case we need to refeed the packet into the
11503 	 * classifier and figure out where the packet should go. Need to
11504 	 * preserve the recv_ill somehow. Until we figure that out, for
11505 	 * now just drop the packet if we can't classify the packet.
11506 	 */
11507 	if (tcp->tcp_state == TCPS_CLOSED ||
11508 	    tcp->tcp_state == TCPS_BOUND) {
11509 		conn_t	*new_connp;
11510 
11511 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11512 		if (new_connp != NULL) {
11513 			tcp_reinput(new_connp, mp, arg2);
11514 			return;
11515 		}
11516 		/* We failed to classify. For now just drop the packet */
11517 		freemsg(mp);
11518 		return;
11519 	}
11520 
11521 	if (DB_TYPE(mp) == M_DATA)
11522 		tcp_rput_data(connp, mp, arg2);
11523 	else
11524 		tcp_rput_common(tcp, mp);
11525 }
11526 
11527 /*
11528  * The read side put procedure.
11529  * The packets passed up by ip are assume to be aligned according to
11530  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11531  */
11532 static void
11533 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11534 {
11535 	/*
11536 	 * tcp_rput_data() does not expect M_CTL except for the case
11537 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11538 	 * type. Need to make sure that any other M_CTLs don't make
11539 	 * it to tcp_rput_data since it is not expecting any and doesn't
11540 	 * check for it.
11541 	 */
11542 	if (DB_TYPE(mp) == M_CTL) {
11543 		switch (*(uint32_t *)(mp->b_rptr)) {
11544 		case TCP_IOC_ABORT_CONN:
11545 			/*
11546 			 * Handle connection abort request.
11547 			 */
11548 			tcp_ioctl_abort_handler(tcp, mp);
11549 			return;
11550 		case IPSEC_IN:
11551 			/*
11552 			 * Only secure icmp arrive in TCP and they
11553 			 * don't go through data path.
11554 			 */
11555 			tcp_icmp_error(tcp, mp);
11556 			return;
11557 		case IN_PKTINFO:
11558 			/*
11559 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11560 			 * sockets that are receiving IPv4 traffic. tcp
11561 			 */
11562 			ASSERT(tcp->tcp_family == AF_INET6);
11563 			ASSERT(tcp->tcp_ipv6_recvancillary &
11564 			    TCP_IPV6_RECVPKTINFO);
11565 			tcp_rput_data(tcp->tcp_connp, mp,
11566 			    tcp->tcp_connp->conn_sqp);
11567 			return;
11568 		case MDT_IOC_INFO_UPDATE:
11569 			/*
11570 			 * Handle Multidata information update; the
11571 			 * following routine will free the message.
11572 			 */
11573 			if (tcp->tcp_connp->conn_mdt_ok) {
11574 				tcp_mdt_update(tcp,
11575 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11576 				    B_FALSE);
11577 			}
11578 			freemsg(mp);
11579 			return;
11580 		default:
11581 			break;
11582 		}
11583 	}
11584 
11585 	/* No point processing the message if tcp is already closed */
11586 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11587 		freemsg(mp);
11588 		return;
11589 	}
11590 
11591 	tcp_rput_other(tcp, mp);
11592 }
11593 
11594 
11595 /* The minimum of smoothed mean deviation in RTO calculation. */
11596 #define	TCP_SD_MIN	400
11597 
11598 /*
11599  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11600  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11601  * are the same as those in Appendix A.2 of that paper.
11602  *
11603  * m = new measurement
11604  * sa = smoothed RTT average (8 * average estimates).
11605  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11606  */
11607 static void
11608 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11609 {
11610 	long m = TICK_TO_MSEC(rtt);
11611 	clock_t sa = tcp->tcp_rtt_sa;
11612 	clock_t sv = tcp->tcp_rtt_sd;
11613 	clock_t rto;
11614 
11615 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
11616 	tcp->tcp_rtt_update++;
11617 
11618 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11619 	if (sa != 0) {
11620 		/*
11621 		 * Update average estimator:
11622 		 *	new rtt = 7/8 old rtt + 1/8 Error
11623 		 */
11624 
11625 		/* m is now Error in estimate. */
11626 		m -= sa >> 3;
11627 		if ((sa += m) <= 0) {
11628 			/*
11629 			 * Don't allow the smoothed average to be negative.
11630 			 * We use 0 to denote reinitialization of the
11631 			 * variables.
11632 			 */
11633 			sa = 1;
11634 		}
11635 
11636 		/*
11637 		 * Update deviation estimator:
11638 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11639 		 */
11640 		if (m < 0)
11641 			m = -m;
11642 		m -= sv >> 2;
11643 		sv += m;
11644 	} else {
11645 		/*
11646 		 * This follows BSD's implementation.  So the reinitialized
11647 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11648 		 * link is bandwidth dominated, doubling the window size
11649 		 * during slow start means doubling the RTT.  We want to be
11650 		 * more conservative when we reinitialize our estimates.  3
11651 		 * is just a convenient number.
11652 		 */
11653 		sa = m << 3;
11654 		sv = m << 1;
11655 	}
11656 	if (sv < TCP_SD_MIN) {
11657 		/*
11658 		 * We do not know that if sa captures the delay ACK
11659 		 * effect as in a long train of segments, a receiver
11660 		 * does not delay its ACKs.  So set the minimum of sv
11661 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11662 		 * of BSD DATO.  That means the minimum of mean
11663 		 * deviation is 100 ms.
11664 		 *
11665 		 */
11666 		sv = TCP_SD_MIN;
11667 	}
11668 	tcp->tcp_rtt_sa = sa;
11669 	tcp->tcp_rtt_sd = sv;
11670 	/*
11671 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11672 	 *
11673 	 * Add tcp_rexmit_interval extra in case of extreme environment
11674 	 * where the algorithm fails to work.  The default value of
11675 	 * tcp_rexmit_interval_extra should be 0.
11676 	 *
11677 	 * As we use a finer grained clock than BSD and update
11678 	 * RTO for every ACKs, add in another .25 of RTT to the
11679 	 * deviation of RTO to accomodate burstiness of 1/4 of
11680 	 * window size.
11681 	 */
11682 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
11683 
11684 	if (rto > tcp_rexmit_interval_max) {
11685 		tcp->tcp_rto = tcp_rexmit_interval_max;
11686 	} else if (rto < tcp_rexmit_interval_min) {
11687 		tcp->tcp_rto = tcp_rexmit_interval_min;
11688 	} else {
11689 		tcp->tcp_rto = rto;
11690 	}
11691 
11692 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11693 	tcp->tcp_timer_backoff = 0;
11694 }
11695 
11696 /*
11697  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11698  * send queue which starts at the given seq. no.
11699  *
11700  * Parameters:
11701  *	tcp_t *tcp: the tcp instance pointer.
11702  *	uint32_t seq: the starting seq. no of the requested segment.
11703  *	int32_t *off: after the execution, *off will be the offset to
11704  *		the returned mblk which points to the requested seq no.
11705  *		It is the caller's responsibility to send in a non-null off.
11706  *
11707  * Return:
11708  *	A mblk_t pointer pointing to the requested segment in send queue.
11709  */
11710 static mblk_t *
11711 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11712 {
11713 	int32_t	cnt;
11714 	mblk_t	*mp;
11715 
11716 	/* Defensive coding.  Make sure we don't send incorrect data. */
11717 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
11718 		return (NULL);
11719 
11720 	cnt = seq - tcp->tcp_suna;
11721 	mp = tcp->tcp_xmit_head;
11722 	while (cnt > 0 && mp != NULL) {
11723 		cnt -= mp->b_wptr - mp->b_rptr;
11724 		if (cnt < 0) {
11725 			cnt += mp->b_wptr - mp->b_rptr;
11726 			break;
11727 		}
11728 		mp = mp->b_cont;
11729 	}
11730 	ASSERT(mp != NULL);
11731 	*off = cnt;
11732 	return (mp);
11733 }
11734 
11735 /*
11736  * This function handles all retransmissions if SACK is enabled for this
11737  * connection.  First it calculates how many segments can be retransmitted
11738  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11739  * segments.  A segment is eligible if sack_cnt for that segment is greater
11740  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11741  * all eligible segments, it checks to see if TCP can send some new segments
11742  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11743  *
11744  * Parameters:
11745  *	tcp_t *tcp: the tcp structure of the connection.
11746  *	uint_t *flags: in return, appropriate value will be set for
11747  *	tcp_rput_data().
11748  */
11749 static void
11750 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11751 {
11752 	notsack_blk_t	*notsack_blk;
11753 	int32_t		usable_swnd;
11754 	int32_t		mss;
11755 	uint32_t	seg_len;
11756 	mblk_t		*xmit_mp;
11757 
11758 	ASSERT(tcp->tcp_sack_info != NULL);
11759 	ASSERT(tcp->tcp_notsack_list != NULL);
11760 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11761 
11762 	/* Defensive coding in case there is a bug... */
11763 	if (tcp->tcp_notsack_list == NULL) {
11764 		return;
11765 	}
11766 	notsack_blk = tcp->tcp_notsack_list;
11767 	mss = tcp->tcp_mss;
11768 
11769 	/*
11770 	 * Limit the num of outstanding data in the network to be
11771 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11772 	 */
11773 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11774 
11775 	/* At least retransmit 1 MSS of data. */
11776 	if (usable_swnd <= 0) {
11777 		usable_swnd = mss;
11778 	}
11779 
11780 	/* Make sure no new RTT samples will be taken. */
11781 	tcp->tcp_csuna = tcp->tcp_snxt;
11782 
11783 	notsack_blk = tcp->tcp_notsack_list;
11784 	while (usable_swnd > 0) {
11785 		mblk_t		*snxt_mp, *tmp_mp;
11786 		tcp_seq		begin = tcp->tcp_sack_snxt;
11787 		tcp_seq		end;
11788 		int32_t		off;
11789 
11790 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11791 			if (SEQ_GT(notsack_blk->end, begin) &&
11792 			    (notsack_blk->sack_cnt >=
11793 			    tcp_dupack_fast_retransmit)) {
11794 				end = notsack_blk->end;
11795 				if (SEQ_LT(begin, notsack_blk->begin)) {
11796 					begin = notsack_blk->begin;
11797 				}
11798 				break;
11799 			}
11800 		}
11801 		/*
11802 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11803 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11804 		 * set to tcp_cwnd_ssthresh.
11805 		 */
11806 		if (notsack_blk == NULL) {
11807 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11808 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11809 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11810 				ASSERT(tcp->tcp_cwnd > 0);
11811 				return;
11812 			} else {
11813 				usable_swnd = usable_swnd / mss;
11814 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11815 				    MAX(usable_swnd * mss, mss);
11816 				*flags |= TH_XMIT_NEEDED;
11817 				return;
11818 			}
11819 		}
11820 
11821 		/*
11822 		 * Note that we may send more than usable_swnd allows here
11823 		 * because of round off, but no more than 1 MSS of data.
11824 		 */
11825 		seg_len = end - begin;
11826 		if (seg_len > mss)
11827 			seg_len = mss;
11828 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11829 		ASSERT(snxt_mp != NULL);
11830 		/* This should not happen.  Defensive coding again... */
11831 		if (snxt_mp == NULL) {
11832 			return;
11833 		}
11834 
11835 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11836 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11837 		if (xmit_mp == NULL)
11838 			return;
11839 
11840 		usable_swnd -= seg_len;
11841 		tcp->tcp_pipe += seg_len;
11842 		tcp->tcp_sack_snxt = begin + seg_len;
11843 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
11844 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11845 
11846 		/*
11847 		 * Update the send timestamp to avoid false retransmission.
11848 		 */
11849 		snxt_mp->b_prev = (mblk_t *)lbolt;
11850 
11851 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
11852 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
11853 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
11854 		/*
11855 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11856 		 * This happens when new data sent during fast recovery is
11857 		 * also lost.  If TCP retransmits those new data, it needs
11858 		 * to extend SACK recover phase to avoid starting another
11859 		 * fast retransmit/recovery unnecessarily.
11860 		 */
11861 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11862 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11863 		}
11864 	}
11865 }
11866 
11867 /*
11868  * This function handles policy checking at TCP level for non-hard_bound/
11869  * detached connections.
11870  */
11871 static boolean_t
11872 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
11873     boolean_t secure, boolean_t mctl_present)
11874 {
11875 	ipsec_latch_t *ipl = NULL;
11876 	ipsec_action_t *act = NULL;
11877 	mblk_t *data_mp;
11878 	ipsec_in_t *ii;
11879 	const char *reason;
11880 	kstat_named_t *counter;
11881 
11882 	ASSERT(mctl_present || !secure);
11883 
11884 	ASSERT((ipha == NULL && ip6h != NULL) ||
11885 	    (ip6h == NULL && ipha != NULL));
11886 
11887 	/*
11888 	 * We don't necessarily have an ipsec_in_act action to verify
11889 	 * policy because of assymetrical policy where we have only
11890 	 * outbound policy and no inbound policy (possible with global
11891 	 * policy).
11892 	 */
11893 	if (!secure) {
11894 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
11895 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
11896 			return (B_TRUE);
11897 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
11898 		    "tcp_check_policy", ipha, ip6h, secure);
11899 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11900 		    &ipdrops_tcp_clear, &tcp_dropper);
11901 		return (B_FALSE);
11902 	}
11903 
11904 	/*
11905 	 * We have a secure packet.
11906 	 */
11907 	if (act == NULL) {
11908 		ipsec_log_policy_failure(tcp->tcp_wq,
11909 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
11910 		    secure);
11911 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11912 		    &ipdrops_tcp_secure, &tcp_dropper);
11913 		return (B_FALSE);
11914 	}
11915 
11916 	/*
11917 	 * XXX This whole routine is currently incorrect.  ipl should
11918 	 * be set to the latch pointer, but is currently not set, so
11919 	 * we initialize it to NULL to avoid picking up random garbage.
11920 	 */
11921 	if (ipl == NULL)
11922 		return (B_TRUE);
11923 
11924 	data_mp = first_mp->b_cont;
11925 
11926 	ii = (ipsec_in_t *)first_mp->b_rptr;
11927 
11928 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
11929 	    &counter, tcp->tcp_connp)) {
11930 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
11931 		return (B_TRUE);
11932 	}
11933 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
11934 	    "tcp inbound policy mismatch: %s, packet dropped\n",
11935 	    reason);
11936 	BUMP_MIB(&ip_mib, ipsecInFailed);
11937 
11938 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
11939 	return (B_FALSE);
11940 }
11941 
11942 /*
11943  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
11944  * retransmission after a timeout.
11945  *
11946  * To limit the number of duplicate segments, we limit the number of segment
11947  * to be sent in one time to tcp_snd_burst, the burst variable.
11948  */
11949 static void
11950 tcp_ss_rexmit(tcp_t *tcp)
11951 {
11952 	uint32_t	snxt;
11953 	uint32_t	smax;
11954 	int32_t		win;
11955 	int32_t		mss;
11956 	int32_t		off;
11957 	int32_t		burst = tcp->tcp_snd_burst;
11958 	mblk_t		*snxt_mp;
11959 
11960 	/*
11961 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
11962 	 * all unack'ed segments.
11963 	 */
11964 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
11965 		smax = tcp->tcp_rexmit_max;
11966 		snxt = tcp->tcp_rexmit_nxt;
11967 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
11968 			snxt = tcp->tcp_suna;
11969 		}
11970 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
11971 		win -= snxt - tcp->tcp_suna;
11972 		mss = tcp->tcp_mss;
11973 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
11974 
11975 		while (SEQ_LT(snxt, smax) && (win > 0) &&
11976 		    (burst > 0) && (snxt_mp != NULL)) {
11977 			mblk_t	*xmit_mp;
11978 			mblk_t	*old_snxt_mp = snxt_mp;
11979 			uint32_t cnt = mss;
11980 
11981 			if (win < cnt) {
11982 				cnt = win;
11983 			}
11984 			if (SEQ_GT(snxt + cnt, smax)) {
11985 				cnt = smax - snxt;
11986 			}
11987 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
11988 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
11989 			if (xmit_mp == NULL)
11990 				return;
11991 
11992 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11993 
11994 			snxt += cnt;
11995 			win -= cnt;
11996 			/*
11997 			 * Update the send timestamp to avoid false
11998 			 * retransmission.
11999 			 */
12000 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12001 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
12002 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
12003 
12004 			tcp->tcp_rexmit_nxt = snxt;
12005 			burst--;
12006 		}
12007 		/*
12008 		 * If we have transmitted all we have at the time
12009 		 * we started the retranmission, we can leave
12010 		 * the rest of the job to tcp_wput_data().  But we
12011 		 * need to check the send window first.  If the
12012 		 * win is not 0, go on with tcp_wput_data().
12013 		 */
12014 		if (SEQ_LT(snxt, smax) || win == 0) {
12015 			return;
12016 		}
12017 	}
12018 	/* Only call tcp_wput_data() if there is data to be sent. */
12019 	if (tcp->tcp_unsent) {
12020 		tcp_wput_data(tcp, NULL, B_FALSE);
12021 	}
12022 }
12023 
12024 /*
12025  * Process all TCP option in SYN segment.  Note that this function should
12026  * be called after tcp_adapt_ire() is called so that the necessary info
12027  * from IRE is already set in the tcp structure.
12028  *
12029  * This function sets up the correct tcp_mss value according to the
12030  * MSS option value and our header size.  It also sets up the window scale
12031  * and timestamp values, and initialize SACK info blocks.  But it does not
12032  * change receive window size after setting the tcp_mss value.  The caller
12033  * should do the appropriate change.
12034  */
12035 void
12036 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12037 {
12038 	int options;
12039 	tcp_opt_t tcpopt;
12040 	uint32_t mss_max;
12041 	char *tmp_tcph;
12042 
12043 	tcpopt.tcp = NULL;
12044 	options = tcp_parse_options(tcph, &tcpopt);
12045 
12046 	/*
12047 	 * Process MSS option.  Note that MSS option value does not account
12048 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12049 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12050 	 * IPv6.
12051 	 */
12052 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12053 		if (tcp->tcp_ipversion == IPV4_VERSION)
12054 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
12055 		else
12056 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
12057 	} else {
12058 		if (tcp->tcp_ipversion == IPV4_VERSION)
12059 			mss_max = tcp_mss_max_ipv4;
12060 		else
12061 			mss_max = tcp_mss_max_ipv6;
12062 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
12063 			tcpopt.tcp_opt_mss = tcp_mss_min;
12064 		else if (tcpopt.tcp_opt_mss > mss_max)
12065 			tcpopt.tcp_opt_mss = mss_max;
12066 	}
12067 
12068 	/* Process Window Scale option. */
12069 	if (options & TCP_OPT_WSCALE_PRESENT) {
12070 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12071 		tcp->tcp_snd_ws_ok = B_TRUE;
12072 	} else {
12073 		tcp->tcp_snd_ws = B_FALSE;
12074 		tcp->tcp_snd_ws_ok = B_FALSE;
12075 		tcp->tcp_rcv_ws = B_FALSE;
12076 	}
12077 
12078 	/* Process Timestamp option. */
12079 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12080 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12081 		tmp_tcph = (char *)tcp->tcp_tcph;
12082 
12083 		tcp->tcp_snd_ts_ok = B_TRUE;
12084 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12085 		tcp->tcp_last_rcv_lbolt = lbolt64;
12086 		ASSERT(OK_32PTR(tmp_tcph));
12087 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12088 
12089 		/* Fill in our template header with basic timestamp option. */
12090 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12091 		tmp_tcph[0] = TCPOPT_NOP;
12092 		tmp_tcph[1] = TCPOPT_NOP;
12093 		tmp_tcph[2] = TCPOPT_TSTAMP;
12094 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12095 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12096 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12097 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12098 	} else {
12099 		tcp->tcp_snd_ts_ok = B_FALSE;
12100 	}
12101 
12102 	/*
12103 	 * Process SACK options.  If SACK is enabled for this connection,
12104 	 * then allocate the SACK info structure.  Note the following ways
12105 	 * when tcp_snd_sack_ok is set to true.
12106 	 *
12107 	 * For active connection: in tcp_adapt_ire() called in
12108 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12109 	 * is checked.
12110 	 *
12111 	 * For passive connection: in tcp_adapt_ire() called in
12112 	 * tcp_accept_comm().
12113 	 *
12114 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12115 	 * That check makes sure that if we did not send a SACK OK option,
12116 	 * we will not enable SACK for this connection even though the other
12117 	 * side sends us SACK OK option.  For active connection, the SACK
12118 	 * info structure has already been allocated.  So we need to free
12119 	 * it if SACK is disabled.
12120 	 */
12121 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12122 	    (tcp->tcp_snd_sack_ok ||
12123 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12124 		/* This should be true only in the passive case. */
12125 		if (tcp->tcp_sack_info == NULL) {
12126 			ASSERT(TCP_IS_DETACHED(tcp));
12127 			tcp->tcp_sack_info =
12128 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12129 		}
12130 		if (tcp->tcp_sack_info == NULL) {
12131 			tcp->tcp_snd_sack_ok = B_FALSE;
12132 		} else {
12133 			tcp->tcp_snd_sack_ok = B_TRUE;
12134 			if (tcp->tcp_snd_ts_ok) {
12135 				tcp->tcp_max_sack_blk = 3;
12136 			} else {
12137 				tcp->tcp_max_sack_blk = 4;
12138 			}
12139 		}
12140 	} else {
12141 		/*
12142 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12143 		 * no SACK info will be used for this
12144 		 * connection.  This assumes that SACK usage
12145 		 * permission is negotiated.  This may need
12146 		 * to be changed once this is clarified.
12147 		 */
12148 		if (tcp->tcp_sack_info != NULL) {
12149 			ASSERT(tcp->tcp_notsack_list == NULL);
12150 			kmem_cache_free(tcp_sack_info_cache,
12151 			    tcp->tcp_sack_info);
12152 			tcp->tcp_sack_info = NULL;
12153 		}
12154 		tcp->tcp_snd_sack_ok = B_FALSE;
12155 	}
12156 
12157 	/*
12158 	 * Now we know the exact TCP/IP header length, subtract
12159 	 * that from tcp_mss to get our side's MSS.
12160 	 */
12161 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12162 	/*
12163 	 * Here we assume that the other side's header size will be equal to
12164 	 * our header size.  We calculate the real MSS accordingly.  Need to
12165 	 * take into additional stuffs IPsec puts in.
12166 	 *
12167 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12168 	 */
12169 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12170 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12171 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12172 
12173 	/*
12174 	 * Set MSS to the smaller one of both ends of the connection.
12175 	 * We should not have called tcp_mss_set() before, but our
12176 	 * side of the MSS should have been set to a proper value
12177 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12178 	 * STREAM head parameters properly.
12179 	 *
12180 	 * If we have a larger-than-16-bit window but the other side
12181 	 * didn't want to do window scale, tcp_rwnd_set() will take
12182 	 * care of that.
12183 	 */
12184 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
12185 }
12186 
12187 /*
12188  * Sends the T_CONN_IND to the listener. The caller calls this
12189  * functions via squeue to get inside the listener's perimeter
12190  * once the 3 way hand shake is done a T_CONN_IND needs to be
12191  * sent. As an optimization, the caller can call this directly
12192  * if listener's perimeter is same as eager's.
12193  */
12194 /* ARGSUSED */
12195 void
12196 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12197 {
12198 	conn_t			*lconnp = (conn_t *)arg;
12199 	tcp_t			*listener = lconnp->conn_tcp;
12200 	tcp_t			*tcp;
12201 	struct T_conn_ind	*conn_ind;
12202 	ipaddr_t 		*addr_cache;
12203 	boolean_t		need_send_conn_ind = B_FALSE;
12204 
12205 	/* retrieve the eager */
12206 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12207 	ASSERT(conn_ind->OPT_offset != 0 &&
12208 	    conn_ind->OPT_length == sizeof (intptr_t));
12209 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12210 		conn_ind->OPT_length);
12211 
12212 	/*
12213 	 * TLI/XTI applications will get confused by
12214 	 * sending eager as an option since it violates
12215 	 * the option semantics. So remove the eager as
12216 	 * option since TLI/XTI app doesn't need it anyway.
12217 	 */
12218 	if (!TCP_IS_SOCKET(listener)) {
12219 		conn_ind->OPT_length = 0;
12220 		conn_ind->OPT_offset = 0;
12221 	}
12222 	if (listener->tcp_state == TCPS_CLOSED ||
12223 	    TCP_IS_DETACHED(listener)) {
12224 		/*
12225 		 * If listener has closed, it would have caused a
12226 		 * a cleanup/blowoff to happen for the eager. We
12227 		 * just need to return.
12228 		 */
12229 		freemsg(mp);
12230 		return;
12231 	}
12232 
12233 
12234 	/*
12235 	 * if the conn_req_q is full defer passing up the
12236 	 * T_CONN_IND until space is availabe after t_accept()
12237 	 * processing
12238 	 */
12239 	mutex_enter(&listener->tcp_eager_lock);
12240 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12241 		tcp_t *tail;
12242 
12243 		/*
12244 		 * The eager already has an extra ref put in tcp_rput_data
12245 		 * so that it stays till accept comes back even though it
12246 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12247 		 */
12248 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12249 		listener->tcp_conn_req_cnt_q0--;
12250 		listener->tcp_conn_req_cnt_q++;
12251 
12252 		/* Move from SYN_RCVD to ESTABLISHED list  */
12253 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12254 		    tcp->tcp_eager_prev_q0;
12255 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12256 		    tcp->tcp_eager_next_q0;
12257 		tcp->tcp_eager_prev_q0 = NULL;
12258 		tcp->tcp_eager_next_q0 = NULL;
12259 
12260 		/*
12261 		 * Insert at end of the queue because sockfs
12262 		 * sends down T_CONN_RES in chronological
12263 		 * order. Leaving the older conn indications
12264 		 * at front of the queue helps reducing search
12265 		 * time.
12266 		 */
12267 		tail = listener->tcp_eager_last_q;
12268 		if (tail != NULL)
12269 			tail->tcp_eager_next_q = tcp;
12270 		else
12271 			listener->tcp_eager_next_q = tcp;
12272 		listener->tcp_eager_last_q = tcp;
12273 		tcp->tcp_eager_next_q = NULL;
12274 		/*
12275 		 * Delay sending up the T_conn_ind until we are
12276 		 * done with the eager. Once we have have sent up
12277 		 * the T_conn_ind, the accept can potentially complete
12278 		 * any time and release the refhold we have on the eager.
12279 		 */
12280 		need_send_conn_ind = B_TRUE;
12281 	} else {
12282 		/*
12283 		 * Defer connection on q0 and set deferred
12284 		 * connection bit true
12285 		 */
12286 		tcp->tcp_conn_def_q0 = B_TRUE;
12287 
12288 		/* take tcp out of q0 ... */
12289 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12290 		    tcp->tcp_eager_next_q0;
12291 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12292 		    tcp->tcp_eager_prev_q0;
12293 
12294 		/* ... and place it at the end of q0 */
12295 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12296 		tcp->tcp_eager_next_q0 = listener;
12297 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12298 		listener->tcp_eager_prev_q0 = tcp;
12299 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12300 	}
12301 
12302 	/* we have timed out before */
12303 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12304 		tcp->tcp_syn_rcvd_timeout = 0;
12305 		listener->tcp_syn_rcvd_timeout--;
12306 		if (listener->tcp_syn_defense &&
12307 		    listener->tcp_syn_rcvd_timeout <=
12308 		    (tcp_conn_req_max_q0 >> 5) &&
12309 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12310 			listener->tcp_last_rcv_lbolt)) {
12311 			/*
12312 			 * Turn off the defense mode if we
12313 			 * believe the SYN attack is over.
12314 			 */
12315 			listener->tcp_syn_defense = B_FALSE;
12316 			if (listener->tcp_ip_addr_cache) {
12317 				kmem_free((void *)listener->tcp_ip_addr_cache,
12318 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12319 				listener->tcp_ip_addr_cache = NULL;
12320 			}
12321 		}
12322 	}
12323 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12324 	if (addr_cache != NULL) {
12325 		/*
12326 		 * We have finished a 3-way handshake with this
12327 		 * remote host. This proves the IP addr is good.
12328 		 * Cache it!
12329 		 */
12330 		addr_cache[IP_ADDR_CACHE_HASH(
12331 			tcp->tcp_remote)] = tcp->tcp_remote;
12332 	}
12333 	mutex_exit(&listener->tcp_eager_lock);
12334 	if (need_send_conn_ind)
12335 		putnext(listener->tcp_rq, mp);
12336 }
12337 
12338 mblk_t *
12339 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12340     uint_t *ifindexp, ip6_pkt_t *ippp)
12341 {
12342 	in_pktinfo_t	*pinfo;
12343 	ip6_t		*ip6h;
12344 	uchar_t		*rptr;
12345 	mblk_t		*first_mp = mp;
12346 	boolean_t	mctl_present = B_FALSE;
12347 	uint_t 		ifindex = 0;
12348 	ip6_pkt_t	ipp;
12349 	uint_t		ipvers;
12350 	uint_t		ip_hdr_len;
12351 
12352 	rptr = mp->b_rptr;
12353 	ASSERT(OK_32PTR(rptr));
12354 	ASSERT(tcp != NULL);
12355 	ipp.ipp_fields = 0;
12356 
12357 	switch DB_TYPE(mp) {
12358 	case M_CTL:
12359 		mp = mp->b_cont;
12360 		if (mp == NULL) {
12361 			freemsg(first_mp);
12362 			return (NULL);
12363 		}
12364 		if (DB_TYPE(mp) != M_DATA) {
12365 			freemsg(first_mp);
12366 			return (NULL);
12367 		}
12368 		mctl_present = B_TRUE;
12369 		break;
12370 	case M_DATA:
12371 		break;
12372 	default:
12373 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12374 		freemsg(mp);
12375 		return (NULL);
12376 	}
12377 	ipvers = IPH_HDR_VERSION(rptr);
12378 	if (ipvers == IPV4_VERSION) {
12379 		if (tcp == NULL) {
12380 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12381 			goto done;
12382 		}
12383 
12384 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12385 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12386 
12387 		/*
12388 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12389 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12390 		 */
12391 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12392 		    mctl_present) {
12393 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
12394 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
12395 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
12396 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
12397 				ipp.ipp_fields |= IPPF_IFINDEX;
12398 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
12399 				ifindex = pinfo->in_pkt_ifindex;
12400 			}
12401 			freeb(first_mp);
12402 			mctl_present = B_FALSE;
12403 		}
12404 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12405 	} else {
12406 		ip6h = (ip6_t *)rptr;
12407 
12408 		ASSERT(ipvers == IPV6_VERSION);
12409 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12410 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12411 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12412 
12413 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12414 			uint8_t	nexthdrp;
12415 
12416 			/* Look for ifindex information */
12417 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12418 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12419 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12420 					BUMP_MIB(&ip_mib, tcpInErrs);
12421 					freemsg(first_mp);
12422 					return (NULL);
12423 				}
12424 
12425 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12426 					ASSERT(ip6i->ip6i_ifindex != 0);
12427 					ipp.ipp_fields |= IPPF_IFINDEX;
12428 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12429 					ifindex = ip6i->ip6i_ifindex;
12430 				}
12431 				rptr = (uchar_t *)&ip6i[1];
12432 				mp->b_rptr = rptr;
12433 				if (rptr == mp->b_wptr) {
12434 					mblk_t *mp1;
12435 					mp1 = mp->b_cont;
12436 					freeb(mp);
12437 					mp = mp1;
12438 					rptr = mp->b_rptr;
12439 				}
12440 				if (MBLKL(mp) < IPV6_HDR_LEN +
12441 				    sizeof (tcph_t)) {
12442 					BUMP_MIB(&ip_mib, tcpInErrs);
12443 					freemsg(first_mp);
12444 					return (NULL);
12445 				}
12446 				ip6h = (ip6_t *)rptr;
12447 			}
12448 
12449 			/*
12450 			 * Find any potentially interesting extension headers
12451 			 * as well as the length of the IPv6 + extension
12452 			 * headers.
12453 			 */
12454 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12455 			/* Verify if this is a TCP packet */
12456 			if (nexthdrp != IPPROTO_TCP) {
12457 				BUMP_MIB(&ip_mib, tcpInErrs);
12458 				freemsg(first_mp);
12459 				return (NULL);
12460 			}
12461 		} else {
12462 			ip_hdr_len = IPV6_HDR_LEN;
12463 		}
12464 	}
12465 
12466 done:
12467 	if (ipversp != NULL)
12468 		*ipversp = ipvers;
12469 	if (ip_hdr_lenp != NULL)
12470 		*ip_hdr_lenp = ip_hdr_len;
12471 	if (ippp != NULL)
12472 		*ippp = ipp;
12473 	if (ifindexp != NULL)
12474 		*ifindexp = ifindex;
12475 	if (mctl_present) {
12476 		freeb(first_mp);
12477 	}
12478 	return (mp);
12479 }
12480 
12481 /*
12482  * Handle M_DATA messages from IP. Its called directly from IP via
12483  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12484  * in this path.
12485  *
12486  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12487  * v4 and v6), we are called through tcp_input() and a M_CTL can
12488  * be present for options but tcp_find_pktinfo() deals with it. We
12489  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12490  *
12491  * The first argument is always the connp/tcp to which the mp belongs.
12492  * There are no exceptions to this rule. The caller has already put
12493  * a reference on this connp/tcp and once tcp_rput_data() returns,
12494  * the squeue will do the refrele.
12495  *
12496  * The TH_SYN for the listener directly go to tcp_conn_request via
12497  * squeue.
12498  *
12499  * sqp: NULL = recursive, sqp != NULL means called from squeue
12500  */
12501 void
12502 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12503 {
12504 	int32_t		bytes_acked;
12505 	int32_t		gap;
12506 	mblk_t		*mp1;
12507 	uint_t		flags;
12508 	uint32_t	new_swnd = 0;
12509 	uchar_t		*iphdr;
12510 	uchar_t		*rptr;
12511 	int32_t		rgap;
12512 	uint32_t	seg_ack;
12513 	int		seg_len;
12514 	uint_t		ip_hdr_len;
12515 	uint32_t	seg_seq;
12516 	tcph_t		*tcph;
12517 	int		urp;
12518 	tcp_opt_t	tcpopt;
12519 	uint_t		ipvers;
12520 	ip6_pkt_t	ipp;
12521 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12522 	uint32_t	cwnd;
12523 	uint32_t	add;
12524 	int		npkt;
12525 	int		mss;
12526 	conn_t		*connp = (conn_t *)arg;
12527 	squeue_t	*sqp = (squeue_t *)arg2;
12528 	tcp_t		*tcp = connp->conn_tcp;
12529 
12530 	/*
12531 	 * RST from fused tcp loopback peer should trigger an unfuse.
12532 	 */
12533 	if (tcp->tcp_fused) {
12534 		TCP_STAT(tcp_fusion_aborted);
12535 		tcp_unfuse(tcp);
12536 	}
12537 
12538 	iphdr = mp->b_rptr;
12539 	rptr = mp->b_rptr;
12540 	ASSERT(OK_32PTR(rptr));
12541 
12542 	/*
12543 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12544 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12545 	 * necessary information.
12546 	 */
12547 	if (IPCL_IS_TCP4(connp)) {
12548 		ipvers = IPV4_VERSION;
12549 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12550 	} else {
12551 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12552 		    NULL, &ipp);
12553 		if (mp == NULL) {
12554 			TCP_STAT(tcp_rput_v6_error);
12555 			return;
12556 		}
12557 		iphdr = mp->b_rptr;
12558 		rptr = mp->b_rptr;
12559 	}
12560 	ASSERT(DB_TYPE(mp) == M_DATA);
12561 
12562 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12563 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12564 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12565 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12566 	seg_len = (int)(mp->b_wptr - rptr) -
12567 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12568 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12569 		do {
12570 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12571 			    (uintptr_t)INT_MAX);
12572 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12573 		} while ((mp1 = mp1->b_cont) != NULL &&
12574 		    mp1->b_datap->db_type == M_DATA);
12575 	}
12576 
12577 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12578 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12579 		    seg_len, tcph);
12580 		return;
12581 	}
12582 
12583 	if (sqp != NULL) {
12584 		/*
12585 		 * This is the correct place to update tcp_last_recv_time. Note
12586 		 * that it is also updated for tcp structure that belongs to
12587 		 * global and listener queues which do not really need updating.
12588 		 * But that should not cause any harm.  And it is updated for
12589 		 * all kinds of incoming segments, not only for data segments.
12590 		 */
12591 		tcp->tcp_last_recv_time = lbolt;
12592 	}
12593 
12594 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12595 
12596 	BUMP_LOCAL(tcp->tcp_ibsegs);
12597 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12598 
12599 	if ((flags & TH_URG) && sqp != NULL) {
12600 		/*
12601 		 * TCP can't handle urgent pointers that arrive before
12602 		 * the connection has been accept()ed since it can't
12603 		 * buffer OOB data.  Discard segment if this happens.
12604 		 *
12605 		 * Nor can it reassemble urgent pointers, so discard
12606 		 * if it's not the next segment expected.
12607 		 *
12608 		 * Otherwise, collapse chain into one mblk (discard if
12609 		 * that fails).  This makes sure the headers, retransmitted
12610 		 * data, and new data all are in the same mblk.
12611 		 */
12612 		ASSERT(mp != NULL);
12613 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
12614 			freemsg(mp);
12615 			return;
12616 		}
12617 		/* Update pointers into message */
12618 		iphdr = rptr = mp->b_rptr;
12619 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12620 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12621 			/*
12622 			 * Since we can't handle any data with this urgent
12623 			 * pointer that is out of sequence, we expunge
12624 			 * the data.  This allows us to still register
12625 			 * the urgent mark and generate the M_PCSIG,
12626 			 * which we can do.
12627 			 */
12628 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12629 			seg_len = 0;
12630 		}
12631 	}
12632 
12633 	switch (tcp->tcp_state) {
12634 	case TCPS_SYN_SENT:
12635 		if (flags & TH_ACK) {
12636 			/*
12637 			 * Note that our stack cannot send data before a
12638 			 * connection is established, therefore the
12639 			 * following check is valid.  Otherwise, it has
12640 			 * to be changed.
12641 			 */
12642 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12643 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12644 				freemsg(mp);
12645 				if (flags & TH_RST)
12646 					return;
12647 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12648 				    tcp, seg_ack, 0, TH_RST);
12649 				return;
12650 			}
12651 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12652 		}
12653 		if (flags & TH_RST) {
12654 			freemsg(mp);
12655 			if (flags & TH_ACK)
12656 				(void) tcp_clean_death(tcp,
12657 				    ECONNREFUSED, 13);
12658 			return;
12659 		}
12660 		if (!(flags & TH_SYN)) {
12661 			freemsg(mp);
12662 			return;
12663 		}
12664 
12665 		/* Process all TCP options. */
12666 		tcp_process_options(tcp, tcph);
12667 		/*
12668 		 * The following changes our rwnd to be a multiple of the
12669 		 * MIN(peer MSS, our MSS) for performance reason.
12670 		 */
12671 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12672 		    tcp->tcp_mss));
12673 
12674 		/* Is the other end ECN capable? */
12675 		if (tcp->tcp_ecn_ok) {
12676 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12677 				tcp->tcp_ecn_ok = B_FALSE;
12678 			}
12679 		}
12680 		/*
12681 		 * Clear ECN flags because it may interfere with later
12682 		 * processing.
12683 		 */
12684 		flags &= ~(TH_ECE|TH_CWR);
12685 
12686 		tcp->tcp_irs = seg_seq;
12687 		tcp->tcp_rack = seg_seq;
12688 		tcp->tcp_rnxt = seg_seq + 1;
12689 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12690 		if (!TCP_IS_DETACHED(tcp)) {
12691 			/* Allocate room for SACK options if needed. */
12692 			if (tcp->tcp_snd_sack_ok) {
12693 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12694 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
12695 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12696 			} else {
12697 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12698 				    tcp->tcp_hdr_len +
12699 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12700 			}
12701 		}
12702 		if (flags & TH_ACK) {
12703 			/*
12704 			 * If we can't get the confirmation upstream, pretend
12705 			 * we didn't even see this one.
12706 			 *
12707 			 * XXX: how can we pretend we didn't see it if we
12708 			 * have updated rnxt et. al.
12709 			 *
12710 			 * For loopback we defer sending up the T_CONN_CON
12711 			 * until after some checks below.
12712 			 */
12713 			mp1 = NULL;
12714 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12715 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12716 				freemsg(mp);
12717 				return;
12718 			}
12719 			/* SYN was acked - making progress */
12720 			if (tcp->tcp_ipversion == IPV6_VERSION)
12721 				tcp->tcp_ip_forward_progress = B_TRUE;
12722 
12723 			/* One for the SYN */
12724 			tcp->tcp_suna = tcp->tcp_iss + 1;
12725 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12726 			tcp->tcp_state = TCPS_ESTABLISHED;
12727 
12728 			/*
12729 			 * If SYN was retransmitted, need to reset all
12730 			 * retransmission info.  This is because this
12731 			 * segment will be treated as a dup ACK.
12732 			 */
12733 			if (tcp->tcp_rexmit) {
12734 				tcp->tcp_rexmit = B_FALSE;
12735 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12736 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12737 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12738 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12739 				tcp->tcp_ms_we_have_waited = 0;
12740 
12741 				/*
12742 				 * Set tcp_cwnd back to 1 MSS, per
12743 				 * recommendation from
12744 				 * draft-floyd-incr-init-win-01.txt,
12745 				 * Increasing TCP's Initial Window.
12746 				 */
12747 				tcp->tcp_cwnd = tcp->tcp_mss;
12748 			}
12749 
12750 			tcp->tcp_swl1 = seg_seq;
12751 			tcp->tcp_swl2 = seg_ack;
12752 
12753 			new_swnd = BE16_TO_U16(tcph->th_win);
12754 			tcp->tcp_swnd = new_swnd;
12755 			if (new_swnd > tcp->tcp_max_swnd)
12756 				tcp->tcp_max_swnd = new_swnd;
12757 
12758 			/*
12759 			 * Always send the three-way handshake ack immediately
12760 			 * in order to make the connection complete as soon as
12761 			 * possible on the accepting host.
12762 			 */
12763 			flags |= TH_ACK_NEEDED;
12764 
12765 			/*
12766 			 * Special case for loopback.  At this point we have
12767 			 * received SYN-ACK from the remote endpoint.  In
12768 			 * order to ensure that both endpoints reach the
12769 			 * fused state prior to any data exchange, the final
12770 			 * ACK needs to be sent before we indicate T_CONN_CON
12771 			 * to the module upstream.
12772 			 */
12773 			if (tcp->tcp_loopback) {
12774 				mblk_t *ack_mp;
12775 
12776 				ASSERT(!tcp->tcp_unfusable);
12777 				ASSERT(mp1 != NULL);
12778 				/*
12779 				 * For loopback, we always get a pure SYN-ACK
12780 				 * and only need to send back the final ACK
12781 				 * with no data (this is because the other
12782 				 * tcp is ours and we don't do T/TCP).  This
12783 				 * final ACK triggers the passive side to
12784 				 * perform fusion in ESTABLISHED state.
12785 				 */
12786 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12787 					if (tcp->tcp_ack_tid != 0) {
12788 						(void) TCP_TIMER_CANCEL(tcp,
12789 						    tcp->tcp_ack_tid);
12790 						tcp->tcp_ack_tid = 0;
12791 					}
12792 					TCP_RECORD_TRACE(tcp, ack_mp,
12793 					    TCP_TRACE_SEND_PKT);
12794 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
12795 					BUMP_LOCAL(tcp->tcp_obsegs);
12796 					BUMP_MIB(&tcp_mib, tcpOutAck);
12797 
12798 					/* Send up T_CONN_CON */
12799 					putnext(tcp->tcp_rq, mp1);
12800 
12801 					freemsg(mp);
12802 					return;
12803 				}
12804 				/*
12805 				 * Forget fusion; we need to handle more
12806 				 * complex cases below.  Send the deferred
12807 				 * T_CONN_CON message upstream and proceed
12808 				 * as usual.  Mark this tcp as not capable
12809 				 * of fusion.
12810 				 */
12811 				TCP_STAT(tcp_fusion_unfusable);
12812 				tcp->tcp_unfusable = B_TRUE;
12813 				putnext(tcp->tcp_rq, mp1);
12814 			}
12815 
12816 			/*
12817 			 * Check to see if there is data to be sent.  If
12818 			 * yes, set the transmit flag.  Then check to see
12819 			 * if received data processing needs to be done.
12820 			 * If not, go straight to xmit_check.  This short
12821 			 * cut is OK as we don't support T/TCP.
12822 			 */
12823 			if (tcp->tcp_unsent)
12824 				flags |= TH_XMIT_NEEDED;
12825 
12826 			if (seg_len == 0 && !(flags & TH_URG)) {
12827 				freemsg(mp);
12828 				goto xmit_check;
12829 			}
12830 
12831 			flags &= ~TH_SYN;
12832 			seg_seq++;
12833 			break;
12834 		}
12835 		tcp->tcp_state = TCPS_SYN_RCVD;
12836 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
12837 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
12838 		if (mp1) {
12839 			DB_CPID(mp1) = tcp->tcp_cpid;
12840 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
12841 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
12842 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12843 		}
12844 		freemsg(mp);
12845 		return;
12846 	case TCPS_SYN_RCVD:
12847 		if (flags & TH_ACK) {
12848 			/*
12849 			 * In this state, a SYN|ACK packet is either bogus
12850 			 * because the other side must be ACKing our SYN which
12851 			 * indicates it has seen the ACK for their SYN and
12852 			 * shouldn't retransmit it or we're crossing SYNs
12853 			 * on active open.
12854 			 */
12855 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
12856 				freemsg(mp);
12857 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
12858 				    tcp, seg_ack, 0, TH_RST);
12859 				return;
12860 			}
12861 			/*
12862 			 * NOTE: RFC 793 pg. 72 says this should be
12863 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
12864 			 * but that would mean we have an ack that ignored
12865 			 * our SYN.
12866 			 */
12867 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
12868 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12869 				freemsg(mp);
12870 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
12871 				    tcp, seg_ack, 0, TH_RST);
12872 				return;
12873 			}
12874 		}
12875 		break;
12876 	case TCPS_LISTEN:
12877 		/*
12878 		 * Only a TLI listener can come through this path when a
12879 		 * acceptor is going back to be a listener and a packet
12880 		 * for the acceptor hits the classifier. For a socket
12881 		 * listener, this can never happen because a listener
12882 		 * can never accept connection on itself and hence a
12883 		 * socket acceptor can not go back to being a listener.
12884 		 */
12885 		ASSERT(!TCP_IS_SOCKET(tcp));
12886 		/*FALLTHRU*/
12887 	case TCPS_CLOSED:
12888 	case TCPS_BOUND: {
12889 		conn_t	*new_connp;
12890 
12891 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
12892 		if (new_connp != NULL) {
12893 			tcp_reinput(new_connp, mp, connp->conn_sqp);
12894 			return;
12895 		}
12896 		/* We failed to classify. For now just drop the packet */
12897 		freemsg(mp);
12898 		return;
12899 	}
12900 	case TCPS_IDLE:
12901 		/*
12902 		 * Handle the case where the tcp_clean_death() has happened
12903 		 * on a connection (application hasn't closed yet) but a packet
12904 		 * was already queued on squeue before tcp_clean_death()
12905 		 * was processed. Calling tcp_clean_death() twice on same
12906 		 * connection can result in weird behaviour.
12907 		 */
12908 		freemsg(mp);
12909 		return;
12910 	default:
12911 		break;
12912 	}
12913 
12914 	/*
12915 	 * Already on the correct queue/perimeter.
12916 	 * If this is a detached connection and not an eager
12917 	 * connection hanging off a listener then new data
12918 	 * (past the FIN) will cause a reset.
12919 	 * We do a special check here where it
12920 	 * is out of the main line, rather than check
12921 	 * if we are detached every time we see new
12922 	 * data down below.
12923 	 */
12924 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
12925 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
12926 		BUMP_MIB(&tcp_mib, tcpInClosed);
12927 		TCP_RECORD_TRACE(tcp,
12928 		    mp, TCP_TRACE_RECV_PKT);
12929 
12930 		freemsg(mp);
12931 		/*
12932 		 * This could be an SSL closure alert. We're detached so just
12933 		 * acknowledge it this last time.
12934 		 */
12935 		if (tcp->tcp_kssl_ctx != NULL) {
12936 			kssl_release_ctx(tcp->tcp_kssl_ctx);
12937 			tcp->tcp_kssl_ctx = NULL;
12938 
12939 			tcp->tcp_rnxt += seg_len;
12940 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12941 			flags |= TH_ACK_NEEDED;
12942 			goto ack_check;
12943 		}
12944 
12945 		tcp_xmit_ctl("new data when detached", tcp,
12946 		    tcp->tcp_snxt, 0, TH_RST);
12947 		(void) tcp_clean_death(tcp, EPROTO, 12);
12948 		return;
12949 	}
12950 
12951 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12952 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
12953 	new_swnd = BE16_TO_U16(tcph->th_win) <<
12954 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
12955 	mss = tcp->tcp_mss;
12956 
12957 	if (tcp->tcp_snd_ts_ok) {
12958 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
12959 			/*
12960 			 * This segment is not acceptable.
12961 			 * Drop it and send back an ACK.
12962 			 */
12963 			freemsg(mp);
12964 			flags |= TH_ACK_NEEDED;
12965 			goto ack_check;
12966 		}
12967 	} else if (tcp->tcp_snd_sack_ok) {
12968 		ASSERT(tcp->tcp_sack_info != NULL);
12969 		tcpopt.tcp = tcp;
12970 		/*
12971 		 * SACK info in already updated in tcp_parse_options.  Ignore
12972 		 * all other TCP options...
12973 		 */
12974 		(void) tcp_parse_options(tcph, &tcpopt);
12975 	}
12976 try_again:;
12977 	gap = seg_seq - tcp->tcp_rnxt;
12978 	rgap = tcp->tcp_rwnd - (gap + seg_len);
12979 	/*
12980 	 * gap is the amount of sequence space between what we expect to see
12981 	 * and what we got for seg_seq.  A positive value for gap means
12982 	 * something got lost.  A negative value means we got some old stuff.
12983 	 */
12984 	if (gap < 0) {
12985 		/* Old stuff present.  Is the SYN in there? */
12986 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
12987 		    (seg_len != 0)) {
12988 			flags &= ~TH_SYN;
12989 			seg_seq++;
12990 			urp--;
12991 			/* Recompute the gaps after noting the SYN. */
12992 			goto try_again;
12993 		}
12994 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
12995 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
12996 		    (seg_len > -gap ? -gap : seg_len));
12997 		/* Remove the old stuff from seg_len. */
12998 		seg_len += gap;
12999 		/*
13000 		 * Anything left?
13001 		 * Make sure to check for unack'd FIN when rest of data
13002 		 * has been previously ack'd.
13003 		 */
13004 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13005 			/*
13006 			 * Resets are only valid if they lie within our offered
13007 			 * window.  If the RST bit is set, we just ignore this
13008 			 * segment.
13009 			 */
13010 			if (flags & TH_RST) {
13011 				freemsg(mp);
13012 				return;
13013 			}
13014 
13015 			/*
13016 			 * The arriving of dup data packets indicate that we
13017 			 * may have postponed an ack for too long, or the other
13018 			 * side's RTT estimate is out of shape. Start acking
13019 			 * more often.
13020 			 */
13021 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13022 			    tcp->tcp_rack_cnt >= 1 &&
13023 			    tcp->tcp_rack_abs_max > 2) {
13024 				tcp->tcp_rack_abs_max--;
13025 			}
13026 			tcp->tcp_rack_cur_max = 1;
13027 
13028 			/*
13029 			 * This segment is "unacceptable".  None of its
13030 			 * sequence space lies within our advertized window.
13031 			 *
13032 			 * Adjust seg_len to the original value for tracing.
13033 			 */
13034 			seg_len -= gap;
13035 			if (tcp->tcp_debug) {
13036 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13037 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13038 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13039 				    "seg_len %d, rnxt %u, snxt %u, %s",
13040 				    gap, rgap, flags, seg_seq, seg_ack,
13041 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13042 				    tcp_display(tcp, NULL,
13043 				    DISP_ADDR_AND_PORT));
13044 			}
13045 
13046 			/*
13047 			 * Arrange to send an ACK in response to the
13048 			 * unacceptable segment per RFC 793 page 69. There
13049 			 * is only one small difference between ours and the
13050 			 * acceptability test in the RFC - we accept ACK-only
13051 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13052 			 * will be generated.
13053 			 *
13054 			 * Note that we have to ACK an ACK-only packet at least
13055 			 * for stacks that send 0-length keep-alives with
13056 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13057 			 * section 4.2.3.6. As long as we don't ever generate
13058 			 * an unacceptable packet in response to an incoming
13059 			 * packet that is unacceptable, it should not cause
13060 			 * "ACK wars".
13061 			 */
13062 			flags |=  TH_ACK_NEEDED;
13063 
13064 			/*
13065 			 * Continue processing this segment in order to use the
13066 			 * ACK information it contains, but skip all other
13067 			 * sequence-number processing.	Processing the ACK
13068 			 * information is necessary in order to
13069 			 * re-synchronize connections that may have lost
13070 			 * synchronization.
13071 			 *
13072 			 * We clear seg_len and flag fields related to
13073 			 * sequence number processing as they are not
13074 			 * to be trusted for an unacceptable segment.
13075 			 */
13076 			seg_len = 0;
13077 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13078 			goto process_ack;
13079 		}
13080 
13081 		/* Fix seg_seq, and chew the gap off the front. */
13082 		seg_seq = tcp->tcp_rnxt;
13083 		urp += gap;
13084 		do {
13085 			mblk_t	*mp2;
13086 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13087 			    (uintptr_t)UINT_MAX);
13088 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13089 			if (gap > 0) {
13090 				mp->b_rptr = mp->b_wptr - gap;
13091 				break;
13092 			}
13093 			mp2 = mp;
13094 			mp = mp->b_cont;
13095 			freeb(mp2);
13096 		} while (gap < 0);
13097 		/*
13098 		 * If the urgent data has already been acknowledged, we
13099 		 * should ignore TH_URG below
13100 		 */
13101 		if (urp < 0)
13102 			flags &= ~TH_URG;
13103 	}
13104 	/*
13105 	 * rgap is the amount of stuff received out of window.  A negative
13106 	 * value is the amount out of window.
13107 	 */
13108 	if (rgap < 0) {
13109 		mblk_t	*mp2;
13110 
13111 		if (tcp->tcp_rwnd == 0) {
13112 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
13113 		} else {
13114 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
13115 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
13116 		}
13117 
13118 		/*
13119 		 * seg_len does not include the FIN, so if more than
13120 		 * just the FIN is out of window, we act like we don't
13121 		 * see it.  (If just the FIN is out of window, rgap
13122 		 * will be zero and we will go ahead and acknowledge
13123 		 * the FIN.)
13124 		 */
13125 		flags &= ~TH_FIN;
13126 
13127 		/* Fix seg_len and make sure there is something left. */
13128 		seg_len += rgap;
13129 		if (seg_len <= 0) {
13130 			/*
13131 			 * Resets are only valid if they lie within our offered
13132 			 * window.  If the RST bit is set, we just ignore this
13133 			 * segment.
13134 			 */
13135 			if (flags & TH_RST) {
13136 				freemsg(mp);
13137 				return;
13138 			}
13139 
13140 			/* Per RFC 793, we need to send back an ACK. */
13141 			flags |= TH_ACK_NEEDED;
13142 
13143 			/*
13144 			 * Send SIGURG as soon as possible i.e. even
13145 			 * if the TH_URG was delivered in a window probe
13146 			 * packet (which will be unacceptable).
13147 			 *
13148 			 * We generate a signal if none has been generated
13149 			 * for this connection or if this is a new urgent
13150 			 * byte. Also send a zero-length "unmarked" message
13151 			 * to inform SIOCATMARK that this is not the mark.
13152 			 *
13153 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13154 			 * is sent up. This plus the check for old data
13155 			 * (gap >= 0) handles the wraparound of the sequence
13156 			 * number space without having to always track the
13157 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13158 			 * this max in its rcv_up variable).
13159 			 *
13160 			 * This prevents duplicate SIGURGS due to a "late"
13161 			 * zero-window probe when the T_EXDATA_IND has already
13162 			 * been sent up.
13163 			 */
13164 			if ((flags & TH_URG) &&
13165 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13166 			    tcp->tcp_urp_last))) {
13167 				mp1 = allocb(0, BPRI_MED);
13168 				if (mp1 == NULL) {
13169 					freemsg(mp);
13170 					return;
13171 				}
13172 				if (!TCP_IS_DETACHED(tcp) &&
13173 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13174 				    SIGURG)) {
13175 					/* Try again on the rexmit. */
13176 					freemsg(mp1);
13177 					freemsg(mp);
13178 					return;
13179 				}
13180 				/*
13181 				 * If the next byte would be the mark
13182 				 * then mark with MARKNEXT else mark
13183 				 * with NOTMARKNEXT.
13184 				 */
13185 				if (gap == 0 && urp == 0)
13186 					mp1->b_flag |= MSGMARKNEXT;
13187 				else
13188 					mp1->b_flag |= MSGNOTMARKNEXT;
13189 				freemsg(tcp->tcp_urp_mark_mp);
13190 				tcp->tcp_urp_mark_mp = mp1;
13191 				flags |= TH_SEND_URP_MARK;
13192 				tcp->tcp_urp_last_valid = B_TRUE;
13193 				tcp->tcp_urp_last = urp + seg_seq;
13194 			}
13195 			/*
13196 			 * If this is a zero window probe, continue to
13197 			 * process the ACK part.  But we need to set seg_len
13198 			 * to 0 to avoid data processing.  Otherwise just
13199 			 * drop the segment and send back an ACK.
13200 			 */
13201 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13202 				flags &= ~(TH_SYN | TH_URG);
13203 				seg_len = 0;
13204 				goto process_ack;
13205 			} else {
13206 				freemsg(mp);
13207 				goto ack_check;
13208 			}
13209 		}
13210 		/* Pitch out of window stuff off the end. */
13211 		rgap = seg_len;
13212 		mp2 = mp;
13213 		do {
13214 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13215 			    (uintptr_t)INT_MAX);
13216 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13217 			if (rgap < 0) {
13218 				mp2->b_wptr += rgap;
13219 				if ((mp1 = mp2->b_cont) != NULL) {
13220 					mp2->b_cont = NULL;
13221 					freemsg(mp1);
13222 				}
13223 				break;
13224 			}
13225 		} while ((mp2 = mp2->b_cont) != NULL);
13226 	}
13227 ok:;
13228 	/*
13229 	 * TCP should check ECN info for segments inside the window only.
13230 	 * Therefore the check should be done here.
13231 	 */
13232 	if (tcp->tcp_ecn_ok) {
13233 		if (flags & TH_CWR) {
13234 			tcp->tcp_ecn_echo_on = B_FALSE;
13235 		}
13236 		/*
13237 		 * Note that both ECN_CE and CWR can be set in the
13238 		 * same segment.  In this case, we once again turn
13239 		 * on ECN_ECHO.
13240 		 */
13241 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13242 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13243 
13244 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13245 				tcp->tcp_ecn_echo_on = B_TRUE;
13246 			}
13247 		} else {
13248 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13249 
13250 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13251 			    htonl(IPH_ECN_CE << 20)) {
13252 				tcp->tcp_ecn_echo_on = B_TRUE;
13253 			}
13254 		}
13255 	}
13256 
13257 	/*
13258 	 * Check whether we can update tcp_ts_recent.  This test is
13259 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13260 	 * Extensions for High Performance: An Update", Internet Draft.
13261 	 */
13262 	if (tcp->tcp_snd_ts_ok &&
13263 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13264 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13265 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13266 		tcp->tcp_last_rcv_lbolt = lbolt64;
13267 	}
13268 
13269 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13270 		/*
13271 		 * FIN in an out of order segment.  We record this in
13272 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13273 		 * Clear the FIN so that any check on FIN flag will fail.
13274 		 * Remember that FIN also counts in the sequence number
13275 		 * space.  So we need to ack out of order FIN only segments.
13276 		 */
13277 		if (flags & TH_FIN) {
13278 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13279 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13280 			flags &= ~TH_FIN;
13281 			flags |= TH_ACK_NEEDED;
13282 		}
13283 		if (seg_len > 0) {
13284 			/* Fill in the SACK blk list. */
13285 			if (tcp->tcp_snd_sack_ok) {
13286 				ASSERT(tcp->tcp_sack_info != NULL);
13287 				tcp_sack_insert(tcp->tcp_sack_list,
13288 				    seg_seq, seg_seq + seg_len,
13289 				    &(tcp->tcp_num_sack_blk));
13290 			}
13291 
13292 			/*
13293 			 * Attempt reassembly and see if we have something
13294 			 * ready to go.
13295 			 */
13296 			mp = tcp_reass(tcp, mp, seg_seq);
13297 			/* Always ack out of order packets */
13298 			flags |= TH_ACK_NEEDED | TH_PUSH;
13299 			if (mp) {
13300 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13301 				    (uintptr_t)INT_MAX);
13302 				seg_len = mp->b_cont ? msgdsize(mp) :
13303 					(int)(mp->b_wptr - mp->b_rptr);
13304 				seg_seq = tcp->tcp_rnxt;
13305 				/*
13306 				 * A gap is filled and the seq num and len
13307 				 * of the gap match that of a previously
13308 				 * received FIN, put the FIN flag back in.
13309 				 */
13310 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13311 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13312 					flags |= TH_FIN;
13313 					tcp->tcp_valid_bits &=
13314 					    ~TCP_OFO_FIN_VALID;
13315 				}
13316 			} else {
13317 				/*
13318 				 * Keep going even with NULL mp.
13319 				 * There may be a useful ACK or something else
13320 				 * we don't want to miss.
13321 				 *
13322 				 * But TCP should not perform fast retransmit
13323 				 * because of the ack number.  TCP uses
13324 				 * seg_len == 0 to determine if it is a pure
13325 				 * ACK.  And this is not a pure ACK.
13326 				 */
13327 				seg_len = 0;
13328 				ofo_seg = B_TRUE;
13329 			}
13330 		}
13331 	} else if (seg_len > 0) {
13332 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
13333 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
13334 		/*
13335 		 * If an out of order FIN was received before, and the seq
13336 		 * num and len of the new segment match that of the FIN,
13337 		 * put the FIN flag back in.
13338 		 */
13339 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13340 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13341 			flags |= TH_FIN;
13342 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13343 		}
13344 	}
13345 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13346 	if (flags & TH_RST) {
13347 		freemsg(mp);
13348 		switch (tcp->tcp_state) {
13349 		case TCPS_SYN_RCVD:
13350 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13351 			break;
13352 		case TCPS_ESTABLISHED:
13353 		case TCPS_FIN_WAIT_1:
13354 		case TCPS_FIN_WAIT_2:
13355 		case TCPS_CLOSE_WAIT:
13356 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13357 			break;
13358 		case TCPS_CLOSING:
13359 		case TCPS_LAST_ACK:
13360 			(void) tcp_clean_death(tcp, 0, 16);
13361 			break;
13362 		default:
13363 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13364 			(void) tcp_clean_death(tcp, ENXIO, 17);
13365 			break;
13366 		}
13367 		return;
13368 	}
13369 	if (flags & TH_SYN) {
13370 		/*
13371 		 * See RFC 793, Page 71
13372 		 *
13373 		 * The seq number must be in the window as it should
13374 		 * be "fixed" above.  If it is outside window, it should
13375 		 * be already rejected.  Note that we allow seg_seq to be
13376 		 * rnxt + rwnd because we want to accept 0 window probe.
13377 		 */
13378 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13379 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13380 		freemsg(mp);
13381 		/*
13382 		 * If the ACK flag is not set, just use our snxt as the
13383 		 * seq number of the RST segment.
13384 		 */
13385 		if (!(flags & TH_ACK)) {
13386 			seg_ack = tcp->tcp_snxt;
13387 		}
13388 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13389 		    TH_RST|TH_ACK);
13390 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13391 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13392 		return;
13393 	}
13394 	/*
13395 	 * urp could be -1 when the urp field in the packet is 0
13396 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13397 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13398 	 */
13399 	if (flags & TH_URG && urp >= 0) {
13400 		if (!tcp->tcp_urp_last_valid ||
13401 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13402 			/*
13403 			 * If we haven't generated the signal yet for this
13404 			 * urgent pointer value, do it now.  Also, send up a
13405 			 * zero-length M_DATA indicating whether or not this is
13406 			 * the mark. The latter is not needed when a
13407 			 * T_EXDATA_IND is sent up. However, if there are
13408 			 * allocation failures this code relies on the sender
13409 			 * retransmitting and the socket code for determining
13410 			 * the mark should not block waiting for the peer to
13411 			 * transmit. Thus, for simplicity we always send up the
13412 			 * mark indication.
13413 			 */
13414 			mp1 = allocb(0, BPRI_MED);
13415 			if (mp1 == NULL) {
13416 				freemsg(mp);
13417 				return;
13418 			}
13419 			if (!TCP_IS_DETACHED(tcp) &&
13420 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13421 				/* Try again on the rexmit. */
13422 				freemsg(mp1);
13423 				freemsg(mp);
13424 				return;
13425 			}
13426 			/*
13427 			 * Mark with NOTMARKNEXT for now.
13428 			 * The code below will change this to MARKNEXT
13429 			 * if we are at the mark.
13430 			 *
13431 			 * If there are allocation failures (e.g. in dupmsg
13432 			 * below) the next time tcp_rput_data sees the urgent
13433 			 * segment it will send up the MSG*MARKNEXT message.
13434 			 */
13435 			mp1->b_flag |= MSGNOTMARKNEXT;
13436 			freemsg(tcp->tcp_urp_mark_mp);
13437 			tcp->tcp_urp_mark_mp = mp1;
13438 			flags |= TH_SEND_URP_MARK;
13439 #ifdef DEBUG
13440 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13441 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13442 			    "last %x, %s",
13443 			    seg_seq, urp, tcp->tcp_urp_last,
13444 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13445 #endif /* DEBUG */
13446 			tcp->tcp_urp_last_valid = B_TRUE;
13447 			tcp->tcp_urp_last = urp + seg_seq;
13448 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13449 			/*
13450 			 * An allocation failure prevented the previous
13451 			 * tcp_rput_data from sending up the allocated
13452 			 * MSG*MARKNEXT message - send it up this time
13453 			 * around.
13454 			 */
13455 			flags |= TH_SEND_URP_MARK;
13456 		}
13457 
13458 		/*
13459 		 * If the urgent byte is in this segment, make sure that it is
13460 		 * all by itself.  This makes it much easier to deal with the
13461 		 * possibility of an allocation failure on the T_exdata_ind.
13462 		 * Note that seg_len is the number of bytes in the segment, and
13463 		 * urp is the offset into the segment of the urgent byte.
13464 		 * urp < seg_len means that the urgent byte is in this segment.
13465 		 */
13466 		if (urp < seg_len) {
13467 			if (seg_len != 1) {
13468 				uint32_t  tmp_rnxt;
13469 				/*
13470 				 * Break it up and feed it back in.
13471 				 * Re-attach the IP header.
13472 				 */
13473 				mp->b_rptr = iphdr;
13474 				if (urp > 0) {
13475 					/*
13476 					 * There is stuff before the urgent
13477 					 * byte.
13478 					 */
13479 					mp1 = dupmsg(mp);
13480 					if (!mp1) {
13481 						/*
13482 						 * Trim from urgent byte on.
13483 						 * The rest will come back.
13484 						 */
13485 						(void) adjmsg(mp,
13486 						    urp - seg_len);
13487 						tcp_rput_data(connp,
13488 						    mp, NULL);
13489 						return;
13490 					}
13491 					(void) adjmsg(mp1, urp - seg_len);
13492 					/* Feed this piece back in. */
13493 					tmp_rnxt = tcp->tcp_rnxt;
13494 					tcp_rput_data(connp, mp1, NULL);
13495 					/*
13496 					 * If the data passed back in was not
13497 					 * processed (ie: bad ACK) sending
13498 					 * the remainder back in will cause a
13499 					 * loop. In this case, drop the
13500 					 * packet and let the sender try
13501 					 * sending a good packet.
13502 					 */
13503 					if (tmp_rnxt == tcp->tcp_rnxt) {
13504 						freemsg(mp);
13505 						return;
13506 					}
13507 				}
13508 				if (urp != seg_len - 1) {
13509 					uint32_t  tmp_rnxt;
13510 					/*
13511 					 * There is stuff after the urgent
13512 					 * byte.
13513 					 */
13514 					mp1 = dupmsg(mp);
13515 					if (!mp1) {
13516 						/*
13517 						 * Trim everything beyond the
13518 						 * urgent byte.  The rest will
13519 						 * come back.
13520 						 */
13521 						(void) adjmsg(mp,
13522 						    urp + 1 - seg_len);
13523 						tcp_rput_data(connp,
13524 						    mp, NULL);
13525 						return;
13526 					}
13527 					(void) adjmsg(mp1, urp + 1 - seg_len);
13528 					tmp_rnxt = tcp->tcp_rnxt;
13529 					tcp_rput_data(connp, mp1, NULL);
13530 					/*
13531 					 * If the data passed back in was not
13532 					 * processed (ie: bad ACK) sending
13533 					 * the remainder back in will cause a
13534 					 * loop. In this case, drop the
13535 					 * packet and let the sender try
13536 					 * sending a good packet.
13537 					 */
13538 					if (tmp_rnxt == tcp->tcp_rnxt) {
13539 						freemsg(mp);
13540 						return;
13541 					}
13542 				}
13543 				tcp_rput_data(connp, mp, NULL);
13544 				return;
13545 			}
13546 			/*
13547 			 * This segment contains only the urgent byte.  We
13548 			 * have to allocate the T_exdata_ind, if we can.
13549 			 */
13550 			if (!tcp->tcp_urp_mp) {
13551 				struct T_exdata_ind *tei;
13552 				mp1 = allocb(sizeof (struct T_exdata_ind),
13553 				    BPRI_MED);
13554 				if (!mp1) {
13555 					/*
13556 					 * Sigh... It'll be back.
13557 					 * Generate any MSG*MARK message now.
13558 					 */
13559 					freemsg(mp);
13560 					seg_len = 0;
13561 					if (flags & TH_SEND_URP_MARK) {
13562 
13563 
13564 						ASSERT(tcp->tcp_urp_mark_mp);
13565 						tcp->tcp_urp_mark_mp->b_flag &=
13566 							~MSGNOTMARKNEXT;
13567 						tcp->tcp_urp_mark_mp->b_flag |=
13568 							MSGMARKNEXT;
13569 					}
13570 					goto ack_check;
13571 				}
13572 				mp1->b_datap->db_type = M_PROTO;
13573 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13574 				tei->PRIM_type = T_EXDATA_IND;
13575 				tei->MORE_flag = 0;
13576 				mp1->b_wptr = (uchar_t *)&tei[1];
13577 				tcp->tcp_urp_mp = mp1;
13578 #ifdef DEBUG
13579 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13580 				    "tcp_rput: allocated exdata_ind %s",
13581 				    tcp_display(tcp, NULL,
13582 				    DISP_PORT_ONLY));
13583 #endif /* DEBUG */
13584 				/*
13585 				 * There is no need to send a separate MSG*MARK
13586 				 * message since the T_EXDATA_IND will be sent
13587 				 * now.
13588 				 */
13589 				flags &= ~TH_SEND_URP_MARK;
13590 				freemsg(tcp->tcp_urp_mark_mp);
13591 				tcp->tcp_urp_mark_mp = NULL;
13592 			}
13593 			/*
13594 			 * Now we are all set.  On the next putnext upstream,
13595 			 * tcp_urp_mp will be non-NULL and will get prepended
13596 			 * to what has to be this piece containing the urgent
13597 			 * byte.  If for any reason we abort this segment below,
13598 			 * if it comes back, we will have this ready, or it
13599 			 * will get blown off in close.
13600 			 */
13601 		} else if (urp == seg_len) {
13602 			/*
13603 			 * The urgent byte is the next byte after this sequence
13604 			 * number. If there is data it is marked with
13605 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13606 			 * since it is not needed. Otherwise, if the code
13607 			 * above just allocated a zero-length tcp_urp_mark_mp
13608 			 * message, that message is tagged with MSGMARKNEXT.
13609 			 * Sending up these MSGMARKNEXT messages makes
13610 			 * SIOCATMARK work correctly even though
13611 			 * the T_EXDATA_IND will not be sent up until the
13612 			 * urgent byte arrives.
13613 			 */
13614 			if (seg_len != 0) {
13615 				flags |= TH_MARKNEXT_NEEDED;
13616 				freemsg(tcp->tcp_urp_mark_mp);
13617 				tcp->tcp_urp_mark_mp = NULL;
13618 				flags &= ~TH_SEND_URP_MARK;
13619 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13620 				flags |= TH_SEND_URP_MARK;
13621 				tcp->tcp_urp_mark_mp->b_flag &=
13622 					~MSGNOTMARKNEXT;
13623 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13624 			}
13625 #ifdef DEBUG
13626 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13627 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13628 			    seg_len, flags,
13629 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13630 #endif /* DEBUG */
13631 		} else {
13632 			/* Data left until we hit mark */
13633 #ifdef DEBUG
13634 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13635 			    "tcp_rput: URP %d bytes left, %s",
13636 			    urp - seg_len, tcp_display(tcp, NULL,
13637 			    DISP_PORT_ONLY));
13638 #endif /* DEBUG */
13639 		}
13640 	}
13641 
13642 process_ack:
13643 	if (!(flags & TH_ACK)) {
13644 		freemsg(mp);
13645 		goto xmit_check;
13646 	}
13647 	}
13648 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13649 
13650 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13651 		tcp->tcp_ip_forward_progress = B_TRUE;
13652 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13653 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13654 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13655 			/* 3-way handshake complete - pass up the T_CONN_IND */
13656 			tcp_t	*listener = tcp->tcp_listener;
13657 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13658 
13659 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13660 			/*
13661 			 * We are here means eager is fine but it can
13662 			 * get a TH_RST at any point between now and till
13663 			 * accept completes and disappear. We need to
13664 			 * ensure that reference to eager is valid after
13665 			 * we get out of eager's perimeter. So we do
13666 			 * an extra refhold.
13667 			 */
13668 			CONN_INC_REF(connp);
13669 
13670 			/*
13671 			 * The listener also exists because of the refhold
13672 			 * done in tcp_conn_request. Its possible that it
13673 			 * might have closed. We will check that once we
13674 			 * get inside listeners context.
13675 			 */
13676 			CONN_INC_REF(listener->tcp_connp);
13677 			if (listener->tcp_connp->conn_sqp ==
13678 			    connp->conn_sqp) {
13679 				tcp_send_conn_ind(listener->tcp_connp, mp,
13680 				    listener->tcp_connp->conn_sqp);
13681 				CONN_DEC_REF(listener->tcp_connp);
13682 			} else if (!tcp->tcp_loopback) {
13683 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
13684 				    tcp_send_conn_ind,
13685 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
13686 			} else {
13687 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
13688 				    tcp_send_conn_ind, listener->tcp_connp,
13689 				    SQTAG_TCP_CONN_IND);
13690 			}
13691 		}
13692 
13693 		if (tcp->tcp_active_open) {
13694 			/*
13695 			 * We are seeing the final ack in the three way
13696 			 * hand shake of a active open'ed connection
13697 			 * so we must send up a T_CONN_CON
13698 			 */
13699 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13700 				freemsg(mp);
13701 				return;
13702 			}
13703 			/*
13704 			 * Don't fuse the loopback endpoints for
13705 			 * simultaneous active opens.
13706 			 */
13707 			if (tcp->tcp_loopback) {
13708 				TCP_STAT(tcp_fusion_unfusable);
13709 				tcp->tcp_unfusable = B_TRUE;
13710 			}
13711 		}
13712 
13713 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
13714 		bytes_acked--;
13715 		/* SYN was acked - making progress */
13716 		if (tcp->tcp_ipversion == IPV6_VERSION)
13717 			tcp->tcp_ip_forward_progress = B_TRUE;
13718 
13719 		/*
13720 		 * If SYN was retransmitted, need to reset all
13721 		 * retransmission info as this segment will be
13722 		 * treated as a dup ACK.
13723 		 */
13724 		if (tcp->tcp_rexmit) {
13725 			tcp->tcp_rexmit = B_FALSE;
13726 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13727 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
13728 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13729 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13730 			tcp->tcp_ms_we_have_waited = 0;
13731 			tcp->tcp_cwnd = mss;
13732 		}
13733 
13734 		/*
13735 		 * We set the send window to zero here.
13736 		 * This is needed if there is data to be
13737 		 * processed already on the queue.
13738 		 * Later (at swnd_update label), the
13739 		 * "new_swnd > tcp_swnd" condition is satisfied
13740 		 * the XMIT_NEEDED flag is set in the current
13741 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
13742 		 * called if there is already data on queue in
13743 		 * this state.
13744 		 */
13745 		tcp->tcp_swnd = 0;
13746 
13747 		if (new_swnd > tcp->tcp_max_swnd)
13748 			tcp->tcp_max_swnd = new_swnd;
13749 		tcp->tcp_swl1 = seg_seq;
13750 		tcp->tcp_swl2 = seg_ack;
13751 		tcp->tcp_state = TCPS_ESTABLISHED;
13752 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13753 
13754 		/* Fuse when both sides are in ESTABLISHED state */
13755 		if (tcp->tcp_loopback && do_tcp_fusion)
13756 			tcp_fuse(tcp, iphdr, tcph);
13757 
13758 	}
13759 	/* This code follows 4.4BSD-Lite2 mostly. */
13760 	if (bytes_acked < 0)
13761 		goto est;
13762 
13763 	/*
13764 	 * If TCP is ECN capable and the congestion experience bit is
13765 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
13766 	 * done once per window (or more loosely, per RTT).
13767 	 */
13768 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
13769 		tcp->tcp_cwr = B_FALSE;
13770 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
13771 		if (!tcp->tcp_cwr) {
13772 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
13773 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
13774 			tcp->tcp_cwnd = npkt * mss;
13775 			/*
13776 			 * If the cwnd is 0, use the timer to clock out
13777 			 * new segments.  This is required by the ECN spec.
13778 			 */
13779 			if (npkt == 0) {
13780 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13781 				/*
13782 				 * This makes sure that when the ACK comes
13783 				 * back, we will increase tcp_cwnd by 1 MSS.
13784 				 */
13785 				tcp->tcp_cwnd_cnt = 0;
13786 			}
13787 			tcp->tcp_cwr = B_TRUE;
13788 			/*
13789 			 * This marks the end of the current window of in
13790 			 * flight data.  That is why we don't use
13791 			 * tcp_suna + tcp_swnd.  Only data in flight can
13792 			 * provide ECN info.
13793 			 */
13794 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13795 			tcp->tcp_ecn_cwr_sent = B_FALSE;
13796 		}
13797 	}
13798 
13799 	mp1 = tcp->tcp_xmit_head;
13800 	if (bytes_acked == 0) {
13801 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
13802 			int dupack_cnt;
13803 
13804 			BUMP_MIB(&tcp_mib, tcpInDupAck);
13805 			/*
13806 			 * Fast retransmit.  When we have seen exactly three
13807 			 * identical ACKs while we have unacked data
13808 			 * outstanding we take it as a hint that our peer
13809 			 * dropped something.
13810 			 *
13811 			 * If TCP is retransmitting, don't do fast retransmit.
13812 			 */
13813 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
13814 			    ! tcp->tcp_rexmit) {
13815 				/* Do Limited Transmit */
13816 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
13817 				    tcp_dupack_fast_retransmit) {
13818 					/*
13819 					 * RFC 3042
13820 					 *
13821 					 * What we need to do is temporarily
13822 					 * increase tcp_cwnd so that new
13823 					 * data can be sent if it is allowed
13824 					 * by the receive window (tcp_rwnd).
13825 					 * tcp_wput_data() will take care of
13826 					 * the rest.
13827 					 *
13828 					 * If the connection is SACK capable,
13829 					 * only do limited xmit when there
13830 					 * is SACK info.
13831 					 *
13832 					 * Note how tcp_cwnd is incremented.
13833 					 * The first dup ACK will increase
13834 					 * it by 1 MSS.  The second dup ACK
13835 					 * will increase it by 2 MSS.  This
13836 					 * means that only 1 new segment will
13837 					 * be sent for each dup ACK.
13838 					 */
13839 					if (tcp->tcp_unsent > 0 &&
13840 					    (!tcp->tcp_snd_sack_ok ||
13841 					    (tcp->tcp_snd_sack_ok &&
13842 					    tcp->tcp_notsack_list != NULL))) {
13843 						tcp->tcp_cwnd += mss <<
13844 						    (tcp->tcp_dupack_cnt - 1);
13845 						flags |= TH_LIMIT_XMIT;
13846 					}
13847 				} else if (dupack_cnt ==
13848 				    tcp_dupack_fast_retransmit) {
13849 
13850 				/*
13851 				 * If we have reduced tcp_ssthresh
13852 				 * because of ECN, do not reduce it again
13853 				 * unless it is already one window of data
13854 				 * away.  After one window of data, tcp_cwr
13855 				 * should then be cleared.  Note that
13856 				 * for non ECN capable connection, tcp_cwr
13857 				 * should always be false.
13858 				 *
13859 				 * Adjust cwnd since the duplicate
13860 				 * ack indicates that a packet was
13861 				 * dropped (due to congestion.)
13862 				 */
13863 				if (!tcp->tcp_cwr) {
13864 					npkt = ((tcp->tcp_snxt -
13865 					    tcp->tcp_suna) >> 1) / mss;
13866 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13867 					    mss;
13868 					tcp->tcp_cwnd = (npkt +
13869 					    tcp->tcp_dupack_cnt) * mss;
13870 				}
13871 				if (tcp->tcp_ecn_ok) {
13872 					tcp->tcp_cwr = B_TRUE;
13873 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13874 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13875 				}
13876 
13877 				/*
13878 				 * We do Hoe's algorithm.  Refer to her
13879 				 * paper "Improving the Start-up Behavior
13880 				 * of a Congestion Control Scheme for TCP,"
13881 				 * appeared in SIGCOMM'96.
13882 				 *
13883 				 * Save highest seq no we have sent so far.
13884 				 * Be careful about the invisible FIN byte.
13885 				 */
13886 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13887 				    (tcp->tcp_unsent == 0)) {
13888 					tcp->tcp_rexmit_max = tcp->tcp_fss;
13889 				} else {
13890 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
13891 				}
13892 
13893 				/*
13894 				 * Do not allow bursty traffic during.
13895 				 * fast recovery.  Refer to Fall and Floyd's
13896 				 * paper "Simulation-based Comparisons of
13897 				 * Tahoe, Reno and SACK TCP" (in CCR?)
13898 				 * This is a best current practise.
13899 				 */
13900 				tcp->tcp_snd_burst = TCP_CWND_SS;
13901 
13902 				/*
13903 				 * For SACK:
13904 				 * Calculate tcp_pipe, which is the
13905 				 * estimated number of bytes in
13906 				 * network.
13907 				 *
13908 				 * tcp_fack is the highest sack'ed seq num
13909 				 * TCP has received.
13910 				 *
13911 				 * tcp_pipe is explained in the above quoted
13912 				 * Fall and Floyd's paper.  tcp_fack is
13913 				 * explained in Mathis and Mahdavi's
13914 				 * "Forward Acknowledgment: Refining TCP
13915 				 * Congestion Control" in SIGCOMM '96.
13916 				 */
13917 				if (tcp->tcp_snd_sack_ok) {
13918 					ASSERT(tcp->tcp_sack_info != NULL);
13919 					if (tcp->tcp_notsack_list != NULL) {
13920 						tcp->tcp_pipe = tcp->tcp_snxt -
13921 						    tcp->tcp_fack;
13922 						tcp->tcp_sack_snxt = seg_ack;
13923 						flags |= TH_NEED_SACK_REXMIT;
13924 					} else {
13925 						/*
13926 						 * Always initialize tcp_pipe
13927 						 * even though we don't have
13928 						 * any SACK info.  If later
13929 						 * we get SACK info and
13930 						 * tcp_pipe is not initialized,
13931 						 * funny things will happen.
13932 						 */
13933 						tcp->tcp_pipe =
13934 						    tcp->tcp_cwnd_ssthresh;
13935 					}
13936 				} else {
13937 					flags |= TH_REXMIT_NEEDED;
13938 				} /* tcp_snd_sack_ok */
13939 
13940 				} else {
13941 					/*
13942 					 * Here we perform congestion
13943 					 * avoidance, but NOT slow start.
13944 					 * This is known as the Fast
13945 					 * Recovery Algorithm.
13946 					 */
13947 					if (tcp->tcp_snd_sack_ok &&
13948 					    tcp->tcp_notsack_list != NULL) {
13949 						flags |= TH_NEED_SACK_REXMIT;
13950 						tcp->tcp_pipe -= mss;
13951 						if (tcp->tcp_pipe < 0)
13952 							tcp->tcp_pipe = 0;
13953 					} else {
13954 					/*
13955 					 * We know that one more packet has
13956 					 * left the pipe thus we can update
13957 					 * cwnd.
13958 					 */
13959 					cwnd = tcp->tcp_cwnd + mss;
13960 					if (cwnd > tcp->tcp_cwnd_max)
13961 						cwnd = tcp->tcp_cwnd_max;
13962 					tcp->tcp_cwnd = cwnd;
13963 					if (tcp->tcp_unsent > 0)
13964 						flags |= TH_XMIT_NEEDED;
13965 					}
13966 				}
13967 			}
13968 		} else if (tcp->tcp_zero_win_probe) {
13969 			/*
13970 			 * If the window has opened, need to arrange
13971 			 * to send additional data.
13972 			 */
13973 			if (new_swnd != 0) {
13974 				/* tcp_suna != tcp_snxt */
13975 				/* Packet contains a window update */
13976 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
13977 				tcp->tcp_zero_win_probe = 0;
13978 				tcp->tcp_timer_backoff = 0;
13979 				tcp->tcp_ms_we_have_waited = 0;
13980 
13981 				/*
13982 				 * Transmit starting with tcp_suna since
13983 				 * the one byte probe is not ack'ed.
13984 				 * If TCP has sent more than one identical
13985 				 * probe, tcp_rexmit will be set.  That means
13986 				 * tcp_ss_rexmit() will send out the one
13987 				 * byte along with new data.  Otherwise,
13988 				 * fake the retransmission.
13989 				 */
13990 				flags |= TH_XMIT_NEEDED;
13991 				if (!tcp->tcp_rexmit) {
13992 					tcp->tcp_rexmit = B_TRUE;
13993 					tcp->tcp_dupack_cnt = 0;
13994 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13995 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
13996 				}
13997 			}
13998 		}
13999 		goto swnd_update;
14000 	}
14001 
14002 	/*
14003 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14004 	 * If the ACK value acks something that we have not yet sent, it might
14005 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14006 	 * other side.
14007 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14008 	 * state is handled above, so we can always just drop the segment and
14009 	 * send an ACK here.
14010 	 *
14011 	 * Should we send ACKs in response to ACK only segments?
14012 	 */
14013 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14014 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
14015 		/* drop the received segment */
14016 		freemsg(mp);
14017 
14018 		/*
14019 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14020 		 * greater than 0, check if the number of such
14021 		 * bogus ACks is greater than that count.  If yes,
14022 		 * don't send back any ACK.  This prevents TCP from
14023 		 * getting into an ACK storm if somehow an attacker
14024 		 * successfully spoofs an acceptable segment to our
14025 		 * peer.
14026 		 */
14027 		if (tcp_drop_ack_unsent_cnt > 0 &&
14028 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14029 			TCP_STAT(tcp_in_ack_unsent_drop);
14030 			return;
14031 		}
14032 		mp = tcp_ack_mp(tcp);
14033 		if (mp != NULL) {
14034 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
14035 			BUMP_LOCAL(tcp->tcp_obsegs);
14036 			BUMP_MIB(&tcp_mib, tcpOutAck);
14037 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14038 		}
14039 		return;
14040 	}
14041 
14042 	/*
14043 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14044 	 * blocks that are covered by this ACK.
14045 	 */
14046 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14047 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14048 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14049 	}
14050 
14051 	/*
14052 	 * If we got an ACK after fast retransmit, check to see
14053 	 * if it is a partial ACK.  If it is not and the congestion
14054 	 * window was inflated to account for the other side's
14055 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14056 	 */
14057 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
14058 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14059 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14060 			tcp->tcp_dupack_cnt = 0;
14061 			/*
14062 			 * Restore the orig tcp_cwnd_ssthresh after
14063 			 * fast retransmit phase.
14064 			 */
14065 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14066 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14067 			}
14068 			tcp->tcp_rexmit_max = seg_ack;
14069 			tcp->tcp_cwnd_cnt = 0;
14070 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14071 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14072 
14073 			/*
14074 			 * Remove all notsack info to avoid confusion with
14075 			 * the next fast retrasnmit/recovery phase.
14076 			 */
14077 			if (tcp->tcp_snd_sack_ok &&
14078 			    tcp->tcp_notsack_list != NULL) {
14079 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14080 			}
14081 		} else {
14082 			if (tcp->tcp_snd_sack_ok &&
14083 			    tcp->tcp_notsack_list != NULL) {
14084 				flags |= TH_NEED_SACK_REXMIT;
14085 				tcp->tcp_pipe -= mss;
14086 				if (tcp->tcp_pipe < 0)
14087 					tcp->tcp_pipe = 0;
14088 			} else {
14089 				/*
14090 				 * Hoe's algorithm:
14091 				 *
14092 				 * Retransmit the unack'ed segment and
14093 				 * restart fast recovery.  Note that we
14094 				 * need to scale back tcp_cwnd to the
14095 				 * original value when we started fast
14096 				 * recovery.  This is to prevent overly
14097 				 * aggressive behaviour in sending new
14098 				 * segments.
14099 				 */
14100 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14101 					tcp_dupack_fast_retransmit * mss;
14102 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14103 				flags |= TH_REXMIT_NEEDED;
14104 			}
14105 		}
14106 	} else {
14107 		tcp->tcp_dupack_cnt = 0;
14108 		if (tcp->tcp_rexmit) {
14109 			/*
14110 			 * TCP is retranmitting.  If the ACK ack's all
14111 			 * outstanding data, update tcp_rexmit_max and
14112 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14113 			 * to the correct value.
14114 			 *
14115 			 * Note that SEQ_LEQ() is used.  This is to avoid
14116 			 * unnecessary fast retransmit caused by dup ACKs
14117 			 * received when TCP does slow start retransmission
14118 			 * after a time out.  During this phase, TCP may
14119 			 * send out segments which are already received.
14120 			 * This causes dup ACKs to be sent back.
14121 			 */
14122 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14123 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14124 					tcp->tcp_rexmit_nxt = seg_ack;
14125 				}
14126 				if (seg_ack != tcp->tcp_rexmit_max) {
14127 					flags |= TH_XMIT_NEEDED;
14128 				}
14129 			} else {
14130 				tcp->tcp_rexmit = B_FALSE;
14131 				tcp->tcp_xmit_zc_clean = B_FALSE;
14132 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14133 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14134 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14135 			}
14136 			tcp->tcp_ms_we_have_waited = 0;
14137 		}
14138 	}
14139 
14140 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
14141 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
14142 	tcp->tcp_suna = seg_ack;
14143 	if (tcp->tcp_zero_win_probe != 0) {
14144 		tcp->tcp_zero_win_probe = 0;
14145 		tcp->tcp_timer_backoff = 0;
14146 	}
14147 
14148 	/*
14149 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14150 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14151 	 * will not reach here.
14152 	 */
14153 	if (mp1 == NULL) {
14154 		goto fin_acked;
14155 	}
14156 
14157 	/*
14158 	 * Update the congestion window.
14159 	 *
14160 	 * If TCP is not ECN capable or TCP is ECN capable but the
14161 	 * congestion experience bit is not set, increase the tcp_cwnd as
14162 	 * usual.
14163 	 */
14164 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14165 		cwnd = tcp->tcp_cwnd;
14166 		add = mss;
14167 
14168 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14169 			/*
14170 			 * This is to prevent an increase of less than 1 MSS of
14171 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14172 			 * may send out tinygrams in order to preserve mblk
14173 			 * boundaries.
14174 			 *
14175 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14176 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14177 			 * increased by 1 MSS for every RTTs.
14178 			 */
14179 			if (tcp->tcp_cwnd_cnt <= 0) {
14180 				tcp->tcp_cwnd_cnt = cwnd + add;
14181 			} else {
14182 				tcp->tcp_cwnd_cnt -= add;
14183 				add = 0;
14184 			}
14185 		}
14186 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14187 	}
14188 
14189 	/* See if the latest urgent data has been acknowledged */
14190 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14191 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14192 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14193 
14194 	/* Can we update the RTT estimates? */
14195 	if (tcp->tcp_snd_ts_ok) {
14196 		/* Ignore zero timestamp echo-reply. */
14197 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14198 			tcp_set_rto(tcp, (int32_t)lbolt -
14199 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14200 		}
14201 
14202 		/* If needed, restart the timer. */
14203 		if (tcp->tcp_set_timer == 1) {
14204 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14205 			tcp->tcp_set_timer = 0;
14206 		}
14207 		/*
14208 		 * Update tcp_csuna in case the other side stops sending
14209 		 * us timestamps.
14210 		 */
14211 		tcp->tcp_csuna = tcp->tcp_snxt;
14212 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14213 		/*
14214 		 * An ACK sequence we haven't seen before, so get the RTT
14215 		 * and update the RTO. But first check if the timestamp is
14216 		 * valid to use.
14217 		 */
14218 		if ((mp1->b_next != NULL) &&
14219 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14220 			tcp_set_rto(tcp, (int32_t)lbolt -
14221 			    (int32_t)(intptr_t)mp1->b_prev);
14222 		else
14223 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14224 
14225 		/* Remeber the last sequence to be ACKed */
14226 		tcp->tcp_csuna = seg_ack;
14227 		if (tcp->tcp_set_timer == 1) {
14228 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14229 			tcp->tcp_set_timer = 0;
14230 		}
14231 	} else {
14232 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14233 	}
14234 
14235 	/* Eat acknowledged bytes off the xmit queue. */
14236 	for (;;) {
14237 		mblk_t	*mp2;
14238 		uchar_t	*wptr;
14239 
14240 		wptr = mp1->b_wptr;
14241 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14242 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14243 		if (bytes_acked < 0) {
14244 			mp1->b_rptr = wptr + bytes_acked;
14245 			/*
14246 			 * Set a new timestamp if all the bytes timed by the
14247 			 * old timestamp have been ack'ed.
14248 			 */
14249 			if (SEQ_GT(seg_ack,
14250 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14251 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14252 				mp1->b_next = NULL;
14253 			}
14254 			break;
14255 		}
14256 		mp1->b_next = NULL;
14257 		mp1->b_prev = NULL;
14258 		mp2 = mp1;
14259 		mp1 = mp1->b_cont;
14260 
14261 		/*
14262 		 * This notification is required for some zero-copy
14263 		 * clients to maintain a copy semantic. After the data
14264 		 * is ack'ed, client is safe to modify or reuse the buffer.
14265 		 */
14266 		if (tcp->tcp_snd_zcopy_aware &&
14267 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14268 			tcp_zcopy_notify(tcp);
14269 		freeb(mp2);
14270 		if (bytes_acked == 0) {
14271 			if (mp1 == NULL) {
14272 				/* Everything is ack'ed, clear the tail. */
14273 				tcp->tcp_xmit_tail = NULL;
14274 				/*
14275 				 * Cancel the timer unless we are still
14276 				 * waiting for an ACK for the FIN packet.
14277 				 */
14278 				if (tcp->tcp_timer_tid != 0 &&
14279 				    tcp->tcp_snxt == tcp->tcp_suna) {
14280 					(void) TCP_TIMER_CANCEL(tcp,
14281 					    tcp->tcp_timer_tid);
14282 					tcp->tcp_timer_tid = 0;
14283 				}
14284 				goto pre_swnd_update;
14285 			}
14286 			if (mp2 != tcp->tcp_xmit_tail)
14287 				break;
14288 			tcp->tcp_xmit_tail = mp1;
14289 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14290 			    (uintptr_t)INT_MAX);
14291 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14292 			    mp1->b_rptr);
14293 			break;
14294 		}
14295 		if (mp1 == NULL) {
14296 			/*
14297 			 * More was acked but there is nothing more
14298 			 * outstanding.  This means that the FIN was
14299 			 * just acked or that we're talking to a clown.
14300 			 */
14301 fin_acked:
14302 			ASSERT(tcp->tcp_fin_sent);
14303 			tcp->tcp_xmit_tail = NULL;
14304 			if (tcp->tcp_fin_sent) {
14305 				/* FIN was acked - making progress */
14306 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14307 				    !tcp->tcp_fin_acked)
14308 					tcp->tcp_ip_forward_progress = B_TRUE;
14309 				tcp->tcp_fin_acked = B_TRUE;
14310 				if (tcp->tcp_linger_tid != 0 &&
14311 				    TCP_TIMER_CANCEL(tcp,
14312 					tcp->tcp_linger_tid) >= 0) {
14313 					tcp_stop_lingering(tcp);
14314 				}
14315 			} else {
14316 				/*
14317 				 * We should never get here because
14318 				 * we have already checked that the
14319 				 * number of bytes ack'ed should be
14320 				 * smaller than or equal to what we
14321 				 * have sent so far (it is the
14322 				 * acceptability check of the ACK).
14323 				 * We can only get here if the send
14324 				 * queue is corrupted.
14325 				 *
14326 				 * Terminate the connection and
14327 				 * panic the system.  It is better
14328 				 * for us to panic instead of
14329 				 * continuing to avoid other disaster.
14330 				 */
14331 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14332 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14333 				panic("Memory corruption "
14334 				    "detected for connection %s.",
14335 				    tcp_display(tcp, NULL,
14336 					DISP_ADDR_AND_PORT));
14337 				/*NOTREACHED*/
14338 			}
14339 			goto pre_swnd_update;
14340 		}
14341 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14342 	}
14343 	if (tcp->tcp_unsent) {
14344 		flags |= TH_XMIT_NEEDED;
14345 	}
14346 pre_swnd_update:
14347 	tcp->tcp_xmit_head = mp1;
14348 swnd_update:
14349 	/*
14350 	 * The following check is different from most other implementations.
14351 	 * For bi-directional transfer, when segments are dropped, the
14352 	 * "normal" check will not accept a window update in those
14353 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14354 	 * segments which are outside receiver's window.  As TCP accepts
14355 	 * the ack in those retransmitted segments, if the window update in
14356 	 * the same segment is not accepted, TCP will incorrectly calculates
14357 	 * that it can send more segments.  This can create a deadlock
14358 	 * with the receiver if its window becomes zero.
14359 	 */
14360 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14361 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14362 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14363 		/*
14364 		 * The criteria for update is:
14365 		 *
14366 		 * 1. the segment acknowledges some data.  Or
14367 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14368 		 * 3. the segment is not old and the advertised window is
14369 		 * larger than the previous advertised window.
14370 		 */
14371 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14372 			flags |= TH_XMIT_NEEDED;
14373 		tcp->tcp_swnd = new_swnd;
14374 		if (new_swnd > tcp->tcp_max_swnd)
14375 			tcp->tcp_max_swnd = new_swnd;
14376 		tcp->tcp_swl1 = seg_seq;
14377 		tcp->tcp_swl2 = seg_ack;
14378 	}
14379 est:
14380 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14381 
14382 		switch (tcp->tcp_state) {
14383 		case TCPS_FIN_WAIT_1:
14384 			if (tcp->tcp_fin_acked) {
14385 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14386 				/*
14387 				 * We implement the non-standard BSD/SunOS
14388 				 * FIN_WAIT_2 flushing algorithm.
14389 				 * If there is no user attached to this
14390 				 * TCP endpoint, then this TCP struct
14391 				 * could hang around forever in FIN_WAIT_2
14392 				 * state if the peer forgets to send us
14393 				 * a FIN.  To prevent this, we wait only
14394 				 * 2*MSL (a convenient time value) for
14395 				 * the FIN to arrive.  If it doesn't show up,
14396 				 * we flush the TCP endpoint.  This algorithm,
14397 				 * though a violation of RFC-793, has worked
14398 				 * for over 10 years in BSD systems.
14399 				 * Note: SunOS 4.x waits 675 seconds before
14400 				 * flushing the FIN_WAIT_2 connection.
14401 				 */
14402 				TCP_TIMER_RESTART(tcp,
14403 				    tcp_fin_wait_2_flush_interval);
14404 			}
14405 			break;
14406 		case TCPS_FIN_WAIT_2:
14407 			break;	/* Shutdown hook? */
14408 		case TCPS_LAST_ACK:
14409 			freemsg(mp);
14410 			if (tcp->tcp_fin_acked) {
14411 				(void) tcp_clean_death(tcp, 0, 19);
14412 				return;
14413 			}
14414 			goto xmit_check;
14415 		case TCPS_CLOSING:
14416 			if (tcp->tcp_fin_acked) {
14417 				tcp->tcp_state = TCPS_TIME_WAIT;
14418 				/*
14419 				 * Unconditionally clear the exclusive binding
14420 				 * bit so this TIME-WAIT connection won't
14421 				 * interfere with new ones.
14422 				 */
14423 				tcp->tcp_exclbind = 0;
14424 				if (!TCP_IS_DETACHED(tcp)) {
14425 					TCP_TIMER_RESTART(tcp,
14426 					    tcp_time_wait_interval);
14427 				} else {
14428 					tcp_time_wait_append(tcp);
14429 					TCP_DBGSTAT(tcp_rput_time_wait);
14430 				}
14431 			}
14432 			/*FALLTHRU*/
14433 		case TCPS_CLOSE_WAIT:
14434 			freemsg(mp);
14435 			goto xmit_check;
14436 		default:
14437 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14438 			break;
14439 		}
14440 	}
14441 	if (flags & TH_FIN) {
14442 		/* Make sure we ack the fin */
14443 		flags |= TH_ACK_NEEDED;
14444 		if (!tcp->tcp_fin_rcvd) {
14445 			tcp->tcp_fin_rcvd = B_TRUE;
14446 			tcp->tcp_rnxt++;
14447 			tcph = tcp->tcp_tcph;
14448 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14449 
14450 			/*
14451 			 * Generate the ordrel_ind at the end unless we
14452 			 * are an eager guy.
14453 			 * In the eager case tcp_rsrv will do this when run
14454 			 * after tcp_accept is done.
14455 			 */
14456 			if (tcp->tcp_listener == NULL &&
14457 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14458 				flags |= TH_ORDREL_NEEDED;
14459 			switch (tcp->tcp_state) {
14460 			case TCPS_SYN_RCVD:
14461 			case TCPS_ESTABLISHED:
14462 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14463 				/* Keepalive? */
14464 				break;
14465 			case TCPS_FIN_WAIT_1:
14466 				if (!tcp->tcp_fin_acked) {
14467 					tcp->tcp_state = TCPS_CLOSING;
14468 					break;
14469 				}
14470 				/* FALLTHRU */
14471 			case TCPS_FIN_WAIT_2:
14472 				tcp->tcp_state = TCPS_TIME_WAIT;
14473 				/*
14474 				 * Unconditionally clear the exclusive binding
14475 				 * bit so this TIME-WAIT connection won't
14476 				 * interfere with new ones.
14477 				 */
14478 				tcp->tcp_exclbind = 0;
14479 				if (!TCP_IS_DETACHED(tcp)) {
14480 					TCP_TIMER_RESTART(tcp,
14481 					    tcp_time_wait_interval);
14482 				} else {
14483 					tcp_time_wait_append(tcp);
14484 					TCP_DBGSTAT(tcp_rput_time_wait);
14485 				}
14486 				if (seg_len) {
14487 					/*
14488 					 * implies data piggybacked on FIN.
14489 					 * break to handle data.
14490 					 */
14491 					break;
14492 				}
14493 				freemsg(mp);
14494 				goto ack_check;
14495 			}
14496 		}
14497 	}
14498 	if (mp == NULL)
14499 		goto xmit_check;
14500 	if (seg_len == 0) {
14501 		freemsg(mp);
14502 		goto xmit_check;
14503 	}
14504 	if (mp->b_rptr == mp->b_wptr) {
14505 		/*
14506 		 * The header has been consumed, so we remove the
14507 		 * zero-length mblk here.
14508 		 */
14509 		mp1 = mp;
14510 		mp = mp->b_cont;
14511 		freeb(mp1);
14512 	}
14513 	tcph = tcp->tcp_tcph;
14514 	tcp->tcp_rack_cnt++;
14515 	{
14516 		uint32_t cur_max;
14517 
14518 		cur_max = tcp->tcp_rack_cur_max;
14519 		if (tcp->tcp_rack_cnt >= cur_max) {
14520 			/*
14521 			 * We have more unacked data than we should - send
14522 			 * an ACK now.
14523 			 */
14524 			flags |= TH_ACK_NEEDED;
14525 			cur_max++;
14526 			if (cur_max > tcp->tcp_rack_abs_max)
14527 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14528 			else
14529 				tcp->tcp_rack_cur_max = cur_max;
14530 		} else if (TCP_IS_DETACHED(tcp)) {
14531 			/* We don't have an ACK timer for detached TCP. */
14532 			flags |= TH_ACK_NEEDED;
14533 		} else if (seg_len < mss) {
14534 			/*
14535 			 * If we get a segment that is less than an mss, and we
14536 			 * already have unacknowledged data, and the amount
14537 			 * unacknowledged is not a multiple of mss, then we
14538 			 * better generate an ACK now.  Otherwise, this may be
14539 			 * the tail piece of a transaction, and we would rather
14540 			 * wait for the response.
14541 			 */
14542 			uint32_t udif;
14543 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14544 			    (uintptr_t)INT_MAX);
14545 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14546 			if (udif && (udif % mss))
14547 				flags |= TH_ACK_NEEDED;
14548 			else
14549 				flags |= TH_ACK_TIMER_NEEDED;
14550 		} else {
14551 			/* Start delayed ack timer */
14552 			flags |= TH_ACK_TIMER_NEEDED;
14553 		}
14554 	}
14555 	tcp->tcp_rnxt += seg_len;
14556 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14557 
14558 	/* Update SACK list */
14559 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14560 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14561 		    &(tcp->tcp_num_sack_blk));
14562 	}
14563 
14564 	if (tcp->tcp_urp_mp) {
14565 		tcp->tcp_urp_mp->b_cont = mp;
14566 		mp = tcp->tcp_urp_mp;
14567 		tcp->tcp_urp_mp = NULL;
14568 		/* Ready for a new signal. */
14569 		tcp->tcp_urp_last_valid = B_FALSE;
14570 #ifdef DEBUG
14571 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14572 		    "tcp_rput: sending exdata_ind %s",
14573 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14574 #endif /* DEBUG */
14575 	}
14576 
14577 	/*
14578 	 * Check for ancillary data changes compared to last segment.
14579 	 */
14580 	if (tcp->tcp_ipv6_recvancillary != 0) {
14581 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14582 		if (mp == NULL)
14583 			return;
14584 	}
14585 
14586 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14587 		/*
14588 		 * Side queue inbound data until the accept happens.
14589 		 * tcp_accept/tcp_rput drains this when the accept happens.
14590 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14591 		 * T_EXDATA_IND) it is queued on b_next.
14592 		 * XXX Make urgent data use this. Requires:
14593 		 *	Removing tcp_listener check for TH_URG
14594 		 *	Making M_PCPROTO and MARK messages skip the eager case
14595 		 */
14596 
14597 		if (tcp->tcp_kssl_pending) {
14598 			tcp_kssl_input(tcp, mp);
14599 		} else {
14600 			tcp_rcv_enqueue(tcp, mp, seg_len);
14601 		}
14602 	} else {
14603 		if (mp->b_datap->db_type != M_DATA ||
14604 		    (flags & TH_MARKNEXT_NEEDED)) {
14605 			if (tcp->tcp_rcv_list != NULL) {
14606 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14607 			}
14608 			ASSERT(tcp->tcp_rcv_list == NULL ||
14609 			    tcp->tcp_fused_sigurg);
14610 			if (flags & TH_MARKNEXT_NEEDED) {
14611 #ifdef DEBUG
14612 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14613 				    "tcp_rput: sending MSGMARKNEXT %s",
14614 				    tcp_display(tcp, NULL,
14615 				    DISP_PORT_ONLY));
14616 #endif /* DEBUG */
14617 				mp->b_flag |= MSGMARKNEXT;
14618 				flags &= ~TH_MARKNEXT_NEEDED;
14619 			}
14620 
14621 			/* Does this need SSL processing first? */
14622 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14623 			    (DB_TYPE(mp) == M_DATA)) {
14624 				tcp_kssl_input(tcp, mp);
14625 			} else {
14626 				putnext(tcp->tcp_rq, mp);
14627 				if (!canputnext(tcp->tcp_rq))
14628 					tcp->tcp_rwnd -= seg_len;
14629 			}
14630 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14631 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
14632 			if (tcp->tcp_rcv_list != NULL) {
14633 				/*
14634 				 * Enqueue the new segment first and then
14635 				 * call tcp_rcv_drain() to send all data
14636 				 * up.  The other way to do this is to
14637 				 * send all queued data up and then call
14638 				 * putnext() to send the new segment up.
14639 				 * This way can remove the else part later
14640 				 * on.
14641 				 *
14642 				 * We don't this to avoid one more call to
14643 				 * canputnext() as tcp_rcv_drain() needs to
14644 				 * call canputnext().
14645 				 */
14646 				tcp_rcv_enqueue(tcp, mp, seg_len);
14647 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14648 			} else {
14649 				/* Does this need SSL processing first? */
14650 				if ((tcp->tcp_kssl_ctx  != NULL) &&
14651 				    (DB_TYPE(mp) == M_DATA)) {
14652 					tcp_kssl_input(tcp, mp);
14653 				} else {
14654 					putnext(tcp->tcp_rq, mp);
14655 					if (!canputnext(tcp->tcp_rq))
14656 						tcp->tcp_rwnd -= seg_len;
14657 				}
14658 			}
14659 		} else {
14660 			/*
14661 			 * Enqueue all packets when processing an mblk
14662 			 * from the co queue and also enqueue normal packets.
14663 			 */
14664 			tcp_rcv_enqueue(tcp, mp, seg_len);
14665 		}
14666 		/*
14667 		 * Make sure the timer is running if we have data waiting
14668 		 * for a push bit. This provides resiliency against
14669 		 * implementations that do not correctly generate push bits.
14670 		 */
14671 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
14672 			/*
14673 			 * The connection may be closed at this point, so don't
14674 			 * do anything for a detached tcp.
14675 			 */
14676 			if (!TCP_IS_DETACHED(tcp))
14677 				tcp->tcp_push_tid = TCP_TIMER(tcp,
14678 				    tcp_push_timer,
14679 				    MSEC_TO_TICK(tcp_push_timer_interval));
14680 		}
14681 	}
14682 xmit_check:
14683 	/* Is there anything left to do? */
14684 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14685 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
14686 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
14687 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14688 		goto done;
14689 
14690 	/* Any transmit work to do and a non-zero window? */
14691 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
14692 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
14693 		if (flags & TH_REXMIT_NEEDED) {
14694 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
14695 
14696 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
14697 			if (snd_size > mss)
14698 				snd_size = mss;
14699 			if (snd_size > tcp->tcp_swnd)
14700 				snd_size = tcp->tcp_swnd;
14701 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
14702 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
14703 			    B_TRUE);
14704 
14705 			if (mp1 != NULL) {
14706 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14707 				tcp->tcp_csuna = tcp->tcp_snxt;
14708 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
14709 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
14710 				TCP_RECORD_TRACE(tcp, mp1,
14711 				    TCP_TRACE_SEND_PKT);
14712 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
14713 			}
14714 		}
14715 		if (flags & TH_NEED_SACK_REXMIT) {
14716 			tcp_sack_rxmit(tcp, &flags);
14717 		}
14718 		/*
14719 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
14720 		 * out new segment.  Note that tcp_rexmit should not be
14721 		 * set, otherwise TH_LIMIT_XMIT should not be set.
14722 		 */
14723 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
14724 			if (!tcp->tcp_rexmit) {
14725 				tcp_wput_data(tcp, NULL, B_FALSE);
14726 			} else {
14727 				tcp_ss_rexmit(tcp);
14728 			}
14729 		}
14730 		/*
14731 		 * Adjust tcp_cwnd back to normal value after sending
14732 		 * new data segments.
14733 		 */
14734 		if (flags & TH_LIMIT_XMIT) {
14735 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
14736 			/*
14737 			 * This will restart the timer.  Restarting the
14738 			 * timer is used to avoid a timeout before the
14739 			 * limited transmitted segment's ACK gets back.
14740 			 */
14741 			if (tcp->tcp_xmit_head != NULL)
14742 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14743 		}
14744 
14745 		/* Anything more to do? */
14746 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
14747 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14748 			goto done;
14749 	}
14750 ack_check:
14751 	if (flags & TH_SEND_URP_MARK) {
14752 		ASSERT(tcp->tcp_urp_mark_mp);
14753 		/*
14754 		 * Send up any queued data and then send the mark message
14755 		 */
14756 		if (tcp->tcp_rcv_list != NULL) {
14757 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14758 		}
14759 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14760 
14761 		mp1 = tcp->tcp_urp_mark_mp;
14762 		tcp->tcp_urp_mark_mp = NULL;
14763 #ifdef DEBUG
14764 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14765 		    "tcp_rput: sending zero-length %s %s",
14766 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
14767 		    "MSGNOTMARKNEXT"),
14768 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14769 #endif /* DEBUG */
14770 		putnext(tcp->tcp_rq, mp1);
14771 		flags &= ~TH_SEND_URP_MARK;
14772 	}
14773 	if (flags & TH_ACK_NEEDED) {
14774 		/*
14775 		 * Time to send an ack for some reason.
14776 		 */
14777 		mp1 = tcp_ack_mp(tcp);
14778 
14779 		if (mp1 != NULL) {
14780 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
14781 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
14782 			BUMP_LOCAL(tcp->tcp_obsegs);
14783 			BUMP_MIB(&tcp_mib, tcpOutAck);
14784 		}
14785 		if (tcp->tcp_ack_tid != 0) {
14786 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
14787 			tcp->tcp_ack_tid = 0;
14788 		}
14789 	}
14790 	if (flags & TH_ACK_TIMER_NEEDED) {
14791 		/*
14792 		 * Arrange for deferred ACK or push wait timeout.
14793 		 * Start timer if it is not already running.
14794 		 */
14795 		if (tcp->tcp_ack_tid == 0) {
14796 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
14797 			    MSEC_TO_TICK(tcp->tcp_localnet ?
14798 			    (clock_t)tcp_local_dack_interval :
14799 			    (clock_t)tcp_deferred_ack_interval));
14800 		}
14801 	}
14802 	if (flags & TH_ORDREL_NEEDED) {
14803 		/*
14804 		 * Send up the ordrel_ind unless we are an eager guy.
14805 		 * In the eager case tcp_rsrv will do this when run
14806 		 * after tcp_accept is done.
14807 		 */
14808 		ASSERT(tcp->tcp_listener == NULL);
14809 		if (tcp->tcp_rcv_list != NULL) {
14810 			/*
14811 			 * Push any mblk(s) enqueued from co processing.
14812 			 */
14813 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14814 		}
14815 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14816 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
14817 			tcp->tcp_ordrel_done = B_TRUE;
14818 			putnext(tcp->tcp_rq, mp1);
14819 			if (tcp->tcp_deferred_clean_death) {
14820 				/*
14821 				 * tcp_clean_death was deferred
14822 				 * for T_ORDREL_IND - do it now
14823 				 */
14824 				(void) tcp_clean_death(tcp,
14825 				    tcp->tcp_client_errno, 20);
14826 				tcp->tcp_deferred_clean_death =	B_FALSE;
14827 			}
14828 		} else {
14829 			/*
14830 			 * Run the orderly release in the
14831 			 * service routine.
14832 			 */
14833 			qenable(tcp->tcp_rq);
14834 			/*
14835 			 * Caveat(XXX): The machine may be so
14836 			 * overloaded that tcp_rsrv() is not scheduled
14837 			 * until after the endpoint has transitioned
14838 			 * to TCPS_TIME_WAIT
14839 			 * and tcp_time_wait_interval expires. Then
14840 			 * tcp_timer() will blow away state in tcp_t
14841 			 * and T_ORDREL_IND will never be delivered
14842 			 * upstream. Unlikely but potentially
14843 			 * a problem.
14844 			 */
14845 		}
14846 	}
14847 done:
14848 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14849 }
14850 
14851 /*
14852  * This function does PAWS protection check. Returns B_TRUE if the
14853  * segment passes the PAWS test, else returns B_FALSE.
14854  */
14855 boolean_t
14856 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
14857 {
14858 	uint8_t	flags;
14859 	int	options;
14860 	uint8_t *up;
14861 
14862 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
14863 	/*
14864 	 * If timestamp option is aligned nicely, get values inline,
14865 	 * otherwise call general routine to parse.  Only do that
14866 	 * if timestamp is the only option.
14867 	 */
14868 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
14869 	    TCPOPT_REAL_TS_LEN &&
14870 	    OK_32PTR((up = ((uint8_t *)tcph) +
14871 	    TCP_MIN_HEADER_LENGTH)) &&
14872 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
14873 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
14874 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
14875 
14876 		options = TCP_OPT_TSTAMP_PRESENT;
14877 	} else {
14878 		if (tcp->tcp_snd_sack_ok) {
14879 			tcpoptp->tcp = tcp;
14880 		} else {
14881 			tcpoptp->tcp = NULL;
14882 		}
14883 		options = tcp_parse_options(tcph, tcpoptp);
14884 	}
14885 
14886 	if (options & TCP_OPT_TSTAMP_PRESENT) {
14887 		/*
14888 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
14889 		 * regardless of the timestamp, page 18 RFC 1323.bis.
14890 		 */
14891 		if ((flags & TH_RST) == 0 &&
14892 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
14893 		    tcp->tcp_ts_recent)) {
14894 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
14895 			    PAWS_TIMEOUT)) {
14896 				/* This segment is not acceptable. */
14897 				return (B_FALSE);
14898 			} else {
14899 				/*
14900 				 * Connection has been idle for
14901 				 * too long.  Reset the timestamp
14902 				 * and assume the segment is valid.
14903 				 */
14904 				tcp->tcp_ts_recent =
14905 				    tcpoptp->tcp_opt_ts_val;
14906 			}
14907 		}
14908 	} else {
14909 		/*
14910 		 * If we don't get a timestamp on every packet, we
14911 		 * figure we can't really trust 'em, so we stop sending
14912 		 * and parsing them.
14913 		 */
14914 		tcp->tcp_snd_ts_ok = B_FALSE;
14915 
14916 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14917 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14918 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
14919 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
14920 		if (tcp->tcp_snd_sack_ok) {
14921 			ASSERT(tcp->tcp_sack_info != NULL);
14922 			tcp->tcp_max_sack_blk = 4;
14923 		}
14924 	}
14925 	return (B_TRUE);
14926 }
14927 
14928 /*
14929  * Attach ancillary data to a received TCP segments for the
14930  * ancillary pieces requested by the application that are
14931  * different than they were in the previous data segment.
14932  *
14933  * Save the "current" values once memory allocation is ok so that
14934  * when memory allocation fails we can just wait for the next data segment.
14935  */
14936 static mblk_t *
14937 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
14938 {
14939 	struct T_optdata_ind *todi;
14940 	int optlen;
14941 	uchar_t *optptr;
14942 	struct T_opthdr *toh;
14943 	uint_t addflag;	/* Which pieces to add */
14944 	mblk_t *mp1;
14945 
14946 	optlen = 0;
14947 	addflag = 0;
14948 	/* If app asked for pktinfo and the index has changed ... */
14949 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
14950 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
14951 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
14952 		optlen += sizeof (struct T_opthdr) +
14953 		    sizeof (struct in6_pktinfo);
14954 		addflag |= TCP_IPV6_RECVPKTINFO;
14955 	}
14956 	/* If app asked for hoplimit and it has changed ... */
14957 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
14958 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
14959 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
14960 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14961 		addflag |= TCP_IPV6_RECVHOPLIMIT;
14962 	}
14963 	/* If app asked for tclass and it has changed ... */
14964 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
14965 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
14966 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
14967 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14968 		addflag |= TCP_IPV6_RECVTCLASS;
14969 	}
14970 	/*
14971 	 * If app asked for hopbyhop headers and it has changed ...
14972 	 * For security labels, note that (1) security labels can't change on
14973 	 * a connected socket at all, (2) we're connected to at most one peer,
14974 	 * (3) if anything changes, then it must be some other extra option.
14975 	 */
14976 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
14977 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
14978 	    (ipp->ipp_fields & IPPF_HOPOPTS),
14979 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
14980 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
14981 		    tcp->tcp_label_len;
14982 		addflag |= TCP_IPV6_RECVHOPOPTS;
14983 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
14984 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
14985 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
14986 			return (mp);
14987 	}
14988 	/* If app asked for dst headers before routing headers ... */
14989 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
14990 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
14991 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
14992 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
14993 		optlen += sizeof (struct T_opthdr) +
14994 		    ipp->ipp_rtdstoptslen;
14995 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
14996 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
14997 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
14998 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
14999 			return (mp);
15000 	}
15001 	/* If app asked for routing headers and it has changed ... */
15002 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15003 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15004 	    (ipp->ipp_fields & IPPF_RTHDR),
15005 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15006 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15007 		addflag |= TCP_IPV6_RECVRTHDR;
15008 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15009 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15010 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15011 			return (mp);
15012 	}
15013 	/* If app asked for dest headers and it has changed ... */
15014 	if ((tcp->tcp_ipv6_recvancillary &
15015 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15016 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15017 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15018 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15019 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15020 		addflag |= TCP_IPV6_RECVDSTOPTS;
15021 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15022 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15023 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15024 			return (mp);
15025 	}
15026 
15027 	if (optlen == 0) {
15028 		/* Nothing to add */
15029 		return (mp);
15030 	}
15031 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15032 	if (mp1 == NULL) {
15033 		/*
15034 		 * Defer sending ancillary data until the next TCP segment
15035 		 * arrives.
15036 		 */
15037 		return (mp);
15038 	}
15039 	mp1->b_cont = mp;
15040 	mp = mp1;
15041 	mp->b_wptr += sizeof (*todi) + optlen;
15042 	mp->b_datap->db_type = M_PROTO;
15043 	todi = (struct T_optdata_ind *)mp->b_rptr;
15044 	todi->PRIM_type = T_OPTDATA_IND;
15045 	todi->DATA_flag = 1;	/* MORE data */
15046 	todi->OPT_length = optlen;
15047 	todi->OPT_offset = sizeof (*todi);
15048 	optptr = (uchar_t *)&todi[1];
15049 	/*
15050 	 * If app asked for pktinfo and the index has changed ...
15051 	 * Note that the local address never changes for the connection.
15052 	 */
15053 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15054 		struct in6_pktinfo *pkti;
15055 
15056 		toh = (struct T_opthdr *)optptr;
15057 		toh->level = IPPROTO_IPV6;
15058 		toh->name = IPV6_PKTINFO;
15059 		toh->len = sizeof (*toh) + sizeof (*pkti);
15060 		toh->status = 0;
15061 		optptr += sizeof (*toh);
15062 		pkti = (struct in6_pktinfo *)optptr;
15063 		if (tcp->tcp_ipversion == IPV6_VERSION)
15064 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15065 		else
15066 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15067 			    &pkti->ipi6_addr);
15068 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15069 		optptr += sizeof (*pkti);
15070 		ASSERT(OK_32PTR(optptr));
15071 		/* Save as "last" value */
15072 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15073 	}
15074 	/* If app asked for hoplimit and it has changed ... */
15075 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15076 		toh = (struct T_opthdr *)optptr;
15077 		toh->level = IPPROTO_IPV6;
15078 		toh->name = IPV6_HOPLIMIT;
15079 		toh->len = sizeof (*toh) + sizeof (uint_t);
15080 		toh->status = 0;
15081 		optptr += sizeof (*toh);
15082 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15083 		optptr += sizeof (uint_t);
15084 		ASSERT(OK_32PTR(optptr));
15085 		/* Save as "last" value */
15086 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15087 	}
15088 	/* If app asked for tclass and it has changed ... */
15089 	if (addflag & TCP_IPV6_RECVTCLASS) {
15090 		toh = (struct T_opthdr *)optptr;
15091 		toh->level = IPPROTO_IPV6;
15092 		toh->name = IPV6_TCLASS;
15093 		toh->len = sizeof (*toh) + sizeof (uint_t);
15094 		toh->status = 0;
15095 		optptr += sizeof (*toh);
15096 		*(uint_t *)optptr = ipp->ipp_tclass;
15097 		optptr += sizeof (uint_t);
15098 		ASSERT(OK_32PTR(optptr));
15099 		/* Save as "last" value */
15100 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15101 	}
15102 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15103 		toh = (struct T_opthdr *)optptr;
15104 		toh->level = IPPROTO_IPV6;
15105 		toh->name = IPV6_HOPOPTS;
15106 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15107 		    tcp->tcp_label_len;
15108 		toh->status = 0;
15109 		optptr += sizeof (*toh);
15110 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15111 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15112 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15113 		ASSERT(OK_32PTR(optptr));
15114 		/* Save as last value */
15115 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15116 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15117 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15118 	}
15119 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15120 		toh = (struct T_opthdr *)optptr;
15121 		toh->level = IPPROTO_IPV6;
15122 		toh->name = IPV6_RTHDRDSTOPTS;
15123 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15124 		toh->status = 0;
15125 		optptr += sizeof (*toh);
15126 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15127 		optptr += ipp->ipp_rtdstoptslen;
15128 		ASSERT(OK_32PTR(optptr));
15129 		/* Save as last value */
15130 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15131 		    &tcp->tcp_rtdstoptslen,
15132 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15133 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15134 	}
15135 	if (addflag & TCP_IPV6_RECVRTHDR) {
15136 		toh = (struct T_opthdr *)optptr;
15137 		toh->level = IPPROTO_IPV6;
15138 		toh->name = IPV6_RTHDR;
15139 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15140 		toh->status = 0;
15141 		optptr += sizeof (*toh);
15142 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15143 		optptr += ipp->ipp_rthdrlen;
15144 		ASSERT(OK_32PTR(optptr));
15145 		/* Save as last value */
15146 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15147 		    (ipp->ipp_fields & IPPF_RTHDR),
15148 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15149 	}
15150 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15151 		toh = (struct T_opthdr *)optptr;
15152 		toh->level = IPPROTO_IPV6;
15153 		toh->name = IPV6_DSTOPTS;
15154 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15155 		toh->status = 0;
15156 		optptr += sizeof (*toh);
15157 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15158 		optptr += ipp->ipp_dstoptslen;
15159 		ASSERT(OK_32PTR(optptr));
15160 		/* Save as last value */
15161 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15162 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15163 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15164 	}
15165 	ASSERT(optptr == mp->b_wptr);
15166 	return (mp);
15167 }
15168 
15169 
15170 /*
15171  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15172  * or a "bad" IRE detected by tcp_adapt_ire.
15173  * We can't tell if the failure was due to the laddr or the faddr
15174  * thus we clear out all addresses and ports.
15175  */
15176 static void
15177 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15178 {
15179 	queue_t	*q = tcp->tcp_rq;
15180 	tcph_t	*tcph;
15181 	struct T_error_ack *tea;
15182 	conn_t	*connp = tcp->tcp_connp;
15183 
15184 
15185 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15186 
15187 	if (mp->b_cont) {
15188 		freemsg(mp->b_cont);
15189 		mp->b_cont = NULL;
15190 	}
15191 	tea = (struct T_error_ack *)mp->b_rptr;
15192 	switch (tea->PRIM_type) {
15193 	case T_BIND_ACK:
15194 		/*
15195 		 * Need to unbind with classifier since we were just told that
15196 		 * our bind succeeded.
15197 		 */
15198 		tcp->tcp_hard_bound = B_FALSE;
15199 		tcp->tcp_hard_binding = B_FALSE;
15200 
15201 		ipcl_hash_remove(connp);
15202 		/* Reuse the mblk if possible */
15203 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15204 			sizeof (*tea));
15205 		mp->b_rptr = mp->b_datap->db_base;
15206 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15207 		tea = (struct T_error_ack *)mp->b_rptr;
15208 		tea->PRIM_type = T_ERROR_ACK;
15209 		tea->TLI_error = TSYSERR;
15210 		tea->UNIX_error = error;
15211 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15212 			tea->ERROR_prim = T_CONN_REQ;
15213 		} else {
15214 			tea->ERROR_prim = O_T_BIND_REQ;
15215 		}
15216 		break;
15217 
15218 	case T_ERROR_ACK:
15219 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15220 			tea->ERROR_prim = T_CONN_REQ;
15221 		break;
15222 	default:
15223 		panic("tcp_bind_failed: unexpected TPI type");
15224 		/*NOTREACHED*/
15225 	}
15226 
15227 	tcp->tcp_state = TCPS_IDLE;
15228 	if (tcp->tcp_ipversion == IPV4_VERSION)
15229 		tcp->tcp_ipha->ipha_src = 0;
15230 	else
15231 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15232 	/*
15233 	 * Copy of the src addr. in tcp_t is needed since
15234 	 * the lookup funcs. can only look at tcp_t
15235 	 */
15236 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15237 
15238 	tcph = tcp->tcp_tcph;
15239 	tcph->th_lport[0] = 0;
15240 	tcph->th_lport[1] = 0;
15241 	tcp_bind_hash_remove(tcp);
15242 	bzero(&connp->u_port, sizeof (connp->u_port));
15243 	/* blow away saved option results if any */
15244 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15245 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15246 
15247 	conn_delete_ire(tcp->tcp_connp, NULL);
15248 	putnext(q, mp);
15249 }
15250 
15251 /*
15252  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15253  * messages.
15254  */
15255 void
15256 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15257 {
15258 	mblk_t	*mp1;
15259 	uchar_t	*rptr = mp->b_rptr;
15260 	queue_t	*q = tcp->tcp_rq;
15261 	struct T_error_ack *tea;
15262 	uint32_t mss;
15263 	mblk_t *syn_mp;
15264 	mblk_t *mdti;
15265 	int	retval;
15266 	mblk_t *ire_mp;
15267 
15268 	switch (mp->b_datap->db_type) {
15269 	case M_PROTO:
15270 	case M_PCPROTO:
15271 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15272 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15273 			break;
15274 		tea = (struct T_error_ack *)rptr;
15275 		switch (tea->PRIM_type) {
15276 		case T_BIND_ACK:
15277 			/*
15278 			 * Adapt Multidata information, if any.  The
15279 			 * following tcp_mdt_update routine will free
15280 			 * the message.
15281 			 */
15282 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15283 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15284 				    b_rptr)->mdt_capab, B_TRUE);
15285 				freemsg(mdti);
15286 			}
15287 
15288 			/* Get the IRE, if we had requested for it */
15289 			ire_mp = tcp_ire_mp(mp);
15290 
15291 			if (tcp->tcp_hard_binding) {
15292 				tcp->tcp_hard_binding = B_FALSE;
15293 				tcp->tcp_hard_bound = B_TRUE;
15294 				CL_INET_CONNECT(tcp);
15295 			} else {
15296 				if (ire_mp != NULL)
15297 					freeb(ire_mp);
15298 				goto after_syn_sent;
15299 			}
15300 
15301 			retval = tcp_adapt_ire(tcp, ire_mp);
15302 			if (ire_mp != NULL)
15303 				freeb(ire_mp);
15304 			if (retval == 0) {
15305 				tcp_bind_failed(tcp, mp,
15306 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15307 				    ENETUNREACH : EADDRNOTAVAIL));
15308 				return;
15309 			}
15310 			/*
15311 			 * Don't let an endpoint connect to itself.
15312 			 * Also checked in tcp_connect() but that
15313 			 * check can't handle the case when the
15314 			 * local IP address is INADDR_ANY.
15315 			 */
15316 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15317 				if ((tcp->tcp_ipha->ipha_dst ==
15318 				    tcp->tcp_ipha->ipha_src) &&
15319 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15320 				    tcp->tcp_tcph->th_fport))) {
15321 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15322 					return;
15323 				}
15324 			} else {
15325 				if (IN6_ARE_ADDR_EQUAL(
15326 				    &tcp->tcp_ip6h->ip6_dst,
15327 				    &tcp->tcp_ip6h->ip6_src) &&
15328 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15329 				    tcp->tcp_tcph->th_fport))) {
15330 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15331 					return;
15332 				}
15333 			}
15334 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15335 			/*
15336 			 * This should not be possible!  Just for
15337 			 * defensive coding...
15338 			 */
15339 			if (tcp->tcp_state != TCPS_SYN_SENT)
15340 				goto after_syn_sent;
15341 
15342 			if (is_system_labeled() &&
15343 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
15344 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
15345 				return;
15346 			}
15347 
15348 			ASSERT(q == tcp->tcp_rq);
15349 			/*
15350 			 * tcp_adapt_ire() does not adjust
15351 			 * for TCP/IP header length.
15352 			 */
15353 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15354 
15355 			/*
15356 			 * Just make sure our rwnd is at
15357 			 * least tcp_recv_hiwat_mss * MSS
15358 			 * large, and round up to the nearest
15359 			 * MSS.
15360 			 *
15361 			 * We do the round up here because
15362 			 * we need to get the interface
15363 			 * MTU first before we can do the
15364 			 * round up.
15365 			 */
15366 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15367 			    tcp_recv_hiwat_minmss * mss);
15368 			q->q_hiwat = tcp->tcp_rwnd;
15369 			tcp_set_ws_value(tcp);
15370 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15371 			    tcp->tcp_tcph->th_win);
15372 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
15373 				tcp->tcp_snd_ws_ok = B_TRUE;
15374 
15375 			/*
15376 			 * Set tcp_snd_ts_ok to true
15377 			 * so that tcp_xmit_mp will
15378 			 * include the timestamp
15379 			 * option in the SYN segment.
15380 			 */
15381 			if (tcp_tstamp_always ||
15382 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
15383 				tcp->tcp_snd_ts_ok = B_TRUE;
15384 			}
15385 
15386 			/*
15387 			 * tcp_snd_sack_ok can be set in
15388 			 * tcp_adapt_ire() if the sack metric
15389 			 * is set.  So check it here also.
15390 			 */
15391 			if (tcp_sack_permitted == 2 ||
15392 			    tcp->tcp_snd_sack_ok) {
15393 				if (tcp->tcp_sack_info == NULL) {
15394 					tcp->tcp_sack_info =
15395 					kmem_cache_alloc(tcp_sack_info_cache,
15396 					    KM_SLEEP);
15397 				}
15398 				tcp->tcp_snd_sack_ok = B_TRUE;
15399 			}
15400 
15401 			/*
15402 			 * Should we use ECN?  Note that the current
15403 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15404 			 * is 1.  The reason for doing this is that there
15405 			 * are equipments out there that will drop ECN
15406 			 * enabled IP packets.  Setting it to 1 avoids
15407 			 * compatibility problems.
15408 			 */
15409 			if (tcp_ecn_permitted == 2)
15410 				tcp->tcp_ecn_ok = B_TRUE;
15411 
15412 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15413 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15414 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15415 			if (syn_mp) {
15416 				cred_t *cr;
15417 				pid_t pid;
15418 
15419 				/*
15420 				 * Obtain the credential from the
15421 				 * thread calling connect(); the credential
15422 				 * lives on in the second mblk which
15423 				 * originated from T_CONN_REQ and is echoed
15424 				 * with the T_BIND_ACK from ip.  If none
15425 				 * can be found, default to the creator
15426 				 * of the socket.
15427 				 */
15428 				if (mp->b_cont == NULL ||
15429 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15430 					cr = tcp->tcp_cred;
15431 					pid = tcp->tcp_cpid;
15432 				} else {
15433 					pid = DB_CPID(mp->b_cont);
15434 				}
15435 
15436 				TCP_RECORD_TRACE(tcp, syn_mp,
15437 				    TCP_TRACE_SEND_PKT);
15438 				mblk_setcred(syn_mp, cr);
15439 				DB_CPID(syn_mp) = pid;
15440 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15441 			}
15442 		after_syn_sent:
15443 			/*
15444 			 * A trailer mblk indicates a waiting client upstream.
15445 			 * We complete here the processing begun in
15446 			 * either tcp_bind() or tcp_connect() by passing
15447 			 * upstream the reply message they supplied.
15448 			 */
15449 			mp1 = mp;
15450 			mp = mp->b_cont;
15451 			freeb(mp1);
15452 			if (mp)
15453 				break;
15454 			return;
15455 		case T_ERROR_ACK:
15456 			if (tcp->tcp_debug) {
15457 				(void) strlog(TCP_MOD_ID, 0, 1,
15458 				    SL_TRACE|SL_ERROR,
15459 				    "tcp_rput_other: case T_ERROR_ACK, "
15460 				    "ERROR_prim == %d",
15461 				    tea->ERROR_prim);
15462 			}
15463 			switch (tea->ERROR_prim) {
15464 			case O_T_BIND_REQ:
15465 			case T_BIND_REQ:
15466 				tcp_bind_failed(tcp, mp,
15467 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15468 				    ENETUNREACH : EADDRNOTAVAIL));
15469 				return;
15470 			case T_UNBIND_REQ:
15471 				tcp->tcp_hard_binding = B_FALSE;
15472 				tcp->tcp_hard_bound = B_FALSE;
15473 				if (mp->b_cont) {
15474 					freemsg(mp->b_cont);
15475 					mp->b_cont = NULL;
15476 				}
15477 				if (tcp->tcp_unbind_pending)
15478 					tcp->tcp_unbind_pending = 0;
15479 				else {
15480 					/* From tcp_ip_unbind() - free */
15481 					freemsg(mp);
15482 					return;
15483 				}
15484 				break;
15485 			case T_SVR4_OPTMGMT_REQ:
15486 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15487 					/* T_OPTMGMT_REQ generated by TCP */
15488 					printf("T_SVR4_OPTMGMT_REQ failed "
15489 					    "%d/%d - dropped (cnt %d)\n",
15490 					    tea->TLI_error, tea->UNIX_error,
15491 					    tcp->tcp_drop_opt_ack_cnt);
15492 					freemsg(mp);
15493 					tcp->tcp_drop_opt_ack_cnt--;
15494 					return;
15495 				}
15496 				break;
15497 			}
15498 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15499 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15500 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15501 				    "- dropped (cnt %d)\n",
15502 				    tea->TLI_error, tea->UNIX_error,
15503 				    tcp->tcp_drop_opt_ack_cnt);
15504 				freemsg(mp);
15505 				tcp->tcp_drop_opt_ack_cnt--;
15506 				return;
15507 			}
15508 			break;
15509 		case T_OPTMGMT_ACK:
15510 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15511 				/* T_OPTMGMT_REQ generated by TCP */
15512 				freemsg(mp);
15513 				tcp->tcp_drop_opt_ack_cnt--;
15514 				return;
15515 			}
15516 			break;
15517 		default:
15518 			break;
15519 		}
15520 		break;
15521 	case M_CTL:
15522 		/*
15523 		 * ICMP messages.
15524 		 */
15525 		tcp_icmp_error(tcp, mp);
15526 		return;
15527 	case M_FLUSH:
15528 		if (*rptr & FLUSHR)
15529 			flushq(q, FLUSHDATA);
15530 		break;
15531 	default:
15532 		break;
15533 	}
15534 	/*
15535 	 * Make sure we set this bit before sending the ACK for
15536 	 * bind. Otherwise accept could possibly run and free
15537 	 * this tcp struct.
15538 	 */
15539 	putnext(q, mp);
15540 }
15541 
15542 /*
15543  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15544  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15545  * tcp_rsrv() try again.
15546  */
15547 static void
15548 tcp_ordrel_kick(void *arg)
15549 {
15550 	conn_t 	*connp = (conn_t *)arg;
15551 	tcp_t	*tcp = connp->conn_tcp;
15552 
15553 	tcp->tcp_ordrelid = 0;
15554 	tcp->tcp_timeout = B_FALSE;
15555 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15556 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15557 		qenable(tcp->tcp_rq);
15558 	}
15559 }
15560 
15561 /* ARGSUSED */
15562 static void
15563 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15564 {
15565 	conn_t	*connp = (conn_t *)arg;
15566 	tcp_t	*tcp = connp->conn_tcp;
15567 	queue_t	*q = tcp->tcp_rq;
15568 	uint_t	thwin;
15569 
15570 	freeb(mp);
15571 
15572 	TCP_STAT(tcp_rsrv_calls);
15573 
15574 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15575 		return;
15576 	}
15577 
15578 	if (tcp->tcp_fused) {
15579 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15580 
15581 		ASSERT(tcp->tcp_fused);
15582 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15583 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15584 		ASSERT(!TCP_IS_DETACHED(tcp));
15585 		ASSERT(tcp->tcp_connp->conn_sqp ==
15586 		    peer_tcp->tcp_connp->conn_sqp);
15587 
15588 		/*
15589 		 * Normally we would not get backenabled in synchronous
15590 		 * streams mode, but in case this happens, we need to plug
15591 		 * synchronous streams during our drain to prevent a race
15592 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15593 		 */
15594 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15595 		if (tcp->tcp_rcv_list != NULL)
15596 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15597 
15598 		tcp_clrqfull(peer_tcp);
15599 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15600 		TCP_STAT(tcp_fusion_backenabled);
15601 		return;
15602 	}
15603 
15604 	if (canputnext(q)) {
15605 		tcp->tcp_rwnd = q->q_hiwat;
15606 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15607 		    << tcp->tcp_rcv_ws;
15608 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15609 		/*
15610 		 * Send back a window update immediately if TCP is above
15611 		 * ESTABLISHED state and the increase of the rcv window
15612 		 * that the other side knows is at least 1 MSS after flow
15613 		 * control is lifted.
15614 		 */
15615 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15616 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15617 			tcp_xmit_ctl(NULL, tcp,
15618 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15619 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15620 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
15621 		}
15622 	}
15623 	/* Handle a failure to allocate a T_ORDREL_IND here */
15624 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15625 		ASSERT(tcp->tcp_listener == NULL);
15626 		if (tcp->tcp_rcv_list != NULL) {
15627 			(void) tcp_rcv_drain(q, tcp);
15628 		}
15629 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15630 		mp = mi_tpi_ordrel_ind();
15631 		if (mp) {
15632 			tcp->tcp_ordrel_done = B_TRUE;
15633 			putnext(q, mp);
15634 			if (tcp->tcp_deferred_clean_death) {
15635 				/*
15636 				 * tcp_clean_death was deferred for
15637 				 * T_ORDREL_IND - do it now
15638 				 */
15639 				tcp->tcp_deferred_clean_death = B_FALSE;
15640 				(void) tcp_clean_death(tcp,
15641 				    tcp->tcp_client_errno, 22);
15642 			}
15643 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15644 			/*
15645 			 * If there isn't already a timer running
15646 			 * start one.  Use a 4 second
15647 			 * timer as a fallback since it can't fail.
15648 			 */
15649 			tcp->tcp_timeout = B_TRUE;
15650 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15651 			    MSEC_TO_TICK(4000));
15652 		}
15653 	}
15654 }
15655 
15656 /*
15657  * The read side service routine is called mostly when we get back-enabled as a
15658  * result of flow control relief.  Since we don't actually queue anything in
15659  * TCP, we have no data to send out of here.  What we do is clear the receive
15660  * window, and send out a window update.
15661  * This routine is also called to drive an orderly release message upstream
15662  * if the attempt in tcp_rput failed.
15663  */
15664 static void
15665 tcp_rsrv(queue_t *q)
15666 {
15667 	conn_t *connp = Q_TO_CONN(q);
15668 	tcp_t	*tcp = connp->conn_tcp;
15669 	mblk_t	*mp;
15670 
15671 	/* No code does a putq on the read side */
15672 	ASSERT(q->q_first == NULL);
15673 
15674 	/* Nothing to do for the default queue */
15675 	if (q == tcp_g_q) {
15676 		return;
15677 	}
15678 
15679 	mp = allocb(0, BPRI_HI);
15680 	if (mp == NULL) {
15681 		/*
15682 		 * We are under memory pressure. Return for now and we
15683 		 * we will be called again later.
15684 		 */
15685 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15686 			/*
15687 			 * If there isn't already a timer running
15688 			 * start one.  Use a 4 second
15689 			 * timer as a fallback since it can't fail.
15690 			 */
15691 			tcp->tcp_timeout = B_TRUE;
15692 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15693 			    MSEC_TO_TICK(4000));
15694 		}
15695 		return;
15696 	}
15697 	CONN_INC_REF(connp);
15698 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15699 	    SQTAG_TCP_RSRV);
15700 }
15701 
15702 /*
15703  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15704  * We do not allow the receive window to shrink.  After setting rwnd,
15705  * set the flow control hiwat of the stream.
15706  *
15707  * This function is called in 2 cases:
15708  *
15709  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15710  *    connection (passive open) and in tcp_rput_data() for active connect.
15711  *    This is called after tcp_mss_set() when the desired MSS value is known.
15712  *    This makes sure that our window size is a mutiple of the other side's
15713  *    MSS.
15714  * 2) Handling SO_RCVBUF option.
15715  *
15716  * It is ASSUMED that the requested size is a multiple of the current MSS.
15717  *
15718  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15719  * user requests so.
15720  */
15721 static int
15722 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15723 {
15724 	uint32_t	mss = tcp->tcp_mss;
15725 	uint32_t	old_max_rwnd;
15726 	uint32_t	max_transmittable_rwnd;
15727 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15728 
15729 	if (tcp->tcp_fused) {
15730 		size_t sth_hiwat;
15731 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15732 
15733 		ASSERT(peer_tcp != NULL);
15734 		/*
15735 		 * Record the stream head's high water mark for
15736 		 * this endpoint; this is used for flow-control
15737 		 * purposes in tcp_fuse_output().
15738 		 */
15739 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15740 		if (!tcp_detached)
15741 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
15742 
15743 		/*
15744 		 * In the fusion case, the maxpsz stream head value of
15745 		 * our peer is set according to its send buffer size
15746 		 * and our receive buffer size; since the latter may
15747 		 * have changed we need to update the peer's maxpsz.
15748 		 */
15749 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15750 		return (rwnd);
15751 	}
15752 
15753 	if (tcp_detached)
15754 		old_max_rwnd = tcp->tcp_rwnd;
15755 	else
15756 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
15757 
15758 	/*
15759 	 * Insist on a receive window that is at least
15760 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15761 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15762 	 * and delayed acknowledgement.
15763 	 */
15764 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
15765 
15766 	/*
15767 	 * If window size info has already been exchanged, TCP should not
15768 	 * shrink the window.  Shrinking window is doable if done carefully.
15769 	 * We may add that support later.  But so far there is not a real
15770 	 * need to do that.
15771 	 */
15772 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15773 		/* MSS may have changed, do a round up again. */
15774 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15775 	}
15776 
15777 	/*
15778 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15779 	 * can be applied even before the window scale option is decided.
15780 	 */
15781 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15782 	if (rwnd > max_transmittable_rwnd) {
15783 		rwnd = max_transmittable_rwnd -
15784 		    (max_transmittable_rwnd % mss);
15785 		if (rwnd < mss)
15786 			rwnd = max_transmittable_rwnd;
15787 		/*
15788 		 * If we're over the limit we may have to back down tcp_rwnd.
15789 		 * The increment below won't work for us. So we set all three
15790 		 * here and the increment below will have no effect.
15791 		 */
15792 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15793 	}
15794 	if (tcp->tcp_localnet) {
15795 		tcp->tcp_rack_abs_max =
15796 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
15797 	} else {
15798 		/*
15799 		 * For a remote host on a different subnet (through a router),
15800 		 * we ack every other packet to be conforming to RFC1122.
15801 		 * tcp_deferred_acks_max is default to 2.
15802 		 */
15803 		tcp->tcp_rack_abs_max =
15804 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
15805 	}
15806 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15807 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15808 	else
15809 		tcp->tcp_rack_cur_max = 0;
15810 	/*
15811 	 * Increment the current rwnd by the amount the maximum grew (we
15812 	 * can not overwrite it since we might be in the middle of a
15813 	 * connection.)
15814 	 */
15815 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15816 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15817 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15818 		tcp->tcp_cwnd_max = rwnd;
15819 
15820 	if (tcp_detached)
15821 		return (rwnd);
15822 	/*
15823 	 * We set the maximum receive window into rq->q_hiwat.
15824 	 * This is not actually used for flow control.
15825 	 */
15826 	tcp->tcp_rq->q_hiwat = rwnd;
15827 	/*
15828 	 * Set the Stream head high water mark. This doesn't have to be
15829 	 * here, since we are simply using default values, but we would
15830 	 * prefer to choose these values algorithmically, with a likely
15831 	 * relationship to rwnd.
15832 	 */
15833 	(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd, tcp_sth_rcv_hiwat));
15834 	return (rwnd);
15835 }
15836 
15837 /*
15838  * Return SNMP stuff in buffer in mpdata.
15839  */
15840 int
15841 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15842 {
15843 	mblk_t			*mpdata;
15844 	mblk_t			*mp_conn_ctl = NULL;
15845 	mblk_t			*mp_conn_tail;
15846 	mblk_t			*mp_attr_ctl = NULL;
15847 	mblk_t			*mp_attr_tail;
15848 	mblk_t			*mp6_conn_ctl = NULL;
15849 	mblk_t			*mp6_conn_tail;
15850 	mblk_t			*mp6_attr_ctl = NULL;
15851 	mblk_t			*mp6_attr_tail;
15852 	struct opthdr		*optp;
15853 	mib2_tcpConnEntry_t	tce;
15854 	mib2_tcp6ConnEntry_t	tce6;
15855 	mib2_transportMLPEntry_t mlp;
15856 	connf_t			*connfp;
15857 	conn_t			*connp;
15858 	int			i;
15859 	boolean_t 		ispriv;
15860 	zoneid_t 		zoneid;
15861 	int			v4_conn_idx;
15862 	int			v6_conn_idx;
15863 
15864 	if (mpctl == NULL ||
15865 	    (mpdata = mpctl->b_cont) == NULL ||
15866 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15867 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
15868 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
15869 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
15870 		freemsg(mp_conn_ctl);
15871 		freemsg(mp_attr_ctl);
15872 		freemsg(mp6_conn_ctl);
15873 		freemsg(mp6_attr_ctl);
15874 		return (0);
15875 	}
15876 
15877 	/* build table of connections -- need count in fixed part */
15878 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
15879 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
15880 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
15881 	SET_MIB(tcp_mib.tcpMaxConn, -1);
15882 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
15883 
15884 	ispriv =
15885 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15886 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15887 
15888 	v4_conn_idx = v6_conn_idx = 0;
15889 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
15890 
15891 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15892 
15893 		connfp = &ipcl_globalhash_fanout[i];
15894 
15895 		connp = NULL;
15896 
15897 		while ((connp =
15898 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15899 			tcp_t *tcp;
15900 			boolean_t needattr;
15901 
15902 			if (connp->conn_zoneid != zoneid)
15903 				continue;	/* not in this zone */
15904 
15905 			tcp = connp->conn_tcp;
15906 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
15907 			tcp->tcp_ibsegs = 0;
15908 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
15909 			tcp->tcp_obsegs = 0;
15910 
15911 			tce6.tcp6ConnState = tce.tcpConnState =
15912 			    tcp_snmp_state(tcp);
15913 			if (tce.tcpConnState == MIB2_TCP_established ||
15914 			    tce.tcpConnState == MIB2_TCP_closeWait)
15915 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
15916 
15917 			needattr = B_FALSE;
15918 			bzero(&mlp, sizeof (mlp));
15919 			if (connp->conn_mlp_type != mlptSingle) {
15920 				if (connp->conn_mlp_type == mlptShared ||
15921 				    connp->conn_mlp_type == mlptBoth)
15922 					mlp.tme_flags |= MIB2_TMEF_SHARED;
15923 				if (connp->conn_mlp_type == mlptPrivate ||
15924 				    connp->conn_mlp_type == mlptBoth)
15925 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
15926 				needattr = B_TRUE;
15927 			}
15928 			if (connp->conn_peercred != NULL) {
15929 				ts_label_t *tsl;
15930 
15931 				tsl = crgetlabel(connp->conn_peercred);
15932 				mlp.tme_doi = label2doi(tsl);
15933 				mlp.tme_label = *label2bslabel(tsl);
15934 				needattr = B_TRUE;
15935 			}
15936 
15937 			/* Create a message to report on IPv6 entries */
15938 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15939 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15940 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15941 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15942 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15943 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15944 			/* Don't want just anybody seeing these... */
15945 			if (ispriv) {
15946 				tce6.tcp6ConnEntryInfo.ce_snxt =
15947 				    tcp->tcp_snxt;
15948 				tce6.tcp6ConnEntryInfo.ce_suna =
15949 				    tcp->tcp_suna;
15950 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15951 				    tcp->tcp_rnxt;
15952 				tce6.tcp6ConnEntryInfo.ce_rack =
15953 				    tcp->tcp_rack;
15954 			} else {
15955 				/*
15956 				 * Netstat, unfortunately, uses this to
15957 				 * get send/receive queue sizes.  How to fix?
15958 				 * Why not compute the difference only?
15959 				 */
15960 				tce6.tcp6ConnEntryInfo.ce_snxt =
15961 				    tcp->tcp_snxt - tcp->tcp_suna;
15962 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
15963 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15964 				    tcp->tcp_rnxt - tcp->tcp_rack;
15965 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
15966 			}
15967 
15968 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15969 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15970 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
15971 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
15972 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
15973 
15974 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
15975 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
15976 
15977 			mlp.tme_connidx = v6_conn_idx++;
15978 			if (needattr)
15979 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
15980 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
15981 			}
15982 			/*
15983 			 * Create an IPv4 table entry for IPv4 entries and also
15984 			 * for IPv6 entries which are bound to in6addr_any
15985 			 * but don't have IPV6_V6ONLY set.
15986 			 * (i.e. anything an IPv4 peer could connect to)
15987 			 */
15988 			if (tcp->tcp_ipversion == IPV4_VERSION ||
15989 			    (tcp->tcp_state <= TCPS_LISTEN &&
15990 			    !tcp->tcp_connp->conn_ipv6_v6only &&
15991 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
15992 				if (tcp->tcp_ipversion == IPV6_VERSION) {
15993 					tce.tcpConnRemAddress = INADDR_ANY;
15994 					tce.tcpConnLocalAddress = INADDR_ANY;
15995 				} else {
15996 					tce.tcpConnRemAddress =
15997 					    tcp->tcp_remote;
15998 					tce.tcpConnLocalAddress =
15999 					    tcp->tcp_ip_src;
16000 				}
16001 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16002 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16003 				/* Don't want just anybody seeing these... */
16004 				if (ispriv) {
16005 					tce.tcpConnEntryInfo.ce_snxt =
16006 					    tcp->tcp_snxt;
16007 					tce.tcpConnEntryInfo.ce_suna =
16008 					    tcp->tcp_suna;
16009 					tce.tcpConnEntryInfo.ce_rnxt =
16010 					    tcp->tcp_rnxt;
16011 					tce.tcpConnEntryInfo.ce_rack =
16012 					    tcp->tcp_rack;
16013 				} else {
16014 					/*
16015 					 * Netstat, unfortunately, uses this to
16016 					 * get send/receive queue sizes.  How
16017 					 * to fix?
16018 					 * Why not compute the difference only?
16019 					 */
16020 					tce.tcpConnEntryInfo.ce_snxt =
16021 					    tcp->tcp_snxt - tcp->tcp_suna;
16022 					tce.tcpConnEntryInfo.ce_suna = 0;
16023 					tce.tcpConnEntryInfo.ce_rnxt =
16024 					    tcp->tcp_rnxt - tcp->tcp_rack;
16025 					tce.tcpConnEntryInfo.ce_rack = 0;
16026 				}
16027 
16028 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16029 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16030 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16031 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16032 				tce.tcpConnEntryInfo.ce_state =
16033 				    tcp->tcp_state;
16034 
16035 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16036 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16037 
16038 				mlp.tme_connidx = v4_conn_idx++;
16039 				if (needattr)
16040 					(void) snmp_append_data2(
16041 					    mp_attr_ctl->b_cont,
16042 					    &mp_attr_tail, (char *)&mlp,
16043 					    sizeof (mlp));
16044 			}
16045 		}
16046 	}
16047 
16048 	/* fixed length structure for IPv4 and IPv6 counters */
16049 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16050 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
16051 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16052 	optp->level = MIB2_TCP;
16053 	optp->name = 0;
16054 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
16055 	optp->len = msgdsize(mpdata);
16056 	qreply(q, mpctl);
16057 
16058 	/* table of connections... */
16059 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16060 	    sizeof (struct T_optmgmt_ack)];
16061 	optp->level = MIB2_TCP;
16062 	optp->name = MIB2_TCP_CONN;
16063 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16064 	qreply(q, mp_conn_ctl);
16065 
16066 	/* table of MLP attributes... */
16067 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16068 	    sizeof (struct T_optmgmt_ack)];
16069 	optp->level = MIB2_TCP;
16070 	optp->name = EXPER_XPORT_MLP;
16071 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16072 	if (optp->len == 0)
16073 		freemsg(mp_attr_ctl);
16074 	else
16075 		qreply(q, mp_attr_ctl);
16076 
16077 	/* table of IPv6 connections... */
16078 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16079 	    sizeof (struct T_optmgmt_ack)];
16080 	optp->level = MIB2_TCP6;
16081 	optp->name = MIB2_TCP6_CONN;
16082 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16083 	qreply(q, mp6_conn_ctl);
16084 
16085 	/* table of IPv6 MLP attributes... */
16086 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16087 	    sizeof (struct T_optmgmt_ack)];
16088 	optp->level = MIB2_TCP6;
16089 	optp->name = EXPER_XPORT_MLP;
16090 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16091 	if (optp->len == 0)
16092 		freemsg(mp6_attr_ctl);
16093 	else
16094 		qreply(q, mp6_attr_ctl);
16095 	return (1);
16096 }
16097 
16098 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16099 /* ARGSUSED */
16100 int
16101 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16102 {
16103 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16104 
16105 	switch (level) {
16106 	case MIB2_TCP:
16107 		switch (name) {
16108 		case 13:
16109 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16110 				return (0);
16111 			/* TODO: delete entry defined by tce */
16112 			return (1);
16113 		default:
16114 			return (0);
16115 		}
16116 	default:
16117 		return (1);
16118 	}
16119 }
16120 
16121 /* Translate TCP state to MIB2 TCP state. */
16122 static int
16123 tcp_snmp_state(tcp_t *tcp)
16124 {
16125 	if (tcp == NULL)
16126 		return (0);
16127 
16128 	switch (tcp->tcp_state) {
16129 	case TCPS_CLOSED:
16130 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16131 	case TCPS_BOUND:
16132 		return (MIB2_TCP_closed);
16133 	case TCPS_LISTEN:
16134 		return (MIB2_TCP_listen);
16135 	case TCPS_SYN_SENT:
16136 		return (MIB2_TCP_synSent);
16137 	case TCPS_SYN_RCVD:
16138 		return (MIB2_TCP_synReceived);
16139 	case TCPS_ESTABLISHED:
16140 		return (MIB2_TCP_established);
16141 	case TCPS_CLOSE_WAIT:
16142 		return (MIB2_TCP_closeWait);
16143 	case TCPS_FIN_WAIT_1:
16144 		return (MIB2_TCP_finWait1);
16145 	case TCPS_CLOSING:
16146 		return (MIB2_TCP_closing);
16147 	case TCPS_LAST_ACK:
16148 		return (MIB2_TCP_lastAck);
16149 	case TCPS_FIN_WAIT_2:
16150 		return (MIB2_TCP_finWait2);
16151 	case TCPS_TIME_WAIT:
16152 		return (MIB2_TCP_timeWait);
16153 	default:
16154 		return (0);
16155 	}
16156 }
16157 
16158 static char tcp_report_header[] =
16159 	"TCP     " MI_COL_HDRPAD_STR
16160 	"zone dest            snxt     suna     "
16161 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16162 	"recent   [lport,fport] state";
16163 
16164 /*
16165  * TCP status report triggered via the Named Dispatch mechanism.
16166  */
16167 /* ARGSUSED */
16168 static void
16169 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16170     cred_t *cr)
16171 {
16172 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16173 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
16174 	char cflag;
16175 	in6_addr_t	v6dst;
16176 	char buf[80];
16177 	uint_t print_len, buf_len;
16178 
16179 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16180 	if (buf_len <= 0)
16181 		return;
16182 
16183 	if (hashval >= 0)
16184 		(void) sprintf(hash, "%03d ", hashval);
16185 	else
16186 		hash[0] = '\0';
16187 
16188 	/*
16189 	 * Note that we use the remote address in the tcp_b  structure.
16190 	 * This means that it will print out the real destination address,
16191 	 * not the next hop's address if source routing is used.  This
16192 	 * avoid the confusion on the output because user may not
16193 	 * know that source routing is used for a connection.
16194 	 */
16195 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16196 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16197 	} else {
16198 		v6dst = tcp->tcp_remote_v6;
16199 	}
16200 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16201 	/*
16202 	 * the ispriv checks are so that normal users cannot determine
16203 	 * sequence number information using NDD.
16204 	 */
16205 
16206 	if (TCP_IS_DETACHED(tcp))
16207 		cflag = '*';
16208 	else
16209 		cflag = ' ';
16210 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16211 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16212 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16213 	    hash,
16214 	    (void *)tcp,
16215 	    tcp->tcp_connp->conn_zoneid,
16216 	    addrbuf,
16217 	    (ispriv) ? tcp->tcp_snxt : 0,
16218 	    (ispriv) ? tcp->tcp_suna : 0,
16219 	    tcp->tcp_swnd,
16220 	    (ispriv) ? tcp->tcp_rnxt : 0,
16221 	    (ispriv) ? tcp->tcp_rack : 0,
16222 	    tcp->tcp_rwnd,
16223 	    tcp->tcp_rto,
16224 	    tcp->tcp_mss,
16225 	    tcp->tcp_snd_ws_ok,
16226 	    tcp->tcp_snd_ws,
16227 	    tcp->tcp_rcv_ws,
16228 	    tcp->tcp_snd_ts_ok,
16229 	    tcp->tcp_ts_recent,
16230 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16231 	if (print_len < buf_len) {
16232 		((mblk_t *)mp)->b_wptr += print_len;
16233 	} else {
16234 		((mblk_t *)mp)->b_wptr += buf_len;
16235 	}
16236 }
16237 
16238 /*
16239  * TCP status report (for listeners only) triggered via the Named Dispatch
16240  * mechanism.
16241  */
16242 /* ARGSUSED */
16243 static void
16244 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16245 {
16246 	char addrbuf[INET6_ADDRSTRLEN];
16247 	in6_addr_t	v6dst;
16248 	uint_t print_len, buf_len;
16249 
16250 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16251 	if (buf_len <= 0)
16252 		return;
16253 
16254 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16255 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16256 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16257 	} else {
16258 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16259 		    addrbuf, sizeof (addrbuf));
16260 	}
16261 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16262 	    "%03d "
16263 	    MI_COL_PTRFMT_STR
16264 	    "%d %s %05u %08u %d/%d/%d%c\n",
16265 	    hashval, (void *)tcp,
16266 	    tcp->tcp_connp->conn_zoneid,
16267 	    addrbuf,
16268 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16269 	    tcp->tcp_conn_req_seqnum,
16270 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16271 	    tcp->tcp_conn_req_max,
16272 	    tcp->tcp_syn_defense ? '*' : ' ');
16273 	if (print_len < buf_len) {
16274 		((mblk_t *)mp)->b_wptr += print_len;
16275 	} else {
16276 		((mblk_t *)mp)->b_wptr += buf_len;
16277 	}
16278 }
16279 
16280 /* TCP status report triggered via the Named Dispatch mechanism. */
16281 /* ARGSUSED */
16282 static int
16283 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16284 {
16285 	tcp_t	*tcp;
16286 	int	i;
16287 	conn_t	*connp;
16288 	connf_t	*connfp;
16289 	zoneid_t zoneid;
16290 
16291 	/*
16292 	 * Because of the ndd constraint, at most we can have 64K buffer
16293 	 * to put in all TCP info.  So to be more efficient, just
16294 	 * allocate a 64K buffer here, assuming we need that large buffer.
16295 	 * This may be a problem as any user can read tcp_status.  Therefore
16296 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16297 	 * This should be OK as normal users should not do this too often.
16298 	 */
16299 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16300 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16301 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16302 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16303 			return (0);
16304 		}
16305 	}
16306 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16307 		/* The following may work even if we cannot get a large buf. */
16308 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16309 		return (0);
16310 	}
16311 
16312 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16313 
16314 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16315 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16316 
16317 		connfp = &ipcl_globalhash_fanout[i];
16318 
16319 		connp = NULL;
16320 
16321 		while ((connp =
16322 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16323 			tcp = connp->conn_tcp;
16324 			if (zoneid != GLOBAL_ZONEID &&
16325 			    zoneid != connp->conn_zoneid)
16326 				continue;
16327 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16328 			    cr);
16329 		}
16330 
16331 	}
16332 
16333 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16334 	return (0);
16335 }
16336 
16337 /* TCP status report triggered via the Named Dispatch mechanism. */
16338 /* ARGSUSED */
16339 static int
16340 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16341 {
16342 	tf_t	*tbf;
16343 	tcp_t	*tcp;
16344 	int	i;
16345 	zoneid_t zoneid;
16346 
16347 	/* Refer to comments in tcp_status_report(). */
16348 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16349 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16350 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16351 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16352 			return (0);
16353 		}
16354 	}
16355 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16356 		/* The following may work even if we cannot get a large buf. */
16357 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16358 		return (0);
16359 	}
16360 
16361 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16362 
16363 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16364 
16365 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
16366 		tbf = &tcp_bind_fanout[i];
16367 		mutex_enter(&tbf->tf_lock);
16368 		for (tcp = tbf->tf_tcp; tcp != NULL;
16369 		    tcp = tcp->tcp_bind_hash) {
16370 			if (zoneid != GLOBAL_ZONEID &&
16371 			    zoneid != tcp->tcp_connp->conn_zoneid)
16372 				continue;
16373 			CONN_INC_REF(tcp->tcp_connp);
16374 			tcp_report_item(mp->b_cont, tcp, i,
16375 			    Q_TO_TCP(q), cr);
16376 			CONN_DEC_REF(tcp->tcp_connp);
16377 		}
16378 		mutex_exit(&tbf->tf_lock);
16379 	}
16380 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16381 	return (0);
16382 }
16383 
16384 /* TCP status report triggered via the Named Dispatch mechanism. */
16385 /* ARGSUSED */
16386 static int
16387 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16388 {
16389 	connf_t	*connfp;
16390 	conn_t	*connp;
16391 	tcp_t	*tcp;
16392 	int	i;
16393 	zoneid_t zoneid;
16394 
16395 	/* Refer to comments in tcp_status_report(). */
16396 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16397 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16398 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16399 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16400 			return (0);
16401 		}
16402 	}
16403 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16404 		/* The following may work even if we cannot get a large buf. */
16405 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16406 		return (0);
16407 	}
16408 
16409 	(void) mi_mpprintf(mp,
16410 	    "    TCP    " MI_COL_HDRPAD_STR
16411 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16412 
16413 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16414 
16415 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
16416 		connfp =  &ipcl_bind_fanout[i];
16417 		connp = NULL;
16418 		while ((connp =
16419 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16420 			tcp = connp->conn_tcp;
16421 			if (zoneid != GLOBAL_ZONEID &&
16422 			    zoneid != connp->conn_zoneid)
16423 				continue;
16424 			tcp_report_listener(mp->b_cont, tcp, i);
16425 		}
16426 	}
16427 
16428 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16429 	return (0);
16430 }
16431 
16432 /* TCP status report triggered via the Named Dispatch mechanism. */
16433 /* ARGSUSED */
16434 static int
16435 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16436 {
16437 	connf_t	*connfp;
16438 	conn_t	*connp;
16439 	tcp_t	*tcp;
16440 	int	i;
16441 	zoneid_t zoneid;
16442 
16443 	/* Refer to comments in tcp_status_report(). */
16444 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16445 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16446 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16447 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16448 			return (0);
16449 		}
16450 	}
16451 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16452 		/* The following may work even if we cannot get a large buf. */
16453 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16454 		return (0);
16455 	}
16456 
16457 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16458 	    ipcl_conn_fanout_size);
16459 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16460 
16461 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16462 
16463 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
16464 		connfp =  &ipcl_conn_fanout[i];
16465 		connp = NULL;
16466 		while ((connp =
16467 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16468 			tcp = connp->conn_tcp;
16469 			if (zoneid != GLOBAL_ZONEID &&
16470 			    zoneid != connp->conn_zoneid)
16471 				continue;
16472 			tcp_report_item(mp->b_cont, tcp, i,
16473 			    Q_TO_TCP(q), cr);
16474 		}
16475 	}
16476 
16477 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16478 	return (0);
16479 }
16480 
16481 /* TCP status report triggered via the Named Dispatch mechanism. */
16482 /* ARGSUSED */
16483 static int
16484 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16485 {
16486 	tf_t	*tf;
16487 	tcp_t	*tcp;
16488 	int	i;
16489 	zoneid_t zoneid;
16490 
16491 	/* Refer to comments in tcp_status_report(). */
16492 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16493 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16494 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16495 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16496 			return (0);
16497 		}
16498 	}
16499 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16500 		/* The following may work even if we cannot get a large buf. */
16501 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16502 		return (0);
16503 	}
16504 
16505 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16506 
16507 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16508 
16509 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16510 		tf = &tcp_acceptor_fanout[i];
16511 		mutex_enter(&tf->tf_lock);
16512 		for (tcp = tf->tf_tcp; tcp != NULL;
16513 		    tcp = tcp->tcp_acceptor_hash) {
16514 			if (zoneid != GLOBAL_ZONEID &&
16515 			    zoneid != tcp->tcp_connp->conn_zoneid)
16516 				continue;
16517 			tcp_report_item(mp->b_cont, tcp, i,
16518 			    Q_TO_TCP(q), cr);
16519 		}
16520 		mutex_exit(&tf->tf_lock);
16521 	}
16522 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16523 	return (0);
16524 }
16525 
16526 /*
16527  * tcp_timer is the timer service routine.  It handles the retransmission,
16528  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16529  * from the state of the tcp instance what kind of action needs to be done
16530  * at the time it is called.
16531  */
16532 static void
16533 tcp_timer(void *arg)
16534 {
16535 	mblk_t		*mp;
16536 	clock_t		first_threshold;
16537 	clock_t		second_threshold;
16538 	clock_t		ms;
16539 	uint32_t	mss;
16540 	conn_t		*connp = (conn_t *)arg;
16541 	tcp_t		*tcp = connp->conn_tcp;
16542 
16543 	tcp->tcp_timer_tid = 0;
16544 
16545 	if (tcp->tcp_fused)
16546 		return;
16547 
16548 	first_threshold =  tcp->tcp_first_timer_threshold;
16549 	second_threshold = tcp->tcp_second_timer_threshold;
16550 	switch (tcp->tcp_state) {
16551 	case TCPS_IDLE:
16552 	case TCPS_BOUND:
16553 	case TCPS_LISTEN:
16554 		return;
16555 	case TCPS_SYN_RCVD: {
16556 		tcp_t	*listener = tcp->tcp_listener;
16557 
16558 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16559 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16560 			/* it's our first timeout */
16561 			tcp->tcp_syn_rcvd_timeout = 1;
16562 			mutex_enter(&listener->tcp_eager_lock);
16563 			listener->tcp_syn_rcvd_timeout++;
16564 			if (!listener->tcp_syn_defense &&
16565 			    (listener->tcp_syn_rcvd_timeout >
16566 			    (tcp_conn_req_max_q0 >> 2)) &&
16567 			    (tcp_conn_req_max_q0 > 200)) {
16568 				/* We may be under attack. Put on a defense. */
16569 				listener->tcp_syn_defense = B_TRUE;
16570 				cmn_err(CE_WARN, "High TCP connect timeout "
16571 				    "rate! System (port %d) may be under a "
16572 				    "SYN flood attack!",
16573 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16574 
16575 				listener->tcp_ip_addr_cache = kmem_zalloc(
16576 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16577 				    KM_NOSLEEP);
16578 			}
16579 			mutex_exit(&listener->tcp_eager_lock);
16580 		}
16581 	}
16582 		/* FALLTHRU */
16583 	case TCPS_SYN_SENT:
16584 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16585 		second_threshold = tcp->tcp_second_ctimer_threshold;
16586 		break;
16587 	case TCPS_ESTABLISHED:
16588 	case TCPS_FIN_WAIT_1:
16589 	case TCPS_CLOSING:
16590 	case TCPS_CLOSE_WAIT:
16591 	case TCPS_LAST_ACK:
16592 		/* If we have data to rexmit */
16593 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16594 			clock_t	time_to_wait;
16595 
16596 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16597 			if (!tcp->tcp_xmit_head)
16598 				break;
16599 			time_to_wait = lbolt -
16600 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16601 			time_to_wait = tcp->tcp_rto -
16602 			    TICK_TO_MSEC(time_to_wait);
16603 			/*
16604 			 * If the timer fires too early, 1 clock tick earlier,
16605 			 * restart the timer.
16606 			 */
16607 			if (time_to_wait > msec_per_tick) {
16608 				TCP_STAT(tcp_timer_fire_early);
16609 				TCP_TIMER_RESTART(tcp, time_to_wait);
16610 				return;
16611 			}
16612 			/*
16613 			 * When we probe zero windows, we force the swnd open.
16614 			 * If our peer acks with a closed window swnd will be
16615 			 * set to zero by tcp_rput(). As long as we are
16616 			 * receiving acks tcp_rput will
16617 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16618 			 * first and second interval actions.  NOTE: the timer
16619 			 * interval is allowed to continue its exponential
16620 			 * backoff.
16621 			 */
16622 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16623 				if (tcp->tcp_debug) {
16624 					(void) strlog(TCP_MOD_ID, 0, 1,
16625 					    SL_TRACE, "tcp_timer: zero win");
16626 				}
16627 			} else {
16628 				/*
16629 				 * After retransmission, we need to do
16630 				 * slow start.  Set the ssthresh to one
16631 				 * half of current effective window and
16632 				 * cwnd to one MSS.  Also reset
16633 				 * tcp_cwnd_cnt.
16634 				 *
16635 				 * Note that if tcp_ssthresh is reduced because
16636 				 * of ECN, do not reduce it again unless it is
16637 				 * already one window of data away (tcp_cwr
16638 				 * should then be cleared) or this is a
16639 				 * timeout for a retransmitted segment.
16640 				 */
16641 				uint32_t npkt;
16642 
16643 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16644 					npkt = ((tcp->tcp_timer_backoff ?
16645 					    tcp->tcp_cwnd_ssthresh :
16646 					    tcp->tcp_snxt -
16647 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16648 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16649 					    tcp->tcp_mss;
16650 				}
16651 				tcp->tcp_cwnd = tcp->tcp_mss;
16652 				tcp->tcp_cwnd_cnt = 0;
16653 				if (tcp->tcp_ecn_ok) {
16654 					tcp->tcp_cwr = B_TRUE;
16655 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16656 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16657 				}
16658 			}
16659 			break;
16660 		}
16661 		/*
16662 		 * We have something to send yet we cannot send.  The
16663 		 * reason can be:
16664 		 *
16665 		 * 1. Zero send window: we need to do zero window probe.
16666 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16667 		 * segments.
16668 		 * 3. SWS avoidance: receiver may have shrunk window,
16669 		 * reset our knowledge.
16670 		 *
16671 		 * Note that condition 2 can happen with either 1 or
16672 		 * 3.  But 1 and 3 are exclusive.
16673 		 */
16674 		if (tcp->tcp_unsent != 0) {
16675 			if (tcp->tcp_cwnd == 0) {
16676 				/*
16677 				 * Set tcp_cwnd to 1 MSS so that a
16678 				 * new segment can be sent out.  We
16679 				 * are "clocking out" new data when
16680 				 * the network is really congested.
16681 				 */
16682 				ASSERT(tcp->tcp_ecn_ok);
16683 				tcp->tcp_cwnd = tcp->tcp_mss;
16684 			}
16685 			if (tcp->tcp_swnd == 0) {
16686 				/* Extend window for zero window probe */
16687 				tcp->tcp_swnd++;
16688 				tcp->tcp_zero_win_probe = B_TRUE;
16689 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
16690 			} else {
16691 				/*
16692 				 * Handle timeout from sender SWS avoidance.
16693 				 * Reset our knowledge of the max send window
16694 				 * since the receiver might have reduced its
16695 				 * receive buffer.  Avoid setting tcp_max_swnd
16696 				 * to one since that will essentially disable
16697 				 * the SWS checks.
16698 				 *
16699 				 * Note that since we don't have a SWS
16700 				 * state variable, if the timeout is set
16701 				 * for ECN but not for SWS, this
16702 				 * code will also be executed.  This is
16703 				 * fine as tcp_max_swnd is updated
16704 				 * constantly and it will not affect
16705 				 * anything.
16706 				 */
16707 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16708 			}
16709 			tcp_wput_data(tcp, NULL, B_FALSE);
16710 			return;
16711 		}
16712 		/* Is there a FIN that needs to be to re retransmitted? */
16713 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16714 		    !tcp->tcp_fin_acked)
16715 			break;
16716 		/* Nothing to do, return without restarting timer. */
16717 		TCP_STAT(tcp_timer_fire_miss);
16718 		return;
16719 	case TCPS_FIN_WAIT_2:
16720 		/*
16721 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16722 		 * We waited some time for for peer's FIN, but it hasn't
16723 		 * arrived.  We flush the connection now to avoid
16724 		 * case where the peer has rebooted.
16725 		 */
16726 		if (TCP_IS_DETACHED(tcp)) {
16727 			(void) tcp_clean_death(tcp, 0, 23);
16728 		} else {
16729 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
16730 		}
16731 		return;
16732 	case TCPS_TIME_WAIT:
16733 		(void) tcp_clean_death(tcp, 0, 24);
16734 		return;
16735 	default:
16736 		if (tcp->tcp_debug) {
16737 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16738 			    "tcp_timer: strange state (%d) %s",
16739 			    tcp->tcp_state, tcp_display(tcp, NULL,
16740 			    DISP_PORT_ONLY));
16741 		}
16742 		return;
16743 	}
16744 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16745 		/*
16746 		 * For zero window probe, we need to send indefinitely,
16747 		 * unless we have not heard from the other side for some
16748 		 * time...
16749 		 */
16750 		if ((tcp->tcp_zero_win_probe == 0) ||
16751 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16752 		    second_threshold)) {
16753 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
16754 			/*
16755 			 * If TCP is in SYN_RCVD state, send back a
16756 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16757 			 * should be zero in TCPS_SYN_RCVD state.
16758 			 */
16759 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16760 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16761 				    "in SYN_RCVD",
16762 				    tcp, tcp->tcp_snxt,
16763 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16764 			}
16765 			(void) tcp_clean_death(tcp,
16766 			    tcp->tcp_client_errno ?
16767 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16768 			return;
16769 		} else {
16770 			/*
16771 			 * Set tcp_ms_we_have_waited to second_threshold
16772 			 * so that in next timeout, we will do the above
16773 			 * check (lbolt - tcp_last_recv_time).  This is
16774 			 * also to avoid overflow.
16775 			 *
16776 			 * We don't need to decrement tcp_timer_backoff
16777 			 * to avoid overflow because it will be decremented
16778 			 * later if new timeout value is greater than
16779 			 * tcp_rexmit_interval_max.  In the case when
16780 			 * tcp_rexmit_interval_max is greater than
16781 			 * second_threshold, it means that we will wait
16782 			 * longer than second_threshold to send the next
16783 			 * window probe.
16784 			 */
16785 			tcp->tcp_ms_we_have_waited = second_threshold;
16786 		}
16787 	} else if (ms > first_threshold) {
16788 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16789 		    tcp->tcp_xmit_head != NULL) {
16790 			tcp->tcp_xmit_head =
16791 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16792 		}
16793 		/*
16794 		 * We have been retransmitting for too long...  The RTT
16795 		 * we calculated is probably incorrect.  Reinitialize it.
16796 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16797 		 * tcp_rtt_update so that we won't accidentally cache a
16798 		 * bad value.  But only do this if this is not a zero
16799 		 * window probe.
16800 		 */
16801 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16802 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16803 			    (tcp->tcp_rtt_sa >> 5);
16804 			tcp->tcp_rtt_sa = 0;
16805 			tcp_ip_notify(tcp);
16806 			tcp->tcp_rtt_update = 0;
16807 		}
16808 	}
16809 	tcp->tcp_timer_backoff++;
16810 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16811 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16812 	    tcp_rexmit_interval_min) {
16813 		/*
16814 		 * This means the original RTO is tcp_rexmit_interval_min.
16815 		 * So we will use tcp_rexmit_interval_min as the RTO value
16816 		 * and do the backoff.
16817 		 */
16818 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
16819 	} else {
16820 		ms <<= tcp->tcp_timer_backoff;
16821 	}
16822 	if (ms > tcp_rexmit_interval_max) {
16823 		ms = tcp_rexmit_interval_max;
16824 		/*
16825 		 * ms is at max, decrement tcp_timer_backoff to avoid
16826 		 * overflow.
16827 		 */
16828 		tcp->tcp_timer_backoff--;
16829 	}
16830 	tcp->tcp_ms_we_have_waited += ms;
16831 	if (tcp->tcp_zero_win_probe == 0) {
16832 		tcp->tcp_rto = ms;
16833 	}
16834 	TCP_TIMER_RESTART(tcp, ms);
16835 	/*
16836 	 * This is after a timeout and tcp_rto is backed off.  Set
16837 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16838 	 * restart the timer with a correct value.
16839 	 */
16840 	tcp->tcp_set_timer = 1;
16841 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16842 	if (mss > tcp->tcp_mss)
16843 		mss = tcp->tcp_mss;
16844 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16845 		mss = tcp->tcp_swnd;
16846 
16847 	if ((mp = tcp->tcp_xmit_head) != NULL)
16848 		mp->b_prev = (mblk_t *)lbolt;
16849 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16850 	    B_TRUE);
16851 
16852 	/*
16853 	 * When slow start after retransmission begins, start with
16854 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16855 	 * start phase.  tcp_snd_burst controls how many segments
16856 	 * can be sent because of an ack.
16857 	 */
16858 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16859 	tcp->tcp_snd_burst = TCP_CWND_SS;
16860 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16861 	    (tcp->tcp_unsent == 0)) {
16862 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16863 	} else {
16864 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16865 	}
16866 	tcp->tcp_rexmit = B_TRUE;
16867 	tcp->tcp_dupack_cnt = 0;
16868 
16869 	/*
16870 	 * Remove all rexmit SACK blk to start from fresh.
16871 	 */
16872 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16873 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16874 		tcp->tcp_num_notsack_blk = 0;
16875 		tcp->tcp_cnt_notsack_list = 0;
16876 	}
16877 	if (mp == NULL) {
16878 		return;
16879 	}
16880 	/* Attach credentials to retransmitted initial SYNs. */
16881 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16882 		mblk_setcred(mp, tcp->tcp_cred);
16883 		DB_CPID(mp) = tcp->tcp_cpid;
16884 	}
16885 
16886 	tcp->tcp_csuna = tcp->tcp_snxt;
16887 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
16888 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
16889 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
16890 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16891 
16892 }
16893 
16894 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16895 static void
16896 tcp_unbind(tcp_t *tcp, mblk_t *mp)
16897 {
16898 	conn_t	*connp;
16899 
16900 	switch (tcp->tcp_state) {
16901 	case TCPS_BOUND:
16902 	case TCPS_LISTEN:
16903 		break;
16904 	default:
16905 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
16906 		return;
16907 	}
16908 
16909 	/*
16910 	 * Need to clean up all the eagers since after the unbind, segments
16911 	 * will no longer be delivered to this listener stream.
16912 	 */
16913 	mutex_enter(&tcp->tcp_eager_lock);
16914 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16915 		tcp_eager_cleanup(tcp, 0);
16916 	}
16917 	mutex_exit(&tcp->tcp_eager_lock);
16918 
16919 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16920 		tcp->tcp_ipha->ipha_src = 0;
16921 	} else {
16922 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16923 	}
16924 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16925 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16926 	tcp_bind_hash_remove(tcp);
16927 	tcp->tcp_state = TCPS_IDLE;
16928 	tcp->tcp_mdt = B_FALSE;
16929 	/* Send M_FLUSH according to TPI */
16930 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16931 	connp = tcp->tcp_connp;
16932 	connp->conn_mdt_ok = B_FALSE;
16933 	ipcl_hash_remove(connp);
16934 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16935 	mp = mi_tpi_ok_ack_alloc(mp);
16936 	putnext(tcp->tcp_rq, mp);
16937 }
16938 
16939 /*
16940  * Don't let port fall into the privileged range.
16941  * Since the extra privileged ports can be arbitrary we also
16942  * ensure that we exclude those from consideration.
16943  * tcp_g_epriv_ports is not sorted thus we loop over it until
16944  * there are no changes.
16945  *
16946  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16947  * but instead the code relies on:
16948  * - the fact that the address of the array and its size never changes
16949  * - the atomic assignment of the elements of the array
16950  *
16951  * Returns 0 if there are no more ports available.
16952  *
16953  * TS note: skip multilevel ports.
16954  */
16955 static in_port_t
16956 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16957 {
16958 	int i;
16959 	boolean_t restart = B_FALSE;
16960 
16961 	if (random && tcp_random_anon_port != 0) {
16962 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16963 		    sizeof (in_port_t));
16964 		/*
16965 		 * Unless changed by a sys admin, the smallest anon port
16966 		 * is 32768 and the largest anon port is 65535.  It is
16967 		 * very likely (50%) for the random port to be smaller
16968 		 * than the smallest anon port.  When that happens,
16969 		 * add port % (anon port range) to the smallest anon
16970 		 * port to get the random port.  It should fall into the
16971 		 * valid anon port range.
16972 		 */
16973 		if (port < tcp_smallest_anon_port) {
16974 			port = tcp_smallest_anon_port +
16975 			    port % (tcp_largest_anon_port -
16976 				tcp_smallest_anon_port);
16977 		}
16978 	}
16979 
16980 retry:
16981 	if (port < tcp_smallest_anon_port)
16982 		port = (in_port_t)tcp_smallest_anon_port;
16983 
16984 	if (port > tcp_largest_anon_port) {
16985 		if (restart)
16986 			return (0);
16987 		restart = B_TRUE;
16988 		port = (in_port_t)tcp_smallest_anon_port;
16989 	}
16990 
16991 	if (port < tcp_smallest_nonpriv_port)
16992 		port = (in_port_t)tcp_smallest_nonpriv_port;
16993 
16994 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
16995 		if (port == tcp_g_epriv_ports[i]) {
16996 			port++;
16997 			/*
16998 			 * Make sure whether the port is in the
16999 			 * valid range.
17000 			 */
17001 			goto retry;
17002 		}
17003 	}
17004 	if (is_system_labeled() &&
17005 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17006 	    IPPROTO_TCP, B_TRUE)) != 0) {
17007 		port = i;
17008 		goto retry;
17009 	}
17010 	return (port);
17011 }
17012 
17013 /*
17014  * Return the next anonymous port in the privileged port range for
17015  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17016  * downwards.  This is the same behavior as documented in the userland
17017  * library call rresvport(3N).
17018  *
17019  * TS note: skip multilevel ports.
17020  */
17021 static in_port_t
17022 tcp_get_next_priv_port(const tcp_t *tcp)
17023 {
17024 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17025 	in_port_t nextport;
17026 	boolean_t restart = B_FALSE;
17027 
17028 retry:
17029 	if (next_priv_port < tcp_min_anonpriv_port ||
17030 	    next_priv_port >= IPPORT_RESERVED) {
17031 		next_priv_port = IPPORT_RESERVED - 1;
17032 		if (restart)
17033 			return (0);
17034 		restart = B_TRUE;
17035 	}
17036 	if (is_system_labeled() &&
17037 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17038 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17039 		next_priv_port = nextport;
17040 		goto retry;
17041 	}
17042 	return (next_priv_port--);
17043 }
17044 
17045 /* The write side r/w procedure. */
17046 
17047 #if CCS_STATS
17048 struct {
17049 	struct {
17050 		int64_t count, bytes;
17051 	} tot, hit;
17052 } wrw_stats;
17053 #endif
17054 
17055 /*
17056  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17057  * messages.
17058  */
17059 /* ARGSUSED */
17060 static void
17061 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17062 {
17063 	conn_t	*connp = (conn_t *)arg;
17064 	tcp_t	*tcp = connp->conn_tcp;
17065 	queue_t	*q = tcp->tcp_wq;
17066 
17067 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17068 	/*
17069 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17070 	 * Once the close starts, streamhead and sockfs will not let any data
17071 	 * packets come down (close ensures that there are no threads using the
17072 	 * queue and no new threads will come down) but since qprocsoff()
17073 	 * hasn't happened yet, a M_FLUSH or some non data message might
17074 	 * get reflected back (in response to our own FLUSHRW) and get
17075 	 * processed after tcp_close() is done. The conn would still be valid
17076 	 * because a ref would have added but we need to check the state
17077 	 * before actually processing the packet.
17078 	 */
17079 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17080 		freemsg(mp);
17081 		return;
17082 	}
17083 
17084 	switch (DB_TYPE(mp)) {
17085 	case M_IOCDATA:
17086 		tcp_wput_iocdata(tcp, mp);
17087 		break;
17088 	case M_FLUSH:
17089 		tcp_wput_flush(tcp, mp);
17090 		break;
17091 	default:
17092 		CALL_IP_WPUT(connp, q, mp);
17093 		break;
17094 	}
17095 }
17096 
17097 /*
17098  * The TCP fast path write put procedure.
17099  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17100  */
17101 /* ARGSUSED */
17102 void
17103 tcp_output(void *arg, mblk_t *mp, void *arg2)
17104 {
17105 	int		len;
17106 	int		hdrlen;
17107 	int		plen;
17108 	mblk_t		*mp1;
17109 	uchar_t		*rptr;
17110 	uint32_t	snxt;
17111 	tcph_t		*tcph;
17112 	struct datab	*db;
17113 	uint32_t	suna;
17114 	uint32_t	mss;
17115 	ipaddr_t	*dst;
17116 	ipaddr_t	*src;
17117 	uint32_t	sum;
17118 	int		usable;
17119 	conn_t		*connp = (conn_t *)arg;
17120 	tcp_t		*tcp = connp->conn_tcp;
17121 	uint32_t	msize;
17122 
17123 	/*
17124 	 * Try and ASSERT the minimum possible references on the
17125 	 * conn early enough. Since we are executing on write side,
17126 	 * the connection is obviously not detached and that means
17127 	 * there is a ref each for TCP and IP. Since we are behind
17128 	 * the squeue, the minimum references needed are 3. If the
17129 	 * conn is in classifier hash list, there should be an
17130 	 * extra ref for that (we check both the possibilities).
17131 	 */
17132 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17133 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17134 
17135 	ASSERT(DB_TYPE(mp) == M_DATA);
17136 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17137 
17138 	mutex_enter(&connp->conn_lock);
17139 	tcp->tcp_squeue_bytes -= msize;
17140 	mutex_exit(&connp->conn_lock);
17141 
17142 	/* Bypass tcp protocol for fused tcp loopback */
17143 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17144 		return;
17145 
17146 	mss = tcp->tcp_mss;
17147 	if (tcp->tcp_xmit_zc_clean)
17148 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17149 
17150 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17151 	len = (int)(mp->b_wptr - mp->b_rptr);
17152 
17153 	/*
17154 	 * Criteria for fast path:
17155 	 *
17156 	 *   1. no unsent data
17157 	 *   2. single mblk in request
17158 	 *   3. connection established
17159 	 *   4. data in mblk
17160 	 *   5. len <= mss
17161 	 *   6. no tcp_valid bits
17162 	 */
17163 	if ((tcp->tcp_unsent != 0) ||
17164 	    (tcp->tcp_cork) ||
17165 	    (mp->b_cont != NULL) ||
17166 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17167 	    (len == 0) ||
17168 	    (len > mss) ||
17169 	    (tcp->tcp_valid_bits != 0)) {
17170 		tcp_wput_data(tcp, mp, B_FALSE);
17171 		return;
17172 	}
17173 
17174 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17175 	ASSERT(tcp->tcp_fin_sent == 0);
17176 
17177 	/* queue new packet onto retransmission queue */
17178 	if (tcp->tcp_xmit_head == NULL) {
17179 		tcp->tcp_xmit_head = mp;
17180 	} else {
17181 		tcp->tcp_xmit_last->b_cont = mp;
17182 	}
17183 	tcp->tcp_xmit_last = mp;
17184 	tcp->tcp_xmit_tail = mp;
17185 
17186 	/* find out how much we can send */
17187 	/* BEGIN CSTYLED */
17188 	/*
17189 	 *    un-acked           usable
17190 	 *  |--------------|-----------------|
17191 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17192 	 */
17193 	/* END CSTYLED */
17194 
17195 	/* start sending from tcp_snxt */
17196 	snxt = tcp->tcp_snxt;
17197 
17198 	/*
17199 	 * Check to see if this connection has been idled for some
17200 	 * time and no ACK is expected.  If it is, we need to slow
17201 	 * start again to get back the connection's "self-clock" as
17202 	 * described in VJ's paper.
17203 	 *
17204 	 * Refer to the comment in tcp_mss_set() for the calculation
17205 	 * of tcp_cwnd after idle.
17206 	 */
17207 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17208 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17209 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
17210 	}
17211 
17212 	usable = tcp->tcp_swnd;		/* tcp window size */
17213 	if (usable > tcp->tcp_cwnd)
17214 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17215 	usable -= snxt;		/* subtract stuff already sent */
17216 	suna = tcp->tcp_suna;
17217 	usable += suna;
17218 	/* usable can be < 0 if the congestion window is smaller */
17219 	if (len > usable) {
17220 		/* Can't send complete M_DATA in one shot */
17221 		goto slow;
17222 	}
17223 
17224 	if (tcp->tcp_flow_stopped &&
17225 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17226 		tcp_clrqfull(tcp);
17227 	}
17228 
17229 	/*
17230 	 * determine if anything to send (Nagle).
17231 	 *
17232 	 *   1. len < tcp_mss (i.e. small)
17233 	 *   2. unacknowledged data present
17234 	 *   3. len < nagle limit
17235 	 *   4. last packet sent < nagle limit (previous packet sent)
17236 	 */
17237 	if ((len < mss) && (snxt != suna) &&
17238 	    (len < (int)tcp->tcp_naglim) &&
17239 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17240 		/*
17241 		 * This was the first unsent packet and normally
17242 		 * mss < xmit_hiwater so there is no need to worry
17243 		 * about flow control. The next packet will go
17244 		 * through the flow control check in tcp_wput_data().
17245 		 */
17246 		/* leftover work from above */
17247 		tcp->tcp_unsent = len;
17248 		tcp->tcp_xmit_tail_unsent = len;
17249 
17250 		return;
17251 	}
17252 
17253 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17254 
17255 	if (snxt == suna) {
17256 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17257 	}
17258 
17259 	/* we have always sent something */
17260 	tcp->tcp_rack_cnt = 0;
17261 
17262 	tcp->tcp_snxt = snxt + len;
17263 	tcp->tcp_rack = tcp->tcp_rnxt;
17264 
17265 	if ((mp1 = dupb(mp)) == 0)
17266 		goto no_memory;
17267 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17268 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17269 
17270 	/* adjust tcp header information */
17271 	tcph = tcp->tcp_tcph;
17272 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17273 
17274 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17275 	sum = (sum >> 16) + (sum & 0xFFFF);
17276 	U16_TO_ABE16(sum, tcph->th_sum);
17277 
17278 	U32_TO_ABE32(snxt, tcph->th_seq);
17279 
17280 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
17281 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
17282 	BUMP_LOCAL(tcp->tcp_obsegs);
17283 
17284 	/* Update the latest receive window size in TCP header. */
17285 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17286 	    tcph->th_win);
17287 
17288 	tcp->tcp_last_sent_len = (ushort_t)len;
17289 
17290 	plen = len + tcp->tcp_hdr_len;
17291 
17292 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17293 		tcp->tcp_ipha->ipha_length = htons(plen);
17294 	} else {
17295 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17296 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17297 	}
17298 
17299 	/* see if we need to allocate a mblk for the headers */
17300 	hdrlen = tcp->tcp_hdr_len;
17301 	rptr = mp1->b_rptr - hdrlen;
17302 	db = mp1->b_datap;
17303 	if ((db->db_ref != 2) || rptr < db->db_base ||
17304 	    (!OK_32PTR(rptr))) {
17305 		/* NOTE: we assume allocb returns an OK_32PTR */
17306 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17307 		    tcp_wroff_xtra, BPRI_MED);
17308 		if (!mp) {
17309 			freemsg(mp1);
17310 			goto no_memory;
17311 		}
17312 		mp->b_cont = mp1;
17313 		mp1 = mp;
17314 		/* Leave room for Link Level header */
17315 		/* hdrlen = tcp->tcp_hdr_len; */
17316 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
17317 		mp1->b_wptr = &rptr[hdrlen];
17318 	}
17319 	mp1->b_rptr = rptr;
17320 
17321 	/* Fill in the timestamp option. */
17322 	if (tcp->tcp_snd_ts_ok) {
17323 		U32_TO_BE32((uint32_t)lbolt,
17324 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17325 		U32_TO_BE32(tcp->tcp_ts_recent,
17326 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17327 	} else {
17328 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17329 	}
17330 
17331 	/* copy header into outgoing packet */
17332 	dst = (ipaddr_t *)rptr;
17333 	src = (ipaddr_t *)tcp->tcp_iphc;
17334 	dst[0] = src[0];
17335 	dst[1] = src[1];
17336 	dst[2] = src[2];
17337 	dst[3] = src[3];
17338 	dst[4] = src[4];
17339 	dst[5] = src[5];
17340 	dst[6] = src[6];
17341 	dst[7] = src[7];
17342 	dst[8] = src[8];
17343 	dst[9] = src[9];
17344 	if (hdrlen -= 40) {
17345 		hdrlen >>= 2;
17346 		dst += 10;
17347 		src += 10;
17348 		do {
17349 			*dst++ = *src++;
17350 		} while (--hdrlen);
17351 	}
17352 
17353 	/*
17354 	 * Set the ECN info in the TCP header.  Note that this
17355 	 * is not the template header.
17356 	 */
17357 	if (tcp->tcp_ecn_ok) {
17358 		SET_ECT(tcp, rptr);
17359 
17360 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17361 		if (tcp->tcp_ecn_echo_on)
17362 			tcph->th_flags[0] |= TH_ECE;
17363 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17364 			tcph->th_flags[0] |= TH_CWR;
17365 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17366 		}
17367 	}
17368 
17369 	if (tcp->tcp_ip_forward_progress) {
17370 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17371 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17372 		tcp->tcp_ip_forward_progress = B_FALSE;
17373 	}
17374 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17375 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17376 	return;
17377 
17378 	/*
17379 	 * If we ran out of memory, we pretend to have sent the packet
17380 	 * and that it was lost on the wire.
17381 	 */
17382 no_memory:
17383 	return;
17384 
17385 slow:
17386 	/* leftover work from above */
17387 	tcp->tcp_unsent = len;
17388 	tcp->tcp_xmit_tail_unsent = len;
17389 	tcp_wput_data(tcp, NULL, B_FALSE);
17390 }
17391 
17392 /*
17393  * The function called through squeue to get behind eager's perimeter to
17394  * finish the accept processing.
17395  */
17396 /* ARGSUSED */
17397 void
17398 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17399 {
17400 	conn_t			*connp = (conn_t *)arg;
17401 	tcp_t			*tcp = connp->conn_tcp;
17402 	queue_t			*q = tcp->tcp_rq;
17403 	mblk_t			*mp1;
17404 	mblk_t			*stropt_mp = mp;
17405 	struct  stroptions	*stropt;
17406 	uint_t			thwin;
17407 
17408 	/*
17409 	 * Drop the eager's ref on the listener, that was placed when
17410 	 * this eager began life in tcp_conn_request.
17411 	 */
17412 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17413 
17414 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17415 		/*
17416 		 * Someone blewoff the eager before we could finish
17417 		 * the accept.
17418 		 *
17419 		 * The only reason eager exists it because we put in
17420 		 * a ref on it when conn ind went up. We need to send
17421 		 * a disconnect indication up while the last reference
17422 		 * on the eager will be dropped by the squeue when we
17423 		 * return.
17424 		 */
17425 		ASSERT(tcp->tcp_listener == NULL);
17426 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17427 			struct	T_discon_ind	*tdi;
17428 
17429 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17430 			/*
17431 			 * Let us reuse the incoming mblk to avoid memory
17432 			 * allocation failure problems. We know that the
17433 			 * size of the incoming mblk i.e. stroptions is greater
17434 			 * than sizeof T_discon_ind. So the reallocb below
17435 			 * can't fail.
17436 			 */
17437 			freemsg(mp->b_cont);
17438 			mp->b_cont = NULL;
17439 			ASSERT(DB_REF(mp) == 1);
17440 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17441 			    B_FALSE);
17442 			ASSERT(mp != NULL);
17443 			DB_TYPE(mp) = M_PROTO;
17444 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17445 			tdi = (struct T_discon_ind *)mp->b_rptr;
17446 			if (tcp->tcp_issocket) {
17447 				tdi->DISCON_reason = ECONNREFUSED;
17448 				tdi->SEQ_number = 0;
17449 			} else {
17450 				tdi->DISCON_reason = ENOPROTOOPT;
17451 				tdi->SEQ_number =
17452 				    tcp->tcp_conn_req_seqnum;
17453 			}
17454 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17455 			putnext(q, mp);
17456 		} else {
17457 			freemsg(mp);
17458 		}
17459 		if (tcp->tcp_hard_binding) {
17460 			tcp->tcp_hard_binding = B_FALSE;
17461 			tcp->tcp_hard_bound = B_TRUE;
17462 		}
17463 		tcp->tcp_detached = B_FALSE;
17464 		return;
17465 	}
17466 
17467 	mp1 = stropt_mp->b_cont;
17468 	stropt_mp->b_cont = NULL;
17469 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17470 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17471 
17472 	while (mp1 != NULL) {
17473 		mp = mp1;
17474 		mp1 = mp1->b_cont;
17475 		mp->b_cont = NULL;
17476 		tcp->tcp_drop_opt_ack_cnt++;
17477 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17478 	}
17479 	mp = NULL;
17480 
17481 	/*
17482 	 * For a loopback connection with tcp_direct_sockfs on, note that
17483 	 * we don't have to protect tcp_rcv_list yet because synchronous
17484 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17485 	 * possibly race with us.
17486 	 */
17487 
17488 	/*
17489 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17490 	 * properly.  This is the first time we know of the acceptor'
17491 	 * queue.  So we do it here.
17492 	 */
17493 	if (tcp->tcp_rcv_list == NULL) {
17494 		/*
17495 		 * Recv queue is empty, tcp_rwnd should not have changed.
17496 		 * That means it should be equal to the listener's tcp_rwnd.
17497 		 */
17498 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17499 	} else {
17500 #ifdef DEBUG
17501 		uint_t cnt = 0;
17502 
17503 		mp1 = tcp->tcp_rcv_list;
17504 		while ((mp = mp1) != NULL) {
17505 			mp1 = mp->b_next;
17506 			cnt += msgdsize(mp);
17507 		}
17508 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17509 #endif
17510 		/* There is some data, add them back to get the max. */
17511 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17512 	}
17513 
17514 	stropt->so_flags = SO_HIWAT;
17515 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
17516 
17517 	stropt->so_flags |= SO_MAXBLK;
17518 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17519 
17520 	/*
17521 	 * This is the first time we run on the correct
17522 	 * queue after tcp_accept. So fix all the q parameters
17523 	 * here.
17524 	 */
17525 	/* Allocate room for SACK options if needed. */
17526 	stropt->so_flags |= SO_WROFF;
17527 	if (tcp->tcp_fused) {
17528 		ASSERT(tcp->tcp_loopback);
17529 		ASSERT(tcp->tcp_loopback_peer != NULL);
17530 		/*
17531 		 * For fused tcp loopback, set the stream head's write
17532 		 * offset value to zero since we won't be needing any room
17533 		 * for TCP/IP headers.  This would also improve performance
17534 		 * since it would reduce the amount of work done by kmem.
17535 		 * Non-fused tcp loopback case is handled separately below.
17536 		 */
17537 		stropt->so_wroff = 0;
17538 		/*
17539 		 * Record the stream head's high water mark for this endpoint;
17540 		 * this is used for flow-control purposes in tcp_fuse_output().
17541 		 */
17542 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17543 		/*
17544 		 * Update the peer's transmit parameters according to
17545 		 * our recently calculated high water mark value.
17546 		 */
17547 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17548 	} else if (tcp->tcp_snd_sack_ok) {
17549 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17550 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17551 	} else {
17552 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17553 		    tcp_wroff_xtra);
17554 	}
17555 
17556 	/*
17557 	 * If this is endpoint is handling SSL, then reserve extra
17558 	 * offset and space at the end.
17559 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17560 	 * overriding the previous setting. The extra cost of signing and
17561 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17562 	 * instead of a single contiguous one by the stream head
17563 	 * largely outweighs the statistical reduction of ACKs, when
17564 	 * applicable. The peer will also save on decyption and verification
17565 	 * costs.
17566 	 */
17567 	if (tcp->tcp_kssl_ctx != NULL) {
17568 		stropt->so_wroff += SSL3_WROFFSET;
17569 
17570 		stropt->so_flags |= SO_TAIL;
17571 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
17572 
17573 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
17574 	}
17575 
17576 	/* Send the options up */
17577 	putnext(q, stropt_mp);
17578 
17579 	/*
17580 	 * Pass up any data and/or a fin that has been received.
17581 	 *
17582 	 * Adjust receive window in case it had decreased
17583 	 * (because there is data <=> tcp_rcv_list != NULL)
17584 	 * while the connection was detached. Note that
17585 	 * in case the eager was flow-controlled, w/o this
17586 	 * code, the rwnd may never open up again!
17587 	 */
17588 	if (tcp->tcp_rcv_list != NULL) {
17589 		/* We drain directly in case of fused tcp loopback */
17590 		if (!tcp->tcp_fused && canputnext(q)) {
17591 			tcp->tcp_rwnd = q->q_hiwat;
17592 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17593 			    << tcp->tcp_rcv_ws;
17594 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17595 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17596 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17597 				tcp_xmit_ctl(NULL,
17598 				    tcp, (tcp->tcp_swnd == 0) ?
17599 				    tcp->tcp_suna : tcp->tcp_snxt,
17600 				    tcp->tcp_rnxt, TH_ACK);
17601 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17602 			}
17603 
17604 		}
17605 		(void) tcp_rcv_drain(q, tcp);
17606 
17607 		/*
17608 		 * For fused tcp loopback, back-enable peer endpoint
17609 		 * if it's currently flow-controlled.
17610 		 */
17611 		if (tcp->tcp_fused &&
17612 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17613 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17614 
17615 			ASSERT(peer_tcp != NULL);
17616 			ASSERT(peer_tcp->tcp_fused);
17617 
17618 			tcp_clrqfull(peer_tcp);
17619 			TCP_STAT(tcp_fusion_backenabled);
17620 		}
17621 	}
17622 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17623 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17624 		mp = mi_tpi_ordrel_ind();
17625 		if (mp) {
17626 			tcp->tcp_ordrel_done = B_TRUE;
17627 			putnext(q, mp);
17628 			if (tcp->tcp_deferred_clean_death) {
17629 				/*
17630 				 * tcp_clean_death was deferred
17631 				 * for T_ORDREL_IND - do it now
17632 				 */
17633 				(void) tcp_clean_death(tcp,
17634 				    tcp->tcp_client_errno, 21);
17635 				tcp->tcp_deferred_clean_death = B_FALSE;
17636 			}
17637 		} else {
17638 			/*
17639 			 * Run the orderly release in the
17640 			 * service routine.
17641 			 */
17642 			qenable(q);
17643 		}
17644 	}
17645 	if (tcp->tcp_hard_binding) {
17646 		tcp->tcp_hard_binding = B_FALSE;
17647 		tcp->tcp_hard_bound = B_TRUE;
17648 	}
17649 
17650 	tcp->tcp_detached = B_FALSE;
17651 
17652 	/* We can enable synchronous streams now */
17653 	if (tcp->tcp_fused) {
17654 		tcp_fuse_syncstr_enable_pair(tcp);
17655 	}
17656 
17657 	if (tcp->tcp_ka_enabled) {
17658 		tcp->tcp_ka_last_intrvl = 0;
17659 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17660 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17661 	}
17662 
17663 	/*
17664 	 * At this point, eager is fully established and will
17665 	 * have the following references -
17666 	 *
17667 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17668 	 * 1 reference for the squeue which will be dropped by the squeue as
17669 	 *	soon as this function returns.
17670 	 * There will be 1 additonal reference for being in classifier
17671 	 *	hash list provided something bad hasn't happened.
17672 	 */
17673 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17674 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17675 }
17676 
17677 /*
17678  * The function called through squeue to get behind listener's perimeter to
17679  * send a deffered conn_ind.
17680  */
17681 /* ARGSUSED */
17682 void
17683 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17684 {
17685 	conn_t	*connp = (conn_t *)arg;
17686 	tcp_t *listener = connp->conn_tcp;
17687 
17688 	if (listener->tcp_state == TCPS_CLOSED ||
17689 	    TCP_IS_DETACHED(listener)) {
17690 		/*
17691 		 * If listener has closed, it would have caused a
17692 		 * a cleanup/blowoff to happen for the eager.
17693 		 */
17694 		tcp_t *tcp;
17695 		struct T_conn_ind	*conn_ind;
17696 
17697 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
17698 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17699 		    conn_ind->OPT_length);
17700 		/*
17701 		 * We need to drop the ref on eager that was put
17702 		 * tcp_rput_data() before trying to send the conn_ind
17703 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17704 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17705 		 * listener is closed so we drop the ref.
17706 		 */
17707 		CONN_DEC_REF(tcp->tcp_connp);
17708 		freemsg(mp);
17709 		return;
17710 	}
17711 	putnext(listener->tcp_rq, mp);
17712 }
17713 
17714 
17715 /*
17716  * This is the STREAMS entry point for T_CONN_RES coming down on
17717  * Acceptor STREAM when  sockfs listener does accept processing.
17718  * Read the block comment on top pf tcp_conn_request().
17719  */
17720 void
17721 tcp_wput_accept(queue_t *q, mblk_t *mp)
17722 {
17723 	queue_t *rq = RD(q);
17724 	struct T_conn_res *conn_res;
17725 	tcp_t *eager;
17726 	tcp_t *listener;
17727 	struct T_ok_ack *ok;
17728 	t_scalar_t PRIM_type;
17729 	mblk_t *opt_mp;
17730 	conn_t *econnp;
17731 
17732 	ASSERT(DB_TYPE(mp) == M_PROTO);
17733 
17734 	conn_res = (struct T_conn_res *)mp->b_rptr;
17735 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17736 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17737 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17738 		if (mp != NULL)
17739 			putnext(rq, mp);
17740 		return;
17741 	}
17742 	switch (conn_res->PRIM_type) {
17743 	case O_T_CONN_RES:
17744 	case T_CONN_RES:
17745 		/*
17746 		 * We pass up an err ack if allocb fails. This will
17747 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17748 		 * tcp_eager_blowoff to be called. sockfs will then call
17749 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17750 		 * we need to do the allocb up here because we have to
17751 		 * make sure rq->q_qinfo->qi_qclose still points to the
17752 		 * correct function (tcpclose_accept) in case allocb
17753 		 * fails.
17754 		 */
17755 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17756 		if (opt_mp == NULL) {
17757 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17758 			if (mp != NULL)
17759 				putnext(rq, mp);
17760 			return;
17761 		}
17762 
17763 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17764 		    &eager, conn_res->OPT_length);
17765 		PRIM_type = conn_res->PRIM_type;
17766 		mp->b_datap->db_type = M_PCPROTO;
17767 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17768 		ok = (struct T_ok_ack *)mp->b_rptr;
17769 		ok->PRIM_type = T_OK_ACK;
17770 		ok->CORRECT_prim = PRIM_type;
17771 		econnp = eager->tcp_connp;
17772 		econnp->conn_dev = (dev_t)q->q_ptr;
17773 		eager->tcp_rq = rq;
17774 		eager->tcp_wq = q;
17775 		rq->q_ptr = econnp;
17776 		rq->q_qinfo = &tcp_rinit;
17777 		q->q_ptr = econnp;
17778 		q->q_qinfo = &tcp_winit;
17779 		listener = eager->tcp_listener;
17780 		eager->tcp_issocket = B_TRUE;
17781 
17782 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17783 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17784 
17785 		/* Put the ref for IP */
17786 		CONN_INC_REF(econnp);
17787 
17788 		/*
17789 		 * We should have minimum of 3 references on the conn
17790 		 * at this point. One each for TCP and IP and one for
17791 		 * the T_conn_ind that was sent up when the 3-way handshake
17792 		 * completed. In the normal case we would also have another
17793 		 * reference (making a total of 4) for the conn being in the
17794 		 * classifier hash list. However the eager could have received
17795 		 * an RST subsequently and tcp_closei_local could have removed
17796 		 * the eager from the classifier hash list, hence we can't
17797 		 * assert that reference.
17798 		 */
17799 		ASSERT(econnp->conn_ref >= 3);
17800 
17801 		/*
17802 		 * Send the new local address also up to sockfs. There
17803 		 * should already be enough space in the mp that came
17804 		 * down from soaccept().
17805 		 */
17806 		if (eager->tcp_family == AF_INET) {
17807 			sin_t *sin;
17808 
17809 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17810 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17811 			sin = (sin_t *)mp->b_wptr;
17812 			mp->b_wptr += sizeof (sin_t);
17813 			sin->sin_family = AF_INET;
17814 			sin->sin_port = eager->tcp_lport;
17815 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17816 		} else {
17817 			sin6_t *sin6;
17818 
17819 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17820 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17821 			sin6 = (sin6_t *)mp->b_wptr;
17822 			mp->b_wptr += sizeof (sin6_t);
17823 			sin6->sin6_family = AF_INET6;
17824 			sin6->sin6_port = eager->tcp_lport;
17825 			if (eager->tcp_ipversion == IPV4_VERSION) {
17826 				sin6->sin6_flowinfo = 0;
17827 				IN6_IPADDR_TO_V4MAPPED(
17828 					eager->tcp_ipha->ipha_src,
17829 					    &sin6->sin6_addr);
17830 			} else {
17831 				ASSERT(eager->tcp_ip6h != NULL);
17832 				sin6->sin6_flowinfo =
17833 				    eager->tcp_ip6h->ip6_vcf &
17834 				    ~IPV6_VERS_AND_FLOW_MASK;
17835 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17836 			}
17837 			sin6->sin6_scope_id = 0;
17838 			sin6->__sin6_src_id = 0;
17839 		}
17840 
17841 		putnext(rq, mp);
17842 
17843 		opt_mp->b_datap->db_type = M_SETOPTS;
17844 		opt_mp->b_wptr += sizeof (struct stroptions);
17845 
17846 		/*
17847 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17848 		 * from listener to acceptor. The message is chained on the
17849 		 * bind_mp which tcp_rput_other will send down to IP.
17850 		 */
17851 		if (listener->tcp_bound_if != 0) {
17852 			/* allocate optmgmt req */
17853 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17854 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
17855 			    sizeof (int));
17856 			if (mp != NULL)
17857 				linkb(opt_mp, mp);
17858 		}
17859 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17860 			uint_t on = 1;
17861 
17862 			/* allocate optmgmt req */
17863 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17864 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
17865 			if (mp != NULL)
17866 				linkb(opt_mp, mp);
17867 		}
17868 
17869 
17870 		mutex_enter(&listener->tcp_eager_lock);
17871 
17872 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17873 
17874 			tcp_t *tail;
17875 			tcp_t *tcp;
17876 			mblk_t *mp1;
17877 
17878 			tcp = listener->tcp_eager_prev_q0;
17879 			/*
17880 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
17881 			 * deferred T_conn_ind queue. We need to get to the head
17882 			 * of the queue in order to send up T_conn_ind the same
17883 			 * order as how the 3WHS is completed.
17884 			 */
17885 			while (tcp != listener) {
17886 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17887 				    !tcp->tcp_kssl_pending)
17888 					break;
17889 				else
17890 					tcp = tcp->tcp_eager_prev_q0;
17891 			}
17892 			/* None of the pending eagers can be sent up now */
17893 			if (tcp == listener)
17894 				goto no_more_eagers;
17895 
17896 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17897 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17898 			/* Move from q0 to q */
17899 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17900 			listener->tcp_conn_req_cnt_q0--;
17901 			listener->tcp_conn_req_cnt_q++;
17902 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17903 			    tcp->tcp_eager_prev_q0;
17904 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17905 			    tcp->tcp_eager_next_q0;
17906 			tcp->tcp_eager_prev_q0 = NULL;
17907 			tcp->tcp_eager_next_q0 = NULL;
17908 			tcp->tcp_conn_def_q0 = B_FALSE;
17909 
17910 			/*
17911 			 * Insert at end of the queue because sockfs sends
17912 			 * down T_CONN_RES in chronological order. Leaving
17913 			 * the older conn indications at front of the queue
17914 			 * helps reducing search time.
17915 			 */
17916 			tail = listener->tcp_eager_last_q;
17917 			if (tail != NULL) {
17918 				tail->tcp_eager_next_q = tcp;
17919 			} else {
17920 				listener->tcp_eager_next_q = tcp;
17921 			}
17922 			listener->tcp_eager_last_q = tcp;
17923 			tcp->tcp_eager_next_q = NULL;
17924 
17925 			/* Need to get inside the listener perimeter */
17926 			CONN_INC_REF(listener->tcp_connp);
17927 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
17928 			    tcp_send_pending, listener->tcp_connp,
17929 			    SQTAG_TCP_SEND_PENDING);
17930 		}
17931 no_more_eagers:
17932 		tcp_eager_unlink(eager);
17933 		mutex_exit(&listener->tcp_eager_lock);
17934 
17935 		/*
17936 		 * At this point, the eager is detached from the listener
17937 		 * but we still have an extra refs on eager (apart from the
17938 		 * usual tcp references). The ref was placed in tcp_rput_data
17939 		 * before sending the conn_ind in tcp_send_conn_ind.
17940 		 * The ref will be dropped in tcp_accept_finish().
17941 		 */
17942 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
17943 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
17944 		return;
17945 	default:
17946 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17947 		if (mp != NULL)
17948 			putnext(rq, mp);
17949 		return;
17950 	}
17951 }
17952 
17953 void
17954 tcp_wput(queue_t *q, mblk_t *mp)
17955 {
17956 	conn_t	*connp = Q_TO_CONN(q);
17957 	tcp_t	*tcp;
17958 	void (*output_proc)();
17959 	t_scalar_t type;
17960 	uchar_t *rptr;
17961 	struct iocblk	*iocp;
17962 	uint32_t	msize;
17963 
17964 	ASSERT(connp->conn_ref >= 2);
17965 
17966 	switch (DB_TYPE(mp)) {
17967 	case M_DATA:
17968 		tcp = connp->conn_tcp;
17969 		ASSERT(tcp != NULL);
17970 
17971 		msize = msgdsize(mp);
17972 
17973 		mutex_enter(&connp->conn_lock);
17974 		CONN_INC_REF_LOCKED(connp);
17975 
17976 		tcp->tcp_squeue_bytes += msize;
17977 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
17978 			mutex_exit(&connp->conn_lock);
17979 			tcp_setqfull(tcp);
17980 		} else
17981 			mutex_exit(&connp->conn_lock);
17982 
17983 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17984 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
17985 		return;
17986 	case M_PROTO:
17987 	case M_PCPROTO:
17988 		/*
17989 		 * if it is a snmp message, don't get behind the squeue
17990 		 */
17991 		tcp = connp->conn_tcp;
17992 		rptr = mp->b_rptr;
17993 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
17994 			type = ((union T_primitives *)rptr)->type;
17995 		} else {
17996 			if (tcp->tcp_debug) {
17997 				(void) strlog(TCP_MOD_ID, 0, 1,
17998 				    SL_ERROR|SL_TRACE,
17999 				    "tcp_wput_proto, dropping one...");
18000 			}
18001 			freemsg(mp);
18002 			return;
18003 		}
18004 		if (type == T_SVR4_OPTMGMT_REQ) {
18005 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18006 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
18007 			    cr)) {
18008 				/*
18009 				 * This was a SNMP request
18010 				 */
18011 				return;
18012 			} else {
18013 				output_proc = tcp_wput_proto;
18014 			}
18015 		} else {
18016 			output_proc = tcp_wput_proto;
18017 		}
18018 		break;
18019 	case M_IOCTL:
18020 		/*
18021 		 * Most ioctls can be processed right away without going via
18022 		 * squeues - process them right here. Those that do require
18023 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18024 		 * are processed by tcp_wput_ioctl().
18025 		 */
18026 		iocp = (struct iocblk *)mp->b_rptr;
18027 		tcp = connp->conn_tcp;
18028 
18029 		switch (iocp->ioc_cmd) {
18030 		case TCP_IOC_ABORT_CONN:
18031 			tcp_ioctl_abort_conn(q, mp);
18032 			return;
18033 		case TI_GETPEERNAME:
18034 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
18035 				iocp->ioc_error = ENOTCONN;
18036 				iocp->ioc_count = 0;
18037 				mp->b_datap->db_type = M_IOCACK;
18038 				qreply(q, mp);
18039 				return;
18040 			}
18041 			/* FALLTHRU */
18042 		case TI_GETMYNAME:
18043 			mi_copyin(q, mp, NULL,
18044 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18045 			return;
18046 		case ND_SET:
18047 			/* nd_getset does the necessary checks */
18048 		case ND_GET:
18049 			if (!nd_getset(q, tcp_g_nd, mp)) {
18050 				CALL_IP_WPUT(connp, q, mp);
18051 				return;
18052 			}
18053 			qreply(q, mp);
18054 			return;
18055 		case TCP_IOC_DEFAULT_Q:
18056 			/*
18057 			 * Wants to be the default wq. Check the credentials
18058 			 * first, the rest is executed via squeue.
18059 			 */
18060 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
18061 				iocp->ioc_error = EPERM;
18062 				iocp->ioc_count = 0;
18063 				mp->b_datap->db_type = M_IOCACK;
18064 				qreply(q, mp);
18065 				return;
18066 			}
18067 			output_proc = tcp_wput_ioctl;
18068 			break;
18069 		default:
18070 			output_proc = tcp_wput_ioctl;
18071 			break;
18072 		}
18073 		break;
18074 	default:
18075 		output_proc = tcp_wput_nondata;
18076 		break;
18077 	}
18078 
18079 	CONN_INC_REF(connp);
18080 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18081 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18082 }
18083 
18084 /*
18085  * Initial STREAMS write side put() procedure for sockets. It tries to
18086  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18087  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18088  * are handled by tcp_wput() as usual.
18089  *
18090  * All further messages will also be handled by tcp_wput() because we cannot
18091  * be sure that the above short cut is safe later.
18092  */
18093 static void
18094 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18095 {
18096 	conn_t			*connp = Q_TO_CONN(wq);
18097 	tcp_t			*tcp = connp->conn_tcp;
18098 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18099 
18100 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18101 	wq->q_qinfo = &tcp_winit;
18102 
18103 	ASSERT(IPCL_IS_TCP(connp));
18104 	ASSERT(TCP_IS_SOCKET(tcp));
18105 
18106 	if (DB_TYPE(mp) == M_PCPROTO &&
18107 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18108 	    car->PRIM_type == T_CAPABILITY_REQ) {
18109 		tcp_capability_req(tcp, mp);
18110 		return;
18111 	}
18112 
18113 	tcp_wput(wq, mp);
18114 }
18115 
18116 static boolean_t
18117 tcp_zcopy_check(tcp_t *tcp)
18118 {
18119 	conn_t	*connp = tcp->tcp_connp;
18120 	ire_t	*ire;
18121 	boolean_t	zc_enabled = B_FALSE;
18122 
18123 	if (do_tcpzcopy == 2)
18124 		zc_enabled = B_TRUE;
18125 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18126 	    IPCL_IS_CONNECTED(connp) &&
18127 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18128 	    connp->conn_dontroute == 0 &&
18129 	    !connp->conn_nexthop_set &&
18130 	    connp->conn_xmit_if_ill == NULL &&
18131 	    connp->conn_nofailover_ill == NULL &&
18132 	    do_tcpzcopy == 1) {
18133 		/*
18134 		 * the checks above  closely resemble the fast path checks
18135 		 * in tcp_send_data().
18136 		 */
18137 		mutex_enter(&connp->conn_lock);
18138 		ire = connp->conn_ire_cache;
18139 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18140 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18141 			IRE_REFHOLD(ire);
18142 			if (ire->ire_stq != NULL) {
18143 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18144 
18145 				zc_enabled = ill && (ill->ill_capabilities &
18146 				    ILL_CAPAB_ZEROCOPY) &&
18147 				    (ill->ill_zerocopy_capab->
18148 				    ill_zerocopy_flags != 0);
18149 			}
18150 			IRE_REFRELE(ire);
18151 		}
18152 		mutex_exit(&connp->conn_lock);
18153 	}
18154 	tcp->tcp_snd_zcopy_on = zc_enabled;
18155 	if (!TCP_IS_DETACHED(tcp)) {
18156 		if (zc_enabled) {
18157 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18158 			TCP_STAT(tcp_zcopy_on);
18159 		} else {
18160 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18161 			TCP_STAT(tcp_zcopy_off);
18162 		}
18163 	}
18164 	return (zc_enabled);
18165 }
18166 
18167 static mblk_t *
18168 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18169 {
18170 	if (do_tcpzcopy == 2)
18171 		return (bp);
18172 	else if (tcp->tcp_snd_zcopy_on) {
18173 		tcp->tcp_snd_zcopy_on = B_FALSE;
18174 		if (!TCP_IS_DETACHED(tcp)) {
18175 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18176 			TCP_STAT(tcp_zcopy_disable);
18177 		}
18178 	}
18179 	return (tcp_zcopy_backoff(tcp, bp, 0));
18180 }
18181 
18182 /*
18183  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18184  * the original desballoca'ed segmapped mblk.
18185  */
18186 static mblk_t *
18187 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18188 {
18189 	mblk_t *head, *tail, *nbp;
18190 	if (IS_VMLOANED_MBLK(bp)) {
18191 		TCP_STAT(tcp_zcopy_backoff);
18192 		if ((head = copyb(bp)) == NULL) {
18193 			/* fail to backoff; leave it for the next backoff */
18194 			tcp->tcp_xmit_zc_clean = B_FALSE;
18195 			return (bp);
18196 		}
18197 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18198 			if (fix_xmitlist)
18199 				tcp_zcopy_notify(tcp);
18200 			else
18201 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18202 		}
18203 		nbp = bp->b_cont;
18204 		if (fix_xmitlist) {
18205 			head->b_prev = bp->b_prev;
18206 			head->b_next = bp->b_next;
18207 			if (tcp->tcp_xmit_tail == bp)
18208 				tcp->tcp_xmit_tail = head;
18209 		}
18210 		bp->b_next = NULL;
18211 		bp->b_prev = NULL;
18212 		freeb(bp);
18213 	} else {
18214 		head = bp;
18215 		nbp = bp->b_cont;
18216 	}
18217 	tail = head;
18218 	while (nbp) {
18219 		if (IS_VMLOANED_MBLK(nbp)) {
18220 			TCP_STAT(tcp_zcopy_backoff);
18221 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18222 				tcp->tcp_xmit_zc_clean = B_FALSE;
18223 				tail->b_cont = nbp;
18224 				return (head);
18225 			}
18226 			tail = tail->b_cont;
18227 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18228 				if (fix_xmitlist)
18229 					tcp_zcopy_notify(tcp);
18230 				else
18231 					tail->b_datap->db_struioflag |=
18232 					    STRUIO_ZCNOTIFY;
18233 			}
18234 			bp = nbp;
18235 			nbp = nbp->b_cont;
18236 			if (fix_xmitlist) {
18237 				tail->b_prev = bp->b_prev;
18238 				tail->b_next = bp->b_next;
18239 				if (tcp->tcp_xmit_tail == bp)
18240 					tcp->tcp_xmit_tail = tail;
18241 			}
18242 			bp->b_next = NULL;
18243 			bp->b_prev = NULL;
18244 			freeb(bp);
18245 		} else {
18246 			tail->b_cont = nbp;
18247 			tail = nbp;
18248 			nbp = nbp->b_cont;
18249 		}
18250 	}
18251 	if (fix_xmitlist) {
18252 		tcp->tcp_xmit_last = tail;
18253 		tcp->tcp_xmit_zc_clean = B_TRUE;
18254 	}
18255 	return (head);
18256 }
18257 
18258 static void
18259 tcp_zcopy_notify(tcp_t *tcp)
18260 {
18261 	struct stdata	*stp;
18262 
18263 	if (tcp->tcp_detached)
18264 		return;
18265 	stp = STREAM(tcp->tcp_rq);
18266 	mutex_enter(&stp->sd_lock);
18267 	stp->sd_flag |= STZCNOTIFY;
18268 	cv_broadcast(&stp->sd_zcopy_wait);
18269 	mutex_exit(&stp->sd_lock);
18270 }
18271 
18272 static void
18273 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18274 {
18275 	ipha_t		*ipha;
18276 	ipaddr_t	src;
18277 	ipaddr_t	dst;
18278 	uint32_t	cksum;
18279 	ire_t		*ire;
18280 	uint16_t	*up;
18281 	ill_t		*ill;
18282 	conn_t		*connp = tcp->tcp_connp;
18283 	uint32_t	hcksum_txflags = 0;
18284 	mblk_t		*ire_fp_mp;
18285 	uint_t		ire_fp_mp_len;
18286 
18287 	ASSERT(DB_TYPE(mp) == M_DATA);
18288 
18289 	if (DB_CRED(mp) == NULL)
18290 		mblk_setcred(mp, CONN_CRED(connp));
18291 
18292 	ipha = (ipha_t *)mp->b_rptr;
18293 	src = ipha->ipha_src;
18294 	dst = ipha->ipha_dst;
18295 
18296 	/*
18297 	 * Drop off fast path for IPv6 and also if options are present or
18298 	 * we need to resolve a TS label.
18299 	 */
18300 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18301 	    !IPCL_IS_CONNECTED(connp) ||
18302 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18303 	    connp->conn_dontroute ||
18304 	    connp->conn_nexthop_set ||
18305 	    connp->conn_xmit_if_ill != NULL ||
18306 	    connp->conn_nofailover_ill != NULL ||
18307 	    !connp->conn_ulp_labeled ||
18308 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18309 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18310 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
18311 		if (tcp->tcp_snd_zcopy_aware)
18312 			mp = tcp_zcopy_disable(tcp, mp);
18313 		TCP_STAT(tcp_ip_send);
18314 		CALL_IP_WPUT(connp, q, mp);
18315 		return;
18316 	}
18317 
18318 	mutex_enter(&connp->conn_lock);
18319 	ire = connp->conn_ire_cache;
18320 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18321 	if (ire != NULL && ire->ire_addr == dst &&
18322 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18323 		IRE_REFHOLD(ire);
18324 		mutex_exit(&connp->conn_lock);
18325 	} else {
18326 		boolean_t cached = B_FALSE;
18327 
18328 		/* force a recheck later on */
18329 		tcp->tcp_ire_ill_check_done = B_FALSE;
18330 
18331 		TCP_DBGSTAT(tcp_ire_null1);
18332 		connp->conn_ire_cache = NULL;
18333 		mutex_exit(&connp->conn_lock);
18334 		if (ire != NULL)
18335 			IRE_REFRELE_NOTR(ire);
18336 		ire = ire_cache_lookup(dst, connp->conn_zoneid,
18337 		    MBLK_GETLABEL(mp));
18338 		if (ire == NULL) {
18339 			if (tcp->tcp_snd_zcopy_aware)
18340 				mp = tcp_zcopy_backoff(tcp, mp, 0);
18341 			TCP_STAT(tcp_ire_null);
18342 			CALL_IP_WPUT(connp, q, mp);
18343 			return;
18344 		}
18345 		IRE_REFHOLD_NOTR(ire);
18346 		/*
18347 		 * Since we are inside the squeue, there cannot be another
18348 		 * thread in TCP trying to set the conn_ire_cache now.  The
18349 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18350 		 * unplumb thread has not yet started cleaning up the conns.
18351 		 * Hence we don't need to grab the conn lock.
18352 		 */
18353 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
18354 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18355 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18356 				connp->conn_ire_cache = ire;
18357 				cached = B_TRUE;
18358 			}
18359 			rw_exit(&ire->ire_bucket->irb_lock);
18360 		}
18361 
18362 		/*
18363 		 * We can continue to use the ire but since it was
18364 		 * not cached, we should drop the extra reference.
18365 		 */
18366 		if (!cached)
18367 			IRE_REFRELE_NOTR(ire);
18368 
18369 		/*
18370 		 * Rampart note: no need to select a new label here, since
18371 		 * labels are not allowed to change during the life of a TCP
18372 		 * connection.
18373 		 */
18374 	}
18375 
18376 	/*
18377 	 * The following if case identifies whether or not
18378 	 * we are forced to take the slowpath.
18379 	 */
18380 	if (ire->ire_flags & RTF_MULTIRT ||
18381 	    ire->ire_stq == NULL ||
18382 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18383 	    (ire->ire_nce != NULL &&
18384 	    (ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18385 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
18386 		if (tcp->tcp_snd_zcopy_aware)
18387 			mp = tcp_zcopy_disable(tcp, mp);
18388 		TCP_STAT(tcp_ip_ire_send);
18389 		IRE_REFRELE(ire);
18390 		CALL_IP_WPUT(connp, q, mp);
18391 		return;
18392 	}
18393 
18394 	ill = ire_to_ill(ire);
18395 	if (connp->conn_outgoing_ill != NULL) {
18396 		ill_t *conn_outgoing_ill = NULL;
18397 		/*
18398 		 * Choose a good ill in the group to send the packets on.
18399 		 */
18400 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18401 		ill = ire_to_ill(ire);
18402 	}
18403 	ASSERT(ill != NULL);
18404 
18405 	if (!tcp->tcp_ire_ill_check_done) {
18406 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18407 		tcp->tcp_ire_ill_check_done = B_TRUE;
18408 	}
18409 
18410 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18411 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18412 #ifndef _BIG_ENDIAN
18413 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18414 #endif
18415 
18416 	/*
18417 	 * Check to see if we need to re-enable MDT for this connection
18418 	 * because it was previously disabled due to changes in the ill;
18419 	 * note that by doing it here, this re-enabling only applies when
18420 	 * the packet is not dispatched through CALL_IP_WPUT().
18421 	 *
18422 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
18423 	 * case, since that's how we ended up here.  For IPv6, we do the
18424 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18425 	 */
18426 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18427 		/*
18428 		 * Restore MDT for this connection, so that next time around
18429 		 * it is eligible to go through tcp_multisend() path again.
18430 		 */
18431 		TCP_STAT(tcp_mdt_conn_resumed1);
18432 		tcp->tcp_mdt = B_TRUE;
18433 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18434 		    "interface %s\n", (void *)connp, ill->ill_name));
18435 	}
18436 
18437 	if (tcp->tcp_snd_zcopy_aware) {
18438 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18439 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18440 			mp = tcp_zcopy_disable(tcp, mp);
18441 		/*
18442 		 * we shouldn't need to reset ipha as the mp containing
18443 		 * ipha should never be a zero-copy mp.
18444 		 */
18445 	}
18446 
18447 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18448 		ASSERT(ill->ill_hcksum_capab != NULL);
18449 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18450 	}
18451 
18452 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18453 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18454 
18455 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18456 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18457 
18458 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18459 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18460 
18461 	/* Software checksum? */
18462 	if (DB_CKSUMFLAGS(mp) == 0) {
18463 		TCP_STAT(tcp_out_sw_cksum);
18464 		TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
18465 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18466 	}
18467 
18468 	ipha->ipha_fragment_offset_and_flags |=
18469 	    (uint32_t)htons(ire->ire_frag_flag);
18470 
18471 	/* Calculate IP header checksum if hardware isn't capable */
18472 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18473 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18474 		    ((uint16_t *)ipha)[4]);
18475 	}
18476 
18477 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18478 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18479 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18480 
18481 	UPDATE_OB_PKT_COUNT(ire);
18482 	ire->ire_last_used_time = lbolt;
18483 	BUMP_MIB(&ip_mib, ipOutRequests);
18484 
18485 	if (ILL_DLS_CAPABLE(ill)) {
18486 		/*
18487 		 * Send the packet directly to DLD, where it may be queued
18488 		 * depending on the availability of transmit resources at
18489 		 * the media layer.
18490 		 */
18491 		IP_DLS_ILL_TX(ill, ipha, mp);
18492 	} else {
18493 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
18494 		DTRACE_PROBE4(ip4__physical__out__start,
18495 		    ill_t *, NULL, ill_t *, out_ill,
18496 		    ipha_t *, ipha, mblk_t *, mp);
18497 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
18498 		    NULL, out_ill, ipha, mp, mp);
18499 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18500 		if (mp != NULL)
18501 			putnext(ire->ire_stq, mp);
18502 	}
18503 	IRE_REFRELE(ire);
18504 }
18505 
18506 /*
18507  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18508  * if the receiver shrinks the window, i.e. moves the right window to the
18509  * left, the we should not send new data, but should retransmit normally the
18510  * old unacked data between suna and suna + swnd. We might has sent data
18511  * that is now outside the new window, pretend that we didn't send  it.
18512  */
18513 static void
18514 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18515 {
18516 	uint32_t	snxt = tcp->tcp_snxt;
18517 	mblk_t		*xmit_tail;
18518 	int32_t		offset;
18519 
18520 	ASSERT(shrunk_count > 0);
18521 
18522 	/* Pretend we didn't send the data outside the window */
18523 	snxt -= shrunk_count;
18524 
18525 	/* Get the mblk and the offset in it per the shrunk window */
18526 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18527 
18528 	ASSERT(xmit_tail != NULL);
18529 
18530 	/* Reset all the values per the now shrunk window */
18531 	tcp->tcp_snxt = snxt;
18532 	tcp->tcp_xmit_tail = xmit_tail;
18533 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18534 	    offset;
18535 	tcp->tcp_unsent += shrunk_count;
18536 
18537 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18538 		/*
18539 		 * Make sure the timer is running so that we will probe a zero
18540 		 * window.
18541 		 */
18542 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18543 }
18544 
18545 
18546 /*
18547  * The TCP normal data output path.
18548  * NOTE: the logic of the fast path is duplicated from this function.
18549  */
18550 static void
18551 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18552 {
18553 	int		len;
18554 	mblk_t		*local_time;
18555 	mblk_t		*mp1;
18556 	uint32_t	snxt;
18557 	int		tail_unsent;
18558 	int		tcpstate;
18559 	int		usable = 0;
18560 	mblk_t		*xmit_tail;
18561 	queue_t		*q = tcp->tcp_wq;
18562 	int32_t		mss;
18563 	int32_t		num_sack_blk = 0;
18564 	int32_t		tcp_hdr_len;
18565 	int32_t		tcp_tcp_hdr_len;
18566 	int		mdt_thres;
18567 	int		rc;
18568 
18569 	tcpstate = tcp->tcp_state;
18570 	if (mp == NULL) {
18571 		/*
18572 		 * tcp_wput_data() with NULL mp should only be called when
18573 		 * there is unsent data.
18574 		 */
18575 		ASSERT(tcp->tcp_unsent > 0);
18576 		/* Really tacky... but we need this for detached closes. */
18577 		len = tcp->tcp_unsent;
18578 		goto data_null;
18579 	}
18580 
18581 #if CCS_STATS
18582 	wrw_stats.tot.count++;
18583 	wrw_stats.tot.bytes += msgdsize(mp);
18584 #endif
18585 	ASSERT(mp->b_datap->db_type == M_DATA);
18586 	/*
18587 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18588 	 * or before a connection attempt has begun.
18589 	 */
18590 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18591 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18592 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18593 #ifdef DEBUG
18594 			cmn_err(CE_WARN,
18595 			    "tcp_wput_data: data after ordrel, %s",
18596 			    tcp_display(tcp, NULL,
18597 			    DISP_ADDR_AND_PORT));
18598 #else
18599 			if (tcp->tcp_debug) {
18600 				(void) strlog(TCP_MOD_ID, 0, 1,
18601 				    SL_TRACE|SL_ERROR,
18602 				    "tcp_wput_data: data after ordrel, %s\n",
18603 				    tcp_display(tcp, NULL,
18604 				    DISP_ADDR_AND_PORT));
18605 			}
18606 #endif /* DEBUG */
18607 		}
18608 		if (tcp->tcp_snd_zcopy_aware &&
18609 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18610 			tcp_zcopy_notify(tcp);
18611 		freemsg(mp);
18612 		if (tcp->tcp_flow_stopped &&
18613 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18614 			tcp_clrqfull(tcp);
18615 		}
18616 		return;
18617 	}
18618 
18619 	/* Strip empties */
18620 	for (;;) {
18621 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18622 		    (uintptr_t)INT_MAX);
18623 		len = (int)(mp->b_wptr - mp->b_rptr);
18624 		if (len > 0)
18625 			break;
18626 		mp1 = mp;
18627 		mp = mp->b_cont;
18628 		freeb(mp1);
18629 		if (!mp) {
18630 			return;
18631 		}
18632 	}
18633 
18634 	/* If we are the first on the list ... */
18635 	if (tcp->tcp_xmit_head == NULL) {
18636 		tcp->tcp_xmit_head = mp;
18637 		tcp->tcp_xmit_tail = mp;
18638 		tcp->tcp_xmit_tail_unsent = len;
18639 	} else {
18640 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18641 		struct datab *dp;
18642 
18643 		mp1 = tcp->tcp_xmit_last;
18644 		if (len < tcp_tx_pull_len &&
18645 		    (dp = mp1->b_datap)->db_ref == 1 &&
18646 		    dp->db_lim - mp1->b_wptr >= len) {
18647 			ASSERT(len > 0);
18648 			ASSERT(!mp1->b_cont);
18649 			if (len == 1) {
18650 				*mp1->b_wptr++ = *mp->b_rptr;
18651 			} else {
18652 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18653 				mp1->b_wptr += len;
18654 			}
18655 			if (mp1 == tcp->tcp_xmit_tail)
18656 				tcp->tcp_xmit_tail_unsent += len;
18657 			mp1->b_cont = mp->b_cont;
18658 			if (tcp->tcp_snd_zcopy_aware &&
18659 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18660 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18661 			freeb(mp);
18662 			mp = mp1;
18663 		} else {
18664 			tcp->tcp_xmit_last->b_cont = mp;
18665 		}
18666 		len += tcp->tcp_unsent;
18667 	}
18668 
18669 	/* Tack on however many more positive length mblks we have */
18670 	if ((mp1 = mp->b_cont) != NULL) {
18671 		do {
18672 			int tlen;
18673 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18674 			    (uintptr_t)INT_MAX);
18675 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18676 			if (tlen <= 0) {
18677 				mp->b_cont = mp1->b_cont;
18678 				freeb(mp1);
18679 			} else {
18680 				len += tlen;
18681 				mp = mp1;
18682 			}
18683 		} while ((mp1 = mp->b_cont) != NULL);
18684 	}
18685 	tcp->tcp_xmit_last = mp;
18686 	tcp->tcp_unsent = len;
18687 
18688 	if (urgent)
18689 		usable = 1;
18690 
18691 data_null:
18692 	snxt = tcp->tcp_snxt;
18693 	xmit_tail = tcp->tcp_xmit_tail;
18694 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18695 
18696 	/*
18697 	 * Note that tcp_mss has been adjusted to take into account the
18698 	 * timestamp option if applicable.  Because SACK options do not
18699 	 * appear in every TCP segments and they are of variable lengths,
18700 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18701 	 * the actual segment length when we need to send a segment which
18702 	 * includes SACK options.
18703 	 */
18704 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18705 		int32_t	opt_len;
18706 
18707 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18708 		    tcp->tcp_num_sack_blk);
18709 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18710 		    2 + TCPOPT_HEADER_LEN;
18711 		mss = tcp->tcp_mss - opt_len;
18712 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18713 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18714 	} else {
18715 		mss = tcp->tcp_mss;
18716 		tcp_hdr_len = tcp->tcp_hdr_len;
18717 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18718 	}
18719 
18720 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18721 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18722 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
18723 	}
18724 	if (tcpstate == TCPS_SYN_RCVD) {
18725 		/*
18726 		 * The three-way connection establishment handshake is not
18727 		 * complete yet. We want to queue the data for transmission
18728 		 * after entering ESTABLISHED state (RFC793). A jump to
18729 		 * "done" label effectively leaves data on the queue.
18730 		 */
18731 		goto done;
18732 	} else {
18733 		int usable_r;
18734 
18735 		/*
18736 		 * In the special case when cwnd is zero, which can only
18737 		 * happen if the connection is ECN capable, return now.
18738 		 * New segments is sent using tcp_timer().  The timer
18739 		 * is set in tcp_rput_data().
18740 		 */
18741 		if (tcp->tcp_cwnd == 0) {
18742 			/*
18743 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18744 			 * finished.
18745 			 */
18746 			ASSERT(tcp->tcp_ecn_ok ||
18747 			    tcp->tcp_state < TCPS_ESTABLISHED);
18748 			return;
18749 		}
18750 
18751 		/* NOTE: trouble if xmitting while SYN not acked? */
18752 		usable_r = snxt - tcp->tcp_suna;
18753 		usable_r = tcp->tcp_swnd - usable_r;
18754 
18755 		/*
18756 		 * Check if the receiver has shrunk the window.  If
18757 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18758 		 * cannot be set as there is unsent data, so FIN cannot
18759 		 * be sent out.  Otherwise, we need to take into account
18760 		 * of FIN as it consumes an "invisible" sequence number.
18761 		 */
18762 		ASSERT(tcp->tcp_fin_sent == 0);
18763 		if (usable_r < 0) {
18764 			/*
18765 			 * The receiver has shrunk the window and we have sent
18766 			 * -usable_r date beyond the window, re-adjust.
18767 			 *
18768 			 * If TCP window scaling is enabled, there can be
18769 			 * round down error as the advertised receive window
18770 			 * is actually right shifted n bits.  This means that
18771 			 * the lower n bits info is wiped out.  It will look
18772 			 * like the window is shrunk.  Do a check here to
18773 			 * see if the shrunk amount is actually within the
18774 			 * error in window calculation.  If it is, just
18775 			 * return.  Note that this check is inside the
18776 			 * shrunk window check.  This makes sure that even
18777 			 * though tcp_process_shrunk_swnd() is not called,
18778 			 * we will stop further processing.
18779 			 */
18780 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18781 				tcp_process_shrunk_swnd(tcp, -usable_r);
18782 			}
18783 			return;
18784 		}
18785 
18786 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18787 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18788 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18789 
18790 		/* usable = MIN(usable, unsent) */
18791 		if (usable_r > len)
18792 			usable_r = len;
18793 
18794 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18795 		if (usable_r > 0) {
18796 			usable = usable_r;
18797 		} else {
18798 			/* Bypass all other unnecessary processing. */
18799 			goto done;
18800 		}
18801 	}
18802 
18803 	local_time = (mblk_t *)lbolt;
18804 
18805 	/*
18806 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18807 	 * BSD.  This is more in line with the true intent of Nagle.
18808 	 *
18809 	 * The conditions are:
18810 	 * 1. The amount of unsent data (or amount of data which can be
18811 	 *    sent, whichever is smaller) is less than Nagle limit.
18812 	 * 2. The last sent size is also less than Nagle limit.
18813 	 * 3. There is unack'ed data.
18814 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18815 	 *    Nagle algorithm.  This reduces the probability that urgent
18816 	 *    bytes get "merged" together.
18817 	 * 5. The app has not closed the connection.  This eliminates the
18818 	 *    wait time of the receiving side waiting for the last piece of
18819 	 *    (small) data.
18820 	 *
18821 	 * If all are satisified, exit without sending anything.  Note
18822 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18823 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18824 	 * 4095).
18825 	 */
18826 	if (usable < (int)tcp->tcp_naglim &&
18827 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18828 	    snxt != tcp->tcp_suna &&
18829 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18830 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18831 		goto done;
18832 	}
18833 
18834 	if (tcp->tcp_cork) {
18835 		/*
18836 		 * if the tcp->tcp_cork option is set, then we have to force
18837 		 * TCP not to send partial segment (smaller than MSS bytes).
18838 		 * We are calculating the usable now based on full mss and
18839 		 * will save the rest of remaining data for later.
18840 		 */
18841 		if (usable < mss)
18842 			goto done;
18843 		usable = (usable / mss) * mss;
18844 	}
18845 
18846 	/* Update the latest receive window size in TCP header. */
18847 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18848 	    tcp->tcp_tcph->th_win);
18849 
18850 	/*
18851 	 * Determine if it's worthwhile to attempt MDT, based on:
18852 	 *
18853 	 * 1. Simple TCP/IP{v4,v6} (no options).
18854 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18855 	 * 3. If the TCP connection is in ESTABLISHED state.
18856 	 * 4. The TCP is not detached.
18857 	 *
18858 	 * If any of the above conditions have changed during the
18859 	 * connection, stop using MDT and restore the stream head
18860 	 * parameters accordingly.
18861 	 */
18862 	if (tcp->tcp_mdt &&
18863 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
18864 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
18865 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18866 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
18867 	    tcp->tcp_state != TCPS_ESTABLISHED ||
18868 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
18869 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
18870 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
18871 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
18872 		tcp->tcp_mdt = B_FALSE;
18873 
18874 		/* Anything other than detached is considered pathological */
18875 		if (!TCP_IS_DETACHED(tcp)) {
18876 			TCP_STAT(tcp_mdt_conn_halted1);
18877 			(void) tcp_maxpsz_set(tcp, B_TRUE);
18878 		}
18879 	}
18880 
18881 	/* Use MDT if sendable amount is greater than the threshold */
18882 	if (tcp->tcp_mdt &&
18883 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
18884 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
18885 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
18886 	    (tcp->tcp_valid_bits == 0 ||
18887 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
18888 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
18889 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18890 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18891 		    local_time, mdt_thres);
18892 	} else {
18893 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18894 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18895 		    local_time, INT_MAX);
18896 	}
18897 
18898 	/* Pretend that all we were trying to send really got sent */
18899 	if (rc < 0 && tail_unsent < 0) {
18900 		do {
18901 			xmit_tail = xmit_tail->b_cont;
18902 			xmit_tail->b_prev = local_time;
18903 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
18904 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
18905 			tail_unsent += (int)(xmit_tail->b_wptr -
18906 			    xmit_tail->b_rptr);
18907 		} while (tail_unsent < 0);
18908 	}
18909 done:;
18910 	tcp->tcp_xmit_tail = xmit_tail;
18911 	tcp->tcp_xmit_tail_unsent = tail_unsent;
18912 	len = tcp->tcp_snxt - snxt;
18913 	if (len) {
18914 		/*
18915 		 * If new data was sent, need to update the notsack
18916 		 * list, which is, afterall, data blocks that have
18917 		 * not been sack'ed by the receiver.  New data is
18918 		 * not sack'ed.
18919 		 */
18920 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
18921 			/* len is a negative value. */
18922 			tcp->tcp_pipe -= len;
18923 			tcp_notsack_update(&(tcp->tcp_notsack_list),
18924 			    tcp->tcp_snxt, snxt,
18925 			    &(tcp->tcp_num_notsack_blk),
18926 			    &(tcp->tcp_cnt_notsack_list));
18927 		}
18928 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
18929 		tcp->tcp_rack = tcp->tcp_rnxt;
18930 		tcp->tcp_rack_cnt = 0;
18931 		if ((snxt + len) == tcp->tcp_suna) {
18932 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18933 		}
18934 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
18935 		/*
18936 		 * Didn't send anything. Make sure the timer is running
18937 		 * so that we will probe a zero window.
18938 		 */
18939 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18940 	}
18941 	/* Note that len is the amount we just sent but with a negative sign */
18942 	tcp->tcp_unsent += len;
18943 	if (tcp->tcp_flow_stopped) {
18944 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18945 			tcp_clrqfull(tcp);
18946 		}
18947 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
18948 		tcp_setqfull(tcp);
18949 	}
18950 }
18951 
18952 /*
18953  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
18954  * outgoing TCP header with the template header, as well as other
18955  * options such as time-stamp, ECN and/or SACK.
18956  */
18957 static void
18958 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
18959 {
18960 	tcph_t *tcp_tmpl, *tcp_h;
18961 	uint32_t *dst, *src;
18962 	int hdrlen;
18963 
18964 	ASSERT(OK_32PTR(rptr));
18965 
18966 	/* Template header */
18967 	tcp_tmpl = tcp->tcp_tcph;
18968 
18969 	/* Header of outgoing packet */
18970 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18971 
18972 	/* dst and src are opaque 32-bit fields, used for copying */
18973 	dst = (uint32_t *)rptr;
18974 	src = (uint32_t *)tcp->tcp_iphc;
18975 	hdrlen = tcp->tcp_hdr_len;
18976 
18977 	/* Fill time-stamp option if needed */
18978 	if (tcp->tcp_snd_ts_ok) {
18979 		U32_TO_BE32((uint32_t)now,
18980 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
18981 		U32_TO_BE32(tcp->tcp_ts_recent,
18982 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
18983 	} else {
18984 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18985 	}
18986 
18987 	/*
18988 	 * Copy the template header; is this really more efficient than
18989 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
18990 	 * but perhaps not for other scenarios.
18991 	 */
18992 	dst[0] = src[0];
18993 	dst[1] = src[1];
18994 	dst[2] = src[2];
18995 	dst[3] = src[3];
18996 	dst[4] = src[4];
18997 	dst[5] = src[5];
18998 	dst[6] = src[6];
18999 	dst[7] = src[7];
19000 	dst[8] = src[8];
19001 	dst[9] = src[9];
19002 	if (hdrlen -= 40) {
19003 		hdrlen >>= 2;
19004 		dst += 10;
19005 		src += 10;
19006 		do {
19007 			*dst++ = *src++;
19008 		} while (--hdrlen);
19009 	}
19010 
19011 	/*
19012 	 * Set the ECN info in the TCP header if it is not a zero
19013 	 * window probe.  Zero window probe is only sent in
19014 	 * tcp_wput_data() and tcp_timer().
19015 	 */
19016 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19017 		SET_ECT(tcp, rptr);
19018 
19019 		if (tcp->tcp_ecn_echo_on)
19020 			tcp_h->th_flags[0] |= TH_ECE;
19021 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19022 			tcp_h->th_flags[0] |= TH_CWR;
19023 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19024 		}
19025 	}
19026 
19027 	/* Fill in SACK options */
19028 	if (num_sack_blk > 0) {
19029 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19030 		sack_blk_t *tmp;
19031 		int32_t	i;
19032 
19033 		wptr[0] = TCPOPT_NOP;
19034 		wptr[1] = TCPOPT_NOP;
19035 		wptr[2] = TCPOPT_SACK;
19036 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19037 		    sizeof (sack_blk_t);
19038 		wptr += TCPOPT_REAL_SACK_LEN;
19039 
19040 		tmp = tcp->tcp_sack_list;
19041 		for (i = 0; i < num_sack_blk; i++) {
19042 			U32_TO_BE32(tmp[i].begin, wptr);
19043 			wptr += sizeof (tcp_seq);
19044 			U32_TO_BE32(tmp[i].end, wptr);
19045 			wptr += sizeof (tcp_seq);
19046 		}
19047 		tcp_h->th_offset_and_rsrvd[0] +=
19048 		    ((num_sack_blk * 2 + 1) << 4);
19049 	}
19050 }
19051 
19052 /*
19053  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19054  * the destination address and SAP attribute, and if necessary, the
19055  * hardware checksum offload attribute to a Multidata message.
19056  */
19057 static int
19058 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19059     const uint32_t start, const uint32_t stuff, const uint32_t end,
19060     const uint32_t flags)
19061 {
19062 	/* Add global destination address & SAP attribute */
19063 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19064 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19065 		    "destination address+SAP\n"));
19066 
19067 		if (dlmp != NULL)
19068 			TCP_STAT(tcp_mdt_allocfail);
19069 		return (-1);
19070 	}
19071 
19072 	/* Add global hwcksum attribute */
19073 	if (hwcksum &&
19074 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19075 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19076 		    "checksum attribute\n"));
19077 
19078 		TCP_STAT(tcp_mdt_allocfail);
19079 		return (-1);
19080 	}
19081 
19082 	return (0);
19083 }
19084 
19085 /*
19086  * Smaller and private version of pdescinfo_t used specifically for TCP,
19087  * which allows for only two payload spans per packet.
19088  */
19089 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19090 
19091 /*
19092  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19093  * scheme, and returns one the following:
19094  *
19095  * -1 = failed allocation.
19096  *  0 = success; burst count reached, or usable send window is too small,
19097  *      and that we'd rather wait until later before sending again.
19098  */
19099 static int
19100 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19101     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19102     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19103     const int mdt_thres)
19104 {
19105 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19106 	multidata_t	*mmd;
19107 	uint_t		obsegs, obbytes, hdr_frag_sz;
19108 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19109 	int		num_burst_seg, max_pld;
19110 	pdesc_t		*pkt;
19111 	tcp_pdescinfo_t	tcp_pkt_info;
19112 	pdescinfo_t	*pkt_info;
19113 	int		pbuf_idx, pbuf_idx_nxt;
19114 	int		seg_len, len, spill, af;
19115 	boolean_t	add_buffer, zcopy, clusterwide;
19116 	boolean_t	buf_trunked = B_FALSE;
19117 	boolean_t	rconfirm = B_FALSE;
19118 	boolean_t	done = B_FALSE;
19119 	uint32_t	cksum;
19120 	uint32_t	hwcksum_flags;
19121 	ire_t		*ire;
19122 	ill_t		*ill;
19123 	ipha_t		*ipha;
19124 	ip6_t		*ip6h;
19125 	ipaddr_t	src, dst;
19126 	ill_zerocopy_capab_t *zc_cap = NULL;
19127 	uint16_t	*up;
19128 	int		err;
19129 	conn_t		*connp;
19130 	mblk_t		*mp, *mp1, *fw_mp_head = NULL;
19131 	uchar_t		*pld_start;
19132 
19133 #ifdef	_BIG_ENDIAN
19134 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19135 #else
19136 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19137 #endif
19138 
19139 #define	PREP_NEW_MULTIDATA() {			\
19140 	mmd = NULL;				\
19141 	md_mp = md_hbuf = NULL;			\
19142 	cur_hdr_off = 0;			\
19143 	max_pld = tcp->tcp_mdt_max_pld;		\
19144 	pbuf_idx = pbuf_idx_nxt = -1;		\
19145 	add_buffer = B_TRUE;			\
19146 	zcopy = B_FALSE;			\
19147 }
19148 
19149 #define	PREP_NEW_PBUF() {			\
19150 	md_pbuf = md_pbuf_nxt = NULL;		\
19151 	pbuf_idx = pbuf_idx_nxt = -1;		\
19152 	cur_pld_off = 0;			\
19153 	first_snxt = *snxt;			\
19154 	ASSERT(*tail_unsent > 0);		\
19155 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19156 }
19157 
19158 	ASSERT(mdt_thres >= mss);
19159 	ASSERT(*usable > 0 && *usable > mdt_thres);
19160 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19161 	ASSERT(!TCP_IS_DETACHED(tcp));
19162 	ASSERT(tcp->tcp_valid_bits == 0 ||
19163 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19164 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19165 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19166 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19167 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19168 
19169 	connp = tcp->tcp_connp;
19170 	ASSERT(connp != NULL);
19171 	ASSERT(CONN_IS_MD_FASTPATH(connp));
19172 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19173 
19174 	/*
19175 	 * Note that tcp will only declare at most 2 payload spans per
19176 	 * packet, which is much lower than the maximum allowable number
19177 	 * of packet spans per Multidata.  For this reason, we use the
19178 	 * privately declared and smaller descriptor info structure, in
19179 	 * order to save some stack space.
19180 	 */
19181 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19182 
19183 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19184 	if (af == AF_INET) {
19185 		dst = tcp->tcp_ipha->ipha_dst;
19186 		src = tcp->tcp_ipha->ipha_src;
19187 		ASSERT(!CLASSD(dst));
19188 	}
19189 	ASSERT(af == AF_INET ||
19190 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19191 
19192 	obsegs = obbytes = 0;
19193 	num_burst_seg = tcp->tcp_snd_burst;
19194 	md_mp_head = NULL;
19195 	PREP_NEW_MULTIDATA();
19196 
19197 	/*
19198 	 * Before we go on further, make sure there is an IRE that we can
19199 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19200 	 * in proceeding any further, and we should just hand everything
19201 	 * off to the legacy path.
19202 	 */
19203 	mutex_enter(&connp->conn_lock);
19204 	ire = connp->conn_ire_cache;
19205 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19206 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
19207 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
19208 	    &tcp->tcp_ip6h->ip6_dst))) &&
19209 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19210 		IRE_REFHOLD(ire);
19211 		mutex_exit(&connp->conn_lock);
19212 	} else {
19213 		boolean_t cached = B_FALSE;
19214 		ts_label_t *tsl;
19215 
19216 		/* force a recheck later on */
19217 		tcp->tcp_ire_ill_check_done = B_FALSE;
19218 
19219 		TCP_DBGSTAT(tcp_ire_null1);
19220 		connp->conn_ire_cache = NULL;
19221 		mutex_exit(&connp->conn_lock);
19222 
19223 		/* Release the old ire */
19224 		if (ire != NULL)
19225 			IRE_REFRELE_NOTR(ire);
19226 
19227 		tsl = crgetlabel(CONN_CRED(connp));
19228 		ire = (af == AF_INET) ?
19229 		    ire_cache_lookup(dst, connp->conn_zoneid, tsl) :
19230 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19231 		    connp->conn_zoneid, tsl);
19232 
19233 		if (ire == NULL) {
19234 			TCP_STAT(tcp_ire_null);
19235 			goto legacy_send_no_md;
19236 		}
19237 
19238 		IRE_REFHOLD_NOTR(ire);
19239 		/*
19240 		 * Since we are inside the squeue, there cannot be another
19241 		 * thread in TCP trying to set the conn_ire_cache now. The
19242 		 * check for IRE_MARK_CONDEMNED ensures that an interface
19243 		 * unplumb thread has not yet started cleaning up the conns.
19244 		 * Hence we don't need to grab the conn lock.
19245 		 */
19246 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
19247 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19248 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19249 				connp->conn_ire_cache = ire;
19250 				cached = B_TRUE;
19251 			}
19252 			rw_exit(&ire->ire_bucket->irb_lock);
19253 		}
19254 
19255 		/*
19256 		 * We can continue to use the ire but since it was not
19257 		 * cached, we should drop the extra reference.
19258 		 */
19259 		if (!cached)
19260 			IRE_REFRELE_NOTR(ire);
19261 	}
19262 
19263 	ASSERT(ire != NULL);
19264 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19265 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19266 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19267 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19268 	/*
19269 	 * If we do support loopback for MDT (which requires modifications
19270 	 * to the receiving paths), the following assertions should go away,
19271 	 * and we would be sending the Multidata to loopback conn later on.
19272 	 */
19273 	ASSERT(!IRE_IS_LOCAL(ire));
19274 	ASSERT(ire->ire_stq != NULL);
19275 
19276 	ill = ire_to_ill(ire);
19277 	ASSERT(ill != NULL);
19278 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19279 
19280 	if (!tcp->tcp_ire_ill_check_done) {
19281 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19282 		tcp->tcp_ire_ill_check_done = B_TRUE;
19283 	}
19284 
19285 	/*
19286 	 * If the underlying interface conditions have changed, or if the
19287 	 * new interface does not support MDT, go back to legacy path.
19288 	 */
19289 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19290 		/* don't go through this path anymore for this connection */
19291 		TCP_STAT(tcp_mdt_conn_halted2);
19292 		tcp->tcp_mdt = B_FALSE;
19293 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19294 		    "interface %s\n", (void *)connp, ill->ill_name));
19295 		/* IRE will be released prior to returning */
19296 		goto legacy_send_no_md;
19297 	}
19298 
19299 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19300 		zc_cap = ill->ill_zerocopy_capab;
19301 
19302 	/*
19303 	 * Check if we can take tcp fast-path. Note that "incomplete"
19304 	 * ire's (where the link-layer for next hop is not resolved
19305 	 * or where the fast-path header in nce_fp_mp is not available
19306 	 * yet) are sent down the legacy (slow) path.
19307 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19308 	 */
19309 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19310 		/* IRE will be released prior to returning */
19311 		goto legacy_send_no_md;
19312 	}
19313 
19314 	/* go to legacy path if interface doesn't support zerocopy */
19315 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19316 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19317 		/* IRE will be released prior to returning */
19318 		goto legacy_send_no_md;
19319 	}
19320 
19321 	/* does the interface support hardware checksum offload? */
19322 	hwcksum_flags = 0;
19323 	if (ILL_HCKSUM_CAPABLE(ill) &&
19324 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19325 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19326 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19327 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19328 		    HCKSUM_IPHDRCKSUM)
19329 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19330 
19331 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19332 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19333 			hwcksum_flags |= HCK_FULLCKSUM;
19334 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19335 		    HCKSUM_INET_PARTIAL)
19336 			hwcksum_flags |= HCK_PARTIALCKSUM;
19337 	}
19338 
19339 	/*
19340 	 * Each header fragment consists of the leading extra space,
19341 	 * followed by the TCP/IP header, and the trailing extra space.
19342 	 * We make sure that each header fragment begins on a 32-bit
19343 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19344 	 * aligned in tcp_mdt_update).
19345 	 */
19346 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19347 	    tcp->tcp_mdt_hdr_tail), 4);
19348 
19349 	/* are we starting from the beginning of data block? */
19350 	if (*tail_unsent == 0) {
19351 		*xmit_tail = (*xmit_tail)->b_cont;
19352 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19353 		*tail_unsent = (int)MBLKL(*xmit_tail);
19354 	}
19355 
19356 	/*
19357 	 * Here we create one or more Multidata messages, each made up of
19358 	 * one header buffer and up to N payload buffers.  This entire
19359 	 * operation is done within two loops:
19360 	 *
19361 	 * The outer loop mostly deals with creating the Multidata message,
19362 	 * as well as the header buffer that gets added to it.  It also
19363 	 * links the Multidata messages together such that all of them can
19364 	 * be sent down to the lower layer in a single putnext call; this
19365 	 * linking behavior depends on the tcp_mdt_chain tunable.
19366 	 *
19367 	 * The inner loop takes an existing Multidata message, and adds
19368 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19369 	 * packetizes those buffers by filling up the corresponding header
19370 	 * buffer fragments with the proper IP and TCP headers, and by
19371 	 * describing the layout of each packet in the packet descriptors
19372 	 * that get added to the Multidata.
19373 	 */
19374 	do {
19375 		/*
19376 		 * If usable send window is too small, or data blocks in
19377 		 * transmit list are smaller than our threshold (i.e. app
19378 		 * performs large writes followed by small ones), we hand
19379 		 * off the control over to the legacy path.  Note that we'll
19380 		 * get back the control once it encounters a large block.
19381 		 */
19382 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19383 		    (*xmit_tail)->b_cont != NULL &&
19384 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19385 			/* send down what we've got so far */
19386 			if (md_mp_head != NULL) {
19387 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19388 				    obsegs, obbytes, &rconfirm);
19389 			}
19390 			/*
19391 			 * Pass control over to tcp_send(), but tell it to
19392 			 * return to us once a large-size transmission is
19393 			 * possible.
19394 			 */
19395 			TCP_STAT(tcp_mdt_legacy_small);
19396 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19397 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19398 			    tail_unsent, xmit_tail, local_time,
19399 			    mdt_thres)) <= 0) {
19400 				/* burst count reached, or alloc failed */
19401 				IRE_REFRELE(ire);
19402 				return (err);
19403 			}
19404 
19405 			/* tcp_send() may have sent everything, so check */
19406 			if (*usable <= 0) {
19407 				IRE_REFRELE(ire);
19408 				return (0);
19409 			}
19410 
19411 			TCP_STAT(tcp_mdt_legacy_ret);
19412 			/*
19413 			 * We may have delivered the Multidata, so make sure
19414 			 * to re-initialize before the next round.
19415 			 */
19416 			md_mp_head = NULL;
19417 			obsegs = obbytes = 0;
19418 			num_burst_seg = tcp->tcp_snd_burst;
19419 			PREP_NEW_MULTIDATA();
19420 
19421 			/* are we starting from the beginning of data block? */
19422 			if (*tail_unsent == 0) {
19423 				*xmit_tail = (*xmit_tail)->b_cont;
19424 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19425 				    (uintptr_t)INT_MAX);
19426 				*tail_unsent = (int)MBLKL(*xmit_tail);
19427 			}
19428 		}
19429 
19430 		/*
19431 		 * max_pld limits the number of mblks in tcp's transmit
19432 		 * queue that can be added to a Multidata message.  Once
19433 		 * this counter reaches zero, no more additional mblks
19434 		 * can be added to it.  What happens afterwards depends
19435 		 * on whether or not we are set to chain the Multidata
19436 		 * messages.  If we are to link them together, reset
19437 		 * max_pld to its original value (tcp_mdt_max_pld) and
19438 		 * prepare to create a new Multidata message which will
19439 		 * get linked to md_mp_head.  Else, leave it alone and
19440 		 * let the inner loop break on its own.
19441 		 */
19442 		if (tcp_mdt_chain && max_pld == 0)
19443 			PREP_NEW_MULTIDATA();
19444 
19445 		/* adding a payload buffer; re-initialize values */
19446 		if (add_buffer)
19447 			PREP_NEW_PBUF();
19448 
19449 		/*
19450 		 * If we don't have a Multidata, either because we just
19451 		 * (re)entered this outer loop, or after we branched off
19452 		 * to tcp_send above, setup the Multidata and header
19453 		 * buffer to be used.
19454 		 */
19455 		if (md_mp == NULL) {
19456 			int md_hbuflen;
19457 			uint32_t start, stuff;
19458 
19459 			/*
19460 			 * Calculate Multidata header buffer size large enough
19461 			 * to hold all of the headers that can possibly be
19462 			 * sent at this moment.  We'd rather over-estimate
19463 			 * the size than running out of space; this is okay
19464 			 * since this buffer is small anyway.
19465 			 */
19466 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19467 
19468 			/*
19469 			 * Start and stuff offset for partial hardware
19470 			 * checksum offload; these are currently for IPv4.
19471 			 * For full checksum offload, they are set to zero.
19472 			 */
19473 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19474 				if (af == AF_INET) {
19475 					start = IP_SIMPLE_HDR_LENGTH;
19476 					stuff = IP_SIMPLE_HDR_LENGTH +
19477 					    TCP_CHECKSUM_OFFSET;
19478 				} else {
19479 					start = IPV6_HDR_LEN;
19480 					stuff = IPV6_HDR_LEN +
19481 					    TCP_CHECKSUM_OFFSET;
19482 				}
19483 			} else {
19484 				start = stuff = 0;
19485 			}
19486 
19487 			/*
19488 			 * Create the header buffer, Multidata, as well as
19489 			 * any necessary attributes (destination address,
19490 			 * SAP and hardware checksum offload) that should
19491 			 * be associated with the Multidata message.
19492 			 */
19493 			ASSERT(cur_hdr_off == 0);
19494 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19495 			    ((md_hbuf->b_wptr += md_hbuflen),
19496 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19497 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19498 			    /* fastpath mblk */
19499 			    ire->ire_nce->nce_res_mp,
19500 			    /* hardware checksum enabled */
19501 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19502 			    /* hardware checksum offsets */
19503 			    start, stuff, 0,
19504 			    /* hardware checksum flag */
19505 			    hwcksum_flags) != 0)) {
19506 legacy_send:
19507 				if (md_mp != NULL) {
19508 					/* Unlink message from the chain */
19509 					if (md_mp_head != NULL) {
19510 						err = (intptr_t)rmvb(md_mp_head,
19511 						    md_mp);
19512 						/*
19513 						 * We can't assert that rmvb
19514 						 * did not return -1, since we
19515 						 * may get here before linkb
19516 						 * happens.  We do, however,
19517 						 * check if we just removed the
19518 						 * only element in the list.
19519 						 */
19520 						if (err == 0)
19521 							md_mp_head = NULL;
19522 					}
19523 					/* md_hbuf gets freed automatically */
19524 					TCP_STAT(tcp_mdt_discarded);
19525 					freeb(md_mp);
19526 				} else {
19527 					/* Either allocb or mmd_alloc failed */
19528 					TCP_STAT(tcp_mdt_allocfail);
19529 					if (md_hbuf != NULL)
19530 						freeb(md_hbuf);
19531 				}
19532 
19533 				/* send down what we've got so far */
19534 				if (md_mp_head != NULL) {
19535 					tcp_multisend_data(tcp, ire, ill,
19536 					    md_mp_head, obsegs, obbytes,
19537 					    &rconfirm);
19538 				}
19539 legacy_send_no_md:
19540 				if (ire != NULL)
19541 					IRE_REFRELE(ire);
19542 				/*
19543 				 * Too bad; let the legacy path handle this.
19544 				 * We specify INT_MAX for the threshold, since
19545 				 * we gave up with the Multidata processings
19546 				 * and let the old path have it all.
19547 				 */
19548 				TCP_STAT(tcp_mdt_legacy_all);
19549 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19550 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19551 				    snxt, tail_unsent, xmit_tail, local_time,
19552 				    INT_MAX));
19553 			}
19554 
19555 			/* link to any existing ones, if applicable */
19556 			TCP_STAT(tcp_mdt_allocd);
19557 			if (md_mp_head == NULL) {
19558 				md_mp_head = md_mp;
19559 			} else if (tcp_mdt_chain) {
19560 				TCP_STAT(tcp_mdt_linked);
19561 				linkb(md_mp_head, md_mp);
19562 			}
19563 		}
19564 
19565 		ASSERT(md_mp_head != NULL);
19566 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19567 		ASSERT(md_mp != NULL && mmd != NULL);
19568 		ASSERT(md_hbuf != NULL);
19569 
19570 		/*
19571 		 * Packetize the transmittable portion of the data block;
19572 		 * each data block is essentially added to the Multidata
19573 		 * as a payload buffer.  We also deal with adding more
19574 		 * than one payload buffers, which happens when the remaining
19575 		 * packetized portion of the current payload buffer is less
19576 		 * than MSS, while the next data block in transmit queue
19577 		 * has enough data to make up for one.  This "spillover"
19578 		 * case essentially creates a split-packet, where portions
19579 		 * of the packet's payload fragments may span across two
19580 		 * virtually discontiguous address blocks.
19581 		 */
19582 		seg_len = mss;
19583 		do {
19584 			len = seg_len;
19585 
19586 			ASSERT(len > 0);
19587 			ASSERT(max_pld >= 0);
19588 			ASSERT(!add_buffer || cur_pld_off == 0);
19589 
19590 			/*
19591 			 * First time around for this payload buffer; note
19592 			 * in the case of a spillover, the following has
19593 			 * been done prior to adding the split-packet
19594 			 * descriptor to Multidata, and we don't want to
19595 			 * repeat the process.
19596 			 */
19597 			if (add_buffer) {
19598 				ASSERT(mmd != NULL);
19599 				ASSERT(md_pbuf == NULL);
19600 				ASSERT(md_pbuf_nxt == NULL);
19601 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19602 
19603 				/*
19604 				 * Have we reached the limit?  We'd get to
19605 				 * this case when we're not chaining the
19606 				 * Multidata messages together, and since
19607 				 * we're done, terminate this loop.
19608 				 */
19609 				if (max_pld == 0)
19610 					break; /* done */
19611 
19612 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19613 					TCP_STAT(tcp_mdt_allocfail);
19614 					goto legacy_send; /* out_of_mem */
19615 				}
19616 
19617 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19618 				    zc_cap != NULL) {
19619 					if (!ip_md_zcopy_attr(mmd, NULL,
19620 					    zc_cap->ill_zerocopy_flags)) {
19621 						freeb(md_pbuf);
19622 						TCP_STAT(tcp_mdt_allocfail);
19623 						/* out_of_mem */
19624 						goto legacy_send;
19625 					}
19626 					zcopy = B_TRUE;
19627 				}
19628 
19629 				md_pbuf->b_rptr += base_pld_off;
19630 
19631 				/*
19632 				 * Add a payload buffer to the Multidata; this
19633 				 * operation must not fail, or otherwise our
19634 				 * logic in this routine is broken.  There
19635 				 * is no memory allocation done by the
19636 				 * routine, so any returned failure simply
19637 				 * tells us that we've done something wrong.
19638 				 *
19639 				 * A failure tells us that either we're adding
19640 				 * the same payload buffer more than once, or
19641 				 * we're trying to add more buffers than
19642 				 * allowed (max_pld calculation is wrong).
19643 				 * None of the above cases should happen, and
19644 				 * we panic because either there's horrible
19645 				 * heap corruption, and/or programming mistake.
19646 				 */
19647 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19648 				if (pbuf_idx < 0) {
19649 					cmn_err(CE_PANIC, "tcp_multisend: "
19650 					    "payload buffer logic error "
19651 					    "detected for tcp %p mmd %p "
19652 					    "pbuf %p (%d)\n",
19653 					    (void *)tcp, (void *)mmd,
19654 					    (void *)md_pbuf, pbuf_idx);
19655 				}
19656 
19657 				ASSERT(max_pld > 0);
19658 				--max_pld;
19659 				add_buffer = B_FALSE;
19660 			}
19661 
19662 			ASSERT(md_mp_head != NULL);
19663 			ASSERT(md_pbuf != NULL);
19664 			ASSERT(md_pbuf_nxt == NULL);
19665 			ASSERT(pbuf_idx != -1);
19666 			ASSERT(pbuf_idx_nxt == -1);
19667 			ASSERT(*usable > 0);
19668 
19669 			/*
19670 			 * We spillover to the next payload buffer only
19671 			 * if all of the following is true:
19672 			 *
19673 			 *   1. There is not enough data on the current
19674 			 *	payload buffer to make up `len',
19675 			 *   2. We are allowed to send `len',
19676 			 *   3. The next payload buffer length is large
19677 			 *	enough to accomodate `spill'.
19678 			 */
19679 			if ((spill = len - *tail_unsent) > 0 &&
19680 			    *usable >= len &&
19681 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19682 			    max_pld > 0) {
19683 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19684 				if (md_pbuf_nxt == NULL) {
19685 					TCP_STAT(tcp_mdt_allocfail);
19686 					goto legacy_send; /* out_of_mem */
19687 				}
19688 
19689 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19690 				    zc_cap != NULL) {
19691 					if (!ip_md_zcopy_attr(mmd, NULL,
19692 					    zc_cap->ill_zerocopy_flags)) {
19693 						freeb(md_pbuf_nxt);
19694 						TCP_STAT(tcp_mdt_allocfail);
19695 						/* out_of_mem */
19696 						goto legacy_send;
19697 					}
19698 					zcopy = B_TRUE;
19699 				}
19700 
19701 				/*
19702 				 * See comments above on the first call to
19703 				 * mmd_addpldbuf for explanation on the panic.
19704 				 */
19705 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19706 				if (pbuf_idx_nxt < 0) {
19707 					panic("tcp_multisend: "
19708 					    "next payload buffer logic error "
19709 					    "detected for tcp %p mmd %p "
19710 					    "pbuf %p (%d)\n",
19711 					    (void *)tcp, (void *)mmd,
19712 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19713 				}
19714 
19715 				ASSERT(max_pld > 0);
19716 				--max_pld;
19717 			} else if (spill > 0) {
19718 				/*
19719 				 * If there's a spillover, but the following
19720 				 * xmit_tail couldn't give us enough octets
19721 				 * to reach "len", then stop the current
19722 				 * Multidata creation and let the legacy
19723 				 * tcp_send() path take over.  We don't want
19724 				 * to send the tiny segment as part of this
19725 				 * Multidata for performance reasons; instead,
19726 				 * we let the legacy path deal with grouping
19727 				 * it with the subsequent small mblks.
19728 				 */
19729 				if (*usable >= len &&
19730 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19731 					max_pld = 0;
19732 					break;	/* done */
19733 				}
19734 
19735 				/*
19736 				 * We can't spillover, and we are near
19737 				 * the end of the current payload buffer,
19738 				 * so send what's left.
19739 				 */
19740 				ASSERT(*tail_unsent > 0);
19741 				len = *tail_unsent;
19742 			}
19743 
19744 			/* tail_unsent is negated if there is a spillover */
19745 			*tail_unsent -= len;
19746 			*usable -= len;
19747 			ASSERT(*usable >= 0);
19748 
19749 			if (*usable < mss)
19750 				seg_len = *usable;
19751 			/*
19752 			 * Sender SWS avoidance; see comments in tcp_send();
19753 			 * everything else is the same, except that we only
19754 			 * do this here if there is no more data to be sent
19755 			 * following the current xmit_tail.  We don't check
19756 			 * for 1-byte urgent data because we shouldn't get
19757 			 * here if TCP_URG_VALID is set.
19758 			 */
19759 			if (*usable > 0 && *usable < mss &&
19760 			    ((md_pbuf_nxt == NULL &&
19761 			    (*xmit_tail)->b_cont == NULL) ||
19762 			    (md_pbuf_nxt != NULL &&
19763 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19764 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19765 			    (tcp->tcp_unsent -
19766 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19767 			    !tcp->tcp_zero_win_probe) {
19768 				if ((*snxt + len) == tcp->tcp_snxt &&
19769 				    (*snxt + len) == tcp->tcp_suna) {
19770 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19771 				}
19772 				done = B_TRUE;
19773 			}
19774 
19775 			/*
19776 			 * Prime pump for IP's checksumming on our behalf;
19777 			 * include the adjustment for a source route if any.
19778 			 * Do this only for software/partial hardware checksum
19779 			 * offload, as this field gets zeroed out later for
19780 			 * the full hardware checksum offload case.
19781 			 */
19782 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19783 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19784 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19785 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19786 			}
19787 
19788 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19789 			*snxt += len;
19790 
19791 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19792 			/*
19793 			 * We set the PUSH bit only if TCP has no more buffered
19794 			 * data to be transmitted (or if sender SWS avoidance
19795 			 * takes place), as opposed to setting it for every
19796 			 * last packet in the burst.
19797 			 */
19798 			if (done ||
19799 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19800 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19801 
19802 			/*
19803 			 * Set FIN bit if this is our last segment; snxt
19804 			 * already includes its length, and it will not
19805 			 * be adjusted after this point.
19806 			 */
19807 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19808 			    *snxt == tcp->tcp_fss) {
19809 				if (!tcp->tcp_fin_acked) {
19810 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19811 					BUMP_MIB(&tcp_mib, tcpOutControl);
19812 				}
19813 				if (!tcp->tcp_fin_sent) {
19814 					tcp->tcp_fin_sent = B_TRUE;
19815 					/*
19816 					 * tcp state must be ESTABLISHED
19817 					 * in order for us to get here in
19818 					 * the first place.
19819 					 */
19820 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19821 
19822 					/*
19823 					 * Upon returning from this routine,
19824 					 * tcp_wput_data() will set tcp_snxt
19825 					 * to be equal to snxt + tcp_fin_sent.
19826 					 * This is essentially the same as
19827 					 * setting it to tcp_fss + 1.
19828 					 */
19829 				}
19830 			}
19831 
19832 			tcp->tcp_last_sent_len = (ushort_t)len;
19833 
19834 			len += tcp_hdr_len;
19835 			if (tcp->tcp_ipversion == IPV4_VERSION)
19836 				tcp->tcp_ipha->ipha_length = htons(len);
19837 			else
19838 				tcp->tcp_ip6h->ip6_plen = htons(len -
19839 				    ((char *)&tcp->tcp_ip6h[1] -
19840 				    tcp->tcp_iphc));
19841 
19842 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19843 
19844 			/* setup header fragment */
19845 			PDESC_HDR_ADD(pkt_info,
19846 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19847 			    tcp->tcp_mdt_hdr_head,		/* head room */
19848 			    tcp_hdr_len,			/* len */
19849 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19850 
19851 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
19852 			    hdr_frag_sz);
19853 			ASSERT(MBLKIN(md_hbuf,
19854 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
19855 			    PDESC_HDRSIZE(pkt_info)));
19856 
19857 			/* setup first payload fragment */
19858 			PDESC_PLD_INIT(pkt_info);
19859 			PDESC_PLD_SPAN_ADD(pkt_info,
19860 			    pbuf_idx,				/* index */
19861 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
19862 			    tcp->tcp_last_sent_len);		/* len */
19863 
19864 			/* create a split-packet in case of a spillover */
19865 			if (md_pbuf_nxt != NULL) {
19866 				ASSERT(spill > 0);
19867 				ASSERT(pbuf_idx_nxt > pbuf_idx);
19868 				ASSERT(!add_buffer);
19869 
19870 				md_pbuf = md_pbuf_nxt;
19871 				md_pbuf_nxt = NULL;
19872 				pbuf_idx = pbuf_idx_nxt;
19873 				pbuf_idx_nxt = -1;
19874 				cur_pld_off = spill;
19875 
19876 				/* trim out first payload fragment */
19877 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
19878 
19879 				/* setup second payload fragment */
19880 				PDESC_PLD_SPAN_ADD(pkt_info,
19881 				    pbuf_idx,			/* index */
19882 				    md_pbuf->b_rptr,		/* start */
19883 				    spill);			/* len */
19884 
19885 				if ((*xmit_tail)->b_next == NULL) {
19886 					/*
19887 					 * Store the lbolt used for RTT
19888 					 * estimation. We can only record one
19889 					 * timestamp per mblk so we do it when
19890 					 * we reach the end of the payload
19891 					 * buffer.  Also we only take a new
19892 					 * timestamp sample when the previous
19893 					 * timed data from the same mblk has
19894 					 * been ack'ed.
19895 					 */
19896 					(*xmit_tail)->b_prev = local_time;
19897 					(*xmit_tail)->b_next =
19898 					    (mblk_t *)(uintptr_t)first_snxt;
19899 				}
19900 
19901 				first_snxt = *snxt - spill;
19902 
19903 				/*
19904 				 * Advance xmit_tail; usable could be 0 by
19905 				 * the time we got here, but we made sure
19906 				 * above that we would only spillover to
19907 				 * the next data block if usable includes
19908 				 * the spilled-over amount prior to the
19909 				 * subtraction.  Therefore, we are sure
19910 				 * that xmit_tail->b_cont can't be NULL.
19911 				 */
19912 				ASSERT((*xmit_tail)->b_cont != NULL);
19913 				*xmit_tail = (*xmit_tail)->b_cont;
19914 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19915 				    (uintptr_t)INT_MAX);
19916 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
19917 			} else {
19918 				cur_pld_off += tcp->tcp_last_sent_len;
19919 			}
19920 
19921 			/*
19922 			 * Fill in the header using the template header, and
19923 			 * add options such as time-stamp, ECN and/or SACK,
19924 			 * as needed.
19925 			 */
19926 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
19927 			    (clock_t)local_time, num_sack_blk);
19928 
19929 			/* take care of some IP header businesses */
19930 			if (af == AF_INET) {
19931 				ipha = (ipha_t *)pkt_info->hdr_rptr;
19932 
19933 				ASSERT(OK_32PTR((uchar_t *)ipha));
19934 				ASSERT(PDESC_HDRL(pkt_info) >=
19935 				    IP_SIMPLE_HDR_LENGTH);
19936 				ASSERT(ipha->ipha_version_and_hdr_length ==
19937 				    IP_SIMPLE_HDR_VERSION);
19938 
19939 				/*
19940 				 * Assign ident value for current packet; see
19941 				 * related comments in ip_wput_ire() about the
19942 				 * contract private interface with clustering
19943 				 * group.
19944 				 */
19945 				clusterwide = B_FALSE;
19946 				if (cl_inet_ipident != NULL) {
19947 					ASSERT(cl_inet_isclusterwide != NULL);
19948 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19949 					    AF_INET,
19950 					    (uint8_t *)(uintptr_t)src)) {
19951 						ipha->ipha_ident =
19952 						    (*cl_inet_ipident)
19953 						    (IPPROTO_IP, AF_INET,
19954 						    (uint8_t *)(uintptr_t)src,
19955 						    (uint8_t *)(uintptr_t)dst);
19956 						clusterwide = B_TRUE;
19957 					}
19958 				}
19959 
19960 				if (!clusterwide) {
19961 					ipha->ipha_ident = (uint16_t)
19962 					    atomic_add_32_nv(
19963 						&ire->ire_ident, 1);
19964 				}
19965 #ifndef _BIG_ENDIAN
19966 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
19967 				    (ipha->ipha_ident >> 8);
19968 #endif
19969 			} else {
19970 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
19971 
19972 				ASSERT(OK_32PTR((uchar_t *)ip6h));
19973 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
19974 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
19975 				ASSERT(PDESC_HDRL(pkt_info) >=
19976 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
19977 				    TCP_CHECKSUM_SIZE));
19978 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
19979 
19980 				if (tcp->tcp_ip_forward_progress) {
19981 					rconfirm = B_TRUE;
19982 					tcp->tcp_ip_forward_progress = B_FALSE;
19983 				}
19984 			}
19985 
19986 			/* at least one payload span, and at most two */
19987 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
19988 
19989 			/* add the packet descriptor to Multidata */
19990 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
19991 			    KM_NOSLEEP)) == NULL) {
19992 				/*
19993 				 * Any failure other than ENOMEM indicates
19994 				 * that we have passed in invalid pkt_info
19995 				 * or parameters to mmd_addpdesc, which must
19996 				 * not happen.
19997 				 *
19998 				 * EINVAL is a result of failure on boundary
19999 				 * checks against the pkt_info contents.  It
20000 				 * should not happen, and we panic because
20001 				 * either there's horrible heap corruption,
20002 				 * and/or programming mistake.
20003 				 */
20004 				if (err != ENOMEM) {
20005 					cmn_err(CE_PANIC, "tcp_multisend: "
20006 					    "pdesc logic error detected for "
20007 					    "tcp %p mmd %p pinfo %p (%d)\n",
20008 					    (void *)tcp, (void *)mmd,
20009 					    (void *)pkt_info, err);
20010 				}
20011 				TCP_STAT(tcp_mdt_addpdescfail);
20012 				goto legacy_send; /* out_of_mem */
20013 			}
20014 			ASSERT(pkt != NULL);
20015 
20016 			/* calculate IP header and TCP checksums */
20017 			if (af == AF_INET) {
20018 				/* calculate pseudo-header checksum */
20019 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20020 				    (src >> 16) + (src & 0xFFFF);
20021 
20022 				/* offset for TCP header checksum */
20023 				up = IPH_TCPH_CHECKSUMP(ipha,
20024 				    IP_SIMPLE_HDR_LENGTH);
20025 			} else {
20026 				up = (uint16_t *)&ip6h->ip6_src;
20027 
20028 				/* calculate pseudo-header checksum */
20029 				cksum = up[0] + up[1] + up[2] + up[3] +
20030 				    up[4] + up[5] + up[6] + up[7] +
20031 				    up[8] + up[9] + up[10] + up[11] +
20032 				    up[12] + up[13] + up[14] + up[15];
20033 
20034 				/* Fold the initial sum */
20035 				cksum = (cksum & 0xffff) + (cksum >> 16);
20036 
20037 				up = (uint16_t *)(((uchar_t *)ip6h) +
20038 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20039 			}
20040 
20041 			if (hwcksum_flags & HCK_FULLCKSUM) {
20042 				/* clear checksum field for hardware */
20043 				*up = 0;
20044 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20045 				uint32_t sum;
20046 
20047 				/* pseudo-header checksumming */
20048 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20049 				sum = (sum & 0xFFFF) + (sum >> 16);
20050 				*up = (sum & 0xFFFF) + (sum >> 16);
20051 			} else {
20052 				/* software checksumming */
20053 				TCP_STAT(tcp_out_sw_cksum);
20054 				TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
20055 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20056 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20057 				    cksum + IP_TCP_CSUM_COMP);
20058 				if (*up == 0)
20059 					*up = 0xFFFF;
20060 			}
20061 
20062 			/* IPv4 header checksum */
20063 			if (af == AF_INET) {
20064 				ipha->ipha_fragment_offset_and_flags |=
20065 				    (uint32_t)htons(ire->ire_frag_flag);
20066 
20067 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20068 					ipha->ipha_hdr_checksum = 0;
20069 				} else {
20070 					IP_HDR_CKSUM(ipha, cksum,
20071 					    ((uint32_t *)ipha)[0],
20072 					    ((uint16_t *)ipha)[4]);
20073 				}
20074 			}
20075 
20076 			if (af == AF_INET && HOOKS4_INTERESTED_PHYSICAL_OUT||
20077 			    af == AF_INET6 && HOOKS6_INTERESTED_PHYSICAL_OUT) {
20078 				/* build header(IP/TCP) mblk for this segment */
20079 				if ((mp = dupb(md_hbuf)) == NULL)
20080 					goto legacy_send;
20081 
20082 				mp->b_rptr = pkt_info->hdr_rptr;
20083 				mp->b_wptr = pkt_info->hdr_wptr;
20084 
20085 				/* build payload mblk for this segment */
20086 				if ((mp1 = dupb(*xmit_tail)) == NULL) {
20087 					freemsg(mp);
20088 					goto legacy_send;
20089 				}
20090 				mp1->b_wptr = md_pbuf->b_rptr + cur_pld_off;
20091 				mp1->b_rptr = mp1->b_wptr -
20092 				    tcp->tcp_last_sent_len;
20093 				linkb(mp, mp1);
20094 
20095 				pld_start = mp1->b_rptr;
20096 
20097 				if (af == AF_INET) {
20098 					DTRACE_PROBE4(
20099 					    ip4__physical__out__start,
20100 					    ill_t *, NULL,
20101 					    ill_t *, ill,
20102 					    ipha_t *, ipha,
20103 					    mblk_t *, mp);
20104 					FW_HOOKS(ip4_physical_out_event,
20105 					    ipv4firewall_physical_out,
20106 					    NULL, ill, ipha, mp, mp);
20107 					DTRACE_PROBE1(
20108 					    ip4__physical__out__end,
20109 					    mblk_t *, mp);
20110 				} else {
20111 					DTRACE_PROBE4(
20112 					    ip6__physical__out_start,
20113 					    ill_t *, NULL,
20114 					    ill_t *, ill,
20115 					    ip6_t *, ip6h,
20116 					    mblk_t *, mp);
20117 					FW_HOOKS6(ip6_physical_out_event,
20118 					    ipv6firewall_physical_out,
20119 					    NULL, ill, ip6h, mp, mp);
20120 					DTRACE_PROBE1(
20121 					    ip6__physical__out__end,
20122 					    mblk_t *, mp);
20123 				}
20124 
20125 				if (buf_trunked && mp != NULL) {
20126 					/*
20127 					 * Need to pass it to normal path.
20128 					 */
20129 					CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20130 				} else if (mp == NULL ||
20131 				    mp->b_rptr != pkt_info->hdr_rptr ||
20132 				    mp->b_wptr != pkt_info->hdr_wptr ||
20133 				    (mp1 = mp->b_cont) == NULL ||
20134 				    mp1->b_rptr != pld_start ||
20135 				    mp1->b_wptr != pld_start +
20136 				    tcp->tcp_last_sent_len ||
20137 				    mp1->b_cont != NULL) {
20138 					/*
20139 					 * Need to pass all packets of this
20140 					 * buffer to normal path, either when
20141 					 * packet is blocked, or when boundary
20142 					 * of header buffer or payload buffer
20143 					 * has been changed by FW_HOOKS[6].
20144 					 */
20145 					buf_trunked = B_TRUE;
20146 					if (md_mp_head != NULL) {
20147 						err = (intptr_t)rmvb(md_mp_head,
20148 						    md_mp);
20149 						if (err == 0)
20150 							md_mp_head = NULL;
20151 					}
20152 
20153 					/* send down what we've got so far */
20154 					if (md_mp_head != NULL) {
20155 						tcp_multisend_data(tcp, ire,
20156 						    ill, md_mp_head, obsegs,
20157 						    obbytes, &rconfirm);
20158 					}
20159 					md_mp_head = NULL;
20160 
20161 					if (mp != NULL)
20162 						CALL_IP_WPUT(tcp->tcp_connp,
20163 						    q, mp);
20164 
20165 					mp1 = fw_mp_head;
20166 					do {
20167 						mp = mp1;
20168 						mp1 = mp1->b_next;
20169 						mp->b_next = NULL;
20170 						mp->b_prev = NULL;
20171 						CALL_IP_WPUT(tcp->tcp_connp,
20172 						    q, mp);
20173 					} while (mp1 != NULL);
20174 
20175 					fw_mp_head = NULL;
20176 				} else {
20177 					if (fw_mp_head == NULL)
20178 						fw_mp_head = mp;
20179 					else
20180 						fw_mp_head->b_prev->b_next = mp;
20181 					fw_mp_head->b_prev = mp;
20182 				}
20183 			}
20184 
20185 			/* advance header offset */
20186 			cur_hdr_off += hdr_frag_sz;
20187 
20188 			obbytes += tcp->tcp_last_sent_len;
20189 			++obsegs;
20190 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20191 		    *tail_unsent > 0);
20192 
20193 		if ((*xmit_tail)->b_next == NULL) {
20194 			/*
20195 			 * Store the lbolt used for RTT estimation. We can only
20196 			 * record one timestamp per mblk so we do it when we
20197 			 * reach the end of the payload buffer. Also we only
20198 			 * take a new timestamp sample when the previous timed
20199 			 * data from the same mblk has been ack'ed.
20200 			 */
20201 			(*xmit_tail)->b_prev = local_time;
20202 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20203 		}
20204 
20205 		ASSERT(*tail_unsent >= 0);
20206 		if (*tail_unsent > 0) {
20207 			/*
20208 			 * We got here because we broke out of the above
20209 			 * loop due to of one of the following cases:
20210 			 *
20211 			 *   1. len < adjusted MSS (i.e. small),
20212 			 *   2. Sender SWS avoidance,
20213 			 *   3. max_pld is zero.
20214 			 *
20215 			 * We are done for this Multidata, so trim our
20216 			 * last payload buffer (if any) accordingly.
20217 			 */
20218 			if (md_pbuf != NULL)
20219 				md_pbuf->b_wptr -= *tail_unsent;
20220 		} else if (*usable > 0) {
20221 			*xmit_tail = (*xmit_tail)->b_cont;
20222 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20223 			    (uintptr_t)INT_MAX);
20224 			*tail_unsent = (int)MBLKL(*xmit_tail);
20225 			add_buffer = B_TRUE;
20226 		}
20227 
20228 		while (fw_mp_head) {
20229 			mp = fw_mp_head;
20230 			fw_mp_head = fw_mp_head->b_next;
20231 			mp->b_prev = mp->b_next = NULL;
20232 			freemsg(mp);
20233 		}
20234 		if (buf_trunked) {
20235 			TCP_STAT(tcp_mdt_discarded);
20236 			freeb(md_mp);
20237 			buf_trunked = B_FALSE;
20238 		}
20239 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20240 	    (tcp_mdt_chain || max_pld > 0));
20241 
20242 	if (md_mp_head != NULL) {
20243 		/* send everything down */
20244 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20245 		    &rconfirm);
20246 	}
20247 
20248 #undef PREP_NEW_MULTIDATA
20249 #undef PREP_NEW_PBUF
20250 #undef IPVER
20251 
20252 	IRE_REFRELE(ire);
20253 	return (0);
20254 }
20255 
20256 /*
20257  * A wrapper function for sending one or more Multidata messages down to
20258  * the module below ip; this routine does not release the reference of the
20259  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20260  */
20261 static void
20262 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20263     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20264 {
20265 	uint64_t delta;
20266 	nce_t *nce;
20267 
20268 	ASSERT(ire != NULL && ill != NULL);
20269 	ASSERT(ire->ire_stq != NULL);
20270 	ASSERT(md_mp_head != NULL);
20271 	ASSERT(rconfirm != NULL);
20272 
20273 	/* adjust MIBs and IRE timestamp */
20274 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20275 	tcp->tcp_obsegs += obsegs;
20276 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
20277 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
20278 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
20279 
20280 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20281 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
20282 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
20283 	} else {
20284 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
20285 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
20286 	}
20287 
20288 	ire->ire_ob_pkt_count += obsegs;
20289 	if (ire->ire_ipif != NULL)
20290 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20291 	ire->ire_last_used_time = lbolt;
20292 
20293 	/* send it down */
20294 	putnext(ire->ire_stq, md_mp_head);
20295 
20296 	/* we're done for TCP/IPv4 */
20297 	if (tcp->tcp_ipversion == IPV4_VERSION)
20298 		return;
20299 
20300 	nce = ire->ire_nce;
20301 
20302 	ASSERT(nce != NULL);
20303 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20304 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20305 
20306 	/* reachability confirmation? */
20307 	if (*rconfirm) {
20308 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20309 		if (nce->nce_state != ND_REACHABLE) {
20310 			mutex_enter(&nce->nce_lock);
20311 			nce->nce_state = ND_REACHABLE;
20312 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20313 			mutex_exit(&nce->nce_lock);
20314 			(void) untimeout(nce->nce_timeout_id);
20315 			if (ip_debug > 2) {
20316 				/* ip1dbg */
20317 				pr_addr_dbg("tcp_multisend_data: state "
20318 				    "for %s changed to REACHABLE\n",
20319 				    AF_INET6, &ire->ire_addr_v6);
20320 			}
20321 		}
20322 		/* reset transport reachability confirmation */
20323 		*rconfirm = B_FALSE;
20324 	}
20325 
20326 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20327 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20328 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20329 
20330 	if (delta > (uint64_t)ill->ill_reachable_time) {
20331 		mutex_enter(&nce->nce_lock);
20332 		switch (nce->nce_state) {
20333 		case ND_REACHABLE:
20334 		case ND_STALE:
20335 			/*
20336 			 * ND_REACHABLE is identical to ND_STALE in this
20337 			 * specific case. If reachable time has expired for
20338 			 * this neighbor (delta is greater than reachable
20339 			 * time), conceptually, the neighbor cache is no
20340 			 * longer in REACHABLE state, but already in STALE
20341 			 * state.  So the correct transition here is to
20342 			 * ND_DELAY.
20343 			 */
20344 			nce->nce_state = ND_DELAY;
20345 			mutex_exit(&nce->nce_lock);
20346 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
20347 			if (ip_debug > 3) {
20348 				/* ip2dbg */
20349 				pr_addr_dbg("tcp_multisend_data: state "
20350 				    "for %s changed to DELAY\n",
20351 				    AF_INET6, &ire->ire_addr_v6);
20352 			}
20353 			break;
20354 		case ND_DELAY:
20355 		case ND_PROBE:
20356 			mutex_exit(&nce->nce_lock);
20357 			/* Timers have already started */
20358 			break;
20359 		case ND_UNREACHABLE:
20360 			/*
20361 			 * ndp timer has detected that this nce is
20362 			 * unreachable and initiated deleting this nce
20363 			 * and all its associated IREs. This is a race
20364 			 * where we found the ire before it was deleted
20365 			 * and have just sent out a packet using this
20366 			 * unreachable nce.
20367 			 */
20368 			mutex_exit(&nce->nce_lock);
20369 			break;
20370 		default:
20371 			ASSERT(0);
20372 		}
20373 	}
20374 }
20375 
20376 /*
20377  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20378  * scheme, and returns one of the following:
20379  *
20380  * -1 = failed allocation.
20381  *  0 = success; burst count reached, or usable send window is too small,
20382  *      and that we'd rather wait until later before sending again.
20383  *  1 = success; we are called from tcp_multisend(), and both usable send
20384  *      window and tail_unsent are greater than the MDT threshold, and thus
20385  *      Multidata Transmit should be used instead.
20386  */
20387 static int
20388 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20389     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20390     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20391     const int mdt_thres)
20392 {
20393 	int num_burst_seg = tcp->tcp_snd_burst;
20394 
20395 	for (;;) {
20396 		struct datab	*db;
20397 		tcph_t		*tcph;
20398 		uint32_t	sum;
20399 		mblk_t		*mp, *mp1;
20400 		uchar_t		*rptr;
20401 		int		len;
20402 
20403 		/*
20404 		 * If we're called by tcp_multisend(), and the amount of
20405 		 * sendable data as well as the size of current xmit_tail
20406 		 * is beyond the MDT threshold, return to the caller and
20407 		 * let the large data transmit be done using MDT.
20408 		 */
20409 		if (*usable > 0 && *usable > mdt_thres &&
20410 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20411 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20412 			ASSERT(tcp->tcp_mdt);
20413 			return (1);	/* success; do large send */
20414 		}
20415 
20416 		if (num_burst_seg-- == 0)
20417 			break;		/* success; burst count reached */
20418 
20419 		len = mss;
20420 		if (len > *usable) {
20421 			len = *usable;
20422 			if (len <= 0) {
20423 				/* Terminate the loop */
20424 				break;	/* success; too small */
20425 			}
20426 			/*
20427 			 * Sender silly-window avoidance.
20428 			 * Ignore this if we are going to send a
20429 			 * zero window probe out.
20430 			 *
20431 			 * TODO: force data into microscopic window?
20432 			 *	==> (!pushed || (unsent > usable))
20433 			 */
20434 			if (len < (tcp->tcp_max_swnd >> 1) &&
20435 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20436 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20437 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20438 				/*
20439 				 * If the retransmit timer is not running
20440 				 * we start it so that we will retransmit
20441 				 * in the case when the the receiver has
20442 				 * decremented the window.
20443 				 */
20444 				if (*snxt == tcp->tcp_snxt &&
20445 				    *snxt == tcp->tcp_suna) {
20446 					/*
20447 					 * We are not supposed to send
20448 					 * anything.  So let's wait a little
20449 					 * bit longer before breaking SWS
20450 					 * avoidance.
20451 					 *
20452 					 * What should the value be?
20453 					 * Suggestion: MAX(init rexmit time,
20454 					 * tcp->tcp_rto)
20455 					 */
20456 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20457 				}
20458 				break;	/* success; too small */
20459 			}
20460 		}
20461 
20462 		tcph = tcp->tcp_tcph;
20463 
20464 		*usable -= len; /* Approximate - can be adjusted later */
20465 		if (*usable > 0)
20466 			tcph->th_flags[0] = TH_ACK;
20467 		else
20468 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20469 
20470 		/*
20471 		 * Prime pump for IP's checksumming on our behalf
20472 		 * Include the adjustment for a source route if any.
20473 		 */
20474 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20475 		sum = (sum >> 16) + (sum & 0xFFFF);
20476 		U16_TO_ABE16(sum, tcph->th_sum);
20477 
20478 		U32_TO_ABE32(*snxt, tcph->th_seq);
20479 
20480 		/*
20481 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20482 		 * set.  For the case when TCP_FSS_VALID is the only valid
20483 		 * bit (normal active close), branch off only when we think
20484 		 * that the FIN flag needs to be set.  Note for this case,
20485 		 * that (snxt + len) may not reflect the actual seg_len,
20486 		 * as len may be further reduced in tcp_xmit_mp().  If len
20487 		 * gets modified, we will end up here again.
20488 		 */
20489 		if (tcp->tcp_valid_bits != 0 &&
20490 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20491 		    ((*snxt + len) == tcp->tcp_fss))) {
20492 			uchar_t		*prev_rptr;
20493 			uint32_t	prev_snxt = tcp->tcp_snxt;
20494 
20495 			if (*tail_unsent == 0) {
20496 				ASSERT((*xmit_tail)->b_cont != NULL);
20497 				*xmit_tail = (*xmit_tail)->b_cont;
20498 				prev_rptr = (*xmit_tail)->b_rptr;
20499 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20500 				    (*xmit_tail)->b_rptr);
20501 			} else {
20502 				prev_rptr = (*xmit_tail)->b_rptr;
20503 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20504 				    *tail_unsent;
20505 			}
20506 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20507 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20508 			/* Restore tcp_snxt so we get amount sent right. */
20509 			tcp->tcp_snxt = prev_snxt;
20510 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20511 				/*
20512 				 * If the previous timestamp is still in use,
20513 				 * don't stomp on it.
20514 				 */
20515 				if ((*xmit_tail)->b_next == NULL) {
20516 					(*xmit_tail)->b_prev = local_time;
20517 					(*xmit_tail)->b_next =
20518 					    (mblk_t *)(uintptr_t)(*snxt);
20519 				}
20520 			} else
20521 				(*xmit_tail)->b_rptr = prev_rptr;
20522 
20523 			if (mp == NULL)
20524 				return (-1);
20525 			mp1 = mp->b_cont;
20526 
20527 			tcp->tcp_last_sent_len = (ushort_t)len;
20528 			while (mp1->b_cont) {
20529 				*xmit_tail = (*xmit_tail)->b_cont;
20530 				(*xmit_tail)->b_prev = local_time;
20531 				(*xmit_tail)->b_next =
20532 				    (mblk_t *)(uintptr_t)(*snxt);
20533 				mp1 = mp1->b_cont;
20534 			}
20535 			*snxt += len;
20536 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20537 			BUMP_LOCAL(tcp->tcp_obsegs);
20538 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20539 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20540 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20541 			tcp_send_data(tcp, q, mp);
20542 			continue;
20543 		}
20544 
20545 		*snxt += len;	/* Adjust later if we don't send all of len */
20546 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20547 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20548 
20549 		if (*tail_unsent) {
20550 			/* Are the bytes above us in flight? */
20551 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20552 			if (rptr != (*xmit_tail)->b_rptr) {
20553 				*tail_unsent -= len;
20554 				tcp->tcp_last_sent_len = (ushort_t)len;
20555 				len += tcp_hdr_len;
20556 				if (tcp->tcp_ipversion == IPV4_VERSION)
20557 					tcp->tcp_ipha->ipha_length = htons(len);
20558 				else
20559 					tcp->tcp_ip6h->ip6_plen =
20560 					    htons(len -
20561 					    ((char *)&tcp->tcp_ip6h[1] -
20562 					    tcp->tcp_iphc));
20563 				mp = dupb(*xmit_tail);
20564 				if (!mp)
20565 					return (-1);	/* out_of_mem */
20566 				mp->b_rptr = rptr;
20567 				/*
20568 				 * If the old timestamp is no longer in use,
20569 				 * sample a new timestamp now.
20570 				 */
20571 				if ((*xmit_tail)->b_next == NULL) {
20572 					(*xmit_tail)->b_prev = local_time;
20573 					(*xmit_tail)->b_next =
20574 					    (mblk_t *)(uintptr_t)(*snxt-len);
20575 				}
20576 				goto must_alloc;
20577 			}
20578 		} else {
20579 			*xmit_tail = (*xmit_tail)->b_cont;
20580 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20581 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20582 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20583 			    (*xmit_tail)->b_rptr);
20584 		}
20585 
20586 		(*xmit_tail)->b_prev = local_time;
20587 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20588 
20589 		*tail_unsent -= len;
20590 		tcp->tcp_last_sent_len = (ushort_t)len;
20591 
20592 		len += tcp_hdr_len;
20593 		if (tcp->tcp_ipversion == IPV4_VERSION)
20594 			tcp->tcp_ipha->ipha_length = htons(len);
20595 		else
20596 			tcp->tcp_ip6h->ip6_plen = htons(len -
20597 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20598 
20599 		mp = dupb(*xmit_tail);
20600 		if (!mp)
20601 			return (-1);	/* out_of_mem */
20602 
20603 		len = tcp_hdr_len;
20604 		/*
20605 		 * There are four reasons to allocate a new hdr mblk:
20606 		 *  1) The bytes above us are in use by another packet
20607 		 *  2) We don't have good alignment
20608 		 *  3) The mblk is being shared
20609 		 *  4) We don't have enough room for a header
20610 		 */
20611 		rptr = mp->b_rptr - len;
20612 		if (!OK_32PTR(rptr) ||
20613 		    ((db = mp->b_datap), db->db_ref != 2) ||
20614 		    rptr < db->db_base) {
20615 			/* NOTE: we assume allocb returns an OK_32PTR */
20616 
20617 		must_alloc:;
20618 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20619 			    tcp_wroff_xtra, BPRI_MED);
20620 			if (!mp1) {
20621 				freemsg(mp);
20622 				return (-1);	/* out_of_mem */
20623 			}
20624 			mp1->b_cont = mp;
20625 			mp = mp1;
20626 			/* Leave room for Link Level header */
20627 			len = tcp_hdr_len;
20628 			rptr = &mp->b_rptr[tcp_wroff_xtra];
20629 			mp->b_wptr = &rptr[len];
20630 		}
20631 
20632 		/*
20633 		 * Fill in the header using the template header, and add
20634 		 * options such as time-stamp, ECN and/or SACK, as needed.
20635 		 */
20636 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20637 
20638 		mp->b_rptr = rptr;
20639 
20640 		if (*tail_unsent) {
20641 			int spill = *tail_unsent;
20642 
20643 			mp1 = mp->b_cont;
20644 			if (!mp1)
20645 				mp1 = mp;
20646 
20647 			/*
20648 			 * If we're a little short, tack on more mblks until
20649 			 * there is no more spillover.
20650 			 */
20651 			while (spill < 0) {
20652 				mblk_t *nmp;
20653 				int nmpsz;
20654 
20655 				nmp = (*xmit_tail)->b_cont;
20656 				nmpsz = MBLKL(nmp);
20657 
20658 				/*
20659 				 * Excess data in mblk; can we split it?
20660 				 * If MDT is enabled for the connection,
20661 				 * keep on splitting as this is a transient
20662 				 * send path.
20663 				 */
20664 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
20665 					/*
20666 					 * Don't split if stream head was
20667 					 * told to break up larger writes
20668 					 * into smaller ones.
20669 					 */
20670 					if (tcp->tcp_maxpsz > 0)
20671 						break;
20672 
20673 					/*
20674 					 * Next mblk is less than SMSS/2
20675 					 * rounded up to nearest 64-byte;
20676 					 * let it get sent as part of the
20677 					 * next segment.
20678 					 */
20679 					if (tcp->tcp_localnet &&
20680 					    !tcp->tcp_cork &&
20681 					    (nmpsz < roundup((mss >> 1), 64)))
20682 						break;
20683 				}
20684 
20685 				*xmit_tail = nmp;
20686 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
20687 				/* Stash for rtt use later */
20688 				(*xmit_tail)->b_prev = local_time;
20689 				(*xmit_tail)->b_next =
20690 				    (mblk_t *)(uintptr_t)(*snxt - len);
20691 				mp1->b_cont = dupb(*xmit_tail);
20692 				mp1 = mp1->b_cont;
20693 
20694 				spill += nmpsz;
20695 				if (mp1 == NULL) {
20696 					*tail_unsent = spill;
20697 					freemsg(mp);
20698 					return (-1);	/* out_of_mem */
20699 				}
20700 			}
20701 
20702 			/* Trim back any surplus on the last mblk */
20703 			if (spill >= 0) {
20704 				mp1->b_wptr -= spill;
20705 				*tail_unsent = spill;
20706 			} else {
20707 				/*
20708 				 * We did not send everything we could in
20709 				 * order to remain within the b_cont limit.
20710 				 */
20711 				*usable -= spill;
20712 				*snxt += spill;
20713 				tcp->tcp_last_sent_len += spill;
20714 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
20715 				/*
20716 				 * Adjust the checksum
20717 				 */
20718 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20719 				sum += spill;
20720 				sum = (sum >> 16) + (sum & 0xFFFF);
20721 				U16_TO_ABE16(sum, tcph->th_sum);
20722 				if (tcp->tcp_ipversion == IPV4_VERSION) {
20723 					sum = ntohs(
20724 					    ((ipha_t *)rptr)->ipha_length) +
20725 					    spill;
20726 					((ipha_t *)rptr)->ipha_length =
20727 					    htons(sum);
20728 				} else {
20729 					sum = ntohs(
20730 					    ((ip6_t *)rptr)->ip6_plen) +
20731 					    spill;
20732 					((ip6_t *)rptr)->ip6_plen =
20733 					    htons(sum);
20734 				}
20735 				*tail_unsent = 0;
20736 			}
20737 		}
20738 		if (tcp->tcp_ip_forward_progress) {
20739 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20740 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20741 			tcp->tcp_ip_forward_progress = B_FALSE;
20742 		}
20743 
20744 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20745 		tcp_send_data(tcp, q, mp);
20746 		BUMP_LOCAL(tcp->tcp_obsegs);
20747 	}
20748 
20749 	return (0);
20750 }
20751 
20752 /* Unlink and return any mblk that looks like it contains a MDT info */
20753 static mblk_t *
20754 tcp_mdt_info_mp(mblk_t *mp)
20755 {
20756 	mblk_t	*prev_mp;
20757 
20758 	for (;;) {
20759 		prev_mp = mp;
20760 		/* no more to process? */
20761 		if ((mp = mp->b_cont) == NULL)
20762 			break;
20763 
20764 		switch (DB_TYPE(mp)) {
20765 		case M_CTL:
20766 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20767 				continue;
20768 			ASSERT(prev_mp != NULL);
20769 			prev_mp->b_cont = mp->b_cont;
20770 			mp->b_cont = NULL;
20771 			return (mp);
20772 		default:
20773 			break;
20774 		}
20775 	}
20776 	return (mp);
20777 }
20778 
20779 /* MDT info update routine, called when IP notifies us about MDT */
20780 static void
20781 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20782 {
20783 	boolean_t prev_state;
20784 
20785 	/*
20786 	 * IP is telling us to abort MDT on this connection?  We know
20787 	 * this because the capability is only turned off when IP
20788 	 * encounters some pathological cases, e.g. link-layer change
20789 	 * where the new driver doesn't support MDT, or in situation
20790 	 * where MDT usage on the link-layer has been switched off.
20791 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20792 	 * if the link-layer doesn't support MDT, and if it does, it
20793 	 * will indicate that the feature is to be turned on.
20794 	 */
20795 	prev_state = tcp->tcp_mdt;
20796 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20797 	if (!tcp->tcp_mdt && !first) {
20798 		TCP_STAT(tcp_mdt_conn_halted3);
20799 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20800 		    (void *)tcp->tcp_connp));
20801 	}
20802 
20803 	/*
20804 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20805 	 * so disable MDT otherwise.  The checks are done here
20806 	 * and in tcp_wput_data().
20807 	 */
20808 	if (tcp->tcp_mdt &&
20809 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20810 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20811 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20812 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20813 		tcp->tcp_mdt = B_FALSE;
20814 
20815 	if (tcp->tcp_mdt) {
20816 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
20817 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
20818 			    "version (%d), expected version is %d",
20819 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
20820 			tcp->tcp_mdt = B_FALSE;
20821 			return;
20822 		}
20823 
20824 		/*
20825 		 * We need the driver to be able to handle at least three
20826 		 * spans per packet in order for tcp MDT to be utilized.
20827 		 * The first is for the header portion, while the rest are
20828 		 * needed to handle a packet that straddles across two
20829 		 * virtually non-contiguous buffers; a typical tcp packet
20830 		 * therefore consists of only two spans.  Note that we take
20831 		 * a zero as "don't care".
20832 		 */
20833 		if (mdt_capab->ill_mdt_span_limit > 0 &&
20834 		    mdt_capab->ill_mdt_span_limit < 3) {
20835 			tcp->tcp_mdt = B_FALSE;
20836 			return;
20837 		}
20838 
20839 		/* a zero means driver wants default value */
20840 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
20841 		    tcp_mdt_max_pbufs);
20842 		if (tcp->tcp_mdt_max_pld == 0)
20843 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
20844 
20845 		/* ensure 32-bit alignment */
20846 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
20847 		    mdt_capab->ill_mdt_hdr_head), 4);
20848 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
20849 		    mdt_capab->ill_mdt_hdr_tail), 4);
20850 
20851 		if (!first && !prev_state) {
20852 			TCP_STAT(tcp_mdt_conn_resumed2);
20853 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
20854 			    (void *)tcp->tcp_connp));
20855 		}
20856 	}
20857 }
20858 
20859 static void
20860 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
20861 {
20862 	conn_t *connp = tcp->tcp_connp;
20863 
20864 	ASSERT(ire != NULL);
20865 
20866 	/*
20867 	 * We may be in the fastpath here, and although we essentially do
20868 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
20869 	 * we try to keep things as brief as possible.  After all, these
20870 	 * are only best-effort checks, and we do more thorough ones prior
20871 	 * to calling tcp_multisend().
20872 	 */
20873 	if (ip_multidata_outbound && check_mdt &&
20874 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
20875 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
20876 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
20877 	    !(ire->ire_flags & RTF_MULTIRT) &&
20878 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
20879 	    CONN_IS_MD_FASTPATH(connp)) {
20880 		/* Remember the result */
20881 		connp->conn_mdt_ok = B_TRUE;
20882 
20883 		ASSERT(ill->ill_mdt_capab != NULL);
20884 		if (!ill->ill_mdt_capab->ill_mdt_on) {
20885 			/*
20886 			 * If MDT has been previously turned off in the past,
20887 			 * and we currently can do MDT (due to IPQoS policy
20888 			 * removal, etc.) then enable it for this interface.
20889 			 */
20890 			ill->ill_mdt_capab->ill_mdt_on = 1;
20891 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
20892 			    "interface %s\n", (void *)connp, ill->ill_name));
20893 		}
20894 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
20895 	}
20896 
20897 	/*
20898 	 * The goal is to reduce the number of generated tcp segments by
20899 	 * setting the maxpsz multiplier to 0; this will have an affect on
20900 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
20901 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
20902 	 * of outbound segments and incoming ACKs, thus allowing for better
20903 	 * network and system performance.  In contrast the legacy behavior
20904 	 * may result in sending less than SMSS size, because the last mblk
20905 	 * for some packets may have more data than needed to make up SMSS,
20906 	 * and the legacy code refused to "split" it.
20907 	 *
20908 	 * We apply the new behavior on following situations:
20909 	 *
20910 	 *   1) Loopback connections,
20911 	 *   2) Connections in which the remote peer is not on local subnet,
20912 	 *   3) Local subnet connections over the bge interface (see below).
20913 	 *
20914 	 * Ideally, we would like this behavior to apply for interfaces other
20915 	 * than bge.  However, doing so would negatively impact drivers which
20916 	 * perform dynamic mapping and unmapping of DMA resources, which are
20917 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
20918 	 * packet will be generated by tcp).  The bge driver does not suffer
20919 	 * from this, as it copies the mblks into pre-mapped buffers, and
20920 	 * therefore does not require more I/O resources than before.
20921 	 *
20922 	 * Otherwise, this behavior is present on all network interfaces when
20923 	 * the destination endpoint is non-local, since reducing the number
20924 	 * of packets in general is good for the network.
20925 	 *
20926 	 * TODO We need to remove this hard-coded conditional for bge once
20927 	 *	a better "self-tuning" mechanism, or a way to comprehend
20928 	 *	the driver transmit strategy is devised.  Until the solution
20929 	 *	is found and well understood, we live with this hack.
20930 	 */
20931 	if (!tcp_static_maxpsz &&
20932 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
20933 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
20934 		/* override the default value */
20935 		tcp->tcp_maxpsz = 0;
20936 
20937 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
20938 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
20939 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
20940 	}
20941 
20942 	/* set the stream head parameters accordingly */
20943 	(void) tcp_maxpsz_set(tcp, B_TRUE);
20944 }
20945 
20946 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
20947 static void
20948 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
20949 {
20950 	uchar_t	fval = *mp->b_rptr;
20951 	mblk_t	*tail;
20952 	queue_t	*q = tcp->tcp_wq;
20953 
20954 	/* TODO: How should flush interact with urgent data? */
20955 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
20956 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
20957 		/*
20958 		 * Flush only data that has not yet been put on the wire.  If
20959 		 * we flush data that we have already transmitted, life, as we
20960 		 * know it, may come to an end.
20961 		 */
20962 		tail = tcp->tcp_xmit_tail;
20963 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
20964 		tcp->tcp_xmit_tail_unsent = 0;
20965 		tcp->tcp_unsent = 0;
20966 		if (tail->b_wptr != tail->b_rptr)
20967 			tail = tail->b_cont;
20968 		if (tail) {
20969 			mblk_t **excess = &tcp->tcp_xmit_head;
20970 			for (;;) {
20971 				mblk_t *mp1 = *excess;
20972 				if (mp1 == tail)
20973 					break;
20974 				tcp->tcp_xmit_tail = mp1;
20975 				tcp->tcp_xmit_last = mp1;
20976 				excess = &mp1->b_cont;
20977 			}
20978 			*excess = NULL;
20979 			tcp_close_mpp(&tail);
20980 			if (tcp->tcp_snd_zcopy_aware)
20981 				tcp_zcopy_notify(tcp);
20982 		}
20983 		/*
20984 		 * We have no unsent data, so unsent must be less than
20985 		 * tcp_xmit_lowater, so re-enable flow.
20986 		 */
20987 		if (tcp->tcp_flow_stopped) {
20988 			tcp_clrqfull(tcp);
20989 		}
20990 	}
20991 	/*
20992 	 * TODO: you can't just flush these, you have to increase rwnd for one
20993 	 * thing.  For another, how should urgent data interact?
20994 	 */
20995 	if (fval & FLUSHR) {
20996 		*mp->b_rptr = fval & ~FLUSHW;
20997 		/* XXX */
20998 		qreply(q, mp);
20999 		return;
21000 	}
21001 	freemsg(mp);
21002 }
21003 
21004 /*
21005  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21006  * messages.
21007  */
21008 static void
21009 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21010 {
21011 	mblk_t	*mp1;
21012 	STRUCT_HANDLE(strbuf, sb);
21013 	uint16_t port;
21014 	queue_t 	*q = tcp->tcp_wq;
21015 	in6_addr_t	v6addr;
21016 	ipaddr_t	v4addr;
21017 	uint32_t	flowinfo = 0;
21018 	int		addrlen;
21019 
21020 	/* Make sure it is one of ours. */
21021 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21022 	case TI_GETMYNAME:
21023 	case TI_GETPEERNAME:
21024 		break;
21025 	default:
21026 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21027 		return;
21028 	}
21029 	switch (mi_copy_state(q, mp, &mp1)) {
21030 	case -1:
21031 		return;
21032 	case MI_COPY_CASE(MI_COPY_IN, 1):
21033 		break;
21034 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21035 		/* Copy out the strbuf. */
21036 		mi_copyout(q, mp);
21037 		return;
21038 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21039 		/* All done. */
21040 		mi_copy_done(q, mp, 0);
21041 		return;
21042 	default:
21043 		mi_copy_done(q, mp, EPROTO);
21044 		return;
21045 	}
21046 	/* Check alignment of the strbuf */
21047 	if (!OK_32PTR(mp1->b_rptr)) {
21048 		mi_copy_done(q, mp, EINVAL);
21049 		return;
21050 	}
21051 
21052 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
21053 	    (void *)mp1->b_rptr);
21054 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21055 
21056 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21057 		mi_copy_done(q, mp, EINVAL);
21058 		return;
21059 	}
21060 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21061 	case TI_GETMYNAME:
21062 		if (tcp->tcp_family == AF_INET) {
21063 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21064 				v4addr = tcp->tcp_ipha->ipha_src;
21065 			} else {
21066 				/* can't return an address in this case */
21067 				v4addr = 0;
21068 			}
21069 		} else {
21070 			/* tcp->tcp_family == AF_INET6 */
21071 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21072 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
21073 				    &v6addr);
21074 			} else {
21075 				v6addr = tcp->tcp_ip6h->ip6_src;
21076 			}
21077 		}
21078 		port = tcp->tcp_lport;
21079 		break;
21080 	case TI_GETPEERNAME:
21081 		if (tcp->tcp_family == AF_INET) {
21082 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21083 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
21084 				    v4addr);
21085 			} else {
21086 				/* can't return an address in this case */
21087 				v4addr = 0;
21088 			}
21089 		} else {
21090 			/* tcp->tcp_family == AF_INET6) */
21091 			v6addr = tcp->tcp_remote_v6;
21092 			if (tcp->tcp_ipversion == IPV6_VERSION) {
21093 				/*
21094 				 * No flowinfo if tcp->tcp_ipversion is v4.
21095 				 *
21096 				 * flowinfo was already initialized to zero
21097 				 * where it was declared above, so only
21098 				 * set it if ipversion is v6.
21099 				 */
21100 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
21101 				    ~IPV6_VERS_AND_FLOW_MASK;
21102 			}
21103 		}
21104 		port = tcp->tcp_fport;
21105 		break;
21106 	default:
21107 		mi_copy_done(q, mp, EPROTO);
21108 		return;
21109 	}
21110 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21111 	if (!mp1)
21112 		return;
21113 
21114 	if (tcp->tcp_family == AF_INET) {
21115 		sin_t *sin;
21116 
21117 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
21118 		sin = (sin_t *)mp1->b_rptr;
21119 		mp1->b_wptr = (uchar_t *)&sin[1];
21120 		*sin = sin_null;
21121 		sin->sin_family = AF_INET;
21122 		sin->sin_addr.s_addr = v4addr;
21123 		sin->sin_port = port;
21124 	} else {
21125 		/* tcp->tcp_family == AF_INET6 */
21126 		sin6_t *sin6;
21127 
21128 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
21129 		sin6 = (sin6_t *)mp1->b_rptr;
21130 		mp1->b_wptr = (uchar_t *)&sin6[1];
21131 		*sin6 = sin6_null;
21132 		sin6->sin6_family = AF_INET6;
21133 		sin6->sin6_flowinfo = flowinfo;
21134 		sin6->sin6_addr = v6addr;
21135 		sin6->sin6_port = port;
21136 	}
21137 	/* Copy out the address */
21138 	mi_copyout(q, mp);
21139 }
21140 
21141 /*
21142  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21143  * messages.
21144  */
21145 /* ARGSUSED */
21146 static void
21147 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21148 {
21149 	conn_t 	*connp = (conn_t *)arg;
21150 	tcp_t	*tcp = connp->conn_tcp;
21151 	queue_t	*q = tcp->tcp_wq;
21152 	struct iocblk	*iocp;
21153 
21154 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21155 	/*
21156 	 * Try and ASSERT the minimum possible references on the
21157 	 * conn early enough. Since we are executing on write side,
21158 	 * the connection is obviously not detached and that means
21159 	 * there is a ref each for TCP and IP. Since we are behind
21160 	 * the squeue, the minimum references needed are 3. If the
21161 	 * conn is in classifier hash list, there should be an
21162 	 * extra ref for that (we check both the possibilities).
21163 	 */
21164 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21165 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21166 
21167 	iocp = (struct iocblk *)mp->b_rptr;
21168 	switch (iocp->ioc_cmd) {
21169 	case TCP_IOC_DEFAULT_Q:
21170 		/* Wants to be the default wq. */
21171 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
21172 			iocp->ioc_error = EPERM;
21173 			iocp->ioc_count = 0;
21174 			mp->b_datap->db_type = M_IOCACK;
21175 			qreply(q, mp);
21176 			return;
21177 		}
21178 		tcp_def_q_set(tcp, mp);
21179 		return;
21180 	case _SIOCSOCKFALLBACK:
21181 		/*
21182 		 * Either sockmod is about to be popped and the socket
21183 		 * would now be treated as a plain stream, or a module
21184 		 * is about to be pushed so we could no longer use read-
21185 		 * side synchronous streams for fused loopback tcp.
21186 		 * Drain any queued data and disable direct sockfs
21187 		 * interface from now on.
21188 		 */
21189 		if (!tcp->tcp_issocket) {
21190 			DB_TYPE(mp) = M_IOCNAK;
21191 			iocp->ioc_error = EINVAL;
21192 		} else {
21193 #ifdef	_ILP32
21194 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
21195 #else
21196 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21197 #endif
21198 			/*
21199 			 * Insert this socket into the acceptor hash.
21200 			 * We might need it for T_CONN_RES message
21201 			 */
21202 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21203 
21204 			if (tcp->tcp_fused) {
21205 				/*
21206 				 * This is a fused loopback tcp; disable
21207 				 * read-side synchronous streams interface
21208 				 * and drain any queued data.  It is okay
21209 				 * to do this for non-synchronous streams
21210 				 * fused tcp as well.
21211 				 */
21212 				tcp_fuse_disable_pair(tcp, B_FALSE);
21213 			}
21214 			tcp->tcp_issocket = B_FALSE;
21215 			TCP_STAT(tcp_sock_fallback);
21216 
21217 			DB_TYPE(mp) = M_IOCACK;
21218 			iocp->ioc_error = 0;
21219 		}
21220 		iocp->ioc_count = 0;
21221 		iocp->ioc_rval = 0;
21222 		qreply(q, mp);
21223 		return;
21224 	}
21225 	CALL_IP_WPUT(connp, q, mp);
21226 }
21227 
21228 /*
21229  * This routine is called by tcp_wput() to handle all TPI requests.
21230  */
21231 /* ARGSUSED */
21232 static void
21233 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21234 {
21235 	conn_t 	*connp = (conn_t *)arg;
21236 	tcp_t	*tcp = connp->conn_tcp;
21237 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21238 	uchar_t *rptr;
21239 	t_scalar_t type;
21240 	int len;
21241 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
21242 
21243 	/*
21244 	 * Try and ASSERT the minimum possible references on the
21245 	 * conn early enough. Since we are executing on write side,
21246 	 * the connection is obviously not detached and that means
21247 	 * there is a ref each for TCP and IP. Since we are behind
21248 	 * the squeue, the minimum references needed are 3. If the
21249 	 * conn is in classifier hash list, there should be an
21250 	 * extra ref for that (we check both the possibilities).
21251 	 */
21252 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21253 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21254 
21255 	rptr = mp->b_rptr;
21256 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21257 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21258 		type = ((union T_primitives *)rptr)->type;
21259 		if (type == T_EXDATA_REQ) {
21260 			uint32_t msize = msgdsize(mp->b_cont);
21261 
21262 			len = msize - 1;
21263 			if (len < 0) {
21264 				freemsg(mp);
21265 				return;
21266 			}
21267 			/*
21268 			 * Try to force urgent data out on the wire.
21269 			 * Even if we have unsent data this will
21270 			 * at least send the urgent flag.
21271 			 * XXX does not handle more flag correctly.
21272 			 */
21273 			len += tcp->tcp_unsent;
21274 			len += tcp->tcp_snxt;
21275 			tcp->tcp_urg = len;
21276 			tcp->tcp_valid_bits |= TCP_URG_VALID;
21277 
21278 			/* Bypass tcp protocol for fused tcp loopback */
21279 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
21280 				return;
21281 		} else if (type != T_DATA_REQ) {
21282 			goto non_urgent_data;
21283 		}
21284 		/* TODO: options, flags, ... from user */
21285 		/* Set length to zero for reclamation below */
21286 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21287 		freeb(mp);
21288 		return;
21289 	} else {
21290 		if (tcp->tcp_debug) {
21291 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21292 			    "tcp_wput_proto, dropping one...");
21293 		}
21294 		freemsg(mp);
21295 		return;
21296 	}
21297 
21298 non_urgent_data:
21299 
21300 	switch ((int)tprim->type) {
21301 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21302 		/*
21303 		 * save the kssl_ent_t from the next block, and convert this
21304 		 * back to a normal bind_req.
21305 		 */
21306 		if (mp->b_cont != NULL) {
21307 		    ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21308 
21309 			if (tcp->tcp_kssl_ent != NULL) {
21310 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21311 				    KSSL_NO_PROXY);
21312 				tcp->tcp_kssl_ent = NULL;
21313 			}
21314 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21315 			    sizeof (kssl_ent_t));
21316 			kssl_hold_ent(tcp->tcp_kssl_ent);
21317 			freemsg(mp->b_cont);
21318 			mp->b_cont = NULL;
21319 		}
21320 		tprim->type = T_BIND_REQ;
21321 
21322 	/* FALLTHROUGH */
21323 	case O_T_BIND_REQ:	/* bind request */
21324 	case T_BIND_REQ:	/* new semantics bind request */
21325 		tcp_bind(tcp, mp);
21326 		break;
21327 	case T_UNBIND_REQ:	/* unbind request */
21328 		tcp_unbind(tcp, mp);
21329 		break;
21330 	case O_T_CONN_RES:	/* old connection response XXX */
21331 	case T_CONN_RES:	/* connection response */
21332 		tcp_accept(tcp, mp);
21333 		break;
21334 	case T_CONN_REQ:	/* connection request */
21335 		tcp_connect(tcp, mp);
21336 		break;
21337 	case T_DISCON_REQ:	/* disconnect request */
21338 		tcp_disconnect(tcp, mp);
21339 		break;
21340 	case T_CAPABILITY_REQ:
21341 		tcp_capability_req(tcp, mp);	/* capability request */
21342 		break;
21343 	case T_INFO_REQ:	/* information request */
21344 		tcp_info_req(tcp, mp);
21345 		break;
21346 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21347 		/* Only IP is allowed to return meaningful value */
21348 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21349 		break;
21350 	case T_OPTMGMT_REQ:
21351 		/*
21352 		 * Note:  no support for snmpcom_req() through new
21353 		 * T_OPTMGMT_REQ. See comments in ip.c
21354 		 */
21355 		/* Only IP is allowed to return meaningful value */
21356 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21357 		break;
21358 
21359 	case T_UNITDATA_REQ:	/* unitdata request */
21360 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21361 		break;
21362 	case T_ORDREL_REQ:	/* orderly release req */
21363 		freemsg(mp);
21364 
21365 		if (tcp->tcp_fused)
21366 			tcp_unfuse(tcp);
21367 
21368 		if (tcp_xmit_end(tcp) != 0) {
21369 			/*
21370 			 * We were crossing FINs and got a reset from
21371 			 * the other side. Just ignore it.
21372 			 */
21373 			if (tcp->tcp_debug) {
21374 				(void) strlog(TCP_MOD_ID, 0, 1,
21375 				    SL_ERROR|SL_TRACE,
21376 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21377 				    "state %s",
21378 				    tcp_display(tcp, NULL,
21379 				    DISP_ADDR_AND_PORT));
21380 			}
21381 		}
21382 		break;
21383 	case T_ADDR_REQ:
21384 		tcp_addr_req(tcp, mp);
21385 		break;
21386 	default:
21387 		if (tcp->tcp_debug) {
21388 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21389 			    "tcp_wput_proto, bogus TPI msg, type %d",
21390 			    tprim->type);
21391 		}
21392 		/*
21393 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21394 		 * to recover.
21395 		 */
21396 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21397 		break;
21398 	}
21399 }
21400 
21401 /*
21402  * The TCP write service routine should never be called...
21403  */
21404 /* ARGSUSED */
21405 static void
21406 tcp_wsrv(queue_t *q)
21407 {
21408 	TCP_STAT(tcp_wsrv_called);
21409 }
21410 
21411 /* Non overlapping byte exchanger */
21412 static void
21413 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21414 {
21415 	uchar_t	uch;
21416 
21417 	while (len-- > 0) {
21418 		uch = a[len];
21419 		a[len] = b[len];
21420 		b[len] = uch;
21421 	}
21422 }
21423 
21424 /*
21425  * Send out a control packet on the tcp connection specified.  This routine
21426  * is typically called where we need a simple ACK or RST generated.
21427  */
21428 static void
21429 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21430 {
21431 	uchar_t		*rptr;
21432 	tcph_t		*tcph;
21433 	ipha_t		*ipha = NULL;
21434 	ip6_t		*ip6h = NULL;
21435 	uint32_t	sum;
21436 	int		tcp_hdr_len;
21437 	int		tcp_ip_hdr_len;
21438 	mblk_t		*mp;
21439 
21440 	/*
21441 	 * Save sum for use in source route later.
21442 	 */
21443 	ASSERT(tcp != NULL);
21444 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21445 	tcp_hdr_len = tcp->tcp_hdr_len;
21446 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21447 
21448 	/* If a text string is passed in with the request, pass it to strlog. */
21449 	if (str != NULL && tcp->tcp_debug) {
21450 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21451 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21452 		    str, seq, ack, ctl);
21453 	}
21454 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21455 	    BPRI_MED);
21456 	if (mp == NULL) {
21457 		return;
21458 	}
21459 	rptr = &mp->b_rptr[tcp_wroff_xtra];
21460 	mp->b_rptr = rptr;
21461 	mp->b_wptr = &rptr[tcp_hdr_len];
21462 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21463 
21464 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21465 		ipha = (ipha_t *)rptr;
21466 		ipha->ipha_length = htons(tcp_hdr_len);
21467 	} else {
21468 		ip6h = (ip6_t *)rptr;
21469 		ASSERT(tcp != NULL);
21470 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21471 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21472 	}
21473 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21474 	tcph->th_flags[0] = (uint8_t)ctl;
21475 	if (ctl & TH_RST) {
21476 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21477 		BUMP_MIB(&tcp_mib, tcpOutControl);
21478 		/*
21479 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21480 		 */
21481 		if (tcp->tcp_snd_ts_ok &&
21482 		    tcp->tcp_state > TCPS_SYN_SENT) {
21483 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21484 			*(mp->b_wptr) = TCPOPT_EOL;
21485 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21486 				ipha->ipha_length = htons(tcp_hdr_len -
21487 				    TCPOPT_REAL_TS_LEN);
21488 			} else {
21489 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21490 				    TCPOPT_REAL_TS_LEN);
21491 			}
21492 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21493 			sum -= TCPOPT_REAL_TS_LEN;
21494 		}
21495 	}
21496 	if (ctl & TH_ACK) {
21497 		if (tcp->tcp_snd_ts_ok) {
21498 			U32_TO_BE32(lbolt,
21499 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21500 			U32_TO_BE32(tcp->tcp_ts_recent,
21501 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21502 		}
21503 
21504 		/* Update the latest receive window size in TCP header. */
21505 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21506 		    tcph->th_win);
21507 		tcp->tcp_rack = ack;
21508 		tcp->tcp_rack_cnt = 0;
21509 		BUMP_MIB(&tcp_mib, tcpOutAck);
21510 	}
21511 	BUMP_LOCAL(tcp->tcp_obsegs);
21512 	U32_TO_BE32(seq, tcph->th_seq);
21513 	U32_TO_BE32(ack, tcph->th_ack);
21514 	/*
21515 	 * Include the adjustment for a source route if any.
21516 	 */
21517 	sum = (sum >> 16) + (sum & 0xFFFF);
21518 	U16_TO_BE16(sum, tcph->th_sum);
21519 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21520 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21521 }
21522 
21523 /*
21524  * If this routine returns B_TRUE, TCP can generate a RST in response
21525  * to a segment.  If it returns B_FALSE, TCP should not respond.
21526  */
21527 static boolean_t
21528 tcp_send_rst_chk(void)
21529 {
21530 	clock_t	now;
21531 
21532 	/*
21533 	 * TCP needs to protect itself from generating too many RSTs.
21534 	 * This can be a DoS attack by sending us random segments
21535 	 * soliciting RSTs.
21536 	 *
21537 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21538 	 * in each 1 second interval.  In this way, TCP still generate
21539 	 * RSTs in normal cases but when under attack, the impact is
21540 	 * limited.
21541 	 */
21542 	if (tcp_rst_sent_rate_enabled != 0) {
21543 		now = lbolt;
21544 		/* lbolt can wrap around. */
21545 		if ((tcp_last_rst_intrvl > now) ||
21546 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
21547 			tcp_last_rst_intrvl = now;
21548 			tcp_rst_cnt = 1;
21549 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
21550 			return (B_FALSE);
21551 		}
21552 	}
21553 	return (B_TRUE);
21554 }
21555 
21556 /*
21557  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21558  */
21559 static void
21560 tcp_ip_ire_mark_advice(tcp_t *tcp)
21561 {
21562 	mblk_t *mp;
21563 	ipic_t *ipic;
21564 
21565 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21566 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21567 		    &ipic);
21568 	} else {
21569 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21570 		    &ipic);
21571 	}
21572 	if (mp == NULL)
21573 		return;
21574 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21575 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21576 }
21577 
21578 /*
21579  * Return an IP advice ioctl mblk and set ipic to be the pointer
21580  * to the advice structure.
21581  */
21582 static mblk_t *
21583 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21584 {
21585 	struct iocblk *ioc;
21586 	mblk_t *mp, *mp1;
21587 
21588 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21589 	if (mp == NULL)
21590 		return (NULL);
21591 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21592 	*ipic = (ipic_t *)mp->b_rptr;
21593 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21594 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21595 
21596 	bcopy(addr, *ipic + 1, addr_len);
21597 
21598 	(*ipic)->ipic_addr_length = addr_len;
21599 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21600 
21601 	mp1 = mkiocb(IP_IOCTL);
21602 	if (mp1 == NULL) {
21603 		freemsg(mp);
21604 		return (NULL);
21605 	}
21606 	mp1->b_cont = mp;
21607 	ioc = (struct iocblk *)mp1->b_rptr;
21608 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
21609 
21610 	return (mp1);
21611 }
21612 
21613 /*
21614  * Generate a reset based on an inbound packet for which there is no active
21615  * tcp state that we can find.
21616  *
21617  * IPSEC NOTE : Try to send the reply with the same protection as it came
21618  * in.  We still have the ipsec_mp that the packet was attached to. Thus
21619  * the packet will go out at the same level of protection as it came in by
21620  * converting the IPSEC_IN to IPSEC_OUT.
21621  */
21622 static void
21623 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
21624     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid)
21625 {
21626 	ipha_t		*ipha = NULL;
21627 	ip6_t		*ip6h = NULL;
21628 	ushort_t	len;
21629 	tcph_t		*tcph;
21630 	int		i;
21631 	mblk_t		*ipsec_mp;
21632 	boolean_t	mctl_present;
21633 	ipic_t		*ipic;
21634 	ipaddr_t	v4addr;
21635 	in6_addr_t	v6addr;
21636 	int		addr_len;
21637 	void		*addr;
21638 	queue_t		*q = tcp_g_q;
21639 	tcp_t		*tcp = Q_TO_TCP(q);
21640 	cred_t		*cr;
21641 	mblk_t		*nmp;
21642 
21643 	if (!tcp_send_rst_chk()) {
21644 		tcp_rst_unsent++;
21645 		freemsg(mp);
21646 		return;
21647 	}
21648 
21649 	if (mp->b_datap->db_type == M_CTL) {
21650 		ipsec_mp = mp;
21651 		mp = mp->b_cont;
21652 		mctl_present = B_TRUE;
21653 	} else {
21654 		ipsec_mp = mp;
21655 		mctl_present = B_FALSE;
21656 	}
21657 
21658 	if (str && q && tcp_dbg) {
21659 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21660 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
21661 		    "flags 0x%x",
21662 		    str, seq, ack, ctl);
21663 	}
21664 	if (mp->b_datap->db_ref != 1) {
21665 		mblk_t *mp1 = copyb(mp);
21666 		freemsg(mp);
21667 		mp = mp1;
21668 		if (!mp) {
21669 			if (mctl_present)
21670 				freeb(ipsec_mp);
21671 			return;
21672 		} else {
21673 			if (mctl_present) {
21674 				ipsec_mp->b_cont = mp;
21675 			} else {
21676 				ipsec_mp = mp;
21677 			}
21678 		}
21679 	} else if (mp->b_cont) {
21680 		freemsg(mp->b_cont);
21681 		mp->b_cont = NULL;
21682 	}
21683 	/*
21684 	 * We skip reversing source route here.
21685 	 * (for now we replace all IP options with EOL)
21686 	 */
21687 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21688 		ipha = (ipha_t *)mp->b_rptr;
21689 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
21690 			mp->b_rptr[i] = IPOPT_EOL;
21691 		/*
21692 		 * Make sure that src address isn't flagrantly invalid.
21693 		 * Not all broadcast address checking for the src address
21694 		 * is possible, since we don't know the netmask of the src
21695 		 * addr.  No check for destination address is done, since
21696 		 * IP will not pass up a packet with a broadcast dest
21697 		 * address to TCP.  Similar checks are done below for IPv6.
21698 		 */
21699 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
21700 		    CLASSD(ipha->ipha_src)) {
21701 			freemsg(ipsec_mp);
21702 			BUMP_MIB(&ip_mib, ipInDiscards);
21703 			return;
21704 		}
21705 	} else {
21706 		ip6h = (ip6_t *)mp->b_rptr;
21707 
21708 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
21709 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
21710 			freemsg(ipsec_mp);
21711 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
21712 			return;
21713 		}
21714 
21715 		/* Remove any extension headers assuming partial overlay */
21716 		if (ip_hdr_len > IPV6_HDR_LEN) {
21717 			uint8_t *to;
21718 
21719 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
21720 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
21721 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
21722 			ip_hdr_len = IPV6_HDR_LEN;
21723 			ip6h = (ip6_t *)mp->b_rptr;
21724 			ip6h->ip6_nxt = IPPROTO_TCP;
21725 		}
21726 	}
21727 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
21728 	if (tcph->th_flags[0] & TH_RST) {
21729 		freemsg(ipsec_mp);
21730 		return;
21731 	}
21732 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
21733 	len = ip_hdr_len + sizeof (tcph_t);
21734 	mp->b_wptr = &mp->b_rptr[len];
21735 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21736 		ipha->ipha_length = htons(len);
21737 		/* Swap addresses */
21738 		v4addr = ipha->ipha_src;
21739 		ipha->ipha_src = ipha->ipha_dst;
21740 		ipha->ipha_dst = v4addr;
21741 		ipha->ipha_ident = 0;
21742 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
21743 		addr_len = IP_ADDR_LEN;
21744 		addr = &v4addr;
21745 	} else {
21746 		/* No ip6i_t in this case */
21747 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
21748 		/* Swap addresses */
21749 		v6addr = ip6h->ip6_src;
21750 		ip6h->ip6_src = ip6h->ip6_dst;
21751 		ip6h->ip6_dst = v6addr;
21752 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21753 		addr_len = IPV6_ADDR_LEN;
21754 		addr = &v6addr;
21755 	}
21756 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21757 	U32_TO_BE32(ack, tcph->th_ack);
21758 	U32_TO_BE32(seq, tcph->th_seq);
21759 	U16_TO_BE16(0, tcph->th_win);
21760 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21761 	tcph->th_flags[0] = (uint8_t)ctl;
21762 	if (ctl & TH_RST) {
21763 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21764 		BUMP_MIB(&tcp_mib, tcpOutControl);
21765 	}
21766 
21767 	/* IP trusts us to set up labels when required. */
21768 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
21769 	    crgetlabel(cr) != NULL) {
21770 		int err, adjust;
21771 
21772 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
21773 			err = tsol_check_label(cr, &mp, &adjust,
21774 			    tcp->tcp_connp->conn_mac_exempt);
21775 		else
21776 			err = tsol_check_label_v6(cr, &mp, &adjust,
21777 			    tcp->tcp_connp->conn_mac_exempt);
21778 		if (mctl_present)
21779 			ipsec_mp->b_cont = mp;
21780 		else
21781 			ipsec_mp = mp;
21782 		if (err != 0) {
21783 			freemsg(ipsec_mp);
21784 			return;
21785 		}
21786 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21787 			ipha = (ipha_t *)mp->b_rptr;
21788 			adjust += ntohs(ipha->ipha_length);
21789 			ipha->ipha_length = htons(adjust);
21790 		} else {
21791 			ip6h = (ip6_t *)mp->b_rptr;
21792 		}
21793 	}
21794 
21795 	if (mctl_present) {
21796 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21797 
21798 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21799 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21800 			return;
21801 		}
21802 	}
21803 	if (zoneid == ALL_ZONES)
21804 		zoneid = GLOBAL_ZONEID;
21805 
21806 	/* Add the zoneid so ip_output routes it properly */
21807 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid)) == NULL) {
21808 		freemsg(ipsec_mp);
21809 		return;
21810 	}
21811 	ipsec_mp = nmp;
21812 
21813 	/*
21814 	 * NOTE:  one might consider tracing a TCP packet here, but
21815 	 * this function has no active TCP state and no tcp structure
21816 	 * that has a trace buffer.  If we traced here, we would have
21817 	 * to keep a local trace buffer in tcp_record_trace().
21818 	 *
21819 	 * TSol note: The mblk that contains the incoming packet was
21820 	 * reused by tcp_xmit_listener_reset, so it already contains
21821 	 * the right credentials and we don't need to call mblk_setcred.
21822 	 * Also the conn's cred is not right since it is associated
21823 	 * with tcp_g_q.
21824 	 */
21825 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21826 
21827 	/*
21828 	 * Tell IP to mark the IRE used for this destination temporary.
21829 	 * This way, we can limit our exposure to DoS attack because IP
21830 	 * creates an IRE for each destination.  If there are too many,
21831 	 * the time to do any routing lookup will be extremely long.  And
21832 	 * the lookup can be in interrupt context.
21833 	 *
21834 	 * Note that in normal circumstances, this marking should not
21835 	 * affect anything.  It would be nice if only 1 message is
21836 	 * needed to inform IP that the IRE created for this RST should
21837 	 * not be added to the cache table.  But there is currently
21838 	 * not such communication mechanism between TCP and IP.  So
21839 	 * the best we can do now is to send the advice ioctl to IP
21840 	 * to mark the IRE temporary.
21841 	 */
21842 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21843 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21844 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21845 	}
21846 }
21847 
21848 /*
21849  * Initiate closedown sequence on an active connection.  (May be called as
21850  * writer.)  Return value zero for OK return, non-zero for error return.
21851  */
21852 static int
21853 tcp_xmit_end(tcp_t *tcp)
21854 {
21855 	ipic_t	*ipic;
21856 	mblk_t	*mp;
21857 
21858 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21859 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21860 		/*
21861 		 * Invalid state, only states TCPS_SYN_RCVD,
21862 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21863 		 */
21864 		return (-1);
21865 	}
21866 
21867 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21868 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21869 	/*
21870 	 * If there is nothing more unsent, send the FIN now.
21871 	 * Otherwise, it will go out with the last segment.
21872 	 */
21873 	if (tcp->tcp_unsent == 0) {
21874 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21875 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21876 
21877 		if (mp) {
21878 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21879 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21880 		} else {
21881 			/*
21882 			 * Couldn't allocate msg.  Pretend we got it out.
21883 			 * Wait for rexmit timeout.
21884 			 */
21885 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21886 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21887 		}
21888 
21889 		/*
21890 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21891 		 * changed.
21892 		 */
21893 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21894 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21895 		}
21896 	} else {
21897 		/*
21898 		 * If tcp->tcp_cork is set, then the data will not get sent,
21899 		 * so we have to check that and unset it first.
21900 		 */
21901 		if (tcp->tcp_cork)
21902 			tcp->tcp_cork = B_FALSE;
21903 		tcp_wput_data(tcp, NULL, B_FALSE);
21904 	}
21905 
21906 	/*
21907 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
21908 	 * is 0, don't update the cache.
21909 	 */
21910 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
21911 		return (0);
21912 
21913 	/*
21914 	 * NOTE: should not update if source routes i.e. if tcp_remote if
21915 	 * different from the destination.
21916 	 */
21917 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21918 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
21919 			return (0);
21920 		}
21921 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21922 		    &ipic);
21923 	} else {
21924 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
21925 		    &tcp->tcp_ip6h->ip6_dst))) {
21926 			return (0);
21927 		}
21928 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21929 		    &ipic);
21930 	}
21931 
21932 	/* Record route attributes in the IRE for use by future connections. */
21933 	if (mp == NULL)
21934 		return (0);
21935 
21936 	/*
21937 	 * We do not have a good algorithm to update ssthresh at this time.
21938 	 * So don't do any update.
21939 	 */
21940 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
21941 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
21942 
21943 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21944 	return (0);
21945 }
21946 
21947 /*
21948  * Generate a "no listener here" RST in response to an "unknown" segment.
21949  * Note that we are reusing the incoming mp to construct the outgoing
21950  * RST.
21951  */
21952 void
21953 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid)
21954 {
21955 	uchar_t		*rptr;
21956 	uint32_t	seg_len;
21957 	tcph_t		*tcph;
21958 	uint32_t	seg_seq;
21959 	uint32_t	seg_ack;
21960 	uint_t		flags;
21961 	mblk_t		*ipsec_mp;
21962 	ipha_t 		*ipha;
21963 	ip6_t 		*ip6h;
21964 	boolean_t	mctl_present = B_FALSE;
21965 	boolean_t	check = B_TRUE;
21966 	boolean_t	policy_present;
21967 
21968 	TCP_STAT(tcp_no_listener);
21969 
21970 	ipsec_mp = mp;
21971 
21972 	if (mp->b_datap->db_type == M_CTL) {
21973 		ipsec_in_t *ii;
21974 
21975 		mctl_present = B_TRUE;
21976 		mp = mp->b_cont;
21977 
21978 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21979 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21980 		if (ii->ipsec_in_dont_check) {
21981 			check = B_FALSE;
21982 			if (!ii->ipsec_in_secure) {
21983 				freeb(ipsec_mp);
21984 				mctl_present = B_FALSE;
21985 				ipsec_mp = mp;
21986 			}
21987 		}
21988 	}
21989 
21990 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21991 		policy_present = ipsec_inbound_v4_policy_present;
21992 		ipha = (ipha_t *)mp->b_rptr;
21993 		ip6h = NULL;
21994 	} else {
21995 		policy_present = ipsec_inbound_v6_policy_present;
21996 		ipha = NULL;
21997 		ip6h = (ip6_t *)mp->b_rptr;
21998 	}
21999 
22000 	if (check && policy_present) {
22001 		/*
22002 		 * The conn_t parameter is NULL because we already know
22003 		 * nobody's home.
22004 		 */
22005 		ipsec_mp = ipsec_check_global_policy(
22006 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
22007 		if (ipsec_mp == NULL)
22008 			return;
22009 	}
22010 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22011 		DTRACE_PROBE2(
22012 		    tx__ip__log__error__nolistener__tcp,
22013 		    char *, "Could not reply with RST to mp(1)",
22014 		    mblk_t *, mp);
22015 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22016 		freemsg(ipsec_mp);
22017 		return;
22018 	}
22019 
22020 	rptr = mp->b_rptr;
22021 
22022 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22023 	seg_seq = BE32_TO_U32(tcph->th_seq);
22024 	seg_ack = BE32_TO_U32(tcph->th_ack);
22025 	flags = tcph->th_flags[0];
22026 
22027 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22028 	if (flags & TH_RST) {
22029 		freemsg(ipsec_mp);
22030 	} else if (flags & TH_ACK) {
22031 		tcp_xmit_early_reset("no tcp, reset",
22032 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid);
22033 	} else {
22034 		if (flags & TH_SYN) {
22035 			seg_len++;
22036 		} else {
22037 			/*
22038 			 * Here we violate the RFC.  Note that a normal
22039 			 * TCP will never send a segment without the ACK
22040 			 * flag, except for RST or SYN segment.  This
22041 			 * segment is neither.  Just drop it on the
22042 			 * floor.
22043 			 */
22044 			freemsg(ipsec_mp);
22045 			tcp_rst_unsent++;
22046 			return;
22047 		}
22048 
22049 		tcp_xmit_early_reset("no tcp, reset/ack",
22050 		    ipsec_mp, 0, seg_seq + seg_len,
22051 		    TH_RST | TH_ACK, ip_hdr_len, zoneid);
22052 	}
22053 }
22054 
22055 /*
22056  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22057  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22058  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22059  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22060  * otherwise it will dup partial mblks.)
22061  * Otherwise, an appropriate ACK packet will be generated.  This
22062  * routine is not usually called to send new data for the first time.  It
22063  * is mostly called out of the timer for retransmits, and to generate ACKs.
22064  *
22065  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22066  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22067  * of the original mblk chain will be returned in *offset and *end_mp.
22068  */
22069 mblk_t *
22070 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22071     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22072     boolean_t rexmit)
22073 {
22074 	int	data_length;
22075 	int32_t	off = 0;
22076 	uint_t	flags;
22077 	mblk_t	*mp1;
22078 	mblk_t	*mp2;
22079 	uchar_t	*rptr;
22080 	tcph_t	*tcph;
22081 	int32_t	num_sack_blk = 0;
22082 	int32_t	sack_opt_len = 0;
22083 
22084 	/* Allocate for our maximum TCP header + link-level */
22085 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
22086 	    BPRI_MED);
22087 	if (!mp1)
22088 		return (NULL);
22089 	data_length = 0;
22090 
22091 	/*
22092 	 * Note that tcp_mss has been adjusted to take into account the
22093 	 * timestamp option if applicable.  Because SACK options do not
22094 	 * appear in every TCP segments and they are of variable lengths,
22095 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22096 	 * the actual segment length when we need to send a segment which
22097 	 * includes SACK options.
22098 	 */
22099 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22100 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22101 		    tcp->tcp_num_sack_blk);
22102 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22103 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22104 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22105 			max_to_send -= sack_opt_len;
22106 	}
22107 
22108 	if (offset != NULL) {
22109 		off = *offset;
22110 		/* We use offset as an indicator that end_mp is not NULL. */
22111 		*end_mp = NULL;
22112 	}
22113 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22114 		/* This could be faster with cooperation from downstream */
22115 		if (mp2 != mp1 && !sendall &&
22116 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22117 		    max_to_send)
22118 			/*
22119 			 * Don't send the next mblk since the whole mblk
22120 			 * does not fit.
22121 			 */
22122 			break;
22123 		mp2->b_cont = dupb(mp);
22124 		mp2 = mp2->b_cont;
22125 		if (!mp2) {
22126 			freemsg(mp1);
22127 			return (NULL);
22128 		}
22129 		mp2->b_rptr += off;
22130 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22131 		    (uintptr_t)INT_MAX);
22132 
22133 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22134 		if (data_length > max_to_send) {
22135 			mp2->b_wptr -= data_length - max_to_send;
22136 			data_length = max_to_send;
22137 			off = mp2->b_wptr - mp->b_rptr;
22138 			break;
22139 		} else {
22140 			off = 0;
22141 		}
22142 	}
22143 	if (offset != NULL) {
22144 		*offset = off;
22145 		*end_mp = mp;
22146 	}
22147 	if (seg_len != NULL) {
22148 		*seg_len = data_length;
22149 	}
22150 
22151 	/* Update the latest receive window size in TCP header. */
22152 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22153 	    tcp->tcp_tcph->th_win);
22154 
22155 	rptr = mp1->b_rptr + tcp_wroff_xtra;
22156 	mp1->b_rptr = rptr;
22157 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22158 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22159 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22160 	U32_TO_ABE32(seq, tcph->th_seq);
22161 
22162 	/*
22163 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22164 	 * that this function was called from tcp_wput_data. Thus, when called
22165 	 * to retransmit data the setting of the PUSH bit may appear some
22166 	 * what random in that it might get set when it should not. This
22167 	 * should not pose any performance issues.
22168 	 */
22169 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22170 	    tcp->tcp_unsent == data_length)) {
22171 		flags = TH_ACK | TH_PUSH;
22172 	} else {
22173 		flags = TH_ACK;
22174 	}
22175 
22176 	if (tcp->tcp_ecn_ok) {
22177 		if (tcp->tcp_ecn_echo_on)
22178 			flags |= TH_ECE;
22179 
22180 		/*
22181 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22182 		 * There is no TCP flow control for non-data segments, and
22183 		 * only data segment is transmitted reliably.
22184 		 */
22185 		if (data_length > 0 && !rexmit) {
22186 			SET_ECT(tcp, rptr);
22187 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22188 				flags |= TH_CWR;
22189 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22190 			}
22191 		}
22192 	}
22193 
22194 	if (tcp->tcp_valid_bits) {
22195 		uint32_t u1;
22196 
22197 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22198 		    seq == tcp->tcp_iss) {
22199 			uchar_t	*wptr;
22200 
22201 			/*
22202 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22203 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22204 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22205 			 * our SYN is not ack'ed but the app closes this
22206 			 * TCP connection.
22207 			 */
22208 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22209 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22210 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22211 
22212 			/*
22213 			 * Tack on the MSS option.  It is always needed
22214 			 * for both active and passive open.
22215 			 *
22216 			 * MSS option value should be interface MTU - MIN
22217 			 * TCP/IP header according to RFC 793 as it means
22218 			 * the maximum segment size TCP can receive.  But
22219 			 * to get around some broken middle boxes/end hosts
22220 			 * out there, we allow the option value to be the
22221 			 * same as the MSS option size on the peer side.
22222 			 * In this way, the other side will not send
22223 			 * anything larger than they can receive.
22224 			 *
22225 			 * Note that for SYN_SENT state, the ndd param
22226 			 * tcp_use_smss_as_mss_opt has no effect as we
22227 			 * don't know the peer's MSS option value. So
22228 			 * the only case we need to take care of is in
22229 			 * SYN_RCVD state, which is done later.
22230 			 */
22231 			wptr = mp1->b_wptr;
22232 			wptr[0] = TCPOPT_MAXSEG;
22233 			wptr[1] = TCPOPT_MAXSEG_LEN;
22234 			wptr += 2;
22235 			u1 = tcp->tcp_if_mtu -
22236 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22237 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22238 			    TCP_MIN_HEADER_LENGTH;
22239 			U16_TO_BE16(u1, wptr);
22240 			mp1->b_wptr = wptr + 2;
22241 			/* Update the offset to cover the additional word */
22242 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22243 
22244 			/*
22245 			 * Note that the following way of filling in
22246 			 * TCP options are not optimal.  Some NOPs can
22247 			 * be saved.  But there is no need at this time
22248 			 * to optimize it.  When it is needed, we will
22249 			 * do it.
22250 			 */
22251 			switch (tcp->tcp_state) {
22252 			case TCPS_SYN_SENT:
22253 				flags = TH_SYN;
22254 
22255 				if (tcp->tcp_snd_ts_ok) {
22256 					uint32_t llbolt = (uint32_t)lbolt;
22257 
22258 					wptr = mp1->b_wptr;
22259 					wptr[0] = TCPOPT_NOP;
22260 					wptr[1] = TCPOPT_NOP;
22261 					wptr[2] = TCPOPT_TSTAMP;
22262 					wptr[3] = TCPOPT_TSTAMP_LEN;
22263 					wptr += 4;
22264 					U32_TO_BE32(llbolt, wptr);
22265 					wptr += 4;
22266 					ASSERT(tcp->tcp_ts_recent == 0);
22267 					U32_TO_BE32(0L, wptr);
22268 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22269 					tcph->th_offset_and_rsrvd[0] +=
22270 					    (3 << 4);
22271 				}
22272 
22273 				/*
22274 				 * Set up all the bits to tell other side
22275 				 * we are ECN capable.
22276 				 */
22277 				if (tcp->tcp_ecn_ok) {
22278 					flags |= (TH_ECE | TH_CWR);
22279 				}
22280 				break;
22281 			case TCPS_SYN_RCVD:
22282 				flags |= TH_SYN;
22283 
22284 				/*
22285 				 * Reset the MSS option value to be SMSS
22286 				 * We should probably add back the bytes
22287 				 * for timestamp option and IPsec.  We
22288 				 * don't do that as this is a workaround
22289 				 * for broken middle boxes/end hosts, it
22290 				 * is better for us to be more cautious.
22291 				 * They may not take these things into
22292 				 * account in their SMSS calculation.  Thus
22293 				 * the peer's calculated SMSS may be smaller
22294 				 * than what it can be.  This should be OK.
22295 				 */
22296 				if (tcp_use_smss_as_mss_opt) {
22297 					u1 = tcp->tcp_mss;
22298 					U16_TO_BE16(u1, wptr);
22299 				}
22300 
22301 				/*
22302 				 * If the other side is ECN capable, reply
22303 				 * that we are also ECN capable.
22304 				 */
22305 				if (tcp->tcp_ecn_ok)
22306 					flags |= TH_ECE;
22307 				break;
22308 			default:
22309 				/*
22310 				 * The above ASSERT() makes sure that this
22311 				 * must be FIN-WAIT-1 state.  Our SYN has
22312 				 * not been ack'ed so retransmit it.
22313 				 */
22314 				flags |= TH_SYN;
22315 				break;
22316 			}
22317 
22318 			if (tcp->tcp_snd_ws_ok) {
22319 				wptr = mp1->b_wptr;
22320 				wptr[0] =  TCPOPT_NOP;
22321 				wptr[1] =  TCPOPT_WSCALE;
22322 				wptr[2] =  TCPOPT_WS_LEN;
22323 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22324 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22325 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22326 			}
22327 
22328 			if (tcp->tcp_snd_sack_ok) {
22329 				wptr = mp1->b_wptr;
22330 				wptr[0] = TCPOPT_NOP;
22331 				wptr[1] = TCPOPT_NOP;
22332 				wptr[2] = TCPOPT_SACK_PERMITTED;
22333 				wptr[3] = TCPOPT_SACK_OK_LEN;
22334 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22335 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22336 			}
22337 
22338 			/* allocb() of adequate mblk assures space */
22339 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22340 			    (uintptr_t)INT_MAX);
22341 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22342 			/*
22343 			 * Get IP set to checksum on our behalf
22344 			 * Include the adjustment for a source route if any.
22345 			 */
22346 			u1 += tcp->tcp_sum;
22347 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22348 			U16_TO_BE16(u1, tcph->th_sum);
22349 			BUMP_MIB(&tcp_mib, tcpOutControl);
22350 		}
22351 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22352 		    (seq + data_length) == tcp->tcp_fss) {
22353 			if (!tcp->tcp_fin_acked) {
22354 				flags |= TH_FIN;
22355 				BUMP_MIB(&tcp_mib, tcpOutControl);
22356 			}
22357 			if (!tcp->tcp_fin_sent) {
22358 				tcp->tcp_fin_sent = B_TRUE;
22359 				switch (tcp->tcp_state) {
22360 				case TCPS_SYN_RCVD:
22361 				case TCPS_ESTABLISHED:
22362 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22363 					break;
22364 				case TCPS_CLOSE_WAIT:
22365 					tcp->tcp_state = TCPS_LAST_ACK;
22366 					break;
22367 				}
22368 				if (tcp->tcp_suna == tcp->tcp_snxt)
22369 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22370 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22371 			}
22372 		}
22373 		/*
22374 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22375 		 * is smaller than seq, u1 will become a very huge value.
22376 		 * So the comparison will fail.  Also note that tcp_urp
22377 		 * should be positive, see RFC 793 page 17.
22378 		 */
22379 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22380 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22381 		    u1 < (uint32_t)(64 * 1024)) {
22382 			flags |= TH_URG;
22383 			BUMP_MIB(&tcp_mib, tcpOutUrg);
22384 			U32_TO_ABE16(u1, tcph->th_urp);
22385 		}
22386 	}
22387 	tcph->th_flags[0] = (uchar_t)flags;
22388 	tcp->tcp_rack = tcp->tcp_rnxt;
22389 	tcp->tcp_rack_cnt = 0;
22390 
22391 	if (tcp->tcp_snd_ts_ok) {
22392 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22393 			uint32_t llbolt = (uint32_t)lbolt;
22394 
22395 			U32_TO_BE32(llbolt,
22396 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22397 			U32_TO_BE32(tcp->tcp_ts_recent,
22398 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22399 		}
22400 	}
22401 
22402 	if (num_sack_blk > 0) {
22403 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22404 		sack_blk_t *tmp;
22405 		int32_t	i;
22406 
22407 		wptr[0] = TCPOPT_NOP;
22408 		wptr[1] = TCPOPT_NOP;
22409 		wptr[2] = TCPOPT_SACK;
22410 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22411 		    sizeof (sack_blk_t);
22412 		wptr += TCPOPT_REAL_SACK_LEN;
22413 
22414 		tmp = tcp->tcp_sack_list;
22415 		for (i = 0; i < num_sack_blk; i++) {
22416 			U32_TO_BE32(tmp[i].begin, wptr);
22417 			wptr += sizeof (tcp_seq);
22418 			U32_TO_BE32(tmp[i].end, wptr);
22419 			wptr += sizeof (tcp_seq);
22420 		}
22421 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22422 	}
22423 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22424 	data_length += (int)(mp1->b_wptr - rptr);
22425 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22426 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22427 	} else {
22428 		ip6_t *ip6 = (ip6_t *)(rptr +
22429 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22430 		    sizeof (ip6i_t) : 0));
22431 
22432 		ip6->ip6_plen = htons(data_length -
22433 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22434 	}
22435 
22436 	/*
22437 	 * Prime pump for IP
22438 	 * Include the adjustment for a source route if any.
22439 	 */
22440 	data_length -= tcp->tcp_ip_hdr_len;
22441 	data_length += tcp->tcp_sum;
22442 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22443 	U16_TO_ABE16(data_length, tcph->th_sum);
22444 	if (tcp->tcp_ip_forward_progress) {
22445 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22446 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22447 		tcp->tcp_ip_forward_progress = B_FALSE;
22448 	}
22449 	return (mp1);
22450 }
22451 
22452 /* This function handles the push timeout. */
22453 void
22454 tcp_push_timer(void *arg)
22455 {
22456 	conn_t	*connp = (conn_t *)arg;
22457 	tcp_t *tcp = connp->conn_tcp;
22458 
22459 	TCP_DBGSTAT(tcp_push_timer_cnt);
22460 
22461 	ASSERT(tcp->tcp_listener == NULL);
22462 
22463 	/*
22464 	 * We need to plug synchronous streams during our drain to prevent
22465 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
22466 	 */
22467 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
22468 	tcp->tcp_push_tid = 0;
22469 	if ((tcp->tcp_rcv_list != NULL) &&
22470 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
22471 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22472 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
22473 }
22474 
22475 /*
22476  * This function handles delayed ACK timeout.
22477  */
22478 static void
22479 tcp_ack_timer(void *arg)
22480 {
22481 	conn_t	*connp = (conn_t *)arg;
22482 	tcp_t *tcp = connp->conn_tcp;
22483 	mblk_t *mp;
22484 
22485 	TCP_DBGSTAT(tcp_ack_timer_cnt);
22486 
22487 	tcp->tcp_ack_tid = 0;
22488 
22489 	if (tcp->tcp_fused)
22490 		return;
22491 
22492 	/*
22493 	 * Do not send ACK if there is no outstanding unack'ed data.
22494 	 */
22495 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22496 		return;
22497 	}
22498 
22499 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22500 		/*
22501 		 * Make sure we don't allow deferred ACKs to result in
22502 		 * timer-based ACKing.  If we have held off an ACK
22503 		 * when there was more than an mss here, and the timer
22504 		 * goes off, we have to worry about the possibility
22505 		 * that the sender isn't doing slow-start, or is out
22506 		 * of step with us for some other reason.  We fall
22507 		 * permanently back in the direction of
22508 		 * ACK-every-other-packet as suggested in RFC 1122.
22509 		 */
22510 		if (tcp->tcp_rack_abs_max > 2)
22511 			tcp->tcp_rack_abs_max--;
22512 		tcp->tcp_rack_cur_max = 2;
22513 	}
22514 	mp = tcp_ack_mp(tcp);
22515 
22516 	if (mp != NULL) {
22517 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22518 		BUMP_LOCAL(tcp->tcp_obsegs);
22519 		BUMP_MIB(&tcp_mib, tcpOutAck);
22520 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
22521 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22522 	}
22523 }
22524 
22525 
22526 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22527 static mblk_t *
22528 tcp_ack_mp(tcp_t *tcp)
22529 {
22530 	uint32_t	seq_no;
22531 
22532 	/*
22533 	 * There are a few cases to be considered while setting the sequence no.
22534 	 * Essentially, we can come here while processing an unacceptable pkt
22535 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
22536 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
22537 	 * If we are here for a zero window probe, stick with suna. In all
22538 	 * other cases, we check if suna + swnd encompasses snxt and set
22539 	 * the sequence number to snxt, if so. If snxt falls outside the
22540 	 * window (the receiver probably shrunk its window), we will go with
22541 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
22542 	 * receiver.
22543 	 */
22544 	if (tcp->tcp_zero_win_probe) {
22545 		seq_no = tcp->tcp_suna;
22546 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
22547 		ASSERT(tcp->tcp_swnd == 0);
22548 		seq_no = tcp->tcp_snxt;
22549 	} else {
22550 		seq_no = SEQ_GT(tcp->tcp_snxt,
22551 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
22552 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
22553 	}
22554 
22555 	if (tcp->tcp_valid_bits) {
22556 		/*
22557 		 * For the complex case where we have to send some
22558 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
22559 		 */
22560 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
22561 		    NULL, B_FALSE));
22562 	} else {
22563 		/* Generate a simple ACK */
22564 		int	data_length;
22565 		uchar_t	*rptr;
22566 		tcph_t	*tcph;
22567 		mblk_t	*mp1;
22568 		int32_t	tcp_hdr_len;
22569 		int32_t	tcp_tcp_hdr_len;
22570 		int32_t	num_sack_blk = 0;
22571 		int32_t sack_opt_len;
22572 
22573 		/*
22574 		 * Allocate space for TCP + IP headers
22575 		 * and link-level header
22576 		 */
22577 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22578 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22579 			    tcp->tcp_num_sack_blk);
22580 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22581 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22582 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
22583 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
22584 		} else {
22585 			tcp_hdr_len = tcp->tcp_hdr_len;
22586 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
22587 		}
22588 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
22589 		if (!mp1)
22590 			return (NULL);
22591 
22592 		/* Update the latest receive window size in TCP header. */
22593 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22594 		    tcp->tcp_tcph->th_win);
22595 		/* copy in prototype TCP + IP header */
22596 		rptr = mp1->b_rptr + tcp_wroff_xtra;
22597 		mp1->b_rptr = rptr;
22598 		mp1->b_wptr = rptr + tcp_hdr_len;
22599 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22600 
22601 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22602 
22603 		/* Set the TCP sequence number. */
22604 		U32_TO_ABE32(seq_no, tcph->th_seq);
22605 
22606 		/* Set up the TCP flag field. */
22607 		tcph->th_flags[0] = (uchar_t)TH_ACK;
22608 		if (tcp->tcp_ecn_echo_on)
22609 			tcph->th_flags[0] |= TH_ECE;
22610 
22611 		tcp->tcp_rack = tcp->tcp_rnxt;
22612 		tcp->tcp_rack_cnt = 0;
22613 
22614 		/* fill in timestamp option if in use */
22615 		if (tcp->tcp_snd_ts_ok) {
22616 			uint32_t llbolt = (uint32_t)lbolt;
22617 
22618 			U32_TO_BE32(llbolt,
22619 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22620 			U32_TO_BE32(tcp->tcp_ts_recent,
22621 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22622 		}
22623 
22624 		/* Fill in SACK options */
22625 		if (num_sack_blk > 0) {
22626 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22627 			sack_blk_t *tmp;
22628 			int32_t	i;
22629 
22630 			wptr[0] = TCPOPT_NOP;
22631 			wptr[1] = TCPOPT_NOP;
22632 			wptr[2] = TCPOPT_SACK;
22633 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22634 			    sizeof (sack_blk_t);
22635 			wptr += TCPOPT_REAL_SACK_LEN;
22636 
22637 			tmp = tcp->tcp_sack_list;
22638 			for (i = 0; i < num_sack_blk; i++) {
22639 				U32_TO_BE32(tmp[i].begin, wptr);
22640 				wptr += sizeof (tcp_seq);
22641 				U32_TO_BE32(tmp[i].end, wptr);
22642 				wptr += sizeof (tcp_seq);
22643 			}
22644 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
22645 			    << 4);
22646 		}
22647 
22648 		if (tcp->tcp_ipversion == IPV4_VERSION) {
22649 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
22650 		} else {
22651 			/* Check for ip6i_t header in sticky hdrs */
22652 			ip6_t *ip6 = (ip6_t *)(rptr +
22653 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22654 			    sizeof (ip6i_t) : 0));
22655 
22656 			ip6->ip6_plen = htons(tcp_hdr_len -
22657 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22658 		}
22659 
22660 		/*
22661 		 * Prime pump for checksum calculation in IP.  Include the
22662 		 * adjustment for a source route if any.
22663 		 */
22664 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
22665 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
22666 		U16_TO_ABE16(data_length, tcph->th_sum);
22667 
22668 		if (tcp->tcp_ip_forward_progress) {
22669 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22670 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22671 			tcp->tcp_ip_forward_progress = B_FALSE;
22672 		}
22673 		return (mp1);
22674 	}
22675 }
22676 
22677 /*
22678  * To create a temporary tcp structure for inserting into bind hash list.
22679  * The parameter is assumed to be in network byte order, ready for use.
22680  */
22681 /* ARGSUSED */
22682 static tcp_t *
22683 tcp_alloc_temp_tcp(in_port_t port)
22684 {
22685 	conn_t	*connp;
22686 	tcp_t	*tcp;
22687 
22688 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
22689 	if (connp == NULL)
22690 		return (NULL);
22691 
22692 	tcp = connp->conn_tcp;
22693 
22694 	/*
22695 	 * Only initialize the necessary info in those structures.  Note
22696 	 * that since INADDR_ANY is all 0, we do not need to set
22697 	 * tcp_bound_source to INADDR_ANY here.
22698 	 */
22699 	tcp->tcp_state = TCPS_BOUND;
22700 	tcp->tcp_lport = port;
22701 	tcp->tcp_exclbind = 1;
22702 	tcp->tcp_reserved_port = 1;
22703 
22704 	/* Just for place holding... */
22705 	tcp->tcp_ipversion = IPV4_VERSION;
22706 
22707 	return (tcp);
22708 }
22709 
22710 /*
22711  * To remove a port range specified by lo_port and hi_port from the
22712  * reserved port ranges.  This is one of the three public functions of
22713  * the reserved port interface.  Note that a port range has to be removed
22714  * as a whole.  Ports in a range cannot be removed individually.
22715  *
22716  * Params:
22717  *	in_port_t lo_port: the beginning port of the reserved port range to
22718  *		be deleted.
22719  *	in_port_t hi_port: the ending port of the reserved port range to
22720  *		be deleted.
22721  *
22722  * Return:
22723  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
22724  */
22725 boolean_t
22726 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
22727 {
22728 	int	i, j;
22729 	int	size;
22730 	tcp_t	**temp_tcp_array;
22731 	tcp_t	*tcp;
22732 
22733 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22734 
22735 	/* First make sure that the port ranage is indeed reserved. */
22736 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22737 		if (tcp_reserved_port[i].lo_port == lo_port) {
22738 			hi_port = tcp_reserved_port[i].hi_port;
22739 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
22740 			break;
22741 		}
22742 	}
22743 	if (i == tcp_reserved_port_array_size) {
22744 		rw_exit(&tcp_reserved_port_lock);
22745 		return (B_FALSE);
22746 	}
22747 
22748 	/*
22749 	 * Remove the range from the array.  This simple loop is possible
22750 	 * because port ranges are inserted in ascending order.
22751 	 */
22752 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
22753 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
22754 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
22755 		tcp_reserved_port[j].temp_tcp_array =
22756 		    tcp_reserved_port[j+1].temp_tcp_array;
22757 	}
22758 
22759 	/* Remove all the temporary tcp structures. */
22760 	size = hi_port - lo_port + 1;
22761 	while (size > 0) {
22762 		tcp = temp_tcp_array[size - 1];
22763 		ASSERT(tcp != NULL);
22764 		tcp_bind_hash_remove(tcp);
22765 		CONN_DEC_REF(tcp->tcp_connp);
22766 		size--;
22767 	}
22768 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
22769 	tcp_reserved_port_array_size--;
22770 	rw_exit(&tcp_reserved_port_lock);
22771 	return (B_TRUE);
22772 }
22773 
22774 /*
22775  * Macro to remove temporary tcp structure from the bind hash list.  The
22776  * first parameter is the list of tcp to be removed.  The second parameter
22777  * is the number of tcps in the array.
22778  */
22779 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
22780 { \
22781 	while ((num) > 0) { \
22782 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
22783 		tf_t *tbf; \
22784 		tcp_t *tcpnext; \
22785 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
22786 		mutex_enter(&tbf->tf_lock); \
22787 		tcpnext = tcp->tcp_bind_hash; \
22788 		if (tcpnext) { \
22789 			tcpnext->tcp_ptpbhn = \
22790 				tcp->tcp_ptpbhn; \
22791 		} \
22792 		*tcp->tcp_ptpbhn = tcpnext; \
22793 		mutex_exit(&tbf->tf_lock); \
22794 		kmem_free(tcp, sizeof (tcp_t)); \
22795 		(tcp_array)[(num) - 1] = NULL; \
22796 		(num)--; \
22797 	} \
22798 }
22799 
22800 /*
22801  * The public interface for other modules to call to reserve a port range
22802  * in TCP.  The caller passes in how large a port range it wants.  TCP
22803  * will try to find a range and return it via lo_port and hi_port.  This is
22804  * used by NCA's nca_conn_init.
22805  * NCA can only be used in the global zone so this only affects the global
22806  * zone's ports.
22807  *
22808  * Params:
22809  *	int size: the size of the port range to be reserved.
22810  *	in_port_t *lo_port (referenced): returns the beginning port of the
22811  *		reserved port range added.
22812  *	in_port_t *hi_port (referenced): returns the ending port of the
22813  *		reserved port range added.
22814  *
22815  * Return:
22816  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22817  */
22818 boolean_t
22819 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22820 {
22821 	tcp_t		*tcp;
22822 	tcp_t		*tmp_tcp;
22823 	tcp_t		**temp_tcp_array;
22824 	tf_t		*tbf;
22825 	in_port_t	net_port;
22826 	in_port_t	port;
22827 	int32_t		cur_size;
22828 	int		i, j;
22829 	boolean_t	used;
22830 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22831 	zoneid_t	zoneid = GLOBAL_ZONEID;
22832 
22833 	/* Sanity check. */
22834 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22835 		return (B_FALSE);
22836 	}
22837 
22838 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22839 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22840 		rw_exit(&tcp_reserved_port_lock);
22841 		return (B_FALSE);
22842 	}
22843 
22844 	/*
22845 	 * Find the starting port to try.  Since the port ranges are ordered
22846 	 * in the reserved port array, we can do a simple search here.
22847 	 */
22848 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22849 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22850 	for (i = 0; i < tcp_reserved_port_array_size;
22851 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22852 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22853 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22854 			break;
22855 		}
22856 	}
22857 	/* No available port range. */
22858 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22859 		rw_exit(&tcp_reserved_port_lock);
22860 		return (B_FALSE);
22861 	}
22862 
22863 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22864 	if (temp_tcp_array == NULL) {
22865 		rw_exit(&tcp_reserved_port_lock);
22866 		return (B_FALSE);
22867 	}
22868 
22869 	/* Go thru the port range to see if some ports are already bound. */
22870 	for (port = *lo_port, cur_size = 0;
22871 	    cur_size < size && port <= *hi_port;
22872 	    cur_size++, port++) {
22873 		used = B_FALSE;
22874 		net_port = htons(port);
22875 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22876 		mutex_enter(&tbf->tf_lock);
22877 		for (tcp = tbf->tf_tcp; tcp != NULL;
22878 		    tcp = tcp->tcp_bind_hash) {
22879 			if (IPCL_ZONE_MATCH(tcp->tcp_connp, zoneid) &&
22880 			    net_port == tcp->tcp_lport) {
22881 				/*
22882 				 * A port is already bound.  Search again
22883 				 * starting from port + 1.  Release all
22884 				 * temporary tcps.
22885 				 */
22886 				mutex_exit(&tbf->tf_lock);
22887 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22888 				*lo_port = port + 1;
22889 				cur_size = -1;
22890 				used = B_TRUE;
22891 				break;
22892 			}
22893 		}
22894 		if (!used) {
22895 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22896 				/*
22897 				 * Allocation failure.  Just fail the request.
22898 				 * Need to remove all those temporary tcp
22899 				 * structures.
22900 				 */
22901 				mutex_exit(&tbf->tf_lock);
22902 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22903 				rw_exit(&tcp_reserved_port_lock);
22904 				kmem_free(temp_tcp_array,
22905 				    (hi_port - lo_port + 1) *
22906 				    sizeof (tcp_t *));
22907 				return (B_FALSE);
22908 			}
22909 			temp_tcp_array[cur_size] = tmp_tcp;
22910 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22911 			mutex_exit(&tbf->tf_lock);
22912 		}
22913 	}
22914 
22915 	/*
22916 	 * The current range is not large enough.  We can actually do another
22917 	 * search if this search is done between 2 reserved port ranges.  But
22918 	 * for first release, we just stop here and return saying that no port
22919 	 * range is available.
22920 	 */
22921 	if (cur_size < size) {
22922 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22923 		rw_exit(&tcp_reserved_port_lock);
22924 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
22925 		return (B_FALSE);
22926 	}
22927 	*hi_port = port - 1;
22928 
22929 	/*
22930 	 * Insert range into array in ascending order.  Since this function
22931 	 * must not be called often, we choose to use the simplest method.
22932 	 * The above array should not consume excessive stack space as
22933 	 * the size must be very small.  If in future releases, we find
22934 	 * that we should provide more reserved port ranges, this function
22935 	 * has to be modified to be more efficient.
22936 	 */
22937 	if (tcp_reserved_port_array_size == 0) {
22938 		tcp_reserved_port[0].lo_port = *lo_port;
22939 		tcp_reserved_port[0].hi_port = *hi_port;
22940 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
22941 	} else {
22942 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
22943 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
22944 				tmp_ports[j].lo_port = *lo_port;
22945 				tmp_ports[j].hi_port = *hi_port;
22946 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
22947 				j++;
22948 			}
22949 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
22950 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
22951 			tmp_ports[j].temp_tcp_array =
22952 			    tcp_reserved_port[i].temp_tcp_array;
22953 		}
22954 		if (j == i) {
22955 			tmp_ports[j].lo_port = *lo_port;
22956 			tmp_ports[j].hi_port = *hi_port;
22957 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
22958 		}
22959 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
22960 	}
22961 	tcp_reserved_port_array_size++;
22962 	rw_exit(&tcp_reserved_port_lock);
22963 	return (B_TRUE);
22964 }
22965 
22966 /*
22967  * Check to see if a port is in any reserved port range.
22968  *
22969  * Params:
22970  *	in_port_t port: the port to be verified.
22971  *
22972  * Return:
22973  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
22974  */
22975 boolean_t
22976 tcp_reserved_port_check(in_port_t port)
22977 {
22978 	int i;
22979 
22980 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22981 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22982 		if (port >= tcp_reserved_port[i].lo_port ||
22983 		    port <= tcp_reserved_port[i].hi_port) {
22984 			rw_exit(&tcp_reserved_port_lock);
22985 			return (B_TRUE);
22986 		}
22987 	}
22988 	rw_exit(&tcp_reserved_port_lock);
22989 	return (B_FALSE);
22990 }
22991 
22992 /*
22993  * To list all reserved port ranges.  This is the function to handle
22994  * ndd tcp_reserved_port_list.
22995  */
22996 /* ARGSUSED */
22997 static int
22998 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22999 {
23000 	int i;
23001 
23002 	rw_enter(&tcp_reserved_port_lock, RW_READER);
23003 	if (tcp_reserved_port_array_size > 0)
23004 		(void) mi_mpprintf(mp, "The following ports are reserved:");
23005 	else
23006 		(void) mi_mpprintf(mp, "No port is reserved.");
23007 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
23008 		(void) mi_mpprintf(mp, "%d-%d",
23009 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
23010 	}
23011 	rw_exit(&tcp_reserved_port_lock);
23012 	return (0);
23013 }
23014 
23015 /*
23016  * Hash list insertion routine for tcp_t structures.
23017  * Inserts entries with the ones bound to a specific IP address first
23018  * followed by those bound to INADDR_ANY.
23019  */
23020 static void
23021 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23022 {
23023 	tcp_t	**tcpp;
23024 	tcp_t	*tcpnext;
23025 
23026 	if (tcp->tcp_ptpbhn != NULL) {
23027 		ASSERT(!caller_holds_lock);
23028 		tcp_bind_hash_remove(tcp);
23029 	}
23030 	tcpp = &tbf->tf_tcp;
23031 	if (!caller_holds_lock) {
23032 		mutex_enter(&tbf->tf_lock);
23033 	} else {
23034 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23035 	}
23036 	tcpnext = tcpp[0];
23037 	if (tcpnext) {
23038 		/*
23039 		 * If the new tcp bound to the INADDR_ANY address
23040 		 * and the first one in the list is not bound to
23041 		 * INADDR_ANY we skip all entries until we find the
23042 		 * first one bound to INADDR_ANY.
23043 		 * This makes sure that applications binding to a
23044 		 * specific address get preference over those binding to
23045 		 * INADDR_ANY.
23046 		 */
23047 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23048 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23049 			while ((tcpnext = tcpp[0]) != NULL &&
23050 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23051 				tcpp = &(tcpnext->tcp_bind_hash);
23052 			if (tcpnext)
23053 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23054 		} else
23055 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23056 	}
23057 	tcp->tcp_bind_hash = tcpnext;
23058 	tcp->tcp_ptpbhn = tcpp;
23059 	tcpp[0] = tcp;
23060 	if (!caller_holds_lock)
23061 		mutex_exit(&tbf->tf_lock);
23062 }
23063 
23064 /*
23065  * Hash list removal routine for tcp_t structures.
23066  */
23067 static void
23068 tcp_bind_hash_remove(tcp_t *tcp)
23069 {
23070 	tcp_t	*tcpnext;
23071 	kmutex_t *lockp;
23072 
23073 	if (tcp->tcp_ptpbhn == NULL)
23074 		return;
23075 
23076 	/*
23077 	 * Extract the lock pointer in case there are concurrent
23078 	 * hash_remove's for this instance.
23079 	 */
23080 	ASSERT(tcp->tcp_lport != 0);
23081 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23082 
23083 	ASSERT(lockp != NULL);
23084 	mutex_enter(lockp);
23085 	if (tcp->tcp_ptpbhn) {
23086 		tcpnext = tcp->tcp_bind_hash;
23087 		if (tcpnext) {
23088 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23089 			tcp->tcp_bind_hash = NULL;
23090 		}
23091 		*tcp->tcp_ptpbhn = tcpnext;
23092 		tcp->tcp_ptpbhn = NULL;
23093 	}
23094 	mutex_exit(lockp);
23095 }
23096 
23097 
23098 /*
23099  * Hash list lookup routine for tcp_t structures.
23100  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23101  */
23102 static tcp_t *
23103 tcp_acceptor_hash_lookup(t_uscalar_t id)
23104 {
23105 	tf_t	*tf;
23106 	tcp_t	*tcp;
23107 
23108 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23109 	mutex_enter(&tf->tf_lock);
23110 	for (tcp = tf->tf_tcp; tcp != NULL;
23111 	    tcp = tcp->tcp_acceptor_hash) {
23112 		if (tcp->tcp_acceptor_id == id) {
23113 			CONN_INC_REF(tcp->tcp_connp);
23114 			mutex_exit(&tf->tf_lock);
23115 			return (tcp);
23116 		}
23117 	}
23118 	mutex_exit(&tf->tf_lock);
23119 	return (NULL);
23120 }
23121 
23122 
23123 /*
23124  * Hash list insertion routine for tcp_t structures.
23125  */
23126 void
23127 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23128 {
23129 	tf_t	*tf;
23130 	tcp_t	**tcpp;
23131 	tcp_t	*tcpnext;
23132 
23133 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23134 
23135 	if (tcp->tcp_ptpahn != NULL)
23136 		tcp_acceptor_hash_remove(tcp);
23137 	tcpp = &tf->tf_tcp;
23138 	mutex_enter(&tf->tf_lock);
23139 	tcpnext = tcpp[0];
23140 	if (tcpnext)
23141 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23142 	tcp->tcp_acceptor_hash = tcpnext;
23143 	tcp->tcp_ptpahn = tcpp;
23144 	tcpp[0] = tcp;
23145 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23146 	mutex_exit(&tf->tf_lock);
23147 }
23148 
23149 /*
23150  * Hash list removal routine for tcp_t structures.
23151  */
23152 static void
23153 tcp_acceptor_hash_remove(tcp_t *tcp)
23154 {
23155 	tcp_t	*tcpnext;
23156 	kmutex_t *lockp;
23157 
23158 	/*
23159 	 * Extract the lock pointer in case there are concurrent
23160 	 * hash_remove's for this instance.
23161 	 */
23162 	lockp = tcp->tcp_acceptor_lockp;
23163 
23164 	if (tcp->tcp_ptpahn == NULL)
23165 		return;
23166 
23167 	ASSERT(lockp != NULL);
23168 	mutex_enter(lockp);
23169 	if (tcp->tcp_ptpahn) {
23170 		tcpnext = tcp->tcp_acceptor_hash;
23171 		if (tcpnext) {
23172 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23173 			tcp->tcp_acceptor_hash = NULL;
23174 		}
23175 		*tcp->tcp_ptpahn = tcpnext;
23176 		tcp->tcp_ptpahn = NULL;
23177 	}
23178 	mutex_exit(lockp);
23179 	tcp->tcp_acceptor_lockp = NULL;
23180 }
23181 
23182 /* ARGSUSED */
23183 static int
23184 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
23185 {
23186 	int error = 0;
23187 	int retval;
23188 	char *end;
23189 
23190 	tcp_hsp_t *hsp;
23191 	tcp_hsp_t *hspprev;
23192 
23193 	ipaddr_t addr = 0;		/* Address we're looking for */
23194 	in6_addr_t v6addr;		/* Address we're looking for */
23195 	uint32_t hash;			/* Hash of that address */
23196 
23197 	/*
23198 	 * If the following variables are still zero after parsing the input
23199 	 * string, the user didn't specify them and we don't change them in
23200 	 * the HSP.
23201 	 */
23202 
23203 	ipaddr_t mask = 0;		/* Subnet mask */
23204 	in6_addr_t v6mask;
23205 	long sendspace = 0;		/* Send buffer size */
23206 	long recvspace = 0;		/* Receive buffer size */
23207 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
23208 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
23209 
23210 	rw_enter(&tcp_hsp_lock, RW_WRITER);
23211 
23212 	/* Parse and validate address */
23213 	if (af == AF_INET) {
23214 		retval = inet_pton(af, value, &addr);
23215 		if (retval == 1)
23216 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
23217 	} else if (af == AF_INET6) {
23218 		retval = inet_pton(af, value, &v6addr);
23219 	} else {
23220 		error = EINVAL;
23221 		goto done;
23222 	}
23223 	if (retval == 0) {
23224 		error = EINVAL;
23225 		goto done;
23226 	}
23227 
23228 	while ((*value) && *value != ' ')
23229 		value++;
23230 
23231 	/* Parse individual keywords, set variables if found */
23232 	while (*value) {
23233 		/* Skip leading blanks */
23234 
23235 		while (*value == ' ' || *value == '\t')
23236 			value++;
23237 
23238 		/* If at end of string, we're done */
23239 
23240 		if (!*value)
23241 			break;
23242 
23243 		/* We have a word, figure out what it is */
23244 
23245 		if (strncmp("mask", value, 4) == 0) {
23246 			value += 4;
23247 			while (*value == ' ' || *value == '\t')
23248 				value++;
23249 			/* Parse subnet mask */
23250 			if (af == AF_INET) {
23251 				retval = inet_pton(af, value, &mask);
23252 				if (retval == 1) {
23253 					V4MASK_TO_V6(mask, v6mask);
23254 				}
23255 			} else if (af == AF_INET6) {
23256 				retval = inet_pton(af, value, &v6mask);
23257 			}
23258 			if (retval != 1) {
23259 				error = EINVAL;
23260 				goto done;
23261 			}
23262 			while ((*value) && *value != ' ')
23263 				value++;
23264 		} else if (strncmp("sendspace", value, 9) == 0) {
23265 			value += 9;
23266 
23267 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
23268 			    sendspace < TCP_XMIT_HIWATER ||
23269 			    sendspace >= (1L<<30)) {
23270 				error = EINVAL;
23271 				goto done;
23272 			}
23273 			value = end;
23274 		} else if (strncmp("recvspace", value, 9) == 0) {
23275 			value += 9;
23276 
23277 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
23278 			    recvspace < TCP_RECV_HIWATER ||
23279 			    recvspace >= (1L<<30)) {
23280 				error = EINVAL;
23281 				goto done;
23282 			}
23283 			value = end;
23284 		} else if (strncmp("timestamp", value, 9) == 0) {
23285 			value += 9;
23286 
23287 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
23288 			    timestamp < 0 || timestamp > 1) {
23289 				error = EINVAL;
23290 				goto done;
23291 			}
23292 
23293 			/*
23294 			 * We increment timestamp so we know it's been set;
23295 			 * this is undone when we put it in the HSP
23296 			 */
23297 			timestamp++;
23298 			value = end;
23299 		} else if (strncmp("delete", value, 6) == 0) {
23300 			value += 6;
23301 			delete = B_TRUE;
23302 		} else {
23303 			error = EINVAL;
23304 			goto done;
23305 		}
23306 	}
23307 
23308 	/* Hash address for lookup */
23309 
23310 	hash = TCP_HSP_HASH(addr);
23311 
23312 	if (delete) {
23313 		/*
23314 		 * Note that deletes don't return an error if the thing
23315 		 * we're trying to delete isn't there.
23316 		 */
23317 		if (tcp_hsp_hash == NULL)
23318 			goto done;
23319 		hsp = tcp_hsp_hash[hash];
23320 
23321 		if (hsp) {
23322 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23323 			    &v6addr)) {
23324 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
23325 				mi_free((char *)hsp);
23326 			} else {
23327 				hspprev = hsp;
23328 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
23329 					if (IN6_ARE_ADDR_EQUAL(
23330 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
23331 						hspprev->tcp_hsp_next =
23332 						    hsp->tcp_hsp_next;
23333 						mi_free((char *)hsp);
23334 						break;
23335 					}
23336 					hspprev = hsp;
23337 				}
23338 			}
23339 		}
23340 	} else {
23341 		/*
23342 		 * We're adding/modifying an HSP.  If we haven't already done
23343 		 * so, allocate the hash table.
23344 		 */
23345 
23346 		if (!tcp_hsp_hash) {
23347 			tcp_hsp_hash = (tcp_hsp_t **)
23348 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
23349 			if (!tcp_hsp_hash) {
23350 				error = EINVAL;
23351 				goto done;
23352 			}
23353 		}
23354 
23355 		/* Get head of hash chain */
23356 
23357 		hsp = tcp_hsp_hash[hash];
23358 
23359 		/* Try to find pre-existing hsp on hash chain */
23360 		/* Doesn't handle CIDR prefixes. */
23361 		while (hsp) {
23362 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
23363 				break;
23364 			hsp = hsp->tcp_hsp_next;
23365 		}
23366 
23367 		/*
23368 		 * If we didn't, create one with default values and put it
23369 		 * at head of hash chain
23370 		 */
23371 
23372 		if (!hsp) {
23373 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
23374 			if (!hsp) {
23375 				error = EINVAL;
23376 				goto done;
23377 			}
23378 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
23379 			tcp_hsp_hash[hash] = hsp;
23380 		}
23381 
23382 		/* Set values that the user asked us to change */
23383 
23384 		hsp->tcp_hsp_addr_v6 = v6addr;
23385 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
23386 			hsp->tcp_hsp_vers = IPV4_VERSION;
23387 		else
23388 			hsp->tcp_hsp_vers = IPV6_VERSION;
23389 		hsp->tcp_hsp_subnet_v6 = v6mask;
23390 		if (sendspace > 0)
23391 			hsp->tcp_hsp_sendspace = sendspace;
23392 		if (recvspace > 0)
23393 			hsp->tcp_hsp_recvspace = recvspace;
23394 		if (timestamp > 0)
23395 			hsp->tcp_hsp_tstamp = timestamp - 1;
23396 	}
23397 
23398 done:
23399 	rw_exit(&tcp_hsp_lock);
23400 	return (error);
23401 }
23402 
23403 /* Set callback routine passed to nd_load by tcp_param_register. */
23404 /* ARGSUSED */
23405 static int
23406 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
23407 {
23408 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
23409 }
23410 /* ARGSUSED */
23411 static int
23412 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23413     cred_t *cr)
23414 {
23415 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
23416 }
23417 
23418 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
23419 /* ARGSUSED */
23420 static int
23421 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23422 {
23423 	tcp_hsp_t *hsp;
23424 	int i;
23425 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
23426 
23427 	rw_enter(&tcp_hsp_lock, RW_READER);
23428 	(void) mi_mpprintf(mp,
23429 	    "Hash HSP     " MI_COL_HDRPAD_STR
23430 	    "Address         Subnet Mask     Send       Receive    TStamp");
23431 	if (tcp_hsp_hash) {
23432 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
23433 			hsp = tcp_hsp_hash[i];
23434 			while (hsp) {
23435 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
23436 					(void) inet_ntop(AF_INET,
23437 					    &hsp->tcp_hsp_addr,
23438 					    addrbuf, sizeof (addrbuf));
23439 					(void) inet_ntop(AF_INET,
23440 					    &hsp->tcp_hsp_subnet,
23441 					    subnetbuf, sizeof (subnetbuf));
23442 				} else {
23443 					(void) inet_ntop(AF_INET6,
23444 					    &hsp->tcp_hsp_addr_v6,
23445 					    addrbuf, sizeof (addrbuf));
23446 					(void) inet_ntop(AF_INET6,
23447 					    &hsp->tcp_hsp_subnet_v6,
23448 					    subnetbuf, sizeof (subnetbuf));
23449 				}
23450 				(void) mi_mpprintf(mp,
23451 				    " %03d " MI_COL_PTRFMT_STR
23452 				    "%s %s %010d %010d      %d",
23453 				    i,
23454 				    (void *)hsp,
23455 				    addrbuf,
23456 				    subnetbuf,
23457 				    hsp->tcp_hsp_sendspace,
23458 				    hsp->tcp_hsp_recvspace,
23459 				    hsp->tcp_hsp_tstamp);
23460 
23461 				hsp = hsp->tcp_hsp_next;
23462 			}
23463 		}
23464 	}
23465 	rw_exit(&tcp_hsp_lock);
23466 	return (0);
23467 }
23468 
23469 
23470 /* Data for fast netmask macro used by tcp_hsp_lookup */
23471 
23472 static ipaddr_t netmasks[] = {
23473 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
23474 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
23475 };
23476 
23477 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
23478 
23479 /*
23480  * XXX This routine should go away and instead we should use the metrics
23481  * associated with the routes to determine the default sndspace and rcvspace.
23482  */
23483 static tcp_hsp_t *
23484 tcp_hsp_lookup(ipaddr_t addr)
23485 {
23486 	tcp_hsp_t *hsp = NULL;
23487 
23488 	/* Quick check without acquiring the lock. */
23489 	if (tcp_hsp_hash == NULL)
23490 		return (NULL);
23491 
23492 	rw_enter(&tcp_hsp_lock, RW_READER);
23493 
23494 	/* This routine finds the best-matching HSP for address addr. */
23495 
23496 	if (tcp_hsp_hash) {
23497 		int i;
23498 		ipaddr_t srchaddr;
23499 		tcp_hsp_t *hsp_net;
23500 
23501 		/* We do three passes: host, network, and subnet. */
23502 
23503 		srchaddr = addr;
23504 
23505 		for (i = 1; i <= 3; i++) {
23506 			/* Look for exact match on srchaddr */
23507 
23508 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
23509 			while (hsp) {
23510 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
23511 				    hsp->tcp_hsp_addr == srchaddr)
23512 					break;
23513 				hsp = hsp->tcp_hsp_next;
23514 			}
23515 			ASSERT(hsp == NULL ||
23516 			    hsp->tcp_hsp_vers == IPV4_VERSION);
23517 
23518 			/*
23519 			 * If this is the first pass:
23520 			 *   If we found a match, great, return it.
23521 			 *   If not, search for the network on the second pass.
23522 			 */
23523 
23524 			if (i == 1)
23525 				if (hsp)
23526 					break;
23527 				else
23528 				{
23529 					srchaddr = addr & netmask(addr);
23530 					continue;
23531 				}
23532 
23533 			/*
23534 			 * If this is the second pass:
23535 			 *   If we found a match, but there's a subnet mask,
23536 			 *    save the match but try again using the subnet
23537 			 *    mask on the third pass.
23538 			 *   Otherwise, return whatever we found.
23539 			 */
23540 
23541 			if (i == 2) {
23542 				if (hsp && hsp->tcp_hsp_subnet) {
23543 					hsp_net = hsp;
23544 					srchaddr = addr & hsp->tcp_hsp_subnet;
23545 					continue;
23546 				} else {
23547 					break;
23548 				}
23549 			}
23550 
23551 			/*
23552 			 * This must be the third pass.  If we didn't find
23553 			 * anything, return the saved network HSP instead.
23554 			 */
23555 
23556 			if (!hsp)
23557 				hsp = hsp_net;
23558 		}
23559 	}
23560 
23561 	rw_exit(&tcp_hsp_lock);
23562 	return (hsp);
23563 }
23564 
23565 /*
23566  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
23567  * match lookup.
23568  */
23569 static tcp_hsp_t *
23570 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
23571 {
23572 	tcp_hsp_t *hsp = NULL;
23573 
23574 	/* Quick check without acquiring the lock. */
23575 	if (tcp_hsp_hash == NULL)
23576 		return (NULL);
23577 
23578 	rw_enter(&tcp_hsp_lock, RW_READER);
23579 
23580 	/* This routine finds the best-matching HSP for address addr. */
23581 
23582 	if (tcp_hsp_hash) {
23583 		int i;
23584 		in6_addr_t v6srchaddr;
23585 		tcp_hsp_t *hsp_net;
23586 
23587 		/* We do three passes: host, network, and subnet. */
23588 
23589 		v6srchaddr = *v6addr;
23590 
23591 		for (i = 1; i <= 3; i++) {
23592 			/* Look for exact match on srchaddr */
23593 
23594 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
23595 			    V4_PART_OF_V6(v6srchaddr))];
23596 			while (hsp) {
23597 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
23598 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23599 				    &v6srchaddr))
23600 					break;
23601 				hsp = hsp->tcp_hsp_next;
23602 			}
23603 
23604 			/*
23605 			 * If this is the first pass:
23606 			 *   If we found a match, great, return it.
23607 			 *   If not, search for the network on the second pass.
23608 			 */
23609 
23610 			if (i == 1)
23611 				if (hsp)
23612 					break;
23613 				else {
23614 					/* Assume a 64 bit mask */
23615 					v6srchaddr.s6_addr32[0] =
23616 					    v6addr->s6_addr32[0];
23617 					v6srchaddr.s6_addr32[1] =
23618 					    v6addr->s6_addr32[1];
23619 					v6srchaddr.s6_addr32[2] = 0;
23620 					v6srchaddr.s6_addr32[3] = 0;
23621 					continue;
23622 				}
23623 
23624 			/*
23625 			 * If this is the second pass:
23626 			 *   If we found a match, but there's a subnet mask,
23627 			 *    save the match but try again using the subnet
23628 			 *    mask on the third pass.
23629 			 *   Otherwise, return whatever we found.
23630 			 */
23631 
23632 			if (i == 2) {
23633 				ASSERT(hsp == NULL ||
23634 				    hsp->tcp_hsp_vers == IPV6_VERSION);
23635 				if (hsp &&
23636 				    !IN6_IS_ADDR_UNSPECIFIED(
23637 				    &hsp->tcp_hsp_subnet_v6)) {
23638 					hsp_net = hsp;
23639 					V6_MASK_COPY(*v6addr,
23640 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
23641 					continue;
23642 				} else {
23643 					break;
23644 				}
23645 			}
23646 
23647 			/*
23648 			 * This must be the third pass.  If we didn't find
23649 			 * anything, return the saved network HSP instead.
23650 			 */
23651 
23652 			if (!hsp)
23653 				hsp = hsp_net;
23654 		}
23655 	}
23656 
23657 	rw_exit(&tcp_hsp_lock);
23658 	return (hsp);
23659 }
23660 
23661 /*
23662  * Type three generator adapted from the random() function in 4.4 BSD:
23663  */
23664 
23665 /*
23666  * Copyright (c) 1983, 1993
23667  *	The Regents of the University of California.  All rights reserved.
23668  *
23669  * Redistribution and use in source and binary forms, with or without
23670  * modification, are permitted provided that the following conditions
23671  * are met:
23672  * 1. Redistributions of source code must retain the above copyright
23673  *    notice, this list of conditions and the following disclaimer.
23674  * 2. Redistributions in binary form must reproduce the above copyright
23675  *    notice, this list of conditions and the following disclaimer in the
23676  *    documentation and/or other materials provided with the distribution.
23677  * 3. All advertising materials mentioning features or use of this software
23678  *    must display the following acknowledgement:
23679  *	This product includes software developed by the University of
23680  *	California, Berkeley and its contributors.
23681  * 4. Neither the name of the University nor the names of its contributors
23682  *    may be used to endorse or promote products derived from this software
23683  *    without specific prior written permission.
23684  *
23685  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23686  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23687  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23688  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23689  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23690  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23691  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23692  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23693  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23694  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23695  * SUCH DAMAGE.
23696  */
23697 
23698 /* Type 3 -- x**31 + x**3 + 1 */
23699 #define	DEG_3		31
23700 #define	SEP_3		3
23701 
23702 
23703 /* Protected by tcp_random_lock */
23704 static int tcp_randtbl[DEG_3 + 1];
23705 
23706 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23707 static int *tcp_random_rptr = &tcp_randtbl[1];
23708 
23709 static int *tcp_random_state = &tcp_randtbl[1];
23710 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23711 
23712 kmutex_t tcp_random_lock;
23713 
23714 void
23715 tcp_random_init(void)
23716 {
23717 	int i;
23718 	hrtime_t hrt;
23719 	time_t wallclock;
23720 	uint64_t result;
23721 
23722 	/*
23723 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23724 	 * a longlong, which may contain resolution down to nanoseconds.
23725 	 * The current time will either be a 32-bit or a 64-bit quantity.
23726 	 * XOR the two together in a 64-bit result variable.
23727 	 * Convert the result to a 32-bit value by multiplying the high-order
23728 	 * 32-bits by the low-order 32-bits.
23729 	 */
23730 
23731 	hrt = gethrtime();
23732 	(void) drv_getparm(TIME, &wallclock);
23733 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23734 	mutex_enter(&tcp_random_lock);
23735 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23736 	    (result & 0xffffffff);
23737 
23738 	for (i = 1; i < DEG_3; i++)
23739 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23740 			+ 12345;
23741 	tcp_random_fptr = &tcp_random_state[SEP_3];
23742 	tcp_random_rptr = &tcp_random_state[0];
23743 	mutex_exit(&tcp_random_lock);
23744 	for (i = 0; i < 10 * DEG_3; i++)
23745 		(void) tcp_random();
23746 }
23747 
23748 /*
23749  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23750  * This range is selected to be approximately centered on TCP_ISS / 2,
23751  * and easy to compute. We get this value by generating a 32-bit random
23752  * number, selecting out the high-order 17 bits, and then adding one so
23753  * that we never return zero.
23754  */
23755 int
23756 tcp_random(void)
23757 {
23758 	int i;
23759 
23760 	mutex_enter(&tcp_random_lock);
23761 	*tcp_random_fptr += *tcp_random_rptr;
23762 
23763 	/*
23764 	 * The high-order bits are more random than the low-order bits,
23765 	 * so we select out the high-order 17 bits and add one so that
23766 	 * we never return zero.
23767 	 */
23768 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23769 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23770 		tcp_random_fptr = tcp_random_state;
23771 		++tcp_random_rptr;
23772 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23773 		tcp_random_rptr = tcp_random_state;
23774 
23775 	mutex_exit(&tcp_random_lock);
23776 	return (i);
23777 }
23778 
23779 /*
23780  * XXX This will go away when TPI is extended to send
23781  * info reqs to sockfs/timod .....
23782  * Given a queue, set the max packet size for the write
23783  * side of the queue below stream head.  This value is
23784  * cached on the stream head.
23785  * Returns 1 on success, 0 otherwise.
23786  */
23787 static int
23788 setmaxps(queue_t *q, int maxpsz)
23789 {
23790 	struct stdata	*stp;
23791 	queue_t		*wq;
23792 	stp = STREAM(q);
23793 
23794 	/*
23795 	 * At this point change of a queue parameter is not allowed
23796 	 * when a multiplexor is sitting on top.
23797 	 */
23798 	if (stp->sd_flag & STPLEX)
23799 		return (0);
23800 
23801 	claimstr(stp->sd_wrq);
23802 	wq = stp->sd_wrq->q_next;
23803 	ASSERT(wq != NULL);
23804 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23805 	releasestr(stp->sd_wrq);
23806 	return (1);
23807 }
23808 
23809 static int
23810 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23811     int *t_errorp, int *sys_errorp)
23812 {
23813 	int error;
23814 	int is_absreq_failure;
23815 	t_scalar_t *opt_lenp;
23816 	t_scalar_t opt_offset;
23817 	int prim_type;
23818 	struct T_conn_req *tcreqp;
23819 	struct T_conn_res *tcresp;
23820 	cred_t *cr;
23821 
23822 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23823 
23824 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23825 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23826 	    prim_type == T_CONN_RES);
23827 
23828 	switch (prim_type) {
23829 	case T_CONN_REQ:
23830 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23831 		opt_offset = tcreqp->OPT_offset;
23832 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23833 		break;
23834 	case O_T_CONN_RES:
23835 	case T_CONN_RES:
23836 		tcresp = (struct T_conn_res *)mp->b_rptr;
23837 		opt_offset = tcresp->OPT_offset;
23838 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23839 		break;
23840 	}
23841 
23842 	*t_errorp = 0;
23843 	*sys_errorp = 0;
23844 	*do_disconnectp = 0;
23845 
23846 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23847 	    opt_offset, cr, &tcp_opt_obj,
23848 	    NULL, &is_absreq_failure);
23849 
23850 	switch (error) {
23851 	case  0:		/* no error */
23852 		ASSERT(is_absreq_failure == 0);
23853 		return (0);
23854 	case ENOPROTOOPT:
23855 		*t_errorp = TBADOPT;
23856 		break;
23857 	case EACCES:
23858 		*t_errorp = TACCES;
23859 		break;
23860 	default:
23861 		*t_errorp = TSYSERR; *sys_errorp = error;
23862 		break;
23863 	}
23864 	if (is_absreq_failure != 0) {
23865 		/*
23866 		 * The connection request should get the local ack
23867 		 * T_OK_ACK and then a T_DISCON_IND.
23868 		 */
23869 		*do_disconnectp = 1;
23870 	}
23871 	return (-1);
23872 }
23873 
23874 /*
23875  * Split this function out so that if the secret changes, I'm okay.
23876  *
23877  * Initialize the tcp_iss_cookie and tcp_iss_key.
23878  */
23879 
23880 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23881 
23882 static void
23883 tcp_iss_key_init(uint8_t *phrase, int len)
23884 {
23885 	struct {
23886 		int32_t current_time;
23887 		uint32_t randnum;
23888 		uint16_t pad;
23889 		uint8_t ether[6];
23890 		uint8_t passwd[PASSWD_SIZE];
23891 	} tcp_iss_cookie;
23892 	time_t t;
23893 
23894 	/*
23895 	 * Start with the current absolute time.
23896 	 */
23897 	(void) drv_getparm(TIME, &t);
23898 	tcp_iss_cookie.current_time = t;
23899 
23900 	/*
23901 	 * XXX - Need a more random number per RFC 1750, not this crap.
23902 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23903 	 */
23904 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23905 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23906 
23907 	/*
23908 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23909 	 * as a good template.
23910 	 */
23911 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23912 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23913 
23914 	/*
23915 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23916 	 */
23917 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23918 
23919 	/*
23920 	 * See 4010593 if this section becomes a problem again,
23921 	 * but the local ethernet address is useful here.
23922 	 */
23923 	(void) localetheraddr(NULL,
23924 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23925 
23926 	/*
23927 	 * Hash 'em all together.  The MD5Final is called per-connection.
23928 	 */
23929 	mutex_enter(&tcp_iss_key_lock);
23930 	MD5Init(&tcp_iss_key);
23931 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
23932 	    sizeof (tcp_iss_cookie));
23933 	mutex_exit(&tcp_iss_key_lock);
23934 }
23935 
23936 /*
23937  * Set the RFC 1948 pass phrase
23938  */
23939 /* ARGSUSED */
23940 static int
23941 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23942     cred_t *cr)
23943 {
23944 	/*
23945 	 * Basically, value contains a new pass phrase.  Pass it along!
23946 	 */
23947 	tcp_iss_key_init((uint8_t *)value, strlen(value));
23948 	return (0);
23949 }
23950 
23951 /* ARGSUSED */
23952 static int
23953 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23954 {
23955 	bzero(buf, sizeof (tcp_sack_info_t));
23956 	return (0);
23957 }
23958 
23959 /* ARGSUSED */
23960 static int
23961 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23962 {
23963 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23964 	return (0);
23965 }
23966 
23967 void
23968 tcp_ddi_init(void)
23969 {
23970 	int i;
23971 
23972 	/* Initialize locks */
23973 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
23974 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23975 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23976 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23977 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23978 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
23979 
23980 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23981 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
23982 		    MUTEX_DEFAULT, NULL);
23983 	}
23984 
23985 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23986 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
23987 		    MUTEX_DEFAULT, NULL);
23988 	}
23989 
23990 	/* TCP's IPsec code calls the packet dropper. */
23991 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
23992 
23993 	if (!tcp_g_nd) {
23994 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
23995 			nd_free(&tcp_g_nd);
23996 		}
23997 	}
23998 
23999 	/*
24000 	 * Note: To really walk the device tree you need the devinfo
24001 	 * pointer to your device which is only available after probe/attach.
24002 	 * The following is safe only because it uses ddi_root_node()
24003 	 */
24004 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24005 	    tcp_opt_obj.odb_opt_arr_cnt);
24006 
24007 	tcp_timercache = kmem_cache_create("tcp_timercache",
24008 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24009 	    NULL, NULL, NULL, NULL, NULL, 0);
24010 
24011 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24012 	    sizeof (tcp_sack_info_t), 0,
24013 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24014 
24015 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24016 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24017 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24018 
24019 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
24020 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
24021 
24022 	ip_squeue_init(tcp_squeue_add);
24023 
24024 	/* Initialize the random number generator */
24025 	tcp_random_init();
24026 
24027 	/*
24028 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24029 	 * by the boot scripts.
24030 	 *
24031 	 * Use NULL name, as the name is caught by the new lockstats.
24032 	 *
24033 	 * Initialize with some random, non-guessable string, like the global
24034 	 * T_INFO_ACK.
24035 	 */
24036 
24037 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24038 	    sizeof (tcp_g_t_info_ack));
24039 
24040 	if ((tcp_kstat = kstat_create(TCP_MOD_NAME, 0, "tcpstat",
24041 		"net", KSTAT_TYPE_NAMED,
24042 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
24043 		KSTAT_FLAG_VIRTUAL)) != NULL) {
24044 		tcp_kstat->ks_data = &tcp_statistics;
24045 		kstat_install(tcp_kstat);
24046 	}
24047 
24048 	tcp_kstat_init();
24049 }
24050 
24051 void
24052 tcp_ddi_destroy(void)
24053 {
24054 	int i;
24055 
24056 	nd_free(&tcp_g_nd);
24057 
24058 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
24059 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
24060 	}
24061 
24062 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
24063 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
24064 	}
24065 
24066 	mutex_destroy(&tcp_iss_key_lock);
24067 	rw_destroy(&tcp_hsp_lock);
24068 	mutex_destroy(&tcp_g_q_lock);
24069 	mutex_destroy(&tcp_random_lock);
24070 	mutex_destroy(&tcp_epriv_port_lock);
24071 	rw_destroy(&tcp_reserved_port_lock);
24072 
24073 	ip_drop_unregister(&tcp_dropper);
24074 
24075 	kmem_cache_destroy(tcp_timercache);
24076 	kmem_cache_destroy(tcp_sack_info_cache);
24077 	kmem_cache_destroy(tcp_iphc_cache);
24078 
24079 	tcp_kstat_fini();
24080 }
24081 
24082 /*
24083  * Generate ISS, taking into account NDD changes may happen halfway through.
24084  * (If the iss is not zero, set it.)
24085  */
24086 
24087 static void
24088 tcp_iss_init(tcp_t *tcp)
24089 {
24090 	MD5_CTX context;
24091 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24092 	uint32_t answer[4];
24093 
24094 	tcp_iss_incr_extra += (ISS_INCR >> 1);
24095 	tcp->tcp_iss = tcp_iss_incr_extra;
24096 	switch (tcp_strong_iss) {
24097 	case 2:
24098 		mutex_enter(&tcp_iss_key_lock);
24099 		context = tcp_iss_key;
24100 		mutex_exit(&tcp_iss_key_lock);
24101 		arg.ports = tcp->tcp_ports;
24102 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24103 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24104 			    &arg.src);
24105 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24106 			    &arg.dst);
24107 		} else {
24108 			arg.src = tcp->tcp_ip6h->ip6_src;
24109 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24110 		}
24111 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24112 		MD5Final((uchar_t *)answer, &context);
24113 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24114 		/*
24115 		 * Now that we've hashed into a unique per-connection sequence
24116 		 * space, add a random increment per strong_iss == 1.  So I
24117 		 * guess we'll have to...
24118 		 */
24119 		/* FALLTHRU */
24120 	case 1:
24121 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24122 		break;
24123 	default:
24124 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24125 		break;
24126 	}
24127 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24128 	tcp->tcp_fss = tcp->tcp_iss - 1;
24129 	tcp->tcp_suna = tcp->tcp_iss;
24130 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24131 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24132 	tcp->tcp_csuna = tcp->tcp_snxt;
24133 }
24134 
24135 /*
24136  * Exported routine for extracting active tcp connection status.
24137  *
24138  * This is used by the Solaris Cluster Networking software to
24139  * gather a list of connections that need to be forwarded to
24140  * specific nodes in the cluster when configuration changes occur.
24141  *
24142  * The callback is invoked for each tcp_t structure. Returning
24143  * non-zero from the callback routine terminates the search.
24144  */
24145 int
24146 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
24147 {
24148 	tcp_t *tcp;
24149 	cl_tcp_info_t	cl_tcpi;
24150 	connf_t	*connfp;
24151 	conn_t	*connp;
24152 	int	i;
24153 
24154 	ASSERT(callback != NULL);
24155 
24156 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24157 
24158 		connfp = &ipcl_globalhash_fanout[i];
24159 		connp = NULL;
24160 
24161 		while ((connp =
24162 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24163 
24164 			tcp = connp->conn_tcp;
24165 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24166 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24167 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24168 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24169 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24170 			/*
24171 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24172 			 * addresses. They are copied implicitly below as
24173 			 * mapped addresses.
24174 			 */
24175 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24176 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24177 				cl_tcpi.cl_tcpi_faddr =
24178 				    tcp->tcp_ipha->ipha_dst;
24179 			} else {
24180 				cl_tcpi.cl_tcpi_faddr_v6 =
24181 				    tcp->tcp_ip6h->ip6_dst;
24182 			}
24183 
24184 			/*
24185 			 * If the callback returns non-zero
24186 			 * we terminate the traversal.
24187 			 */
24188 			if ((*callback)(&cl_tcpi, arg) != 0) {
24189 				CONN_DEC_REF(tcp->tcp_connp);
24190 				return (1);
24191 			}
24192 		}
24193 	}
24194 
24195 	return (0);
24196 }
24197 
24198 /*
24199  * Macros used for accessing the different types of sockaddr
24200  * structures inside a tcp_ioc_abort_conn_t.
24201  */
24202 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24203 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24204 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24205 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24206 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24207 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24208 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24209 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24210 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24211 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24212 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24213 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24214 
24215 /*
24216  * Return the correct error code to mimic the behavior
24217  * of a connection reset.
24218  */
24219 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24220 		switch ((state)) {		\
24221 		case TCPS_SYN_SENT:		\
24222 		case TCPS_SYN_RCVD:		\
24223 			(err) = ECONNREFUSED;	\
24224 			break;			\
24225 		case TCPS_ESTABLISHED:		\
24226 		case TCPS_FIN_WAIT_1:		\
24227 		case TCPS_FIN_WAIT_2:		\
24228 		case TCPS_CLOSE_WAIT:		\
24229 			(err) = ECONNRESET;	\
24230 			break;			\
24231 		case TCPS_CLOSING:		\
24232 		case TCPS_LAST_ACK:		\
24233 		case TCPS_TIME_WAIT:		\
24234 			(err) = 0;		\
24235 			break;			\
24236 		default:			\
24237 			(err) = ENXIO;		\
24238 		}				\
24239 	}
24240 
24241 /*
24242  * Check if a tcp structure matches the info in acp.
24243  */
24244 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24245 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24246 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24247 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24248 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24249 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24250 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24251 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24252 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24253 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24254 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24255 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24256 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24257 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24258 	&(tcp)->tcp_ip_src_v6)) &&				\
24259 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24260 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24261 	&(tcp)->tcp_remote_v6)) &&				\
24262 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24263 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24264 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24265 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24266 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24267 	(acp)->ac_end >= (tcp)->tcp_state))
24268 
24269 #define	TCP_AC_MATCH(acp, tcp)					\
24270 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24271 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24272 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24273 
24274 /*
24275  * Build a message containing a tcp_ioc_abort_conn_t structure
24276  * which is filled in with information from acp and tp.
24277  */
24278 static mblk_t *
24279 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24280 {
24281 	mblk_t *mp;
24282 	tcp_ioc_abort_conn_t *tacp;
24283 
24284 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24285 	if (mp == NULL)
24286 		return (NULL);
24287 
24288 	mp->b_datap->db_type = M_CTL;
24289 
24290 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24291 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24292 		sizeof (uint32_t));
24293 
24294 	tacp->ac_start = acp->ac_start;
24295 	tacp->ac_end = acp->ac_end;
24296 	tacp->ac_zoneid = acp->ac_zoneid;
24297 
24298 	if (acp->ac_local.ss_family == AF_INET) {
24299 		tacp->ac_local.ss_family = AF_INET;
24300 		tacp->ac_remote.ss_family = AF_INET;
24301 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24302 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24303 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24304 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24305 	} else {
24306 		tacp->ac_local.ss_family = AF_INET6;
24307 		tacp->ac_remote.ss_family = AF_INET6;
24308 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24309 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24310 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24311 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24312 	}
24313 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24314 	return (mp);
24315 }
24316 
24317 /*
24318  * Print a tcp_ioc_abort_conn_t structure.
24319  */
24320 static void
24321 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24322 {
24323 	char lbuf[128];
24324 	char rbuf[128];
24325 	sa_family_t af;
24326 	in_port_t lport, rport;
24327 	ushort_t logflags;
24328 
24329 	af = acp->ac_local.ss_family;
24330 
24331 	if (af == AF_INET) {
24332 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24333 				lbuf, 128);
24334 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24335 				rbuf, 128);
24336 		lport = ntohs(TCP_AC_V4LPORT(acp));
24337 		rport = ntohs(TCP_AC_V4RPORT(acp));
24338 	} else {
24339 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24340 				lbuf, 128);
24341 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24342 				rbuf, 128);
24343 		lport = ntohs(TCP_AC_V6LPORT(acp));
24344 		rport = ntohs(TCP_AC_V6RPORT(acp));
24345 	}
24346 
24347 	logflags = SL_TRACE | SL_NOTE;
24348 	/*
24349 	 * Don't print this message to the console if the operation was done
24350 	 * to a non-global zone.
24351 	 */
24352 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24353 		logflags |= SL_CONSOLE;
24354 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24355 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24356 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24357 		acp->ac_start, acp->ac_end);
24358 }
24359 
24360 /*
24361  * Called inside tcp_rput when a message built using
24362  * tcp_ioctl_abort_build_msg is put into a queue.
24363  * Note that when we get here there is no wildcard in acp any more.
24364  */
24365 static void
24366 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24367 {
24368 	tcp_ioc_abort_conn_t *acp;
24369 
24370 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24371 	if (tcp->tcp_state <= acp->ac_end) {
24372 		/*
24373 		 * If we get here, we are already on the correct
24374 		 * squeue. This ioctl follows the following path
24375 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24376 		 * ->tcp_ioctl_abort->squeue_fill (if on a
24377 		 * different squeue)
24378 		 */
24379 		int errcode;
24380 
24381 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24382 		(void) tcp_clean_death(tcp, errcode, 26);
24383 	}
24384 	freemsg(mp);
24385 }
24386 
24387 /*
24388  * Abort all matching connections on a hash chain.
24389  */
24390 static int
24391 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24392     boolean_t exact)
24393 {
24394 	int nmatch, err = 0;
24395 	tcp_t *tcp;
24396 	MBLKP mp, last, listhead = NULL;
24397 	conn_t	*tconnp;
24398 	connf_t	*connfp = &ipcl_conn_fanout[index];
24399 
24400 startover:
24401 	nmatch = 0;
24402 
24403 	mutex_enter(&connfp->connf_lock);
24404 	for (tconnp = connfp->connf_head; tconnp != NULL;
24405 	    tconnp = tconnp->conn_next) {
24406 		tcp = tconnp->conn_tcp;
24407 		if (TCP_AC_MATCH(acp, tcp)) {
24408 			CONN_INC_REF(tcp->tcp_connp);
24409 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24410 			if (mp == NULL) {
24411 				err = ENOMEM;
24412 				CONN_DEC_REF(tcp->tcp_connp);
24413 				break;
24414 			}
24415 			mp->b_prev = (mblk_t *)tcp;
24416 
24417 			if (listhead == NULL) {
24418 				listhead = mp;
24419 				last = mp;
24420 			} else {
24421 				last->b_next = mp;
24422 				last = mp;
24423 			}
24424 			nmatch++;
24425 			if (exact)
24426 				break;
24427 		}
24428 
24429 		/* Avoid holding lock for too long. */
24430 		if (nmatch >= 500)
24431 			break;
24432 	}
24433 	mutex_exit(&connfp->connf_lock);
24434 
24435 	/* Pass mp into the correct tcp */
24436 	while ((mp = listhead) != NULL) {
24437 		listhead = listhead->b_next;
24438 		tcp = (tcp_t *)mp->b_prev;
24439 		mp->b_next = mp->b_prev = NULL;
24440 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
24441 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
24442 	}
24443 
24444 	*count += nmatch;
24445 	if (nmatch >= 500 && err == 0)
24446 		goto startover;
24447 	return (err);
24448 }
24449 
24450 /*
24451  * Abort all connections that matches the attributes specified in acp.
24452  */
24453 static int
24454 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
24455 {
24456 	sa_family_t af;
24457 	uint32_t  ports;
24458 	uint16_t *pports;
24459 	int err = 0, count = 0;
24460 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24461 	int index = -1;
24462 	ushort_t logflags;
24463 
24464 	af = acp->ac_local.ss_family;
24465 
24466 	if (af == AF_INET) {
24467 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24468 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24469 			pports = (uint16_t *)&ports;
24470 			pports[1] = TCP_AC_V4LPORT(acp);
24471 			pports[0] = TCP_AC_V4RPORT(acp);
24472 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24473 		}
24474 	} else {
24475 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24476 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24477 			pports = (uint16_t *)&ports;
24478 			pports[1] = TCP_AC_V6LPORT(acp);
24479 			pports[0] = TCP_AC_V6RPORT(acp);
24480 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24481 		}
24482 	}
24483 
24484 	/*
24485 	 * For cases where remote addr, local port, and remote port are non-
24486 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24487 	 */
24488 	if (index != -1) {
24489 		err = tcp_ioctl_abort_bucket(acp, index,
24490 			    &count, exact);
24491 	} else {
24492 		/*
24493 		 * loop through all entries for wildcard case
24494 		 */
24495 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
24496 			err = tcp_ioctl_abort_bucket(acp, index,
24497 			    &count, exact);
24498 			if (err != 0)
24499 				break;
24500 		}
24501 	}
24502 
24503 	logflags = SL_TRACE | SL_NOTE;
24504 	/*
24505 	 * Don't print this message to the console if the operation was done
24506 	 * to a non-global zone.
24507 	 */
24508 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24509 		logflags |= SL_CONSOLE;
24510 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24511 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24512 	if (err == 0 && count == 0)
24513 		err = ENOENT;
24514 	return (err);
24515 }
24516 
24517 /*
24518  * Process the TCP_IOC_ABORT_CONN ioctl request.
24519  */
24520 static void
24521 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24522 {
24523 	int	err;
24524 	IOCP    iocp;
24525 	MBLKP   mp1;
24526 	sa_family_t laf, raf;
24527 	tcp_ioc_abort_conn_t *acp;
24528 	zone_t *zptr;
24529 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
24530 
24531 	iocp = (IOCP)mp->b_rptr;
24532 
24533 	if ((mp1 = mp->b_cont) == NULL ||
24534 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24535 		err = EINVAL;
24536 		goto out;
24537 	}
24538 
24539 	/* check permissions */
24540 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
24541 		err = EPERM;
24542 		goto out;
24543 	}
24544 
24545 	if (mp1->b_cont != NULL) {
24546 		freemsg(mp1->b_cont);
24547 		mp1->b_cont = NULL;
24548 	}
24549 
24550 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24551 	laf = acp->ac_local.ss_family;
24552 	raf = acp->ac_remote.ss_family;
24553 
24554 	/* check that a zone with the supplied zoneid exists */
24555 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24556 		zptr = zone_find_by_id(zoneid);
24557 		if (zptr != NULL) {
24558 			zone_rele(zptr);
24559 		} else {
24560 			err = EINVAL;
24561 			goto out;
24562 		}
24563 	}
24564 
24565 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24566 	    acp->ac_start > acp->ac_end || laf != raf ||
24567 	    (laf != AF_INET && laf != AF_INET6)) {
24568 		err = EINVAL;
24569 		goto out;
24570 	}
24571 
24572 	tcp_ioctl_abort_dump(acp);
24573 	err = tcp_ioctl_abort(acp);
24574 
24575 out:
24576 	if (mp1 != NULL) {
24577 		freemsg(mp1);
24578 		mp->b_cont = NULL;
24579 	}
24580 
24581 	if (err != 0)
24582 		miocnak(q, mp, 0, err);
24583 	else
24584 		miocack(q, mp, 0, 0);
24585 }
24586 
24587 /*
24588  * tcp_time_wait_processing() handles processing of incoming packets when
24589  * the tcp is in the TIME_WAIT state.
24590  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24591  * on the time wait list.
24592  */
24593 void
24594 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24595     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24596 {
24597 	int32_t		bytes_acked;
24598 	int32_t		gap;
24599 	int32_t		rgap;
24600 	tcp_opt_t	tcpopt;
24601 	uint_t		flags;
24602 	uint32_t	new_swnd = 0;
24603 	conn_t		*connp;
24604 
24605 	BUMP_LOCAL(tcp->tcp_ibsegs);
24606 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
24607 
24608 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24609 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24610 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24611 	if (tcp->tcp_snd_ts_ok) {
24612 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24613 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24614 			    tcp->tcp_rnxt, TH_ACK);
24615 			goto done;
24616 		}
24617 	}
24618 	gap = seg_seq - tcp->tcp_rnxt;
24619 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24620 	if (gap < 0) {
24621 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
24622 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
24623 		    (seg_len > -gap ? -gap : seg_len));
24624 		seg_len += gap;
24625 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24626 			if (flags & TH_RST) {
24627 				goto done;
24628 			}
24629 			if ((flags & TH_FIN) && seg_len == -1) {
24630 				/*
24631 				 * When TCP receives a duplicate FIN in
24632 				 * TIME_WAIT state, restart the 2 MSL timer.
24633 				 * See page 73 in RFC 793. Make sure this TCP
24634 				 * is already on the TIME_WAIT list. If not,
24635 				 * just restart the timer.
24636 				 */
24637 				if (TCP_IS_DETACHED(tcp)) {
24638 					tcp_time_wait_remove(tcp, NULL);
24639 					tcp_time_wait_append(tcp);
24640 					TCP_DBGSTAT(tcp_rput_time_wait);
24641 				} else {
24642 					ASSERT(tcp != NULL);
24643 					TCP_TIMER_RESTART(tcp,
24644 					    tcp_time_wait_interval);
24645 				}
24646 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24647 				    tcp->tcp_rnxt, TH_ACK);
24648 				goto done;
24649 			}
24650 			flags |=  TH_ACK_NEEDED;
24651 			seg_len = 0;
24652 			goto process_ack;
24653 		}
24654 
24655 		/* Fix seg_seq, and chew the gap off the front. */
24656 		seg_seq = tcp->tcp_rnxt;
24657 	}
24658 
24659 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24660 		/*
24661 		 * Make sure that when we accept the connection, pick
24662 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24663 		 * old connection.
24664 		 *
24665 		 * The next ISS generated is equal to tcp_iss_incr_extra
24666 		 * + ISS_INCR/2 + other components depending on the
24667 		 * value of tcp_strong_iss.  We pre-calculate the new
24668 		 * ISS here and compare with tcp_snxt to determine if
24669 		 * we need to make adjustment to tcp_iss_incr_extra.
24670 		 *
24671 		 * The above calculation is ugly and is a
24672 		 * waste of CPU cycles...
24673 		 */
24674 		uint32_t new_iss = tcp_iss_incr_extra;
24675 		int32_t adj;
24676 
24677 		switch (tcp_strong_iss) {
24678 		case 2: {
24679 			/* Add time and MD5 components. */
24680 			uint32_t answer[4];
24681 			struct {
24682 				uint32_t ports;
24683 				in6_addr_t src;
24684 				in6_addr_t dst;
24685 			} arg;
24686 			MD5_CTX context;
24687 
24688 			mutex_enter(&tcp_iss_key_lock);
24689 			context = tcp_iss_key;
24690 			mutex_exit(&tcp_iss_key_lock);
24691 			arg.ports = tcp->tcp_ports;
24692 			/* We use MAPPED addresses in tcp_iss_init */
24693 			arg.src = tcp->tcp_ip_src_v6;
24694 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24695 				IN6_IPADDR_TO_V4MAPPED(
24696 					tcp->tcp_ipha->ipha_dst,
24697 					    &arg.dst);
24698 			} else {
24699 				arg.dst =
24700 				    tcp->tcp_ip6h->ip6_dst;
24701 			}
24702 			MD5Update(&context, (uchar_t *)&arg,
24703 			    sizeof (arg));
24704 			MD5Final((uchar_t *)answer, &context);
24705 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24706 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24707 			break;
24708 		}
24709 		case 1:
24710 			/* Add time component and min random (i.e. 1). */
24711 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24712 			break;
24713 		default:
24714 			/* Add only time component. */
24715 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24716 			break;
24717 		}
24718 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24719 			/*
24720 			 * New ISS not guaranteed to be ISS_INCR/2
24721 			 * ahead of the current tcp_snxt, so add the
24722 			 * difference to tcp_iss_incr_extra.
24723 			 */
24724 			tcp_iss_incr_extra += adj;
24725 		}
24726 		/*
24727 		 * If tcp_clean_death() can not perform the task now,
24728 		 * drop the SYN packet and let the other side re-xmit.
24729 		 * Otherwise pass the SYN packet back in, since the
24730 		 * old tcp state has been cleaned up or freed.
24731 		 */
24732 		if (tcp_clean_death(tcp, 0, 27) == -1)
24733 			goto done;
24734 		/*
24735 		 * We will come back to tcp_rput_data
24736 		 * on the global queue. Packets destined
24737 		 * for the global queue will be checked
24738 		 * with global policy. But the policy for
24739 		 * this packet has already been checked as
24740 		 * this was destined for the detached
24741 		 * connection. We need to bypass policy
24742 		 * check this time by attaching a dummy
24743 		 * ipsec_in with ipsec_in_dont_check set.
24744 		 */
24745 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
24746 		    NULL) {
24747 			TCP_STAT(tcp_time_wait_syn_success);
24748 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24749 			return;
24750 		}
24751 		goto done;
24752 	}
24753 
24754 	/*
24755 	 * rgap is the amount of stuff received out of window.  A negative
24756 	 * value is the amount out of window.
24757 	 */
24758 	if (rgap < 0) {
24759 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
24760 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
24761 		/* Fix seg_len and make sure there is something left. */
24762 		seg_len += rgap;
24763 		if (seg_len <= 0) {
24764 			if (flags & TH_RST) {
24765 				goto done;
24766 			}
24767 			flags |=  TH_ACK_NEEDED;
24768 			seg_len = 0;
24769 			goto process_ack;
24770 		}
24771 	}
24772 	/*
24773 	 * Check whether we can update tcp_ts_recent.  This test is
24774 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24775 	 * Extensions for High Performance: An Update", Internet Draft.
24776 	 */
24777 	if (tcp->tcp_snd_ts_ok &&
24778 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24779 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24780 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24781 		tcp->tcp_last_rcv_lbolt = lbolt64;
24782 	}
24783 
24784 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24785 		/* Always ack out of order packets */
24786 		flags |= TH_ACK_NEEDED;
24787 		seg_len = 0;
24788 	} else if (seg_len > 0) {
24789 		BUMP_MIB(&tcp_mib, tcpInClosed);
24790 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
24791 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
24792 	}
24793 	if (flags & TH_RST) {
24794 		(void) tcp_clean_death(tcp, 0, 28);
24795 		goto done;
24796 	}
24797 	if (flags & TH_SYN) {
24798 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24799 		    TH_RST|TH_ACK);
24800 		/*
24801 		 * Do not delete the TCP structure if it is in
24802 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24803 		 */
24804 		goto done;
24805 	}
24806 process_ack:
24807 	if (flags & TH_ACK) {
24808 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24809 		if (bytes_acked <= 0) {
24810 			if (bytes_acked == 0 && seg_len == 0 &&
24811 			    new_swnd == tcp->tcp_swnd)
24812 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24813 		} else {
24814 			/* Acks something not sent */
24815 			flags |= TH_ACK_NEEDED;
24816 		}
24817 	}
24818 	if (flags & TH_ACK_NEEDED) {
24819 		/*
24820 		 * Time to send an ack for some reason.
24821 		 */
24822 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24823 		    tcp->tcp_rnxt, TH_ACK);
24824 	}
24825 done:
24826 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24827 		DB_CKSUMSTART(mp) = 0;
24828 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24829 		TCP_STAT(tcp_time_wait_syn_fail);
24830 	}
24831 	freemsg(mp);
24832 }
24833 
24834 /*
24835  * Allocate a T_SVR4_OPTMGMT_REQ.
24836  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24837  * that tcp_rput_other can drop the acks.
24838  */
24839 static mblk_t *
24840 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24841 {
24842 	mblk_t *mp;
24843 	struct T_optmgmt_req *tor;
24844 	struct opthdr *oh;
24845 	uint_t size;
24846 	char *optptr;
24847 
24848 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24849 	mp = allocb(size, BPRI_MED);
24850 	if (mp == NULL)
24851 		return (NULL);
24852 
24853 	mp->b_wptr += size;
24854 	mp->b_datap->db_type = M_PROTO;
24855 	tor = (struct T_optmgmt_req *)mp->b_rptr;
24856 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
24857 	tor->MGMT_flags = T_NEGOTIATE;
24858 	tor->OPT_length = sizeof (*oh) + optlen;
24859 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
24860 
24861 	oh = (struct opthdr *)&tor[1];
24862 	oh->level = level;
24863 	oh->name = cmd;
24864 	oh->len = optlen;
24865 	if (optlen != 0) {
24866 		optptr = (char *)&oh[1];
24867 		bcopy(opt, optptr, optlen);
24868 	}
24869 	return (mp);
24870 }
24871 
24872 /*
24873  * TCP Timers Implementation.
24874  */
24875 timeout_id_t
24876 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24877 {
24878 	mblk_t *mp;
24879 	tcp_timer_t *tcpt;
24880 	tcp_t *tcp = connp->conn_tcp;
24881 
24882 	ASSERT(connp->conn_sqp != NULL);
24883 
24884 	TCP_DBGSTAT(tcp_timeout_calls);
24885 
24886 	if (tcp->tcp_timercache == NULL) {
24887 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24888 	} else {
24889 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
24890 		mp = tcp->tcp_timercache;
24891 		tcp->tcp_timercache = mp->b_next;
24892 		mp->b_next = NULL;
24893 		ASSERT(mp->b_wptr == NULL);
24894 	}
24895 
24896 	CONN_INC_REF(connp);
24897 	tcpt = (tcp_timer_t *)mp->b_rptr;
24898 	tcpt->connp = connp;
24899 	tcpt->tcpt_proc = f;
24900 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
24901 	return ((timeout_id_t)mp);
24902 }
24903 
24904 static void
24905 tcp_timer_callback(void *arg)
24906 {
24907 	mblk_t *mp = (mblk_t *)arg;
24908 	tcp_timer_t *tcpt;
24909 	conn_t	*connp;
24910 
24911 	tcpt = (tcp_timer_t *)mp->b_rptr;
24912 	connp = tcpt->connp;
24913 	squeue_fill(connp->conn_sqp, mp,
24914 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
24915 }
24916 
24917 static void
24918 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24919 {
24920 	tcp_timer_t *tcpt;
24921 	conn_t *connp = (conn_t *)arg;
24922 	tcp_t *tcp = connp->conn_tcp;
24923 
24924 	tcpt = (tcp_timer_t *)mp->b_rptr;
24925 	ASSERT(connp == tcpt->connp);
24926 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24927 
24928 	/*
24929 	 * If the TCP has reached the closed state, don't proceed any
24930 	 * further. This TCP logically does not exist on the system.
24931 	 * tcpt_proc could for example access queues, that have already
24932 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24933 	 */
24934 	if (tcp->tcp_state != TCPS_CLOSED) {
24935 		(*tcpt->tcpt_proc)(connp);
24936 	} else {
24937 		tcp->tcp_timer_tid = 0;
24938 	}
24939 	tcp_timer_free(connp->conn_tcp, mp);
24940 }
24941 
24942 /*
24943  * There is potential race with untimeout and the handler firing at the same
24944  * time. The mblock may be freed by the handler while we are trying to use
24945  * it. But since both should execute on the same squeue, this race should not
24946  * occur.
24947  */
24948 clock_t
24949 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24950 {
24951 	mblk_t	*mp = (mblk_t *)id;
24952 	tcp_timer_t *tcpt;
24953 	clock_t delta;
24954 
24955 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
24956 
24957 	if (mp == NULL)
24958 		return (-1);
24959 
24960 	tcpt = (tcp_timer_t *)mp->b_rptr;
24961 	ASSERT(tcpt->connp == connp);
24962 
24963 	delta = untimeout(tcpt->tcpt_tid);
24964 
24965 	if (delta >= 0) {
24966 		TCP_DBGSTAT(tcp_timeout_canceled);
24967 		tcp_timer_free(connp->conn_tcp, mp);
24968 		CONN_DEC_REF(connp);
24969 	}
24970 
24971 	return (delta);
24972 }
24973 
24974 /*
24975  * Allocate space for the timer event. The allocation looks like mblk, but it is
24976  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24977  *
24978  * Dealing with failures: If we can't allocate from the timer cache we try
24979  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24980  * points to b_rptr.
24981  * If we can't allocate anything using allocb_tryhard(), we perform a last
24982  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24983  * save the actual allocation size in b_datap.
24984  */
24985 mblk_t *
24986 tcp_timermp_alloc(int kmflags)
24987 {
24988 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
24989 	    kmflags & ~KM_PANIC);
24990 
24991 	if (mp != NULL) {
24992 		mp->b_next = mp->b_prev = NULL;
24993 		mp->b_rptr = (uchar_t *)(&mp[1]);
24994 		mp->b_wptr = NULL;
24995 		mp->b_datap = NULL;
24996 		mp->b_queue = NULL;
24997 	} else if (kmflags & KM_PANIC) {
24998 		/*
24999 		 * Failed to allocate memory for the timer. Try allocating from
25000 		 * dblock caches.
25001 		 */
25002 		TCP_STAT(tcp_timermp_allocfail);
25003 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25004 		if (mp == NULL) {
25005 			size_t size = 0;
25006 			/*
25007 			 * Memory is really low. Try tryhard allocation.
25008 			 */
25009 			TCP_STAT(tcp_timermp_allocdblfail);
25010 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25011 			    sizeof (tcp_timer_t), &size, kmflags);
25012 			mp->b_rptr = (uchar_t *)(&mp[1]);
25013 			mp->b_next = mp->b_prev = NULL;
25014 			mp->b_wptr = (uchar_t *)-1;
25015 			mp->b_datap = (dblk_t *)size;
25016 			mp->b_queue = NULL;
25017 		}
25018 		ASSERT(mp->b_wptr != NULL);
25019 	}
25020 	TCP_DBGSTAT(tcp_timermp_alloced);
25021 
25022 	return (mp);
25023 }
25024 
25025 /*
25026  * Free per-tcp timer cache.
25027  * It can only contain entries from tcp_timercache.
25028  */
25029 void
25030 tcp_timermp_free(tcp_t *tcp)
25031 {
25032 	mblk_t *mp;
25033 
25034 	while ((mp = tcp->tcp_timercache) != NULL) {
25035 		ASSERT(mp->b_wptr == NULL);
25036 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25037 		kmem_cache_free(tcp_timercache, mp);
25038 	}
25039 }
25040 
25041 /*
25042  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25043  * events there already (currently at most two events are cached).
25044  * If the event is not allocated from the timer cache, free it right away.
25045  */
25046 static void
25047 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25048 {
25049 	mblk_t *mp1 = tcp->tcp_timercache;
25050 
25051 	if (mp->b_wptr != NULL) {
25052 		/*
25053 		 * This allocation is not from a timer cache, free it right
25054 		 * away.
25055 		 */
25056 		if (mp->b_wptr != (uchar_t *)-1)
25057 			freeb(mp);
25058 		else
25059 			kmem_free(mp, (size_t)mp->b_datap);
25060 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25061 		/* Cache this timer block for future allocations */
25062 		mp->b_rptr = (uchar_t *)(&mp[1]);
25063 		mp->b_next = mp1;
25064 		tcp->tcp_timercache = mp;
25065 	} else {
25066 		kmem_cache_free(tcp_timercache, mp);
25067 		TCP_DBGSTAT(tcp_timermp_freed);
25068 	}
25069 }
25070 
25071 /*
25072  * End of TCP Timers implementation.
25073  */
25074 
25075 /*
25076  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25077  * on the specified backing STREAMS q. Note, the caller may make the
25078  * decision to call based on the tcp_t.tcp_flow_stopped value which
25079  * when check outside the q's lock is only an advisory check ...
25080  */
25081 
25082 void
25083 tcp_setqfull(tcp_t *tcp)
25084 {
25085 	queue_t *q = tcp->tcp_wq;
25086 
25087 	if (!(q->q_flag & QFULL)) {
25088 		mutex_enter(QLOCK(q));
25089 		if (!(q->q_flag & QFULL)) {
25090 			/* still need to set QFULL */
25091 			q->q_flag |= QFULL;
25092 			tcp->tcp_flow_stopped = B_TRUE;
25093 			mutex_exit(QLOCK(q));
25094 			TCP_STAT(tcp_flwctl_on);
25095 		} else {
25096 			mutex_exit(QLOCK(q));
25097 		}
25098 	}
25099 }
25100 
25101 void
25102 tcp_clrqfull(tcp_t *tcp)
25103 {
25104 	queue_t *q = tcp->tcp_wq;
25105 
25106 	if (q->q_flag & QFULL) {
25107 		mutex_enter(QLOCK(q));
25108 		if (q->q_flag & QFULL) {
25109 			q->q_flag &= ~QFULL;
25110 			tcp->tcp_flow_stopped = B_FALSE;
25111 			mutex_exit(QLOCK(q));
25112 			if (q->q_flag & QWANTW)
25113 				qbackenable(q, 0);
25114 		} else {
25115 			mutex_exit(QLOCK(q));
25116 		}
25117 	}
25118 }
25119 
25120 /*
25121  * TCP Kstats implementation
25122  */
25123 static void
25124 tcp_kstat_init(void)
25125 {
25126 	tcp_named_kstat_t template = {
25127 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25128 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25129 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25130 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25131 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25132 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25133 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25134 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25135 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25136 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
25137 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
25138 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25139 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25140 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25141 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25142 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25143 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25144 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25145 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25146 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25147 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25148 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25149 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25150 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25151 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25152 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25153 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25154 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25155 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25156 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25157 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25158 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25159 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25160 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25161 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25162 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25163 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25164 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25165 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25166 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25167 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25168 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25169 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25170 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25171 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25172 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25173 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25174 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25175 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25176 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25177 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25178 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25179 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25180 	};
25181 
25182 	tcp_mibkp = kstat_create(TCP_MOD_NAME, 0, TCP_MOD_NAME,
25183 	    "mib2", KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0);
25184 
25185 	if (tcp_mibkp == NULL)
25186 		return;
25187 
25188 	template.rtoAlgorithm.value.ui32 = 4;
25189 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
25190 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
25191 	template.maxConn.value.i32 = -1;
25192 
25193 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
25194 
25195 	tcp_mibkp->ks_update = tcp_kstat_update;
25196 
25197 	kstat_install(tcp_mibkp);
25198 }
25199 
25200 static void
25201 tcp_kstat_fini(void)
25202 {
25203 
25204 	if (tcp_mibkp != NULL) {
25205 		kstat_delete(tcp_mibkp);
25206 		tcp_mibkp = NULL;
25207 	}
25208 }
25209 
25210 static int
25211 tcp_kstat_update(kstat_t *kp, int rw)
25212 {
25213 	tcp_named_kstat_t	*tcpkp;
25214 	tcp_t			*tcp;
25215 	connf_t			*connfp;
25216 	conn_t			*connp;
25217 	int 			i;
25218 
25219 	if (!kp || !kp->ks_data)
25220 		return (EIO);
25221 
25222 	if (rw == KSTAT_WRITE)
25223 		return (EACCES);
25224 
25225 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25226 
25227 	tcpkp->currEstab.value.ui32 = 0;
25228 
25229 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25230 		connfp = &ipcl_globalhash_fanout[i];
25231 		connp = NULL;
25232 		while ((connp =
25233 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25234 			tcp = connp->conn_tcp;
25235 			switch (tcp_snmp_state(tcp)) {
25236 			case MIB2_TCP_established:
25237 			case MIB2_TCP_closeWait:
25238 				tcpkp->currEstab.value.ui32++;
25239 				break;
25240 			}
25241 		}
25242 	}
25243 
25244 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
25245 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
25246 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
25247 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
25248 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
25249 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
25250 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
25251 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
25252 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
25253 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
25254 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
25255 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
25256 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
25257 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
25258 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
25259 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
25260 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
25261 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
25262 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
25263 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
25264 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
25265 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
25266 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
25267 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
25268 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
25269 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
25270 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
25271 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
25272 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
25273 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
25274 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
25275 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
25276 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
25277 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
25278 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
25279 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
25280 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
25281 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
25282 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
25283 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
25284 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
25285 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
25286 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
25287 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
25288 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
25289 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
25290 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
25291 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
25292 
25293 	return (0);
25294 }
25295 
25296 void
25297 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25298 {
25299 	uint16_t	hdr_len;
25300 	ipha_t		*ipha;
25301 	uint8_t		*nexthdrp;
25302 	tcph_t		*tcph;
25303 
25304 	/* Already has an eager */
25305 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25306 		TCP_STAT(tcp_reinput_syn);
25307 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
25308 		    connp, SQTAG_TCP_REINPUT_EAGER);
25309 		return;
25310 	}
25311 
25312 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25313 	case IPV4_VERSION:
25314 		ipha = (ipha_t *)mp->b_rptr;
25315 		hdr_len = IPH_HDR_LENGTH(ipha);
25316 		break;
25317 	case IPV6_VERSION:
25318 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25319 		    &hdr_len, &nexthdrp)) {
25320 			CONN_DEC_REF(connp);
25321 			freemsg(mp);
25322 			return;
25323 		}
25324 		break;
25325 	}
25326 
25327 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25328 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25329 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25330 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25331 	}
25332 
25333 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
25334 	    SQTAG_TCP_REINPUT);
25335 }
25336 
25337 static squeue_func_t
25338 tcp_squeue_switch(int val)
25339 {
25340 	squeue_func_t rval = squeue_fill;
25341 
25342 	switch (val) {
25343 	case 1:
25344 		rval = squeue_enter_nodrain;
25345 		break;
25346 	case 2:
25347 		rval = squeue_enter;
25348 		break;
25349 	default:
25350 		break;
25351 	}
25352 	return (rval);
25353 }
25354 
25355 static void
25356 tcp_squeue_add(squeue_t *sqp)
25357 {
25358 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25359 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
25360 
25361 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25362 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
25363 	    sqp, TCP_TIME_WAIT_DELAY);
25364 	if (tcp_free_list_max_cnt == 0) {
25365 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25366 			max_ncpus : boot_max_ncpus);
25367 
25368 		/*
25369 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25370 		 */
25371 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25372 			(tcp_ncpus * sizeof (tcp_t) * 100);
25373 	}
25374 	tcp_time_wait->tcp_free_list_cnt = 0;
25375 }
25376