xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 1979231e)
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/vtrace.h>
49 #include <sys/kmem.h>
50 #include <sys/ethernet.h>
51 #include <sys/cpuvar.h>
52 #include <sys/dlpi.h>
53 #include <sys/multidata.h>
54 #include <sys/multidata_impl.h>
55 #include <sys/pattr.h>
56 #include <sys/policy.h>
57 #include <sys/priv.h>
58 #include <sys/zone.h>
59 
60 #include <sys/errno.h>
61 #include <sys/signal.h>
62 #include <sys/socket.h>
63 #include <sys/sockio.h>
64 #include <sys/isa_defs.h>
65 #include <sys/md5.h>
66 #include <sys/random.h>
67 #include <netinet/in.h>
68 #include <netinet/tcp.h>
69 #include <netinet/ip6.h>
70 #include <netinet/icmp6.h>
71 #include <net/if.h>
72 #include <net/route.h>
73 #include <inet/ipsec_impl.h>
74 
75 #include <inet/common.h>
76 #include <inet/ip.h>
77 #include <inet/ip_impl.h>
78 #include <inet/ip6.h>
79 #include <inet/ip_ndp.h>
80 #include <inet/mi.h>
81 #include <inet/mib2.h>
82 #include <inet/nd.h>
83 #include <inet/optcom.h>
84 #include <inet/snmpcom.h>
85 #include <inet/kstatcom.h>
86 #include <inet/tcp.h>
87 #include <inet/tcp_impl.h>
88 #include <net/pfkeyv2.h>
89 #include <inet/ipsec_info.h>
90 #include <inet/ipdrop.h>
91 #include <inet/tcp_trace.h>
92 
93 #include <inet/ipclassifier.h>
94 #include <inet/ip_ire.h>
95 #include <inet/ip_if.h>
96 #include <inet/ipp_common.h>
97 #include <sys/squeue.h>
98 #include <inet/kssl/ksslapi.h>
99 #include <sys/tsol/label.h>
100 #include <sys/tsol/tnet.h>
101 #include <sys/sdt.h>
102 #include <rpc/pmap_prot.h>
103 
104 /*
105  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
106  *
107  * (Read the detailed design doc in PSARC case directory)
108  *
109  * The entire tcp state is contained in tcp_t and conn_t structure
110  * which are allocated in tandem using ipcl_conn_create() and passing
111  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
112  * the references on the tcp_t. The tcp_t structure is never compressed
113  * and packets always land on the correct TCP perimeter from the time
114  * eager is created till the time tcp_t dies (as such the old mentat
115  * TCP global queue is not used for detached state and no IPSEC checking
116  * is required). The global queue is still allocated to send out resets
117  * for connection which have no listeners and IP directly calls
118  * tcp_xmit_listeners_reset() which does any policy check.
119  *
120  * Protection and Synchronisation mechanism:
121  *
122  * The tcp data structure does not use any kind of lock for protecting
123  * its state but instead uses 'squeues' for mutual exclusion from various
124  * read and write side threads. To access a tcp member, the thread should
125  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
126  * squeue_fill). Since the squeues allow a direct function call, caller
127  * can pass any tcp function having prototype of edesc_t as argument
128  * (different from traditional STREAMs model where packets come in only
129  * designated entry points). The list of functions that can be directly
130  * called via squeue are listed before the usual function prototype.
131  *
132  * Referencing:
133  *
134  * TCP is MT-Hot and we use a reference based scheme to make sure that the
135  * tcp structure doesn't disappear when its needed. When the application
136  * creates an outgoing connection or accepts an incoming connection, we
137  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
138  * The IP reference is just a symbolic reference since ip_tcpclose()
139  * looks at tcp structure after tcp_close_output() returns which could
140  * have dropped the last TCP reference. So as long as the connection is
141  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
142  * conn_t. The classifier puts its own reference when the connection is
143  * inserted in listen or connected hash. Anytime a thread needs to enter
144  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
145  * on write side or by doing a classify on read side and then puts a
146  * reference on the conn before doing squeue_enter/tryenter/fill. For
147  * read side, the classifier itself puts the reference under fanout lock
148  * to make sure that tcp can't disappear before it gets processed. The
149  * squeue will drop this reference automatically so the called function
150  * doesn't have to do a DEC_REF.
151  *
152  * Opening a new connection:
153  *
154  * The outgoing connection open is pretty simple. ip_tcpopen() does the
155  * work in creating the conn/tcp structure and initializing it. The
156  * squeue assignment is done based on the CPU the application
157  * is running on. So for outbound connections, processing is always done
158  * on application CPU which might be different from the incoming CPU
159  * being interrupted by the NIC. An optimal way would be to figure out
160  * the NIC <-> CPU binding at listen time, and assign the outgoing
161  * connection to the squeue attached to the CPU that will be interrupted
162  * for incoming packets (we know the NIC based on the bind IP address).
163  * This might seem like a problem if more data is going out but the
164  * fact is that in most cases the transmit is ACK driven transmit where
165  * the outgoing data normally sits on TCP's xmit queue waiting to be
166  * transmitted.
167  *
168  * Accepting a connection:
169  *
170  * This is a more interesting case because of various races involved in
171  * establishing a eager in its own perimeter. Read the meta comment on
172  * top of tcp_conn_request(). But briefly, the squeue is picked by
173  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
174  *
175  * Closing a connection:
176  *
177  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
178  * via squeue to do the close and mark the tcp as detached if the connection
179  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
180  * reference but tcp_close() drop IP's reference always. So if tcp was
181  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
182  * and 1 because it is in classifier's connected hash. This is the condition
183  * we use to determine that its OK to clean up the tcp outside of squeue
184  * when time wait expires (check the ref under fanout and conn_lock and
185  * if it is 2, remove it from fanout hash and kill it).
186  *
187  * Although close just drops the necessary references and marks the
188  * tcp_detached state, tcp_close needs to know the tcp_detached has been
189  * set (under squeue) before letting the STREAM go away (because a
190  * inbound packet might attempt to go up the STREAM while the close
191  * has happened and tcp_detached is not set). So a special lock and
192  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
193  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
194  * tcp_detached.
195  *
196  * Special provisions and fast paths:
197  *
198  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
199  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
200  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
201  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
202  * check to send packets directly to tcp_rput_data via squeue. Everyone
203  * else comes through tcp_input() on the read side.
204  *
205  * We also make special provisions for sockfs by marking tcp_issocket
206  * whenever we have only sockfs on top of TCP. This allows us to skip
207  * putting the tcp in acceptor hash since a sockfs listener can never
208  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
209  * since eager has already been allocated and the accept now happens
210  * on acceptor STREAM. There is a big blob of comment on top of
211  * tcp_conn_request explaining the new accept. When socket is POP'd,
212  * sockfs sends us an ioctl to mark the fact and we go back to old
213  * behaviour. Once tcp_issocket is unset, its never set for the
214  * life of that connection.
215  *
216  * IPsec notes :
217  *
218  * Since a packet is always executed on the correct TCP perimeter
219  * all IPsec processing is defered to IP including checking new
220  * connections and setting IPSEC policies for new connection. The
221  * only exception is tcp_xmit_listeners_reset() which is called
222  * directly from IP and needs to policy check to see if TH_RST
223  * can be sent out.
224  */
225 
226 extern major_t TCP6_MAJ;
227 
228 /*
229  * Values for squeue switch:
230  * 1: squeue_enter_nodrain
231  * 2: squeue_enter
232  * 3: squeue_fill
233  */
234 int tcp_squeue_close = 2;
235 int tcp_squeue_wput = 2;
236 
237 squeue_func_t tcp_squeue_close_proc;
238 squeue_func_t tcp_squeue_wput_proc;
239 
240 /*
241  * This controls how tiny a write must be before we try to copy it
242  * into the the mblk on the tail of the transmit queue.  Not much
243  * speedup is observed for values larger than sixteen.  Zero will
244  * disable the optimisation.
245  */
246 int tcp_tx_pull_len = 16;
247 
248 /*
249  * TCP Statistics.
250  *
251  * How TCP statistics work.
252  *
253  * There are two types of statistics invoked by two macros.
254  *
255  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
256  * supposed to be used in non MT-hot paths of the code.
257  *
258  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
259  * supposed to be used for DEBUG purposes and may be used on a hot path.
260  *
261  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
262  * (use "kstat tcp" to get them).
263  *
264  * There is also additional debugging facility that marks tcp_clean_death()
265  * instances and saves them in tcp_t structure. It is triggered by
266  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
267  * tcp_clean_death() calls that counts the number of times each tag was hit. It
268  * is triggered by TCP_CLD_COUNTERS define.
269  *
270  * How to add new counters.
271  *
272  * 1) Add a field in the tcp_stat structure describing your counter.
273  * 2) Add a line in tcp_statistics with the name of the counter.
274  *
275  *    IMPORTANT!! - make sure that both are in sync !!
276  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
277  *
278  * Please avoid using private counters which are not kstat-exported.
279  *
280  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
281  * in tcp_t structure.
282  *
283  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
284  */
285 
286 #ifndef TCP_DEBUG_COUNTER
287 #ifdef DEBUG
288 #define	TCP_DEBUG_COUNTER 1
289 #else
290 #define	TCP_DEBUG_COUNTER 0
291 #endif
292 #endif
293 
294 #define	TCP_CLD_COUNTERS 0
295 
296 #define	TCP_TAG_CLEAN_DEATH 1
297 #define	TCP_MAX_CLEAN_DEATH_TAG 32
298 
299 #ifdef lint
300 static int _lint_dummy_;
301 #endif
302 
303 #if TCP_CLD_COUNTERS
304 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
305 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
306 #elif defined(lint)
307 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
308 #else
309 #define	TCP_CLD_STAT(x)
310 #endif
311 
312 #if TCP_DEBUG_COUNTER
313 #define	TCP_DBGSTAT(x) atomic_add_64(&(tcp_statistics.x.value.ui64), 1)
314 #elif defined(lint)
315 #define	TCP_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
316 #else
317 #define	TCP_DBGSTAT(x)
318 #endif
319 
320 tcp_stat_t tcp_statistics = {
321 	{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
322 	{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
323 	{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
324 	{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
325 	{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
326 	{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
327 	{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
328 	{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
329 	{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
330 	{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
331 	{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
332 	{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
333 	{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
334 	{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
335 	{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
336 	{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
337 	{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
338 	{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
339 	{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
340 	{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
341 	{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
342 	{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
343 	{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
344 	{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
345 	{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
346 	{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
347 	{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
348 	{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
349 	{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
350 	{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
351 	{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
352 	{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
353 	{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
354 	{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
355 	{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
356 	{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
357 	{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
358 	{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
359 	{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
360 	{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
361 	{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
362 	{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
363 	{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
364 	{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
365 	{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
366 	{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
367 	{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
368 	{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
369 	{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
370 	{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
371 	{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
372 	{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
373 	{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
374 	{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
375 	{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
376 	{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
377 	{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
378 	{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
379 	{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
380 	{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
381 	{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
382 	{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
383 	{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
384 	{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
385 	{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
386 	{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
387 	{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
388 	{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
389 	{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
390 	{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
391 	{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
392 	{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
393 	{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
394 	{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
395 	{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
396 	{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
397 	{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
398 	{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
399 	{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
400 	{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
401 	{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
402 	{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
403 	{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
404 	{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
405 	{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
406 	{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
407 	{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
408 	{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
409 	{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
410 };
411 
412 static kstat_t *tcp_kstat;
413 
414 /*
415  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
416  * tcp write side.
417  */
418 #define	CALL_IP_WPUT(connp, q, mp) {					\
419 	ASSERT(((q)->q_flag & QREADR) == 0);				\
420 	TCP_DBGSTAT(tcp_ip_output);					\
421 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
422 }
423 
424 /* Macros for timestamp comparisons */
425 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
426 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
427 
428 /*
429  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
430  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
431  * by adding three components: a time component which grows by 1 every 4096
432  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
433  * a per-connection component which grows by 125000 for every new connection;
434  * and an "extra" component that grows by a random amount centered
435  * approximately on 64000.  This causes the the ISS generator to cycle every
436  * 4.89 hours if no TCP connections are made, and faster if connections are
437  * made.
438  *
439  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
440  * components: a time component which grows by 250000 every second; and
441  * a per-connection component which grows by 125000 for every new connections.
442  *
443  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
444  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
445  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
446  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
447  * password.
448  */
449 #define	ISS_INCR	250000
450 #define	ISS_NSEC_SHT	12
451 
452 static uint32_t tcp_iss_incr_extra;	/* Incremented for each connection */
453 static kmutex_t tcp_iss_key_lock;
454 static MD5_CTX tcp_iss_key;
455 static sin_t	sin_null;	/* Zero address for quick clears */
456 static sin6_t	sin6_null;	/* Zero address for quick clears */
457 
458 /* Packet dropper for TCP IPsec policy drops. */
459 static ipdropper_t tcp_dropper;
460 
461 /*
462  * This implementation follows the 4.3BSD interpretation of the urgent
463  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
464  * incompatible changes in protocols like telnet and rlogin.
465  */
466 #define	TCP_OLD_URP_INTERPRETATION	1
467 
468 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
469 	(TCP_IS_DETACHED(tcp) && \
470 	    (!(tcp)->tcp_hard_binding))
471 
472 /*
473  * TCP reassembly macros.  We hide starting and ending sequence numbers in
474  * b_next and b_prev of messages on the reassembly queue.  The messages are
475  * chained using b_cont.  These macros are used in tcp_reass() so we don't
476  * have to see the ugly casts and assignments.
477  */
478 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
479 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
480 					(mblk_t *)(uintptr_t)(u))
481 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
482 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
483 					(mblk_t *)(uintptr_t)(u))
484 
485 /*
486  * Implementation of TCP Timers.
487  * =============================
488  *
489  * INTERFACE:
490  *
491  * There are two basic functions dealing with tcp timers:
492  *
493  *	timeout_id_t	tcp_timeout(connp, func, time)
494  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
495  *	TCP_TIMER_RESTART(tcp, intvl)
496  *
497  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
498  * after 'time' ticks passed. The function called by timeout() must adhere to
499  * the same restrictions as a driver soft interrupt handler - it must not sleep
500  * or call other functions that might sleep. The value returned is the opaque
501  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
502  * cancel the request. The call to tcp_timeout() may fail in which case it
503  * returns zero. This is different from the timeout(9F) function which never
504  * fails.
505  *
506  * The call-back function 'func' always receives 'connp' as its single
507  * argument. It is always executed in the squeue corresponding to the tcp
508  * structure. The tcp structure is guaranteed to be present at the time the
509  * call-back is called.
510  *
511  * NOTE: The call-back function 'func' is never called if tcp is in
512  * 	the TCPS_CLOSED state.
513  *
514  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
515  * request. locks acquired by the call-back routine should not be held across
516  * the call to tcp_timeout_cancel() or a deadlock may result.
517  *
518  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
519  * Otherwise, it returns an integer value greater than or equal to 0. In
520  * particular, if the call-back function is already placed on the squeue, it can
521  * not be canceled.
522  *
523  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
524  * 	within squeue context corresponding to the tcp instance. Since the
525  *	call-back is also called via the same squeue, there are no race
526  *	conditions described in untimeout(9F) manual page since all calls are
527  *	strictly serialized.
528  *
529  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
530  *	stored in tcp_timer_tid and starts a new one using
531  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
532  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
533  *	field.
534  *
535  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
536  *	call-back may still be called, so it is possible tcp_timer() will be
537  *	called several times. This should not be a problem since tcp_timer()
538  *	should always check the tcp instance state.
539  *
540  *
541  * IMPLEMENTATION:
542  *
543  * TCP timers are implemented using three-stage process. The call to
544  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
545  * when the timer expires. The tcp_timer_callback() arranges the call of the
546  * tcp_timer_handler() function via squeue corresponding to the tcp
547  * instance. The tcp_timer_handler() calls actual requested timeout call-back
548  * and passes tcp instance as an argument to it. Information is passed between
549  * stages using the tcp_timer_t structure which contains the connp pointer, the
550  * tcp call-back to call and the timeout id returned by the timeout(9F).
551  *
552  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
553  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
554  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
555  * returns the pointer to this mblk.
556  *
557  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
558  * looks like a normal mblk without actual dblk attached to it.
559  *
560  * To optimize performance each tcp instance holds a small cache of timer
561  * mblocks. In the current implementation it caches up to two timer mblocks per
562  * tcp instance. The cache is preserved over tcp frees and is only freed when
563  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
564  * timer processing happens on a corresponding squeue, the cache manipulation
565  * does not require any locks. Experiments show that majority of timer mblocks
566  * allocations are satisfied from the tcp cache and do not involve kmem calls.
567  *
568  * The tcp_timeout() places a refhold on the connp instance which guarantees
569  * that it will be present at the time the call-back function fires. The
570  * tcp_timer_handler() drops the reference after calling the call-back, so the
571  * call-back function does not need to manipulate the references explicitly.
572  */
573 
574 typedef struct tcp_timer_s {
575 	conn_t	*connp;
576 	void 	(*tcpt_proc)(void *);
577 	timeout_id_t   tcpt_tid;
578 } tcp_timer_t;
579 
580 static kmem_cache_t *tcp_timercache;
581 kmem_cache_t	*tcp_sack_info_cache;
582 kmem_cache_t	*tcp_iphc_cache;
583 
584 /*
585  * For scalability, we must not run a timer for every TCP connection
586  * in TIME_WAIT state.  To see why, consider (for time wait interval of
587  * 4 minutes):
588  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
589  *
590  * This list is ordered by time, so you need only delete from the head
591  * until you get to entries which aren't old enough to delete yet.
592  * The list consists of only the detached TIME_WAIT connections.
593  *
594  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
595  * becomes detached TIME_WAIT (either by changing the state and already
596  * being detached or the other way around). This means that the TIME_WAIT
597  * state can be extended (up to doubled) if the connection doesn't become
598  * detached for a long time.
599  *
600  * The list manipulations (including tcp_time_wait_next/prev)
601  * are protected by the tcp_time_wait_lock. The content of the
602  * detached TIME_WAIT connections is protected by the normal perimeters.
603  */
604 
605 typedef struct tcp_squeue_priv_s {
606 	kmutex_t	tcp_time_wait_lock;
607 				/* Protects the next 3 globals */
608 	timeout_id_t	tcp_time_wait_tid;
609 	tcp_t		*tcp_time_wait_head;
610 	tcp_t		*tcp_time_wait_tail;
611 	tcp_t		*tcp_free_list;
612 	uint_t		tcp_free_list_cnt;
613 } tcp_squeue_priv_t;
614 
615 /*
616  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
617  * Running it every 5 seconds seems to give the best results.
618  */
619 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
620 
621 /*
622  * To prevent memory hog, limit the number of entries in tcp_free_list
623  * to 1% of available memory / number of cpus
624  */
625 uint_t tcp_free_list_max_cnt = 0;
626 
627 #define	TCP_XMIT_LOWATER	4096
628 #define	TCP_XMIT_HIWATER	49152
629 #define	TCP_RECV_LOWATER	2048
630 #define	TCP_RECV_HIWATER	49152
631 
632 /*
633  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
634  */
635 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
636 
637 #define	TIDUSZ	4096	/* transport interface data unit size */
638 
639 /*
640  * Bind hash list size and has function.  It has to be a power of 2 for
641  * hashing.
642  */
643 #define	TCP_BIND_FANOUT_SIZE	512
644 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
645 /*
646  * Size of listen and acceptor hash list.  It has to be a power of 2 for
647  * hashing.
648  */
649 #define	TCP_FANOUT_SIZE		256
650 
651 #ifdef	_ILP32
652 #define	TCP_ACCEPTOR_HASH(accid)					\
653 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
654 #else
655 #define	TCP_ACCEPTOR_HASH(accid)					\
656 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
657 #endif	/* _ILP32 */
658 
659 #define	IP_ADDR_CACHE_SIZE	2048
660 #define	IP_ADDR_CACHE_HASH(faddr)					\
661 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
662 
663 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
664 #define	TCP_HSP_HASH_SIZE 256
665 
666 #define	TCP_HSP_HASH(addr)					\
667 	(((addr>>24) ^ (addr >>16) ^			\
668 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
669 
670 /*
671  * TCP options struct returned from tcp_parse_options.
672  */
673 typedef struct tcp_opt_s {
674 	uint32_t	tcp_opt_mss;
675 	uint32_t	tcp_opt_wscale;
676 	uint32_t	tcp_opt_ts_val;
677 	uint32_t	tcp_opt_ts_ecr;
678 	tcp_t		*tcp;
679 } tcp_opt_t;
680 
681 /*
682  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
683  */
684 
685 #ifdef _BIG_ENDIAN
686 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
687 	(TCPOPT_TSTAMP << 8) | 10)
688 #else
689 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
690 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
691 #endif
692 
693 /*
694  * Flags returned from tcp_parse_options.
695  */
696 #define	TCP_OPT_MSS_PRESENT	1
697 #define	TCP_OPT_WSCALE_PRESENT	2
698 #define	TCP_OPT_TSTAMP_PRESENT	4
699 #define	TCP_OPT_SACK_OK_PRESENT	8
700 #define	TCP_OPT_SACK_PRESENT	16
701 
702 /* TCP option length */
703 #define	TCPOPT_NOP_LEN		1
704 #define	TCPOPT_MAXSEG_LEN	4
705 #define	TCPOPT_WS_LEN		3
706 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
707 #define	TCPOPT_TSTAMP_LEN	10
708 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
709 #define	TCPOPT_SACK_OK_LEN	2
710 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
711 #define	TCPOPT_REAL_SACK_LEN	4
712 #define	TCPOPT_MAX_SACK_LEN	36
713 #define	TCPOPT_HEADER_LEN	2
714 
715 /* TCP cwnd burst factor. */
716 #define	TCP_CWND_INFINITE	65535
717 #define	TCP_CWND_SS		3
718 #define	TCP_CWND_NORMAL		5
719 
720 /* Maximum TCP initial cwin (start/restart). */
721 #define	TCP_MAX_INIT_CWND	8
722 
723 /*
724  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
725  * either tcp_slow_start_initial or tcp_slow_start_after idle
726  * depending on the caller.  If the upper layer has not used the
727  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
728  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
729  * If the upper layer has changed set the tcp_init_cwnd, just use
730  * it to calculate the tcp_cwnd.
731  */
732 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
733 {									\
734 	if ((tcp)->tcp_init_cwnd == 0) {				\
735 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
736 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
737 	} else {							\
738 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
739 	}								\
740 	tcp->tcp_cwnd_cnt = 0;						\
741 }
742 
743 /* TCP Timer control structure */
744 typedef struct tcpt_s {
745 	pfv_t	tcpt_pfv;	/* The routine we are to call */
746 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
747 } tcpt_t;
748 
749 /* Host Specific Parameter structure */
750 typedef struct tcp_hsp {
751 	struct tcp_hsp	*tcp_hsp_next;
752 	in6_addr_t	tcp_hsp_addr_v6;
753 	in6_addr_t	tcp_hsp_subnet_v6;
754 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
755 	int32_t		tcp_hsp_sendspace;
756 	int32_t		tcp_hsp_recvspace;
757 	int32_t		tcp_hsp_tstamp;
758 } tcp_hsp_t;
759 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
760 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
761 
762 /*
763  * Functions called directly via squeue having a prototype of edesc_t.
764  */
765 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
766 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
767 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
768 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
769 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
770 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
771 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
772 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
773 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
774 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
775 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
776 
777 
778 /* Prototype for TCP functions */
779 static void	tcp_random_init(void);
780 int		tcp_random(void);
781 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
782 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
783 		    tcp_t *eager);
784 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
785 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
786     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
787     boolean_t user_specified);
788 static void	tcp_closei_local(tcp_t *tcp);
789 static void	tcp_close_detached(tcp_t *tcp);
790 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
791 			mblk_t *idmp, mblk_t **defermp);
792 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
793 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
794 		    in_port_t dstport, uint_t srcid);
795 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
796 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
797 		    uint32_t scope_id);
798 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
799 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
800 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
801 static char	*tcp_display(tcp_t *tcp, char *, char);
802 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
803 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
804 static void	tcp_eager_unlink(tcp_t *tcp);
805 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
806 		    int unixerr);
807 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
808 		    int tlierr, int unixerr);
809 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
810 		    cred_t *cr);
811 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
812 		    char *value, caddr_t cp, cred_t *cr);
813 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
814 		    char *value, caddr_t cp, cred_t *cr);
815 static int	tcp_tpistate(tcp_t *tcp);
816 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
817     int caller_holds_lock);
818 static void	tcp_bind_hash_remove(tcp_t *tcp);
819 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id);
820 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
821 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
822 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
823 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
824 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
825 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
826 static int	tcp_header_init_ipv4(tcp_t *tcp);
827 static int	tcp_header_init_ipv6(tcp_t *tcp);
828 int		tcp_init(tcp_t *tcp, queue_t *q);
829 static int	tcp_init_values(tcp_t *tcp);
830 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
831 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
832 		    t_scalar_t addr_length);
833 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
834 static void	tcp_ip_notify(tcp_t *tcp);
835 static mblk_t	*tcp_ire_mp(mblk_t *mp);
836 static void	tcp_iss_init(tcp_t *tcp);
837 static void	tcp_keepalive_killer(void *arg);
838 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
839 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
840 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
841 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
842 static boolean_t tcp_allow_connopt_set(int level, int name);
843 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
844 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
845 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
846 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
847 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
848 		    mblk_t *mblk);
849 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
850 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
851 		    uchar_t *ptr, uint_t len);
852 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
853 static boolean_t tcp_param_register(tcpparam_t *tcppa, int cnt);
854 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
855 		    caddr_t cp, cred_t *cr);
856 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
857 		    caddr_t cp, cred_t *cr);
858 static void	tcp_iss_key_init(uint8_t *phrase, int len);
859 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
860 		    caddr_t cp, cred_t *cr);
861 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
862 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
863 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
864 static void	tcp_reinit(tcp_t *tcp);
865 static void	tcp_reinit_values(tcp_t *tcp);
866 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
867 		    tcp_t *thisstream, cred_t *cr);
868 
869 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
870 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
871 static boolean_t tcp_send_rst_chk(void);
872 static void	tcp_ss_rexmit(tcp_t *tcp);
873 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
874 static void	tcp_process_options(tcp_t *, tcph_t *);
875 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
876 static void	tcp_rsrv(queue_t *q);
877 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
878 static int	tcp_snmp_state(tcp_t *tcp);
879 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
880 		    cred_t *cr);
881 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
882 		    cred_t *cr);
883 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
884 		    cred_t *cr);
885 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
886 		    cred_t *cr);
887 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
888 		    cred_t *cr);
889 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
890 		    caddr_t cp, cred_t *cr);
891 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
892 		    caddr_t cp, cred_t *cr);
893 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
894 		    cred_t *cr);
895 static void	tcp_timer(void *arg);
896 static void	tcp_timer_callback(void *);
897 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
898     boolean_t random);
899 static in_port_t tcp_get_next_priv_port(const tcp_t *);
900 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
901 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
902 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
903 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
904 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
905 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
906 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
907 		    const int num_sack_blk, int *usable, uint_t *snxt,
908 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
909 		    const int mdt_thres);
910 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
911 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
912 		    const int num_sack_blk, int *usable, uint_t *snxt,
913 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
914 		    const int mdt_thres);
915 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
916 		    int num_sack_blk);
917 static void	tcp_wsrv(queue_t *q);
918 static int	tcp_xmit_end(tcp_t *tcp);
919 static mblk_t	*tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send,
920 		    int32_t *offset, mblk_t **end_mp, uint32_t seq,
921 		    boolean_t sendall, uint32_t *seg_len, boolean_t rexmit);
922 static void	tcp_ack_timer(void *arg);
923 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
924 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
925 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len);
926 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
927 		    uint32_t ack, int ctl);
928 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr);
929 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr);
930 static int	setmaxps(queue_t *q, int maxpsz);
931 static void	tcp_set_rto(tcp_t *, time_t);
932 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
933 		    boolean_t, boolean_t);
934 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
935 		    boolean_t ipsec_mctl);
936 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
937 		    char *opt, int optlen);
938 static int	tcp_build_hdrs(queue_t *, tcp_t *);
939 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
940 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
941 		    tcph_t *tcph);
942 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
943 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
944 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
945 boolean_t	tcp_reserved_port_check(in_port_t);
946 static tcp_t	*tcp_alloc_temp_tcp(in_port_t);
947 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
948 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
949 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
950 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
951 		    const boolean_t, const uint32_t, const uint32_t,
952 		    const uint32_t, const uint32_t);
953 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
954 		    const uint_t, const uint_t, boolean_t *);
955 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
956 extern mblk_t	*tcp_timermp_alloc(int);
957 extern void	tcp_timermp_free(tcp_t *);
958 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
959 static void	tcp_stop_lingering(tcp_t *tcp);
960 static void	tcp_close_linger_timeout(void *arg);
961 void		tcp_ddi_init(void);
962 void		tcp_ddi_destroy(void);
963 static void	tcp_kstat_init(void);
964 static void	tcp_kstat_fini(void);
965 static int	tcp_kstat_update(kstat_t *kp, int rw);
966 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
967 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
968 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
969 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
970 			tcph_t *tcph, mblk_t *idmp);
971 static squeue_func_t tcp_squeue_switch(int);
972 
973 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
974 static int	tcp_close(queue_t *, int);
975 static int	tcpclose_accept(queue_t *);
976 static int	tcp_modclose(queue_t *);
977 static void	tcp_wput_mod(queue_t *, mblk_t *);
978 
979 static void	tcp_squeue_add(squeue_t *);
980 static boolean_t tcp_zcopy_check(tcp_t *);
981 static void	tcp_zcopy_notify(tcp_t *);
982 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
983 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
984 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
985 
986 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
987 
988 /*
989  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
990  *
991  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
992  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
993  * (defined in tcp.h) needs to be filled in and passed into the kernel
994  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
995  * structure contains the four-tuple of a TCP connection and a range of TCP
996  * states (specified by ac_start and ac_end). The use of wildcard addresses
997  * and ports is allowed. Connections with a matching four tuple and a state
998  * within the specified range will be aborted. The valid states for the
999  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
1000  * inclusive.
1001  *
1002  * An application which has its connection aborted by this ioctl will receive
1003  * an error that is dependent on the connection state at the time of the abort.
1004  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1005  * though a RST packet has been received.  If the connection state is equal to
1006  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1007  * and all resources associated with the connection will be freed.
1008  */
1009 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1010 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1011 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1012 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *);
1013 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1014 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1015     boolean_t);
1016 
1017 static struct module_info tcp_rinfo =  {
1018 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1019 };
1020 
1021 static struct module_info tcp_winfo =  {
1022 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1023 };
1024 
1025 /*
1026  * Entry points for TCP as a module. It only allows SNMP requests
1027  * to pass through.
1028  */
1029 struct qinit tcp_mod_rinit = {
1030 	(pfi_t)putnext, NULL, tcp_open, ip_snmpmod_close, NULL, &tcp_rinfo,
1031 };
1032 
1033 struct qinit tcp_mod_winit = {
1034 	(pfi_t)ip_snmpmod_wput, NULL, tcp_open, ip_snmpmod_close, NULL,
1035 	&tcp_rinfo
1036 };
1037 
1038 /*
1039  * Entry points for TCP as a device. The normal case which supports
1040  * the TCP functionality.
1041  */
1042 struct qinit tcp_rinit = {
1043 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
1044 };
1045 
1046 struct qinit tcp_winit = {
1047 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1048 };
1049 
1050 /* Initial entry point for TCP in socket mode. */
1051 struct qinit tcp_sock_winit = {
1052 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1053 };
1054 
1055 /*
1056  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1057  * an accept. Avoid allocating data structures since eager has already
1058  * been created.
1059  */
1060 struct qinit tcp_acceptor_rinit = {
1061 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1062 };
1063 
1064 struct qinit tcp_acceptor_winit = {
1065 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1066 };
1067 
1068 /*
1069  * Entry points for TCP loopback (read side only)
1070  */
1071 struct qinit tcp_loopback_rinit = {
1072 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_open, tcp_close, (pfi_t)0,
1073 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1074 };
1075 
1076 struct streamtab tcpinfo = {
1077 	&tcp_rinit, &tcp_winit
1078 };
1079 
1080 extern squeue_func_t tcp_squeue_wput_proc;
1081 extern squeue_func_t tcp_squeue_timer_proc;
1082 
1083 /* Protected by tcp_g_q_lock */
1084 static queue_t	*tcp_g_q;	/* Default queue used during detached closes */
1085 kmutex_t tcp_g_q_lock;
1086 
1087 /* Protected by tcp_hsp_lock */
1088 /*
1089  * XXX The host param mechanism should go away and instead we should use
1090  * the metrics associated with the routes to determine the default sndspace
1091  * and rcvspace.
1092  */
1093 static tcp_hsp_t	**tcp_hsp_hash;	/* Hash table for HSPs */
1094 krwlock_t tcp_hsp_lock;
1095 
1096 /*
1097  * Extra privileged ports. In host byte order.
1098  * Protected by tcp_epriv_port_lock.
1099  */
1100 #define	TCP_NUM_EPRIV_PORTS	64
1101 static int	tcp_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
1102 static uint16_t	tcp_g_epriv_ports[TCP_NUM_EPRIV_PORTS] = { 2049, 4045 };
1103 kmutex_t tcp_epriv_port_lock;
1104 
1105 /*
1106  * The smallest anonymous port in the privileged port range which TCP
1107  * looks for free port.  Use in the option TCP_ANONPRIVBIND.
1108  */
1109 static in_port_t tcp_min_anonpriv_port = 512;
1110 
1111 /* Only modified during _init and _fini thus no locking is needed. */
1112 static caddr_t	tcp_g_nd;	/* Head of 'named dispatch' variable list */
1113 
1114 /* Hint not protected by any lock */
1115 static uint_t	tcp_next_port_to_try;
1116 
1117 
1118 /* TCP bind hash list - all tcp_t with state >= BOUND. */
1119 tf_t	tcp_bind_fanout[TCP_BIND_FANOUT_SIZE];
1120 
1121 /* TCP queue hash list - all tcp_t in case they will be an acceptor. */
1122 static tf_t	tcp_acceptor_fanout[TCP_FANOUT_SIZE];
1123 
1124 /*
1125  * TCP has a private interface for other kernel modules to reserve a
1126  * port range for them to use.  Once reserved, TCP will not use any ports
1127  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1128  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1129  * has to be verified.
1130  *
1131  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1132  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1133  * range is [port a, port b] inclusive.  And each port range is between
1134  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1135  *
1136  * Note that the default anonymous port range starts from 32768.  There is
1137  * no port "collision" between that and the reserved port range.  If there
1138  * is port collision (because the default smallest anonymous port is lowered
1139  * or some apps specifically bind to ports in the reserved port range), the
1140  * system may not be able to reserve a port range even there are enough
1141  * unbound ports as a reserved port range contains consecutive ports .
1142  */
1143 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1144 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1145 #define	TCP_SMALLEST_RESERVED_PORT		10240
1146 #define	TCP_LARGEST_RESERVED_PORT		20480
1147 
1148 /* Structure to represent those reserved port ranges. */
1149 typedef struct tcp_rport_s {
1150 	in_port_t	lo_port;
1151 	in_port_t	hi_port;
1152 	tcp_t		**temp_tcp_array;
1153 } tcp_rport_t;
1154 
1155 /* The reserved port array. */
1156 static tcp_rport_t tcp_reserved_port[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
1157 
1158 /* Locks to protect the tcp_reserved_ports array. */
1159 static krwlock_t tcp_reserved_port_lock;
1160 
1161 /* The number of ranges in the array. */
1162 uint32_t tcp_reserved_port_array_size = 0;
1163 
1164 /*
1165  * MIB-2 stuff for SNMP
1166  * Note: tcpInErrs {tcp 15} is accumulated in ip.c
1167  */
1168 mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */
1169 kstat_t		*tcp_mibkp;	/* kstat exporting tcp_mib data */
1170 
1171 boolean_t tcp_icmp_source_quench = B_FALSE;
1172 /*
1173  * Following assumes TPI alignment requirements stay along 32 bit
1174  * boundaries
1175  */
1176 #define	ROUNDUP32(x) \
1177 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1178 
1179 /* Template for response to info request. */
1180 static struct T_info_ack tcp_g_t_info_ack = {
1181 	T_INFO_ACK,		/* PRIM_type */
1182 	0,			/* TSDU_size */
1183 	T_INFINITE,		/* ETSDU_size */
1184 	T_INVALID,		/* CDATA_size */
1185 	T_INVALID,		/* DDATA_size */
1186 	sizeof (sin_t),		/* ADDR_size */
1187 	0,			/* OPT_size - not initialized here */
1188 	TIDUSZ,			/* TIDU_size */
1189 	T_COTS_ORD,		/* SERV_type */
1190 	TCPS_IDLE,		/* CURRENT_state */
1191 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1192 };
1193 
1194 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1195 	T_INFO_ACK,		/* PRIM_type */
1196 	0,			/* TSDU_size */
1197 	T_INFINITE,		/* ETSDU_size */
1198 	T_INVALID,		/* CDATA_size */
1199 	T_INVALID,		/* DDATA_size */
1200 	sizeof (sin6_t),	/* ADDR_size */
1201 	0,			/* OPT_size - not initialized here */
1202 	TIDUSZ,		/* TIDU_size */
1203 	T_COTS_ORD,		/* SERV_type */
1204 	TCPS_IDLE,		/* CURRENT_state */
1205 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1206 };
1207 
1208 #define	MS	1L
1209 #define	SECONDS	(1000 * MS)
1210 #define	MINUTES	(60 * SECONDS)
1211 #define	HOURS	(60 * MINUTES)
1212 #define	DAYS	(24 * HOURS)
1213 
1214 #define	PARAM_MAX (~(uint32_t)0)
1215 
1216 /* Max size IP datagram is 64k - 1 */
1217 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1218 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1219 /* Max of the above */
1220 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1221 
1222 /* Largest TCP port number */
1223 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1224 
1225 /*
1226  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1227  * layer header.  It has to be a multiple of 4.
1228  */
1229 static tcpparam_t tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1230 #define	tcp_wroff_xtra	tcp_wroff_xtra_param.tcp_param_val
1231 
1232 /*
1233  * All of these are alterable, within the min/max values given, at run time.
1234  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1235  * per the TCP spec.
1236  */
1237 /* BEGIN CSTYLED */
1238 tcpparam_t	tcp_param_arr[] = {
1239  /*min		max		value		name */
1240  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1241  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1242  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1243  { 1,		1024,		1,		"tcp_conn_req_min" },
1244  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1245  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1246  { 0,		10,		0,		"tcp_debug" },
1247  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1248  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1249  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1250  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1251  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1252  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1253  { 1,		255,		64,		"tcp_ipv4_ttl"},
1254  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1255  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1256  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1257  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1258  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1259  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1260  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1261  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1262  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1263  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1264  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1265  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1266  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1267  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1268  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1269  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1270  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1271  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1272  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1273  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1274  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1275  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1276  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1277  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1278 /*
1279  * Question:  What default value should I set for tcp_strong_iss?
1280  */
1281  { 0,		2,		1,		"tcp_strong_iss"},
1282  { 0,		65536,		20,		"tcp_rtt_updates"},
1283  { 0,		1,		1,		"tcp_wscale_always"},
1284  { 0,		1,		0,		"tcp_tstamp_always"},
1285  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1286  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1287  { 0,		16,		2,		"tcp_deferred_acks_max"},
1288  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1289  { 1,		4,		4,		"tcp_slow_start_initial"},
1290  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1291  { 0,		2,		2,		"tcp_sack_permitted"},
1292  { 0,		1,		0,		"tcp_trace"},
1293  { 0,		1,		1,		"tcp_compression_enabled"},
1294  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1295  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1296  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1297  { 0,		1,		0,		"tcp_rev_src_routes"},
1298  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1299  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1300  { 0,		16,		8,		"tcp_local_dacks_max"},
1301  { 0,		2,		1,		"tcp_ecn_permitted"},
1302  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1303  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1304  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1305  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1306  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1307 };
1308 /* END CSTYLED */
1309 
1310 /*
1311  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1312  * each header fragment in the header buffer.  Each parameter value has
1313  * to be a multiple of 4 (32-bit aligned).
1314  */
1315 static tcpparam_t tcp_mdt_head_param = { 32, 256, 32, "tcp_mdt_hdr_head_min" };
1316 static tcpparam_t tcp_mdt_tail_param = { 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1317 #define	tcp_mdt_hdr_head_min	tcp_mdt_head_param.tcp_param_val
1318 #define	tcp_mdt_hdr_tail_min	tcp_mdt_tail_param.tcp_param_val
1319 
1320 /*
1321  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1322  * the maximum number of payload buffers associated per Multidata.
1323  */
1324 static tcpparam_t tcp_mdt_max_pbufs_param =
1325 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1326 #define	tcp_mdt_max_pbufs	tcp_mdt_max_pbufs_param.tcp_param_val
1327 
1328 /* Round up the value to the nearest mss. */
1329 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1330 
1331 /*
1332  * Set ECN capable transport (ECT) code point in IP header.
1333  *
1334  * Note that there are 2 ECT code points '01' and '10', which are called
1335  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1336  * point ECT(0) for TCP as described in RFC 2481.
1337  */
1338 #define	SET_ECT(tcp, iph) \
1339 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1340 		/* We need to clear the code point first. */ \
1341 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1342 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1343 	} else { \
1344 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1345 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1346 	}
1347 
1348 /*
1349  * The format argument to pass to tcp_display().
1350  * DISP_PORT_ONLY means that the returned string has only port info.
1351  * DISP_ADDR_AND_PORT means that the returned string also contains the
1352  * remote and local IP address.
1353  */
1354 #define	DISP_PORT_ONLY		1
1355 #define	DISP_ADDR_AND_PORT	2
1356 
1357 /*
1358  * This controls the rate some ndd info report functions can be used
1359  * by non-privileged users.  It stores the last time such info is
1360  * requested.  When those report functions are called again, this
1361  * is checked with the current time and compare with the ndd param
1362  * tcp_ndd_get_info_interval.
1363  */
1364 static clock_t tcp_last_ndd_get_info_time = 0;
1365 #define	NDD_TOO_QUICK_MSG \
1366 	"ndd get info rate too high for non-privileged users, try again " \
1367 	"later.\n"
1368 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1369 
1370 #define	IS_VMLOANED_MBLK(mp) \
1371 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1372 
1373 /*
1374  * These two variables control the rate for TCP to generate RSTs in
1375  * response to segments not belonging to any connections.  We limit
1376  * TCP to sent out tcp_rst_sent_rate (ndd param) number of RSTs in
1377  * each 1 second interval.  This is to protect TCP against DoS attack.
1378  */
1379 static clock_t tcp_last_rst_intrvl;
1380 static uint32_t tcp_rst_cnt;
1381 
1382 /* The number of RST not sent because of the rate limit. */
1383 static uint32_t tcp_rst_unsent;
1384 
1385 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1386 boolean_t tcp_mdt_chain = B_TRUE;
1387 
1388 /*
1389  * MDT threshold in the form of effective send MSS multiplier; we take
1390  * the MDT path if the amount of unsent data exceeds the threshold value
1391  * (default threshold is 1*SMSS).
1392  */
1393 uint_t tcp_mdt_smss_threshold = 1;
1394 
1395 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1396 
1397 /*
1398  * Forces all connections to obey the value of the tcp_maxpsz_multiplier
1399  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1400  * determined dynamically during tcp_adapt_ire(), which is the default.
1401  */
1402 boolean_t tcp_static_maxpsz = B_FALSE;
1403 
1404 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1405 uint32_t tcp_random_anon_port = 1;
1406 
1407 /*
1408  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1409  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1410  * data, TCP will not respond with an ACK.  RFC 793 requires that
1411  * TCP responds with an ACK for such a bogus ACK.  By not following
1412  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1413  * an attacker successfully spoofs an acceptable segment to our
1414  * peer; or when our peer is "confused."
1415  */
1416 uint32_t tcp_drop_ack_unsent_cnt = 10;
1417 
1418 /*
1419  * Hook functions to enable cluster networking
1420  * On non-clustered systems these vectors must always be NULL.
1421  */
1422 
1423 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1424 			    uint8_t *laddrp, in_port_t lport) = NULL;
1425 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1426 			    uint8_t *laddrp, in_port_t lport) = NULL;
1427 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1428 			    uint8_t *laddrp, in_port_t lport,
1429 			    uint8_t *faddrp, in_port_t fport) = NULL;
1430 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1431 			    uint8_t *laddrp, in_port_t lport,
1432 			    uint8_t *faddrp, in_port_t fport) = NULL;
1433 
1434 /*
1435  * The following are defined in ip.c
1436  */
1437 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1438 				uint8_t *laddrp);
1439 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1440 				uint8_t *laddrp, uint8_t *faddrp);
1441 
1442 #define	CL_INET_CONNECT(tcp)		{			\
1443 	if (cl_inet_connect != NULL) {				\
1444 		/*						\
1445 		 * Running in cluster mode - register active connection	\
1446 		 * information						\
1447 		 */							\
1448 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1449 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1450 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1451 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1452 				    (in_port_t)(tcp)->tcp_lport,	\
1453 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1454 				    (in_port_t)(tcp)->tcp_fport);	\
1455 			}						\
1456 		} else {						\
1457 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1458 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1459 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1460 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1461 				    (in_port_t)(tcp)->tcp_lport,	\
1462 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1463 				    (in_port_t)(tcp)->tcp_fport);	\
1464 			}						\
1465 		}							\
1466 	}								\
1467 }
1468 
1469 #define	CL_INET_DISCONNECT(tcp)	{				\
1470 	if (cl_inet_disconnect != NULL) {				\
1471 		/*							\
1472 		 * Running in cluster mode - deregister active		\
1473 		 * connection information				\
1474 		 */							\
1475 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1476 			if ((tcp)->tcp_ip_src != 0) {			\
1477 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1478 				    AF_INET,				\
1479 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1480 				    (in_port_t)(tcp)->tcp_lport,	\
1481 				    (uint8_t *)				\
1482 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1483 				    (in_port_t)(tcp)->tcp_fport);	\
1484 			}						\
1485 		} else {						\
1486 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1487 			    &(tcp)->tcp_ip_src_v6)) {			\
1488 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1489 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1490 				    (in_port_t)(tcp)->tcp_lport,	\
1491 				    (uint8_t *)				\
1492 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1493 				    (in_port_t)(tcp)->tcp_fport);	\
1494 			}						\
1495 		}							\
1496 	}								\
1497 }
1498 
1499 /*
1500  * Cluster networking hook for traversing current connection list.
1501  * This routine is used to extract the current list of live connections
1502  * which must continue to to be dispatched to this node.
1503  */
1504 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1505 
1506 /*
1507  * Figure out the value of window scale opton.  Note that the rwnd is
1508  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1509  * We cannot find the scale value and then do a round up of tcp_rwnd
1510  * because the scale value may not be correct after that.
1511  *
1512  * Set the compiler flag to make this function inline.
1513  */
1514 static void
1515 tcp_set_ws_value(tcp_t *tcp)
1516 {
1517 	int i;
1518 	uint32_t rwnd = tcp->tcp_rwnd;
1519 
1520 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1521 	    i++, rwnd >>= 1)
1522 		;
1523 	tcp->tcp_rcv_ws = i;
1524 }
1525 
1526 /*
1527  * Remove a connection from the list of detached TIME_WAIT connections.
1528  */
1529 static void
1530 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1531 {
1532 	boolean_t	locked = B_FALSE;
1533 
1534 	if (tcp_time_wait == NULL) {
1535 		tcp_time_wait = *((tcp_squeue_priv_t **)
1536 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1537 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1538 		locked = B_TRUE;
1539 	}
1540 
1541 	if (tcp->tcp_time_wait_expire == 0) {
1542 		ASSERT(tcp->tcp_time_wait_next == NULL);
1543 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1544 		if (locked)
1545 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1546 		return;
1547 	}
1548 	ASSERT(TCP_IS_DETACHED(tcp));
1549 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1550 
1551 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1552 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1553 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1554 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1555 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1556 			    NULL;
1557 		} else {
1558 			tcp_time_wait->tcp_time_wait_tail = NULL;
1559 		}
1560 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1561 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1562 		ASSERT(tcp->tcp_time_wait_next == NULL);
1563 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1564 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1565 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1566 	} else {
1567 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1568 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1569 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1570 		    tcp->tcp_time_wait_next;
1571 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1572 		    tcp->tcp_time_wait_prev;
1573 	}
1574 	tcp->tcp_time_wait_next = NULL;
1575 	tcp->tcp_time_wait_prev = NULL;
1576 	tcp->tcp_time_wait_expire = 0;
1577 
1578 	if (locked)
1579 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1580 }
1581 
1582 /*
1583  * Add a connection to the list of detached TIME_WAIT connections
1584  * and set its time to expire.
1585  */
1586 static void
1587 tcp_time_wait_append(tcp_t *tcp)
1588 {
1589 	tcp_squeue_priv_t *tcp_time_wait =
1590 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1591 		SQPRIVATE_TCP));
1592 
1593 	tcp_timers_stop(tcp);
1594 
1595 	/* Freed above */
1596 	ASSERT(tcp->tcp_timer_tid == 0);
1597 	ASSERT(tcp->tcp_ack_tid == 0);
1598 
1599 	/* must have happened at the time of detaching the tcp */
1600 	ASSERT(tcp->tcp_ptpahn == NULL);
1601 	ASSERT(tcp->tcp_flow_stopped == 0);
1602 	ASSERT(tcp->tcp_time_wait_next == NULL);
1603 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1604 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1605 	ASSERT(tcp->tcp_listener == NULL);
1606 
1607 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1608 	/*
1609 	 * The value computed below in tcp->tcp_time_wait_expire may
1610 	 * appear negative or wrap around. That is ok since our
1611 	 * interest is only in the difference between the current lbolt
1612 	 * value and tcp->tcp_time_wait_expire. But the value should not
1613 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1614 	 * The corresponding comparison in tcp_time_wait_collector() uses
1615 	 * modular arithmetic.
1616 	 */
1617 	tcp->tcp_time_wait_expire +=
1618 	    drv_usectohz(tcp_time_wait_interval * 1000);
1619 	if (tcp->tcp_time_wait_expire == 0)
1620 		tcp->tcp_time_wait_expire = 1;
1621 
1622 	ASSERT(TCP_IS_DETACHED(tcp));
1623 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1624 	ASSERT(tcp->tcp_time_wait_next == NULL);
1625 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1626 	TCP_DBGSTAT(tcp_time_wait);
1627 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1628 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1629 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1630 		tcp_time_wait->tcp_time_wait_head = tcp;
1631 	} else {
1632 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1633 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1634 		    TCPS_TIME_WAIT);
1635 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1636 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1637 	}
1638 	tcp_time_wait->tcp_time_wait_tail = tcp;
1639 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1640 }
1641 
1642 /* ARGSUSED */
1643 void
1644 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1645 {
1646 	conn_t	*connp = (conn_t *)arg;
1647 	tcp_t	*tcp = connp->conn_tcp;
1648 
1649 	ASSERT(tcp != NULL);
1650 	if (tcp->tcp_state == TCPS_CLOSED) {
1651 		return;
1652 	}
1653 
1654 	ASSERT((tcp->tcp_family == AF_INET &&
1655 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1656 	    (tcp->tcp_family == AF_INET6 &&
1657 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1658 	    tcp->tcp_ipversion == IPV6_VERSION)));
1659 	ASSERT(!tcp->tcp_listener);
1660 
1661 	TCP_STAT(tcp_time_wait_reap);
1662 	ASSERT(TCP_IS_DETACHED(tcp));
1663 
1664 	/*
1665 	 * Because they have no upstream client to rebind or tcp_close()
1666 	 * them later, we axe the connection here and now.
1667 	 */
1668 	tcp_close_detached(tcp);
1669 }
1670 
1671 void
1672 tcp_cleanup(tcp_t *tcp)
1673 {
1674 	mblk_t		*mp;
1675 	char		*tcp_iphc;
1676 	int		tcp_iphc_len;
1677 	int		tcp_hdr_grown;
1678 	tcp_sack_info_t	*tcp_sack_info;
1679 	conn_t		*connp = tcp->tcp_connp;
1680 
1681 	tcp_bind_hash_remove(tcp);
1682 	tcp_free(tcp);
1683 
1684 	/* Release any SSL context */
1685 	if (tcp->tcp_kssl_ent != NULL) {
1686 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1687 		tcp->tcp_kssl_ent = NULL;
1688 	}
1689 
1690 	if (tcp->tcp_kssl_ctx != NULL) {
1691 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1692 		tcp->tcp_kssl_ctx = NULL;
1693 	}
1694 	tcp->tcp_kssl_pending = B_FALSE;
1695 
1696 	conn_delete_ire(connp, NULL);
1697 	if (connp->conn_flags & IPCL_TCPCONN) {
1698 		if (connp->conn_latch != NULL)
1699 			IPLATCH_REFRELE(connp->conn_latch);
1700 		if (connp->conn_policy != NULL)
1701 			IPPH_REFRELE(connp->conn_policy);
1702 	}
1703 
1704 	/*
1705 	 * Since we will bzero the entire structure, we need to
1706 	 * remove it and reinsert it in global hash list. We
1707 	 * know the walkers can't get to this conn because we
1708 	 * had set CONDEMNED flag earlier and checked reference
1709 	 * under conn_lock so walker won't pick it and when we
1710 	 * go the ipcl_globalhash_remove() below, no walker
1711 	 * can get to it.
1712 	 */
1713 	ipcl_globalhash_remove(connp);
1714 
1715 	/* Save some state */
1716 	mp = tcp->tcp_timercache;
1717 
1718 	tcp_sack_info = tcp->tcp_sack_info;
1719 	tcp_iphc = tcp->tcp_iphc;
1720 	tcp_iphc_len = tcp->tcp_iphc_len;
1721 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1722 
1723 	if (connp->conn_cred != NULL)
1724 		crfree(connp->conn_cred);
1725 	if (connp->conn_peercred != NULL)
1726 		crfree(connp->conn_peercred);
1727 	bzero(connp, sizeof (conn_t));
1728 	bzero(tcp, sizeof (tcp_t));
1729 
1730 	/* restore the state */
1731 	tcp->tcp_timercache = mp;
1732 
1733 	tcp->tcp_sack_info = tcp_sack_info;
1734 	tcp->tcp_iphc = tcp_iphc;
1735 	tcp->tcp_iphc_len = tcp_iphc_len;
1736 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1737 
1738 
1739 	tcp->tcp_connp = connp;
1740 
1741 	connp->conn_tcp = tcp;
1742 	connp->conn_flags = IPCL_TCPCONN;
1743 	connp->conn_state_flags = CONN_INCIPIENT;
1744 	connp->conn_ulp = IPPROTO_TCP;
1745 	connp->conn_ref = 1;
1746 
1747 	ipcl_globalhash_insert(connp);
1748 }
1749 
1750 /*
1751  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1752  * is done forwards from the head.
1753  */
1754 /* ARGSUSED */
1755 void
1756 tcp_time_wait_collector(void *arg)
1757 {
1758 	tcp_t *tcp;
1759 	clock_t now;
1760 	mblk_t *mp;
1761 	conn_t *connp;
1762 	kmutex_t *lock;
1763 
1764 	squeue_t *sqp = (squeue_t *)arg;
1765 	tcp_squeue_priv_t *tcp_time_wait =
1766 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1767 
1768 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1769 	tcp_time_wait->tcp_time_wait_tid = 0;
1770 
1771 	if (tcp_time_wait->tcp_free_list != NULL &&
1772 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1773 		TCP_STAT(tcp_freelist_cleanup);
1774 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1775 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1776 			CONN_DEC_REF(tcp->tcp_connp);
1777 		}
1778 		tcp_time_wait->tcp_free_list_cnt = 0;
1779 	}
1780 
1781 	/*
1782 	 * In order to reap time waits reliably, we should use a
1783 	 * source of time that is not adjustable by the user -- hence
1784 	 * the call to ddi_get_lbolt().
1785 	 */
1786 	now = ddi_get_lbolt();
1787 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1788 		/*
1789 		 * Compare times using modular arithmetic, since
1790 		 * lbolt can wrapover.
1791 		 */
1792 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1793 			break;
1794 		}
1795 
1796 		tcp_time_wait_remove(tcp, tcp_time_wait);
1797 
1798 		connp = tcp->tcp_connp;
1799 		ASSERT(connp->conn_fanout != NULL);
1800 		lock = &connp->conn_fanout->connf_lock;
1801 		/*
1802 		 * This is essentially a TW reclaim fast path optimization for
1803 		 * performance where the timewait collector checks under the
1804 		 * fanout lock (so that no one else can get access to the
1805 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1806 		 * the classifier hash list. If ref count is indeed 2, we can
1807 		 * just remove the conn under the fanout lock and avoid
1808 		 * cleaning up the conn under the squeue, provided that
1809 		 * clustering callbacks are not enabled. If clustering is
1810 		 * enabled, we need to make the clustering callback before
1811 		 * setting the CONDEMNED flag and after dropping all locks and
1812 		 * so we forego this optimization and fall back to the slow
1813 		 * path. Also please see the comments in tcp_closei_local
1814 		 * regarding the refcnt logic.
1815 		 *
1816 		 * Since we are holding the tcp_time_wait_lock, its better
1817 		 * not to block on the fanout_lock because other connections
1818 		 * can't add themselves to time_wait list. So we do a
1819 		 * tryenter instead of mutex_enter.
1820 		 */
1821 		if (mutex_tryenter(lock)) {
1822 			mutex_enter(&connp->conn_lock);
1823 			if ((connp->conn_ref == 2) &&
1824 			    (cl_inet_disconnect == NULL)) {
1825 				ipcl_hash_remove_locked(connp,
1826 				    connp->conn_fanout);
1827 				/*
1828 				 * Set the CONDEMNED flag now itself so that
1829 				 * the refcnt cannot increase due to any
1830 				 * walker. But we have still not cleaned up
1831 				 * conn_ire_cache. This is still ok since
1832 				 * we are going to clean it up in tcp_cleanup
1833 				 * immediately and any interface unplumb
1834 				 * thread will wait till the ire is blown away
1835 				 */
1836 				connp->conn_state_flags |= CONN_CONDEMNED;
1837 				mutex_exit(lock);
1838 				mutex_exit(&connp->conn_lock);
1839 				if (tcp_time_wait->tcp_free_list_cnt <
1840 				    tcp_free_list_max_cnt) {
1841 					/* Add to head of tcp_free_list */
1842 					mutex_exit(
1843 					    &tcp_time_wait->tcp_time_wait_lock);
1844 					tcp_cleanup(tcp);
1845 					mutex_enter(
1846 					    &tcp_time_wait->tcp_time_wait_lock);
1847 					tcp->tcp_time_wait_next =
1848 					    tcp_time_wait->tcp_free_list;
1849 					tcp_time_wait->tcp_free_list = tcp;
1850 					tcp_time_wait->tcp_free_list_cnt++;
1851 					continue;
1852 				} else {
1853 					/* Do not add to tcp_free_list */
1854 					mutex_exit(
1855 					    &tcp_time_wait->tcp_time_wait_lock);
1856 					tcp_bind_hash_remove(tcp);
1857 					conn_delete_ire(tcp->tcp_connp, NULL);
1858 					CONN_DEC_REF(tcp->tcp_connp);
1859 				}
1860 			} else {
1861 				CONN_INC_REF_LOCKED(connp);
1862 				mutex_exit(lock);
1863 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1864 				mutex_exit(&connp->conn_lock);
1865 				/*
1866 				 * We can reuse the closemp here since conn has
1867 				 * detached (otherwise we wouldn't even be in
1868 				 * time_wait list).
1869 				 */
1870 				mp = &tcp->tcp_closemp;
1871 				squeue_fill(connp->conn_sqp, mp,
1872 				    tcp_timewait_output, connp,
1873 				    SQTAG_TCP_TIMEWAIT);
1874 			}
1875 		} else {
1876 			mutex_enter(&connp->conn_lock);
1877 			CONN_INC_REF_LOCKED(connp);
1878 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1879 			mutex_exit(&connp->conn_lock);
1880 			/*
1881 			 * We can reuse the closemp here since conn has
1882 			 * detached (otherwise we wouldn't even be in
1883 			 * time_wait list).
1884 			 */
1885 			mp = &tcp->tcp_closemp;
1886 			squeue_fill(connp->conn_sqp, mp,
1887 			    tcp_timewait_output, connp, 0);
1888 		}
1889 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1890 	}
1891 
1892 	if (tcp_time_wait->tcp_free_list != NULL)
1893 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1894 
1895 	tcp_time_wait->tcp_time_wait_tid =
1896 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1897 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1898 }
1899 
1900 /*
1901  * Reply to a clients T_CONN_RES TPI message. This function
1902  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1903  * on the acceptor STREAM and processed in tcp_wput_accept().
1904  * Read the block comment on top of tcp_conn_request().
1905  */
1906 static void
1907 tcp_accept(tcp_t *listener, mblk_t *mp)
1908 {
1909 	tcp_t	*acceptor;
1910 	tcp_t	*eager;
1911 	tcp_t   *tcp;
1912 	struct T_conn_res	*tcr;
1913 	t_uscalar_t	acceptor_id;
1914 	t_scalar_t	seqnum;
1915 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1916 	mblk_t	*ok_mp;
1917 	mblk_t	*mp1;
1918 
1919 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1920 		tcp_err_ack(listener, mp, TPROTO, 0);
1921 		return;
1922 	}
1923 	tcr = (struct T_conn_res *)mp->b_rptr;
1924 
1925 	/*
1926 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1927 	 * read side queue of the streams device underneath us i.e. the
1928 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1929 	 * look it up in the queue_hash.  Under LP64 it sends down the
1930 	 * minor_t of the accepting endpoint.
1931 	 *
1932 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1933 	 * fanout hash lock is held.
1934 	 * This prevents any thread from entering the acceptor queue from
1935 	 * below (since it has not been hard bound yet i.e. any inbound
1936 	 * packets will arrive on the listener or default tcp queue and
1937 	 * go through tcp_lookup).
1938 	 * The CONN_INC_REF will prevent the acceptor from closing.
1939 	 *
1940 	 * XXX It is still possible for a tli application to send down data
1941 	 * on the accepting stream while another thread calls t_accept.
1942 	 * This should not be a problem for well-behaved applications since
1943 	 * the T_OK_ACK is sent after the queue swapping is completed.
1944 	 *
1945 	 * If the accepting fd is the same as the listening fd, avoid
1946 	 * queue hash lookup since that will return an eager listener in a
1947 	 * already established state.
1948 	 */
1949 	acceptor_id = tcr->ACCEPTOR_id;
1950 	mutex_enter(&listener->tcp_eager_lock);
1951 	if (listener->tcp_acceptor_id == acceptor_id) {
1952 		eager = listener->tcp_eager_next_q;
1953 		/* only count how many T_CONN_INDs so don't count q0 */
1954 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1955 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1956 			mutex_exit(&listener->tcp_eager_lock);
1957 			tcp_err_ack(listener, mp, TBADF, 0);
1958 			return;
1959 		}
1960 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1961 			/* Throw away all the eagers on q0. */
1962 			tcp_eager_cleanup(listener, 1);
1963 		}
1964 		if (listener->tcp_syn_defense) {
1965 			listener->tcp_syn_defense = B_FALSE;
1966 			if (listener->tcp_ip_addr_cache != NULL) {
1967 				kmem_free(listener->tcp_ip_addr_cache,
1968 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1969 				listener->tcp_ip_addr_cache = NULL;
1970 			}
1971 		}
1972 		/*
1973 		 * Transfer tcp_conn_req_max to the eager so that when
1974 		 * a disconnect occurs we can revert the endpoint to the
1975 		 * listen state.
1976 		 */
1977 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1978 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1979 		/*
1980 		 * Get a reference on the acceptor just like the
1981 		 * tcp_acceptor_hash_lookup below.
1982 		 */
1983 		acceptor = listener;
1984 		CONN_INC_REF(acceptor->tcp_connp);
1985 	} else {
1986 		acceptor = tcp_acceptor_hash_lookup(acceptor_id);
1987 		if (acceptor == NULL) {
1988 			if (listener->tcp_debug) {
1989 				(void) strlog(TCP_MOD_ID, 0, 1,
1990 				    SL_ERROR|SL_TRACE,
1991 				    "tcp_accept: did not find acceptor 0x%x\n",
1992 				    acceptor_id);
1993 			}
1994 			mutex_exit(&listener->tcp_eager_lock);
1995 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1996 			return;
1997 		}
1998 		/*
1999 		 * Verify acceptor state. The acceptable states for an acceptor
2000 		 * include TCPS_IDLE and TCPS_BOUND.
2001 		 */
2002 		switch (acceptor->tcp_state) {
2003 		case TCPS_IDLE:
2004 			/* FALLTHRU */
2005 		case TCPS_BOUND:
2006 			break;
2007 		default:
2008 			CONN_DEC_REF(acceptor->tcp_connp);
2009 			mutex_exit(&listener->tcp_eager_lock);
2010 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2011 			return;
2012 		}
2013 	}
2014 
2015 	/* The listener must be in TCPS_LISTEN */
2016 	if (listener->tcp_state != TCPS_LISTEN) {
2017 		CONN_DEC_REF(acceptor->tcp_connp);
2018 		mutex_exit(&listener->tcp_eager_lock);
2019 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2020 		return;
2021 	}
2022 
2023 	/*
2024 	 * Rendezvous with an eager connection request packet hanging off
2025 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2026 	 * tcp structure when the connection packet arrived in
2027 	 * tcp_conn_request().
2028 	 */
2029 	seqnum = tcr->SEQ_number;
2030 	eager = listener;
2031 	do {
2032 		eager = eager->tcp_eager_next_q;
2033 		if (eager == NULL) {
2034 			CONN_DEC_REF(acceptor->tcp_connp);
2035 			mutex_exit(&listener->tcp_eager_lock);
2036 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2037 			return;
2038 		}
2039 	} while (eager->tcp_conn_req_seqnum != seqnum);
2040 	mutex_exit(&listener->tcp_eager_lock);
2041 
2042 	/*
2043 	 * At this point, both acceptor and listener have 2 ref
2044 	 * that they begin with. Acceptor has one additional ref
2045 	 * we placed in lookup while listener has 3 additional
2046 	 * ref for being behind the squeue (tcp_accept() is
2047 	 * done on listener's squeue); being in classifier hash;
2048 	 * and eager's ref on listener.
2049 	 */
2050 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2051 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2052 
2053 	/*
2054 	 * The eager at this point is set in its own squeue and
2055 	 * could easily have been killed (tcp_accept_finish will
2056 	 * deal with that) because of a TH_RST so we can only
2057 	 * ASSERT for a single ref.
2058 	 */
2059 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2060 
2061 	/* Pre allocate the stroptions mblk also */
2062 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2063 	if (opt_mp == NULL) {
2064 		CONN_DEC_REF(acceptor->tcp_connp);
2065 		CONN_DEC_REF(eager->tcp_connp);
2066 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2067 		return;
2068 	}
2069 	DB_TYPE(opt_mp) = M_SETOPTS;
2070 	opt_mp->b_wptr += sizeof (struct stroptions);
2071 
2072 	/*
2073 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2074 	 * from listener to acceptor. The message is chained on opt_mp
2075 	 * which will be sent onto eager's squeue.
2076 	 */
2077 	if (listener->tcp_bound_if != 0) {
2078 		/* allocate optmgmt req */
2079 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2080 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2081 		    sizeof (int));
2082 		if (mp1 != NULL)
2083 			linkb(opt_mp, mp1);
2084 	}
2085 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2086 		uint_t on = 1;
2087 
2088 		/* allocate optmgmt req */
2089 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2090 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2091 		if (mp1 != NULL)
2092 			linkb(opt_mp, mp1);
2093 	}
2094 
2095 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2096 	if ((mp1 = copymsg(mp)) == NULL) {
2097 		CONN_DEC_REF(acceptor->tcp_connp);
2098 		CONN_DEC_REF(eager->tcp_connp);
2099 		freemsg(opt_mp);
2100 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2101 		return;
2102 	}
2103 
2104 	tcr = (struct T_conn_res *)mp1->b_rptr;
2105 
2106 	/*
2107 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2108 	 * which allocates a larger mblk and appends the new
2109 	 * local address to the ok_ack.  The address is copied by
2110 	 * soaccept() for getsockname().
2111 	 */
2112 	{
2113 		int extra;
2114 
2115 		extra = (eager->tcp_family == AF_INET) ?
2116 		    sizeof (sin_t) : sizeof (sin6_t);
2117 
2118 		/*
2119 		 * Try to re-use mp, if possible.  Otherwise, allocate
2120 		 * an mblk and return it as ok_mp.  In any case, mp
2121 		 * is no longer usable upon return.
2122 		 */
2123 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2124 			CONN_DEC_REF(acceptor->tcp_connp);
2125 			CONN_DEC_REF(eager->tcp_connp);
2126 			freemsg(opt_mp);
2127 			/* Original mp has been freed by now, so use mp1 */
2128 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2129 			return;
2130 		}
2131 
2132 		mp = NULL;	/* We should never use mp after this point */
2133 
2134 		switch (extra) {
2135 		case sizeof (sin_t): {
2136 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2137 
2138 				ok_mp->b_wptr += extra;
2139 				sin->sin_family = AF_INET;
2140 				sin->sin_port = eager->tcp_lport;
2141 				sin->sin_addr.s_addr =
2142 				    eager->tcp_ipha->ipha_src;
2143 				break;
2144 			}
2145 		case sizeof (sin6_t): {
2146 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2147 
2148 				ok_mp->b_wptr += extra;
2149 				sin6->sin6_family = AF_INET6;
2150 				sin6->sin6_port = eager->tcp_lport;
2151 				if (eager->tcp_ipversion == IPV4_VERSION) {
2152 					sin6->sin6_flowinfo = 0;
2153 					IN6_IPADDR_TO_V4MAPPED(
2154 					    eager->tcp_ipha->ipha_src,
2155 					    &sin6->sin6_addr);
2156 				} else {
2157 					ASSERT(eager->tcp_ip6h != NULL);
2158 					sin6->sin6_flowinfo =
2159 					    eager->tcp_ip6h->ip6_vcf &
2160 					    ~IPV6_VERS_AND_FLOW_MASK;
2161 					sin6->sin6_addr =
2162 					    eager->tcp_ip6h->ip6_src;
2163 				}
2164 				break;
2165 			}
2166 		default:
2167 			break;
2168 		}
2169 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2170 	}
2171 
2172 	/*
2173 	 * If there are no options we know that the T_CONN_RES will
2174 	 * succeed. However, we can't send the T_OK_ACK upstream until
2175 	 * the tcp_accept_swap is done since it would be dangerous to
2176 	 * let the application start using the new fd prior to the swap.
2177 	 */
2178 	tcp_accept_swap(listener, acceptor, eager);
2179 
2180 	/*
2181 	 * tcp_accept_swap unlinks eager from listener but does not drop
2182 	 * the eager's reference on the listener.
2183 	 */
2184 	ASSERT(eager->tcp_listener == NULL);
2185 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2186 
2187 	/*
2188 	 * The eager is now associated with its own queue. Insert in
2189 	 * the hash so that the connection can be reused for a future
2190 	 * T_CONN_RES.
2191 	 */
2192 	tcp_acceptor_hash_insert(acceptor_id, eager);
2193 
2194 	/*
2195 	 * We now do the processing of options with T_CONN_RES.
2196 	 * We delay till now since we wanted to have queue to pass to
2197 	 * option processing routines that points back to the right
2198 	 * instance structure which does not happen until after
2199 	 * tcp_accept_swap().
2200 	 *
2201 	 * Note:
2202 	 * The sanity of the logic here assumes that whatever options
2203 	 * are appropriate to inherit from listner=>eager are done
2204 	 * before this point, and whatever were to be overridden (or not)
2205 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2206 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2207 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2208 	 * This may not be true at this point in time but can be fixed
2209 	 * independently. This option processing code starts with
2210 	 * the instantiated acceptor instance and the final queue at
2211 	 * this point.
2212 	 */
2213 
2214 	if (tcr->OPT_length != 0) {
2215 		/* Options to process */
2216 		int t_error = 0;
2217 		int sys_error = 0;
2218 		int do_disconnect = 0;
2219 
2220 		if (tcp_conprim_opt_process(eager, mp1,
2221 		    &do_disconnect, &t_error, &sys_error) < 0) {
2222 			eager->tcp_accept_error = 1;
2223 			if (do_disconnect) {
2224 				/*
2225 				 * An option failed which does not allow
2226 				 * connection to be accepted.
2227 				 *
2228 				 * We allow T_CONN_RES to succeed and
2229 				 * put a T_DISCON_IND on the eager queue.
2230 				 */
2231 				ASSERT(t_error == 0 && sys_error == 0);
2232 				eager->tcp_send_discon_ind = 1;
2233 			} else {
2234 				ASSERT(t_error != 0);
2235 				freemsg(ok_mp);
2236 				/*
2237 				 * Original mp was either freed or set
2238 				 * to ok_mp above, so use mp1 instead.
2239 				 */
2240 				tcp_err_ack(listener, mp1, t_error, sys_error);
2241 				goto finish;
2242 			}
2243 		}
2244 		/*
2245 		 * Most likely success in setting options (except if
2246 		 * eager->tcp_send_discon_ind set).
2247 		 * mp1 option buffer represented by OPT_length/offset
2248 		 * potentially modified and contains results of setting
2249 		 * options at this point
2250 		 */
2251 	}
2252 
2253 	/* We no longer need mp1, since all options processing has passed */
2254 	freemsg(mp1);
2255 
2256 	putnext(listener->tcp_rq, ok_mp);
2257 
2258 	mutex_enter(&listener->tcp_eager_lock);
2259 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2260 		tcp_t	*tail;
2261 		mblk_t	*conn_ind;
2262 
2263 		/*
2264 		 * This path should not be executed if listener and
2265 		 * acceptor streams are the same.
2266 		 */
2267 		ASSERT(listener != acceptor);
2268 
2269 		tcp = listener->tcp_eager_prev_q0;
2270 		/*
2271 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2272 		 * deferred T_conn_ind queue. We need to get to the head of
2273 		 * the queue in order to send up T_conn_ind the same order as
2274 		 * how the 3WHS is completed.
2275 		 */
2276 		while (tcp != listener) {
2277 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2278 				break;
2279 			else
2280 				tcp = tcp->tcp_eager_prev_q0;
2281 		}
2282 		ASSERT(tcp != listener);
2283 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2284 		ASSERT(conn_ind != NULL);
2285 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2286 
2287 		/* Move from q0 to q */
2288 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2289 		listener->tcp_conn_req_cnt_q0--;
2290 		listener->tcp_conn_req_cnt_q++;
2291 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2292 		    tcp->tcp_eager_prev_q0;
2293 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2294 		    tcp->tcp_eager_next_q0;
2295 		tcp->tcp_eager_prev_q0 = NULL;
2296 		tcp->tcp_eager_next_q0 = NULL;
2297 		tcp->tcp_conn_def_q0 = B_FALSE;
2298 
2299 		/*
2300 		 * Insert at end of the queue because sockfs sends
2301 		 * down T_CONN_RES in chronological order. Leaving
2302 		 * the older conn indications at front of the queue
2303 		 * helps reducing search time.
2304 		 */
2305 		tail = listener->tcp_eager_last_q;
2306 		if (tail != NULL)
2307 			tail->tcp_eager_next_q = tcp;
2308 		else
2309 			listener->tcp_eager_next_q = tcp;
2310 		listener->tcp_eager_last_q = tcp;
2311 		tcp->tcp_eager_next_q = NULL;
2312 		mutex_exit(&listener->tcp_eager_lock);
2313 		putnext(tcp->tcp_rq, conn_ind);
2314 	} else {
2315 		mutex_exit(&listener->tcp_eager_lock);
2316 	}
2317 
2318 	/*
2319 	 * Done with the acceptor - free it
2320 	 *
2321 	 * Note: from this point on, no access to listener should be made
2322 	 * as listener can be equal to acceptor.
2323 	 */
2324 finish:
2325 	ASSERT(acceptor->tcp_detached);
2326 	acceptor->tcp_rq = tcp_g_q;
2327 	acceptor->tcp_wq = WR(tcp_g_q);
2328 	(void) tcp_clean_death(acceptor, 0, 2);
2329 	CONN_DEC_REF(acceptor->tcp_connp);
2330 
2331 	/*
2332 	 * In case we already received a FIN we have to make tcp_rput send
2333 	 * the ordrel_ind. This will also send up a window update if the window
2334 	 * has opened up.
2335 	 *
2336 	 * In the normal case of a successful connection acceptance
2337 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2338 	 * indication that this was just accepted. This tells tcp_rput to
2339 	 * pass up any data queued in tcp_rcv_list.
2340 	 *
2341 	 * In the fringe case where options sent with T_CONN_RES failed and
2342 	 * we required, we would be indicating a T_DISCON_IND to blow
2343 	 * away this connection.
2344 	 */
2345 
2346 	/*
2347 	 * XXX: we currently have a problem if XTI application closes the
2348 	 * acceptor stream in between. This problem exists in on10-gate also
2349 	 * and is well know but nothing can be done short of major rewrite
2350 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2351 	 * eager same squeue as listener (we can distinguish non socket
2352 	 * listeners at the time of handling a SYN in tcp_conn_request)
2353 	 * and do most of the work that tcp_accept_finish does here itself
2354 	 * and then get behind the acceptor squeue to access the acceptor
2355 	 * queue.
2356 	 */
2357 	/*
2358 	 * We already have a ref on tcp so no need to do one before squeue_fill
2359 	 */
2360 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2361 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2362 }
2363 
2364 /*
2365  * Swap information between the eager and acceptor for a TLI/XTI client.
2366  * The sockfs accept is done on the acceptor stream and control goes
2367  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2368  * called. In either case, both the eager and listener are in their own
2369  * perimeter (squeue) and the code has to deal with potential race.
2370  *
2371  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2372  */
2373 static void
2374 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2375 {
2376 	conn_t	*econnp, *aconnp;
2377 
2378 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2379 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2380 	ASSERT(!eager->tcp_hard_bound);
2381 	ASSERT(!TCP_IS_SOCKET(acceptor));
2382 	ASSERT(!TCP_IS_SOCKET(eager));
2383 	ASSERT(!TCP_IS_SOCKET(listener));
2384 
2385 	acceptor->tcp_detached = B_TRUE;
2386 	/*
2387 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2388 	 * the acceptor id.
2389 	 */
2390 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2391 
2392 	/* remove eager from listen list... */
2393 	mutex_enter(&listener->tcp_eager_lock);
2394 	tcp_eager_unlink(eager);
2395 	ASSERT(eager->tcp_eager_next_q == NULL &&
2396 	    eager->tcp_eager_last_q == NULL);
2397 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2398 	    eager->tcp_eager_prev_q0 == NULL);
2399 	mutex_exit(&listener->tcp_eager_lock);
2400 	eager->tcp_rq = acceptor->tcp_rq;
2401 	eager->tcp_wq = acceptor->tcp_wq;
2402 
2403 	econnp = eager->tcp_connp;
2404 	aconnp = acceptor->tcp_connp;
2405 
2406 	eager->tcp_rq->q_ptr = econnp;
2407 	eager->tcp_wq->q_ptr = econnp;
2408 	eager->tcp_detached = B_FALSE;
2409 
2410 	ASSERT(eager->tcp_ack_tid == 0);
2411 
2412 	econnp->conn_dev = aconnp->conn_dev;
2413 	if (eager->tcp_cred != NULL)
2414 		crfree(eager->tcp_cred);
2415 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2416 	econnp->conn_zoneid = aconnp->conn_zoneid;
2417 	aconnp->conn_cred = NULL;
2418 
2419 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2420 	aconnp->conn_mac_exempt = B_FALSE;
2421 
2422 	ASSERT(aconnp->conn_peercred == NULL);
2423 
2424 	/* Do the IPC initialization */
2425 	CONN_INC_REF(econnp);
2426 
2427 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2428 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2429 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2430 	econnp->conn_ulp = aconnp->conn_ulp;
2431 
2432 	/* Done with old IPC. Drop its ref on its connp */
2433 	CONN_DEC_REF(aconnp);
2434 }
2435 
2436 
2437 /*
2438  * Adapt to the information, such as rtt and rtt_sd, provided from the
2439  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2440  *
2441  * Checks for multicast and broadcast destination address.
2442  * Returns zero on failure; non-zero if ok.
2443  *
2444  * Note that the MSS calculation here is based on the info given in
2445  * the IRE.  We do not do any calculation based on TCP options.  They
2446  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2447  * knows which options to use.
2448  *
2449  * Note on how TCP gets its parameters for a connection.
2450  *
2451  * When a tcp_t structure is allocated, it gets all the default parameters.
2452  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2453  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2454  * default.  But if there is an associated tcp_host_param, it will override
2455  * the metrics.
2456  *
2457  * An incoming SYN with a multicast or broadcast destination address, is dropped
2458  * in 1 of 2 places.
2459  *
2460  * 1. If the packet was received over the wire it is dropped in
2461  * ip_rput_process_broadcast()
2462  *
2463  * 2. If the packet was received through internal IP loopback, i.e. the packet
2464  * was generated and received on the same machine, it is dropped in
2465  * ip_wput_local()
2466  *
2467  * An incoming SYN with a multicast or broadcast source address is always
2468  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2469  * reject an attempt to connect to a broadcast or multicast (destination)
2470  * address.
2471  */
2472 static int
2473 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2474 {
2475 	tcp_hsp_t	*hsp;
2476 	ire_t		*ire;
2477 	ire_t		*sire = NULL;
2478 	iulp_t		*ire_uinfo = NULL;
2479 	uint32_t	mss_max;
2480 	uint32_t	mss;
2481 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2482 	conn_t		*connp = tcp->tcp_connp;
2483 	boolean_t	ire_cacheable = B_FALSE;
2484 	zoneid_t	zoneid = connp->conn_zoneid;
2485 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2486 			    MATCH_IRE_SECATTR;
2487 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2488 	ill_t		*ill = NULL;
2489 	boolean_t	incoming = (ire_mp == NULL);
2490 
2491 	ASSERT(connp->conn_ire_cache == NULL);
2492 
2493 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2494 
2495 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2496 			BUMP_MIB(&ip_mib, ipInDiscards);
2497 			return (0);
2498 		}
2499 		/*
2500 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2501 		 * for the destination with the nexthop as gateway.
2502 		 * ire_ctable_lookup() is used because this particular
2503 		 * ire, if it exists, will be marked private.
2504 		 * If that is not available, use the interface ire
2505 		 * for the nexthop.
2506 		 *
2507 		 * TSol: tcp_update_label will detect label mismatches based
2508 		 * only on the destination's label, but that would not
2509 		 * detect label mismatches based on the security attributes
2510 		 * of routes or next hop gateway. Hence we need to pass the
2511 		 * label to ire_ftable_lookup below in order to locate the
2512 		 * right prefix (and/or) ire cache. Similarly we also need
2513 		 * pass the label to the ire_cache_lookup below to locate
2514 		 * the right ire that also matches on the label.
2515 		 */
2516 		if (tcp->tcp_connp->conn_nexthop_set) {
2517 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2518 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2519 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2520 			if (ire == NULL) {
2521 				ire = ire_ftable_lookup(
2522 				    tcp->tcp_connp->conn_nexthop_v4,
2523 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2524 				    tsl, match_flags);
2525 				if (ire == NULL)
2526 					return (0);
2527 			} else {
2528 				ire_uinfo = &ire->ire_uinfo;
2529 			}
2530 		} else {
2531 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2532 			    zoneid, tsl);
2533 			if (ire != NULL) {
2534 				ire_cacheable = B_TRUE;
2535 				ire_uinfo = (ire_mp != NULL) ?
2536 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2537 				    &ire->ire_uinfo;
2538 
2539 			} else {
2540 				if (ire_mp == NULL) {
2541 					ire = ire_ftable_lookup(
2542 					    tcp->tcp_connp->conn_rem,
2543 					    0, 0, 0, NULL, &sire, zoneid, 0,
2544 					    tsl, (MATCH_IRE_RECURSIVE |
2545 					    MATCH_IRE_DEFAULT));
2546 					if (ire == NULL)
2547 						return (0);
2548 					ire_uinfo = (sire != NULL) ?
2549 					    &sire->ire_uinfo :
2550 					    &ire->ire_uinfo;
2551 				} else {
2552 					ire = (ire_t *)ire_mp->b_rptr;
2553 					ire_uinfo =
2554 					    &((ire_t *)
2555 					    ire_mp->b_rptr)->ire_uinfo;
2556 				}
2557 			}
2558 		}
2559 		ASSERT(ire != NULL);
2560 
2561 		if ((ire->ire_src_addr == INADDR_ANY) ||
2562 		    (ire->ire_type & IRE_BROADCAST)) {
2563 			/*
2564 			 * ire->ire_mp is non null when ire_mp passed in is used
2565 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2566 			 */
2567 			if (ire->ire_mp == NULL)
2568 				ire_refrele(ire);
2569 			if (sire != NULL)
2570 				ire_refrele(sire);
2571 			return (0);
2572 		}
2573 
2574 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2575 			ipaddr_t src_addr;
2576 
2577 			/*
2578 			 * ip_bind_connected() has stored the correct source
2579 			 * address in conn_src.
2580 			 */
2581 			src_addr = tcp->tcp_connp->conn_src;
2582 			tcp->tcp_ipha->ipha_src = src_addr;
2583 			/*
2584 			 * Copy of the src addr. in tcp_t is needed
2585 			 * for the lookup funcs.
2586 			 */
2587 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2588 		}
2589 		/*
2590 		 * Set the fragment bit so that IP will tell us if the MTU
2591 		 * should change. IP tells us the latest setting of
2592 		 * ip_path_mtu_discovery through ire_frag_flag.
2593 		 */
2594 		if (ip_path_mtu_discovery) {
2595 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2596 			    htons(IPH_DF);
2597 		}
2598 		/*
2599 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2600 		 * for IP_NEXTHOP. No cache ire has been found for the
2601 		 * destination and we are working with the nexthop's
2602 		 * interface ire. Since we need to forward all packets
2603 		 * to the nexthop first, we "blindly" set tcp_localnet
2604 		 * to false, eventhough the destination may also be
2605 		 * onlink.
2606 		 */
2607 		if (ire_uinfo == NULL)
2608 			tcp->tcp_localnet = 0;
2609 		else
2610 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2611 	} else {
2612 		/*
2613 		 * For incoming connection ire_mp = NULL
2614 		 * For outgoing connection ire_mp != NULL
2615 		 * Technically we should check conn_incoming_ill
2616 		 * when ire_mp is NULL and conn_outgoing_ill when
2617 		 * ire_mp is non-NULL. But this is performance
2618 		 * critical path and for IPV*_BOUND_IF, outgoing
2619 		 * and incoming ill are always set to the same value.
2620 		 */
2621 		ill_t	*dst_ill = NULL;
2622 		ipif_t  *dst_ipif = NULL;
2623 
2624 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2625 
2626 		if (connp->conn_outgoing_ill != NULL) {
2627 			/* Outgoing or incoming path */
2628 			int   err;
2629 
2630 			dst_ill = conn_get_held_ill(connp,
2631 			    &connp->conn_outgoing_ill, &err);
2632 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2633 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2634 				return (0);
2635 			}
2636 			match_flags |= MATCH_IRE_ILL;
2637 			dst_ipif = dst_ill->ill_ipif;
2638 		}
2639 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2640 		    0, 0, dst_ipif, zoneid, tsl, match_flags);
2641 
2642 		if (ire != NULL) {
2643 			ire_cacheable = B_TRUE;
2644 			ire_uinfo = (ire_mp != NULL) ?
2645 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2646 			    &ire->ire_uinfo;
2647 		} else {
2648 			if (ire_mp == NULL) {
2649 				ire = ire_ftable_lookup_v6(
2650 				    &tcp->tcp_connp->conn_remv6,
2651 				    0, 0, 0, dst_ipif, &sire, zoneid,
2652 				    0, tsl, match_flags);
2653 				if (ire == NULL) {
2654 					if (dst_ill != NULL)
2655 						ill_refrele(dst_ill);
2656 					return (0);
2657 				}
2658 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2659 				    &ire->ire_uinfo;
2660 			} else {
2661 				ire = (ire_t *)ire_mp->b_rptr;
2662 				ire_uinfo =
2663 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2664 			}
2665 		}
2666 		if (dst_ill != NULL)
2667 			ill_refrele(dst_ill);
2668 
2669 		ASSERT(ire != NULL);
2670 		ASSERT(ire_uinfo != NULL);
2671 
2672 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2673 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2674 			/*
2675 			 * ire->ire_mp is non null when ire_mp passed in is used
2676 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2677 			 */
2678 			if (ire->ire_mp == NULL)
2679 				ire_refrele(ire);
2680 			if (sire != NULL)
2681 				ire_refrele(sire);
2682 			return (0);
2683 		}
2684 
2685 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2686 			in6_addr_t	src_addr;
2687 
2688 			/*
2689 			 * ip_bind_connected_v6() has stored the correct source
2690 			 * address per IPv6 addr. selection policy in
2691 			 * conn_src_v6.
2692 			 */
2693 			src_addr = tcp->tcp_connp->conn_srcv6;
2694 
2695 			tcp->tcp_ip6h->ip6_src = src_addr;
2696 			/*
2697 			 * Copy of the src addr. in tcp_t is needed
2698 			 * for the lookup funcs.
2699 			 */
2700 			tcp->tcp_ip_src_v6 = src_addr;
2701 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2702 			    &connp->conn_srcv6));
2703 		}
2704 		tcp->tcp_localnet =
2705 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2706 	}
2707 
2708 	/*
2709 	 * This allows applications to fail quickly when connections are made
2710 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2711 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2712 	 */
2713 	if ((ire->ire_flags & RTF_REJECT) &&
2714 	    (ire->ire_flags & RTF_PRIVATE))
2715 		goto error;
2716 
2717 	/*
2718 	 * Make use of the cached rtt and rtt_sd values to calculate the
2719 	 * initial RTO.  Note that they are already initialized in
2720 	 * tcp_init_values().
2721 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2722 	 * IP_NEXTHOP, but instead are using the interface ire for the
2723 	 * nexthop, then we do not use the ire_uinfo from that ire to
2724 	 * do any initializations.
2725 	 */
2726 	if (ire_uinfo != NULL) {
2727 		if (ire_uinfo->iulp_rtt != 0) {
2728 			clock_t	rto;
2729 
2730 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2731 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2732 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2733 			    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
2734 
2735 			if (rto > tcp_rexmit_interval_max) {
2736 				tcp->tcp_rto = tcp_rexmit_interval_max;
2737 			} else if (rto < tcp_rexmit_interval_min) {
2738 				tcp->tcp_rto = tcp_rexmit_interval_min;
2739 			} else {
2740 				tcp->tcp_rto = rto;
2741 			}
2742 		}
2743 		if (ire_uinfo->iulp_ssthresh != 0)
2744 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2745 		else
2746 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2747 		if (ire_uinfo->iulp_spipe > 0) {
2748 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2749 			    tcp_max_buf);
2750 			if (tcp_snd_lowat_fraction != 0)
2751 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2752 				    tcp_snd_lowat_fraction;
2753 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2754 		}
2755 		/*
2756 		 * Note that up till now, acceptor always inherits receive
2757 		 * window from the listener.  But if there is a metrics
2758 		 * associated with a host, we should use that instead of
2759 		 * inheriting it from listener. Thus we need to pass this
2760 		 * info back to the caller.
2761 		 */
2762 		if (ire_uinfo->iulp_rpipe > 0) {
2763 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
2764 		}
2765 
2766 		if (ire_uinfo->iulp_rtomax > 0) {
2767 			tcp->tcp_second_timer_threshold =
2768 			    ire_uinfo->iulp_rtomax;
2769 		}
2770 
2771 		/*
2772 		 * Use the metric option settings, iulp_tstamp_ok and
2773 		 * iulp_wscale_ok, only for active open. What this means
2774 		 * is that if the other side uses timestamp or window
2775 		 * scale option, TCP will also use those options. That
2776 		 * is for passive open.  If the application sets a
2777 		 * large window, window scale is enabled regardless of
2778 		 * the value in iulp_wscale_ok.  This is the behavior
2779 		 * since 2.6.  So we keep it.
2780 		 * The only case left in passive open processing is the
2781 		 * check for SACK.
2782 		 * For ECN, it should probably be like SACK.  But the
2783 		 * current value is binary, so we treat it like the other
2784 		 * cases.  The metric only controls active open.For passive
2785 		 * open, the ndd param, tcp_ecn_permitted, controls the
2786 		 * behavior.
2787 		 */
2788 		if (!tcp_detached) {
2789 			/*
2790 			 * The if check means that the following can only
2791 			 * be turned on by the metrics only IRE, but not off.
2792 			 */
2793 			if (ire_uinfo->iulp_tstamp_ok)
2794 				tcp->tcp_snd_ts_ok = B_TRUE;
2795 			if (ire_uinfo->iulp_wscale_ok)
2796 				tcp->tcp_snd_ws_ok = B_TRUE;
2797 			if (ire_uinfo->iulp_sack == 2)
2798 				tcp->tcp_snd_sack_ok = B_TRUE;
2799 			if (ire_uinfo->iulp_ecn_ok)
2800 				tcp->tcp_ecn_ok = B_TRUE;
2801 		} else {
2802 			/*
2803 			 * Passive open.
2804 			 *
2805 			 * As above, the if check means that SACK can only be
2806 			 * turned on by the metric only IRE.
2807 			 */
2808 			if (ire_uinfo->iulp_sack > 0) {
2809 				tcp->tcp_snd_sack_ok = B_TRUE;
2810 			}
2811 		}
2812 	}
2813 
2814 
2815 	/*
2816 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2817 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2818 	 * length of all those options exceeds 28 bytes.  But because
2819 	 * of the tcp_mss_min check below, we may not have a problem if
2820 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2821 	 * the negative problem still exists.  And the check defeats PMTUd.
2822 	 * In fact, if PMTUd finds that the MSS should be smaller than
2823 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2824 	 * value.
2825 	 *
2826 	 * We do not deal with that now.  All those problems related to
2827 	 * PMTUd will be fixed later.
2828 	 */
2829 	ASSERT(ire->ire_max_frag != 0);
2830 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2831 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2832 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2833 			mss = MIN(mss, IPV6_MIN_MTU);
2834 		}
2835 	}
2836 
2837 	/* Sanity check for MSS value. */
2838 	if (tcp->tcp_ipversion == IPV4_VERSION)
2839 		mss_max = tcp_mss_max_ipv4;
2840 	else
2841 		mss_max = tcp_mss_max_ipv6;
2842 
2843 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2844 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2845 		/*
2846 		 * After receiving an ICMPv6 "packet too big" message with a
2847 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2848 		 * will insert a 8-byte fragment header in every packet; we
2849 		 * reduce the MSS by that amount here.
2850 		 */
2851 		mss -= sizeof (ip6_frag_t);
2852 	}
2853 
2854 	if (tcp->tcp_ipsec_overhead == 0)
2855 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2856 
2857 	mss -= tcp->tcp_ipsec_overhead;
2858 
2859 	if (mss < tcp_mss_min)
2860 		mss = tcp_mss_min;
2861 	if (mss > mss_max)
2862 		mss = mss_max;
2863 
2864 	/* Note that this is the maximum MSS, excluding all options. */
2865 	tcp->tcp_mss = mss;
2866 
2867 	/*
2868 	 * Initialize the ISS here now that we have the full connection ID.
2869 	 * The RFC 1948 method of initial sequence number generation requires
2870 	 * knowledge of the full connection ID before setting the ISS.
2871 	 */
2872 
2873 	tcp_iss_init(tcp);
2874 
2875 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2876 		tcp->tcp_loopback = B_TRUE;
2877 
2878 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2879 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
2880 	} else {
2881 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
2882 	}
2883 
2884 	if (hsp != NULL) {
2885 		/* Only modify if we're going to make them bigger */
2886 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2887 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2888 			if (tcp_snd_lowat_fraction != 0)
2889 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2890 					tcp_snd_lowat_fraction;
2891 		}
2892 
2893 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2894 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2895 		}
2896 
2897 		/* Copy timestamp flag only for active open */
2898 		if (!tcp_detached)
2899 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2900 	}
2901 
2902 	if (sire != NULL)
2903 		IRE_REFRELE(sire);
2904 
2905 	/*
2906 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2907 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2908 	 */
2909 	if (tcp->tcp_loopback ||
2910 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2911 		/*
2912 		 * For incoming, see if this tcp may be MDT-capable.  For
2913 		 * outgoing, this process has been taken care of through
2914 		 * tcp_rput_other.
2915 		 */
2916 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2917 		tcp->tcp_ire_ill_check_done = B_TRUE;
2918 	}
2919 
2920 	mutex_enter(&connp->conn_lock);
2921 	/*
2922 	 * Make sure that conn is not marked incipient
2923 	 * for incoming connections. A blind
2924 	 * removal of incipient flag is cheaper than
2925 	 * check and removal.
2926 	 */
2927 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2928 
2929 	/* Must not cache forwarding table routes. */
2930 	if (ire_cacheable) {
2931 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2932 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2933 			connp->conn_ire_cache = ire;
2934 			IRE_UNTRACE_REF(ire);
2935 			rw_exit(&ire->ire_bucket->irb_lock);
2936 			mutex_exit(&connp->conn_lock);
2937 			return (1);
2938 		}
2939 		rw_exit(&ire->ire_bucket->irb_lock);
2940 	}
2941 	mutex_exit(&connp->conn_lock);
2942 
2943 	if (ire->ire_mp == NULL)
2944 		ire_refrele(ire);
2945 	return (1);
2946 
2947 error:
2948 	if (ire->ire_mp == NULL)
2949 		ire_refrele(ire);
2950 	if (sire != NULL)
2951 		ire_refrele(sire);
2952 	return (0);
2953 }
2954 
2955 /*
2956  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2957  * O_T_BIND_REQ/T_BIND_REQ message.
2958  */
2959 static void
2960 tcp_bind(tcp_t *tcp, mblk_t *mp)
2961 {
2962 	sin_t	*sin;
2963 	sin6_t	*sin6;
2964 	mblk_t	*mp1;
2965 	in_port_t requested_port;
2966 	in_port_t allocated_port;
2967 	struct T_bind_req *tbr;
2968 	boolean_t	bind_to_req_port_only;
2969 	boolean_t	backlog_update = B_FALSE;
2970 	boolean_t	user_specified;
2971 	in6_addr_t	v6addr;
2972 	ipaddr_t	v4addr;
2973 	uint_t	origipversion;
2974 	int	err;
2975 	queue_t *q = tcp->tcp_wq;
2976 	conn_t	*connp;
2977 	mlp_type_t addrtype, mlptype;
2978 	zone_t	*zone;
2979 	cred_t	*cr;
2980 	in_port_t mlp_port;
2981 
2982 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2983 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2984 		if (tcp->tcp_debug) {
2985 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2986 			    "tcp_bind: bad req, len %u",
2987 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2988 		}
2989 		tcp_err_ack(tcp, mp, TPROTO, 0);
2990 		return;
2991 	}
2992 	/* Make sure the largest address fits */
2993 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
2994 	if (mp1 == NULL) {
2995 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2996 		return;
2997 	}
2998 	mp = mp1;
2999 	tbr = (struct T_bind_req *)mp->b_rptr;
3000 	if (tcp->tcp_state >= TCPS_BOUND) {
3001 		if ((tcp->tcp_state == TCPS_BOUND ||
3002 		    tcp->tcp_state == TCPS_LISTEN) &&
3003 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3004 		    tbr->CONIND_number > 0) {
3005 			/*
3006 			 * Handle listen() increasing CONIND_number.
3007 			 * This is more "liberal" then what the TPI spec
3008 			 * requires but is needed to avoid a t_unbind
3009 			 * when handling listen() since the port number
3010 			 * might be "stolen" between the unbind and bind.
3011 			 */
3012 			backlog_update = B_TRUE;
3013 			goto do_bind;
3014 		}
3015 		if (tcp->tcp_debug) {
3016 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3017 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3018 		}
3019 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3020 		return;
3021 	}
3022 	origipversion = tcp->tcp_ipversion;
3023 
3024 	switch (tbr->ADDR_length) {
3025 	case 0:			/* request for a generic port */
3026 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3027 		if (tcp->tcp_family == AF_INET) {
3028 			tbr->ADDR_length = sizeof (sin_t);
3029 			sin = (sin_t *)&tbr[1];
3030 			*sin = sin_null;
3031 			sin->sin_family = AF_INET;
3032 			mp->b_wptr = (uchar_t *)&sin[1];
3033 			tcp->tcp_ipversion = IPV4_VERSION;
3034 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3035 		} else {
3036 			ASSERT(tcp->tcp_family == AF_INET6);
3037 			tbr->ADDR_length = sizeof (sin6_t);
3038 			sin6 = (sin6_t *)&tbr[1];
3039 			*sin6 = sin6_null;
3040 			sin6->sin6_family = AF_INET6;
3041 			mp->b_wptr = (uchar_t *)&sin6[1];
3042 			tcp->tcp_ipversion = IPV6_VERSION;
3043 			V6_SET_ZERO(v6addr);
3044 		}
3045 		requested_port = 0;
3046 		break;
3047 
3048 	case sizeof (sin_t):	/* Complete IPv4 address */
3049 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3050 		    sizeof (sin_t));
3051 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3052 			if (tcp->tcp_debug) {
3053 				(void) strlog(TCP_MOD_ID, 0, 1,
3054 				    SL_ERROR|SL_TRACE,
3055 				    "tcp_bind: bad address parameter, "
3056 				    "offset %d, len %d",
3057 				    tbr->ADDR_offset, tbr->ADDR_length);
3058 			}
3059 			tcp_err_ack(tcp, mp, TPROTO, 0);
3060 			return;
3061 		}
3062 		/*
3063 		 * With sockets sockfs will accept bogus sin_family in
3064 		 * bind() and replace it with the family used in the socket
3065 		 * call.
3066 		 */
3067 		if (sin->sin_family != AF_INET ||
3068 		    tcp->tcp_family != AF_INET) {
3069 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3070 			return;
3071 		}
3072 		requested_port = ntohs(sin->sin_port);
3073 		tcp->tcp_ipversion = IPV4_VERSION;
3074 		v4addr = sin->sin_addr.s_addr;
3075 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3076 		break;
3077 
3078 	case sizeof (sin6_t): /* Complete IPv6 address */
3079 		sin6 = (sin6_t *)mi_offset_param(mp,
3080 		    tbr->ADDR_offset, sizeof (sin6_t));
3081 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3082 			if (tcp->tcp_debug) {
3083 				(void) strlog(TCP_MOD_ID, 0, 1,
3084 				    SL_ERROR|SL_TRACE,
3085 				    "tcp_bind: bad IPv6 address parameter, "
3086 				    "offset %d, len %d", tbr->ADDR_offset,
3087 				    tbr->ADDR_length);
3088 			}
3089 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3090 			return;
3091 		}
3092 		if (sin6->sin6_family != AF_INET6 ||
3093 		    tcp->tcp_family != AF_INET6) {
3094 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3095 			return;
3096 		}
3097 		requested_port = ntohs(sin6->sin6_port);
3098 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3099 		    IPV4_VERSION : IPV6_VERSION;
3100 		v6addr = sin6->sin6_addr;
3101 		break;
3102 
3103 	default:
3104 		if (tcp->tcp_debug) {
3105 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3106 			    "tcp_bind: bad address length, %d",
3107 			    tbr->ADDR_length);
3108 		}
3109 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3110 		return;
3111 	}
3112 	tcp->tcp_bound_source_v6 = v6addr;
3113 
3114 	/* Check for change in ipversion */
3115 	if (origipversion != tcp->tcp_ipversion) {
3116 		ASSERT(tcp->tcp_family == AF_INET6);
3117 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3118 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3119 		if (err) {
3120 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3121 			return;
3122 		}
3123 	}
3124 
3125 	/*
3126 	 * Initialize family specific fields. Copy of the src addr.
3127 	 * in tcp_t is needed for the lookup funcs.
3128 	 */
3129 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3130 		tcp->tcp_ip6h->ip6_src = v6addr;
3131 	} else {
3132 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3133 	}
3134 	tcp->tcp_ip_src_v6 = v6addr;
3135 
3136 	/*
3137 	 * For O_T_BIND_REQ:
3138 	 * Verify that the target port/addr is available, or choose
3139 	 * another.
3140 	 * For  T_BIND_REQ:
3141 	 * Verify that the target port/addr is available or fail.
3142 	 * In both cases when it succeeds the tcp is inserted in the
3143 	 * bind hash table. This ensures that the operation is atomic
3144 	 * under the lock on the hash bucket.
3145 	 */
3146 	bind_to_req_port_only = requested_port != 0 &&
3147 	    tbr->PRIM_type != O_T_BIND_REQ;
3148 	/*
3149 	 * Get a valid port (within the anonymous range and should not
3150 	 * be a privileged one) to use if the user has not given a port.
3151 	 * If multiple threads are here, they may all start with
3152 	 * with the same initial port. But, it should be fine as long as
3153 	 * tcp_bindi will ensure that no two threads will be assigned
3154 	 * the same port.
3155 	 *
3156 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3157 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3158 	 * unless TCP_ANONPRIVBIND option is set.
3159 	 */
3160 	mlptype = mlptSingle;
3161 	mlp_port = requested_port;
3162 	if (requested_port == 0) {
3163 		requested_port = tcp->tcp_anon_priv_bind ?
3164 		    tcp_get_next_priv_port(tcp) :
3165 		    tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
3166 		if (requested_port == 0) {
3167 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3168 			return;
3169 		}
3170 		user_specified = B_FALSE;
3171 
3172 		/*
3173 		 * If the user went through one of the RPC interfaces to create
3174 		 * this socket and RPC is MLP in this zone, then give him an
3175 		 * anonymous MLP.
3176 		 */
3177 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3178 		connp = tcp->tcp_connp;
3179 		if (connp->conn_anon_mlp && is_system_labeled()) {
3180 			zone = crgetzone(cr);
3181 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3182 			    IPV6_VERSION, &v6addr);
3183 			if (addrtype == mlptSingle) {
3184 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3185 				return;
3186 			}
3187 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3188 			    PMAPPORT, addrtype);
3189 			mlp_port = PMAPPORT;
3190 		}
3191 	} else {
3192 		int i;
3193 		boolean_t priv = B_FALSE;
3194 
3195 		/*
3196 		 * If the requested_port is in the well-known privileged range,
3197 		 * verify that the stream was opened by a privileged user.
3198 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3199 		 * but instead the code relies on:
3200 		 * - the fact that the address of the array and its size never
3201 		 *   changes
3202 		 * - the atomic assignment of the elements of the array
3203 		 */
3204 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3205 		if (requested_port < tcp_smallest_nonpriv_port) {
3206 			priv = B_TRUE;
3207 		} else {
3208 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3209 				if (requested_port ==
3210 				    tcp_g_epriv_ports[i]) {
3211 					priv = B_TRUE;
3212 					break;
3213 				}
3214 			}
3215 		}
3216 		if (priv) {
3217 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3218 				if (tcp->tcp_debug) {
3219 					(void) strlog(TCP_MOD_ID, 0, 1,
3220 					    SL_ERROR|SL_TRACE,
3221 					    "tcp_bind: no priv for port %d",
3222 					    requested_port);
3223 				}
3224 				tcp_err_ack(tcp, mp, TACCES, 0);
3225 				return;
3226 			}
3227 		}
3228 		user_specified = B_TRUE;
3229 
3230 		connp = tcp->tcp_connp;
3231 		if (is_system_labeled()) {
3232 			zone = crgetzone(cr);
3233 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3234 			    IPV6_VERSION, &v6addr);
3235 			if (addrtype == mlptSingle) {
3236 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3237 				return;
3238 			}
3239 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3240 			    requested_port, addrtype);
3241 		}
3242 	}
3243 
3244 	if (mlptype != mlptSingle) {
3245 		if (secpolicy_net_bindmlp(cr) != 0) {
3246 			if (tcp->tcp_debug) {
3247 				(void) strlog(TCP_MOD_ID, 0, 1,
3248 				    SL_ERROR|SL_TRACE,
3249 				    "tcp_bind: no priv for multilevel port %d",
3250 				    requested_port);
3251 			}
3252 			tcp_err_ack(tcp, mp, TACCES, 0);
3253 			return;
3254 		}
3255 
3256 		/*
3257 		 * If we're specifically binding a shared IP address and the
3258 		 * port is MLP on shared addresses, then check to see if this
3259 		 * zone actually owns the MLP.  Reject if not.
3260 		 */
3261 		if (mlptype == mlptShared && addrtype == mlptShared) {
3262 			zoneid_t mlpzone;
3263 
3264 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3265 			    htons(mlp_port));
3266 			if (connp->conn_zoneid != mlpzone) {
3267 				if (tcp->tcp_debug) {
3268 					(void) strlog(TCP_MOD_ID, 0, 1,
3269 					    SL_ERROR|SL_TRACE,
3270 					    "tcp_bind: attempt to bind port "
3271 					    "%d on shared addr in zone %d "
3272 					    "(should be %d)",
3273 					    mlp_port, connp->conn_zoneid,
3274 					    mlpzone);
3275 				}
3276 				tcp_err_ack(tcp, mp, TACCES, 0);
3277 				return;
3278 			}
3279 		}
3280 
3281 		if (!user_specified) {
3282 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3283 			    requested_port, B_TRUE);
3284 			if (err != 0) {
3285 				if (tcp->tcp_debug) {
3286 					(void) strlog(TCP_MOD_ID, 0, 1,
3287 					    SL_ERROR|SL_TRACE,
3288 					    "tcp_bind: cannot establish anon "
3289 					    "MLP for port %d",
3290 					    requested_port);
3291 				}
3292 				tcp_err_ack(tcp, mp, TSYSERR, err);
3293 				return;
3294 			}
3295 			connp->conn_anon_port = B_TRUE;
3296 		}
3297 		connp->conn_mlp_type = mlptype;
3298 	}
3299 
3300 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3301 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3302 
3303 	if (allocated_port == 0) {
3304 		connp->conn_mlp_type = mlptSingle;
3305 		if (connp->conn_anon_port) {
3306 			connp->conn_anon_port = B_FALSE;
3307 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3308 			    requested_port, B_FALSE);
3309 		}
3310 		if (bind_to_req_port_only) {
3311 			if (tcp->tcp_debug) {
3312 				(void) strlog(TCP_MOD_ID, 0, 1,
3313 				    SL_ERROR|SL_TRACE,
3314 				    "tcp_bind: requested addr busy");
3315 			}
3316 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3317 		} else {
3318 			/* If we are out of ports, fail the bind. */
3319 			if (tcp->tcp_debug) {
3320 				(void) strlog(TCP_MOD_ID, 0, 1,
3321 				    SL_ERROR|SL_TRACE,
3322 				    "tcp_bind: out of ports?");
3323 			}
3324 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3325 		}
3326 		return;
3327 	}
3328 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3329 do_bind:
3330 	if (!backlog_update) {
3331 		if (tcp->tcp_family == AF_INET)
3332 			sin->sin_port = htons(allocated_port);
3333 		else
3334 			sin6->sin6_port = htons(allocated_port);
3335 	}
3336 	if (tcp->tcp_family == AF_INET) {
3337 		if (tbr->CONIND_number != 0) {
3338 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3339 			    sizeof (sin_t));
3340 		} else {
3341 			/* Just verify the local IP address */
3342 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3343 		}
3344 	} else {
3345 		if (tbr->CONIND_number != 0) {
3346 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3347 			    sizeof (sin6_t));
3348 		} else {
3349 			/* Just verify the local IP address */
3350 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3351 			    IPV6_ADDR_LEN);
3352 		}
3353 	}
3354 	if (mp1 == NULL) {
3355 		if (connp->conn_anon_port) {
3356 			connp->conn_anon_port = B_FALSE;
3357 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3358 			    requested_port, B_FALSE);
3359 		}
3360 		connp->conn_mlp_type = mlptSingle;
3361 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3362 		return;
3363 	}
3364 
3365 	tbr->PRIM_type = T_BIND_ACK;
3366 	mp->b_datap->db_type = M_PCPROTO;
3367 
3368 	/* Chain in the reply mp for tcp_rput() */
3369 	mp1->b_cont = mp;
3370 	mp = mp1;
3371 
3372 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3373 	if (tcp->tcp_conn_req_max) {
3374 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
3375 			tcp->tcp_conn_req_max = tcp_conn_req_min;
3376 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
3377 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
3378 		/*
3379 		 * If this is a listener, do not reset the eager list
3380 		 * and other stuffs.  Note that we don't check if the
3381 		 * existing eager list meets the new tcp_conn_req_max
3382 		 * requirement.
3383 		 */
3384 		if (tcp->tcp_state != TCPS_LISTEN) {
3385 			tcp->tcp_state = TCPS_LISTEN;
3386 			/* Initialize the chain. Don't need the eager_lock */
3387 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3388 			tcp->tcp_second_ctimer_threshold =
3389 			    tcp_ip_abort_linterval;
3390 		}
3391 	}
3392 
3393 	/*
3394 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3395 	 * processing continues in tcp_rput_other().
3396 	 */
3397 	if (tcp->tcp_family == AF_INET6) {
3398 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3399 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3400 	} else {
3401 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3402 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3403 	}
3404 	/*
3405 	 * If the bind cannot complete immediately
3406 	 * IP will arrange to call tcp_rput_other
3407 	 * when the bind completes.
3408 	 */
3409 	if (mp != NULL) {
3410 		tcp_rput_other(tcp, mp);
3411 	} else {
3412 		/*
3413 		 * Bind will be resumed later. Need to ensure
3414 		 * that conn doesn't disappear when that happens.
3415 		 * This will be decremented in ip_resume_tcp_bind().
3416 		 */
3417 		CONN_INC_REF(tcp->tcp_connp);
3418 	}
3419 }
3420 
3421 
3422 /*
3423  * If the "bind_to_req_port_only" parameter is set, if the requested port
3424  * number is available, return it, If not return 0
3425  *
3426  * If "bind_to_req_port_only" parameter is not set and
3427  * If the requested port number is available, return it.  If not, return
3428  * the first anonymous port we happen across.  If no anonymous ports are
3429  * available, return 0. addr is the requested local address, if any.
3430  *
3431  * In either case, when succeeding update the tcp_t to record the port number
3432  * and insert it in the bind hash table.
3433  *
3434  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3435  * without setting SO_REUSEADDR. This is needed so that they
3436  * can be viewed as two independent transport protocols.
3437  */
3438 static in_port_t
3439 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3440     int reuseaddr, boolean_t quick_connect,
3441     boolean_t bind_to_req_port_only, boolean_t user_specified)
3442 {
3443 	/* number of times we have run around the loop */
3444 	int count = 0;
3445 	/* maximum number of times to run around the loop */
3446 	int loopmax;
3447 	conn_t *connp = tcp->tcp_connp;
3448 	zoneid_t zoneid = connp->conn_zoneid;
3449 
3450 	/*
3451 	 * Lookup for free addresses is done in a loop and "loopmax"
3452 	 * influences how long we spin in the loop
3453 	 */
3454 	if (bind_to_req_port_only) {
3455 		/*
3456 		 * If the requested port is busy, don't bother to look
3457 		 * for a new one. Setting loop maximum count to 1 has
3458 		 * that effect.
3459 		 */
3460 		loopmax = 1;
3461 	} else {
3462 		/*
3463 		 * If the requested port is busy, look for a free one
3464 		 * in the anonymous port range.
3465 		 * Set loopmax appropriately so that one does not look
3466 		 * forever in the case all of the anonymous ports are in use.
3467 		 */
3468 		if (tcp->tcp_anon_priv_bind) {
3469 			/*
3470 			 * loopmax =
3471 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3472 			 */
3473 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
3474 		} else {
3475 			loopmax = (tcp_largest_anon_port -
3476 			    tcp_smallest_anon_port + 1);
3477 		}
3478 	}
3479 	do {
3480 		uint16_t	lport;
3481 		tf_t		*tbf;
3482 		tcp_t		*ltcp;
3483 		conn_t		*lconnp;
3484 
3485 		lport = htons(port);
3486 
3487 		/*
3488 		 * Ensure that the tcp_t is not currently in the bind hash.
3489 		 * Hold the lock on the hash bucket to ensure that
3490 		 * the duplicate check plus the insertion is an atomic
3491 		 * operation.
3492 		 *
3493 		 * This function does an inline lookup on the bind hash list
3494 		 * Make sure that we access only members of tcp_t
3495 		 * and that we don't look at tcp_tcp, since we are not
3496 		 * doing a CONN_INC_REF.
3497 		 */
3498 		tcp_bind_hash_remove(tcp);
3499 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
3500 		mutex_enter(&tbf->tf_lock);
3501 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3502 		    ltcp = ltcp->tcp_bind_hash) {
3503 			boolean_t not_socket;
3504 			boolean_t exclbind;
3505 
3506 			if (lport != ltcp->tcp_lport)
3507 				continue;
3508 
3509 			lconnp = ltcp->tcp_connp;
3510 
3511 			/*
3512 			 * On a labeled system, we must treat bindings to ports
3513 			 * on shared IP addresses by sockets with MAC exemption
3514 			 * privilege as being in all zones, as there's
3515 			 * otherwise no way to identify the right receiver.
3516 			 */
3517 			if (!IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) &&
3518 			    !lconnp->conn_mac_exempt &&
3519 			    !connp->conn_mac_exempt)
3520 				continue;
3521 
3522 			/*
3523 			 * If TCP_EXCLBIND is set for either the bound or
3524 			 * binding endpoint, the semantics of bind
3525 			 * is changed according to the following.
3526 			 *
3527 			 * spec = specified address (v4 or v6)
3528 			 * unspec = unspecified address (v4 or v6)
3529 			 * A = specified addresses are different for endpoints
3530 			 *
3531 			 * bound	bind to		allowed
3532 			 * -------------------------------------
3533 			 * unspec	unspec		no
3534 			 * unspec	spec		no
3535 			 * spec		unspec		no
3536 			 * spec		spec		yes if A
3537 			 *
3538 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3539 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3540 			 *
3541 			 * Note:
3542 			 *
3543 			 * 1. Because of TLI semantics, an endpoint can go
3544 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3545 			 * TCPS_BOUND, depending on whether it is originally
3546 			 * a listener or not.  That is why we need to check
3547 			 * for states greater than or equal to TCPS_BOUND
3548 			 * here.
3549 			 *
3550 			 * 2. Ideally, we should only check for state equals
3551 			 * to TCPS_LISTEN. And the following check should be
3552 			 * added.
3553 			 *
3554 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3555 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3556 			 *		...
3557 			 * }
3558 			 *
3559 			 * The semantics will be changed to this.  If the
3560 			 * endpoint on the list is in state not equal to
3561 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3562 			 * set, let the bind succeed.
3563 			 *
3564 			 * Because of (1), we cannot do that for TLI
3565 			 * endpoints.  But we can do that for socket endpoints.
3566 			 * If in future, we can change this going back
3567 			 * semantics, we can use the above check for TLI also.
3568 			 */
3569 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3570 			    TCP_IS_SOCKET(tcp));
3571 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3572 
3573 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3574 			    (exclbind && (not_socket ||
3575 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3576 				if (V6_OR_V4_INADDR_ANY(
3577 				    ltcp->tcp_bound_source_v6) ||
3578 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3579 				    IN6_ARE_ADDR_EQUAL(laddr,
3580 				    &ltcp->tcp_bound_source_v6)) {
3581 					break;
3582 				}
3583 				continue;
3584 			}
3585 
3586 			/*
3587 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3588 			 * have disjoint port number spaces, if *_EXCLBIND
3589 			 * is not set and only if the application binds to a
3590 			 * specific port. We use the same autoassigned port
3591 			 * number space for IPv4 and IPv6 sockets.
3592 			 */
3593 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3594 			    bind_to_req_port_only)
3595 				continue;
3596 
3597 			/*
3598 			 * Ideally, we should make sure that the source
3599 			 * address, remote address, and remote port in the
3600 			 * four tuple for this tcp-connection is unique.
3601 			 * However, trying to find out the local source
3602 			 * address would require too much code duplication
3603 			 * with IP, since IP needs needs to have that code
3604 			 * to support userland TCP implementations.
3605 			 */
3606 			if (quick_connect &&
3607 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3608 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3609 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3610 				    &ltcp->tcp_remote_v6)))
3611 				continue;
3612 
3613 			if (!reuseaddr) {
3614 				/*
3615 				 * No socket option SO_REUSEADDR.
3616 				 * If existing port is bound to
3617 				 * a non-wildcard IP address
3618 				 * and the requesting stream is
3619 				 * bound to a distinct
3620 				 * different IP addresses
3621 				 * (non-wildcard, also), keep
3622 				 * going.
3623 				 */
3624 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3625 				    !V6_OR_V4_INADDR_ANY(
3626 				    ltcp->tcp_bound_source_v6) &&
3627 				    !IN6_ARE_ADDR_EQUAL(laddr,
3628 					&ltcp->tcp_bound_source_v6))
3629 					continue;
3630 				if (ltcp->tcp_state >= TCPS_BOUND) {
3631 					/*
3632 					 * This port is being used and
3633 					 * its state is >= TCPS_BOUND,
3634 					 * so we can't bind to it.
3635 					 */
3636 					break;
3637 				}
3638 			} else {
3639 				/*
3640 				 * socket option SO_REUSEADDR is set on the
3641 				 * binding tcp_t.
3642 				 *
3643 				 * If two streams are bound to
3644 				 * same IP address or both addr
3645 				 * and bound source are wildcards
3646 				 * (INADDR_ANY), we want to stop
3647 				 * searching.
3648 				 * We have found a match of IP source
3649 				 * address and source port, which is
3650 				 * refused regardless of the
3651 				 * SO_REUSEADDR setting, so we break.
3652 				 */
3653 				if (IN6_ARE_ADDR_EQUAL(laddr,
3654 				    &ltcp->tcp_bound_source_v6) &&
3655 				    (ltcp->tcp_state == TCPS_LISTEN ||
3656 					ltcp->tcp_state == TCPS_BOUND))
3657 					break;
3658 			}
3659 		}
3660 		if (ltcp != NULL) {
3661 			/* The port number is busy */
3662 			mutex_exit(&tbf->tf_lock);
3663 		} else {
3664 			/*
3665 			 * This port is ours. Insert in fanout and mark as
3666 			 * bound to prevent others from getting the port
3667 			 * number.
3668 			 */
3669 			tcp->tcp_state = TCPS_BOUND;
3670 			tcp->tcp_lport = htons(port);
3671 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3672 
3673 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
3674 			    tcp->tcp_lport)] == tbf);
3675 			tcp_bind_hash_insert(tbf, tcp, 1);
3676 
3677 			mutex_exit(&tbf->tf_lock);
3678 
3679 			/*
3680 			 * We don't want tcp_next_port_to_try to "inherit"
3681 			 * a port number supplied by the user in a bind.
3682 			 */
3683 			if (user_specified)
3684 				return (port);
3685 
3686 			/*
3687 			 * This is the only place where tcp_next_port_to_try
3688 			 * is updated. After the update, it may or may not
3689 			 * be in the valid range.
3690 			 */
3691 			if (!tcp->tcp_anon_priv_bind)
3692 				tcp_next_port_to_try = port + 1;
3693 			return (port);
3694 		}
3695 
3696 		if (tcp->tcp_anon_priv_bind) {
3697 			port = tcp_get_next_priv_port(tcp);
3698 		} else {
3699 			if (count == 0 && user_specified) {
3700 				/*
3701 				 * We may have to return an anonymous port. So
3702 				 * get one to start with.
3703 				 */
3704 				port =
3705 				    tcp_update_next_port(tcp_next_port_to_try,
3706 					tcp, B_TRUE);
3707 				user_specified = B_FALSE;
3708 			} else {
3709 				port = tcp_update_next_port(port + 1, tcp,
3710 				    B_FALSE);
3711 			}
3712 		}
3713 		if (port == 0)
3714 			break;
3715 
3716 		/*
3717 		 * Don't let this loop run forever in the case where
3718 		 * all of the anonymous ports are in use.
3719 		 */
3720 	} while (++count < loopmax);
3721 	return (0);
3722 }
3723 
3724 /*
3725  * We are dying for some reason.  Try to do it gracefully.  (May be called
3726  * as writer.)
3727  *
3728  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3729  * done by a service procedure).
3730  * TBD - Should the return value distinguish between the tcp_t being
3731  * freed and it being reinitialized?
3732  */
3733 static int
3734 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3735 {
3736 	mblk_t	*mp;
3737 	queue_t	*q;
3738 
3739 	TCP_CLD_STAT(tag);
3740 
3741 #if TCP_TAG_CLEAN_DEATH
3742 	tcp->tcp_cleandeathtag = tag;
3743 #endif
3744 
3745 	if (tcp->tcp_fused)
3746 		tcp_unfuse(tcp);
3747 
3748 	if (tcp->tcp_linger_tid != 0 &&
3749 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3750 		tcp_stop_lingering(tcp);
3751 	}
3752 
3753 	ASSERT(tcp != NULL);
3754 	ASSERT((tcp->tcp_family == AF_INET &&
3755 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3756 	    (tcp->tcp_family == AF_INET6 &&
3757 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3758 	    tcp->tcp_ipversion == IPV6_VERSION)));
3759 
3760 	if (TCP_IS_DETACHED(tcp)) {
3761 		if (tcp->tcp_hard_binding) {
3762 			/*
3763 			 * Its an eager that we are dealing with. We close the
3764 			 * eager but in case a conn_ind has already gone to the
3765 			 * listener, let tcp_accept_finish() send a discon_ind
3766 			 * to the listener and drop the last reference. If the
3767 			 * listener doesn't even know about the eager i.e. the
3768 			 * conn_ind hasn't gone up, blow away the eager and drop
3769 			 * the last reference as well. If the conn_ind has gone
3770 			 * up, state should be BOUND. tcp_accept_finish
3771 			 * will figure out that the connection has received a
3772 			 * RST and will send a DISCON_IND to the application.
3773 			 */
3774 			tcp_closei_local(tcp);
3775 			if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
3776 				CONN_DEC_REF(tcp->tcp_connp);
3777 			} else {
3778 				tcp->tcp_state = TCPS_BOUND;
3779 			}
3780 		} else {
3781 			tcp_close_detached(tcp);
3782 		}
3783 		return (0);
3784 	}
3785 
3786 	TCP_STAT(tcp_clean_death_nondetached);
3787 
3788 	/*
3789 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3790 	 * is run) postpone cleaning up the endpoint until service routine
3791 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3792 	 * client_errno since tcp_close uses the client_errno field.
3793 	 */
3794 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3795 		if (err != 0)
3796 			tcp->tcp_client_errno = err;
3797 
3798 		tcp->tcp_deferred_clean_death = B_TRUE;
3799 		return (-1);
3800 	}
3801 
3802 	q = tcp->tcp_rq;
3803 
3804 	/* Trash all inbound data */
3805 	flushq(q, FLUSHALL);
3806 
3807 	/*
3808 	 * If we are at least part way open and there is error
3809 	 * (err==0 implies no error)
3810 	 * notify our client by a T_DISCON_IND.
3811 	 */
3812 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3813 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3814 		    !TCP_IS_SOCKET(tcp)) {
3815 			/*
3816 			 * Send M_FLUSH according to TPI. Because sockets will
3817 			 * (and must) ignore FLUSHR we do that only for TPI
3818 			 * endpoints and sockets in STREAMS mode.
3819 			 */
3820 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3821 		}
3822 		if (tcp->tcp_debug) {
3823 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3824 			    "tcp_clean_death: discon err %d", err);
3825 		}
3826 		mp = mi_tpi_discon_ind(NULL, err, 0);
3827 		if (mp != NULL) {
3828 			putnext(q, mp);
3829 		} else {
3830 			if (tcp->tcp_debug) {
3831 				(void) strlog(TCP_MOD_ID, 0, 1,
3832 				    SL_ERROR|SL_TRACE,
3833 				    "tcp_clean_death, sending M_ERROR");
3834 			}
3835 			(void) putnextctl1(q, M_ERROR, EPROTO);
3836 		}
3837 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3838 			/* SYN_SENT or SYN_RCVD */
3839 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3840 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3841 			/* ESTABLISHED or CLOSE_WAIT */
3842 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3843 		}
3844 	}
3845 
3846 	tcp_reinit(tcp);
3847 	return (-1);
3848 }
3849 
3850 /*
3851  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3852  * to expire, stop the wait and finish the close.
3853  */
3854 static void
3855 tcp_stop_lingering(tcp_t *tcp)
3856 {
3857 	clock_t	delta = 0;
3858 
3859 	tcp->tcp_linger_tid = 0;
3860 	if (tcp->tcp_state > TCPS_LISTEN) {
3861 		tcp_acceptor_hash_remove(tcp);
3862 		if (tcp->tcp_flow_stopped) {
3863 			tcp_clrqfull(tcp);
3864 		}
3865 
3866 		if (tcp->tcp_timer_tid != 0) {
3867 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3868 			tcp->tcp_timer_tid = 0;
3869 		}
3870 		/*
3871 		 * Need to cancel those timers which will not be used when
3872 		 * TCP is detached.  This has to be done before the tcp_wq
3873 		 * is set to the global queue.
3874 		 */
3875 		tcp_timers_stop(tcp);
3876 
3877 
3878 		tcp->tcp_detached = B_TRUE;
3879 		tcp->tcp_rq = tcp_g_q;
3880 		tcp->tcp_wq = WR(tcp_g_q);
3881 
3882 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3883 			tcp_time_wait_append(tcp);
3884 			TCP_DBGSTAT(tcp_detach_time_wait);
3885 			goto finish;
3886 		}
3887 
3888 		/*
3889 		 * If delta is zero the timer event wasn't executed and was
3890 		 * successfully canceled. In this case we need to restart it
3891 		 * with the minimal delta possible.
3892 		 */
3893 		if (delta >= 0) {
3894 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3895 			    delta ? delta : 1);
3896 		}
3897 	} else {
3898 		tcp_closei_local(tcp);
3899 		CONN_DEC_REF(tcp->tcp_connp);
3900 	}
3901 finish:
3902 	/* Signal closing thread that it can complete close */
3903 	mutex_enter(&tcp->tcp_closelock);
3904 	tcp->tcp_detached = B_TRUE;
3905 	tcp->tcp_rq = tcp_g_q;
3906 	tcp->tcp_wq = WR(tcp_g_q);
3907 	tcp->tcp_closed = 1;
3908 	cv_signal(&tcp->tcp_closecv);
3909 	mutex_exit(&tcp->tcp_closelock);
3910 }
3911 
3912 /*
3913  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3914  * expires.
3915  */
3916 static void
3917 tcp_close_linger_timeout(void *arg)
3918 {
3919 	conn_t	*connp = (conn_t *)arg;
3920 	tcp_t 	*tcp = connp->conn_tcp;
3921 
3922 	tcp->tcp_client_errno = ETIMEDOUT;
3923 	tcp_stop_lingering(tcp);
3924 }
3925 
3926 static int
3927 tcp_close(queue_t *q, int flags)
3928 {
3929 	conn_t		*connp = Q_TO_CONN(q);
3930 	tcp_t		*tcp = connp->conn_tcp;
3931 	mblk_t 		*mp = &tcp->tcp_closemp;
3932 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3933 
3934 	ASSERT(WR(q)->q_next == NULL);
3935 	ASSERT(connp->conn_ref >= 2);
3936 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
3937 
3938 	/*
3939 	 * We are being closed as /dev/tcp or /dev/tcp6.
3940 	 *
3941 	 * Mark the conn as closing. ill_pending_mp_add will not
3942 	 * add any mp to the pending mp list, after this conn has
3943 	 * started closing. Same for sq_pending_mp_add
3944 	 */
3945 	mutex_enter(&connp->conn_lock);
3946 	connp->conn_state_flags |= CONN_CLOSING;
3947 	if (connp->conn_oper_pending_ill != NULL)
3948 		conn_ioctl_cleanup_reqd = B_TRUE;
3949 	CONN_INC_REF_LOCKED(connp);
3950 	mutex_exit(&connp->conn_lock);
3951 	tcp->tcp_closeflags = (uint8_t)flags;
3952 	ASSERT(connp->conn_ref >= 3);
3953 
3954 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
3955 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
3956 
3957 	mutex_enter(&tcp->tcp_closelock);
3958 
3959 	while (!tcp->tcp_closed)
3960 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3961 	mutex_exit(&tcp->tcp_closelock);
3962 	/*
3963 	 * In the case of listener streams that have eagers in the q or q0
3964 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3965 	 * tcp_wq of the eagers point to our queues. By waiting for the
3966 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3967 	 * up their queue pointers and also dropped their references to us.
3968 	 */
3969 	if (tcp->tcp_wait_for_eagers) {
3970 		mutex_enter(&connp->conn_lock);
3971 		while (connp->conn_ref != 1) {
3972 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3973 		}
3974 		mutex_exit(&connp->conn_lock);
3975 	}
3976 	/*
3977 	 * ioctl cleanup. The mp is queued in the
3978 	 * ill_pending_mp or in the sq_pending_mp.
3979 	 */
3980 	if (conn_ioctl_cleanup_reqd)
3981 		conn_ioctl_cleanup(connp);
3982 
3983 	qprocsoff(q);
3984 	inet_minor_free(ip_minor_arena, connp->conn_dev);
3985 
3986 	tcp->tcp_cpid = -1;
3987 
3988 	/*
3989 	 * Drop IP's reference on the conn. This is the last reference
3990 	 * on the connp if the state was less than established. If the
3991 	 * connection has gone into timewait state, then we will have
3992 	 * one ref for the TCP and one more ref (total of two) for the
3993 	 * classifier connected hash list (a timewait connections stays
3994 	 * in connected hash till closed).
3995 	 *
3996 	 * We can't assert the references because there might be other
3997 	 * transient reference places because of some walkers or queued
3998 	 * packets in squeue for the timewait state.
3999 	 */
4000 	CONN_DEC_REF(connp);
4001 	q->q_ptr = WR(q)->q_ptr = NULL;
4002 	return (0);
4003 }
4004 
4005 static int
4006 tcpclose_accept(queue_t *q)
4007 {
4008 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4009 
4010 	/*
4011 	 * We had opened an acceptor STREAM for sockfs which is
4012 	 * now being closed due to some error.
4013 	 */
4014 	qprocsoff(q);
4015 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
4016 	q->q_ptr = WR(q)->q_ptr = NULL;
4017 	return (0);
4018 }
4019 
4020 
4021 /*
4022  * Called by streams close routine via squeues when our client blows off her
4023  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4024  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4025  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4026  * acked.
4027  *
4028  * NOTE: tcp_close potentially returns error when lingering.
4029  * However, the stream head currently does not pass these errors
4030  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4031  * errors to the application (from tsleep()) and not errors
4032  * like ECONNRESET caused by receiving a reset packet.
4033  */
4034 
4035 /* ARGSUSED */
4036 static void
4037 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4038 {
4039 	char	*msg;
4040 	conn_t	*connp = (conn_t *)arg;
4041 	tcp_t	*tcp = connp->conn_tcp;
4042 	clock_t	delta = 0;
4043 
4044 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4045 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4046 
4047 	/* Cancel any pending timeout */
4048 	if (tcp->tcp_ordrelid != 0) {
4049 		if (tcp->tcp_timeout) {
4050 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4051 		}
4052 		tcp->tcp_ordrelid = 0;
4053 		tcp->tcp_timeout = B_FALSE;
4054 	}
4055 
4056 	mutex_enter(&tcp->tcp_eager_lock);
4057 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4058 		/* Cleanup for listener */
4059 		tcp_eager_cleanup(tcp, 0);
4060 		tcp->tcp_wait_for_eagers = 1;
4061 	}
4062 	mutex_exit(&tcp->tcp_eager_lock);
4063 
4064 	connp->conn_mdt_ok = B_FALSE;
4065 	tcp->tcp_mdt = B_FALSE;
4066 
4067 	msg = NULL;
4068 	switch (tcp->tcp_state) {
4069 	case TCPS_CLOSED:
4070 	case TCPS_IDLE:
4071 	case TCPS_BOUND:
4072 	case TCPS_LISTEN:
4073 		break;
4074 	case TCPS_SYN_SENT:
4075 		msg = "tcp_close, during connect";
4076 		break;
4077 	case TCPS_SYN_RCVD:
4078 		/*
4079 		 * Close during the connect 3-way handshake
4080 		 * but here there may or may not be pending data
4081 		 * already on queue. Process almost same as in
4082 		 * the ESTABLISHED state.
4083 		 */
4084 		/* FALLTHRU */
4085 	default:
4086 		if (tcp->tcp_fused)
4087 			tcp_unfuse(tcp);
4088 
4089 		/*
4090 		 * If SO_LINGER has set a zero linger time, abort the
4091 		 * connection with a reset.
4092 		 */
4093 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4094 			msg = "tcp_close, zero lingertime";
4095 			break;
4096 		}
4097 
4098 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4099 		/*
4100 		 * Abort connection if there is unread data queued.
4101 		 */
4102 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4103 			msg = "tcp_close, unread data";
4104 			break;
4105 		}
4106 		/*
4107 		 * tcp_hard_bound is now cleared thus all packets go through
4108 		 * tcp_lookup. This fact is used by tcp_detach below.
4109 		 *
4110 		 * We have done a qwait() above which could have possibly
4111 		 * drained more messages in turn causing transition to a
4112 		 * different state. Check whether we have to do the rest
4113 		 * of the processing or not.
4114 		 */
4115 		if (tcp->tcp_state <= TCPS_LISTEN)
4116 			break;
4117 
4118 		/*
4119 		 * Transmit the FIN before detaching the tcp_t.
4120 		 * After tcp_detach returns this queue/perimeter
4121 		 * no longer owns the tcp_t thus others can modify it.
4122 		 */
4123 		(void) tcp_xmit_end(tcp);
4124 
4125 		/*
4126 		 * If lingering on close then wait until the fin is acked,
4127 		 * the SO_LINGER time passes, or a reset is sent/received.
4128 		 */
4129 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4130 		    !(tcp->tcp_fin_acked) &&
4131 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4132 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4133 				tcp->tcp_client_errno = EWOULDBLOCK;
4134 			} else if (tcp->tcp_client_errno == 0) {
4135 
4136 				ASSERT(tcp->tcp_linger_tid == 0);
4137 
4138 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4139 				    tcp_close_linger_timeout,
4140 				    tcp->tcp_lingertime * hz);
4141 
4142 				/* tcp_close_linger_timeout will finish close */
4143 				if (tcp->tcp_linger_tid == 0)
4144 					tcp->tcp_client_errno = ENOSR;
4145 				else
4146 					return;
4147 			}
4148 
4149 			/*
4150 			 * Check if we need to detach or just close
4151 			 * the instance.
4152 			 */
4153 			if (tcp->tcp_state <= TCPS_LISTEN)
4154 				break;
4155 		}
4156 
4157 		/*
4158 		 * Make sure that no other thread will access the tcp_rq of
4159 		 * this instance (through lookups etc.) as tcp_rq will go
4160 		 * away shortly.
4161 		 */
4162 		tcp_acceptor_hash_remove(tcp);
4163 
4164 		if (tcp->tcp_flow_stopped) {
4165 			tcp_clrqfull(tcp);
4166 		}
4167 
4168 		if (tcp->tcp_timer_tid != 0) {
4169 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4170 			tcp->tcp_timer_tid = 0;
4171 		}
4172 		/*
4173 		 * Need to cancel those timers which will not be used when
4174 		 * TCP is detached.  This has to be done before the tcp_wq
4175 		 * is set to the global queue.
4176 		 */
4177 		tcp_timers_stop(tcp);
4178 
4179 		tcp->tcp_detached = B_TRUE;
4180 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4181 			tcp_time_wait_append(tcp);
4182 			TCP_DBGSTAT(tcp_detach_time_wait);
4183 			ASSERT(connp->conn_ref >= 3);
4184 			goto finish;
4185 		}
4186 
4187 		/*
4188 		 * If delta is zero the timer event wasn't executed and was
4189 		 * successfully canceled. In this case we need to restart it
4190 		 * with the minimal delta possible.
4191 		 */
4192 		if (delta >= 0)
4193 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4194 			    delta ? delta : 1);
4195 
4196 		ASSERT(connp->conn_ref >= 3);
4197 		goto finish;
4198 	}
4199 
4200 	/* Detach did not complete. Still need to remove q from stream. */
4201 	if (msg) {
4202 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4203 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4204 			BUMP_MIB(&tcp_mib, tcpEstabResets);
4205 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4206 		    tcp->tcp_state == TCPS_SYN_RCVD)
4207 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
4208 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4209 	}
4210 
4211 	tcp_closei_local(tcp);
4212 	CONN_DEC_REF(connp);
4213 	ASSERT(connp->conn_ref >= 2);
4214 
4215 finish:
4216 	/*
4217 	 * Although packets are always processed on the correct
4218 	 * tcp's perimeter and access is serialized via squeue's,
4219 	 * IP still needs a queue when sending packets in time_wait
4220 	 * state so use WR(tcp_g_q) till ip_output() can be
4221 	 * changed to deal with just connp. For read side, we
4222 	 * could have set tcp_rq to NULL but there are some cases
4223 	 * in tcp_rput_data() from early days of this code which
4224 	 * do a putnext without checking if tcp is closed. Those
4225 	 * need to be identified before both tcp_rq and tcp_wq
4226 	 * can be set to NULL and tcp_q_q can disappear forever.
4227 	 */
4228 	mutex_enter(&tcp->tcp_closelock);
4229 	/*
4230 	 * Don't change the queues in the case of a listener that has
4231 	 * eagers in its q or q0. It could surprise the eagers.
4232 	 * Instead wait for the eagers outside the squeue.
4233 	 */
4234 	if (!tcp->tcp_wait_for_eagers) {
4235 		tcp->tcp_detached = B_TRUE;
4236 		tcp->tcp_rq = tcp_g_q;
4237 		tcp->tcp_wq = WR(tcp_g_q);
4238 	}
4239 
4240 	/* Signal tcp_close() to finish closing. */
4241 	tcp->tcp_closed = 1;
4242 	cv_signal(&tcp->tcp_closecv);
4243 	mutex_exit(&tcp->tcp_closelock);
4244 }
4245 
4246 
4247 /*
4248  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4249  * Some stream heads get upset if they see these later on as anything but NULL.
4250  */
4251 static void
4252 tcp_close_mpp(mblk_t **mpp)
4253 {
4254 	mblk_t	*mp;
4255 
4256 	if ((mp = *mpp) != NULL) {
4257 		do {
4258 			mp->b_next = NULL;
4259 			mp->b_prev = NULL;
4260 		} while ((mp = mp->b_cont) != NULL);
4261 
4262 		mp = *mpp;
4263 		*mpp = NULL;
4264 		freemsg(mp);
4265 	}
4266 }
4267 
4268 /* Do detached close. */
4269 static void
4270 tcp_close_detached(tcp_t *tcp)
4271 {
4272 	if (tcp->tcp_fused)
4273 		tcp_unfuse(tcp);
4274 
4275 	/*
4276 	 * Clustering code serializes TCP disconnect callbacks and
4277 	 * cluster tcp list walks by blocking a TCP disconnect callback
4278 	 * if a cluster tcp list walk is in progress. This ensures
4279 	 * accurate accounting of TCPs in the cluster code even though
4280 	 * the TCP list walk itself is not atomic.
4281 	 */
4282 	tcp_closei_local(tcp);
4283 	CONN_DEC_REF(tcp->tcp_connp);
4284 }
4285 
4286 /*
4287  * Stop all TCP timers, and free the timer mblks if requested.
4288  */
4289 void
4290 tcp_timers_stop(tcp_t *tcp)
4291 {
4292 	if (tcp->tcp_timer_tid != 0) {
4293 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4294 		tcp->tcp_timer_tid = 0;
4295 	}
4296 	if (tcp->tcp_ka_tid != 0) {
4297 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4298 		tcp->tcp_ka_tid = 0;
4299 	}
4300 	if (tcp->tcp_ack_tid != 0) {
4301 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4302 		tcp->tcp_ack_tid = 0;
4303 	}
4304 	if (tcp->tcp_push_tid != 0) {
4305 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4306 		tcp->tcp_push_tid = 0;
4307 	}
4308 }
4309 
4310 /*
4311  * The tcp_t is going away. Remove it from all lists and set it
4312  * to TCPS_CLOSED. The freeing up of memory is deferred until
4313  * tcp_inactive. This is needed since a thread in tcp_rput might have
4314  * done a CONN_INC_REF on this structure before it was removed from the
4315  * hashes.
4316  */
4317 static void
4318 tcp_closei_local(tcp_t *tcp)
4319 {
4320 	ire_t 	*ire;
4321 	conn_t	*connp = tcp->tcp_connp;
4322 
4323 	if (!TCP_IS_SOCKET(tcp))
4324 		tcp_acceptor_hash_remove(tcp);
4325 
4326 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
4327 	tcp->tcp_ibsegs = 0;
4328 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
4329 	tcp->tcp_obsegs = 0;
4330 
4331 	/*
4332 	 * If we are an eager connection hanging off a listener that
4333 	 * hasn't formally accepted the connection yet, get off his
4334 	 * list and blow off any data that we have accumulated.
4335 	 */
4336 	if (tcp->tcp_listener != NULL) {
4337 		tcp_t	*listener = tcp->tcp_listener;
4338 		mutex_enter(&listener->tcp_eager_lock);
4339 		/*
4340 		 * tcp_eager_conn_ind == NULL means that the
4341 		 * conn_ind has already gone to listener. At
4342 		 * this point, eager will be closed but we
4343 		 * leave it in listeners eager list so that
4344 		 * if listener decides to close without doing
4345 		 * accept, we can clean this up. In tcp_wput_accept
4346 		 * we take case of the case of accept on closed
4347 		 * eager.
4348 		 */
4349 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4350 			tcp_eager_unlink(tcp);
4351 			mutex_exit(&listener->tcp_eager_lock);
4352 			/*
4353 			 * We don't want to have any pointers to the
4354 			 * listener queue, after we have released our
4355 			 * reference on the listener
4356 			 */
4357 			tcp->tcp_rq = tcp_g_q;
4358 			tcp->tcp_wq = WR(tcp_g_q);
4359 			CONN_DEC_REF(listener->tcp_connp);
4360 		} else {
4361 			mutex_exit(&listener->tcp_eager_lock);
4362 		}
4363 	}
4364 
4365 	/* Stop all the timers */
4366 	tcp_timers_stop(tcp);
4367 
4368 	if (tcp->tcp_state == TCPS_LISTEN) {
4369 		if (tcp->tcp_ip_addr_cache) {
4370 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4371 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4372 			tcp->tcp_ip_addr_cache = NULL;
4373 		}
4374 	}
4375 	if (tcp->tcp_flow_stopped)
4376 		tcp_clrqfull(tcp);
4377 
4378 	tcp_bind_hash_remove(tcp);
4379 	/*
4380 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4381 	 * is trying to remove this tcp from the time wait list, we will
4382 	 * block in tcp_time_wait_remove while trying to acquire the
4383 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4384 	 * requires the ipcl_hash_remove to be ordered after the
4385 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4386 	 */
4387 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4388 		tcp_time_wait_remove(tcp, NULL);
4389 	CL_INET_DISCONNECT(tcp);
4390 	ipcl_hash_remove(connp);
4391 
4392 	/*
4393 	 * Delete the cached ire in conn_ire_cache and also mark
4394 	 * the conn as CONDEMNED
4395 	 */
4396 	mutex_enter(&connp->conn_lock);
4397 	connp->conn_state_flags |= CONN_CONDEMNED;
4398 	ire = connp->conn_ire_cache;
4399 	connp->conn_ire_cache = NULL;
4400 	mutex_exit(&connp->conn_lock);
4401 	if (ire != NULL)
4402 		IRE_REFRELE_NOTR(ire);
4403 
4404 	/* Need to cleanup any pending ioctls */
4405 	ASSERT(tcp->tcp_time_wait_next == NULL);
4406 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4407 	ASSERT(tcp->tcp_time_wait_expire == 0);
4408 	tcp->tcp_state = TCPS_CLOSED;
4409 
4410 	/* Release any SSL context */
4411 	if (tcp->tcp_kssl_ent != NULL) {
4412 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4413 		tcp->tcp_kssl_ent = NULL;
4414 	}
4415 	if (tcp->tcp_kssl_ctx != NULL) {
4416 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4417 		tcp->tcp_kssl_ctx = NULL;
4418 	}
4419 	tcp->tcp_kssl_pending = B_FALSE;
4420 }
4421 
4422 /*
4423  * tcp is dying (called from ipcl_conn_destroy and error cases).
4424  * Free the tcp_t in either case.
4425  */
4426 void
4427 tcp_free(tcp_t *tcp)
4428 {
4429 	mblk_t	*mp;
4430 	ip6_pkt_t	*ipp;
4431 
4432 	ASSERT(tcp != NULL);
4433 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4434 
4435 	tcp->tcp_rq = NULL;
4436 	tcp->tcp_wq = NULL;
4437 
4438 	tcp_close_mpp(&tcp->tcp_xmit_head);
4439 	tcp_close_mpp(&tcp->tcp_reass_head);
4440 	if (tcp->tcp_rcv_list != NULL) {
4441 		/* Free b_next chain */
4442 		tcp_close_mpp(&tcp->tcp_rcv_list);
4443 	}
4444 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4445 		freemsg(mp);
4446 	}
4447 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4448 		freemsg(mp);
4449 	}
4450 
4451 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4452 		freeb(tcp->tcp_fused_sigurg_mp);
4453 		tcp->tcp_fused_sigurg_mp = NULL;
4454 	}
4455 
4456 	if (tcp->tcp_sack_info != NULL) {
4457 		if (tcp->tcp_notsack_list != NULL) {
4458 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4459 		}
4460 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4461 	}
4462 
4463 	if (tcp->tcp_hopopts != NULL) {
4464 		mi_free(tcp->tcp_hopopts);
4465 		tcp->tcp_hopopts = NULL;
4466 		tcp->tcp_hopoptslen = 0;
4467 	}
4468 	ASSERT(tcp->tcp_hopoptslen == 0);
4469 	if (tcp->tcp_dstopts != NULL) {
4470 		mi_free(tcp->tcp_dstopts);
4471 		tcp->tcp_dstopts = NULL;
4472 		tcp->tcp_dstoptslen = 0;
4473 	}
4474 	ASSERT(tcp->tcp_dstoptslen == 0);
4475 	if (tcp->tcp_rtdstopts != NULL) {
4476 		mi_free(tcp->tcp_rtdstopts);
4477 		tcp->tcp_rtdstopts = NULL;
4478 		tcp->tcp_rtdstoptslen = 0;
4479 	}
4480 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4481 	if (tcp->tcp_rthdr != NULL) {
4482 		mi_free(tcp->tcp_rthdr);
4483 		tcp->tcp_rthdr = NULL;
4484 		tcp->tcp_rthdrlen = 0;
4485 	}
4486 	ASSERT(tcp->tcp_rthdrlen == 0);
4487 
4488 	ipp = &tcp->tcp_sticky_ipp;
4489 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4490 	    IPPF_RTHDR))
4491 		ip6_pkt_free(ipp);
4492 
4493 	/*
4494 	 * Free memory associated with the tcp/ip header template.
4495 	 */
4496 
4497 	if (tcp->tcp_iphc != NULL)
4498 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4499 
4500 	/*
4501 	 * Following is really a blowing away a union.
4502 	 * It happens to have exactly two members of identical size
4503 	 * the following code is enough.
4504 	 */
4505 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4506 
4507 	if (tcp->tcp_tracebuf != NULL) {
4508 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4509 		tcp->tcp_tracebuf = NULL;
4510 	}
4511 }
4512 
4513 
4514 /*
4515  * Put a connection confirmation message upstream built from the
4516  * address information within 'iph' and 'tcph'.  Report our success or failure.
4517  */
4518 static boolean_t
4519 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4520     mblk_t **defermp)
4521 {
4522 	sin_t	sin;
4523 	sin6_t	sin6;
4524 	mblk_t	*mp;
4525 	char	*optp = NULL;
4526 	int	optlen = 0;
4527 	cred_t	*cr;
4528 
4529 	if (defermp != NULL)
4530 		*defermp = NULL;
4531 
4532 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4533 		/*
4534 		 * Return in T_CONN_CON results of option negotiation through
4535 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4536 		 * negotiation, then what is received from remote end needs
4537 		 * to be taken into account but there is no such thing (yet?)
4538 		 * in our TCP/IP.
4539 		 * Note: We do not use mi_offset_param() here as
4540 		 * tcp_opts_conn_req contents do not directly come from
4541 		 * an application and are either generated in kernel or
4542 		 * from user input that was already verified.
4543 		 */
4544 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4545 		optp = (char *)(mp->b_rptr +
4546 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4547 		optlen = (int)
4548 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4549 	}
4550 
4551 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4552 		ipha_t *ipha = (ipha_t *)iphdr;
4553 
4554 		/* packet is IPv4 */
4555 		if (tcp->tcp_family == AF_INET) {
4556 			sin = sin_null;
4557 			sin.sin_addr.s_addr = ipha->ipha_src;
4558 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4559 			sin.sin_family = AF_INET;
4560 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4561 			    (int)sizeof (sin_t), optp, optlen);
4562 		} else {
4563 			sin6 = sin6_null;
4564 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4565 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4566 			sin6.sin6_family = AF_INET6;
4567 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4568 			    (int)sizeof (sin6_t), optp, optlen);
4569 
4570 		}
4571 	} else {
4572 		ip6_t	*ip6h = (ip6_t *)iphdr;
4573 
4574 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4575 		ASSERT(tcp->tcp_family == AF_INET6);
4576 		sin6 = sin6_null;
4577 		sin6.sin6_addr = ip6h->ip6_src;
4578 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4579 		sin6.sin6_family = AF_INET6;
4580 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4581 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4582 		    (int)sizeof (sin6_t), optp, optlen);
4583 	}
4584 
4585 	if (!mp)
4586 		return (B_FALSE);
4587 
4588 	if ((cr = DB_CRED(idmp)) != NULL) {
4589 		mblk_setcred(mp, cr);
4590 		DB_CPID(mp) = DB_CPID(idmp);
4591 	}
4592 
4593 	if (defermp == NULL)
4594 		putnext(tcp->tcp_rq, mp);
4595 	else
4596 		*defermp = mp;
4597 
4598 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4599 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4600 	return (B_TRUE);
4601 }
4602 
4603 /*
4604  * Defense for the SYN attack -
4605  * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
4606  *    one that doesn't have the dontdrop bit set.
4607  * 2. Don't drop a SYN request before its first timeout. This gives every
4608  *    request at least til the first timeout to complete its 3-way handshake.
4609  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4610  *    requests currently on the queue that has timed out. This will be used
4611  *    as an indicator of whether an attack is under way, so that appropriate
4612  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4613  *    either when eager goes into ESTABLISHED, or gets freed up.)
4614  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4615  *    # of timeout drops back to <= q0len/32 => SYN alert off
4616  */
4617 static boolean_t
4618 tcp_drop_q0(tcp_t *tcp)
4619 {
4620 	tcp_t	*eager;
4621 
4622 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4623 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4624 	/*
4625 	 * New one is added after next_q0 so prev_q0 points to the oldest
4626 	 * Also do not drop any established connections that are deferred on
4627 	 * q0 due to q being full
4628 	 */
4629 
4630 	eager = tcp->tcp_eager_prev_q0;
4631 	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
4632 		eager = eager->tcp_eager_prev_q0;
4633 		if (eager == tcp) {
4634 			eager = tcp->tcp_eager_prev_q0;
4635 			break;
4636 		}
4637 	}
4638 	if (eager->tcp_syn_rcvd_timeout == 0)
4639 		return (B_FALSE);
4640 
4641 	if (tcp->tcp_debug) {
4642 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4643 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4644 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
4645 		    tcp->tcp_conn_req_cnt_q0,
4646 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4647 	}
4648 
4649 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
4650 
4651 	/*
4652 	 * need to do refhold here because the selected eager could
4653 	 * be removed by someone else if we release the eager lock.
4654 	 */
4655 	CONN_INC_REF(eager->tcp_connp);
4656 	mutex_exit(&tcp->tcp_eager_lock);
4657 
4658 	/* Mark the IRE created for this SYN request temporary */
4659 	tcp_ip_ire_mark_advice(eager);
4660 	(void) tcp_clean_death(eager, ETIMEDOUT, 5);
4661 	CONN_DEC_REF(eager->tcp_connp);
4662 
4663 	mutex_enter(&tcp->tcp_eager_lock);
4664 	return (B_TRUE);
4665 }
4666 
4667 int
4668 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4669     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4670 {
4671 	tcp_t 		*ltcp = lconnp->conn_tcp;
4672 	tcp_t		*tcp = connp->conn_tcp;
4673 	mblk_t		*tpi_mp;
4674 	ipha_t		*ipha;
4675 	ip6_t		*ip6h;
4676 	sin6_t 		sin6;
4677 	in6_addr_t 	v6dst;
4678 	int		err;
4679 	int		ifindex = 0;
4680 	cred_t		*cr;
4681 
4682 	if (ipvers == IPV4_VERSION) {
4683 		ipha = (ipha_t *)mp->b_rptr;
4684 
4685 		connp->conn_send = ip_output;
4686 		connp->conn_recv = tcp_input;
4687 
4688 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4689 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4690 
4691 		sin6 = sin6_null;
4692 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4693 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4694 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4695 		sin6.sin6_family = AF_INET6;
4696 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4697 		    lconnp->conn_zoneid);
4698 		if (tcp->tcp_recvdstaddr) {
4699 			sin6_t	sin6d;
4700 
4701 			sin6d = sin6_null;
4702 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4703 			    &sin6d.sin6_addr);
4704 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4705 			sin6d.sin6_family = AF_INET;
4706 			tpi_mp = mi_tpi_extconn_ind(NULL,
4707 			    (char *)&sin6d, sizeof (sin6_t),
4708 			    (char *)&tcp,
4709 			    (t_scalar_t)sizeof (intptr_t),
4710 			    (char *)&sin6d, sizeof (sin6_t),
4711 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4712 		} else {
4713 			tpi_mp = mi_tpi_conn_ind(NULL,
4714 			    (char *)&sin6, sizeof (sin6_t),
4715 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4716 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4717 		}
4718 	} else {
4719 		ip6h = (ip6_t *)mp->b_rptr;
4720 
4721 		connp->conn_send = ip_output_v6;
4722 		connp->conn_recv = tcp_input;
4723 
4724 		connp->conn_srcv6 = ip6h->ip6_dst;
4725 		connp->conn_remv6 = ip6h->ip6_src;
4726 
4727 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4728 		ifindex = (int)DB_CKSUMSTUFF(mp);
4729 		DB_CKSUMSTUFF(mp) = 0;
4730 
4731 		sin6 = sin6_null;
4732 		sin6.sin6_addr = ip6h->ip6_src;
4733 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4734 		sin6.sin6_family = AF_INET6;
4735 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4736 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4737 		    lconnp->conn_zoneid);
4738 
4739 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4740 			/* Pass up the scope_id of remote addr */
4741 			sin6.sin6_scope_id = ifindex;
4742 		} else {
4743 			sin6.sin6_scope_id = 0;
4744 		}
4745 		if (tcp->tcp_recvdstaddr) {
4746 			sin6_t	sin6d;
4747 
4748 			sin6d = sin6_null;
4749 			sin6.sin6_addr = ip6h->ip6_dst;
4750 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4751 			sin6d.sin6_family = AF_INET;
4752 			tpi_mp = mi_tpi_extconn_ind(NULL,
4753 			    (char *)&sin6d, sizeof (sin6_t),
4754 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4755 			    (char *)&sin6d, sizeof (sin6_t),
4756 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4757 		} else {
4758 			tpi_mp = mi_tpi_conn_ind(NULL,
4759 			    (char *)&sin6, sizeof (sin6_t),
4760 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4761 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4762 		}
4763 	}
4764 
4765 	if (tpi_mp == NULL)
4766 		return (ENOMEM);
4767 
4768 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4769 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4770 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4771 	connp->conn_fully_bound = B_FALSE;
4772 
4773 	if (tcp_trace)
4774 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4775 
4776 	/* Inherit information from the "parent" */
4777 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4778 	tcp->tcp_family = ltcp->tcp_family;
4779 	tcp->tcp_wq = ltcp->tcp_wq;
4780 	tcp->tcp_rq = ltcp->tcp_rq;
4781 	tcp->tcp_mss = tcp_mss_def_ipv6;
4782 	tcp->tcp_detached = B_TRUE;
4783 	if ((err = tcp_init_values(tcp)) != 0) {
4784 		freemsg(tpi_mp);
4785 		return (err);
4786 	}
4787 
4788 	if (ipvers == IPV4_VERSION) {
4789 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4790 			freemsg(tpi_mp);
4791 			return (err);
4792 		}
4793 		ASSERT(tcp->tcp_ipha != NULL);
4794 	} else {
4795 		/* ifindex must be already set */
4796 		ASSERT(ifindex != 0);
4797 
4798 		if (ltcp->tcp_bound_if != 0) {
4799 			/*
4800 			 * Set newtcp's bound_if equal to
4801 			 * listener's value. If ifindex is
4802 			 * not the same as ltcp->tcp_bound_if,
4803 			 * it must be a packet for the ipmp group
4804 			 * of interfaces
4805 			 */
4806 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4807 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4808 			tcp->tcp_bound_if = ifindex;
4809 		}
4810 
4811 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4812 		tcp->tcp_recvifindex = 0;
4813 		tcp->tcp_recvhops = 0xffffffffU;
4814 		ASSERT(tcp->tcp_ip6h != NULL);
4815 	}
4816 
4817 	tcp->tcp_lport = ltcp->tcp_lport;
4818 
4819 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4820 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4821 			/*
4822 			 * Listener had options of some sort; eager inherits.
4823 			 * Free up the eager template and allocate one
4824 			 * of the right size.
4825 			 */
4826 			if (tcp->tcp_hdr_grown) {
4827 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4828 			} else {
4829 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4830 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4831 			}
4832 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4833 			    KM_NOSLEEP);
4834 			if (tcp->tcp_iphc == NULL) {
4835 				tcp->tcp_iphc_len = 0;
4836 				freemsg(tpi_mp);
4837 				return (ENOMEM);
4838 			}
4839 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4840 			tcp->tcp_hdr_grown = B_TRUE;
4841 		}
4842 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4843 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4844 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4845 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4846 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4847 
4848 		/*
4849 		 * Copy the IP+TCP header template from listener to eager
4850 		 */
4851 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4852 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4853 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4854 			    IPPROTO_RAW) {
4855 				tcp->tcp_ip6h =
4856 				    (ip6_t *)(tcp->tcp_iphc +
4857 					sizeof (ip6i_t));
4858 			} else {
4859 				tcp->tcp_ip6h =
4860 				    (ip6_t *)(tcp->tcp_iphc);
4861 			}
4862 			tcp->tcp_ipha = NULL;
4863 		} else {
4864 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4865 			tcp->tcp_ip6h = NULL;
4866 		}
4867 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4868 		    tcp->tcp_ip_hdr_len);
4869 	} else {
4870 		/*
4871 		 * only valid case when ipversion of listener and
4872 		 * eager differ is when listener is IPv6 and
4873 		 * eager is IPv4.
4874 		 * Eager header template has been initialized to the
4875 		 * maximum v4 header sizes, which includes space for
4876 		 * TCP and IP options.
4877 		 */
4878 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4879 		    (tcp->tcp_ipversion == IPV4_VERSION));
4880 		ASSERT(tcp->tcp_iphc_len >=
4881 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4882 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4883 		/* copy IP header fields individually */
4884 		tcp->tcp_ipha->ipha_ttl =
4885 		    ltcp->tcp_ip6h->ip6_hops;
4886 		bcopy(ltcp->tcp_tcph->th_lport,
4887 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4888 	}
4889 
4890 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4891 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4892 	    sizeof (in_port_t));
4893 
4894 	if (ltcp->tcp_lport == 0) {
4895 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4896 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4897 		    sizeof (in_port_t));
4898 	}
4899 
4900 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4901 		ASSERT(ipha != NULL);
4902 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4903 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4904 
4905 		/* Source routing option copyover (reverse it) */
4906 		if (tcp_rev_src_routes)
4907 			tcp_opt_reverse(tcp, ipha);
4908 	} else {
4909 		ASSERT(ip6h != NULL);
4910 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4911 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4912 	}
4913 
4914 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4915 	/*
4916 	 * If the SYN contains a credential, it's a loopback packet; attach
4917 	 * the credential to the TPI message.
4918 	 */
4919 	if ((cr = DB_CRED(idmp)) != NULL) {
4920 		mblk_setcred(tpi_mp, cr);
4921 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4922 	}
4923 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4924 
4925 	/* Inherit the listener's SSL protection state */
4926 
4927 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4928 		kssl_hold_ent(tcp->tcp_kssl_ent);
4929 		tcp->tcp_kssl_pending = B_TRUE;
4930 	}
4931 
4932 	return (0);
4933 }
4934 
4935 
4936 int
4937 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4938     tcph_t *tcph, mblk_t *idmp)
4939 {
4940 	tcp_t 		*ltcp = lconnp->conn_tcp;
4941 	tcp_t		*tcp = connp->conn_tcp;
4942 	sin_t		sin;
4943 	mblk_t		*tpi_mp = NULL;
4944 	int		err;
4945 	cred_t		*cr;
4946 
4947 	sin = sin_null;
4948 	sin.sin_addr.s_addr = ipha->ipha_src;
4949 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4950 	sin.sin_family = AF_INET;
4951 	if (ltcp->tcp_recvdstaddr) {
4952 		sin_t	sind;
4953 
4954 		sind = sin_null;
4955 		sind.sin_addr.s_addr = ipha->ipha_dst;
4956 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4957 		sind.sin_family = AF_INET;
4958 		tpi_mp = mi_tpi_extconn_ind(NULL,
4959 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4960 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4961 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4962 	} else {
4963 		tpi_mp = mi_tpi_conn_ind(NULL,
4964 		    (char *)&sin, sizeof (sin_t),
4965 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4966 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4967 	}
4968 
4969 	if (tpi_mp == NULL) {
4970 		return (ENOMEM);
4971 	}
4972 
4973 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4974 	connp->conn_send = ip_output;
4975 	connp->conn_recv = tcp_input;
4976 	connp->conn_fully_bound = B_FALSE;
4977 
4978 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4979 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4980 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4981 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4982 
4983 	if (tcp_trace) {
4984 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4985 	}
4986 
4987 	/* Inherit information from the "parent" */
4988 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4989 	tcp->tcp_family = ltcp->tcp_family;
4990 	tcp->tcp_wq = ltcp->tcp_wq;
4991 	tcp->tcp_rq = ltcp->tcp_rq;
4992 	tcp->tcp_mss = tcp_mss_def_ipv4;
4993 	tcp->tcp_detached = B_TRUE;
4994 	if ((err = tcp_init_values(tcp)) != 0) {
4995 		freemsg(tpi_mp);
4996 		return (err);
4997 	}
4998 
4999 	/*
5000 	 * Let's make sure that eager tcp template has enough space to
5001 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5002 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5003 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5004 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5005 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5006 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5007 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5008 	 */
5009 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5010 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5011 
5012 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5013 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5014 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5015 	tcp->tcp_ttl = ltcp->tcp_ttl;
5016 	tcp->tcp_tos = ltcp->tcp_tos;
5017 
5018 	/* Copy the IP+TCP header template from listener to eager */
5019 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5020 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5021 	tcp->tcp_ip6h = NULL;
5022 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5023 	    tcp->tcp_ip_hdr_len);
5024 
5025 	/* Initialize the IP addresses and Ports */
5026 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5027 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5028 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5029 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5030 
5031 	/* Source routing option copyover (reverse it) */
5032 	if (tcp_rev_src_routes)
5033 		tcp_opt_reverse(tcp, ipha);
5034 
5035 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5036 
5037 	/*
5038 	 * If the SYN contains a credential, it's a loopback packet; attach
5039 	 * the credential to the TPI message.
5040 	 */
5041 	if ((cr = DB_CRED(idmp)) != NULL) {
5042 		mblk_setcred(tpi_mp, cr);
5043 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5044 	}
5045 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5046 
5047 	/* Inherit the listener's SSL protection state */
5048 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5049 		kssl_hold_ent(tcp->tcp_kssl_ent);
5050 		tcp->tcp_kssl_pending = B_TRUE;
5051 	}
5052 
5053 	return (0);
5054 }
5055 
5056 /*
5057  * sets up conn for ipsec.
5058  * if the first mblk is M_CTL it is consumed and mpp is updated.
5059  * in case of error mpp is freed.
5060  */
5061 conn_t *
5062 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5063 {
5064 	conn_t 		*connp = tcp->tcp_connp;
5065 	conn_t 		*econnp;
5066 	squeue_t 	*new_sqp;
5067 	mblk_t 		*first_mp = *mpp;
5068 	mblk_t		*mp = *mpp;
5069 	boolean_t	mctl_present = B_FALSE;
5070 	uint_t		ipvers;
5071 
5072 	econnp = tcp_get_conn(sqp);
5073 	if (econnp == NULL) {
5074 		freemsg(first_mp);
5075 		return (NULL);
5076 	}
5077 	if (DB_TYPE(mp) == M_CTL) {
5078 		if (mp->b_cont == NULL ||
5079 		    mp->b_cont->b_datap->db_type != M_DATA) {
5080 			freemsg(first_mp);
5081 			return (NULL);
5082 		}
5083 		mp = mp->b_cont;
5084 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5085 			freemsg(first_mp);
5086 			return (NULL);
5087 		}
5088 
5089 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5090 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5091 		mctl_present = B_TRUE;
5092 	} else {
5093 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5094 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5095 	}
5096 
5097 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5098 	DB_CKSUMSTART(mp) = 0;
5099 
5100 	ASSERT(OK_32PTR(mp->b_rptr));
5101 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5102 	if (ipvers == IPV4_VERSION) {
5103 		uint16_t  	*up;
5104 		uint32_t	ports;
5105 		ipha_t		*ipha;
5106 
5107 		ipha = (ipha_t *)mp->b_rptr;
5108 		up = (uint16_t *)((uchar_t *)ipha +
5109 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5110 		ports = *(uint32_t *)up;
5111 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5112 		    ipha->ipha_dst, ipha->ipha_src, ports);
5113 	} else {
5114 		uint16_t  	*up;
5115 		uint32_t	ports;
5116 		uint16_t	ip_hdr_len;
5117 		uint8_t		*nexthdrp;
5118 		ip6_t 		*ip6h;
5119 		tcph_t		*tcph;
5120 
5121 		ip6h = (ip6_t *)mp->b_rptr;
5122 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5123 			ip_hdr_len = IPV6_HDR_LEN;
5124 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5125 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5126 			CONN_DEC_REF(econnp);
5127 			freemsg(first_mp);
5128 			return (NULL);
5129 		}
5130 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5131 		up = (uint16_t *)tcph->th_lport;
5132 		ports = *(uint32_t *)up;
5133 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5134 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5135 	}
5136 
5137 	/*
5138 	 * The caller already ensured that there is a sqp present.
5139 	 */
5140 	econnp->conn_sqp = new_sqp;
5141 
5142 	if (connp->conn_policy != NULL) {
5143 		ipsec_in_t *ii;
5144 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5145 		ASSERT(ii->ipsec_in_policy == NULL);
5146 		IPPH_REFHOLD(connp->conn_policy);
5147 		ii->ipsec_in_policy = connp->conn_policy;
5148 
5149 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5150 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5151 			CONN_DEC_REF(econnp);
5152 			freemsg(first_mp);
5153 			return (NULL);
5154 		}
5155 	}
5156 
5157 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5158 		CONN_DEC_REF(econnp);
5159 		freemsg(first_mp);
5160 		return (NULL);
5161 	}
5162 
5163 	/*
5164 	 * If we know we have some policy, pass the "IPSEC"
5165 	 * options size TCP uses this adjust the MSS.
5166 	 */
5167 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5168 	if (mctl_present) {
5169 		freeb(first_mp);
5170 		*mpp = mp;
5171 	}
5172 
5173 	return (econnp);
5174 }
5175 
5176 /*
5177  * tcp_get_conn/tcp_free_conn
5178  *
5179  * tcp_get_conn is used to get a clean tcp connection structure.
5180  * It tries to reuse the connections put on the freelist by the
5181  * time_wait_collector failing which it goes to kmem_cache. This
5182  * way has two benefits compared to just allocating from and
5183  * freeing to kmem_cache.
5184  * 1) The time_wait_collector can free (which includes the cleanup)
5185  * outside the squeue. So when the interrupt comes, we have a clean
5186  * connection sitting in the freelist. Obviously, this buys us
5187  * performance.
5188  *
5189  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5190  * has multiple disadvantages - tying up the squeue during alloc, and the
5191  * fact that IPSec policy initialization has to happen here which
5192  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5193  * But allocating the conn/tcp in IP land is also not the best since
5194  * we can't check the 'q' and 'q0' which are protected by squeue and
5195  * blindly allocate memory which might have to be freed here if we are
5196  * not allowed to accept the connection. By using the freelist and
5197  * putting the conn/tcp back in freelist, we don't pay a penalty for
5198  * allocating memory without checking 'q/q0' and freeing it if we can't
5199  * accept the connection.
5200  *
5201  * Care should be taken to put the conn back in the same squeue's freelist
5202  * from which it was allocated. Best results are obtained if conn is
5203  * allocated from listener's squeue and freed to the same. Time wait
5204  * collector will free up the freelist is the connection ends up sitting
5205  * there for too long.
5206  */
5207 void *
5208 tcp_get_conn(void *arg)
5209 {
5210 	tcp_t			*tcp = NULL;
5211 	conn_t			*connp = NULL;
5212 	squeue_t		*sqp = (squeue_t *)arg;
5213 	tcp_squeue_priv_t 	*tcp_time_wait;
5214 
5215 	tcp_time_wait =
5216 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5217 
5218 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5219 	tcp = tcp_time_wait->tcp_free_list;
5220 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5221 	if (tcp != NULL) {
5222 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5223 		tcp_time_wait->tcp_free_list_cnt--;
5224 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5225 		tcp->tcp_time_wait_next = NULL;
5226 		connp = tcp->tcp_connp;
5227 		connp->conn_flags |= IPCL_REUSED;
5228 		return ((void *)connp);
5229 	}
5230 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5231 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
5232 		return (NULL);
5233 	return ((void *)connp);
5234 }
5235 
5236 /*
5237  * Update the cached label for the given tcp_t.  This should be called once per
5238  * connection, and before any packets are sent or tcp_process_options is
5239  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5240  */
5241 static boolean_t
5242 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5243 {
5244 	conn_t *connp = tcp->tcp_connp;
5245 
5246 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5247 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5248 		int added;
5249 
5250 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5251 		    connp->conn_mac_exempt) != 0)
5252 			return (B_FALSE);
5253 
5254 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5255 		if (added == -1)
5256 			return (B_FALSE);
5257 		tcp->tcp_hdr_len += added;
5258 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5259 		tcp->tcp_ip_hdr_len += added;
5260 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5261 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5262 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5263 			    tcp->tcp_hdr_len);
5264 			if (added == -1)
5265 				return (B_FALSE);
5266 			tcp->tcp_hdr_len += added;
5267 			tcp->tcp_tcph = (tcph_t *)
5268 			    ((uchar_t *)tcp->tcp_tcph + added);
5269 			tcp->tcp_ip_hdr_len += added;
5270 		}
5271 	} else {
5272 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5273 
5274 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5275 		    connp->conn_mac_exempt) != 0)
5276 			return (B_FALSE);
5277 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5278 		    &tcp->tcp_label_len, optbuf) != 0)
5279 			return (B_FALSE);
5280 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5281 			return (B_FALSE);
5282 	}
5283 
5284 	connp->conn_ulp_labeled = 1;
5285 
5286 	return (B_TRUE);
5287 }
5288 
5289 /* BEGIN CSTYLED */
5290 /*
5291  *
5292  * The sockfs ACCEPT path:
5293  * =======================
5294  *
5295  * The eager is now established in its own perimeter as soon as SYN is
5296  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5297  * completes the accept processing on the acceptor STREAM. The sending
5298  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5299  * listener but a TLI/XTI listener completes the accept processing
5300  * on the listener perimeter.
5301  *
5302  * Common control flow for 3 way handshake:
5303  * ----------------------------------------
5304  *
5305  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5306  *					-> tcp_conn_request()
5307  *
5308  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5309  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5310  *
5311  * Sockfs ACCEPT Path:
5312  * -------------------
5313  *
5314  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5315  * as STREAM entry point)
5316  *
5317  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5318  *
5319  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5320  * association (we are not behind eager's squeue but sockfs is protecting us
5321  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5322  * is changed to point at tcp_wput().
5323  *
5324  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5325  * listener (done on listener's perimeter).
5326  *
5327  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5328  * accept.
5329  *
5330  * TLI/XTI client ACCEPT path:
5331  * ---------------------------
5332  *
5333  * soaccept() sends T_CONN_RES on the listener STREAM.
5334  *
5335  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5336  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5337  *
5338  * Locks:
5339  * ======
5340  *
5341  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5342  * and listeners->tcp_eager_next_q.
5343  *
5344  * Referencing:
5345  * ============
5346  *
5347  * 1) We start out in tcp_conn_request by eager placing a ref on
5348  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5349  *
5350  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5351  * doing so we place a ref on the eager. This ref is finally dropped at the
5352  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5353  * reference is dropped by the squeue framework.
5354  *
5355  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5356  *
5357  * The reference must be released by the same entity that added the reference
5358  * In the above scheme, the eager is the entity that adds and releases the
5359  * references. Note that tcp_accept_finish executes in the squeue of the eager
5360  * (albeit after it is attached to the acceptor stream). Though 1. executes
5361  * in the listener's squeue, the eager is nascent at this point and the
5362  * reference can be considered to have been added on behalf of the eager.
5363  *
5364  * Eager getting a Reset or listener closing:
5365  * ==========================================
5366  *
5367  * Once the listener and eager are linked, the listener never does the unlink.
5368  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5369  * a message on all eager perimeter. The eager then does the unlink, clears
5370  * any pointers to the listener's queue and drops the reference to the
5371  * listener. The listener waits in tcp_close outside the squeue until its
5372  * refcount has dropped to 1. This ensures that the listener has waited for
5373  * all eagers to clear their association with the listener.
5374  *
5375  * Similarly, if eager decides to go away, it can unlink itself and close.
5376  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5377  * the reference to eager is still valid because of the extra ref we put
5378  * in tcp_send_conn_ind.
5379  *
5380  * Listener can always locate the eager under the protection
5381  * of the listener->tcp_eager_lock, and then do a refhold
5382  * on the eager during the accept processing.
5383  *
5384  * The acceptor stream accesses the eager in the accept processing
5385  * based on the ref placed on eager before sending T_conn_ind.
5386  * The only entity that can negate this refhold is a listener close
5387  * which is mutually exclusive with an active acceptor stream.
5388  *
5389  * Eager's reference on the listener
5390  * ===================================
5391  *
5392  * If the accept happens (even on a closed eager) the eager drops its
5393  * reference on the listener at the start of tcp_accept_finish. If the
5394  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5395  * the reference is dropped in tcp_closei_local. If the listener closes,
5396  * the reference is dropped in tcp_eager_kill. In all cases the reference
5397  * is dropped while executing in the eager's context (squeue).
5398  */
5399 /* END CSTYLED */
5400 
5401 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5402 
5403 /*
5404  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5405  * tcp_rput_data will not see any SYN packets.
5406  */
5407 /* ARGSUSED */
5408 void
5409 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5410 {
5411 	tcph_t		*tcph;
5412 	uint32_t	seg_seq;
5413 	tcp_t		*eager;
5414 	uint_t		ipvers;
5415 	ipha_t		*ipha;
5416 	ip6_t		*ip6h;
5417 	int		err;
5418 	conn_t		*econnp = NULL;
5419 	squeue_t	*new_sqp;
5420 	mblk_t		*mp1;
5421 	uint_t 		ip_hdr_len;
5422 	conn_t		*connp = (conn_t *)arg;
5423 	tcp_t		*tcp = connp->conn_tcp;
5424 	ire_t		*ire;
5425 	cred_t		*credp;
5426 
5427 	if (tcp->tcp_state != TCPS_LISTEN)
5428 		goto error2;
5429 
5430 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5431 
5432 	mutex_enter(&tcp->tcp_eager_lock);
5433 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5434 		mutex_exit(&tcp->tcp_eager_lock);
5435 		TCP_STAT(tcp_listendrop);
5436 		BUMP_MIB(&tcp_mib, tcpListenDrop);
5437 		if (tcp->tcp_debug) {
5438 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5439 			    "tcp_conn_request: listen backlog (max=%d) "
5440 			    "overflow (%d pending) on %s",
5441 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5442 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5443 		}
5444 		goto error2;
5445 	}
5446 
5447 	if (tcp->tcp_conn_req_cnt_q0 >=
5448 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
5449 		/*
5450 		 * Q0 is full. Drop a pending half-open req from the queue
5451 		 * to make room for the new SYN req. Also mark the time we
5452 		 * drop a SYN.
5453 		 *
5454 		 * A more aggressive defense against SYN attack will
5455 		 * be to set the "tcp_syn_defense" flag now.
5456 		 */
5457 		TCP_STAT(tcp_listendropq0);
5458 		tcp->tcp_last_rcv_lbolt = lbolt64;
5459 		if (!tcp_drop_q0(tcp)) {
5460 			mutex_exit(&tcp->tcp_eager_lock);
5461 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
5462 			if (tcp->tcp_debug) {
5463 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5464 				    "tcp_conn_request: listen half-open queue "
5465 				    "(max=%d) full (%d pending) on %s",
5466 				    tcp_conn_req_max_q0,
5467 				    tcp->tcp_conn_req_cnt_q0,
5468 				    tcp_display(tcp, NULL,
5469 				    DISP_PORT_ONLY));
5470 			}
5471 			goto error2;
5472 		}
5473 	}
5474 	mutex_exit(&tcp->tcp_eager_lock);
5475 
5476 	/*
5477 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5478 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5479 	 * link local address.  If IPSec is enabled, db_struioflag has
5480 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5481 	 * otherwise an error case if neither of them is set.
5482 	 */
5483 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5484 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5485 		DB_CKSUMSTART(mp) = 0;
5486 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5487 		econnp = (conn_t *)tcp_get_conn(arg2);
5488 		if (econnp == NULL)
5489 			goto error2;
5490 		econnp->conn_sqp = new_sqp;
5491 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5492 		/*
5493 		 * mp is updated in tcp_get_ipsec_conn().
5494 		 */
5495 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5496 		if (econnp == NULL) {
5497 			/*
5498 			 * mp freed by tcp_get_ipsec_conn.
5499 			 */
5500 			return;
5501 		}
5502 	} else {
5503 		goto error2;
5504 	}
5505 
5506 	ASSERT(DB_TYPE(mp) == M_DATA);
5507 
5508 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5509 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5510 	ASSERT(OK_32PTR(mp->b_rptr));
5511 	if (ipvers == IPV4_VERSION) {
5512 		ipha = (ipha_t *)mp->b_rptr;
5513 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5514 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5515 	} else {
5516 		ip6h = (ip6_t *)mp->b_rptr;
5517 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5518 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5519 	}
5520 
5521 	if (tcp->tcp_family == AF_INET) {
5522 		ASSERT(ipvers == IPV4_VERSION);
5523 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5524 	} else {
5525 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5526 	}
5527 
5528 	if (err)
5529 		goto error3;
5530 
5531 	eager = econnp->conn_tcp;
5532 
5533 	/* Inherit various TCP parameters from the listener */
5534 	eager->tcp_naglim = tcp->tcp_naglim;
5535 	eager->tcp_first_timer_threshold =
5536 	    tcp->tcp_first_timer_threshold;
5537 	eager->tcp_second_timer_threshold =
5538 	    tcp->tcp_second_timer_threshold;
5539 
5540 	eager->tcp_first_ctimer_threshold =
5541 	    tcp->tcp_first_ctimer_threshold;
5542 	eager->tcp_second_ctimer_threshold =
5543 	    tcp->tcp_second_ctimer_threshold;
5544 
5545 	/*
5546 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5547 	 * If it does not, the eager's receive window will be set to the
5548 	 * listener's receive window later in this function.
5549 	 */
5550 	eager->tcp_rwnd = 0;
5551 
5552 	/*
5553 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5554 	 * calling tcp_process_options() where tcp_mss_set() is called
5555 	 * to set the initial cwnd.
5556 	 */
5557 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5558 
5559 	/*
5560 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5561 	 * zone id before the accept is completed in tcp_wput_accept().
5562 	 */
5563 	econnp->conn_zoneid = connp->conn_zoneid;
5564 
5565 	/* Copy nexthop information from listener to eager */
5566 	if (connp->conn_nexthop_set) {
5567 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5568 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5569 	}
5570 
5571 	/*
5572 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5573 	 * eager is accepted
5574 	 */
5575 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5576 	crhold(credp);
5577 
5578 	/*
5579 	 * If the caller has the process-wide flag set, then default to MAC
5580 	 * exempt mode.  This allows read-down to unlabeled hosts.
5581 	 */
5582 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5583 		econnp->conn_mac_exempt = B_TRUE;
5584 
5585 	if (is_system_labeled()) {
5586 		cred_t *cr;
5587 
5588 		if (connp->conn_mlp_type != mlptSingle) {
5589 			cr = econnp->conn_peercred = DB_CRED(mp);
5590 			if (cr != NULL)
5591 				crhold(cr);
5592 			else
5593 				cr = econnp->conn_cred;
5594 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5595 			    econnp, cred_t *, cr)
5596 		} else {
5597 			cr = econnp->conn_cred;
5598 			DTRACE_PROBE2(syn_accept, conn_t *,
5599 			    econnp, cred_t *, cr)
5600 		}
5601 
5602 		if (!tcp_update_label(eager, cr)) {
5603 			DTRACE_PROBE3(
5604 			    tx__ip__log__error__connrequest__tcp,
5605 			    char *, "eager connp(1) label on SYN mp(2) failed",
5606 			    conn_t *, econnp, mblk_t *, mp);
5607 			goto error3;
5608 		}
5609 	}
5610 
5611 	eager->tcp_hard_binding = B_TRUE;
5612 
5613 	tcp_bind_hash_insert(&tcp_bind_fanout[
5614 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5615 
5616 	CL_INET_CONNECT(eager);
5617 
5618 	/*
5619 	 * No need to check for multicast destination since ip will only pass
5620 	 * up multicasts to those that have expressed interest
5621 	 * TODO: what about rejecting broadcasts?
5622 	 * Also check that source is not a multicast or broadcast address.
5623 	 */
5624 	eager->tcp_state = TCPS_SYN_RCVD;
5625 
5626 
5627 	/*
5628 	 * There should be no ire in the mp as we are being called after
5629 	 * receiving the SYN.
5630 	 */
5631 	ASSERT(tcp_ire_mp(mp) == NULL);
5632 
5633 	/*
5634 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5635 	 */
5636 
5637 	if (tcp_adapt_ire(eager, NULL) == 0) {
5638 		/* Undo the bind_hash_insert */
5639 		tcp_bind_hash_remove(eager);
5640 		goto error3;
5641 	}
5642 
5643 	/* Process all TCP options. */
5644 	tcp_process_options(eager, tcph);
5645 
5646 	/* Is the other end ECN capable? */
5647 	if (tcp_ecn_permitted >= 1 &&
5648 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5649 		eager->tcp_ecn_ok = B_TRUE;
5650 	}
5651 
5652 	/*
5653 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5654 	 * window size changed via SO_RCVBUF option.  First round up the
5655 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5656 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5657 	 * setting.
5658 	 *
5659 	 * Note if there is a rpipe metric associated with the remote host,
5660 	 * we should not inherit receive window size from listener.
5661 	 */
5662 	eager->tcp_rwnd = MSS_ROUNDUP(
5663 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5664 	    eager->tcp_rwnd), eager->tcp_mss);
5665 	if (eager->tcp_snd_ws_ok)
5666 		tcp_set_ws_value(eager);
5667 	/*
5668 	 * Note that this is the only place tcp_rwnd_set() is called for
5669 	 * accepting a connection.  We need to call it here instead of
5670 	 * after the 3-way handshake because we need to tell the other
5671 	 * side our rwnd in the SYN-ACK segment.
5672 	 */
5673 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5674 
5675 	/*
5676 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5677 	 * via soaccept()->soinheritoptions() which essentially applies
5678 	 * all the listener options to the new STREAM. The options that we
5679 	 * need to take care of are:
5680 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5681 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5682 	 * SO_SNDBUF, SO_RCVBUF.
5683 	 *
5684 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5685 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5686 	 *		tcp_maxpsz_set() gets called later from
5687 	 *		tcp_accept_finish(), the option takes effect.
5688 	 *
5689 	 */
5690 	/* Set the TCP options */
5691 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5692 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5693 	eager->tcp_oobinline = tcp->tcp_oobinline;
5694 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5695 	eager->tcp_broadcast = tcp->tcp_broadcast;
5696 	eager->tcp_useloopback = tcp->tcp_useloopback;
5697 	eager->tcp_dontroute = tcp->tcp_dontroute;
5698 	eager->tcp_linger = tcp->tcp_linger;
5699 	eager->tcp_lingertime = tcp->tcp_lingertime;
5700 	if (tcp->tcp_ka_enabled)
5701 		eager->tcp_ka_enabled = 1;
5702 
5703 	/* Set the IP options */
5704 	econnp->conn_broadcast = connp->conn_broadcast;
5705 	econnp->conn_loopback = connp->conn_loopback;
5706 	econnp->conn_dontroute = connp->conn_dontroute;
5707 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5708 
5709 	/* Put a ref on the listener for the eager. */
5710 	CONN_INC_REF(connp);
5711 	mutex_enter(&tcp->tcp_eager_lock);
5712 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5713 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5714 	tcp->tcp_eager_next_q0 = eager;
5715 	eager->tcp_eager_prev_q0 = tcp;
5716 
5717 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5718 	eager->tcp_listener = tcp;
5719 	eager->tcp_saved_listener = tcp;
5720 
5721 	/*
5722 	 * Tag this detached tcp vector for later retrieval
5723 	 * by our listener client in tcp_accept().
5724 	 */
5725 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5726 	tcp->tcp_conn_req_cnt_q0++;
5727 	if (++tcp->tcp_conn_req_seqnum == -1) {
5728 		/*
5729 		 * -1 is "special" and defined in TPI as something
5730 		 * that should never be used in T_CONN_IND
5731 		 */
5732 		++tcp->tcp_conn_req_seqnum;
5733 	}
5734 	mutex_exit(&tcp->tcp_eager_lock);
5735 
5736 	if (tcp->tcp_syn_defense) {
5737 		/* Don't drop the SYN that comes from a good IP source */
5738 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5739 		if (addr_cache != NULL && eager->tcp_remote ==
5740 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5741 			eager->tcp_dontdrop = B_TRUE;
5742 		}
5743 	}
5744 
5745 	/*
5746 	 * We need to insert the eager in its own perimeter but as soon
5747 	 * as we do that, we expose the eager to the classifier and
5748 	 * should not touch any field outside the eager's perimeter.
5749 	 * So do all the work necessary before inserting the eager
5750 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5751 	 * will succeed but undo everything if it fails.
5752 	 */
5753 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5754 	eager->tcp_irs = seg_seq;
5755 	eager->tcp_rack = seg_seq;
5756 	eager->tcp_rnxt = seg_seq + 1;
5757 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5758 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
5759 	eager->tcp_state = TCPS_SYN_RCVD;
5760 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5761 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5762 	if (mp1 == NULL)
5763 		goto error1;
5764 	DB_CPID(mp1) = tcp->tcp_cpid;
5765 
5766 	/*
5767 	 * We need to start the rto timer. In normal case, we start
5768 	 * the timer after sending the packet on the wire (or at
5769 	 * least believing that packet was sent by waiting for
5770 	 * CALL_IP_WPUT() to return). Since this is the first packet
5771 	 * being sent on the wire for the eager, our initial tcp_rto
5772 	 * is at least tcp_rexmit_interval_min which is a fairly
5773 	 * large value to allow the algorithm to adjust slowly to large
5774 	 * fluctuations of RTT during first few transmissions.
5775 	 *
5776 	 * Starting the timer first and then sending the packet in this
5777 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5778 	 * is of the order of several 100ms and starting the timer
5779 	 * first and then sending the packet will result in difference
5780 	 * of few micro seconds.
5781 	 *
5782 	 * Without this optimization, we are forced to hold the fanout
5783 	 * lock across the ipcl_bind_insert() and sending the packet
5784 	 * so that we don't race against an incoming packet (maybe RST)
5785 	 * for this eager.
5786 	 */
5787 
5788 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5789 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5790 
5791 
5792 	/*
5793 	 * Insert the eager in its own perimeter now. We are ready to deal
5794 	 * with any packets on eager.
5795 	 */
5796 	if (eager->tcp_ipversion == IPV4_VERSION) {
5797 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5798 			goto error;
5799 		}
5800 	} else {
5801 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5802 			goto error;
5803 		}
5804 	}
5805 
5806 	/* mark conn as fully-bound */
5807 	econnp->conn_fully_bound = B_TRUE;
5808 
5809 	/* Send the SYN-ACK */
5810 	tcp_send_data(eager, eager->tcp_wq, mp1);
5811 	freemsg(mp);
5812 
5813 	return;
5814 error:
5815 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
5816 	freemsg(mp1);
5817 error1:
5818 	/* Undo what we did above */
5819 	mutex_enter(&tcp->tcp_eager_lock);
5820 	tcp_eager_unlink(eager);
5821 	mutex_exit(&tcp->tcp_eager_lock);
5822 	/* Drop eager's reference on the listener */
5823 	CONN_DEC_REF(connp);
5824 
5825 	/*
5826 	 * Delete the cached ire in conn_ire_cache and also mark
5827 	 * the conn as CONDEMNED
5828 	 */
5829 	mutex_enter(&econnp->conn_lock);
5830 	econnp->conn_state_flags |= CONN_CONDEMNED;
5831 	ire = econnp->conn_ire_cache;
5832 	econnp->conn_ire_cache = NULL;
5833 	mutex_exit(&econnp->conn_lock);
5834 	if (ire != NULL)
5835 		IRE_REFRELE_NOTR(ire);
5836 
5837 	/*
5838 	 * tcp_accept_comm inserts the eager to the bind_hash
5839 	 * we need to remove it from the hash if ipcl_conn_insert
5840 	 * fails.
5841 	 */
5842 	tcp_bind_hash_remove(eager);
5843 	/* Drop the eager ref placed in tcp_open_detached */
5844 	CONN_DEC_REF(econnp);
5845 
5846 	/*
5847 	 * If a connection already exists, send the mp to that connections so
5848 	 * that it can be appropriately dealt with.
5849 	 */
5850 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
5851 		if (!IPCL_IS_CONNECTED(econnp)) {
5852 			/*
5853 			 * Something bad happened. ipcl_conn_insert()
5854 			 * failed because a connection already existed
5855 			 * in connected hash but we can't find it
5856 			 * anymore (someone blew it away). Just
5857 			 * free this message and hopefully remote
5858 			 * will retransmit at which time the SYN can be
5859 			 * treated as a new connection or dealth with
5860 			 * a TH_RST if a connection already exists.
5861 			 */
5862 			freemsg(mp);
5863 		} else {
5864 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
5865 			    econnp, SQTAG_TCP_CONN_REQ);
5866 		}
5867 	} else {
5868 		/* Nobody wants this packet */
5869 		freemsg(mp);
5870 	}
5871 	return;
5872 error2:
5873 	freemsg(mp);
5874 	return;
5875 error3:
5876 	CONN_DEC_REF(econnp);
5877 	freemsg(mp);
5878 }
5879 
5880 /*
5881  * In an ideal case of vertical partition in NUMA architecture, its
5882  * beneficial to have the listener and all the incoming connections
5883  * tied to the same squeue. The other constraint is that incoming
5884  * connections should be tied to the squeue attached to interrupted
5885  * CPU for obvious locality reason so this leaves the listener to
5886  * be tied to the same squeue. Our only problem is that when listener
5887  * is binding, the CPU that will get interrupted by the NIC whose
5888  * IP address the listener is binding to is not even known. So
5889  * the code below allows us to change that binding at the time the
5890  * CPU is interrupted by virtue of incoming connection's squeue.
5891  *
5892  * This is usefull only in case of a listener bound to a specific IP
5893  * address. For other kind of listeners, they get bound the
5894  * very first time and there is no attempt to rebind them.
5895  */
5896 void
5897 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5898 {
5899 	conn_t		*connp = (conn_t *)arg;
5900 	squeue_t	*sqp = (squeue_t *)arg2;
5901 	squeue_t	*new_sqp;
5902 	uint32_t	conn_flags;
5903 
5904 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5905 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5906 	} else {
5907 		goto done;
5908 	}
5909 
5910 	if (connp->conn_fanout == NULL)
5911 		goto done;
5912 
5913 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5914 		mutex_enter(&connp->conn_fanout->connf_lock);
5915 		mutex_enter(&connp->conn_lock);
5916 		/*
5917 		 * No one from read or write side can access us now
5918 		 * except for already queued packets on this squeue.
5919 		 * But since we haven't changed the squeue yet, they
5920 		 * can't execute. If they are processed after we have
5921 		 * changed the squeue, they are sent back to the
5922 		 * correct squeue down below.
5923 		 */
5924 		if (connp->conn_sqp != new_sqp) {
5925 			while (connp->conn_sqp != new_sqp)
5926 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5927 		}
5928 
5929 		do {
5930 			conn_flags = connp->conn_flags;
5931 			conn_flags |= IPCL_FULLY_BOUND;
5932 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5933 			    conn_flags);
5934 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5935 
5936 		mutex_exit(&connp->conn_fanout->connf_lock);
5937 		mutex_exit(&connp->conn_lock);
5938 	}
5939 
5940 done:
5941 	if (connp->conn_sqp != sqp) {
5942 		CONN_INC_REF(connp);
5943 		squeue_fill(connp->conn_sqp, mp,
5944 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
5945 	} else {
5946 		tcp_conn_request(connp, mp, sqp);
5947 	}
5948 }
5949 
5950 /*
5951  * Successful connect request processing begins when our client passes
5952  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5953  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5954  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
5955  *   upstream <- tcp_rput()                <- IP
5956  * After various error checks are completed, tcp_connect() lays
5957  * the target address and port into the composite header template,
5958  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5959  * request followed by an IRE request, and passes the three mblk message
5960  * down to IP looking like this:
5961  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5962  * Processing continues in tcp_rput() when we receive the following message:
5963  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5964  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5965  * to fire off the connection request, and then passes the T_OK_ACK mblk
5966  * upstream that we filled in below.  There are, of course, numerous
5967  * error conditions along the way which truncate the processing described
5968  * above.
5969  */
5970 static void
5971 tcp_connect(tcp_t *tcp, mblk_t *mp)
5972 {
5973 	sin_t		*sin;
5974 	sin6_t		*sin6;
5975 	queue_t		*q = tcp->tcp_wq;
5976 	struct T_conn_req	*tcr;
5977 	ipaddr_t	*dstaddrp;
5978 	in_port_t	dstport;
5979 	uint_t		srcid;
5980 
5981 	tcr = (struct T_conn_req *)mp->b_rptr;
5982 
5983 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5984 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5985 		tcp_err_ack(tcp, mp, TPROTO, 0);
5986 		return;
5987 	}
5988 
5989 	/*
5990 	 * Determine packet type based on type of address passed in
5991 	 * the request should contain an IPv4 or IPv6 address.
5992 	 * Make sure that address family matches the type of
5993 	 * family of the the address passed down
5994 	 */
5995 	switch (tcr->DEST_length) {
5996 	default:
5997 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5998 		return;
5999 
6000 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6001 		/*
6002 		 * XXX: The check for valid DEST_length was not there
6003 		 * in earlier releases and some buggy
6004 		 * TLI apps (e.g Sybase) got away with not feeding
6005 		 * in sin_zero part of address.
6006 		 * We allow that bug to keep those buggy apps humming.
6007 		 * Test suites require the check on DEST_length.
6008 		 * We construct a new mblk with valid DEST_length
6009 		 * free the original so the rest of the code does
6010 		 * not have to keep track of this special shorter
6011 		 * length address case.
6012 		 */
6013 		mblk_t *nmp;
6014 		struct T_conn_req *ntcr;
6015 		sin_t *nsin;
6016 
6017 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6018 		    tcr->OPT_length, BPRI_HI);
6019 		if (nmp == NULL) {
6020 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6021 			return;
6022 		}
6023 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6024 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6025 		ntcr->PRIM_type = T_CONN_REQ;
6026 		ntcr->DEST_length = sizeof (sin_t);
6027 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6028 
6029 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6030 		*nsin = sin_null;
6031 		/* Get pointer to shorter address to copy from original mp */
6032 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6033 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6034 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6035 			freemsg(nmp);
6036 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6037 			return;
6038 		}
6039 		nsin->sin_family = sin->sin_family;
6040 		nsin->sin_port = sin->sin_port;
6041 		nsin->sin_addr = sin->sin_addr;
6042 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6043 		nmp->b_wptr = (uchar_t *)&nsin[1];
6044 		if (tcr->OPT_length != 0) {
6045 			ntcr->OPT_length = tcr->OPT_length;
6046 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6047 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6048 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6049 			    tcr->OPT_length);
6050 			nmp->b_wptr += tcr->OPT_length;
6051 		}
6052 		freemsg(mp);	/* original mp freed */
6053 		mp = nmp;	/* re-initialize original variables */
6054 		tcr = ntcr;
6055 	}
6056 	/* FALLTHRU */
6057 
6058 	case sizeof (sin_t):
6059 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6060 		    sizeof (sin_t));
6061 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6062 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6063 			return;
6064 		}
6065 		if (tcp->tcp_family != AF_INET ||
6066 		    sin->sin_family != AF_INET) {
6067 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6068 			return;
6069 		}
6070 		if (sin->sin_port == 0) {
6071 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6072 			return;
6073 		}
6074 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6075 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6076 			return;
6077 		}
6078 
6079 		break;
6080 
6081 	case sizeof (sin6_t):
6082 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6083 		    sizeof (sin6_t));
6084 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6085 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6086 			return;
6087 		}
6088 		if (tcp->tcp_family != AF_INET6 ||
6089 		    sin6->sin6_family != AF_INET6) {
6090 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6091 			return;
6092 		}
6093 		if (sin6->sin6_port == 0) {
6094 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6095 			return;
6096 		}
6097 		break;
6098 	}
6099 	/*
6100 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6101 	 * should key on their sequence number and cut them loose.
6102 	 */
6103 
6104 	/*
6105 	 * If options passed in, feed it for verification and handling
6106 	 */
6107 	if (tcr->OPT_length != 0) {
6108 		mblk_t	*ok_mp;
6109 		mblk_t	*discon_mp;
6110 		mblk_t  *conn_opts_mp;
6111 		int t_error, sys_error, do_disconnect;
6112 
6113 		conn_opts_mp = NULL;
6114 
6115 		if (tcp_conprim_opt_process(tcp, mp,
6116 			&do_disconnect, &t_error, &sys_error) < 0) {
6117 			if (do_disconnect) {
6118 				ASSERT(t_error == 0 && sys_error == 0);
6119 				discon_mp = mi_tpi_discon_ind(NULL,
6120 				    ECONNREFUSED, 0);
6121 				if (!discon_mp) {
6122 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6123 					    TSYSERR, ENOMEM);
6124 					return;
6125 				}
6126 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6127 				if (!ok_mp) {
6128 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6129 					    TSYSERR, ENOMEM);
6130 					return;
6131 				}
6132 				qreply(q, ok_mp);
6133 				qreply(q, discon_mp); /* no flush! */
6134 			} else {
6135 				ASSERT(t_error != 0);
6136 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6137 				    sys_error);
6138 			}
6139 			return;
6140 		}
6141 		/*
6142 		 * Success in setting options, the mp option buffer represented
6143 		 * by OPT_length/offset has been potentially modified and
6144 		 * contains results of option processing. We copy it in
6145 		 * another mp to save it for potentially influencing returning
6146 		 * it in T_CONN_CONN.
6147 		 */
6148 		if (tcr->OPT_length != 0) { /* there are resulting options */
6149 			conn_opts_mp = copyb(mp);
6150 			if (!conn_opts_mp) {
6151 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6152 				    TSYSERR, ENOMEM);
6153 				return;
6154 			}
6155 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6156 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6157 			/*
6158 			 * Note:
6159 			 * These resulting option negotiation can include any
6160 			 * end-to-end negotiation options but there no such
6161 			 * thing (yet?) in our TCP/IP.
6162 			 */
6163 		}
6164 	}
6165 
6166 	/*
6167 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6168 	 * make sure that the template IP header in the tcp structure is an
6169 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6170 	 * need to this before we call tcp_bindi() so that the port lookup
6171 	 * code will look for ports in the correct port space (IPv4 and
6172 	 * IPv6 have separate port spaces).
6173 	 */
6174 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6175 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6176 		int err = 0;
6177 
6178 		err = tcp_header_init_ipv4(tcp);
6179 		if (err != 0) {
6180 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6181 			goto connect_failed;
6182 		}
6183 		if (tcp->tcp_lport != 0)
6184 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6185 	}
6186 
6187 	switch (tcp->tcp_state) {
6188 	case TCPS_IDLE:
6189 		/*
6190 		 * We support quick connect, refer to comments in
6191 		 * tcp_connect_*()
6192 		 */
6193 		/* FALLTHRU */
6194 	case TCPS_BOUND:
6195 	case TCPS_LISTEN:
6196 		if (tcp->tcp_family == AF_INET6) {
6197 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6198 				tcp_connect_ipv6(tcp, mp,
6199 				    &sin6->sin6_addr,
6200 				    sin6->sin6_port, sin6->sin6_flowinfo,
6201 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6202 				return;
6203 			}
6204 			/*
6205 			 * Destination adress is mapped IPv6 address.
6206 			 * Source bound address should be unspecified or
6207 			 * IPv6 mapped address as well.
6208 			 */
6209 			if (!IN6_IS_ADDR_UNSPECIFIED(
6210 			    &tcp->tcp_bound_source_v6) &&
6211 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6212 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6213 				    EADDRNOTAVAIL);
6214 				break;
6215 			}
6216 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6217 			dstport = sin6->sin6_port;
6218 			srcid = sin6->__sin6_src_id;
6219 		} else {
6220 			dstaddrp = &sin->sin_addr.s_addr;
6221 			dstport = sin->sin_port;
6222 			srcid = 0;
6223 		}
6224 
6225 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6226 		return;
6227 	default:
6228 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6229 		break;
6230 	}
6231 	/*
6232 	 * Note: Code below is the "failure" case
6233 	 */
6234 	/* return error ack and blow away saved option results if any */
6235 connect_failed:
6236 	if (mp != NULL)
6237 		putnext(tcp->tcp_rq, mp);
6238 	else {
6239 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6240 		    TSYSERR, ENOMEM);
6241 	}
6242 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6243 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6244 }
6245 
6246 /*
6247  * Handle connect to IPv4 destinations, including connections for AF_INET6
6248  * sockets connecting to IPv4 mapped IPv6 destinations.
6249  */
6250 static void
6251 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6252     uint_t srcid)
6253 {
6254 	tcph_t	*tcph;
6255 	mblk_t	*mp1;
6256 	ipaddr_t dstaddr = *dstaddrp;
6257 	int32_t	oldstate;
6258 	uint16_t lport;
6259 
6260 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6261 
6262 	/* Check for attempt to connect to INADDR_ANY */
6263 	if (dstaddr == INADDR_ANY)  {
6264 		/*
6265 		 * SunOS 4.x and 4.3 BSD allow an application
6266 		 * to connect a TCP socket to INADDR_ANY.
6267 		 * When they do this, the kernel picks the
6268 		 * address of one interface and uses it
6269 		 * instead.  The kernel usually ends up
6270 		 * picking the address of the loopback
6271 		 * interface.  This is an undocumented feature.
6272 		 * However, we provide the same thing here
6273 		 * in order to have source and binary
6274 		 * compatibility with SunOS 4.x.
6275 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6276 		 * generate the T_CONN_CON.
6277 		 */
6278 		dstaddr = htonl(INADDR_LOOPBACK);
6279 		*dstaddrp = dstaddr;
6280 	}
6281 
6282 	/* Handle __sin6_src_id if socket not bound to an IP address */
6283 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6284 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6285 		    tcp->tcp_connp->conn_zoneid);
6286 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6287 		    tcp->tcp_ipha->ipha_src);
6288 	}
6289 
6290 	/*
6291 	 * Don't let an endpoint connect to itself.  Note that
6292 	 * the test here does not catch the case where the
6293 	 * source IP addr was left unspecified by the user. In
6294 	 * this case, the source addr is set in tcp_adapt_ire()
6295 	 * using the reply to the T_BIND message that we send
6296 	 * down to IP here and the check is repeated in tcp_rput_other.
6297 	 */
6298 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6299 	    dstport == tcp->tcp_lport) {
6300 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6301 		goto failed;
6302 	}
6303 
6304 	tcp->tcp_ipha->ipha_dst = dstaddr;
6305 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6306 
6307 	/*
6308 	 * Massage a source route if any putting the first hop
6309 	 * in iph_dst. Compute a starting value for the checksum which
6310 	 * takes into account that the original iph_dst should be
6311 	 * included in the checksum but that ip will include the
6312 	 * first hop in the source route in the tcp checksum.
6313 	 */
6314 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
6315 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6316 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6317 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6318 	if ((int)tcp->tcp_sum < 0)
6319 		tcp->tcp_sum--;
6320 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6321 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6322 	    (tcp->tcp_sum >> 16));
6323 	tcph = tcp->tcp_tcph;
6324 	*(uint16_t *)tcph->th_fport = dstport;
6325 	tcp->tcp_fport = dstport;
6326 
6327 	oldstate = tcp->tcp_state;
6328 	/*
6329 	 * At this point the remote destination address and remote port fields
6330 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6331 	 * have to see which state tcp was in so we can take apropriate action.
6332 	 */
6333 	if (oldstate == TCPS_IDLE) {
6334 		/*
6335 		 * We support a quick connect capability here, allowing
6336 		 * clients to transition directly from IDLE to SYN_SENT
6337 		 * tcp_bindi will pick an unused port, insert the connection
6338 		 * in the bind hash and transition to BOUND state.
6339 		 */
6340 		lport = tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
6341 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6342 		    B_FALSE, B_FALSE);
6343 		if (lport == 0) {
6344 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6345 			goto failed;
6346 		}
6347 	}
6348 	tcp->tcp_state = TCPS_SYN_SENT;
6349 
6350 	/*
6351 	 * TODO: allow data with connect requests
6352 	 * by unlinking M_DATA trailers here and
6353 	 * linking them in behind the T_OK_ACK mblk.
6354 	 * The tcp_rput() bind ack handler would then
6355 	 * feed them to tcp_wput_data() rather than call
6356 	 * tcp_timer().
6357 	 */
6358 	mp = mi_tpi_ok_ack_alloc(mp);
6359 	if (!mp) {
6360 		tcp->tcp_state = oldstate;
6361 		goto failed;
6362 	}
6363 	if (tcp->tcp_family == AF_INET) {
6364 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6365 		    sizeof (ipa_conn_t));
6366 	} else {
6367 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6368 		    sizeof (ipa6_conn_t));
6369 	}
6370 	if (mp1) {
6371 		/* Hang onto the T_OK_ACK for later. */
6372 		linkb(mp1, mp);
6373 		mblk_setcred(mp1, tcp->tcp_cred);
6374 		if (tcp->tcp_family == AF_INET)
6375 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6376 		else {
6377 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6378 			    &tcp->tcp_sticky_ipp);
6379 		}
6380 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6381 		tcp->tcp_active_open = 1;
6382 		/*
6383 		 * If the bind cannot complete immediately
6384 		 * IP will arrange to call tcp_rput_other
6385 		 * when the bind completes.
6386 		 */
6387 		if (mp1 != NULL)
6388 			tcp_rput_other(tcp, mp1);
6389 		return;
6390 	}
6391 	/* Error case */
6392 	tcp->tcp_state = oldstate;
6393 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6394 
6395 failed:
6396 	/* return error ack and blow away saved option results if any */
6397 	if (mp != NULL)
6398 		putnext(tcp->tcp_rq, mp);
6399 	else {
6400 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6401 		    TSYSERR, ENOMEM);
6402 	}
6403 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6404 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6405 
6406 }
6407 
6408 /*
6409  * Handle connect to IPv6 destinations.
6410  */
6411 static void
6412 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6413     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6414 {
6415 	tcph_t	*tcph;
6416 	mblk_t	*mp1;
6417 	ip6_rthdr_t *rth;
6418 	int32_t  oldstate;
6419 	uint16_t lport;
6420 
6421 	ASSERT(tcp->tcp_family == AF_INET6);
6422 
6423 	/*
6424 	 * If we're here, it means that the destination address is a native
6425 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6426 	 * reason why it might not be IPv6 is if the socket was bound to an
6427 	 * IPv4-mapped IPv6 address.
6428 	 */
6429 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6430 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6431 		goto failed;
6432 	}
6433 
6434 	/*
6435 	 * Interpret a zero destination to mean loopback.
6436 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6437 	 * generate the T_CONN_CON.
6438 	 */
6439 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6440 		*dstaddrp = ipv6_loopback;
6441 	}
6442 
6443 	/* Handle __sin6_src_id if socket not bound to an IP address */
6444 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6445 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6446 		    tcp->tcp_connp->conn_zoneid);
6447 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6448 	}
6449 
6450 	/*
6451 	 * Take care of the scope_id now and add ip6i_t
6452 	 * if ip6i_t is not already allocated through TCP
6453 	 * sticky options. At this point tcp_ip6h does not
6454 	 * have dst info, thus use dstaddrp.
6455 	 */
6456 	if (scope_id != 0 &&
6457 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6458 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6459 		ip6i_t  *ip6i;
6460 
6461 		ipp->ipp_ifindex = scope_id;
6462 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6463 
6464 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6465 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6466 			/* Already allocated */
6467 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6468 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6469 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6470 		} else {
6471 			int reterr;
6472 
6473 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6474 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6475 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6476 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6477 			if (reterr != 0)
6478 				goto failed;
6479 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6480 		}
6481 	}
6482 
6483 	/*
6484 	 * Don't let an endpoint connect to itself.  Note that
6485 	 * the test here does not catch the case where the
6486 	 * source IP addr was left unspecified by the user. In
6487 	 * this case, the source addr is set in tcp_adapt_ire()
6488 	 * using the reply to the T_BIND message that we send
6489 	 * down to IP here and the check is repeated in tcp_rput_other.
6490 	 */
6491 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6492 	    (dstport == tcp->tcp_lport)) {
6493 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6494 		goto failed;
6495 	}
6496 
6497 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6498 	tcp->tcp_remote_v6 = *dstaddrp;
6499 	tcp->tcp_ip6h->ip6_vcf =
6500 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6501 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6502 
6503 
6504 	/*
6505 	 * Massage a routing header (if present) putting the first hop
6506 	 * in ip6_dst. Compute a starting value for the checksum which
6507 	 * takes into account that the original ip6_dst should be
6508 	 * included in the checksum but that ip will include the
6509 	 * first hop in the source route in the tcp checksum.
6510 	 */
6511 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6512 	if (rth != NULL) {
6513 
6514 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
6515 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6516 		    (tcp->tcp_sum >> 16));
6517 	} else {
6518 		tcp->tcp_sum = 0;
6519 	}
6520 
6521 	tcph = tcp->tcp_tcph;
6522 	*(uint16_t *)tcph->th_fport = dstport;
6523 	tcp->tcp_fport = dstport;
6524 
6525 	oldstate = tcp->tcp_state;
6526 	/*
6527 	 * At this point the remote destination address and remote port fields
6528 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6529 	 * have to see which state tcp was in so we can take apropriate action.
6530 	 */
6531 	if (oldstate == TCPS_IDLE) {
6532 		/*
6533 		 * We support a quick connect capability here, allowing
6534 		 * clients to transition directly from IDLE to SYN_SENT
6535 		 * tcp_bindi will pick an unused port, insert the connection
6536 		 * in the bind hash and transition to BOUND state.
6537 		 */
6538 		lport = tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
6539 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6540 		    B_FALSE, B_FALSE);
6541 		if (lport == 0) {
6542 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6543 			goto failed;
6544 		}
6545 	}
6546 	tcp->tcp_state = TCPS_SYN_SENT;
6547 	/*
6548 	 * TODO: allow data with connect requests
6549 	 * by unlinking M_DATA trailers here and
6550 	 * linking them in behind the T_OK_ACK mblk.
6551 	 * The tcp_rput() bind ack handler would then
6552 	 * feed them to tcp_wput_data() rather than call
6553 	 * tcp_timer().
6554 	 */
6555 	mp = mi_tpi_ok_ack_alloc(mp);
6556 	if (!mp) {
6557 		tcp->tcp_state = oldstate;
6558 		goto failed;
6559 	}
6560 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6561 	if (mp1) {
6562 		/* Hang onto the T_OK_ACK for later. */
6563 		linkb(mp1, mp);
6564 		mblk_setcred(mp1, tcp->tcp_cred);
6565 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6566 		    &tcp->tcp_sticky_ipp);
6567 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6568 		tcp->tcp_active_open = 1;
6569 		/* ip_bind_v6() may return ACK or ERROR */
6570 		if (mp1 != NULL)
6571 			tcp_rput_other(tcp, mp1);
6572 		return;
6573 	}
6574 	/* Error case */
6575 	tcp->tcp_state = oldstate;
6576 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6577 
6578 failed:
6579 	/* return error ack and blow away saved option results if any */
6580 	if (mp != NULL)
6581 		putnext(tcp->tcp_rq, mp);
6582 	else {
6583 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6584 		    TSYSERR, ENOMEM);
6585 	}
6586 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6587 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6588 }
6589 
6590 /*
6591  * We need a stream q for detached closing tcp connections
6592  * to use.  Our client hereby indicates that this q is the
6593  * one to use.
6594  */
6595 static void
6596 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6597 {
6598 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6599 	queue_t	*q = tcp->tcp_wq;
6600 
6601 	mp->b_datap->db_type = M_IOCACK;
6602 	iocp->ioc_count = 0;
6603 	mutex_enter(&tcp_g_q_lock);
6604 	if (tcp_g_q != NULL) {
6605 		mutex_exit(&tcp_g_q_lock);
6606 		iocp->ioc_error = EALREADY;
6607 	} else {
6608 		mblk_t *mp1;
6609 
6610 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6611 		if (mp1 == NULL) {
6612 			mutex_exit(&tcp_g_q_lock);
6613 			iocp->ioc_error = ENOMEM;
6614 		} else {
6615 			tcp_g_q = tcp->tcp_rq;
6616 			mutex_exit(&tcp_g_q_lock);
6617 			iocp->ioc_error = 0;
6618 			iocp->ioc_rval = 0;
6619 			/*
6620 			 * We are passing tcp_sticky_ipp as NULL
6621 			 * as it is not useful for tcp_default queue
6622 			 */
6623 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6624 			if (mp1 != NULL)
6625 				tcp_rput_other(tcp, mp1);
6626 		}
6627 	}
6628 	qreply(q, mp);
6629 }
6630 
6631 /*
6632  * Our client hereby directs us to reject the connection request
6633  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6634  * of sending the appropriate RST, not an ICMP error.
6635  */
6636 static void
6637 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6638 {
6639 	tcp_t	*ltcp = NULL;
6640 	t_scalar_t seqnum;
6641 	conn_t	*connp;
6642 
6643 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6644 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6645 		tcp_err_ack(tcp, mp, TPROTO, 0);
6646 		return;
6647 	}
6648 
6649 	/*
6650 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6651 	 * when the stream is in BOUND state. Do not send a reset,
6652 	 * since the destination IP address is not valid, and it can
6653 	 * be the initialized value of all zeros (broadcast address).
6654 	 *
6655 	 * If TCP has sent down a bind request to IP and has not
6656 	 * received the reply, reject the request.  Otherwise, TCP
6657 	 * will be confused.
6658 	 */
6659 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6660 		if (tcp->tcp_debug) {
6661 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6662 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6663 		}
6664 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6665 		return;
6666 	}
6667 
6668 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6669 
6670 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6671 
6672 		/*
6673 		 * According to TPI, for non-listeners, ignore seqnum
6674 		 * and disconnect.
6675 		 * Following interpretation of -1 seqnum is historical
6676 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6677 		 * a valid seqnum should not be -1).
6678 		 *
6679 		 *	-1 means disconnect everything
6680 		 *	regardless even on a listener.
6681 		 */
6682 
6683 		int old_state = tcp->tcp_state;
6684 
6685 		/*
6686 		 * The connection can't be on the tcp_time_wait_head list
6687 		 * since it is not detached.
6688 		 */
6689 		ASSERT(tcp->tcp_time_wait_next == NULL);
6690 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6691 		ASSERT(tcp->tcp_time_wait_expire == 0);
6692 		ltcp = NULL;
6693 		/*
6694 		 * If it used to be a listener, check to make sure no one else
6695 		 * has taken the port before switching back to LISTEN state.
6696 		 */
6697 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6698 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6699 			    tcp->tcp_ipha->ipha_src,
6700 			    tcp->tcp_connp->conn_zoneid);
6701 			if (connp != NULL)
6702 				ltcp = connp->conn_tcp;
6703 		} else {
6704 			/* Allow tcp_bound_if listeners? */
6705 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6706 			    &tcp->tcp_ip6h->ip6_src, 0,
6707 			    tcp->tcp_connp->conn_zoneid);
6708 			if (connp != NULL)
6709 				ltcp = connp->conn_tcp;
6710 		}
6711 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6712 			tcp->tcp_state = TCPS_LISTEN;
6713 		} else if (old_state > TCPS_BOUND) {
6714 			tcp->tcp_conn_req_max = 0;
6715 			tcp->tcp_state = TCPS_BOUND;
6716 		}
6717 		if (ltcp != NULL)
6718 			CONN_DEC_REF(ltcp->tcp_connp);
6719 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6720 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
6721 		} else if (old_state == TCPS_ESTABLISHED ||
6722 		    old_state == TCPS_CLOSE_WAIT) {
6723 			BUMP_MIB(&tcp_mib, tcpEstabResets);
6724 		}
6725 
6726 		if (tcp->tcp_fused)
6727 			tcp_unfuse(tcp);
6728 
6729 		mutex_enter(&tcp->tcp_eager_lock);
6730 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6731 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6732 			tcp_eager_cleanup(tcp, 0);
6733 		}
6734 		mutex_exit(&tcp->tcp_eager_lock);
6735 
6736 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6737 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6738 
6739 		tcp_reinit(tcp);
6740 
6741 		if (old_state >= TCPS_ESTABLISHED) {
6742 			/* Send M_FLUSH according to TPI */
6743 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6744 		}
6745 		mp = mi_tpi_ok_ack_alloc(mp);
6746 		if (mp)
6747 			putnext(tcp->tcp_rq, mp);
6748 		return;
6749 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6750 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6751 		return;
6752 	}
6753 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6754 		/* Send M_FLUSH according to TPI */
6755 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6756 	}
6757 	mp = mi_tpi_ok_ack_alloc(mp);
6758 	if (mp)
6759 		putnext(tcp->tcp_rq, mp);
6760 }
6761 
6762 /*
6763  * Diagnostic routine used to return a string associated with the tcp state.
6764  * Note that if the caller does not supply a buffer, it will use an internal
6765  * static string.  This means that if multiple threads call this function at
6766  * the same time, output can be corrupted...  Note also that this function
6767  * does not check the size of the supplied buffer.  The caller has to make
6768  * sure that it is big enough.
6769  */
6770 static char *
6771 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6772 {
6773 	char		buf1[30];
6774 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6775 	char		*buf;
6776 	char		*cp;
6777 	in6_addr_t	local, remote;
6778 	char		local_addrbuf[INET6_ADDRSTRLEN];
6779 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6780 
6781 	if (sup_buf != NULL)
6782 		buf = sup_buf;
6783 	else
6784 		buf = priv_buf;
6785 
6786 	if (tcp == NULL)
6787 		return ("NULL_TCP");
6788 	switch (tcp->tcp_state) {
6789 	case TCPS_CLOSED:
6790 		cp = "TCP_CLOSED";
6791 		break;
6792 	case TCPS_IDLE:
6793 		cp = "TCP_IDLE";
6794 		break;
6795 	case TCPS_BOUND:
6796 		cp = "TCP_BOUND";
6797 		break;
6798 	case TCPS_LISTEN:
6799 		cp = "TCP_LISTEN";
6800 		break;
6801 	case TCPS_SYN_SENT:
6802 		cp = "TCP_SYN_SENT";
6803 		break;
6804 	case TCPS_SYN_RCVD:
6805 		cp = "TCP_SYN_RCVD";
6806 		break;
6807 	case TCPS_ESTABLISHED:
6808 		cp = "TCP_ESTABLISHED";
6809 		break;
6810 	case TCPS_CLOSE_WAIT:
6811 		cp = "TCP_CLOSE_WAIT";
6812 		break;
6813 	case TCPS_FIN_WAIT_1:
6814 		cp = "TCP_FIN_WAIT_1";
6815 		break;
6816 	case TCPS_CLOSING:
6817 		cp = "TCP_CLOSING";
6818 		break;
6819 	case TCPS_LAST_ACK:
6820 		cp = "TCP_LAST_ACK";
6821 		break;
6822 	case TCPS_FIN_WAIT_2:
6823 		cp = "TCP_FIN_WAIT_2";
6824 		break;
6825 	case TCPS_TIME_WAIT:
6826 		cp = "TCP_TIME_WAIT";
6827 		break;
6828 	default:
6829 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6830 		cp = buf1;
6831 		break;
6832 	}
6833 	switch (format) {
6834 	case DISP_ADDR_AND_PORT:
6835 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6836 			/*
6837 			 * Note that we use the remote address in the tcp_b
6838 			 * structure.  This means that it will print out
6839 			 * the real destination address, not the next hop's
6840 			 * address if source routing is used.
6841 			 */
6842 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6843 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6844 
6845 		} else {
6846 			local = tcp->tcp_ip_src_v6;
6847 			remote = tcp->tcp_remote_v6;
6848 		}
6849 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6850 		    sizeof (local_addrbuf));
6851 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6852 		    sizeof (remote_addrbuf));
6853 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6854 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6855 		    ntohs(tcp->tcp_fport), cp);
6856 		break;
6857 	case DISP_PORT_ONLY:
6858 	default:
6859 		(void) mi_sprintf(buf, "[%u, %u] %s",
6860 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6861 		break;
6862 	}
6863 
6864 	return (buf);
6865 }
6866 
6867 /*
6868  * Called via squeue to get on to eager's perimeter to send a
6869  * TH_RST. The listener wants the eager to disappear either
6870  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
6871  * being called.
6872  */
6873 /* ARGSUSED */
6874 void
6875 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6876 {
6877 	conn_t	*econnp = (conn_t *)arg;
6878 	tcp_t	*eager = econnp->conn_tcp;
6879 	tcp_t	*listener = eager->tcp_listener;
6880 
6881 	/*
6882 	 * We could be called because listener is closing. Since
6883 	 * the eager is using listener's queue's, its not safe.
6884 	 * Better use the default queue just to send the TH_RST
6885 	 * out.
6886 	 */
6887 	eager->tcp_rq = tcp_g_q;
6888 	eager->tcp_wq = WR(tcp_g_q);
6889 
6890 	if (eager->tcp_state > TCPS_LISTEN) {
6891 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6892 		    eager, eager->tcp_snxt, 0, TH_RST);
6893 	}
6894 
6895 	/* We are here because listener wants this eager gone */
6896 	if (listener != NULL) {
6897 		mutex_enter(&listener->tcp_eager_lock);
6898 		tcp_eager_unlink(eager);
6899 		if (eager->tcp_conn.tcp_eager_conn_ind == NULL) {
6900 			/*
6901 			 * The eager has sent a conn_ind up to the
6902 			 * listener but listener decides to close
6903 			 * instead. We need to drop the extra ref
6904 			 * placed on eager in tcp_rput_data() before
6905 			 * sending the conn_ind to listener.
6906 			 */
6907 			CONN_DEC_REF(econnp);
6908 		}
6909 		mutex_exit(&listener->tcp_eager_lock);
6910 		CONN_DEC_REF(listener->tcp_connp);
6911 	}
6912 
6913 	if (eager->tcp_state > TCPS_BOUND)
6914 		tcp_close_detached(eager);
6915 }
6916 
6917 /*
6918  * Reset any eager connection hanging off this listener marked
6919  * with 'seqnum' and then reclaim it's resources.
6920  */
6921 static boolean_t
6922 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6923 {
6924 	tcp_t	*eager;
6925 	mblk_t 	*mp;
6926 
6927 	TCP_STAT(tcp_eager_blowoff_calls);
6928 	eager = listener;
6929 	mutex_enter(&listener->tcp_eager_lock);
6930 	do {
6931 		eager = eager->tcp_eager_next_q;
6932 		if (eager == NULL) {
6933 			mutex_exit(&listener->tcp_eager_lock);
6934 			return (B_FALSE);
6935 		}
6936 	} while (eager->tcp_conn_req_seqnum != seqnum);
6937 	CONN_INC_REF(eager->tcp_connp);
6938 	mutex_exit(&listener->tcp_eager_lock);
6939 	mp = &eager->tcp_closemp;
6940 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6941 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
6942 	return (B_TRUE);
6943 }
6944 
6945 /*
6946  * Reset any eager connection hanging off this listener
6947  * and then reclaim it's resources.
6948  */
6949 static void
6950 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6951 {
6952 	tcp_t	*eager;
6953 	mblk_t	*mp;
6954 
6955 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6956 
6957 	if (!q0_only) {
6958 		/* First cleanup q */
6959 		TCP_STAT(tcp_eager_blowoff_q);
6960 		eager = listener->tcp_eager_next_q;
6961 		while (eager != NULL) {
6962 			CONN_INC_REF(eager->tcp_connp);
6963 			mp = &eager->tcp_closemp;
6964 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
6965 			    tcp_eager_kill, eager->tcp_connp,
6966 			    SQTAG_TCP_EAGER_CLEANUP);
6967 			eager = eager->tcp_eager_next_q;
6968 		}
6969 	}
6970 	/* Then cleanup q0 */
6971 	TCP_STAT(tcp_eager_blowoff_q0);
6972 	eager = listener->tcp_eager_next_q0;
6973 	while (eager != listener) {
6974 		CONN_INC_REF(eager->tcp_connp);
6975 		mp = &eager->tcp_closemp;
6976 		squeue_fill(eager->tcp_connp->conn_sqp, mp,
6977 		    tcp_eager_kill, eager->tcp_connp,
6978 		    SQTAG_TCP_EAGER_CLEANUP_Q0);
6979 		eager = eager->tcp_eager_next_q0;
6980 	}
6981 }
6982 
6983 /*
6984  * If we are an eager connection hanging off a listener that hasn't
6985  * formally accepted the connection yet, get off his list and blow off
6986  * any data that we have accumulated.
6987  */
6988 static void
6989 tcp_eager_unlink(tcp_t *tcp)
6990 {
6991 	tcp_t	*listener = tcp->tcp_listener;
6992 
6993 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6994 	ASSERT(listener != NULL);
6995 	if (tcp->tcp_eager_next_q0 != NULL) {
6996 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6997 
6998 		/* Remove the eager tcp from q0 */
6999 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7000 		    tcp->tcp_eager_prev_q0;
7001 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7002 		    tcp->tcp_eager_next_q0;
7003 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7004 		listener->tcp_conn_req_cnt_q0--;
7005 
7006 		tcp->tcp_eager_next_q0 = NULL;
7007 		tcp->tcp_eager_prev_q0 = NULL;
7008 
7009 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7010 			/* we have timed out before */
7011 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7012 			listener->tcp_syn_rcvd_timeout--;
7013 		}
7014 	} else {
7015 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7016 		tcp_t	*prev = NULL;
7017 
7018 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7019 			if (tcpp[0] == tcp) {
7020 				if (listener->tcp_eager_last_q == tcp) {
7021 					/*
7022 					 * If we are unlinking the last
7023 					 * element on the list, adjust
7024 					 * tail pointer. Set tail pointer
7025 					 * to nil when list is empty.
7026 					 */
7027 					ASSERT(tcp->tcp_eager_next_q == NULL);
7028 					if (listener->tcp_eager_last_q ==
7029 					    listener->tcp_eager_next_q) {
7030 						listener->tcp_eager_last_q =
7031 						NULL;
7032 					} else {
7033 						/*
7034 						 * We won't get here if there
7035 						 * is only one eager in the
7036 						 * list.
7037 						 */
7038 						ASSERT(prev != NULL);
7039 						listener->tcp_eager_last_q =
7040 						    prev;
7041 					}
7042 				}
7043 				tcpp[0] = tcp->tcp_eager_next_q;
7044 				tcp->tcp_eager_next_q = NULL;
7045 				tcp->tcp_eager_last_q = NULL;
7046 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7047 				listener->tcp_conn_req_cnt_q--;
7048 				break;
7049 			}
7050 			prev = tcpp[0];
7051 		}
7052 	}
7053 	tcp->tcp_listener = NULL;
7054 }
7055 
7056 /* Shorthand to generate and send TPI error acks to our client */
7057 static void
7058 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7059 {
7060 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7061 		putnext(tcp->tcp_rq, mp);
7062 }
7063 
7064 /* Shorthand to generate and send TPI error acks to our client */
7065 static void
7066 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7067     int t_error, int sys_error)
7068 {
7069 	struct T_error_ack	*teackp;
7070 
7071 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7072 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7073 		teackp = (struct T_error_ack *)mp->b_rptr;
7074 		teackp->ERROR_prim = primitive;
7075 		teackp->TLI_error = t_error;
7076 		teackp->UNIX_error = sys_error;
7077 		putnext(tcp->tcp_rq, mp);
7078 	}
7079 }
7080 
7081 /*
7082  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7083  * but instead the code relies on:
7084  * - the fact that the address of the array and its size never changes
7085  * - the atomic assignment of the elements of the array
7086  */
7087 /* ARGSUSED */
7088 static int
7089 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7090 {
7091 	int i;
7092 
7093 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7094 		if (tcp_g_epriv_ports[i] != 0)
7095 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
7096 	}
7097 	return (0);
7098 }
7099 
7100 /*
7101  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7102  * threads from changing it at the same time.
7103  */
7104 /* ARGSUSED */
7105 static int
7106 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7107     cred_t *cr)
7108 {
7109 	long	new_value;
7110 	int	i;
7111 
7112 	/*
7113 	 * Fail the request if the new value does not lie within the
7114 	 * port number limits.
7115 	 */
7116 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7117 	    new_value <= 0 || new_value >= 65536) {
7118 		return (EINVAL);
7119 	}
7120 
7121 	mutex_enter(&tcp_epriv_port_lock);
7122 	/* Check if the value is already in the list */
7123 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7124 		if (new_value == tcp_g_epriv_ports[i]) {
7125 			mutex_exit(&tcp_epriv_port_lock);
7126 			return (EEXIST);
7127 		}
7128 	}
7129 	/* Find an empty slot */
7130 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7131 		if (tcp_g_epriv_ports[i] == 0)
7132 			break;
7133 	}
7134 	if (i == tcp_g_num_epriv_ports) {
7135 		mutex_exit(&tcp_epriv_port_lock);
7136 		return (EOVERFLOW);
7137 	}
7138 	/* Set the new value */
7139 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
7140 	mutex_exit(&tcp_epriv_port_lock);
7141 	return (0);
7142 }
7143 
7144 /*
7145  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7146  * threads from changing it at the same time.
7147  */
7148 /* ARGSUSED */
7149 static int
7150 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7151     cred_t *cr)
7152 {
7153 	long	new_value;
7154 	int	i;
7155 
7156 	/*
7157 	 * Fail the request if the new value does not lie within the
7158 	 * port number limits.
7159 	 */
7160 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7161 	    new_value >= 65536) {
7162 		return (EINVAL);
7163 	}
7164 
7165 	mutex_enter(&tcp_epriv_port_lock);
7166 	/* Check that the value is already in the list */
7167 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7168 		if (tcp_g_epriv_ports[i] == new_value)
7169 			break;
7170 	}
7171 	if (i == tcp_g_num_epriv_ports) {
7172 		mutex_exit(&tcp_epriv_port_lock);
7173 		return (ESRCH);
7174 	}
7175 	/* Clear the value */
7176 	tcp_g_epriv_ports[i] = 0;
7177 	mutex_exit(&tcp_epriv_port_lock);
7178 	return (0);
7179 }
7180 
7181 /* Return the TPI/TLI equivalent of our current tcp_state */
7182 static int
7183 tcp_tpistate(tcp_t *tcp)
7184 {
7185 	switch (tcp->tcp_state) {
7186 	case TCPS_IDLE:
7187 		return (TS_UNBND);
7188 	case TCPS_LISTEN:
7189 		/*
7190 		 * Return whether there are outstanding T_CONN_IND waiting
7191 		 * for the matching T_CONN_RES. Therefore don't count q0.
7192 		 */
7193 		if (tcp->tcp_conn_req_cnt_q > 0)
7194 			return (TS_WRES_CIND);
7195 		else
7196 			return (TS_IDLE);
7197 	case TCPS_BOUND:
7198 		return (TS_IDLE);
7199 	case TCPS_SYN_SENT:
7200 		return (TS_WCON_CREQ);
7201 	case TCPS_SYN_RCVD:
7202 		/*
7203 		 * Note: assumption: this has to the active open SYN_RCVD.
7204 		 * The passive instance is detached in SYN_RCVD stage of
7205 		 * incoming connection processing so we cannot get request
7206 		 * for T_info_ack on it.
7207 		 */
7208 		return (TS_WACK_CRES);
7209 	case TCPS_ESTABLISHED:
7210 		return (TS_DATA_XFER);
7211 	case TCPS_CLOSE_WAIT:
7212 		return (TS_WREQ_ORDREL);
7213 	case TCPS_FIN_WAIT_1:
7214 		return (TS_WIND_ORDREL);
7215 	case TCPS_FIN_WAIT_2:
7216 		return (TS_WIND_ORDREL);
7217 
7218 	case TCPS_CLOSING:
7219 	case TCPS_LAST_ACK:
7220 	case TCPS_TIME_WAIT:
7221 	case TCPS_CLOSED:
7222 		/*
7223 		 * Following TS_WACK_DREQ7 is a rendition of "not
7224 		 * yet TS_IDLE" TPI state. There is no best match to any
7225 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7226 		 * choose a value chosen that will map to TLI/XTI level
7227 		 * state of TSTATECHNG (state is process of changing) which
7228 		 * captures what this dummy state represents.
7229 		 */
7230 		return (TS_WACK_DREQ7);
7231 	default:
7232 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7233 		    tcp->tcp_state, tcp_display(tcp, NULL,
7234 		    DISP_PORT_ONLY));
7235 		return (TS_UNBND);
7236 	}
7237 }
7238 
7239 static void
7240 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7241 {
7242 	if (tcp->tcp_family == AF_INET6)
7243 		*tia = tcp_g_t_info_ack_v6;
7244 	else
7245 		*tia = tcp_g_t_info_ack;
7246 	tia->CURRENT_state = tcp_tpistate(tcp);
7247 	tia->OPT_size = tcp_max_optsize;
7248 	if (tcp->tcp_mss == 0) {
7249 		/* Not yet set - tcp_open does not set mss */
7250 		if (tcp->tcp_ipversion == IPV4_VERSION)
7251 			tia->TIDU_size = tcp_mss_def_ipv4;
7252 		else
7253 			tia->TIDU_size = tcp_mss_def_ipv6;
7254 	} else {
7255 		tia->TIDU_size = tcp->tcp_mss;
7256 	}
7257 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7258 }
7259 
7260 /*
7261  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7262  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7263  * tcp_g_t_info_ack.  The current state of the stream is copied from
7264  * tcp_state.
7265  */
7266 static void
7267 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7268 {
7269 	t_uscalar_t		cap_bits1;
7270 	struct T_capability_ack	*tcap;
7271 
7272 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7273 		freemsg(mp);
7274 		return;
7275 	}
7276 
7277 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7278 
7279 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7280 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7281 	if (mp == NULL)
7282 		return;
7283 
7284 	tcap = (struct T_capability_ack *)mp->b_rptr;
7285 	tcap->CAP_bits1 = 0;
7286 
7287 	if (cap_bits1 & TC1_INFO) {
7288 		tcp_copy_info(&tcap->INFO_ack, tcp);
7289 		tcap->CAP_bits1 |= TC1_INFO;
7290 	}
7291 
7292 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7293 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7294 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7295 	}
7296 
7297 	putnext(tcp->tcp_rq, mp);
7298 }
7299 
7300 /*
7301  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7302  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7303  * The current state of the stream is copied from tcp_state.
7304  */
7305 static void
7306 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7307 {
7308 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7309 	    T_INFO_ACK);
7310 	if (!mp) {
7311 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7312 		return;
7313 	}
7314 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7315 	putnext(tcp->tcp_rq, mp);
7316 }
7317 
7318 /* Respond to the TPI addr request */
7319 static void
7320 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7321 {
7322 	sin_t	*sin;
7323 	mblk_t	*ackmp;
7324 	struct T_addr_ack *taa;
7325 
7326 	/* Make it large enough for worst case */
7327 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7328 	    2 * sizeof (sin6_t), 1);
7329 	if (ackmp == NULL) {
7330 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7331 		return;
7332 	}
7333 
7334 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7335 		tcp_addr_req_ipv6(tcp, ackmp);
7336 		return;
7337 	}
7338 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7339 
7340 	bzero(taa, sizeof (struct T_addr_ack));
7341 	ackmp->b_wptr = (uchar_t *)&taa[1];
7342 
7343 	taa->PRIM_type = T_ADDR_ACK;
7344 	ackmp->b_datap->db_type = M_PCPROTO;
7345 
7346 	/*
7347 	 * Note: Following code assumes 32 bit alignment of basic
7348 	 * data structures like sin_t and struct T_addr_ack.
7349 	 */
7350 	if (tcp->tcp_state >= TCPS_BOUND) {
7351 		/*
7352 		 * Fill in local address
7353 		 */
7354 		taa->LOCADDR_length = sizeof (sin_t);
7355 		taa->LOCADDR_offset = sizeof (*taa);
7356 
7357 		sin = (sin_t *)&taa[1];
7358 
7359 		/* Fill zeroes and then intialize non-zero fields */
7360 		*sin = sin_null;
7361 
7362 		sin->sin_family = AF_INET;
7363 
7364 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7365 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7366 
7367 		ackmp->b_wptr = (uchar_t *)&sin[1];
7368 
7369 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7370 			/*
7371 			 * Fill in Remote address
7372 			 */
7373 			taa->REMADDR_length = sizeof (sin_t);
7374 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7375 						taa->LOCADDR_length);
7376 
7377 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7378 			*sin = sin_null;
7379 			sin->sin_family = AF_INET;
7380 			sin->sin_addr.s_addr = tcp->tcp_remote;
7381 			sin->sin_port = tcp->tcp_fport;
7382 
7383 			ackmp->b_wptr = (uchar_t *)&sin[1];
7384 		}
7385 	}
7386 	putnext(tcp->tcp_rq, ackmp);
7387 }
7388 
7389 /* Assumes that tcp_addr_req gets enough space and alignment */
7390 static void
7391 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7392 {
7393 	sin6_t	*sin6;
7394 	struct T_addr_ack *taa;
7395 
7396 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7397 	ASSERT(OK_32PTR(ackmp->b_rptr));
7398 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7399 	    2 * sizeof (sin6_t));
7400 
7401 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7402 
7403 	bzero(taa, sizeof (struct T_addr_ack));
7404 	ackmp->b_wptr = (uchar_t *)&taa[1];
7405 
7406 	taa->PRIM_type = T_ADDR_ACK;
7407 	ackmp->b_datap->db_type = M_PCPROTO;
7408 
7409 	/*
7410 	 * Note: Following code assumes 32 bit alignment of basic
7411 	 * data structures like sin6_t and struct T_addr_ack.
7412 	 */
7413 	if (tcp->tcp_state >= TCPS_BOUND) {
7414 		/*
7415 		 * Fill in local address
7416 		 */
7417 		taa->LOCADDR_length = sizeof (sin6_t);
7418 		taa->LOCADDR_offset = sizeof (*taa);
7419 
7420 		sin6 = (sin6_t *)&taa[1];
7421 		*sin6 = sin6_null;
7422 
7423 		sin6->sin6_family = AF_INET6;
7424 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7425 		sin6->sin6_port = tcp->tcp_lport;
7426 
7427 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7428 
7429 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7430 			/*
7431 			 * Fill in Remote address
7432 			 */
7433 			taa->REMADDR_length = sizeof (sin6_t);
7434 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7435 						taa->LOCADDR_length);
7436 
7437 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7438 			*sin6 = sin6_null;
7439 			sin6->sin6_family = AF_INET6;
7440 			sin6->sin6_flowinfo =
7441 			    tcp->tcp_ip6h->ip6_vcf &
7442 			    ~IPV6_VERS_AND_FLOW_MASK;
7443 			sin6->sin6_addr = tcp->tcp_remote_v6;
7444 			sin6->sin6_port = tcp->tcp_fport;
7445 
7446 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7447 		}
7448 	}
7449 	putnext(tcp->tcp_rq, ackmp);
7450 }
7451 
7452 /*
7453  * Handle reinitialization of a tcp structure.
7454  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7455  */
7456 static void
7457 tcp_reinit(tcp_t *tcp)
7458 {
7459 	mblk_t	*mp;
7460 	int 	err;
7461 
7462 	TCP_STAT(tcp_reinit_calls);
7463 
7464 	/* tcp_reinit should never be called for detached tcp_t's */
7465 	ASSERT(tcp->tcp_listener == NULL);
7466 	ASSERT((tcp->tcp_family == AF_INET &&
7467 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7468 	    (tcp->tcp_family == AF_INET6 &&
7469 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7470 	    tcp->tcp_ipversion == IPV6_VERSION)));
7471 
7472 	/* Cancel outstanding timers */
7473 	tcp_timers_stop(tcp);
7474 
7475 	/*
7476 	 * Reset everything in the state vector, after updating global
7477 	 * MIB data from instance counters.
7478 	 */
7479 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
7480 	tcp->tcp_ibsegs = 0;
7481 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
7482 	tcp->tcp_obsegs = 0;
7483 
7484 	tcp_close_mpp(&tcp->tcp_xmit_head);
7485 	if (tcp->tcp_snd_zcopy_aware)
7486 		tcp_zcopy_notify(tcp);
7487 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7488 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7489 	if (tcp->tcp_flow_stopped &&
7490 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7491 		tcp_clrqfull(tcp);
7492 	}
7493 	tcp_close_mpp(&tcp->tcp_reass_head);
7494 	tcp->tcp_reass_tail = NULL;
7495 	if (tcp->tcp_rcv_list != NULL) {
7496 		/* Free b_next chain */
7497 		tcp_close_mpp(&tcp->tcp_rcv_list);
7498 		tcp->tcp_rcv_last_head = NULL;
7499 		tcp->tcp_rcv_last_tail = NULL;
7500 		tcp->tcp_rcv_cnt = 0;
7501 	}
7502 	tcp->tcp_rcv_last_tail = NULL;
7503 
7504 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7505 		freemsg(mp);
7506 		tcp->tcp_urp_mp = NULL;
7507 	}
7508 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7509 		freemsg(mp);
7510 		tcp->tcp_urp_mark_mp = NULL;
7511 	}
7512 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7513 		freeb(tcp->tcp_fused_sigurg_mp);
7514 		tcp->tcp_fused_sigurg_mp = NULL;
7515 	}
7516 
7517 	/*
7518 	 * Following is a union with two members which are
7519 	 * identical types and size so the following cleanup
7520 	 * is enough.
7521 	 */
7522 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7523 
7524 	CL_INET_DISCONNECT(tcp);
7525 
7526 	/*
7527 	 * The connection can't be on the tcp_time_wait_head list
7528 	 * since it is not detached.
7529 	 */
7530 	ASSERT(tcp->tcp_time_wait_next == NULL);
7531 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7532 	ASSERT(tcp->tcp_time_wait_expire == 0);
7533 
7534 	if (tcp->tcp_kssl_pending) {
7535 		tcp->tcp_kssl_pending = B_FALSE;
7536 
7537 		/* Don't reset if the initialized by bind. */
7538 		if (tcp->tcp_kssl_ent != NULL) {
7539 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7540 			    KSSL_NO_PROXY);
7541 		}
7542 	}
7543 	if (tcp->tcp_kssl_ctx != NULL) {
7544 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7545 		tcp->tcp_kssl_ctx = NULL;
7546 	}
7547 
7548 	/*
7549 	 * Reset/preserve other values
7550 	 */
7551 	tcp_reinit_values(tcp);
7552 	ipcl_hash_remove(tcp->tcp_connp);
7553 	conn_delete_ire(tcp->tcp_connp, NULL);
7554 
7555 	if (tcp->tcp_conn_req_max != 0) {
7556 		/*
7557 		 * This is the case when a TLI program uses the same
7558 		 * transport end point to accept a connection.  This
7559 		 * makes the TCP both a listener and acceptor.  When
7560 		 * this connection is closed, we need to set the state
7561 		 * back to TCPS_LISTEN.  Make sure that the eager list
7562 		 * is reinitialized.
7563 		 *
7564 		 * Note that this stream is still bound to the four
7565 		 * tuples of the previous connection in IP.  If a new
7566 		 * SYN with different foreign address comes in, IP will
7567 		 * not find it and will send it to the global queue.  In
7568 		 * the global queue, TCP will do a tcp_lookup_listener()
7569 		 * to find this stream.  This works because this stream
7570 		 * is only removed from connected hash.
7571 		 *
7572 		 */
7573 		tcp->tcp_state = TCPS_LISTEN;
7574 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7575 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7576 		if (tcp->tcp_family == AF_INET6) {
7577 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7578 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7579 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7580 		} else {
7581 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7582 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7583 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7584 		}
7585 	} else {
7586 		tcp->tcp_state = TCPS_BOUND;
7587 	}
7588 
7589 	/*
7590 	 * Initialize to default values
7591 	 * Can't fail since enough header template space already allocated
7592 	 * at open().
7593 	 */
7594 	err = tcp_init_values(tcp);
7595 	ASSERT(err == 0);
7596 	/* Restore state in tcp_tcph */
7597 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7598 	if (tcp->tcp_ipversion == IPV4_VERSION)
7599 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7600 	else
7601 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7602 	/*
7603 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7604 	 * since the lookup funcs can only lookup on tcp_t
7605 	 */
7606 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7607 
7608 	ASSERT(tcp->tcp_ptpbhn != NULL);
7609 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
7610 	tcp->tcp_rwnd = tcp_recv_hiwat;
7611 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7612 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
7613 }
7614 
7615 /*
7616  * Force values to zero that need be zero.
7617  * Do not touch values asociated with the BOUND or LISTEN state
7618  * since the connection will end up in that state after the reinit.
7619  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7620  * structure!
7621  */
7622 static void
7623 tcp_reinit_values(tcp)
7624 	tcp_t *tcp;
7625 {
7626 #ifndef	lint
7627 #define	DONTCARE(x)
7628 #define	PRESERVE(x)
7629 #else
7630 #define	DONTCARE(x)	((x) = (x))
7631 #define	PRESERVE(x)	((x) = (x))
7632 #endif	/* lint */
7633 
7634 	PRESERVE(tcp->tcp_bind_hash);
7635 	PRESERVE(tcp->tcp_ptpbhn);
7636 	PRESERVE(tcp->tcp_acceptor_hash);
7637 	PRESERVE(tcp->tcp_ptpahn);
7638 
7639 	/* Should be ASSERT NULL on these with new code! */
7640 	ASSERT(tcp->tcp_time_wait_next == NULL);
7641 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7642 	ASSERT(tcp->tcp_time_wait_expire == 0);
7643 	PRESERVE(tcp->tcp_state);
7644 	PRESERVE(tcp->tcp_rq);
7645 	PRESERVE(tcp->tcp_wq);
7646 
7647 	ASSERT(tcp->tcp_xmit_head == NULL);
7648 	ASSERT(tcp->tcp_xmit_last == NULL);
7649 	ASSERT(tcp->tcp_unsent == 0);
7650 	ASSERT(tcp->tcp_xmit_tail == NULL);
7651 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7652 
7653 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7654 	tcp->tcp_suna = 0;			/* Displayed in mib */
7655 	tcp->tcp_swnd = 0;
7656 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7657 
7658 	ASSERT(tcp->tcp_ibsegs == 0);
7659 	ASSERT(tcp->tcp_obsegs == 0);
7660 
7661 	if (tcp->tcp_iphc != NULL) {
7662 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7663 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7664 	}
7665 
7666 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7667 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7668 	DONTCARE(tcp->tcp_ipha);
7669 	DONTCARE(tcp->tcp_ip6h);
7670 	DONTCARE(tcp->tcp_ip_hdr_len);
7671 	DONTCARE(tcp->tcp_tcph);
7672 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7673 	tcp->tcp_valid_bits = 0;
7674 
7675 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7676 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7677 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7678 	tcp->tcp_last_rcv_lbolt = 0;
7679 
7680 	tcp->tcp_init_cwnd = 0;
7681 
7682 	tcp->tcp_urp_last_valid = 0;
7683 	tcp->tcp_hard_binding = 0;
7684 	tcp->tcp_hard_bound = 0;
7685 	PRESERVE(tcp->tcp_cred);
7686 	PRESERVE(tcp->tcp_cpid);
7687 	PRESERVE(tcp->tcp_exclbind);
7688 
7689 	tcp->tcp_fin_acked = 0;
7690 	tcp->tcp_fin_rcvd = 0;
7691 	tcp->tcp_fin_sent = 0;
7692 	tcp->tcp_ordrel_done = 0;
7693 
7694 	tcp->tcp_debug = 0;
7695 	tcp->tcp_dontroute = 0;
7696 	tcp->tcp_broadcast = 0;
7697 
7698 	tcp->tcp_useloopback = 0;
7699 	tcp->tcp_reuseaddr = 0;
7700 	tcp->tcp_oobinline = 0;
7701 	tcp->tcp_dgram_errind = 0;
7702 
7703 	tcp->tcp_detached = 0;
7704 	tcp->tcp_bind_pending = 0;
7705 	tcp->tcp_unbind_pending = 0;
7706 	tcp->tcp_deferred_clean_death = 0;
7707 
7708 	tcp->tcp_snd_ws_ok = B_FALSE;
7709 	tcp->tcp_snd_ts_ok = B_FALSE;
7710 	tcp->tcp_linger = 0;
7711 	tcp->tcp_ka_enabled = 0;
7712 	tcp->tcp_zero_win_probe = 0;
7713 
7714 	tcp->tcp_loopback = 0;
7715 	tcp->tcp_localnet = 0;
7716 	tcp->tcp_syn_defense = 0;
7717 	tcp->tcp_set_timer = 0;
7718 
7719 	tcp->tcp_active_open = 0;
7720 	ASSERT(tcp->tcp_timeout == B_FALSE);
7721 	tcp->tcp_rexmit = B_FALSE;
7722 	tcp->tcp_xmit_zc_clean = B_FALSE;
7723 
7724 	tcp->tcp_snd_sack_ok = B_FALSE;
7725 	PRESERVE(tcp->tcp_recvdstaddr);
7726 	tcp->tcp_hwcksum = B_FALSE;
7727 
7728 	tcp->tcp_ire_ill_check_done = B_FALSE;
7729 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7730 
7731 	tcp->tcp_mdt = B_FALSE;
7732 	tcp->tcp_mdt_hdr_head = 0;
7733 	tcp->tcp_mdt_hdr_tail = 0;
7734 
7735 	tcp->tcp_conn_def_q0 = 0;
7736 	tcp->tcp_ip_forward_progress = B_FALSE;
7737 	tcp->tcp_anon_priv_bind = 0;
7738 	tcp->tcp_ecn_ok = B_FALSE;
7739 
7740 	tcp->tcp_cwr = B_FALSE;
7741 	tcp->tcp_ecn_echo_on = B_FALSE;
7742 
7743 	if (tcp->tcp_sack_info != NULL) {
7744 		if (tcp->tcp_notsack_list != NULL) {
7745 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7746 		}
7747 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7748 		tcp->tcp_sack_info = NULL;
7749 	}
7750 
7751 	tcp->tcp_rcv_ws = 0;
7752 	tcp->tcp_snd_ws = 0;
7753 	tcp->tcp_ts_recent = 0;
7754 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7755 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7756 	tcp->tcp_if_mtu = 0;
7757 
7758 	ASSERT(tcp->tcp_reass_head == NULL);
7759 	ASSERT(tcp->tcp_reass_tail == NULL);
7760 
7761 	tcp->tcp_cwnd_cnt = 0;
7762 
7763 	ASSERT(tcp->tcp_rcv_list == NULL);
7764 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7765 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7766 	ASSERT(tcp->tcp_rcv_cnt == 0);
7767 
7768 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7769 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7770 	tcp->tcp_csuna = 0;
7771 
7772 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7773 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7774 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7775 	tcp->tcp_rtt_update = 0;
7776 
7777 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7778 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7779 
7780 	tcp->tcp_rack = 0;			/* Displayed in mib */
7781 	tcp->tcp_rack_cnt = 0;
7782 	tcp->tcp_rack_cur_max = 0;
7783 	tcp->tcp_rack_abs_max = 0;
7784 
7785 	tcp->tcp_max_swnd = 0;
7786 
7787 	ASSERT(tcp->tcp_listener == NULL);
7788 
7789 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7790 
7791 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7792 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7793 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7794 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7795 
7796 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7797 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7798 	PRESERVE(tcp->tcp_conn_req_max);
7799 	PRESERVE(tcp->tcp_conn_req_seqnum);
7800 
7801 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7802 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7803 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7804 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7805 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7806 
7807 	tcp->tcp_lingertime = 0;
7808 
7809 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7810 	ASSERT(tcp->tcp_urp_mp == NULL);
7811 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7812 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7813 
7814 	ASSERT(tcp->tcp_eager_next_q == NULL);
7815 	ASSERT(tcp->tcp_eager_last_q == NULL);
7816 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7817 	    tcp->tcp_eager_prev_q0 == NULL) ||
7818 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7819 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7820 
7821 	tcp->tcp_client_errno = 0;
7822 
7823 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7824 
7825 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7826 
7827 	PRESERVE(tcp->tcp_bound_source_v6);
7828 	tcp->tcp_last_sent_len = 0;
7829 	tcp->tcp_dupack_cnt = 0;
7830 
7831 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7832 	PRESERVE(tcp->tcp_lport);
7833 
7834 	PRESERVE(tcp->tcp_acceptor_lockp);
7835 
7836 	ASSERT(tcp->tcp_ordrelid == 0);
7837 	PRESERVE(tcp->tcp_acceptor_id);
7838 	DONTCARE(tcp->tcp_ipsec_overhead);
7839 
7840 	/*
7841 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
7842 	 * in tcp structure and now tracing), Re-initialize all
7843 	 * members of tcp_traceinfo.
7844 	 */
7845 	if (tcp->tcp_tracebuf != NULL) {
7846 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
7847 	}
7848 
7849 	PRESERVE(tcp->tcp_family);
7850 	if (tcp->tcp_family == AF_INET6) {
7851 		tcp->tcp_ipversion = IPV6_VERSION;
7852 		tcp->tcp_mss = tcp_mss_def_ipv6;
7853 	} else {
7854 		tcp->tcp_ipversion = IPV4_VERSION;
7855 		tcp->tcp_mss = tcp_mss_def_ipv4;
7856 	}
7857 
7858 	tcp->tcp_bound_if = 0;
7859 	tcp->tcp_ipv6_recvancillary = 0;
7860 	tcp->tcp_recvifindex = 0;
7861 	tcp->tcp_recvhops = 0;
7862 	tcp->tcp_closed = 0;
7863 	tcp->tcp_cleandeathtag = 0;
7864 	if (tcp->tcp_hopopts != NULL) {
7865 		mi_free(tcp->tcp_hopopts);
7866 		tcp->tcp_hopopts = NULL;
7867 		tcp->tcp_hopoptslen = 0;
7868 	}
7869 	ASSERT(tcp->tcp_hopoptslen == 0);
7870 	if (tcp->tcp_dstopts != NULL) {
7871 		mi_free(tcp->tcp_dstopts);
7872 		tcp->tcp_dstopts = NULL;
7873 		tcp->tcp_dstoptslen = 0;
7874 	}
7875 	ASSERT(tcp->tcp_dstoptslen == 0);
7876 	if (tcp->tcp_rtdstopts != NULL) {
7877 		mi_free(tcp->tcp_rtdstopts);
7878 		tcp->tcp_rtdstopts = NULL;
7879 		tcp->tcp_rtdstoptslen = 0;
7880 	}
7881 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7882 	if (tcp->tcp_rthdr != NULL) {
7883 		mi_free(tcp->tcp_rthdr);
7884 		tcp->tcp_rthdr = NULL;
7885 		tcp->tcp_rthdrlen = 0;
7886 	}
7887 	ASSERT(tcp->tcp_rthdrlen == 0);
7888 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7889 
7890 	/* Reset fusion-related fields */
7891 	tcp->tcp_fused = B_FALSE;
7892 	tcp->tcp_unfusable = B_FALSE;
7893 	tcp->tcp_fused_sigurg = B_FALSE;
7894 	tcp->tcp_direct_sockfs = B_FALSE;
7895 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7896 	tcp->tcp_loopback_peer = NULL;
7897 	tcp->tcp_fuse_rcv_hiwater = 0;
7898 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7899 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7900 
7901 	tcp->tcp_in_ack_unsent = 0;
7902 	tcp->tcp_cork = B_FALSE;
7903 
7904 	PRESERVE(tcp->tcp_squeue_bytes);
7905 
7906 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7907 	ASSERT(!tcp->tcp_kssl_pending);
7908 	PRESERVE(tcp->tcp_kssl_ent);
7909 
7910 #undef	DONTCARE
7911 #undef	PRESERVE
7912 }
7913 
7914 /*
7915  * Allocate necessary resources and initialize state vector.
7916  * Guaranteed not to fail so that when an error is returned,
7917  * the caller doesn't need to do any additional cleanup.
7918  */
7919 int
7920 tcp_init(tcp_t *tcp, queue_t *q)
7921 {
7922 	int	err;
7923 
7924 	tcp->tcp_rq = q;
7925 	tcp->tcp_wq = WR(q);
7926 	tcp->tcp_state = TCPS_IDLE;
7927 	if ((err = tcp_init_values(tcp)) != 0)
7928 		tcp_timers_stop(tcp);
7929 	return (err);
7930 }
7931 
7932 static int
7933 tcp_init_values(tcp_t *tcp)
7934 {
7935 	int	err;
7936 
7937 	ASSERT((tcp->tcp_family == AF_INET &&
7938 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7939 	    (tcp->tcp_family == AF_INET6 &&
7940 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7941 	    tcp->tcp_ipversion == IPV6_VERSION)));
7942 
7943 	/*
7944 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7945 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7946 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7947 	 * during first few transmissions of a connection as seen in slow
7948 	 * links.
7949 	 */
7950 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
7951 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
7952 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7953 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7954 	    tcp_conn_grace_period;
7955 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
7956 		tcp->tcp_rto = tcp_rexmit_interval_min;
7957 	tcp->tcp_timer_backoff = 0;
7958 	tcp->tcp_ms_we_have_waited = 0;
7959 	tcp->tcp_last_recv_time = lbolt;
7960 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
7961 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7962 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7963 
7964 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
7965 
7966 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
7967 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
7968 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
7969 	/*
7970 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7971 	 * passive open.
7972 	 */
7973 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
7974 
7975 	tcp->tcp_naglim = tcp_naglim_def;
7976 
7977 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7978 
7979 	tcp->tcp_mdt_hdr_head = 0;
7980 	tcp->tcp_mdt_hdr_tail = 0;
7981 
7982 	/* Reset fusion-related fields */
7983 	tcp->tcp_fused = B_FALSE;
7984 	tcp->tcp_unfusable = B_FALSE;
7985 	tcp->tcp_fused_sigurg = B_FALSE;
7986 	tcp->tcp_direct_sockfs = B_FALSE;
7987 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7988 	tcp->tcp_loopback_peer = NULL;
7989 	tcp->tcp_fuse_rcv_hiwater = 0;
7990 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7991 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7992 
7993 	/* Initialize the header template */
7994 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7995 		err = tcp_header_init_ipv4(tcp);
7996 	} else {
7997 		err = tcp_header_init_ipv6(tcp);
7998 	}
7999 	if (err)
8000 		return (err);
8001 
8002 	/*
8003 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8004 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8005 	 */
8006 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8007 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
8008 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
8009 
8010 	tcp->tcp_cork = B_FALSE;
8011 	/*
8012 	 * Init the tcp_debug option.  This value determines whether TCP
8013 	 * calls strlog() to print out debug messages.  Doing this
8014 	 * initialization here means that this value is not inherited thru
8015 	 * tcp_reinit().
8016 	 */
8017 	tcp->tcp_debug = tcp_dbg;
8018 
8019 	tcp->tcp_ka_interval = tcp_keepalive_interval;
8020 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
8021 
8022 	return (0);
8023 }
8024 
8025 /*
8026  * Initialize the IPv4 header. Loses any record of any IP options.
8027  */
8028 static int
8029 tcp_header_init_ipv4(tcp_t *tcp)
8030 {
8031 	tcph_t		*tcph;
8032 	uint32_t	sum;
8033 	conn_t		*connp;
8034 
8035 	/*
8036 	 * This is a simple initialization. If there's
8037 	 * already a template, it should never be too small,
8038 	 * so reuse it.  Otherwise, allocate space for the new one.
8039 	 */
8040 	if (tcp->tcp_iphc == NULL) {
8041 		ASSERT(tcp->tcp_iphc_len == 0);
8042 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8043 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8044 		if (tcp->tcp_iphc == NULL) {
8045 			tcp->tcp_iphc_len = 0;
8046 			return (ENOMEM);
8047 		}
8048 	}
8049 
8050 	/* options are gone; may need a new label */
8051 	connp = tcp->tcp_connp;
8052 	connp->conn_mlp_type = mlptSingle;
8053 	connp->conn_ulp_labeled = !is_system_labeled();
8054 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8055 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8056 	tcp->tcp_ip6h = NULL;
8057 	tcp->tcp_ipversion = IPV4_VERSION;
8058 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8059 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8060 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8061 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8062 	tcp->tcp_ipha->ipha_version_and_hdr_length
8063 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8064 	tcp->tcp_ipha->ipha_ident = 0;
8065 
8066 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
8067 	tcp->tcp_tos = 0;
8068 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8069 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
8070 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8071 
8072 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8073 	tcp->tcp_tcph = tcph;
8074 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8075 	/*
8076 	 * IP wants our header length in the checksum field to
8077 	 * allow it to perform a single pseudo-header+checksum
8078 	 * calculation on behalf of TCP.
8079 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8080 	 */
8081 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8082 	sum = (sum >> 16) + (sum & 0xFFFF);
8083 	U16_TO_ABE16(sum, tcph->th_sum);
8084 	return (0);
8085 }
8086 
8087 /*
8088  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8089  */
8090 static int
8091 tcp_header_init_ipv6(tcp_t *tcp)
8092 {
8093 	tcph_t	*tcph;
8094 	uint32_t	sum;
8095 	conn_t	*connp;
8096 
8097 	/*
8098 	 * This is a simple initialization. If there's
8099 	 * already a template, it should never be too small,
8100 	 * so reuse it. Otherwise, allocate space for the new one.
8101 	 * Ensure that there is enough space to "downgrade" the tcp_t
8102 	 * to an IPv4 tcp_t. This requires having space for a full load
8103 	 * of IPv4 options, as well as a full load of TCP options
8104 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8105 	 * than a v6 header and a TCP header with a full load of TCP options
8106 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8107 	 * We want to avoid reallocation in the "downgraded" case when
8108 	 * processing outbound IPv4 options.
8109 	 */
8110 	if (tcp->tcp_iphc == NULL) {
8111 		ASSERT(tcp->tcp_iphc_len == 0);
8112 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8113 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8114 		if (tcp->tcp_iphc == NULL) {
8115 			tcp->tcp_iphc_len = 0;
8116 			return (ENOMEM);
8117 		}
8118 	}
8119 
8120 	/* options are gone; may need a new label */
8121 	connp = tcp->tcp_connp;
8122 	connp->conn_mlp_type = mlptSingle;
8123 	connp->conn_ulp_labeled = !is_system_labeled();
8124 
8125 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8126 	tcp->tcp_ipversion = IPV6_VERSION;
8127 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8128 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8129 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8130 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8131 	tcp->tcp_ipha = NULL;
8132 
8133 	/* Initialize the header template */
8134 
8135 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8136 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8137 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8138 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
8139 
8140 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8141 	tcp->tcp_tcph = tcph;
8142 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8143 	/*
8144 	 * IP wants our header length in the checksum field to
8145 	 * allow it to perform a single psuedo-header+checksum
8146 	 * calculation on behalf of TCP.
8147 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8148 	 */
8149 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8150 	sum = (sum >> 16) + (sum & 0xFFFF);
8151 	U16_TO_ABE16(sum, tcph->th_sum);
8152 	return (0);
8153 }
8154 
8155 /* At minimum we need 4 bytes in the TCP header for the lookup */
8156 #define	ICMP_MIN_TCP_HDR	12
8157 
8158 /*
8159  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8160  * passed up by IP. The message is always received on the correct tcp_t.
8161  * Assumes that IP has pulled up everything up to and including the ICMP header.
8162  */
8163 void
8164 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8165 {
8166 	icmph_t *icmph;
8167 	ipha_t	*ipha;
8168 	int	iph_hdr_length;
8169 	tcph_t	*tcph;
8170 	boolean_t ipsec_mctl = B_FALSE;
8171 	boolean_t secure;
8172 	mblk_t *first_mp = mp;
8173 	uint32_t new_mss;
8174 	uint32_t ratio;
8175 	size_t mp_size = MBLKL(mp);
8176 	uint32_t seg_ack;
8177 	uint32_t seg_seq;
8178 
8179 	/* Assume IP provides aligned packets - otherwise toss */
8180 	if (!OK_32PTR(mp->b_rptr)) {
8181 		freemsg(mp);
8182 		return;
8183 	}
8184 
8185 	/*
8186 	 * Since ICMP errors are normal data marked with M_CTL when sent
8187 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8188 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8189 	 */
8190 	if ((mp_size == sizeof (ipsec_info_t)) &&
8191 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8192 		ASSERT(mp->b_cont != NULL);
8193 		mp = mp->b_cont;
8194 		/* IP should have done this */
8195 		ASSERT(OK_32PTR(mp->b_rptr));
8196 		mp_size = MBLKL(mp);
8197 		ipsec_mctl = B_TRUE;
8198 	}
8199 
8200 	/*
8201 	 * Verify that we have a complete outer IP header. If not, drop it.
8202 	 */
8203 	if (mp_size < sizeof (ipha_t)) {
8204 noticmpv4:
8205 		freemsg(first_mp);
8206 		return;
8207 	}
8208 
8209 	ipha = (ipha_t *)mp->b_rptr;
8210 	/*
8211 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8212 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8213 	 */
8214 	switch (IPH_HDR_VERSION(ipha)) {
8215 	case IPV6_VERSION:
8216 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8217 		return;
8218 	case IPV4_VERSION:
8219 		break;
8220 	default:
8221 		goto noticmpv4;
8222 	}
8223 
8224 	/* Skip past the outer IP and ICMP headers */
8225 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8226 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8227 	/*
8228 	 * If we don't have the correct outer IP header length or if the ULP
8229 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8230 	 * send it upstream.
8231 	 */
8232 	if (iph_hdr_length < sizeof (ipha_t) ||
8233 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8234 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8235 		goto noticmpv4;
8236 	}
8237 	ipha = (ipha_t *)&icmph[1];
8238 
8239 	/* Skip past the inner IP and find the ULP header */
8240 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8241 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8242 	/*
8243 	 * If we don't have the correct inner IP header length or if the ULP
8244 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8245 	 * bytes of TCP header, drop it.
8246 	 */
8247 	if (iph_hdr_length < sizeof (ipha_t) ||
8248 	    ipha->ipha_protocol != IPPROTO_TCP ||
8249 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8250 		goto noticmpv4;
8251 	}
8252 
8253 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8254 		if (ipsec_mctl) {
8255 			secure = ipsec_in_is_secure(first_mp);
8256 		} else {
8257 			secure = B_FALSE;
8258 		}
8259 		if (secure) {
8260 			/*
8261 			 * If we are willing to accept this in clear
8262 			 * we don't have to verify policy.
8263 			 */
8264 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8265 				if (!tcp_check_policy(tcp, first_mp,
8266 				    ipha, NULL, secure, ipsec_mctl)) {
8267 					/*
8268 					 * tcp_check_policy called
8269 					 * ip_drop_packet() on failure.
8270 					 */
8271 					return;
8272 				}
8273 			}
8274 		}
8275 	} else if (ipsec_mctl) {
8276 		/*
8277 		 * This is a hard_bound connection. IP has already
8278 		 * verified policy. We don't have to do it again.
8279 		 */
8280 		freeb(first_mp);
8281 		first_mp = mp;
8282 		ipsec_mctl = B_FALSE;
8283 	}
8284 
8285 	seg_ack = ABE32_TO_U32(tcph->th_ack);
8286 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8287 	/*
8288 	 * TCP SHOULD check that the TCP sequence number contained in
8289 	 * payload of the ICMP error message is within the range
8290 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8291 	 */
8292 	if (SEQ_LT(seg_seq, tcp->tcp_suna) ||
8293 		SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8294 		SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8295 		/*
8296 		 * If the ICMP message is bogus, should we kill the
8297 		 * connection, or should we just drop the bogus ICMP
8298 		 * message? It would probably make more sense to just
8299 		 * drop the message so that if this one managed to get
8300 		 * in, the real connection should not suffer.
8301 		 */
8302 		goto noticmpv4;
8303 	}
8304 
8305 	switch (icmph->icmph_type) {
8306 	case ICMP_DEST_UNREACHABLE:
8307 		switch (icmph->icmph_code) {
8308 		case ICMP_FRAGMENTATION_NEEDED:
8309 			/*
8310 			 * Reduce the MSS based on the new MTU.  This will
8311 			 * eliminate any fragmentation locally.
8312 			 * N.B.  There may well be some funny side-effects on
8313 			 * the local send policy and the remote receive policy.
8314 			 * Pending further research, we provide
8315 			 * tcp_ignore_path_mtu just in case this proves
8316 			 * disastrous somewhere.
8317 			 *
8318 			 * After updating the MSS, retransmit part of the
8319 			 * dropped segment using the new mss by calling
8320 			 * tcp_wput_data().  Need to adjust all those
8321 			 * params to make sure tcp_wput_data() work properly.
8322 			 */
8323 			if (tcp_ignore_path_mtu)
8324 				break;
8325 
8326 			/*
8327 			 * Decrease the MSS by time stamp options
8328 			 * IP options and IPSEC options. tcp_hdr_len
8329 			 * includes time stamp option and IP option
8330 			 * length.
8331 			 */
8332 
8333 			new_mss = ntohs(icmph->icmph_du_mtu) -
8334 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8335 
8336 			/*
8337 			 * Only update the MSS if the new one is
8338 			 * smaller than the previous one.  This is
8339 			 * to avoid problems when getting multiple
8340 			 * ICMP errors for the same MTU.
8341 			 */
8342 			if (new_mss >= tcp->tcp_mss)
8343 				break;
8344 
8345 			/*
8346 			 * Stop doing PMTU if new_mss is less than 68
8347 			 * or less than tcp_mss_min.
8348 			 * The value 68 comes from rfc 1191.
8349 			 */
8350 			if (new_mss < MAX(68, tcp_mss_min))
8351 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8352 				    0;
8353 
8354 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8355 			ASSERT(ratio >= 1);
8356 			tcp_mss_set(tcp, new_mss);
8357 
8358 			/*
8359 			 * Make sure we have something to
8360 			 * send.
8361 			 */
8362 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8363 			    (tcp->tcp_xmit_head != NULL)) {
8364 				/*
8365 				 * Shrink tcp_cwnd in
8366 				 * proportion to the old MSS/new MSS.
8367 				 */
8368 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8369 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8370 				    (tcp->tcp_unsent == 0)) {
8371 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8372 				} else {
8373 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8374 				}
8375 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8376 				tcp->tcp_rexmit = B_TRUE;
8377 				tcp->tcp_dupack_cnt = 0;
8378 				tcp->tcp_snd_burst = TCP_CWND_SS;
8379 				tcp_ss_rexmit(tcp);
8380 			}
8381 			break;
8382 		case ICMP_PORT_UNREACHABLE:
8383 		case ICMP_PROTOCOL_UNREACHABLE:
8384 			switch (tcp->tcp_state) {
8385 			case TCPS_SYN_SENT:
8386 			case TCPS_SYN_RCVD:
8387 				/*
8388 				 * ICMP can snipe away incipient
8389 				 * TCP connections as long as
8390 				 * seq number is same as initial
8391 				 * send seq number.
8392 				 */
8393 				if (seg_seq == tcp->tcp_iss) {
8394 					(void) tcp_clean_death(tcp,
8395 					    ECONNREFUSED, 6);
8396 				}
8397 				break;
8398 			}
8399 			break;
8400 		case ICMP_HOST_UNREACHABLE:
8401 		case ICMP_NET_UNREACHABLE:
8402 			/* Record the error in case we finally time out. */
8403 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8404 				tcp->tcp_client_errno = EHOSTUNREACH;
8405 			else
8406 				tcp->tcp_client_errno = ENETUNREACH;
8407 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8408 				if (tcp->tcp_listener != NULL &&
8409 				    tcp->tcp_listener->tcp_syn_defense) {
8410 					/*
8411 					 * Ditch the half-open connection if we
8412 					 * suspect a SYN attack is under way.
8413 					 */
8414 					tcp_ip_ire_mark_advice(tcp);
8415 					(void) tcp_clean_death(tcp,
8416 					    tcp->tcp_client_errno, 7);
8417 				}
8418 			}
8419 			break;
8420 		default:
8421 			break;
8422 		}
8423 		break;
8424 	case ICMP_SOURCE_QUENCH: {
8425 		/*
8426 		 * use a global boolean to control
8427 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8428 		 * The default is false.
8429 		 */
8430 		if (tcp_icmp_source_quench) {
8431 			/*
8432 			 * Reduce the sending rate as if we got a
8433 			 * retransmit timeout
8434 			 */
8435 			uint32_t npkt;
8436 
8437 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8438 			    tcp->tcp_mss;
8439 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8440 			tcp->tcp_cwnd = tcp->tcp_mss;
8441 			tcp->tcp_cwnd_cnt = 0;
8442 		}
8443 		break;
8444 	}
8445 	}
8446 	freemsg(first_mp);
8447 }
8448 
8449 /*
8450  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8451  * error messages passed up by IP.
8452  * Assumes that IP has pulled up all the extension headers as well
8453  * as the ICMPv6 header.
8454  */
8455 static void
8456 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8457 {
8458 	icmp6_t *icmp6;
8459 	ip6_t	*ip6h;
8460 	uint16_t	iph_hdr_length;
8461 	tcpha_t	*tcpha;
8462 	uint8_t	*nexthdrp;
8463 	uint32_t new_mss;
8464 	uint32_t ratio;
8465 	boolean_t secure;
8466 	mblk_t *first_mp = mp;
8467 	size_t mp_size;
8468 	uint32_t seg_ack;
8469 	uint32_t seg_seq;
8470 
8471 	/*
8472 	 * The caller has determined if this is an IPSEC_IN packet and
8473 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8474 	 */
8475 	if (ipsec_mctl)
8476 		mp = mp->b_cont;
8477 
8478 	mp_size = MBLKL(mp);
8479 
8480 	/*
8481 	 * Verify that we have a complete IP header. If not, send it upstream.
8482 	 */
8483 	if (mp_size < sizeof (ip6_t)) {
8484 noticmpv6:
8485 		freemsg(first_mp);
8486 		return;
8487 	}
8488 
8489 	/*
8490 	 * Verify this is an ICMPV6 packet, else send it upstream.
8491 	 */
8492 	ip6h = (ip6_t *)mp->b_rptr;
8493 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8494 		iph_hdr_length = IPV6_HDR_LEN;
8495 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8496 	    &nexthdrp) ||
8497 	    *nexthdrp != IPPROTO_ICMPV6) {
8498 		goto noticmpv6;
8499 	}
8500 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8501 	ip6h = (ip6_t *)&icmp6[1];
8502 	/*
8503 	 * Verify if we have a complete ICMP and inner IP header.
8504 	 */
8505 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8506 		goto noticmpv6;
8507 
8508 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8509 		goto noticmpv6;
8510 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8511 	/*
8512 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8513 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8514 	 * packet.
8515 	 */
8516 	if ((*nexthdrp != IPPROTO_TCP) ||
8517 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8518 		goto noticmpv6;
8519 	}
8520 
8521 	/*
8522 	 * ICMP errors come on the right queue or come on
8523 	 * listener/global queue for detached connections and
8524 	 * get switched to the right queue. If it comes on the
8525 	 * right queue, policy check has already been done by IP
8526 	 * and thus free the first_mp without verifying the policy.
8527 	 * If it has come for a non-hard bound connection, we need
8528 	 * to verify policy as IP may not have done it.
8529 	 */
8530 	if (!tcp->tcp_hard_bound) {
8531 		if (ipsec_mctl) {
8532 			secure = ipsec_in_is_secure(first_mp);
8533 		} else {
8534 			secure = B_FALSE;
8535 		}
8536 		if (secure) {
8537 			/*
8538 			 * If we are willing to accept this in clear
8539 			 * we don't have to verify policy.
8540 			 */
8541 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8542 				if (!tcp_check_policy(tcp, first_mp,
8543 				    NULL, ip6h, secure, ipsec_mctl)) {
8544 					/*
8545 					 * tcp_check_policy called
8546 					 * ip_drop_packet() on failure.
8547 					 */
8548 					return;
8549 				}
8550 			}
8551 		}
8552 	} else if (ipsec_mctl) {
8553 		/*
8554 		 * This is a hard_bound connection. IP has already
8555 		 * verified policy. We don't have to do it again.
8556 		 */
8557 		freeb(first_mp);
8558 		first_mp = mp;
8559 		ipsec_mctl = B_FALSE;
8560 	}
8561 
8562 	seg_ack = ntohl(tcpha->tha_ack);
8563 	seg_seq = ntohl(tcpha->tha_seq);
8564 	/*
8565 	 * TCP SHOULD check that the TCP sequence number contained in
8566 	 * payload of the ICMP error message is within the range
8567 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8568 	 */
8569 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8570 	    SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8571 		/*
8572 		 * If the ICMP message is bogus, should we kill the
8573 		 * connection, or should we just drop the bogus ICMP
8574 		 * message? It would probably make more sense to just
8575 		 * drop the message so that if this one managed to get
8576 		 * in, the real connection should not suffer.
8577 		 */
8578 		goto noticmpv6;
8579 	}
8580 
8581 	switch (icmp6->icmp6_type) {
8582 	case ICMP6_PACKET_TOO_BIG:
8583 		/*
8584 		 * Reduce the MSS based on the new MTU.  This will
8585 		 * eliminate any fragmentation locally.
8586 		 * N.B.  There may well be some funny side-effects on
8587 		 * the local send policy and the remote receive policy.
8588 		 * Pending further research, we provide
8589 		 * tcp_ignore_path_mtu just in case this proves
8590 		 * disastrous somewhere.
8591 		 *
8592 		 * After updating the MSS, retransmit part of the
8593 		 * dropped segment using the new mss by calling
8594 		 * tcp_wput_data().  Need to adjust all those
8595 		 * params to make sure tcp_wput_data() work properly.
8596 		 */
8597 		if (tcp_ignore_path_mtu)
8598 			break;
8599 
8600 		/*
8601 		 * Decrease the MSS by time stamp options
8602 		 * IP options and IPSEC options. tcp_hdr_len
8603 		 * includes time stamp option and IP option
8604 		 * length.
8605 		 */
8606 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8607 			    tcp->tcp_ipsec_overhead;
8608 
8609 		/*
8610 		 * Only update the MSS if the new one is
8611 		 * smaller than the previous one.  This is
8612 		 * to avoid problems when getting multiple
8613 		 * ICMP errors for the same MTU.
8614 		 */
8615 		if (new_mss >= tcp->tcp_mss)
8616 			break;
8617 
8618 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8619 		ASSERT(ratio >= 1);
8620 		tcp_mss_set(tcp, new_mss);
8621 
8622 		/*
8623 		 * Make sure we have something to
8624 		 * send.
8625 		 */
8626 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8627 		    (tcp->tcp_xmit_head != NULL)) {
8628 			/*
8629 			 * Shrink tcp_cwnd in
8630 			 * proportion to the old MSS/new MSS.
8631 			 */
8632 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8633 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8634 			    (tcp->tcp_unsent == 0)) {
8635 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8636 			} else {
8637 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8638 			}
8639 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8640 			tcp->tcp_rexmit = B_TRUE;
8641 			tcp->tcp_dupack_cnt = 0;
8642 			tcp->tcp_snd_burst = TCP_CWND_SS;
8643 			tcp_ss_rexmit(tcp);
8644 		}
8645 		break;
8646 
8647 	case ICMP6_DST_UNREACH:
8648 		switch (icmp6->icmp6_code) {
8649 		case ICMP6_DST_UNREACH_NOPORT:
8650 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8651 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8652 			    (seg_seq == tcp->tcp_iss)) {
8653 				(void) tcp_clean_death(tcp,
8654 				    ECONNREFUSED, 8);
8655 			}
8656 			break;
8657 
8658 		case ICMP6_DST_UNREACH_ADMIN:
8659 		case ICMP6_DST_UNREACH_NOROUTE:
8660 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8661 		case ICMP6_DST_UNREACH_ADDR:
8662 			/* Record the error in case we finally time out. */
8663 			tcp->tcp_client_errno = EHOSTUNREACH;
8664 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8665 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8666 			    (seg_seq == tcp->tcp_iss)) {
8667 				if (tcp->tcp_listener != NULL &&
8668 				    tcp->tcp_listener->tcp_syn_defense) {
8669 					/*
8670 					 * Ditch the half-open connection if we
8671 					 * suspect a SYN attack is under way.
8672 					 */
8673 					tcp_ip_ire_mark_advice(tcp);
8674 					(void) tcp_clean_death(tcp,
8675 					    tcp->tcp_client_errno, 9);
8676 				}
8677 			}
8678 
8679 
8680 			break;
8681 		default:
8682 			break;
8683 		}
8684 		break;
8685 
8686 	case ICMP6_PARAM_PROB:
8687 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8688 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8689 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8690 		    (uchar_t *)nexthdrp) {
8691 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8692 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8693 				(void) tcp_clean_death(tcp,
8694 				    ECONNREFUSED, 10);
8695 			}
8696 			break;
8697 		}
8698 		break;
8699 
8700 	case ICMP6_TIME_EXCEEDED:
8701 	default:
8702 		break;
8703 	}
8704 	freemsg(first_mp);
8705 }
8706 
8707 /*
8708  * IP recognizes seven kinds of bind requests:
8709  *
8710  * - A zero-length address binds only to the protocol number.
8711  *
8712  * - A 4-byte address is treated as a request to
8713  * validate that the address is a valid local IPv4
8714  * address, appropriate for an application to bind to.
8715  * IP does the verification, but does not make any note
8716  * of the address at this time.
8717  *
8718  * - A 16-byte address contains is treated as a request
8719  * to validate a local IPv6 address, as the 4-byte
8720  * address case above.
8721  *
8722  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8723  * use it for the inbound fanout of packets.
8724  *
8725  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8726  * use it for the inbound fanout of packets.
8727  *
8728  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8729  * information consisting of local and remote addresses
8730  * and ports.  In this case, the addresses are both
8731  * validated as appropriate for this operation, and, if
8732  * so, the information is retained for use in the
8733  * inbound fanout.
8734  *
8735  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8736  * fanout information, like the 12-byte case above.
8737  *
8738  * IP will also fill in the IRE request mblk with information
8739  * regarding our peer.  In all cases, we notify IP of our protocol
8740  * type by appending a single protocol byte to the bind request.
8741  */
8742 static mblk_t *
8743 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8744 {
8745 	char	*cp;
8746 	mblk_t	*mp;
8747 	struct T_bind_req *tbr;
8748 	ipa_conn_t	*ac;
8749 	ipa6_conn_t	*ac6;
8750 	sin_t		*sin;
8751 	sin6_t		*sin6;
8752 
8753 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
8754 	ASSERT((tcp->tcp_family == AF_INET &&
8755 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8756 	    (tcp->tcp_family == AF_INET6 &&
8757 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8758 	    tcp->tcp_ipversion == IPV6_VERSION)));
8759 
8760 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
8761 	if (!mp)
8762 		return (mp);
8763 	mp->b_datap->db_type = M_PROTO;
8764 	tbr = (struct T_bind_req *)mp->b_rptr;
8765 	tbr->PRIM_type = bind_prim;
8766 	tbr->ADDR_offset = sizeof (*tbr);
8767 	tbr->CONIND_number = 0;
8768 	tbr->ADDR_length = addr_length;
8769 	cp = (char *)&tbr[1];
8770 	switch (addr_length) {
8771 	case sizeof (ipa_conn_t):
8772 		ASSERT(tcp->tcp_family == AF_INET);
8773 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8774 
8775 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8776 		if (mp->b_cont == NULL) {
8777 			freemsg(mp);
8778 			return (NULL);
8779 		}
8780 		mp->b_cont->b_wptr += sizeof (ire_t);
8781 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8782 
8783 		/* cp known to be 32 bit aligned */
8784 		ac = (ipa_conn_t *)cp;
8785 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
8786 		ac->ac_faddr = tcp->tcp_remote;
8787 		ac->ac_fport = tcp->tcp_fport;
8788 		ac->ac_lport = tcp->tcp_lport;
8789 		tcp->tcp_hard_binding = 1;
8790 		break;
8791 
8792 	case sizeof (ipa6_conn_t):
8793 		ASSERT(tcp->tcp_family == AF_INET6);
8794 
8795 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8796 		if (mp->b_cont == NULL) {
8797 			freemsg(mp);
8798 			return (NULL);
8799 		}
8800 		mp->b_cont->b_wptr += sizeof (ire_t);
8801 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8802 
8803 		/* cp known to be 32 bit aligned */
8804 		ac6 = (ipa6_conn_t *)cp;
8805 		if (tcp->tcp_ipversion == IPV4_VERSION) {
8806 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
8807 			    &ac6->ac6_laddr);
8808 		} else {
8809 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
8810 		}
8811 		ac6->ac6_faddr = tcp->tcp_remote_v6;
8812 		ac6->ac6_fport = tcp->tcp_fport;
8813 		ac6->ac6_lport = tcp->tcp_lport;
8814 		tcp->tcp_hard_binding = 1;
8815 		break;
8816 
8817 	case sizeof (sin_t):
8818 		/*
8819 		 * NOTE: IPV6_ADDR_LEN also has same size.
8820 		 * Use family to discriminate.
8821 		 */
8822 		if (tcp->tcp_family == AF_INET) {
8823 			sin = (sin_t *)cp;
8824 
8825 			*sin = sin_null;
8826 			sin->sin_family = AF_INET;
8827 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
8828 			sin->sin_port = tcp->tcp_lport;
8829 			break;
8830 		} else {
8831 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
8832 		}
8833 		break;
8834 
8835 	case sizeof (sin6_t):
8836 		ASSERT(tcp->tcp_family == AF_INET6);
8837 		sin6 = (sin6_t *)cp;
8838 
8839 		*sin6 = sin6_null;
8840 		sin6->sin6_family = AF_INET6;
8841 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
8842 		sin6->sin6_port = tcp->tcp_lport;
8843 		break;
8844 
8845 	case IP_ADDR_LEN:
8846 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8847 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
8848 		break;
8849 
8850 	}
8851 	/* Add protocol number to end */
8852 	cp[addr_length] = (char)IPPROTO_TCP;
8853 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
8854 	return (mp);
8855 }
8856 
8857 /*
8858  * Notify IP that we are having trouble with this connection.  IP should
8859  * blow the IRE away and start over.
8860  */
8861 static void
8862 tcp_ip_notify(tcp_t *tcp)
8863 {
8864 	struct iocblk	*iocp;
8865 	ipid_t	*ipid;
8866 	mblk_t	*mp;
8867 
8868 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8869 	if (tcp->tcp_ipversion == IPV6_VERSION)
8870 		return;
8871 
8872 	mp = mkiocb(IP_IOCTL);
8873 	if (mp == NULL)
8874 		return;
8875 
8876 	iocp = (struct iocblk *)mp->b_rptr;
8877 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8878 
8879 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8880 	if (!mp->b_cont) {
8881 		freeb(mp);
8882 		return;
8883 	}
8884 
8885 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8886 	mp->b_cont->b_wptr += iocp->ioc_count;
8887 	bzero(ipid, sizeof (*ipid));
8888 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8889 	ipid->ipid_ire_type = IRE_CACHE;
8890 	ipid->ipid_addr_offset = sizeof (ipid_t);
8891 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8892 	/*
8893 	 * Note: in the case of source routing we want to blow away the
8894 	 * route to the first source route hop.
8895 	 */
8896 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8897 	    sizeof (tcp->tcp_ipha->ipha_dst));
8898 
8899 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8900 }
8901 
8902 /* Unlink and return any mblk that looks like it contains an ire */
8903 static mblk_t *
8904 tcp_ire_mp(mblk_t *mp)
8905 {
8906 	mblk_t	*prev_mp;
8907 
8908 	for (;;) {
8909 		prev_mp = mp;
8910 		mp = mp->b_cont;
8911 		if (mp == NULL)
8912 			break;
8913 		switch (DB_TYPE(mp)) {
8914 		case IRE_DB_TYPE:
8915 		case IRE_DB_REQ_TYPE:
8916 			if (prev_mp != NULL)
8917 				prev_mp->b_cont = mp->b_cont;
8918 			mp->b_cont = NULL;
8919 			return (mp);
8920 		default:
8921 			break;
8922 		}
8923 	}
8924 	return (mp);
8925 }
8926 
8927 /*
8928  * Timer callback routine for keepalive probe.  We do a fake resend of
8929  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8930  * check to see if we have heard anything from the other end for the last
8931  * RTO period.  If we have, set the timer to expire for another
8932  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8933  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8934  * the timeout if we have not heard from the other side.  If for more than
8935  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8936  * kill the connection unless the keepalive abort threshold is 0.  In
8937  * that case, we will probe "forever."
8938  */
8939 static void
8940 tcp_keepalive_killer(void *arg)
8941 {
8942 	mblk_t	*mp;
8943 	conn_t	*connp = (conn_t *)arg;
8944 	tcp_t  	*tcp = connp->conn_tcp;
8945 	int32_t	firetime;
8946 	int32_t	idletime;
8947 	int32_t	ka_intrvl;
8948 
8949 	tcp->tcp_ka_tid = 0;
8950 
8951 	if (tcp->tcp_fused)
8952 		return;
8953 
8954 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
8955 	ka_intrvl = tcp->tcp_ka_interval;
8956 
8957 	/*
8958 	 * Keepalive probe should only be sent if the application has not
8959 	 * done a close on the connection.
8960 	 */
8961 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8962 		return;
8963 	}
8964 	/* Timer fired too early, restart it. */
8965 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8966 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8967 		    MSEC_TO_TICK(ka_intrvl));
8968 		return;
8969 	}
8970 
8971 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8972 	/*
8973 	 * If we have not heard from the other side for a long
8974 	 * time, kill the connection unless the keepalive abort
8975 	 * threshold is 0.  In that case, we will probe "forever."
8976 	 */
8977 	if (tcp->tcp_ka_abort_thres != 0 &&
8978 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8979 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
8980 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8981 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8982 		return;
8983 	}
8984 
8985 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8986 	    idletime >= ka_intrvl) {
8987 		/* Fake resend of last ACKed byte. */
8988 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8989 
8990 		if (mp1 != NULL) {
8991 			*mp1->b_wptr++ = '\0';
8992 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8993 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8994 			freeb(mp1);
8995 			/*
8996 			 * if allocation failed, fall through to start the
8997 			 * timer back.
8998 			 */
8999 			if (mp != NULL) {
9000 				TCP_RECORD_TRACE(tcp, mp,
9001 				    TCP_TRACE_SEND_PKT);
9002 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9003 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
9004 				if (tcp->tcp_ka_last_intrvl != 0) {
9005 					/*
9006 					 * We should probe again at least
9007 					 * in ka_intrvl, but not more than
9008 					 * tcp_rexmit_interval_max.
9009 					 */
9010 					firetime = MIN(ka_intrvl - 1,
9011 					    tcp->tcp_ka_last_intrvl << 1);
9012 					if (firetime > tcp_rexmit_interval_max)
9013 						firetime =
9014 						    tcp_rexmit_interval_max;
9015 				} else {
9016 					firetime = tcp->tcp_rto;
9017 				}
9018 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9019 				    tcp_keepalive_killer,
9020 				    MSEC_TO_TICK(firetime));
9021 				tcp->tcp_ka_last_intrvl = firetime;
9022 				return;
9023 			}
9024 		}
9025 	} else {
9026 		tcp->tcp_ka_last_intrvl = 0;
9027 	}
9028 
9029 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9030 	if ((firetime = ka_intrvl - idletime) < 0) {
9031 		firetime = ka_intrvl;
9032 	}
9033 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9034 	    MSEC_TO_TICK(firetime));
9035 }
9036 
9037 int
9038 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9039 {
9040 	queue_t	*q = tcp->tcp_rq;
9041 	int32_t	mss = tcp->tcp_mss;
9042 	int	maxpsz;
9043 
9044 	if (TCP_IS_DETACHED(tcp))
9045 		return (mss);
9046 
9047 	if (tcp->tcp_fused) {
9048 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9049 		mss = INFPSZ;
9050 	} else if (tcp->tcp_mdt || tcp->tcp_maxpsz == 0) {
9051 		/*
9052 		 * Set the sd_qn_maxpsz according to the socket send buffer
9053 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9054 		 * instruct the stream head to copyin user data into contiguous
9055 		 * kernel-allocated buffers without breaking it up into smaller
9056 		 * chunks.  We round up the buffer size to the nearest SMSS.
9057 		 */
9058 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9059 		if (tcp->tcp_kssl_ctx == NULL)
9060 			mss = INFPSZ;
9061 		else
9062 			mss = SSL3_MAX_RECORD_LEN;
9063 	} else {
9064 		/*
9065 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9066 		 * (and a multiple of the mss).  This instructs the stream
9067 		 * head to break down larger than SMSS writes into SMSS-
9068 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9069 		 */
9070 		maxpsz = tcp->tcp_maxpsz * mss;
9071 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9072 			maxpsz = tcp->tcp_xmit_hiwater/2;
9073 			/* Round up to nearest mss */
9074 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9075 		}
9076 	}
9077 	(void) setmaxps(q, maxpsz);
9078 	tcp->tcp_wq->q_maxpsz = maxpsz;
9079 
9080 	if (set_maxblk)
9081 		(void) mi_set_sth_maxblk(q, mss);
9082 
9083 	return (mss);
9084 }
9085 
9086 /*
9087  * Extract option values from a tcp header.  We put any found values into the
9088  * tcpopt struct and return a bitmask saying which options were found.
9089  */
9090 static int
9091 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9092 {
9093 	uchar_t		*endp;
9094 	int		len;
9095 	uint32_t	mss;
9096 	uchar_t		*up = (uchar_t *)tcph;
9097 	int		found = 0;
9098 	int32_t		sack_len;
9099 	tcp_seq		sack_begin, sack_end;
9100 	tcp_t		*tcp;
9101 
9102 	endp = up + TCP_HDR_LENGTH(tcph);
9103 	up += TCP_MIN_HEADER_LENGTH;
9104 	while (up < endp) {
9105 		len = endp - up;
9106 		switch (*up) {
9107 		case TCPOPT_EOL:
9108 			break;
9109 
9110 		case TCPOPT_NOP:
9111 			up++;
9112 			continue;
9113 
9114 		case TCPOPT_MAXSEG:
9115 			if (len < TCPOPT_MAXSEG_LEN ||
9116 			    up[1] != TCPOPT_MAXSEG_LEN)
9117 				break;
9118 
9119 			mss = BE16_TO_U16(up+2);
9120 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9121 			tcpopt->tcp_opt_mss = mss;
9122 			found |= TCP_OPT_MSS_PRESENT;
9123 
9124 			up += TCPOPT_MAXSEG_LEN;
9125 			continue;
9126 
9127 		case TCPOPT_WSCALE:
9128 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9129 				break;
9130 
9131 			if (up[2] > TCP_MAX_WINSHIFT)
9132 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9133 			else
9134 				tcpopt->tcp_opt_wscale = up[2];
9135 			found |= TCP_OPT_WSCALE_PRESENT;
9136 
9137 			up += TCPOPT_WS_LEN;
9138 			continue;
9139 
9140 		case TCPOPT_SACK_PERMITTED:
9141 			if (len < TCPOPT_SACK_OK_LEN ||
9142 			    up[1] != TCPOPT_SACK_OK_LEN)
9143 				break;
9144 			found |= TCP_OPT_SACK_OK_PRESENT;
9145 			up += TCPOPT_SACK_OK_LEN;
9146 			continue;
9147 
9148 		case TCPOPT_SACK:
9149 			if (len <= 2 || up[1] <= 2 || len < up[1])
9150 				break;
9151 
9152 			/* If TCP is not interested in SACK blks... */
9153 			if ((tcp = tcpopt->tcp) == NULL) {
9154 				up += up[1];
9155 				continue;
9156 			}
9157 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9158 			up += TCPOPT_HEADER_LEN;
9159 
9160 			/*
9161 			 * If the list is empty, allocate one and assume
9162 			 * nothing is sack'ed.
9163 			 */
9164 			ASSERT(tcp->tcp_sack_info != NULL);
9165 			if (tcp->tcp_notsack_list == NULL) {
9166 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9167 				    tcp->tcp_suna, tcp->tcp_snxt,
9168 				    &(tcp->tcp_num_notsack_blk),
9169 				    &(tcp->tcp_cnt_notsack_list));
9170 
9171 				/*
9172 				 * Make sure tcp_notsack_list is not NULL.
9173 				 * This happens when kmem_alloc(KM_NOSLEEP)
9174 				 * returns NULL.
9175 				 */
9176 				if (tcp->tcp_notsack_list == NULL) {
9177 					up += sack_len;
9178 					continue;
9179 				}
9180 				tcp->tcp_fack = tcp->tcp_suna;
9181 			}
9182 
9183 			while (sack_len > 0) {
9184 				if (up + 8 > endp) {
9185 					up = endp;
9186 					break;
9187 				}
9188 				sack_begin = BE32_TO_U32(up);
9189 				up += 4;
9190 				sack_end = BE32_TO_U32(up);
9191 				up += 4;
9192 				sack_len -= 8;
9193 				/*
9194 				 * Bounds checking.  Make sure the SACK
9195 				 * info is within tcp_suna and tcp_snxt.
9196 				 * If this SACK blk is out of bound, ignore
9197 				 * it but continue to parse the following
9198 				 * blks.
9199 				 */
9200 				if (SEQ_LEQ(sack_end, sack_begin) ||
9201 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9202 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9203 					continue;
9204 				}
9205 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9206 				    sack_begin, sack_end,
9207 				    &(tcp->tcp_num_notsack_blk),
9208 				    &(tcp->tcp_cnt_notsack_list));
9209 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9210 					tcp->tcp_fack = sack_end;
9211 				}
9212 			}
9213 			found |= TCP_OPT_SACK_PRESENT;
9214 			continue;
9215 
9216 		case TCPOPT_TSTAMP:
9217 			if (len < TCPOPT_TSTAMP_LEN ||
9218 			    up[1] != TCPOPT_TSTAMP_LEN)
9219 				break;
9220 
9221 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9222 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9223 
9224 			found |= TCP_OPT_TSTAMP_PRESENT;
9225 
9226 			up += TCPOPT_TSTAMP_LEN;
9227 			continue;
9228 
9229 		default:
9230 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9231 				break;
9232 			up += up[1];
9233 			continue;
9234 		}
9235 		break;
9236 	}
9237 	return (found);
9238 }
9239 
9240 /*
9241  * Set the mss associated with a particular tcp based on its current value,
9242  * and a new one passed in. Observe minimums and maximums, and reset
9243  * other state variables that we want to view as multiples of mss.
9244  *
9245  * This function is called in various places mainly because
9246  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
9247  *    other side's SYN/SYN-ACK packet arrives.
9248  * 2) PMTUd may get us a new MSS.
9249  * 3) If the other side stops sending us timestamp option, we need to
9250  *    increase the MSS size to use the extra bytes available.
9251  */
9252 static void
9253 tcp_mss_set(tcp_t *tcp, uint32_t mss)
9254 {
9255 	uint32_t	mss_max;
9256 
9257 	if (tcp->tcp_ipversion == IPV4_VERSION)
9258 		mss_max = tcp_mss_max_ipv4;
9259 	else
9260 		mss_max = tcp_mss_max_ipv6;
9261 
9262 	if (mss < tcp_mss_min)
9263 		mss = tcp_mss_min;
9264 	if (mss > mss_max)
9265 		mss = mss_max;
9266 	/*
9267 	 * Unless naglim has been set by our client to
9268 	 * a non-mss value, force naglim to track mss.
9269 	 * This can help to aggregate small writes.
9270 	 */
9271 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9272 		tcp->tcp_naglim = mss;
9273 	/*
9274 	 * TCP should be able to buffer at least 4 MSS data for obvious
9275 	 * performance reason.
9276 	 */
9277 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9278 		tcp->tcp_xmit_hiwater = mss << 2;
9279 
9280 	/*
9281 	 * Check if we need to apply the tcp_init_cwnd here.  If
9282 	 * it is set and the MSS gets bigger (should not happen
9283 	 * normally), we need to adjust the resulting tcp_cwnd properly.
9284 	 * The new tcp_cwnd should not get bigger.
9285 	 */
9286 	if (tcp->tcp_init_cwnd == 0) {
9287 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
9288 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
9289 	} else {
9290 		if (tcp->tcp_mss < mss) {
9291 			tcp->tcp_cwnd = MAX(1,
9292 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
9293 		} else {
9294 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
9295 		}
9296 	}
9297 	tcp->tcp_mss = mss;
9298 	tcp->tcp_cwnd_cnt = 0;
9299 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9300 }
9301 
9302 static int
9303 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9304 {
9305 	tcp_t		*tcp = NULL;
9306 	conn_t		*connp;
9307 	int		err;
9308 	dev_t		conn_dev;
9309 	zoneid_t	zoneid = getzoneid();
9310 
9311 	/*
9312 	 * Special case for install: miniroot needs to be able to access files
9313 	 * via NFS as though it were always in the global zone.
9314 	 */
9315 	if (credp == kcred && nfs_global_client_only != 0)
9316 		zoneid = GLOBAL_ZONEID;
9317 
9318 	if (q->q_ptr != NULL)
9319 		return (0);
9320 
9321 	if (sflag == MODOPEN) {
9322 		/*
9323 		 * This is a special case. The purpose of a modopen
9324 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
9325 		 * through for MIB browsers. Everything else is failed.
9326 		 */
9327 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9328 
9329 		if (connp == NULL)
9330 			return (ENOMEM);
9331 
9332 		connp->conn_flags |= IPCL_TCPMOD;
9333 		connp->conn_cred = credp;
9334 		connp->conn_zoneid = zoneid;
9335 		q->q_ptr = WR(q)->q_ptr = connp;
9336 		crhold(credp);
9337 		q->q_qinfo = &tcp_mod_rinit;
9338 		WR(q)->q_qinfo = &tcp_mod_winit;
9339 		qprocson(q);
9340 		return (0);
9341 	}
9342 
9343 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
9344 		return (EBUSY);
9345 
9346 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9347 
9348 	if (flag & SO_ACCEPTOR) {
9349 		q->q_qinfo = &tcp_acceptor_rinit;
9350 		q->q_ptr = (void *)conn_dev;
9351 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9352 		WR(q)->q_ptr = (void *)conn_dev;
9353 		qprocson(q);
9354 		return (0);
9355 	}
9356 
9357 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9358 	if (connp == NULL) {
9359 		inet_minor_free(ip_minor_arena, conn_dev);
9360 		q->q_ptr = NULL;
9361 		return (ENOSR);
9362 	}
9363 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9364 	tcp = connp->conn_tcp;
9365 
9366 	q->q_ptr = WR(q)->q_ptr = connp;
9367 	if (getmajor(*devp) == TCP6_MAJ) {
9368 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9369 		connp->conn_send = ip_output_v6;
9370 		connp->conn_af_isv6 = B_TRUE;
9371 		connp->conn_pkt_isv6 = B_TRUE;
9372 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9373 		tcp->tcp_ipversion = IPV6_VERSION;
9374 		tcp->tcp_family = AF_INET6;
9375 		tcp->tcp_mss = tcp_mss_def_ipv6;
9376 	} else {
9377 		connp->conn_flags |= IPCL_TCP4;
9378 		connp->conn_send = ip_output;
9379 		connp->conn_af_isv6 = B_FALSE;
9380 		connp->conn_pkt_isv6 = B_FALSE;
9381 		tcp->tcp_ipversion = IPV4_VERSION;
9382 		tcp->tcp_family = AF_INET;
9383 		tcp->tcp_mss = tcp_mss_def_ipv4;
9384 	}
9385 
9386 	/*
9387 	 * TCP keeps a copy of cred for cache locality reasons but
9388 	 * we put a reference only once. If connp->conn_cred
9389 	 * becomes invalid, tcp_cred should also be set to NULL.
9390 	 */
9391 	tcp->tcp_cred = connp->conn_cred = credp;
9392 	crhold(connp->conn_cred);
9393 	tcp->tcp_cpid = curproc->p_pid;
9394 	connp->conn_zoneid = zoneid;
9395 	connp->conn_mlp_type = mlptSingle;
9396 	connp->conn_ulp_labeled = !is_system_labeled();
9397 
9398 	/*
9399 	 * If the caller has the process-wide flag set, then default to MAC
9400 	 * exempt mode.  This allows read-down to unlabeled hosts.
9401 	 */
9402 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9403 		connp->conn_mac_exempt = B_TRUE;
9404 
9405 	connp->conn_dev = conn_dev;
9406 
9407 	ASSERT(q->q_qinfo == &tcp_rinit);
9408 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9409 
9410 	if (flag & SO_SOCKSTR) {
9411 		/*
9412 		 * No need to insert a socket in tcp acceptor hash.
9413 		 * If it was a socket acceptor stream, we dealt with
9414 		 * it above. A socket listener can never accept a
9415 		 * connection and doesn't need acceptor_id.
9416 		 */
9417 		connp->conn_flags |= IPCL_SOCKET;
9418 		tcp->tcp_issocket = 1;
9419 		WR(q)->q_qinfo = &tcp_sock_winit;
9420 	} else {
9421 #ifdef	_ILP32
9422 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9423 #else
9424 		tcp->tcp_acceptor_id = conn_dev;
9425 #endif	/* _ILP32 */
9426 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9427 	}
9428 
9429 	if (tcp_trace)
9430 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9431 
9432 	err = tcp_init(tcp, q);
9433 	if (err != 0) {
9434 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9435 		tcp_acceptor_hash_remove(tcp);
9436 		CONN_DEC_REF(connp);
9437 		q->q_ptr = WR(q)->q_ptr = NULL;
9438 		return (err);
9439 	}
9440 
9441 	RD(q)->q_hiwat = tcp_recv_hiwat;
9442 	tcp->tcp_rwnd = tcp_recv_hiwat;
9443 
9444 	/* Non-zero default values */
9445 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9446 	/*
9447 	 * Put the ref for TCP. Ref for IP was already put
9448 	 * by ipcl_conn_create. Also Make the conn_t globally
9449 	 * visible to walkers
9450 	 */
9451 	mutex_enter(&connp->conn_lock);
9452 	CONN_INC_REF_LOCKED(connp);
9453 	ASSERT(connp->conn_ref == 2);
9454 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9455 	mutex_exit(&connp->conn_lock);
9456 
9457 	qprocson(q);
9458 	return (0);
9459 }
9460 
9461 /*
9462  * Some TCP options can be "set" by requesting them in the option
9463  * buffer. This is needed for XTI feature test though we do not
9464  * allow it in general. We interpret that this mechanism is more
9465  * applicable to OSI protocols and need not be allowed in general.
9466  * This routine filters out options for which it is not allowed (most)
9467  * and lets through those (few) for which it is. [ The XTI interface
9468  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9469  * ever implemented will have to be allowed here ].
9470  */
9471 static boolean_t
9472 tcp_allow_connopt_set(int level, int name)
9473 {
9474 
9475 	switch (level) {
9476 	case IPPROTO_TCP:
9477 		switch (name) {
9478 		case TCP_NODELAY:
9479 			return (B_TRUE);
9480 		default:
9481 			return (B_FALSE);
9482 		}
9483 		/*NOTREACHED*/
9484 	default:
9485 		return (B_FALSE);
9486 	}
9487 	/*NOTREACHED*/
9488 }
9489 
9490 /*
9491  * This routine gets default values of certain options whose default
9492  * values are maintained by protocol specific code
9493  */
9494 /* ARGSUSED */
9495 int
9496 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9497 {
9498 	int32_t	*i1 = (int32_t *)ptr;
9499 
9500 	switch (level) {
9501 	case IPPROTO_TCP:
9502 		switch (name) {
9503 		case TCP_NOTIFY_THRESHOLD:
9504 			*i1 = tcp_ip_notify_interval;
9505 			break;
9506 		case TCP_ABORT_THRESHOLD:
9507 			*i1 = tcp_ip_abort_interval;
9508 			break;
9509 		case TCP_CONN_NOTIFY_THRESHOLD:
9510 			*i1 = tcp_ip_notify_cinterval;
9511 			break;
9512 		case TCP_CONN_ABORT_THRESHOLD:
9513 			*i1 = tcp_ip_abort_cinterval;
9514 			break;
9515 		default:
9516 			return (-1);
9517 		}
9518 		break;
9519 	case IPPROTO_IP:
9520 		switch (name) {
9521 		case IP_TTL:
9522 			*i1 = tcp_ipv4_ttl;
9523 			break;
9524 		default:
9525 			return (-1);
9526 		}
9527 		break;
9528 	case IPPROTO_IPV6:
9529 		switch (name) {
9530 		case IPV6_UNICAST_HOPS:
9531 			*i1 = tcp_ipv6_hoplimit;
9532 			break;
9533 		default:
9534 			return (-1);
9535 		}
9536 		break;
9537 	default:
9538 		return (-1);
9539 	}
9540 	return (sizeof (int));
9541 }
9542 
9543 
9544 /*
9545  * TCP routine to get the values of options.
9546  */
9547 int
9548 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9549 {
9550 	int		*i1 = (int *)ptr;
9551 	conn_t		*connp = Q_TO_CONN(q);
9552 	tcp_t		*tcp = connp->conn_tcp;
9553 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9554 
9555 	switch (level) {
9556 	case SOL_SOCKET:
9557 		switch (name) {
9558 		case SO_LINGER:	{
9559 			struct linger *lgr = (struct linger *)ptr;
9560 
9561 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9562 			lgr->l_linger = tcp->tcp_lingertime;
9563 			}
9564 			return (sizeof (struct linger));
9565 		case SO_DEBUG:
9566 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9567 			break;
9568 		case SO_KEEPALIVE:
9569 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9570 			break;
9571 		case SO_DONTROUTE:
9572 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9573 			break;
9574 		case SO_USELOOPBACK:
9575 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9576 			break;
9577 		case SO_BROADCAST:
9578 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9579 			break;
9580 		case SO_REUSEADDR:
9581 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9582 			break;
9583 		case SO_OOBINLINE:
9584 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9585 			break;
9586 		case SO_DGRAM_ERRIND:
9587 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9588 			break;
9589 		case SO_TYPE:
9590 			*i1 = SOCK_STREAM;
9591 			break;
9592 		case SO_SNDBUF:
9593 			*i1 = tcp->tcp_xmit_hiwater;
9594 			break;
9595 		case SO_RCVBUF:
9596 			*i1 = RD(q)->q_hiwat;
9597 			break;
9598 		case SO_SND_COPYAVOID:
9599 			*i1 = tcp->tcp_snd_zcopy_on ?
9600 			    SO_SND_COPYAVOID : 0;
9601 			break;
9602 		case SO_ALLZONES:
9603 			*i1 = connp->conn_allzones ? 1 : 0;
9604 			break;
9605 		case SO_ANON_MLP:
9606 			*i1 = connp->conn_anon_mlp;
9607 			break;
9608 		case SO_MAC_EXEMPT:
9609 			*i1 = connp->conn_mac_exempt;
9610 			break;
9611 		case SO_EXCLBIND:
9612 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9613 			break;
9614 		default:
9615 			return (-1);
9616 		}
9617 		break;
9618 	case IPPROTO_TCP:
9619 		switch (name) {
9620 		case TCP_NODELAY:
9621 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9622 			break;
9623 		case TCP_MAXSEG:
9624 			*i1 = tcp->tcp_mss;
9625 			break;
9626 		case TCP_NOTIFY_THRESHOLD:
9627 			*i1 = (int)tcp->tcp_first_timer_threshold;
9628 			break;
9629 		case TCP_ABORT_THRESHOLD:
9630 			*i1 = tcp->tcp_second_timer_threshold;
9631 			break;
9632 		case TCP_CONN_NOTIFY_THRESHOLD:
9633 			*i1 = tcp->tcp_first_ctimer_threshold;
9634 			break;
9635 		case TCP_CONN_ABORT_THRESHOLD:
9636 			*i1 = tcp->tcp_second_ctimer_threshold;
9637 			break;
9638 		case TCP_RECVDSTADDR:
9639 			*i1 = tcp->tcp_recvdstaddr;
9640 			break;
9641 		case TCP_ANONPRIVBIND:
9642 			*i1 = tcp->tcp_anon_priv_bind;
9643 			break;
9644 		case TCP_EXCLBIND:
9645 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9646 			break;
9647 		case TCP_INIT_CWND:
9648 			*i1 = tcp->tcp_init_cwnd;
9649 			break;
9650 		case TCP_KEEPALIVE_THRESHOLD:
9651 			*i1 = tcp->tcp_ka_interval;
9652 			break;
9653 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9654 			*i1 = tcp->tcp_ka_abort_thres;
9655 			break;
9656 		case TCP_CORK:
9657 			*i1 = tcp->tcp_cork;
9658 			break;
9659 		default:
9660 			return (-1);
9661 		}
9662 		break;
9663 	case IPPROTO_IP:
9664 		if (tcp->tcp_family != AF_INET)
9665 			return (-1);
9666 		switch (name) {
9667 		case IP_OPTIONS:
9668 		case T_IP_OPTIONS: {
9669 			/*
9670 			 * This is compatible with BSD in that in only return
9671 			 * the reverse source route with the final destination
9672 			 * as the last entry. The first 4 bytes of the option
9673 			 * will contain the final destination.
9674 			 */
9675 			int	opt_len;
9676 
9677 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9678 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9679 			ASSERT(opt_len >= 0);
9680 			/* Caller ensures enough space */
9681 			if (opt_len > 0) {
9682 				/*
9683 				 * TODO: Do we have to handle getsockopt on an
9684 				 * initiator as well?
9685 				 */
9686 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9687 			}
9688 			return (0);
9689 			}
9690 		case IP_TOS:
9691 		case T_IP_TOS:
9692 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9693 			break;
9694 		case IP_TTL:
9695 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9696 			break;
9697 		case IP_NEXTHOP:
9698 			/* Handled at IP level */
9699 			return (-EINVAL);
9700 		default:
9701 			return (-1);
9702 		}
9703 		break;
9704 	case IPPROTO_IPV6:
9705 		/*
9706 		 * IPPROTO_IPV6 options are only supported for sockets
9707 		 * that are using IPv6 on the wire.
9708 		 */
9709 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9710 			return (-1);
9711 		}
9712 		switch (name) {
9713 		case IPV6_UNICAST_HOPS:
9714 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9715 			break;	/* goto sizeof (int) option return */
9716 		case IPV6_BOUND_IF:
9717 			/* Zero if not set */
9718 			*i1 = tcp->tcp_bound_if;
9719 			break;	/* goto sizeof (int) option return */
9720 		case IPV6_RECVPKTINFO:
9721 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9722 				*i1 = 1;
9723 			else
9724 				*i1 = 0;
9725 			break;	/* goto sizeof (int) option return */
9726 		case IPV6_RECVTCLASS:
9727 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9728 				*i1 = 1;
9729 			else
9730 				*i1 = 0;
9731 			break;	/* goto sizeof (int) option return */
9732 		case IPV6_RECVHOPLIMIT:
9733 			if (tcp->tcp_ipv6_recvancillary &
9734 			    TCP_IPV6_RECVHOPLIMIT)
9735 				*i1 = 1;
9736 			else
9737 				*i1 = 0;
9738 			break;	/* goto sizeof (int) option return */
9739 		case IPV6_RECVHOPOPTS:
9740 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9741 				*i1 = 1;
9742 			else
9743 				*i1 = 0;
9744 			break;	/* goto sizeof (int) option return */
9745 		case IPV6_RECVDSTOPTS:
9746 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9747 				*i1 = 1;
9748 			else
9749 				*i1 = 0;
9750 			break;	/* goto sizeof (int) option return */
9751 		case _OLD_IPV6_RECVDSTOPTS:
9752 			if (tcp->tcp_ipv6_recvancillary &
9753 			    TCP_OLD_IPV6_RECVDSTOPTS)
9754 				*i1 = 1;
9755 			else
9756 				*i1 = 0;
9757 			break;	/* goto sizeof (int) option return */
9758 		case IPV6_RECVRTHDR:
9759 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9760 				*i1 = 1;
9761 			else
9762 				*i1 = 0;
9763 			break;	/* goto sizeof (int) option return */
9764 		case IPV6_RECVRTHDRDSTOPTS:
9765 			if (tcp->tcp_ipv6_recvancillary &
9766 			    TCP_IPV6_RECVRTDSTOPTS)
9767 				*i1 = 1;
9768 			else
9769 				*i1 = 0;
9770 			break;	/* goto sizeof (int) option return */
9771 		case IPV6_PKTINFO: {
9772 			/* XXX assumes that caller has room for max size! */
9773 			struct in6_pktinfo *pkti;
9774 
9775 			pkti = (struct in6_pktinfo *)ptr;
9776 			if (ipp->ipp_fields & IPPF_IFINDEX)
9777 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9778 			else
9779 				pkti->ipi6_ifindex = 0;
9780 			if (ipp->ipp_fields & IPPF_ADDR)
9781 				pkti->ipi6_addr = ipp->ipp_addr;
9782 			else
9783 				pkti->ipi6_addr = ipv6_all_zeros;
9784 			return (sizeof (struct in6_pktinfo));
9785 		}
9786 		case IPV6_TCLASS:
9787 			if (ipp->ipp_fields & IPPF_TCLASS)
9788 				*i1 = ipp->ipp_tclass;
9789 			else
9790 				*i1 = IPV6_FLOW_TCLASS(
9791 				    IPV6_DEFAULT_VERS_AND_FLOW);
9792 			break;	/* goto sizeof (int) option return */
9793 		case IPV6_NEXTHOP: {
9794 			sin6_t *sin6 = (sin6_t *)ptr;
9795 
9796 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9797 				return (0);
9798 			*sin6 = sin6_null;
9799 			sin6->sin6_family = AF_INET6;
9800 			sin6->sin6_addr = ipp->ipp_nexthop;
9801 			return (sizeof (sin6_t));
9802 		}
9803 		case IPV6_HOPOPTS:
9804 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9805 				return (0);
9806 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9807 				return (0);
9808 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9809 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9810 			if (tcp->tcp_label_len > 0) {
9811 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9812 				ptr[1] = (ipp->ipp_hopoptslen -
9813 				    tcp->tcp_label_len + 7) / 8 - 1;
9814 			}
9815 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9816 		case IPV6_RTHDRDSTOPTS:
9817 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9818 				return (0);
9819 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9820 			return (ipp->ipp_rtdstoptslen);
9821 		case IPV6_RTHDR:
9822 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9823 				return (0);
9824 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9825 			return (ipp->ipp_rthdrlen);
9826 		case IPV6_DSTOPTS:
9827 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9828 				return (0);
9829 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9830 			return (ipp->ipp_dstoptslen);
9831 		case IPV6_SRC_PREFERENCES:
9832 			return (ip6_get_src_preferences(connp,
9833 			    (uint32_t *)ptr));
9834 		case IPV6_PATHMTU: {
9835 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9836 
9837 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9838 				return (-1);
9839 
9840 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9841 				connp->conn_fport, mtuinfo));
9842 		}
9843 		default:
9844 			return (-1);
9845 		}
9846 		break;
9847 	default:
9848 		return (-1);
9849 	}
9850 	return (sizeof (int));
9851 }
9852 
9853 /*
9854  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9855  * Parameters are assumed to be verified by the caller.
9856  */
9857 /* ARGSUSED */
9858 int
9859 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9860     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9861     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9862 {
9863 	conn_t	*connp = Q_TO_CONN(q);
9864 	tcp_t	*tcp = connp->conn_tcp;
9865 	int	*i1 = (int *)invalp;
9866 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9867 	boolean_t checkonly;
9868 	int	reterr;
9869 
9870 	switch (optset_context) {
9871 	case SETFN_OPTCOM_CHECKONLY:
9872 		checkonly = B_TRUE;
9873 		/*
9874 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9875 		 * inlen != 0 implies value supplied and
9876 		 * 	we have to "pretend" to set it.
9877 		 * inlen == 0 implies that there is no
9878 		 * 	value part in T_CHECK request and just validation
9879 		 * done elsewhere should be enough, we just return here.
9880 		 */
9881 		if (inlen == 0) {
9882 			*outlenp = 0;
9883 			return (0);
9884 		}
9885 		break;
9886 	case SETFN_OPTCOM_NEGOTIATE:
9887 		checkonly = B_FALSE;
9888 		break;
9889 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9890 	case SETFN_CONN_NEGOTIATE:
9891 		checkonly = B_FALSE;
9892 		/*
9893 		 * Negotiating local and "association-related" options
9894 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9895 		 * primitives is allowed by XTI, but we choose
9896 		 * to not implement this style negotiation for Internet
9897 		 * protocols (We interpret it is a must for OSI world but
9898 		 * optional for Internet protocols) for all options.
9899 		 * [ Will do only for the few options that enable test
9900 		 * suites that our XTI implementation of this feature
9901 		 * works for transports that do allow it ]
9902 		 */
9903 		if (!tcp_allow_connopt_set(level, name)) {
9904 			*outlenp = 0;
9905 			return (EINVAL);
9906 		}
9907 		break;
9908 	default:
9909 		/*
9910 		 * We should never get here
9911 		 */
9912 		*outlenp = 0;
9913 		return (EINVAL);
9914 	}
9915 
9916 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9917 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9918 
9919 	/*
9920 	 * For TCP, we should have no ancillary data sent down
9921 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9922 	 * has to be zero.
9923 	 */
9924 	ASSERT(thisdg_attrs == NULL);
9925 
9926 	/*
9927 	 * For fixed length options, no sanity check
9928 	 * of passed in length is done. It is assumed *_optcom_req()
9929 	 * routines do the right thing.
9930 	 */
9931 
9932 	switch (level) {
9933 	case SOL_SOCKET:
9934 		switch (name) {
9935 		case SO_LINGER: {
9936 			struct linger *lgr = (struct linger *)invalp;
9937 
9938 			if (!checkonly) {
9939 				if (lgr->l_onoff) {
9940 					tcp->tcp_linger = 1;
9941 					tcp->tcp_lingertime = lgr->l_linger;
9942 				} else {
9943 					tcp->tcp_linger = 0;
9944 					tcp->tcp_lingertime = 0;
9945 				}
9946 				/* struct copy */
9947 				*(struct linger *)outvalp = *lgr;
9948 			} else {
9949 				if (!lgr->l_onoff) {
9950 				    ((struct linger *)outvalp)->l_onoff = 0;
9951 				    ((struct linger *)outvalp)->l_linger = 0;
9952 				} else {
9953 				    /* struct copy */
9954 				    *(struct linger *)outvalp = *lgr;
9955 				}
9956 			}
9957 			*outlenp = sizeof (struct linger);
9958 			return (0);
9959 		}
9960 		case SO_DEBUG:
9961 			if (!checkonly)
9962 				tcp->tcp_debug = onoff;
9963 			break;
9964 		case SO_KEEPALIVE:
9965 			if (checkonly) {
9966 				/* T_CHECK case */
9967 				break;
9968 			}
9969 
9970 			if (!onoff) {
9971 				if (tcp->tcp_ka_enabled) {
9972 					if (tcp->tcp_ka_tid != 0) {
9973 						(void) TCP_TIMER_CANCEL(tcp,
9974 						    tcp->tcp_ka_tid);
9975 						tcp->tcp_ka_tid = 0;
9976 					}
9977 					tcp->tcp_ka_enabled = 0;
9978 				}
9979 				break;
9980 			}
9981 			if (!tcp->tcp_ka_enabled) {
9982 				/* Crank up the keepalive timer */
9983 				tcp->tcp_ka_last_intrvl = 0;
9984 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9985 				    tcp_keepalive_killer,
9986 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
9987 				tcp->tcp_ka_enabled = 1;
9988 			}
9989 			break;
9990 		case SO_DONTROUTE:
9991 			/*
9992 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
9993 			 * only of interest to IP.  We track them here only so
9994 			 * that we can report their current value.
9995 			 */
9996 			if (!checkonly) {
9997 				tcp->tcp_dontroute = onoff;
9998 				tcp->tcp_connp->conn_dontroute = onoff;
9999 			}
10000 			break;
10001 		case SO_USELOOPBACK:
10002 			if (!checkonly) {
10003 				tcp->tcp_useloopback = onoff;
10004 				tcp->tcp_connp->conn_loopback = onoff;
10005 			}
10006 			break;
10007 		case SO_BROADCAST:
10008 			if (!checkonly) {
10009 				tcp->tcp_broadcast = onoff;
10010 				tcp->tcp_connp->conn_broadcast = onoff;
10011 			}
10012 			break;
10013 		case SO_REUSEADDR:
10014 			if (!checkonly) {
10015 				tcp->tcp_reuseaddr = onoff;
10016 				tcp->tcp_connp->conn_reuseaddr = onoff;
10017 			}
10018 			break;
10019 		case SO_OOBINLINE:
10020 			if (!checkonly)
10021 				tcp->tcp_oobinline = onoff;
10022 			break;
10023 		case SO_DGRAM_ERRIND:
10024 			if (!checkonly)
10025 				tcp->tcp_dgram_errind = onoff;
10026 			break;
10027 		case SO_SNDBUF: {
10028 			tcp_t *peer_tcp;
10029 
10030 			if (*i1 > tcp_max_buf) {
10031 				*outlenp = 0;
10032 				return (ENOBUFS);
10033 			}
10034 			if (checkonly)
10035 				break;
10036 
10037 			tcp->tcp_xmit_hiwater = *i1;
10038 			if (tcp_snd_lowat_fraction != 0)
10039 				tcp->tcp_xmit_lowater =
10040 				    tcp->tcp_xmit_hiwater /
10041 				    tcp_snd_lowat_fraction;
10042 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10043 			/*
10044 			 * If we are flow-controlled, recheck the condition.
10045 			 * There are apps that increase SO_SNDBUF size when
10046 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10047 			 * control condition to be lifted right away.
10048 			 *
10049 			 * For the fused tcp loopback case, in order to avoid
10050 			 * a race with the peer's tcp_fuse_rrw() we need to
10051 			 * hold its fuse_lock while accessing tcp_flow_stopped.
10052 			 */
10053 			peer_tcp = tcp->tcp_loopback_peer;
10054 			ASSERT(!tcp->tcp_fused || peer_tcp != NULL);
10055 			if (tcp->tcp_fused)
10056 				mutex_enter(&peer_tcp->tcp_fuse_lock);
10057 
10058 			if (tcp->tcp_flow_stopped &&
10059 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10060 				tcp_clrqfull(tcp);
10061 			}
10062 			if (tcp->tcp_fused)
10063 				mutex_exit(&peer_tcp->tcp_fuse_lock);
10064 			break;
10065 		}
10066 		case SO_RCVBUF:
10067 			if (*i1 > tcp_max_buf) {
10068 				*outlenp = 0;
10069 				return (ENOBUFS);
10070 			}
10071 			/* Silently ignore zero */
10072 			if (!checkonly && *i1 != 0) {
10073 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10074 				(void) tcp_rwnd_set(tcp, *i1);
10075 			}
10076 			/*
10077 			 * XXX should we return the rwnd here
10078 			 * and tcp_opt_get ?
10079 			 */
10080 			break;
10081 		case SO_SND_COPYAVOID:
10082 			if (!checkonly) {
10083 				/* we only allow enable at most once for now */
10084 				if (tcp->tcp_loopback ||
10085 				    (!tcp->tcp_snd_zcopy_aware &&
10086 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10087 					*outlenp = 0;
10088 					return (EOPNOTSUPP);
10089 				}
10090 				tcp->tcp_snd_zcopy_aware = 1;
10091 			}
10092 			break;
10093 		case SO_ALLZONES:
10094 			/* Handled at the IP level */
10095 			return (-EINVAL);
10096 		case SO_ANON_MLP:
10097 			if (!checkonly) {
10098 				mutex_enter(&connp->conn_lock);
10099 				connp->conn_anon_mlp = onoff;
10100 				mutex_exit(&connp->conn_lock);
10101 			}
10102 			break;
10103 		case SO_MAC_EXEMPT:
10104 			if (secpolicy_net_mac_aware(cr) != 0 ||
10105 			    IPCL_IS_BOUND(connp))
10106 				return (EACCES);
10107 			if (!checkonly) {
10108 				mutex_enter(&connp->conn_lock);
10109 				connp->conn_mac_exempt = onoff;
10110 				mutex_exit(&connp->conn_lock);
10111 			}
10112 			break;
10113 		case SO_EXCLBIND:
10114 			if (!checkonly)
10115 				tcp->tcp_exclbind = onoff;
10116 			break;
10117 		default:
10118 			*outlenp = 0;
10119 			return (EINVAL);
10120 		}
10121 		break;
10122 	case IPPROTO_TCP:
10123 		switch (name) {
10124 		case TCP_NODELAY:
10125 			if (!checkonly)
10126 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10127 			break;
10128 		case TCP_NOTIFY_THRESHOLD:
10129 			if (!checkonly)
10130 				tcp->tcp_first_timer_threshold = *i1;
10131 			break;
10132 		case TCP_ABORT_THRESHOLD:
10133 			if (!checkonly)
10134 				tcp->tcp_second_timer_threshold = *i1;
10135 			break;
10136 		case TCP_CONN_NOTIFY_THRESHOLD:
10137 			if (!checkonly)
10138 				tcp->tcp_first_ctimer_threshold = *i1;
10139 			break;
10140 		case TCP_CONN_ABORT_THRESHOLD:
10141 			if (!checkonly)
10142 				tcp->tcp_second_ctimer_threshold = *i1;
10143 			break;
10144 		case TCP_RECVDSTADDR:
10145 			if (tcp->tcp_state > TCPS_LISTEN)
10146 				return (EOPNOTSUPP);
10147 			if (!checkonly)
10148 				tcp->tcp_recvdstaddr = onoff;
10149 			break;
10150 		case TCP_ANONPRIVBIND:
10151 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
10152 				*outlenp = 0;
10153 				return (reterr);
10154 			}
10155 			if (!checkonly) {
10156 				tcp->tcp_anon_priv_bind = onoff;
10157 			}
10158 			break;
10159 		case TCP_EXCLBIND:
10160 			if (!checkonly)
10161 				tcp->tcp_exclbind = onoff;
10162 			break;	/* goto sizeof (int) option return */
10163 		case TCP_INIT_CWND: {
10164 			uint32_t init_cwnd = *((uint32_t *)invalp);
10165 
10166 			if (checkonly)
10167 				break;
10168 
10169 			/*
10170 			 * Only allow socket with network configuration
10171 			 * privilege to set the initial cwnd to be larger
10172 			 * than allowed by RFC 3390.
10173 			 */
10174 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10175 				tcp->tcp_init_cwnd = init_cwnd;
10176 				break;
10177 			}
10178 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
10179 				*outlenp = 0;
10180 				return (reterr);
10181 			}
10182 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10183 				*outlenp = 0;
10184 				return (EINVAL);
10185 			}
10186 			tcp->tcp_init_cwnd = init_cwnd;
10187 			break;
10188 		}
10189 		case TCP_KEEPALIVE_THRESHOLD:
10190 			if (checkonly)
10191 				break;
10192 
10193 			if (*i1 < tcp_keepalive_interval_low ||
10194 			    *i1 > tcp_keepalive_interval_high) {
10195 				*outlenp = 0;
10196 				return (EINVAL);
10197 			}
10198 			if (*i1 != tcp->tcp_ka_interval) {
10199 				tcp->tcp_ka_interval = *i1;
10200 				/*
10201 				 * Check if we need to restart the
10202 				 * keepalive timer.
10203 				 */
10204 				if (tcp->tcp_ka_tid != 0) {
10205 					ASSERT(tcp->tcp_ka_enabled);
10206 					(void) TCP_TIMER_CANCEL(tcp,
10207 					    tcp->tcp_ka_tid);
10208 					tcp->tcp_ka_last_intrvl = 0;
10209 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10210 					    tcp_keepalive_killer,
10211 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10212 				}
10213 			}
10214 			break;
10215 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10216 			if (!checkonly) {
10217 				if (*i1 < tcp_keepalive_abort_interval_low ||
10218 				    *i1 > tcp_keepalive_abort_interval_high) {
10219 					*outlenp = 0;
10220 					return (EINVAL);
10221 				}
10222 				tcp->tcp_ka_abort_thres = *i1;
10223 			}
10224 			break;
10225 		case TCP_CORK:
10226 			if (!checkonly) {
10227 				/*
10228 				 * if tcp->tcp_cork was set and is now
10229 				 * being unset, we have to make sure that
10230 				 * the remaining data gets sent out. Also
10231 				 * unset tcp->tcp_cork so that tcp_wput_data()
10232 				 * can send data even if it is less than mss
10233 				 */
10234 				if (tcp->tcp_cork && onoff == 0 &&
10235 				    tcp->tcp_unsent > 0) {
10236 					tcp->tcp_cork = B_FALSE;
10237 					tcp_wput_data(tcp, NULL, B_FALSE);
10238 				}
10239 				tcp->tcp_cork = onoff;
10240 			}
10241 			break;
10242 		default:
10243 			*outlenp = 0;
10244 			return (EINVAL);
10245 		}
10246 		break;
10247 	case IPPROTO_IP:
10248 		if (tcp->tcp_family != AF_INET) {
10249 			*outlenp = 0;
10250 			return (ENOPROTOOPT);
10251 		}
10252 		switch (name) {
10253 		case IP_OPTIONS:
10254 		case T_IP_OPTIONS:
10255 			reterr = tcp_opt_set_header(tcp, checkonly,
10256 			    invalp, inlen);
10257 			if (reterr) {
10258 				*outlenp = 0;
10259 				return (reterr);
10260 			}
10261 			/* OK return - copy input buffer into output buffer */
10262 			if (invalp != outvalp) {
10263 				/* don't trust bcopy for identical src/dst */
10264 				bcopy(invalp, outvalp, inlen);
10265 			}
10266 			*outlenp = inlen;
10267 			return (0);
10268 		case IP_TOS:
10269 		case T_IP_TOS:
10270 			if (!checkonly) {
10271 				tcp->tcp_ipha->ipha_type_of_service =
10272 				    (uchar_t)*i1;
10273 				tcp->tcp_tos = (uchar_t)*i1;
10274 			}
10275 			break;
10276 		case IP_TTL:
10277 			if (!checkonly) {
10278 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10279 				tcp->tcp_ttl = (uchar_t)*i1;
10280 			}
10281 			break;
10282 		case IP_BOUND_IF:
10283 		case IP_NEXTHOP:
10284 			/* Handled at the IP level */
10285 			return (-EINVAL);
10286 		case IP_SEC_OPT:
10287 			/*
10288 			 * We should not allow policy setting after
10289 			 * we start listening for connections.
10290 			 */
10291 			if (tcp->tcp_state == TCPS_LISTEN) {
10292 				return (EINVAL);
10293 			} else {
10294 				/* Handled at the IP level */
10295 				return (-EINVAL);
10296 			}
10297 		default:
10298 			*outlenp = 0;
10299 			return (EINVAL);
10300 		}
10301 		break;
10302 	case IPPROTO_IPV6: {
10303 		ip6_pkt_t		*ipp;
10304 
10305 		/*
10306 		 * IPPROTO_IPV6 options are only supported for sockets
10307 		 * that are using IPv6 on the wire.
10308 		 */
10309 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10310 			*outlenp = 0;
10311 			return (ENOPROTOOPT);
10312 		}
10313 		/*
10314 		 * Only sticky options; no ancillary data
10315 		 */
10316 		ASSERT(thisdg_attrs == NULL);
10317 		ipp = &tcp->tcp_sticky_ipp;
10318 
10319 		switch (name) {
10320 		case IPV6_UNICAST_HOPS:
10321 			/* -1 means use default */
10322 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10323 				*outlenp = 0;
10324 				return (EINVAL);
10325 			}
10326 			if (!checkonly) {
10327 				if (*i1 == -1) {
10328 					tcp->tcp_ip6h->ip6_hops =
10329 					    ipp->ipp_unicast_hops =
10330 					    (uint8_t)tcp_ipv6_hoplimit;
10331 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10332 					/* Pass modified value to IP. */
10333 					*i1 = tcp->tcp_ip6h->ip6_hops;
10334 				} else {
10335 					tcp->tcp_ip6h->ip6_hops =
10336 					    ipp->ipp_unicast_hops =
10337 					    (uint8_t)*i1;
10338 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10339 				}
10340 				reterr = tcp_build_hdrs(q, tcp);
10341 				if (reterr != 0)
10342 					return (reterr);
10343 			}
10344 			break;
10345 		case IPV6_BOUND_IF:
10346 			if (!checkonly) {
10347 				int error = 0;
10348 
10349 				tcp->tcp_bound_if = *i1;
10350 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10351 				    B_TRUE, checkonly, level, name, mblk);
10352 				if (error != 0) {
10353 					*outlenp = 0;
10354 					return (error);
10355 				}
10356 			}
10357 			break;
10358 		/*
10359 		 * Set boolean switches for ancillary data delivery
10360 		 */
10361 		case IPV6_RECVPKTINFO:
10362 			if (!checkonly) {
10363 				if (onoff)
10364 					tcp->tcp_ipv6_recvancillary |=
10365 					    TCP_IPV6_RECVPKTINFO;
10366 				else
10367 					tcp->tcp_ipv6_recvancillary &=
10368 					    ~TCP_IPV6_RECVPKTINFO;
10369 				/* Force it to be sent up with the next msg */
10370 				tcp->tcp_recvifindex = 0;
10371 			}
10372 			break;
10373 		case IPV6_RECVTCLASS:
10374 			if (!checkonly) {
10375 				if (onoff)
10376 					tcp->tcp_ipv6_recvancillary |=
10377 					    TCP_IPV6_RECVTCLASS;
10378 				else
10379 					tcp->tcp_ipv6_recvancillary &=
10380 					    ~TCP_IPV6_RECVTCLASS;
10381 			}
10382 			break;
10383 		case IPV6_RECVHOPLIMIT:
10384 			if (!checkonly) {
10385 				if (onoff)
10386 					tcp->tcp_ipv6_recvancillary |=
10387 					    TCP_IPV6_RECVHOPLIMIT;
10388 				else
10389 					tcp->tcp_ipv6_recvancillary &=
10390 					    ~TCP_IPV6_RECVHOPLIMIT;
10391 				/* Force it to be sent up with the next msg */
10392 				tcp->tcp_recvhops = 0xffffffffU;
10393 			}
10394 			break;
10395 		case IPV6_RECVHOPOPTS:
10396 			if (!checkonly) {
10397 				if (onoff)
10398 					tcp->tcp_ipv6_recvancillary |=
10399 					    TCP_IPV6_RECVHOPOPTS;
10400 				else
10401 					tcp->tcp_ipv6_recvancillary &=
10402 					    ~TCP_IPV6_RECVHOPOPTS;
10403 			}
10404 			break;
10405 		case IPV6_RECVDSTOPTS:
10406 			if (!checkonly) {
10407 				if (onoff)
10408 					tcp->tcp_ipv6_recvancillary |=
10409 					    TCP_IPV6_RECVDSTOPTS;
10410 				else
10411 					tcp->tcp_ipv6_recvancillary &=
10412 					    ~TCP_IPV6_RECVDSTOPTS;
10413 			}
10414 			break;
10415 		case _OLD_IPV6_RECVDSTOPTS:
10416 			if (!checkonly) {
10417 				if (onoff)
10418 					tcp->tcp_ipv6_recvancillary |=
10419 					    TCP_OLD_IPV6_RECVDSTOPTS;
10420 				else
10421 					tcp->tcp_ipv6_recvancillary &=
10422 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10423 			}
10424 			break;
10425 		case IPV6_RECVRTHDR:
10426 			if (!checkonly) {
10427 				if (onoff)
10428 					tcp->tcp_ipv6_recvancillary |=
10429 					    TCP_IPV6_RECVRTHDR;
10430 				else
10431 					tcp->tcp_ipv6_recvancillary &=
10432 					    ~TCP_IPV6_RECVRTHDR;
10433 			}
10434 			break;
10435 		case IPV6_RECVRTHDRDSTOPTS:
10436 			if (!checkonly) {
10437 				if (onoff)
10438 					tcp->tcp_ipv6_recvancillary |=
10439 					    TCP_IPV6_RECVRTDSTOPTS;
10440 				else
10441 					tcp->tcp_ipv6_recvancillary &=
10442 					    ~TCP_IPV6_RECVRTDSTOPTS;
10443 			}
10444 			break;
10445 		case IPV6_PKTINFO:
10446 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10447 				return (EINVAL);
10448 			if (checkonly)
10449 				break;
10450 
10451 			if (inlen == 0) {
10452 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10453 			} else {
10454 				struct in6_pktinfo *pkti;
10455 
10456 				pkti = (struct in6_pktinfo *)invalp;
10457 				/*
10458 				 * RFC 3542 states that ipi6_addr must be
10459 				 * the unspecified address when setting the
10460 				 * IPV6_PKTINFO sticky socket option on a
10461 				 * TCP socket.
10462 				 */
10463 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10464 					return (EINVAL);
10465 				/*
10466 				 * ip6_set_pktinfo() validates the source
10467 				 * address and interface index.
10468 				 */
10469 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10470 				    pkti, mblk);
10471 				if (reterr != 0)
10472 					return (reterr);
10473 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10474 				ipp->ipp_addr = pkti->ipi6_addr;
10475 				if (ipp->ipp_ifindex != 0)
10476 					ipp->ipp_fields |= IPPF_IFINDEX;
10477 				else
10478 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10479 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10480 					ipp->ipp_fields |= IPPF_ADDR;
10481 				else
10482 					ipp->ipp_fields &= ~IPPF_ADDR;
10483 			}
10484 			reterr = tcp_build_hdrs(q, tcp);
10485 			if (reterr != 0)
10486 				return (reterr);
10487 			break;
10488 		case IPV6_TCLASS:
10489 			if (inlen != 0 && inlen != sizeof (int))
10490 				return (EINVAL);
10491 			if (checkonly)
10492 				break;
10493 
10494 			if (inlen == 0) {
10495 				ipp->ipp_fields &= ~IPPF_TCLASS;
10496 			} else {
10497 				if (*i1 > 255 || *i1 < -1)
10498 					return (EINVAL);
10499 				if (*i1 == -1) {
10500 					ipp->ipp_tclass = 0;
10501 					*i1 = 0;
10502 				} else {
10503 					ipp->ipp_tclass = *i1;
10504 				}
10505 				ipp->ipp_fields |= IPPF_TCLASS;
10506 			}
10507 			reterr = tcp_build_hdrs(q, tcp);
10508 			if (reterr != 0)
10509 				return (reterr);
10510 			break;
10511 		case IPV6_NEXTHOP:
10512 			/*
10513 			 * IP will verify that the nexthop is reachable
10514 			 * and fail for sticky options.
10515 			 */
10516 			if (inlen != 0 && inlen != sizeof (sin6_t))
10517 				return (EINVAL);
10518 			if (checkonly)
10519 				break;
10520 
10521 			if (inlen == 0) {
10522 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10523 			} else {
10524 				sin6_t *sin6 = (sin6_t *)invalp;
10525 
10526 				if (sin6->sin6_family != AF_INET6)
10527 					return (EAFNOSUPPORT);
10528 				if (IN6_IS_ADDR_V4MAPPED(
10529 				    &sin6->sin6_addr))
10530 					return (EADDRNOTAVAIL);
10531 				ipp->ipp_nexthop = sin6->sin6_addr;
10532 				if (!IN6_IS_ADDR_UNSPECIFIED(
10533 				    &ipp->ipp_nexthop))
10534 					ipp->ipp_fields |= IPPF_NEXTHOP;
10535 				else
10536 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10537 			}
10538 			reterr = tcp_build_hdrs(q, tcp);
10539 			if (reterr != 0)
10540 				return (reterr);
10541 			break;
10542 		case IPV6_HOPOPTS: {
10543 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10544 
10545 			/*
10546 			 * Sanity checks - minimum size, size a multiple of
10547 			 * eight bytes, and matching size passed in.
10548 			 */
10549 			if (inlen != 0 &&
10550 			    inlen != (8 * (hopts->ip6h_len + 1)))
10551 				return (EINVAL);
10552 
10553 			if (checkonly)
10554 				break;
10555 
10556 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10557 			    (uchar_t **)&ipp->ipp_hopopts,
10558 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10559 			if (reterr != 0)
10560 				return (reterr);
10561 			if (ipp->ipp_hopoptslen == 0)
10562 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10563 			else
10564 				ipp->ipp_fields |= IPPF_HOPOPTS;
10565 			reterr = tcp_build_hdrs(q, tcp);
10566 			if (reterr != 0)
10567 				return (reterr);
10568 			break;
10569 		}
10570 		case IPV6_RTHDRDSTOPTS: {
10571 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10572 
10573 			/*
10574 			 * Sanity checks - minimum size, size a multiple of
10575 			 * eight bytes, and matching size passed in.
10576 			 */
10577 			if (inlen != 0 &&
10578 			    inlen != (8 * (dopts->ip6d_len + 1)))
10579 				return (EINVAL);
10580 
10581 			if (checkonly)
10582 				break;
10583 
10584 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10585 			    (uchar_t **)&ipp->ipp_rtdstopts,
10586 			    &ipp->ipp_rtdstoptslen, 0);
10587 			if (reterr != 0)
10588 				return (reterr);
10589 			if (ipp->ipp_rtdstoptslen == 0)
10590 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10591 			else
10592 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10593 			reterr = tcp_build_hdrs(q, tcp);
10594 			if (reterr != 0)
10595 				return (reterr);
10596 			break;
10597 		}
10598 		case IPV6_DSTOPTS: {
10599 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10600 
10601 			/*
10602 			 * Sanity checks - minimum size, size a multiple of
10603 			 * eight bytes, and matching size passed in.
10604 			 */
10605 			if (inlen != 0 &&
10606 			    inlen != (8 * (dopts->ip6d_len + 1)))
10607 				return (EINVAL);
10608 
10609 			if (checkonly)
10610 				break;
10611 
10612 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10613 			    (uchar_t **)&ipp->ipp_dstopts,
10614 			    &ipp->ipp_dstoptslen, 0);
10615 			if (reterr != 0)
10616 				return (reterr);
10617 			if (ipp->ipp_dstoptslen == 0)
10618 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10619 			else
10620 				ipp->ipp_fields |= IPPF_DSTOPTS;
10621 			reterr = tcp_build_hdrs(q, tcp);
10622 			if (reterr != 0)
10623 				return (reterr);
10624 			break;
10625 		}
10626 		case IPV6_RTHDR: {
10627 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10628 
10629 			/*
10630 			 * Sanity checks - minimum size, size a multiple of
10631 			 * eight bytes, and matching size passed in.
10632 			 */
10633 			if (inlen != 0 &&
10634 			    inlen != (8 * (rt->ip6r_len + 1)))
10635 				return (EINVAL);
10636 
10637 			if (checkonly)
10638 				break;
10639 
10640 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10641 			    (uchar_t **)&ipp->ipp_rthdr,
10642 			    &ipp->ipp_rthdrlen, 0);
10643 			if (reterr != 0)
10644 				return (reterr);
10645 			if (ipp->ipp_rthdrlen == 0)
10646 				ipp->ipp_fields &= ~IPPF_RTHDR;
10647 			else
10648 				ipp->ipp_fields |= IPPF_RTHDR;
10649 			reterr = tcp_build_hdrs(q, tcp);
10650 			if (reterr != 0)
10651 				return (reterr);
10652 			break;
10653 		}
10654 		case IPV6_V6ONLY:
10655 			if (!checkonly)
10656 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10657 			break;
10658 		case IPV6_USE_MIN_MTU:
10659 			if (inlen != sizeof (int))
10660 				return (EINVAL);
10661 
10662 			if (*i1 < -1 || *i1 > 1)
10663 				return (EINVAL);
10664 
10665 			if (checkonly)
10666 				break;
10667 
10668 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10669 			ipp->ipp_use_min_mtu = *i1;
10670 			break;
10671 		case IPV6_BOUND_PIF:
10672 			/* Handled at the IP level */
10673 			return (-EINVAL);
10674 		case IPV6_SEC_OPT:
10675 			/*
10676 			 * We should not allow policy setting after
10677 			 * we start listening for connections.
10678 			 */
10679 			if (tcp->tcp_state == TCPS_LISTEN) {
10680 				return (EINVAL);
10681 			} else {
10682 				/* Handled at the IP level */
10683 				return (-EINVAL);
10684 			}
10685 		case IPV6_SRC_PREFERENCES:
10686 			if (inlen != sizeof (uint32_t))
10687 				return (EINVAL);
10688 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10689 			    *(uint32_t *)invalp);
10690 			if (reterr != 0) {
10691 				*outlenp = 0;
10692 				return (reterr);
10693 			}
10694 			break;
10695 		default:
10696 			*outlenp = 0;
10697 			return (EINVAL);
10698 		}
10699 		break;
10700 	}		/* end IPPROTO_IPV6 */
10701 	default:
10702 		*outlenp = 0;
10703 		return (EINVAL);
10704 	}
10705 	/*
10706 	 * Common case of OK return with outval same as inval
10707 	 */
10708 	if (invalp != outvalp) {
10709 		/* don't trust bcopy for identical src/dst */
10710 		(void) bcopy(invalp, outvalp, inlen);
10711 	}
10712 	*outlenp = inlen;
10713 	return (0);
10714 }
10715 
10716 /*
10717  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10718  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10719  * headers, and the maximum size tcp header (to avoid reallocation
10720  * on the fly for additional tcp options).
10721  * Returns failure if can't allocate memory.
10722  */
10723 static int
10724 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
10725 {
10726 	char	*hdrs;
10727 	uint_t	hdrs_len;
10728 	ip6i_t	*ip6i;
10729 	char	buf[TCP_MAX_HDR_LENGTH];
10730 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10731 	in6_addr_t src, dst;
10732 
10733 	/*
10734 	 * save the existing tcp header and source/dest IP addresses
10735 	 */
10736 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10737 	src = tcp->tcp_ip6h->ip6_src;
10738 	dst = tcp->tcp_ip6h->ip6_dst;
10739 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10740 	ASSERT(hdrs_len != 0);
10741 	if (hdrs_len > tcp->tcp_iphc_len) {
10742 		/* Need to reallocate */
10743 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10744 		if (hdrs == NULL)
10745 			return (ENOMEM);
10746 		if (tcp->tcp_iphc != NULL) {
10747 			if (tcp->tcp_hdr_grown) {
10748 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10749 			} else {
10750 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10751 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10752 			}
10753 			tcp->tcp_iphc_len = 0;
10754 		}
10755 		ASSERT(tcp->tcp_iphc_len == 0);
10756 		tcp->tcp_iphc = hdrs;
10757 		tcp->tcp_iphc_len = hdrs_len;
10758 		tcp->tcp_hdr_grown = B_TRUE;
10759 	}
10760 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10761 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10762 
10763 	/* Set header fields not in ipp */
10764 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10765 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10766 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10767 	} else {
10768 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10769 	}
10770 	/*
10771 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10772 	 *
10773 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10774 	 */
10775 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10776 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10777 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10778 
10779 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10780 
10781 	tcp->tcp_ip6h->ip6_src = src;
10782 	tcp->tcp_ip6h->ip6_dst = dst;
10783 
10784 	/*
10785 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10786 	 * the default value for TCP.
10787 	 */
10788 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10789 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
10790 
10791 	/*
10792 	 * If we're setting extension headers after a connection
10793 	 * has been established, and if we have a routing header
10794 	 * among the extension headers, call ip_massage_options_v6 to
10795 	 * manipulate the routing header/ip6_dst set the checksum
10796 	 * difference in the tcp header template.
10797 	 * (This happens in tcp_connect_ipv6 if the routing header
10798 	 * is set prior to the connect.)
10799 	 * Set the tcp_sum to zero first in case we've cleared a
10800 	 * routing header or don't have one at all.
10801 	 */
10802 	tcp->tcp_sum = 0;
10803 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10804 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10805 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10806 		    (uint8_t *)tcp->tcp_tcph);
10807 		if (rth != NULL) {
10808 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10809 			    rth);
10810 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10811 			    (tcp->tcp_sum >> 16));
10812 		}
10813 	}
10814 
10815 	/* Try to get everything in a single mblk */
10816 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
10817 	return (0);
10818 }
10819 
10820 /*
10821  * Transfer any source route option from ipha to buf/dst in reversed form.
10822  */
10823 static int
10824 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10825 {
10826 	ipoptp_t	opts;
10827 	uchar_t		*opt;
10828 	uint8_t		optval;
10829 	uint8_t		optlen;
10830 	uint32_t	len = 0;
10831 
10832 	for (optval = ipoptp_first(&opts, ipha);
10833 	    optval != IPOPT_EOL;
10834 	    optval = ipoptp_next(&opts)) {
10835 		opt = opts.ipoptp_cur;
10836 		optlen = opts.ipoptp_len;
10837 		switch (optval) {
10838 			int	off1, off2;
10839 		case IPOPT_SSRR:
10840 		case IPOPT_LSRR:
10841 
10842 			/* Reverse source route */
10843 			/*
10844 			 * First entry should be the next to last one in the
10845 			 * current source route (the last entry is our
10846 			 * address.)
10847 			 * The last entry should be the final destination.
10848 			 */
10849 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10850 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10851 			off1 = IPOPT_MINOFF_SR - 1;
10852 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10853 			if (off2 < 0) {
10854 				/* No entries in source route */
10855 				break;
10856 			}
10857 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10858 			/*
10859 			 * Note: use src since ipha has not had its src
10860 			 * and dst reversed (it is in the state it was
10861 			 * received.
10862 			 */
10863 			bcopy(&ipha->ipha_src, buf + off2,
10864 			    IP_ADDR_LEN);
10865 			off2 -= IP_ADDR_LEN;
10866 
10867 			while (off2 > 0) {
10868 				bcopy(opt + off2, buf + off1,
10869 				    IP_ADDR_LEN);
10870 				off1 += IP_ADDR_LEN;
10871 				off2 -= IP_ADDR_LEN;
10872 			}
10873 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10874 			buf += optlen;
10875 			len += optlen;
10876 			break;
10877 		}
10878 	}
10879 done:
10880 	/* Pad the resulting options */
10881 	while (len & 0x3) {
10882 		*buf++ = IPOPT_EOL;
10883 		len++;
10884 	}
10885 	return (len);
10886 }
10887 
10888 
10889 /*
10890  * Extract and revert a source route from ipha (if any)
10891  * and then update the relevant fields in both tcp_t and the standard header.
10892  */
10893 static void
10894 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
10895 {
10896 	char	buf[TCP_MAX_HDR_LENGTH];
10897 	uint_t	tcph_len;
10898 	int	len;
10899 
10900 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
10901 	len = IPH_HDR_LENGTH(ipha);
10902 	if (len == IP_SIMPLE_HDR_LENGTH)
10903 		/* Nothing to do */
10904 		return;
10905 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
10906 	    (len & 0x3))
10907 		return;
10908 
10909 	tcph_len = tcp->tcp_tcp_hdr_len;
10910 	bcopy(tcp->tcp_tcph, buf, tcph_len);
10911 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
10912 		(tcp->tcp_ipha->ipha_dst & 0xffff);
10913 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
10914 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
10915 	len += IP_SIMPLE_HDR_LENGTH;
10916 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
10917 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
10918 	if ((int)tcp->tcp_sum < 0)
10919 		tcp->tcp_sum--;
10920 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
10921 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
10922 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
10923 	bcopy(buf, tcp->tcp_tcph, tcph_len);
10924 	tcp->tcp_ip_hdr_len = len;
10925 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10926 	    (IP_VERSION << 4) | (len >> 2);
10927 	len += tcph_len;
10928 	tcp->tcp_hdr_len = len;
10929 }
10930 
10931 /*
10932  * Copy the standard header into its new location,
10933  * lay in the new options and then update the relevant
10934  * fields in both tcp_t and the standard header.
10935  */
10936 static int
10937 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
10938 {
10939 	uint_t	tcph_len;
10940 	uint8_t	*ip_optp;
10941 	tcph_t	*new_tcph;
10942 
10943 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10944 		return (EINVAL);
10945 
10946 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
10947 		return (EINVAL);
10948 
10949 	if (checkonly) {
10950 		/*
10951 		 * do not really set, just pretend to - T_CHECK
10952 		 */
10953 		return (0);
10954 	}
10955 
10956 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
10957 	if (tcp->tcp_label_len > 0) {
10958 		int padlen;
10959 		uint8_t opt;
10960 
10961 		/* convert list termination to no-ops */
10962 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
10963 		ip_optp += ip_optp[IPOPT_OLEN];
10964 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
10965 		while (--padlen >= 0)
10966 			*ip_optp++ = opt;
10967 	}
10968 	tcph_len = tcp->tcp_tcp_hdr_len;
10969 	new_tcph = (tcph_t *)(ip_optp + len);
10970 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
10971 	tcp->tcp_tcph = new_tcph;
10972 	bcopy(ptr, ip_optp, len);
10973 
10974 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
10975 
10976 	tcp->tcp_ip_hdr_len = len;
10977 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10978 	    (IP_VERSION << 4) | (len >> 2);
10979 	tcp->tcp_hdr_len = len + tcph_len;
10980 	if (!TCP_IS_DETACHED(tcp)) {
10981 		/* Always allocate room for all options. */
10982 		(void) mi_set_sth_wroff(tcp->tcp_rq,
10983 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
10984 	}
10985 	return (0);
10986 }
10987 
10988 /* Get callback routine passed to nd_load by tcp_param_register */
10989 /* ARGSUSED */
10990 static int
10991 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
10992 {
10993 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10994 
10995 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
10996 	return (0);
10997 }
10998 
10999 /*
11000  * Walk through the param array specified registering each element with the
11001  * named dispatch handler.
11002  */
11003 static boolean_t
11004 tcp_param_register(tcpparam_t *tcppa, int cnt)
11005 {
11006 	for (; cnt-- > 0; tcppa++) {
11007 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11008 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
11009 			    tcp_param_get, tcp_param_set,
11010 			    (caddr_t)tcppa)) {
11011 				nd_free(&tcp_g_nd);
11012 				return (B_FALSE);
11013 			}
11014 		}
11015 	}
11016 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
11017 	    tcp_param_get, tcp_param_set_aligned,
11018 	    (caddr_t)&tcp_wroff_xtra_param)) {
11019 		nd_free(&tcp_g_nd);
11020 		return (B_FALSE);
11021 	}
11022 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
11023 	    tcp_param_get, tcp_param_set_aligned,
11024 	    (caddr_t)&tcp_mdt_head_param)) {
11025 		nd_free(&tcp_g_nd);
11026 		return (B_FALSE);
11027 	}
11028 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
11029 	    tcp_param_get, tcp_param_set_aligned,
11030 	    (caddr_t)&tcp_mdt_tail_param)) {
11031 		nd_free(&tcp_g_nd);
11032 		return (B_FALSE);
11033 	}
11034 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
11035 	    tcp_param_get, tcp_param_set,
11036 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
11037 		nd_free(&tcp_g_nd);
11038 		return (B_FALSE);
11039 	}
11040 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
11041 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11042 		nd_free(&tcp_g_nd);
11043 		return (B_FALSE);
11044 	}
11045 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
11046 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11047 		nd_free(&tcp_g_nd);
11048 		return (B_FALSE);
11049 	}
11050 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
11051 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11052 		nd_free(&tcp_g_nd);
11053 		return (B_FALSE);
11054 	}
11055 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
11056 	    NULL)) {
11057 		nd_free(&tcp_g_nd);
11058 		return (B_FALSE);
11059 	}
11060 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
11061 	    NULL, NULL)) {
11062 		nd_free(&tcp_g_nd);
11063 		return (B_FALSE);
11064 	}
11065 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
11066 	    NULL, NULL)) {
11067 		nd_free(&tcp_g_nd);
11068 		return (B_FALSE);
11069 	}
11070 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
11071 	    NULL, NULL)) {
11072 		nd_free(&tcp_g_nd);
11073 		return (B_FALSE);
11074 	}
11075 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
11076 	    NULL, NULL)) {
11077 		nd_free(&tcp_g_nd);
11078 		return (B_FALSE);
11079 	}
11080 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
11081 	    tcp_host_param_set, NULL)) {
11082 		nd_free(&tcp_g_nd);
11083 		return (B_FALSE);
11084 	}
11085 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
11086 	    tcp_host_param_set_ipv6, NULL)) {
11087 		nd_free(&tcp_g_nd);
11088 		return (B_FALSE);
11089 	}
11090 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
11091 	    NULL)) {
11092 		nd_free(&tcp_g_nd);
11093 		return (B_FALSE);
11094 	}
11095 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
11096 	    tcp_reserved_port_list, NULL, NULL)) {
11097 		nd_free(&tcp_g_nd);
11098 		return (B_FALSE);
11099 	}
11100 	/*
11101 	 * Dummy ndd variables - only to convey obsolescence information
11102 	 * through printing of their name (no get or set routines)
11103 	 * XXX Remove in future releases ?
11104 	 */
11105 	if (!nd_load(&tcp_g_nd,
11106 	    "tcp_close_wait_interval(obsoleted - "
11107 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11108 		nd_free(&tcp_g_nd);
11109 		return (B_FALSE);
11110 	}
11111 	return (B_TRUE);
11112 }
11113 
11114 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11115 /* ARGSUSED */
11116 static int
11117 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11118     cred_t *cr)
11119 {
11120 	long new_value;
11121 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11122 
11123 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11124 	    new_value < tcppa->tcp_param_min ||
11125 	    new_value > tcppa->tcp_param_max) {
11126 		return (EINVAL);
11127 	}
11128 	/*
11129 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11130 	 * round it up.  For future 64 bit requirement, we actually make it
11131 	 * a multiple of 8.
11132 	 */
11133 	if (new_value & 0x7) {
11134 		new_value = (new_value & ~0x7) + 0x8;
11135 	}
11136 	tcppa->tcp_param_val = new_value;
11137 	return (0);
11138 }
11139 
11140 /* Set callback routine passed to nd_load by tcp_param_register */
11141 /* ARGSUSED */
11142 static int
11143 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11144 {
11145 	long	new_value;
11146 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11147 
11148 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11149 	    new_value < tcppa->tcp_param_min ||
11150 	    new_value > tcppa->tcp_param_max) {
11151 		return (EINVAL);
11152 	}
11153 	tcppa->tcp_param_val = new_value;
11154 	return (0);
11155 }
11156 
11157 /*
11158  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11159  * is filled, return as much as we can.  The message passed in may be
11160  * multi-part, chained using b_cont.  "start" is the starting sequence
11161  * number for this piece.
11162  */
11163 static mblk_t *
11164 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11165 {
11166 	uint32_t	end;
11167 	mblk_t		*mp1;
11168 	mblk_t		*mp2;
11169 	mblk_t		*next_mp;
11170 	uint32_t	u1;
11171 
11172 	/* Walk through all the new pieces. */
11173 	do {
11174 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11175 		    (uintptr_t)INT_MAX);
11176 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11177 		next_mp = mp->b_cont;
11178 		if (start == end) {
11179 			/* Empty.  Blast it. */
11180 			freeb(mp);
11181 			continue;
11182 		}
11183 		mp->b_cont = NULL;
11184 		TCP_REASS_SET_SEQ(mp, start);
11185 		TCP_REASS_SET_END(mp, end);
11186 		mp1 = tcp->tcp_reass_tail;
11187 		if (!mp1) {
11188 			tcp->tcp_reass_tail = mp;
11189 			tcp->tcp_reass_head = mp;
11190 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11191 			UPDATE_MIB(&tcp_mib,
11192 			    tcpInDataUnorderBytes, end - start);
11193 			continue;
11194 		}
11195 		/* New stuff completely beyond tail? */
11196 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11197 			/* Link it on end. */
11198 			mp1->b_cont = mp;
11199 			tcp->tcp_reass_tail = mp;
11200 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11201 			UPDATE_MIB(&tcp_mib,
11202 			    tcpInDataUnorderBytes, end - start);
11203 			continue;
11204 		}
11205 		mp1 = tcp->tcp_reass_head;
11206 		u1 = TCP_REASS_SEQ(mp1);
11207 		/* New stuff at the front? */
11208 		if (SEQ_LT(start, u1)) {
11209 			/* Yes... Check for overlap. */
11210 			mp->b_cont = mp1;
11211 			tcp->tcp_reass_head = mp;
11212 			tcp_reass_elim_overlap(tcp, mp);
11213 			continue;
11214 		}
11215 		/*
11216 		 * The new piece fits somewhere between the head and tail.
11217 		 * We find our slot, where mp1 precedes us and mp2 trails.
11218 		 */
11219 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11220 			u1 = TCP_REASS_SEQ(mp2);
11221 			if (SEQ_LEQ(start, u1))
11222 				break;
11223 		}
11224 		/* Link ourselves in */
11225 		mp->b_cont = mp2;
11226 		mp1->b_cont = mp;
11227 
11228 		/* Trim overlap with following mblk(s) first */
11229 		tcp_reass_elim_overlap(tcp, mp);
11230 
11231 		/* Trim overlap with preceding mblk */
11232 		tcp_reass_elim_overlap(tcp, mp1);
11233 
11234 	} while (start = end, mp = next_mp);
11235 	mp1 = tcp->tcp_reass_head;
11236 	/* Anything ready to go? */
11237 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11238 		return (NULL);
11239 	/* Eat what we can off the queue */
11240 	for (;;) {
11241 		mp = mp1->b_cont;
11242 		end = TCP_REASS_END(mp1);
11243 		TCP_REASS_SET_SEQ(mp1, 0);
11244 		TCP_REASS_SET_END(mp1, 0);
11245 		if (!mp) {
11246 			tcp->tcp_reass_tail = NULL;
11247 			break;
11248 		}
11249 		if (end != TCP_REASS_SEQ(mp)) {
11250 			mp1->b_cont = NULL;
11251 			break;
11252 		}
11253 		mp1 = mp;
11254 	}
11255 	mp1 = tcp->tcp_reass_head;
11256 	tcp->tcp_reass_head = mp;
11257 	return (mp1);
11258 }
11259 
11260 /* Eliminate any overlap that mp may have over later mblks */
11261 static void
11262 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11263 {
11264 	uint32_t	end;
11265 	mblk_t		*mp1;
11266 	uint32_t	u1;
11267 
11268 	end = TCP_REASS_END(mp);
11269 	while ((mp1 = mp->b_cont) != NULL) {
11270 		u1 = TCP_REASS_SEQ(mp1);
11271 		if (!SEQ_GT(end, u1))
11272 			break;
11273 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11274 			mp->b_wptr -= end - u1;
11275 			TCP_REASS_SET_END(mp, u1);
11276 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
11277 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
11278 			break;
11279 		}
11280 		mp->b_cont = mp1->b_cont;
11281 		TCP_REASS_SET_SEQ(mp1, 0);
11282 		TCP_REASS_SET_END(mp1, 0);
11283 		freeb(mp1);
11284 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
11285 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
11286 	}
11287 	if (!mp1)
11288 		tcp->tcp_reass_tail = mp;
11289 }
11290 
11291 /*
11292  * Send up all messages queued on tcp_rcv_list.
11293  */
11294 static uint_t
11295 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11296 {
11297 	mblk_t *mp;
11298 	uint_t ret = 0;
11299 	uint_t thwin;
11300 #ifdef DEBUG
11301 	uint_t cnt = 0;
11302 #endif
11303 	/* Can't drain on an eager connection */
11304 	if (tcp->tcp_listener != NULL)
11305 		return (ret);
11306 
11307 	/*
11308 	 * Handle two cases here: we are currently fused or we were
11309 	 * previously fused and have some urgent data to be delivered
11310 	 * upstream.  The latter happens because we either ran out of
11311 	 * memory or were detached and therefore sending the SIGURG was
11312 	 * deferred until this point.  In either case we pass control
11313 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11314 	 * some work.
11315 	 */
11316 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11317 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11318 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11319 		    &tcp->tcp_fused_sigurg_mp))
11320 			return (ret);
11321 	}
11322 
11323 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11324 		tcp->tcp_rcv_list = mp->b_next;
11325 		mp->b_next = NULL;
11326 #ifdef DEBUG
11327 		cnt += msgdsize(mp);
11328 #endif
11329 		/* Does this need SSL processing first? */
11330 		if ((tcp->tcp_kssl_ctx  != NULL) && (DB_TYPE(mp) == M_DATA)) {
11331 			tcp_kssl_input(tcp, mp);
11332 			continue;
11333 		}
11334 		putnext(q, mp);
11335 	}
11336 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11337 	tcp->tcp_rcv_last_head = NULL;
11338 	tcp->tcp_rcv_last_tail = NULL;
11339 	tcp->tcp_rcv_cnt = 0;
11340 
11341 	/* Learn the latest rwnd information that we sent to the other side. */
11342 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11343 	    << tcp->tcp_rcv_ws;
11344 	/* This is peer's calculated send window (our receive window). */
11345 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11346 	/*
11347 	 * Increase the receive window to max.  But we need to do receiver
11348 	 * SWS avoidance.  This means that we need to check the increase of
11349 	 * of receive window is at least 1 MSS.
11350 	 */
11351 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11352 		/*
11353 		 * If the window that the other side knows is less than max
11354 		 * deferred acks segments, send an update immediately.
11355 		 */
11356 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11357 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11358 			ret = TH_ACK_NEEDED;
11359 		}
11360 		tcp->tcp_rwnd = q->q_hiwat;
11361 	}
11362 	/* No need for the push timer now. */
11363 	if (tcp->tcp_push_tid != 0) {
11364 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11365 		tcp->tcp_push_tid = 0;
11366 	}
11367 	return (ret);
11368 }
11369 
11370 /*
11371  * Queue data on tcp_rcv_list which is a b_next chain.
11372  * tcp_rcv_last_head/tail is the last element of this chain.
11373  * Each element of the chain is a b_cont chain.
11374  *
11375  * M_DATA messages are added to the current element.
11376  * Other messages are added as new (b_next) elements.
11377  */
11378 void
11379 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11380 {
11381 	ASSERT(seg_len == msgdsize(mp));
11382 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11383 
11384 	if (tcp->tcp_rcv_list == NULL) {
11385 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11386 		tcp->tcp_rcv_list = mp;
11387 		tcp->tcp_rcv_last_head = mp;
11388 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11389 		tcp->tcp_rcv_last_tail->b_cont = mp;
11390 	} else {
11391 		tcp->tcp_rcv_last_head->b_next = mp;
11392 		tcp->tcp_rcv_last_head = mp;
11393 	}
11394 
11395 	while (mp->b_cont)
11396 		mp = mp->b_cont;
11397 
11398 	tcp->tcp_rcv_last_tail = mp;
11399 	tcp->tcp_rcv_cnt += seg_len;
11400 	tcp->tcp_rwnd -= seg_len;
11401 }
11402 
11403 /*
11404  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11405  *
11406  * This is the default entry function into TCP on the read side. TCP is
11407  * always entered via squeue i.e. using squeue's for mutual exclusion.
11408  * When classifier does a lookup to find the tcp, it also puts a reference
11409  * on the conn structure associated so the tcp is guaranteed to exist
11410  * when we come here. We still need to check the state because it might
11411  * as well has been closed. The squeue processing function i.e. squeue_enter,
11412  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11413  * CONN_DEC_REF.
11414  *
11415  * Apart from the default entry point, IP also sends packets directly to
11416  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11417  * connections.
11418  */
11419 void
11420 tcp_input(void *arg, mblk_t *mp, void *arg2)
11421 {
11422 	conn_t	*connp = (conn_t *)arg;
11423 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11424 
11425 	/* arg2 is the sqp */
11426 	ASSERT(arg2 != NULL);
11427 	ASSERT(mp != NULL);
11428 
11429 	/*
11430 	 * Don't accept any input on a closed tcp as this TCP logically does
11431 	 * not exist on the system. Don't proceed further with this TCP.
11432 	 * For eg. this packet could trigger another close of this tcp
11433 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11434 	 * tcp_clean_death / tcp_closei_local must be called at most once
11435 	 * on a TCP. In this case we need to refeed the packet into the
11436 	 * classifier and figure out where the packet should go. Need to
11437 	 * preserve the recv_ill somehow. Until we figure that out, for
11438 	 * now just drop the packet if we can't classify the packet.
11439 	 */
11440 	if (tcp->tcp_state == TCPS_CLOSED ||
11441 	    tcp->tcp_state == TCPS_BOUND) {
11442 		conn_t	*new_connp;
11443 
11444 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11445 		if (new_connp != NULL) {
11446 			tcp_reinput(new_connp, mp, arg2);
11447 			return;
11448 		}
11449 		/* We failed to classify. For now just drop the packet */
11450 		freemsg(mp);
11451 		return;
11452 	}
11453 
11454 	if (DB_TYPE(mp) == M_DATA)
11455 		tcp_rput_data(connp, mp, arg2);
11456 	else
11457 		tcp_rput_common(tcp, mp);
11458 }
11459 
11460 /*
11461  * The read side put procedure.
11462  * The packets passed up by ip are assume to be aligned according to
11463  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11464  */
11465 static void
11466 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11467 {
11468 	/*
11469 	 * tcp_rput_data() does not expect M_CTL except for the case
11470 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11471 	 * type. Need to make sure that any other M_CTLs don't make
11472 	 * it to tcp_rput_data since it is not expecting any and doesn't
11473 	 * check for it.
11474 	 */
11475 	if (DB_TYPE(mp) == M_CTL) {
11476 		switch (*(uint32_t *)(mp->b_rptr)) {
11477 		case TCP_IOC_ABORT_CONN:
11478 			/*
11479 			 * Handle connection abort request.
11480 			 */
11481 			tcp_ioctl_abort_handler(tcp, mp);
11482 			return;
11483 		case IPSEC_IN:
11484 			/*
11485 			 * Only secure icmp arrive in TCP and they
11486 			 * don't go through data path.
11487 			 */
11488 			tcp_icmp_error(tcp, mp);
11489 			return;
11490 		case IN_PKTINFO:
11491 			/*
11492 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11493 			 * sockets that are receiving IPv4 traffic. tcp
11494 			 */
11495 			ASSERT(tcp->tcp_family == AF_INET6);
11496 			ASSERT(tcp->tcp_ipv6_recvancillary &
11497 			    TCP_IPV6_RECVPKTINFO);
11498 			tcp_rput_data(tcp->tcp_connp, mp,
11499 			    tcp->tcp_connp->conn_sqp);
11500 			return;
11501 		case MDT_IOC_INFO_UPDATE:
11502 			/*
11503 			 * Handle Multidata information update; the
11504 			 * following routine will free the message.
11505 			 */
11506 			if (tcp->tcp_connp->conn_mdt_ok) {
11507 				tcp_mdt_update(tcp,
11508 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11509 				    B_FALSE);
11510 			}
11511 			freemsg(mp);
11512 			return;
11513 		default:
11514 			break;
11515 		}
11516 	}
11517 
11518 	/* No point processing the message if tcp is already closed */
11519 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11520 		freemsg(mp);
11521 		return;
11522 	}
11523 
11524 	tcp_rput_other(tcp, mp);
11525 }
11526 
11527 
11528 /* The minimum of smoothed mean deviation in RTO calculation. */
11529 #define	TCP_SD_MIN	400
11530 
11531 /*
11532  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11533  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11534  * are the same as those in Appendix A.2 of that paper.
11535  *
11536  * m = new measurement
11537  * sa = smoothed RTT average (8 * average estimates).
11538  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11539  */
11540 static void
11541 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11542 {
11543 	long m = TICK_TO_MSEC(rtt);
11544 	clock_t sa = tcp->tcp_rtt_sa;
11545 	clock_t sv = tcp->tcp_rtt_sd;
11546 	clock_t rto;
11547 
11548 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
11549 	tcp->tcp_rtt_update++;
11550 
11551 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11552 	if (sa != 0) {
11553 		/*
11554 		 * Update average estimator:
11555 		 *	new rtt = 7/8 old rtt + 1/8 Error
11556 		 */
11557 
11558 		/* m is now Error in estimate. */
11559 		m -= sa >> 3;
11560 		if ((sa += m) <= 0) {
11561 			/*
11562 			 * Don't allow the smoothed average to be negative.
11563 			 * We use 0 to denote reinitialization of the
11564 			 * variables.
11565 			 */
11566 			sa = 1;
11567 		}
11568 
11569 		/*
11570 		 * Update deviation estimator:
11571 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11572 		 */
11573 		if (m < 0)
11574 			m = -m;
11575 		m -= sv >> 2;
11576 		sv += m;
11577 	} else {
11578 		/*
11579 		 * This follows BSD's implementation.  So the reinitialized
11580 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11581 		 * link is bandwidth dominated, doubling the window size
11582 		 * during slow start means doubling the RTT.  We want to be
11583 		 * more conservative when we reinitialize our estimates.  3
11584 		 * is just a convenient number.
11585 		 */
11586 		sa = m << 3;
11587 		sv = m << 1;
11588 	}
11589 	if (sv < TCP_SD_MIN) {
11590 		/*
11591 		 * We do not know that if sa captures the delay ACK
11592 		 * effect as in a long train of segments, a receiver
11593 		 * does not delay its ACKs.  So set the minimum of sv
11594 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11595 		 * of BSD DATO.  That means the minimum of mean
11596 		 * deviation is 100 ms.
11597 		 *
11598 		 */
11599 		sv = TCP_SD_MIN;
11600 	}
11601 	tcp->tcp_rtt_sa = sa;
11602 	tcp->tcp_rtt_sd = sv;
11603 	/*
11604 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11605 	 *
11606 	 * Add tcp_rexmit_interval extra in case of extreme environment
11607 	 * where the algorithm fails to work.  The default value of
11608 	 * tcp_rexmit_interval_extra should be 0.
11609 	 *
11610 	 * As we use a finer grained clock than BSD and update
11611 	 * RTO for every ACKs, add in another .25 of RTT to the
11612 	 * deviation of RTO to accomodate burstiness of 1/4 of
11613 	 * window size.
11614 	 */
11615 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
11616 
11617 	if (rto > tcp_rexmit_interval_max) {
11618 		tcp->tcp_rto = tcp_rexmit_interval_max;
11619 	} else if (rto < tcp_rexmit_interval_min) {
11620 		tcp->tcp_rto = tcp_rexmit_interval_min;
11621 	} else {
11622 		tcp->tcp_rto = rto;
11623 	}
11624 
11625 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11626 	tcp->tcp_timer_backoff = 0;
11627 }
11628 
11629 /*
11630  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11631  * send queue which starts at the given seq. no.
11632  *
11633  * Parameters:
11634  *	tcp_t *tcp: the tcp instance pointer.
11635  *	uint32_t seq: the starting seq. no of the requested segment.
11636  *	int32_t *off: after the execution, *off will be the offset to
11637  *		the returned mblk which points to the requested seq no.
11638  *		It is the caller's responsibility to send in a non-null off.
11639  *
11640  * Return:
11641  *	A mblk_t pointer pointing to the requested segment in send queue.
11642  */
11643 static mblk_t *
11644 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11645 {
11646 	int32_t	cnt;
11647 	mblk_t	*mp;
11648 
11649 	/* Defensive coding.  Make sure we don't send incorrect data. */
11650 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
11651 		return (NULL);
11652 
11653 	cnt = seq - tcp->tcp_suna;
11654 	mp = tcp->tcp_xmit_head;
11655 	while (cnt > 0 && mp != NULL) {
11656 		cnt -= mp->b_wptr - mp->b_rptr;
11657 		if (cnt < 0) {
11658 			cnt += mp->b_wptr - mp->b_rptr;
11659 			break;
11660 		}
11661 		mp = mp->b_cont;
11662 	}
11663 	ASSERT(mp != NULL);
11664 	*off = cnt;
11665 	return (mp);
11666 }
11667 
11668 /*
11669  * This function handles all retransmissions if SACK is enabled for this
11670  * connection.  First it calculates how many segments can be retransmitted
11671  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11672  * segments.  A segment is eligible if sack_cnt for that segment is greater
11673  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11674  * all eligible segments, it checks to see if TCP can send some new segments
11675  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11676  *
11677  * Parameters:
11678  *	tcp_t *tcp: the tcp structure of the connection.
11679  *	uint_t *flags: in return, appropriate value will be set for
11680  *	tcp_rput_data().
11681  */
11682 static void
11683 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11684 {
11685 	notsack_blk_t	*notsack_blk;
11686 	int32_t		usable_swnd;
11687 	int32_t		mss;
11688 	uint32_t	seg_len;
11689 	mblk_t		*xmit_mp;
11690 
11691 	ASSERT(tcp->tcp_sack_info != NULL);
11692 	ASSERT(tcp->tcp_notsack_list != NULL);
11693 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11694 
11695 	/* Defensive coding in case there is a bug... */
11696 	if (tcp->tcp_notsack_list == NULL) {
11697 		return;
11698 	}
11699 	notsack_blk = tcp->tcp_notsack_list;
11700 	mss = tcp->tcp_mss;
11701 
11702 	/*
11703 	 * Limit the num of outstanding data in the network to be
11704 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11705 	 */
11706 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11707 
11708 	/* At least retransmit 1 MSS of data. */
11709 	if (usable_swnd <= 0) {
11710 		usable_swnd = mss;
11711 	}
11712 
11713 	/* Make sure no new RTT samples will be taken. */
11714 	tcp->tcp_csuna = tcp->tcp_snxt;
11715 
11716 	notsack_blk = tcp->tcp_notsack_list;
11717 	while (usable_swnd > 0) {
11718 		mblk_t		*snxt_mp, *tmp_mp;
11719 		tcp_seq		begin = tcp->tcp_sack_snxt;
11720 		tcp_seq		end;
11721 		int32_t		off;
11722 
11723 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11724 			if (SEQ_GT(notsack_blk->end, begin) &&
11725 			    (notsack_blk->sack_cnt >=
11726 			    tcp_dupack_fast_retransmit)) {
11727 				end = notsack_blk->end;
11728 				if (SEQ_LT(begin, notsack_blk->begin)) {
11729 					begin = notsack_blk->begin;
11730 				}
11731 				break;
11732 			}
11733 		}
11734 		/*
11735 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11736 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11737 		 * set to tcp_cwnd_ssthresh.
11738 		 */
11739 		if (notsack_blk == NULL) {
11740 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11741 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11742 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11743 				ASSERT(tcp->tcp_cwnd > 0);
11744 				return;
11745 			} else {
11746 				usable_swnd = usable_swnd / mss;
11747 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11748 				    MAX(usable_swnd * mss, mss);
11749 				*flags |= TH_XMIT_NEEDED;
11750 				return;
11751 			}
11752 		}
11753 
11754 		/*
11755 		 * Note that we may send more than usable_swnd allows here
11756 		 * because of round off, but no more than 1 MSS of data.
11757 		 */
11758 		seg_len = end - begin;
11759 		if (seg_len > mss)
11760 			seg_len = mss;
11761 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11762 		ASSERT(snxt_mp != NULL);
11763 		/* This should not happen.  Defensive coding again... */
11764 		if (snxt_mp == NULL) {
11765 			return;
11766 		}
11767 
11768 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11769 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11770 		if (xmit_mp == NULL)
11771 			return;
11772 
11773 		usable_swnd -= seg_len;
11774 		tcp->tcp_pipe += seg_len;
11775 		tcp->tcp_sack_snxt = begin + seg_len;
11776 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
11777 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11778 
11779 		/*
11780 		 * Update the send timestamp to avoid false retransmission.
11781 		 */
11782 		snxt_mp->b_prev = (mblk_t *)lbolt;
11783 
11784 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
11785 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
11786 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
11787 		/*
11788 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11789 		 * This happens when new data sent during fast recovery is
11790 		 * also lost.  If TCP retransmits those new data, it needs
11791 		 * to extend SACK recover phase to avoid starting another
11792 		 * fast retransmit/recovery unnecessarily.
11793 		 */
11794 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11795 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11796 		}
11797 	}
11798 }
11799 
11800 /*
11801  * This function handles policy checking at TCP level for non-hard_bound/
11802  * detached connections.
11803  */
11804 static boolean_t
11805 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
11806     boolean_t secure, boolean_t mctl_present)
11807 {
11808 	ipsec_latch_t *ipl = NULL;
11809 	ipsec_action_t *act = NULL;
11810 	mblk_t *data_mp;
11811 	ipsec_in_t *ii;
11812 	const char *reason;
11813 	kstat_named_t *counter;
11814 
11815 	ASSERT(mctl_present || !secure);
11816 
11817 	ASSERT((ipha == NULL && ip6h != NULL) ||
11818 	    (ip6h == NULL && ipha != NULL));
11819 
11820 	/*
11821 	 * We don't necessarily have an ipsec_in_act action to verify
11822 	 * policy because of assymetrical policy where we have only
11823 	 * outbound policy and no inbound policy (possible with global
11824 	 * policy).
11825 	 */
11826 	if (!secure) {
11827 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
11828 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
11829 			return (B_TRUE);
11830 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
11831 		    "tcp_check_policy", ipha, ip6h, secure);
11832 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11833 		    &ipdrops_tcp_clear, &tcp_dropper);
11834 		return (B_FALSE);
11835 	}
11836 
11837 	/*
11838 	 * We have a secure packet.
11839 	 */
11840 	if (act == NULL) {
11841 		ipsec_log_policy_failure(tcp->tcp_wq,
11842 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
11843 		    secure);
11844 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11845 		    &ipdrops_tcp_secure, &tcp_dropper);
11846 		return (B_FALSE);
11847 	}
11848 
11849 	/*
11850 	 * XXX This whole routine is currently incorrect.  ipl should
11851 	 * be set to the latch pointer, but is currently not set, so
11852 	 * we initialize it to NULL to avoid picking up random garbage.
11853 	 */
11854 	if (ipl == NULL)
11855 		return (B_TRUE);
11856 
11857 	data_mp = first_mp->b_cont;
11858 
11859 	ii = (ipsec_in_t *)first_mp->b_rptr;
11860 
11861 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
11862 	    &counter)) {
11863 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
11864 		return (B_TRUE);
11865 	}
11866 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
11867 	    "tcp inbound policy mismatch: %s, packet dropped\n",
11868 	    reason);
11869 	BUMP_MIB(&ip_mib, ipsecInFailed);
11870 
11871 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
11872 	return (B_FALSE);
11873 }
11874 
11875 /*
11876  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
11877  * retransmission after a timeout.
11878  *
11879  * To limit the number of duplicate segments, we limit the number of segment
11880  * to be sent in one time to tcp_snd_burst, the burst variable.
11881  */
11882 static void
11883 tcp_ss_rexmit(tcp_t *tcp)
11884 {
11885 	uint32_t	snxt;
11886 	uint32_t	smax;
11887 	int32_t		win;
11888 	int32_t		mss;
11889 	int32_t		off;
11890 	int32_t		burst = tcp->tcp_snd_burst;
11891 	mblk_t		*snxt_mp;
11892 
11893 	/*
11894 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
11895 	 * all unack'ed segments.
11896 	 */
11897 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
11898 		smax = tcp->tcp_rexmit_max;
11899 		snxt = tcp->tcp_rexmit_nxt;
11900 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
11901 			snxt = tcp->tcp_suna;
11902 		}
11903 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
11904 		win -= snxt - tcp->tcp_suna;
11905 		mss = tcp->tcp_mss;
11906 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
11907 
11908 		while (SEQ_LT(snxt, smax) && (win > 0) &&
11909 		    (burst > 0) && (snxt_mp != NULL)) {
11910 			mblk_t	*xmit_mp;
11911 			mblk_t	*old_snxt_mp = snxt_mp;
11912 			uint32_t cnt = mss;
11913 
11914 			if (win < cnt) {
11915 				cnt = win;
11916 			}
11917 			if (SEQ_GT(snxt + cnt, smax)) {
11918 				cnt = smax - snxt;
11919 			}
11920 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
11921 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
11922 			if (xmit_mp == NULL)
11923 				return;
11924 
11925 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11926 
11927 			snxt += cnt;
11928 			win -= cnt;
11929 			/*
11930 			 * Update the send timestamp to avoid false
11931 			 * retransmission.
11932 			 */
11933 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
11934 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
11935 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
11936 
11937 			tcp->tcp_rexmit_nxt = snxt;
11938 			burst--;
11939 		}
11940 		/*
11941 		 * If we have transmitted all we have at the time
11942 		 * we started the retranmission, we can leave
11943 		 * the rest of the job to tcp_wput_data().  But we
11944 		 * need to check the send window first.  If the
11945 		 * win is not 0, go on with tcp_wput_data().
11946 		 */
11947 		if (SEQ_LT(snxt, smax) || win == 0) {
11948 			return;
11949 		}
11950 	}
11951 	/* Only call tcp_wput_data() if there is data to be sent. */
11952 	if (tcp->tcp_unsent) {
11953 		tcp_wput_data(tcp, NULL, B_FALSE);
11954 	}
11955 }
11956 
11957 /*
11958  * Process all TCP option in SYN segment.  Note that this function should
11959  * be called after tcp_adapt_ire() is called so that the necessary info
11960  * from IRE is already set in the tcp structure.
11961  *
11962  * This function sets up the correct tcp_mss value according to the
11963  * MSS option value and our header size.  It also sets up the window scale
11964  * and timestamp values, and initialize SACK info blocks.  But it does not
11965  * change receive window size after setting the tcp_mss value.  The caller
11966  * should do the appropriate change.
11967  */
11968 void
11969 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
11970 {
11971 	int options;
11972 	tcp_opt_t tcpopt;
11973 	uint32_t mss_max;
11974 	char *tmp_tcph;
11975 
11976 	tcpopt.tcp = NULL;
11977 	options = tcp_parse_options(tcph, &tcpopt);
11978 
11979 	/*
11980 	 * Process MSS option.  Note that MSS option value does not account
11981 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
11982 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
11983 	 * IPv6.
11984 	 */
11985 	if (!(options & TCP_OPT_MSS_PRESENT)) {
11986 		if (tcp->tcp_ipversion == IPV4_VERSION)
11987 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
11988 		else
11989 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
11990 	} else {
11991 		if (tcp->tcp_ipversion == IPV4_VERSION)
11992 			mss_max = tcp_mss_max_ipv4;
11993 		else
11994 			mss_max = tcp_mss_max_ipv6;
11995 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
11996 			tcpopt.tcp_opt_mss = tcp_mss_min;
11997 		else if (tcpopt.tcp_opt_mss > mss_max)
11998 			tcpopt.tcp_opt_mss = mss_max;
11999 	}
12000 
12001 	/* Process Window Scale option. */
12002 	if (options & TCP_OPT_WSCALE_PRESENT) {
12003 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12004 		tcp->tcp_snd_ws_ok = B_TRUE;
12005 	} else {
12006 		tcp->tcp_snd_ws = B_FALSE;
12007 		tcp->tcp_snd_ws_ok = B_FALSE;
12008 		tcp->tcp_rcv_ws = B_FALSE;
12009 	}
12010 
12011 	/* Process Timestamp option. */
12012 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12013 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12014 		tmp_tcph = (char *)tcp->tcp_tcph;
12015 
12016 		tcp->tcp_snd_ts_ok = B_TRUE;
12017 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12018 		tcp->tcp_last_rcv_lbolt = lbolt64;
12019 		ASSERT(OK_32PTR(tmp_tcph));
12020 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12021 
12022 		/* Fill in our template header with basic timestamp option. */
12023 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12024 		tmp_tcph[0] = TCPOPT_NOP;
12025 		tmp_tcph[1] = TCPOPT_NOP;
12026 		tmp_tcph[2] = TCPOPT_TSTAMP;
12027 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12028 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12029 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12030 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12031 	} else {
12032 		tcp->tcp_snd_ts_ok = B_FALSE;
12033 	}
12034 
12035 	/*
12036 	 * Process SACK options.  If SACK is enabled for this connection,
12037 	 * then allocate the SACK info structure.  Note the following ways
12038 	 * when tcp_snd_sack_ok is set to true.
12039 	 *
12040 	 * For active connection: in tcp_adapt_ire() called in
12041 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12042 	 * is checked.
12043 	 *
12044 	 * For passive connection: in tcp_adapt_ire() called in
12045 	 * tcp_accept_comm().
12046 	 *
12047 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12048 	 * That check makes sure that if we did not send a SACK OK option,
12049 	 * we will not enable SACK for this connection even though the other
12050 	 * side sends us SACK OK option.  For active connection, the SACK
12051 	 * info structure has already been allocated.  So we need to free
12052 	 * it if SACK is disabled.
12053 	 */
12054 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12055 	    (tcp->tcp_snd_sack_ok ||
12056 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12057 		/* This should be true only in the passive case. */
12058 		if (tcp->tcp_sack_info == NULL) {
12059 			ASSERT(TCP_IS_DETACHED(tcp));
12060 			tcp->tcp_sack_info =
12061 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12062 		}
12063 		if (tcp->tcp_sack_info == NULL) {
12064 			tcp->tcp_snd_sack_ok = B_FALSE;
12065 		} else {
12066 			tcp->tcp_snd_sack_ok = B_TRUE;
12067 			if (tcp->tcp_snd_ts_ok) {
12068 				tcp->tcp_max_sack_blk = 3;
12069 			} else {
12070 				tcp->tcp_max_sack_blk = 4;
12071 			}
12072 		}
12073 	} else {
12074 		/*
12075 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12076 		 * no SACK info will be used for this
12077 		 * connection.  This assumes that SACK usage
12078 		 * permission is negotiated.  This may need
12079 		 * to be changed once this is clarified.
12080 		 */
12081 		if (tcp->tcp_sack_info != NULL) {
12082 			ASSERT(tcp->tcp_notsack_list == NULL);
12083 			kmem_cache_free(tcp_sack_info_cache,
12084 			    tcp->tcp_sack_info);
12085 			tcp->tcp_sack_info = NULL;
12086 		}
12087 		tcp->tcp_snd_sack_ok = B_FALSE;
12088 	}
12089 
12090 	/*
12091 	 * Now we know the exact TCP/IP header length, subtract
12092 	 * that from tcp_mss to get our side's MSS.
12093 	 */
12094 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12095 	/*
12096 	 * Here we assume that the other side's header size will be equal to
12097 	 * our header size.  We calculate the real MSS accordingly.  Need to
12098 	 * take into additional stuffs IPsec puts in.
12099 	 *
12100 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12101 	 */
12102 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12103 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12104 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12105 
12106 	/*
12107 	 * Set MSS to the smaller one of both ends of the connection.
12108 	 * We should not have called tcp_mss_set() before, but our
12109 	 * side of the MSS should have been set to a proper value
12110 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12111 	 * STREAM head parameters properly.
12112 	 *
12113 	 * If we have a larger-than-16-bit window but the other side
12114 	 * didn't want to do window scale, tcp_rwnd_set() will take
12115 	 * care of that.
12116 	 */
12117 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
12118 }
12119 
12120 /*
12121  * Sends the T_CONN_IND to the listener. The caller calls this
12122  * functions via squeue to get inside the listener's perimeter
12123  * once the 3 way hand shake is done a T_CONN_IND needs to be
12124  * sent. As an optimization, the caller can call this directly
12125  * if listener's perimeter is same as eager's.
12126  */
12127 /* ARGSUSED */
12128 void
12129 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12130 {
12131 	conn_t			*lconnp = (conn_t *)arg;
12132 	tcp_t			*listener = lconnp->conn_tcp;
12133 	tcp_t			*tcp;
12134 	struct T_conn_ind	*conn_ind;
12135 	ipaddr_t 		*addr_cache;
12136 	boolean_t		need_send_conn_ind = B_FALSE;
12137 
12138 	/* retrieve the eager */
12139 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12140 	ASSERT(conn_ind->OPT_offset != 0 &&
12141 	    conn_ind->OPT_length == sizeof (intptr_t));
12142 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12143 		conn_ind->OPT_length);
12144 
12145 	/*
12146 	 * TLI/XTI applications will get confused by
12147 	 * sending eager as an option since it violates
12148 	 * the option semantics. So remove the eager as
12149 	 * option since TLI/XTI app doesn't need it anyway.
12150 	 */
12151 	if (!TCP_IS_SOCKET(listener)) {
12152 		conn_ind->OPT_length = 0;
12153 		conn_ind->OPT_offset = 0;
12154 	}
12155 	if (listener->tcp_state == TCPS_CLOSED ||
12156 	    TCP_IS_DETACHED(listener)) {
12157 		/*
12158 		 * If listener has closed, it would have caused a
12159 		 * a cleanup/blowoff to happen for the eager. We
12160 		 * just need to return.
12161 		 */
12162 		freemsg(mp);
12163 		return;
12164 	}
12165 
12166 
12167 	/*
12168 	 * if the conn_req_q is full defer passing up the
12169 	 * T_CONN_IND until space is availabe after t_accept()
12170 	 * processing
12171 	 */
12172 	mutex_enter(&listener->tcp_eager_lock);
12173 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12174 		tcp_t *tail;
12175 
12176 		/*
12177 		 * The eager already has an extra ref put in tcp_rput_data
12178 		 * so that it stays till accept comes back even though it
12179 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12180 		 */
12181 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12182 		listener->tcp_conn_req_cnt_q0--;
12183 		listener->tcp_conn_req_cnt_q++;
12184 
12185 		/* Move from SYN_RCVD to ESTABLISHED list  */
12186 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12187 		    tcp->tcp_eager_prev_q0;
12188 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12189 		    tcp->tcp_eager_next_q0;
12190 		tcp->tcp_eager_prev_q0 = NULL;
12191 		tcp->tcp_eager_next_q0 = NULL;
12192 
12193 		/*
12194 		 * Insert at end of the queue because sockfs
12195 		 * sends down T_CONN_RES in chronological
12196 		 * order. Leaving the older conn indications
12197 		 * at front of the queue helps reducing search
12198 		 * time.
12199 		 */
12200 		tail = listener->tcp_eager_last_q;
12201 		if (tail != NULL)
12202 			tail->tcp_eager_next_q = tcp;
12203 		else
12204 			listener->tcp_eager_next_q = tcp;
12205 		listener->tcp_eager_last_q = tcp;
12206 		tcp->tcp_eager_next_q = NULL;
12207 		/*
12208 		 * Delay sending up the T_conn_ind until we are
12209 		 * done with the eager. Once we have have sent up
12210 		 * the T_conn_ind, the accept can potentially complete
12211 		 * any time and release the refhold we have on the eager.
12212 		 */
12213 		need_send_conn_ind = B_TRUE;
12214 	} else {
12215 		/*
12216 		 * Defer connection on q0 and set deferred
12217 		 * connection bit true
12218 		 */
12219 		tcp->tcp_conn_def_q0 = B_TRUE;
12220 
12221 		/* take tcp out of q0 ... */
12222 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12223 		    tcp->tcp_eager_next_q0;
12224 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12225 		    tcp->tcp_eager_prev_q0;
12226 
12227 		/* ... and place it at the end of q0 */
12228 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12229 		tcp->tcp_eager_next_q0 = listener;
12230 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12231 		listener->tcp_eager_prev_q0 = tcp;
12232 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12233 	}
12234 
12235 	/* we have timed out before */
12236 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12237 		tcp->tcp_syn_rcvd_timeout = 0;
12238 		listener->tcp_syn_rcvd_timeout--;
12239 		if (listener->tcp_syn_defense &&
12240 		    listener->tcp_syn_rcvd_timeout <=
12241 		    (tcp_conn_req_max_q0 >> 5) &&
12242 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12243 			listener->tcp_last_rcv_lbolt)) {
12244 			/*
12245 			 * Turn off the defense mode if we
12246 			 * believe the SYN attack is over.
12247 			 */
12248 			listener->tcp_syn_defense = B_FALSE;
12249 			if (listener->tcp_ip_addr_cache) {
12250 				kmem_free((void *)listener->tcp_ip_addr_cache,
12251 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12252 				listener->tcp_ip_addr_cache = NULL;
12253 			}
12254 		}
12255 	}
12256 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12257 	if (addr_cache != NULL) {
12258 		/*
12259 		 * We have finished a 3-way handshake with this
12260 		 * remote host. This proves the IP addr is good.
12261 		 * Cache it!
12262 		 */
12263 		addr_cache[IP_ADDR_CACHE_HASH(
12264 			tcp->tcp_remote)] = tcp->tcp_remote;
12265 	}
12266 	mutex_exit(&listener->tcp_eager_lock);
12267 	if (need_send_conn_ind)
12268 		putnext(listener->tcp_rq, mp);
12269 }
12270 
12271 mblk_t *
12272 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12273     uint_t *ifindexp, ip6_pkt_t *ippp)
12274 {
12275 	in_pktinfo_t	*pinfo;
12276 	ip6_t		*ip6h;
12277 	uchar_t		*rptr;
12278 	mblk_t		*first_mp = mp;
12279 	boolean_t	mctl_present = B_FALSE;
12280 	uint_t 		ifindex = 0;
12281 	ip6_pkt_t	ipp;
12282 	uint_t		ipvers;
12283 	uint_t		ip_hdr_len;
12284 
12285 	rptr = mp->b_rptr;
12286 	ASSERT(OK_32PTR(rptr));
12287 	ASSERT(tcp != NULL);
12288 	ipp.ipp_fields = 0;
12289 
12290 	switch DB_TYPE(mp) {
12291 	case M_CTL:
12292 		mp = mp->b_cont;
12293 		if (mp == NULL) {
12294 			freemsg(first_mp);
12295 			return (NULL);
12296 		}
12297 		if (DB_TYPE(mp) != M_DATA) {
12298 			freemsg(first_mp);
12299 			return (NULL);
12300 		}
12301 		mctl_present = B_TRUE;
12302 		break;
12303 	case M_DATA:
12304 		break;
12305 	default:
12306 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12307 		freemsg(mp);
12308 		return (NULL);
12309 	}
12310 	ipvers = IPH_HDR_VERSION(rptr);
12311 	if (ipvers == IPV4_VERSION) {
12312 		if (tcp == NULL) {
12313 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12314 			goto done;
12315 		}
12316 
12317 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12318 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12319 
12320 		/*
12321 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12322 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12323 		 */
12324 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12325 		    mctl_present) {
12326 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
12327 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
12328 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
12329 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
12330 				ipp.ipp_fields |= IPPF_IFINDEX;
12331 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
12332 				ifindex = pinfo->in_pkt_ifindex;
12333 			}
12334 			freeb(first_mp);
12335 			mctl_present = B_FALSE;
12336 		}
12337 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12338 	} else {
12339 		ip6h = (ip6_t *)rptr;
12340 
12341 		ASSERT(ipvers == IPV6_VERSION);
12342 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12343 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12344 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12345 
12346 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12347 			uint8_t	nexthdrp;
12348 
12349 			/* Look for ifindex information */
12350 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12351 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12352 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12353 					BUMP_MIB(&ip_mib, tcpInErrs);
12354 					freemsg(first_mp);
12355 					return (NULL);
12356 				}
12357 
12358 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12359 					ASSERT(ip6i->ip6i_ifindex != 0);
12360 					ipp.ipp_fields |= IPPF_IFINDEX;
12361 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12362 					ifindex = ip6i->ip6i_ifindex;
12363 				}
12364 				rptr = (uchar_t *)&ip6i[1];
12365 				mp->b_rptr = rptr;
12366 				if (rptr == mp->b_wptr) {
12367 					mblk_t *mp1;
12368 					mp1 = mp->b_cont;
12369 					freeb(mp);
12370 					mp = mp1;
12371 					rptr = mp->b_rptr;
12372 				}
12373 				if (MBLKL(mp) < IPV6_HDR_LEN +
12374 				    sizeof (tcph_t)) {
12375 					BUMP_MIB(&ip_mib, tcpInErrs);
12376 					freemsg(first_mp);
12377 					return (NULL);
12378 				}
12379 				ip6h = (ip6_t *)rptr;
12380 			}
12381 
12382 			/*
12383 			 * Find any potentially interesting extension headers
12384 			 * as well as the length of the IPv6 + extension
12385 			 * headers.
12386 			 */
12387 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12388 			/* Verify if this is a TCP packet */
12389 			if (nexthdrp != IPPROTO_TCP) {
12390 				BUMP_MIB(&ip_mib, tcpInErrs);
12391 				freemsg(first_mp);
12392 				return (NULL);
12393 			}
12394 		} else {
12395 			ip_hdr_len = IPV6_HDR_LEN;
12396 		}
12397 	}
12398 
12399 done:
12400 	if (ipversp != NULL)
12401 		*ipversp = ipvers;
12402 	if (ip_hdr_lenp != NULL)
12403 		*ip_hdr_lenp = ip_hdr_len;
12404 	if (ippp != NULL)
12405 		*ippp = ipp;
12406 	if (ifindexp != NULL)
12407 		*ifindexp = ifindex;
12408 	if (mctl_present) {
12409 		freeb(first_mp);
12410 	}
12411 	return (mp);
12412 }
12413 
12414 /*
12415  * Handle M_DATA messages from IP. Its called directly from IP via
12416  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12417  * in this path.
12418  *
12419  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12420  * v4 and v6), we are called through tcp_input() and a M_CTL can
12421  * be present for options but tcp_find_pktinfo() deals with it. We
12422  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12423  *
12424  * The first argument is always the connp/tcp to which the mp belongs.
12425  * There are no exceptions to this rule. The caller has already put
12426  * a reference on this connp/tcp and once tcp_rput_data() returns,
12427  * the squeue will do the refrele.
12428  *
12429  * The TH_SYN for the listener directly go to tcp_conn_request via
12430  * squeue.
12431  *
12432  * sqp: NULL = recursive, sqp != NULL means called from squeue
12433  */
12434 void
12435 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12436 {
12437 	int32_t		bytes_acked;
12438 	int32_t		gap;
12439 	mblk_t		*mp1;
12440 	uint_t		flags;
12441 	uint32_t	new_swnd = 0;
12442 	uchar_t		*iphdr;
12443 	uchar_t		*rptr;
12444 	int32_t		rgap;
12445 	uint32_t	seg_ack;
12446 	int		seg_len;
12447 	uint_t		ip_hdr_len;
12448 	uint32_t	seg_seq;
12449 	tcph_t		*tcph;
12450 	int		urp;
12451 	tcp_opt_t	tcpopt;
12452 	uint_t		ipvers;
12453 	ip6_pkt_t	ipp;
12454 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12455 	uint32_t	cwnd;
12456 	uint32_t	add;
12457 	int		npkt;
12458 	int		mss;
12459 	conn_t		*connp = (conn_t *)arg;
12460 	squeue_t	*sqp = (squeue_t *)arg2;
12461 	tcp_t		*tcp = connp->conn_tcp;
12462 
12463 	/*
12464 	 * RST from fused tcp loopback peer should trigger an unfuse.
12465 	 */
12466 	if (tcp->tcp_fused) {
12467 		TCP_STAT(tcp_fusion_aborted);
12468 		tcp_unfuse(tcp);
12469 	}
12470 
12471 	iphdr = mp->b_rptr;
12472 	rptr = mp->b_rptr;
12473 	ASSERT(OK_32PTR(rptr));
12474 
12475 	/*
12476 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12477 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12478 	 * necessary information.
12479 	 */
12480 	if (IPCL_IS_TCP4(connp)) {
12481 		ipvers = IPV4_VERSION;
12482 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12483 	} else {
12484 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12485 		    NULL, &ipp);
12486 		if (mp == NULL) {
12487 			TCP_STAT(tcp_rput_v6_error);
12488 			return;
12489 		}
12490 		iphdr = mp->b_rptr;
12491 		rptr = mp->b_rptr;
12492 	}
12493 	ASSERT(DB_TYPE(mp) == M_DATA);
12494 
12495 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12496 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12497 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12498 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12499 	seg_len = (int)(mp->b_wptr - rptr) -
12500 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12501 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12502 		do {
12503 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12504 			    (uintptr_t)INT_MAX);
12505 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12506 		} while ((mp1 = mp1->b_cont) != NULL &&
12507 		    mp1->b_datap->db_type == M_DATA);
12508 	}
12509 
12510 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12511 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12512 		    seg_len, tcph);
12513 		return;
12514 	}
12515 
12516 	if (sqp != NULL) {
12517 		/*
12518 		 * This is the correct place to update tcp_last_recv_time. Note
12519 		 * that it is also updated for tcp structure that belongs to
12520 		 * global and listener queues which do not really need updating.
12521 		 * But that should not cause any harm.  And it is updated for
12522 		 * all kinds of incoming segments, not only for data segments.
12523 		 */
12524 		tcp->tcp_last_recv_time = lbolt;
12525 	}
12526 
12527 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12528 
12529 	BUMP_LOCAL(tcp->tcp_ibsegs);
12530 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12531 
12532 	if ((flags & TH_URG) && sqp != NULL) {
12533 		/*
12534 		 * TCP can't handle urgent pointers that arrive before
12535 		 * the connection has been accept()ed since it can't
12536 		 * buffer OOB data.  Discard segment if this happens.
12537 		 *
12538 		 * Nor can it reassemble urgent pointers, so discard
12539 		 * if it's not the next segment expected.
12540 		 *
12541 		 * Otherwise, collapse chain into one mblk (discard if
12542 		 * that fails).  This makes sure the headers, retransmitted
12543 		 * data, and new data all are in the same mblk.
12544 		 */
12545 		ASSERT(mp != NULL);
12546 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
12547 			freemsg(mp);
12548 			return;
12549 		}
12550 		/* Update pointers into message */
12551 		iphdr = rptr = mp->b_rptr;
12552 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12553 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12554 			/*
12555 			 * Since we can't handle any data with this urgent
12556 			 * pointer that is out of sequence, we expunge
12557 			 * the data.  This allows us to still register
12558 			 * the urgent mark and generate the M_PCSIG,
12559 			 * which we can do.
12560 			 */
12561 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12562 			seg_len = 0;
12563 		}
12564 	}
12565 
12566 	switch (tcp->tcp_state) {
12567 	case TCPS_SYN_SENT:
12568 		if (flags & TH_ACK) {
12569 			/*
12570 			 * Note that our stack cannot send data before a
12571 			 * connection is established, therefore the
12572 			 * following check is valid.  Otherwise, it has
12573 			 * to be changed.
12574 			 */
12575 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12576 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12577 				freemsg(mp);
12578 				if (flags & TH_RST)
12579 					return;
12580 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12581 				    tcp, seg_ack, 0, TH_RST);
12582 				return;
12583 			}
12584 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12585 		}
12586 		if (flags & TH_RST) {
12587 			freemsg(mp);
12588 			if (flags & TH_ACK)
12589 				(void) tcp_clean_death(tcp,
12590 				    ECONNREFUSED, 13);
12591 			return;
12592 		}
12593 		if (!(flags & TH_SYN)) {
12594 			freemsg(mp);
12595 			return;
12596 		}
12597 
12598 		/* Process all TCP options. */
12599 		tcp_process_options(tcp, tcph);
12600 		/*
12601 		 * The following changes our rwnd to be a multiple of the
12602 		 * MIN(peer MSS, our MSS) for performance reason.
12603 		 */
12604 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12605 		    tcp->tcp_mss));
12606 
12607 		/* Is the other end ECN capable? */
12608 		if (tcp->tcp_ecn_ok) {
12609 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12610 				tcp->tcp_ecn_ok = B_FALSE;
12611 			}
12612 		}
12613 		/*
12614 		 * Clear ECN flags because it may interfere with later
12615 		 * processing.
12616 		 */
12617 		flags &= ~(TH_ECE|TH_CWR);
12618 
12619 		tcp->tcp_irs = seg_seq;
12620 		tcp->tcp_rack = seg_seq;
12621 		tcp->tcp_rnxt = seg_seq + 1;
12622 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12623 		if (!TCP_IS_DETACHED(tcp)) {
12624 			/* Allocate room for SACK options if needed. */
12625 			if (tcp->tcp_snd_sack_ok) {
12626 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12627 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
12628 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12629 			} else {
12630 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12631 				    tcp->tcp_hdr_len +
12632 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12633 			}
12634 		}
12635 		if (flags & TH_ACK) {
12636 			/*
12637 			 * If we can't get the confirmation upstream, pretend
12638 			 * we didn't even see this one.
12639 			 *
12640 			 * XXX: how can we pretend we didn't see it if we
12641 			 * have updated rnxt et. al.
12642 			 *
12643 			 * For loopback we defer sending up the T_CONN_CON
12644 			 * until after some checks below.
12645 			 */
12646 			mp1 = NULL;
12647 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12648 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12649 				freemsg(mp);
12650 				return;
12651 			}
12652 			/* SYN was acked - making progress */
12653 			if (tcp->tcp_ipversion == IPV6_VERSION)
12654 				tcp->tcp_ip_forward_progress = B_TRUE;
12655 
12656 			/* One for the SYN */
12657 			tcp->tcp_suna = tcp->tcp_iss + 1;
12658 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12659 			tcp->tcp_state = TCPS_ESTABLISHED;
12660 
12661 			/*
12662 			 * If SYN was retransmitted, need to reset all
12663 			 * retransmission info.  This is because this
12664 			 * segment will be treated as a dup ACK.
12665 			 */
12666 			if (tcp->tcp_rexmit) {
12667 				tcp->tcp_rexmit = B_FALSE;
12668 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12669 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12670 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12671 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12672 				tcp->tcp_ms_we_have_waited = 0;
12673 
12674 				/*
12675 				 * Set tcp_cwnd back to 1 MSS, per
12676 				 * recommendation from
12677 				 * draft-floyd-incr-init-win-01.txt,
12678 				 * Increasing TCP's Initial Window.
12679 				 */
12680 				tcp->tcp_cwnd = tcp->tcp_mss;
12681 			}
12682 
12683 			tcp->tcp_swl1 = seg_seq;
12684 			tcp->tcp_swl2 = seg_ack;
12685 
12686 			new_swnd = BE16_TO_U16(tcph->th_win);
12687 			tcp->tcp_swnd = new_swnd;
12688 			if (new_swnd > tcp->tcp_max_swnd)
12689 				tcp->tcp_max_swnd = new_swnd;
12690 
12691 			/*
12692 			 * Always send the three-way handshake ack immediately
12693 			 * in order to make the connection complete as soon as
12694 			 * possible on the accepting host.
12695 			 */
12696 			flags |= TH_ACK_NEEDED;
12697 
12698 			/*
12699 			 * Special case for loopback.  At this point we have
12700 			 * received SYN-ACK from the remote endpoint.  In
12701 			 * order to ensure that both endpoints reach the
12702 			 * fused state prior to any data exchange, the final
12703 			 * ACK needs to be sent before we indicate T_CONN_CON
12704 			 * to the module upstream.
12705 			 */
12706 			if (tcp->tcp_loopback) {
12707 				mblk_t *ack_mp;
12708 
12709 				ASSERT(!tcp->tcp_unfusable);
12710 				ASSERT(mp1 != NULL);
12711 				/*
12712 				 * For loopback, we always get a pure SYN-ACK
12713 				 * and only need to send back the final ACK
12714 				 * with no data (this is because the other
12715 				 * tcp is ours and we don't do T/TCP).  This
12716 				 * final ACK triggers the passive side to
12717 				 * perform fusion in ESTABLISHED state.
12718 				 */
12719 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12720 					if (tcp->tcp_ack_tid != 0) {
12721 						(void) TCP_TIMER_CANCEL(tcp,
12722 						    tcp->tcp_ack_tid);
12723 						tcp->tcp_ack_tid = 0;
12724 					}
12725 					TCP_RECORD_TRACE(tcp, ack_mp,
12726 					    TCP_TRACE_SEND_PKT);
12727 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
12728 					BUMP_LOCAL(tcp->tcp_obsegs);
12729 					BUMP_MIB(&tcp_mib, tcpOutAck);
12730 
12731 					/* Send up T_CONN_CON */
12732 					putnext(tcp->tcp_rq, mp1);
12733 
12734 					freemsg(mp);
12735 					return;
12736 				}
12737 				/*
12738 				 * Forget fusion; we need to handle more
12739 				 * complex cases below.  Send the deferred
12740 				 * T_CONN_CON message upstream and proceed
12741 				 * as usual.  Mark this tcp as not capable
12742 				 * of fusion.
12743 				 */
12744 				TCP_STAT(tcp_fusion_unfusable);
12745 				tcp->tcp_unfusable = B_TRUE;
12746 				putnext(tcp->tcp_rq, mp1);
12747 			}
12748 
12749 			/*
12750 			 * Check to see if there is data to be sent.  If
12751 			 * yes, set the transmit flag.  Then check to see
12752 			 * if received data processing needs to be done.
12753 			 * If not, go straight to xmit_check.  This short
12754 			 * cut is OK as we don't support T/TCP.
12755 			 */
12756 			if (tcp->tcp_unsent)
12757 				flags |= TH_XMIT_NEEDED;
12758 
12759 			if (seg_len == 0 && !(flags & TH_URG)) {
12760 				freemsg(mp);
12761 				goto xmit_check;
12762 			}
12763 
12764 			flags &= ~TH_SYN;
12765 			seg_seq++;
12766 			break;
12767 		}
12768 		tcp->tcp_state = TCPS_SYN_RCVD;
12769 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
12770 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
12771 		if (mp1) {
12772 			DB_CPID(mp1) = tcp->tcp_cpid;
12773 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
12774 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
12775 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12776 		}
12777 		freemsg(mp);
12778 		return;
12779 	case TCPS_SYN_RCVD:
12780 		if (flags & TH_ACK) {
12781 			/*
12782 			 * In this state, a SYN|ACK packet is either bogus
12783 			 * because the other side must be ACKing our SYN which
12784 			 * indicates it has seen the ACK for their SYN and
12785 			 * shouldn't retransmit it or we're crossing SYNs
12786 			 * on active open.
12787 			 */
12788 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
12789 				freemsg(mp);
12790 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
12791 				    tcp, seg_ack, 0, TH_RST);
12792 				return;
12793 			}
12794 			/*
12795 			 * NOTE: RFC 793 pg. 72 says this should be
12796 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
12797 			 * but that would mean we have an ack that ignored
12798 			 * our SYN.
12799 			 */
12800 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
12801 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12802 				freemsg(mp);
12803 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
12804 				    tcp, seg_ack, 0, TH_RST);
12805 				return;
12806 			}
12807 		}
12808 		break;
12809 	case TCPS_LISTEN:
12810 		/*
12811 		 * Only a TLI listener can come through this path when a
12812 		 * acceptor is going back to be a listener and a packet
12813 		 * for the acceptor hits the classifier. For a socket
12814 		 * listener, this can never happen because a listener
12815 		 * can never accept connection on itself and hence a
12816 		 * socket acceptor can not go back to being a listener.
12817 		 */
12818 		ASSERT(!TCP_IS_SOCKET(tcp));
12819 		/*FALLTHRU*/
12820 	case TCPS_CLOSED:
12821 	case TCPS_BOUND: {
12822 		conn_t	*new_connp;
12823 
12824 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
12825 		if (new_connp != NULL) {
12826 			tcp_reinput(new_connp, mp, connp->conn_sqp);
12827 			return;
12828 		}
12829 		/* We failed to classify. For now just drop the packet */
12830 		freemsg(mp);
12831 		return;
12832 	}
12833 	case TCPS_IDLE:
12834 		/*
12835 		 * Handle the case where the tcp_clean_death() has happened
12836 		 * on a connection (application hasn't closed yet) but a packet
12837 		 * was already queued on squeue before tcp_clean_death()
12838 		 * was processed. Calling tcp_clean_death() twice on same
12839 		 * connection can result in weird behaviour.
12840 		 */
12841 		freemsg(mp);
12842 		return;
12843 	default:
12844 		break;
12845 	}
12846 
12847 	/*
12848 	 * Already on the correct queue/perimeter.
12849 	 * If this is a detached connection and not an eager
12850 	 * connection hanging off a listener then new data
12851 	 * (past the FIN) will cause a reset.
12852 	 * We do a special check here where it
12853 	 * is out of the main line, rather than check
12854 	 * if we are detached every time we see new
12855 	 * data down below.
12856 	 */
12857 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
12858 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
12859 		BUMP_MIB(&tcp_mib, tcpInClosed);
12860 		TCP_RECORD_TRACE(tcp,
12861 		    mp, TCP_TRACE_RECV_PKT);
12862 
12863 		freemsg(mp);
12864 		/*
12865 		 * This could be an SSL closure alert. We're detached so just
12866 		 * acknowledge it this last time.
12867 		 */
12868 		if (tcp->tcp_kssl_ctx != NULL) {
12869 			kssl_release_ctx(tcp->tcp_kssl_ctx);
12870 			tcp->tcp_kssl_ctx = NULL;
12871 
12872 			tcp->tcp_rnxt += seg_len;
12873 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12874 			flags |= TH_ACK_NEEDED;
12875 			goto ack_check;
12876 		}
12877 
12878 		tcp_xmit_ctl("new data when detached", tcp,
12879 		    tcp->tcp_snxt, 0, TH_RST);
12880 		(void) tcp_clean_death(tcp, EPROTO, 12);
12881 		return;
12882 	}
12883 
12884 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12885 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
12886 	new_swnd = BE16_TO_U16(tcph->th_win) <<
12887 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
12888 	mss = tcp->tcp_mss;
12889 
12890 	if (tcp->tcp_snd_ts_ok) {
12891 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
12892 			/*
12893 			 * This segment is not acceptable.
12894 			 * Drop it and send back an ACK.
12895 			 */
12896 			freemsg(mp);
12897 			flags |= TH_ACK_NEEDED;
12898 			goto ack_check;
12899 		}
12900 	} else if (tcp->tcp_snd_sack_ok) {
12901 		ASSERT(tcp->tcp_sack_info != NULL);
12902 		tcpopt.tcp = tcp;
12903 		/*
12904 		 * SACK info in already updated in tcp_parse_options.  Ignore
12905 		 * all other TCP options...
12906 		 */
12907 		(void) tcp_parse_options(tcph, &tcpopt);
12908 	}
12909 try_again:;
12910 	gap = seg_seq - tcp->tcp_rnxt;
12911 	rgap = tcp->tcp_rwnd - (gap + seg_len);
12912 	/*
12913 	 * gap is the amount of sequence space between what we expect to see
12914 	 * and what we got for seg_seq.  A positive value for gap means
12915 	 * something got lost.  A negative value means we got some old stuff.
12916 	 */
12917 	if (gap < 0) {
12918 		/* Old stuff present.  Is the SYN in there? */
12919 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
12920 		    (seg_len != 0)) {
12921 			flags &= ~TH_SYN;
12922 			seg_seq++;
12923 			urp--;
12924 			/* Recompute the gaps after noting the SYN. */
12925 			goto try_again;
12926 		}
12927 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
12928 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
12929 		    (seg_len > -gap ? -gap : seg_len));
12930 		/* Remove the old stuff from seg_len. */
12931 		seg_len += gap;
12932 		/*
12933 		 * Anything left?
12934 		 * Make sure to check for unack'd FIN when rest of data
12935 		 * has been previously ack'd.
12936 		 */
12937 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
12938 			/*
12939 			 * Resets are only valid if they lie within our offered
12940 			 * window.  If the RST bit is set, we just ignore this
12941 			 * segment.
12942 			 */
12943 			if (flags & TH_RST) {
12944 				freemsg(mp);
12945 				return;
12946 			}
12947 
12948 			/*
12949 			 * The arriving of dup data packets indicate that we
12950 			 * may have postponed an ack for too long, or the other
12951 			 * side's RTT estimate is out of shape. Start acking
12952 			 * more often.
12953 			 */
12954 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
12955 			    tcp->tcp_rack_cnt >= 1 &&
12956 			    tcp->tcp_rack_abs_max > 2) {
12957 				tcp->tcp_rack_abs_max--;
12958 			}
12959 			tcp->tcp_rack_cur_max = 1;
12960 
12961 			/*
12962 			 * This segment is "unacceptable".  None of its
12963 			 * sequence space lies within our advertized window.
12964 			 *
12965 			 * Adjust seg_len to the original value for tracing.
12966 			 */
12967 			seg_len -= gap;
12968 			if (tcp->tcp_debug) {
12969 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12970 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
12971 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
12972 				    "seg_len %d, rnxt %u, snxt %u, %s",
12973 				    gap, rgap, flags, seg_seq, seg_ack,
12974 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
12975 				    tcp_display(tcp, NULL,
12976 				    DISP_ADDR_AND_PORT));
12977 			}
12978 
12979 			/*
12980 			 * Arrange to send an ACK in response to the
12981 			 * unacceptable segment per RFC 793 page 69. There
12982 			 * is only one small difference between ours and the
12983 			 * acceptability test in the RFC - we accept ACK-only
12984 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
12985 			 * will be generated.
12986 			 *
12987 			 * Note that we have to ACK an ACK-only packet at least
12988 			 * for stacks that send 0-length keep-alives with
12989 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
12990 			 * section 4.2.3.6. As long as we don't ever generate
12991 			 * an unacceptable packet in response to an incoming
12992 			 * packet that is unacceptable, it should not cause
12993 			 * "ACK wars".
12994 			 */
12995 			flags |=  TH_ACK_NEEDED;
12996 
12997 			/*
12998 			 * Continue processing this segment in order to use the
12999 			 * ACK information it contains, but skip all other
13000 			 * sequence-number processing.	Processing the ACK
13001 			 * information is necessary in order to
13002 			 * re-synchronize connections that may have lost
13003 			 * synchronization.
13004 			 *
13005 			 * We clear seg_len and flag fields related to
13006 			 * sequence number processing as they are not
13007 			 * to be trusted for an unacceptable segment.
13008 			 */
13009 			seg_len = 0;
13010 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13011 			goto process_ack;
13012 		}
13013 
13014 		/* Fix seg_seq, and chew the gap off the front. */
13015 		seg_seq = tcp->tcp_rnxt;
13016 		urp += gap;
13017 		do {
13018 			mblk_t	*mp2;
13019 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13020 			    (uintptr_t)UINT_MAX);
13021 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13022 			if (gap > 0) {
13023 				mp->b_rptr = mp->b_wptr - gap;
13024 				break;
13025 			}
13026 			mp2 = mp;
13027 			mp = mp->b_cont;
13028 			freeb(mp2);
13029 		} while (gap < 0);
13030 		/*
13031 		 * If the urgent data has already been acknowledged, we
13032 		 * should ignore TH_URG below
13033 		 */
13034 		if (urp < 0)
13035 			flags &= ~TH_URG;
13036 	}
13037 	/*
13038 	 * rgap is the amount of stuff received out of window.  A negative
13039 	 * value is the amount out of window.
13040 	 */
13041 	if (rgap < 0) {
13042 		mblk_t	*mp2;
13043 
13044 		if (tcp->tcp_rwnd == 0) {
13045 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
13046 		} else {
13047 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
13048 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
13049 		}
13050 
13051 		/*
13052 		 * seg_len does not include the FIN, so if more than
13053 		 * just the FIN is out of window, we act like we don't
13054 		 * see it.  (If just the FIN is out of window, rgap
13055 		 * will be zero and we will go ahead and acknowledge
13056 		 * the FIN.)
13057 		 */
13058 		flags &= ~TH_FIN;
13059 
13060 		/* Fix seg_len and make sure there is something left. */
13061 		seg_len += rgap;
13062 		if (seg_len <= 0) {
13063 			/*
13064 			 * Resets are only valid if they lie within our offered
13065 			 * window.  If the RST bit is set, we just ignore this
13066 			 * segment.
13067 			 */
13068 			if (flags & TH_RST) {
13069 				freemsg(mp);
13070 				return;
13071 			}
13072 
13073 			/* Per RFC 793, we need to send back an ACK. */
13074 			flags |= TH_ACK_NEEDED;
13075 
13076 			/*
13077 			 * Send SIGURG as soon as possible i.e. even
13078 			 * if the TH_URG was delivered in a window probe
13079 			 * packet (which will be unacceptable).
13080 			 *
13081 			 * We generate a signal if none has been generated
13082 			 * for this connection or if this is a new urgent
13083 			 * byte. Also send a zero-length "unmarked" message
13084 			 * to inform SIOCATMARK that this is not the mark.
13085 			 *
13086 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13087 			 * is sent up. This plus the check for old data
13088 			 * (gap >= 0) handles the wraparound of the sequence
13089 			 * number space without having to always track the
13090 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13091 			 * this max in its rcv_up variable).
13092 			 *
13093 			 * This prevents duplicate SIGURGS due to a "late"
13094 			 * zero-window probe when the T_EXDATA_IND has already
13095 			 * been sent up.
13096 			 */
13097 			if ((flags & TH_URG) &&
13098 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13099 			    tcp->tcp_urp_last))) {
13100 				mp1 = allocb(0, BPRI_MED);
13101 				if (mp1 == NULL) {
13102 					freemsg(mp);
13103 					return;
13104 				}
13105 				if (!TCP_IS_DETACHED(tcp) &&
13106 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13107 				    SIGURG)) {
13108 					/* Try again on the rexmit. */
13109 					freemsg(mp1);
13110 					freemsg(mp);
13111 					return;
13112 				}
13113 				/*
13114 				 * If the next byte would be the mark
13115 				 * then mark with MARKNEXT else mark
13116 				 * with NOTMARKNEXT.
13117 				 */
13118 				if (gap == 0 && urp == 0)
13119 					mp1->b_flag |= MSGMARKNEXT;
13120 				else
13121 					mp1->b_flag |= MSGNOTMARKNEXT;
13122 				freemsg(tcp->tcp_urp_mark_mp);
13123 				tcp->tcp_urp_mark_mp = mp1;
13124 				flags |= TH_SEND_URP_MARK;
13125 				tcp->tcp_urp_last_valid = B_TRUE;
13126 				tcp->tcp_urp_last = urp + seg_seq;
13127 			}
13128 			/*
13129 			 * If this is a zero window probe, continue to
13130 			 * process the ACK part.  But we need to set seg_len
13131 			 * to 0 to avoid data processing.  Otherwise just
13132 			 * drop the segment and send back an ACK.
13133 			 */
13134 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13135 				flags &= ~(TH_SYN | TH_URG);
13136 				seg_len = 0;
13137 				goto process_ack;
13138 			} else {
13139 				freemsg(mp);
13140 				goto ack_check;
13141 			}
13142 		}
13143 		/* Pitch out of window stuff off the end. */
13144 		rgap = seg_len;
13145 		mp2 = mp;
13146 		do {
13147 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13148 			    (uintptr_t)INT_MAX);
13149 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13150 			if (rgap < 0) {
13151 				mp2->b_wptr += rgap;
13152 				if ((mp1 = mp2->b_cont) != NULL) {
13153 					mp2->b_cont = NULL;
13154 					freemsg(mp1);
13155 				}
13156 				break;
13157 			}
13158 		} while ((mp2 = mp2->b_cont) != NULL);
13159 	}
13160 ok:;
13161 	/*
13162 	 * TCP should check ECN info for segments inside the window only.
13163 	 * Therefore the check should be done here.
13164 	 */
13165 	if (tcp->tcp_ecn_ok) {
13166 		if (flags & TH_CWR) {
13167 			tcp->tcp_ecn_echo_on = B_FALSE;
13168 		}
13169 		/*
13170 		 * Note that both ECN_CE and CWR can be set in the
13171 		 * same segment.  In this case, we once again turn
13172 		 * on ECN_ECHO.
13173 		 */
13174 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13175 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13176 
13177 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13178 				tcp->tcp_ecn_echo_on = B_TRUE;
13179 			}
13180 		} else {
13181 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13182 
13183 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13184 			    htonl(IPH_ECN_CE << 20)) {
13185 				tcp->tcp_ecn_echo_on = B_TRUE;
13186 			}
13187 		}
13188 	}
13189 
13190 	/*
13191 	 * Check whether we can update tcp_ts_recent.  This test is
13192 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13193 	 * Extensions for High Performance: An Update", Internet Draft.
13194 	 */
13195 	if (tcp->tcp_snd_ts_ok &&
13196 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13197 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13198 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13199 		tcp->tcp_last_rcv_lbolt = lbolt64;
13200 	}
13201 
13202 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13203 		/*
13204 		 * FIN in an out of order segment.  We record this in
13205 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13206 		 * Clear the FIN so that any check on FIN flag will fail.
13207 		 * Remember that FIN also counts in the sequence number
13208 		 * space.  So we need to ack out of order FIN only segments.
13209 		 */
13210 		if (flags & TH_FIN) {
13211 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13212 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13213 			flags &= ~TH_FIN;
13214 			flags |= TH_ACK_NEEDED;
13215 		}
13216 		if (seg_len > 0) {
13217 			/* Fill in the SACK blk list. */
13218 			if (tcp->tcp_snd_sack_ok) {
13219 				ASSERT(tcp->tcp_sack_info != NULL);
13220 				tcp_sack_insert(tcp->tcp_sack_list,
13221 				    seg_seq, seg_seq + seg_len,
13222 				    &(tcp->tcp_num_sack_blk));
13223 			}
13224 
13225 			/*
13226 			 * Attempt reassembly and see if we have something
13227 			 * ready to go.
13228 			 */
13229 			mp = tcp_reass(tcp, mp, seg_seq);
13230 			/* Always ack out of order packets */
13231 			flags |= TH_ACK_NEEDED | TH_PUSH;
13232 			if (mp) {
13233 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13234 				    (uintptr_t)INT_MAX);
13235 				seg_len = mp->b_cont ? msgdsize(mp) :
13236 					(int)(mp->b_wptr - mp->b_rptr);
13237 				seg_seq = tcp->tcp_rnxt;
13238 				/*
13239 				 * A gap is filled and the seq num and len
13240 				 * of the gap match that of a previously
13241 				 * received FIN, put the FIN flag back in.
13242 				 */
13243 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13244 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13245 					flags |= TH_FIN;
13246 					tcp->tcp_valid_bits &=
13247 					    ~TCP_OFO_FIN_VALID;
13248 				}
13249 			} else {
13250 				/*
13251 				 * Keep going even with NULL mp.
13252 				 * There may be a useful ACK or something else
13253 				 * we don't want to miss.
13254 				 *
13255 				 * But TCP should not perform fast retransmit
13256 				 * because of the ack number.  TCP uses
13257 				 * seg_len == 0 to determine if it is a pure
13258 				 * ACK.  And this is not a pure ACK.
13259 				 */
13260 				seg_len = 0;
13261 				ofo_seg = B_TRUE;
13262 			}
13263 		}
13264 	} else if (seg_len > 0) {
13265 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
13266 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
13267 		/*
13268 		 * If an out of order FIN was received before, and the seq
13269 		 * num and len of the new segment match that of the FIN,
13270 		 * put the FIN flag back in.
13271 		 */
13272 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13273 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13274 			flags |= TH_FIN;
13275 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13276 		}
13277 	}
13278 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13279 	if (flags & TH_RST) {
13280 		freemsg(mp);
13281 		switch (tcp->tcp_state) {
13282 		case TCPS_SYN_RCVD:
13283 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13284 			break;
13285 		case TCPS_ESTABLISHED:
13286 		case TCPS_FIN_WAIT_1:
13287 		case TCPS_FIN_WAIT_2:
13288 		case TCPS_CLOSE_WAIT:
13289 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13290 			break;
13291 		case TCPS_CLOSING:
13292 		case TCPS_LAST_ACK:
13293 			(void) tcp_clean_death(tcp, 0, 16);
13294 			break;
13295 		default:
13296 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13297 			(void) tcp_clean_death(tcp, ENXIO, 17);
13298 			break;
13299 		}
13300 		return;
13301 	}
13302 	if (flags & TH_SYN) {
13303 		/*
13304 		 * See RFC 793, Page 71
13305 		 *
13306 		 * The seq number must be in the window as it should
13307 		 * be "fixed" above.  If it is outside window, it should
13308 		 * be already rejected.  Note that we allow seg_seq to be
13309 		 * rnxt + rwnd because we want to accept 0 window probe.
13310 		 */
13311 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13312 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13313 		freemsg(mp);
13314 		/*
13315 		 * If the ACK flag is not set, just use our snxt as the
13316 		 * seq number of the RST segment.
13317 		 */
13318 		if (!(flags & TH_ACK)) {
13319 			seg_ack = tcp->tcp_snxt;
13320 		}
13321 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13322 		    TH_RST|TH_ACK);
13323 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13324 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13325 		return;
13326 	}
13327 	/*
13328 	 * urp could be -1 when the urp field in the packet is 0
13329 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13330 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13331 	 */
13332 	if (flags & TH_URG && urp >= 0) {
13333 		if (!tcp->tcp_urp_last_valid ||
13334 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13335 			/*
13336 			 * If we haven't generated the signal yet for this
13337 			 * urgent pointer value, do it now.  Also, send up a
13338 			 * zero-length M_DATA indicating whether or not this is
13339 			 * the mark. The latter is not needed when a
13340 			 * T_EXDATA_IND is sent up. However, if there are
13341 			 * allocation failures this code relies on the sender
13342 			 * retransmitting and the socket code for determining
13343 			 * the mark should not block waiting for the peer to
13344 			 * transmit. Thus, for simplicity we always send up the
13345 			 * mark indication.
13346 			 */
13347 			mp1 = allocb(0, BPRI_MED);
13348 			if (mp1 == NULL) {
13349 				freemsg(mp);
13350 				return;
13351 			}
13352 			if (!TCP_IS_DETACHED(tcp) &&
13353 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13354 				/* Try again on the rexmit. */
13355 				freemsg(mp1);
13356 				freemsg(mp);
13357 				return;
13358 			}
13359 			/*
13360 			 * Mark with NOTMARKNEXT for now.
13361 			 * The code below will change this to MARKNEXT
13362 			 * if we are at the mark.
13363 			 *
13364 			 * If there are allocation failures (e.g. in dupmsg
13365 			 * below) the next time tcp_rput_data sees the urgent
13366 			 * segment it will send up the MSG*MARKNEXT message.
13367 			 */
13368 			mp1->b_flag |= MSGNOTMARKNEXT;
13369 			freemsg(tcp->tcp_urp_mark_mp);
13370 			tcp->tcp_urp_mark_mp = mp1;
13371 			flags |= TH_SEND_URP_MARK;
13372 #ifdef DEBUG
13373 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13374 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13375 			    "last %x, %s",
13376 			    seg_seq, urp, tcp->tcp_urp_last,
13377 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13378 #endif /* DEBUG */
13379 			tcp->tcp_urp_last_valid = B_TRUE;
13380 			tcp->tcp_urp_last = urp + seg_seq;
13381 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13382 			/*
13383 			 * An allocation failure prevented the previous
13384 			 * tcp_rput_data from sending up the allocated
13385 			 * MSG*MARKNEXT message - send it up this time
13386 			 * around.
13387 			 */
13388 			flags |= TH_SEND_URP_MARK;
13389 		}
13390 
13391 		/*
13392 		 * If the urgent byte is in this segment, make sure that it is
13393 		 * all by itself.  This makes it much easier to deal with the
13394 		 * possibility of an allocation failure on the T_exdata_ind.
13395 		 * Note that seg_len is the number of bytes in the segment, and
13396 		 * urp is the offset into the segment of the urgent byte.
13397 		 * urp < seg_len means that the urgent byte is in this segment.
13398 		 */
13399 		if (urp < seg_len) {
13400 			if (seg_len != 1) {
13401 				uint32_t  tmp_rnxt;
13402 				/*
13403 				 * Break it up and feed it back in.
13404 				 * Re-attach the IP header.
13405 				 */
13406 				mp->b_rptr = iphdr;
13407 				if (urp > 0) {
13408 					/*
13409 					 * There is stuff before the urgent
13410 					 * byte.
13411 					 */
13412 					mp1 = dupmsg(mp);
13413 					if (!mp1) {
13414 						/*
13415 						 * Trim from urgent byte on.
13416 						 * The rest will come back.
13417 						 */
13418 						(void) adjmsg(mp,
13419 						    urp - seg_len);
13420 						tcp_rput_data(connp,
13421 						    mp, NULL);
13422 						return;
13423 					}
13424 					(void) adjmsg(mp1, urp - seg_len);
13425 					/* Feed this piece back in. */
13426 					tmp_rnxt = tcp->tcp_rnxt;
13427 					tcp_rput_data(connp, mp1, NULL);
13428 					/*
13429 					 * If the data passed back in was not
13430 					 * processed (ie: bad ACK) sending
13431 					 * the remainder back in will cause a
13432 					 * loop. In this case, drop the
13433 					 * packet and let the sender try
13434 					 * sending a good packet.
13435 					 */
13436 					if (tmp_rnxt == tcp->tcp_rnxt) {
13437 						freemsg(mp);
13438 						return;
13439 					}
13440 				}
13441 				if (urp != seg_len - 1) {
13442 					uint32_t  tmp_rnxt;
13443 					/*
13444 					 * There is stuff after the urgent
13445 					 * byte.
13446 					 */
13447 					mp1 = dupmsg(mp);
13448 					if (!mp1) {
13449 						/*
13450 						 * Trim everything beyond the
13451 						 * urgent byte.  The rest will
13452 						 * come back.
13453 						 */
13454 						(void) adjmsg(mp,
13455 						    urp + 1 - seg_len);
13456 						tcp_rput_data(connp,
13457 						    mp, NULL);
13458 						return;
13459 					}
13460 					(void) adjmsg(mp1, urp + 1 - seg_len);
13461 					tmp_rnxt = tcp->tcp_rnxt;
13462 					tcp_rput_data(connp, mp1, NULL);
13463 					/*
13464 					 * If the data passed back in was not
13465 					 * processed (ie: bad ACK) sending
13466 					 * the remainder back in will cause a
13467 					 * loop. In this case, drop the
13468 					 * packet and let the sender try
13469 					 * sending a good packet.
13470 					 */
13471 					if (tmp_rnxt == tcp->tcp_rnxt) {
13472 						freemsg(mp);
13473 						return;
13474 					}
13475 				}
13476 				tcp_rput_data(connp, mp, NULL);
13477 				return;
13478 			}
13479 			/*
13480 			 * This segment contains only the urgent byte.  We
13481 			 * have to allocate the T_exdata_ind, if we can.
13482 			 */
13483 			if (!tcp->tcp_urp_mp) {
13484 				struct T_exdata_ind *tei;
13485 				mp1 = allocb(sizeof (struct T_exdata_ind),
13486 				    BPRI_MED);
13487 				if (!mp1) {
13488 					/*
13489 					 * Sigh... It'll be back.
13490 					 * Generate any MSG*MARK message now.
13491 					 */
13492 					freemsg(mp);
13493 					seg_len = 0;
13494 					if (flags & TH_SEND_URP_MARK) {
13495 
13496 
13497 						ASSERT(tcp->tcp_urp_mark_mp);
13498 						tcp->tcp_urp_mark_mp->b_flag &=
13499 							~MSGNOTMARKNEXT;
13500 						tcp->tcp_urp_mark_mp->b_flag |=
13501 							MSGMARKNEXT;
13502 					}
13503 					goto ack_check;
13504 				}
13505 				mp1->b_datap->db_type = M_PROTO;
13506 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13507 				tei->PRIM_type = T_EXDATA_IND;
13508 				tei->MORE_flag = 0;
13509 				mp1->b_wptr = (uchar_t *)&tei[1];
13510 				tcp->tcp_urp_mp = mp1;
13511 #ifdef DEBUG
13512 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13513 				    "tcp_rput: allocated exdata_ind %s",
13514 				    tcp_display(tcp, NULL,
13515 				    DISP_PORT_ONLY));
13516 #endif /* DEBUG */
13517 				/*
13518 				 * There is no need to send a separate MSG*MARK
13519 				 * message since the T_EXDATA_IND will be sent
13520 				 * now.
13521 				 */
13522 				flags &= ~TH_SEND_URP_MARK;
13523 				freemsg(tcp->tcp_urp_mark_mp);
13524 				tcp->tcp_urp_mark_mp = NULL;
13525 			}
13526 			/*
13527 			 * Now we are all set.  On the next putnext upstream,
13528 			 * tcp_urp_mp will be non-NULL and will get prepended
13529 			 * to what has to be this piece containing the urgent
13530 			 * byte.  If for any reason we abort this segment below,
13531 			 * if it comes back, we will have this ready, or it
13532 			 * will get blown off in close.
13533 			 */
13534 		} else if (urp == seg_len) {
13535 			/*
13536 			 * The urgent byte is the next byte after this sequence
13537 			 * number. If there is data it is marked with
13538 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13539 			 * since it is not needed. Otherwise, if the code
13540 			 * above just allocated a zero-length tcp_urp_mark_mp
13541 			 * message, that message is tagged with MSGMARKNEXT.
13542 			 * Sending up these MSGMARKNEXT messages makes
13543 			 * SIOCATMARK work correctly even though
13544 			 * the T_EXDATA_IND will not be sent up until the
13545 			 * urgent byte arrives.
13546 			 */
13547 			if (seg_len != 0) {
13548 				flags |= TH_MARKNEXT_NEEDED;
13549 				freemsg(tcp->tcp_urp_mark_mp);
13550 				tcp->tcp_urp_mark_mp = NULL;
13551 				flags &= ~TH_SEND_URP_MARK;
13552 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13553 				flags |= TH_SEND_URP_MARK;
13554 				tcp->tcp_urp_mark_mp->b_flag &=
13555 					~MSGNOTMARKNEXT;
13556 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13557 			}
13558 #ifdef DEBUG
13559 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13560 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13561 			    seg_len, flags,
13562 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13563 #endif /* DEBUG */
13564 		} else {
13565 			/* Data left until we hit mark */
13566 #ifdef DEBUG
13567 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13568 			    "tcp_rput: URP %d bytes left, %s",
13569 			    urp - seg_len, tcp_display(tcp, NULL,
13570 			    DISP_PORT_ONLY));
13571 #endif /* DEBUG */
13572 		}
13573 	}
13574 
13575 process_ack:
13576 	if (!(flags & TH_ACK)) {
13577 		freemsg(mp);
13578 		goto xmit_check;
13579 	}
13580 	}
13581 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13582 
13583 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13584 		tcp->tcp_ip_forward_progress = B_TRUE;
13585 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13586 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13587 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13588 			/* 3-way handshake complete - pass up the T_CONN_IND */
13589 			tcp_t	*listener = tcp->tcp_listener;
13590 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13591 
13592 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13593 			/*
13594 			 * We are here means eager is fine but it can
13595 			 * get a TH_RST at any point between now and till
13596 			 * accept completes and disappear. We need to
13597 			 * ensure that reference to eager is valid after
13598 			 * we get out of eager's perimeter. So we do
13599 			 * an extra refhold.
13600 			 */
13601 			CONN_INC_REF(connp);
13602 
13603 			/*
13604 			 * The listener also exists because of the refhold
13605 			 * done in tcp_conn_request. Its possible that it
13606 			 * might have closed. We will check that once we
13607 			 * get inside listeners context.
13608 			 */
13609 			CONN_INC_REF(listener->tcp_connp);
13610 			if (listener->tcp_connp->conn_sqp ==
13611 			    connp->conn_sqp) {
13612 				tcp_send_conn_ind(listener->tcp_connp, mp,
13613 				    listener->tcp_connp->conn_sqp);
13614 				CONN_DEC_REF(listener->tcp_connp);
13615 			} else if (!tcp->tcp_loopback) {
13616 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
13617 				    tcp_send_conn_ind,
13618 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
13619 			} else {
13620 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
13621 				    tcp_send_conn_ind, listener->tcp_connp,
13622 				    SQTAG_TCP_CONN_IND);
13623 			}
13624 		}
13625 
13626 		if (tcp->tcp_active_open) {
13627 			/*
13628 			 * We are seeing the final ack in the three way
13629 			 * hand shake of a active open'ed connection
13630 			 * so we must send up a T_CONN_CON
13631 			 */
13632 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13633 				freemsg(mp);
13634 				return;
13635 			}
13636 			/*
13637 			 * Don't fuse the loopback endpoints for
13638 			 * simultaneous active opens.
13639 			 */
13640 			if (tcp->tcp_loopback) {
13641 				TCP_STAT(tcp_fusion_unfusable);
13642 				tcp->tcp_unfusable = B_TRUE;
13643 			}
13644 		}
13645 
13646 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
13647 		bytes_acked--;
13648 		/* SYN was acked - making progress */
13649 		if (tcp->tcp_ipversion == IPV6_VERSION)
13650 			tcp->tcp_ip_forward_progress = B_TRUE;
13651 
13652 		/*
13653 		 * If SYN was retransmitted, need to reset all
13654 		 * retransmission info as this segment will be
13655 		 * treated as a dup ACK.
13656 		 */
13657 		if (tcp->tcp_rexmit) {
13658 			tcp->tcp_rexmit = B_FALSE;
13659 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13660 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
13661 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13662 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13663 			tcp->tcp_ms_we_have_waited = 0;
13664 			tcp->tcp_cwnd = mss;
13665 		}
13666 
13667 		/*
13668 		 * We set the send window to zero here.
13669 		 * This is needed if there is data to be
13670 		 * processed already on the queue.
13671 		 * Later (at swnd_update label), the
13672 		 * "new_swnd > tcp_swnd" condition is satisfied
13673 		 * the XMIT_NEEDED flag is set in the current
13674 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
13675 		 * called if there is already data on queue in
13676 		 * this state.
13677 		 */
13678 		tcp->tcp_swnd = 0;
13679 
13680 		if (new_swnd > tcp->tcp_max_swnd)
13681 			tcp->tcp_max_swnd = new_swnd;
13682 		tcp->tcp_swl1 = seg_seq;
13683 		tcp->tcp_swl2 = seg_ack;
13684 		tcp->tcp_state = TCPS_ESTABLISHED;
13685 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13686 
13687 		/* Fuse when both sides are in ESTABLISHED state */
13688 		if (tcp->tcp_loopback && do_tcp_fusion)
13689 			tcp_fuse(tcp, iphdr, tcph);
13690 
13691 	}
13692 	/* This code follows 4.4BSD-Lite2 mostly. */
13693 	if (bytes_acked < 0)
13694 		goto est;
13695 
13696 	/*
13697 	 * If TCP is ECN capable and the congestion experience bit is
13698 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
13699 	 * done once per window (or more loosely, per RTT).
13700 	 */
13701 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
13702 		tcp->tcp_cwr = B_FALSE;
13703 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
13704 		if (!tcp->tcp_cwr) {
13705 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
13706 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
13707 			tcp->tcp_cwnd = npkt * mss;
13708 			/*
13709 			 * If the cwnd is 0, use the timer to clock out
13710 			 * new segments.  This is required by the ECN spec.
13711 			 */
13712 			if (npkt == 0) {
13713 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13714 				/*
13715 				 * This makes sure that when the ACK comes
13716 				 * back, we will increase tcp_cwnd by 1 MSS.
13717 				 */
13718 				tcp->tcp_cwnd_cnt = 0;
13719 			}
13720 			tcp->tcp_cwr = B_TRUE;
13721 			/*
13722 			 * This marks the end of the current window of in
13723 			 * flight data.  That is why we don't use
13724 			 * tcp_suna + tcp_swnd.  Only data in flight can
13725 			 * provide ECN info.
13726 			 */
13727 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13728 			tcp->tcp_ecn_cwr_sent = B_FALSE;
13729 		}
13730 	}
13731 
13732 	mp1 = tcp->tcp_xmit_head;
13733 	if (bytes_acked == 0) {
13734 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
13735 			int dupack_cnt;
13736 
13737 			BUMP_MIB(&tcp_mib, tcpInDupAck);
13738 			/*
13739 			 * Fast retransmit.  When we have seen exactly three
13740 			 * identical ACKs while we have unacked data
13741 			 * outstanding we take it as a hint that our peer
13742 			 * dropped something.
13743 			 *
13744 			 * If TCP is retransmitting, don't do fast retransmit.
13745 			 */
13746 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
13747 			    ! tcp->tcp_rexmit) {
13748 				/* Do Limited Transmit */
13749 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
13750 				    tcp_dupack_fast_retransmit) {
13751 					/*
13752 					 * RFC 3042
13753 					 *
13754 					 * What we need to do is temporarily
13755 					 * increase tcp_cwnd so that new
13756 					 * data can be sent if it is allowed
13757 					 * by the receive window (tcp_rwnd).
13758 					 * tcp_wput_data() will take care of
13759 					 * the rest.
13760 					 *
13761 					 * If the connection is SACK capable,
13762 					 * only do limited xmit when there
13763 					 * is SACK info.
13764 					 *
13765 					 * Note how tcp_cwnd is incremented.
13766 					 * The first dup ACK will increase
13767 					 * it by 1 MSS.  The second dup ACK
13768 					 * will increase it by 2 MSS.  This
13769 					 * means that only 1 new segment will
13770 					 * be sent for each dup ACK.
13771 					 */
13772 					if (tcp->tcp_unsent > 0 &&
13773 					    (!tcp->tcp_snd_sack_ok ||
13774 					    (tcp->tcp_snd_sack_ok &&
13775 					    tcp->tcp_notsack_list != NULL))) {
13776 						tcp->tcp_cwnd += mss <<
13777 						    (tcp->tcp_dupack_cnt - 1);
13778 						flags |= TH_LIMIT_XMIT;
13779 					}
13780 				} else if (dupack_cnt ==
13781 				    tcp_dupack_fast_retransmit) {
13782 
13783 				/*
13784 				 * If we have reduced tcp_ssthresh
13785 				 * because of ECN, do not reduce it again
13786 				 * unless it is already one window of data
13787 				 * away.  After one window of data, tcp_cwr
13788 				 * should then be cleared.  Note that
13789 				 * for non ECN capable connection, tcp_cwr
13790 				 * should always be false.
13791 				 *
13792 				 * Adjust cwnd since the duplicate
13793 				 * ack indicates that a packet was
13794 				 * dropped (due to congestion.)
13795 				 */
13796 				if (!tcp->tcp_cwr) {
13797 					npkt = ((tcp->tcp_snxt -
13798 					    tcp->tcp_suna) >> 1) / mss;
13799 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13800 					    mss;
13801 					tcp->tcp_cwnd = (npkt +
13802 					    tcp->tcp_dupack_cnt) * mss;
13803 				}
13804 				if (tcp->tcp_ecn_ok) {
13805 					tcp->tcp_cwr = B_TRUE;
13806 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13807 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13808 				}
13809 
13810 				/*
13811 				 * We do Hoe's algorithm.  Refer to her
13812 				 * paper "Improving the Start-up Behavior
13813 				 * of a Congestion Control Scheme for TCP,"
13814 				 * appeared in SIGCOMM'96.
13815 				 *
13816 				 * Save highest seq no we have sent so far.
13817 				 * Be careful about the invisible FIN byte.
13818 				 */
13819 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13820 				    (tcp->tcp_unsent == 0)) {
13821 					tcp->tcp_rexmit_max = tcp->tcp_fss;
13822 				} else {
13823 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
13824 				}
13825 
13826 				/*
13827 				 * Do not allow bursty traffic during.
13828 				 * fast recovery.  Refer to Fall and Floyd's
13829 				 * paper "Simulation-based Comparisons of
13830 				 * Tahoe, Reno and SACK TCP" (in CCR?)
13831 				 * This is a best current practise.
13832 				 */
13833 				tcp->tcp_snd_burst = TCP_CWND_SS;
13834 
13835 				/*
13836 				 * For SACK:
13837 				 * Calculate tcp_pipe, which is the
13838 				 * estimated number of bytes in
13839 				 * network.
13840 				 *
13841 				 * tcp_fack is the highest sack'ed seq num
13842 				 * TCP has received.
13843 				 *
13844 				 * tcp_pipe is explained in the above quoted
13845 				 * Fall and Floyd's paper.  tcp_fack is
13846 				 * explained in Mathis and Mahdavi's
13847 				 * "Forward Acknowledgment: Refining TCP
13848 				 * Congestion Control" in SIGCOMM '96.
13849 				 */
13850 				if (tcp->tcp_snd_sack_ok) {
13851 					ASSERT(tcp->tcp_sack_info != NULL);
13852 					if (tcp->tcp_notsack_list != NULL) {
13853 						tcp->tcp_pipe = tcp->tcp_snxt -
13854 						    tcp->tcp_fack;
13855 						tcp->tcp_sack_snxt = seg_ack;
13856 						flags |= TH_NEED_SACK_REXMIT;
13857 					} else {
13858 						/*
13859 						 * Always initialize tcp_pipe
13860 						 * even though we don't have
13861 						 * any SACK info.  If later
13862 						 * we get SACK info and
13863 						 * tcp_pipe is not initialized,
13864 						 * funny things will happen.
13865 						 */
13866 						tcp->tcp_pipe =
13867 						    tcp->tcp_cwnd_ssthresh;
13868 					}
13869 				} else {
13870 					flags |= TH_REXMIT_NEEDED;
13871 				} /* tcp_snd_sack_ok */
13872 
13873 				} else {
13874 					/*
13875 					 * Here we perform congestion
13876 					 * avoidance, but NOT slow start.
13877 					 * This is known as the Fast
13878 					 * Recovery Algorithm.
13879 					 */
13880 					if (tcp->tcp_snd_sack_ok &&
13881 					    tcp->tcp_notsack_list != NULL) {
13882 						flags |= TH_NEED_SACK_REXMIT;
13883 						tcp->tcp_pipe -= mss;
13884 						if (tcp->tcp_pipe < 0)
13885 							tcp->tcp_pipe = 0;
13886 					} else {
13887 					/*
13888 					 * We know that one more packet has
13889 					 * left the pipe thus we can update
13890 					 * cwnd.
13891 					 */
13892 					cwnd = tcp->tcp_cwnd + mss;
13893 					if (cwnd > tcp->tcp_cwnd_max)
13894 						cwnd = tcp->tcp_cwnd_max;
13895 					tcp->tcp_cwnd = cwnd;
13896 					if (tcp->tcp_unsent > 0)
13897 						flags |= TH_XMIT_NEEDED;
13898 					}
13899 				}
13900 			}
13901 		} else if (tcp->tcp_zero_win_probe) {
13902 			/*
13903 			 * If the window has opened, need to arrange
13904 			 * to send additional data.
13905 			 */
13906 			if (new_swnd != 0) {
13907 				/* tcp_suna != tcp_snxt */
13908 				/* Packet contains a window update */
13909 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
13910 				tcp->tcp_zero_win_probe = 0;
13911 				tcp->tcp_timer_backoff = 0;
13912 				tcp->tcp_ms_we_have_waited = 0;
13913 
13914 				/*
13915 				 * Transmit starting with tcp_suna since
13916 				 * the one byte probe is not ack'ed.
13917 				 * If TCP has sent more than one identical
13918 				 * probe, tcp_rexmit will be set.  That means
13919 				 * tcp_ss_rexmit() will send out the one
13920 				 * byte along with new data.  Otherwise,
13921 				 * fake the retransmission.
13922 				 */
13923 				flags |= TH_XMIT_NEEDED;
13924 				if (!tcp->tcp_rexmit) {
13925 					tcp->tcp_rexmit = B_TRUE;
13926 					tcp->tcp_dupack_cnt = 0;
13927 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13928 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
13929 				}
13930 			}
13931 		}
13932 		goto swnd_update;
13933 	}
13934 
13935 	/*
13936 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
13937 	 * If the ACK value acks something that we have not yet sent, it might
13938 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
13939 	 * other side.
13940 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
13941 	 * state is handled above, so we can always just drop the segment and
13942 	 * send an ACK here.
13943 	 *
13944 	 * Should we send ACKs in response to ACK only segments?
13945 	 */
13946 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13947 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
13948 		/* drop the received segment */
13949 		freemsg(mp);
13950 
13951 		/*
13952 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
13953 		 * greater than 0, check if the number of such
13954 		 * bogus ACks is greater than that count.  If yes,
13955 		 * don't send back any ACK.  This prevents TCP from
13956 		 * getting into an ACK storm if somehow an attacker
13957 		 * successfully spoofs an acceptable segment to our
13958 		 * peer.
13959 		 */
13960 		if (tcp_drop_ack_unsent_cnt > 0 &&
13961 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
13962 			TCP_STAT(tcp_in_ack_unsent_drop);
13963 			return;
13964 		}
13965 		mp = tcp_ack_mp(tcp);
13966 		if (mp != NULL) {
13967 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
13968 			BUMP_LOCAL(tcp->tcp_obsegs);
13969 			BUMP_MIB(&tcp_mib, tcpOutAck);
13970 			tcp_send_data(tcp, tcp->tcp_wq, mp);
13971 		}
13972 		return;
13973 	}
13974 
13975 	/*
13976 	 * TCP gets a new ACK, update the notsack'ed list to delete those
13977 	 * blocks that are covered by this ACK.
13978 	 */
13979 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
13980 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
13981 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
13982 	}
13983 
13984 	/*
13985 	 * If we got an ACK after fast retransmit, check to see
13986 	 * if it is a partial ACK.  If it is not and the congestion
13987 	 * window was inflated to account for the other side's
13988 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
13989 	 */
13990 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
13991 		ASSERT(tcp->tcp_rexmit == B_FALSE);
13992 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
13993 			tcp->tcp_dupack_cnt = 0;
13994 			/*
13995 			 * Restore the orig tcp_cwnd_ssthresh after
13996 			 * fast retransmit phase.
13997 			 */
13998 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
13999 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14000 			}
14001 			tcp->tcp_rexmit_max = seg_ack;
14002 			tcp->tcp_cwnd_cnt = 0;
14003 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14004 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14005 
14006 			/*
14007 			 * Remove all notsack info to avoid confusion with
14008 			 * the next fast retrasnmit/recovery phase.
14009 			 */
14010 			if (tcp->tcp_snd_sack_ok &&
14011 			    tcp->tcp_notsack_list != NULL) {
14012 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14013 			}
14014 		} else {
14015 			if (tcp->tcp_snd_sack_ok &&
14016 			    tcp->tcp_notsack_list != NULL) {
14017 				flags |= TH_NEED_SACK_REXMIT;
14018 				tcp->tcp_pipe -= mss;
14019 				if (tcp->tcp_pipe < 0)
14020 					tcp->tcp_pipe = 0;
14021 			} else {
14022 				/*
14023 				 * Hoe's algorithm:
14024 				 *
14025 				 * Retransmit the unack'ed segment and
14026 				 * restart fast recovery.  Note that we
14027 				 * need to scale back tcp_cwnd to the
14028 				 * original value when we started fast
14029 				 * recovery.  This is to prevent overly
14030 				 * aggressive behaviour in sending new
14031 				 * segments.
14032 				 */
14033 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14034 					tcp_dupack_fast_retransmit * mss;
14035 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14036 				flags |= TH_REXMIT_NEEDED;
14037 			}
14038 		}
14039 	} else {
14040 		tcp->tcp_dupack_cnt = 0;
14041 		if (tcp->tcp_rexmit) {
14042 			/*
14043 			 * TCP is retranmitting.  If the ACK ack's all
14044 			 * outstanding data, update tcp_rexmit_max and
14045 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14046 			 * to the correct value.
14047 			 *
14048 			 * Note that SEQ_LEQ() is used.  This is to avoid
14049 			 * unnecessary fast retransmit caused by dup ACKs
14050 			 * received when TCP does slow start retransmission
14051 			 * after a time out.  During this phase, TCP may
14052 			 * send out segments which are already received.
14053 			 * This causes dup ACKs to be sent back.
14054 			 */
14055 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14056 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14057 					tcp->tcp_rexmit_nxt = seg_ack;
14058 				}
14059 				if (seg_ack != tcp->tcp_rexmit_max) {
14060 					flags |= TH_XMIT_NEEDED;
14061 				}
14062 			} else {
14063 				tcp->tcp_rexmit = B_FALSE;
14064 				tcp->tcp_xmit_zc_clean = B_FALSE;
14065 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14066 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14067 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14068 			}
14069 			tcp->tcp_ms_we_have_waited = 0;
14070 		}
14071 	}
14072 
14073 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
14074 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
14075 	tcp->tcp_suna = seg_ack;
14076 	if (tcp->tcp_zero_win_probe != 0) {
14077 		tcp->tcp_zero_win_probe = 0;
14078 		tcp->tcp_timer_backoff = 0;
14079 	}
14080 
14081 	/*
14082 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14083 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14084 	 * will not reach here.
14085 	 */
14086 	if (mp1 == NULL) {
14087 		goto fin_acked;
14088 	}
14089 
14090 	/*
14091 	 * Update the congestion window.
14092 	 *
14093 	 * If TCP is not ECN capable or TCP is ECN capable but the
14094 	 * congestion experience bit is not set, increase the tcp_cwnd as
14095 	 * usual.
14096 	 */
14097 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14098 		cwnd = tcp->tcp_cwnd;
14099 		add = mss;
14100 
14101 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14102 			/*
14103 			 * This is to prevent an increase of less than 1 MSS of
14104 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14105 			 * may send out tinygrams in order to preserve mblk
14106 			 * boundaries.
14107 			 *
14108 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14109 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14110 			 * increased by 1 MSS for every RTTs.
14111 			 */
14112 			if (tcp->tcp_cwnd_cnt <= 0) {
14113 				tcp->tcp_cwnd_cnt = cwnd + add;
14114 			} else {
14115 				tcp->tcp_cwnd_cnt -= add;
14116 				add = 0;
14117 			}
14118 		}
14119 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14120 	}
14121 
14122 	/* See if the latest urgent data has been acknowledged */
14123 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14124 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14125 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14126 
14127 	/* Can we update the RTT estimates? */
14128 	if (tcp->tcp_snd_ts_ok) {
14129 		/* Ignore zero timestamp echo-reply. */
14130 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14131 			tcp_set_rto(tcp, (int32_t)lbolt -
14132 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14133 		}
14134 
14135 		/* If needed, restart the timer. */
14136 		if (tcp->tcp_set_timer == 1) {
14137 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14138 			tcp->tcp_set_timer = 0;
14139 		}
14140 		/*
14141 		 * Update tcp_csuna in case the other side stops sending
14142 		 * us timestamps.
14143 		 */
14144 		tcp->tcp_csuna = tcp->tcp_snxt;
14145 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14146 		/*
14147 		 * An ACK sequence we haven't seen before, so get the RTT
14148 		 * and update the RTO. But first check if the timestamp is
14149 		 * valid to use.
14150 		 */
14151 		if ((mp1->b_next != NULL) &&
14152 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14153 			tcp_set_rto(tcp, (int32_t)lbolt -
14154 			    (int32_t)(intptr_t)mp1->b_prev);
14155 		else
14156 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14157 
14158 		/* Remeber the last sequence to be ACKed */
14159 		tcp->tcp_csuna = seg_ack;
14160 		if (tcp->tcp_set_timer == 1) {
14161 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14162 			tcp->tcp_set_timer = 0;
14163 		}
14164 	} else {
14165 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14166 	}
14167 
14168 	/* Eat acknowledged bytes off the xmit queue. */
14169 	for (;;) {
14170 		mblk_t	*mp2;
14171 		uchar_t	*wptr;
14172 
14173 		wptr = mp1->b_wptr;
14174 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14175 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14176 		if (bytes_acked < 0) {
14177 			mp1->b_rptr = wptr + bytes_acked;
14178 			/*
14179 			 * Set a new timestamp if all the bytes timed by the
14180 			 * old timestamp have been ack'ed.
14181 			 */
14182 			if (SEQ_GT(seg_ack,
14183 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14184 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14185 				mp1->b_next = NULL;
14186 			}
14187 			break;
14188 		}
14189 		mp1->b_next = NULL;
14190 		mp1->b_prev = NULL;
14191 		mp2 = mp1;
14192 		mp1 = mp1->b_cont;
14193 
14194 		/*
14195 		 * This notification is required for some zero-copy
14196 		 * clients to maintain a copy semantic. After the data
14197 		 * is ack'ed, client is safe to modify or reuse the buffer.
14198 		 */
14199 		if (tcp->tcp_snd_zcopy_aware &&
14200 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14201 			tcp_zcopy_notify(tcp);
14202 		freeb(mp2);
14203 		if (bytes_acked == 0) {
14204 			if (mp1 == NULL) {
14205 				/* Everything is ack'ed, clear the tail. */
14206 				tcp->tcp_xmit_tail = NULL;
14207 				/*
14208 				 * Cancel the timer unless we are still
14209 				 * waiting for an ACK for the FIN packet.
14210 				 */
14211 				if (tcp->tcp_timer_tid != 0 &&
14212 				    tcp->tcp_snxt == tcp->tcp_suna) {
14213 					(void) TCP_TIMER_CANCEL(tcp,
14214 					    tcp->tcp_timer_tid);
14215 					tcp->tcp_timer_tid = 0;
14216 				}
14217 				goto pre_swnd_update;
14218 			}
14219 			if (mp2 != tcp->tcp_xmit_tail)
14220 				break;
14221 			tcp->tcp_xmit_tail = mp1;
14222 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14223 			    (uintptr_t)INT_MAX);
14224 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14225 			    mp1->b_rptr);
14226 			break;
14227 		}
14228 		if (mp1 == NULL) {
14229 			/*
14230 			 * More was acked but there is nothing more
14231 			 * outstanding.  This means that the FIN was
14232 			 * just acked or that we're talking to a clown.
14233 			 */
14234 fin_acked:
14235 			ASSERT(tcp->tcp_fin_sent);
14236 			tcp->tcp_xmit_tail = NULL;
14237 			if (tcp->tcp_fin_sent) {
14238 				/* FIN was acked - making progress */
14239 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14240 				    !tcp->tcp_fin_acked)
14241 					tcp->tcp_ip_forward_progress = B_TRUE;
14242 				tcp->tcp_fin_acked = B_TRUE;
14243 				if (tcp->tcp_linger_tid != 0 &&
14244 				    TCP_TIMER_CANCEL(tcp,
14245 					tcp->tcp_linger_tid) >= 0) {
14246 					tcp_stop_lingering(tcp);
14247 				}
14248 			} else {
14249 				/*
14250 				 * We should never get here because
14251 				 * we have already checked that the
14252 				 * number of bytes ack'ed should be
14253 				 * smaller than or equal to what we
14254 				 * have sent so far (it is the
14255 				 * acceptability check of the ACK).
14256 				 * We can only get here if the send
14257 				 * queue is corrupted.
14258 				 *
14259 				 * Terminate the connection and
14260 				 * panic the system.  It is better
14261 				 * for us to panic instead of
14262 				 * continuing to avoid other disaster.
14263 				 */
14264 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14265 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14266 				panic("Memory corruption "
14267 				    "detected for connection %s.",
14268 				    tcp_display(tcp, NULL,
14269 					DISP_ADDR_AND_PORT));
14270 				/*NOTREACHED*/
14271 			}
14272 			goto pre_swnd_update;
14273 		}
14274 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14275 	}
14276 	if (tcp->tcp_unsent) {
14277 		flags |= TH_XMIT_NEEDED;
14278 	}
14279 pre_swnd_update:
14280 	tcp->tcp_xmit_head = mp1;
14281 swnd_update:
14282 	/*
14283 	 * The following check is different from most other implementations.
14284 	 * For bi-directional transfer, when segments are dropped, the
14285 	 * "normal" check will not accept a window update in those
14286 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14287 	 * segments which are outside receiver's window.  As TCP accepts
14288 	 * the ack in those retransmitted segments, if the window update in
14289 	 * the same segment is not accepted, TCP will incorrectly calculates
14290 	 * that it can send more segments.  This can create a deadlock
14291 	 * with the receiver if its window becomes zero.
14292 	 */
14293 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14294 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14295 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14296 		/*
14297 		 * The criteria for update is:
14298 		 *
14299 		 * 1. the segment acknowledges some data.  Or
14300 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14301 		 * 3. the segment is not old and the advertised window is
14302 		 * larger than the previous advertised window.
14303 		 */
14304 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14305 			flags |= TH_XMIT_NEEDED;
14306 		tcp->tcp_swnd = new_swnd;
14307 		if (new_swnd > tcp->tcp_max_swnd)
14308 			tcp->tcp_max_swnd = new_swnd;
14309 		tcp->tcp_swl1 = seg_seq;
14310 		tcp->tcp_swl2 = seg_ack;
14311 	}
14312 est:
14313 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14314 
14315 		switch (tcp->tcp_state) {
14316 		case TCPS_FIN_WAIT_1:
14317 			if (tcp->tcp_fin_acked) {
14318 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14319 				/*
14320 				 * We implement the non-standard BSD/SunOS
14321 				 * FIN_WAIT_2 flushing algorithm.
14322 				 * If there is no user attached to this
14323 				 * TCP endpoint, then this TCP struct
14324 				 * could hang around forever in FIN_WAIT_2
14325 				 * state if the peer forgets to send us
14326 				 * a FIN.  To prevent this, we wait only
14327 				 * 2*MSL (a convenient time value) for
14328 				 * the FIN to arrive.  If it doesn't show up,
14329 				 * we flush the TCP endpoint.  This algorithm,
14330 				 * though a violation of RFC-793, has worked
14331 				 * for over 10 years in BSD systems.
14332 				 * Note: SunOS 4.x waits 675 seconds before
14333 				 * flushing the FIN_WAIT_2 connection.
14334 				 */
14335 				TCP_TIMER_RESTART(tcp,
14336 				    tcp_fin_wait_2_flush_interval);
14337 			}
14338 			break;
14339 		case TCPS_FIN_WAIT_2:
14340 			break;	/* Shutdown hook? */
14341 		case TCPS_LAST_ACK:
14342 			freemsg(mp);
14343 			if (tcp->tcp_fin_acked) {
14344 				(void) tcp_clean_death(tcp, 0, 19);
14345 				return;
14346 			}
14347 			goto xmit_check;
14348 		case TCPS_CLOSING:
14349 			if (tcp->tcp_fin_acked) {
14350 				tcp->tcp_state = TCPS_TIME_WAIT;
14351 				/*
14352 				 * Unconditionally clear the exclusive binding
14353 				 * bit so this TIME-WAIT connection won't
14354 				 * interfere with new ones.
14355 				 */
14356 				tcp->tcp_exclbind = 0;
14357 				if (!TCP_IS_DETACHED(tcp)) {
14358 					TCP_TIMER_RESTART(tcp,
14359 					    tcp_time_wait_interval);
14360 				} else {
14361 					tcp_time_wait_append(tcp);
14362 					TCP_DBGSTAT(tcp_rput_time_wait);
14363 				}
14364 			}
14365 			/*FALLTHRU*/
14366 		case TCPS_CLOSE_WAIT:
14367 			freemsg(mp);
14368 			goto xmit_check;
14369 		default:
14370 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14371 			break;
14372 		}
14373 	}
14374 	if (flags & TH_FIN) {
14375 		/* Make sure we ack the fin */
14376 		flags |= TH_ACK_NEEDED;
14377 		if (!tcp->tcp_fin_rcvd) {
14378 			tcp->tcp_fin_rcvd = B_TRUE;
14379 			tcp->tcp_rnxt++;
14380 			tcph = tcp->tcp_tcph;
14381 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14382 
14383 			/*
14384 			 * Generate the ordrel_ind at the end unless we
14385 			 * are an eager guy.
14386 			 * In the eager case tcp_rsrv will do this when run
14387 			 * after tcp_accept is done.
14388 			 */
14389 			if (tcp->tcp_listener == NULL &&
14390 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14391 				flags |= TH_ORDREL_NEEDED;
14392 			switch (tcp->tcp_state) {
14393 			case TCPS_SYN_RCVD:
14394 			case TCPS_ESTABLISHED:
14395 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14396 				/* Keepalive? */
14397 				break;
14398 			case TCPS_FIN_WAIT_1:
14399 				if (!tcp->tcp_fin_acked) {
14400 					tcp->tcp_state = TCPS_CLOSING;
14401 					break;
14402 				}
14403 				/* FALLTHRU */
14404 			case TCPS_FIN_WAIT_2:
14405 				tcp->tcp_state = TCPS_TIME_WAIT;
14406 				/*
14407 				 * Unconditionally clear the exclusive binding
14408 				 * bit so this TIME-WAIT connection won't
14409 				 * interfere with new ones.
14410 				 */
14411 				tcp->tcp_exclbind = 0;
14412 				if (!TCP_IS_DETACHED(tcp)) {
14413 					TCP_TIMER_RESTART(tcp,
14414 					    tcp_time_wait_interval);
14415 				} else {
14416 					tcp_time_wait_append(tcp);
14417 					TCP_DBGSTAT(tcp_rput_time_wait);
14418 				}
14419 				if (seg_len) {
14420 					/*
14421 					 * implies data piggybacked on FIN.
14422 					 * break to handle data.
14423 					 */
14424 					break;
14425 				}
14426 				freemsg(mp);
14427 				goto ack_check;
14428 			}
14429 		}
14430 	}
14431 	if (mp == NULL)
14432 		goto xmit_check;
14433 	if (seg_len == 0) {
14434 		freemsg(mp);
14435 		goto xmit_check;
14436 	}
14437 	if (mp->b_rptr == mp->b_wptr) {
14438 		/*
14439 		 * The header has been consumed, so we remove the
14440 		 * zero-length mblk here.
14441 		 */
14442 		mp1 = mp;
14443 		mp = mp->b_cont;
14444 		freeb(mp1);
14445 	}
14446 	tcph = tcp->tcp_tcph;
14447 	tcp->tcp_rack_cnt++;
14448 	{
14449 		uint32_t cur_max;
14450 
14451 		cur_max = tcp->tcp_rack_cur_max;
14452 		if (tcp->tcp_rack_cnt >= cur_max) {
14453 			/*
14454 			 * We have more unacked data than we should - send
14455 			 * an ACK now.
14456 			 */
14457 			flags |= TH_ACK_NEEDED;
14458 			cur_max++;
14459 			if (cur_max > tcp->tcp_rack_abs_max)
14460 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14461 			else
14462 				tcp->tcp_rack_cur_max = cur_max;
14463 		} else if (TCP_IS_DETACHED(tcp)) {
14464 			/* We don't have an ACK timer for detached TCP. */
14465 			flags |= TH_ACK_NEEDED;
14466 		} else if (seg_len < mss) {
14467 			/*
14468 			 * If we get a segment that is less than an mss, and we
14469 			 * already have unacknowledged data, and the amount
14470 			 * unacknowledged is not a multiple of mss, then we
14471 			 * better generate an ACK now.  Otherwise, this may be
14472 			 * the tail piece of a transaction, and we would rather
14473 			 * wait for the response.
14474 			 */
14475 			uint32_t udif;
14476 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14477 			    (uintptr_t)INT_MAX);
14478 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14479 			if (udif && (udif % mss))
14480 				flags |= TH_ACK_NEEDED;
14481 			else
14482 				flags |= TH_ACK_TIMER_NEEDED;
14483 		} else {
14484 			/* Start delayed ack timer */
14485 			flags |= TH_ACK_TIMER_NEEDED;
14486 		}
14487 	}
14488 	tcp->tcp_rnxt += seg_len;
14489 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14490 
14491 	/* Update SACK list */
14492 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14493 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14494 		    &(tcp->tcp_num_sack_blk));
14495 	}
14496 
14497 	if (tcp->tcp_urp_mp) {
14498 		tcp->tcp_urp_mp->b_cont = mp;
14499 		mp = tcp->tcp_urp_mp;
14500 		tcp->tcp_urp_mp = NULL;
14501 		/* Ready for a new signal. */
14502 		tcp->tcp_urp_last_valid = B_FALSE;
14503 #ifdef DEBUG
14504 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14505 		    "tcp_rput: sending exdata_ind %s",
14506 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14507 #endif /* DEBUG */
14508 	}
14509 
14510 	/*
14511 	 * Check for ancillary data changes compared to last segment.
14512 	 */
14513 	if (tcp->tcp_ipv6_recvancillary != 0) {
14514 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14515 		if (mp == NULL)
14516 			return;
14517 	}
14518 
14519 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14520 		/*
14521 		 * Side queue inbound data until the accept happens.
14522 		 * tcp_accept/tcp_rput drains this when the accept happens.
14523 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14524 		 * T_EXDATA_IND) it is queued on b_next.
14525 		 * XXX Make urgent data use this. Requires:
14526 		 *	Removing tcp_listener check for TH_URG
14527 		 *	Making M_PCPROTO and MARK messages skip the eager case
14528 		 */
14529 
14530 		if (tcp->tcp_kssl_pending) {
14531 			tcp_kssl_input(tcp, mp);
14532 		} else {
14533 			tcp_rcv_enqueue(tcp, mp, seg_len);
14534 		}
14535 	} else {
14536 		if (mp->b_datap->db_type != M_DATA ||
14537 		    (flags & TH_MARKNEXT_NEEDED)) {
14538 			if (tcp->tcp_rcv_list != NULL) {
14539 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14540 			}
14541 			ASSERT(tcp->tcp_rcv_list == NULL ||
14542 			    tcp->tcp_fused_sigurg);
14543 			if (flags & TH_MARKNEXT_NEEDED) {
14544 #ifdef DEBUG
14545 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14546 				    "tcp_rput: sending MSGMARKNEXT %s",
14547 				    tcp_display(tcp, NULL,
14548 				    DISP_PORT_ONLY));
14549 #endif /* DEBUG */
14550 				mp->b_flag |= MSGMARKNEXT;
14551 				flags &= ~TH_MARKNEXT_NEEDED;
14552 			}
14553 
14554 			/* Does this need SSL processing first? */
14555 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14556 			    (DB_TYPE(mp) == M_DATA)) {
14557 				tcp_kssl_input(tcp, mp);
14558 			} else {
14559 				putnext(tcp->tcp_rq, mp);
14560 				if (!canputnext(tcp->tcp_rq))
14561 					tcp->tcp_rwnd -= seg_len;
14562 			}
14563 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14564 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
14565 			if (tcp->tcp_rcv_list != NULL) {
14566 				/*
14567 				 * Enqueue the new segment first and then
14568 				 * call tcp_rcv_drain() to send all data
14569 				 * up.  The other way to do this is to
14570 				 * send all queued data up and then call
14571 				 * putnext() to send the new segment up.
14572 				 * This way can remove the else part later
14573 				 * on.
14574 				 *
14575 				 * We don't this to avoid one more call to
14576 				 * canputnext() as tcp_rcv_drain() needs to
14577 				 * call canputnext().
14578 				 */
14579 				tcp_rcv_enqueue(tcp, mp, seg_len);
14580 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14581 			} else {
14582 				/* Does this need SSL processing first? */
14583 				if ((tcp->tcp_kssl_ctx  != NULL) &&
14584 				    (DB_TYPE(mp) == M_DATA)) {
14585 					tcp_kssl_input(tcp, mp);
14586 				} else {
14587 					putnext(tcp->tcp_rq, mp);
14588 					if (!canputnext(tcp->tcp_rq))
14589 						tcp->tcp_rwnd -= seg_len;
14590 				}
14591 			}
14592 		} else {
14593 			/*
14594 			 * Enqueue all packets when processing an mblk
14595 			 * from the co queue and also enqueue normal packets.
14596 			 */
14597 			tcp_rcv_enqueue(tcp, mp, seg_len);
14598 		}
14599 		/*
14600 		 * Make sure the timer is running if we have data waiting
14601 		 * for a push bit. This provides resiliency against
14602 		 * implementations that do not correctly generate push bits.
14603 		 */
14604 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
14605 			/*
14606 			 * The connection may be closed at this point, so don't
14607 			 * do anything for a detached tcp.
14608 			 */
14609 			if (!TCP_IS_DETACHED(tcp))
14610 				tcp->tcp_push_tid = TCP_TIMER(tcp,
14611 				    tcp_push_timer,
14612 				    MSEC_TO_TICK(tcp_push_timer_interval));
14613 		}
14614 	}
14615 xmit_check:
14616 	/* Is there anything left to do? */
14617 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14618 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
14619 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
14620 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14621 		goto done;
14622 
14623 	/* Any transmit work to do and a non-zero window? */
14624 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
14625 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
14626 		if (flags & TH_REXMIT_NEEDED) {
14627 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
14628 
14629 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
14630 			if (snd_size > mss)
14631 				snd_size = mss;
14632 			if (snd_size > tcp->tcp_swnd)
14633 				snd_size = tcp->tcp_swnd;
14634 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
14635 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
14636 			    B_TRUE);
14637 
14638 			if (mp1 != NULL) {
14639 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14640 				tcp->tcp_csuna = tcp->tcp_snxt;
14641 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
14642 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
14643 				TCP_RECORD_TRACE(tcp, mp1,
14644 				    TCP_TRACE_SEND_PKT);
14645 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
14646 			}
14647 		}
14648 		if (flags & TH_NEED_SACK_REXMIT) {
14649 			tcp_sack_rxmit(tcp, &flags);
14650 		}
14651 		/*
14652 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
14653 		 * out new segment.  Note that tcp_rexmit should not be
14654 		 * set, otherwise TH_LIMIT_XMIT should not be set.
14655 		 */
14656 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
14657 			if (!tcp->tcp_rexmit) {
14658 				tcp_wput_data(tcp, NULL, B_FALSE);
14659 			} else {
14660 				tcp_ss_rexmit(tcp);
14661 			}
14662 		}
14663 		/*
14664 		 * Adjust tcp_cwnd back to normal value after sending
14665 		 * new data segments.
14666 		 */
14667 		if (flags & TH_LIMIT_XMIT) {
14668 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
14669 			/*
14670 			 * This will restart the timer.  Restarting the
14671 			 * timer is used to avoid a timeout before the
14672 			 * limited transmitted segment's ACK gets back.
14673 			 */
14674 			if (tcp->tcp_xmit_head != NULL)
14675 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14676 		}
14677 
14678 		/* Anything more to do? */
14679 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
14680 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14681 			goto done;
14682 	}
14683 ack_check:
14684 	if (flags & TH_SEND_URP_MARK) {
14685 		ASSERT(tcp->tcp_urp_mark_mp);
14686 		/*
14687 		 * Send up any queued data and then send the mark message
14688 		 */
14689 		if (tcp->tcp_rcv_list != NULL) {
14690 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14691 		}
14692 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14693 
14694 		mp1 = tcp->tcp_urp_mark_mp;
14695 		tcp->tcp_urp_mark_mp = NULL;
14696 #ifdef DEBUG
14697 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14698 		    "tcp_rput: sending zero-length %s %s",
14699 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
14700 		    "MSGNOTMARKNEXT"),
14701 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14702 #endif /* DEBUG */
14703 		putnext(tcp->tcp_rq, mp1);
14704 		flags &= ~TH_SEND_URP_MARK;
14705 	}
14706 	if (flags & TH_ACK_NEEDED) {
14707 		/*
14708 		 * Time to send an ack for some reason.
14709 		 */
14710 		mp1 = tcp_ack_mp(tcp);
14711 
14712 		if (mp1 != NULL) {
14713 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
14714 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
14715 			BUMP_LOCAL(tcp->tcp_obsegs);
14716 			BUMP_MIB(&tcp_mib, tcpOutAck);
14717 		}
14718 		if (tcp->tcp_ack_tid != 0) {
14719 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
14720 			tcp->tcp_ack_tid = 0;
14721 		}
14722 	}
14723 	if (flags & TH_ACK_TIMER_NEEDED) {
14724 		/*
14725 		 * Arrange for deferred ACK or push wait timeout.
14726 		 * Start timer if it is not already running.
14727 		 */
14728 		if (tcp->tcp_ack_tid == 0) {
14729 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
14730 			    MSEC_TO_TICK(tcp->tcp_localnet ?
14731 			    (clock_t)tcp_local_dack_interval :
14732 			    (clock_t)tcp_deferred_ack_interval));
14733 		}
14734 	}
14735 	if (flags & TH_ORDREL_NEEDED) {
14736 		/*
14737 		 * Send up the ordrel_ind unless we are an eager guy.
14738 		 * In the eager case tcp_rsrv will do this when run
14739 		 * after tcp_accept is done.
14740 		 */
14741 		ASSERT(tcp->tcp_listener == NULL);
14742 		if (tcp->tcp_rcv_list != NULL) {
14743 			/*
14744 			 * Push any mblk(s) enqueued from co processing.
14745 			 */
14746 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14747 		}
14748 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14749 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
14750 			tcp->tcp_ordrel_done = B_TRUE;
14751 			putnext(tcp->tcp_rq, mp1);
14752 			if (tcp->tcp_deferred_clean_death) {
14753 				/*
14754 				 * tcp_clean_death was deferred
14755 				 * for T_ORDREL_IND - do it now
14756 				 */
14757 				(void) tcp_clean_death(tcp,
14758 				    tcp->tcp_client_errno, 20);
14759 				tcp->tcp_deferred_clean_death =	B_FALSE;
14760 			}
14761 		} else {
14762 			/*
14763 			 * Run the orderly release in the
14764 			 * service routine.
14765 			 */
14766 			qenable(tcp->tcp_rq);
14767 			/*
14768 			 * Caveat(XXX): The machine may be so
14769 			 * overloaded that tcp_rsrv() is not scheduled
14770 			 * until after the endpoint has transitioned
14771 			 * to TCPS_TIME_WAIT
14772 			 * and tcp_time_wait_interval expires. Then
14773 			 * tcp_timer() will blow away state in tcp_t
14774 			 * and T_ORDREL_IND will never be delivered
14775 			 * upstream. Unlikely but potentially
14776 			 * a problem.
14777 			 */
14778 		}
14779 	}
14780 done:
14781 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14782 }
14783 
14784 /*
14785  * This function does PAWS protection check. Returns B_TRUE if the
14786  * segment passes the PAWS test, else returns B_FALSE.
14787  */
14788 boolean_t
14789 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
14790 {
14791 	uint8_t	flags;
14792 	int	options;
14793 	uint8_t *up;
14794 
14795 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
14796 	/*
14797 	 * If timestamp option is aligned nicely, get values inline,
14798 	 * otherwise call general routine to parse.  Only do that
14799 	 * if timestamp is the only option.
14800 	 */
14801 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
14802 	    TCPOPT_REAL_TS_LEN &&
14803 	    OK_32PTR((up = ((uint8_t *)tcph) +
14804 	    TCP_MIN_HEADER_LENGTH)) &&
14805 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
14806 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
14807 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
14808 
14809 		options = TCP_OPT_TSTAMP_PRESENT;
14810 	} else {
14811 		if (tcp->tcp_snd_sack_ok) {
14812 			tcpoptp->tcp = tcp;
14813 		} else {
14814 			tcpoptp->tcp = NULL;
14815 		}
14816 		options = tcp_parse_options(tcph, tcpoptp);
14817 	}
14818 
14819 	if (options & TCP_OPT_TSTAMP_PRESENT) {
14820 		/*
14821 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
14822 		 * regardless of the timestamp, page 18 RFC 1323.bis.
14823 		 */
14824 		if ((flags & TH_RST) == 0 &&
14825 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
14826 		    tcp->tcp_ts_recent)) {
14827 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
14828 			    PAWS_TIMEOUT)) {
14829 				/* This segment is not acceptable. */
14830 				return (B_FALSE);
14831 			} else {
14832 				/*
14833 				 * Connection has been idle for
14834 				 * too long.  Reset the timestamp
14835 				 * and assume the segment is valid.
14836 				 */
14837 				tcp->tcp_ts_recent =
14838 				    tcpoptp->tcp_opt_ts_val;
14839 			}
14840 		}
14841 	} else {
14842 		/*
14843 		 * If we don't get a timestamp on every packet, we
14844 		 * figure we can't really trust 'em, so we stop sending
14845 		 * and parsing them.
14846 		 */
14847 		tcp->tcp_snd_ts_ok = B_FALSE;
14848 
14849 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14850 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14851 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
14852 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
14853 		if (tcp->tcp_snd_sack_ok) {
14854 			ASSERT(tcp->tcp_sack_info != NULL);
14855 			tcp->tcp_max_sack_blk = 4;
14856 		}
14857 	}
14858 	return (B_TRUE);
14859 }
14860 
14861 /*
14862  * Attach ancillary data to a received TCP segments for the
14863  * ancillary pieces requested by the application that are
14864  * different than they were in the previous data segment.
14865  *
14866  * Save the "current" values once memory allocation is ok so that
14867  * when memory allocation fails we can just wait for the next data segment.
14868  */
14869 static mblk_t *
14870 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
14871 {
14872 	struct T_optdata_ind *todi;
14873 	int optlen;
14874 	uchar_t *optptr;
14875 	struct T_opthdr *toh;
14876 	uint_t addflag;	/* Which pieces to add */
14877 	mblk_t *mp1;
14878 
14879 	optlen = 0;
14880 	addflag = 0;
14881 	/* If app asked for pktinfo and the index has changed ... */
14882 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
14883 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
14884 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
14885 		optlen += sizeof (struct T_opthdr) +
14886 		    sizeof (struct in6_pktinfo);
14887 		addflag |= TCP_IPV6_RECVPKTINFO;
14888 	}
14889 	/* If app asked for hoplimit and it has changed ... */
14890 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
14891 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
14892 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
14893 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14894 		addflag |= TCP_IPV6_RECVHOPLIMIT;
14895 	}
14896 	/* If app asked for tclass and it has changed ... */
14897 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
14898 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
14899 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
14900 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14901 		addflag |= TCP_IPV6_RECVTCLASS;
14902 	}
14903 	/*
14904 	 * If app asked for hopbyhop headers and it has changed ...
14905 	 * For security labels, note that (1) security labels can't change on
14906 	 * a connected socket at all, (2) we're connected to at most one peer,
14907 	 * (3) if anything changes, then it must be some other extra option.
14908 	 */
14909 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
14910 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
14911 	    (ipp->ipp_fields & IPPF_HOPOPTS),
14912 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
14913 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
14914 		    tcp->tcp_label_len;
14915 		addflag |= TCP_IPV6_RECVHOPOPTS;
14916 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
14917 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
14918 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
14919 			return (mp);
14920 	}
14921 	/* If app asked for dst headers before routing headers ... */
14922 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
14923 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
14924 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
14925 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
14926 		optlen += sizeof (struct T_opthdr) +
14927 		    ipp->ipp_rtdstoptslen;
14928 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
14929 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
14930 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
14931 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
14932 			return (mp);
14933 	}
14934 	/* If app asked for routing headers and it has changed ... */
14935 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
14936 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
14937 	    (ipp->ipp_fields & IPPF_RTHDR),
14938 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
14939 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
14940 		addflag |= TCP_IPV6_RECVRTHDR;
14941 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
14942 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
14943 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
14944 			return (mp);
14945 	}
14946 	/* If app asked for dest headers and it has changed ... */
14947 	if ((tcp->tcp_ipv6_recvancillary &
14948 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
14949 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
14950 	    (ipp->ipp_fields & IPPF_DSTOPTS),
14951 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
14952 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
14953 		addflag |= TCP_IPV6_RECVDSTOPTS;
14954 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
14955 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
14956 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
14957 			return (mp);
14958 	}
14959 
14960 	if (optlen == 0) {
14961 		/* Nothing to add */
14962 		return (mp);
14963 	}
14964 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
14965 	if (mp1 == NULL) {
14966 		/*
14967 		 * Defer sending ancillary data until the next TCP segment
14968 		 * arrives.
14969 		 */
14970 		return (mp);
14971 	}
14972 	mp1->b_cont = mp;
14973 	mp = mp1;
14974 	mp->b_wptr += sizeof (*todi) + optlen;
14975 	mp->b_datap->db_type = M_PROTO;
14976 	todi = (struct T_optdata_ind *)mp->b_rptr;
14977 	todi->PRIM_type = T_OPTDATA_IND;
14978 	todi->DATA_flag = 1;	/* MORE data */
14979 	todi->OPT_length = optlen;
14980 	todi->OPT_offset = sizeof (*todi);
14981 	optptr = (uchar_t *)&todi[1];
14982 	/*
14983 	 * If app asked for pktinfo and the index has changed ...
14984 	 * Note that the local address never changes for the connection.
14985 	 */
14986 	if (addflag & TCP_IPV6_RECVPKTINFO) {
14987 		struct in6_pktinfo *pkti;
14988 
14989 		toh = (struct T_opthdr *)optptr;
14990 		toh->level = IPPROTO_IPV6;
14991 		toh->name = IPV6_PKTINFO;
14992 		toh->len = sizeof (*toh) + sizeof (*pkti);
14993 		toh->status = 0;
14994 		optptr += sizeof (*toh);
14995 		pkti = (struct in6_pktinfo *)optptr;
14996 		if (tcp->tcp_ipversion == IPV6_VERSION)
14997 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
14998 		else
14999 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15000 			    &pkti->ipi6_addr);
15001 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15002 		optptr += sizeof (*pkti);
15003 		ASSERT(OK_32PTR(optptr));
15004 		/* Save as "last" value */
15005 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15006 	}
15007 	/* If app asked for hoplimit and it has changed ... */
15008 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15009 		toh = (struct T_opthdr *)optptr;
15010 		toh->level = IPPROTO_IPV6;
15011 		toh->name = IPV6_HOPLIMIT;
15012 		toh->len = sizeof (*toh) + sizeof (uint_t);
15013 		toh->status = 0;
15014 		optptr += sizeof (*toh);
15015 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15016 		optptr += sizeof (uint_t);
15017 		ASSERT(OK_32PTR(optptr));
15018 		/* Save as "last" value */
15019 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15020 	}
15021 	/* If app asked for tclass and it has changed ... */
15022 	if (addflag & TCP_IPV6_RECVTCLASS) {
15023 		toh = (struct T_opthdr *)optptr;
15024 		toh->level = IPPROTO_IPV6;
15025 		toh->name = IPV6_TCLASS;
15026 		toh->len = sizeof (*toh) + sizeof (uint_t);
15027 		toh->status = 0;
15028 		optptr += sizeof (*toh);
15029 		*(uint_t *)optptr = ipp->ipp_tclass;
15030 		optptr += sizeof (uint_t);
15031 		ASSERT(OK_32PTR(optptr));
15032 		/* Save as "last" value */
15033 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15034 	}
15035 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15036 		toh = (struct T_opthdr *)optptr;
15037 		toh->level = IPPROTO_IPV6;
15038 		toh->name = IPV6_HOPOPTS;
15039 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15040 		    tcp->tcp_label_len;
15041 		toh->status = 0;
15042 		optptr += sizeof (*toh);
15043 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15044 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15045 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15046 		ASSERT(OK_32PTR(optptr));
15047 		/* Save as last value */
15048 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15049 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15050 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15051 	}
15052 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15053 		toh = (struct T_opthdr *)optptr;
15054 		toh->level = IPPROTO_IPV6;
15055 		toh->name = IPV6_RTHDRDSTOPTS;
15056 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15057 		toh->status = 0;
15058 		optptr += sizeof (*toh);
15059 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15060 		optptr += ipp->ipp_rtdstoptslen;
15061 		ASSERT(OK_32PTR(optptr));
15062 		/* Save as last value */
15063 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15064 		    &tcp->tcp_rtdstoptslen,
15065 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15066 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15067 	}
15068 	if (addflag & TCP_IPV6_RECVRTHDR) {
15069 		toh = (struct T_opthdr *)optptr;
15070 		toh->level = IPPROTO_IPV6;
15071 		toh->name = IPV6_RTHDR;
15072 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15073 		toh->status = 0;
15074 		optptr += sizeof (*toh);
15075 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15076 		optptr += ipp->ipp_rthdrlen;
15077 		ASSERT(OK_32PTR(optptr));
15078 		/* Save as last value */
15079 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15080 		    (ipp->ipp_fields & IPPF_RTHDR),
15081 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15082 	}
15083 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15084 		toh = (struct T_opthdr *)optptr;
15085 		toh->level = IPPROTO_IPV6;
15086 		toh->name = IPV6_DSTOPTS;
15087 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15088 		toh->status = 0;
15089 		optptr += sizeof (*toh);
15090 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15091 		optptr += ipp->ipp_dstoptslen;
15092 		ASSERT(OK_32PTR(optptr));
15093 		/* Save as last value */
15094 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15095 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15096 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15097 	}
15098 	ASSERT(optptr == mp->b_wptr);
15099 	return (mp);
15100 }
15101 
15102 
15103 /*
15104  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15105  * or a "bad" IRE detected by tcp_adapt_ire.
15106  * We can't tell if the failure was due to the laddr or the faddr
15107  * thus we clear out all addresses and ports.
15108  */
15109 static void
15110 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15111 {
15112 	queue_t	*q = tcp->tcp_rq;
15113 	tcph_t	*tcph;
15114 	struct T_error_ack *tea;
15115 	conn_t	*connp = tcp->tcp_connp;
15116 
15117 
15118 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15119 
15120 	if (mp->b_cont) {
15121 		freemsg(mp->b_cont);
15122 		mp->b_cont = NULL;
15123 	}
15124 	tea = (struct T_error_ack *)mp->b_rptr;
15125 	switch (tea->PRIM_type) {
15126 	case T_BIND_ACK:
15127 		/*
15128 		 * Need to unbind with classifier since we were just told that
15129 		 * our bind succeeded.
15130 		 */
15131 		tcp->tcp_hard_bound = B_FALSE;
15132 		tcp->tcp_hard_binding = B_FALSE;
15133 
15134 		ipcl_hash_remove(connp);
15135 		/* Reuse the mblk if possible */
15136 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15137 			sizeof (*tea));
15138 		mp->b_rptr = mp->b_datap->db_base;
15139 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15140 		tea = (struct T_error_ack *)mp->b_rptr;
15141 		tea->PRIM_type = T_ERROR_ACK;
15142 		tea->TLI_error = TSYSERR;
15143 		tea->UNIX_error = error;
15144 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15145 			tea->ERROR_prim = T_CONN_REQ;
15146 		} else {
15147 			tea->ERROR_prim = O_T_BIND_REQ;
15148 		}
15149 		break;
15150 
15151 	case T_ERROR_ACK:
15152 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15153 			tea->ERROR_prim = T_CONN_REQ;
15154 		break;
15155 	default:
15156 		panic("tcp_bind_failed: unexpected TPI type");
15157 		/*NOTREACHED*/
15158 	}
15159 
15160 	tcp->tcp_state = TCPS_IDLE;
15161 	if (tcp->tcp_ipversion == IPV4_VERSION)
15162 		tcp->tcp_ipha->ipha_src = 0;
15163 	else
15164 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15165 	/*
15166 	 * Copy of the src addr. in tcp_t is needed since
15167 	 * the lookup funcs. can only look at tcp_t
15168 	 */
15169 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15170 
15171 	tcph = tcp->tcp_tcph;
15172 	tcph->th_lport[0] = 0;
15173 	tcph->th_lport[1] = 0;
15174 	tcp_bind_hash_remove(tcp);
15175 	bzero(&connp->u_port, sizeof (connp->u_port));
15176 	/* blow away saved option results if any */
15177 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15178 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15179 
15180 	conn_delete_ire(tcp->tcp_connp, NULL);
15181 	putnext(q, mp);
15182 }
15183 
15184 /*
15185  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15186  * messages.
15187  */
15188 void
15189 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15190 {
15191 	mblk_t	*mp1;
15192 	uchar_t	*rptr = mp->b_rptr;
15193 	queue_t	*q = tcp->tcp_rq;
15194 	struct T_error_ack *tea;
15195 	uint32_t mss;
15196 	mblk_t *syn_mp;
15197 	mblk_t *mdti;
15198 	int	retval;
15199 	mblk_t *ire_mp;
15200 
15201 	switch (mp->b_datap->db_type) {
15202 	case M_PROTO:
15203 	case M_PCPROTO:
15204 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15205 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15206 			break;
15207 		tea = (struct T_error_ack *)rptr;
15208 		switch (tea->PRIM_type) {
15209 		case T_BIND_ACK:
15210 			/*
15211 			 * Adapt Multidata information, if any.  The
15212 			 * following tcp_mdt_update routine will free
15213 			 * the message.
15214 			 */
15215 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15216 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15217 				    b_rptr)->mdt_capab, B_TRUE);
15218 				freemsg(mdti);
15219 			}
15220 
15221 			/* Get the IRE, if we had requested for it */
15222 			ire_mp = tcp_ire_mp(mp);
15223 
15224 			if (tcp->tcp_hard_binding) {
15225 				tcp->tcp_hard_binding = B_FALSE;
15226 				tcp->tcp_hard_bound = B_TRUE;
15227 				CL_INET_CONNECT(tcp);
15228 			} else {
15229 				if (ire_mp != NULL)
15230 					freeb(ire_mp);
15231 				goto after_syn_sent;
15232 			}
15233 
15234 			retval = tcp_adapt_ire(tcp, ire_mp);
15235 			if (ire_mp != NULL)
15236 				freeb(ire_mp);
15237 			if (retval == 0) {
15238 				tcp_bind_failed(tcp, mp,
15239 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15240 				    ENETUNREACH : EADDRNOTAVAIL));
15241 				return;
15242 			}
15243 			/*
15244 			 * Don't let an endpoint connect to itself.
15245 			 * Also checked in tcp_connect() but that
15246 			 * check can't handle the case when the
15247 			 * local IP address is INADDR_ANY.
15248 			 */
15249 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15250 				if ((tcp->tcp_ipha->ipha_dst ==
15251 				    tcp->tcp_ipha->ipha_src) &&
15252 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15253 				    tcp->tcp_tcph->th_fport))) {
15254 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15255 					return;
15256 				}
15257 			} else {
15258 				if (IN6_ARE_ADDR_EQUAL(
15259 				    &tcp->tcp_ip6h->ip6_dst,
15260 				    &tcp->tcp_ip6h->ip6_src) &&
15261 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15262 				    tcp->tcp_tcph->th_fport))) {
15263 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15264 					return;
15265 				}
15266 			}
15267 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15268 			/*
15269 			 * This should not be possible!  Just for
15270 			 * defensive coding...
15271 			 */
15272 			if (tcp->tcp_state != TCPS_SYN_SENT)
15273 				goto after_syn_sent;
15274 
15275 			if (is_system_labeled() &&
15276 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
15277 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
15278 				return;
15279 			}
15280 
15281 			ASSERT(q == tcp->tcp_rq);
15282 			/*
15283 			 * tcp_adapt_ire() does not adjust
15284 			 * for TCP/IP header length.
15285 			 */
15286 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15287 
15288 			/*
15289 			 * Just make sure our rwnd is at
15290 			 * least tcp_recv_hiwat_mss * MSS
15291 			 * large, and round up to the nearest
15292 			 * MSS.
15293 			 *
15294 			 * We do the round up here because
15295 			 * we need to get the interface
15296 			 * MTU first before we can do the
15297 			 * round up.
15298 			 */
15299 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15300 			    tcp_recv_hiwat_minmss * mss);
15301 			q->q_hiwat = tcp->tcp_rwnd;
15302 			tcp_set_ws_value(tcp);
15303 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15304 			    tcp->tcp_tcph->th_win);
15305 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
15306 				tcp->tcp_snd_ws_ok = B_TRUE;
15307 
15308 			/*
15309 			 * Set tcp_snd_ts_ok to true
15310 			 * so that tcp_xmit_mp will
15311 			 * include the timestamp
15312 			 * option in the SYN segment.
15313 			 */
15314 			if (tcp_tstamp_always ||
15315 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
15316 				tcp->tcp_snd_ts_ok = B_TRUE;
15317 			}
15318 
15319 			/*
15320 			 * tcp_snd_sack_ok can be set in
15321 			 * tcp_adapt_ire() if the sack metric
15322 			 * is set.  So check it here also.
15323 			 */
15324 			if (tcp_sack_permitted == 2 ||
15325 			    tcp->tcp_snd_sack_ok) {
15326 				if (tcp->tcp_sack_info == NULL) {
15327 					tcp->tcp_sack_info =
15328 					kmem_cache_alloc(tcp_sack_info_cache,
15329 					    KM_SLEEP);
15330 				}
15331 				tcp->tcp_snd_sack_ok = B_TRUE;
15332 			}
15333 
15334 			/*
15335 			 * Should we use ECN?  Note that the current
15336 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15337 			 * is 1.  The reason for doing this is that there
15338 			 * are equipments out there that will drop ECN
15339 			 * enabled IP packets.  Setting it to 1 avoids
15340 			 * compatibility problems.
15341 			 */
15342 			if (tcp_ecn_permitted == 2)
15343 				tcp->tcp_ecn_ok = B_TRUE;
15344 
15345 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15346 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15347 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15348 			if (syn_mp) {
15349 				cred_t *cr;
15350 				pid_t pid;
15351 
15352 				/*
15353 				 * Obtain the credential from the
15354 				 * thread calling connect(); the credential
15355 				 * lives on in the second mblk which
15356 				 * originated from T_CONN_REQ and is echoed
15357 				 * with the T_BIND_ACK from ip.  If none
15358 				 * can be found, default to the creator
15359 				 * of the socket.
15360 				 */
15361 				if (mp->b_cont == NULL ||
15362 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15363 					cr = tcp->tcp_cred;
15364 					pid = tcp->tcp_cpid;
15365 				} else {
15366 					pid = DB_CPID(mp->b_cont);
15367 				}
15368 
15369 				TCP_RECORD_TRACE(tcp, syn_mp,
15370 				    TCP_TRACE_SEND_PKT);
15371 				mblk_setcred(syn_mp, cr);
15372 				DB_CPID(syn_mp) = pid;
15373 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15374 			}
15375 		after_syn_sent:
15376 			/*
15377 			 * A trailer mblk indicates a waiting client upstream.
15378 			 * We complete here the processing begun in
15379 			 * either tcp_bind() or tcp_connect() by passing
15380 			 * upstream the reply message they supplied.
15381 			 */
15382 			mp1 = mp;
15383 			mp = mp->b_cont;
15384 			freeb(mp1);
15385 			if (mp)
15386 				break;
15387 			return;
15388 		case T_ERROR_ACK:
15389 			if (tcp->tcp_debug) {
15390 				(void) strlog(TCP_MOD_ID, 0, 1,
15391 				    SL_TRACE|SL_ERROR,
15392 				    "tcp_rput_other: case T_ERROR_ACK, "
15393 				    "ERROR_prim == %d",
15394 				    tea->ERROR_prim);
15395 			}
15396 			switch (tea->ERROR_prim) {
15397 			case O_T_BIND_REQ:
15398 			case T_BIND_REQ:
15399 				tcp_bind_failed(tcp, mp,
15400 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15401 				    ENETUNREACH : EADDRNOTAVAIL));
15402 				return;
15403 			case T_UNBIND_REQ:
15404 				tcp->tcp_hard_binding = B_FALSE;
15405 				tcp->tcp_hard_bound = B_FALSE;
15406 				if (mp->b_cont) {
15407 					freemsg(mp->b_cont);
15408 					mp->b_cont = NULL;
15409 				}
15410 				if (tcp->tcp_unbind_pending)
15411 					tcp->tcp_unbind_pending = 0;
15412 				else {
15413 					/* From tcp_ip_unbind() - free */
15414 					freemsg(mp);
15415 					return;
15416 				}
15417 				break;
15418 			case T_SVR4_OPTMGMT_REQ:
15419 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15420 					/* T_OPTMGMT_REQ generated by TCP */
15421 					printf("T_SVR4_OPTMGMT_REQ failed "
15422 					    "%d/%d - dropped (cnt %d)\n",
15423 					    tea->TLI_error, tea->UNIX_error,
15424 					    tcp->tcp_drop_opt_ack_cnt);
15425 					freemsg(mp);
15426 					tcp->tcp_drop_opt_ack_cnt--;
15427 					return;
15428 				}
15429 				break;
15430 			}
15431 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15432 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15433 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15434 				    "- dropped (cnt %d)\n",
15435 				    tea->TLI_error, tea->UNIX_error,
15436 				    tcp->tcp_drop_opt_ack_cnt);
15437 				freemsg(mp);
15438 				tcp->tcp_drop_opt_ack_cnt--;
15439 				return;
15440 			}
15441 			break;
15442 		case T_OPTMGMT_ACK:
15443 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15444 				/* T_OPTMGMT_REQ generated by TCP */
15445 				freemsg(mp);
15446 				tcp->tcp_drop_opt_ack_cnt--;
15447 				return;
15448 			}
15449 			break;
15450 		default:
15451 			break;
15452 		}
15453 		break;
15454 	case M_CTL:
15455 		/*
15456 		 * ICMP messages.
15457 		 */
15458 		tcp_icmp_error(tcp, mp);
15459 		return;
15460 	case M_FLUSH:
15461 		if (*rptr & FLUSHR)
15462 			flushq(q, FLUSHDATA);
15463 		break;
15464 	default:
15465 		break;
15466 	}
15467 	/*
15468 	 * Make sure we set this bit before sending the ACK for
15469 	 * bind. Otherwise accept could possibly run and free
15470 	 * this tcp struct.
15471 	 */
15472 	putnext(q, mp);
15473 }
15474 
15475 /*
15476  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15477  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15478  * tcp_rsrv() try again.
15479  */
15480 static void
15481 tcp_ordrel_kick(void *arg)
15482 {
15483 	conn_t 	*connp = (conn_t *)arg;
15484 	tcp_t	*tcp = connp->conn_tcp;
15485 
15486 	tcp->tcp_ordrelid = 0;
15487 	tcp->tcp_timeout = B_FALSE;
15488 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15489 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15490 		qenable(tcp->tcp_rq);
15491 	}
15492 }
15493 
15494 /* ARGSUSED */
15495 static void
15496 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15497 {
15498 	conn_t	*connp = (conn_t *)arg;
15499 	tcp_t	*tcp = connp->conn_tcp;
15500 	queue_t	*q = tcp->tcp_rq;
15501 	uint_t	thwin;
15502 
15503 	freeb(mp);
15504 
15505 	TCP_STAT(tcp_rsrv_calls);
15506 
15507 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15508 		return;
15509 	}
15510 
15511 	if (tcp->tcp_fused) {
15512 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15513 
15514 		ASSERT(tcp->tcp_fused);
15515 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15516 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15517 		ASSERT(!TCP_IS_DETACHED(tcp));
15518 		ASSERT(tcp->tcp_connp->conn_sqp ==
15519 		    peer_tcp->tcp_connp->conn_sqp);
15520 
15521 		/*
15522 		 * Normally we would not get backenabled in synchronous
15523 		 * streams mode, but in case this happens, we need to stop
15524 		 * synchronous streams temporarily to prevent a race with
15525 		 * tcp_fuse_rrw() or tcp_fuse_rinfop().  It is safe to access
15526 		 * tcp_rcv_list here because those entry points will return
15527 		 * right away when synchronous streams is stopped.
15528 		 */
15529 		TCP_FUSE_SYNCSTR_STOP(tcp);
15530 		if (tcp->tcp_rcv_list != NULL)
15531 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15532 
15533 		tcp_clrqfull(peer_tcp);
15534 		TCP_FUSE_SYNCSTR_RESUME(tcp);
15535 		TCP_STAT(tcp_fusion_backenabled);
15536 		return;
15537 	}
15538 
15539 	if (canputnext(q)) {
15540 		tcp->tcp_rwnd = q->q_hiwat;
15541 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15542 		    << tcp->tcp_rcv_ws;
15543 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15544 		/*
15545 		 * Send back a window update immediately if TCP is above
15546 		 * ESTABLISHED state and the increase of the rcv window
15547 		 * that the other side knows is at least 1 MSS after flow
15548 		 * control is lifted.
15549 		 */
15550 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15551 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15552 			tcp_xmit_ctl(NULL, tcp,
15553 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15554 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15555 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
15556 		}
15557 	}
15558 	/* Handle a failure to allocate a T_ORDREL_IND here */
15559 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15560 		ASSERT(tcp->tcp_listener == NULL);
15561 		if (tcp->tcp_rcv_list != NULL) {
15562 			(void) tcp_rcv_drain(q, tcp);
15563 		}
15564 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15565 		mp = mi_tpi_ordrel_ind();
15566 		if (mp) {
15567 			tcp->tcp_ordrel_done = B_TRUE;
15568 			putnext(q, mp);
15569 			if (tcp->tcp_deferred_clean_death) {
15570 				/*
15571 				 * tcp_clean_death was deferred for
15572 				 * T_ORDREL_IND - do it now
15573 				 */
15574 				tcp->tcp_deferred_clean_death = B_FALSE;
15575 				(void) tcp_clean_death(tcp,
15576 				    tcp->tcp_client_errno, 22);
15577 			}
15578 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15579 			/*
15580 			 * If there isn't already a timer running
15581 			 * start one.  Use a 4 second
15582 			 * timer as a fallback since it can't fail.
15583 			 */
15584 			tcp->tcp_timeout = B_TRUE;
15585 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15586 			    MSEC_TO_TICK(4000));
15587 		}
15588 	}
15589 }
15590 
15591 /*
15592  * The read side service routine is called mostly when we get back-enabled as a
15593  * result of flow control relief.  Since we don't actually queue anything in
15594  * TCP, we have no data to send out of here.  What we do is clear the receive
15595  * window, and send out a window update.
15596  * This routine is also called to drive an orderly release message upstream
15597  * if the attempt in tcp_rput failed.
15598  */
15599 static void
15600 tcp_rsrv(queue_t *q)
15601 {
15602 	conn_t *connp = Q_TO_CONN(q);
15603 	tcp_t	*tcp = connp->conn_tcp;
15604 	mblk_t	*mp;
15605 
15606 	/* No code does a putq on the read side */
15607 	ASSERT(q->q_first == NULL);
15608 
15609 	/* Nothing to do for the default queue */
15610 	if (q == tcp_g_q) {
15611 		return;
15612 	}
15613 
15614 	mp = allocb(0, BPRI_HI);
15615 	if (mp == NULL) {
15616 		/*
15617 		 * We are under memory pressure. Return for now and we
15618 		 * we will be called again later.
15619 		 */
15620 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15621 			/*
15622 			 * If there isn't already a timer running
15623 			 * start one.  Use a 4 second
15624 			 * timer as a fallback since it can't fail.
15625 			 */
15626 			tcp->tcp_timeout = B_TRUE;
15627 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15628 			    MSEC_TO_TICK(4000));
15629 		}
15630 		return;
15631 	}
15632 	CONN_INC_REF(connp);
15633 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15634 	    SQTAG_TCP_RSRV);
15635 }
15636 
15637 /*
15638  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15639  * We do not allow the receive window to shrink.  After setting rwnd,
15640  * set the flow control hiwat of the stream.
15641  *
15642  * This function is called in 2 cases:
15643  *
15644  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15645  *    connection (passive open) and in tcp_rput_data() for active connect.
15646  *    This is called after tcp_mss_set() when the desired MSS value is known.
15647  *    This makes sure that our window size is a mutiple of the other side's
15648  *    MSS.
15649  * 2) Handling SO_RCVBUF option.
15650  *
15651  * It is ASSUMED that the requested size is a multiple of the current MSS.
15652  *
15653  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15654  * user requests so.
15655  */
15656 static int
15657 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15658 {
15659 	uint32_t	mss = tcp->tcp_mss;
15660 	uint32_t	old_max_rwnd;
15661 	uint32_t	max_transmittable_rwnd;
15662 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15663 
15664 	if (tcp->tcp_fused) {
15665 		size_t sth_hiwat;
15666 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15667 
15668 		ASSERT(peer_tcp != NULL);
15669 		/*
15670 		 * Record the stream head's high water mark for
15671 		 * this endpoint; this is used for flow-control
15672 		 * purposes in tcp_fuse_output().
15673 		 */
15674 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15675 		if (!tcp_detached)
15676 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
15677 
15678 		/*
15679 		 * In the fusion case, the maxpsz stream head value of
15680 		 * our peer is set according to its send buffer size
15681 		 * and our receive buffer size; since the latter may
15682 		 * have changed we need to update the peer's maxpsz.
15683 		 */
15684 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15685 		return (rwnd);
15686 	}
15687 
15688 	if (tcp_detached)
15689 		old_max_rwnd = tcp->tcp_rwnd;
15690 	else
15691 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
15692 
15693 	/*
15694 	 * Insist on a receive window that is at least
15695 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15696 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15697 	 * and delayed acknowledgement.
15698 	 */
15699 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
15700 
15701 	/*
15702 	 * If window size info has already been exchanged, TCP should not
15703 	 * shrink the window.  Shrinking window is doable if done carefully.
15704 	 * We may add that support later.  But so far there is not a real
15705 	 * need to do that.
15706 	 */
15707 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15708 		/* MSS may have changed, do a round up again. */
15709 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15710 	}
15711 
15712 	/*
15713 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15714 	 * can be applied even before the window scale option is decided.
15715 	 */
15716 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15717 	if (rwnd > max_transmittable_rwnd) {
15718 		rwnd = max_transmittable_rwnd -
15719 		    (max_transmittable_rwnd % mss);
15720 		if (rwnd < mss)
15721 			rwnd = max_transmittable_rwnd;
15722 		/*
15723 		 * If we're over the limit we may have to back down tcp_rwnd.
15724 		 * The increment below won't work for us. So we set all three
15725 		 * here and the increment below will have no effect.
15726 		 */
15727 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15728 	}
15729 	if (tcp->tcp_localnet) {
15730 		tcp->tcp_rack_abs_max =
15731 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
15732 	} else {
15733 		/*
15734 		 * For a remote host on a different subnet (through a router),
15735 		 * we ack every other packet to be conforming to RFC1122.
15736 		 * tcp_deferred_acks_max is default to 2.
15737 		 */
15738 		tcp->tcp_rack_abs_max =
15739 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
15740 	}
15741 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15742 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15743 	else
15744 		tcp->tcp_rack_cur_max = 0;
15745 	/*
15746 	 * Increment the current rwnd by the amount the maximum grew (we
15747 	 * can not overwrite it since we might be in the middle of a
15748 	 * connection.)
15749 	 */
15750 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15751 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15752 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15753 		tcp->tcp_cwnd_max = rwnd;
15754 
15755 	if (tcp_detached)
15756 		return (rwnd);
15757 	/*
15758 	 * We set the maximum receive window into rq->q_hiwat.
15759 	 * This is not actually used for flow control.
15760 	 */
15761 	tcp->tcp_rq->q_hiwat = rwnd;
15762 	/*
15763 	 * Set the Stream head high water mark. This doesn't have to be
15764 	 * here, since we are simply using default values, but we would
15765 	 * prefer to choose these values algorithmically, with a likely
15766 	 * relationship to rwnd.
15767 	 */
15768 	(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd, tcp_sth_rcv_hiwat));
15769 	return (rwnd);
15770 }
15771 
15772 /*
15773  * Return SNMP stuff in buffer in mpdata.
15774  */
15775 int
15776 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15777 {
15778 	mblk_t			*mpdata;
15779 	mblk_t			*mp_conn_ctl = NULL;
15780 	mblk_t			*mp_conn_tail;
15781 	mblk_t			*mp_attr_ctl = NULL;
15782 	mblk_t			*mp_attr_tail;
15783 	mblk_t			*mp6_conn_ctl = NULL;
15784 	mblk_t			*mp6_conn_tail;
15785 	mblk_t			*mp6_attr_ctl = NULL;
15786 	mblk_t			*mp6_attr_tail;
15787 	struct opthdr		*optp;
15788 	mib2_tcpConnEntry_t	tce;
15789 	mib2_tcp6ConnEntry_t	tce6;
15790 	mib2_transportMLPEntry_t mlp;
15791 	connf_t			*connfp;
15792 	conn_t			*connp;
15793 	int			i;
15794 	boolean_t 		ispriv;
15795 	zoneid_t 		zoneid;
15796 	int			v4_conn_idx;
15797 	int			v6_conn_idx;
15798 
15799 	if (mpctl == NULL ||
15800 	    (mpdata = mpctl->b_cont) == NULL ||
15801 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15802 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
15803 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
15804 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
15805 		freemsg(mp_conn_ctl);
15806 		freemsg(mp_attr_ctl);
15807 		freemsg(mp6_conn_ctl);
15808 		freemsg(mp6_attr_ctl);
15809 		return (0);
15810 	}
15811 
15812 	/* build table of connections -- need count in fixed part */
15813 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
15814 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
15815 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
15816 	SET_MIB(tcp_mib.tcpMaxConn, -1);
15817 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
15818 
15819 	ispriv =
15820 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15821 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15822 
15823 	v4_conn_idx = v6_conn_idx = 0;
15824 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
15825 
15826 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15827 
15828 		connfp = &ipcl_globalhash_fanout[i];
15829 
15830 		connp = NULL;
15831 
15832 		while ((connp =
15833 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15834 			tcp_t *tcp;
15835 			boolean_t needattr;
15836 
15837 			if (connp->conn_zoneid != zoneid)
15838 				continue;	/* not in this zone */
15839 
15840 			tcp = connp->conn_tcp;
15841 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
15842 			tcp->tcp_ibsegs = 0;
15843 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
15844 			tcp->tcp_obsegs = 0;
15845 
15846 			tce6.tcp6ConnState = tce.tcpConnState =
15847 			    tcp_snmp_state(tcp);
15848 			if (tce.tcpConnState == MIB2_TCP_established ||
15849 			    tce.tcpConnState == MIB2_TCP_closeWait)
15850 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
15851 
15852 			needattr = B_FALSE;
15853 			bzero(&mlp, sizeof (mlp));
15854 			if (connp->conn_mlp_type != mlptSingle) {
15855 				if (connp->conn_mlp_type == mlptShared ||
15856 				    connp->conn_mlp_type == mlptBoth)
15857 					mlp.tme_flags |= MIB2_TMEF_SHARED;
15858 				if (connp->conn_mlp_type == mlptPrivate ||
15859 				    connp->conn_mlp_type == mlptBoth)
15860 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
15861 				needattr = B_TRUE;
15862 			}
15863 			if (connp->conn_peercred != NULL) {
15864 				ts_label_t *tsl;
15865 
15866 				tsl = crgetlabel(connp->conn_peercred);
15867 				mlp.tme_doi = label2doi(tsl);
15868 				mlp.tme_label = *label2bslabel(tsl);
15869 				needattr = B_TRUE;
15870 			}
15871 
15872 			/* Create a message to report on IPv6 entries */
15873 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15874 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15875 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15876 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15877 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15878 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15879 			/* Don't want just anybody seeing these... */
15880 			if (ispriv) {
15881 				tce6.tcp6ConnEntryInfo.ce_snxt =
15882 				    tcp->tcp_snxt;
15883 				tce6.tcp6ConnEntryInfo.ce_suna =
15884 				    tcp->tcp_suna;
15885 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15886 				    tcp->tcp_rnxt;
15887 				tce6.tcp6ConnEntryInfo.ce_rack =
15888 				    tcp->tcp_rack;
15889 			} else {
15890 				/*
15891 				 * Netstat, unfortunately, uses this to
15892 				 * get send/receive queue sizes.  How to fix?
15893 				 * Why not compute the difference only?
15894 				 */
15895 				tce6.tcp6ConnEntryInfo.ce_snxt =
15896 				    tcp->tcp_snxt - tcp->tcp_suna;
15897 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
15898 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15899 				    tcp->tcp_rnxt - tcp->tcp_rack;
15900 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
15901 			}
15902 
15903 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15904 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15905 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
15906 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
15907 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
15908 
15909 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
15910 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
15911 
15912 			mlp.tme_connidx = v6_conn_idx++;
15913 			if (needattr)
15914 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
15915 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
15916 			}
15917 			/*
15918 			 * Create an IPv4 table entry for IPv4 entries and also
15919 			 * for IPv6 entries which are bound to in6addr_any
15920 			 * but don't have IPV6_V6ONLY set.
15921 			 * (i.e. anything an IPv4 peer could connect to)
15922 			 */
15923 			if (tcp->tcp_ipversion == IPV4_VERSION ||
15924 			    (tcp->tcp_state <= TCPS_LISTEN &&
15925 			    !tcp->tcp_connp->conn_ipv6_v6only &&
15926 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
15927 				if (tcp->tcp_ipversion == IPV6_VERSION) {
15928 					tce.tcpConnRemAddress = INADDR_ANY;
15929 					tce.tcpConnLocalAddress = INADDR_ANY;
15930 				} else {
15931 					tce.tcpConnRemAddress =
15932 					    tcp->tcp_remote;
15933 					tce.tcpConnLocalAddress =
15934 					    tcp->tcp_ip_src;
15935 				}
15936 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
15937 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
15938 				/* Don't want just anybody seeing these... */
15939 				if (ispriv) {
15940 					tce.tcpConnEntryInfo.ce_snxt =
15941 					    tcp->tcp_snxt;
15942 					tce.tcpConnEntryInfo.ce_suna =
15943 					    tcp->tcp_suna;
15944 					tce.tcpConnEntryInfo.ce_rnxt =
15945 					    tcp->tcp_rnxt;
15946 					tce.tcpConnEntryInfo.ce_rack =
15947 					    tcp->tcp_rack;
15948 				} else {
15949 					/*
15950 					 * Netstat, unfortunately, uses this to
15951 					 * get send/receive queue sizes.  How
15952 					 * to fix?
15953 					 * Why not compute the difference only?
15954 					 */
15955 					tce.tcpConnEntryInfo.ce_snxt =
15956 					    tcp->tcp_snxt - tcp->tcp_suna;
15957 					tce.tcpConnEntryInfo.ce_suna = 0;
15958 					tce.tcpConnEntryInfo.ce_rnxt =
15959 					    tcp->tcp_rnxt - tcp->tcp_rack;
15960 					tce.tcpConnEntryInfo.ce_rack = 0;
15961 				}
15962 
15963 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15964 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15965 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
15966 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
15967 				tce.tcpConnEntryInfo.ce_state =
15968 				    tcp->tcp_state;
15969 
15970 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
15971 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
15972 
15973 				mlp.tme_connidx = v4_conn_idx++;
15974 				if (needattr)
15975 					(void) snmp_append_data2(
15976 					    mp_attr_ctl->b_cont,
15977 					    &mp_attr_tail, (char *)&mlp,
15978 					    sizeof (mlp));
15979 			}
15980 		}
15981 	}
15982 
15983 	/* fixed length structure for IPv4 and IPv6 counters */
15984 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
15985 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
15986 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
15987 	optp->level = MIB2_TCP;
15988 	optp->name = 0;
15989 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
15990 	optp->len = msgdsize(mpdata);
15991 	qreply(q, mpctl);
15992 
15993 	/* table of connections... */
15994 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
15995 	    sizeof (struct T_optmgmt_ack)];
15996 	optp->level = MIB2_TCP;
15997 	optp->name = MIB2_TCP_CONN;
15998 	optp->len = msgdsize(mp_conn_ctl->b_cont);
15999 	qreply(q, mp_conn_ctl);
16000 
16001 	/* table of MLP attributes... */
16002 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16003 	    sizeof (struct T_optmgmt_ack)];
16004 	optp->level = MIB2_TCP;
16005 	optp->name = EXPER_XPORT_MLP;
16006 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16007 	if (optp->len == 0)
16008 		freemsg(mp_attr_ctl);
16009 	else
16010 		qreply(q, mp_attr_ctl);
16011 
16012 	/* table of IPv6 connections... */
16013 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16014 	    sizeof (struct T_optmgmt_ack)];
16015 	optp->level = MIB2_TCP6;
16016 	optp->name = MIB2_TCP6_CONN;
16017 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16018 	qreply(q, mp6_conn_ctl);
16019 
16020 	/* table of IPv6 MLP attributes... */
16021 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16022 	    sizeof (struct T_optmgmt_ack)];
16023 	optp->level = MIB2_TCP6;
16024 	optp->name = EXPER_XPORT_MLP;
16025 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16026 	if (optp->len == 0)
16027 		freemsg(mp6_attr_ctl);
16028 	else
16029 		qreply(q, mp6_attr_ctl);
16030 	return (1);
16031 }
16032 
16033 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16034 /* ARGSUSED */
16035 int
16036 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16037 {
16038 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16039 
16040 	switch (level) {
16041 	case MIB2_TCP:
16042 		switch (name) {
16043 		case 13:
16044 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16045 				return (0);
16046 			/* TODO: delete entry defined by tce */
16047 			return (1);
16048 		default:
16049 			return (0);
16050 		}
16051 	default:
16052 		return (1);
16053 	}
16054 }
16055 
16056 /* Translate TCP state to MIB2 TCP state. */
16057 static int
16058 tcp_snmp_state(tcp_t *tcp)
16059 {
16060 	if (tcp == NULL)
16061 		return (0);
16062 
16063 	switch (tcp->tcp_state) {
16064 	case TCPS_CLOSED:
16065 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16066 	case TCPS_BOUND:
16067 		return (MIB2_TCP_closed);
16068 	case TCPS_LISTEN:
16069 		return (MIB2_TCP_listen);
16070 	case TCPS_SYN_SENT:
16071 		return (MIB2_TCP_synSent);
16072 	case TCPS_SYN_RCVD:
16073 		return (MIB2_TCP_synReceived);
16074 	case TCPS_ESTABLISHED:
16075 		return (MIB2_TCP_established);
16076 	case TCPS_CLOSE_WAIT:
16077 		return (MIB2_TCP_closeWait);
16078 	case TCPS_FIN_WAIT_1:
16079 		return (MIB2_TCP_finWait1);
16080 	case TCPS_CLOSING:
16081 		return (MIB2_TCP_closing);
16082 	case TCPS_LAST_ACK:
16083 		return (MIB2_TCP_lastAck);
16084 	case TCPS_FIN_WAIT_2:
16085 		return (MIB2_TCP_finWait2);
16086 	case TCPS_TIME_WAIT:
16087 		return (MIB2_TCP_timeWait);
16088 	default:
16089 		return (0);
16090 	}
16091 }
16092 
16093 static char tcp_report_header[] =
16094 	"TCP     " MI_COL_HDRPAD_STR
16095 	"zone dest            snxt     suna     "
16096 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16097 	"recent   [lport,fport] state";
16098 
16099 /*
16100  * TCP status report triggered via the Named Dispatch mechanism.
16101  */
16102 /* ARGSUSED */
16103 static void
16104 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16105     cred_t *cr)
16106 {
16107 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16108 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
16109 	char cflag;
16110 	in6_addr_t	v6dst;
16111 	char buf[80];
16112 	uint_t print_len, buf_len;
16113 
16114 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16115 	if (buf_len <= 0)
16116 		return;
16117 
16118 	if (hashval >= 0)
16119 		(void) sprintf(hash, "%03d ", hashval);
16120 	else
16121 		hash[0] = '\0';
16122 
16123 	/*
16124 	 * Note that we use the remote address in the tcp_b  structure.
16125 	 * This means that it will print out the real destination address,
16126 	 * not the next hop's address if source routing is used.  This
16127 	 * avoid the confusion on the output because user may not
16128 	 * know that source routing is used for a connection.
16129 	 */
16130 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16131 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16132 	} else {
16133 		v6dst = tcp->tcp_remote_v6;
16134 	}
16135 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16136 	/*
16137 	 * the ispriv checks are so that normal users cannot determine
16138 	 * sequence number information using NDD.
16139 	 */
16140 
16141 	if (TCP_IS_DETACHED(tcp))
16142 		cflag = '*';
16143 	else
16144 		cflag = ' ';
16145 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16146 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16147 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16148 	    hash,
16149 	    (void *)tcp,
16150 	    tcp->tcp_connp->conn_zoneid,
16151 	    addrbuf,
16152 	    (ispriv) ? tcp->tcp_snxt : 0,
16153 	    (ispriv) ? tcp->tcp_suna : 0,
16154 	    tcp->tcp_swnd,
16155 	    (ispriv) ? tcp->tcp_rnxt : 0,
16156 	    (ispriv) ? tcp->tcp_rack : 0,
16157 	    tcp->tcp_rwnd,
16158 	    tcp->tcp_rto,
16159 	    tcp->tcp_mss,
16160 	    tcp->tcp_snd_ws_ok,
16161 	    tcp->tcp_snd_ws,
16162 	    tcp->tcp_rcv_ws,
16163 	    tcp->tcp_snd_ts_ok,
16164 	    tcp->tcp_ts_recent,
16165 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16166 	if (print_len < buf_len) {
16167 		((mblk_t *)mp)->b_wptr += print_len;
16168 	} else {
16169 		((mblk_t *)mp)->b_wptr += buf_len;
16170 	}
16171 }
16172 
16173 /*
16174  * TCP status report (for listeners only) triggered via the Named Dispatch
16175  * mechanism.
16176  */
16177 /* ARGSUSED */
16178 static void
16179 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16180 {
16181 	char addrbuf[INET6_ADDRSTRLEN];
16182 	in6_addr_t	v6dst;
16183 	uint_t print_len, buf_len;
16184 
16185 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16186 	if (buf_len <= 0)
16187 		return;
16188 
16189 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16190 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16191 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16192 	} else {
16193 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16194 		    addrbuf, sizeof (addrbuf));
16195 	}
16196 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16197 	    "%03d "
16198 	    MI_COL_PTRFMT_STR
16199 	    "%d %s %05u %08u %d/%d/%d%c\n",
16200 	    hashval, (void *)tcp,
16201 	    tcp->tcp_connp->conn_zoneid,
16202 	    addrbuf,
16203 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16204 	    tcp->tcp_conn_req_seqnum,
16205 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16206 	    tcp->tcp_conn_req_max,
16207 	    tcp->tcp_syn_defense ? '*' : ' ');
16208 	if (print_len < buf_len) {
16209 		((mblk_t *)mp)->b_wptr += print_len;
16210 	} else {
16211 		((mblk_t *)mp)->b_wptr += buf_len;
16212 	}
16213 }
16214 
16215 /* TCP status report triggered via the Named Dispatch mechanism. */
16216 /* ARGSUSED */
16217 static int
16218 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16219 {
16220 	tcp_t	*tcp;
16221 	int	i;
16222 	conn_t	*connp;
16223 	connf_t	*connfp;
16224 	zoneid_t zoneid;
16225 
16226 	/*
16227 	 * Because of the ndd constraint, at most we can have 64K buffer
16228 	 * to put in all TCP info.  So to be more efficient, just
16229 	 * allocate a 64K buffer here, assuming we need that large buffer.
16230 	 * This may be a problem as any user can read tcp_status.  Therefore
16231 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16232 	 * This should be OK as normal users should not do this too often.
16233 	 */
16234 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16235 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16236 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16237 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16238 			return (0);
16239 		}
16240 	}
16241 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16242 		/* The following may work even if we cannot get a large buf. */
16243 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16244 		return (0);
16245 	}
16246 
16247 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16248 
16249 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16250 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16251 
16252 		connfp = &ipcl_globalhash_fanout[i];
16253 
16254 		connp = NULL;
16255 
16256 		while ((connp =
16257 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16258 			tcp = connp->conn_tcp;
16259 			if (zoneid != GLOBAL_ZONEID &&
16260 			    zoneid != connp->conn_zoneid)
16261 				continue;
16262 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16263 			    cr);
16264 		}
16265 
16266 	}
16267 
16268 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16269 	return (0);
16270 }
16271 
16272 /* TCP status report triggered via the Named Dispatch mechanism. */
16273 /* ARGSUSED */
16274 static int
16275 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16276 {
16277 	tf_t	*tbf;
16278 	tcp_t	*tcp;
16279 	int	i;
16280 	zoneid_t zoneid;
16281 
16282 	/* Refer to comments in tcp_status_report(). */
16283 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16284 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16285 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16286 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16287 			return (0);
16288 		}
16289 	}
16290 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16291 		/* The following may work even if we cannot get a large buf. */
16292 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16293 		return (0);
16294 	}
16295 
16296 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16297 
16298 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16299 
16300 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
16301 		tbf = &tcp_bind_fanout[i];
16302 		mutex_enter(&tbf->tf_lock);
16303 		for (tcp = tbf->tf_tcp; tcp != NULL;
16304 		    tcp = tcp->tcp_bind_hash) {
16305 			if (zoneid != GLOBAL_ZONEID &&
16306 			    zoneid != tcp->tcp_connp->conn_zoneid)
16307 				continue;
16308 			CONN_INC_REF(tcp->tcp_connp);
16309 			tcp_report_item(mp->b_cont, tcp, i,
16310 			    Q_TO_TCP(q), cr);
16311 			CONN_DEC_REF(tcp->tcp_connp);
16312 		}
16313 		mutex_exit(&tbf->tf_lock);
16314 	}
16315 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16316 	return (0);
16317 }
16318 
16319 /* TCP status report triggered via the Named Dispatch mechanism. */
16320 /* ARGSUSED */
16321 static int
16322 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16323 {
16324 	connf_t	*connfp;
16325 	conn_t	*connp;
16326 	tcp_t	*tcp;
16327 	int	i;
16328 	zoneid_t zoneid;
16329 
16330 	/* Refer to comments in tcp_status_report(). */
16331 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16332 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16333 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16334 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16335 			return (0);
16336 		}
16337 	}
16338 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16339 		/* The following may work even if we cannot get a large buf. */
16340 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16341 		return (0);
16342 	}
16343 
16344 	(void) mi_mpprintf(mp,
16345 	    "    TCP    " MI_COL_HDRPAD_STR
16346 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16347 
16348 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16349 
16350 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
16351 		connfp =  &ipcl_bind_fanout[i];
16352 		connp = NULL;
16353 		while ((connp =
16354 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16355 			tcp = connp->conn_tcp;
16356 			if (zoneid != GLOBAL_ZONEID &&
16357 			    zoneid != connp->conn_zoneid)
16358 				continue;
16359 			tcp_report_listener(mp->b_cont, tcp, i);
16360 		}
16361 	}
16362 
16363 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16364 	return (0);
16365 }
16366 
16367 /* TCP status report triggered via the Named Dispatch mechanism. */
16368 /* ARGSUSED */
16369 static int
16370 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16371 {
16372 	connf_t	*connfp;
16373 	conn_t	*connp;
16374 	tcp_t	*tcp;
16375 	int	i;
16376 	zoneid_t zoneid;
16377 
16378 	/* Refer to comments in tcp_status_report(). */
16379 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16380 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16381 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16382 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16383 			return (0);
16384 		}
16385 	}
16386 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16387 		/* The following may work even if we cannot get a large buf. */
16388 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16389 		return (0);
16390 	}
16391 
16392 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16393 	    ipcl_conn_fanout_size);
16394 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16395 
16396 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16397 
16398 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
16399 		connfp =  &ipcl_conn_fanout[i];
16400 		connp = NULL;
16401 		while ((connp =
16402 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16403 			tcp = connp->conn_tcp;
16404 			if (zoneid != GLOBAL_ZONEID &&
16405 			    zoneid != connp->conn_zoneid)
16406 				continue;
16407 			tcp_report_item(mp->b_cont, tcp, i,
16408 			    Q_TO_TCP(q), cr);
16409 		}
16410 	}
16411 
16412 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16413 	return (0);
16414 }
16415 
16416 /* TCP status report triggered via the Named Dispatch mechanism. */
16417 /* ARGSUSED */
16418 static int
16419 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16420 {
16421 	tf_t	*tf;
16422 	tcp_t	*tcp;
16423 	int	i;
16424 	zoneid_t zoneid;
16425 
16426 	/* Refer to comments in tcp_status_report(). */
16427 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16428 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16429 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16430 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16431 			return (0);
16432 		}
16433 	}
16434 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16435 		/* The following may work even if we cannot get a large buf. */
16436 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16437 		return (0);
16438 	}
16439 
16440 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16441 
16442 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16443 
16444 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16445 		tf = &tcp_acceptor_fanout[i];
16446 		mutex_enter(&tf->tf_lock);
16447 		for (tcp = tf->tf_tcp; tcp != NULL;
16448 		    tcp = tcp->tcp_acceptor_hash) {
16449 			if (zoneid != GLOBAL_ZONEID &&
16450 			    zoneid != tcp->tcp_connp->conn_zoneid)
16451 				continue;
16452 			tcp_report_item(mp->b_cont, tcp, i,
16453 			    Q_TO_TCP(q), cr);
16454 		}
16455 		mutex_exit(&tf->tf_lock);
16456 	}
16457 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16458 	return (0);
16459 }
16460 
16461 /*
16462  * tcp_timer is the timer service routine.  It handles the retransmission,
16463  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16464  * from the state of the tcp instance what kind of action needs to be done
16465  * at the time it is called.
16466  */
16467 static void
16468 tcp_timer(void *arg)
16469 {
16470 	mblk_t		*mp;
16471 	clock_t		first_threshold;
16472 	clock_t		second_threshold;
16473 	clock_t		ms;
16474 	uint32_t	mss;
16475 	conn_t		*connp = (conn_t *)arg;
16476 	tcp_t		*tcp = connp->conn_tcp;
16477 
16478 	tcp->tcp_timer_tid = 0;
16479 
16480 	if (tcp->tcp_fused)
16481 		return;
16482 
16483 	first_threshold =  tcp->tcp_first_timer_threshold;
16484 	second_threshold = tcp->tcp_second_timer_threshold;
16485 	switch (tcp->tcp_state) {
16486 	case TCPS_IDLE:
16487 	case TCPS_BOUND:
16488 	case TCPS_LISTEN:
16489 		return;
16490 	case TCPS_SYN_RCVD: {
16491 		tcp_t	*listener = tcp->tcp_listener;
16492 
16493 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16494 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16495 			/* it's our first timeout */
16496 			tcp->tcp_syn_rcvd_timeout = 1;
16497 			mutex_enter(&listener->tcp_eager_lock);
16498 			listener->tcp_syn_rcvd_timeout++;
16499 			if (!listener->tcp_syn_defense &&
16500 			    (listener->tcp_syn_rcvd_timeout >
16501 			    (tcp_conn_req_max_q0 >> 2)) &&
16502 			    (tcp_conn_req_max_q0 > 200)) {
16503 				/* We may be under attack. Put on a defense. */
16504 				listener->tcp_syn_defense = B_TRUE;
16505 				cmn_err(CE_WARN, "High TCP connect timeout "
16506 				    "rate! System (port %d) may be under a "
16507 				    "SYN flood attack!",
16508 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16509 
16510 				listener->tcp_ip_addr_cache = kmem_zalloc(
16511 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16512 				    KM_NOSLEEP);
16513 			}
16514 			mutex_exit(&listener->tcp_eager_lock);
16515 		}
16516 	}
16517 		/* FALLTHRU */
16518 	case TCPS_SYN_SENT:
16519 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16520 		second_threshold = tcp->tcp_second_ctimer_threshold;
16521 		break;
16522 	case TCPS_ESTABLISHED:
16523 	case TCPS_FIN_WAIT_1:
16524 	case TCPS_CLOSING:
16525 	case TCPS_CLOSE_WAIT:
16526 	case TCPS_LAST_ACK:
16527 		/* If we have data to rexmit */
16528 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16529 			clock_t	time_to_wait;
16530 
16531 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16532 			if (!tcp->tcp_xmit_head)
16533 				break;
16534 			time_to_wait = lbolt -
16535 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16536 			time_to_wait = tcp->tcp_rto -
16537 			    TICK_TO_MSEC(time_to_wait);
16538 			/*
16539 			 * If the timer fires too early, 1 clock tick earlier,
16540 			 * restart the timer.
16541 			 */
16542 			if (time_to_wait > msec_per_tick) {
16543 				TCP_STAT(tcp_timer_fire_early);
16544 				TCP_TIMER_RESTART(tcp, time_to_wait);
16545 				return;
16546 			}
16547 			/*
16548 			 * When we probe zero windows, we force the swnd open.
16549 			 * If our peer acks with a closed window swnd will be
16550 			 * set to zero by tcp_rput(). As long as we are
16551 			 * receiving acks tcp_rput will
16552 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16553 			 * first and second interval actions.  NOTE: the timer
16554 			 * interval is allowed to continue its exponential
16555 			 * backoff.
16556 			 */
16557 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16558 				if (tcp->tcp_debug) {
16559 					(void) strlog(TCP_MOD_ID, 0, 1,
16560 					    SL_TRACE, "tcp_timer: zero win");
16561 				}
16562 			} else {
16563 				/*
16564 				 * After retransmission, we need to do
16565 				 * slow start.  Set the ssthresh to one
16566 				 * half of current effective window and
16567 				 * cwnd to one MSS.  Also reset
16568 				 * tcp_cwnd_cnt.
16569 				 *
16570 				 * Note that if tcp_ssthresh is reduced because
16571 				 * of ECN, do not reduce it again unless it is
16572 				 * already one window of data away (tcp_cwr
16573 				 * should then be cleared) or this is a
16574 				 * timeout for a retransmitted segment.
16575 				 */
16576 				uint32_t npkt;
16577 
16578 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16579 					npkt = ((tcp->tcp_timer_backoff ?
16580 					    tcp->tcp_cwnd_ssthresh :
16581 					    tcp->tcp_snxt -
16582 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16583 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16584 					    tcp->tcp_mss;
16585 				}
16586 				tcp->tcp_cwnd = tcp->tcp_mss;
16587 				tcp->tcp_cwnd_cnt = 0;
16588 				if (tcp->tcp_ecn_ok) {
16589 					tcp->tcp_cwr = B_TRUE;
16590 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16591 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16592 				}
16593 			}
16594 			break;
16595 		}
16596 		/*
16597 		 * We have something to send yet we cannot send.  The
16598 		 * reason can be:
16599 		 *
16600 		 * 1. Zero send window: we need to do zero window probe.
16601 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16602 		 * segments.
16603 		 * 3. SWS avoidance: receiver may have shrunk window,
16604 		 * reset our knowledge.
16605 		 *
16606 		 * Note that condition 2 can happen with either 1 or
16607 		 * 3.  But 1 and 3 are exclusive.
16608 		 */
16609 		if (tcp->tcp_unsent != 0) {
16610 			if (tcp->tcp_cwnd == 0) {
16611 				/*
16612 				 * Set tcp_cwnd to 1 MSS so that a
16613 				 * new segment can be sent out.  We
16614 				 * are "clocking out" new data when
16615 				 * the network is really congested.
16616 				 */
16617 				ASSERT(tcp->tcp_ecn_ok);
16618 				tcp->tcp_cwnd = tcp->tcp_mss;
16619 			}
16620 			if (tcp->tcp_swnd == 0) {
16621 				/* Extend window for zero window probe */
16622 				tcp->tcp_swnd++;
16623 				tcp->tcp_zero_win_probe = B_TRUE;
16624 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
16625 			} else {
16626 				/*
16627 				 * Handle timeout from sender SWS avoidance.
16628 				 * Reset our knowledge of the max send window
16629 				 * since the receiver might have reduced its
16630 				 * receive buffer.  Avoid setting tcp_max_swnd
16631 				 * to one since that will essentially disable
16632 				 * the SWS checks.
16633 				 *
16634 				 * Note that since we don't have a SWS
16635 				 * state variable, if the timeout is set
16636 				 * for ECN but not for SWS, this
16637 				 * code will also be executed.  This is
16638 				 * fine as tcp_max_swnd is updated
16639 				 * constantly and it will not affect
16640 				 * anything.
16641 				 */
16642 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16643 			}
16644 			tcp_wput_data(tcp, NULL, B_FALSE);
16645 			return;
16646 		}
16647 		/* Is there a FIN that needs to be to re retransmitted? */
16648 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16649 		    !tcp->tcp_fin_acked)
16650 			break;
16651 		/* Nothing to do, return without restarting timer. */
16652 		TCP_STAT(tcp_timer_fire_miss);
16653 		return;
16654 	case TCPS_FIN_WAIT_2:
16655 		/*
16656 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16657 		 * We waited some time for for peer's FIN, but it hasn't
16658 		 * arrived.  We flush the connection now to avoid
16659 		 * case where the peer has rebooted.
16660 		 */
16661 		if (TCP_IS_DETACHED(tcp)) {
16662 			(void) tcp_clean_death(tcp, 0, 23);
16663 		} else {
16664 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
16665 		}
16666 		return;
16667 	case TCPS_TIME_WAIT:
16668 		(void) tcp_clean_death(tcp, 0, 24);
16669 		return;
16670 	default:
16671 		if (tcp->tcp_debug) {
16672 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16673 			    "tcp_timer: strange state (%d) %s",
16674 			    tcp->tcp_state, tcp_display(tcp, NULL,
16675 			    DISP_PORT_ONLY));
16676 		}
16677 		return;
16678 	}
16679 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16680 		/*
16681 		 * For zero window probe, we need to send indefinitely,
16682 		 * unless we have not heard from the other side for some
16683 		 * time...
16684 		 */
16685 		if ((tcp->tcp_zero_win_probe == 0) ||
16686 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16687 		    second_threshold)) {
16688 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
16689 			/*
16690 			 * If TCP is in SYN_RCVD state, send back a
16691 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16692 			 * should be zero in TCPS_SYN_RCVD state.
16693 			 */
16694 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16695 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16696 				    "in SYN_RCVD",
16697 				    tcp, tcp->tcp_snxt,
16698 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16699 			}
16700 			(void) tcp_clean_death(tcp,
16701 			    tcp->tcp_client_errno ?
16702 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16703 			return;
16704 		} else {
16705 			/*
16706 			 * Set tcp_ms_we_have_waited to second_threshold
16707 			 * so that in next timeout, we will do the above
16708 			 * check (lbolt - tcp_last_recv_time).  This is
16709 			 * also to avoid overflow.
16710 			 *
16711 			 * We don't need to decrement tcp_timer_backoff
16712 			 * to avoid overflow because it will be decremented
16713 			 * later if new timeout value is greater than
16714 			 * tcp_rexmit_interval_max.  In the case when
16715 			 * tcp_rexmit_interval_max is greater than
16716 			 * second_threshold, it means that we will wait
16717 			 * longer than second_threshold to send the next
16718 			 * window probe.
16719 			 */
16720 			tcp->tcp_ms_we_have_waited = second_threshold;
16721 		}
16722 	} else if (ms > first_threshold) {
16723 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16724 		    tcp->tcp_xmit_head != NULL) {
16725 			tcp->tcp_xmit_head =
16726 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16727 		}
16728 		/*
16729 		 * We have been retransmitting for too long...  The RTT
16730 		 * we calculated is probably incorrect.  Reinitialize it.
16731 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16732 		 * tcp_rtt_update so that we won't accidentally cache a
16733 		 * bad value.  But only do this if this is not a zero
16734 		 * window probe.
16735 		 */
16736 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16737 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16738 			    (tcp->tcp_rtt_sa >> 5);
16739 			tcp->tcp_rtt_sa = 0;
16740 			tcp_ip_notify(tcp);
16741 			tcp->tcp_rtt_update = 0;
16742 		}
16743 	}
16744 	tcp->tcp_timer_backoff++;
16745 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16746 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16747 	    tcp_rexmit_interval_min) {
16748 		/*
16749 		 * This means the original RTO is tcp_rexmit_interval_min.
16750 		 * So we will use tcp_rexmit_interval_min as the RTO value
16751 		 * and do the backoff.
16752 		 */
16753 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
16754 	} else {
16755 		ms <<= tcp->tcp_timer_backoff;
16756 	}
16757 	if (ms > tcp_rexmit_interval_max) {
16758 		ms = tcp_rexmit_interval_max;
16759 		/*
16760 		 * ms is at max, decrement tcp_timer_backoff to avoid
16761 		 * overflow.
16762 		 */
16763 		tcp->tcp_timer_backoff--;
16764 	}
16765 	tcp->tcp_ms_we_have_waited += ms;
16766 	if (tcp->tcp_zero_win_probe == 0) {
16767 		tcp->tcp_rto = ms;
16768 	}
16769 	TCP_TIMER_RESTART(tcp, ms);
16770 	/*
16771 	 * This is after a timeout and tcp_rto is backed off.  Set
16772 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16773 	 * restart the timer with a correct value.
16774 	 */
16775 	tcp->tcp_set_timer = 1;
16776 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16777 	if (mss > tcp->tcp_mss)
16778 		mss = tcp->tcp_mss;
16779 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16780 		mss = tcp->tcp_swnd;
16781 
16782 	if ((mp = tcp->tcp_xmit_head) != NULL)
16783 		mp->b_prev = (mblk_t *)lbolt;
16784 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16785 	    B_TRUE);
16786 
16787 	/*
16788 	 * When slow start after retransmission begins, start with
16789 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16790 	 * start phase.  tcp_snd_burst controls how many segments
16791 	 * can be sent because of an ack.
16792 	 */
16793 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16794 	tcp->tcp_snd_burst = TCP_CWND_SS;
16795 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16796 	    (tcp->tcp_unsent == 0)) {
16797 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16798 	} else {
16799 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16800 	}
16801 	tcp->tcp_rexmit = B_TRUE;
16802 	tcp->tcp_dupack_cnt = 0;
16803 
16804 	/*
16805 	 * Remove all rexmit SACK blk to start from fresh.
16806 	 */
16807 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16808 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16809 		tcp->tcp_num_notsack_blk = 0;
16810 		tcp->tcp_cnt_notsack_list = 0;
16811 	}
16812 	if (mp == NULL) {
16813 		return;
16814 	}
16815 	/* Attach credentials to retransmitted initial SYNs. */
16816 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16817 		mblk_setcred(mp, tcp->tcp_cred);
16818 		DB_CPID(mp) = tcp->tcp_cpid;
16819 	}
16820 
16821 	tcp->tcp_csuna = tcp->tcp_snxt;
16822 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
16823 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
16824 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
16825 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16826 
16827 }
16828 
16829 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16830 static void
16831 tcp_unbind(tcp_t *tcp, mblk_t *mp)
16832 {
16833 	conn_t	*connp;
16834 
16835 	switch (tcp->tcp_state) {
16836 	case TCPS_BOUND:
16837 	case TCPS_LISTEN:
16838 		break;
16839 	default:
16840 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
16841 		return;
16842 	}
16843 
16844 	/*
16845 	 * Need to clean up all the eagers since after the unbind, segments
16846 	 * will no longer be delivered to this listener stream.
16847 	 */
16848 	mutex_enter(&tcp->tcp_eager_lock);
16849 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16850 		tcp_eager_cleanup(tcp, 0);
16851 	}
16852 	mutex_exit(&tcp->tcp_eager_lock);
16853 
16854 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16855 		tcp->tcp_ipha->ipha_src = 0;
16856 	} else {
16857 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16858 	}
16859 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16860 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16861 	tcp_bind_hash_remove(tcp);
16862 	tcp->tcp_state = TCPS_IDLE;
16863 	tcp->tcp_mdt = B_FALSE;
16864 	/* Send M_FLUSH according to TPI */
16865 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16866 	connp = tcp->tcp_connp;
16867 	connp->conn_mdt_ok = B_FALSE;
16868 	ipcl_hash_remove(connp);
16869 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16870 	mp = mi_tpi_ok_ack_alloc(mp);
16871 	putnext(tcp->tcp_rq, mp);
16872 }
16873 
16874 /*
16875  * Don't let port fall into the privileged range.
16876  * Since the extra privileged ports can be arbitrary we also
16877  * ensure that we exclude those from consideration.
16878  * tcp_g_epriv_ports is not sorted thus we loop over it until
16879  * there are no changes.
16880  *
16881  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16882  * but instead the code relies on:
16883  * - the fact that the address of the array and its size never changes
16884  * - the atomic assignment of the elements of the array
16885  *
16886  * Returns 0 if there are no more ports available.
16887  *
16888  * TS note: skip multilevel ports.
16889  */
16890 static in_port_t
16891 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16892 {
16893 	int i;
16894 	boolean_t restart = B_FALSE;
16895 
16896 	if (random && tcp_random_anon_port != 0) {
16897 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16898 		    sizeof (in_port_t));
16899 		/*
16900 		 * Unless changed by a sys admin, the smallest anon port
16901 		 * is 32768 and the largest anon port is 65535.  It is
16902 		 * very likely (50%) for the random port to be smaller
16903 		 * than the smallest anon port.  When that happens,
16904 		 * add port % (anon port range) to the smallest anon
16905 		 * port to get the random port.  It should fall into the
16906 		 * valid anon port range.
16907 		 */
16908 		if (port < tcp_smallest_anon_port) {
16909 			port = tcp_smallest_anon_port +
16910 			    port % (tcp_largest_anon_port -
16911 				tcp_smallest_anon_port);
16912 		}
16913 	}
16914 
16915 retry:
16916 	if (port < tcp_smallest_anon_port)
16917 		port = (in_port_t)tcp_smallest_anon_port;
16918 
16919 	if (port > tcp_largest_anon_port) {
16920 		if (restart)
16921 			return (0);
16922 		restart = B_TRUE;
16923 		port = (in_port_t)tcp_smallest_anon_port;
16924 	}
16925 
16926 	if (port < tcp_smallest_nonpriv_port)
16927 		port = (in_port_t)tcp_smallest_nonpriv_port;
16928 
16929 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
16930 		if (port == tcp_g_epriv_ports[i]) {
16931 			port++;
16932 			/*
16933 			 * Make sure whether the port is in the
16934 			 * valid range.
16935 			 */
16936 			goto retry;
16937 		}
16938 	}
16939 	if (is_system_labeled() &&
16940 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
16941 	    IPPROTO_TCP, B_TRUE)) != 0) {
16942 		port = i;
16943 		goto retry;
16944 	}
16945 	return (port);
16946 }
16947 
16948 /*
16949  * Return the next anonymous port in the privileged port range for
16950  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16951  * downwards.  This is the same behavior as documented in the userland
16952  * library call rresvport(3N).
16953  *
16954  * TS note: skip multilevel ports.
16955  */
16956 static in_port_t
16957 tcp_get_next_priv_port(const tcp_t *tcp)
16958 {
16959 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16960 	in_port_t nextport;
16961 	boolean_t restart = B_FALSE;
16962 
16963 retry:
16964 	if (next_priv_port < tcp_min_anonpriv_port ||
16965 	    next_priv_port >= IPPORT_RESERVED) {
16966 		next_priv_port = IPPORT_RESERVED - 1;
16967 		if (restart)
16968 			return (0);
16969 		restart = B_TRUE;
16970 	}
16971 	if (is_system_labeled() &&
16972 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
16973 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
16974 		next_priv_port = nextport;
16975 		goto retry;
16976 	}
16977 	return (next_priv_port--);
16978 }
16979 
16980 /* The write side r/w procedure. */
16981 
16982 #if CCS_STATS
16983 struct {
16984 	struct {
16985 		int64_t count, bytes;
16986 	} tot, hit;
16987 } wrw_stats;
16988 #endif
16989 
16990 /*
16991  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16992  * messages.
16993  */
16994 /* ARGSUSED */
16995 static void
16996 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16997 {
16998 	conn_t	*connp = (conn_t *)arg;
16999 	tcp_t	*tcp = connp->conn_tcp;
17000 	queue_t	*q = tcp->tcp_wq;
17001 
17002 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17003 	/*
17004 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17005 	 * Once the close starts, streamhead and sockfs will not let any data
17006 	 * packets come down (close ensures that there are no threads using the
17007 	 * queue and no new threads will come down) but since qprocsoff()
17008 	 * hasn't happened yet, a M_FLUSH or some non data message might
17009 	 * get reflected back (in response to our own FLUSHRW) and get
17010 	 * processed after tcp_close() is done. The conn would still be valid
17011 	 * because a ref would have added but we need to check the state
17012 	 * before actually processing the packet.
17013 	 */
17014 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17015 		freemsg(mp);
17016 		return;
17017 	}
17018 
17019 	switch (DB_TYPE(mp)) {
17020 	case M_IOCDATA:
17021 		tcp_wput_iocdata(tcp, mp);
17022 		break;
17023 	case M_FLUSH:
17024 		tcp_wput_flush(tcp, mp);
17025 		break;
17026 	default:
17027 		CALL_IP_WPUT(connp, q, mp);
17028 		break;
17029 	}
17030 }
17031 
17032 /*
17033  * The TCP fast path write put procedure.
17034  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17035  */
17036 /* ARGSUSED */
17037 void
17038 tcp_output(void *arg, mblk_t *mp, void *arg2)
17039 {
17040 	int		len;
17041 	int		hdrlen;
17042 	int		plen;
17043 	mblk_t		*mp1;
17044 	uchar_t		*rptr;
17045 	uint32_t	snxt;
17046 	tcph_t		*tcph;
17047 	struct datab	*db;
17048 	uint32_t	suna;
17049 	uint32_t	mss;
17050 	ipaddr_t	*dst;
17051 	ipaddr_t	*src;
17052 	uint32_t	sum;
17053 	int		usable;
17054 	conn_t		*connp = (conn_t *)arg;
17055 	tcp_t		*tcp = connp->conn_tcp;
17056 	uint32_t	msize;
17057 
17058 	/*
17059 	 * Try and ASSERT the minimum possible references on the
17060 	 * conn early enough. Since we are executing on write side,
17061 	 * the connection is obviously not detached and that means
17062 	 * there is a ref each for TCP and IP. Since we are behind
17063 	 * the squeue, the minimum references needed are 3. If the
17064 	 * conn is in classifier hash list, there should be an
17065 	 * extra ref for that (we check both the possibilities).
17066 	 */
17067 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17068 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17069 
17070 	ASSERT(DB_TYPE(mp) == M_DATA);
17071 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17072 
17073 	mutex_enter(&connp->conn_lock);
17074 	tcp->tcp_squeue_bytes -= msize;
17075 	mutex_exit(&connp->conn_lock);
17076 
17077 	/* Bypass tcp protocol for fused tcp loopback */
17078 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17079 		return;
17080 
17081 	mss = tcp->tcp_mss;
17082 	if (tcp->tcp_xmit_zc_clean)
17083 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17084 
17085 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17086 	len = (int)(mp->b_wptr - mp->b_rptr);
17087 
17088 	/*
17089 	 * Criteria for fast path:
17090 	 *
17091 	 *   1. no unsent data
17092 	 *   2. single mblk in request
17093 	 *   3. connection established
17094 	 *   4. data in mblk
17095 	 *   5. len <= mss
17096 	 *   6. no tcp_valid bits
17097 	 */
17098 	if ((tcp->tcp_unsent != 0) ||
17099 	    (tcp->tcp_cork) ||
17100 	    (mp->b_cont != NULL) ||
17101 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17102 	    (len == 0) ||
17103 	    (len > mss) ||
17104 	    (tcp->tcp_valid_bits != 0)) {
17105 		tcp_wput_data(tcp, mp, B_FALSE);
17106 		return;
17107 	}
17108 
17109 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17110 	ASSERT(tcp->tcp_fin_sent == 0);
17111 
17112 	/* queue new packet onto retransmission queue */
17113 	if (tcp->tcp_xmit_head == NULL) {
17114 		tcp->tcp_xmit_head = mp;
17115 	} else {
17116 		tcp->tcp_xmit_last->b_cont = mp;
17117 	}
17118 	tcp->tcp_xmit_last = mp;
17119 	tcp->tcp_xmit_tail = mp;
17120 
17121 	/* find out how much we can send */
17122 	/* BEGIN CSTYLED */
17123 	/*
17124 	 *    un-acked           usable
17125 	 *  |--------------|-----------------|
17126 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17127 	 */
17128 	/* END CSTYLED */
17129 
17130 	/* start sending from tcp_snxt */
17131 	snxt = tcp->tcp_snxt;
17132 
17133 	/*
17134 	 * Check to see if this connection has been idled for some
17135 	 * time and no ACK is expected.  If it is, we need to slow
17136 	 * start again to get back the connection's "self-clock" as
17137 	 * described in VJ's paper.
17138 	 *
17139 	 * Refer to the comment in tcp_mss_set() for the calculation
17140 	 * of tcp_cwnd after idle.
17141 	 */
17142 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17143 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17144 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
17145 	}
17146 
17147 	usable = tcp->tcp_swnd;		/* tcp window size */
17148 	if (usable > tcp->tcp_cwnd)
17149 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17150 	usable -= snxt;		/* subtract stuff already sent */
17151 	suna = tcp->tcp_suna;
17152 	usable += suna;
17153 	/* usable can be < 0 if the congestion window is smaller */
17154 	if (len > usable) {
17155 		/* Can't send complete M_DATA in one shot */
17156 		goto slow;
17157 	}
17158 
17159 	if (tcp->tcp_flow_stopped &&
17160 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17161 		tcp_clrqfull(tcp);
17162 	}
17163 
17164 	/*
17165 	 * determine if anything to send (Nagle).
17166 	 *
17167 	 *   1. len < tcp_mss (i.e. small)
17168 	 *   2. unacknowledged data present
17169 	 *   3. len < nagle limit
17170 	 *   4. last packet sent < nagle limit (previous packet sent)
17171 	 */
17172 	if ((len < mss) && (snxt != suna) &&
17173 	    (len < (int)tcp->tcp_naglim) &&
17174 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17175 		/*
17176 		 * This was the first unsent packet and normally
17177 		 * mss < xmit_hiwater so there is no need to worry
17178 		 * about flow control. The next packet will go
17179 		 * through the flow control check in tcp_wput_data().
17180 		 */
17181 		/* leftover work from above */
17182 		tcp->tcp_unsent = len;
17183 		tcp->tcp_xmit_tail_unsent = len;
17184 
17185 		return;
17186 	}
17187 
17188 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17189 
17190 	if (snxt == suna) {
17191 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17192 	}
17193 
17194 	/* we have always sent something */
17195 	tcp->tcp_rack_cnt = 0;
17196 
17197 	tcp->tcp_snxt = snxt + len;
17198 	tcp->tcp_rack = tcp->tcp_rnxt;
17199 
17200 	if ((mp1 = dupb(mp)) == 0)
17201 		goto no_memory;
17202 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17203 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17204 
17205 	/* adjust tcp header information */
17206 	tcph = tcp->tcp_tcph;
17207 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17208 
17209 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17210 	sum = (sum >> 16) + (sum & 0xFFFF);
17211 	U16_TO_ABE16(sum, tcph->th_sum);
17212 
17213 	U32_TO_ABE32(snxt, tcph->th_seq);
17214 
17215 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
17216 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
17217 	BUMP_LOCAL(tcp->tcp_obsegs);
17218 
17219 	/* Update the latest receive window size in TCP header. */
17220 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17221 	    tcph->th_win);
17222 
17223 	tcp->tcp_last_sent_len = (ushort_t)len;
17224 
17225 	plen = len + tcp->tcp_hdr_len;
17226 
17227 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17228 		tcp->tcp_ipha->ipha_length = htons(plen);
17229 	} else {
17230 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17231 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17232 	}
17233 
17234 	/* see if we need to allocate a mblk for the headers */
17235 	hdrlen = tcp->tcp_hdr_len;
17236 	rptr = mp1->b_rptr - hdrlen;
17237 	db = mp1->b_datap;
17238 	if ((db->db_ref != 2) || rptr < db->db_base ||
17239 	    (!OK_32PTR(rptr))) {
17240 		/* NOTE: we assume allocb returns an OK_32PTR */
17241 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17242 		    tcp_wroff_xtra, BPRI_MED);
17243 		if (!mp) {
17244 			freemsg(mp1);
17245 			goto no_memory;
17246 		}
17247 		mp->b_cont = mp1;
17248 		mp1 = mp;
17249 		/* Leave room for Link Level header */
17250 		/* hdrlen = tcp->tcp_hdr_len; */
17251 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
17252 		mp1->b_wptr = &rptr[hdrlen];
17253 	}
17254 	mp1->b_rptr = rptr;
17255 
17256 	/* Fill in the timestamp option. */
17257 	if (tcp->tcp_snd_ts_ok) {
17258 		U32_TO_BE32((uint32_t)lbolt,
17259 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17260 		U32_TO_BE32(tcp->tcp_ts_recent,
17261 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17262 	} else {
17263 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17264 	}
17265 
17266 	/* copy header into outgoing packet */
17267 	dst = (ipaddr_t *)rptr;
17268 	src = (ipaddr_t *)tcp->tcp_iphc;
17269 	dst[0] = src[0];
17270 	dst[1] = src[1];
17271 	dst[2] = src[2];
17272 	dst[3] = src[3];
17273 	dst[4] = src[4];
17274 	dst[5] = src[5];
17275 	dst[6] = src[6];
17276 	dst[7] = src[7];
17277 	dst[8] = src[8];
17278 	dst[9] = src[9];
17279 	if (hdrlen -= 40) {
17280 		hdrlen >>= 2;
17281 		dst += 10;
17282 		src += 10;
17283 		do {
17284 			*dst++ = *src++;
17285 		} while (--hdrlen);
17286 	}
17287 
17288 	/*
17289 	 * Set the ECN info in the TCP header.  Note that this
17290 	 * is not the template header.
17291 	 */
17292 	if (tcp->tcp_ecn_ok) {
17293 		SET_ECT(tcp, rptr);
17294 
17295 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17296 		if (tcp->tcp_ecn_echo_on)
17297 			tcph->th_flags[0] |= TH_ECE;
17298 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17299 			tcph->th_flags[0] |= TH_CWR;
17300 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17301 		}
17302 	}
17303 
17304 	if (tcp->tcp_ip_forward_progress) {
17305 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17306 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17307 		tcp->tcp_ip_forward_progress = B_FALSE;
17308 	}
17309 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17310 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17311 	return;
17312 
17313 	/*
17314 	 * If we ran out of memory, we pretend to have sent the packet
17315 	 * and that it was lost on the wire.
17316 	 */
17317 no_memory:
17318 	return;
17319 
17320 slow:
17321 	/* leftover work from above */
17322 	tcp->tcp_unsent = len;
17323 	tcp->tcp_xmit_tail_unsent = len;
17324 	tcp_wput_data(tcp, NULL, B_FALSE);
17325 }
17326 
17327 /*
17328  * The function called through squeue to get behind eager's perimeter to
17329  * finish the accept processing.
17330  */
17331 /* ARGSUSED */
17332 void
17333 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17334 {
17335 	conn_t			*connp = (conn_t *)arg;
17336 	tcp_t			*tcp = connp->conn_tcp;
17337 	queue_t			*q = tcp->tcp_rq;
17338 	mblk_t			*mp1;
17339 	mblk_t			*stropt_mp = mp;
17340 	struct  stroptions	*stropt;
17341 	uint_t			thwin;
17342 
17343 	/*
17344 	 * Drop the eager's ref on the listener, that was placed when
17345 	 * this eager began life in tcp_conn_request.
17346 	 */
17347 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17348 
17349 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17350 		/*
17351 		 * Someone blewoff the eager before we could finish
17352 		 * the accept.
17353 		 *
17354 		 * The only reason eager exists it because we put in
17355 		 * a ref on it when conn ind went up. We need to send
17356 		 * a disconnect indication up while the last reference
17357 		 * on the eager will be dropped by the squeue when we
17358 		 * return.
17359 		 */
17360 		ASSERT(tcp->tcp_listener == NULL);
17361 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17362 			struct	T_discon_ind	*tdi;
17363 
17364 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17365 			/*
17366 			 * Let us reuse the incoming mblk to avoid memory
17367 			 * allocation failure problems. We know that the
17368 			 * size of the incoming mblk i.e. stroptions is greater
17369 			 * than sizeof T_discon_ind. So the reallocb below
17370 			 * can't fail.
17371 			 */
17372 			freemsg(mp->b_cont);
17373 			mp->b_cont = NULL;
17374 			ASSERT(DB_REF(mp) == 1);
17375 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17376 			    B_FALSE);
17377 			ASSERT(mp != NULL);
17378 			DB_TYPE(mp) = M_PROTO;
17379 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17380 			tdi = (struct T_discon_ind *)mp->b_rptr;
17381 			if (tcp->tcp_issocket) {
17382 				tdi->DISCON_reason = ECONNREFUSED;
17383 				tdi->SEQ_number = 0;
17384 			} else {
17385 				tdi->DISCON_reason = ENOPROTOOPT;
17386 				tdi->SEQ_number =
17387 				    tcp->tcp_conn_req_seqnum;
17388 			}
17389 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17390 			putnext(q, mp);
17391 		} else {
17392 			freemsg(mp);
17393 		}
17394 		if (tcp->tcp_hard_binding) {
17395 			tcp->tcp_hard_binding = B_FALSE;
17396 			tcp->tcp_hard_bound = B_TRUE;
17397 		}
17398 		tcp->tcp_detached = B_FALSE;
17399 		return;
17400 	}
17401 
17402 	mp1 = stropt_mp->b_cont;
17403 	stropt_mp->b_cont = NULL;
17404 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17405 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17406 
17407 	while (mp1 != NULL) {
17408 		mp = mp1;
17409 		mp1 = mp1->b_cont;
17410 		mp->b_cont = NULL;
17411 		tcp->tcp_drop_opt_ack_cnt++;
17412 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17413 	}
17414 	mp = NULL;
17415 
17416 	/*
17417 	 * For a loopback connection with tcp_direct_sockfs on, note that
17418 	 * we don't have to protect tcp_rcv_list yet because synchronous
17419 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17420 	 * possibly race with us.
17421 	 */
17422 
17423 	/*
17424 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17425 	 * properly.  This is the first time we know of the acceptor'
17426 	 * queue.  So we do it here.
17427 	 */
17428 	if (tcp->tcp_rcv_list == NULL) {
17429 		/*
17430 		 * Recv queue is empty, tcp_rwnd should not have changed.
17431 		 * That means it should be equal to the listener's tcp_rwnd.
17432 		 */
17433 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17434 	} else {
17435 #ifdef DEBUG
17436 		uint_t cnt = 0;
17437 
17438 		mp1 = tcp->tcp_rcv_list;
17439 		while ((mp = mp1) != NULL) {
17440 			mp1 = mp->b_next;
17441 			cnt += msgdsize(mp);
17442 		}
17443 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17444 #endif
17445 		/* There is some data, add them back to get the max. */
17446 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17447 	}
17448 
17449 	stropt->so_flags = SO_HIWAT;
17450 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
17451 
17452 	stropt->so_flags |= SO_MAXBLK;
17453 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17454 
17455 	/*
17456 	 * This is the first time we run on the correct
17457 	 * queue after tcp_accept. So fix all the q parameters
17458 	 * here.
17459 	 */
17460 	/* Allocate room for SACK options if needed. */
17461 	stropt->so_flags |= SO_WROFF;
17462 	if (tcp->tcp_fused) {
17463 		ASSERT(tcp->tcp_loopback);
17464 		ASSERT(tcp->tcp_loopback_peer != NULL);
17465 		/*
17466 		 * For fused tcp loopback, set the stream head's write
17467 		 * offset value to zero since we won't be needing any room
17468 		 * for TCP/IP headers.  This would also improve performance
17469 		 * since it would reduce the amount of work done by kmem.
17470 		 * Non-fused tcp loopback case is handled separately below.
17471 		 */
17472 		stropt->so_wroff = 0;
17473 		/*
17474 		 * Record the stream head's high water mark for this endpoint;
17475 		 * this is used for flow-control purposes in tcp_fuse_output().
17476 		 */
17477 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17478 		/*
17479 		 * Update the peer's transmit parameters according to
17480 		 * our recently calculated high water mark value.
17481 		 */
17482 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17483 	} else if (tcp->tcp_snd_sack_ok) {
17484 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17485 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17486 	} else {
17487 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17488 		    tcp_wroff_xtra);
17489 	}
17490 
17491 	/*
17492 	 * If this is endpoint is handling SSL, then reserve extra
17493 	 * offset and space at the end.
17494 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17495 	 * overriding the previous setting. The extra cost of signing and
17496 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17497 	 * instead of a single contiguous one by the stream head
17498 	 * largely outweighs the statistical reduction of ACKs, when
17499 	 * applicable. The peer will also save on decyption and verification
17500 	 * costs.
17501 	 */
17502 	if (tcp->tcp_kssl_ctx != NULL) {
17503 		stropt->so_wroff += SSL3_WROFFSET;
17504 
17505 		stropt->so_flags |= SO_TAIL;
17506 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
17507 
17508 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
17509 	}
17510 
17511 	/* Send the options up */
17512 	putnext(q, stropt_mp);
17513 
17514 	/*
17515 	 * Pass up any data and/or a fin that has been received.
17516 	 *
17517 	 * Adjust receive window in case it had decreased
17518 	 * (because there is data <=> tcp_rcv_list != NULL)
17519 	 * while the connection was detached. Note that
17520 	 * in case the eager was flow-controlled, w/o this
17521 	 * code, the rwnd may never open up again!
17522 	 */
17523 	if (tcp->tcp_rcv_list != NULL) {
17524 		/* We drain directly in case of fused tcp loopback */
17525 		if (!tcp->tcp_fused && canputnext(q)) {
17526 			tcp->tcp_rwnd = q->q_hiwat;
17527 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17528 			    << tcp->tcp_rcv_ws;
17529 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17530 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17531 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17532 				tcp_xmit_ctl(NULL,
17533 				    tcp, (tcp->tcp_swnd == 0) ?
17534 				    tcp->tcp_suna : tcp->tcp_snxt,
17535 				    tcp->tcp_rnxt, TH_ACK);
17536 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17537 			}
17538 
17539 		}
17540 		(void) tcp_rcv_drain(q, tcp);
17541 
17542 		/*
17543 		 * For fused tcp loopback, back-enable peer endpoint
17544 		 * if it's currently flow-controlled.
17545 		 */
17546 		if (tcp->tcp_fused &&
17547 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17548 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17549 
17550 			ASSERT(peer_tcp != NULL);
17551 			ASSERT(peer_tcp->tcp_fused);
17552 
17553 			tcp_clrqfull(peer_tcp);
17554 			TCP_STAT(tcp_fusion_backenabled);
17555 		}
17556 	}
17557 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17558 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17559 		mp = mi_tpi_ordrel_ind();
17560 		if (mp) {
17561 			tcp->tcp_ordrel_done = B_TRUE;
17562 			putnext(q, mp);
17563 			if (tcp->tcp_deferred_clean_death) {
17564 				/*
17565 				 * tcp_clean_death was deferred
17566 				 * for T_ORDREL_IND - do it now
17567 				 */
17568 				(void) tcp_clean_death(tcp,
17569 				    tcp->tcp_client_errno, 21);
17570 				tcp->tcp_deferred_clean_death = B_FALSE;
17571 			}
17572 		} else {
17573 			/*
17574 			 * Run the orderly release in the
17575 			 * service routine.
17576 			 */
17577 			qenable(q);
17578 		}
17579 	}
17580 	if (tcp->tcp_hard_binding) {
17581 		tcp->tcp_hard_binding = B_FALSE;
17582 		tcp->tcp_hard_bound = B_TRUE;
17583 	}
17584 
17585 	tcp->tcp_detached = B_FALSE;
17586 
17587 	/* We can enable synchronous streams now */
17588 	if (tcp->tcp_fused) {
17589 		tcp_fuse_syncstr_enable_pair(tcp);
17590 	}
17591 
17592 	if (tcp->tcp_ka_enabled) {
17593 		tcp->tcp_ka_last_intrvl = 0;
17594 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17595 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17596 	}
17597 
17598 	/*
17599 	 * At this point, eager is fully established and will
17600 	 * have the following references -
17601 	 *
17602 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17603 	 * 1 reference for the squeue which will be dropped by the squeue as
17604 	 *	soon as this function returns.
17605 	 * There will be 1 additonal reference for being in classifier
17606 	 *	hash list provided something bad hasn't happened.
17607 	 */
17608 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17609 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17610 }
17611 
17612 /*
17613  * The function called through squeue to get behind listener's perimeter to
17614  * send a deffered conn_ind.
17615  */
17616 /* ARGSUSED */
17617 void
17618 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17619 {
17620 	conn_t	*connp = (conn_t *)arg;
17621 	tcp_t *listener = connp->conn_tcp;
17622 
17623 	if (listener->tcp_state == TCPS_CLOSED ||
17624 	    TCP_IS_DETACHED(listener)) {
17625 		/*
17626 		 * If listener has closed, it would have caused a
17627 		 * a cleanup/blowoff to happen for the eager.
17628 		 */
17629 		tcp_t *tcp;
17630 		struct T_conn_ind	*conn_ind;
17631 
17632 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
17633 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17634 		    conn_ind->OPT_length);
17635 		/*
17636 		 * We need to drop the ref on eager that was put
17637 		 * tcp_rput_data() before trying to send the conn_ind
17638 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17639 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17640 		 * listener is closed so we drop the ref.
17641 		 */
17642 		CONN_DEC_REF(tcp->tcp_connp);
17643 		freemsg(mp);
17644 		return;
17645 	}
17646 	putnext(listener->tcp_rq, mp);
17647 }
17648 
17649 
17650 /*
17651  * This is the STREAMS entry point for T_CONN_RES coming down on
17652  * Acceptor STREAM when  sockfs listener does accept processing.
17653  * Read the block comment on top pf tcp_conn_request().
17654  */
17655 void
17656 tcp_wput_accept(queue_t *q, mblk_t *mp)
17657 {
17658 	queue_t *rq = RD(q);
17659 	struct T_conn_res *conn_res;
17660 	tcp_t *eager;
17661 	tcp_t *listener;
17662 	struct T_ok_ack *ok;
17663 	t_scalar_t PRIM_type;
17664 	mblk_t *opt_mp;
17665 	conn_t *econnp;
17666 
17667 	ASSERT(DB_TYPE(mp) == M_PROTO);
17668 
17669 	conn_res = (struct T_conn_res *)mp->b_rptr;
17670 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17671 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17672 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17673 		if (mp != NULL)
17674 			putnext(rq, mp);
17675 		return;
17676 	}
17677 	switch (conn_res->PRIM_type) {
17678 	case O_T_CONN_RES:
17679 	case T_CONN_RES:
17680 		/*
17681 		 * We pass up an err ack if allocb fails. This will
17682 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17683 		 * tcp_eager_blowoff to be called. sockfs will then call
17684 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17685 		 * we need to do the allocb up here because we have to
17686 		 * make sure rq->q_qinfo->qi_qclose still points to the
17687 		 * correct function (tcpclose_accept) in case allocb
17688 		 * fails.
17689 		 */
17690 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17691 		if (opt_mp == NULL) {
17692 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17693 			if (mp != NULL)
17694 				putnext(rq, mp);
17695 			return;
17696 		}
17697 
17698 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17699 		    &eager, conn_res->OPT_length);
17700 		PRIM_type = conn_res->PRIM_type;
17701 		mp->b_datap->db_type = M_PCPROTO;
17702 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17703 		ok = (struct T_ok_ack *)mp->b_rptr;
17704 		ok->PRIM_type = T_OK_ACK;
17705 		ok->CORRECT_prim = PRIM_type;
17706 		econnp = eager->tcp_connp;
17707 		econnp->conn_dev = (dev_t)q->q_ptr;
17708 		eager->tcp_rq = rq;
17709 		eager->tcp_wq = q;
17710 		rq->q_ptr = econnp;
17711 		rq->q_qinfo = &tcp_rinit;
17712 		q->q_ptr = econnp;
17713 		q->q_qinfo = &tcp_winit;
17714 		listener = eager->tcp_listener;
17715 		eager->tcp_issocket = B_TRUE;
17716 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17717 
17718 		/* Put the ref for IP */
17719 		CONN_INC_REF(econnp);
17720 
17721 		/*
17722 		 * We should have minimum of 3 references on the conn
17723 		 * at this point. One each for TCP and IP and one for
17724 		 * the T_conn_ind that was sent up when the 3-way handshake
17725 		 * completed. In the normal case we would also have another
17726 		 * reference (making a total of 4) for the conn being in the
17727 		 * classifier hash list. However the eager could have received
17728 		 * an RST subsequently and tcp_closei_local could have removed
17729 		 * the eager from the classifier hash list, hence we can't
17730 		 * assert that reference.
17731 		 */
17732 		ASSERT(econnp->conn_ref >= 3);
17733 
17734 		/*
17735 		 * Send the new local address also up to sockfs. There
17736 		 * should already be enough space in the mp that came
17737 		 * down from soaccept().
17738 		 */
17739 		if (eager->tcp_family == AF_INET) {
17740 			sin_t *sin;
17741 
17742 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17743 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17744 			sin = (sin_t *)mp->b_wptr;
17745 			mp->b_wptr += sizeof (sin_t);
17746 			sin->sin_family = AF_INET;
17747 			sin->sin_port = eager->tcp_lport;
17748 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17749 		} else {
17750 			sin6_t *sin6;
17751 
17752 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17753 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17754 			sin6 = (sin6_t *)mp->b_wptr;
17755 			mp->b_wptr += sizeof (sin6_t);
17756 			sin6->sin6_family = AF_INET6;
17757 			sin6->sin6_port = eager->tcp_lport;
17758 			if (eager->tcp_ipversion == IPV4_VERSION) {
17759 				sin6->sin6_flowinfo = 0;
17760 				IN6_IPADDR_TO_V4MAPPED(
17761 					eager->tcp_ipha->ipha_src,
17762 					    &sin6->sin6_addr);
17763 			} else {
17764 				ASSERT(eager->tcp_ip6h != NULL);
17765 				sin6->sin6_flowinfo =
17766 				    eager->tcp_ip6h->ip6_vcf &
17767 				    ~IPV6_VERS_AND_FLOW_MASK;
17768 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17769 			}
17770 			sin6->sin6_scope_id = 0;
17771 			sin6->__sin6_src_id = 0;
17772 		}
17773 
17774 		putnext(rq, mp);
17775 
17776 		opt_mp->b_datap->db_type = M_SETOPTS;
17777 		opt_mp->b_wptr += sizeof (struct stroptions);
17778 
17779 		/*
17780 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17781 		 * from listener to acceptor. The message is chained on the
17782 		 * bind_mp which tcp_rput_other will send down to IP.
17783 		 */
17784 		if (listener->tcp_bound_if != 0) {
17785 			/* allocate optmgmt req */
17786 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17787 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
17788 			    sizeof (int));
17789 			if (mp != NULL)
17790 				linkb(opt_mp, mp);
17791 		}
17792 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17793 			uint_t on = 1;
17794 
17795 			/* allocate optmgmt req */
17796 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17797 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
17798 			if (mp != NULL)
17799 				linkb(opt_mp, mp);
17800 		}
17801 
17802 
17803 		mutex_enter(&listener->tcp_eager_lock);
17804 
17805 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17806 
17807 			tcp_t *tail;
17808 			tcp_t *tcp;
17809 			mblk_t *mp1;
17810 
17811 			tcp = listener->tcp_eager_prev_q0;
17812 			/*
17813 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
17814 			 * deferred T_conn_ind queue. We need to get to the head
17815 			 * of the queue in order to send up T_conn_ind the same
17816 			 * order as how the 3WHS is completed.
17817 			 */
17818 			while (tcp != listener) {
17819 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17820 				    !tcp->tcp_kssl_pending)
17821 					break;
17822 				else
17823 					tcp = tcp->tcp_eager_prev_q0;
17824 			}
17825 			/* None of the pending eagers can be sent up now */
17826 			if (tcp == listener)
17827 				goto no_more_eagers;
17828 
17829 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17830 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17831 			/* Move from q0 to q */
17832 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17833 			listener->tcp_conn_req_cnt_q0--;
17834 			listener->tcp_conn_req_cnt_q++;
17835 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17836 			    tcp->tcp_eager_prev_q0;
17837 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17838 			    tcp->tcp_eager_next_q0;
17839 			tcp->tcp_eager_prev_q0 = NULL;
17840 			tcp->tcp_eager_next_q0 = NULL;
17841 			tcp->tcp_conn_def_q0 = B_FALSE;
17842 
17843 			/*
17844 			 * Insert at end of the queue because sockfs sends
17845 			 * down T_CONN_RES in chronological order. Leaving
17846 			 * the older conn indications at front of the queue
17847 			 * helps reducing search time.
17848 			 */
17849 			tail = listener->tcp_eager_last_q;
17850 			if (tail != NULL) {
17851 				tail->tcp_eager_next_q = tcp;
17852 			} else {
17853 				listener->tcp_eager_next_q = tcp;
17854 			}
17855 			listener->tcp_eager_last_q = tcp;
17856 			tcp->tcp_eager_next_q = NULL;
17857 
17858 			/* Need to get inside the listener perimeter */
17859 			CONN_INC_REF(listener->tcp_connp);
17860 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
17861 			    tcp_send_pending, listener->tcp_connp,
17862 			    SQTAG_TCP_SEND_PENDING);
17863 		}
17864 no_more_eagers:
17865 		tcp_eager_unlink(eager);
17866 		mutex_exit(&listener->tcp_eager_lock);
17867 
17868 		/*
17869 		 * At this point, the eager is detached from the listener
17870 		 * but we still have an extra refs on eager (apart from the
17871 		 * usual tcp references). The ref was placed in tcp_rput_data
17872 		 * before sending the conn_ind in tcp_send_conn_ind.
17873 		 * The ref will be dropped in tcp_accept_finish().
17874 		 */
17875 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
17876 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
17877 		return;
17878 	default:
17879 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17880 		if (mp != NULL)
17881 			putnext(rq, mp);
17882 		return;
17883 	}
17884 }
17885 
17886 void
17887 tcp_wput(queue_t *q, mblk_t *mp)
17888 {
17889 	conn_t	*connp = Q_TO_CONN(q);
17890 	tcp_t	*tcp;
17891 	void (*output_proc)();
17892 	t_scalar_t type;
17893 	uchar_t *rptr;
17894 	struct iocblk	*iocp;
17895 	uint32_t	msize;
17896 
17897 	ASSERT(connp->conn_ref >= 2);
17898 
17899 	switch (DB_TYPE(mp)) {
17900 	case M_DATA:
17901 		tcp = connp->conn_tcp;
17902 		ASSERT(tcp != NULL);
17903 
17904 		msize = msgdsize(mp);
17905 
17906 		mutex_enter(&connp->conn_lock);
17907 		CONN_INC_REF_LOCKED(connp);
17908 
17909 		tcp->tcp_squeue_bytes += msize;
17910 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
17911 			mutex_exit(&connp->conn_lock);
17912 			tcp_setqfull(tcp);
17913 		} else
17914 			mutex_exit(&connp->conn_lock);
17915 
17916 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17917 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
17918 		return;
17919 	case M_PROTO:
17920 	case M_PCPROTO:
17921 		/*
17922 		 * if it is a snmp message, don't get behind the squeue
17923 		 */
17924 		tcp = connp->conn_tcp;
17925 		rptr = mp->b_rptr;
17926 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
17927 			type = ((union T_primitives *)rptr)->type;
17928 		} else {
17929 			if (tcp->tcp_debug) {
17930 				(void) strlog(TCP_MOD_ID, 0, 1,
17931 				    SL_ERROR|SL_TRACE,
17932 				    "tcp_wput_proto, dropping one...");
17933 			}
17934 			freemsg(mp);
17935 			return;
17936 		}
17937 		if (type == T_SVR4_OPTMGMT_REQ) {
17938 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
17939 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
17940 			    cr)) {
17941 				/*
17942 				 * This was a SNMP request
17943 				 */
17944 				return;
17945 			} else {
17946 				output_proc = tcp_wput_proto;
17947 			}
17948 		} else {
17949 			output_proc = tcp_wput_proto;
17950 		}
17951 		break;
17952 	case M_IOCTL:
17953 		/*
17954 		 * Most ioctls can be processed right away without going via
17955 		 * squeues - process them right here. Those that do require
17956 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
17957 		 * are processed by tcp_wput_ioctl().
17958 		 */
17959 		iocp = (struct iocblk *)mp->b_rptr;
17960 		tcp = connp->conn_tcp;
17961 
17962 		switch (iocp->ioc_cmd) {
17963 		case TCP_IOC_ABORT_CONN:
17964 			tcp_ioctl_abort_conn(q, mp);
17965 			return;
17966 		case TI_GETPEERNAME:
17967 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
17968 				iocp->ioc_error = ENOTCONN;
17969 				iocp->ioc_count = 0;
17970 				mp->b_datap->db_type = M_IOCACK;
17971 				qreply(q, mp);
17972 				return;
17973 			}
17974 			/* FALLTHRU */
17975 		case TI_GETMYNAME:
17976 			mi_copyin(q, mp, NULL,
17977 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
17978 			return;
17979 		case ND_SET:
17980 			/* nd_getset does the necessary checks */
17981 		case ND_GET:
17982 			if (!nd_getset(q, tcp_g_nd, mp)) {
17983 				CALL_IP_WPUT(connp, q, mp);
17984 				return;
17985 			}
17986 			qreply(q, mp);
17987 			return;
17988 		case TCP_IOC_DEFAULT_Q:
17989 			/*
17990 			 * Wants to be the default wq. Check the credentials
17991 			 * first, the rest is executed via squeue.
17992 			 */
17993 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
17994 				iocp->ioc_error = EPERM;
17995 				iocp->ioc_count = 0;
17996 				mp->b_datap->db_type = M_IOCACK;
17997 				qreply(q, mp);
17998 				return;
17999 			}
18000 			output_proc = tcp_wput_ioctl;
18001 			break;
18002 		default:
18003 			output_proc = tcp_wput_ioctl;
18004 			break;
18005 		}
18006 		break;
18007 	default:
18008 		output_proc = tcp_wput_nondata;
18009 		break;
18010 	}
18011 
18012 	CONN_INC_REF(connp);
18013 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18014 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18015 }
18016 
18017 /*
18018  * Initial STREAMS write side put() procedure for sockets. It tries to
18019  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18020  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18021  * are handled by tcp_wput() as usual.
18022  *
18023  * All further messages will also be handled by tcp_wput() because we cannot
18024  * be sure that the above short cut is safe later.
18025  */
18026 static void
18027 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18028 {
18029 	conn_t			*connp = Q_TO_CONN(wq);
18030 	tcp_t			*tcp = connp->conn_tcp;
18031 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18032 
18033 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18034 	wq->q_qinfo = &tcp_winit;
18035 
18036 	ASSERT(IPCL_IS_TCP(connp));
18037 	ASSERT(TCP_IS_SOCKET(tcp));
18038 
18039 	if (DB_TYPE(mp) == M_PCPROTO &&
18040 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18041 	    car->PRIM_type == T_CAPABILITY_REQ) {
18042 		tcp_capability_req(tcp, mp);
18043 		return;
18044 	}
18045 
18046 	tcp_wput(wq, mp);
18047 }
18048 
18049 static boolean_t
18050 tcp_zcopy_check(tcp_t *tcp)
18051 {
18052 	conn_t	*connp = tcp->tcp_connp;
18053 	ire_t	*ire;
18054 	boolean_t	zc_enabled = B_FALSE;
18055 
18056 	if (do_tcpzcopy == 2)
18057 		zc_enabled = B_TRUE;
18058 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18059 	    IPCL_IS_CONNECTED(connp) &&
18060 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18061 	    connp->conn_dontroute == 0 &&
18062 	    !connp->conn_nexthop_set &&
18063 	    connp->conn_xmit_if_ill == NULL &&
18064 	    connp->conn_nofailover_ill == NULL &&
18065 	    do_tcpzcopy == 1) {
18066 		/*
18067 		 * the checks above  closely resemble the fast path checks
18068 		 * in tcp_send_data().
18069 		 */
18070 		mutex_enter(&connp->conn_lock);
18071 		ire = connp->conn_ire_cache;
18072 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18073 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18074 			IRE_REFHOLD(ire);
18075 			if (ire->ire_stq != NULL) {
18076 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18077 
18078 				zc_enabled = ill && (ill->ill_capabilities &
18079 				    ILL_CAPAB_ZEROCOPY) &&
18080 				    (ill->ill_zerocopy_capab->
18081 				    ill_zerocopy_flags != 0);
18082 			}
18083 			IRE_REFRELE(ire);
18084 		}
18085 		mutex_exit(&connp->conn_lock);
18086 	}
18087 	tcp->tcp_snd_zcopy_on = zc_enabled;
18088 	if (!TCP_IS_DETACHED(tcp)) {
18089 		if (zc_enabled) {
18090 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18091 			TCP_STAT(tcp_zcopy_on);
18092 		} else {
18093 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18094 			TCP_STAT(tcp_zcopy_off);
18095 		}
18096 	}
18097 	return (zc_enabled);
18098 }
18099 
18100 static mblk_t *
18101 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18102 {
18103 	if (do_tcpzcopy == 2)
18104 		return (bp);
18105 	else if (tcp->tcp_snd_zcopy_on) {
18106 		tcp->tcp_snd_zcopy_on = B_FALSE;
18107 		if (!TCP_IS_DETACHED(tcp)) {
18108 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18109 			TCP_STAT(tcp_zcopy_disable);
18110 		}
18111 	}
18112 	return (tcp_zcopy_backoff(tcp, bp, 0));
18113 }
18114 
18115 /*
18116  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18117  * the original desballoca'ed segmapped mblk.
18118  */
18119 static mblk_t *
18120 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18121 {
18122 	mblk_t *head, *tail, *nbp;
18123 	if (IS_VMLOANED_MBLK(bp)) {
18124 		TCP_STAT(tcp_zcopy_backoff);
18125 		if ((head = copyb(bp)) == NULL) {
18126 			/* fail to backoff; leave it for the next backoff */
18127 			tcp->tcp_xmit_zc_clean = B_FALSE;
18128 			return (bp);
18129 		}
18130 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18131 			if (fix_xmitlist)
18132 				tcp_zcopy_notify(tcp);
18133 			else
18134 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18135 		}
18136 		nbp = bp->b_cont;
18137 		if (fix_xmitlist) {
18138 			head->b_prev = bp->b_prev;
18139 			head->b_next = bp->b_next;
18140 			if (tcp->tcp_xmit_tail == bp)
18141 				tcp->tcp_xmit_tail = head;
18142 		}
18143 		bp->b_next = NULL;
18144 		bp->b_prev = NULL;
18145 		freeb(bp);
18146 	} else {
18147 		head = bp;
18148 		nbp = bp->b_cont;
18149 	}
18150 	tail = head;
18151 	while (nbp) {
18152 		if (IS_VMLOANED_MBLK(nbp)) {
18153 			TCP_STAT(tcp_zcopy_backoff);
18154 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18155 				tcp->tcp_xmit_zc_clean = B_FALSE;
18156 				tail->b_cont = nbp;
18157 				return (head);
18158 			}
18159 			tail = tail->b_cont;
18160 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18161 				if (fix_xmitlist)
18162 					tcp_zcopy_notify(tcp);
18163 				else
18164 					tail->b_datap->db_struioflag |=
18165 					    STRUIO_ZCNOTIFY;
18166 			}
18167 			bp = nbp;
18168 			nbp = nbp->b_cont;
18169 			if (fix_xmitlist) {
18170 				tail->b_prev = bp->b_prev;
18171 				tail->b_next = bp->b_next;
18172 				if (tcp->tcp_xmit_tail == bp)
18173 					tcp->tcp_xmit_tail = tail;
18174 			}
18175 			bp->b_next = NULL;
18176 			bp->b_prev = NULL;
18177 			freeb(bp);
18178 		} else {
18179 			tail->b_cont = nbp;
18180 			tail = nbp;
18181 			nbp = nbp->b_cont;
18182 		}
18183 	}
18184 	if (fix_xmitlist) {
18185 		tcp->tcp_xmit_last = tail;
18186 		tcp->tcp_xmit_zc_clean = B_TRUE;
18187 	}
18188 	return (head);
18189 }
18190 
18191 static void
18192 tcp_zcopy_notify(tcp_t *tcp)
18193 {
18194 	struct stdata	*stp;
18195 
18196 	if (tcp->tcp_detached)
18197 		return;
18198 	stp = STREAM(tcp->tcp_rq);
18199 	mutex_enter(&stp->sd_lock);
18200 	stp->sd_flag |= STZCNOTIFY;
18201 	cv_broadcast(&stp->sd_zcopy_wait);
18202 	mutex_exit(&stp->sd_lock);
18203 }
18204 
18205 static void
18206 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18207 {
18208 	ipha_t		*ipha;
18209 	ipaddr_t	src;
18210 	ipaddr_t	dst;
18211 	uint32_t	cksum;
18212 	ire_t		*ire;
18213 	uint16_t	*up;
18214 	ill_t		*ill;
18215 	conn_t		*connp = tcp->tcp_connp;
18216 	uint32_t	hcksum_txflags = 0;
18217 	mblk_t		*ire_fp_mp;
18218 	uint_t		ire_fp_mp_len;
18219 
18220 	ASSERT(DB_TYPE(mp) == M_DATA);
18221 
18222 	if (DB_CRED(mp) == NULL)
18223 		mblk_setcred(mp, CONN_CRED(connp));
18224 
18225 	ipha = (ipha_t *)mp->b_rptr;
18226 	src = ipha->ipha_src;
18227 	dst = ipha->ipha_dst;
18228 
18229 	/*
18230 	 * Drop off fast path for IPv6 and also if options are present or
18231 	 * we need to resolve a TS label.
18232 	 */
18233 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18234 	    !IPCL_IS_CONNECTED(connp) ||
18235 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18236 	    connp->conn_dontroute ||
18237 	    connp->conn_nexthop_set ||
18238 	    connp->conn_xmit_if_ill != NULL ||
18239 	    connp->conn_nofailover_ill != NULL ||
18240 	    !connp->conn_ulp_labeled ||
18241 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18242 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18243 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
18244 		if (tcp->tcp_snd_zcopy_aware)
18245 			mp = tcp_zcopy_disable(tcp, mp);
18246 		TCP_STAT(tcp_ip_send);
18247 		CALL_IP_WPUT(connp, q, mp);
18248 		return;
18249 	}
18250 
18251 	mutex_enter(&connp->conn_lock);
18252 	ire = connp->conn_ire_cache;
18253 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18254 	if (ire != NULL && ire->ire_addr == dst &&
18255 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18256 		IRE_REFHOLD(ire);
18257 		mutex_exit(&connp->conn_lock);
18258 	} else {
18259 		boolean_t cached = B_FALSE;
18260 
18261 		/* force a recheck later on */
18262 		tcp->tcp_ire_ill_check_done = B_FALSE;
18263 
18264 		TCP_DBGSTAT(tcp_ire_null1);
18265 		connp->conn_ire_cache = NULL;
18266 		mutex_exit(&connp->conn_lock);
18267 		if (ire != NULL)
18268 			IRE_REFRELE_NOTR(ire);
18269 		ire = ire_cache_lookup(dst, connp->conn_zoneid,
18270 		    MBLK_GETLABEL(mp));
18271 		if (ire == NULL) {
18272 			if (tcp->tcp_snd_zcopy_aware)
18273 				mp = tcp_zcopy_backoff(tcp, mp, 0);
18274 			TCP_STAT(tcp_ire_null);
18275 			CALL_IP_WPUT(connp, q, mp);
18276 			return;
18277 		}
18278 		IRE_REFHOLD_NOTR(ire);
18279 		/*
18280 		 * Since we are inside the squeue, there cannot be another
18281 		 * thread in TCP trying to set the conn_ire_cache now.  The
18282 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18283 		 * unplumb thread has not yet started cleaning up the conns.
18284 		 * Hence we don't need to grab the conn lock.
18285 		 */
18286 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
18287 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18288 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18289 				connp->conn_ire_cache = ire;
18290 				cached = B_TRUE;
18291 			}
18292 			rw_exit(&ire->ire_bucket->irb_lock);
18293 		}
18294 
18295 		/*
18296 		 * We can continue to use the ire but since it was
18297 		 * not cached, we should drop the extra reference.
18298 		 */
18299 		if (!cached)
18300 			IRE_REFRELE_NOTR(ire);
18301 
18302 		/*
18303 		 * Rampart note: no need to select a new label here, since
18304 		 * labels are not allowed to change during the life of a TCP
18305 		 * connection.
18306 		 */
18307 	}
18308 
18309 	if (ire->ire_flags & RTF_MULTIRT ||
18310 	    ire->ire_stq == NULL ||
18311 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18312 	    (ire_fp_mp = ire->ire_fp_mp) == NULL ||
18313 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
18314 		if (tcp->tcp_snd_zcopy_aware)
18315 			mp = tcp_zcopy_disable(tcp, mp);
18316 		TCP_STAT(tcp_ip_ire_send);
18317 		IRE_REFRELE(ire);
18318 		CALL_IP_WPUT(connp, q, mp);
18319 		return;
18320 	}
18321 
18322 	ill = ire_to_ill(ire);
18323 	if (connp->conn_outgoing_ill != NULL) {
18324 		ill_t *conn_outgoing_ill = NULL;
18325 		/*
18326 		 * Choose a good ill in the group to send the packets on.
18327 		 */
18328 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18329 		ill = ire_to_ill(ire);
18330 	}
18331 	ASSERT(ill != NULL);
18332 
18333 	if (!tcp->tcp_ire_ill_check_done) {
18334 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18335 		tcp->tcp_ire_ill_check_done = B_TRUE;
18336 	}
18337 
18338 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18339 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18340 #ifndef _BIG_ENDIAN
18341 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18342 #endif
18343 
18344 	/*
18345 	 * Check to see if we need to re-enable MDT for this connection
18346 	 * because it was previously disabled due to changes in the ill;
18347 	 * note that by doing it here, this re-enabling only applies when
18348 	 * the packet is not dispatched through CALL_IP_WPUT().
18349 	 *
18350 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
18351 	 * case, since that's how we ended up here.  For IPv6, we do the
18352 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18353 	 */
18354 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18355 		/*
18356 		 * Restore MDT for this connection, so that next time around
18357 		 * it is eligible to go through tcp_multisend() path again.
18358 		 */
18359 		TCP_STAT(tcp_mdt_conn_resumed1);
18360 		tcp->tcp_mdt = B_TRUE;
18361 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18362 		    "interface %s\n", (void *)connp, ill->ill_name));
18363 	}
18364 
18365 	if (tcp->tcp_snd_zcopy_aware) {
18366 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18367 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18368 			mp = tcp_zcopy_disable(tcp, mp);
18369 		/*
18370 		 * we shouldn't need to reset ipha as the mp containing
18371 		 * ipha should never be a zero-copy mp.
18372 		 */
18373 	}
18374 
18375 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18376 		ASSERT(ill->ill_hcksum_capab != NULL);
18377 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18378 	}
18379 
18380 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18381 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18382 
18383 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18384 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18385 
18386 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18387 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18388 
18389 	/* Software checksum? */
18390 	if (DB_CKSUMFLAGS(mp) == 0) {
18391 		TCP_STAT(tcp_out_sw_cksum);
18392 		TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
18393 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18394 	}
18395 
18396 	ipha->ipha_fragment_offset_and_flags |=
18397 	    (uint32_t)htons(ire->ire_frag_flag);
18398 
18399 	/* Calculate IP header checksum if hardware isn't capable */
18400 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18401 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18402 		    ((uint16_t *)ipha)[4]);
18403 	}
18404 
18405 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18406 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18407 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18408 
18409 	UPDATE_OB_PKT_COUNT(ire);
18410 	ire->ire_last_used_time = lbolt;
18411 	BUMP_MIB(&ip_mib, ipOutRequests);
18412 
18413 	if (ILL_DLS_CAPABLE(ill)) {
18414 		/*
18415 		 * Send the packet directly to DLD, where it may be queued
18416 		 * depending on the availability of transmit resources at
18417 		 * the media layer.
18418 		 */
18419 		IP_DLS_ILL_TX(ill, mp);
18420 	} else {
18421 		putnext(ire->ire_stq, mp);
18422 	}
18423 	IRE_REFRELE(ire);
18424 }
18425 
18426 /*
18427  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18428  * if the receiver shrinks the window, i.e. moves the right window to the
18429  * left, the we should not send new data, but should retransmit normally the
18430  * old unacked data between suna and suna + swnd. We might has sent data
18431  * that is now outside the new window, pretend that we didn't send  it.
18432  */
18433 static void
18434 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18435 {
18436 	uint32_t	snxt = tcp->tcp_snxt;
18437 	mblk_t		*xmit_tail;
18438 	int32_t		offset;
18439 
18440 	ASSERT(shrunk_count > 0);
18441 
18442 	/* Pretend we didn't send the data outside the window */
18443 	snxt -= shrunk_count;
18444 
18445 	/* Get the mblk and the offset in it per the shrunk window */
18446 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18447 
18448 	ASSERT(xmit_tail != NULL);
18449 
18450 	/* Reset all the values per the now shrunk window */
18451 	tcp->tcp_snxt = snxt;
18452 	tcp->tcp_xmit_tail = xmit_tail;
18453 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18454 	    offset;
18455 	tcp->tcp_unsent += shrunk_count;
18456 
18457 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18458 		/*
18459 		 * Make sure the timer is running so that we will probe a zero
18460 		 * window.
18461 		 */
18462 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18463 }
18464 
18465 
18466 /*
18467  * The TCP normal data output path.
18468  * NOTE: the logic of the fast path is duplicated from this function.
18469  */
18470 static void
18471 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18472 {
18473 	int		len;
18474 	mblk_t		*local_time;
18475 	mblk_t		*mp1;
18476 	uint32_t	snxt;
18477 	int		tail_unsent;
18478 	int		tcpstate;
18479 	int		usable = 0;
18480 	mblk_t		*xmit_tail;
18481 	queue_t		*q = tcp->tcp_wq;
18482 	int32_t		mss;
18483 	int32_t		num_sack_blk = 0;
18484 	int32_t		tcp_hdr_len;
18485 	int32_t		tcp_tcp_hdr_len;
18486 	int		mdt_thres;
18487 	int		rc;
18488 
18489 	tcpstate = tcp->tcp_state;
18490 	if (mp == NULL) {
18491 		/*
18492 		 * tcp_wput_data() with NULL mp should only be called when
18493 		 * there is unsent data.
18494 		 */
18495 		ASSERT(tcp->tcp_unsent > 0);
18496 		/* Really tacky... but we need this for detached closes. */
18497 		len = tcp->tcp_unsent;
18498 		goto data_null;
18499 	}
18500 
18501 #if CCS_STATS
18502 	wrw_stats.tot.count++;
18503 	wrw_stats.tot.bytes += msgdsize(mp);
18504 #endif
18505 	ASSERT(mp->b_datap->db_type == M_DATA);
18506 	/*
18507 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18508 	 * or before a connection attempt has begun.
18509 	 */
18510 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18511 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18512 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18513 #ifdef DEBUG
18514 			cmn_err(CE_WARN,
18515 			    "tcp_wput_data: data after ordrel, %s",
18516 			    tcp_display(tcp, NULL,
18517 			    DISP_ADDR_AND_PORT));
18518 #else
18519 			if (tcp->tcp_debug) {
18520 				(void) strlog(TCP_MOD_ID, 0, 1,
18521 				    SL_TRACE|SL_ERROR,
18522 				    "tcp_wput_data: data after ordrel, %s\n",
18523 				    tcp_display(tcp, NULL,
18524 				    DISP_ADDR_AND_PORT));
18525 			}
18526 #endif /* DEBUG */
18527 		}
18528 		if (tcp->tcp_snd_zcopy_aware &&
18529 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18530 			tcp_zcopy_notify(tcp);
18531 		freemsg(mp);
18532 		if (tcp->tcp_flow_stopped &&
18533 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18534 			tcp_clrqfull(tcp);
18535 		}
18536 		return;
18537 	}
18538 
18539 	/* Strip empties */
18540 	for (;;) {
18541 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18542 		    (uintptr_t)INT_MAX);
18543 		len = (int)(mp->b_wptr - mp->b_rptr);
18544 		if (len > 0)
18545 			break;
18546 		mp1 = mp;
18547 		mp = mp->b_cont;
18548 		freeb(mp1);
18549 		if (!mp) {
18550 			return;
18551 		}
18552 	}
18553 
18554 	/* If we are the first on the list ... */
18555 	if (tcp->tcp_xmit_head == NULL) {
18556 		tcp->tcp_xmit_head = mp;
18557 		tcp->tcp_xmit_tail = mp;
18558 		tcp->tcp_xmit_tail_unsent = len;
18559 	} else {
18560 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18561 		struct datab *dp;
18562 
18563 		mp1 = tcp->tcp_xmit_last;
18564 		if (len < tcp_tx_pull_len &&
18565 		    (dp = mp1->b_datap)->db_ref == 1 &&
18566 		    dp->db_lim - mp1->b_wptr >= len) {
18567 			ASSERT(len > 0);
18568 			ASSERT(!mp1->b_cont);
18569 			if (len == 1) {
18570 				*mp1->b_wptr++ = *mp->b_rptr;
18571 			} else {
18572 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18573 				mp1->b_wptr += len;
18574 			}
18575 			if (mp1 == tcp->tcp_xmit_tail)
18576 				tcp->tcp_xmit_tail_unsent += len;
18577 			mp1->b_cont = mp->b_cont;
18578 			if (tcp->tcp_snd_zcopy_aware &&
18579 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18580 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18581 			freeb(mp);
18582 			mp = mp1;
18583 		} else {
18584 			tcp->tcp_xmit_last->b_cont = mp;
18585 		}
18586 		len += tcp->tcp_unsent;
18587 	}
18588 
18589 	/* Tack on however many more positive length mblks we have */
18590 	if ((mp1 = mp->b_cont) != NULL) {
18591 		do {
18592 			int tlen;
18593 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18594 			    (uintptr_t)INT_MAX);
18595 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18596 			if (tlen <= 0) {
18597 				mp->b_cont = mp1->b_cont;
18598 				freeb(mp1);
18599 			} else {
18600 				len += tlen;
18601 				mp = mp1;
18602 			}
18603 		} while ((mp1 = mp->b_cont) != NULL);
18604 	}
18605 	tcp->tcp_xmit_last = mp;
18606 	tcp->tcp_unsent = len;
18607 
18608 	if (urgent)
18609 		usable = 1;
18610 
18611 data_null:
18612 	snxt = tcp->tcp_snxt;
18613 	xmit_tail = tcp->tcp_xmit_tail;
18614 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18615 
18616 	/*
18617 	 * Note that tcp_mss has been adjusted to take into account the
18618 	 * timestamp option if applicable.  Because SACK options do not
18619 	 * appear in every TCP segments and they are of variable lengths,
18620 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18621 	 * the actual segment length when we need to send a segment which
18622 	 * includes SACK options.
18623 	 */
18624 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18625 		int32_t	opt_len;
18626 
18627 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18628 		    tcp->tcp_num_sack_blk);
18629 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18630 		    2 + TCPOPT_HEADER_LEN;
18631 		mss = tcp->tcp_mss - opt_len;
18632 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18633 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18634 	} else {
18635 		mss = tcp->tcp_mss;
18636 		tcp_hdr_len = tcp->tcp_hdr_len;
18637 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18638 	}
18639 
18640 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18641 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18642 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
18643 	}
18644 	if (tcpstate == TCPS_SYN_RCVD) {
18645 		/*
18646 		 * The three-way connection establishment handshake is not
18647 		 * complete yet. We want to queue the data for transmission
18648 		 * after entering ESTABLISHED state (RFC793). A jump to
18649 		 * "done" label effectively leaves data on the queue.
18650 		 */
18651 		goto done;
18652 	} else {
18653 		int usable_r;
18654 
18655 		/*
18656 		 * In the special case when cwnd is zero, which can only
18657 		 * happen if the connection is ECN capable, return now.
18658 		 * New segments is sent using tcp_timer().  The timer
18659 		 * is set in tcp_rput_data().
18660 		 */
18661 		if (tcp->tcp_cwnd == 0) {
18662 			/*
18663 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18664 			 * finished.
18665 			 */
18666 			ASSERT(tcp->tcp_ecn_ok ||
18667 			    tcp->tcp_state < TCPS_ESTABLISHED);
18668 			return;
18669 		}
18670 
18671 		/* NOTE: trouble if xmitting while SYN not acked? */
18672 		usable_r = snxt - tcp->tcp_suna;
18673 		usable_r = tcp->tcp_swnd - usable_r;
18674 
18675 		/*
18676 		 * Check if the receiver has shrunk the window.  If
18677 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18678 		 * cannot be set as there is unsent data, so FIN cannot
18679 		 * be sent out.  Otherwise, we need to take into account
18680 		 * of FIN as it consumes an "invisible" sequence number.
18681 		 */
18682 		ASSERT(tcp->tcp_fin_sent == 0);
18683 		if (usable_r < 0) {
18684 			/*
18685 			 * The receiver has shrunk the window and we have sent
18686 			 * -usable_r date beyond the window, re-adjust.
18687 			 *
18688 			 * If TCP window scaling is enabled, there can be
18689 			 * round down error as the advertised receive window
18690 			 * is actually right shifted n bits.  This means that
18691 			 * the lower n bits info is wiped out.  It will look
18692 			 * like the window is shrunk.  Do a check here to
18693 			 * see if the shrunk amount is actually within the
18694 			 * error in window calculation.  If it is, just
18695 			 * return.  Note that this check is inside the
18696 			 * shrunk window check.  This makes sure that even
18697 			 * though tcp_process_shrunk_swnd() is not called,
18698 			 * we will stop further processing.
18699 			 */
18700 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18701 				tcp_process_shrunk_swnd(tcp, -usable_r);
18702 			}
18703 			return;
18704 		}
18705 
18706 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18707 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18708 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18709 
18710 		/* usable = MIN(usable, unsent) */
18711 		if (usable_r > len)
18712 			usable_r = len;
18713 
18714 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18715 		if (usable_r > 0) {
18716 			usable = usable_r;
18717 		} else {
18718 			/* Bypass all other unnecessary processing. */
18719 			goto done;
18720 		}
18721 	}
18722 
18723 	local_time = (mblk_t *)lbolt;
18724 
18725 	/*
18726 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18727 	 * BSD.  This is more in line with the true intent of Nagle.
18728 	 *
18729 	 * The conditions are:
18730 	 * 1. The amount of unsent data (or amount of data which can be
18731 	 *    sent, whichever is smaller) is less than Nagle limit.
18732 	 * 2. The last sent size is also less than Nagle limit.
18733 	 * 3. There is unack'ed data.
18734 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18735 	 *    Nagle algorithm.  This reduces the probability that urgent
18736 	 *    bytes get "merged" together.
18737 	 * 5. The app has not closed the connection.  This eliminates the
18738 	 *    wait time of the receiving side waiting for the last piece of
18739 	 *    (small) data.
18740 	 *
18741 	 * If all are satisified, exit without sending anything.  Note
18742 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18743 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18744 	 * 4095).
18745 	 */
18746 	if (usable < (int)tcp->tcp_naglim &&
18747 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18748 	    snxt != tcp->tcp_suna &&
18749 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18750 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18751 		goto done;
18752 	}
18753 
18754 	if (tcp->tcp_cork) {
18755 		/*
18756 		 * if the tcp->tcp_cork option is set, then we have to force
18757 		 * TCP not to send partial segment (smaller than MSS bytes).
18758 		 * We are calculating the usable now based on full mss and
18759 		 * will save the rest of remaining data for later.
18760 		 */
18761 		if (usable < mss)
18762 			goto done;
18763 		usable = (usable / mss) * mss;
18764 	}
18765 
18766 	/* Update the latest receive window size in TCP header. */
18767 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18768 	    tcp->tcp_tcph->th_win);
18769 
18770 	/*
18771 	 * Determine if it's worthwhile to attempt MDT, based on:
18772 	 *
18773 	 * 1. Simple TCP/IP{v4,v6} (no options).
18774 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18775 	 * 3. If the TCP connection is in ESTABLISHED state.
18776 	 * 4. The TCP is not detached.
18777 	 *
18778 	 * If any of the above conditions have changed during the
18779 	 * connection, stop using MDT and restore the stream head
18780 	 * parameters accordingly.
18781 	 */
18782 	if (tcp->tcp_mdt &&
18783 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
18784 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
18785 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18786 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
18787 	    tcp->tcp_state != TCPS_ESTABLISHED ||
18788 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
18789 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
18790 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
18791 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
18792 		tcp->tcp_mdt = B_FALSE;
18793 
18794 		/* Anything other than detached is considered pathological */
18795 		if (!TCP_IS_DETACHED(tcp)) {
18796 			TCP_STAT(tcp_mdt_conn_halted1);
18797 			(void) tcp_maxpsz_set(tcp, B_TRUE);
18798 		}
18799 	}
18800 
18801 	/* Use MDT if sendable amount is greater than the threshold */
18802 	if (tcp->tcp_mdt &&
18803 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
18804 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
18805 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
18806 	    (tcp->tcp_valid_bits == 0 ||
18807 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
18808 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
18809 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18810 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18811 		    local_time, mdt_thres);
18812 	} else {
18813 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18814 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18815 		    local_time, INT_MAX);
18816 	}
18817 
18818 	/* Pretend that all we were trying to send really got sent */
18819 	if (rc < 0 && tail_unsent < 0) {
18820 		do {
18821 			xmit_tail = xmit_tail->b_cont;
18822 			xmit_tail->b_prev = local_time;
18823 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
18824 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
18825 			tail_unsent += (int)(xmit_tail->b_wptr -
18826 			    xmit_tail->b_rptr);
18827 		} while (tail_unsent < 0);
18828 	}
18829 done:;
18830 	tcp->tcp_xmit_tail = xmit_tail;
18831 	tcp->tcp_xmit_tail_unsent = tail_unsent;
18832 	len = tcp->tcp_snxt - snxt;
18833 	if (len) {
18834 		/*
18835 		 * If new data was sent, need to update the notsack
18836 		 * list, which is, afterall, data blocks that have
18837 		 * not been sack'ed by the receiver.  New data is
18838 		 * not sack'ed.
18839 		 */
18840 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
18841 			/* len is a negative value. */
18842 			tcp->tcp_pipe -= len;
18843 			tcp_notsack_update(&(tcp->tcp_notsack_list),
18844 			    tcp->tcp_snxt, snxt,
18845 			    &(tcp->tcp_num_notsack_blk),
18846 			    &(tcp->tcp_cnt_notsack_list));
18847 		}
18848 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
18849 		tcp->tcp_rack = tcp->tcp_rnxt;
18850 		tcp->tcp_rack_cnt = 0;
18851 		if ((snxt + len) == tcp->tcp_suna) {
18852 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18853 		}
18854 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
18855 		/*
18856 		 * Didn't send anything. Make sure the timer is running
18857 		 * so that we will probe a zero window.
18858 		 */
18859 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18860 	}
18861 	/* Note that len is the amount we just sent but with a negative sign */
18862 	tcp->tcp_unsent += len;
18863 	if (tcp->tcp_flow_stopped) {
18864 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18865 			tcp_clrqfull(tcp);
18866 		}
18867 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
18868 		tcp_setqfull(tcp);
18869 	}
18870 }
18871 
18872 /*
18873  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
18874  * outgoing TCP header with the template header, as well as other
18875  * options such as time-stamp, ECN and/or SACK.
18876  */
18877 static void
18878 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
18879 {
18880 	tcph_t *tcp_tmpl, *tcp_h;
18881 	uint32_t *dst, *src;
18882 	int hdrlen;
18883 
18884 	ASSERT(OK_32PTR(rptr));
18885 
18886 	/* Template header */
18887 	tcp_tmpl = tcp->tcp_tcph;
18888 
18889 	/* Header of outgoing packet */
18890 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18891 
18892 	/* dst and src are opaque 32-bit fields, used for copying */
18893 	dst = (uint32_t *)rptr;
18894 	src = (uint32_t *)tcp->tcp_iphc;
18895 	hdrlen = tcp->tcp_hdr_len;
18896 
18897 	/* Fill time-stamp option if needed */
18898 	if (tcp->tcp_snd_ts_ok) {
18899 		U32_TO_BE32((uint32_t)now,
18900 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
18901 		U32_TO_BE32(tcp->tcp_ts_recent,
18902 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
18903 	} else {
18904 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18905 	}
18906 
18907 	/*
18908 	 * Copy the template header; is this really more efficient than
18909 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
18910 	 * but perhaps not for other scenarios.
18911 	 */
18912 	dst[0] = src[0];
18913 	dst[1] = src[1];
18914 	dst[2] = src[2];
18915 	dst[3] = src[3];
18916 	dst[4] = src[4];
18917 	dst[5] = src[5];
18918 	dst[6] = src[6];
18919 	dst[7] = src[7];
18920 	dst[8] = src[8];
18921 	dst[9] = src[9];
18922 	if (hdrlen -= 40) {
18923 		hdrlen >>= 2;
18924 		dst += 10;
18925 		src += 10;
18926 		do {
18927 			*dst++ = *src++;
18928 		} while (--hdrlen);
18929 	}
18930 
18931 	/*
18932 	 * Set the ECN info in the TCP header if it is not a zero
18933 	 * window probe.  Zero window probe is only sent in
18934 	 * tcp_wput_data() and tcp_timer().
18935 	 */
18936 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
18937 		SET_ECT(tcp, rptr);
18938 
18939 		if (tcp->tcp_ecn_echo_on)
18940 			tcp_h->th_flags[0] |= TH_ECE;
18941 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18942 			tcp_h->th_flags[0] |= TH_CWR;
18943 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18944 		}
18945 	}
18946 
18947 	/* Fill in SACK options */
18948 	if (num_sack_blk > 0) {
18949 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
18950 		sack_blk_t *tmp;
18951 		int32_t	i;
18952 
18953 		wptr[0] = TCPOPT_NOP;
18954 		wptr[1] = TCPOPT_NOP;
18955 		wptr[2] = TCPOPT_SACK;
18956 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18957 		    sizeof (sack_blk_t);
18958 		wptr += TCPOPT_REAL_SACK_LEN;
18959 
18960 		tmp = tcp->tcp_sack_list;
18961 		for (i = 0; i < num_sack_blk; i++) {
18962 			U32_TO_BE32(tmp[i].begin, wptr);
18963 			wptr += sizeof (tcp_seq);
18964 			U32_TO_BE32(tmp[i].end, wptr);
18965 			wptr += sizeof (tcp_seq);
18966 		}
18967 		tcp_h->th_offset_and_rsrvd[0] +=
18968 		    ((num_sack_blk * 2 + 1) << 4);
18969 	}
18970 }
18971 
18972 /*
18973  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
18974  * the destination address and SAP attribute, and if necessary, the
18975  * hardware checksum offload attribute to a Multidata message.
18976  */
18977 static int
18978 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
18979     const uint32_t start, const uint32_t stuff, const uint32_t end,
18980     const uint32_t flags)
18981 {
18982 	/* Add global destination address & SAP attribute */
18983 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
18984 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
18985 		    "destination address+SAP\n"));
18986 
18987 		if (dlmp != NULL)
18988 			TCP_STAT(tcp_mdt_allocfail);
18989 		return (-1);
18990 	}
18991 
18992 	/* Add global hwcksum attribute */
18993 	if (hwcksum &&
18994 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
18995 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
18996 		    "checksum attribute\n"));
18997 
18998 		TCP_STAT(tcp_mdt_allocfail);
18999 		return (-1);
19000 	}
19001 
19002 	return (0);
19003 }
19004 
19005 /*
19006  * Smaller and private version of pdescinfo_t used specifically for TCP,
19007  * which allows for only two payload spans per packet.
19008  */
19009 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19010 
19011 /*
19012  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19013  * scheme, and returns one the following:
19014  *
19015  * -1 = failed allocation.
19016  *  0 = success; burst count reached, or usable send window is too small,
19017  *      and that we'd rather wait until later before sending again.
19018  */
19019 static int
19020 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19021     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19022     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19023     const int mdt_thres)
19024 {
19025 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19026 	multidata_t	*mmd;
19027 	uint_t		obsegs, obbytes, hdr_frag_sz;
19028 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19029 	int		num_burst_seg, max_pld;
19030 	pdesc_t		*pkt;
19031 	tcp_pdescinfo_t	tcp_pkt_info;
19032 	pdescinfo_t	*pkt_info;
19033 	int		pbuf_idx, pbuf_idx_nxt;
19034 	int		seg_len, len, spill, af;
19035 	boolean_t	add_buffer, zcopy, clusterwide;
19036 	boolean_t	rconfirm = B_FALSE;
19037 	boolean_t	done = B_FALSE;
19038 	uint32_t	cksum;
19039 	uint32_t	hwcksum_flags;
19040 	ire_t		*ire;
19041 	ill_t		*ill;
19042 	ipha_t		*ipha;
19043 	ip6_t		*ip6h;
19044 	ipaddr_t	src, dst;
19045 	ill_zerocopy_capab_t *zc_cap = NULL;
19046 	uint16_t	*up;
19047 	int		err;
19048 	conn_t		*connp;
19049 
19050 #ifdef	_BIG_ENDIAN
19051 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19052 #else
19053 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19054 #endif
19055 
19056 #define	PREP_NEW_MULTIDATA() {			\
19057 	mmd = NULL;				\
19058 	md_mp = md_hbuf = NULL;			\
19059 	cur_hdr_off = 0;			\
19060 	max_pld = tcp->tcp_mdt_max_pld;		\
19061 	pbuf_idx = pbuf_idx_nxt = -1;		\
19062 	add_buffer = B_TRUE;			\
19063 	zcopy = B_FALSE;			\
19064 }
19065 
19066 #define	PREP_NEW_PBUF() {			\
19067 	md_pbuf = md_pbuf_nxt = NULL;		\
19068 	pbuf_idx = pbuf_idx_nxt = -1;		\
19069 	cur_pld_off = 0;			\
19070 	first_snxt = *snxt;			\
19071 	ASSERT(*tail_unsent > 0);		\
19072 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19073 }
19074 
19075 	ASSERT(mdt_thres >= mss);
19076 	ASSERT(*usable > 0 && *usable > mdt_thres);
19077 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19078 	ASSERT(!TCP_IS_DETACHED(tcp));
19079 	ASSERT(tcp->tcp_valid_bits == 0 ||
19080 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19081 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19082 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19083 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19084 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19085 
19086 	connp = tcp->tcp_connp;
19087 	ASSERT(connp != NULL);
19088 	ASSERT(CONN_IS_MD_FASTPATH(connp));
19089 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19090 
19091 	/*
19092 	 * Note that tcp will only declare at most 2 payload spans per
19093 	 * packet, which is much lower than the maximum allowable number
19094 	 * of packet spans per Multidata.  For this reason, we use the
19095 	 * privately declared and smaller descriptor info structure, in
19096 	 * order to save some stack space.
19097 	 */
19098 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19099 
19100 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19101 	if (af == AF_INET) {
19102 		dst = tcp->tcp_ipha->ipha_dst;
19103 		src = tcp->tcp_ipha->ipha_src;
19104 		ASSERT(!CLASSD(dst));
19105 	}
19106 	ASSERT(af == AF_INET ||
19107 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19108 
19109 	obsegs = obbytes = 0;
19110 	num_burst_seg = tcp->tcp_snd_burst;
19111 	md_mp_head = NULL;
19112 	PREP_NEW_MULTIDATA();
19113 
19114 	/*
19115 	 * Before we go on further, make sure there is an IRE that we can
19116 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19117 	 * in proceeding any further, and we should just hand everything
19118 	 * off to the legacy path.
19119 	 */
19120 	mutex_enter(&connp->conn_lock);
19121 	ire = connp->conn_ire_cache;
19122 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19123 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
19124 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
19125 	    &tcp->tcp_ip6h->ip6_dst))) &&
19126 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19127 		IRE_REFHOLD(ire);
19128 		mutex_exit(&connp->conn_lock);
19129 	} else {
19130 		boolean_t cached = B_FALSE;
19131 		ts_label_t *tsl;
19132 
19133 		/* force a recheck later on */
19134 		tcp->tcp_ire_ill_check_done = B_FALSE;
19135 
19136 		TCP_DBGSTAT(tcp_ire_null1);
19137 		connp->conn_ire_cache = NULL;
19138 		mutex_exit(&connp->conn_lock);
19139 
19140 		/* Release the old ire */
19141 		if (ire != NULL)
19142 			IRE_REFRELE_NOTR(ire);
19143 
19144 		tsl = crgetlabel(CONN_CRED(connp));
19145 		ire = (af == AF_INET) ?
19146 		    ire_cache_lookup(dst, connp->conn_zoneid, tsl) :
19147 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19148 		    connp->conn_zoneid, tsl);
19149 
19150 		if (ire == NULL) {
19151 			TCP_STAT(tcp_ire_null);
19152 			goto legacy_send_no_md;
19153 		}
19154 
19155 		IRE_REFHOLD_NOTR(ire);
19156 		/*
19157 		 * Since we are inside the squeue, there cannot be another
19158 		 * thread in TCP trying to set the conn_ire_cache now. The
19159 		 * check for IRE_MARK_CONDEMNED ensures that an interface
19160 		 * unplumb thread has not yet started cleaning up the conns.
19161 		 * Hence we don't need to grab the conn lock.
19162 		 */
19163 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
19164 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19165 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19166 				connp->conn_ire_cache = ire;
19167 				cached = B_TRUE;
19168 			}
19169 			rw_exit(&ire->ire_bucket->irb_lock);
19170 		}
19171 
19172 		/*
19173 		 * We can continue to use the ire but since it was not
19174 		 * cached, we should drop the extra reference.
19175 		 */
19176 		if (!cached)
19177 			IRE_REFRELE_NOTR(ire);
19178 	}
19179 
19180 	ASSERT(ire != NULL);
19181 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19182 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19183 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19184 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19185 	/*
19186 	 * If we do support loopback for MDT (which requires modifications
19187 	 * to the receiving paths), the following assertions should go away,
19188 	 * and we would be sending the Multidata to loopback conn later on.
19189 	 */
19190 	ASSERT(!IRE_IS_LOCAL(ire));
19191 	ASSERT(ire->ire_stq != NULL);
19192 
19193 	ill = ire_to_ill(ire);
19194 	ASSERT(ill != NULL);
19195 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19196 
19197 	if (!tcp->tcp_ire_ill_check_done) {
19198 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19199 		tcp->tcp_ire_ill_check_done = B_TRUE;
19200 	}
19201 
19202 	/*
19203 	 * If the underlying interface conditions have changed, or if the
19204 	 * new interface does not support MDT, go back to legacy path.
19205 	 */
19206 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19207 		/* don't go through this path anymore for this connection */
19208 		TCP_STAT(tcp_mdt_conn_halted2);
19209 		tcp->tcp_mdt = B_FALSE;
19210 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19211 		    "interface %s\n", (void *)connp, ill->ill_name));
19212 		/* IRE will be released prior to returning */
19213 		goto legacy_send_no_md;
19214 	}
19215 
19216 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19217 		zc_cap = ill->ill_zerocopy_capab;
19218 
19219 	/* go to legacy path if interface doesn't support zerocopy */
19220 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19221 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19222 		/* IRE will be released prior to returning */
19223 		goto legacy_send_no_md;
19224 	}
19225 
19226 	/* does the interface support hardware checksum offload? */
19227 	hwcksum_flags = 0;
19228 	if (ILL_HCKSUM_CAPABLE(ill) &&
19229 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19230 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19231 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19232 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19233 		    HCKSUM_IPHDRCKSUM)
19234 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19235 
19236 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19237 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19238 			hwcksum_flags |= HCK_FULLCKSUM;
19239 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19240 		    HCKSUM_INET_PARTIAL)
19241 			hwcksum_flags |= HCK_PARTIALCKSUM;
19242 	}
19243 
19244 	/*
19245 	 * Each header fragment consists of the leading extra space,
19246 	 * followed by the TCP/IP header, and the trailing extra space.
19247 	 * We make sure that each header fragment begins on a 32-bit
19248 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19249 	 * aligned in tcp_mdt_update).
19250 	 */
19251 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19252 	    tcp->tcp_mdt_hdr_tail), 4);
19253 
19254 	/* are we starting from the beginning of data block? */
19255 	if (*tail_unsent == 0) {
19256 		*xmit_tail = (*xmit_tail)->b_cont;
19257 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19258 		*tail_unsent = (int)MBLKL(*xmit_tail);
19259 	}
19260 
19261 	/*
19262 	 * Here we create one or more Multidata messages, each made up of
19263 	 * one header buffer and up to N payload buffers.  This entire
19264 	 * operation is done within two loops:
19265 	 *
19266 	 * The outer loop mostly deals with creating the Multidata message,
19267 	 * as well as the header buffer that gets added to it.  It also
19268 	 * links the Multidata messages together such that all of them can
19269 	 * be sent down to the lower layer in a single putnext call; this
19270 	 * linking behavior depends on the tcp_mdt_chain tunable.
19271 	 *
19272 	 * The inner loop takes an existing Multidata message, and adds
19273 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19274 	 * packetizes those buffers by filling up the corresponding header
19275 	 * buffer fragments with the proper IP and TCP headers, and by
19276 	 * describing the layout of each packet in the packet descriptors
19277 	 * that get added to the Multidata.
19278 	 */
19279 	do {
19280 		/*
19281 		 * If usable send window is too small, or data blocks in
19282 		 * transmit list are smaller than our threshold (i.e. app
19283 		 * performs large writes followed by small ones), we hand
19284 		 * off the control over to the legacy path.  Note that we'll
19285 		 * get back the control once it encounters a large block.
19286 		 */
19287 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19288 		    (*xmit_tail)->b_cont != NULL &&
19289 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19290 			/* send down what we've got so far */
19291 			if (md_mp_head != NULL) {
19292 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19293 				    obsegs, obbytes, &rconfirm);
19294 			}
19295 			/*
19296 			 * Pass control over to tcp_send(), but tell it to
19297 			 * return to us once a large-size transmission is
19298 			 * possible.
19299 			 */
19300 			TCP_STAT(tcp_mdt_legacy_small);
19301 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19302 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19303 			    tail_unsent, xmit_tail, local_time,
19304 			    mdt_thres)) <= 0) {
19305 				/* burst count reached, or alloc failed */
19306 				IRE_REFRELE(ire);
19307 				return (err);
19308 			}
19309 
19310 			/* tcp_send() may have sent everything, so check */
19311 			if (*usable <= 0) {
19312 				IRE_REFRELE(ire);
19313 				return (0);
19314 			}
19315 
19316 			TCP_STAT(tcp_mdt_legacy_ret);
19317 			/*
19318 			 * We may have delivered the Multidata, so make sure
19319 			 * to re-initialize before the next round.
19320 			 */
19321 			md_mp_head = NULL;
19322 			obsegs = obbytes = 0;
19323 			num_burst_seg = tcp->tcp_snd_burst;
19324 			PREP_NEW_MULTIDATA();
19325 
19326 			/* are we starting from the beginning of data block? */
19327 			if (*tail_unsent == 0) {
19328 				*xmit_tail = (*xmit_tail)->b_cont;
19329 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19330 				    (uintptr_t)INT_MAX);
19331 				*tail_unsent = (int)MBLKL(*xmit_tail);
19332 			}
19333 		}
19334 
19335 		/*
19336 		 * max_pld limits the number of mblks in tcp's transmit
19337 		 * queue that can be added to a Multidata message.  Once
19338 		 * this counter reaches zero, no more additional mblks
19339 		 * can be added to it.  What happens afterwards depends
19340 		 * on whether or not we are set to chain the Multidata
19341 		 * messages.  If we are to link them together, reset
19342 		 * max_pld to its original value (tcp_mdt_max_pld) and
19343 		 * prepare to create a new Multidata message which will
19344 		 * get linked to md_mp_head.  Else, leave it alone and
19345 		 * let the inner loop break on its own.
19346 		 */
19347 		if (tcp_mdt_chain && max_pld == 0)
19348 			PREP_NEW_MULTIDATA();
19349 
19350 		/* adding a payload buffer; re-initialize values */
19351 		if (add_buffer)
19352 			PREP_NEW_PBUF();
19353 
19354 		/*
19355 		 * If we don't have a Multidata, either because we just
19356 		 * (re)entered this outer loop, or after we branched off
19357 		 * to tcp_send above, setup the Multidata and header
19358 		 * buffer to be used.
19359 		 */
19360 		if (md_mp == NULL) {
19361 			int md_hbuflen;
19362 			uint32_t start, stuff;
19363 
19364 			/*
19365 			 * Calculate Multidata header buffer size large enough
19366 			 * to hold all of the headers that can possibly be
19367 			 * sent at this moment.  We'd rather over-estimate
19368 			 * the size than running out of space; this is okay
19369 			 * since this buffer is small anyway.
19370 			 */
19371 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19372 
19373 			/*
19374 			 * Start and stuff offset for partial hardware
19375 			 * checksum offload; these are currently for IPv4.
19376 			 * For full checksum offload, they are set to zero.
19377 			 */
19378 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19379 				if (af == AF_INET) {
19380 					start = IP_SIMPLE_HDR_LENGTH;
19381 					stuff = IP_SIMPLE_HDR_LENGTH +
19382 					    TCP_CHECKSUM_OFFSET;
19383 				} else {
19384 					start = IPV6_HDR_LEN;
19385 					stuff = IPV6_HDR_LEN +
19386 					    TCP_CHECKSUM_OFFSET;
19387 				}
19388 			} else {
19389 				start = stuff = 0;
19390 			}
19391 
19392 			/*
19393 			 * Create the header buffer, Multidata, as well as
19394 			 * any necessary attributes (destination address,
19395 			 * SAP and hardware checksum offload) that should
19396 			 * be associated with the Multidata message.
19397 			 */
19398 			ASSERT(cur_hdr_off == 0);
19399 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19400 			    ((md_hbuf->b_wptr += md_hbuflen),
19401 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19402 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19403 			    /* fastpath mblk */
19404 			    (af == AF_INET) ? ire->ire_dlureq_mp :
19405 			    ire->ire_nce->nce_res_mp,
19406 			    /* hardware checksum enabled */
19407 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19408 			    /* hardware checksum offsets */
19409 			    start, stuff, 0,
19410 			    /* hardware checksum flag */
19411 			    hwcksum_flags) != 0)) {
19412 legacy_send:
19413 				if (md_mp != NULL) {
19414 					/* Unlink message from the chain */
19415 					if (md_mp_head != NULL) {
19416 						err = (intptr_t)rmvb(md_mp_head,
19417 						    md_mp);
19418 						/*
19419 						 * We can't assert that rmvb
19420 						 * did not return -1, since we
19421 						 * may get here before linkb
19422 						 * happens.  We do, however,
19423 						 * check if we just removed the
19424 						 * only element in the list.
19425 						 */
19426 						if (err == 0)
19427 							md_mp_head = NULL;
19428 					}
19429 					/* md_hbuf gets freed automatically */
19430 					TCP_STAT(tcp_mdt_discarded);
19431 					freeb(md_mp);
19432 				} else {
19433 					/* Either allocb or mmd_alloc failed */
19434 					TCP_STAT(tcp_mdt_allocfail);
19435 					if (md_hbuf != NULL)
19436 						freeb(md_hbuf);
19437 				}
19438 
19439 				/* send down what we've got so far */
19440 				if (md_mp_head != NULL) {
19441 					tcp_multisend_data(tcp, ire, ill,
19442 					    md_mp_head, obsegs, obbytes,
19443 					    &rconfirm);
19444 				}
19445 legacy_send_no_md:
19446 				if (ire != NULL)
19447 					IRE_REFRELE(ire);
19448 				/*
19449 				 * Too bad; let the legacy path handle this.
19450 				 * We specify INT_MAX for the threshold, since
19451 				 * we gave up with the Multidata processings
19452 				 * and let the old path have it all.
19453 				 */
19454 				TCP_STAT(tcp_mdt_legacy_all);
19455 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19456 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19457 				    snxt, tail_unsent, xmit_tail, local_time,
19458 				    INT_MAX));
19459 			}
19460 
19461 			/* link to any existing ones, if applicable */
19462 			TCP_STAT(tcp_mdt_allocd);
19463 			if (md_mp_head == NULL) {
19464 				md_mp_head = md_mp;
19465 			} else if (tcp_mdt_chain) {
19466 				TCP_STAT(tcp_mdt_linked);
19467 				linkb(md_mp_head, md_mp);
19468 			}
19469 		}
19470 
19471 		ASSERT(md_mp_head != NULL);
19472 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19473 		ASSERT(md_mp != NULL && mmd != NULL);
19474 		ASSERT(md_hbuf != NULL);
19475 
19476 		/*
19477 		 * Packetize the transmittable portion of the data block;
19478 		 * each data block is essentially added to the Multidata
19479 		 * as a payload buffer.  We also deal with adding more
19480 		 * than one payload buffers, which happens when the remaining
19481 		 * packetized portion of the current payload buffer is less
19482 		 * than MSS, while the next data block in transmit queue
19483 		 * has enough data to make up for one.  This "spillover"
19484 		 * case essentially creates a split-packet, where portions
19485 		 * of the packet's payload fragments may span across two
19486 		 * virtually discontiguous address blocks.
19487 		 */
19488 		seg_len = mss;
19489 		do {
19490 			len = seg_len;
19491 
19492 			ASSERT(len > 0);
19493 			ASSERT(max_pld >= 0);
19494 			ASSERT(!add_buffer || cur_pld_off == 0);
19495 
19496 			/*
19497 			 * First time around for this payload buffer; note
19498 			 * in the case of a spillover, the following has
19499 			 * been done prior to adding the split-packet
19500 			 * descriptor to Multidata, and we don't want to
19501 			 * repeat the process.
19502 			 */
19503 			if (add_buffer) {
19504 				ASSERT(mmd != NULL);
19505 				ASSERT(md_pbuf == NULL);
19506 				ASSERT(md_pbuf_nxt == NULL);
19507 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19508 
19509 				/*
19510 				 * Have we reached the limit?  We'd get to
19511 				 * this case when we're not chaining the
19512 				 * Multidata messages together, and since
19513 				 * we're done, terminate this loop.
19514 				 */
19515 				if (max_pld == 0)
19516 					break; /* done */
19517 
19518 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19519 					TCP_STAT(tcp_mdt_allocfail);
19520 					goto legacy_send; /* out_of_mem */
19521 				}
19522 
19523 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19524 				    zc_cap != NULL) {
19525 					if (!ip_md_zcopy_attr(mmd, NULL,
19526 					    zc_cap->ill_zerocopy_flags)) {
19527 						freeb(md_pbuf);
19528 						TCP_STAT(tcp_mdt_allocfail);
19529 						/* out_of_mem */
19530 						goto legacy_send;
19531 					}
19532 					zcopy = B_TRUE;
19533 				}
19534 
19535 				md_pbuf->b_rptr += base_pld_off;
19536 
19537 				/*
19538 				 * Add a payload buffer to the Multidata; this
19539 				 * operation must not fail, or otherwise our
19540 				 * logic in this routine is broken.  There
19541 				 * is no memory allocation done by the
19542 				 * routine, so any returned failure simply
19543 				 * tells us that we've done something wrong.
19544 				 *
19545 				 * A failure tells us that either we're adding
19546 				 * the same payload buffer more than once, or
19547 				 * we're trying to add more buffers than
19548 				 * allowed (max_pld calculation is wrong).
19549 				 * None of the above cases should happen, and
19550 				 * we panic because either there's horrible
19551 				 * heap corruption, and/or programming mistake.
19552 				 */
19553 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19554 				if (pbuf_idx < 0) {
19555 					cmn_err(CE_PANIC, "tcp_multisend: "
19556 					    "payload buffer logic error "
19557 					    "detected for tcp %p mmd %p "
19558 					    "pbuf %p (%d)\n",
19559 					    (void *)tcp, (void *)mmd,
19560 					    (void *)md_pbuf, pbuf_idx);
19561 				}
19562 
19563 				ASSERT(max_pld > 0);
19564 				--max_pld;
19565 				add_buffer = B_FALSE;
19566 			}
19567 
19568 			ASSERT(md_mp_head != NULL);
19569 			ASSERT(md_pbuf != NULL);
19570 			ASSERT(md_pbuf_nxt == NULL);
19571 			ASSERT(pbuf_idx != -1);
19572 			ASSERT(pbuf_idx_nxt == -1);
19573 			ASSERT(*usable > 0);
19574 
19575 			/*
19576 			 * We spillover to the next payload buffer only
19577 			 * if all of the following is true:
19578 			 *
19579 			 *   1. There is not enough data on the current
19580 			 *	payload buffer to make up `len',
19581 			 *   2. We are allowed to send `len',
19582 			 *   3. The next payload buffer length is large
19583 			 *	enough to accomodate `spill'.
19584 			 */
19585 			if ((spill = len - *tail_unsent) > 0 &&
19586 			    *usable >= len &&
19587 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19588 			    max_pld > 0) {
19589 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19590 				if (md_pbuf_nxt == NULL) {
19591 					TCP_STAT(tcp_mdt_allocfail);
19592 					goto legacy_send; /* out_of_mem */
19593 				}
19594 
19595 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19596 				    zc_cap != NULL) {
19597 					if (!ip_md_zcopy_attr(mmd, NULL,
19598 					    zc_cap->ill_zerocopy_flags)) {
19599 						freeb(md_pbuf_nxt);
19600 						TCP_STAT(tcp_mdt_allocfail);
19601 						/* out_of_mem */
19602 						goto legacy_send;
19603 					}
19604 					zcopy = B_TRUE;
19605 				}
19606 
19607 				/*
19608 				 * See comments above on the first call to
19609 				 * mmd_addpldbuf for explanation on the panic.
19610 				 */
19611 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19612 				if (pbuf_idx_nxt < 0) {
19613 					panic("tcp_multisend: "
19614 					    "next payload buffer logic error "
19615 					    "detected for tcp %p mmd %p "
19616 					    "pbuf %p (%d)\n",
19617 					    (void *)tcp, (void *)mmd,
19618 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19619 				}
19620 
19621 				ASSERT(max_pld > 0);
19622 				--max_pld;
19623 			} else if (spill > 0) {
19624 				/*
19625 				 * If there's a spillover, but the following
19626 				 * xmit_tail couldn't give us enough octets
19627 				 * to reach "len", then stop the current
19628 				 * Multidata creation and let the legacy
19629 				 * tcp_send() path take over.  We don't want
19630 				 * to send the tiny segment as part of this
19631 				 * Multidata for performance reasons; instead,
19632 				 * we let the legacy path deal with grouping
19633 				 * it with the subsequent small mblks.
19634 				 */
19635 				if (*usable >= len &&
19636 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19637 					max_pld = 0;
19638 					break;	/* done */
19639 				}
19640 
19641 				/*
19642 				 * We can't spillover, and we are near
19643 				 * the end of the current payload buffer,
19644 				 * so send what's left.
19645 				 */
19646 				ASSERT(*tail_unsent > 0);
19647 				len = *tail_unsent;
19648 			}
19649 
19650 			/* tail_unsent is negated if there is a spillover */
19651 			*tail_unsent -= len;
19652 			*usable -= len;
19653 			ASSERT(*usable >= 0);
19654 
19655 			if (*usable < mss)
19656 				seg_len = *usable;
19657 			/*
19658 			 * Sender SWS avoidance; see comments in tcp_send();
19659 			 * everything else is the same, except that we only
19660 			 * do this here if there is no more data to be sent
19661 			 * following the current xmit_tail.  We don't check
19662 			 * for 1-byte urgent data because we shouldn't get
19663 			 * here if TCP_URG_VALID is set.
19664 			 */
19665 			if (*usable > 0 && *usable < mss &&
19666 			    ((md_pbuf_nxt == NULL &&
19667 			    (*xmit_tail)->b_cont == NULL) ||
19668 			    (md_pbuf_nxt != NULL &&
19669 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19670 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19671 			    (tcp->tcp_unsent -
19672 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19673 			    !tcp->tcp_zero_win_probe) {
19674 				if ((*snxt + len) == tcp->tcp_snxt &&
19675 				    (*snxt + len) == tcp->tcp_suna) {
19676 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19677 				}
19678 				done = B_TRUE;
19679 			}
19680 
19681 			/*
19682 			 * Prime pump for IP's checksumming on our behalf;
19683 			 * include the adjustment for a source route if any.
19684 			 * Do this only for software/partial hardware checksum
19685 			 * offload, as this field gets zeroed out later for
19686 			 * the full hardware checksum offload case.
19687 			 */
19688 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19689 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19690 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19691 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19692 			}
19693 
19694 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19695 			*snxt += len;
19696 
19697 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19698 			/*
19699 			 * We set the PUSH bit only if TCP has no more buffered
19700 			 * data to be transmitted (or if sender SWS avoidance
19701 			 * takes place), as opposed to setting it for every
19702 			 * last packet in the burst.
19703 			 */
19704 			if (done ||
19705 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19706 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19707 
19708 			/*
19709 			 * Set FIN bit if this is our last segment; snxt
19710 			 * already includes its length, and it will not
19711 			 * be adjusted after this point.
19712 			 */
19713 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19714 			    *snxt == tcp->tcp_fss) {
19715 				if (!tcp->tcp_fin_acked) {
19716 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19717 					BUMP_MIB(&tcp_mib, tcpOutControl);
19718 				}
19719 				if (!tcp->tcp_fin_sent) {
19720 					tcp->tcp_fin_sent = B_TRUE;
19721 					/*
19722 					 * tcp state must be ESTABLISHED
19723 					 * in order for us to get here in
19724 					 * the first place.
19725 					 */
19726 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19727 
19728 					/*
19729 					 * Upon returning from this routine,
19730 					 * tcp_wput_data() will set tcp_snxt
19731 					 * to be equal to snxt + tcp_fin_sent.
19732 					 * This is essentially the same as
19733 					 * setting it to tcp_fss + 1.
19734 					 */
19735 				}
19736 			}
19737 
19738 			tcp->tcp_last_sent_len = (ushort_t)len;
19739 
19740 			len += tcp_hdr_len;
19741 			if (tcp->tcp_ipversion == IPV4_VERSION)
19742 				tcp->tcp_ipha->ipha_length = htons(len);
19743 			else
19744 				tcp->tcp_ip6h->ip6_plen = htons(len -
19745 				    ((char *)&tcp->tcp_ip6h[1] -
19746 				    tcp->tcp_iphc));
19747 
19748 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19749 
19750 			/* setup header fragment */
19751 			PDESC_HDR_ADD(pkt_info,
19752 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19753 			    tcp->tcp_mdt_hdr_head,		/* head room */
19754 			    tcp_hdr_len,			/* len */
19755 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19756 
19757 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
19758 			    hdr_frag_sz);
19759 			ASSERT(MBLKIN(md_hbuf,
19760 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
19761 			    PDESC_HDRSIZE(pkt_info)));
19762 
19763 			/* setup first payload fragment */
19764 			PDESC_PLD_INIT(pkt_info);
19765 			PDESC_PLD_SPAN_ADD(pkt_info,
19766 			    pbuf_idx,				/* index */
19767 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
19768 			    tcp->tcp_last_sent_len);		/* len */
19769 
19770 			/* create a split-packet in case of a spillover */
19771 			if (md_pbuf_nxt != NULL) {
19772 				ASSERT(spill > 0);
19773 				ASSERT(pbuf_idx_nxt > pbuf_idx);
19774 				ASSERT(!add_buffer);
19775 
19776 				md_pbuf = md_pbuf_nxt;
19777 				md_pbuf_nxt = NULL;
19778 				pbuf_idx = pbuf_idx_nxt;
19779 				pbuf_idx_nxt = -1;
19780 				cur_pld_off = spill;
19781 
19782 				/* trim out first payload fragment */
19783 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
19784 
19785 				/* setup second payload fragment */
19786 				PDESC_PLD_SPAN_ADD(pkt_info,
19787 				    pbuf_idx,			/* index */
19788 				    md_pbuf->b_rptr,		/* start */
19789 				    spill);			/* len */
19790 
19791 				if ((*xmit_tail)->b_next == NULL) {
19792 					/*
19793 					 * Store the lbolt used for RTT
19794 					 * estimation. We can only record one
19795 					 * timestamp per mblk so we do it when
19796 					 * we reach the end of the payload
19797 					 * buffer.  Also we only take a new
19798 					 * timestamp sample when the previous
19799 					 * timed data from the same mblk has
19800 					 * been ack'ed.
19801 					 */
19802 					(*xmit_tail)->b_prev = local_time;
19803 					(*xmit_tail)->b_next =
19804 					    (mblk_t *)(uintptr_t)first_snxt;
19805 				}
19806 
19807 				first_snxt = *snxt - spill;
19808 
19809 				/*
19810 				 * Advance xmit_tail; usable could be 0 by
19811 				 * the time we got here, but we made sure
19812 				 * above that we would only spillover to
19813 				 * the next data block if usable includes
19814 				 * the spilled-over amount prior to the
19815 				 * subtraction.  Therefore, we are sure
19816 				 * that xmit_tail->b_cont can't be NULL.
19817 				 */
19818 				ASSERT((*xmit_tail)->b_cont != NULL);
19819 				*xmit_tail = (*xmit_tail)->b_cont;
19820 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19821 				    (uintptr_t)INT_MAX);
19822 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
19823 			} else {
19824 				cur_pld_off += tcp->tcp_last_sent_len;
19825 			}
19826 
19827 			/*
19828 			 * Fill in the header using the template header, and
19829 			 * add options such as time-stamp, ECN and/or SACK,
19830 			 * as needed.
19831 			 */
19832 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
19833 			    (clock_t)local_time, num_sack_blk);
19834 
19835 			/* take care of some IP header businesses */
19836 			if (af == AF_INET) {
19837 				ipha = (ipha_t *)pkt_info->hdr_rptr;
19838 
19839 				ASSERT(OK_32PTR((uchar_t *)ipha));
19840 				ASSERT(PDESC_HDRL(pkt_info) >=
19841 				    IP_SIMPLE_HDR_LENGTH);
19842 				ASSERT(ipha->ipha_version_and_hdr_length ==
19843 				    IP_SIMPLE_HDR_VERSION);
19844 
19845 				/*
19846 				 * Assign ident value for current packet; see
19847 				 * related comments in ip_wput_ire() about the
19848 				 * contract private interface with clustering
19849 				 * group.
19850 				 */
19851 				clusterwide = B_FALSE;
19852 				if (cl_inet_ipident != NULL) {
19853 					ASSERT(cl_inet_isclusterwide != NULL);
19854 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19855 					    AF_INET,
19856 					    (uint8_t *)(uintptr_t)src)) {
19857 						ipha->ipha_ident =
19858 						    (*cl_inet_ipident)
19859 						    (IPPROTO_IP, AF_INET,
19860 						    (uint8_t *)(uintptr_t)src,
19861 						    (uint8_t *)(uintptr_t)dst);
19862 						clusterwide = B_TRUE;
19863 					}
19864 				}
19865 
19866 				if (!clusterwide) {
19867 					ipha->ipha_ident = (uint16_t)
19868 					    atomic_add_32_nv(
19869 						&ire->ire_ident, 1);
19870 				}
19871 #ifndef _BIG_ENDIAN
19872 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
19873 				    (ipha->ipha_ident >> 8);
19874 #endif
19875 			} else {
19876 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
19877 
19878 				ASSERT(OK_32PTR((uchar_t *)ip6h));
19879 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
19880 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
19881 				ASSERT(PDESC_HDRL(pkt_info) >=
19882 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
19883 				    TCP_CHECKSUM_SIZE));
19884 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
19885 
19886 				if (tcp->tcp_ip_forward_progress) {
19887 					rconfirm = B_TRUE;
19888 					tcp->tcp_ip_forward_progress = B_FALSE;
19889 				}
19890 			}
19891 
19892 			/* at least one payload span, and at most two */
19893 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
19894 
19895 			/* add the packet descriptor to Multidata */
19896 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
19897 			    KM_NOSLEEP)) == NULL) {
19898 				/*
19899 				 * Any failure other than ENOMEM indicates
19900 				 * that we have passed in invalid pkt_info
19901 				 * or parameters to mmd_addpdesc, which must
19902 				 * not happen.
19903 				 *
19904 				 * EINVAL is a result of failure on boundary
19905 				 * checks against the pkt_info contents.  It
19906 				 * should not happen, and we panic because
19907 				 * either there's horrible heap corruption,
19908 				 * and/or programming mistake.
19909 				 */
19910 				if (err != ENOMEM) {
19911 					cmn_err(CE_PANIC, "tcp_multisend: "
19912 					    "pdesc logic error detected for "
19913 					    "tcp %p mmd %p pinfo %p (%d)\n",
19914 					    (void *)tcp, (void *)mmd,
19915 					    (void *)pkt_info, err);
19916 				}
19917 				TCP_STAT(tcp_mdt_addpdescfail);
19918 				goto legacy_send; /* out_of_mem */
19919 			}
19920 			ASSERT(pkt != NULL);
19921 
19922 			/* calculate IP header and TCP checksums */
19923 			if (af == AF_INET) {
19924 				/* calculate pseudo-header checksum */
19925 				cksum = (dst >> 16) + (dst & 0xFFFF) +
19926 				    (src >> 16) + (src & 0xFFFF);
19927 
19928 				/* offset for TCP header checksum */
19929 				up = IPH_TCPH_CHECKSUMP(ipha,
19930 				    IP_SIMPLE_HDR_LENGTH);
19931 			} else {
19932 				up = (uint16_t *)&ip6h->ip6_src;
19933 
19934 				/* calculate pseudo-header checksum */
19935 				cksum = up[0] + up[1] + up[2] + up[3] +
19936 				    up[4] + up[5] + up[6] + up[7] +
19937 				    up[8] + up[9] + up[10] + up[11] +
19938 				    up[12] + up[13] + up[14] + up[15];
19939 
19940 				/* Fold the initial sum */
19941 				cksum = (cksum & 0xffff) + (cksum >> 16);
19942 
19943 				up = (uint16_t *)(((uchar_t *)ip6h) +
19944 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
19945 			}
19946 
19947 			if (hwcksum_flags & HCK_FULLCKSUM) {
19948 				/* clear checksum field for hardware */
19949 				*up = 0;
19950 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
19951 				uint32_t sum;
19952 
19953 				/* pseudo-header checksumming */
19954 				sum = *up + cksum + IP_TCP_CSUM_COMP;
19955 				sum = (sum & 0xFFFF) + (sum >> 16);
19956 				*up = (sum & 0xFFFF) + (sum >> 16);
19957 			} else {
19958 				/* software checksumming */
19959 				TCP_STAT(tcp_out_sw_cksum);
19960 				TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
19961 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
19962 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
19963 				    cksum + IP_TCP_CSUM_COMP);
19964 				if (*up == 0)
19965 					*up = 0xFFFF;
19966 			}
19967 
19968 			/* IPv4 header checksum */
19969 			if (af == AF_INET) {
19970 				ipha->ipha_fragment_offset_and_flags |=
19971 				    (uint32_t)htons(ire->ire_frag_flag);
19972 
19973 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
19974 					ipha->ipha_hdr_checksum = 0;
19975 				} else {
19976 					IP_HDR_CKSUM(ipha, cksum,
19977 					    ((uint32_t *)ipha)[0],
19978 					    ((uint16_t *)ipha)[4]);
19979 				}
19980 			}
19981 
19982 			/* advance header offset */
19983 			cur_hdr_off += hdr_frag_sz;
19984 
19985 			obbytes += tcp->tcp_last_sent_len;
19986 			++obsegs;
19987 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
19988 		    *tail_unsent > 0);
19989 
19990 		if ((*xmit_tail)->b_next == NULL) {
19991 			/*
19992 			 * Store the lbolt used for RTT estimation. We can only
19993 			 * record one timestamp per mblk so we do it when we
19994 			 * reach the end of the payload buffer. Also we only
19995 			 * take a new timestamp sample when the previous timed
19996 			 * data from the same mblk has been ack'ed.
19997 			 */
19998 			(*xmit_tail)->b_prev = local_time;
19999 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20000 		}
20001 
20002 		ASSERT(*tail_unsent >= 0);
20003 		if (*tail_unsent > 0) {
20004 			/*
20005 			 * We got here because we broke out of the above
20006 			 * loop due to of one of the following cases:
20007 			 *
20008 			 *   1. len < adjusted MSS (i.e. small),
20009 			 *   2. Sender SWS avoidance,
20010 			 *   3. max_pld is zero.
20011 			 *
20012 			 * We are done for this Multidata, so trim our
20013 			 * last payload buffer (if any) accordingly.
20014 			 */
20015 			if (md_pbuf != NULL)
20016 				md_pbuf->b_wptr -= *tail_unsent;
20017 		} else if (*usable > 0) {
20018 			*xmit_tail = (*xmit_tail)->b_cont;
20019 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20020 			    (uintptr_t)INT_MAX);
20021 			*tail_unsent = (int)MBLKL(*xmit_tail);
20022 			add_buffer = B_TRUE;
20023 		}
20024 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20025 	    (tcp_mdt_chain || max_pld > 0));
20026 
20027 	/* send everything down */
20028 	tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20029 	    &rconfirm);
20030 
20031 #undef PREP_NEW_MULTIDATA
20032 #undef PREP_NEW_PBUF
20033 #undef IPVER
20034 
20035 	IRE_REFRELE(ire);
20036 	return (0);
20037 }
20038 
20039 /*
20040  * A wrapper function for sending one or more Multidata messages down to
20041  * the module below ip; this routine does not release the reference of the
20042  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20043  */
20044 static void
20045 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20046     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20047 {
20048 	uint64_t delta;
20049 	nce_t *nce;
20050 
20051 	ASSERT(ire != NULL && ill != NULL);
20052 	ASSERT(ire->ire_stq != NULL);
20053 	ASSERT(md_mp_head != NULL);
20054 	ASSERT(rconfirm != NULL);
20055 
20056 	/* adjust MIBs and IRE timestamp */
20057 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20058 	tcp->tcp_obsegs += obsegs;
20059 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
20060 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
20061 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
20062 
20063 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20064 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
20065 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
20066 	} else {
20067 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
20068 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
20069 	}
20070 
20071 	ire->ire_ob_pkt_count += obsegs;
20072 	if (ire->ire_ipif != NULL)
20073 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20074 	ire->ire_last_used_time = lbolt;
20075 
20076 	/* send it down */
20077 	putnext(ire->ire_stq, md_mp_head);
20078 
20079 	/* we're done for TCP/IPv4 */
20080 	if (tcp->tcp_ipversion == IPV4_VERSION)
20081 		return;
20082 
20083 	nce = ire->ire_nce;
20084 
20085 	ASSERT(nce != NULL);
20086 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20087 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20088 
20089 	/* reachability confirmation? */
20090 	if (*rconfirm) {
20091 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20092 		if (nce->nce_state != ND_REACHABLE) {
20093 			mutex_enter(&nce->nce_lock);
20094 			nce->nce_state = ND_REACHABLE;
20095 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20096 			mutex_exit(&nce->nce_lock);
20097 			(void) untimeout(nce->nce_timeout_id);
20098 			if (ip_debug > 2) {
20099 				/* ip1dbg */
20100 				pr_addr_dbg("tcp_multisend_data: state "
20101 				    "for %s changed to REACHABLE\n",
20102 				    AF_INET6, &ire->ire_addr_v6);
20103 			}
20104 		}
20105 		/* reset transport reachability confirmation */
20106 		*rconfirm = B_FALSE;
20107 	}
20108 
20109 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20110 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20111 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20112 
20113 	if (delta > (uint64_t)ill->ill_reachable_time) {
20114 		mutex_enter(&nce->nce_lock);
20115 		switch (nce->nce_state) {
20116 		case ND_REACHABLE:
20117 		case ND_STALE:
20118 			/*
20119 			 * ND_REACHABLE is identical to ND_STALE in this
20120 			 * specific case. If reachable time has expired for
20121 			 * this neighbor (delta is greater than reachable
20122 			 * time), conceptually, the neighbor cache is no
20123 			 * longer in REACHABLE state, but already in STALE
20124 			 * state.  So the correct transition here is to
20125 			 * ND_DELAY.
20126 			 */
20127 			nce->nce_state = ND_DELAY;
20128 			mutex_exit(&nce->nce_lock);
20129 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
20130 			if (ip_debug > 3) {
20131 				/* ip2dbg */
20132 				pr_addr_dbg("tcp_multisend_data: state "
20133 				    "for %s changed to DELAY\n",
20134 				    AF_INET6, &ire->ire_addr_v6);
20135 			}
20136 			break;
20137 		case ND_DELAY:
20138 		case ND_PROBE:
20139 			mutex_exit(&nce->nce_lock);
20140 			/* Timers have already started */
20141 			break;
20142 		case ND_UNREACHABLE:
20143 			/*
20144 			 * ndp timer has detected that this nce is
20145 			 * unreachable and initiated deleting this nce
20146 			 * and all its associated IREs. This is a race
20147 			 * where we found the ire before it was deleted
20148 			 * and have just sent out a packet using this
20149 			 * unreachable nce.
20150 			 */
20151 			mutex_exit(&nce->nce_lock);
20152 			break;
20153 		default:
20154 			ASSERT(0);
20155 		}
20156 	}
20157 }
20158 
20159 /*
20160  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20161  * scheme, and returns one of the following:
20162  *
20163  * -1 = failed allocation.
20164  *  0 = success; burst count reached, or usable send window is too small,
20165  *      and that we'd rather wait until later before sending again.
20166  *  1 = success; we are called from tcp_multisend(), and both usable send
20167  *      window and tail_unsent are greater than the MDT threshold, and thus
20168  *      Multidata Transmit should be used instead.
20169  */
20170 static int
20171 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20172     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20173     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20174     const int mdt_thres)
20175 {
20176 	int num_burst_seg = tcp->tcp_snd_burst;
20177 
20178 	for (;;) {
20179 		struct datab	*db;
20180 		tcph_t		*tcph;
20181 		uint32_t	sum;
20182 		mblk_t		*mp, *mp1;
20183 		uchar_t		*rptr;
20184 		int		len;
20185 
20186 		/*
20187 		 * If we're called by tcp_multisend(), and the amount of
20188 		 * sendable data as well as the size of current xmit_tail
20189 		 * is beyond the MDT threshold, return to the caller and
20190 		 * let the large data transmit be done using MDT.
20191 		 */
20192 		if (*usable > 0 && *usable > mdt_thres &&
20193 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20194 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20195 			ASSERT(tcp->tcp_mdt);
20196 			return (1);	/* success; do large send */
20197 		}
20198 
20199 		if (num_burst_seg-- == 0)
20200 			break;		/* success; burst count reached */
20201 
20202 		len = mss;
20203 		if (len > *usable) {
20204 			len = *usable;
20205 			if (len <= 0) {
20206 				/* Terminate the loop */
20207 				break;	/* success; too small */
20208 			}
20209 			/*
20210 			 * Sender silly-window avoidance.
20211 			 * Ignore this if we are going to send a
20212 			 * zero window probe out.
20213 			 *
20214 			 * TODO: force data into microscopic window?
20215 			 *	==> (!pushed || (unsent > usable))
20216 			 */
20217 			if (len < (tcp->tcp_max_swnd >> 1) &&
20218 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20219 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20220 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20221 				/*
20222 				 * If the retransmit timer is not running
20223 				 * we start it so that we will retransmit
20224 				 * in the case when the the receiver has
20225 				 * decremented the window.
20226 				 */
20227 				if (*snxt == tcp->tcp_snxt &&
20228 				    *snxt == tcp->tcp_suna) {
20229 					/*
20230 					 * We are not supposed to send
20231 					 * anything.  So let's wait a little
20232 					 * bit longer before breaking SWS
20233 					 * avoidance.
20234 					 *
20235 					 * What should the value be?
20236 					 * Suggestion: MAX(init rexmit time,
20237 					 * tcp->tcp_rto)
20238 					 */
20239 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20240 				}
20241 				break;	/* success; too small */
20242 			}
20243 		}
20244 
20245 		tcph = tcp->tcp_tcph;
20246 
20247 		*usable -= len; /* Approximate - can be adjusted later */
20248 		if (*usable > 0)
20249 			tcph->th_flags[0] = TH_ACK;
20250 		else
20251 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20252 
20253 		/*
20254 		 * Prime pump for IP's checksumming on our behalf
20255 		 * Include the adjustment for a source route if any.
20256 		 */
20257 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20258 		sum = (sum >> 16) + (sum & 0xFFFF);
20259 		U16_TO_ABE16(sum, tcph->th_sum);
20260 
20261 		U32_TO_ABE32(*snxt, tcph->th_seq);
20262 
20263 		/*
20264 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20265 		 * set.  For the case when TCP_FSS_VALID is the only valid
20266 		 * bit (normal active close), branch off only when we think
20267 		 * that the FIN flag needs to be set.  Note for this case,
20268 		 * that (snxt + len) may not reflect the actual seg_len,
20269 		 * as len may be further reduced in tcp_xmit_mp().  If len
20270 		 * gets modified, we will end up here again.
20271 		 */
20272 		if (tcp->tcp_valid_bits != 0 &&
20273 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20274 		    ((*snxt + len) == tcp->tcp_fss))) {
20275 			uchar_t		*prev_rptr;
20276 			uint32_t	prev_snxt = tcp->tcp_snxt;
20277 
20278 			if (*tail_unsent == 0) {
20279 				ASSERT((*xmit_tail)->b_cont != NULL);
20280 				*xmit_tail = (*xmit_tail)->b_cont;
20281 				prev_rptr = (*xmit_tail)->b_rptr;
20282 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20283 				    (*xmit_tail)->b_rptr);
20284 			} else {
20285 				prev_rptr = (*xmit_tail)->b_rptr;
20286 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20287 				    *tail_unsent;
20288 			}
20289 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20290 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20291 			/* Restore tcp_snxt so we get amount sent right. */
20292 			tcp->tcp_snxt = prev_snxt;
20293 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20294 				/*
20295 				 * If the previous timestamp is still in use,
20296 				 * don't stomp on it.
20297 				 */
20298 				if ((*xmit_tail)->b_next == NULL) {
20299 					(*xmit_tail)->b_prev = local_time;
20300 					(*xmit_tail)->b_next =
20301 					    (mblk_t *)(uintptr_t)(*snxt);
20302 				}
20303 			} else
20304 				(*xmit_tail)->b_rptr = prev_rptr;
20305 
20306 			if (mp == NULL)
20307 				return (-1);
20308 			mp1 = mp->b_cont;
20309 
20310 			tcp->tcp_last_sent_len = (ushort_t)len;
20311 			while (mp1->b_cont) {
20312 				*xmit_tail = (*xmit_tail)->b_cont;
20313 				(*xmit_tail)->b_prev = local_time;
20314 				(*xmit_tail)->b_next =
20315 				    (mblk_t *)(uintptr_t)(*snxt);
20316 				mp1 = mp1->b_cont;
20317 			}
20318 			*snxt += len;
20319 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20320 			BUMP_LOCAL(tcp->tcp_obsegs);
20321 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20322 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20323 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20324 			tcp_send_data(tcp, q, mp);
20325 			continue;
20326 		}
20327 
20328 		*snxt += len;	/* Adjust later if we don't send all of len */
20329 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20330 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20331 
20332 		if (*tail_unsent) {
20333 			/* Are the bytes above us in flight? */
20334 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20335 			if (rptr != (*xmit_tail)->b_rptr) {
20336 				*tail_unsent -= len;
20337 				tcp->tcp_last_sent_len = (ushort_t)len;
20338 				len += tcp_hdr_len;
20339 				if (tcp->tcp_ipversion == IPV4_VERSION)
20340 					tcp->tcp_ipha->ipha_length = htons(len);
20341 				else
20342 					tcp->tcp_ip6h->ip6_plen =
20343 					    htons(len -
20344 					    ((char *)&tcp->tcp_ip6h[1] -
20345 					    tcp->tcp_iphc));
20346 				mp = dupb(*xmit_tail);
20347 				if (!mp)
20348 					return (-1);	/* out_of_mem */
20349 				mp->b_rptr = rptr;
20350 				/*
20351 				 * If the old timestamp is no longer in use,
20352 				 * sample a new timestamp now.
20353 				 */
20354 				if ((*xmit_tail)->b_next == NULL) {
20355 					(*xmit_tail)->b_prev = local_time;
20356 					(*xmit_tail)->b_next =
20357 					    (mblk_t *)(uintptr_t)(*snxt-len);
20358 				}
20359 				goto must_alloc;
20360 			}
20361 		} else {
20362 			*xmit_tail = (*xmit_tail)->b_cont;
20363 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20364 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20365 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20366 			    (*xmit_tail)->b_rptr);
20367 		}
20368 
20369 		(*xmit_tail)->b_prev = local_time;
20370 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20371 
20372 		*tail_unsent -= len;
20373 		tcp->tcp_last_sent_len = (ushort_t)len;
20374 
20375 		len += tcp_hdr_len;
20376 		if (tcp->tcp_ipversion == IPV4_VERSION)
20377 			tcp->tcp_ipha->ipha_length = htons(len);
20378 		else
20379 			tcp->tcp_ip6h->ip6_plen = htons(len -
20380 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20381 
20382 		mp = dupb(*xmit_tail);
20383 		if (!mp)
20384 			return (-1);	/* out_of_mem */
20385 
20386 		len = tcp_hdr_len;
20387 		/*
20388 		 * There are four reasons to allocate a new hdr mblk:
20389 		 *  1) The bytes above us are in use by another packet
20390 		 *  2) We don't have good alignment
20391 		 *  3) The mblk is being shared
20392 		 *  4) We don't have enough room for a header
20393 		 */
20394 		rptr = mp->b_rptr - len;
20395 		if (!OK_32PTR(rptr) ||
20396 		    ((db = mp->b_datap), db->db_ref != 2) ||
20397 		    rptr < db->db_base) {
20398 			/* NOTE: we assume allocb returns an OK_32PTR */
20399 
20400 		must_alloc:;
20401 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20402 			    tcp_wroff_xtra, BPRI_MED);
20403 			if (!mp1) {
20404 				freemsg(mp);
20405 				return (-1);	/* out_of_mem */
20406 			}
20407 			mp1->b_cont = mp;
20408 			mp = mp1;
20409 			/* Leave room for Link Level header */
20410 			len = tcp_hdr_len;
20411 			rptr = &mp->b_rptr[tcp_wroff_xtra];
20412 			mp->b_wptr = &rptr[len];
20413 		}
20414 
20415 		/*
20416 		 * Fill in the header using the template header, and add
20417 		 * options such as time-stamp, ECN and/or SACK, as needed.
20418 		 */
20419 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20420 
20421 		mp->b_rptr = rptr;
20422 
20423 		if (*tail_unsent) {
20424 			int spill = *tail_unsent;
20425 
20426 			mp1 = mp->b_cont;
20427 			if (!mp1)
20428 				mp1 = mp;
20429 
20430 			/*
20431 			 * If we're a little short, tack on more mblks until
20432 			 * there is no more spillover.
20433 			 */
20434 			while (spill < 0) {
20435 				mblk_t *nmp;
20436 				int nmpsz;
20437 
20438 				nmp = (*xmit_tail)->b_cont;
20439 				nmpsz = MBLKL(nmp);
20440 
20441 				/*
20442 				 * Excess data in mblk; can we split it?
20443 				 * If MDT is enabled for the connection,
20444 				 * keep on splitting as this is a transient
20445 				 * send path.
20446 				 */
20447 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
20448 					/*
20449 					 * Don't split if stream head was
20450 					 * told to break up larger writes
20451 					 * into smaller ones.
20452 					 */
20453 					if (tcp->tcp_maxpsz > 0)
20454 						break;
20455 
20456 					/*
20457 					 * Next mblk is less than SMSS/2
20458 					 * rounded up to nearest 64-byte;
20459 					 * let it get sent as part of the
20460 					 * next segment.
20461 					 */
20462 					if (tcp->tcp_localnet &&
20463 					    !tcp->tcp_cork &&
20464 					    (nmpsz < roundup((mss >> 1), 64)))
20465 						break;
20466 				}
20467 
20468 				*xmit_tail = nmp;
20469 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
20470 				/* Stash for rtt use later */
20471 				(*xmit_tail)->b_prev = local_time;
20472 				(*xmit_tail)->b_next =
20473 				    (mblk_t *)(uintptr_t)(*snxt - len);
20474 				mp1->b_cont = dupb(*xmit_tail);
20475 				mp1 = mp1->b_cont;
20476 
20477 				spill += nmpsz;
20478 				if (mp1 == NULL) {
20479 					*tail_unsent = spill;
20480 					freemsg(mp);
20481 					return (-1);	/* out_of_mem */
20482 				}
20483 			}
20484 
20485 			/* Trim back any surplus on the last mblk */
20486 			if (spill >= 0) {
20487 				mp1->b_wptr -= spill;
20488 				*tail_unsent = spill;
20489 			} else {
20490 				/*
20491 				 * We did not send everything we could in
20492 				 * order to remain within the b_cont limit.
20493 				 */
20494 				*usable -= spill;
20495 				*snxt += spill;
20496 				tcp->tcp_last_sent_len += spill;
20497 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
20498 				/*
20499 				 * Adjust the checksum
20500 				 */
20501 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20502 				sum += spill;
20503 				sum = (sum >> 16) + (sum & 0xFFFF);
20504 				U16_TO_ABE16(sum, tcph->th_sum);
20505 				if (tcp->tcp_ipversion == IPV4_VERSION) {
20506 					sum = ntohs(
20507 					    ((ipha_t *)rptr)->ipha_length) +
20508 					    spill;
20509 					((ipha_t *)rptr)->ipha_length =
20510 					    htons(sum);
20511 				} else {
20512 					sum = ntohs(
20513 					    ((ip6_t *)rptr)->ip6_plen) +
20514 					    spill;
20515 					((ip6_t *)rptr)->ip6_plen =
20516 					    htons(sum);
20517 				}
20518 				*tail_unsent = 0;
20519 			}
20520 		}
20521 		if (tcp->tcp_ip_forward_progress) {
20522 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20523 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20524 			tcp->tcp_ip_forward_progress = B_FALSE;
20525 		}
20526 
20527 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20528 		tcp_send_data(tcp, q, mp);
20529 		BUMP_LOCAL(tcp->tcp_obsegs);
20530 	}
20531 
20532 	return (0);
20533 }
20534 
20535 /* Unlink and return any mblk that looks like it contains a MDT info */
20536 static mblk_t *
20537 tcp_mdt_info_mp(mblk_t *mp)
20538 {
20539 	mblk_t	*prev_mp;
20540 
20541 	for (;;) {
20542 		prev_mp = mp;
20543 		/* no more to process? */
20544 		if ((mp = mp->b_cont) == NULL)
20545 			break;
20546 
20547 		switch (DB_TYPE(mp)) {
20548 		case M_CTL:
20549 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20550 				continue;
20551 			ASSERT(prev_mp != NULL);
20552 			prev_mp->b_cont = mp->b_cont;
20553 			mp->b_cont = NULL;
20554 			return (mp);
20555 		default:
20556 			break;
20557 		}
20558 	}
20559 	return (mp);
20560 }
20561 
20562 /* MDT info update routine, called when IP notifies us about MDT */
20563 static void
20564 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20565 {
20566 	boolean_t prev_state;
20567 
20568 	/*
20569 	 * IP is telling us to abort MDT on this connection?  We know
20570 	 * this because the capability is only turned off when IP
20571 	 * encounters some pathological cases, e.g. link-layer change
20572 	 * where the new driver doesn't support MDT, or in situation
20573 	 * where MDT usage on the link-layer has been switched off.
20574 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20575 	 * if the link-layer doesn't support MDT, and if it does, it
20576 	 * will indicate that the feature is to be turned on.
20577 	 */
20578 	prev_state = tcp->tcp_mdt;
20579 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20580 	if (!tcp->tcp_mdt && !first) {
20581 		TCP_STAT(tcp_mdt_conn_halted3);
20582 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20583 		    (void *)tcp->tcp_connp));
20584 	}
20585 
20586 	/*
20587 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20588 	 * so disable MDT otherwise.  The checks are done here
20589 	 * and in tcp_wput_data().
20590 	 */
20591 	if (tcp->tcp_mdt &&
20592 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20593 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20594 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20595 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20596 		tcp->tcp_mdt = B_FALSE;
20597 
20598 	if (tcp->tcp_mdt) {
20599 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
20600 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
20601 			    "version (%d), expected version is %d",
20602 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
20603 			tcp->tcp_mdt = B_FALSE;
20604 			return;
20605 		}
20606 
20607 		/*
20608 		 * We need the driver to be able to handle at least three
20609 		 * spans per packet in order for tcp MDT to be utilized.
20610 		 * The first is for the header portion, while the rest are
20611 		 * needed to handle a packet that straddles across two
20612 		 * virtually non-contiguous buffers; a typical tcp packet
20613 		 * therefore consists of only two spans.  Note that we take
20614 		 * a zero as "don't care".
20615 		 */
20616 		if (mdt_capab->ill_mdt_span_limit > 0 &&
20617 		    mdt_capab->ill_mdt_span_limit < 3) {
20618 			tcp->tcp_mdt = B_FALSE;
20619 			return;
20620 		}
20621 
20622 		/* a zero means driver wants default value */
20623 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
20624 		    tcp_mdt_max_pbufs);
20625 		if (tcp->tcp_mdt_max_pld == 0)
20626 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
20627 
20628 		/* ensure 32-bit alignment */
20629 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
20630 		    mdt_capab->ill_mdt_hdr_head), 4);
20631 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
20632 		    mdt_capab->ill_mdt_hdr_tail), 4);
20633 
20634 		if (!first && !prev_state) {
20635 			TCP_STAT(tcp_mdt_conn_resumed2);
20636 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
20637 			    (void *)tcp->tcp_connp));
20638 		}
20639 	}
20640 }
20641 
20642 static void
20643 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
20644 {
20645 	conn_t *connp = tcp->tcp_connp;
20646 
20647 	ASSERT(ire != NULL);
20648 
20649 	/*
20650 	 * We may be in the fastpath here, and although we essentially do
20651 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
20652 	 * we try to keep things as brief as possible.  After all, these
20653 	 * are only best-effort checks, and we do more thorough ones prior
20654 	 * to calling tcp_multisend().
20655 	 */
20656 	if (ip_multidata_outbound && check_mdt &&
20657 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
20658 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
20659 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
20660 	    !(ire->ire_flags & RTF_MULTIRT) &&
20661 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
20662 	    CONN_IS_MD_FASTPATH(connp)) {
20663 		/* Remember the result */
20664 		connp->conn_mdt_ok = B_TRUE;
20665 
20666 		ASSERT(ill->ill_mdt_capab != NULL);
20667 		if (!ill->ill_mdt_capab->ill_mdt_on) {
20668 			/*
20669 			 * If MDT has been previously turned off in the past,
20670 			 * and we currently can do MDT (due to IPQoS policy
20671 			 * removal, etc.) then enable it for this interface.
20672 			 */
20673 			ill->ill_mdt_capab->ill_mdt_on = 1;
20674 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
20675 			    "interface %s\n", (void *)connp, ill->ill_name));
20676 		}
20677 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
20678 	}
20679 
20680 	/*
20681 	 * The goal is to reduce the number of generated tcp segments by
20682 	 * setting the maxpsz multiplier to 0; this will have an affect on
20683 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
20684 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
20685 	 * of outbound segments and incoming ACKs, thus allowing for better
20686 	 * network and system performance.  In contrast the legacy behavior
20687 	 * may result in sending less than SMSS size, because the last mblk
20688 	 * for some packets may have more data than needed to make up SMSS,
20689 	 * and the legacy code refused to "split" it.
20690 	 *
20691 	 * We apply the new behavior on following situations:
20692 	 *
20693 	 *   1) Loopback connections,
20694 	 *   2) Connections in which the remote peer is not on local subnet,
20695 	 *   3) Local subnet connections over the bge interface (see below).
20696 	 *
20697 	 * Ideally, we would like this behavior to apply for interfaces other
20698 	 * than bge.  However, doing so would negatively impact drivers which
20699 	 * perform dynamic mapping and unmapping of DMA resources, which are
20700 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
20701 	 * packet will be generated by tcp).  The bge driver does not suffer
20702 	 * from this, as it copies the mblks into pre-mapped buffers, and
20703 	 * therefore does not require more I/O resources than before.
20704 	 *
20705 	 * Otherwise, this behavior is present on all network interfaces when
20706 	 * the destination endpoint is non-local, since reducing the number
20707 	 * of packets in general is good for the network.
20708 	 *
20709 	 * TODO We need to remove this hard-coded conditional for bge once
20710 	 *	a better "self-tuning" mechanism, or a way to comprehend
20711 	 *	the driver transmit strategy is devised.  Until the solution
20712 	 *	is found and well understood, we live with this hack.
20713 	 */
20714 	if (!tcp_static_maxpsz &&
20715 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
20716 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
20717 		/* override the default value */
20718 		tcp->tcp_maxpsz = 0;
20719 
20720 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
20721 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
20722 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
20723 	}
20724 
20725 	/* set the stream head parameters accordingly */
20726 	(void) tcp_maxpsz_set(tcp, B_TRUE);
20727 }
20728 
20729 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
20730 static void
20731 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
20732 {
20733 	uchar_t	fval = *mp->b_rptr;
20734 	mblk_t	*tail;
20735 	queue_t	*q = tcp->tcp_wq;
20736 
20737 	/* TODO: How should flush interact with urgent data? */
20738 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
20739 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
20740 		/*
20741 		 * Flush only data that has not yet been put on the wire.  If
20742 		 * we flush data that we have already transmitted, life, as we
20743 		 * know it, may come to an end.
20744 		 */
20745 		tail = tcp->tcp_xmit_tail;
20746 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
20747 		tcp->tcp_xmit_tail_unsent = 0;
20748 		tcp->tcp_unsent = 0;
20749 		if (tail->b_wptr != tail->b_rptr)
20750 			tail = tail->b_cont;
20751 		if (tail) {
20752 			mblk_t **excess = &tcp->tcp_xmit_head;
20753 			for (;;) {
20754 				mblk_t *mp1 = *excess;
20755 				if (mp1 == tail)
20756 					break;
20757 				tcp->tcp_xmit_tail = mp1;
20758 				tcp->tcp_xmit_last = mp1;
20759 				excess = &mp1->b_cont;
20760 			}
20761 			*excess = NULL;
20762 			tcp_close_mpp(&tail);
20763 			if (tcp->tcp_snd_zcopy_aware)
20764 				tcp_zcopy_notify(tcp);
20765 		}
20766 		/*
20767 		 * We have no unsent data, so unsent must be less than
20768 		 * tcp_xmit_lowater, so re-enable flow.
20769 		 */
20770 		if (tcp->tcp_flow_stopped) {
20771 			tcp_clrqfull(tcp);
20772 		}
20773 	}
20774 	/*
20775 	 * TODO: you can't just flush these, you have to increase rwnd for one
20776 	 * thing.  For another, how should urgent data interact?
20777 	 */
20778 	if (fval & FLUSHR) {
20779 		*mp->b_rptr = fval & ~FLUSHW;
20780 		/* XXX */
20781 		qreply(q, mp);
20782 		return;
20783 	}
20784 	freemsg(mp);
20785 }
20786 
20787 /*
20788  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
20789  * messages.
20790  */
20791 static void
20792 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
20793 {
20794 	mblk_t	*mp1;
20795 	STRUCT_HANDLE(strbuf, sb);
20796 	uint16_t port;
20797 	queue_t 	*q = tcp->tcp_wq;
20798 	in6_addr_t	v6addr;
20799 	ipaddr_t	v4addr;
20800 	uint32_t	flowinfo = 0;
20801 	int		addrlen;
20802 
20803 	/* Make sure it is one of ours. */
20804 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20805 	case TI_GETMYNAME:
20806 	case TI_GETPEERNAME:
20807 		break;
20808 	default:
20809 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20810 		return;
20811 	}
20812 	switch (mi_copy_state(q, mp, &mp1)) {
20813 	case -1:
20814 		return;
20815 	case MI_COPY_CASE(MI_COPY_IN, 1):
20816 		break;
20817 	case MI_COPY_CASE(MI_COPY_OUT, 1):
20818 		/* Copy out the strbuf. */
20819 		mi_copyout(q, mp);
20820 		return;
20821 	case MI_COPY_CASE(MI_COPY_OUT, 2):
20822 		/* All done. */
20823 		mi_copy_done(q, mp, 0);
20824 		return;
20825 	default:
20826 		mi_copy_done(q, mp, EPROTO);
20827 		return;
20828 	}
20829 	/* Check alignment of the strbuf */
20830 	if (!OK_32PTR(mp1->b_rptr)) {
20831 		mi_copy_done(q, mp, EINVAL);
20832 		return;
20833 	}
20834 
20835 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
20836 	    (void *)mp1->b_rptr);
20837 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
20838 
20839 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
20840 		mi_copy_done(q, mp, EINVAL);
20841 		return;
20842 	}
20843 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20844 	case TI_GETMYNAME:
20845 		if (tcp->tcp_family == AF_INET) {
20846 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20847 				v4addr = tcp->tcp_ipha->ipha_src;
20848 			} else {
20849 				/* can't return an address in this case */
20850 				v4addr = 0;
20851 			}
20852 		} else {
20853 			/* tcp->tcp_family == AF_INET6 */
20854 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20855 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
20856 				    &v6addr);
20857 			} else {
20858 				v6addr = tcp->tcp_ip6h->ip6_src;
20859 			}
20860 		}
20861 		port = tcp->tcp_lport;
20862 		break;
20863 	case TI_GETPEERNAME:
20864 		if (tcp->tcp_family == AF_INET) {
20865 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20866 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
20867 				    v4addr);
20868 			} else {
20869 				/* can't return an address in this case */
20870 				v4addr = 0;
20871 			}
20872 		} else {
20873 			/* tcp->tcp_family == AF_INET6) */
20874 			v6addr = tcp->tcp_remote_v6;
20875 			if (tcp->tcp_ipversion == IPV6_VERSION) {
20876 				/*
20877 				 * No flowinfo if tcp->tcp_ipversion is v4.
20878 				 *
20879 				 * flowinfo was already initialized to zero
20880 				 * where it was declared above, so only
20881 				 * set it if ipversion is v6.
20882 				 */
20883 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
20884 				    ~IPV6_VERS_AND_FLOW_MASK;
20885 			}
20886 		}
20887 		port = tcp->tcp_fport;
20888 		break;
20889 	default:
20890 		mi_copy_done(q, mp, EPROTO);
20891 		return;
20892 	}
20893 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
20894 	if (!mp1)
20895 		return;
20896 
20897 	if (tcp->tcp_family == AF_INET) {
20898 		sin_t *sin;
20899 
20900 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
20901 		sin = (sin_t *)mp1->b_rptr;
20902 		mp1->b_wptr = (uchar_t *)&sin[1];
20903 		*sin = sin_null;
20904 		sin->sin_family = AF_INET;
20905 		sin->sin_addr.s_addr = v4addr;
20906 		sin->sin_port = port;
20907 	} else {
20908 		/* tcp->tcp_family == AF_INET6 */
20909 		sin6_t *sin6;
20910 
20911 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
20912 		sin6 = (sin6_t *)mp1->b_rptr;
20913 		mp1->b_wptr = (uchar_t *)&sin6[1];
20914 		*sin6 = sin6_null;
20915 		sin6->sin6_family = AF_INET6;
20916 		sin6->sin6_flowinfo = flowinfo;
20917 		sin6->sin6_addr = v6addr;
20918 		sin6->sin6_port = port;
20919 	}
20920 	/* Copy out the address */
20921 	mi_copyout(q, mp);
20922 }
20923 
20924 /*
20925  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
20926  * messages.
20927  */
20928 /* ARGSUSED */
20929 static void
20930 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
20931 {
20932 	conn_t 	*connp = (conn_t *)arg;
20933 	tcp_t	*tcp = connp->conn_tcp;
20934 	queue_t	*q = tcp->tcp_wq;
20935 	struct iocblk	*iocp;
20936 
20937 	ASSERT(DB_TYPE(mp) == M_IOCTL);
20938 	/*
20939 	 * Try and ASSERT the minimum possible references on the
20940 	 * conn early enough. Since we are executing on write side,
20941 	 * the connection is obviously not detached and that means
20942 	 * there is a ref each for TCP and IP. Since we are behind
20943 	 * the squeue, the minimum references needed are 3. If the
20944 	 * conn is in classifier hash list, there should be an
20945 	 * extra ref for that (we check both the possibilities).
20946 	 */
20947 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20948 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20949 
20950 	iocp = (struct iocblk *)mp->b_rptr;
20951 	switch (iocp->ioc_cmd) {
20952 	case TCP_IOC_DEFAULT_Q:
20953 		/* Wants to be the default wq. */
20954 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
20955 			iocp->ioc_error = EPERM;
20956 			iocp->ioc_count = 0;
20957 			mp->b_datap->db_type = M_IOCACK;
20958 			qreply(q, mp);
20959 			return;
20960 		}
20961 		tcp_def_q_set(tcp, mp);
20962 		return;
20963 	case _SIOCSOCKFALLBACK:
20964 		/*
20965 		 * Either sockmod is about to be popped and the socket
20966 		 * would now be treated as a plain stream, or a module
20967 		 * is about to be pushed so we could no longer use read-
20968 		 * side synchronous streams for fused loopback tcp.
20969 		 * Drain any queued data and disable direct sockfs
20970 		 * interface from now on.
20971 		 */
20972 		if (!tcp->tcp_issocket) {
20973 			DB_TYPE(mp) = M_IOCNAK;
20974 			iocp->ioc_error = EINVAL;
20975 		} else {
20976 #ifdef	_ILP32
20977 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
20978 #else
20979 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
20980 #endif
20981 			/*
20982 			 * Insert this socket into the acceptor hash.
20983 			 * We might need it for T_CONN_RES message
20984 			 */
20985 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
20986 
20987 			if (tcp->tcp_fused) {
20988 				/*
20989 				 * This is a fused loopback tcp; disable
20990 				 * read-side synchronous streams interface
20991 				 * and drain any queued data.  It is okay
20992 				 * to do this for non-synchronous streams
20993 				 * fused tcp as well.
20994 				 */
20995 				tcp_fuse_disable_pair(tcp, B_FALSE);
20996 			}
20997 			tcp->tcp_issocket = B_FALSE;
20998 			TCP_STAT(tcp_sock_fallback);
20999 
21000 			DB_TYPE(mp) = M_IOCACK;
21001 			iocp->ioc_error = 0;
21002 		}
21003 		iocp->ioc_count = 0;
21004 		iocp->ioc_rval = 0;
21005 		qreply(q, mp);
21006 		return;
21007 	}
21008 	CALL_IP_WPUT(connp, q, mp);
21009 }
21010 
21011 /*
21012  * This routine is called by tcp_wput() to handle all TPI requests.
21013  */
21014 /* ARGSUSED */
21015 static void
21016 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21017 {
21018 	conn_t 	*connp = (conn_t *)arg;
21019 	tcp_t	*tcp = connp->conn_tcp;
21020 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21021 	uchar_t *rptr;
21022 	t_scalar_t type;
21023 	int len;
21024 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
21025 
21026 	/*
21027 	 * Try and ASSERT the minimum possible references on the
21028 	 * conn early enough. Since we are executing on write side,
21029 	 * the connection is obviously not detached and that means
21030 	 * there is a ref each for TCP and IP. Since we are behind
21031 	 * the squeue, the minimum references needed are 3. If the
21032 	 * conn is in classifier hash list, there should be an
21033 	 * extra ref for that (we check both the possibilities).
21034 	 */
21035 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21036 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21037 
21038 	rptr = mp->b_rptr;
21039 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21040 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21041 		type = ((union T_primitives *)rptr)->type;
21042 		if (type == T_EXDATA_REQ) {
21043 			uint32_t msize = msgdsize(mp->b_cont);
21044 
21045 			len = msize - 1;
21046 			if (len < 0) {
21047 				freemsg(mp);
21048 				return;
21049 			}
21050 			/*
21051 			 * Try to force urgent data out on the wire.
21052 			 * Even if we have unsent data this will
21053 			 * at least send the urgent flag.
21054 			 * XXX does not handle more flag correctly.
21055 			 */
21056 			len += tcp->tcp_unsent;
21057 			len += tcp->tcp_snxt;
21058 			tcp->tcp_urg = len;
21059 			tcp->tcp_valid_bits |= TCP_URG_VALID;
21060 
21061 			/* Bypass tcp protocol for fused tcp loopback */
21062 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
21063 				return;
21064 		} else if (type != T_DATA_REQ) {
21065 			goto non_urgent_data;
21066 		}
21067 		/* TODO: options, flags, ... from user */
21068 		/* Set length to zero for reclamation below */
21069 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21070 		freeb(mp);
21071 		return;
21072 	} else {
21073 		if (tcp->tcp_debug) {
21074 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21075 			    "tcp_wput_proto, dropping one...");
21076 		}
21077 		freemsg(mp);
21078 		return;
21079 	}
21080 
21081 non_urgent_data:
21082 
21083 	switch ((int)tprim->type) {
21084 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21085 		/*
21086 		 * save the kssl_ent_t from the next block, and convert this
21087 		 * back to a normal bind_req.
21088 		 */
21089 		if (mp->b_cont != NULL) {
21090 		    ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21091 
21092 			if (tcp->tcp_kssl_ent != NULL) {
21093 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21094 				    KSSL_NO_PROXY);
21095 				tcp->tcp_kssl_ent = NULL;
21096 			}
21097 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21098 			    sizeof (kssl_ent_t));
21099 			kssl_hold_ent(tcp->tcp_kssl_ent);
21100 			freemsg(mp->b_cont);
21101 			mp->b_cont = NULL;
21102 		}
21103 		tprim->type = T_BIND_REQ;
21104 
21105 	/* FALLTHROUGH */
21106 	case O_T_BIND_REQ:	/* bind request */
21107 	case T_BIND_REQ:	/* new semantics bind request */
21108 		tcp_bind(tcp, mp);
21109 		break;
21110 	case T_UNBIND_REQ:	/* unbind request */
21111 		tcp_unbind(tcp, mp);
21112 		break;
21113 	case O_T_CONN_RES:	/* old connection response XXX */
21114 	case T_CONN_RES:	/* connection response */
21115 		tcp_accept(tcp, mp);
21116 		break;
21117 	case T_CONN_REQ:	/* connection request */
21118 		tcp_connect(tcp, mp);
21119 		break;
21120 	case T_DISCON_REQ:	/* disconnect request */
21121 		tcp_disconnect(tcp, mp);
21122 		break;
21123 	case T_CAPABILITY_REQ:
21124 		tcp_capability_req(tcp, mp);	/* capability request */
21125 		break;
21126 	case T_INFO_REQ:	/* information request */
21127 		tcp_info_req(tcp, mp);
21128 		break;
21129 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21130 		/* Only IP is allowed to return meaningful value */
21131 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21132 		break;
21133 	case T_OPTMGMT_REQ:
21134 		/*
21135 		 * Note:  no support for snmpcom_req() through new
21136 		 * T_OPTMGMT_REQ. See comments in ip.c
21137 		 */
21138 		/* Only IP is allowed to return meaningful value */
21139 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21140 		break;
21141 
21142 	case T_UNITDATA_REQ:	/* unitdata request */
21143 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21144 		break;
21145 	case T_ORDREL_REQ:	/* orderly release req */
21146 		freemsg(mp);
21147 
21148 		if (tcp->tcp_fused)
21149 			tcp_unfuse(tcp);
21150 
21151 		if (tcp_xmit_end(tcp) != 0) {
21152 			/*
21153 			 * We were crossing FINs and got a reset from
21154 			 * the other side. Just ignore it.
21155 			 */
21156 			if (tcp->tcp_debug) {
21157 				(void) strlog(TCP_MOD_ID, 0, 1,
21158 				    SL_ERROR|SL_TRACE,
21159 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21160 				    "state %s",
21161 				    tcp_display(tcp, NULL,
21162 				    DISP_ADDR_AND_PORT));
21163 			}
21164 		}
21165 		break;
21166 	case T_ADDR_REQ:
21167 		tcp_addr_req(tcp, mp);
21168 		break;
21169 	default:
21170 		if (tcp->tcp_debug) {
21171 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21172 			    "tcp_wput_proto, bogus TPI msg, type %d",
21173 			    tprim->type);
21174 		}
21175 		/*
21176 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21177 		 * to recover.
21178 		 */
21179 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21180 		break;
21181 	}
21182 }
21183 
21184 /*
21185  * The TCP write service routine should never be called...
21186  */
21187 /* ARGSUSED */
21188 static void
21189 tcp_wsrv(queue_t *q)
21190 {
21191 	TCP_STAT(tcp_wsrv_called);
21192 }
21193 
21194 /* Non overlapping byte exchanger */
21195 static void
21196 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21197 {
21198 	uchar_t	uch;
21199 
21200 	while (len-- > 0) {
21201 		uch = a[len];
21202 		a[len] = b[len];
21203 		b[len] = uch;
21204 	}
21205 }
21206 
21207 /*
21208  * Send out a control packet on the tcp connection specified.  This routine
21209  * is typically called where we need a simple ACK or RST generated.
21210  */
21211 static void
21212 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21213 {
21214 	uchar_t		*rptr;
21215 	tcph_t		*tcph;
21216 	ipha_t		*ipha = NULL;
21217 	ip6_t		*ip6h = NULL;
21218 	uint32_t	sum;
21219 	int		tcp_hdr_len;
21220 	int		tcp_ip_hdr_len;
21221 	mblk_t		*mp;
21222 
21223 	/*
21224 	 * Save sum for use in source route later.
21225 	 */
21226 	ASSERT(tcp != NULL);
21227 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21228 	tcp_hdr_len = tcp->tcp_hdr_len;
21229 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21230 
21231 	/* If a text string is passed in with the request, pass it to strlog. */
21232 	if (str != NULL && tcp->tcp_debug) {
21233 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21234 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21235 		    str, seq, ack, ctl);
21236 	}
21237 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21238 	    BPRI_MED);
21239 	if (mp == NULL) {
21240 		return;
21241 	}
21242 	rptr = &mp->b_rptr[tcp_wroff_xtra];
21243 	mp->b_rptr = rptr;
21244 	mp->b_wptr = &rptr[tcp_hdr_len];
21245 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21246 
21247 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21248 		ipha = (ipha_t *)rptr;
21249 		ipha->ipha_length = htons(tcp_hdr_len);
21250 	} else {
21251 		ip6h = (ip6_t *)rptr;
21252 		ASSERT(tcp != NULL);
21253 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21254 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21255 	}
21256 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21257 	tcph->th_flags[0] = (uint8_t)ctl;
21258 	if (ctl & TH_RST) {
21259 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21260 		BUMP_MIB(&tcp_mib, tcpOutControl);
21261 		/*
21262 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21263 		 */
21264 		if (tcp->tcp_snd_ts_ok &&
21265 		    tcp->tcp_state > TCPS_SYN_SENT) {
21266 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21267 			*(mp->b_wptr) = TCPOPT_EOL;
21268 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21269 				ipha->ipha_length = htons(tcp_hdr_len -
21270 				    TCPOPT_REAL_TS_LEN);
21271 			} else {
21272 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21273 				    TCPOPT_REAL_TS_LEN);
21274 			}
21275 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21276 			sum -= TCPOPT_REAL_TS_LEN;
21277 		}
21278 	}
21279 	if (ctl & TH_ACK) {
21280 		if (tcp->tcp_snd_ts_ok) {
21281 			U32_TO_BE32(lbolt,
21282 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21283 			U32_TO_BE32(tcp->tcp_ts_recent,
21284 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21285 		}
21286 
21287 		/* Update the latest receive window size in TCP header. */
21288 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21289 		    tcph->th_win);
21290 		tcp->tcp_rack = ack;
21291 		tcp->tcp_rack_cnt = 0;
21292 		BUMP_MIB(&tcp_mib, tcpOutAck);
21293 	}
21294 	BUMP_LOCAL(tcp->tcp_obsegs);
21295 	U32_TO_BE32(seq, tcph->th_seq);
21296 	U32_TO_BE32(ack, tcph->th_ack);
21297 	/*
21298 	 * Include the adjustment for a source route if any.
21299 	 */
21300 	sum = (sum >> 16) + (sum & 0xFFFF);
21301 	U16_TO_BE16(sum, tcph->th_sum);
21302 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21303 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21304 }
21305 
21306 /*
21307  * If this routine returns B_TRUE, TCP can generate a RST in response
21308  * to a segment.  If it returns B_FALSE, TCP should not respond.
21309  */
21310 static boolean_t
21311 tcp_send_rst_chk(void)
21312 {
21313 	clock_t	now;
21314 
21315 	/*
21316 	 * TCP needs to protect itself from generating too many RSTs.
21317 	 * This can be a DoS attack by sending us random segments
21318 	 * soliciting RSTs.
21319 	 *
21320 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21321 	 * in each 1 second interval.  In this way, TCP still generate
21322 	 * RSTs in normal cases but when under attack, the impact is
21323 	 * limited.
21324 	 */
21325 	if (tcp_rst_sent_rate_enabled != 0) {
21326 		now = lbolt;
21327 		/* lbolt can wrap around. */
21328 		if ((tcp_last_rst_intrvl > now) ||
21329 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
21330 			tcp_last_rst_intrvl = now;
21331 			tcp_rst_cnt = 1;
21332 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
21333 			return (B_FALSE);
21334 		}
21335 	}
21336 	return (B_TRUE);
21337 }
21338 
21339 /*
21340  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21341  */
21342 static void
21343 tcp_ip_ire_mark_advice(tcp_t *tcp)
21344 {
21345 	mblk_t *mp;
21346 	ipic_t *ipic;
21347 
21348 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21349 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21350 		    &ipic);
21351 	} else {
21352 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21353 		    &ipic);
21354 	}
21355 	if (mp == NULL)
21356 		return;
21357 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21358 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21359 }
21360 
21361 /*
21362  * Return an IP advice ioctl mblk and set ipic to be the pointer
21363  * to the advice structure.
21364  */
21365 static mblk_t *
21366 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21367 {
21368 	struct iocblk *ioc;
21369 	mblk_t *mp, *mp1;
21370 
21371 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21372 	if (mp == NULL)
21373 		return (NULL);
21374 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21375 	*ipic = (ipic_t *)mp->b_rptr;
21376 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21377 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21378 
21379 	bcopy(addr, *ipic + 1, addr_len);
21380 
21381 	(*ipic)->ipic_addr_length = addr_len;
21382 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21383 
21384 	mp1 = mkiocb(IP_IOCTL);
21385 	if (mp1 == NULL) {
21386 		freemsg(mp);
21387 		return (NULL);
21388 	}
21389 	mp1->b_cont = mp;
21390 	ioc = (struct iocblk *)mp1->b_rptr;
21391 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
21392 
21393 	return (mp1);
21394 }
21395 
21396 /*
21397  * Generate a reset based on an inbound packet for which there is no active
21398  * tcp state that we can find.
21399  *
21400  * IPSEC NOTE : Try to send the reply with the same protection as it came
21401  * in.  We still have the ipsec_mp that the packet was attached to. Thus
21402  * the packet will go out at the same level of protection as it came in by
21403  * converting the IPSEC_IN to IPSEC_OUT.
21404  */
21405 static void
21406 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
21407     uint32_t ack, int ctl, uint_t ip_hdr_len)
21408 {
21409 	ipha_t		*ipha = NULL;
21410 	ip6_t		*ip6h = NULL;
21411 	ushort_t	len;
21412 	tcph_t		*tcph;
21413 	int		i;
21414 	mblk_t		*ipsec_mp;
21415 	boolean_t	mctl_present;
21416 	ipic_t		*ipic;
21417 	ipaddr_t	v4addr;
21418 	in6_addr_t	v6addr;
21419 	int		addr_len;
21420 	void		*addr;
21421 	queue_t		*q = tcp_g_q;
21422 	tcp_t		*tcp = Q_TO_TCP(q);
21423 	cred_t		*cr;
21424 
21425 	if (!tcp_send_rst_chk()) {
21426 		tcp_rst_unsent++;
21427 		freemsg(mp);
21428 		return;
21429 	}
21430 
21431 	if (mp->b_datap->db_type == M_CTL) {
21432 		ipsec_mp = mp;
21433 		mp = mp->b_cont;
21434 		mctl_present = B_TRUE;
21435 	} else {
21436 		ipsec_mp = mp;
21437 		mctl_present = B_FALSE;
21438 	}
21439 
21440 	if (str && q && tcp_dbg) {
21441 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21442 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
21443 		    "flags 0x%x",
21444 		    str, seq, ack, ctl);
21445 	}
21446 	if (mp->b_datap->db_ref != 1) {
21447 		mblk_t *mp1 = copyb(mp);
21448 		freemsg(mp);
21449 		mp = mp1;
21450 		if (!mp) {
21451 			if (mctl_present)
21452 				freeb(ipsec_mp);
21453 			return;
21454 		} else {
21455 			if (mctl_present) {
21456 				ipsec_mp->b_cont = mp;
21457 			} else {
21458 				ipsec_mp = mp;
21459 			}
21460 		}
21461 	} else if (mp->b_cont) {
21462 		freemsg(mp->b_cont);
21463 		mp->b_cont = NULL;
21464 	}
21465 	/*
21466 	 * We skip reversing source route here.
21467 	 * (for now we replace all IP options with EOL)
21468 	 */
21469 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21470 		ipha = (ipha_t *)mp->b_rptr;
21471 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
21472 			mp->b_rptr[i] = IPOPT_EOL;
21473 		/*
21474 		 * Make sure that src address isn't flagrantly invalid.
21475 		 * Not all broadcast address checking for the src address
21476 		 * is possible, since we don't know the netmask of the src
21477 		 * addr.  No check for destination address is done, since
21478 		 * IP will not pass up a packet with a broadcast dest
21479 		 * address to TCP.  Similar checks are done below for IPv6.
21480 		 */
21481 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
21482 		    CLASSD(ipha->ipha_src)) {
21483 			freemsg(ipsec_mp);
21484 			BUMP_MIB(&ip_mib, ipInDiscards);
21485 			return;
21486 		}
21487 	} else {
21488 		ip6h = (ip6_t *)mp->b_rptr;
21489 
21490 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
21491 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
21492 			freemsg(ipsec_mp);
21493 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
21494 			return;
21495 		}
21496 
21497 		/* Remove any extension headers assuming partial overlay */
21498 		if (ip_hdr_len > IPV6_HDR_LEN) {
21499 			uint8_t *to;
21500 
21501 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
21502 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
21503 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
21504 			ip_hdr_len = IPV6_HDR_LEN;
21505 			ip6h = (ip6_t *)mp->b_rptr;
21506 			ip6h->ip6_nxt = IPPROTO_TCP;
21507 		}
21508 	}
21509 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
21510 	if (tcph->th_flags[0] & TH_RST) {
21511 		freemsg(ipsec_mp);
21512 		return;
21513 	}
21514 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
21515 	len = ip_hdr_len + sizeof (tcph_t);
21516 	mp->b_wptr = &mp->b_rptr[len];
21517 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21518 		ipha->ipha_length = htons(len);
21519 		/* Swap addresses */
21520 		v4addr = ipha->ipha_src;
21521 		ipha->ipha_src = ipha->ipha_dst;
21522 		ipha->ipha_dst = v4addr;
21523 		ipha->ipha_ident = 0;
21524 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
21525 		addr_len = IP_ADDR_LEN;
21526 		addr = &v4addr;
21527 	} else {
21528 		/* No ip6i_t in this case */
21529 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
21530 		/* Swap addresses */
21531 		v6addr = ip6h->ip6_src;
21532 		ip6h->ip6_src = ip6h->ip6_dst;
21533 		ip6h->ip6_dst = v6addr;
21534 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21535 		addr_len = IPV6_ADDR_LEN;
21536 		addr = &v6addr;
21537 	}
21538 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21539 	U32_TO_BE32(ack, tcph->th_ack);
21540 	U32_TO_BE32(seq, tcph->th_seq);
21541 	U16_TO_BE16(0, tcph->th_win);
21542 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21543 	tcph->th_flags[0] = (uint8_t)ctl;
21544 	if (ctl & TH_RST) {
21545 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21546 		BUMP_MIB(&tcp_mib, tcpOutControl);
21547 	}
21548 
21549 	/* IP trusts us to set up labels when required. */
21550 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
21551 	    crgetlabel(cr) != NULL) {
21552 		int err, adjust;
21553 
21554 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
21555 			err = tsol_check_label(cr, &mp, &adjust,
21556 			    tcp->tcp_connp->conn_mac_exempt);
21557 		else
21558 			err = tsol_check_label_v6(cr, &mp, &adjust,
21559 			    tcp->tcp_connp->conn_mac_exempt);
21560 		if (mctl_present)
21561 			ipsec_mp->b_cont = mp;
21562 		else
21563 			ipsec_mp = mp;
21564 		if (err != 0) {
21565 			freemsg(ipsec_mp);
21566 			return;
21567 		}
21568 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21569 			ipha = (ipha_t *)mp->b_rptr;
21570 			adjust += ntohs(ipha->ipha_length);
21571 			ipha->ipha_length = htons(adjust);
21572 		} else {
21573 			ip6h = (ip6_t *)mp->b_rptr;
21574 		}
21575 	}
21576 
21577 	if (mctl_present) {
21578 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21579 
21580 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21581 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21582 			return;
21583 		}
21584 	}
21585 	/*
21586 	 * NOTE:  one might consider tracing a TCP packet here, but
21587 	 * this function has no active TCP state and no tcp structure
21588 	 * that has a trace buffer.  If we traced here, we would have
21589 	 * to keep a local trace buffer in tcp_record_trace().
21590 	 *
21591 	 * TSol note: The mblk that contains the incoming packet was
21592 	 * reused by tcp_xmit_listener_reset, so it already contains
21593 	 * the right credentials and we don't need to call mblk_setcred.
21594 	 * Also the conn's cred is not right since it is associated
21595 	 * with tcp_g_q.
21596 	 */
21597 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21598 
21599 	/*
21600 	 * Tell IP to mark the IRE used for this destination temporary.
21601 	 * This way, we can limit our exposure to DoS attack because IP
21602 	 * creates an IRE for each destination.  If there are too many,
21603 	 * the time to do any routing lookup will be extremely long.  And
21604 	 * the lookup can be in interrupt context.
21605 	 *
21606 	 * Note that in normal circumstances, this marking should not
21607 	 * affect anything.  It would be nice if only 1 message is
21608 	 * needed to inform IP that the IRE created for this RST should
21609 	 * not be added to the cache table.  But there is currently
21610 	 * not such communication mechanism between TCP and IP.  So
21611 	 * the best we can do now is to send the advice ioctl to IP
21612 	 * to mark the IRE temporary.
21613 	 */
21614 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21615 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21616 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21617 	}
21618 }
21619 
21620 /*
21621  * Initiate closedown sequence on an active connection.  (May be called as
21622  * writer.)  Return value zero for OK return, non-zero for error return.
21623  */
21624 static int
21625 tcp_xmit_end(tcp_t *tcp)
21626 {
21627 	ipic_t	*ipic;
21628 	mblk_t	*mp;
21629 
21630 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21631 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21632 		/*
21633 		 * Invalid state, only states TCPS_SYN_RCVD,
21634 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21635 		 */
21636 		return (-1);
21637 	}
21638 
21639 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21640 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21641 	/*
21642 	 * If there is nothing more unsent, send the FIN now.
21643 	 * Otherwise, it will go out with the last segment.
21644 	 */
21645 	if (tcp->tcp_unsent == 0) {
21646 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21647 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21648 
21649 		if (mp) {
21650 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21651 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21652 		} else {
21653 			/*
21654 			 * Couldn't allocate msg.  Pretend we got it out.
21655 			 * Wait for rexmit timeout.
21656 			 */
21657 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21658 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21659 		}
21660 
21661 		/*
21662 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21663 		 * changed.
21664 		 */
21665 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21666 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21667 		}
21668 	} else {
21669 		/*
21670 		 * If tcp->tcp_cork is set, then the data will not get sent,
21671 		 * so we have to check that and unset it first.
21672 		 */
21673 		if (tcp->tcp_cork)
21674 			tcp->tcp_cork = B_FALSE;
21675 		tcp_wput_data(tcp, NULL, B_FALSE);
21676 	}
21677 
21678 	/*
21679 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
21680 	 * is 0, don't update the cache.
21681 	 */
21682 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
21683 		return (0);
21684 
21685 	/*
21686 	 * NOTE: should not update if source routes i.e. if tcp_remote if
21687 	 * different from the destination.
21688 	 */
21689 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21690 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
21691 			return (0);
21692 		}
21693 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21694 		    &ipic);
21695 	} else {
21696 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
21697 		    &tcp->tcp_ip6h->ip6_dst))) {
21698 			return (0);
21699 		}
21700 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21701 		    &ipic);
21702 	}
21703 
21704 	/* Record route attributes in the IRE for use by future connections. */
21705 	if (mp == NULL)
21706 		return (0);
21707 
21708 	/*
21709 	 * We do not have a good algorithm to update ssthresh at this time.
21710 	 * So don't do any update.
21711 	 */
21712 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
21713 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
21714 
21715 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21716 	return (0);
21717 }
21718 
21719 /*
21720  * Generate a "no listener here" RST in response to an "unknown" segment.
21721  * Note that we are reusing the incoming mp to construct the outgoing
21722  * RST.
21723  */
21724 void
21725 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len)
21726 {
21727 	uchar_t		*rptr;
21728 	uint32_t	seg_len;
21729 	tcph_t		*tcph;
21730 	uint32_t	seg_seq;
21731 	uint32_t	seg_ack;
21732 	uint_t		flags;
21733 	mblk_t		*ipsec_mp;
21734 	ipha_t 		*ipha;
21735 	ip6_t 		*ip6h;
21736 	boolean_t	mctl_present = B_FALSE;
21737 	boolean_t	check = B_TRUE;
21738 	boolean_t	policy_present;
21739 
21740 	TCP_STAT(tcp_no_listener);
21741 
21742 	ipsec_mp = mp;
21743 
21744 	if (mp->b_datap->db_type == M_CTL) {
21745 		ipsec_in_t *ii;
21746 
21747 		mctl_present = B_TRUE;
21748 		mp = mp->b_cont;
21749 
21750 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21751 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21752 		if (ii->ipsec_in_dont_check) {
21753 			check = B_FALSE;
21754 			if (!ii->ipsec_in_secure) {
21755 				freeb(ipsec_mp);
21756 				mctl_present = B_FALSE;
21757 				ipsec_mp = mp;
21758 			}
21759 		}
21760 	}
21761 
21762 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21763 		policy_present = ipsec_inbound_v4_policy_present;
21764 		ipha = (ipha_t *)mp->b_rptr;
21765 		ip6h = NULL;
21766 	} else {
21767 		policy_present = ipsec_inbound_v6_policy_present;
21768 		ipha = NULL;
21769 		ip6h = (ip6_t *)mp->b_rptr;
21770 	}
21771 
21772 	if (check && policy_present) {
21773 		/*
21774 		 * The conn_t parameter is NULL because we already know
21775 		 * nobody's home.
21776 		 */
21777 		ipsec_mp = ipsec_check_global_policy(
21778 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
21779 		if (ipsec_mp == NULL)
21780 			return;
21781 	}
21782 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
21783 		DTRACE_PROBE2(
21784 		    tx__ip__log__error__nolistener__tcp,
21785 		    char *, "Could not reply with RST to mp(1)",
21786 		    mblk_t *, mp);
21787 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
21788 		freemsg(ipsec_mp);
21789 		return;
21790 	}
21791 
21792 	rptr = mp->b_rptr;
21793 
21794 	tcph = (tcph_t *)&rptr[ip_hdr_len];
21795 	seg_seq = BE32_TO_U32(tcph->th_seq);
21796 	seg_ack = BE32_TO_U32(tcph->th_ack);
21797 	flags = tcph->th_flags[0];
21798 
21799 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
21800 	if (flags & TH_RST) {
21801 		freemsg(ipsec_mp);
21802 	} else if (flags & TH_ACK) {
21803 		tcp_xmit_early_reset("no tcp, reset",
21804 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len);
21805 	} else {
21806 		if (flags & TH_SYN) {
21807 			seg_len++;
21808 		} else {
21809 			/*
21810 			 * Here we violate the RFC.  Note that a normal
21811 			 * TCP will never send a segment without the ACK
21812 			 * flag, except for RST or SYN segment.  This
21813 			 * segment is neither.  Just drop it on the
21814 			 * floor.
21815 			 */
21816 			freemsg(ipsec_mp);
21817 			tcp_rst_unsent++;
21818 			return;
21819 		}
21820 
21821 		tcp_xmit_early_reset("no tcp, reset/ack",
21822 		    ipsec_mp, 0, seg_seq + seg_len,
21823 		    TH_RST | TH_ACK, ip_hdr_len);
21824 	}
21825 }
21826 
21827 /*
21828  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
21829  * ip and tcp header ready to pass down to IP.  If the mp passed in is
21830  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
21831  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
21832  * otherwise it will dup partial mblks.)
21833  * Otherwise, an appropriate ACK packet will be generated.  This
21834  * routine is not usually called to send new data for the first time.  It
21835  * is mostly called out of the timer for retransmits, and to generate ACKs.
21836  *
21837  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
21838  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
21839  * of the original mblk chain will be returned in *offset and *end_mp.
21840  */
21841 static mblk_t *
21842 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
21843     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
21844     boolean_t rexmit)
21845 {
21846 	int	data_length;
21847 	int32_t	off = 0;
21848 	uint_t	flags;
21849 	mblk_t	*mp1;
21850 	mblk_t	*mp2;
21851 	uchar_t	*rptr;
21852 	tcph_t	*tcph;
21853 	int32_t	num_sack_blk = 0;
21854 	int32_t	sack_opt_len = 0;
21855 
21856 	/* Allocate for our maximum TCP header + link-level */
21857 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21858 	    BPRI_MED);
21859 	if (!mp1)
21860 		return (NULL);
21861 	data_length = 0;
21862 
21863 	/*
21864 	 * Note that tcp_mss has been adjusted to take into account the
21865 	 * timestamp option if applicable.  Because SACK options do not
21866 	 * appear in every TCP segments and they are of variable lengths,
21867 	 * they cannot be included in tcp_mss.  Thus we need to calculate
21868 	 * the actual segment length when we need to send a segment which
21869 	 * includes SACK options.
21870 	 */
21871 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21872 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21873 		    tcp->tcp_num_sack_blk);
21874 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21875 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21876 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
21877 			max_to_send -= sack_opt_len;
21878 	}
21879 
21880 	if (offset != NULL) {
21881 		off = *offset;
21882 		/* We use offset as an indicator that end_mp is not NULL. */
21883 		*end_mp = NULL;
21884 	}
21885 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
21886 		/* This could be faster with cooperation from downstream */
21887 		if (mp2 != mp1 && !sendall &&
21888 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
21889 		    max_to_send)
21890 			/*
21891 			 * Don't send the next mblk since the whole mblk
21892 			 * does not fit.
21893 			 */
21894 			break;
21895 		mp2->b_cont = dupb(mp);
21896 		mp2 = mp2->b_cont;
21897 		if (!mp2) {
21898 			freemsg(mp1);
21899 			return (NULL);
21900 		}
21901 		mp2->b_rptr += off;
21902 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
21903 		    (uintptr_t)INT_MAX);
21904 
21905 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
21906 		if (data_length > max_to_send) {
21907 			mp2->b_wptr -= data_length - max_to_send;
21908 			data_length = max_to_send;
21909 			off = mp2->b_wptr - mp->b_rptr;
21910 			break;
21911 		} else {
21912 			off = 0;
21913 		}
21914 	}
21915 	if (offset != NULL) {
21916 		*offset = off;
21917 		*end_mp = mp;
21918 	}
21919 	if (seg_len != NULL) {
21920 		*seg_len = data_length;
21921 	}
21922 
21923 	/* Update the latest receive window size in TCP header. */
21924 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21925 	    tcp->tcp_tcph->th_win);
21926 
21927 	rptr = mp1->b_rptr + tcp_wroff_xtra;
21928 	mp1->b_rptr = rptr;
21929 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
21930 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21931 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21932 	U32_TO_ABE32(seq, tcph->th_seq);
21933 
21934 	/*
21935 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
21936 	 * that this function was called from tcp_wput_data. Thus, when called
21937 	 * to retransmit data the setting of the PUSH bit may appear some
21938 	 * what random in that it might get set when it should not. This
21939 	 * should not pose any performance issues.
21940 	 */
21941 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
21942 	    tcp->tcp_unsent == data_length)) {
21943 		flags = TH_ACK | TH_PUSH;
21944 	} else {
21945 		flags = TH_ACK;
21946 	}
21947 
21948 	if (tcp->tcp_ecn_ok) {
21949 		if (tcp->tcp_ecn_echo_on)
21950 			flags |= TH_ECE;
21951 
21952 		/*
21953 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
21954 		 * There is no TCP flow control for non-data segments, and
21955 		 * only data segment is transmitted reliably.
21956 		 */
21957 		if (data_length > 0 && !rexmit) {
21958 			SET_ECT(tcp, rptr);
21959 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
21960 				flags |= TH_CWR;
21961 				tcp->tcp_ecn_cwr_sent = B_TRUE;
21962 			}
21963 		}
21964 	}
21965 
21966 	if (tcp->tcp_valid_bits) {
21967 		uint32_t u1;
21968 
21969 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
21970 		    seq == tcp->tcp_iss) {
21971 			uchar_t	*wptr;
21972 
21973 			/*
21974 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
21975 			 * TCP can only be in SYN-SENT, SYN-RCVD or
21976 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
21977 			 * our SYN is not ack'ed but the app closes this
21978 			 * TCP connection.
21979 			 */
21980 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
21981 			    tcp->tcp_state == TCPS_SYN_RCVD ||
21982 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
21983 
21984 			/*
21985 			 * Tack on the MSS option.  It is always needed
21986 			 * for both active and passive open.
21987 			 *
21988 			 * MSS option value should be interface MTU - MIN
21989 			 * TCP/IP header according to RFC 793 as it means
21990 			 * the maximum segment size TCP can receive.  But
21991 			 * to get around some broken middle boxes/end hosts
21992 			 * out there, we allow the option value to be the
21993 			 * same as the MSS option size on the peer side.
21994 			 * In this way, the other side will not send
21995 			 * anything larger than they can receive.
21996 			 *
21997 			 * Note that for SYN_SENT state, the ndd param
21998 			 * tcp_use_smss_as_mss_opt has no effect as we
21999 			 * don't know the peer's MSS option value. So
22000 			 * the only case we need to take care of is in
22001 			 * SYN_RCVD state, which is done later.
22002 			 */
22003 			wptr = mp1->b_wptr;
22004 			wptr[0] = TCPOPT_MAXSEG;
22005 			wptr[1] = TCPOPT_MAXSEG_LEN;
22006 			wptr += 2;
22007 			u1 = tcp->tcp_if_mtu -
22008 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22009 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22010 			    TCP_MIN_HEADER_LENGTH;
22011 			U16_TO_BE16(u1, wptr);
22012 			mp1->b_wptr = wptr + 2;
22013 			/* Update the offset to cover the additional word */
22014 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22015 
22016 			/*
22017 			 * Note that the following way of filling in
22018 			 * TCP options are not optimal.  Some NOPs can
22019 			 * be saved.  But there is no need at this time
22020 			 * to optimize it.  When it is needed, we will
22021 			 * do it.
22022 			 */
22023 			switch (tcp->tcp_state) {
22024 			case TCPS_SYN_SENT:
22025 				flags = TH_SYN;
22026 
22027 				if (tcp->tcp_snd_ts_ok) {
22028 					uint32_t llbolt = (uint32_t)lbolt;
22029 
22030 					wptr = mp1->b_wptr;
22031 					wptr[0] = TCPOPT_NOP;
22032 					wptr[1] = TCPOPT_NOP;
22033 					wptr[2] = TCPOPT_TSTAMP;
22034 					wptr[3] = TCPOPT_TSTAMP_LEN;
22035 					wptr += 4;
22036 					U32_TO_BE32(llbolt, wptr);
22037 					wptr += 4;
22038 					ASSERT(tcp->tcp_ts_recent == 0);
22039 					U32_TO_BE32(0L, wptr);
22040 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22041 					tcph->th_offset_and_rsrvd[0] +=
22042 					    (3 << 4);
22043 				}
22044 
22045 				/*
22046 				 * Set up all the bits to tell other side
22047 				 * we are ECN capable.
22048 				 */
22049 				if (tcp->tcp_ecn_ok) {
22050 					flags |= (TH_ECE | TH_CWR);
22051 				}
22052 				break;
22053 			case TCPS_SYN_RCVD:
22054 				flags |= TH_SYN;
22055 
22056 				/*
22057 				 * Reset the MSS option value to be SMSS
22058 				 * We should probably add back the bytes
22059 				 * for timestamp option and IPsec.  We
22060 				 * don't do that as this is a workaround
22061 				 * for broken middle boxes/end hosts, it
22062 				 * is better for us to be more cautious.
22063 				 * They may not take these things into
22064 				 * account in their SMSS calculation.  Thus
22065 				 * the peer's calculated SMSS may be smaller
22066 				 * than what it can be.  This should be OK.
22067 				 */
22068 				if (tcp_use_smss_as_mss_opt) {
22069 					u1 = tcp->tcp_mss;
22070 					U16_TO_BE16(u1, wptr);
22071 				}
22072 
22073 				/*
22074 				 * If the other side is ECN capable, reply
22075 				 * that we are also ECN capable.
22076 				 */
22077 				if (tcp->tcp_ecn_ok)
22078 					flags |= TH_ECE;
22079 				break;
22080 			default:
22081 				/*
22082 				 * The above ASSERT() makes sure that this
22083 				 * must be FIN-WAIT-1 state.  Our SYN has
22084 				 * not been ack'ed so retransmit it.
22085 				 */
22086 				flags |= TH_SYN;
22087 				break;
22088 			}
22089 
22090 			if (tcp->tcp_snd_ws_ok) {
22091 				wptr = mp1->b_wptr;
22092 				wptr[0] =  TCPOPT_NOP;
22093 				wptr[1] =  TCPOPT_WSCALE;
22094 				wptr[2] =  TCPOPT_WS_LEN;
22095 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22096 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22097 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22098 			}
22099 
22100 			if (tcp->tcp_snd_sack_ok) {
22101 				wptr = mp1->b_wptr;
22102 				wptr[0] = TCPOPT_NOP;
22103 				wptr[1] = TCPOPT_NOP;
22104 				wptr[2] = TCPOPT_SACK_PERMITTED;
22105 				wptr[3] = TCPOPT_SACK_OK_LEN;
22106 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22107 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22108 			}
22109 
22110 			/* allocb() of adequate mblk assures space */
22111 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22112 			    (uintptr_t)INT_MAX);
22113 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22114 			/*
22115 			 * Get IP set to checksum on our behalf
22116 			 * Include the adjustment for a source route if any.
22117 			 */
22118 			u1 += tcp->tcp_sum;
22119 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22120 			U16_TO_BE16(u1, tcph->th_sum);
22121 			BUMP_MIB(&tcp_mib, tcpOutControl);
22122 		}
22123 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22124 		    (seq + data_length) == tcp->tcp_fss) {
22125 			if (!tcp->tcp_fin_acked) {
22126 				flags |= TH_FIN;
22127 				BUMP_MIB(&tcp_mib, tcpOutControl);
22128 			}
22129 			if (!tcp->tcp_fin_sent) {
22130 				tcp->tcp_fin_sent = B_TRUE;
22131 				switch (tcp->tcp_state) {
22132 				case TCPS_SYN_RCVD:
22133 				case TCPS_ESTABLISHED:
22134 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22135 					break;
22136 				case TCPS_CLOSE_WAIT:
22137 					tcp->tcp_state = TCPS_LAST_ACK;
22138 					break;
22139 				}
22140 				if (tcp->tcp_suna == tcp->tcp_snxt)
22141 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22142 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22143 			}
22144 		}
22145 		/*
22146 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22147 		 * is smaller than seq, u1 will become a very huge value.
22148 		 * So the comparison will fail.  Also note that tcp_urp
22149 		 * should be positive, see RFC 793 page 17.
22150 		 */
22151 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22152 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22153 		    u1 < (uint32_t)(64 * 1024)) {
22154 			flags |= TH_URG;
22155 			BUMP_MIB(&tcp_mib, tcpOutUrg);
22156 			U32_TO_ABE16(u1, tcph->th_urp);
22157 		}
22158 	}
22159 	tcph->th_flags[0] = (uchar_t)flags;
22160 	tcp->tcp_rack = tcp->tcp_rnxt;
22161 	tcp->tcp_rack_cnt = 0;
22162 
22163 	if (tcp->tcp_snd_ts_ok) {
22164 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22165 			uint32_t llbolt = (uint32_t)lbolt;
22166 
22167 			U32_TO_BE32(llbolt,
22168 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22169 			U32_TO_BE32(tcp->tcp_ts_recent,
22170 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22171 		}
22172 	}
22173 
22174 	if (num_sack_blk > 0) {
22175 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22176 		sack_blk_t *tmp;
22177 		int32_t	i;
22178 
22179 		wptr[0] = TCPOPT_NOP;
22180 		wptr[1] = TCPOPT_NOP;
22181 		wptr[2] = TCPOPT_SACK;
22182 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22183 		    sizeof (sack_blk_t);
22184 		wptr += TCPOPT_REAL_SACK_LEN;
22185 
22186 		tmp = tcp->tcp_sack_list;
22187 		for (i = 0; i < num_sack_blk; i++) {
22188 			U32_TO_BE32(tmp[i].begin, wptr);
22189 			wptr += sizeof (tcp_seq);
22190 			U32_TO_BE32(tmp[i].end, wptr);
22191 			wptr += sizeof (tcp_seq);
22192 		}
22193 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22194 	}
22195 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22196 	data_length += (int)(mp1->b_wptr - rptr);
22197 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22198 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22199 	} else {
22200 		ip6_t *ip6 = (ip6_t *)(rptr +
22201 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22202 		    sizeof (ip6i_t) : 0));
22203 
22204 		ip6->ip6_plen = htons(data_length -
22205 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22206 	}
22207 
22208 	/*
22209 	 * Prime pump for IP
22210 	 * Include the adjustment for a source route if any.
22211 	 */
22212 	data_length -= tcp->tcp_ip_hdr_len;
22213 	data_length += tcp->tcp_sum;
22214 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22215 	U16_TO_ABE16(data_length, tcph->th_sum);
22216 	if (tcp->tcp_ip_forward_progress) {
22217 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22218 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22219 		tcp->tcp_ip_forward_progress = B_FALSE;
22220 	}
22221 	return (mp1);
22222 }
22223 
22224 /* This function handles the push timeout. */
22225 void
22226 tcp_push_timer(void *arg)
22227 {
22228 	conn_t	*connp = (conn_t *)arg;
22229 	tcp_t *tcp = connp->conn_tcp;
22230 
22231 	TCP_DBGSTAT(tcp_push_timer_cnt);
22232 
22233 	ASSERT(tcp->tcp_listener == NULL);
22234 
22235 	/*
22236 	 * We need to stop synchronous streams temporarily to prevent a race
22237 	 * with tcp_fuse_rrw() or tcp_fusion rinfop().  It is safe to access
22238 	 * tcp_rcv_list here because those entry points will return right
22239 	 * away when synchronous streams is stopped.
22240 	 */
22241 	TCP_FUSE_SYNCSTR_STOP(tcp);
22242 	tcp->tcp_push_tid = 0;
22243 	if ((tcp->tcp_rcv_list != NULL) &&
22244 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
22245 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22246 	TCP_FUSE_SYNCSTR_RESUME(tcp);
22247 }
22248 
22249 /*
22250  * This function handles delayed ACK timeout.
22251  */
22252 static void
22253 tcp_ack_timer(void *arg)
22254 {
22255 	conn_t	*connp = (conn_t *)arg;
22256 	tcp_t *tcp = connp->conn_tcp;
22257 	mblk_t *mp;
22258 
22259 	TCP_DBGSTAT(tcp_ack_timer_cnt);
22260 
22261 	tcp->tcp_ack_tid = 0;
22262 
22263 	if (tcp->tcp_fused)
22264 		return;
22265 
22266 	/*
22267 	 * Do not send ACK if there is no outstanding unack'ed data.
22268 	 */
22269 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22270 		return;
22271 	}
22272 
22273 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22274 		/*
22275 		 * Make sure we don't allow deferred ACKs to result in
22276 		 * timer-based ACKing.  If we have held off an ACK
22277 		 * when there was more than an mss here, and the timer
22278 		 * goes off, we have to worry about the possibility
22279 		 * that the sender isn't doing slow-start, or is out
22280 		 * of step with us for some other reason.  We fall
22281 		 * permanently back in the direction of
22282 		 * ACK-every-other-packet as suggested in RFC 1122.
22283 		 */
22284 		if (tcp->tcp_rack_abs_max > 2)
22285 			tcp->tcp_rack_abs_max--;
22286 		tcp->tcp_rack_cur_max = 2;
22287 	}
22288 	mp = tcp_ack_mp(tcp);
22289 
22290 	if (mp != NULL) {
22291 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22292 		BUMP_LOCAL(tcp->tcp_obsegs);
22293 		BUMP_MIB(&tcp_mib, tcpOutAck);
22294 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
22295 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22296 	}
22297 }
22298 
22299 
22300 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22301 static mblk_t *
22302 tcp_ack_mp(tcp_t *tcp)
22303 {
22304 	uint32_t	seq_no;
22305 
22306 	/*
22307 	 * There are a few cases to be considered while setting the sequence no.
22308 	 * Essentially, we can come here while processing an unacceptable pkt
22309 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
22310 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
22311 	 * If we are here for a zero window probe, stick with suna. In all
22312 	 * other cases, we check if suna + swnd encompasses snxt and set
22313 	 * the sequence number to snxt, if so. If snxt falls outside the
22314 	 * window (the receiver probably shrunk its window), we will go with
22315 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
22316 	 * receiver.
22317 	 */
22318 	if (tcp->tcp_zero_win_probe) {
22319 		seq_no = tcp->tcp_suna;
22320 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
22321 		ASSERT(tcp->tcp_swnd == 0);
22322 		seq_no = tcp->tcp_snxt;
22323 	} else {
22324 		seq_no = SEQ_GT(tcp->tcp_snxt,
22325 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
22326 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
22327 	}
22328 
22329 	if (tcp->tcp_valid_bits) {
22330 		/*
22331 		 * For the complex case where we have to send some
22332 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
22333 		 */
22334 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
22335 		    NULL, B_FALSE));
22336 	} else {
22337 		/* Generate a simple ACK */
22338 		int	data_length;
22339 		uchar_t	*rptr;
22340 		tcph_t	*tcph;
22341 		mblk_t	*mp1;
22342 		int32_t	tcp_hdr_len;
22343 		int32_t	tcp_tcp_hdr_len;
22344 		int32_t	num_sack_blk = 0;
22345 		int32_t sack_opt_len;
22346 
22347 		/*
22348 		 * Allocate space for TCP + IP headers
22349 		 * and link-level header
22350 		 */
22351 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22352 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22353 			    tcp->tcp_num_sack_blk);
22354 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22355 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22356 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
22357 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
22358 		} else {
22359 			tcp_hdr_len = tcp->tcp_hdr_len;
22360 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
22361 		}
22362 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
22363 		if (!mp1)
22364 			return (NULL);
22365 
22366 		/* Update the latest receive window size in TCP header. */
22367 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22368 		    tcp->tcp_tcph->th_win);
22369 		/* copy in prototype TCP + IP header */
22370 		rptr = mp1->b_rptr + tcp_wroff_xtra;
22371 		mp1->b_rptr = rptr;
22372 		mp1->b_wptr = rptr + tcp_hdr_len;
22373 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22374 
22375 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22376 
22377 		/* Set the TCP sequence number. */
22378 		U32_TO_ABE32(seq_no, tcph->th_seq);
22379 
22380 		/* Set up the TCP flag field. */
22381 		tcph->th_flags[0] = (uchar_t)TH_ACK;
22382 		if (tcp->tcp_ecn_echo_on)
22383 			tcph->th_flags[0] |= TH_ECE;
22384 
22385 		tcp->tcp_rack = tcp->tcp_rnxt;
22386 		tcp->tcp_rack_cnt = 0;
22387 
22388 		/* fill in timestamp option if in use */
22389 		if (tcp->tcp_snd_ts_ok) {
22390 			uint32_t llbolt = (uint32_t)lbolt;
22391 
22392 			U32_TO_BE32(llbolt,
22393 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22394 			U32_TO_BE32(tcp->tcp_ts_recent,
22395 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22396 		}
22397 
22398 		/* Fill in SACK options */
22399 		if (num_sack_blk > 0) {
22400 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22401 			sack_blk_t *tmp;
22402 			int32_t	i;
22403 
22404 			wptr[0] = TCPOPT_NOP;
22405 			wptr[1] = TCPOPT_NOP;
22406 			wptr[2] = TCPOPT_SACK;
22407 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22408 			    sizeof (sack_blk_t);
22409 			wptr += TCPOPT_REAL_SACK_LEN;
22410 
22411 			tmp = tcp->tcp_sack_list;
22412 			for (i = 0; i < num_sack_blk; i++) {
22413 				U32_TO_BE32(tmp[i].begin, wptr);
22414 				wptr += sizeof (tcp_seq);
22415 				U32_TO_BE32(tmp[i].end, wptr);
22416 				wptr += sizeof (tcp_seq);
22417 			}
22418 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
22419 			    << 4);
22420 		}
22421 
22422 		if (tcp->tcp_ipversion == IPV4_VERSION) {
22423 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
22424 		} else {
22425 			/* Check for ip6i_t header in sticky hdrs */
22426 			ip6_t *ip6 = (ip6_t *)(rptr +
22427 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22428 			    sizeof (ip6i_t) : 0));
22429 
22430 			ip6->ip6_plen = htons(tcp_hdr_len -
22431 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22432 		}
22433 
22434 		/*
22435 		 * Prime pump for checksum calculation in IP.  Include the
22436 		 * adjustment for a source route if any.
22437 		 */
22438 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
22439 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
22440 		U16_TO_ABE16(data_length, tcph->th_sum);
22441 
22442 		if (tcp->tcp_ip_forward_progress) {
22443 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22444 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22445 			tcp->tcp_ip_forward_progress = B_FALSE;
22446 		}
22447 		return (mp1);
22448 	}
22449 }
22450 
22451 /*
22452  * To create a temporary tcp structure for inserting into bind hash list.
22453  * The parameter is assumed to be in network byte order, ready for use.
22454  */
22455 /* ARGSUSED */
22456 static tcp_t *
22457 tcp_alloc_temp_tcp(in_port_t port)
22458 {
22459 	conn_t	*connp;
22460 	tcp_t	*tcp;
22461 
22462 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
22463 	if (connp == NULL)
22464 		return (NULL);
22465 
22466 	tcp = connp->conn_tcp;
22467 
22468 	/*
22469 	 * Only initialize the necessary info in those structures.  Note
22470 	 * that since INADDR_ANY is all 0, we do not need to set
22471 	 * tcp_bound_source to INADDR_ANY here.
22472 	 */
22473 	tcp->tcp_state = TCPS_BOUND;
22474 	tcp->tcp_lport = port;
22475 	tcp->tcp_exclbind = 1;
22476 	tcp->tcp_reserved_port = 1;
22477 
22478 	/* Just for place holding... */
22479 	tcp->tcp_ipversion = IPV4_VERSION;
22480 
22481 	return (tcp);
22482 }
22483 
22484 /*
22485  * To remove a port range specified by lo_port and hi_port from the
22486  * reserved port ranges.  This is one of the three public functions of
22487  * the reserved port interface.  Note that a port range has to be removed
22488  * as a whole.  Ports in a range cannot be removed individually.
22489  *
22490  * Params:
22491  *	in_port_t lo_port: the beginning port of the reserved port range to
22492  *		be deleted.
22493  *	in_port_t hi_port: the ending port of the reserved port range to
22494  *		be deleted.
22495  *
22496  * Return:
22497  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
22498  */
22499 boolean_t
22500 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
22501 {
22502 	int	i, j;
22503 	int	size;
22504 	tcp_t	**temp_tcp_array;
22505 	tcp_t	*tcp;
22506 
22507 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22508 
22509 	/* First make sure that the port ranage is indeed reserved. */
22510 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22511 		if (tcp_reserved_port[i].lo_port == lo_port) {
22512 			hi_port = tcp_reserved_port[i].hi_port;
22513 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
22514 			break;
22515 		}
22516 	}
22517 	if (i == tcp_reserved_port_array_size) {
22518 		rw_exit(&tcp_reserved_port_lock);
22519 		return (B_FALSE);
22520 	}
22521 
22522 	/*
22523 	 * Remove the range from the array.  This simple loop is possible
22524 	 * because port ranges are inserted in ascending order.
22525 	 */
22526 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
22527 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
22528 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
22529 		tcp_reserved_port[j].temp_tcp_array =
22530 		    tcp_reserved_port[j+1].temp_tcp_array;
22531 	}
22532 
22533 	/* Remove all the temporary tcp structures. */
22534 	size = hi_port - lo_port + 1;
22535 	while (size > 0) {
22536 		tcp = temp_tcp_array[size - 1];
22537 		ASSERT(tcp != NULL);
22538 		tcp_bind_hash_remove(tcp);
22539 		CONN_DEC_REF(tcp->tcp_connp);
22540 		size--;
22541 	}
22542 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
22543 	tcp_reserved_port_array_size--;
22544 	rw_exit(&tcp_reserved_port_lock);
22545 	return (B_TRUE);
22546 }
22547 
22548 /*
22549  * Macro to remove temporary tcp structure from the bind hash list.  The
22550  * first parameter is the list of tcp to be removed.  The second parameter
22551  * is the number of tcps in the array.
22552  */
22553 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
22554 { \
22555 	while ((num) > 0) { \
22556 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
22557 		tf_t *tbf; \
22558 		tcp_t *tcpnext; \
22559 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
22560 		mutex_enter(&tbf->tf_lock); \
22561 		tcpnext = tcp->tcp_bind_hash; \
22562 		if (tcpnext) { \
22563 			tcpnext->tcp_ptpbhn = \
22564 				tcp->tcp_ptpbhn; \
22565 		} \
22566 		*tcp->tcp_ptpbhn = tcpnext; \
22567 		mutex_exit(&tbf->tf_lock); \
22568 		kmem_free(tcp, sizeof (tcp_t)); \
22569 		(tcp_array)[(num) - 1] = NULL; \
22570 		(num)--; \
22571 	} \
22572 }
22573 
22574 /*
22575  * The public interface for other modules to call to reserve a port range
22576  * in TCP.  The caller passes in how large a port range it wants.  TCP
22577  * will try to find a range and return it via lo_port and hi_port.  This is
22578  * used by NCA's nca_conn_init.
22579  * NCA can only be used in the global zone so this only affects the global
22580  * zone's ports.
22581  *
22582  * Params:
22583  *	int size: the size of the port range to be reserved.
22584  *	in_port_t *lo_port (referenced): returns the beginning port of the
22585  *		reserved port range added.
22586  *	in_port_t *hi_port (referenced): returns the ending port of the
22587  *		reserved port range added.
22588  *
22589  * Return:
22590  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22591  */
22592 boolean_t
22593 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22594 {
22595 	tcp_t		*tcp;
22596 	tcp_t		*tmp_tcp;
22597 	tcp_t		**temp_tcp_array;
22598 	tf_t		*tbf;
22599 	in_port_t	net_port;
22600 	in_port_t	port;
22601 	int32_t		cur_size;
22602 	int		i, j;
22603 	boolean_t	used;
22604 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22605 	zoneid_t	zoneid = GLOBAL_ZONEID;
22606 
22607 	/* Sanity check. */
22608 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22609 		return (B_FALSE);
22610 	}
22611 
22612 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22613 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22614 		rw_exit(&tcp_reserved_port_lock);
22615 		return (B_FALSE);
22616 	}
22617 
22618 	/*
22619 	 * Find the starting port to try.  Since the port ranges are ordered
22620 	 * in the reserved port array, we can do a simple search here.
22621 	 */
22622 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22623 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22624 	for (i = 0; i < tcp_reserved_port_array_size;
22625 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22626 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22627 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22628 			break;
22629 		}
22630 	}
22631 	/* No available port range. */
22632 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22633 		rw_exit(&tcp_reserved_port_lock);
22634 		return (B_FALSE);
22635 	}
22636 
22637 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22638 	if (temp_tcp_array == NULL) {
22639 		rw_exit(&tcp_reserved_port_lock);
22640 		return (B_FALSE);
22641 	}
22642 
22643 	/* Go thru the port range to see if some ports are already bound. */
22644 	for (port = *lo_port, cur_size = 0;
22645 	    cur_size < size && port <= *hi_port;
22646 	    cur_size++, port++) {
22647 		used = B_FALSE;
22648 		net_port = htons(port);
22649 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22650 		mutex_enter(&tbf->tf_lock);
22651 		for (tcp = tbf->tf_tcp; tcp != NULL;
22652 		    tcp = tcp->tcp_bind_hash) {
22653 			if (IPCL_ZONE_MATCH(tcp->tcp_connp, zoneid) &&
22654 			    net_port == tcp->tcp_lport) {
22655 				/*
22656 				 * A port is already bound.  Search again
22657 				 * starting from port + 1.  Release all
22658 				 * temporary tcps.
22659 				 */
22660 				mutex_exit(&tbf->tf_lock);
22661 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22662 				*lo_port = port + 1;
22663 				cur_size = -1;
22664 				used = B_TRUE;
22665 				break;
22666 			}
22667 		}
22668 		if (!used) {
22669 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22670 				/*
22671 				 * Allocation failure.  Just fail the request.
22672 				 * Need to remove all those temporary tcp
22673 				 * structures.
22674 				 */
22675 				mutex_exit(&tbf->tf_lock);
22676 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22677 				rw_exit(&tcp_reserved_port_lock);
22678 				kmem_free(temp_tcp_array,
22679 				    (hi_port - lo_port + 1) *
22680 				    sizeof (tcp_t *));
22681 				return (B_FALSE);
22682 			}
22683 			temp_tcp_array[cur_size] = tmp_tcp;
22684 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22685 			mutex_exit(&tbf->tf_lock);
22686 		}
22687 	}
22688 
22689 	/*
22690 	 * The current range is not large enough.  We can actually do another
22691 	 * search if this search is done between 2 reserved port ranges.  But
22692 	 * for first release, we just stop here and return saying that no port
22693 	 * range is available.
22694 	 */
22695 	if (cur_size < size) {
22696 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22697 		rw_exit(&tcp_reserved_port_lock);
22698 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
22699 		return (B_FALSE);
22700 	}
22701 	*hi_port = port - 1;
22702 
22703 	/*
22704 	 * Insert range into array in ascending order.  Since this function
22705 	 * must not be called often, we choose to use the simplest method.
22706 	 * The above array should not consume excessive stack space as
22707 	 * the size must be very small.  If in future releases, we find
22708 	 * that we should provide more reserved port ranges, this function
22709 	 * has to be modified to be more efficient.
22710 	 */
22711 	if (tcp_reserved_port_array_size == 0) {
22712 		tcp_reserved_port[0].lo_port = *lo_port;
22713 		tcp_reserved_port[0].hi_port = *hi_port;
22714 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
22715 	} else {
22716 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
22717 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
22718 				tmp_ports[j].lo_port = *lo_port;
22719 				tmp_ports[j].hi_port = *hi_port;
22720 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
22721 				j++;
22722 			}
22723 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
22724 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
22725 			tmp_ports[j].temp_tcp_array =
22726 			    tcp_reserved_port[i].temp_tcp_array;
22727 		}
22728 		if (j == i) {
22729 			tmp_ports[j].lo_port = *lo_port;
22730 			tmp_ports[j].hi_port = *hi_port;
22731 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
22732 		}
22733 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
22734 	}
22735 	tcp_reserved_port_array_size++;
22736 	rw_exit(&tcp_reserved_port_lock);
22737 	return (B_TRUE);
22738 }
22739 
22740 /*
22741  * Check to see if a port is in any reserved port range.
22742  *
22743  * Params:
22744  *	in_port_t port: the port to be verified.
22745  *
22746  * Return:
22747  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
22748  */
22749 boolean_t
22750 tcp_reserved_port_check(in_port_t port)
22751 {
22752 	int i;
22753 
22754 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22755 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22756 		if (port >= tcp_reserved_port[i].lo_port ||
22757 		    port <= tcp_reserved_port[i].hi_port) {
22758 			rw_exit(&tcp_reserved_port_lock);
22759 			return (B_TRUE);
22760 		}
22761 	}
22762 	rw_exit(&tcp_reserved_port_lock);
22763 	return (B_FALSE);
22764 }
22765 
22766 /*
22767  * To list all reserved port ranges.  This is the function to handle
22768  * ndd tcp_reserved_port_list.
22769  */
22770 /* ARGSUSED */
22771 static int
22772 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22773 {
22774 	int i;
22775 
22776 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22777 	if (tcp_reserved_port_array_size > 0)
22778 		(void) mi_mpprintf(mp, "The following ports are reserved:");
22779 	else
22780 		(void) mi_mpprintf(mp, "No port is reserved.");
22781 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22782 		(void) mi_mpprintf(mp, "%d-%d",
22783 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
22784 	}
22785 	rw_exit(&tcp_reserved_port_lock);
22786 	return (0);
22787 }
22788 
22789 /*
22790  * Hash list insertion routine for tcp_t structures.
22791  * Inserts entries with the ones bound to a specific IP address first
22792  * followed by those bound to INADDR_ANY.
22793  */
22794 static void
22795 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
22796 {
22797 	tcp_t	**tcpp;
22798 	tcp_t	*tcpnext;
22799 
22800 	if (tcp->tcp_ptpbhn != NULL) {
22801 		ASSERT(!caller_holds_lock);
22802 		tcp_bind_hash_remove(tcp);
22803 	}
22804 	tcpp = &tbf->tf_tcp;
22805 	if (!caller_holds_lock) {
22806 		mutex_enter(&tbf->tf_lock);
22807 	} else {
22808 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
22809 	}
22810 	tcpnext = tcpp[0];
22811 	if (tcpnext) {
22812 		/*
22813 		 * If the new tcp bound to the INADDR_ANY address
22814 		 * and the first one in the list is not bound to
22815 		 * INADDR_ANY we skip all entries until we find the
22816 		 * first one bound to INADDR_ANY.
22817 		 * This makes sure that applications binding to a
22818 		 * specific address get preference over those binding to
22819 		 * INADDR_ANY.
22820 		 */
22821 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
22822 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
22823 			while ((tcpnext = tcpp[0]) != NULL &&
22824 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
22825 				tcpp = &(tcpnext->tcp_bind_hash);
22826 			if (tcpnext)
22827 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22828 		} else
22829 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22830 	}
22831 	tcp->tcp_bind_hash = tcpnext;
22832 	tcp->tcp_ptpbhn = tcpp;
22833 	tcpp[0] = tcp;
22834 	if (!caller_holds_lock)
22835 		mutex_exit(&tbf->tf_lock);
22836 }
22837 
22838 /*
22839  * Hash list removal routine for tcp_t structures.
22840  */
22841 static void
22842 tcp_bind_hash_remove(tcp_t *tcp)
22843 {
22844 	tcp_t	*tcpnext;
22845 	kmutex_t *lockp;
22846 
22847 	if (tcp->tcp_ptpbhn == NULL)
22848 		return;
22849 
22850 	/*
22851 	 * Extract the lock pointer in case there are concurrent
22852 	 * hash_remove's for this instance.
22853 	 */
22854 	ASSERT(tcp->tcp_lport != 0);
22855 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
22856 
22857 	ASSERT(lockp != NULL);
22858 	mutex_enter(lockp);
22859 	if (tcp->tcp_ptpbhn) {
22860 		tcpnext = tcp->tcp_bind_hash;
22861 		if (tcpnext) {
22862 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
22863 			tcp->tcp_bind_hash = NULL;
22864 		}
22865 		*tcp->tcp_ptpbhn = tcpnext;
22866 		tcp->tcp_ptpbhn = NULL;
22867 	}
22868 	mutex_exit(lockp);
22869 }
22870 
22871 
22872 /*
22873  * Hash list lookup routine for tcp_t structures.
22874  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
22875  */
22876 static tcp_t *
22877 tcp_acceptor_hash_lookup(t_uscalar_t id)
22878 {
22879 	tf_t	*tf;
22880 	tcp_t	*tcp;
22881 
22882 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22883 	mutex_enter(&tf->tf_lock);
22884 	for (tcp = tf->tf_tcp; tcp != NULL;
22885 	    tcp = tcp->tcp_acceptor_hash) {
22886 		if (tcp->tcp_acceptor_id == id) {
22887 			CONN_INC_REF(tcp->tcp_connp);
22888 			mutex_exit(&tf->tf_lock);
22889 			return (tcp);
22890 		}
22891 	}
22892 	mutex_exit(&tf->tf_lock);
22893 	return (NULL);
22894 }
22895 
22896 
22897 /*
22898  * Hash list insertion routine for tcp_t structures.
22899  */
22900 void
22901 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
22902 {
22903 	tf_t	*tf;
22904 	tcp_t	**tcpp;
22905 	tcp_t	*tcpnext;
22906 
22907 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22908 
22909 	if (tcp->tcp_ptpahn != NULL)
22910 		tcp_acceptor_hash_remove(tcp);
22911 	tcpp = &tf->tf_tcp;
22912 	mutex_enter(&tf->tf_lock);
22913 	tcpnext = tcpp[0];
22914 	if (tcpnext)
22915 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
22916 	tcp->tcp_acceptor_hash = tcpnext;
22917 	tcp->tcp_ptpahn = tcpp;
22918 	tcpp[0] = tcp;
22919 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
22920 	mutex_exit(&tf->tf_lock);
22921 }
22922 
22923 /*
22924  * Hash list removal routine for tcp_t structures.
22925  */
22926 static void
22927 tcp_acceptor_hash_remove(tcp_t *tcp)
22928 {
22929 	tcp_t	*tcpnext;
22930 	kmutex_t *lockp;
22931 
22932 	/*
22933 	 * Extract the lock pointer in case there are concurrent
22934 	 * hash_remove's for this instance.
22935 	 */
22936 	lockp = tcp->tcp_acceptor_lockp;
22937 
22938 	if (tcp->tcp_ptpahn == NULL)
22939 		return;
22940 
22941 	ASSERT(lockp != NULL);
22942 	mutex_enter(lockp);
22943 	if (tcp->tcp_ptpahn) {
22944 		tcpnext = tcp->tcp_acceptor_hash;
22945 		if (tcpnext) {
22946 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
22947 			tcp->tcp_acceptor_hash = NULL;
22948 		}
22949 		*tcp->tcp_ptpahn = tcpnext;
22950 		tcp->tcp_ptpahn = NULL;
22951 	}
22952 	mutex_exit(lockp);
22953 	tcp->tcp_acceptor_lockp = NULL;
22954 }
22955 
22956 /* ARGSUSED */
22957 static int
22958 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
22959 {
22960 	int error = 0;
22961 	int retval;
22962 	char *end;
22963 
22964 	tcp_hsp_t *hsp;
22965 	tcp_hsp_t *hspprev;
22966 
22967 	ipaddr_t addr = 0;		/* Address we're looking for */
22968 	in6_addr_t v6addr;		/* Address we're looking for */
22969 	uint32_t hash;			/* Hash of that address */
22970 
22971 	/*
22972 	 * If the following variables are still zero after parsing the input
22973 	 * string, the user didn't specify them and we don't change them in
22974 	 * the HSP.
22975 	 */
22976 
22977 	ipaddr_t mask = 0;		/* Subnet mask */
22978 	in6_addr_t v6mask;
22979 	long sendspace = 0;		/* Send buffer size */
22980 	long recvspace = 0;		/* Receive buffer size */
22981 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
22982 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
22983 
22984 	rw_enter(&tcp_hsp_lock, RW_WRITER);
22985 
22986 	/* Parse and validate address */
22987 	if (af == AF_INET) {
22988 		retval = inet_pton(af, value, &addr);
22989 		if (retval == 1)
22990 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
22991 	} else if (af == AF_INET6) {
22992 		retval = inet_pton(af, value, &v6addr);
22993 	} else {
22994 		error = EINVAL;
22995 		goto done;
22996 	}
22997 	if (retval == 0) {
22998 		error = EINVAL;
22999 		goto done;
23000 	}
23001 
23002 	while ((*value) && *value != ' ')
23003 		value++;
23004 
23005 	/* Parse individual keywords, set variables if found */
23006 	while (*value) {
23007 		/* Skip leading blanks */
23008 
23009 		while (*value == ' ' || *value == '\t')
23010 			value++;
23011 
23012 		/* If at end of string, we're done */
23013 
23014 		if (!*value)
23015 			break;
23016 
23017 		/* We have a word, figure out what it is */
23018 
23019 		if (strncmp("mask", value, 4) == 0) {
23020 			value += 4;
23021 			while (*value == ' ' || *value == '\t')
23022 				value++;
23023 			/* Parse subnet mask */
23024 			if (af == AF_INET) {
23025 				retval = inet_pton(af, value, &mask);
23026 				if (retval == 1) {
23027 					V4MASK_TO_V6(mask, v6mask);
23028 				}
23029 			} else if (af == AF_INET6) {
23030 				retval = inet_pton(af, value, &v6mask);
23031 			}
23032 			if (retval != 1) {
23033 				error = EINVAL;
23034 				goto done;
23035 			}
23036 			while ((*value) && *value != ' ')
23037 				value++;
23038 		} else if (strncmp("sendspace", value, 9) == 0) {
23039 			value += 9;
23040 
23041 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
23042 			    sendspace < TCP_XMIT_HIWATER ||
23043 			    sendspace >= (1L<<30)) {
23044 				error = EINVAL;
23045 				goto done;
23046 			}
23047 			value = end;
23048 		} else if (strncmp("recvspace", value, 9) == 0) {
23049 			value += 9;
23050 
23051 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
23052 			    recvspace < TCP_RECV_HIWATER ||
23053 			    recvspace >= (1L<<30)) {
23054 				error = EINVAL;
23055 				goto done;
23056 			}
23057 			value = end;
23058 		} else if (strncmp("timestamp", value, 9) == 0) {
23059 			value += 9;
23060 
23061 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
23062 			    timestamp < 0 || timestamp > 1) {
23063 				error = EINVAL;
23064 				goto done;
23065 			}
23066 
23067 			/*
23068 			 * We increment timestamp so we know it's been set;
23069 			 * this is undone when we put it in the HSP
23070 			 */
23071 			timestamp++;
23072 			value = end;
23073 		} else if (strncmp("delete", value, 6) == 0) {
23074 			value += 6;
23075 			delete = B_TRUE;
23076 		} else {
23077 			error = EINVAL;
23078 			goto done;
23079 		}
23080 	}
23081 
23082 	/* Hash address for lookup */
23083 
23084 	hash = TCP_HSP_HASH(addr);
23085 
23086 	if (delete) {
23087 		/*
23088 		 * Note that deletes don't return an error if the thing
23089 		 * we're trying to delete isn't there.
23090 		 */
23091 		if (tcp_hsp_hash == NULL)
23092 			goto done;
23093 		hsp = tcp_hsp_hash[hash];
23094 
23095 		if (hsp) {
23096 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23097 			    &v6addr)) {
23098 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
23099 				mi_free((char *)hsp);
23100 			} else {
23101 				hspprev = hsp;
23102 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
23103 					if (IN6_ARE_ADDR_EQUAL(
23104 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
23105 						hspprev->tcp_hsp_next =
23106 						    hsp->tcp_hsp_next;
23107 						mi_free((char *)hsp);
23108 						break;
23109 					}
23110 					hspprev = hsp;
23111 				}
23112 			}
23113 		}
23114 	} else {
23115 		/*
23116 		 * We're adding/modifying an HSP.  If we haven't already done
23117 		 * so, allocate the hash table.
23118 		 */
23119 
23120 		if (!tcp_hsp_hash) {
23121 			tcp_hsp_hash = (tcp_hsp_t **)
23122 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
23123 			if (!tcp_hsp_hash) {
23124 				error = EINVAL;
23125 				goto done;
23126 			}
23127 		}
23128 
23129 		/* Get head of hash chain */
23130 
23131 		hsp = tcp_hsp_hash[hash];
23132 
23133 		/* Try to find pre-existing hsp on hash chain */
23134 		/* Doesn't handle CIDR prefixes. */
23135 		while (hsp) {
23136 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
23137 				break;
23138 			hsp = hsp->tcp_hsp_next;
23139 		}
23140 
23141 		/*
23142 		 * If we didn't, create one with default values and put it
23143 		 * at head of hash chain
23144 		 */
23145 
23146 		if (!hsp) {
23147 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
23148 			if (!hsp) {
23149 				error = EINVAL;
23150 				goto done;
23151 			}
23152 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
23153 			tcp_hsp_hash[hash] = hsp;
23154 		}
23155 
23156 		/* Set values that the user asked us to change */
23157 
23158 		hsp->tcp_hsp_addr_v6 = v6addr;
23159 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
23160 			hsp->tcp_hsp_vers = IPV4_VERSION;
23161 		else
23162 			hsp->tcp_hsp_vers = IPV6_VERSION;
23163 		hsp->tcp_hsp_subnet_v6 = v6mask;
23164 		if (sendspace > 0)
23165 			hsp->tcp_hsp_sendspace = sendspace;
23166 		if (recvspace > 0)
23167 			hsp->tcp_hsp_recvspace = recvspace;
23168 		if (timestamp > 0)
23169 			hsp->tcp_hsp_tstamp = timestamp - 1;
23170 	}
23171 
23172 done:
23173 	rw_exit(&tcp_hsp_lock);
23174 	return (error);
23175 }
23176 
23177 /* Set callback routine passed to nd_load by tcp_param_register. */
23178 /* ARGSUSED */
23179 static int
23180 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
23181 {
23182 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
23183 }
23184 /* ARGSUSED */
23185 static int
23186 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23187     cred_t *cr)
23188 {
23189 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
23190 }
23191 
23192 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
23193 /* ARGSUSED */
23194 static int
23195 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23196 {
23197 	tcp_hsp_t *hsp;
23198 	int i;
23199 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
23200 
23201 	rw_enter(&tcp_hsp_lock, RW_READER);
23202 	(void) mi_mpprintf(mp,
23203 	    "Hash HSP     " MI_COL_HDRPAD_STR
23204 	    "Address         Subnet Mask     Send       Receive    TStamp");
23205 	if (tcp_hsp_hash) {
23206 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
23207 			hsp = tcp_hsp_hash[i];
23208 			while (hsp) {
23209 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
23210 					(void) inet_ntop(AF_INET,
23211 					    &hsp->tcp_hsp_addr,
23212 					    addrbuf, sizeof (addrbuf));
23213 					(void) inet_ntop(AF_INET,
23214 					    &hsp->tcp_hsp_subnet,
23215 					    subnetbuf, sizeof (subnetbuf));
23216 				} else {
23217 					(void) inet_ntop(AF_INET6,
23218 					    &hsp->tcp_hsp_addr_v6,
23219 					    addrbuf, sizeof (addrbuf));
23220 					(void) inet_ntop(AF_INET6,
23221 					    &hsp->tcp_hsp_subnet_v6,
23222 					    subnetbuf, sizeof (subnetbuf));
23223 				}
23224 				(void) mi_mpprintf(mp,
23225 				    " %03d " MI_COL_PTRFMT_STR
23226 				    "%s %s %010d %010d      %d",
23227 				    i,
23228 				    (void *)hsp,
23229 				    addrbuf,
23230 				    subnetbuf,
23231 				    hsp->tcp_hsp_sendspace,
23232 				    hsp->tcp_hsp_recvspace,
23233 				    hsp->tcp_hsp_tstamp);
23234 
23235 				hsp = hsp->tcp_hsp_next;
23236 			}
23237 		}
23238 	}
23239 	rw_exit(&tcp_hsp_lock);
23240 	return (0);
23241 }
23242 
23243 
23244 /* Data for fast netmask macro used by tcp_hsp_lookup */
23245 
23246 static ipaddr_t netmasks[] = {
23247 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
23248 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
23249 };
23250 
23251 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
23252 
23253 /*
23254  * XXX This routine should go away and instead we should use the metrics
23255  * associated with the routes to determine the default sndspace and rcvspace.
23256  */
23257 static tcp_hsp_t *
23258 tcp_hsp_lookup(ipaddr_t addr)
23259 {
23260 	tcp_hsp_t *hsp = NULL;
23261 
23262 	/* Quick check without acquiring the lock. */
23263 	if (tcp_hsp_hash == NULL)
23264 		return (NULL);
23265 
23266 	rw_enter(&tcp_hsp_lock, RW_READER);
23267 
23268 	/* This routine finds the best-matching HSP for address addr. */
23269 
23270 	if (tcp_hsp_hash) {
23271 		int i;
23272 		ipaddr_t srchaddr;
23273 		tcp_hsp_t *hsp_net;
23274 
23275 		/* We do three passes: host, network, and subnet. */
23276 
23277 		srchaddr = addr;
23278 
23279 		for (i = 1; i <= 3; i++) {
23280 			/* Look for exact match on srchaddr */
23281 
23282 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
23283 			while (hsp) {
23284 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
23285 				    hsp->tcp_hsp_addr == srchaddr)
23286 					break;
23287 				hsp = hsp->tcp_hsp_next;
23288 			}
23289 			ASSERT(hsp == NULL ||
23290 			    hsp->tcp_hsp_vers == IPV4_VERSION);
23291 
23292 			/*
23293 			 * If this is the first pass:
23294 			 *   If we found a match, great, return it.
23295 			 *   If not, search for the network on the second pass.
23296 			 */
23297 
23298 			if (i == 1)
23299 				if (hsp)
23300 					break;
23301 				else
23302 				{
23303 					srchaddr = addr & netmask(addr);
23304 					continue;
23305 				}
23306 
23307 			/*
23308 			 * If this is the second pass:
23309 			 *   If we found a match, but there's a subnet mask,
23310 			 *    save the match but try again using the subnet
23311 			 *    mask on the third pass.
23312 			 *   Otherwise, return whatever we found.
23313 			 */
23314 
23315 			if (i == 2) {
23316 				if (hsp && hsp->tcp_hsp_subnet) {
23317 					hsp_net = hsp;
23318 					srchaddr = addr & hsp->tcp_hsp_subnet;
23319 					continue;
23320 				} else {
23321 					break;
23322 				}
23323 			}
23324 
23325 			/*
23326 			 * This must be the third pass.  If we didn't find
23327 			 * anything, return the saved network HSP instead.
23328 			 */
23329 
23330 			if (!hsp)
23331 				hsp = hsp_net;
23332 		}
23333 	}
23334 
23335 	rw_exit(&tcp_hsp_lock);
23336 	return (hsp);
23337 }
23338 
23339 /*
23340  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
23341  * match lookup.
23342  */
23343 static tcp_hsp_t *
23344 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
23345 {
23346 	tcp_hsp_t *hsp = NULL;
23347 
23348 	/* Quick check without acquiring the lock. */
23349 	if (tcp_hsp_hash == NULL)
23350 		return (NULL);
23351 
23352 	rw_enter(&tcp_hsp_lock, RW_READER);
23353 
23354 	/* This routine finds the best-matching HSP for address addr. */
23355 
23356 	if (tcp_hsp_hash) {
23357 		int i;
23358 		in6_addr_t v6srchaddr;
23359 		tcp_hsp_t *hsp_net;
23360 
23361 		/* We do three passes: host, network, and subnet. */
23362 
23363 		v6srchaddr = *v6addr;
23364 
23365 		for (i = 1; i <= 3; i++) {
23366 			/* Look for exact match on srchaddr */
23367 
23368 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
23369 			    V4_PART_OF_V6(v6srchaddr))];
23370 			while (hsp) {
23371 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
23372 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23373 				    &v6srchaddr))
23374 					break;
23375 				hsp = hsp->tcp_hsp_next;
23376 			}
23377 
23378 			/*
23379 			 * If this is the first pass:
23380 			 *   If we found a match, great, return it.
23381 			 *   If not, search for the network on the second pass.
23382 			 */
23383 
23384 			if (i == 1)
23385 				if (hsp)
23386 					break;
23387 				else {
23388 					/* Assume a 64 bit mask */
23389 					v6srchaddr.s6_addr32[0] =
23390 					    v6addr->s6_addr32[0];
23391 					v6srchaddr.s6_addr32[1] =
23392 					    v6addr->s6_addr32[1];
23393 					v6srchaddr.s6_addr32[2] = 0;
23394 					v6srchaddr.s6_addr32[3] = 0;
23395 					continue;
23396 				}
23397 
23398 			/*
23399 			 * If this is the second pass:
23400 			 *   If we found a match, but there's a subnet mask,
23401 			 *    save the match but try again using the subnet
23402 			 *    mask on the third pass.
23403 			 *   Otherwise, return whatever we found.
23404 			 */
23405 
23406 			if (i == 2) {
23407 				ASSERT(hsp == NULL ||
23408 				    hsp->tcp_hsp_vers == IPV6_VERSION);
23409 				if (hsp &&
23410 				    !IN6_IS_ADDR_UNSPECIFIED(
23411 				    &hsp->tcp_hsp_subnet_v6)) {
23412 					hsp_net = hsp;
23413 					V6_MASK_COPY(*v6addr,
23414 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
23415 					continue;
23416 				} else {
23417 					break;
23418 				}
23419 			}
23420 
23421 			/*
23422 			 * This must be the third pass.  If we didn't find
23423 			 * anything, return the saved network HSP instead.
23424 			 */
23425 
23426 			if (!hsp)
23427 				hsp = hsp_net;
23428 		}
23429 	}
23430 
23431 	rw_exit(&tcp_hsp_lock);
23432 	return (hsp);
23433 }
23434 
23435 /*
23436  * Type three generator adapted from the random() function in 4.4 BSD:
23437  */
23438 
23439 /*
23440  * Copyright (c) 1983, 1993
23441  *	The Regents of the University of California.  All rights reserved.
23442  *
23443  * Redistribution and use in source and binary forms, with or without
23444  * modification, are permitted provided that the following conditions
23445  * are met:
23446  * 1. Redistributions of source code must retain the above copyright
23447  *    notice, this list of conditions and the following disclaimer.
23448  * 2. Redistributions in binary form must reproduce the above copyright
23449  *    notice, this list of conditions and the following disclaimer in the
23450  *    documentation and/or other materials provided with the distribution.
23451  * 3. All advertising materials mentioning features or use of this software
23452  *    must display the following acknowledgement:
23453  *	This product includes software developed by the University of
23454  *	California, Berkeley and its contributors.
23455  * 4. Neither the name of the University nor the names of its contributors
23456  *    may be used to endorse or promote products derived from this software
23457  *    without specific prior written permission.
23458  *
23459  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23460  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23461  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23462  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23463  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23464  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23465  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23466  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23467  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23468  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23469  * SUCH DAMAGE.
23470  */
23471 
23472 /* Type 3 -- x**31 + x**3 + 1 */
23473 #define	DEG_3		31
23474 #define	SEP_3		3
23475 
23476 
23477 /* Protected by tcp_random_lock */
23478 static int tcp_randtbl[DEG_3 + 1];
23479 
23480 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23481 static int *tcp_random_rptr = &tcp_randtbl[1];
23482 
23483 static int *tcp_random_state = &tcp_randtbl[1];
23484 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23485 
23486 kmutex_t tcp_random_lock;
23487 
23488 void
23489 tcp_random_init(void)
23490 {
23491 	int i;
23492 	hrtime_t hrt;
23493 	time_t wallclock;
23494 	uint64_t result;
23495 
23496 	/*
23497 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23498 	 * a longlong, which may contain resolution down to nanoseconds.
23499 	 * The current time will either be a 32-bit or a 64-bit quantity.
23500 	 * XOR the two together in a 64-bit result variable.
23501 	 * Convert the result to a 32-bit value by multiplying the high-order
23502 	 * 32-bits by the low-order 32-bits.
23503 	 */
23504 
23505 	hrt = gethrtime();
23506 	(void) drv_getparm(TIME, &wallclock);
23507 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23508 	mutex_enter(&tcp_random_lock);
23509 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23510 	    (result & 0xffffffff);
23511 
23512 	for (i = 1; i < DEG_3; i++)
23513 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23514 			+ 12345;
23515 	tcp_random_fptr = &tcp_random_state[SEP_3];
23516 	tcp_random_rptr = &tcp_random_state[0];
23517 	mutex_exit(&tcp_random_lock);
23518 	for (i = 0; i < 10 * DEG_3; i++)
23519 		(void) tcp_random();
23520 }
23521 
23522 /*
23523  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23524  * This range is selected to be approximately centered on TCP_ISS / 2,
23525  * and easy to compute. We get this value by generating a 32-bit random
23526  * number, selecting out the high-order 17 bits, and then adding one so
23527  * that we never return zero.
23528  */
23529 int
23530 tcp_random(void)
23531 {
23532 	int i;
23533 
23534 	mutex_enter(&tcp_random_lock);
23535 	*tcp_random_fptr += *tcp_random_rptr;
23536 
23537 	/*
23538 	 * The high-order bits are more random than the low-order bits,
23539 	 * so we select out the high-order 17 bits and add one so that
23540 	 * we never return zero.
23541 	 */
23542 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23543 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23544 		tcp_random_fptr = tcp_random_state;
23545 		++tcp_random_rptr;
23546 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23547 		tcp_random_rptr = tcp_random_state;
23548 
23549 	mutex_exit(&tcp_random_lock);
23550 	return (i);
23551 }
23552 
23553 /*
23554  * XXX This will go away when TPI is extended to send
23555  * info reqs to sockfs/timod .....
23556  * Given a queue, set the max packet size for the write
23557  * side of the queue below stream head.  This value is
23558  * cached on the stream head.
23559  * Returns 1 on success, 0 otherwise.
23560  */
23561 static int
23562 setmaxps(queue_t *q, int maxpsz)
23563 {
23564 	struct stdata	*stp;
23565 	queue_t		*wq;
23566 	stp = STREAM(q);
23567 
23568 	/*
23569 	 * At this point change of a queue parameter is not allowed
23570 	 * when a multiplexor is sitting on top.
23571 	 */
23572 	if (stp->sd_flag & STPLEX)
23573 		return (0);
23574 
23575 	claimstr(stp->sd_wrq);
23576 	wq = stp->sd_wrq->q_next;
23577 	ASSERT(wq != NULL);
23578 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23579 	releasestr(stp->sd_wrq);
23580 	return (1);
23581 }
23582 
23583 static int
23584 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23585     int *t_errorp, int *sys_errorp)
23586 {
23587 	int error;
23588 	int is_absreq_failure;
23589 	t_scalar_t *opt_lenp;
23590 	t_scalar_t opt_offset;
23591 	int prim_type;
23592 	struct T_conn_req *tcreqp;
23593 	struct T_conn_res *tcresp;
23594 	cred_t *cr;
23595 
23596 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23597 
23598 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23599 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23600 	    prim_type == T_CONN_RES);
23601 
23602 	switch (prim_type) {
23603 	case T_CONN_REQ:
23604 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23605 		opt_offset = tcreqp->OPT_offset;
23606 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23607 		break;
23608 	case O_T_CONN_RES:
23609 	case T_CONN_RES:
23610 		tcresp = (struct T_conn_res *)mp->b_rptr;
23611 		opt_offset = tcresp->OPT_offset;
23612 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23613 		break;
23614 	}
23615 
23616 	*t_errorp = 0;
23617 	*sys_errorp = 0;
23618 	*do_disconnectp = 0;
23619 
23620 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23621 	    opt_offset, cr, &tcp_opt_obj,
23622 	    NULL, &is_absreq_failure);
23623 
23624 	switch (error) {
23625 	case  0:		/* no error */
23626 		ASSERT(is_absreq_failure == 0);
23627 		return (0);
23628 	case ENOPROTOOPT:
23629 		*t_errorp = TBADOPT;
23630 		break;
23631 	case EACCES:
23632 		*t_errorp = TACCES;
23633 		break;
23634 	default:
23635 		*t_errorp = TSYSERR; *sys_errorp = error;
23636 		break;
23637 	}
23638 	if (is_absreq_failure != 0) {
23639 		/*
23640 		 * The connection request should get the local ack
23641 		 * T_OK_ACK and then a T_DISCON_IND.
23642 		 */
23643 		*do_disconnectp = 1;
23644 	}
23645 	return (-1);
23646 }
23647 
23648 /*
23649  * Split this function out so that if the secret changes, I'm okay.
23650  *
23651  * Initialize the tcp_iss_cookie and tcp_iss_key.
23652  */
23653 
23654 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23655 
23656 static void
23657 tcp_iss_key_init(uint8_t *phrase, int len)
23658 {
23659 	struct {
23660 		int32_t current_time;
23661 		uint32_t randnum;
23662 		uint16_t pad;
23663 		uint8_t ether[6];
23664 		uint8_t passwd[PASSWD_SIZE];
23665 	} tcp_iss_cookie;
23666 	time_t t;
23667 
23668 	/*
23669 	 * Start with the current absolute time.
23670 	 */
23671 	(void) drv_getparm(TIME, &t);
23672 	tcp_iss_cookie.current_time = t;
23673 
23674 	/*
23675 	 * XXX - Need a more random number per RFC 1750, not this crap.
23676 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23677 	 */
23678 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23679 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23680 
23681 	/*
23682 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23683 	 * as a good template.
23684 	 */
23685 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23686 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23687 
23688 	/*
23689 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23690 	 */
23691 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23692 
23693 	/*
23694 	 * See 4010593 if this section becomes a problem again,
23695 	 * but the local ethernet address is useful here.
23696 	 */
23697 	(void) localetheraddr(NULL,
23698 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23699 
23700 	/*
23701 	 * Hash 'em all together.  The MD5Final is called per-connection.
23702 	 */
23703 	mutex_enter(&tcp_iss_key_lock);
23704 	MD5Init(&tcp_iss_key);
23705 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
23706 	    sizeof (tcp_iss_cookie));
23707 	mutex_exit(&tcp_iss_key_lock);
23708 }
23709 
23710 /*
23711  * Set the RFC 1948 pass phrase
23712  */
23713 /* ARGSUSED */
23714 static int
23715 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23716     cred_t *cr)
23717 {
23718 	/*
23719 	 * Basically, value contains a new pass phrase.  Pass it along!
23720 	 */
23721 	tcp_iss_key_init((uint8_t *)value, strlen(value));
23722 	return (0);
23723 }
23724 
23725 /* ARGSUSED */
23726 static int
23727 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23728 {
23729 	bzero(buf, sizeof (tcp_sack_info_t));
23730 	return (0);
23731 }
23732 
23733 /* ARGSUSED */
23734 static int
23735 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23736 {
23737 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23738 	return (0);
23739 }
23740 
23741 void
23742 tcp_ddi_init(void)
23743 {
23744 	int i;
23745 
23746 	/* Initialize locks */
23747 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
23748 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23749 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23750 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23751 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23752 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
23753 
23754 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23755 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
23756 		    MUTEX_DEFAULT, NULL);
23757 	}
23758 
23759 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23760 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
23761 		    MUTEX_DEFAULT, NULL);
23762 	}
23763 
23764 	/* TCP's IPsec code calls the packet dropper. */
23765 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
23766 
23767 	if (!tcp_g_nd) {
23768 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
23769 			nd_free(&tcp_g_nd);
23770 		}
23771 	}
23772 
23773 	/*
23774 	 * Note: To really walk the device tree you need the devinfo
23775 	 * pointer to your device which is only available after probe/attach.
23776 	 * The following is safe only because it uses ddi_root_node()
23777 	 */
23778 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23779 	    tcp_opt_obj.odb_opt_arr_cnt);
23780 
23781 	tcp_timercache = kmem_cache_create("tcp_timercache",
23782 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23783 	    NULL, NULL, NULL, NULL, NULL, 0);
23784 
23785 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23786 	    sizeof (tcp_sack_info_t), 0,
23787 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23788 
23789 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23790 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23791 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23792 
23793 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
23794 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
23795 
23796 	ip_squeue_init(tcp_squeue_add);
23797 
23798 	/* Initialize the random number generator */
23799 	tcp_random_init();
23800 
23801 	/*
23802 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23803 	 * by the boot scripts.
23804 	 *
23805 	 * Use NULL name, as the name is caught by the new lockstats.
23806 	 *
23807 	 * Initialize with some random, non-guessable string, like the global
23808 	 * T_INFO_ACK.
23809 	 */
23810 
23811 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23812 	    sizeof (tcp_g_t_info_ack));
23813 
23814 	if ((tcp_kstat = kstat_create(TCP_MOD_NAME, 0, "tcpstat",
23815 		"net", KSTAT_TYPE_NAMED,
23816 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
23817 		KSTAT_FLAG_VIRTUAL)) != NULL) {
23818 		tcp_kstat->ks_data = &tcp_statistics;
23819 		kstat_install(tcp_kstat);
23820 	}
23821 
23822 	tcp_kstat_init();
23823 }
23824 
23825 void
23826 tcp_ddi_destroy(void)
23827 {
23828 	int i;
23829 
23830 	nd_free(&tcp_g_nd);
23831 
23832 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23833 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
23834 	}
23835 
23836 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23837 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
23838 	}
23839 
23840 	mutex_destroy(&tcp_iss_key_lock);
23841 	rw_destroy(&tcp_hsp_lock);
23842 	mutex_destroy(&tcp_g_q_lock);
23843 	mutex_destroy(&tcp_random_lock);
23844 	mutex_destroy(&tcp_epriv_port_lock);
23845 	rw_destroy(&tcp_reserved_port_lock);
23846 
23847 	ip_drop_unregister(&tcp_dropper);
23848 
23849 	kmem_cache_destroy(tcp_timercache);
23850 	kmem_cache_destroy(tcp_sack_info_cache);
23851 	kmem_cache_destroy(tcp_iphc_cache);
23852 
23853 	tcp_kstat_fini();
23854 }
23855 
23856 /*
23857  * Generate ISS, taking into account NDD changes may happen halfway through.
23858  * (If the iss is not zero, set it.)
23859  */
23860 
23861 static void
23862 tcp_iss_init(tcp_t *tcp)
23863 {
23864 	MD5_CTX context;
23865 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
23866 	uint32_t answer[4];
23867 
23868 	tcp_iss_incr_extra += (ISS_INCR >> 1);
23869 	tcp->tcp_iss = tcp_iss_incr_extra;
23870 	switch (tcp_strong_iss) {
23871 	case 2:
23872 		mutex_enter(&tcp_iss_key_lock);
23873 		context = tcp_iss_key;
23874 		mutex_exit(&tcp_iss_key_lock);
23875 		arg.ports = tcp->tcp_ports;
23876 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23877 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
23878 			    &arg.src);
23879 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
23880 			    &arg.dst);
23881 		} else {
23882 			arg.src = tcp->tcp_ip6h->ip6_src;
23883 			arg.dst = tcp->tcp_ip6h->ip6_dst;
23884 		}
23885 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
23886 		MD5Final((uchar_t *)answer, &context);
23887 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
23888 		/*
23889 		 * Now that we've hashed into a unique per-connection sequence
23890 		 * space, add a random increment per strong_iss == 1.  So I
23891 		 * guess we'll have to...
23892 		 */
23893 		/* FALLTHRU */
23894 	case 1:
23895 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
23896 		break;
23897 	default:
23898 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
23899 		break;
23900 	}
23901 	tcp->tcp_valid_bits = TCP_ISS_VALID;
23902 	tcp->tcp_fss = tcp->tcp_iss - 1;
23903 	tcp->tcp_suna = tcp->tcp_iss;
23904 	tcp->tcp_snxt = tcp->tcp_iss + 1;
23905 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23906 	tcp->tcp_csuna = tcp->tcp_snxt;
23907 }
23908 
23909 /*
23910  * Exported routine for extracting active tcp connection status.
23911  *
23912  * This is used by the Solaris Cluster Networking software to
23913  * gather a list of connections that need to be forwarded to
23914  * specific nodes in the cluster when configuration changes occur.
23915  *
23916  * The callback is invoked for each tcp_t structure. Returning
23917  * non-zero from the callback routine terminates the search.
23918  */
23919 int
23920 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
23921 {
23922 	tcp_t *tcp;
23923 	cl_tcp_info_t	cl_tcpi;
23924 	connf_t	*connfp;
23925 	conn_t	*connp;
23926 	int	i;
23927 
23928 	ASSERT(callback != NULL);
23929 
23930 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
23931 
23932 		connfp = &ipcl_globalhash_fanout[i];
23933 		connp = NULL;
23934 
23935 		while ((connp =
23936 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
23937 
23938 			tcp = connp->conn_tcp;
23939 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
23940 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
23941 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
23942 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
23943 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
23944 			/*
23945 			 * The macros tcp_laddr and tcp_faddr give the IPv4
23946 			 * addresses. They are copied implicitly below as
23947 			 * mapped addresses.
23948 			 */
23949 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
23950 			if (tcp->tcp_ipversion == IPV4_VERSION) {
23951 				cl_tcpi.cl_tcpi_faddr =
23952 				    tcp->tcp_ipha->ipha_dst;
23953 			} else {
23954 				cl_tcpi.cl_tcpi_faddr_v6 =
23955 				    tcp->tcp_ip6h->ip6_dst;
23956 			}
23957 
23958 			/*
23959 			 * If the callback returns non-zero
23960 			 * we terminate the traversal.
23961 			 */
23962 			if ((*callback)(&cl_tcpi, arg) != 0) {
23963 				CONN_DEC_REF(tcp->tcp_connp);
23964 				return (1);
23965 			}
23966 		}
23967 	}
23968 
23969 	return (0);
23970 }
23971 
23972 /*
23973  * Macros used for accessing the different types of sockaddr
23974  * structures inside a tcp_ioc_abort_conn_t.
23975  */
23976 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
23977 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
23978 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
23979 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
23980 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
23981 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
23982 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
23983 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
23984 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
23985 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
23986 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
23987 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
23988 
23989 /*
23990  * Return the correct error code to mimic the behavior
23991  * of a connection reset.
23992  */
23993 #define	TCP_AC_GET_ERRCODE(state, err) {	\
23994 		switch ((state)) {		\
23995 		case TCPS_SYN_SENT:		\
23996 		case TCPS_SYN_RCVD:		\
23997 			(err) = ECONNREFUSED;	\
23998 			break;			\
23999 		case TCPS_ESTABLISHED:		\
24000 		case TCPS_FIN_WAIT_1:		\
24001 		case TCPS_FIN_WAIT_2:		\
24002 		case TCPS_CLOSE_WAIT:		\
24003 			(err) = ECONNRESET;	\
24004 			break;			\
24005 		case TCPS_CLOSING:		\
24006 		case TCPS_LAST_ACK:		\
24007 		case TCPS_TIME_WAIT:		\
24008 			(err) = 0;		\
24009 			break;			\
24010 		default:			\
24011 			(err) = ENXIO;		\
24012 		}				\
24013 	}
24014 
24015 /*
24016  * Check if a tcp structure matches the info in acp.
24017  */
24018 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24019 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24020 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24021 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24022 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24023 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24024 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24025 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24026 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24027 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24028 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24029 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24030 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24031 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24032 	&(tcp)->tcp_ip_src_v6)) &&				\
24033 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24034 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24035 	&(tcp)->tcp_remote_v6)) &&				\
24036 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24037 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24038 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24039 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24040 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24041 	(acp)->ac_end >= (tcp)->tcp_state))
24042 
24043 #define	TCP_AC_MATCH(acp, tcp)					\
24044 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24045 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24046 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24047 
24048 /*
24049  * Build a message containing a tcp_ioc_abort_conn_t structure
24050  * which is filled in with information from acp and tp.
24051  */
24052 static mblk_t *
24053 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24054 {
24055 	mblk_t *mp;
24056 	tcp_ioc_abort_conn_t *tacp;
24057 
24058 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24059 	if (mp == NULL)
24060 		return (NULL);
24061 
24062 	mp->b_datap->db_type = M_CTL;
24063 
24064 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24065 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24066 		sizeof (uint32_t));
24067 
24068 	tacp->ac_start = acp->ac_start;
24069 	tacp->ac_end = acp->ac_end;
24070 	tacp->ac_zoneid = acp->ac_zoneid;
24071 
24072 	if (acp->ac_local.ss_family == AF_INET) {
24073 		tacp->ac_local.ss_family = AF_INET;
24074 		tacp->ac_remote.ss_family = AF_INET;
24075 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24076 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24077 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24078 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24079 	} else {
24080 		tacp->ac_local.ss_family = AF_INET6;
24081 		tacp->ac_remote.ss_family = AF_INET6;
24082 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24083 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24084 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24085 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24086 	}
24087 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24088 	return (mp);
24089 }
24090 
24091 /*
24092  * Print a tcp_ioc_abort_conn_t structure.
24093  */
24094 static void
24095 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24096 {
24097 	char lbuf[128];
24098 	char rbuf[128];
24099 	sa_family_t af;
24100 	in_port_t lport, rport;
24101 	ushort_t logflags;
24102 
24103 	af = acp->ac_local.ss_family;
24104 
24105 	if (af == AF_INET) {
24106 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24107 				lbuf, 128);
24108 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24109 				rbuf, 128);
24110 		lport = ntohs(TCP_AC_V4LPORT(acp));
24111 		rport = ntohs(TCP_AC_V4RPORT(acp));
24112 	} else {
24113 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24114 				lbuf, 128);
24115 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24116 				rbuf, 128);
24117 		lport = ntohs(TCP_AC_V6LPORT(acp));
24118 		rport = ntohs(TCP_AC_V6RPORT(acp));
24119 	}
24120 
24121 	logflags = SL_TRACE | SL_NOTE;
24122 	/*
24123 	 * Don't print this message to the console if the operation was done
24124 	 * to a non-global zone.
24125 	 */
24126 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24127 		logflags |= SL_CONSOLE;
24128 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24129 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24130 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24131 		acp->ac_start, acp->ac_end);
24132 }
24133 
24134 /*
24135  * Called inside tcp_rput when a message built using
24136  * tcp_ioctl_abort_build_msg is put into a queue.
24137  * Note that when we get here there is no wildcard in acp any more.
24138  */
24139 static void
24140 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24141 {
24142 	tcp_ioc_abort_conn_t *acp;
24143 
24144 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24145 	if (tcp->tcp_state <= acp->ac_end) {
24146 		/*
24147 		 * If we get here, we are already on the correct
24148 		 * squeue. This ioctl follows the following path
24149 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24150 		 * ->tcp_ioctl_abort->squeue_fill (if on a
24151 		 * different squeue)
24152 		 */
24153 		int errcode;
24154 
24155 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24156 		(void) tcp_clean_death(tcp, errcode, 26);
24157 	}
24158 	freemsg(mp);
24159 }
24160 
24161 /*
24162  * Abort all matching connections on a hash chain.
24163  */
24164 static int
24165 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24166     boolean_t exact)
24167 {
24168 	int nmatch, err = 0;
24169 	tcp_t *tcp;
24170 	MBLKP mp, last, listhead = NULL;
24171 	conn_t	*tconnp;
24172 	connf_t	*connfp = &ipcl_conn_fanout[index];
24173 
24174 startover:
24175 	nmatch = 0;
24176 
24177 	mutex_enter(&connfp->connf_lock);
24178 	for (tconnp = connfp->connf_head; tconnp != NULL;
24179 	    tconnp = tconnp->conn_next) {
24180 		tcp = tconnp->conn_tcp;
24181 		if (TCP_AC_MATCH(acp, tcp)) {
24182 			CONN_INC_REF(tcp->tcp_connp);
24183 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24184 			if (mp == NULL) {
24185 				err = ENOMEM;
24186 				CONN_DEC_REF(tcp->tcp_connp);
24187 				break;
24188 			}
24189 			mp->b_prev = (mblk_t *)tcp;
24190 
24191 			if (listhead == NULL) {
24192 				listhead = mp;
24193 				last = mp;
24194 			} else {
24195 				last->b_next = mp;
24196 				last = mp;
24197 			}
24198 			nmatch++;
24199 			if (exact)
24200 				break;
24201 		}
24202 
24203 		/* Avoid holding lock for too long. */
24204 		if (nmatch >= 500)
24205 			break;
24206 	}
24207 	mutex_exit(&connfp->connf_lock);
24208 
24209 	/* Pass mp into the correct tcp */
24210 	while ((mp = listhead) != NULL) {
24211 		listhead = listhead->b_next;
24212 		tcp = (tcp_t *)mp->b_prev;
24213 		mp->b_next = mp->b_prev = NULL;
24214 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
24215 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
24216 	}
24217 
24218 	*count += nmatch;
24219 	if (nmatch >= 500 && err == 0)
24220 		goto startover;
24221 	return (err);
24222 }
24223 
24224 /*
24225  * Abort all connections that matches the attributes specified in acp.
24226  */
24227 static int
24228 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
24229 {
24230 	sa_family_t af;
24231 	uint32_t  ports;
24232 	uint16_t *pports;
24233 	int err = 0, count = 0;
24234 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24235 	int index = -1;
24236 	ushort_t logflags;
24237 
24238 	af = acp->ac_local.ss_family;
24239 
24240 	if (af == AF_INET) {
24241 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24242 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24243 			pports = (uint16_t *)&ports;
24244 			pports[1] = TCP_AC_V4LPORT(acp);
24245 			pports[0] = TCP_AC_V4RPORT(acp);
24246 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24247 		}
24248 	} else {
24249 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24250 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24251 			pports = (uint16_t *)&ports;
24252 			pports[1] = TCP_AC_V6LPORT(acp);
24253 			pports[0] = TCP_AC_V6RPORT(acp);
24254 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24255 		}
24256 	}
24257 
24258 	/*
24259 	 * For cases where remote addr, local port, and remote port are non-
24260 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24261 	 */
24262 	if (index != -1) {
24263 		err = tcp_ioctl_abort_bucket(acp, index,
24264 			    &count, exact);
24265 	} else {
24266 		/*
24267 		 * loop through all entries for wildcard case
24268 		 */
24269 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
24270 			err = tcp_ioctl_abort_bucket(acp, index,
24271 			    &count, exact);
24272 			if (err != 0)
24273 				break;
24274 		}
24275 	}
24276 
24277 	logflags = SL_TRACE | SL_NOTE;
24278 	/*
24279 	 * Don't print this message to the console if the operation was done
24280 	 * to a non-global zone.
24281 	 */
24282 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24283 		logflags |= SL_CONSOLE;
24284 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24285 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24286 	if (err == 0 && count == 0)
24287 		err = ENOENT;
24288 	return (err);
24289 }
24290 
24291 /*
24292  * Process the TCP_IOC_ABORT_CONN ioctl request.
24293  */
24294 static void
24295 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24296 {
24297 	int	err;
24298 	IOCP    iocp;
24299 	MBLKP   mp1;
24300 	sa_family_t laf, raf;
24301 	tcp_ioc_abort_conn_t *acp;
24302 	zone_t *zptr;
24303 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
24304 
24305 	iocp = (IOCP)mp->b_rptr;
24306 
24307 	if ((mp1 = mp->b_cont) == NULL ||
24308 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24309 		err = EINVAL;
24310 		goto out;
24311 	}
24312 
24313 	/* check permissions */
24314 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
24315 		err = EPERM;
24316 		goto out;
24317 	}
24318 
24319 	if (mp1->b_cont != NULL) {
24320 		freemsg(mp1->b_cont);
24321 		mp1->b_cont = NULL;
24322 	}
24323 
24324 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24325 	laf = acp->ac_local.ss_family;
24326 	raf = acp->ac_remote.ss_family;
24327 
24328 	/* check that a zone with the supplied zoneid exists */
24329 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24330 		zptr = zone_find_by_id(zoneid);
24331 		if (zptr != NULL) {
24332 			zone_rele(zptr);
24333 		} else {
24334 			err = EINVAL;
24335 			goto out;
24336 		}
24337 	}
24338 
24339 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24340 	    acp->ac_start > acp->ac_end || laf != raf ||
24341 	    (laf != AF_INET && laf != AF_INET6)) {
24342 		err = EINVAL;
24343 		goto out;
24344 	}
24345 
24346 	tcp_ioctl_abort_dump(acp);
24347 	err = tcp_ioctl_abort(acp);
24348 
24349 out:
24350 	if (mp1 != NULL) {
24351 		freemsg(mp1);
24352 		mp->b_cont = NULL;
24353 	}
24354 
24355 	if (err != 0)
24356 		miocnak(q, mp, 0, err);
24357 	else
24358 		miocack(q, mp, 0, 0);
24359 }
24360 
24361 /*
24362  * tcp_time_wait_processing() handles processing of incoming packets when
24363  * the tcp is in the TIME_WAIT state.
24364  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24365  * on the time wait list.
24366  */
24367 void
24368 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24369     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24370 {
24371 	int32_t		bytes_acked;
24372 	int32_t		gap;
24373 	int32_t		rgap;
24374 	tcp_opt_t	tcpopt;
24375 	uint_t		flags;
24376 	uint32_t	new_swnd = 0;
24377 	conn_t		*connp;
24378 
24379 	BUMP_LOCAL(tcp->tcp_ibsegs);
24380 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
24381 
24382 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24383 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24384 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24385 	if (tcp->tcp_snd_ts_ok) {
24386 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24387 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24388 			    tcp->tcp_rnxt, TH_ACK);
24389 			goto done;
24390 		}
24391 	}
24392 	gap = seg_seq - tcp->tcp_rnxt;
24393 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24394 	if (gap < 0) {
24395 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
24396 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
24397 		    (seg_len > -gap ? -gap : seg_len));
24398 		seg_len += gap;
24399 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24400 			if (flags & TH_RST) {
24401 				goto done;
24402 			}
24403 			if ((flags & TH_FIN) && seg_len == -1) {
24404 				/*
24405 				 * When TCP receives a duplicate FIN in
24406 				 * TIME_WAIT state, restart the 2 MSL timer.
24407 				 * See page 73 in RFC 793. Make sure this TCP
24408 				 * is already on the TIME_WAIT list. If not,
24409 				 * just restart the timer.
24410 				 */
24411 				if (TCP_IS_DETACHED(tcp)) {
24412 					tcp_time_wait_remove(tcp, NULL);
24413 					tcp_time_wait_append(tcp);
24414 					TCP_DBGSTAT(tcp_rput_time_wait);
24415 				} else {
24416 					ASSERT(tcp != NULL);
24417 					TCP_TIMER_RESTART(tcp,
24418 					    tcp_time_wait_interval);
24419 				}
24420 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24421 				    tcp->tcp_rnxt, TH_ACK);
24422 				goto done;
24423 			}
24424 			flags |=  TH_ACK_NEEDED;
24425 			seg_len = 0;
24426 			goto process_ack;
24427 		}
24428 
24429 		/* Fix seg_seq, and chew the gap off the front. */
24430 		seg_seq = tcp->tcp_rnxt;
24431 	}
24432 
24433 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24434 		/*
24435 		 * Make sure that when we accept the connection, pick
24436 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24437 		 * old connection.
24438 		 *
24439 		 * The next ISS generated is equal to tcp_iss_incr_extra
24440 		 * + ISS_INCR/2 + other components depending on the
24441 		 * value of tcp_strong_iss.  We pre-calculate the new
24442 		 * ISS here and compare with tcp_snxt to determine if
24443 		 * we need to make adjustment to tcp_iss_incr_extra.
24444 		 *
24445 		 * The above calculation is ugly and is a
24446 		 * waste of CPU cycles...
24447 		 */
24448 		uint32_t new_iss = tcp_iss_incr_extra;
24449 		int32_t adj;
24450 
24451 		switch (tcp_strong_iss) {
24452 		case 2: {
24453 			/* Add time and MD5 components. */
24454 			uint32_t answer[4];
24455 			struct {
24456 				uint32_t ports;
24457 				in6_addr_t src;
24458 				in6_addr_t dst;
24459 			} arg;
24460 			MD5_CTX context;
24461 
24462 			mutex_enter(&tcp_iss_key_lock);
24463 			context = tcp_iss_key;
24464 			mutex_exit(&tcp_iss_key_lock);
24465 			arg.ports = tcp->tcp_ports;
24466 			/* We use MAPPED addresses in tcp_iss_init */
24467 			arg.src = tcp->tcp_ip_src_v6;
24468 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24469 				IN6_IPADDR_TO_V4MAPPED(
24470 					tcp->tcp_ipha->ipha_dst,
24471 					    &arg.dst);
24472 			} else {
24473 				arg.dst =
24474 				    tcp->tcp_ip6h->ip6_dst;
24475 			}
24476 			MD5Update(&context, (uchar_t *)&arg,
24477 			    sizeof (arg));
24478 			MD5Final((uchar_t *)answer, &context);
24479 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24480 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24481 			break;
24482 		}
24483 		case 1:
24484 			/* Add time component and min random (i.e. 1). */
24485 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24486 			break;
24487 		default:
24488 			/* Add only time component. */
24489 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24490 			break;
24491 		}
24492 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24493 			/*
24494 			 * New ISS not guaranteed to be ISS_INCR/2
24495 			 * ahead of the current tcp_snxt, so add the
24496 			 * difference to tcp_iss_incr_extra.
24497 			 */
24498 			tcp_iss_incr_extra += adj;
24499 		}
24500 		/*
24501 		 * If tcp_clean_death() can not perform the task now,
24502 		 * drop the SYN packet and let the other side re-xmit.
24503 		 * Otherwise pass the SYN packet back in, since the
24504 		 * old tcp state has been cleaned up or freed.
24505 		 */
24506 		if (tcp_clean_death(tcp, 0, 27) == -1)
24507 			goto done;
24508 		/*
24509 		 * We will come back to tcp_rput_data
24510 		 * on the global queue. Packets destined
24511 		 * for the global queue will be checked
24512 		 * with global policy. But the policy for
24513 		 * this packet has already been checked as
24514 		 * this was destined for the detached
24515 		 * connection. We need to bypass policy
24516 		 * check this time by attaching a dummy
24517 		 * ipsec_in with ipsec_in_dont_check set.
24518 		 */
24519 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
24520 		    NULL) {
24521 			TCP_STAT(tcp_time_wait_syn_success);
24522 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24523 			return;
24524 		}
24525 		goto done;
24526 	}
24527 
24528 	/*
24529 	 * rgap is the amount of stuff received out of window.  A negative
24530 	 * value is the amount out of window.
24531 	 */
24532 	if (rgap < 0) {
24533 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
24534 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
24535 		/* Fix seg_len and make sure there is something left. */
24536 		seg_len += rgap;
24537 		if (seg_len <= 0) {
24538 			if (flags & TH_RST) {
24539 				goto done;
24540 			}
24541 			flags |=  TH_ACK_NEEDED;
24542 			seg_len = 0;
24543 			goto process_ack;
24544 		}
24545 	}
24546 	/*
24547 	 * Check whether we can update tcp_ts_recent.  This test is
24548 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24549 	 * Extensions for High Performance: An Update", Internet Draft.
24550 	 */
24551 	if (tcp->tcp_snd_ts_ok &&
24552 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24553 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24554 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24555 		tcp->tcp_last_rcv_lbolt = lbolt64;
24556 	}
24557 
24558 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24559 		/* Always ack out of order packets */
24560 		flags |= TH_ACK_NEEDED;
24561 		seg_len = 0;
24562 	} else if (seg_len > 0) {
24563 		BUMP_MIB(&tcp_mib, tcpInClosed);
24564 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
24565 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
24566 	}
24567 	if (flags & TH_RST) {
24568 		(void) tcp_clean_death(tcp, 0, 28);
24569 		goto done;
24570 	}
24571 	if (flags & TH_SYN) {
24572 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24573 		    TH_RST|TH_ACK);
24574 		/*
24575 		 * Do not delete the TCP structure if it is in
24576 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24577 		 */
24578 		goto done;
24579 	}
24580 process_ack:
24581 	if (flags & TH_ACK) {
24582 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24583 		if (bytes_acked <= 0) {
24584 			if (bytes_acked == 0 && seg_len == 0 &&
24585 			    new_swnd == tcp->tcp_swnd)
24586 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24587 		} else {
24588 			/* Acks something not sent */
24589 			flags |= TH_ACK_NEEDED;
24590 		}
24591 	}
24592 	if (flags & TH_ACK_NEEDED) {
24593 		/*
24594 		 * Time to send an ack for some reason.
24595 		 */
24596 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24597 		    tcp->tcp_rnxt, TH_ACK);
24598 	}
24599 done:
24600 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24601 		DB_CKSUMSTART(mp) = 0;
24602 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24603 		TCP_STAT(tcp_time_wait_syn_fail);
24604 	}
24605 	freemsg(mp);
24606 }
24607 
24608 /*
24609  * Allocate a T_SVR4_OPTMGMT_REQ.
24610  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24611  * that tcp_rput_other can drop the acks.
24612  */
24613 static mblk_t *
24614 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24615 {
24616 	mblk_t *mp;
24617 	struct T_optmgmt_req *tor;
24618 	struct opthdr *oh;
24619 	uint_t size;
24620 	char *optptr;
24621 
24622 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24623 	mp = allocb(size, BPRI_MED);
24624 	if (mp == NULL)
24625 		return (NULL);
24626 
24627 	mp->b_wptr += size;
24628 	mp->b_datap->db_type = M_PROTO;
24629 	tor = (struct T_optmgmt_req *)mp->b_rptr;
24630 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
24631 	tor->MGMT_flags = T_NEGOTIATE;
24632 	tor->OPT_length = sizeof (*oh) + optlen;
24633 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
24634 
24635 	oh = (struct opthdr *)&tor[1];
24636 	oh->level = level;
24637 	oh->name = cmd;
24638 	oh->len = optlen;
24639 	if (optlen != 0) {
24640 		optptr = (char *)&oh[1];
24641 		bcopy(opt, optptr, optlen);
24642 	}
24643 	return (mp);
24644 }
24645 
24646 /*
24647  * TCP Timers Implementation.
24648  */
24649 timeout_id_t
24650 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24651 {
24652 	mblk_t *mp;
24653 	tcp_timer_t *tcpt;
24654 	tcp_t *tcp = connp->conn_tcp;
24655 
24656 	ASSERT(connp->conn_sqp != NULL);
24657 
24658 	TCP_DBGSTAT(tcp_timeout_calls);
24659 
24660 	if (tcp->tcp_timercache == NULL) {
24661 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24662 	} else {
24663 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
24664 		mp = tcp->tcp_timercache;
24665 		tcp->tcp_timercache = mp->b_next;
24666 		mp->b_next = NULL;
24667 		ASSERT(mp->b_wptr == NULL);
24668 	}
24669 
24670 	CONN_INC_REF(connp);
24671 	tcpt = (tcp_timer_t *)mp->b_rptr;
24672 	tcpt->connp = connp;
24673 	tcpt->tcpt_proc = f;
24674 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
24675 	return ((timeout_id_t)mp);
24676 }
24677 
24678 static void
24679 tcp_timer_callback(void *arg)
24680 {
24681 	mblk_t *mp = (mblk_t *)arg;
24682 	tcp_timer_t *tcpt;
24683 	conn_t	*connp;
24684 
24685 	tcpt = (tcp_timer_t *)mp->b_rptr;
24686 	connp = tcpt->connp;
24687 	squeue_fill(connp->conn_sqp, mp,
24688 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
24689 }
24690 
24691 static void
24692 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24693 {
24694 	tcp_timer_t *tcpt;
24695 	conn_t *connp = (conn_t *)arg;
24696 	tcp_t *tcp = connp->conn_tcp;
24697 
24698 	tcpt = (tcp_timer_t *)mp->b_rptr;
24699 	ASSERT(connp == tcpt->connp);
24700 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24701 
24702 	/*
24703 	 * If the TCP has reached the closed state, don't proceed any
24704 	 * further. This TCP logically does not exist on the system.
24705 	 * tcpt_proc could for example access queues, that have already
24706 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24707 	 */
24708 	if (tcp->tcp_state != TCPS_CLOSED) {
24709 		(*tcpt->tcpt_proc)(connp);
24710 	} else {
24711 		tcp->tcp_timer_tid = 0;
24712 	}
24713 	tcp_timer_free(connp->conn_tcp, mp);
24714 }
24715 
24716 /*
24717  * There is potential race with untimeout and the handler firing at the same
24718  * time. The mblock may be freed by the handler while we are trying to use
24719  * it. But since both should execute on the same squeue, this race should not
24720  * occur.
24721  */
24722 clock_t
24723 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24724 {
24725 	mblk_t	*mp = (mblk_t *)id;
24726 	tcp_timer_t *tcpt;
24727 	clock_t delta;
24728 
24729 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
24730 
24731 	if (mp == NULL)
24732 		return (-1);
24733 
24734 	tcpt = (tcp_timer_t *)mp->b_rptr;
24735 	ASSERT(tcpt->connp == connp);
24736 
24737 	delta = untimeout(tcpt->tcpt_tid);
24738 
24739 	if (delta >= 0) {
24740 		TCP_DBGSTAT(tcp_timeout_canceled);
24741 		tcp_timer_free(connp->conn_tcp, mp);
24742 		CONN_DEC_REF(connp);
24743 	}
24744 
24745 	return (delta);
24746 }
24747 
24748 /*
24749  * Allocate space for the timer event. The allocation looks like mblk, but it is
24750  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24751  *
24752  * Dealing with failures: If we can't allocate from the timer cache we try
24753  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24754  * points to b_rptr.
24755  * If we can't allocate anything using allocb_tryhard(), we perform a last
24756  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24757  * save the actual allocation size in b_datap.
24758  */
24759 mblk_t *
24760 tcp_timermp_alloc(int kmflags)
24761 {
24762 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
24763 	    kmflags & ~KM_PANIC);
24764 
24765 	if (mp != NULL) {
24766 		mp->b_next = mp->b_prev = NULL;
24767 		mp->b_rptr = (uchar_t *)(&mp[1]);
24768 		mp->b_wptr = NULL;
24769 		mp->b_datap = NULL;
24770 		mp->b_queue = NULL;
24771 	} else if (kmflags & KM_PANIC) {
24772 		/*
24773 		 * Failed to allocate memory for the timer. Try allocating from
24774 		 * dblock caches.
24775 		 */
24776 		TCP_STAT(tcp_timermp_allocfail);
24777 		mp = allocb_tryhard(sizeof (tcp_timer_t));
24778 		if (mp == NULL) {
24779 			size_t size = 0;
24780 			/*
24781 			 * Memory is really low. Try tryhard allocation.
24782 			 */
24783 			TCP_STAT(tcp_timermp_allocdblfail);
24784 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
24785 			    sizeof (tcp_timer_t), &size, kmflags);
24786 			mp->b_rptr = (uchar_t *)(&mp[1]);
24787 			mp->b_next = mp->b_prev = NULL;
24788 			mp->b_wptr = (uchar_t *)-1;
24789 			mp->b_datap = (dblk_t *)size;
24790 			mp->b_queue = NULL;
24791 		}
24792 		ASSERT(mp->b_wptr != NULL);
24793 	}
24794 	TCP_DBGSTAT(tcp_timermp_alloced);
24795 
24796 	return (mp);
24797 }
24798 
24799 /*
24800  * Free per-tcp timer cache.
24801  * It can only contain entries from tcp_timercache.
24802  */
24803 void
24804 tcp_timermp_free(tcp_t *tcp)
24805 {
24806 	mblk_t *mp;
24807 
24808 	while ((mp = tcp->tcp_timercache) != NULL) {
24809 		ASSERT(mp->b_wptr == NULL);
24810 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
24811 		kmem_cache_free(tcp_timercache, mp);
24812 	}
24813 }
24814 
24815 /*
24816  * Free timer event. Put it on the per-tcp timer cache if there is not too many
24817  * events there already (currently at most two events are cached).
24818  * If the event is not allocated from the timer cache, free it right away.
24819  */
24820 static void
24821 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
24822 {
24823 	mblk_t *mp1 = tcp->tcp_timercache;
24824 
24825 	if (mp->b_wptr != NULL) {
24826 		/*
24827 		 * This allocation is not from a timer cache, free it right
24828 		 * away.
24829 		 */
24830 		if (mp->b_wptr != (uchar_t *)-1)
24831 			freeb(mp);
24832 		else
24833 			kmem_free(mp, (size_t)mp->b_datap);
24834 	} else if (mp1 == NULL || mp1->b_next == NULL) {
24835 		/* Cache this timer block for future allocations */
24836 		mp->b_rptr = (uchar_t *)(&mp[1]);
24837 		mp->b_next = mp1;
24838 		tcp->tcp_timercache = mp;
24839 	} else {
24840 		kmem_cache_free(tcp_timercache, mp);
24841 		TCP_DBGSTAT(tcp_timermp_freed);
24842 	}
24843 }
24844 
24845 /*
24846  * End of TCP Timers implementation.
24847  */
24848 
24849 /*
24850  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
24851  * on the specified backing STREAMS q. Note, the caller may make the
24852  * decision to call based on the tcp_t.tcp_flow_stopped value which
24853  * when check outside the q's lock is only an advisory check ...
24854  */
24855 
24856 void
24857 tcp_setqfull(tcp_t *tcp)
24858 {
24859 	queue_t *q = tcp->tcp_wq;
24860 
24861 	if (!(q->q_flag & QFULL)) {
24862 		mutex_enter(QLOCK(q));
24863 		if (!(q->q_flag & QFULL)) {
24864 			/* still need to set QFULL */
24865 			q->q_flag |= QFULL;
24866 			tcp->tcp_flow_stopped = B_TRUE;
24867 			mutex_exit(QLOCK(q));
24868 			TCP_STAT(tcp_flwctl_on);
24869 		} else {
24870 			mutex_exit(QLOCK(q));
24871 		}
24872 	}
24873 }
24874 
24875 void
24876 tcp_clrqfull(tcp_t *tcp)
24877 {
24878 	queue_t *q = tcp->tcp_wq;
24879 
24880 	if (q->q_flag & QFULL) {
24881 		mutex_enter(QLOCK(q));
24882 		if (q->q_flag & QFULL) {
24883 			q->q_flag &= ~QFULL;
24884 			tcp->tcp_flow_stopped = B_FALSE;
24885 			mutex_exit(QLOCK(q));
24886 			if (q->q_flag & QWANTW)
24887 				qbackenable(q, 0);
24888 		} else {
24889 			mutex_exit(QLOCK(q));
24890 		}
24891 	}
24892 }
24893 
24894 /*
24895  * TCP Kstats implementation
24896  */
24897 static void
24898 tcp_kstat_init(void)
24899 {
24900 	tcp_named_kstat_t template = {
24901 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
24902 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
24903 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
24904 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
24905 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
24906 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
24907 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
24908 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
24909 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
24910 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
24911 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
24912 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
24913 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
24914 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
24915 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
24916 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
24917 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
24918 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
24919 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
24920 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
24921 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
24922 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
24923 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
24924 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
24925 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
24926 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
24927 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
24928 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
24929 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
24930 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
24931 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
24932 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
24933 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
24934 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
24935 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
24936 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
24937 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
24938 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
24939 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
24940 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
24941 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
24942 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
24943 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
24944 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
24945 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
24946 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
24947 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
24948 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
24949 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
24950 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
24951 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
24952 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
24953 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
24954 	};
24955 
24956 	tcp_mibkp = kstat_create(TCP_MOD_NAME, 0, TCP_MOD_NAME,
24957 	    "mib2", KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0);
24958 
24959 	if (tcp_mibkp == NULL)
24960 		return;
24961 
24962 	template.rtoAlgorithm.value.ui32 = 4;
24963 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
24964 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
24965 	template.maxConn.value.i32 = -1;
24966 
24967 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
24968 
24969 	tcp_mibkp->ks_update = tcp_kstat_update;
24970 
24971 	kstat_install(tcp_mibkp);
24972 }
24973 
24974 static void
24975 tcp_kstat_fini(void)
24976 {
24977 
24978 	if (tcp_mibkp != NULL) {
24979 		kstat_delete(tcp_mibkp);
24980 		tcp_mibkp = NULL;
24981 	}
24982 }
24983 
24984 static int
24985 tcp_kstat_update(kstat_t *kp, int rw)
24986 {
24987 	tcp_named_kstat_t	*tcpkp;
24988 	tcp_t			*tcp;
24989 	connf_t			*connfp;
24990 	conn_t			*connp;
24991 	int 			i;
24992 
24993 	if (!kp || !kp->ks_data)
24994 		return (EIO);
24995 
24996 	if (rw == KSTAT_WRITE)
24997 		return (EACCES);
24998 
24999 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25000 
25001 	tcpkp->currEstab.value.ui32 = 0;
25002 
25003 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25004 		connfp = &ipcl_globalhash_fanout[i];
25005 		connp = NULL;
25006 		while ((connp =
25007 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25008 			tcp = connp->conn_tcp;
25009 			switch (tcp_snmp_state(tcp)) {
25010 			case MIB2_TCP_established:
25011 			case MIB2_TCP_closeWait:
25012 				tcpkp->currEstab.value.ui32++;
25013 				break;
25014 			}
25015 		}
25016 	}
25017 
25018 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
25019 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
25020 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
25021 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
25022 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
25023 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
25024 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
25025 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
25026 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
25027 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
25028 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
25029 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
25030 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
25031 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
25032 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
25033 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
25034 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
25035 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
25036 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
25037 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
25038 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
25039 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
25040 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
25041 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
25042 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
25043 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
25044 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
25045 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
25046 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
25047 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
25048 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
25049 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
25050 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
25051 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
25052 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
25053 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
25054 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
25055 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
25056 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
25057 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
25058 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
25059 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
25060 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
25061 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
25062 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
25063 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
25064 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
25065 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
25066 
25067 	return (0);
25068 }
25069 
25070 void
25071 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25072 {
25073 	uint16_t	hdr_len;
25074 	ipha_t		*ipha;
25075 	uint8_t		*nexthdrp;
25076 	tcph_t		*tcph;
25077 
25078 	/* Already has an eager */
25079 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25080 		TCP_STAT(tcp_reinput_syn);
25081 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
25082 		    connp, SQTAG_TCP_REINPUT_EAGER);
25083 		return;
25084 	}
25085 
25086 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25087 	case IPV4_VERSION:
25088 		ipha = (ipha_t *)mp->b_rptr;
25089 		hdr_len = IPH_HDR_LENGTH(ipha);
25090 		break;
25091 	case IPV6_VERSION:
25092 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25093 		    &hdr_len, &nexthdrp)) {
25094 			CONN_DEC_REF(connp);
25095 			freemsg(mp);
25096 			return;
25097 		}
25098 		break;
25099 	}
25100 
25101 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25102 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25103 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25104 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25105 	}
25106 
25107 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
25108 	    SQTAG_TCP_REINPUT);
25109 }
25110 
25111 static squeue_func_t
25112 tcp_squeue_switch(int val)
25113 {
25114 	squeue_func_t rval = squeue_fill;
25115 
25116 	switch (val) {
25117 	case 1:
25118 		rval = squeue_enter_nodrain;
25119 		break;
25120 	case 2:
25121 		rval = squeue_enter;
25122 		break;
25123 	default:
25124 		break;
25125 	}
25126 	return (rval);
25127 }
25128 
25129 static void
25130 tcp_squeue_add(squeue_t *sqp)
25131 {
25132 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25133 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
25134 
25135 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25136 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
25137 	    sqp, TCP_TIME_WAIT_DELAY);
25138 	if (tcp_free_list_max_cnt == 0) {
25139 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25140 			max_ncpus : boot_max_ncpus);
25141 
25142 		/*
25143 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25144 		 */
25145 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25146 			(tcp_ncpus * sizeof (tcp_t) * 100);
25147 	}
25148 	tcp_time_wait->tcp_free_list_cnt = 0;
25149 }
25150