xref: /titanic_41/usr/src/uts/common/inet/tcp/tcp.c (revision fd9cb95cbb2f626355a60efb9d02c5f0a33c10e6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 const char tcp_version[] = "%Z%%M%	%I%	%E% SMI";
31 
32 #include <sys/types.h>
33 #include <sys/stream.h>
34 #include <sys/strsun.h>
35 #include <sys/strsubr.h>
36 #include <sys/stropts.h>
37 #include <sys/strlog.h>
38 #include <sys/strsun.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/timod.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/suntpi.h>
45 #include <sys/xti_inet.h>
46 #include <sys/cmn_err.h>
47 #include <sys/debug.h>
48 #include <sys/vtrace.h>
49 #include <sys/kmem.h>
50 #include <sys/ethernet.h>
51 #include <sys/cpuvar.h>
52 #include <sys/dlpi.h>
53 #include <sys/multidata.h>
54 #include <sys/multidata_impl.h>
55 #include <sys/pattr.h>
56 #include <sys/policy.h>
57 #include <sys/zone.h>
58 
59 #include <sys/errno.h>
60 #include <sys/signal.h>
61 #include <sys/socket.h>
62 #include <sys/sockio.h>
63 #include <sys/isa_defs.h>
64 #include <sys/md5.h>
65 #include <sys/random.h>
66 #include <netinet/in.h>
67 #include <netinet/tcp.h>
68 #include <netinet/ip6.h>
69 #include <netinet/icmp6.h>
70 #include <net/if.h>
71 #include <net/route.h>
72 #include <inet/ipsec_impl.h>
73 
74 #include <inet/common.h>
75 #include <inet/ip.h>
76 #include <inet/ip_impl.h>
77 #include <inet/ip6.h>
78 #include <inet/ip_ndp.h>
79 #include <inet/mi.h>
80 #include <inet/mib2.h>
81 #include <inet/nd.h>
82 #include <inet/optcom.h>
83 #include <inet/snmpcom.h>
84 #include <inet/kstatcom.h>
85 #include <inet/tcp.h>
86 #include <inet/tcp_impl.h>
87 #include <net/pfkeyv2.h>
88 #include <inet/ipsec_info.h>
89 #include <inet/ipdrop.h>
90 #include <inet/tcp_trace.h>
91 
92 #include <inet/ipclassifier.h>
93 #include <inet/ip_ire.h>
94 #include <inet/ip_if.h>
95 #include <inet/ipp_common.h>
96 #include <sys/squeue.h>
97 
98 /*
99  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
100  *
101  * (Read the detailed design doc in PSARC case directory)
102  *
103  * The entire tcp state is contained in tcp_t and conn_t structure
104  * which are allocated in tandem using ipcl_conn_create() and passing
105  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
106  * the references on the tcp_t. The tcp_t structure is never compressed
107  * and packets always land on the correct TCP perimeter from the time
108  * eager is created till the time tcp_t dies (as such the old mentat
109  * TCP global queue is not used for detached state and no IPSEC checking
110  * is required). The global queue is still allocated to send out resets
111  * for connection which have no listeners and IP directly calls
112  * tcp_xmit_listeners_reset() which does any policy check.
113  *
114  * Protection and Synchronisation mechanism:
115  *
116  * The tcp data structure does not use any kind of lock for protecting
117  * its state but instead uses 'squeues' for mutual exclusion from various
118  * read and write side threads. To access a tcp member, the thread should
119  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
120  * squeue_fill). Since the squeues allow a direct function call, caller
121  * can pass any tcp function having prototype of edesc_t as argument
122  * (different from traditional STREAMs model where packets come in only
123  * designated entry points). The list of functions that can be directly
124  * called via squeue are listed before the usual function prototype.
125  *
126  * Referencing:
127  *
128  * TCP is MT-Hot and we use a reference based scheme to make sure that the
129  * tcp structure doesn't disappear when its needed. When the application
130  * creates an outgoing connection or accepts an incoming connection, we
131  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
132  * The IP reference is just a symbolic reference since ip_tcpclose()
133  * looks at tcp structure after tcp_close_output() returns which could
134  * have dropped the last TCP reference. So as long as the connection is
135  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
136  * conn_t. The classifier puts its own reference when the connection is
137  * inserted in listen or connected hash. Anytime a thread needs to enter
138  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
139  * on write side or by doing a classify on read side and then puts a
140  * reference on the conn before doing squeue_enter/tryenter/fill. For
141  * read side, the classifier itself puts the reference under fanout lock
142  * to make sure that tcp can't disappear before it gets processed. The
143  * squeue will drop this reference automatically so the called function
144  * doesn't have to do a DEC_REF.
145  *
146  * Opening a new connection:
147  *
148  * The outgoing connection open is pretty simple. ip_tcpopen() does the
149  * work in creating the conn/tcp structure and initializing it. The
150  * squeue assignment is done based on the CPU the application
151  * is running on. So for outbound connections, processing is always done
152  * on application CPU which might be different from the incoming CPU
153  * being interrupted by the NIC. An optimal way would be to figure out
154  * the NIC <-> CPU binding at listen time, and assign the outgoing
155  * connection to the squeue attached to the CPU that will be interrupted
156  * for incoming packets (we know the NIC based on the bind IP address).
157  * This might seem like a problem if more data is going out but the
158  * fact is that in most cases the transmit is ACK driven transmit where
159  * the outgoing data normally sits on TCP's xmit queue waiting to be
160  * transmitted.
161  *
162  * Accepting a connection:
163  *
164  * This is a more interesting case because of various races involved in
165  * establishing a eager in its own perimeter. Read the meta comment on
166  * top of tcp_conn_request(). But briefly, the squeue is picked by
167  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
168  *
169  * Closing a connection:
170  *
171  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
172  * via squeue to do the close and mark the tcp as detached if the connection
173  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
174  * reference but tcp_close() drop IP's reference always. So if tcp was
175  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
176  * and 1 because it is in classifier's connected hash. This is the condition
177  * we use to determine that its OK to clean up the tcp outside of squeue
178  * when time wait expires (check the ref under fanout and conn_lock and
179  * if it is 2, remove it from fanout hash and kill it).
180  *
181  * Although close just drops the necessary references and marks the
182  * tcp_detached state, tcp_close needs to know the tcp_detached has been
183  * set (under squeue) before letting the STREAM go away (because a
184  * inbound packet might attempt to go up the STREAM while the close
185  * has happened and tcp_detached is not set). So a special lock and
186  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
187  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
188  * tcp_detached.
189  *
190  * Special provisions and fast paths:
191  *
192  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
193  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
194  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
195  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
196  * check to send packets directly to tcp_rput_data via squeue. Everyone
197  * else comes through tcp_input() on the read side.
198  *
199  * We also make special provisions for sockfs by marking tcp_issocket
200  * whenever we have only sockfs on top of TCP. This allows us to skip
201  * putting the tcp in acceptor hash since a sockfs listener can never
202  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
203  * since eager has already been allocated and the accept now happens
204  * on acceptor STREAM. There is a big blob of comment on top of
205  * tcp_conn_request explaining the new accept. When socket is POP'd,
206  * sockfs sends us an ioctl to mark the fact and we go back to old
207  * behaviour. Once tcp_issocket is unset, its never set for the
208  * life of that connection.
209  *
210  * IPsec notes :
211  *
212  * Since a packet is always executed on the correct TCP perimeter
213  * all IPsec processing is defered to IP including checking new
214  * connections and setting IPSEC policies for new connection. The
215  * only exception is tcp_xmit_listeners_reset() which is called
216  * directly from IP and needs to policy check to see if TH_RST
217  * can be sent out.
218  */
219 
220 
221 extern major_t TCP6_MAJ;
222 
223 /*
224  * Values for squeue switch:
225  * 1: squeue_enter_nodrain
226  * 2: squeue_enter
227  * 3: squeue_fill
228  */
229 int tcp_squeue_close = 2;
230 int tcp_squeue_wput = 2;
231 
232 squeue_func_t tcp_squeue_close_proc;
233 squeue_func_t tcp_squeue_wput_proc;
234 
235 /*
236  * This controls how tiny a write must be before we try to copy it
237  * into the the mblk on the tail of the transmit queue.  Not much
238  * speedup is observed for values larger than sixteen.  Zero will
239  * disable the optimisation.
240  */
241 int tcp_tx_pull_len = 16;
242 
243 /*
244  * TCP Statistics.
245  *
246  * How TCP statistics work.
247  *
248  * There are two types of statistics invoked by two macros.
249  *
250  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
251  * supposed to be used in non MT-hot paths of the code.
252  *
253  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
254  * supposed to be used for DEBUG purposes and may be used on a hot path.
255  *
256  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
257  * (use "kstat tcp" to get them).
258  *
259  * There is also additional debugging facility that marks tcp_clean_death()
260  * instances and saves them in tcp_t structure. It is triggered by
261  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
262  * tcp_clean_death() calls that counts the number of times each tag was hit. It
263  * is triggered by TCP_CLD_COUNTERS define.
264  *
265  * How to add new counters.
266  *
267  * 1) Add a field in the tcp_stat structure describing your counter.
268  * 2) Add a line in tcp_statistics with the name of the counter.
269  *
270  *    IMPORTANT!! - make sure that both are in sync !!
271  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
272  *
273  * Please avoid using private counters which are not kstat-exported.
274  *
275  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
276  * in tcp_t structure.
277  *
278  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
279  */
280 
281 #ifndef TCP_DEBUG_COUNTER
282 #ifdef DEBUG
283 #define	TCP_DEBUG_COUNTER 1
284 #else
285 #define	TCP_DEBUG_COUNTER 0
286 #endif
287 #endif
288 
289 #define	TCP_CLD_COUNTERS 0
290 
291 #define	TCP_TAG_CLEAN_DEATH 1
292 #define	TCP_MAX_CLEAN_DEATH_TAG 32
293 
294 #ifdef lint
295 static int _lint_dummy_;
296 #endif
297 
298 #if TCP_CLD_COUNTERS
299 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
300 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
301 #elif defined(lint)
302 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
303 #else
304 #define	TCP_CLD_STAT(x)
305 #endif
306 
307 #if TCP_DEBUG_COUNTER
308 #define	TCP_DBGSTAT(x) atomic_add_64(&(tcp_statistics.x.value.ui64), 1)
309 #elif defined(lint)
310 #define	TCP_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
311 #else
312 #define	TCP_DBGSTAT(x)
313 #endif
314 
315 tcp_stat_t tcp_statistics = {
316 	{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
317 	{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
318 	{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
319 	{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
320 	{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
321 	{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
322 	{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
323 	{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
324 	{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
325 	{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
326 	{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
327 	{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
328 	{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
329 	{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
330 	{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
331 	{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
332 	{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
333 	{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
334 	{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
335 	{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
336 	{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
337 	{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
338 	{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
339 	{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
340 	{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
341 	{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
342 	{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
343 	{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
344 	{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
345 	{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
346 	{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
347 	{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
348 	{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
349 	{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
350 	{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
351 	{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
352 	{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
353 	{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
354 	{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
355 	{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
356 	{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
357 	{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
358 	{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
359 	{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
360 	{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
361 	{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
362 	{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
363 	{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
364 	{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
365 	{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
366 	{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
367 	{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
368 	{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
369 	{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
370 	{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
371 	{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
372 	{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
373 	{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
374 	{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
375 	{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
376 	{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
377 	{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
378 	{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
379 	{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
380 	{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
381 	{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
382 	{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
383 	{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
384 	{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
385 	{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
386 	{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
387 	{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
388 	{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
389 	{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
390 	{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
391 	{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
392 	{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
393 	{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
394 	{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
395 	{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
396 	{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
397 	{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
398 	{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
399 	{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
400 	{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
401 	{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
402 	{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
403 	{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
404 	{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
405 };
406 
407 static kstat_t *tcp_kstat;
408 
409 /*
410  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
411  * tcp write side.
412  */
413 #define	CALL_IP_WPUT(connp, q, mp) {					\
414 	ASSERT(((q)->q_flag & QREADR) == 0);				\
415 	TCP_DBGSTAT(tcp_ip_output);					\
416 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
417 }
418 
419 /* Macros for timestamp comparisons */
420 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
421 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
422 
423 /*
424  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
425  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
426  * by adding three components: a time component which grows by 1 every 4096
427  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
428  * a per-connection component which grows by 125000 for every new connection;
429  * and an "extra" component that grows by a random amount centered
430  * approximately on 64000.  This causes the the ISS generator to cycle every
431  * 4.89 hours if no TCP connections are made, and faster if connections are
432  * made.
433  *
434  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
435  * components: a time component which grows by 250000 every second; and
436  * a per-connection component which grows by 125000 for every new connections.
437  *
438  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
439  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
440  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
441  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
442  * password.
443  */
444 #define	ISS_INCR	250000
445 #define	ISS_NSEC_SHT	12
446 
447 static uint32_t tcp_iss_incr_extra;	/* Incremented for each connection */
448 static kmutex_t tcp_iss_key_lock;
449 static MD5_CTX tcp_iss_key;
450 static sin_t	sin_null;	/* Zero address for quick clears */
451 static sin6_t	sin6_null;	/* Zero address for quick clears */
452 
453 /* Packet dropper for TCP IPsec policy drops. */
454 static ipdropper_t tcp_dropper;
455 
456 /*
457  * This implementation follows the 4.3BSD interpretation of the urgent
458  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
459  * incompatible changes in protocols like telnet and rlogin.
460  */
461 #define	TCP_OLD_URP_INTERPRETATION	1
462 
463 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
464 	(TCP_IS_DETACHED(tcp) && \
465 	    (!(tcp)->tcp_hard_binding))
466 
467 /*
468  * TCP reassembly macros.  We hide starting and ending sequence numbers in
469  * b_next and b_prev of messages on the reassembly queue.  The messages are
470  * chained using b_cont.  These macros are used in tcp_reass() so we don't
471  * have to see the ugly casts and assignments.
472  */
473 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
474 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
475 					(mblk_t *)(uintptr_t)(u))
476 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
477 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
478 					(mblk_t *)(uintptr_t)(u))
479 
480 /*
481  * Implementation of TCP Timers.
482  * =============================
483  *
484  * INTERFACE:
485  *
486  * There are two basic functions dealing with tcp timers:
487  *
488  *	timeout_id_t	tcp_timeout(connp, func, time)
489  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
490  *	TCP_TIMER_RESTART(tcp, intvl)
491  *
492  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
493  * after 'time' ticks passed. The function called by timeout() must adhere to
494  * the same restrictions as a driver soft interrupt handler - it must not sleep
495  * or call other functions that might sleep. The value returned is the opaque
496  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
497  * cancel the request. The call to tcp_timeout() may fail in which case it
498  * returns zero. This is different from the timeout(9F) function which never
499  * fails.
500  *
501  * The call-back function 'func' always receives 'connp' as its single
502  * argument. It is always executed in the squeue corresponding to the tcp
503  * structure. The tcp structure is guaranteed to be present at the time the
504  * call-back is called.
505  *
506  * NOTE: The call-back function 'func' is never called if tcp is in
507  * 	the TCPS_CLOSED state.
508  *
509  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
510  * request. locks acquired by the call-back routine should not be held across
511  * the call to tcp_timeout_cancel() or a deadlock may result.
512  *
513  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
514  * Otherwise, it returns an integer value greater than or equal to 0. In
515  * particular, if the call-back function is already placed on the squeue, it can
516  * not be canceled.
517  *
518  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
519  * 	within squeue context corresponding to the tcp instance. Since the
520  *	call-back is also called via the same squeue, there are no race
521  *	conditions described in untimeout(9F) manual page since all calls are
522  *	strictly serialized.
523  *
524  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
525  *	stored in tcp_timer_tid and starts a new one using
526  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
527  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
528  *	field.
529  *
530  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
531  *	call-back may still be called, so it is possible tcp_timer() will be
532  *	called several times. This should not be a problem since tcp_timer()
533  *	should always check the tcp instance state.
534  *
535  *
536  * IMPLEMENTATION:
537  *
538  * TCP timers are implemented using three-stage process. The call to
539  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
540  * when the timer expires. The tcp_timer_callback() arranges the call of the
541  * tcp_timer_handler() function via squeue corresponding to the tcp
542  * instance. The tcp_timer_handler() calls actual requested timeout call-back
543  * and passes tcp instance as an argument to it. Information is passed between
544  * stages using the tcp_timer_t structure which contains the connp pointer, the
545  * tcp call-back to call and the timeout id returned by the timeout(9F).
546  *
547  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
548  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
549  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
550  * returns the pointer to this mblk.
551  *
552  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
553  * looks like a normal mblk without actual dblk attached to it.
554  *
555  * To optimize performance each tcp instance holds a small cache of timer
556  * mblocks. In the current implementation it caches up to two timer mblocks per
557  * tcp instance. The cache is preserved over tcp frees and is only freed when
558  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
559  * timer processing happens on a corresponding squeue, the cache manipulation
560  * does not require any locks. Experiments show that majority of timer mblocks
561  * allocations are satisfied from the tcp cache and do not involve kmem calls.
562  *
563  * The tcp_timeout() places a refhold on the connp instance which guarantees
564  * that it will be present at the time the call-back function fires. The
565  * tcp_timer_handler() drops the reference after calling the call-back, so the
566  * call-back function does not need to manipulate the references explicitly.
567  */
568 
569 typedef struct tcp_timer_s {
570 	conn_t	*connp;
571 	void 	(*tcpt_proc)(void *);
572 	timeout_id_t   tcpt_tid;
573 } tcp_timer_t;
574 
575 static kmem_cache_t *tcp_timercache;
576 kmem_cache_t	*tcp_sack_info_cache;
577 kmem_cache_t	*tcp_iphc_cache;
578 
579 /*
580  * For scalability, we must not run a timer for every TCP connection
581  * in TIME_WAIT state.  To see why, consider (for time wait interval of
582  * 4 minutes):
583  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
584  *
585  * This list is ordered by time, so you need only delete from the head
586  * until you get to entries which aren't old enough to delete yet.
587  * The list consists of only the detached TIME_WAIT connections.
588  *
589  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
590  * becomes detached TIME_WAIT (either by changing the state and already
591  * being detached or the other way around). This means that the TIME_WAIT
592  * state can be extended (up to doubled) if the connection doesn't become
593  * detached for a long time.
594  *
595  * The list manipulations (including tcp_time_wait_next/prev)
596  * are protected by the tcp_time_wait_lock. The content of the
597  * detached TIME_WAIT connections is protected by the normal perimeters.
598  */
599 
600 typedef struct tcp_squeue_priv_s {
601 	kmutex_t	tcp_time_wait_lock;
602 				/* Protects the next 3 globals */
603 	timeout_id_t	tcp_time_wait_tid;
604 	tcp_t		*tcp_time_wait_head;
605 	tcp_t		*tcp_time_wait_tail;
606 	tcp_t		*tcp_free_list;
607 } tcp_squeue_priv_t;
608 
609 /*
610  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
611  * Running it every 5 seconds seems to give the best results.
612  */
613 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
614 
615 
616 #define	TCP_XMIT_LOWATER	4096
617 #define	TCP_XMIT_HIWATER	49152
618 #define	TCP_RECV_LOWATER	2048
619 #define	TCP_RECV_HIWATER	49152
620 
621 /*
622  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
623  */
624 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
625 
626 #define	TIDUSZ	4096	/* transport interface data unit size */
627 
628 /*
629  * Bind hash list size and has function.  It has to be a power of 2 for
630  * hashing.
631  */
632 #define	TCP_BIND_FANOUT_SIZE	512
633 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
634 /*
635  * Size of listen and acceptor hash list.  It has to be a power of 2 for
636  * hashing.
637  */
638 #define	TCP_FANOUT_SIZE		256
639 
640 #ifdef	_ILP32
641 #define	TCP_ACCEPTOR_HASH(accid)					\
642 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
643 #else
644 #define	TCP_ACCEPTOR_HASH(accid)					\
645 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
646 #endif	/* _ILP32 */
647 
648 #define	IP_ADDR_CACHE_SIZE	2048
649 #define	IP_ADDR_CACHE_HASH(faddr)					\
650 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
651 
652 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
653 #define	TCP_HSP_HASH_SIZE 256
654 
655 #define	TCP_HSP_HASH(addr)					\
656 	(((addr>>24) ^ (addr >>16) ^			\
657 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
658 
659 /*
660  * TCP options struct returned from tcp_parse_options.
661  */
662 typedef struct tcp_opt_s {
663 	uint32_t	tcp_opt_mss;
664 	uint32_t	tcp_opt_wscale;
665 	uint32_t	tcp_opt_ts_val;
666 	uint32_t	tcp_opt_ts_ecr;
667 	tcp_t		*tcp;
668 } tcp_opt_t;
669 
670 /*
671  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
672  */
673 
674 #ifdef _BIG_ENDIAN
675 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
676 	(TCPOPT_TSTAMP << 8) | 10)
677 #else
678 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
679 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
680 #endif
681 
682 /*
683  * Flags returned from tcp_parse_options.
684  */
685 #define	TCP_OPT_MSS_PRESENT	1
686 #define	TCP_OPT_WSCALE_PRESENT	2
687 #define	TCP_OPT_TSTAMP_PRESENT	4
688 #define	TCP_OPT_SACK_OK_PRESENT	8
689 #define	TCP_OPT_SACK_PRESENT	16
690 
691 /* TCP option length */
692 #define	TCPOPT_NOP_LEN		1
693 #define	TCPOPT_MAXSEG_LEN	4
694 #define	TCPOPT_WS_LEN		3
695 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
696 #define	TCPOPT_TSTAMP_LEN	10
697 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
698 #define	TCPOPT_SACK_OK_LEN	2
699 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
700 #define	TCPOPT_REAL_SACK_LEN	4
701 #define	TCPOPT_MAX_SACK_LEN	36
702 #define	TCPOPT_HEADER_LEN	2
703 
704 /* TCP cwnd burst factor. */
705 #define	TCP_CWND_INFINITE	65535
706 #define	TCP_CWND_SS		3
707 #define	TCP_CWND_NORMAL		5
708 
709 /* Maximum TCP initial cwin (start/restart). */
710 #define	TCP_MAX_INIT_CWND	8
711 
712 /*
713  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
714  * either tcp_slow_start_initial or tcp_slow_start_after idle
715  * depending on the caller.  If the upper layer has not used the
716  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
717  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
718  * If the upper layer has changed set the tcp_init_cwnd, just use
719  * it to calculate the tcp_cwnd.
720  */
721 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
722 {									\
723 	if ((tcp)->tcp_init_cwnd == 0) {				\
724 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
725 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
726 	} else {							\
727 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
728 	}								\
729 	tcp->tcp_cwnd_cnt = 0;						\
730 }
731 
732 /* TCP Timer control structure */
733 typedef struct tcpt_s {
734 	pfv_t	tcpt_pfv;	/* The routine we are to call */
735 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
736 } tcpt_t;
737 
738 /* Host Specific Parameter structure */
739 typedef struct tcp_hsp {
740 	struct tcp_hsp	*tcp_hsp_next;
741 	in6_addr_t	tcp_hsp_addr_v6;
742 	in6_addr_t	tcp_hsp_subnet_v6;
743 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
744 	int32_t		tcp_hsp_sendspace;
745 	int32_t		tcp_hsp_recvspace;
746 	int32_t		tcp_hsp_tstamp;
747 } tcp_hsp_t;
748 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
749 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
750 
751 /*
752  * Functions called directly via squeue having a prototype of edesc_t.
753  */
754 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
755 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
756 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
757 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
758 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
759 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
760 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
761 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
762 static void	tcp_output(void *arg, mblk_t *mp, void *arg2);
763 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
764 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
765 
766 
767 /* Prototype for TCP functions */
768 static void	tcp_random_init(void);
769 int		tcp_random(void);
770 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
771 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
772 		    tcp_t *eager);
773 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
774 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
775     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
776     boolean_t user_specified);
777 static void	tcp_closei_local(tcp_t *tcp);
778 static void	tcp_close_detached(tcp_t *tcp);
779 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
780 			mblk_t *idmp, mblk_t **defermp);
781 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
782 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
783 		    in_port_t dstport, uint_t srcid);
784 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
785 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
786 		    uint32_t scope_id);
787 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
788 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
789 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
790 static char	*tcp_display(tcp_t *tcp, char *, char);
791 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
792 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
793 static void	tcp_eager_unlink(tcp_t *tcp);
794 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
795 		    int unixerr);
796 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
797 		    int tlierr, int unixerr);
798 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
799 		    cred_t *cr);
800 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
801 		    char *value, caddr_t cp, cred_t *cr);
802 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
803 		    char *value, caddr_t cp, cred_t *cr);
804 static int	tcp_tpistate(tcp_t *tcp);
805 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
806     int caller_holds_lock);
807 static void	tcp_bind_hash_remove(tcp_t *tcp);
808 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id);
809 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
810 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
811 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
812 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
813 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
814 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
815 static int	tcp_header_init_ipv4(tcp_t *tcp);
816 static int	tcp_header_init_ipv6(tcp_t *tcp);
817 int		tcp_init(tcp_t *tcp, queue_t *q);
818 static int	tcp_init_values(tcp_t *tcp);
819 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
820 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
821 		    t_scalar_t addr_length);
822 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
823 static void	tcp_ip_notify(tcp_t *tcp);
824 static mblk_t	*tcp_ire_mp(mblk_t *mp);
825 static void	tcp_iss_init(tcp_t *tcp);
826 static void	tcp_keepalive_killer(void *arg);
827 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
828 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
829 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
830 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
831 static boolean_t tcp_allow_connopt_set(int level, int name);
832 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
833 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
834 static int	tcp_opt_get_user(ipha_t *ipha, uchar_t *ptr);
835 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
836 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
837 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
838 		    mblk_t *mblk);
839 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
840 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
841 		    uchar_t *ptr, uint_t len);
842 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
843 static boolean_t tcp_param_register(tcpparam_t *tcppa, int cnt);
844 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
845 		    caddr_t cp, cred_t *cr);
846 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
847 		    caddr_t cp, cred_t *cr);
848 static void	tcp_iss_key_init(uint8_t *phrase, int len);
849 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
850 		    caddr_t cp, cred_t *cr);
851 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
852 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
853 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
854 static void	tcp_reinit(tcp_t *tcp);
855 static void	tcp_reinit_values(tcp_t *tcp);
856 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
857 		    tcp_t *thisstream, cred_t *cr);
858 
859 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
860 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
861 static boolean_t tcp_send_rst_chk(void);
862 static void	tcp_ss_rexmit(tcp_t *tcp);
863 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
864 static void	tcp_process_options(tcp_t *, tcph_t *);
865 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
866 static void	tcp_rsrv(queue_t *q);
867 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
868 static int	tcp_snmp_state(tcp_t *tcp);
869 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
870 		    cred_t *cr);
871 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
872 		    cred_t *cr);
873 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
874 		    cred_t *cr);
875 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
876 		    cred_t *cr);
877 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
878 		    cred_t *cr);
879 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
880 		    caddr_t cp, cred_t *cr);
881 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
882 		    caddr_t cp, cred_t *cr);
883 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
884 		    cred_t *cr);
885 static void	tcp_timer(void *arg);
886 static void	tcp_timer_callback(void *);
887 static in_port_t tcp_update_next_port(in_port_t port, boolean_t random);
888 static in_port_t tcp_get_next_priv_port(void);
889 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
890 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
891 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
892 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
893 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
894 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
895 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
896 		    const int num_sack_blk, int *usable, uint_t *snxt,
897 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
898 		    const int mdt_thres);
899 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
900 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
901 		    const int num_sack_blk, int *usable, uint_t *snxt,
902 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
903 		    const int mdt_thres);
904 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
905 		    int num_sack_blk);
906 static void	tcp_wsrv(queue_t *q);
907 static int	tcp_xmit_end(tcp_t *tcp);
908 void		tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len);
909 static mblk_t	*tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send,
910 		    int32_t *offset, mblk_t **end_mp, uint32_t seq,
911 		    boolean_t sendall, uint32_t *seg_len, boolean_t rexmit);
912 static void	tcp_ack_timer(void *arg);
913 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
914 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
915 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len);
916 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
917 		    uint32_t ack, int ctl);
918 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr);
919 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr);
920 static int	setmaxps(queue_t *q, int maxpsz);
921 static void	tcp_set_rto(tcp_t *, time_t);
922 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
923 		    boolean_t, boolean_t);
924 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
925 		    boolean_t ipsec_mctl);
926 static boolean_t tcp_cmpbuf(void *a, uint_t alen,
927 		    boolean_t b_valid, void *b, uint_t blen);
928 static boolean_t tcp_allocbuf(void **dstp, uint_t *dstlenp,
929 		    boolean_t src_valid, void *src, uint_t srclen);
930 static void	tcp_savebuf(void **dstp, uint_t *dstlenp,
931 		    boolean_t src_valid, void *src, uint_t srclen);
932 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
933 		    char *opt, int optlen);
934 static int	tcp_pkt_set(uchar_t *, uint_t, uchar_t **, uint_t *);
935 static int	tcp_build_hdrs(queue_t *, tcp_t *);
936 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
937 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
938 		    tcph_t *tcph);
939 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
940 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
941 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
942 boolean_t	tcp_reserved_port_check(in_port_t);
943 static tcp_t	*tcp_alloc_temp_tcp(in_port_t);
944 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
945 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
946 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
947 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
948 		    const boolean_t, const uint32_t, const uint32_t,
949 		    const uint32_t, const uint32_t);
950 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
951 		    const uint_t, const uint_t, boolean_t *);
952 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
953 extern mblk_t	*tcp_timermp_alloc(int);
954 extern void	tcp_timermp_free(tcp_t *);
955 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
956 static void	tcp_stop_lingering(tcp_t *tcp);
957 static void	tcp_close_linger_timeout(void *arg);
958 void		tcp_ddi_init(void);
959 void		tcp_ddi_destroy(void);
960 static void	tcp_kstat_init(void);
961 static void	tcp_kstat_fini(void);
962 static int	tcp_kstat_update(kstat_t *kp, int rw);
963 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
964 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
965 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
966 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
967 			tcph_t *tcph, mblk_t *idmp);
968 static squeue_func_t tcp_squeue_switch(int);
969 
970 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
971 static int	tcp_close(queue_t *, int);
972 static int	tcpclose_accept(queue_t *);
973 static int	tcp_modclose(queue_t *);
974 static void	tcp_wput_mod(queue_t *, mblk_t *);
975 
976 static void	tcp_squeue_add(squeue_t *);
977 static boolean_t tcp_zcopy_check(tcp_t *);
978 static void	tcp_zcopy_notify(tcp_t *);
979 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
980 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
981 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
982 
983 /*
984  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
985  *
986  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
987  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
988  * (defined in tcp.h) needs to be filled in and passed into the kernel
989  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
990  * structure contains the four-tuple of a TCP connection and a range of TCP
991  * states (specified by ac_start and ac_end). The use of wildcard addresses
992  * and ports is allowed. Connections with a matching four tuple and a state
993  * within the specified range will be aborted. The valid states for the
994  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
995  * inclusive.
996  *
997  * An application which has its connection aborted by this ioctl will receive
998  * an error that is dependent on the connection state at the time of the abort.
999  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1000  * though a RST packet has been received.  If the connection state is equal to
1001  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1002  * and all resources associated with the connection will be freed.
1003  */
1004 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1005 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1006 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1007 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *);
1008 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1009 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1010     boolean_t);
1011 
1012 static struct module_info tcp_rinfo =  {
1013 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1014 };
1015 
1016 static struct module_info tcp_winfo =  {
1017 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1018 };
1019 
1020 /*
1021  * Entry points for TCP as a module. It only allows SNMP requests
1022  * to pass through.
1023  */
1024 struct qinit tcp_mod_rinit = {
1025 	(pfi_t)putnext, NULL, tcp_open, ip_snmpmod_close, NULL, &tcp_rinfo,
1026 };
1027 
1028 struct qinit tcp_mod_winit = {
1029 	(pfi_t)ip_snmpmod_wput, NULL, tcp_open, ip_snmpmod_close, NULL,
1030 	&tcp_rinfo
1031 };
1032 
1033 /*
1034  * Entry points for TCP as a device. The normal case which supports
1035  * the TCP functionality.
1036  */
1037 struct qinit tcp_rinit = {
1038 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
1039 };
1040 
1041 struct qinit tcp_winit = {
1042 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1043 };
1044 
1045 /* Initial entry point for TCP in socket mode. */
1046 struct qinit tcp_sock_winit = {
1047 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1048 };
1049 
1050 /*
1051  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1052  * an accept. Avoid allocating data structures since eager has already
1053  * been created.
1054  */
1055 struct qinit tcp_acceptor_rinit = {
1056 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1057 };
1058 
1059 struct qinit tcp_acceptor_winit = {
1060 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1061 };
1062 
1063 /*
1064  * Entry points for TCP loopback (read side only)
1065  */
1066 struct qinit tcp_loopback_rinit = {
1067 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_open, tcp_close, (pfi_t)0,
1068 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1069 };
1070 
1071 struct streamtab tcpinfo = {
1072 	&tcp_rinit, &tcp_winit
1073 };
1074 
1075 extern squeue_func_t tcp_squeue_wput_proc;
1076 extern squeue_func_t tcp_squeue_timer_proc;
1077 
1078 /* Protected by tcp_g_q_lock */
1079 static queue_t	*tcp_g_q;	/* Default queue used during detached closes */
1080 kmutex_t tcp_g_q_lock;
1081 
1082 /* Protected by tcp_hsp_lock */
1083 /*
1084  * XXX The host param mechanism should go away and instead we should use
1085  * the metrics associated with the routes to determine the default sndspace
1086  * and rcvspace.
1087  */
1088 static tcp_hsp_t	**tcp_hsp_hash;	/* Hash table for HSPs */
1089 krwlock_t tcp_hsp_lock;
1090 
1091 /*
1092  * Extra privileged ports. In host byte order.
1093  * Protected by tcp_epriv_port_lock.
1094  */
1095 #define	TCP_NUM_EPRIV_PORTS	64
1096 static int	tcp_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
1097 static uint16_t	tcp_g_epriv_ports[TCP_NUM_EPRIV_PORTS] = { 2049, 4045 };
1098 kmutex_t tcp_epriv_port_lock;
1099 
1100 /*
1101  * The smallest anonymous port in the priviledged port range which TCP
1102  * looks for free port.  Use in the option TCP_ANONPRIVBIND.
1103  */
1104 static in_port_t tcp_min_anonpriv_port = 512;
1105 
1106 /* Only modified during _init and _fini thus no locking is needed. */
1107 static caddr_t	tcp_g_nd;	/* Head of 'named dispatch' variable list */
1108 
1109 /* Hint not protected by any lock */
1110 static uint_t	tcp_next_port_to_try;
1111 
1112 
1113 /* TCP bind hash list - all tcp_t with state >= BOUND. */
1114 static tf_t	tcp_bind_fanout[TCP_BIND_FANOUT_SIZE];
1115 
1116 /* TCP queue hash list - all tcp_t in case they will be an acceptor. */
1117 static tf_t	tcp_acceptor_fanout[TCP_FANOUT_SIZE];
1118 
1119 /*
1120  * TCP has a private interface for other kernel modules to reserve a
1121  * port range for them to use.  Once reserved, TCP will not use any ports
1122  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1123  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1124  * has to be verified.
1125  *
1126  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1127  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1128  * range is [port a, port b] inclusive.  And each port range is between
1129  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1130  *
1131  * Note that the default anonymous port range starts from 32768.  There is
1132  * no port "collision" between that and the reserved port range.  If there
1133  * is port collision (because the default smallest anonymous port is lowered
1134  * or some apps specifically bind to ports in the reserved port range), the
1135  * system may not be able to reserve a port range even there are enough
1136  * unbound ports as a reserved port range contains consecutive ports .
1137  */
1138 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1139 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1140 #define	TCP_SMALLEST_RESERVED_PORT		10240
1141 #define	TCP_LARGEST_RESERVED_PORT		20480
1142 
1143 /* Structure to represent those reserved port ranges. */
1144 typedef struct tcp_rport_s {
1145 	in_port_t	lo_port;
1146 	in_port_t	hi_port;
1147 	tcp_t		**temp_tcp_array;
1148 } tcp_rport_t;
1149 
1150 /* The reserved port array. */
1151 static tcp_rport_t tcp_reserved_port[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
1152 
1153 /* Locks to protect the tcp_reserved_ports array. */
1154 static krwlock_t tcp_reserved_port_lock;
1155 
1156 /* The number of ranges in the array. */
1157 uint32_t tcp_reserved_port_array_size = 0;
1158 
1159 /*
1160  * MIB-2 stuff for SNMP
1161  * Note: tcpInErrs {tcp 15} is accumulated in ip.c
1162  */
1163 mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */
1164 kstat_t		*tcp_mibkp;	/* kstat exporting tcp_mib data */
1165 
1166 boolean_t tcp_icmp_source_quench = B_FALSE;
1167 /*
1168  * Following assumes TPI alignment requirements stay along 32 bit
1169  * boundaries
1170  */
1171 #define	ROUNDUP32(x) \
1172 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1173 
1174 /* Template for response to info request. */
1175 static struct T_info_ack tcp_g_t_info_ack = {
1176 	T_INFO_ACK,		/* PRIM_type */
1177 	0,			/* TSDU_size */
1178 	T_INFINITE,		/* ETSDU_size */
1179 	T_INVALID,		/* CDATA_size */
1180 	T_INVALID,		/* DDATA_size */
1181 	sizeof (sin_t),		/* ADDR_size */
1182 	0,			/* OPT_size - not initialized here */
1183 	TIDUSZ,			/* TIDU_size */
1184 	T_COTS_ORD,		/* SERV_type */
1185 	TCPS_IDLE,		/* CURRENT_state */
1186 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1187 };
1188 
1189 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1190 	T_INFO_ACK,		/* PRIM_type */
1191 	0,			/* TSDU_size */
1192 	T_INFINITE,		/* ETSDU_size */
1193 	T_INVALID,		/* CDATA_size */
1194 	T_INVALID,		/* DDATA_size */
1195 	sizeof (sin6_t),	/* ADDR_size */
1196 	0,			/* OPT_size - not initialized here */
1197 	TIDUSZ,		/* TIDU_size */
1198 	T_COTS_ORD,		/* SERV_type */
1199 	TCPS_IDLE,		/* CURRENT_state */
1200 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1201 };
1202 
1203 #define	MS	1L
1204 #define	SECONDS	(1000 * MS)
1205 #define	MINUTES	(60 * SECONDS)
1206 #define	HOURS	(60 * MINUTES)
1207 #define	DAYS	(24 * HOURS)
1208 
1209 #define	PARAM_MAX (~(uint32_t)0)
1210 
1211 /* Max size IP datagram is 64k - 1 */
1212 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1213 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1214 /* Max of the above */
1215 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1216 
1217 /* Largest TCP port number */
1218 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1219 
1220 /*
1221  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1222  * layer header.  It has to be a multiple of 4.
1223  */
1224 static tcpparam_t tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1225 #define	tcp_wroff_xtra	tcp_wroff_xtra_param.tcp_param_val
1226 
1227 /*
1228  * All of these are alterable, within the min/max values given, at run time.
1229  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1230  * per the TCP spec.
1231  */
1232 /* BEGIN CSTYLED */
1233 tcpparam_t	tcp_param_arr[] = {
1234  /*min		max		value		name */
1235  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1236  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1237  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1238  { 1,		1024,		1,		"tcp_conn_req_min" },
1239  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1240  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1241  { 0,		10,		0,		"tcp_debug" },
1242  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1243  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1244  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1245  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1246  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1247  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1248  { 1,		255,		64,		"tcp_ipv4_ttl"},
1249  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1250  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1251  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1252  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1253  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1254  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1255  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1256  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1257  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1258  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1259  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1260  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1261  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1262  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1263  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1264  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1265  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1266  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1267  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1268  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1269  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1270  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1271  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1272  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1273 /*
1274  * Question:  What default value should I set for tcp_strong_iss?
1275  */
1276  { 0,		2,		1,		"tcp_strong_iss"},
1277  { 0,		65536,		20,		"tcp_rtt_updates"},
1278  { 0,		1,		1,		"tcp_wscale_always"},
1279  { 0,		1,		0,		"tcp_tstamp_always"},
1280  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1281  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1282  { 0,		16,		2,		"tcp_deferred_acks_max"},
1283  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1284  { 1,		4,		4,		"tcp_slow_start_initial"},
1285  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1286  { 0,		2,		2,		"tcp_sack_permitted"},
1287  { 0,		1,		0,		"tcp_trace"},
1288  { 0,		1,		1,		"tcp_compression_enabled"},
1289  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1290  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1291  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1292  { 0,		1,		0,		"tcp_rev_src_routes"},
1293  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1294  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1295  { 0,		16,		8,		"tcp_local_dacks_max"},
1296  { 0,		2,		1,		"tcp_ecn_permitted"},
1297  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1298  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1299  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1300  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1301  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1302 };
1303 /* END CSTYLED */
1304 
1305 /*
1306  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1307  * each header fragment in the header buffer.  Each parameter value has
1308  * to be a multiple of 4 (32-bit aligned).
1309  */
1310 static tcpparam_t tcp_mdt_head_param = { 32, 256, 32, "tcp_mdt_hdr_head_min" };
1311 static tcpparam_t tcp_mdt_tail_param = { 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1312 #define	tcp_mdt_hdr_head_min	tcp_mdt_head_param.tcp_param_val
1313 #define	tcp_mdt_hdr_tail_min	tcp_mdt_tail_param.tcp_param_val
1314 
1315 /*
1316  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1317  * the maximum number of payload buffers associated per Multidata.
1318  */
1319 static tcpparam_t tcp_mdt_max_pbufs_param =
1320 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1321 #define	tcp_mdt_max_pbufs	tcp_mdt_max_pbufs_param.tcp_param_val
1322 
1323 /* Round up the value to the nearest mss. */
1324 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1325 
1326 /*
1327  * Set ECN capable transport (ECT) code point in IP header.
1328  *
1329  * Note that there are 2 ECT code points '01' and '10', which are called
1330  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1331  * point ECT(0) for TCP as described in RFC 2481.
1332  */
1333 #define	SET_ECT(tcp, iph) \
1334 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1335 		/* We need to clear the code point first. */ \
1336 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1337 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1338 	} else { \
1339 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1340 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1341 	}
1342 
1343 /*
1344  * The format argument to pass to tcp_display().
1345  * DISP_PORT_ONLY means that the returned string has only port info.
1346  * DISP_ADDR_AND_PORT means that the returned string also contains the
1347  * remote and local IP address.
1348  */
1349 #define	DISP_PORT_ONLY		1
1350 #define	DISP_ADDR_AND_PORT	2
1351 
1352 /*
1353  * This controls the rate some ndd info report functions can be used
1354  * by non-priviledged users.  It stores the last time such info is
1355  * requested.  When those report functions are called again, this
1356  * is checked with the current time and compare with the ndd param
1357  * tcp_ndd_get_info_interval.
1358  */
1359 static clock_t tcp_last_ndd_get_info_time = 0;
1360 #define	NDD_TOO_QUICK_MSG \
1361 	"ndd get info rate too high for non-priviledged users, try again " \
1362 	"later.\n"
1363 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1364 
1365 #define	IS_VMLOANED_MBLK(mp) \
1366 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1367 
1368 /*
1369  * These two variables control the rate for TCP to generate RSTs in
1370  * response to segments not belonging to any connections.  We limit
1371  * TCP to sent out tcp_rst_sent_rate (ndd param) number of RSTs in
1372  * each 1 second interval.  This is to protect TCP against DoS attack.
1373  */
1374 static clock_t tcp_last_rst_intrvl;
1375 static uint32_t tcp_rst_cnt;
1376 
1377 /* The number of RST not sent because of the rate limit. */
1378 static uint32_t tcp_rst_unsent;
1379 
1380 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1381 boolean_t tcp_mdt_chain = B_TRUE;
1382 
1383 /*
1384  * MDT threshold in the form of effective send MSS multiplier; we take
1385  * the MDT path if the amount of unsent data exceeds the threshold value
1386  * (default threshold is 1*SMSS).
1387  */
1388 uint_t tcp_mdt_smss_threshold = 1;
1389 
1390 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1391 
1392 /*
1393  * Forces all connections to obey the value of the tcp_maxpsz_multiplier
1394  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1395  * determined dynamically during tcp_adapt_ire(), which is the default.
1396  */
1397 boolean_t tcp_static_maxpsz = B_FALSE;
1398 
1399 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1400 uint32_t tcp_random_anon_port = 1;
1401 
1402 /*
1403  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1404  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1405  * data, TCP will not respond with an ACK.  RFC 793 requires that
1406  * TCP responds with an ACK for such a bogus ACK.  By not following
1407  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1408  * an attacker successfully spoofs an acceptable segment to our
1409  * peer; or when our peer is "confused."
1410  */
1411 uint32_t tcp_drop_ack_unsent_cnt = 10;
1412 
1413 /*
1414  * Hook functions to enable cluster networking
1415  * On non-clustered systems these vectors must always be NULL.
1416  */
1417 
1418 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1419 			    uint8_t *laddrp, in_port_t lport) = NULL;
1420 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1421 			    uint8_t *laddrp, in_port_t lport) = NULL;
1422 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1423 			    uint8_t *laddrp, in_port_t lport,
1424 			    uint8_t *faddrp, in_port_t fport) = NULL;
1425 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1426 			    uint8_t *laddrp, in_port_t lport,
1427 			    uint8_t *faddrp, in_port_t fport) = NULL;
1428 
1429 /*
1430  * The following are defined in ip.c
1431  */
1432 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1433 				uint8_t *laddrp);
1434 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1435 				uint8_t *laddrp, uint8_t *faddrp);
1436 
1437 #define	CL_INET_CONNECT(tcp)		{			\
1438 	if (cl_inet_connect != NULL) {				\
1439 		/*						\
1440 		 * Running in cluster mode - register active connection	\
1441 		 * information						\
1442 		 */							\
1443 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1444 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1445 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1446 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1447 				    (in_port_t)(tcp)->tcp_lport,	\
1448 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1449 				    (in_port_t)(tcp)->tcp_fport);	\
1450 			}						\
1451 		} else {						\
1452 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1453 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1454 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1455 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1456 				    (in_port_t)(tcp)->tcp_lport,	\
1457 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1458 				    (in_port_t)(tcp)->tcp_fport);	\
1459 			}						\
1460 		}							\
1461 	}								\
1462 }
1463 
1464 #define	CL_INET_DISCONNECT(tcp)	{				\
1465 	if (cl_inet_disconnect != NULL) {				\
1466 		/*							\
1467 		 * Running in cluster mode - deregister active		\
1468 		 * connection information				\
1469 		 */							\
1470 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1471 			if ((tcp)->tcp_ip_src != 0) {			\
1472 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1473 				    AF_INET,				\
1474 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1475 				    (in_port_t)(tcp)->tcp_lport,	\
1476 				    (uint8_t *)				\
1477 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1478 				    (in_port_t)(tcp)->tcp_fport);	\
1479 			}						\
1480 		} else {						\
1481 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1482 			    &(tcp)->tcp_ip_src_v6)) {			\
1483 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1484 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1485 				    (in_port_t)(tcp)->tcp_lport,	\
1486 				    (uint8_t *)				\
1487 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1488 				    (in_port_t)(tcp)->tcp_fport);	\
1489 			}						\
1490 		}							\
1491 	}								\
1492 }
1493 
1494 /*
1495  * Cluster networking hook for traversing current connection list.
1496  * This routine is used to extract the current list of live connections
1497  * which must continue to to be dispatched to this node.
1498  */
1499 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1500 
1501 /*
1502  * Figure out the value of window scale opton.  Note that the rwnd is
1503  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1504  * We cannot find the scale value and then do a round up of tcp_rwnd
1505  * because the scale value may not be correct after that.
1506  *
1507  * Set the compiler flag to make this function inline.
1508  */
1509 static void
1510 tcp_set_ws_value(tcp_t *tcp)
1511 {
1512 	int i;
1513 	uint32_t rwnd = tcp->tcp_rwnd;
1514 
1515 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1516 	    i++, rwnd >>= 1)
1517 		;
1518 	tcp->tcp_rcv_ws = i;
1519 }
1520 
1521 /*
1522  * Remove a connection from the list of detached TIME_WAIT connections.
1523  */
1524 static void
1525 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1526 {
1527 	boolean_t	locked = B_FALSE;
1528 
1529 	if (tcp_time_wait == NULL) {
1530 		tcp_time_wait = *((tcp_squeue_priv_t **)
1531 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1532 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1533 		locked = B_TRUE;
1534 	}
1535 
1536 	if (tcp->tcp_time_wait_expire == 0) {
1537 		ASSERT(tcp->tcp_time_wait_next == NULL);
1538 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1539 		if (locked)
1540 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1541 		return;
1542 	}
1543 	ASSERT(TCP_IS_DETACHED(tcp));
1544 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1545 
1546 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1547 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1548 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1549 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1550 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1551 			    NULL;
1552 		} else {
1553 			tcp_time_wait->tcp_time_wait_tail = NULL;
1554 		}
1555 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1556 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1557 		ASSERT(tcp->tcp_time_wait_next == NULL);
1558 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1559 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1560 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1561 	} else {
1562 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1563 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1564 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1565 		    tcp->tcp_time_wait_next;
1566 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1567 		    tcp->tcp_time_wait_prev;
1568 	}
1569 	tcp->tcp_time_wait_next = NULL;
1570 	tcp->tcp_time_wait_prev = NULL;
1571 	tcp->tcp_time_wait_expire = 0;
1572 
1573 	if (locked)
1574 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1575 }
1576 
1577 /*
1578  * Add a connection to the list of detached TIME_WAIT connections
1579  * and set its time to expire.
1580  */
1581 static void
1582 tcp_time_wait_append(tcp_t *tcp)
1583 {
1584 	tcp_squeue_priv_t *tcp_time_wait =
1585 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1586 		SQPRIVATE_TCP));
1587 
1588 	tcp_timers_stop(tcp);
1589 
1590 	/* Freed above */
1591 	ASSERT(tcp->tcp_timer_tid == 0);
1592 	ASSERT(tcp->tcp_ack_tid == 0);
1593 
1594 	/* must have happened at the time of detaching the tcp */
1595 	ASSERT(tcp->tcp_ptpahn == NULL);
1596 	ASSERT(tcp->tcp_flow_stopped == 0);
1597 	ASSERT(tcp->tcp_time_wait_next == NULL);
1598 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1599 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1600 	ASSERT(tcp->tcp_listener == NULL);
1601 
1602 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1603 	/*
1604 	 * The value computed below in tcp->tcp_time_wait_expire may
1605 	 * appear negative or wrap around. That is ok since our
1606 	 * interest is only in the difference between the current lbolt
1607 	 * value and tcp->tcp_time_wait_expire. But the value should not
1608 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1609 	 * The corresponding comparison in tcp_time_wait_collector() uses
1610 	 * modular arithmetic.
1611 	 */
1612 	tcp->tcp_time_wait_expire +=
1613 	    drv_usectohz(tcp_time_wait_interval * 1000);
1614 	if (tcp->tcp_time_wait_expire == 0)
1615 		tcp->tcp_time_wait_expire = 1;
1616 
1617 	ASSERT(TCP_IS_DETACHED(tcp));
1618 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1619 	ASSERT(tcp->tcp_time_wait_next == NULL);
1620 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1621 	TCP_DBGSTAT(tcp_time_wait);
1622 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1623 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1624 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1625 		tcp_time_wait->tcp_time_wait_head = tcp;
1626 	} else {
1627 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1628 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1629 		    TCPS_TIME_WAIT);
1630 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1631 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1632 	}
1633 	tcp_time_wait->tcp_time_wait_tail = tcp;
1634 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1635 }
1636 
1637 /* ARGSUSED */
1638 void
1639 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1640 {
1641 	conn_t	*connp = (conn_t *)arg;
1642 	tcp_t	*tcp = connp->conn_tcp;
1643 
1644 	ASSERT(tcp != NULL);
1645 	if (tcp->tcp_state == TCPS_CLOSED) {
1646 		return;
1647 	}
1648 
1649 	ASSERT((tcp->tcp_family == AF_INET &&
1650 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1651 	    (tcp->tcp_family == AF_INET6 &&
1652 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1653 	    tcp->tcp_ipversion == IPV6_VERSION)));
1654 	ASSERT(!tcp->tcp_listener);
1655 
1656 	TCP_STAT(tcp_time_wait_reap);
1657 	ASSERT(TCP_IS_DETACHED(tcp));
1658 
1659 	/*
1660 	 * Because they have no upstream client to rebind or tcp_close()
1661 	 * them later, we axe the connection here and now.
1662 	 */
1663 	tcp_close_detached(tcp);
1664 }
1665 
1666 void
1667 tcp_cleanup(tcp_t *tcp)
1668 {
1669 	mblk_t		*mp;
1670 	char		*tcp_iphc;
1671 	int		tcp_iphc_len;
1672 	int		tcp_hdr_grown;
1673 	tcp_sack_info_t	*tcp_sack_info;
1674 	conn_t		*connp = tcp->tcp_connp;
1675 
1676 	tcp_bind_hash_remove(tcp);
1677 	tcp_free(tcp);
1678 
1679 	conn_delete_ire(connp, NULL);
1680 	if (connp->conn_flags & IPCL_TCPCONN) {
1681 		if (connp->conn_latch != NULL)
1682 			IPLATCH_REFRELE(connp->conn_latch);
1683 		if (connp->conn_policy != NULL)
1684 			IPPH_REFRELE(connp->conn_policy);
1685 	}
1686 
1687 	/*
1688 	 * Since we will bzero the entire structure, we need to
1689 	 * remove it and reinsert it in global hash list. We
1690 	 * know the walkers can't get to this conn because we
1691 	 * had set CONDEMNED flag earlier and checked reference
1692 	 * under conn_lock so walker won't pick it and when we
1693 	 * go the ipcl_globalhash_remove() below, no walker
1694 	 * can get to it.
1695 	 */
1696 	ipcl_globalhash_remove(connp);
1697 
1698 	/* Save some state */
1699 	mp = tcp->tcp_timercache;
1700 
1701 	tcp_sack_info = tcp->tcp_sack_info;
1702 	tcp_iphc = tcp->tcp_iphc;
1703 	tcp_iphc_len = tcp->tcp_iphc_len;
1704 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1705 
1706 	bzero(connp, sizeof (conn_t));
1707 	bzero(tcp, sizeof (tcp_t));
1708 
1709 	/* restore the state */
1710 	tcp->tcp_timercache = mp;
1711 
1712 	tcp->tcp_sack_info = tcp_sack_info;
1713 	tcp->tcp_iphc = tcp_iphc;
1714 	tcp->tcp_iphc_len = tcp_iphc_len;
1715 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1716 
1717 
1718 	tcp->tcp_connp = connp;
1719 
1720 	connp->conn_tcp = tcp;
1721 	connp->conn_flags = IPCL_TCPCONN;
1722 	connp->conn_state_flags = CONN_INCIPIENT;
1723 	connp->conn_ulp = IPPROTO_TCP;
1724 	connp->conn_ref = 1;
1725 
1726 	ipcl_globalhash_insert(connp);
1727 }
1728 
1729 /*
1730  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1731  * is done forwards from the head.
1732  */
1733 /* ARGSUSED */
1734 void
1735 tcp_time_wait_collector(void *arg)
1736 {
1737 	tcp_t *tcp;
1738 	clock_t now;
1739 	mblk_t *mp;
1740 	conn_t *connp;
1741 	kmutex_t *lock;
1742 
1743 	squeue_t *sqp = (squeue_t *)arg;
1744 	tcp_squeue_priv_t *tcp_time_wait =
1745 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1746 
1747 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1748 	tcp_time_wait->tcp_time_wait_tid = 0;
1749 
1750 	if (tcp_time_wait->tcp_free_list != NULL &&
1751 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1752 		TCP_STAT(tcp_freelist_cleanup);
1753 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1754 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1755 			CONN_DEC_REF(tcp->tcp_connp);
1756 		}
1757 	}
1758 
1759 	/*
1760 	 * In order to reap time waits reliably, we should use a
1761 	 * source of time that is not adjustable by the user -- hence
1762 	 * the call to ddi_get_lbolt().
1763 	 */
1764 	now = ddi_get_lbolt();
1765 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1766 		/*
1767 		 * Compare times using modular arithmetic, since
1768 		 * lbolt can wrapover.
1769 		 */
1770 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1771 			break;
1772 		}
1773 
1774 		tcp_time_wait_remove(tcp, tcp_time_wait);
1775 
1776 		connp = tcp->tcp_connp;
1777 		ASSERT(connp->conn_fanout != NULL);
1778 		lock = &connp->conn_fanout->connf_lock;
1779 		/*
1780 		 * This is essentially a TW reclaim fast path optimization for
1781 		 * performance where the timewait collector checks under the
1782 		 * fanout lock (so that no one else can get access to the
1783 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1784 		 * the classifier hash list. If ref count is indeed 2, we can
1785 		 * just remove the conn under the fanout lock and avoid
1786 		 * cleaning up the conn under the squeue, provided that
1787 		 * clustering callbacks are not enabled. If clustering is
1788 		 * enabled, we need to make the clustering callback before
1789 		 * setting the CONDEMNED flag and after dropping all locks and
1790 		 * so we forego this optimization and fall back to the slow
1791 		 * path. Also please see the comments in tcp_closei_local
1792 		 * regarding the refcnt logic.
1793 		 *
1794 		 * Since we are holding the tcp_time_wait_lock, its better
1795 		 * not to block on the fanout_lock because other connections
1796 		 * can't add themselves to time_wait list. So we do a
1797 		 * tryenter instead of mutex_enter.
1798 		 */
1799 		if (mutex_tryenter(lock)) {
1800 			mutex_enter(&connp->conn_lock);
1801 			if ((connp->conn_ref == 2) &&
1802 			    (cl_inet_disconnect == NULL)) {
1803 				ipcl_hash_remove_locked(connp,
1804 				    connp->conn_fanout);
1805 				/*
1806 				 * Set the CONDEMNED flag now itself so that
1807 				 * the refcnt cannot increase due to any
1808 				 * walker. But we have still not cleaned up
1809 				 * conn_ire_cache. This is still ok since
1810 				 * we are going to clean it up in tcp_cleanup
1811 				 * immediately and any interface unplumb
1812 				 * thread will wait till the ire is blown away
1813 				 */
1814 				connp->conn_state_flags |= CONN_CONDEMNED;
1815 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1816 				mutex_exit(lock);
1817 				mutex_exit(&connp->conn_lock);
1818 				tcp_cleanup(tcp);
1819 				mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1820 				tcp->tcp_time_wait_next =
1821 				    tcp_time_wait->tcp_free_list;
1822 				tcp_time_wait->tcp_free_list = tcp;
1823 				continue;
1824 			} else {
1825 				CONN_INC_REF_LOCKED(connp);
1826 				mutex_exit(lock);
1827 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1828 				mutex_exit(&connp->conn_lock);
1829 				/*
1830 				 * We can reuse the closemp here since conn has
1831 				 * detached (otherwise we wouldn't even be in
1832 				 * time_wait list).
1833 				 */
1834 				mp = &tcp->tcp_closemp;
1835 				squeue_fill(connp->conn_sqp, mp,
1836 				    tcp_timewait_output, connp,
1837 				    SQTAG_TCP_TIMEWAIT);
1838 			}
1839 		} else {
1840 			mutex_enter(&connp->conn_lock);
1841 			CONN_INC_REF_LOCKED(connp);
1842 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1843 			mutex_exit(&connp->conn_lock);
1844 			/*
1845 			 * We can reuse the closemp here since conn has
1846 			 * detached (otherwise we wouldn't even be in
1847 			 * time_wait list).
1848 			 */
1849 			mp = &tcp->tcp_closemp;
1850 			squeue_fill(connp->conn_sqp, mp,
1851 			    tcp_timewait_output, connp, 0);
1852 		}
1853 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1854 	}
1855 
1856 	if (tcp_time_wait->tcp_free_list != NULL)
1857 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1858 
1859 	tcp_time_wait->tcp_time_wait_tid =
1860 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1861 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1862 }
1863 
1864 /*
1865  * Reply to a clients T_CONN_RES TPI message. This function
1866  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1867  * on the acceptor STREAM and processed in tcp_wput_accept().
1868  * Read the block comment on top of tcp_conn_request().
1869  */
1870 static void
1871 tcp_accept(tcp_t *listener, mblk_t *mp)
1872 {
1873 	tcp_t	*acceptor;
1874 	tcp_t	*eager;
1875 	tcp_t   *tcp;
1876 	struct T_conn_res	*tcr;
1877 	t_uscalar_t	acceptor_id;
1878 	t_scalar_t	seqnum;
1879 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1880 	mblk_t	*ok_mp;
1881 	mblk_t	*mp1;
1882 
1883 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1884 		tcp_err_ack(listener, mp, TPROTO, 0);
1885 		return;
1886 	}
1887 	tcr = (struct T_conn_res *)mp->b_rptr;
1888 
1889 	/*
1890 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1891 	 * read side queue of the streams device underneath us i.e. the
1892 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1893 	 * look it up in the queue_hash.  Under LP64 it sends down the
1894 	 * minor_t of the accepting endpoint.
1895 	 *
1896 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1897 	 * fanout hash lock is held.
1898 	 * This prevents any thread from entering the acceptor queue from
1899 	 * below (since it has not been hard bound yet i.e. any inbound
1900 	 * packets will arrive on the listener or default tcp queue and
1901 	 * go through tcp_lookup).
1902 	 * The CONN_INC_REF will prevent the acceptor from closing.
1903 	 *
1904 	 * XXX It is still possible for a tli application to send down data
1905 	 * on the accepting stream while another thread calls t_accept.
1906 	 * This should not be a problem for well-behaved applications since
1907 	 * the T_OK_ACK is sent after the queue swapping is completed.
1908 	 *
1909 	 * If the accepting fd is the same as the listening fd, avoid
1910 	 * queue hash lookup since that will return an eager listener in a
1911 	 * already established state.
1912 	 */
1913 	acceptor_id = tcr->ACCEPTOR_id;
1914 	mutex_enter(&listener->tcp_eager_lock);
1915 	if (listener->tcp_acceptor_id == acceptor_id) {
1916 		eager = listener->tcp_eager_next_q;
1917 		/* only count how many T_CONN_INDs so don't count q0 */
1918 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1919 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1920 			mutex_exit(&listener->tcp_eager_lock);
1921 			tcp_err_ack(listener, mp, TBADF, 0);
1922 			return;
1923 		}
1924 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1925 			/* Throw away all the eagers on q0. */
1926 			tcp_eager_cleanup(listener, 1);
1927 		}
1928 		if (listener->tcp_syn_defense) {
1929 			listener->tcp_syn_defense = B_FALSE;
1930 			if (listener->tcp_ip_addr_cache != NULL) {
1931 				kmem_free(listener->tcp_ip_addr_cache,
1932 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1933 				listener->tcp_ip_addr_cache = NULL;
1934 			}
1935 		}
1936 		/*
1937 		 * Transfer tcp_conn_req_max to the eager so that when
1938 		 * a disconnect occurs we can revert the endpoint to the
1939 		 * listen state.
1940 		 */
1941 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1942 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1943 		/*
1944 		 * Get a reference on the acceptor just like the
1945 		 * tcp_acceptor_hash_lookup below.
1946 		 */
1947 		acceptor = listener;
1948 		CONN_INC_REF(acceptor->tcp_connp);
1949 	} else {
1950 		acceptor = tcp_acceptor_hash_lookup(acceptor_id);
1951 		if (acceptor == NULL) {
1952 			if (listener->tcp_debug) {
1953 				(void) strlog(TCP_MOD_ID, 0, 1,
1954 				    SL_ERROR|SL_TRACE,
1955 				    "tcp_accept: did not find acceptor 0x%x\n",
1956 				    acceptor_id);
1957 			}
1958 			mutex_exit(&listener->tcp_eager_lock);
1959 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1960 			return;
1961 		}
1962 		/*
1963 		 * Verify acceptor state. The acceptable states for an acceptor
1964 		 * include TCPS_IDLE and TCPS_BOUND.
1965 		 */
1966 		switch (acceptor->tcp_state) {
1967 		case TCPS_IDLE:
1968 			/* FALLTHRU */
1969 		case TCPS_BOUND:
1970 			break;
1971 		default:
1972 			CONN_DEC_REF(acceptor->tcp_connp);
1973 			mutex_exit(&listener->tcp_eager_lock);
1974 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
1975 			return;
1976 		}
1977 	}
1978 
1979 	/* The listener must be in TCPS_LISTEN */
1980 	if (listener->tcp_state != TCPS_LISTEN) {
1981 		CONN_DEC_REF(acceptor->tcp_connp);
1982 		mutex_exit(&listener->tcp_eager_lock);
1983 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
1984 		return;
1985 	}
1986 
1987 	/*
1988 	 * Rendezvous with an eager connection request packet hanging off
1989 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
1990 	 * tcp structure when the connection packet arrived in
1991 	 * tcp_conn_request().
1992 	 */
1993 	seqnum = tcr->SEQ_number;
1994 	eager = listener;
1995 	do {
1996 		eager = eager->tcp_eager_next_q;
1997 		if (eager == NULL) {
1998 			CONN_DEC_REF(acceptor->tcp_connp);
1999 			mutex_exit(&listener->tcp_eager_lock);
2000 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2001 			return;
2002 		}
2003 	} while (eager->tcp_conn_req_seqnum != seqnum);
2004 	mutex_exit(&listener->tcp_eager_lock);
2005 
2006 	/*
2007 	 * At this point, both acceptor and listener have 2 ref
2008 	 * that they begin with. Acceptor has one additional ref
2009 	 * we placed in lookup while listener has 3 additional
2010 	 * ref for being behind the squeue (tcp_accept() is
2011 	 * done on listener's squeue); being in classifier hash;
2012 	 * and eager's ref on listener.
2013 	 */
2014 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2015 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2016 
2017 	/*
2018 	 * The eager at this point is set in its own squeue and
2019 	 * could easily have been killed (tcp_accept_finish will
2020 	 * deal with that) because of a TH_RST so we can only
2021 	 * ASSERT for a single ref.
2022 	 */
2023 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2024 
2025 	/* Pre allocate the stroptions mblk also */
2026 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2027 	if (opt_mp == NULL) {
2028 		CONN_DEC_REF(acceptor->tcp_connp);
2029 		CONN_DEC_REF(eager->tcp_connp);
2030 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2031 		return;
2032 	}
2033 	DB_TYPE(opt_mp) = M_SETOPTS;
2034 	opt_mp->b_wptr += sizeof (struct stroptions);
2035 
2036 	/*
2037 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2038 	 * from listener to acceptor. The message is chained on opt_mp
2039 	 * which will be sent onto eager's squeue.
2040 	 */
2041 	if (listener->tcp_bound_if != 0) {
2042 		/* allocate optmgmt req */
2043 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2044 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2045 		    sizeof (int));
2046 		if (mp1 != NULL)
2047 			linkb(opt_mp, mp1);
2048 	}
2049 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2050 		uint_t on = 1;
2051 
2052 		/* allocate optmgmt req */
2053 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2054 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2055 		if (mp1 != NULL)
2056 			linkb(opt_mp, mp1);
2057 	}
2058 
2059 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2060 	if ((mp1 = copymsg(mp)) == NULL) {
2061 		CONN_DEC_REF(acceptor->tcp_connp);
2062 		CONN_DEC_REF(eager->tcp_connp);
2063 		freemsg(opt_mp);
2064 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2065 		return;
2066 	}
2067 
2068 	tcr = (struct T_conn_res *)mp1->b_rptr;
2069 
2070 	/*
2071 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2072 	 * which allocates a larger mblk and appends the new
2073 	 * local address to the ok_ack.  The address is copied by
2074 	 * soaccept() for getsockname().
2075 	 */
2076 	{
2077 		int extra;
2078 
2079 		extra = (eager->tcp_family == AF_INET) ?
2080 		    sizeof (sin_t) : sizeof (sin6_t);
2081 
2082 		/*
2083 		 * Try to re-use mp, if possible.  Otherwise, allocate
2084 		 * an mblk and return it as ok_mp.  In any case, mp
2085 		 * is no longer usable upon return.
2086 		 */
2087 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2088 			CONN_DEC_REF(acceptor->tcp_connp);
2089 			CONN_DEC_REF(eager->tcp_connp);
2090 			freemsg(opt_mp);
2091 			/* Original mp has been freed by now, so use mp1 */
2092 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2093 			return;
2094 		}
2095 
2096 		mp = NULL;	/* We should never use mp after this point */
2097 
2098 		switch (extra) {
2099 		case sizeof (sin_t): {
2100 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2101 
2102 				ok_mp->b_wptr += extra;
2103 				sin->sin_family = AF_INET;
2104 				sin->sin_port = eager->tcp_lport;
2105 				sin->sin_addr.s_addr =
2106 				    eager->tcp_ipha->ipha_src;
2107 				break;
2108 			}
2109 		case sizeof (sin6_t): {
2110 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2111 
2112 				ok_mp->b_wptr += extra;
2113 				sin6->sin6_family = AF_INET6;
2114 				sin6->sin6_port = eager->tcp_lport;
2115 				if (eager->tcp_ipversion == IPV4_VERSION) {
2116 					sin6->sin6_flowinfo = 0;
2117 					IN6_IPADDR_TO_V4MAPPED(
2118 					    eager->tcp_ipha->ipha_src,
2119 					    &sin6->sin6_addr);
2120 				} else {
2121 					ASSERT(eager->tcp_ip6h != NULL);
2122 					sin6->sin6_flowinfo =
2123 					    eager->tcp_ip6h->ip6_vcf &
2124 					    ~IPV6_VERS_AND_FLOW_MASK;
2125 					sin6->sin6_addr =
2126 					    eager->tcp_ip6h->ip6_src;
2127 				}
2128 				break;
2129 			}
2130 		default:
2131 			break;
2132 		}
2133 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2134 	}
2135 
2136 	/*
2137 	 * If there are no options we know that the T_CONN_RES will
2138 	 * succeed. However, we can't send the T_OK_ACK upstream until
2139 	 * the tcp_accept_swap is done since it would be dangerous to
2140 	 * let the application start using the new fd prior to the swap.
2141 	 */
2142 	tcp_accept_swap(listener, acceptor, eager);
2143 
2144 	/*
2145 	 * tcp_accept_swap unlinks eager from listener but does not drop
2146 	 * the eager's reference on the listener.
2147 	 */
2148 	ASSERT(eager->tcp_listener == NULL);
2149 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2150 
2151 	/*
2152 	 * The eager is now associated with its own queue. Insert in
2153 	 * the hash so that the connection can be reused for a future
2154 	 * T_CONN_RES.
2155 	 */
2156 	tcp_acceptor_hash_insert(acceptor_id, eager);
2157 
2158 	/*
2159 	 * We now do the processing of options with T_CONN_RES.
2160 	 * We delay till now since we wanted to have queue to pass to
2161 	 * option processing routines that points back to the right
2162 	 * instance structure which does not happen until after
2163 	 * tcp_accept_swap().
2164 	 *
2165 	 * Note:
2166 	 * The sanity of the logic here assumes that whatever options
2167 	 * are appropriate to inherit from listner=>eager are done
2168 	 * before this point, and whatever were to be overridden (or not)
2169 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2170 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2171 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2172 	 * This may not be true at this point in time but can be fixed
2173 	 * independently. This option processing code starts with
2174 	 * the instantiated acceptor instance and the final queue at
2175 	 * this point.
2176 	 */
2177 
2178 	if (tcr->OPT_length != 0) {
2179 		/* Options to process */
2180 		int t_error = 0;
2181 		int sys_error = 0;
2182 		int do_disconnect = 0;
2183 
2184 		if (tcp_conprim_opt_process(eager, mp1,
2185 		    &do_disconnect, &t_error, &sys_error) < 0) {
2186 			eager->tcp_accept_error = 1;
2187 			if (do_disconnect) {
2188 				/*
2189 				 * An option failed which does not allow
2190 				 * connection to be accepted.
2191 				 *
2192 				 * We allow T_CONN_RES to succeed and
2193 				 * put a T_DISCON_IND on the eager queue.
2194 				 */
2195 				ASSERT(t_error == 0 && sys_error == 0);
2196 				eager->tcp_send_discon_ind = 1;
2197 			} else {
2198 				ASSERT(t_error != 0);
2199 				freemsg(ok_mp);
2200 				/*
2201 				 * Original mp was either freed or set
2202 				 * to ok_mp above, so use mp1 instead.
2203 				 */
2204 				tcp_err_ack(listener, mp1, t_error, sys_error);
2205 				goto finish;
2206 			}
2207 		}
2208 		/*
2209 		 * Most likely success in setting options (except if
2210 		 * eager->tcp_send_discon_ind set).
2211 		 * mp1 option buffer represented by OPT_length/offset
2212 		 * potentially modified and contains results of setting
2213 		 * options at this point
2214 		 */
2215 	}
2216 
2217 	/* We no longer need mp1, since all options processing has passed */
2218 	freemsg(mp1);
2219 
2220 	putnext(listener->tcp_rq, ok_mp);
2221 
2222 	mutex_enter(&listener->tcp_eager_lock);
2223 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2224 		tcp_t	*tail;
2225 		mblk_t	*conn_ind;
2226 
2227 		/*
2228 		 * This path should not be executed if listener and
2229 		 * acceptor streams are the same.
2230 		 */
2231 		ASSERT(listener != acceptor);
2232 
2233 		tcp = listener->tcp_eager_prev_q0;
2234 		/*
2235 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2236 		 * deferred T_conn_ind queue. We need to get to the head of
2237 		 * the queue in order to send up T_conn_ind the same order as
2238 		 * how the 3WHS is completed.
2239 		 */
2240 		while (tcp != listener) {
2241 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2242 				break;
2243 			else
2244 				tcp = tcp->tcp_eager_prev_q0;
2245 		}
2246 		ASSERT(tcp != listener);
2247 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2248 		ASSERT(conn_ind != NULL);
2249 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2250 
2251 		/* Move from q0 to q */
2252 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2253 		listener->tcp_conn_req_cnt_q0--;
2254 		listener->tcp_conn_req_cnt_q++;
2255 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2256 		    tcp->tcp_eager_prev_q0;
2257 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2258 		    tcp->tcp_eager_next_q0;
2259 		tcp->tcp_eager_prev_q0 = NULL;
2260 		tcp->tcp_eager_next_q0 = NULL;
2261 		tcp->tcp_conn_def_q0 = B_FALSE;
2262 
2263 		/*
2264 		 * Insert at end of the queue because sockfs sends
2265 		 * down T_CONN_RES in chronological order. Leaving
2266 		 * the older conn indications at front of the queue
2267 		 * helps reducing search time.
2268 		 */
2269 		tail = listener->tcp_eager_last_q;
2270 		if (tail != NULL)
2271 			tail->tcp_eager_next_q = tcp;
2272 		else
2273 			listener->tcp_eager_next_q = tcp;
2274 		listener->tcp_eager_last_q = tcp;
2275 		tcp->tcp_eager_next_q = NULL;
2276 		mutex_exit(&listener->tcp_eager_lock);
2277 		putnext(tcp->tcp_rq, conn_ind);
2278 	} else {
2279 		mutex_exit(&listener->tcp_eager_lock);
2280 	}
2281 
2282 	/*
2283 	 * Done with the acceptor - free it
2284 	 *
2285 	 * Note: from this point on, no access to listener should be made
2286 	 * as listener can be equal to acceptor.
2287 	 */
2288 finish:
2289 	ASSERT(acceptor->tcp_detached);
2290 	acceptor->tcp_rq = tcp_g_q;
2291 	acceptor->tcp_wq = WR(tcp_g_q);
2292 	(void) tcp_clean_death(acceptor, 0, 2);
2293 	CONN_DEC_REF(acceptor->tcp_connp);
2294 
2295 	/*
2296 	 * In case we already received a FIN we have to make tcp_rput send
2297 	 * the ordrel_ind. This will also send up a window update if the window
2298 	 * has opened up.
2299 	 *
2300 	 * In the normal case of a successful connection acceptance
2301 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2302 	 * indication that this was just accepted. This tells tcp_rput to
2303 	 * pass up any data queued in tcp_rcv_list.
2304 	 *
2305 	 * In the fringe case where options sent with T_CONN_RES failed and
2306 	 * we required, we would be indicating a T_DISCON_IND to blow
2307 	 * away this connection.
2308 	 */
2309 
2310 	/*
2311 	 * XXX: we currently have a problem if XTI application closes the
2312 	 * acceptor stream in between. This problem exists in on10-gate also
2313 	 * and is well know but nothing can be done short of major rewrite
2314 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2315 	 * eager same squeue as listener (we can distinguish non socket
2316 	 * listeners at the time of handling a SYN in tcp_conn_request)
2317 	 * and do most of the work that tcp_accept_finish does here itself
2318 	 * and then get behind the acceptor squeue to access the acceptor
2319 	 * queue.
2320 	 */
2321 	/*
2322 	 * We already have a ref on tcp so no need to do one before squeue_fill
2323 	 */
2324 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2325 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2326 }
2327 
2328 /*
2329  * Swap information between the eager and acceptor for a TLI/XTI client.
2330  * The sockfs accept is done on the acceptor stream and control goes
2331  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2332  * called. In either case, both the eager and listener are in their own
2333  * perimeter (squeue) and the code has to deal with potential race.
2334  *
2335  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2336  */
2337 static void
2338 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2339 {
2340 	conn_t	*econnp, *aconnp;
2341 
2342 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2343 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2344 	ASSERT(!eager->tcp_hard_bound);
2345 	ASSERT(!TCP_IS_SOCKET(acceptor));
2346 	ASSERT(!TCP_IS_SOCKET(eager));
2347 	ASSERT(!TCP_IS_SOCKET(listener));
2348 
2349 	acceptor->tcp_detached = B_TRUE;
2350 	/*
2351 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2352 	 * the acceptor id.
2353 	 */
2354 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2355 
2356 	/* remove eager from listen list... */
2357 	mutex_enter(&listener->tcp_eager_lock);
2358 	tcp_eager_unlink(eager);
2359 	ASSERT(eager->tcp_eager_next_q == NULL &&
2360 	    eager->tcp_eager_last_q == NULL);
2361 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2362 	    eager->tcp_eager_prev_q0 == NULL);
2363 	mutex_exit(&listener->tcp_eager_lock);
2364 	eager->tcp_rq = acceptor->tcp_rq;
2365 	eager->tcp_wq = acceptor->tcp_wq;
2366 
2367 	econnp = eager->tcp_connp;
2368 	aconnp = acceptor->tcp_connp;
2369 
2370 	eager->tcp_rq->q_ptr = econnp;
2371 	eager->tcp_wq->q_ptr = econnp;
2372 	eager->tcp_detached = B_FALSE;
2373 
2374 	ASSERT(eager->tcp_ack_tid == 0);
2375 
2376 	econnp->conn_dev = aconnp->conn_dev;
2377 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2378 	econnp->conn_zoneid = aconnp->conn_zoneid;
2379 	aconnp->conn_cred = NULL;
2380 
2381 	/* Do the IPC initialization */
2382 	CONN_INC_REF(econnp);
2383 
2384 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2385 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2386 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2387 	econnp->conn_ulp = aconnp->conn_ulp;
2388 
2389 	/* Done with old IPC. Drop its ref on its connp */
2390 	CONN_DEC_REF(aconnp);
2391 }
2392 
2393 
2394 /*
2395  * Adapt to the information, such as rtt and rtt_sd, provided from the
2396  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2397  *
2398  * Checks for multicast and broadcast destination address.
2399  * Returns zero on failure; non-zero if ok.
2400  *
2401  * Note that the MSS calculation here is based on the info given in
2402  * the IRE.  We do not do any calculation based on TCP options.  They
2403  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2404  * knows which options to use.
2405  *
2406  * Note on how TCP gets its parameters for a connection.
2407  *
2408  * When a tcp_t structure is allocated, it gets all the default parameters.
2409  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2410  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2411  * default.  But if there is an associated tcp_host_param, it will override
2412  * the metrics.
2413  *
2414  * An incoming SYN with a multicast or broadcast destination address, is dropped
2415  * in 1 of 2 places.
2416  *
2417  * 1. If the packet was received over the wire it is dropped in
2418  * ip_rput_process_broadcast()
2419  *
2420  * 2. If the packet was received through internal IP loopback, i.e. the packet
2421  * was generated and received on the same machine, it is dropped in
2422  * ip_wput_local()
2423  *
2424  * An incoming SYN with a multicast or broadcast source address is always
2425  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2426  * reject an attempt to connect to a broadcast or multicast (destination)
2427  * address.
2428  */
2429 static int
2430 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2431 {
2432 	tcp_hsp_t	*hsp;
2433 	ire_t		*ire;
2434 	ire_t		*sire = NULL;
2435 	iulp_t		*ire_uinfo;
2436 	uint32_t	mss_max;
2437 	uint32_t	mss;
2438 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2439 	conn_t		*connp = tcp->tcp_connp;
2440 	boolean_t	ire_cacheable = B_FALSE;
2441 	zoneid_t	zoneid = connp->conn_zoneid;
2442 	ill_t		*ill = NULL;
2443 	boolean_t	incoming = (ire_mp == NULL);
2444 
2445 	ASSERT(connp->conn_ire_cache == NULL);
2446 
2447 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2448 
2449 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2450 			BUMP_MIB(&ip_mib, ipInDiscards);
2451 			return (0);
2452 		}
2453 
2454 		ire = ire_cache_lookup(tcp->tcp_connp->conn_rem, zoneid);
2455 		if (ire != NULL) {
2456 			ire_cacheable = B_TRUE;
2457 			ire_uinfo = (ire_mp != NULL) ?
2458 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2459 			    &ire->ire_uinfo;
2460 
2461 		} else {
2462 			if (ire_mp == NULL) {
2463 				ire = ire_ftable_lookup(
2464 				    tcp->tcp_connp->conn_rem,
2465 				    0, 0, 0, NULL, &sire, zoneid, 0,
2466 				    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT));
2467 				if (ire == NULL)
2468 					return (0);
2469 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2470 				    &ire->ire_uinfo;
2471 			} else {
2472 				ire = (ire_t *)ire_mp->b_rptr;
2473 				ire_uinfo =
2474 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2475 			}
2476 		}
2477 		ASSERT(ire != NULL);
2478 		ASSERT(ire_uinfo != NULL);
2479 
2480 		if ((ire->ire_src_addr == INADDR_ANY) ||
2481 		    (ire->ire_type & IRE_BROADCAST)) {
2482 			/*
2483 			 * ire->ire_mp is non null when ire_mp passed in is used
2484 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2485 			 */
2486 			if (ire->ire_mp == NULL)
2487 				ire_refrele(ire);
2488 			if (sire != NULL)
2489 				ire_refrele(sire);
2490 			return (0);
2491 		}
2492 
2493 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2494 			ipaddr_t src_addr;
2495 
2496 			/*
2497 			 * ip_bind_connected() has stored the correct source
2498 			 * address in conn_src.
2499 			 */
2500 			src_addr = tcp->tcp_connp->conn_src;
2501 			tcp->tcp_ipha->ipha_src = src_addr;
2502 			/*
2503 			 * Copy of the src addr. in tcp_t is needed
2504 			 * for the lookup funcs.
2505 			 */
2506 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2507 		}
2508 		/*
2509 		 * Set the fragment bit so that IP will tell us if the MTU
2510 		 * should change. IP tells us the latest setting of
2511 		 * ip_path_mtu_discovery through ire_frag_flag.
2512 		 */
2513 		if (ip_path_mtu_discovery) {
2514 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2515 			    htons(IPH_DF);
2516 		}
2517 		tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2518 	} else {
2519 		/*
2520 		 * For incoming connection ire_mp = NULL
2521 		 * For outgoing connection ire_mp != NULL
2522 		 * Technically we should check conn_incoming_ill
2523 		 * when ire_mp is NULL and conn_outgoing_ill when
2524 		 * ire_mp is non-NULL. But this is performance
2525 		 * critical path and for IPV*_BOUND_IF, outgoing
2526 		 * and incoming ill are always set to the same value.
2527 		 */
2528 		ill_t	*dst_ill = NULL;
2529 		ipif_t  *dst_ipif = NULL;
2530 		int match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT;
2531 
2532 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2533 
2534 		if (connp->conn_outgoing_ill != NULL) {
2535 			/* Outgoing or incoming path */
2536 			int   err;
2537 
2538 			dst_ill = conn_get_held_ill(connp,
2539 			    &connp->conn_outgoing_ill, &err);
2540 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2541 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2542 				return (0);
2543 			}
2544 			match_flags |= MATCH_IRE_ILL;
2545 			dst_ipif = dst_ill->ill_ipif;
2546 		}
2547 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2548 		    0, 0, dst_ipif, zoneid, match_flags);
2549 
2550 		if (ire != NULL) {
2551 			ire_cacheable = B_TRUE;
2552 			ire_uinfo = (ire_mp != NULL) ?
2553 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2554 			    &ire->ire_uinfo;
2555 		} else {
2556 			if (ire_mp == NULL) {
2557 				ire = ire_ftable_lookup_v6(
2558 				    &tcp->tcp_connp->conn_remv6,
2559 				    0, 0, 0, dst_ipif, &sire, zoneid,
2560 				    0, match_flags);
2561 				if (ire == NULL) {
2562 					if (dst_ill != NULL)
2563 						ill_refrele(dst_ill);
2564 					return (0);
2565 				}
2566 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2567 				    &ire->ire_uinfo;
2568 			} else {
2569 				ire = (ire_t *)ire_mp->b_rptr;
2570 				ire_uinfo =
2571 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2572 			}
2573 		}
2574 		if (dst_ill != NULL)
2575 			ill_refrele(dst_ill);
2576 
2577 		ASSERT(ire != NULL);
2578 		ASSERT(ire_uinfo != NULL);
2579 
2580 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2581 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2582 			/*
2583 			 * ire->ire_mp is non null when ire_mp passed in is used
2584 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2585 			 */
2586 			if (ire->ire_mp == NULL)
2587 				ire_refrele(ire);
2588 			if (sire != NULL)
2589 				ire_refrele(sire);
2590 			return (0);
2591 		}
2592 
2593 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2594 			in6_addr_t	src_addr;
2595 
2596 			/*
2597 			 * ip_bind_connected_v6() has stored the correct source
2598 			 * address per IPv6 addr. selection policy in
2599 			 * conn_src_v6.
2600 			 */
2601 			src_addr = tcp->tcp_connp->conn_srcv6;
2602 
2603 			tcp->tcp_ip6h->ip6_src = src_addr;
2604 			/*
2605 			 * Copy of the src addr. in tcp_t is needed
2606 			 * for the lookup funcs.
2607 			 */
2608 			tcp->tcp_ip_src_v6 = src_addr;
2609 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2610 			    &connp->conn_srcv6));
2611 		}
2612 		tcp->tcp_localnet =
2613 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2614 	}
2615 
2616 	/*
2617 	 * This allows applications to fail quickly when connections are made
2618 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2619 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2620 	 */
2621 	if ((ire->ire_flags & RTF_REJECT) &&
2622 	    (ire->ire_flags & RTF_PRIVATE))
2623 		goto error;
2624 
2625 	/*
2626 	 * Make use of the cached rtt and rtt_sd values to calculate the
2627 	 * initial RTO.  Note that they are already initialized in
2628 	 * tcp_init_values().
2629 	 */
2630 	if (ire_uinfo->iulp_rtt != 0) {
2631 		clock_t	rto;
2632 
2633 		tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2634 		tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2635 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2636 		    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
2637 
2638 		if (rto > tcp_rexmit_interval_max) {
2639 			tcp->tcp_rto = tcp_rexmit_interval_max;
2640 		} else if (rto < tcp_rexmit_interval_min) {
2641 			tcp->tcp_rto = tcp_rexmit_interval_min;
2642 		} else {
2643 			tcp->tcp_rto = rto;
2644 		}
2645 	}
2646 	if (ire_uinfo->iulp_ssthresh != 0)
2647 		tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2648 	else
2649 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2650 	if (ire_uinfo->iulp_spipe > 0) {
2651 		tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2652 		    tcp_max_buf);
2653 		if (tcp_snd_lowat_fraction != 0)
2654 			tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2655 			    tcp_snd_lowat_fraction;
2656 		(void) tcp_maxpsz_set(tcp, B_TRUE);
2657 	}
2658 	/*
2659 	 * Note that up till now, acceptor always inherits receive
2660 	 * window from the listener.  But if there is a metrics associated
2661 	 * with a host, we should use that instead of inheriting it from
2662 	 * listener.  Thus we need to pass this info back to the caller.
2663 	 */
2664 	if (ire_uinfo->iulp_rpipe > 0) {
2665 		tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
2666 	} else {
2667 		/*
2668 		 * For passive open, set tcp_rwnd to 0 so that the caller
2669 		 * knows that there is no rpipe metric for this connection.
2670 		 */
2671 		if (tcp_detached)
2672 			tcp->tcp_rwnd = 0;
2673 	}
2674 	if (ire_uinfo->iulp_rtomax > 0) {
2675 		tcp->tcp_second_timer_threshold = ire_uinfo->iulp_rtomax;
2676 	}
2677 
2678 	/*
2679 	 * Use the metric option settings, iulp_tstamp_ok and iulp_wscale_ok,
2680 	 * only for active open.  What this means is that if the other side
2681 	 * uses timestamp or window scale option, TCP will also use those
2682 	 * options.  That is for passive open.  If the application sets a
2683 	 * large window, window scale is enabled regardless of the value in
2684 	 * iulp_wscale_ok.  This is the behavior since 2.6.  So we keep it.
2685 	 * The only case left in passive open processing is the check for SACK.
2686 	 *
2687 	 * For ECN, it should probably be like SACK.  But the current
2688 	 * value is binary, so we treat it like the other cases.  The
2689 	 * metric only controls active open.  For passive open, the ndd
2690 	 * param, tcp_ecn_permitted, controls the behavior.
2691 	 */
2692 	if (!tcp_detached) {
2693 		/*
2694 		 * The if check means that the following can only be turned
2695 		 * on by the metrics only IRE, but not off.
2696 		 */
2697 		if (ire_uinfo->iulp_tstamp_ok)
2698 			tcp->tcp_snd_ts_ok = B_TRUE;
2699 		if (ire_uinfo->iulp_wscale_ok)
2700 			tcp->tcp_snd_ws_ok = B_TRUE;
2701 		if (ire_uinfo->iulp_sack == 2)
2702 			tcp->tcp_snd_sack_ok = B_TRUE;
2703 		if (ire_uinfo->iulp_ecn_ok)
2704 			tcp->tcp_ecn_ok = B_TRUE;
2705 	} else {
2706 		/*
2707 		 * Passive open.
2708 		 *
2709 		 * As above, the if check means that SACK can only be
2710 		 * turned on by the metric only IRE.
2711 		 */
2712 		if (ire_uinfo->iulp_sack > 0) {
2713 			tcp->tcp_snd_sack_ok = B_TRUE;
2714 		}
2715 	}
2716 
2717 	/*
2718 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2719 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2720 	 * length of all those options exceeds 28 bytes.  But because
2721 	 * of the tcp_mss_min check below, we may not have a problem if
2722 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2723 	 * the negative problem still exists.  And the check defeats PMTUd.
2724 	 * In fact, if PMTUd finds that the MSS should be smaller than
2725 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2726 	 * value.
2727 	 *
2728 	 * We do not deal with that now.  All those problems related to
2729 	 * PMTUd will be fixed later.
2730 	 */
2731 	ASSERT(ire->ire_max_frag != 0);
2732 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2733 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2734 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2735 			mss = MIN(mss, IPV6_MIN_MTU);
2736 		}
2737 	}
2738 
2739 	/* Sanity check for MSS value. */
2740 	if (tcp->tcp_ipversion == IPV4_VERSION)
2741 		mss_max = tcp_mss_max_ipv4;
2742 	else
2743 		mss_max = tcp_mss_max_ipv6;
2744 
2745 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2746 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2747 		/*
2748 		 * After receiving an ICMPv6 "packet too big" message with a
2749 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2750 		 * will insert a 8-byte fragment header in every packet; we
2751 		 * reduce the MSS by that amount here.
2752 		 */
2753 		mss -= sizeof (ip6_frag_t);
2754 	}
2755 
2756 	if (tcp->tcp_ipsec_overhead == 0)
2757 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2758 
2759 	mss -= tcp->tcp_ipsec_overhead;
2760 
2761 	if (mss < tcp_mss_min)
2762 		mss = tcp_mss_min;
2763 	if (mss > mss_max)
2764 		mss = mss_max;
2765 
2766 	/* Note that this is the maximum MSS, excluding all options. */
2767 	tcp->tcp_mss = mss;
2768 
2769 	/*
2770 	 * Initialize the ISS here now that we have the full connection ID.
2771 	 * The RFC 1948 method of initial sequence number generation requires
2772 	 * knowledge of the full connection ID before setting the ISS.
2773 	 */
2774 
2775 	tcp_iss_init(tcp);
2776 
2777 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2778 		tcp->tcp_loopback = B_TRUE;
2779 
2780 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2781 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
2782 	} else {
2783 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
2784 	}
2785 
2786 	if (hsp != NULL) {
2787 		/* Only modify if we're going to make them bigger */
2788 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2789 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2790 			if (tcp_snd_lowat_fraction != 0)
2791 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2792 					tcp_snd_lowat_fraction;
2793 		}
2794 
2795 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2796 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2797 		}
2798 
2799 		/* Copy timestamp flag only for active open */
2800 		if (!tcp_detached)
2801 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2802 	}
2803 
2804 	if (sire != NULL)
2805 		IRE_REFRELE(sire);
2806 
2807 	/*
2808 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2809 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2810 	 */
2811 	if (tcp->tcp_loopback ||
2812 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2813 		/*
2814 		 * For incoming, see if this tcp may be MDT-capable.  For
2815 		 * outgoing, this process has been taken care of through
2816 		 * tcp_rput_other.
2817 		 */
2818 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2819 		tcp->tcp_ire_ill_check_done = B_TRUE;
2820 	}
2821 
2822 	mutex_enter(&connp->conn_lock);
2823 	/*
2824 	 * Make sure that conn is not marked incipient
2825 	 * for incoming connections. A blind
2826 	 * removal of incipient flag is cheaper than
2827 	 * check and removal.
2828 	 */
2829 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2830 
2831 	/* Must not cache forwarding table routes. */
2832 	if (ire_cacheable) {
2833 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2834 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2835 			connp->conn_ire_cache = ire;
2836 			IRE_UNTRACE_REF(ire);
2837 			rw_exit(&ire->ire_bucket->irb_lock);
2838 			mutex_exit(&connp->conn_lock);
2839 			return (1);
2840 		}
2841 		rw_exit(&ire->ire_bucket->irb_lock);
2842 	}
2843 	mutex_exit(&connp->conn_lock);
2844 
2845 	if (ire->ire_mp == NULL)
2846 		ire_refrele(ire);
2847 	return (1);
2848 
2849 error:
2850 	if (ire->ire_mp == NULL)
2851 		ire_refrele(ire);
2852 	if (sire != NULL)
2853 		ire_refrele(sire);
2854 	return (0);
2855 }
2856 
2857 /*
2858  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2859  * O_T_BIND_REQ/T_BIND_REQ message.
2860  */
2861 static void
2862 tcp_bind(tcp_t *tcp, mblk_t *mp)
2863 {
2864 	sin_t	*sin;
2865 	sin6_t	*sin6;
2866 	mblk_t	*mp1;
2867 	in_port_t requested_port;
2868 	in_port_t allocated_port;
2869 	struct T_bind_req *tbr;
2870 	boolean_t	bind_to_req_port_only;
2871 	boolean_t	backlog_update = B_FALSE;
2872 	boolean_t	user_specified;
2873 	in6_addr_t	v6addr;
2874 	ipaddr_t	v4addr;
2875 	uint_t	origipversion;
2876 	int	err;
2877 	queue_t *q = tcp->tcp_wq;
2878 
2879 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2880 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2881 		if (tcp->tcp_debug) {
2882 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2883 			    "tcp_bind: bad req, len %u",
2884 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2885 		}
2886 		tcp_err_ack(tcp, mp, TPROTO, 0);
2887 		return;
2888 	}
2889 	/* Make sure the largest address fits */
2890 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
2891 	if (mp1 == NULL) {
2892 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2893 		return;
2894 	}
2895 	mp = mp1;
2896 	tbr = (struct T_bind_req *)mp->b_rptr;
2897 	if (tcp->tcp_state >= TCPS_BOUND) {
2898 		if ((tcp->tcp_state == TCPS_BOUND ||
2899 		    tcp->tcp_state == TCPS_LISTEN) &&
2900 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
2901 		    tbr->CONIND_number > 0) {
2902 			/*
2903 			 * Handle listen() increasing CONIND_number.
2904 			 * This is more "liberal" then what the TPI spec
2905 			 * requires but is needed to avoid a t_unbind
2906 			 * when handling listen() since the port number
2907 			 * might be "stolen" between the unbind and bind.
2908 			 */
2909 			backlog_update = B_TRUE;
2910 			goto do_bind;
2911 		}
2912 		if (tcp->tcp_debug) {
2913 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2914 			    "tcp_bind: bad state, %d", tcp->tcp_state);
2915 		}
2916 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
2917 		return;
2918 	}
2919 	origipversion = tcp->tcp_ipversion;
2920 
2921 	switch (tbr->ADDR_length) {
2922 	case 0:			/* request for a generic port */
2923 		tbr->ADDR_offset = sizeof (struct T_bind_req);
2924 		if (tcp->tcp_family == AF_INET) {
2925 			tbr->ADDR_length = sizeof (sin_t);
2926 			sin = (sin_t *)&tbr[1];
2927 			*sin = sin_null;
2928 			sin->sin_family = AF_INET;
2929 			mp->b_wptr = (uchar_t *)&sin[1];
2930 			tcp->tcp_ipversion = IPV4_VERSION;
2931 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
2932 		} else {
2933 			ASSERT(tcp->tcp_family == AF_INET6);
2934 			tbr->ADDR_length = sizeof (sin6_t);
2935 			sin6 = (sin6_t *)&tbr[1];
2936 			*sin6 = sin6_null;
2937 			sin6->sin6_family = AF_INET6;
2938 			mp->b_wptr = (uchar_t *)&sin6[1];
2939 			tcp->tcp_ipversion = IPV6_VERSION;
2940 			V6_SET_ZERO(v6addr);
2941 		}
2942 		requested_port = 0;
2943 		break;
2944 
2945 	case sizeof (sin_t):	/* Complete IPv4 address */
2946 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
2947 		    sizeof (sin_t));
2948 		if (sin == NULL || !OK_32PTR((char *)sin)) {
2949 			if (tcp->tcp_debug) {
2950 				(void) strlog(TCP_MOD_ID, 0, 1,
2951 				    SL_ERROR|SL_TRACE,
2952 				    "tcp_bind: bad address parameter, "
2953 				    "offset %d, len %d",
2954 				    tbr->ADDR_offset, tbr->ADDR_length);
2955 			}
2956 			tcp_err_ack(tcp, mp, TPROTO, 0);
2957 			return;
2958 		}
2959 		/*
2960 		 * With sockets sockfs will accept bogus sin_family in
2961 		 * bind() and replace it with the family used in the socket
2962 		 * call.
2963 		 */
2964 		if (sin->sin_family != AF_INET ||
2965 		    tcp->tcp_family != AF_INET) {
2966 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
2967 			return;
2968 		}
2969 		requested_port = ntohs(sin->sin_port);
2970 		tcp->tcp_ipversion = IPV4_VERSION;
2971 		v4addr = sin->sin_addr.s_addr;
2972 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
2973 		break;
2974 
2975 	case sizeof (sin6_t): /* Complete IPv6 address */
2976 		sin6 = (sin6_t *)mi_offset_param(mp,
2977 		    tbr->ADDR_offset, sizeof (sin6_t));
2978 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
2979 			if (tcp->tcp_debug) {
2980 				(void) strlog(TCP_MOD_ID, 0, 1,
2981 				    SL_ERROR|SL_TRACE,
2982 				    "tcp_bind: bad IPv6 address parameter, "
2983 				    "offset %d, len %d", tbr->ADDR_offset,
2984 				    tbr->ADDR_length);
2985 			}
2986 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2987 			return;
2988 		}
2989 		if (sin6->sin6_family != AF_INET6 ||
2990 		    tcp->tcp_family != AF_INET6) {
2991 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
2992 			return;
2993 		}
2994 		requested_port = ntohs(sin6->sin6_port);
2995 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
2996 		    IPV4_VERSION : IPV6_VERSION;
2997 		v6addr = sin6->sin6_addr;
2998 		break;
2999 
3000 	default:
3001 		if (tcp->tcp_debug) {
3002 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3003 			    "tcp_bind: bad address length, %d",
3004 			    tbr->ADDR_length);
3005 		}
3006 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3007 		return;
3008 	}
3009 	tcp->tcp_bound_source_v6 = v6addr;
3010 
3011 	/* Check for change in ipversion */
3012 	if (origipversion != tcp->tcp_ipversion) {
3013 		ASSERT(tcp->tcp_family == AF_INET6);
3014 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3015 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3016 		if (err) {
3017 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3018 			return;
3019 		}
3020 	}
3021 
3022 	/*
3023 	 * Initialize family specific fields. Copy of the src addr.
3024 	 * in tcp_t is needed for the lookup funcs.
3025 	 */
3026 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3027 		tcp->tcp_ip6h->ip6_src = v6addr;
3028 	} else {
3029 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3030 	}
3031 	tcp->tcp_ip_src_v6 = v6addr;
3032 
3033 	/*
3034 	 * For O_T_BIND_REQ:
3035 	 * Verify that the target port/addr is available, or choose
3036 	 * another.
3037 	 * For  T_BIND_REQ:
3038 	 * Verify that the target port/addr is available or fail.
3039 	 * In both cases when it succeeds the tcp is inserted in the
3040 	 * bind hash table. This ensures that the operation is atomic
3041 	 * under the lock on the hash bucket.
3042 	 */
3043 	bind_to_req_port_only = requested_port != 0 &&
3044 	    tbr->PRIM_type != O_T_BIND_REQ;
3045 	/*
3046 	 * Get a valid port (within the anonymous range and should not
3047 	 * be a privileged one) to use if the user has not given a port.
3048 	 * If multiple threads are here, they may all start with
3049 	 * with the same initial port. But, it should be fine as long as
3050 	 * tcp_bindi will ensure that no two threads will be assigned
3051 	 * the same port.
3052 	 *
3053 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3054 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3055 	 * unless TCP_ANONPRIVBIND option is set.
3056 	 */
3057 	if (requested_port == 0) {
3058 		requested_port = tcp->tcp_anon_priv_bind ?
3059 		    tcp_get_next_priv_port() :
3060 		    tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
3061 		user_specified = B_FALSE;
3062 	} else {
3063 		int i;
3064 		boolean_t priv = B_FALSE;
3065 		/*
3066 		 * If the requested_port is in the well-known privileged range,
3067 		 * verify that the stream was opened by a privileged user.
3068 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3069 		 * but instead the code relies on:
3070 		 * - the fact that the address of the array and its size never
3071 		 *   changes
3072 		 * - the atomic assignment of the elements of the array
3073 		 */
3074 		if (requested_port < tcp_smallest_nonpriv_port) {
3075 			priv = B_TRUE;
3076 		} else {
3077 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3078 				if (requested_port ==
3079 				    tcp_g_epriv_ports[i]) {
3080 					priv = B_TRUE;
3081 					break;
3082 				}
3083 			}
3084 		}
3085 		if (priv) {
3086 			cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
3087 
3088 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3089 				if (tcp->tcp_debug) {
3090 					(void) strlog(TCP_MOD_ID, 0, 1,
3091 					    SL_ERROR|SL_TRACE,
3092 					    "tcp_bind: no priv for port %d",
3093 					    requested_port);
3094 				}
3095 				tcp_err_ack(tcp, mp, TACCES, 0);
3096 				return;
3097 			}
3098 		}
3099 		user_specified = B_TRUE;
3100 	}
3101 
3102 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3103 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3104 
3105 	if (allocated_port == 0) {
3106 		if (bind_to_req_port_only) {
3107 			if (tcp->tcp_debug) {
3108 				(void) strlog(TCP_MOD_ID, 0, 1,
3109 				    SL_ERROR|SL_TRACE,
3110 				    "tcp_bind: requested addr busy");
3111 			}
3112 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3113 		} else {
3114 			/* If we are out of ports, fail the bind. */
3115 			if (tcp->tcp_debug) {
3116 				(void) strlog(TCP_MOD_ID, 0, 1,
3117 				    SL_ERROR|SL_TRACE,
3118 				    "tcp_bind: out of ports?");
3119 			}
3120 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3121 		}
3122 		return;
3123 	}
3124 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3125 do_bind:
3126 	if (!backlog_update) {
3127 		if (tcp->tcp_family == AF_INET)
3128 			sin->sin_port = htons(allocated_port);
3129 		else
3130 			sin6->sin6_port = htons(allocated_port);
3131 	}
3132 	if (tcp->tcp_family == AF_INET) {
3133 		if (tbr->CONIND_number != 0) {
3134 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3135 			    sizeof (sin_t));
3136 		} else {
3137 			/* Just verify the local IP address */
3138 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3139 		}
3140 	} else {
3141 		if (tbr->CONIND_number != 0) {
3142 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3143 			    sizeof (sin6_t));
3144 		} else {
3145 			/* Just verify the local IP address */
3146 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3147 			    IPV6_ADDR_LEN);
3148 		}
3149 	}
3150 	if (!mp1) {
3151 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3152 		return;
3153 	}
3154 
3155 	tbr->PRIM_type = T_BIND_ACK;
3156 	mp->b_datap->db_type = M_PCPROTO;
3157 
3158 	/* Chain in the reply mp for tcp_rput() */
3159 	mp1->b_cont = mp;
3160 	mp = mp1;
3161 
3162 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3163 	if (tcp->tcp_conn_req_max) {
3164 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
3165 			tcp->tcp_conn_req_max = tcp_conn_req_min;
3166 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
3167 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
3168 		/*
3169 		 * If this is a listener, do not reset the eager list
3170 		 * and other stuffs.  Note that we don't check if the
3171 		 * existing eager list meets the new tcp_conn_req_max
3172 		 * requirement.
3173 		 */
3174 		if (tcp->tcp_state != TCPS_LISTEN) {
3175 			tcp->tcp_state = TCPS_LISTEN;
3176 			/* Initialize the chain. Don't need the eager_lock */
3177 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3178 			tcp->tcp_second_ctimer_threshold =
3179 			    tcp_ip_abort_linterval;
3180 		}
3181 	}
3182 
3183 	/*
3184 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3185 	 * processing continues in tcp_rput_other().
3186 	 */
3187 	if (tcp->tcp_family == AF_INET6) {
3188 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3189 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3190 	} else {
3191 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3192 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3193 	}
3194 	/*
3195 	 * If the bind cannot complete immediately
3196 	 * IP will arrange to call tcp_rput_other
3197 	 * when the bind completes.
3198 	 */
3199 	if (mp != NULL) {
3200 		tcp_rput_other(tcp, mp);
3201 	} else {
3202 		/*
3203 		 * Bind will be resumed later. Need to ensure
3204 		 * that conn doesn't disappear when that happens.
3205 		 * This will be decremented in ip_resume_tcp_bind().
3206 		 */
3207 		CONN_INC_REF(tcp->tcp_connp);
3208 	}
3209 }
3210 
3211 
3212 /*
3213  * If the "bind_to_req_port_only" parameter is set, if the requested port
3214  * number is available, return it, If not return 0
3215  *
3216  * If "bind_to_req_port_only" parameter is not set and
3217  * If the requested port number is available, return it.  If not, return
3218  * the first anonymous port we happen across.  If no anonymous ports are
3219  * available, return 0. addr is the requested local address, if any.
3220  *
3221  * In either case, when succeeding update the tcp_t to record the port number
3222  * and insert it in the bind hash table.
3223  *
3224  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3225  * without setting SO_REUSEADDR. This is needed so that they
3226  * can be viewed as two independent transport protocols.
3227  */
3228 static in_port_t
3229 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3230     int reuseaddr, boolean_t quick_connect,
3231     boolean_t bind_to_req_port_only, boolean_t user_specified)
3232 {
3233 	/* number of times we have run around the loop */
3234 	int count = 0;
3235 	/* maximum number of times to run around the loop */
3236 	int loopmax;
3237 	zoneid_t zoneid = tcp->tcp_connp->conn_zoneid;
3238 
3239 	/*
3240 	 * Lookup for free addresses is done in a loop and "loopmax"
3241 	 * influences how long we spin in the loop
3242 	 */
3243 	if (bind_to_req_port_only) {
3244 		/*
3245 		 * If the requested port is busy, don't bother to look
3246 		 * for a new one. Setting loop maximum count to 1 has
3247 		 * that effect.
3248 		 */
3249 		loopmax = 1;
3250 	} else {
3251 		/*
3252 		 * If the requested port is busy, look for a free one
3253 		 * in the anonymous port range.
3254 		 * Set loopmax appropriately so that one does not look
3255 		 * forever in the case all of the anonymous ports are in use.
3256 		 */
3257 		if (tcp->tcp_anon_priv_bind) {
3258 			/*
3259 			 * loopmax =
3260 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3261 			 */
3262 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
3263 		} else {
3264 			loopmax = (tcp_largest_anon_port -
3265 			    tcp_smallest_anon_port + 1);
3266 		}
3267 	}
3268 	do {
3269 		uint16_t	lport;
3270 		tf_t		*tbf;
3271 		tcp_t		*ltcp;
3272 
3273 		lport = htons(port);
3274 
3275 		/*
3276 		 * Ensure that the tcp_t is not currently in the bind hash.
3277 		 * Hold the lock on the hash bucket to ensure that
3278 		 * the duplicate check plus the insertion is an atomic
3279 		 * operation.
3280 		 *
3281 		 * This function does an inline lookup on the bind hash list
3282 		 * Make sure that we access only members of tcp_t
3283 		 * and that we don't look at tcp_tcp, since we are not
3284 		 * doing a CONN_INC_REF.
3285 		 */
3286 		tcp_bind_hash_remove(tcp);
3287 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
3288 		mutex_enter(&tbf->tf_lock);
3289 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3290 		    ltcp = ltcp->tcp_bind_hash) {
3291 			if (lport != ltcp->tcp_lport ||
3292 			    ltcp->tcp_connp->conn_zoneid != zoneid) {
3293 				continue;
3294 			}
3295 
3296 			/*
3297 			 * If TCP_EXCLBIND is set for either the bound or
3298 			 * binding endpoint, the semantics of bind
3299 			 * is changed according to the following.
3300 			 *
3301 			 * spec = specified address (v4 or v6)
3302 			 * unspec = unspecified address (v4 or v6)
3303 			 * A = specified addresses are different for endpoints
3304 			 *
3305 			 * bound	bind to		allowed
3306 			 * -------------------------------------
3307 			 * unspec	unspec		no
3308 			 * unspec	spec		no
3309 			 * spec		unspec		no
3310 			 * spec		spec		yes if A
3311 			 *
3312 			 * Note:
3313 			 *
3314 			 * 1. Because of TLI semantics, an endpoint can go
3315 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3316 			 * TCPS_BOUND, depending on whether it is originally
3317 			 * a listener or not.  That is why we need to check
3318 			 * for states greater than or equal to TCPS_BOUND
3319 			 * here.
3320 			 *
3321 			 * 2. Ideally, we should only check for state equals
3322 			 * to TCPS_LISTEN. And the following check should be
3323 			 * added.
3324 			 *
3325 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3326 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3327 			 *		...
3328 			 * }
3329 			 *
3330 			 * The semantics will be changed to this.  If the
3331 			 * endpoint on the list is in state not equal to
3332 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3333 			 * set, let the bind succeed.
3334 			 *
3335 			 * But because of (1), we cannot do that now.  If
3336 			 * in future, we can change this going back semantics,
3337 			 * we can add the above check.
3338 			 */
3339 			if (ltcp->tcp_exclbind || tcp->tcp_exclbind) {
3340 				if (V6_OR_V4_INADDR_ANY(
3341 				    ltcp->tcp_bound_source_v6) ||
3342 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3343 				    IN6_ARE_ADDR_EQUAL(laddr,
3344 				    &ltcp->tcp_bound_source_v6)) {
3345 					break;
3346 				}
3347 				continue;
3348 			}
3349 
3350 			/*
3351 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3352 			 * have disjoint port number spaces, if *_EXCLBIND
3353 			 * is not set and only if the application binds to a
3354 			 * specific port. We use the same autoassigned port
3355 			 * number space for IPv4 and IPv6 sockets.
3356 			 */
3357 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3358 			    bind_to_req_port_only)
3359 				continue;
3360 
3361 			/*
3362 			 * Ideally, we should make sure that the source
3363 			 * address, remote address, and remote port in the
3364 			 * four tuple for this tcp-connection is unique.
3365 			 * However, trying to find out the local source
3366 			 * address would require too much code duplication
3367 			 * with IP, since IP needs needs to have that code
3368 			 * to support userland TCP implementations.
3369 			 */
3370 			if (quick_connect &&
3371 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3372 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3373 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3374 				    &ltcp->tcp_remote_v6)))
3375 				continue;
3376 
3377 			if (!reuseaddr) {
3378 				/*
3379 				 * No socket option SO_REUSEADDR.
3380 				 * If existing port is bound to
3381 				 * a non-wildcard IP address
3382 				 * and the requesting stream is
3383 				 * bound to a distinct
3384 				 * different IP addresses
3385 				 * (non-wildcard, also), keep
3386 				 * going.
3387 				 */
3388 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3389 				    !V6_OR_V4_INADDR_ANY(
3390 				    ltcp->tcp_bound_source_v6) &&
3391 				    !IN6_ARE_ADDR_EQUAL(laddr,
3392 					&ltcp->tcp_bound_source_v6))
3393 					continue;
3394 				if (ltcp->tcp_state >= TCPS_BOUND) {
3395 					/*
3396 					 * This port is being used and
3397 					 * its state is >= TCPS_BOUND,
3398 					 * so we can't bind to it.
3399 					 */
3400 					break;
3401 				}
3402 			} else {
3403 				/*
3404 				 * socket option SO_REUSEADDR is set on the
3405 				 * binding tcp_t.
3406 				 *
3407 				 * If two streams are bound to
3408 				 * same IP address or both addr
3409 				 * and bound source are wildcards
3410 				 * (INADDR_ANY), we want to stop
3411 				 * searching.
3412 				 * We have found a match of IP source
3413 				 * address and source port, which is
3414 				 * refused regardless of the
3415 				 * SO_REUSEADDR setting, so we break.
3416 				 */
3417 				if (IN6_ARE_ADDR_EQUAL(laddr,
3418 				    &ltcp->tcp_bound_source_v6) &&
3419 				    (ltcp->tcp_state == TCPS_LISTEN ||
3420 					ltcp->tcp_state == TCPS_BOUND))
3421 					break;
3422 			}
3423 		}
3424 		if (ltcp != NULL) {
3425 			/* The port number is busy */
3426 			mutex_exit(&tbf->tf_lock);
3427 		} else {
3428 			/*
3429 			 * This port is ours. Insert in fanout and mark as
3430 			 * bound to prevent others from getting the port
3431 			 * number.
3432 			 */
3433 			tcp->tcp_state = TCPS_BOUND;
3434 			tcp->tcp_lport = htons(port);
3435 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3436 
3437 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
3438 			    tcp->tcp_lport)] == tbf);
3439 			tcp_bind_hash_insert(tbf, tcp, 1);
3440 
3441 			mutex_exit(&tbf->tf_lock);
3442 
3443 			/*
3444 			 * We don't want tcp_next_port_to_try to "inherit"
3445 			 * a port number supplied by the user in a bind.
3446 			 */
3447 			if (user_specified)
3448 				return (port);
3449 
3450 			/*
3451 			 * This is the only place where tcp_next_port_to_try
3452 			 * is updated. After the update, it may or may not
3453 			 * be in the valid range.
3454 			 */
3455 			if (!tcp->tcp_anon_priv_bind)
3456 				tcp_next_port_to_try = port + 1;
3457 			return (port);
3458 		}
3459 
3460 		if (tcp->tcp_anon_priv_bind) {
3461 			port = tcp_get_next_priv_port();
3462 		} else {
3463 			if (count == 0 && user_specified) {
3464 				/*
3465 				 * We may have to return an anonymous port. So
3466 				 * get one to start with.
3467 				 */
3468 				port =
3469 				    tcp_update_next_port(tcp_next_port_to_try,
3470 					B_TRUE);
3471 				user_specified = B_FALSE;
3472 			} else {
3473 				port = tcp_update_next_port(port + 1, B_FALSE);
3474 			}
3475 		}
3476 
3477 		/*
3478 		 * Don't let this loop run forever in the case where
3479 		 * all of the anonymous ports are in use.
3480 		 */
3481 	} while (++count < loopmax);
3482 	return (0);
3483 }
3484 
3485 /*
3486  * We are dying for some reason.  Try to do it gracefully.  (May be called
3487  * as writer.)
3488  *
3489  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3490  * done by a service procedure).
3491  * TBD - Should the return value distinguish between the tcp_t being
3492  * freed and it being reinitialized?
3493  */
3494 static int
3495 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3496 {
3497 	mblk_t	*mp;
3498 	queue_t	*q;
3499 
3500 	TCP_CLD_STAT(tag);
3501 
3502 #if TCP_TAG_CLEAN_DEATH
3503 	tcp->tcp_cleandeathtag = tag;
3504 #endif
3505 
3506 	if (tcp->tcp_linger_tid != 0 &&
3507 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3508 		tcp_stop_lingering(tcp);
3509 	}
3510 
3511 	ASSERT(tcp != NULL);
3512 	ASSERT((tcp->tcp_family == AF_INET &&
3513 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3514 	    (tcp->tcp_family == AF_INET6 &&
3515 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3516 	    tcp->tcp_ipversion == IPV6_VERSION)));
3517 
3518 	if (TCP_IS_DETACHED(tcp)) {
3519 		if (tcp->tcp_hard_binding) {
3520 			/*
3521 			 * Its an eager that we are dealing with. We close the
3522 			 * eager but in case a conn_ind has already gone to the
3523 			 * listener, let tcp_accept_finish() send a discon_ind
3524 			 * to the listener and drop the last reference. If the
3525 			 * listener doesn't even know about the eager i.e. the
3526 			 * conn_ind hasn't gone up, blow away the eager and drop
3527 			 * the last reference as well. If the conn_ind has gone
3528 			 * up, state should be BOUND. tcp_accept_finish
3529 			 * will figure out that the connection has received a
3530 			 * RST and will send a DISCON_IND to the application.
3531 			 */
3532 			tcp_closei_local(tcp);
3533 			if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
3534 				CONN_DEC_REF(tcp->tcp_connp);
3535 			} else {
3536 				tcp->tcp_state = TCPS_BOUND;
3537 			}
3538 		} else {
3539 			tcp_close_detached(tcp);
3540 		}
3541 		return (0);
3542 	}
3543 
3544 	TCP_STAT(tcp_clean_death_nondetached);
3545 
3546 	/*
3547 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3548 	 * is run) postpone cleaning up the endpoint until service routine
3549 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3550 	 * client_errno since tcp_close uses the client_errno field.
3551 	 */
3552 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3553 		if (err != 0)
3554 			tcp->tcp_client_errno = err;
3555 
3556 		tcp->tcp_deferred_clean_death = B_TRUE;
3557 		return (-1);
3558 	}
3559 
3560 	q = tcp->tcp_rq;
3561 
3562 	/* Trash all inbound data */
3563 	flushq(q, FLUSHALL);
3564 
3565 	/*
3566 	 * If we are at least part way open and there is error
3567 	 * (err==0 implies no error)
3568 	 * notify our client by a T_DISCON_IND.
3569 	 */
3570 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3571 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3572 		    !TCP_IS_SOCKET(tcp)) {
3573 			/*
3574 			 * Send M_FLUSH according to TPI. Because sockets will
3575 			 * (and must) ignore FLUSHR we do that only for TPI
3576 			 * endpoints and sockets in STREAMS mode.
3577 			 */
3578 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3579 		}
3580 		if (tcp->tcp_debug) {
3581 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3582 			    "tcp_clean_death: discon err %d", err);
3583 		}
3584 		mp = mi_tpi_discon_ind(NULL, err, 0);
3585 		if (mp != NULL) {
3586 			putnext(q, mp);
3587 		} else {
3588 			if (tcp->tcp_debug) {
3589 				(void) strlog(TCP_MOD_ID, 0, 1,
3590 				    SL_ERROR|SL_TRACE,
3591 				    "tcp_clean_death, sending M_ERROR");
3592 			}
3593 			(void) putnextctl1(q, M_ERROR, EPROTO);
3594 		}
3595 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3596 			/* SYN_SENT or SYN_RCVD */
3597 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3598 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3599 			/* ESTABLISHED or CLOSE_WAIT */
3600 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3601 		}
3602 	}
3603 
3604 	tcp_reinit(tcp);
3605 	return (-1);
3606 }
3607 
3608 /*
3609  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3610  * to expire, stop the wait and finish the close.
3611  */
3612 static void
3613 tcp_stop_lingering(tcp_t *tcp)
3614 {
3615 	clock_t	delta = 0;
3616 
3617 	tcp->tcp_linger_tid = 0;
3618 	if (tcp->tcp_state > TCPS_LISTEN) {
3619 		tcp_acceptor_hash_remove(tcp);
3620 		if (tcp->tcp_flow_stopped) {
3621 			tcp_clrqfull(tcp);
3622 		}
3623 
3624 		if (tcp->tcp_timer_tid != 0) {
3625 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3626 			tcp->tcp_timer_tid = 0;
3627 		}
3628 		/*
3629 		 * Need to cancel those timers which will not be used when
3630 		 * TCP is detached.  This has to be done before the tcp_wq
3631 		 * is set to the global queue.
3632 		 */
3633 		tcp_timers_stop(tcp);
3634 
3635 
3636 		tcp->tcp_detached = B_TRUE;
3637 		tcp->tcp_rq = tcp_g_q;
3638 		tcp->tcp_wq = WR(tcp_g_q);
3639 
3640 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3641 			tcp_time_wait_append(tcp);
3642 			TCP_DBGSTAT(tcp_detach_time_wait);
3643 			goto finish;
3644 		}
3645 
3646 		/*
3647 		 * If delta is zero the timer event wasn't executed and was
3648 		 * successfully canceled. In this case we need to restart it
3649 		 * with the minimal delta possible.
3650 		 */
3651 		if (delta >= 0) {
3652 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3653 			    delta ? delta : 1);
3654 		}
3655 	} else {
3656 		tcp_closei_local(tcp);
3657 		CONN_DEC_REF(tcp->tcp_connp);
3658 	}
3659 finish:
3660 	/* Signal closing thread that it can complete close */
3661 	mutex_enter(&tcp->tcp_closelock);
3662 	tcp->tcp_detached = B_TRUE;
3663 	tcp->tcp_rq = tcp_g_q;
3664 	tcp->tcp_wq = WR(tcp_g_q);
3665 	tcp->tcp_closed = 1;
3666 	cv_signal(&tcp->tcp_closecv);
3667 	mutex_exit(&tcp->tcp_closelock);
3668 }
3669 
3670 /*
3671  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3672  * expires.
3673  */
3674 static void
3675 tcp_close_linger_timeout(void *arg)
3676 {
3677 	conn_t	*connp = (conn_t *)arg;
3678 	tcp_t 	*tcp = connp->conn_tcp;
3679 
3680 	tcp->tcp_client_errno = ETIMEDOUT;
3681 	tcp_stop_lingering(tcp);
3682 }
3683 
3684 static int
3685 tcp_close(queue_t *q, int flags)
3686 {
3687 	conn_t		*connp = Q_TO_CONN(q);
3688 	tcp_t		*tcp = connp->conn_tcp;
3689 	mblk_t 		*mp = &tcp->tcp_closemp;
3690 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3691 
3692 	ASSERT(WR(q)->q_next == NULL);
3693 	ASSERT(connp->conn_ref >= 2);
3694 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
3695 
3696 	/*
3697 	 * We are being closed as /dev/tcp or /dev/tcp6.
3698 	 *
3699 	 * Mark the conn as closing. ill_pending_mp_add will not
3700 	 * add any mp to the pending mp list, after this conn has
3701 	 * started closing. Same for sq_pending_mp_add
3702 	 */
3703 	mutex_enter(&connp->conn_lock);
3704 	connp->conn_state_flags |= CONN_CLOSING;
3705 	if (connp->conn_oper_pending_ill != NULL)
3706 		conn_ioctl_cleanup_reqd = B_TRUE;
3707 	CONN_INC_REF_LOCKED(connp);
3708 	mutex_exit(&connp->conn_lock);
3709 	tcp->tcp_closeflags = (uint8_t)flags;
3710 	ASSERT(connp->conn_ref >= 3);
3711 
3712 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
3713 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
3714 
3715 	mutex_enter(&tcp->tcp_closelock);
3716 	while (!tcp->tcp_closed)
3717 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3718 	mutex_exit(&tcp->tcp_closelock);
3719 	/*
3720 	 * In the case of listener streams that have eagers in the q or q0
3721 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3722 	 * tcp_wq of the eagers point to our queues. By waiting for the
3723 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3724 	 * up their queue pointers and also dropped their references to us.
3725 	 */
3726 	if (tcp->tcp_wait_for_eagers) {
3727 		mutex_enter(&connp->conn_lock);
3728 		while (connp->conn_ref != 1) {
3729 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3730 		}
3731 		mutex_exit(&connp->conn_lock);
3732 	}
3733 	/*
3734 	 * ioctl cleanup. The mp is queued in the
3735 	 * ill_pending_mp or in the sq_pending_mp.
3736 	 */
3737 	if (conn_ioctl_cleanup_reqd)
3738 		conn_ioctl_cleanup(connp);
3739 
3740 	qprocsoff(q);
3741 	inet_minor_free(ip_minor_arena, connp->conn_dev);
3742 
3743 	ASSERT(connp->conn_cred != NULL);
3744 	crfree(connp->conn_cred);
3745 	tcp->tcp_cred = connp->conn_cred = NULL;
3746 	tcp->tcp_cpid = -1;
3747 
3748 	/*
3749 	 * Drop IP's reference on the conn. This is the last reference
3750 	 * on the connp if the state was less than established. If the
3751 	 * connection has gone into timewait state, then we will have
3752 	 * one ref for the TCP and one more ref (total of two) for the
3753 	 * classifier connected hash list (a timewait connections stays
3754 	 * in connected hash till closed).
3755 	 *
3756 	 * We can't assert the references because there might be other
3757 	 * transient reference places because of some walkers or queued
3758 	 * packets in squeue for the timewait state.
3759 	 */
3760 	CONN_DEC_REF(connp);
3761 	q->q_ptr = WR(q)->q_ptr = NULL;
3762 	return (0);
3763 }
3764 
3765 static int
3766 tcpclose_accept(queue_t *q)
3767 {
3768 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3769 
3770 	/*
3771 	 * We had opened an acceptor STREAM for sockfs which is
3772 	 * now being closed due to some error.
3773 	 */
3774 	qprocsoff(q);
3775 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
3776 	q->q_ptr = WR(q)->q_ptr = NULL;
3777 	return (0);
3778 }
3779 
3780 
3781 /*
3782  * Called by streams close routine via squeues when our client blows off her
3783  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3784  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3785  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3786  * acked.
3787  *
3788  * NOTE: tcp_close potentially returns error when lingering.
3789  * However, the stream head currently does not pass these errors
3790  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3791  * errors to the application (from tsleep()) and not errors
3792  * like ECONNRESET caused by receiving a reset packet.
3793  */
3794 
3795 /* ARGSUSED */
3796 static void
3797 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3798 {
3799 	char	*msg;
3800 	conn_t	*connp = (conn_t *)arg;
3801 	tcp_t	*tcp = connp->conn_tcp;
3802 	clock_t	delta = 0;
3803 
3804 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3805 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3806 
3807 	/* Cancel any pending timeout */
3808 	if (tcp->tcp_ordrelid != 0) {
3809 		if (tcp->tcp_timeout) {
3810 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
3811 		}
3812 		tcp->tcp_ordrelid = 0;
3813 		tcp->tcp_timeout = B_FALSE;
3814 	}
3815 
3816 	mutex_enter(&tcp->tcp_eager_lock);
3817 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3818 		/* Cleanup for listener */
3819 		tcp_eager_cleanup(tcp, 0);
3820 		tcp->tcp_wait_for_eagers = 1;
3821 	}
3822 	mutex_exit(&tcp->tcp_eager_lock);
3823 
3824 	connp->conn_mdt_ok = B_FALSE;
3825 	tcp->tcp_mdt = B_FALSE;
3826 
3827 	msg = NULL;
3828 	switch (tcp->tcp_state) {
3829 	case TCPS_CLOSED:
3830 	case TCPS_IDLE:
3831 	case TCPS_BOUND:
3832 	case TCPS_LISTEN:
3833 		break;
3834 	case TCPS_SYN_SENT:
3835 		msg = "tcp_close, during connect";
3836 		break;
3837 	case TCPS_SYN_RCVD:
3838 		/*
3839 		 * Close during the connect 3-way handshake
3840 		 * but here there may or may not be pending data
3841 		 * already on queue. Process almost same as in
3842 		 * the ESTABLISHED state.
3843 		 */
3844 		/* FALLTHRU */
3845 	default:
3846 		if (tcp->tcp_fused)
3847 			tcp_unfuse(tcp);
3848 
3849 		/*
3850 		 * If SO_LINGER has set a zero linger time, abort the
3851 		 * connection with a reset.
3852 		 */
3853 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3854 			msg = "tcp_close, zero lingertime";
3855 			break;
3856 		}
3857 
3858 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3859 		/*
3860 		 * Abort connection if there is unread data queued.
3861 		 */
3862 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3863 			msg = "tcp_close, unread data";
3864 			break;
3865 		}
3866 		/*
3867 		 * tcp_hard_bound is now cleared thus all packets go through
3868 		 * tcp_lookup. This fact is used by tcp_detach below.
3869 		 *
3870 		 * We have done a qwait() above which could have possibly
3871 		 * drained more messages in turn causing transition to a
3872 		 * different state. Check whether we have to do the rest
3873 		 * of the processing or not.
3874 		 */
3875 		if (tcp->tcp_state <= TCPS_LISTEN)
3876 			break;
3877 
3878 		/*
3879 		 * Transmit the FIN before detaching the tcp_t.
3880 		 * After tcp_detach returns this queue/perimeter
3881 		 * no longer owns the tcp_t thus others can modify it.
3882 		 */
3883 		(void) tcp_xmit_end(tcp);
3884 
3885 		/*
3886 		 * If lingering on close then wait until the fin is acked,
3887 		 * the SO_LINGER time passes, or a reset is sent/received.
3888 		 */
3889 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3890 		    !(tcp->tcp_fin_acked) &&
3891 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3892 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3893 				tcp->tcp_client_errno = EWOULDBLOCK;
3894 			} else if (tcp->tcp_client_errno == 0) {
3895 
3896 				ASSERT(tcp->tcp_linger_tid == 0);
3897 
3898 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3899 				    tcp_close_linger_timeout,
3900 				    tcp->tcp_lingertime * hz);
3901 
3902 				/* tcp_close_linger_timeout will finish close */
3903 				if (tcp->tcp_linger_tid == 0)
3904 					tcp->tcp_client_errno = ENOSR;
3905 				else
3906 					return;
3907 			}
3908 
3909 			/*
3910 			 * Check if we need to detach or just close
3911 			 * the instance.
3912 			 */
3913 			if (tcp->tcp_state <= TCPS_LISTEN)
3914 				break;
3915 		}
3916 
3917 		/*
3918 		 * Make sure that no other thread will access the tcp_rq of
3919 		 * this instance (through lookups etc.) as tcp_rq will go
3920 		 * away shortly.
3921 		 */
3922 		tcp_acceptor_hash_remove(tcp);
3923 
3924 		if (tcp->tcp_flow_stopped) {
3925 			tcp_clrqfull(tcp);
3926 		}
3927 
3928 		if (tcp->tcp_timer_tid != 0) {
3929 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3930 			tcp->tcp_timer_tid = 0;
3931 		}
3932 		/*
3933 		 * Need to cancel those timers which will not be used when
3934 		 * TCP is detached.  This has to be done before the tcp_wq
3935 		 * is set to the global queue.
3936 		 */
3937 		tcp_timers_stop(tcp);
3938 
3939 		tcp->tcp_detached = B_TRUE;
3940 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3941 			tcp_time_wait_append(tcp);
3942 			TCP_DBGSTAT(tcp_detach_time_wait);
3943 			ASSERT(connp->conn_ref >= 3);
3944 			goto finish;
3945 		}
3946 
3947 		/*
3948 		 * If delta is zero the timer event wasn't executed and was
3949 		 * successfully canceled. In this case we need to restart it
3950 		 * with the minimal delta possible.
3951 		 */
3952 		if (delta >= 0)
3953 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3954 			    delta ? delta : 1);
3955 
3956 		ASSERT(connp->conn_ref >= 3);
3957 		goto finish;
3958 	}
3959 
3960 	/* Detach did not complete. Still need to remove q from stream. */
3961 	if (msg) {
3962 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3963 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3964 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3965 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3966 		    tcp->tcp_state == TCPS_SYN_RCVD)
3967 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3968 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3969 	}
3970 
3971 	tcp_closei_local(tcp);
3972 	CONN_DEC_REF(connp);
3973 	ASSERT(connp->conn_ref >= 2);
3974 
3975 finish:
3976 	/*
3977 	 * Although packets are always processed on the correct
3978 	 * tcp's perimeter and access is serialized via squeue's,
3979 	 * IP still needs a queue when sending packets in time_wait
3980 	 * state so use WR(tcp_g_q) till ip_output() can be
3981 	 * changed to deal with just connp. For read side, we
3982 	 * could have set tcp_rq to NULL but there are some cases
3983 	 * in tcp_rput_data() from early days of this code which
3984 	 * do a putnext without checking if tcp is closed. Those
3985 	 * need to be identified before both tcp_rq and tcp_wq
3986 	 * can be set to NULL and tcp_q_q can disappear forever.
3987 	 */
3988 	mutex_enter(&tcp->tcp_closelock);
3989 	/*
3990 	 * Don't change the queues in the case of a listener that has
3991 	 * eagers in its q or q0. It could surprise the eagers.
3992 	 * Instead wait for the eagers outside the squeue.
3993 	 */
3994 	if (!tcp->tcp_wait_for_eagers) {
3995 		tcp->tcp_detached = B_TRUE;
3996 		tcp->tcp_rq = tcp_g_q;
3997 		tcp->tcp_wq = WR(tcp_g_q);
3998 	}
3999 	/* Signal tcp_close() to finish closing. */
4000 	tcp->tcp_closed = 1;
4001 	cv_signal(&tcp->tcp_closecv);
4002 	mutex_exit(&tcp->tcp_closelock);
4003 }
4004 
4005 
4006 /*
4007  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4008  * Some stream heads get upset if they see these later on as anything but NULL.
4009  */
4010 static void
4011 tcp_close_mpp(mblk_t **mpp)
4012 {
4013 	mblk_t	*mp;
4014 
4015 	if ((mp = *mpp) != NULL) {
4016 		do {
4017 			mp->b_next = NULL;
4018 			mp->b_prev = NULL;
4019 		} while ((mp = mp->b_cont) != NULL);
4020 
4021 		mp = *mpp;
4022 		*mpp = NULL;
4023 		freemsg(mp);
4024 	}
4025 }
4026 
4027 /* Do detached close. */
4028 static void
4029 tcp_close_detached(tcp_t *tcp)
4030 {
4031 	if (tcp->tcp_fused)
4032 		tcp_unfuse(tcp);
4033 
4034 	/*
4035 	 * Clustering code serializes TCP disconnect callbacks and
4036 	 * cluster tcp list walks by blocking a TCP disconnect callback
4037 	 * if a cluster tcp list walk is in progress. This ensures
4038 	 * accurate accounting of TCPs in the cluster code even though
4039 	 * the TCP list walk itself is not atomic.
4040 	 */
4041 	tcp_closei_local(tcp);
4042 	CONN_DEC_REF(tcp->tcp_connp);
4043 }
4044 
4045 /*
4046  * Stop all TCP timers, and free the timer mblks if requested.
4047  */
4048 void
4049 tcp_timers_stop(tcp_t *tcp)
4050 {
4051 	if (tcp->tcp_timer_tid != 0) {
4052 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4053 		tcp->tcp_timer_tid = 0;
4054 	}
4055 	if (tcp->tcp_ka_tid != 0) {
4056 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4057 		tcp->tcp_ka_tid = 0;
4058 	}
4059 	if (tcp->tcp_ack_tid != 0) {
4060 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4061 		tcp->tcp_ack_tid = 0;
4062 	}
4063 	if (tcp->tcp_push_tid != 0) {
4064 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4065 		tcp->tcp_push_tid = 0;
4066 	}
4067 }
4068 
4069 /*
4070  * The tcp_t is going away. Remove it from all lists and set it
4071  * to TCPS_CLOSED. The freeing up of memory is deferred until
4072  * tcp_inactive. This is needed since a thread in tcp_rput might have
4073  * done a CONN_INC_REF on this structure before it was removed from the
4074  * hashes.
4075  */
4076 static void
4077 tcp_closei_local(tcp_t *tcp)
4078 {
4079 	ire_t 	*ire;
4080 	conn_t	*connp = tcp->tcp_connp;
4081 
4082 	if (!TCP_IS_SOCKET(tcp))
4083 		tcp_acceptor_hash_remove(tcp);
4084 
4085 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
4086 	tcp->tcp_ibsegs = 0;
4087 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
4088 	tcp->tcp_obsegs = 0;
4089 	/*
4090 	 * If we are an eager connection hanging off a listener that
4091 	 * hasn't formally accepted the connection yet, get off his
4092 	 * list and blow off any data that we have accumulated.
4093 	 */
4094 	if (tcp->tcp_listener != NULL) {
4095 		tcp_t	*listener = tcp->tcp_listener;
4096 		mutex_enter(&listener->tcp_eager_lock);
4097 		/*
4098 		 * tcp_eager_conn_ind == NULL means that the
4099 		 * conn_ind has already gone to listener. At
4100 		 * this point, eager will be closed but we
4101 		 * leave it in listeners eager list so that
4102 		 * if listener decides to close without doing
4103 		 * accept, we can clean this up. In tcp_wput_accept
4104 		 * we take case of the case of accept on closed
4105 		 * eager.
4106 		 */
4107 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4108 			tcp_eager_unlink(tcp);
4109 			mutex_exit(&listener->tcp_eager_lock);
4110 			/*
4111 			 * We don't want to have any pointers to the
4112 			 * listener queue, after we have released our
4113 			 * reference on the listener
4114 			 */
4115 			tcp->tcp_rq = tcp_g_q;
4116 			tcp->tcp_wq = WR(tcp_g_q);
4117 			CONN_DEC_REF(listener->tcp_connp);
4118 		} else {
4119 			mutex_exit(&listener->tcp_eager_lock);
4120 		}
4121 	}
4122 
4123 	/* Stop all the timers */
4124 	tcp_timers_stop(tcp);
4125 
4126 	if (tcp->tcp_state == TCPS_LISTEN) {
4127 		if (tcp->tcp_ip_addr_cache) {
4128 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4129 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4130 			tcp->tcp_ip_addr_cache = NULL;
4131 		}
4132 	}
4133 	if (tcp->tcp_flow_stopped)
4134 		tcp_clrqfull(tcp);
4135 
4136 	tcp_bind_hash_remove(tcp);
4137 	/*
4138 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4139 	 * is trying to remove this tcp from the time wait list, we will
4140 	 * block in tcp_time_wait_remove while trying to acquire the
4141 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4142 	 * requires the ipcl_hash_remove to be ordered after the
4143 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4144 	 */
4145 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4146 		tcp_time_wait_remove(tcp, NULL);
4147 	CL_INET_DISCONNECT(tcp);
4148 	ipcl_hash_remove(connp);
4149 
4150 	/*
4151 	 * Delete the cached ire in conn_ire_cache and also mark
4152 	 * the conn as CONDEMNED
4153 	 */
4154 	mutex_enter(&connp->conn_lock);
4155 	connp->conn_state_flags |= CONN_CONDEMNED;
4156 	ire = connp->conn_ire_cache;
4157 	connp->conn_ire_cache = NULL;
4158 	mutex_exit(&connp->conn_lock);
4159 	if (ire != NULL)
4160 		IRE_REFRELE_NOTR(ire);
4161 
4162 	/* Need to cleanup any pending ioctls */
4163 	ASSERT(tcp->tcp_time_wait_next == NULL);
4164 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4165 	ASSERT(tcp->tcp_time_wait_expire == 0);
4166 	tcp->tcp_state = TCPS_CLOSED;
4167 }
4168 
4169 /*
4170  * tcp is dying (called from ipcl_conn_destroy and error cases).
4171  * Free the tcp_t in either case.
4172  */
4173 void
4174 tcp_free(tcp_t *tcp)
4175 {
4176 	mblk_t	*mp;
4177 	ip6_pkt_t	*ipp;
4178 
4179 	ASSERT(tcp != NULL);
4180 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4181 
4182 	tcp->tcp_rq = NULL;
4183 	tcp->tcp_wq = NULL;
4184 
4185 	tcp_close_mpp(&tcp->tcp_xmit_head);
4186 	tcp_close_mpp(&tcp->tcp_reass_head);
4187 	if (tcp->tcp_rcv_list != NULL) {
4188 		/* Free b_next chain */
4189 		tcp_close_mpp(&tcp->tcp_rcv_list);
4190 	}
4191 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4192 		freemsg(mp);
4193 	}
4194 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4195 		freemsg(mp);
4196 	}
4197 
4198 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4199 		freeb(tcp->tcp_fused_sigurg_mp);
4200 		tcp->tcp_fused_sigurg_mp = NULL;
4201 	}
4202 
4203 	if (tcp->tcp_sack_info != NULL) {
4204 		if (tcp->tcp_notsack_list != NULL) {
4205 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4206 		}
4207 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4208 	}
4209 
4210 	if (tcp->tcp_hopopts != NULL) {
4211 		mi_free(tcp->tcp_hopopts);
4212 		tcp->tcp_hopopts = NULL;
4213 		tcp->tcp_hopoptslen = 0;
4214 	}
4215 	ASSERT(tcp->tcp_hopoptslen == 0);
4216 	if (tcp->tcp_dstopts != NULL) {
4217 		mi_free(tcp->tcp_dstopts);
4218 		tcp->tcp_dstopts = NULL;
4219 		tcp->tcp_dstoptslen = 0;
4220 	}
4221 	ASSERT(tcp->tcp_dstoptslen == 0);
4222 	if (tcp->tcp_rtdstopts != NULL) {
4223 		mi_free(tcp->tcp_rtdstopts);
4224 		tcp->tcp_rtdstopts = NULL;
4225 		tcp->tcp_rtdstoptslen = 0;
4226 	}
4227 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4228 	if (tcp->tcp_rthdr != NULL) {
4229 		mi_free(tcp->tcp_rthdr);
4230 		tcp->tcp_rthdr = NULL;
4231 		tcp->tcp_rthdrlen = 0;
4232 	}
4233 	ASSERT(tcp->tcp_rthdrlen == 0);
4234 
4235 	ipp = &tcp->tcp_sticky_ipp;
4236 	if ((ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS |
4237 	    IPPF_DSTOPTS | IPPF_RTHDR)) != 0) {
4238 		if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
4239 			kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
4240 			ipp->ipp_hopopts = NULL;
4241 			ipp->ipp_hopoptslen = 0;
4242 		}
4243 		if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
4244 			kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
4245 			ipp->ipp_rtdstopts = NULL;
4246 			ipp->ipp_rtdstoptslen = 0;
4247 		}
4248 		if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
4249 			kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
4250 			ipp->ipp_dstopts = NULL;
4251 			ipp->ipp_dstoptslen = 0;
4252 		}
4253 		if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
4254 			kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
4255 			ipp->ipp_rthdr = NULL;
4256 			ipp->ipp_rthdrlen = 0;
4257 		}
4258 		ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS |
4259 		    IPPF_DSTOPTS | IPPF_RTHDR);
4260 	}
4261 
4262 	/*
4263 	 * Free memory associated with the tcp/ip header template.
4264 	 */
4265 
4266 	if (tcp->tcp_iphc != NULL)
4267 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4268 
4269 	/*
4270 	 * Following is really a blowing away a union.
4271 	 * It happens to have exactly two members of identical size
4272 	 * the following code is enough.
4273 	 */
4274 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4275 
4276 	if (tcp->tcp_tracebuf != NULL) {
4277 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4278 		tcp->tcp_tracebuf = NULL;
4279 	}
4280 }
4281 
4282 
4283 /*
4284  * Put a connection confirmation message upstream built from the
4285  * address information within 'iph' and 'tcph'.  Report our success or failure.
4286  */
4287 static boolean_t
4288 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4289     mblk_t **defermp)
4290 {
4291 	sin_t	sin;
4292 	sin6_t	sin6;
4293 	mblk_t	*mp;
4294 	char	*optp = NULL;
4295 	int	optlen = 0;
4296 	cred_t	*cr;
4297 
4298 	if (defermp != NULL)
4299 		*defermp = NULL;
4300 
4301 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4302 		/*
4303 		 * Return in T_CONN_CON results of option negotiation through
4304 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4305 		 * negotiation, then what is received from remote end needs
4306 		 * to be taken into account but there is no such thing (yet?)
4307 		 * in our TCP/IP.
4308 		 * Note: We do not use mi_offset_param() here as
4309 		 * tcp_opts_conn_req contents do not directly come from
4310 		 * an application and are either generated in kernel or
4311 		 * from user input that was already verified.
4312 		 */
4313 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4314 		optp = (char *)(mp->b_rptr +
4315 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4316 		optlen = (int)
4317 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4318 	}
4319 
4320 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4321 		ipha_t *ipha = (ipha_t *)iphdr;
4322 
4323 		/* packet is IPv4 */
4324 		if (tcp->tcp_family == AF_INET) {
4325 			sin = sin_null;
4326 			sin.sin_addr.s_addr = ipha->ipha_src;
4327 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4328 			sin.sin_family = AF_INET;
4329 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4330 			    (int)sizeof (sin_t), optp, optlen);
4331 		} else {
4332 			sin6 = sin6_null;
4333 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4334 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4335 			sin6.sin6_family = AF_INET6;
4336 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4337 			    (int)sizeof (sin6_t), optp, optlen);
4338 
4339 		}
4340 	} else {
4341 		ip6_t	*ip6h = (ip6_t *)iphdr;
4342 
4343 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4344 		ASSERT(tcp->tcp_family == AF_INET6);
4345 		sin6 = sin6_null;
4346 		sin6.sin6_addr = ip6h->ip6_src;
4347 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4348 		sin6.sin6_family = AF_INET6;
4349 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4350 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4351 		    (int)sizeof (sin6_t), optp, optlen);
4352 	}
4353 
4354 	if (!mp)
4355 		return (B_FALSE);
4356 
4357 	if ((cr = DB_CRED(idmp)) != NULL) {
4358 		mblk_setcred(mp, cr);
4359 		DB_CPID(mp) = DB_CPID(idmp);
4360 	}
4361 
4362 	if (defermp == NULL)
4363 		putnext(tcp->tcp_rq, mp);
4364 	else
4365 		*defermp = mp;
4366 
4367 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4368 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4369 	return (B_TRUE);
4370 }
4371 
4372 /*
4373  * Defense for the SYN attack -
4374  * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
4375  *    one that doesn't have the dontdrop bit set.
4376  * 2. Don't drop a SYN request before its first timeout. This gives every
4377  *    request at least til the first timeout to complete its 3-way handshake.
4378  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4379  *    requests currently on the queue that has timed out. This will be used
4380  *    as an indicator of whether an attack is under way, so that appropriate
4381  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4382  *    either when eager goes into ESTABLISHED, or gets freed up.)
4383  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4384  *    # of timeout drops back to <= q0len/32 => SYN alert off
4385  */
4386 static boolean_t
4387 tcp_drop_q0(tcp_t *tcp)
4388 {
4389 	tcp_t	*eager;
4390 
4391 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4392 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4393 	/*
4394 	 * New one is added after next_q0 so prev_q0 points to the oldest
4395 	 * Also do not drop any established connections that are deferred on
4396 	 * q0 due to q being full
4397 	 */
4398 
4399 	eager = tcp->tcp_eager_prev_q0;
4400 	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
4401 		eager = eager->tcp_eager_prev_q0;
4402 		if (eager == tcp) {
4403 			eager = tcp->tcp_eager_prev_q0;
4404 			break;
4405 		}
4406 	}
4407 	if (eager->tcp_syn_rcvd_timeout == 0)
4408 		return (B_FALSE);
4409 
4410 	if (tcp->tcp_debug) {
4411 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4412 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4413 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
4414 		    tcp->tcp_conn_req_cnt_q0,
4415 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4416 	}
4417 
4418 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
4419 
4420 	/*
4421 	 * need to do refhold here because the selected eager could
4422 	 * be removed by someone else if we release the eager lock.
4423 	 */
4424 	CONN_INC_REF(eager->tcp_connp);
4425 	mutex_exit(&tcp->tcp_eager_lock);
4426 
4427 	/* Mark the IRE created for this SYN request temporary */
4428 	tcp_ip_ire_mark_advice(eager);
4429 	(void) tcp_clean_death(eager, ETIMEDOUT, 5);
4430 	CONN_DEC_REF(eager->tcp_connp);
4431 
4432 	mutex_enter(&tcp->tcp_eager_lock);
4433 	return (B_TRUE);
4434 }
4435 
4436 int
4437 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4438     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4439 {
4440 	tcp_t 		*ltcp = lconnp->conn_tcp;
4441 	tcp_t		*tcp = connp->conn_tcp;
4442 	mblk_t		*tpi_mp;
4443 	ipha_t		*ipha;
4444 	ip6_t		*ip6h;
4445 	sin6_t 		sin6;
4446 	in6_addr_t 	v6dst;
4447 	int		err;
4448 	int		ifindex = 0;
4449 	cred_t		*cr;
4450 
4451 	if (ipvers == IPV4_VERSION) {
4452 		ipha = (ipha_t *)mp->b_rptr;
4453 
4454 		connp->conn_send = ip_output;
4455 		connp->conn_recv = tcp_input;
4456 
4457 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4458 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4459 
4460 		sin6 = sin6_null;
4461 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4462 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4463 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4464 		sin6.sin6_family = AF_INET6;
4465 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4466 		    lconnp->conn_zoneid);
4467 		if (tcp->tcp_recvdstaddr) {
4468 			sin6_t	sin6d;
4469 
4470 			sin6d = sin6_null;
4471 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4472 			    &sin6d.sin6_addr);
4473 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4474 			sin6d.sin6_family = AF_INET;
4475 			tpi_mp = mi_tpi_extconn_ind(NULL,
4476 			    (char *)&sin6d, sizeof (sin6_t),
4477 			    (char *)&tcp,
4478 			    (t_scalar_t)sizeof (intptr_t),
4479 			    (char *)&sin6d, sizeof (sin6_t),
4480 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4481 		} else {
4482 			tpi_mp = mi_tpi_conn_ind(NULL,
4483 			    (char *)&sin6, sizeof (sin6_t),
4484 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4485 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4486 		}
4487 	} else {
4488 		ip6h = (ip6_t *)mp->b_rptr;
4489 
4490 		connp->conn_send = ip_output_v6;
4491 		connp->conn_recv = tcp_input;
4492 
4493 		connp->conn_srcv6 = ip6h->ip6_dst;
4494 		connp->conn_remv6 = ip6h->ip6_src;
4495 
4496 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4497 		ifindex = (int)DB_CKSUMSTUFF(mp);
4498 		DB_CKSUMSTUFF(mp) = 0;
4499 
4500 		sin6 = sin6_null;
4501 		sin6.sin6_addr = ip6h->ip6_src;
4502 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4503 		sin6.sin6_family = AF_INET6;
4504 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4505 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4506 		    lconnp->conn_zoneid);
4507 
4508 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4509 			/* Pass up the scope_id of remote addr */
4510 			sin6.sin6_scope_id = ifindex;
4511 		} else {
4512 			sin6.sin6_scope_id = 0;
4513 		}
4514 		if (tcp->tcp_recvdstaddr) {
4515 			sin6_t	sin6d;
4516 
4517 			sin6d = sin6_null;
4518 			sin6.sin6_addr = ip6h->ip6_dst;
4519 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4520 			sin6d.sin6_family = AF_INET;
4521 			tpi_mp = mi_tpi_extconn_ind(NULL,
4522 			    (char *)&sin6d, sizeof (sin6_t),
4523 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4524 			    (char *)&sin6d, sizeof (sin6_t),
4525 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4526 		} else {
4527 			tpi_mp = mi_tpi_conn_ind(NULL,
4528 			    (char *)&sin6, sizeof (sin6_t),
4529 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4530 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4531 		}
4532 	}
4533 
4534 	if (tpi_mp == NULL)
4535 		return (ENOMEM);
4536 
4537 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4538 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4539 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4540 	connp->conn_fully_bound = B_FALSE;
4541 
4542 	if (tcp_trace)
4543 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4544 
4545 	/* Inherit information from the "parent" */
4546 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4547 	tcp->tcp_family = ltcp->tcp_family;
4548 	tcp->tcp_wq = ltcp->tcp_wq;
4549 	tcp->tcp_rq = ltcp->tcp_rq;
4550 	tcp->tcp_mss = tcp_mss_def_ipv6;
4551 	tcp->tcp_detached = B_TRUE;
4552 	if ((err = tcp_init_values(tcp)) != 0) {
4553 		freemsg(tpi_mp);
4554 		return (err);
4555 	}
4556 
4557 	if (ipvers == IPV4_VERSION) {
4558 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4559 			freemsg(tpi_mp);
4560 			return (err);
4561 		}
4562 		ASSERT(tcp->tcp_ipha != NULL);
4563 	} else {
4564 		/* ifindex must be already set */
4565 		ASSERT(ifindex != 0);
4566 
4567 		if (ltcp->tcp_bound_if != 0) {
4568 			/*
4569 			 * Set newtcp's bound_if equal to
4570 			 * listener's value. If ifindex is
4571 			 * not the same as ltcp->tcp_bound_if,
4572 			 * it must be a packet for the ipmp group
4573 			 * of interfaces
4574 			 */
4575 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4576 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4577 			tcp->tcp_bound_if = ifindex;
4578 		}
4579 
4580 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4581 		tcp->tcp_recvifindex = 0;
4582 		tcp->tcp_recvhops = 0xffffffffU;
4583 		ASSERT(tcp->tcp_ip6h != NULL);
4584 	}
4585 
4586 	tcp->tcp_lport = ltcp->tcp_lport;
4587 
4588 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4589 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4590 			/*
4591 			 * Listener had options of some sort; eager inherits.
4592 			 * Free up the eager template and allocate one
4593 			 * of the right size.
4594 			 */
4595 			if (tcp->tcp_hdr_grown) {
4596 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4597 			} else {
4598 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4599 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4600 			}
4601 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4602 			    KM_NOSLEEP);
4603 			if (tcp->tcp_iphc == NULL) {
4604 				tcp->tcp_iphc_len = 0;
4605 				freemsg(tpi_mp);
4606 				return (ENOMEM);
4607 			}
4608 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4609 			tcp->tcp_hdr_grown = B_TRUE;
4610 		}
4611 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4612 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4613 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4614 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4615 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4616 
4617 		/*
4618 		 * Copy the IP+TCP header template from listener to eager
4619 		 */
4620 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4621 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4622 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4623 			    IPPROTO_RAW) {
4624 				tcp->tcp_ip6h =
4625 				    (ip6_t *)(tcp->tcp_iphc +
4626 					sizeof (ip6i_t));
4627 			} else {
4628 				tcp->tcp_ip6h =
4629 				    (ip6_t *)(tcp->tcp_iphc);
4630 			}
4631 			tcp->tcp_ipha = NULL;
4632 		} else {
4633 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4634 			tcp->tcp_ip6h = NULL;
4635 		}
4636 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4637 		    tcp->tcp_ip_hdr_len);
4638 	} else {
4639 		/*
4640 		 * only valid case when ipversion of listener and
4641 		 * eager differ is when listener is IPv6 and
4642 		 * eager is IPv4.
4643 		 * Eager header template has been initialized to the
4644 		 * maximum v4 header sizes, which includes space for
4645 		 * TCP and IP options.
4646 		 */
4647 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4648 		    (tcp->tcp_ipversion == IPV4_VERSION));
4649 		ASSERT(tcp->tcp_iphc_len >=
4650 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4651 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4652 		/* copy IP header fields individually */
4653 		tcp->tcp_ipha->ipha_ttl =
4654 		    ltcp->tcp_ip6h->ip6_hops;
4655 		bcopy(ltcp->tcp_tcph->th_lport,
4656 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4657 	}
4658 
4659 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4660 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4661 	    sizeof (in_port_t));
4662 
4663 	if (ltcp->tcp_lport == 0) {
4664 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4665 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4666 		    sizeof (in_port_t));
4667 	}
4668 
4669 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4670 		ASSERT(ipha != NULL);
4671 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4672 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4673 
4674 		/* Source routing option copyover (reverse it) */
4675 		if (tcp_rev_src_routes)
4676 			tcp_opt_reverse(tcp, ipha);
4677 	} else {
4678 		ASSERT(ip6h != NULL);
4679 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4680 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4681 	}
4682 
4683 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4684 	/*
4685 	 * If the SYN contains a credential, it's a loopback packet; attach
4686 	 * the credential to the TPI message.
4687 	 */
4688 	if ((cr = DB_CRED(idmp)) != NULL) {
4689 		mblk_setcred(tpi_mp, cr);
4690 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4691 	}
4692 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4693 
4694 	return (0);
4695 }
4696 
4697 
4698 int
4699 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4700     tcph_t *tcph, mblk_t *idmp)
4701 {
4702 	tcp_t 		*ltcp = lconnp->conn_tcp;
4703 	tcp_t		*tcp = connp->conn_tcp;
4704 	sin_t		sin;
4705 	mblk_t		*tpi_mp = NULL;
4706 	int		err;
4707 	cred_t		*cr;
4708 
4709 	sin = sin_null;
4710 	sin.sin_addr.s_addr = ipha->ipha_src;
4711 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4712 	sin.sin_family = AF_INET;
4713 	if (ltcp->tcp_recvdstaddr) {
4714 		sin_t	sind;
4715 
4716 		sind = sin_null;
4717 		sind.sin_addr.s_addr = ipha->ipha_dst;
4718 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4719 		sind.sin_family = AF_INET;
4720 		tpi_mp = mi_tpi_extconn_ind(NULL,
4721 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4722 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4723 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4724 	} else {
4725 		tpi_mp = mi_tpi_conn_ind(NULL,
4726 		    (char *)&sin, sizeof (sin_t),
4727 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4728 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4729 	}
4730 
4731 	if (tpi_mp == NULL) {
4732 		return (ENOMEM);
4733 	}
4734 
4735 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4736 	connp->conn_send = ip_output;
4737 	connp->conn_recv = tcp_input;
4738 	connp->conn_fully_bound = B_FALSE;
4739 
4740 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4741 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4742 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4743 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4744 
4745 	if (tcp_trace) {
4746 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4747 	}
4748 
4749 	/* Inherit information from the "parent" */
4750 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4751 	tcp->tcp_family = ltcp->tcp_family;
4752 	tcp->tcp_wq = ltcp->tcp_wq;
4753 	tcp->tcp_rq = ltcp->tcp_rq;
4754 	tcp->tcp_mss = tcp_mss_def_ipv4;
4755 	tcp->tcp_detached = B_TRUE;
4756 	if ((err = tcp_init_values(tcp)) != 0) {
4757 		freemsg(tpi_mp);
4758 		return (err);
4759 	}
4760 
4761 	/*
4762 	 * Let's make sure that eager tcp template has enough space to
4763 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4764 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4765 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4766 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4767 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4768 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4769 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4770 	 */
4771 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4772 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4773 
4774 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4775 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4776 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4777 	tcp->tcp_ttl = ltcp->tcp_ttl;
4778 	tcp->tcp_tos = ltcp->tcp_tos;
4779 
4780 	/* Copy the IP+TCP header template from listener to eager */
4781 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4782 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4783 	tcp->tcp_ip6h = NULL;
4784 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4785 	    tcp->tcp_ip_hdr_len);
4786 
4787 	/* Initialize the IP addresses and Ports */
4788 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4789 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4790 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4791 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4792 
4793 	/* Source routing option copyover (reverse it) */
4794 	if (tcp_rev_src_routes)
4795 		tcp_opt_reverse(tcp, ipha);
4796 
4797 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4798 
4799 	/*
4800 	 * If the SYN contains a credential, it's a loopback packet; attach
4801 	 * the credential to the TPI message.
4802 	 */
4803 	if ((cr = DB_CRED(idmp)) != NULL) {
4804 		mblk_setcred(tpi_mp, cr);
4805 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4806 	}
4807 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4808 
4809 	return (0);
4810 }
4811 
4812 /*
4813  * sets up conn for ipsec.
4814  * if the first mblk is M_CTL it is consumed and mpp is updated.
4815  * in case of error mpp is freed.
4816  */
4817 conn_t *
4818 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4819 {
4820 	conn_t 		*connp = tcp->tcp_connp;
4821 	conn_t 		*econnp;
4822 	squeue_t 	*new_sqp;
4823 	mblk_t 		*first_mp = *mpp;
4824 	mblk_t		*mp = *mpp;
4825 	boolean_t	mctl_present = B_FALSE;
4826 	uint_t		ipvers;
4827 
4828 	econnp = tcp_get_conn(sqp);
4829 	if (econnp == NULL) {
4830 		freemsg(first_mp);
4831 		return (NULL);
4832 	}
4833 	if (DB_TYPE(mp) == M_CTL) {
4834 		if (mp->b_cont == NULL ||
4835 		    mp->b_cont->b_datap->db_type != M_DATA) {
4836 			freemsg(first_mp);
4837 			return (NULL);
4838 		}
4839 		mp = mp->b_cont;
4840 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4841 			freemsg(first_mp);
4842 			return (NULL);
4843 		}
4844 
4845 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4846 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4847 		mctl_present = B_TRUE;
4848 	} else {
4849 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4850 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4851 	}
4852 
4853 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4854 	DB_CKSUMSTART(mp) = 0;
4855 
4856 	ASSERT(OK_32PTR(mp->b_rptr));
4857 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4858 	if (ipvers == IPV4_VERSION) {
4859 		uint16_t  	*up;
4860 		uint32_t	ports;
4861 		ipha_t		*ipha;
4862 
4863 		ipha = (ipha_t *)mp->b_rptr;
4864 		up = (uint16_t *)((uchar_t *)ipha +
4865 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4866 		ports = *(uint32_t *)up;
4867 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4868 		    ipha->ipha_dst, ipha->ipha_src, ports);
4869 	} else {
4870 		uint16_t  	*up;
4871 		uint32_t	ports;
4872 		uint16_t	ip_hdr_len;
4873 		uint8_t		*nexthdrp;
4874 		ip6_t 		*ip6h;
4875 		tcph_t		*tcph;
4876 
4877 		ip6h = (ip6_t *)mp->b_rptr;
4878 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4879 			ip_hdr_len = IPV6_HDR_LEN;
4880 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4881 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4882 			CONN_DEC_REF(econnp);
4883 			freemsg(first_mp);
4884 			return (NULL);
4885 		}
4886 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4887 		up = (uint16_t *)tcph->th_lport;
4888 		ports = *(uint32_t *)up;
4889 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4890 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4891 	}
4892 
4893 	/*
4894 	 * The caller already ensured that there is a sqp present.
4895 	 */
4896 	econnp->conn_sqp = new_sqp;
4897 
4898 	if (connp->conn_policy != NULL) {
4899 		ipsec_in_t *ii;
4900 		ii = (ipsec_in_t *)(first_mp->b_rptr);
4901 		ASSERT(ii->ipsec_in_policy == NULL);
4902 		IPPH_REFHOLD(connp->conn_policy);
4903 		ii->ipsec_in_policy = connp->conn_policy;
4904 
4905 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
4906 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
4907 			CONN_DEC_REF(econnp);
4908 			freemsg(first_mp);
4909 			return (NULL);
4910 		}
4911 	}
4912 
4913 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
4914 		CONN_DEC_REF(econnp);
4915 		freemsg(first_mp);
4916 		return (NULL);
4917 	}
4918 
4919 	/*
4920 	 * If we know we have some policy, pass the "IPSEC"
4921 	 * options size TCP uses this adjust the MSS.
4922 	 */
4923 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
4924 	if (mctl_present) {
4925 		freeb(first_mp);
4926 		*mpp = mp;
4927 	}
4928 
4929 	return (econnp);
4930 }
4931 
4932 /*
4933  * tcp_get_conn/tcp_free_conn
4934  *
4935  * tcp_get_conn is used to get a clean tcp connection structure.
4936  * It tries to reuse the connections put on the freelist by the
4937  * time_wait_collector failing which it goes to kmem_cache. This
4938  * way has two benefits compared to just allocating from and
4939  * freeing to kmem_cache.
4940  * 1) The time_wait_collector can free (which includes the cleanup)
4941  * outside the squeue. So when the interrupt comes, we have a clean
4942  * connection sitting in the freelist. Obviously, this buys us
4943  * performance.
4944  *
4945  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
4946  * has multiple disadvantages - tying up the squeue during alloc, and the
4947  * fact that IPSec policy initialization has to happen here which
4948  * requires us sending a M_CTL and checking for it i.e. real ugliness.
4949  * But allocating the conn/tcp in IP land is also not the best since
4950  * we can't check the 'q' and 'q0' which are protected by squeue and
4951  * blindly allocate memory which might have to be freed here if we are
4952  * not allowed to accept the connection. By using the freelist and
4953  * putting the conn/tcp back in freelist, we don't pay a penalty for
4954  * allocating memory without checking 'q/q0' and freeing it if we can't
4955  * accept the connection.
4956  *
4957  * Care should be taken to put the conn back in the same squeue's freelist
4958  * from which it was allocated. Best results are obtained if conn is
4959  * allocated from listener's squeue and freed to the same. Time wait
4960  * collector will free up the freelist is the connection ends up sitting
4961  * there for too long.
4962  */
4963 void *
4964 tcp_get_conn(void *arg)
4965 {
4966 	tcp_t			*tcp = NULL;
4967 	conn_t			*connp = NULL;
4968 	squeue_t		*sqp = (squeue_t *)arg;
4969 	tcp_squeue_priv_t 	*tcp_time_wait;
4970 
4971 	tcp_time_wait =
4972 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
4973 
4974 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
4975 	tcp = tcp_time_wait->tcp_free_list;
4976 	if (tcp != NULL) {
4977 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
4978 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4979 		tcp->tcp_time_wait_next = NULL;
4980 		connp = tcp->tcp_connp;
4981 		connp->conn_flags |= IPCL_REUSED;
4982 		return ((void *)connp);
4983 	}
4984 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4985 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
4986 		return (NULL);
4987 	return ((void *)connp);
4988 }
4989 
4990 /* BEGIN CSTYLED */
4991 /*
4992  *
4993  * The sockfs ACCEPT path:
4994  * =======================
4995  *
4996  * The eager is now established in its own perimeter as soon as SYN is
4997  * received in tcp_conn_request(). When sockfs receives conn_ind, it
4998  * completes the accept processing on the acceptor STREAM. The sending
4999  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5000  * listener but a TLI/XTI listener completes the accept processing
5001  * on the listener perimeter.
5002  *
5003  * Common control flow for 3 way handshake:
5004  * ----------------------------------------
5005  *
5006  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5007  *					-> tcp_conn_request()
5008  *
5009  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5010  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5011  *
5012  * Sockfs ACCEPT Path:
5013  * -------------------
5014  *
5015  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5016  * as STREAM entry point)
5017  *
5018  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5019  *
5020  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5021  * association (we are not behind eager's squeue but sockfs is protecting us
5022  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5023  * is changed to point at tcp_wput().
5024  *
5025  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5026  * listener (done on listener's perimeter).
5027  *
5028  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5029  * accept.
5030  *
5031  * TLI/XTI client ACCEPT path:
5032  * ---------------------------
5033  *
5034  * soaccept() sends T_CONN_RES on the listener STREAM.
5035  *
5036  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5037  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5038  *
5039  * Locks:
5040  * ======
5041  *
5042  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5043  * and listeners->tcp_eager_next_q.
5044  *
5045  * Referencing:
5046  * ============
5047  *
5048  * 1) We start out in tcp_conn_request by eager placing a ref on
5049  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5050  *
5051  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5052  * doing so we place a ref on the eager. This ref is finally dropped at the
5053  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5054  * reference is dropped by the squeue framework.
5055  *
5056  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5057  *
5058  * The reference must be released by the same entity that added the reference
5059  * In the above scheme, the eager is the entity that adds and releases the
5060  * references. Note that tcp_accept_finish executes in the squeue of the eager
5061  * (albeit after it is attached to the acceptor stream). Though 1. executes
5062  * in the listener's squeue, the eager is nascent at this point and the
5063  * reference can be considered to have been added on behalf of the eager.
5064  *
5065  * Eager getting a Reset or listener closing:
5066  * ==========================================
5067  *
5068  * Once the listener and eager are linked, the listener never does the unlink.
5069  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5070  * a message on all eager perimeter. The eager then does the unlink, clears
5071  * any pointers to the listener's queue and drops the reference to the
5072  * listener. The listener waits in tcp_close outside the squeue until its
5073  * refcount has dropped to 1. This ensures that the listener has waited for
5074  * all eagers to clear their association with the listener.
5075  *
5076  * Similarly, if eager decides to go away, it can unlink itself and close.
5077  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5078  * the reference to eager is still valid because of the extra ref we put
5079  * in tcp_send_conn_ind.
5080  *
5081  * Listener can always locate the eager under the protection
5082  * of the listener->tcp_eager_lock, and then do a refhold
5083  * on the eager during the accept processing.
5084  *
5085  * The acceptor stream accesses the eager in the accept processing
5086  * based on the ref placed on eager before sending T_conn_ind.
5087  * The only entity that can negate this refhold is a listener close
5088  * which is mutually exclusive with an active acceptor stream.
5089  *
5090  * Eager's reference on the listener
5091  * ===================================
5092  *
5093  * If the accept happens (even on a closed eager) the eager drops its
5094  * reference on the listener at the start of tcp_accept_finish. If the
5095  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5096  * the reference is dropped in tcp_closei_local. If the listener closes,
5097  * the reference is dropped in tcp_eager_kill. In all cases the reference
5098  * is dropped while executing in the eager's context (squeue).
5099  */
5100 /* END CSTYLED */
5101 
5102 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5103 
5104 /*
5105  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5106  * tcp_rput_data will not see any SYN packets.
5107  */
5108 /* ARGSUSED */
5109 void
5110 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5111 {
5112 	tcph_t		*tcph;
5113 	uint32_t	seg_seq;
5114 	tcp_t		*eager;
5115 	uint_t		ipvers;
5116 	ipha_t		*ipha;
5117 	ip6_t		*ip6h;
5118 	int		err;
5119 	conn_t		*econnp = NULL;
5120 	squeue_t	*new_sqp;
5121 	mblk_t		*mp1;
5122 	uint_t 		ip_hdr_len;
5123 	conn_t		*connp = (conn_t *)arg;
5124 	tcp_t		*tcp = connp->conn_tcp;
5125 	ire_t		*ire;
5126 
5127 	if (tcp->tcp_state != TCPS_LISTEN)
5128 		goto error2;
5129 
5130 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5131 
5132 	mutex_enter(&tcp->tcp_eager_lock);
5133 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5134 		mutex_exit(&tcp->tcp_eager_lock);
5135 		TCP_STAT(tcp_listendrop);
5136 		BUMP_MIB(&tcp_mib, tcpListenDrop);
5137 		if (tcp->tcp_debug) {
5138 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5139 			    "tcp_conn_request: listen backlog (max=%d) "
5140 			    "overflow (%d pending) on %s",
5141 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5142 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5143 		}
5144 		goto error2;
5145 	}
5146 
5147 	if (tcp->tcp_conn_req_cnt_q0 >=
5148 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
5149 		/*
5150 		 * Q0 is full. Drop a pending half-open req from the queue
5151 		 * to make room for the new SYN req. Also mark the time we
5152 		 * drop a SYN.
5153 		 *
5154 		 * A more aggressive defense against SYN attack will
5155 		 * be to set the "tcp_syn_defense" flag now.
5156 		 */
5157 		TCP_STAT(tcp_listendropq0);
5158 		tcp->tcp_last_rcv_lbolt = lbolt64;
5159 		if (!tcp_drop_q0(tcp)) {
5160 			mutex_exit(&tcp->tcp_eager_lock);
5161 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
5162 			if (tcp->tcp_debug) {
5163 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5164 				    "tcp_conn_request: listen half-open queue "
5165 				    "(max=%d) full (%d pending) on %s",
5166 				    tcp_conn_req_max_q0,
5167 				    tcp->tcp_conn_req_cnt_q0,
5168 				    tcp_display(tcp, NULL,
5169 				    DISP_PORT_ONLY));
5170 			}
5171 			goto error2;
5172 		}
5173 	}
5174 	mutex_exit(&tcp->tcp_eager_lock);
5175 
5176 	/*
5177 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5178 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5179 	 * link local address.  If IPSec is enabled, db_struioflag has
5180 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5181 	 * otherwise an error case if neither of them is set.
5182 	 */
5183 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5184 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5185 		DB_CKSUMSTART(mp) = 0;
5186 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5187 		econnp = (conn_t *)tcp_get_conn(arg2);
5188 		if (econnp == NULL)
5189 			goto error2;
5190 		econnp->conn_sqp = new_sqp;
5191 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5192 		/*
5193 		 * mp is updated in tcp_get_ipsec_conn().
5194 		 */
5195 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5196 		if (econnp == NULL) {
5197 			/*
5198 			 * mp freed by tcp_get_ipsec_conn.
5199 			 */
5200 			return;
5201 		}
5202 	} else {
5203 		goto error2;
5204 	}
5205 
5206 	ASSERT(DB_TYPE(mp) == M_DATA);
5207 
5208 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5209 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5210 	ASSERT(OK_32PTR(mp->b_rptr));
5211 	if (ipvers == IPV4_VERSION) {
5212 		ipha = (ipha_t *)mp->b_rptr;
5213 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5214 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5215 	} else {
5216 		ip6h = (ip6_t *)mp->b_rptr;
5217 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5218 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5219 	}
5220 
5221 	if (tcp->tcp_family == AF_INET) {
5222 		ASSERT(ipvers == IPV4_VERSION);
5223 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5224 	} else {
5225 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5226 	}
5227 
5228 	if (err)
5229 		goto error3;
5230 
5231 	eager = econnp->conn_tcp;
5232 
5233 	/* Inherit various TCP parameters from the listener */
5234 	eager->tcp_naglim = tcp->tcp_naglim;
5235 	eager->tcp_first_timer_threshold =
5236 	    tcp->tcp_first_timer_threshold;
5237 	eager->tcp_second_timer_threshold =
5238 	    tcp->tcp_second_timer_threshold;
5239 
5240 	eager->tcp_first_ctimer_threshold =
5241 	    tcp->tcp_first_ctimer_threshold;
5242 	eager->tcp_second_ctimer_threshold =
5243 	    tcp->tcp_second_ctimer_threshold;
5244 
5245 	/*
5246 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5247 	 * zone id before the accept is completed in tcp_wput_accept().
5248 	 */
5249 	econnp->conn_zoneid = connp->conn_zoneid;
5250 
5251 	eager->tcp_hard_binding = B_TRUE;
5252 
5253 	tcp_bind_hash_insert(&tcp_bind_fanout[
5254 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5255 
5256 	CL_INET_CONNECT(eager);
5257 
5258 	/*
5259 	 * No need to check for multicast destination since ip will only pass
5260 	 * up multicasts to those that have expressed interest
5261 	 * TODO: what about rejecting broadcasts?
5262 	 * Also check that source is not a multicast or broadcast address.
5263 	 */
5264 	eager->tcp_state = TCPS_SYN_RCVD;
5265 
5266 
5267 	/*
5268 	 * There should be no ire in the mp as we are being called after
5269 	 * receiving the SYN.
5270 	 */
5271 	ASSERT(tcp_ire_mp(mp) == NULL);
5272 
5273 	/*
5274 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5275 	 */
5276 
5277 	if (tcp_adapt_ire(eager, NULL) == 0) {
5278 		/* Undo the bind_hash_insert */
5279 		tcp_bind_hash_remove(eager);
5280 		goto error3;
5281 	}
5282 
5283 	/* Process all TCP options. */
5284 	tcp_process_options(eager, tcph);
5285 
5286 	/* Is the other end ECN capable? */
5287 	if (tcp_ecn_permitted >= 1 &&
5288 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5289 		eager->tcp_ecn_ok = B_TRUE;
5290 	}
5291 
5292 	/*
5293 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5294 	 * window size changed via SO_RCVBUF option.  First round up the
5295 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5296 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5297 	 * setting.
5298 	 *
5299 	 * Note if there is a rpipe metric associated with the remote host,
5300 	 * we should not inherit receive window size from listener.
5301 	 */
5302 	eager->tcp_rwnd = MSS_ROUNDUP(
5303 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5304 	    eager->tcp_rwnd), eager->tcp_mss);
5305 	if (eager->tcp_snd_ws_ok)
5306 		tcp_set_ws_value(eager);
5307 	/*
5308 	 * Note that this is the only place tcp_rwnd_set() is called for
5309 	 * accepting a connection.  We need to call it here instead of
5310 	 * after the 3-way handshake because we need to tell the other
5311 	 * side our rwnd in the SYN-ACK segment.
5312 	 */
5313 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5314 
5315 	/*
5316 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5317 	 * via soaccept()->soinheritoptions() which essentially applies
5318 	 * all the listener options to the new STREAM. The options that we
5319 	 * need to take care of are:
5320 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5321 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5322 	 * SO_SNDBUF, SO_RCVBUF.
5323 	 *
5324 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5325 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5326 	 *		tcp_maxpsz_set() gets called later from
5327 	 *		tcp_accept_finish(), the option takes effect.
5328 	 *
5329 	 */
5330 	/* Set the TCP options */
5331 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5332 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5333 	eager->tcp_oobinline = tcp->tcp_oobinline;
5334 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5335 	eager->tcp_broadcast = tcp->tcp_broadcast;
5336 	eager->tcp_useloopback = tcp->tcp_useloopback;
5337 	eager->tcp_dontroute = tcp->tcp_dontroute;
5338 	eager->tcp_linger = tcp->tcp_linger;
5339 	eager->tcp_lingertime = tcp->tcp_lingertime;
5340 	if (tcp->tcp_ka_enabled)
5341 		eager->tcp_ka_enabled = 1;
5342 
5343 	/* Set the IP options */
5344 	econnp->conn_broadcast = connp->conn_broadcast;
5345 	econnp->conn_loopback = connp->conn_loopback;
5346 	econnp->conn_dontroute = connp->conn_dontroute;
5347 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5348 
5349 	/* Put a ref on the listener for the eager. */
5350 	CONN_INC_REF(connp);
5351 	mutex_enter(&tcp->tcp_eager_lock);
5352 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5353 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5354 	tcp->tcp_eager_next_q0 = eager;
5355 	eager->tcp_eager_prev_q0 = tcp;
5356 
5357 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5358 	eager->tcp_listener = tcp;
5359 	eager->tcp_saved_listener = tcp;
5360 
5361 	/*
5362 	 * Tag this detached tcp vector for later retrieval
5363 	 * by our listener client in tcp_accept().
5364 	 */
5365 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5366 	tcp->tcp_conn_req_cnt_q0++;
5367 	if (++tcp->tcp_conn_req_seqnum == -1) {
5368 		/*
5369 		 * -1 is "special" and defined in TPI as something
5370 		 * that should never be used in T_CONN_IND
5371 		 */
5372 		++tcp->tcp_conn_req_seqnum;
5373 	}
5374 	mutex_exit(&tcp->tcp_eager_lock);
5375 
5376 	if (tcp->tcp_syn_defense) {
5377 		/* Don't drop the SYN that comes from a good IP source */
5378 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5379 		if (addr_cache != NULL && eager->tcp_remote ==
5380 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5381 			eager->tcp_dontdrop = B_TRUE;
5382 		}
5383 	}
5384 
5385 	/*
5386 	 * We need to insert the eager in its own perimeter but as soon
5387 	 * as we do that, we expose the eager to the classifier and
5388 	 * should not touch any field outside the eager's perimeter.
5389 	 * So do all the work necessary before inserting the eager
5390 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5391 	 * will succeed but undo everything if it fails.
5392 	 */
5393 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5394 	eager->tcp_irs = seg_seq;
5395 	eager->tcp_rack = seg_seq;
5396 	eager->tcp_rnxt = seg_seq + 1;
5397 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5398 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
5399 	eager->tcp_state = TCPS_SYN_RCVD;
5400 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5401 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5402 	if (mp1 == NULL)
5403 		goto error1;
5404 	mblk_setcred(mp1, tcp->tcp_cred);
5405 	DB_CPID(mp1) = tcp->tcp_cpid;
5406 
5407 	/*
5408 	 * We need to start the rto timer. In normal case, we start
5409 	 * the timer after sending the packet on the wire (or at
5410 	 * least believing that packet was sent by waiting for
5411 	 * CALL_IP_WPUT() to return). Since this is the first packet
5412 	 * being sent on the wire for the eager, our initial tcp_rto
5413 	 * is at least tcp_rexmit_interval_min which is a fairly
5414 	 * large value to allow the algorithm to adjust slowly to large
5415 	 * fluctuations of RTT during first few transmissions.
5416 	 *
5417 	 * Starting the timer first and then sending the packet in this
5418 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5419 	 * is of the order of several 100ms and starting the timer
5420 	 * first and then sending the packet will result in difference
5421 	 * of few micro seconds.
5422 	 *
5423 	 * Without this optimization, we are forced to hold the fanout
5424 	 * lock across the ipcl_bind_insert() and sending the packet
5425 	 * so that we don't race against an incoming packet (maybe RST)
5426 	 * for this eager.
5427 	 */
5428 
5429 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5430 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5431 
5432 
5433 	/*
5434 	 * Insert the eager in its own perimeter now. We are ready to deal
5435 	 * with any packets on eager.
5436 	 */
5437 	if (eager->tcp_ipversion == IPV4_VERSION) {
5438 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5439 			goto error;
5440 		}
5441 	} else {
5442 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5443 			goto error;
5444 		}
5445 	}
5446 
5447 	/* mark conn as fully-bound */
5448 	econnp->conn_fully_bound = B_TRUE;
5449 
5450 	/* Send the SYN-ACK */
5451 	tcp_send_data(eager, eager->tcp_wq, mp1);
5452 	freemsg(mp);
5453 
5454 	return;
5455 error:
5456 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
5457 	freemsg(mp1);
5458 error1:
5459 	/* Undo what we did above */
5460 	mutex_enter(&tcp->tcp_eager_lock);
5461 	tcp_eager_unlink(eager);
5462 	mutex_exit(&tcp->tcp_eager_lock);
5463 	/* Drop eager's reference on the listener */
5464 	CONN_DEC_REF(connp);
5465 
5466 	/*
5467 	 * Delete the cached ire in conn_ire_cache and also mark
5468 	 * the conn as CONDEMNED
5469 	 */
5470 	mutex_enter(&econnp->conn_lock);
5471 	econnp->conn_state_flags |= CONN_CONDEMNED;
5472 	ire = econnp->conn_ire_cache;
5473 	econnp->conn_ire_cache = NULL;
5474 	mutex_exit(&econnp->conn_lock);
5475 	if (ire != NULL)
5476 		IRE_REFRELE_NOTR(ire);
5477 
5478 	/*
5479 	 * tcp_accept_comm inserts the eager to the bind_hash
5480 	 * we need to remove it from the hash if ipcl_conn_insert
5481 	 * fails.
5482 	 */
5483 	tcp_bind_hash_remove(eager);
5484 	/* Drop the eager ref placed in tcp_open_detached */
5485 	CONN_DEC_REF(econnp);
5486 
5487 	/*
5488 	 * If a connection already exists, send the mp to that connections so
5489 	 * that it can be appropriately dealt with.
5490 	 */
5491 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
5492 		if (!IPCL_IS_CONNECTED(econnp)) {
5493 			/*
5494 			 * Something bad happened. ipcl_conn_insert()
5495 			 * failed because a connection already existed
5496 			 * in connected hash but we can't find it
5497 			 * anymore (someone blew it away). Just
5498 			 * free this message and hopefully remote
5499 			 * will retransmit at which time the SYN can be
5500 			 * treated as a new connection or dealth with
5501 			 * a TH_RST if a connection already exists.
5502 			 */
5503 			freemsg(mp);
5504 		} else {
5505 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
5506 			    econnp, SQTAG_TCP_CONN_REQ);
5507 		}
5508 	} else {
5509 		/* Nobody wants this packet */
5510 		freemsg(mp);
5511 	}
5512 	return;
5513 error2:
5514 	freemsg(mp);
5515 	return;
5516 error3:
5517 	CONN_DEC_REF(econnp);
5518 	freemsg(mp);
5519 }
5520 
5521 /*
5522  * In an ideal case of vertical partition in NUMA architecture, its
5523  * beneficial to have the listener and all the incoming connections
5524  * tied to the same squeue. The other constraint is that incoming
5525  * connections should be tied to the squeue attached to interrupted
5526  * CPU for obvious locality reason so this leaves the listener to
5527  * be tied to the same squeue. Our only problem is that when listener
5528  * is binding, the CPU that will get interrupted by the NIC whose
5529  * IP address the listener is binding to is not even known. So
5530  * the code below allows us to change that binding at the time the
5531  * CPU is interrupted by virtue of incoming connection's squeue.
5532  *
5533  * This is usefull only in case of a listener bound to a specific IP
5534  * address. For other kind of listeners, they get bound the
5535  * very first time and there is no attempt to rebind them.
5536  */
5537 void
5538 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5539 {
5540 	conn_t		*connp = (conn_t *)arg;
5541 	squeue_t	*sqp = (squeue_t *)arg2;
5542 	squeue_t	*new_sqp;
5543 	uint32_t	conn_flags;
5544 
5545 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5546 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5547 	} else {
5548 		goto done;
5549 	}
5550 
5551 	if (connp->conn_fanout == NULL)
5552 		goto done;
5553 
5554 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5555 		mutex_enter(&connp->conn_fanout->connf_lock);
5556 		mutex_enter(&connp->conn_lock);
5557 		/*
5558 		 * No one from read or write side can access us now
5559 		 * except for already queued packets on this squeue.
5560 		 * But since we haven't changed the squeue yet, they
5561 		 * can't execute. If they are processed after we have
5562 		 * changed the squeue, they are sent back to the
5563 		 * correct squeue down below.
5564 		 */
5565 		if (connp->conn_sqp != new_sqp) {
5566 			while (connp->conn_sqp != new_sqp)
5567 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5568 		}
5569 
5570 		do {
5571 			conn_flags = connp->conn_flags;
5572 			conn_flags |= IPCL_FULLY_BOUND;
5573 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5574 			    conn_flags);
5575 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5576 
5577 		mutex_exit(&connp->conn_fanout->connf_lock);
5578 		mutex_exit(&connp->conn_lock);
5579 	}
5580 
5581 done:
5582 	if (connp->conn_sqp != sqp) {
5583 		CONN_INC_REF(connp);
5584 		squeue_fill(connp->conn_sqp, mp,
5585 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
5586 	} else {
5587 		tcp_conn_request(connp, mp, sqp);
5588 	}
5589 }
5590 
5591 /*
5592  * Successful connect request processing begins when our client passes
5593  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5594  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5595  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
5596  *   upstream <- tcp_rput()                <- IP
5597  * After various error checks are completed, tcp_connect() lays
5598  * the target address and port into the composite header template,
5599  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5600  * request followed by an IRE request, and passes the three mblk message
5601  * down to IP looking like this:
5602  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5603  * Processing continues in tcp_rput() when we receive the following message:
5604  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5605  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5606  * to fire off the connection request, and then passes the T_OK_ACK mblk
5607  * upstream that we filled in below.  There are, of course, numerous
5608  * error conditions along the way which truncate the processing described
5609  * above.
5610  */
5611 static void
5612 tcp_connect(tcp_t *tcp, mblk_t *mp)
5613 {
5614 	sin_t		*sin;
5615 	sin6_t		*sin6;
5616 	queue_t		*q = tcp->tcp_wq;
5617 	struct T_conn_req	*tcr;
5618 	ipaddr_t	*dstaddrp;
5619 	in_port_t	dstport;
5620 	uint_t		srcid;
5621 
5622 	tcr = (struct T_conn_req *)mp->b_rptr;
5623 
5624 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5625 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5626 		tcp_err_ack(tcp, mp, TPROTO, 0);
5627 		return;
5628 	}
5629 
5630 	/*
5631 	 * Determine packet type based on type of address passed in
5632 	 * the request should contain an IPv4 or IPv6 address.
5633 	 * Make sure that address family matches the type of
5634 	 * family of the the address passed down
5635 	 */
5636 	switch (tcr->DEST_length) {
5637 	default:
5638 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5639 		return;
5640 
5641 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5642 		/*
5643 		 * XXX: The check for valid DEST_length was not there
5644 		 * in earlier releases and some buggy
5645 		 * TLI apps (e.g Sybase) got away with not feeding
5646 		 * in sin_zero part of address.
5647 		 * We allow that bug to keep those buggy apps humming.
5648 		 * Test suites require the check on DEST_length.
5649 		 * We construct a new mblk with valid DEST_length
5650 		 * free the original so the rest of the code does
5651 		 * not have to keep track of this special shorter
5652 		 * length address case.
5653 		 */
5654 		mblk_t *nmp;
5655 		struct T_conn_req *ntcr;
5656 		sin_t *nsin;
5657 
5658 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5659 		    tcr->OPT_length, BPRI_HI);
5660 		if (nmp == NULL) {
5661 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5662 			return;
5663 		}
5664 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5665 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5666 		ntcr->PRIM_type = T_CONN_REQ;
5667 		ntcr->DEST_length = sizeof (sin_t);
5668 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5669 
5670 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5671 		*nsin = sin_null;
5672 		/* Get pointer to shorter address to copy from original mp */
5673 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5674 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5675 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5676 			freemsg(nmp);
5677 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5678 			return;
5679 		}
5680 		nsin->sin_family = sin->sin_family;
5681 		nsin->sin_port = sin->sin_port;
5682 		nsin->sin_addr = sin->sin_addr;
5683 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5684 		nmp->b_wptr = (uchar_t *)&nsin[1];
5685 		if (tcr->OPT_length != 0) {
5686 			ntcr->OPT_length = tcr->OPT_length;
5687 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5688 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5689 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5690 			    tcr->OPT_length);
5691 			nmp->b_wptr += tcr->OPT_length;
5692 		}
5693 		freemsg(mp);	/* original mp freed */
5694 		mp = nmp;	/* re-initialize original variables */
5695 		tcr = ntcr;
5696 	}
5697 	/* FALLTHRU */
5698 
5699 	case sizeof (sin_t):
5700 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5701 		    sizeof (sin_t));
5702 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5703 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5704 			return;
5705 		}
5706 		if (tcp->tcp_family != AF_INET ||
5707 		    sin->sin_family != AF_INET) {
5708 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5709 			return;
5710 		}
5711 		if (sin->sin_port == 0) {
5712 			tcp_err_ack(tcp, mp, TBADADDR, 0);
5713 			return;
5714 		}
5715 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
5716 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5717 			return;
5718 		}
5719 
5720 		break;
5721 
5722 	case sizeof (sin6_t):
5723 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
5724 		    sizeof (sin6_t));
5725 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
5726 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5727 			return;
5728 		}
5729 		if (tcp->tcp_family != AF_INET6 ||
5730 		    sin6->sin6_family != AF_INET6) {
5731 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5732 			return;
5733 		}
5734 		if (sin6->sin6_port == 0) {
5735 			tcp_err_ack(tcp, mp, TBADADDR, 0);
5736 			return;
5737 		}
5738 		break;
5739 	}
5740 	/*
5741 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5742 	 * should key on their sequence number and cut them loose.
5743 	 */
5744 
5745 	/*
5746 	 * If options passed in, feed it for verification and handling
5747 	 */
5748 	if (tcr->OPT_length != 0) {
5749 		mblk_t	*ok_mp;
5750 		mblk_t	*discon_mp;
5751 		mblk_t  *conn_opts_mp;
5752 		int t_error, sys_error, do_disconnect;
5753 
5754 		conn_opts_mp = NULL;
5755 
5756 		if (tcp_conprim_opt_process(tcp, mp,
5757 			&do_disconnect, &t_error, &sys_error) < 0) {
5758 			if (do_disconnect) {
5759 				ASSERT(t_error == 0 && sys_error == 0);
5760 				discon_mp = mi_tpi_discon_ind(NULL,
5761 				    ECONNREFUSED, 0);
5762 				if (!discon_mp) {
5763 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5764 					    TSYSERR, ENOMEM);
5765 					return;
5766 				}
5767 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5768 				if (!ok_mp) {
5769 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5770 					    TSYSERR, ENOMEM);
5771 					return;
5772 				}
5773 				qreply(q, ok_mp);
5774 				qreply(q, discon_mp); /* no flush! */
5775 			} else {
5776 				ASSERT(t_error != 0);
5777 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5778 				    sys_error);
5779 			}
5780 			return;
5781 		}
5782 		/*
5783 		 * Success in setting options, the mp option buffer represented
5784 		 * by OPT_length/offset has been potentially modified and
5785 		 * contains results of option processing. We copy it in
5786 		 * another mp to save it for potentially influencing returning
5787 		 * it in T_CONN_CONN.
5788 		 */
5789 		if (tcr->OPT_length != 0) { /* there are resulting options */
5790 			conn_opts_mp = copyb(mp);
5791 			if (!conn_opts_mp) {
5792 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5793 				    TSYSERR, ENOMEM);
5794 				return;
5795 			}
5796 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5797 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5798 			/*
5799 			 * Note:
5800 			 * These resulting option negotiation can include any
5801 			 * end-to-end negotiation options but there no such
5802 			 * thing (yet?) in our TCP/IP.
5803 			 */
5804 		}
5805 	}
5806 
5807 	/*
5808 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
5809 	 * make sure that the template IP header in the tcp structure is an
5810 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
5811 	 * need to this before we call tcp_bindi() so that the port lookup
5812 	 * code will look for ports in the correct port space (IPv4 and
5813 	 * IPv6 have separate port spaces).
5814 	 */
5815 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
5816 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
5817 		int err = 0;
5818 
5819 		err = tcp_header_init_ipv4(tcp);
5820 		if (err != 0) {
5821 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
5822 			goto connect_failed;
5823 		}
5824 		if (tcp->tcp_lport != 0)
5825 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
5826 	}
5827 
5828 	switch (tcp->tcp_state) {
5829 	case TCPS_IDLE:
5830 		/*
5831 		 * We support quick connect, refer to comments in
5832 		 * tcp_connect_*()
5833 		 */
5834 		/* FALLTHRU */
5835 	case TCPS_BOUND:
5836 	case TCPS_LISTEN:
5837 		if (tcp->tcp_family == AF_INET6) {
5838 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
5839 				tcp_connect_ipv6(tcp, mp,
5840 				    &sin6->sin6_addr,
5841 				    sin6->sin6_port, sin6->sin6_flowinfo,
5842 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
5843 				return;
5844 			}
5845 			/*
5846 			 * Destination adress is mapped IPv6 address.
5847 			 * Source bound address should be unspecified or
5848 			 * IPv6 mapped address as well.
5849 			 */
5850 			if (!IN6_IS_ADDR_UNSPECIFIED(
5851 			    &tcp->tcp_bound_source_v6) &&
5852 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
5853 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
5854 				    EADDRNOTAVAIL);
5855 				break;
5856 			}
5857 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
5858 			dstport = sin6->sin6_port;
5859 			srcid = sin6->__sin6_src_id;
5860 		} else {
5861 			dstaddrp = &sin->sin_addr.s_addr;
5862 			dstport = sin->sin_port;
5863 			srcid = 0;
5864 		}
5865 
5866 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
5867 		return;
5868 	default:
5869 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
5870 		break;
5871 	}
5872 	/*
5873 	 * Note: Code below is the "failure" case
5874 	 */
5875 	/* return error ack and blow away saved option results if any */
5876 connect_failed:
5877 	if (mp != NULL)
5878 		putnext(tcp->tcp_rq, mp);
5879 	else {
5880 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5881 		    TSYSERR, ENOMEM);
5882 	}
5883 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
5884 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
5885 }
5886 
5887 /*
5888  * Handle connect to IPv4 destinations, including connections for AF_INET6
5889  * sockets connecting to IPv4 mapped IPv6 destinations.
5890  */
5891 static void
5892 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
5893     uint_t srcid)
5894 {
5895 	tcph_t	*tcph;
5896 	mblk_t	*mp1;
5897 	ipaddr_t dstaddr = *dstaddrp;
5898 	int32_t	oldstate;
5899 	uint16_t lport;
5900 
5901 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
5902 
5903 	/* Check for attempt to connect to INADDR_ANY */
5904 	if (dstaddr == INADDR_ANY)  {
5905 		/*
5906 		 * SunOS 4.x and 4.3 BSD allow an application
5907 		 * to connect a TCP socket to INADDR_ANY.
5908 		 * When they do this, the kernel picks the
5909 		 * address of one interface and uses it
5910 		 * instead.  The kernel usually ends up
5911 		 * picking the address of the loopback
5912 		 * interface.  This is an undocumented feature.
5913 		 * However, we provide the same thing here
5914 		 * in order to have source and binary
5915 		 * compatibility with SunOS 4.x.
5916 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
5917 		 * generate the T_CONN_CON.
5918 		 */
5919 		dstaddr = htonl(INADDR_LOOPBACK);
5920 		*dstaddrp = dstaddr;
5921 	}
5922 
5923 	/* Handle __sin6_src_id if socket not bound to an IP address */
5924 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
5925 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
5926 		    tcp->tcp_connp->conn_zoneid);
5927 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
5928 		    tcp->tcp_ipha->ipha_src);
5929 	}
5930 
5931 	/*
5932 	 * Don't let an endpoint connect to itself.  Note that
5933 	 * the test here does not catch the case where the
5934 	 * source IP addr was left unspecified by the user. In
5935 	 * this case, the source addr is set in tcp_adapt_ire()
5936 	 * using the reply to the T_BIND message that we send
5937 	 * down to IP here and the check is repeated in tcp_rput_other.
5938 	 */
5939 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
5940 	    dstport == tcp->tcp_lport) {
5941 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
5942 		goto failed;
5943 	}
5944 
5945 	tcp->tcp_ipha->ipha_dst = dstaddr;
5946 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
5947 
5948 	/*
5949 	 * Massage a source route if any putting the first hop
5950 	 * in iph_dst. Compute a starting value for the checksum which
5951 	 * takes into account that the original iph_dst should be
5952 	 * included in the checksum but that ip will include the
5953 	 * first hop in the source route in the tcp checksum.
5954 	 */
5955 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
5956 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
5957 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
5958 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
5959 	if ((int)tcp->tcp_sum < 0)
5960 		tcp->tcp_sum--;
5961 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
5962 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
5963 	    (tcp->tcp_sum >> 16));
5964 	tcph = tcp->tcp_tcph;
5965 	*(uint16_t *)tcph->th_fport = dstport;
5966 	tcp->tcp_fport = dstport;
5967 
5968 	oldstate = tcp->tcp_state;
5969 	/*
5970 	 * At this point the remote destination address and remote port fields
5971 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5972 	 * have to see which state tcp was in so we can take apropriate action.
5973 	 */
5974 	if (oldstate == TCPS_IDLE) {
5975 		/*
5976 		 * We support a quick connect capability here, allowing
5977 		 * clients to transition directly from IDLE to SYN_SENT
5978 		 * tcp_bindi will pick an unused port, insert the connection
5979 		 * in the bind hash and transition to BOUND state.
5980 		 */
5981 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
5982 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
5983 		    B_FALSE, B_FALSE);
5984 		if (lport == 0) {
5985 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
5986 			goto failed;
5987 		}
5988 	}
5989 	tcp->tcp_state = TCPS_SYN_SENT;
5990 
5991 	/*
5992 	 * TODO: allow data with connect requests
5993 	 * by unlinking M_DATA trailers here and
5994 	 * linking them in behind the T_OK_ACK mblk.
5995 	 * The tcp_rput() bind ack handler would then
5996 	 * feed them to tcp_wput_data() rather than call
5997 	 * tcp_timer().
5998 	 */
5999 	mp = mi_tpi_ok_ack_alloc(mp);
6000 	if (!mp) {
6001 		tcp->tcp_state = oldstate;
6002 		goto failed;
6003 	}
6004 	if (tcp->tcp_family == AF_INET) {
6005 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6006 		    sizeof (ipa_conn_t));
6007 	} else {
6008 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6009 		    sizeof (ipa6_conn_t));
6010 	}
6011 	if (mp1) {
6012 		/* Hang onto the T_OK_ACK for later. */
6013 		linkb(mp1, mp);
6014 		if (tcp->tcp_family == AF_INET)
6015 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6016 		else {
6017 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6018 			    &tcp->tcp_sticky_ipp);
6019 		}
6020 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6021 		tcp->tcp_active_open = 1;
6022 		/*
6023 		 * If the bind cannot complete immediately
6024 		 * IP will arrange to call tcp_rput_other
6025 		 * when the bind completes.
6026 		 */
6027 		if (mp1 != NULL)
6028 			tcp_rput_other(tcp, mp1);
6029 		return;
6030 	}
6031 	/* Error case */
6032 	tcp->tcp_state = oldstate;
6033 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6034 
6035 failed:
6036 	/* return error ack and blow away saved option results if any */
6037 	if (mp != NULL)
6038 		putnext(tcp->tcp_rq, mp);
6039 	else {
6040 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6041 		    TSYSERR, ENOMEM);
6042 	}
6043 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6044 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6045 
6046 }
6047 
6048 /*
6049  * Handle connect to IPv6 destinations.
6050  */
6051 static void
6052 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6053     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6054 {
6055 	tcph_t	*tcph;
6056 	mblk_t	*mp1;
6057 	ip6_rthdr_t *rth;
6058 	int32_t  oldstate;
6059 	uint16_t lport;
6060 
6061 	ASSERT(tcp->tcp_family == AF_INET6);
6062 
6063 	/*
6064 	 * If we're here, it means that the destination address is a native
6065 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6066 	 * reason why it might not be IPv6 is if the socket was bound to an
6067 	 * IPv4-mapped IPv6 address.
6068 	 */
6069 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6070 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6071 		goto failed;
6072 	}
6073 
6074 	/*
6075 	 * Interpret a zero destination to mean loopback.
6076 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6077 	 * generate the T_CONN_CON.
6078 	 */
6079 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6080 		*dstaddrp = ipv6_loopback;
6081 	}
6082 
6083 	/* Handle __sin6_src_id if socket not bound to an IP address */
6084 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6085 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6086 		    tcp->tcp_connp->conn_zoneid);
6087 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6088 	}
6089 
6090 	/*
6091 	 * Take care of the scope_id now and add ip6i_t
6092 	 * if ip6i_t is not already allocated through TCP
6093 	 * sticky options. At this point tcp_ip6h does not
6094 	 * have dst info, thus use dstaddrp.
6095 	 */
6096 	if (scope_id != 0 &&
6097 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6098 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6099 		ip6i_t  *ip6i;
6100 
6101 		ipp->ipp_ifindex = scope_id;
6102 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6103 
6104 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6105 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6106 			/* Already allocated */
6107 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6108 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6109 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6110 		} else {
6111 			int reterr;
6112 
6113 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6114 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6115 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6116 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6117 			if (reterr != 0)
6118 				goto failed;
6119 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6120 		}
6121 	}
6122 
6123 	/*
6124 	 * Don't let an endpoint connect to itself.  Note that
6125 	 * the test here does not catch the case where the
6126 	 * source IP addr was left unspecified by the user. In
6127 	 * this case, the source addr is set in tcp_adapt_ire()
6128 	 * using the reply to the T_BIND message that we send
6129 	 * down to IP here and the check is repeated in tcp_rput_other.
6130 	 */
6131 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6132 	    (dstport == tcp->tcp_lport)) {
6133 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6134 		goto failed;
6135 	}
6136 
6137 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6138 	tcp->tcp_remote_v6 = *dstaddrp;
6139 	tcp->tcp_ip6h->ip6_vcf =
6140 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6141 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6142 
6143 
6144 	/*
6145 	 * Massage a routing header (if present) putting the first hop
6146 	 * in ip6_dst. Compute a starting value for the checksum which
6147 	 * takes into account that the original ip6_dst should be
6148 	 * included in the checksum but that ip will include the
6149 	 * first hop in the source route in the tcp checksum.
6150 	 */
6151 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6152 	if (rth != NULL) {
6153 
6154 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
6155 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6156 		    (tcp->tcp_sum >> 16));
6157 	} else {
6158 		tcp->tcp_sum = 0;
6159 	}
6160 
6161 	tcph = tcp->tcp_tcph;
6162 	*(uint16_t *)tcph->th_fport = dstport;
6163 	tcp->tcp_fport = dstport;
6164 
6165 	oldstate = tcp->tcp_state;
6166 	/*
6167 	 * At this point the remote destination address and remote port fields
6168 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6169 	 * have to see which state tcp was in so we can take apropriate action.
6170 	 */
6171 	if (oldstate == TCPS_IDLE) {
6172 		/*
6173 		 * We support a quick connect capability here, allowing
6174 		 * clients to transition directly from IDLE to SYN_SENT
6175 		 * tcp_bindi will pick an unused port, insert the connection
6176 		 * in the bind hash and transition to BOUND state.
6177 		 */
6178 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
6179 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6180 		    B_FALSE, B_FALSE);
6181 		if (lport == 0) {
6182 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6183 			goto failed;
6184 		}
6185 	}
6186 	tcp->tcp_state = TCPS_SYN_SENT;
6187 	/*
6188 	 * TODO: allow data with connect requests
6189 	 * by unlinking M_DATA trailers here and
6190 	 * linking them in behind the T_OK_ACK mblk.
6191 	 * The tcp_rput() bind ack handler would then
6192 	 * feed them to tcp_wput_data() rather than call
6193 	 * tcp_timer().
6194 	 */
6195 	mp = mi_tpi_ok_ack_alloc(mp);
6196 	if (!mp) {
6197 		tcp->tcp_state = oldstate;
6198 		goto failed;
6199 	}
6200 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6201 	if (mp1) {
6202 		/* Hang onto the T_OK_ACK for later. */
6203 		linkb(mp1, mp);
6204 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6205 		    &tcp->tcp_sticky_ipp);
6206 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6207 		tcp->tcp_active_open = 1;
6208 		/* ip_bind_v6() may return ACK or ERROR */
6209 		if (mp1 != NULL)
6210 			tcp_rput_other(tcp, mp1);
6211 		return;
6212 	}
6213 	/* Error case */
6214 	tcp->tcp_state = oldstate;
6215 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6216 
6217 failed:
6218 	/* return error ack and blow away saved option results if any */
6219 	if (mp != NULL)
6220 		putnext(tcp->tcp_rq, mp);
6221 	else {
6222 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6223 		    TSYSERR, ENOMEM);
6224 	}
6225 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6226 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6227 }
6228 
6229 /*
6230  * We need a stream q for detached closing tcp connections
6231  * to use.  Our client hereby indicates that this q is the
6232  * one to use.
6233  */
6234 static void
6235 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6236 {
6237 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6238 	queue_t	*q = tcp->tcp_wq;
6239 
6240 	mp->b_datap->db_type = M_IOCACK;
6241 	iocp->ioc_count = 0;
6242 	mutex_enter(&tcp_g_q_lock);
6243 	if (tcp_g_q != NULL) {
6244 		mutex_exit(&tcp_g_q_lock);
6245 		iocp->ioc_error = EALREADY;
6246 	} else {
6247 		mblk_t *mp1;
6248 
6249 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6250 		if (mp1 == NULL) {
6251 			mutex_exit(&tcp_g_q_lock);
6252 			iocp->ioc_error = ENOMEM;
6253 		} else {
6254 			tcp_g_q = tcp->tcp_rq;
6255 			mutex_exit(&tcp_g_q_lock);
6256 			iocp->ioc_error = 0;
6257 			iocp->ioc_rval = 0;
6258 			/*
6259 			 * We are passing tcp_sticky_ipp as NULL
6260 			 * as it is not useful for tcp_default queue
6261 			 */
6262 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6263 			if (mp1 != NULL)
6264 				tcp_rput_other(tcp, mp1);
6265 		}
6266 	}
6267 	qreply(q, mp);
6268 }
6269 
6270 /*
6271  * Our client hereby directs us to reject the connection request
6272  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6273  * of sending the appropriate RST, not an ICMP error.
6274  */
6275 static void
6276 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6277 {
6278 	tcp_t	*ltcp = NULL;
6279 	t_scalar_t seqnum;
6280 	conn_t	*connp;
6281 
6282 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6283 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6284 		tcp_err_ack(tcp, mp, TPROTO, 0);
6285 		return;
6286 	}
6287 
6288 	/*
6289 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6290 	 * when the stream is in BOUND state. Do not send a reset,
6291 	 * since the destination IP address is not valid, and it can
6292 	 * be the initialized value of all zeros (broadcast address).
6293 	 *
6294 	 * If TCP has sent down a bind request to IP and has not
6295 	 * received the reply, reject the request.  Otherwise, TCP
6296 	 * will be confused.
6297 	 */
6298 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6299 		if (tcp->tcp_debug) {
6300 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6301 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6302 		}
6303 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6304 		return;
6305 	}
6306 
6307 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6308 
6309 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6310 
6311 		/*
6312 		 * According to TPI, for non-listeners, ignore seqnum
6313 		 * and disconnect.
6314 		 * Following interpretation of -1 seqnum is historical
6315 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6316 		 * a valid seqnum should not be -1).
6317 		 *
6318 		 *	-1 means disconnect everything
6319 		 *	regardless even on a listener.
6320 		 */
6321 
6322 		int old_state = tcp->tcp_state;
6323 
6324 		/*
6325 		 * The connection can't be on the tcp_time_wait_head list
6326 		 * since it is not detached.
6327 		 */
6328 		ASSERT(tcp->tcp_time_wait_next == NULL);
6329 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6330 		ASSERT(tcp->tcp_time_wait_expire == 0);
6331 		ltcp = NULL;
6332 		/*
6333 		 * If it used to be a listener, check to make sure no one else
6334 		 * has taken the port before switching back to LISTEN state.
6335 		 */
6336 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6337 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6338 			    tcp->tcp_ipha->ipha_src,
6339 			    tcp->tcp_connp->conn_zoneid);
6340 			if (connp != NULL)
6341 				ltcp = connp->conn_tcp;
6342 		} else {
6343 			/* Allow tcp_bound_if listeners? */
6344 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6345 			    &tcp->tcp_ip6h->ip6_src, 0,
6346 			    tcp->tcp_connp->conn_zoneid);
6347 			if (connp != NULL)
6348 				ltcp = connp->conn_tcp;
6349 		}
6350 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6351 			tcp->tcp_state = TCPS_LISTEN;
6352 		} else if (old_state > TCPS_BOUND) {
6353 			tcp->tcp_conn_req_max = 0;
6354 			tcp->tcp_state = TCPS_BOUND;
6355 		}
6356 		if (ltcp != NULL)
6357 			CONN_DEC_REF(ltcp->tcp_connp);
6358 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6359 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
6360 		} else if (old_state == TCPS_ESTABLISHED ||
6361 		    old_state == TCPS_CLOSE_WAIT) {
6362 			BUMP_MIB(&tcp_mib, tcpEstabResets);
6363 		}
6364 
6365 		if (tcp->tcp_fused)
6366 			tcp_unfuse(tcp);
6367 
6368 		mutex_enter(&tcp->tcp_eager_lock);
6369 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6370 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6371 			tcp_eager_cleanup(tcp, 0);
6372 		}
6373 		mutex_exit(&tcp->tcp_eager_lock);
6374 
6375 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6376 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6377 
6378 		tcp_reinit(tcp);
6379 
6380 		if (old_state >= TCPS_ESTABLISHED) {
6381 			/* Send M_FLUSH according to TPI */
6382 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6383 		}
6384 		mp = mi_tpi_ok_ack_alloc(mp);
6385 		if (mp)
6386 			putnext(tcp->tcp_rq, mp);
6387 		return;
6388 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6389 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6390 		return;
6391 	}
6392 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6393 		/* Send M_FLUSH according to TPI */
6394 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6395 	}
6396 	mp = mi_tpi_ok_ack_alloc(mp);
6397 	if (mp)
6398 		putnext(tcp->tcp_rq, mp);
6399 }
6400 
6401 /*
6402  * Diagnostic routine used to return a string associated with the tcp state.
6403  * Note that if the caller does not supply a buffer, it will use an internal
6404  * static string.  This means that if multiple threads call this function at
6405  * the same time, output can be corrupted...  Note also that this function
6406  * does not check the size of the supplied buffer.  The caller has to make
6407  * sure that it is big enough.
6408  */
6409 static char *
6410 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6411 {
6412 	char		buf1[30];
6413 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6414 	char		*buf;
6415 	char		*cp;
6416 	in6_addr_t	local, remote;
6417 	char		local_addrbuf[INET6_ADDRSTRLEN];
6418 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6419 
6420 	if (sup_buf != NULL)
6421 		buf = sup_buf;
6422 	else
6423 		buf = priv_buf;
6424 
6425 	if (tcp == NULL)
6426 		return ("NULL_TCP");
6427 	switch (tcp->tcp_state) {
6428 	case TCPS_CLOSED:
6429 		cp = "TCP_CLOSED";
6430 		break;
6431 	case TCPS_IDLE:
6432 		cp = "TCP_IDLE";
6433 		break;
6434 	case TCPS_BOUND:
6435 		cp = "TCP_BOUND";
6436 		break;
6437 	case TCPS_LISTEN:
6438 		cp = "TCP_LISTEN";
6439 		break;
6440 	case TCPS_SYN_SENT:
6441 		cp = "TCP_SYN_SENT";
6442 		break;
6443 	case TCPS_SYN_RCVD:
6444 		cp = "TCP_SYN_RCVD";
6445 		break;
6446 	case TCPS_ESTABLISHED:
6447 		cp = "TCP_ESTABLISHED";
6448 		break;
6449 	case TCPS_CLOSE_WAIT:
6450 		cp = "TCP_CLOSE_WAIT";
6451 		break;
6452 	case TCPS_FIN_WAIT_1:
6453 		cp = "TCP_FIN_WAIT_1";
6454 		break;
6455 	case TCPS_CLOSING:
6456 		cp = "TCP_CLOSING";
6457 		break;
6458 	case TCPS_LAST_ACK:
6459 		cp = "TCP_LAST_ACK";
6460 		break;
6461 	case TCPS_FIN_WAIT_2:
6462 		cp = "TCP_FIN_WAIT_2";
6463 		break;
6464 	case TCPS_TIME_WAIT:
6465 		cp = "TCP_TIME_WAIT";
6466 		break;
6467 	default:
6468 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6469 		cp = buf1;
6470 		break;
6471 	}
6472 	switch (format) {
6473 	case DISP_ADDR_AND_PORT:
6474 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6475 			/*
6476 			 * Note that we use the remote address in the tcp_b
6477 			 * structure.  This means that it will print out
6478 			 * the real destination address, not the next hop's
6479 			 * address if source routing is used.
6480 			 */
6481 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6482 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6483 
6484 		} else {
6485 			local = tcp->tcp_ip_src_v6;
6486 			remote = tcp->tcp_remote_v6;
6487 		}
6488 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6489 		    sizeof (local_addrbuf));
6490 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6491 		    sizeof (remote_addrbuf));
6492 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6493 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6494 		    ntohs(tcp->tcp_fport), cp);
6495 		break;
6496 	case DISP_PORT_ONLY:
6497 	default:
6498 		(void) mi_sprintf(buf, "[%u, %u] %s",
6499 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6500 		break;
6501 	}
6502 
6503 	return (buf);
6504 }
6505 
6506 /*
6507  * Called via squeue to get on to eager's perimeter to send a
6508  * TH_RST. The listener wants the eager to disappear either
6509  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
6510  * being called.
6511  */
6512 /* ARGSUSED */
6513 void
6514 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6515 {
6516 	conn_t	*econnp = (conn_t *)arg;
6517 	tcp_t	*eager = econnp->conn_tcp;
6518 	tcp_t	*listener = eager->tcp_listener;
6519 
6520 	/*
6521 	 * We could be called because listener is closing. Since
6522 	 * the eager is using listener's queue's, its not safe.
6523 	 * Better use the default queue just to send the TH_RST
6524 	 * out.
6525 	 */
6526 	eager->tcp_rq = tcp_g_q;
6527 	eager->tcp_wq = WR(tcp_g_q);
6528 
6529 	if (eager->tcp_state > TCPS_LISTEN) {
6530 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6531 		    eager, eager->tcp_snxt, 0, TH_RST);
6532 	}
6533 
6534 	/* We are here because listener wants this eager gone */
6535 	if (listener != NULL) {
6536 		mutex_enter(&listener->tcp_eager_lock);
6537 		tcp_eager_unlink(eager);
6538 		if (eager->tcp_conn.tcp_eager_conn_ind == NULL) {
6539 			/*
6540 			 * The eager has sent a conn_ind up to the
6541 			 * listener but listener decides to close
6542 			 * instead. We need to drop the extra ref
6543 			 * placed on eager in tcp_rput_data() before
6544 			 * sending the conn_ind to listener.
6545 			 */
6546 			CONN_DEC_REF(econnp);
6547 		}
6548 		mutex_exit(&listener->tcp_eager_lock);
6549 		CONN_DEC_REF(listener->tcp_connp);
6550 	}
6551 
6552 	if (eager->tcp_state > TCPS_BOUND)
6553 		tcp_close_detached(eager);
6554 }
6555 
6556 /*
6557  * Reset any eager connection hanging off this listener marked
6558  * with 'seqnum' and then reclaim it's resources.
6559  */
6560 static boolean_t
6561 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6562 {
6563 	tcp_t	*eager;
6564 	mblk_t 	*mp;
6565 
6566 	TCP_STAT(tcp_eager_blowoff_calls);
6567 	eager = listener;
6568 	mutex_enter(&listener->tcp_eager_lock);
6569 	do {
6570 		eager = eager->tcp_eager_next_q;
6571 		if (eager == NULL) {
6572 			mutex_exit(&listener->tcp_eager_lock);
6573 			return (B_FALSE);
6574 		}
6575 	} while (eager->tcp_conn_req_seqnum != seqnum);
6576 	CONN_INC_REF(eager->tcp_connp);
6577 	mutex_exit(&listener->tcp_eager_lock);
6578 	mp = &eager->tcp_closemp;
6579 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6580 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
6581 	return (B_TRUE);
6582 }
6583 
6584 /*
6585  * Reset any eager connection hanging off this listener
6586  * and then reclaim it's resources.
6587  */
6588 static void
6589 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6590 {
6591 	tcp_t	*eager;
6592 	mblk_t	*mp;
6593 
6594 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6595 
6596 	if (!q0_only) {
6597 		/* First cleanup q */
6598 		TCP_STAT(tcp_eager_blowoff_q);
6599 		eager = listener->tcp_eager_next_q;
6600 		while (eager != NULL) {
6601 			CONN_INC_REF(eager->tcp_connp);
6602 			mp = &eager->tcp_closemp;
6603 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
6604 			    tcp_eager_kill, eager->tcp_connp,
6605 			    SQTAG_TCP_EAGER_CLEANUP);
6606 			eager = eager->tcp_eager_next_q;
6607 		}
6608 	}
6609 	/* Then cleanup q0 */
6610 	TCP_STAT(tcp_eager_blowoff_q0);
6611 	eager = listener->tcp_eager_next_q0;
6612 	while (eager != listener) {
6613 		CONN_INC_REF(eager->tcp_connp);
6614 		mp = &eager->tcp_closemp;
6615 		squeue_fill(eager->tcp_connp->conn_sqp, mp,
6616 		    tcp_eager_kill, eager->tcp_connp,
6617 		    SQTAG_TCP_EAGER_CLEANUP_Q0);
6618 		eager = eager->tcp_eager_next_q0;
6619 	}
6620 }
6621 
6622 /*
6623  * If we are an eager connection hanging off a listener that hasn't
6624  * formally accepted the connection yet, get off his list and blow off
6625  * any data that we have accumulated.
6626  */
6627 static void
6628 tcp_eager_unlink(tcp_t *tcp)
6629 {
6630 	tcp_t	*listener = tcp->tcp_listener;
6631 
6632 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6633 	ASSERT(listener != NULL);
6634 	if (tcp->tcp_eager_next_q0 != NULL) {
6635 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6636 
6637 		/* Remove the eager tcp from q0 */
6638 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6639 		    tcp->tcp_eager_prev_q0;
6640 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6641 		    tcp->tcp_eager_next_q0;
6642 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6643 		listener->tcp_conn_req_cnt_q0--;
6644 
6645 		tcp->tcp_eager_next_q0 = NULL;
6646 		tcp->tcp_eager_prev_q0 = NULL;
6647 
6648 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6649 			/* we have timed out before */
6650 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6651 			listener->tcp_syn_rcvd_timeout--;
6652 		}
6653 	} else {
6654 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6655 		tcp_t	*prev = NULL;
6656 
6657 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6658 			if (tcpp[0] == tcp) {
6659 				if (listener->tcp_eager_last_q == tcp) {
6660 					/*
6661 					 * If we are unlinking the last
6662 					 * element on the list, adjust
6663 					 * tail pointer. Set tail pointer
6664 					 * to nil when list is empty.
6665 					 */
6666 					ASSERT(tcp->tcp_eager_next_q == NULL);
6667 					if (listener->tcp_eager_last_q ==
6668 					    listener->tcp_eager_next_q) {
6669 						listener->tcp_eager_last_q =
6670 						NULL;
6671 					} else {
6672 						/*
6673 						 * We won't get here if there
6674 						 * is only one eager in the
6675 						 * list.
6676 						 */
6677 						ASSERT(prev != NULL);
6678 						listener->tcp_eager_last_q =
6679 						    prev;
6680 					}
6681 				}
6682 				tcpp[0] = tcp->tcp_eager_next_q;
6683 				tcp->tcp_eager_next_q = NULL;
6684 				tcp->tcp_eager_last_q = NULL;
6685 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6686 				listener->tcp_conn_req_cnt_q--;
6687 				break;
6688 			}
6689 			prev = tcpp[0];
6690 		}
6691 	}
6692 	tcp->tcp_listener = NULL;
6693 }
6694 
6695 /* Shorthand to generate and send TPI error acks to our client */
6696 static void
6697 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6698 {
6699 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6700 		putnext(tcp->tcp_rq, mp);
6701 }
6702 
6703 /* Shorthand to generate and send TPI error acks to our client */
6704 static void
6705 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6706     int t_error, int sys_error)
6707 {
6708 	struct T_error_ack	*teackp;
6709 
6710 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6711 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6712 		teackp = (struct T_error_ack *)mp->b_rptr;
6713 		teackp->ERROR_prim = primitive;
6714 		teackp->TLI_error = t_error;
6715 		teackp->UNIX_error = sys_error;
6716 		putnext(tcp->tcp_rq, mp);
6717 	}
6718 }
6719 
6720 /*
6721  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6722  * but instead the code relies on:
6723  * - the fact that the address of the array and its size never changes
6724  * - the atomic assignment of the elements of the array
6725  */
6726 /* ARGSUSED */
6727 static int
6728 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6729 {
6730 	int i;
6731 
6732 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6733 		if (tcp_g_epriv_ports[i] != 0)
6734 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
6735 	}
6736 	return (0);
6737 }
6738 
6739 /*
6740  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6741  * threads from changing it at the same time.
6742  */
6743 /* ARGSUSED */
6744 static int
6745 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6746     cred_t *cr)
6747 {
6748 	long	new_value;
6749 	int	i;
6750 
6751 	/*
6752 	 * Fail the request if the new value does not lie within the
6753 	 * port number limits.
6754 	 */
6755 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6756 	    new_value <= 0 || new_value >= 65536) {
6757 		return (EINVAL);
6758 	}
6759 
6760 	mutex_enter(&tcp_epriv_port_lock);
6761 	/* Check if the value is already in the list */
6762 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6763 		if (new_value == tcp_g_epriv_ports[i]) {
6764 			mutex_exit(&tcp_epriv_port_lock);
6765 			return (EEXIST);
6766 		}
6767 	}
6768 	/* Find an empty slot */
6769 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6770 		if (tcp_g_epriv_ports[i] == 0)
6771 			break;
6772 	}
6773 	if (i == tcp_g_num_epriv_ports) {
6774 		mutex_exit(&tcp_epriv_port_lock);
6775 		return (EOVERFLOW);
6776 	}
6777 	/* Set the new value */
6778 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
6779 	mutex_exit(&tcp_epriv_port_lock);
6780 	return (0);
6781 }
6782 
6783 /*
6784  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6785  * threads from changing it at the same time.
6786  */
6787 /* ARGSUSED */
6788 static int
6789 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6790     cred_t *cr)
6791 {
6792 	long	new_value;
6793 	int	i;
6794 
6795 	/*
6796 	 * Fail the request if the new value does not lie within the
6797 	 * port number limits.
6798 	 */
6799 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
6800 	    new_value >= 65536) {
6801 		return (EINVAL);
6802 	}
6803 
6804 	mutex_enter(&tcp_epriv_port_lock);
6805 	/* Check that the value is already in the list */
6806 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6807 		if (tcp_g_epriv_ports[i] == new_value)
6808 			break;
6809 	}
6810 	if (i == tcp_g_num_epriv_ports) {
6811 		mutex_exit(&tcp_epriv_port_lock);
6812 		return (ESRCH);
6813 	}
6814 	/* Clear the value */
6815 	tcp_g_epriv_ports[i] = 0;
6816 	mutex_exit(&tcp_epriv_port_lock);
6817 	return (0);
6818 }
6819 
6820 /* Return the TPI/TLI equivalent of our current tcp_state */
6821 static int
6822 tcp_tpistate(tcp_t *tcp)
6823 {
6824 	switch (tcp->tcp_state) {
6825 	case TCPS_IDLE:
6826 		return (TS_UNBND);
6827 	case TCPS_LISTEN:
6828 		/*
6829 		 * Return whether there are outstanding T_CONN_IND waiting
6830 		 * for the matching T_CONN_RES. Therefore don't count q0.
6831 		 */
6832 		if (tcp->tcp_conn_req_cnt_q > 0)
6833 			return (TS_WRES_CIND);
6834 		else
6835 			return (TS_IDLE);
6836 	case TCPS_BOUND:
6837 		return (TS_IDLE);
6838 	case TCPS_SYN_SENT:
6839 		return (TS_WCON_CREQ);
6840 	case TCPS_SYN_RCVD:
6841 		/*
6842 		 * Note: assumption: this has to the active open SYN_RCVD.
6843 		 * The passive instance is detached in SYN_RCVD stage of
6844 		 * incoming connection processing so we cannot get request
6845 		 * for T_info_ack on it.
6846 		 */
6847 		return (TS_WACK_CRES);
6848 	case TCPS_ESTABLISHED:
6849 		return (TS_DATA_XFER);
6850 	case TCPS_CLOSE_WAIT:
6851 		return (TS_WREQ_ORDREL);
6852 	case TCPS_FIN_WAIT_1:
6853 		return (TS_WIND_ORDREL);
6854 	case TCPS_FIN_WAIT_2:
6855 		return (TS_WIND_ORDREL);
6856 
6857 	case TCPS_CLOSING:
6858 	case TCPS_LAST_ACK:
6859 	case TCPS_TIME_WAIT:
6860 	case TCPS_CLOSED:
6861 		/*
6862 		 * Following TS_WACK_DREQ7 is a rendition of "not
6863 		 * yet TS_IDLE" TPI state. There is no best match to any
6864 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6865 		 * choose a value chosen that will map to TLI/XTI level
6866 		 * state of TSTATECHNG (state is process of changing) which
6867 		 * captures what this dummy state represents.
6868 		 */
6869 		return (TS_WACK_DREQ7);
6870 	default:
6871 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6872 		    tcp->tcp_state, tcp_display(tcp, NULL,
6873 		    DISP_PORT_ONLY));
6874 		return (TS_UNBND);
6875 	}
6876 }
6877 
6878 static void
6879 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
6880 {
6881 	if (tcp->tcp_family == AF_INET6)
6882 		*tia = tcp_g_t_info_ack_v6;
6883 	else
6884 		*tia = tcp_g_t_info_ack;
6885 	tia->CURRENT_state = tcp_tpistate(tcp);
6886 	tia->OPT_size = tcp_max_optsize;
6887 	if (tcp->tcp_mss == 0) {
6888 		/* Not yet set - tcp_open does not set mss */
6889 		if (tcp->tcp_ipversion == IPV4_VERSION)
6890 			tia->TIDU_size = tcp_mss_def_ipv4;
6891 		else
6892 			tia->TIDU_size = tcp_mss_def_ipv6;
6893 	} else {
6894 		tia->TIDU_size = tcp->tcp_mss;
6895 	}
6896 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
6897 }
6898 
6899 /*
6900  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
6901  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
6902  * tcp_g_t_info_ack.  The current state of the stream is copied from
6903  * tcp_state.
6904  */
6905 static void
6906 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
6907 {
6908 	t_uscalar_t		cap_bits1;
6909 	struct T_capability_ack	*tcap;
6910 
6911 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
6912 		freemsg(mp);
6913 		return;
6914 	}
6915 
6916 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
6917 
6918 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
6919 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
6920 	if (mp == NULL)
6921 		return;
6922 
6923 	tcap = (struct T_capability_ack *)mp->b_rptr;
6924 	tcap->CAP_bits1 = 0;
6925 
6926 	if (cap_bits1 & TC1_INFO) {
6927 		tcp_copy_info(&tcap->INFO_ack, tcp);
6928 		tcap->CAP_bits1 |= TC1_INFO;
6929 	}
6930 
6931 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
6932 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
6933 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
6934 	}
6935 
6936 	putnext(tcp->tcp_rq, mp);
6937 }
6938 
6939 /*
6940  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
6941  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
6942  * The current state of the stream is copied from tcp_state.
6943  */
6944 static void
6945 tcp_info_req(tcp_t *tcp, mblk_t *mp)
6946 {
6947 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
6948 	    T_INFO_ACK);
6949 	if (!mp) {
6950 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6951 		return;
6952 	}
6953 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
6954 	putnext(tcp->tcp_rq, mp);
6955 }
6956 
6957 /* Respond to the TPI addr request */
6958 static void
6959 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
6960 {
6961 	sin_t	*sin;
6962 	mblk_t	*ackmp;
6963 	struct T_addr_ack *taa;
6964 
6965 	/* Make it large enough for worst case */
6966 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
6967 	    2 * sizeof (sin6_t), 1);
6968 	if (ackmp == NULL) {
6969 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6970 		return;
6971 	}
6972 
6973 	if (tcp->tcp_ipversion == IPV6_VERSION) {
6974 		tcp_addr_req_ipv6(tcp, ackmp);
6975 		return;
6976 	}
6977 	taa = (struct T_addr_ack *)ackmp->b_rptr;
6978 
6979 	bzero(taa, sizeof (struct T_addr_ack));
6980 	ackmp->b_wptr = (uchar_t *)&taa[1];
6981 
6982 	taa->PRIM_type = T_ADDR_ACK;
6983 	ackmp->b_datap->db_type = M_PCPROTO;
6984 
6985 	/*
6986 	 * Note: Following code assumes 32 bit alignment of basic
6987 	 * data structures like sin_t and struct T_addr_ack.
6988 	 */
6989 	if (tcp->tcp_state >= TCPS_BOUND) {
6990 		/*
6991 		 * Fill in local address
6992 		 */
6993 		taa->LOCADDR_length = sizeof (sin_t);
6994 		taa->LOCADDR_offset = sizeof (*taa);
6995 
6996 		sin = (sin_t *)&taa[1];
6997 
6998 		/* Fill zeroes and then intialize non-zero fields */
6999 		*sin = sin_null;
7000 
7001 		sin->sin_family = AF_INET;
7002 
7003 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7004 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7005 
7006 		ackmp->b_wptr = (uchar_t *)&sin[1];
7007 
7008 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7009 			/*
7010 			 * Fill in Remote address
7011 			 */
7012 			taa->REMADDR_length = sizeof (sin_t);
7013 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7014 						taa->LOCADDR_length);
7015 
7016 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7017 			*sin = sin_null;
7018 			sin->sin_family = AF_INET;
7019 			sin->sin_addr.s_addr = tcp->tcp_remote;
7020 			sin->sin_port = tcp->tcp_fport;
7021 
7022 			ackmp->b_wptr = (uchar_t *)&sin[1];
7023 		}
7024 	}
7025 	putnext(tcp->tcp_rq, ackmp);
7026 }
7027 
7028 /* Assumes that tcp_addr_req gets enough space and alignment */
7029 static void
7030 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7031 {
7032 	sin6_t	*sin6;
7033 	struct T_addr_ack *taa;
7034 
7035 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7036 	ASSERT(OK_32PTR(ackmp->b_rptr));
7037 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7038 	    2 * sizeof (sin6_t));
7039 
7040 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7041 
7042 	bzero(taa, sizeof (struct T_addr_ack));
7043 	ackmp->b_wptr = (uchar_t *)&taa[1];
7044 
7045 	taa->PRIM_type = T_ADDR_ACK;
7046 	ackmp->b_datap->db_type = M_PCPROTO;
7047 
7048 	/*
7049 	 * Note: Following code assumes 32 bit alignment of basic
7050 	 * data structures like sin6_t and struct T_addr_ack.
7051 	 */
7052 	if (tcp->tcp_state >= TCPS_BOUND) {
7053 		/*
7054 		 * Fill in local address
7055 		 */
7056 		taa->LOCADDR_length = sizeof (sin6_t);
7057 		taa->LOCADDR_offset = sizeof (*taa);
7058 
7059 		sin6 = (sin6_t *)&taa[1];
7060 		*sin6 = sin6_null;
7061 
7062 		sin6->sin6_family = AF_INET6;
7063 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7064 		sin6->sin6_port = tcp->tcp_lport;
7065 
7066 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7067 
7068 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7069 			/*
7070 			 * Fill in Remote address
7071 			 */
7072 			taa->REMADDR_length = sizeof (sin6_t);
7073 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7074 						taa->LOCADDR_length);
7075 
7076 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7077 			*sin6 = sin6_null;
7078 			sin6->sin6_family = AF_INET6;
7079 			sin6->sin6_flowinfo =
7080 			    tcp->tcp_ip6h->ip6_vcf &
7081 			    ~IPV6_VERS_AND_FLOW_MASK;
7082 			sin6->sin6_addr = tcp->tcp_remote_v6;
7083 			sin6->sin6_port = tcp->tcp_fport;
7084 
7085 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7086 		}
7087 	}
7088 	putnext(tcp->tcp_rq, ackmp);
7089 }
7090 
7091 /*
7092  * Handle reinitialization of a tcp structure.
7093  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7094  */
7095 static void
7096 tcp_reinit(tcp_t *tcp)
7097 {
7098 	mblk_t	*mp;
7099 	int 	err;
7100 
7101 	TCP_STAT(tcp_reinit_calls);
7102 
7103 	/* tcp_reinit should never be called for detached tcp_t's */
7104 	ASSERT(tcp->tcp_listener == NULL);
7105 	ASSERT((tcp->tcp_family == AF_INET &&
7106 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7107 	    (tcp->tcp_family == AF_INET6 &&
7108 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7109 	    tcp->tcp_ipversion == IPV6_VERSION)));
7110 
7111 	/* Cancel outstanding timers */
7112 	tcp_timers_stop(tcp);
7113 
7114 	/*
7115 	 * Reset everything in the state vector, after updating global
7116 	 * MIB data from instance counters.
7117 	 */
7118 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
7119 	tcp->tcp_ibsegs = 0;
7120 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
7121 	tcp->tcp_obsegs = 0;
7122 
7123 	tcp_close_mpp(&tcp->tcp_xmit_head);
7124 	if (tcp->tcp_snd_zcopy_aware)
7125 		tcp_zcopy_notify(tcp);
7126 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7127 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7128 	if (tcp->tcp_flow_stopped &&
7129 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7130 		tcp_clrqfull(tcp);
7131 	}
7132 	tcp_close_mpp(&tcp->tcp_reass_head);
7133 	tcp->tcp_reass_tail = NULL;
7134 	if (tcp->tcp_rcv_list != NULL) {
7135 		/* Free b_next chain */
7136 		tcp_close_mpp(&tcp->tcp_rcv_list);
7137 		tcp->tcp_rcv_last_head = NULL;
7138 		tcp->tcp_rcv_last_tail = NULL;
7139 		tcp->tcp_rcv_cnt = 0;
7140 	}
7141 	tcp->tcp_rcv_last_tail = NULL;
7142 
7143 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7144 		freemsg(mp);
7145 		tcp->tcp_urp_mp = NULL;
7146 	}
7147 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7148 		freemsg(mp);
7149 		tcp->tcp_urp_mark_mp = NULL;
7150 	}
7151 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7152 		freeb(tcp->tcp_fused_sigurg_mp);
7153 		tcp->tcp_fused_sigurg_mp = NULL;
7154 	}
7155 
7156 	/*
7157 	 * Following is a union with two members which are
7158 	 * identical types and size so the following cleanup
7159 	 * is enough.
7160 	 */
7161 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7162 
7163 	CL_INET_DISCONNECT(tcp);
7164 
7165 	/*
7166 	 * The connection can't be on the tcp_time_wait_head list
7167 	 * since it is not detached.
7168 	 */
7169 	ASSERT(tcp->tcp_time_wait_next == NULL);
7170 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7171 	ASSERT(tcp->tcp_time_wait_expire == 0);
7172 
7173 	/*
7174 	 * Reset/preserve other values
7175 	 */
7176 	tcp_reinit_values(tcp);
7177 	ipcl_hash_remove(tcp->tcp_connp);
7178 	conn_delete_ire(tcp->tcp_connp, NULL);
7179 
7180 	if (tcp->tcp_conn_req_max != 0) {
7181 		/*
7182 		 * This is the case when a TLI program uses the same
7183 		 * transport end point to accept a connection.  This
7184 		 * makes the TCP both a listener and acceptor.  When
7185 		 * this connection is closed, we need to set the state
7186 		 * back to TCPS_LISTEN.  Make sure that the eager list
7187 		 * is reinitialized.
7188 		 *
7189 		 * Note that this stream is still bound to the four
7190 		 * tuples of the previous connection in IP.  If a new
7191 		 * SYN with different foreign address comes in, IP will
7192 		 * not find it and will send it to the global queue.  In
7193 		 * the global queue, TCP will do a tcp_lookup_listener()
7194 		 * to find this stream.  This works because this stream
7195 		 * is only removed from connected hash.
7196 		 *
7197 		 */
7198 		tcp->tcp_state = TCPS_LISTEN;
7199 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7200 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7201 		if (tcp->tcp_family == AF_INET6) {
7202 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7203 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7204 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7205 		} else {
7206 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7207 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7208 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7209 		}
7210 	} else {
7211 		tcp->tcp_state = TCPS_BOUND;
7212 	}
7213 
7214 	/*
7215 	 * Initialize to default values
7216 	 * Can't fail since enough header template space already allocated
7217 	 * at open().
7218 	 */
7219 	err = tcp_init_values(tcp);
7220 	ASSERT(err == 0);
7221 	/* Restore state in tcp_tcph */
7222 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7223 	if (tcp->tcp_ipversion == IPV4_VERSION)
7224 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7225 	else
7226 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7227 	/*
7228 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7229 	 * since the lookup funcs can only lookup on tcp_t
7230 	 */
7231 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7232 
7233 	ASSERT(tcp->tcp_ptpbhn != NULL);
7234 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
7235 	tcp->tcp_rwnd = tcp_recv_hiwat;
7236 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7237 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
7238 }
7239 
7240 /*
7241  * Force values to zero that need be zero.
7242  * Do not touch values asociated with the BOUND or LISTEN state
7243  * since the connection will end up in that state after the reinit.
7244  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7245  * structure!
7246  */
7247 static void
7248 tcp_reinit_values(tcp)
7249 	tcp_t *tcp;
7250 {
7251 #ifndef	lint
7252 #define	DONTCARE(x)
7253 #define	PRESERVE(x)
7254 #else
7255 #define	DONTCARE(x)	((x) = (x))
7256 #define	PRESERVE(x)	((x) = (x))
7257 #endif	/* lint */
7258 
7259 	PRESERVE(tcp->tcp_bind_hash);
7260 	PRESERVE(tcp->tcp_ptpbhn);
7261 	PRESERVE(tcp->tcp_acceptor_hash);
7262 	PRESERVE(tcp->tcp_ptpahn);
7263 
7264 	/* Should be ASSERT NULL on these with new code! */
7265 	ASSERT(tcp->tcp_time_wait_next == NULL);
7266 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7267 	ASSERT(tcp->tcp_time_wait_expire == 0);
7268 	PRESERVE(tcp->tcp_state);
7269 	PRESERVE(tcp->tcp_rq);
7270 	PRESERVE(tcp->tcp_wq);
7271 
7272 	ASSERT(tcp->tcp_xmit_head == NULL);
7273 	ASSERT(tcp->tcp_xmit_last == NULL);
7274 	ASSERT(tcp->tcp_unsent == 0);
7275 	ASSERT(tcp->tcp_xmit_tail == NULL);
7276 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7277 
7278 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7279 	tcp->tcp_suna = 0;			/* Displayed in mib */
7280 	tcp->tcp_swnd = 0;
7281 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7282 
7283 	ASSERT(tcp->tcp_ibsegs == 0);
7284 	ASSERT(tcp->tcp_obsegs == 0);
7285 
7286 	if (tcp->tcp_iphc != NULL) {
7287 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7288 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7289 	}
7290 
7291 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7292 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7293 	DONTCARE(tcp->tcp_ipha);
7294 	DONTCARE(tcp->tcp_ip6h);
7295 	DONTCARE(tcp->tcp_ip_hdr_len);
7296 	DONTCARE(tcp->tcp_tcph);
7297 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7298 	tcp->tcp_valid_bits = 0;
7299 
7300 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7301 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7302 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7303 	tcp->tcp_last_rcv_lbolt = 0;
7304 
7305 	tcp->tcp_init_cwnd = 0;
7306 
7307 	tcp->tcp_urp_last_valid = 0;
7308 	tcp->tcp_hard_binding = 0;
7309 	tcp->tcp_hard_bound = 0;
7310 	PRESERVE(tcp->tcp_cred);
7311 	PRESERVE(tcp->tcp_cpid);
7312 	PRESERVE(tcp->tcp_exclbind);
7313 
7314 	tcp->tcp_fin_acked = 0;
7315 	tcp->tcp_fin_rcvd = 0;
7316 	tcp->tcp_fin_sent = 0;
7317 	tcp->tcp_ordrel_done = 0;
7318 
7319 	tcp->tcp_debug = 0;
7320 	tcp->tcp_dontroute = 0;
7321 	tcp->tcp_broadcast = 0;
7322 
7323 	tcp->tcp_useloopback = 0;
7324 	tcp->tcp_reuseaddr = 0;
7325 	tcp->tcp_oobinline = 0;
7326 	tcp->tcp_dgram_errind = 0;
7327 
7328 	tcp->tcp_detached = 0;
7329 	tcp->tcp_bind_pending = 0;
7330 	tcp->tcp_unbind_pending = 0;
7331 	tcp->tcp_deferred_clean_death = 0;
7332 
7333 	tcp->tcp_snd_ws_ok = B_FALSE;
7334 	tcp->tcp_snd_ts_ok = B_FALSE;
7335 	tcp->tcp_linger = 0;
7336 	tcp->tcp_ka_enabled = 0;
7337 	tcp->tcp_zero_win_probe = 0;
7338 
7339 	tcp->tcp_loopback = 0;
7340 	tcp->tcp_localnet = 0;
7341 	tcp->tcp_syn_defense = 0;
7342 	tcp->tcp_set_timer = 0;
7343 
7344 	tcp->tcp_active_open = 0;
7345 	ASSERT(tcp->tcp_timeout == B_FALSE);
7346 	tcp->tcp_rexmit = B_FALSE;
7347 	tcp->tcp_xmit_zc_clean = B_FALSE;
7348 
7349 	tcp->tcp_snd_sack_ok = B_FALSE;
7350 	PRESERVE(tcp->tcp_recvdstaddr);
7351 	tcp->tcp_hwcksum = B_FALSE;
7352 
7353 	tcp->tcp_ire_ill_check_done = B_FALSE;
7354 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7355 
7356 	tcp->tcp_mdt = B_FALSE;
7357 	tcp->tcp_mdt_hdr_head = 0;
7358 	tcp->tcp_mdt_hdr_tail = 0;
7359 
7360 	tcp->tcp_conn_def_q0 = 0;
7361 	tcp->tcp_ip_forward_progress = B_FALSE;
7362 	tcp->tcp_anon_priv_bind = 0;
7363 	tcp->tcp_ecn_ok = B_FALSE;
7364 
7365 	tcp->tcp_cwr = B_FALSE;
7366 	tcp->tcp_ecn_echo_on = B_FALSE;
7367 
7368 	if (tcp->tcp_sack_info != NULL) {
7369 		if (tcp->tcp_notsack_list != NULL) {
7370 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7371 		}
7372 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7373 		tcp->tcp_sack_info = NULL;
7374 	}
7375 
7376 	tcp->tcp_rcv_ws = 0;
7377 	tcp->tcp_snd_ws = 0;
7378 	tcp->tcp_ts_recent = 0;
7379 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7380 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7381 	tcp->tcp_if_mtu = 0;
7382 
7383 	ASSERT(tcp->tcp_reass_head == NULL);
7384 	ASSERT(tcp->tcp_reass_tail == NULL);
7385 
7386 	tcp->tcp_cwnd_cnt = 0;
7387 
7388 	ASSERT(tcp->tcp_rcv_list == NULL);
7389 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7390 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7391 	ASSERT(tcp->tcp_rcv_cnt == 0);
7392 
7393 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7394 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7395 	tcp->tcp_csuna = 0;
7396 
7397 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7398 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7399 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7400 	tcp->tcp_rtt_update = 0;
7401 
7402 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7403 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7404 
7405 	tcp->tcp_rack = 0;			/* Displayed in mib */
7406 	tcp->tcp_rack_cnt = 0;
7407 	tcp->tcp_rack_cur_max = 0;
7408 	tcp->tcp_rack_abs_max = 0;
7409 
7410 	tcp->tcp_max_swnd = 0;
7411 
7412 	ASSERT(tcp->tcp_listener == NULL);
7413 
7414 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7415 
7416 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7417 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7418 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7419 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7420 
7421 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7422 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7423 	PRESERVE(tcp->tcp_conn_req_max);
7424 	PRESERVE(tcp->tcp_conn_req_seqnum);
7425 
7426 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7427 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7428 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7429 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7430 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7431 
7432 	tcp->tcp_lingertime = 0;
7433 
7434 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7435 	ASSERT(tcp->tcp_urp_mp == NULL);
7436 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7437 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7438 
7439 	ASSERT(tcp->tcp_eager_next_q == NULL);
7440 	ASSERT(tcp->tcp_eager_last_q == NULL);
7441 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7442 	    tcp->tcp_eager_prev_q0 == NULL) ||
7443 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7444 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7445 
7446 	tcp->tcp_client_errno = 0;
7447 
7448 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7449 
7450 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7451 
7452 	PRESERVE(tcp->tcp_bound_source_v6);
7453 	tcp->tcp_last_sent_len = 0;
7454 	tcp->tcp_dupack_cnt = 0;
7455 
7456 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7457 	PRESERVE(tcp->tcp_lport);
7458 
7459 	PRESERVE(tcp->tcp_acceptor_lockp);
7460 
7461 	ASSERT(tcp->tcp_ordrelid == 0);
7462 	PRESERVE(tcp->tcp_acceptor_id);
7463 	DONTCARE(tcp->tcp_ipsec_overhead);
7464 
7465 	/*
7466 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
7467 	 * in tcp structure and now tracing), Re-initialize all
7468 	 * members of tcp_traceinfo.
7469 	 */
7470 	if (tcp->tcp_tracebuf != NULL) {
7471 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
7472 	}
7473 
7474 	PRESERVE(tcp->tcp_family);
7475 	if (tcp->tcp_family == AF_INET6) {
7476 		tcp->tcp_ipversion = IPV6_VERSION;
7477 		tcp->tcp_mss = tcp_mss_def_ipv6;
7478 	} else {
7479 		tcp->tcp_ipversion = IPV4_VERSION;
7480 		tcp->tcp_mss = tcp_mss_def_ipv4;
7481 	}
7482 
7483 	tcp->tcp_bound_if = 0;
7484 	tcp->tcp_ipv6_recvancillary = 0;
7485 	tcp->tcp_recvifindex = 0;
7486 	tcp->tcp_recvhops = 0;
7487 	tcp->tcp_closed = 0;
7488 	tcp->tcp_cleandeathtag = 0;
7489 	if (tcp->tcp_hopopts != NULL) {
7490 		mi_free(tcp->tcp_hopopts);
7491 		tcp->tcp_hopopts = NULL;
7492 		tcp->tcp_hopoptslen = 0;
7493 	}
7494 	ASSERT(tcp->tcp_hopoptslen == 0);
7495 	if (tcp->tcp_dstopts != NULL) {
7496 		mi_free(tcp->tcp_dstopts);
7497 		tcp->tcp_dstopts = NULL;
7498 		tcp->tcp_dstoptslen = 0;
7499 	}
7500 	ASSERT(tcp->tcp_dstoptslen == 0);
7501 	if (tcp->tcp_rtdstopts != NULL) {
7502 		mi_free(tcp->tcp_rtdstopts);
7503 		tcp->tcp_rtdstopts = NULL;
7504 		tcp->tcp_rtdstoptslen = 0;
7505 	}
7506 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7507 	if (tcp->tcp_rthdr != NULL) {
7508 		mi_free(tcp->tcp_rthdr);
7509 		tcp->tcp_rthdr = NULL;
7510 		tcp->tcp_rthdrlen = 0;
7511 	}
7512 	ASSERT(tcp->tcp_rthdrlen == 0);
7513 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7514 
7515 	/* Reset fusion-related fields */
7516 	tcp->tcp_fused = B_FALSE;
7517 	tcp->tcp_unfusable = B_FALSE;
7518 	tcp->tcp_fused_sigurg = B_FALSE;
7519 	tcp->tcp_direct_sockfs = B_FALSE;
7520 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7521 	tcp->tcp_loopback_peer = NULL;
7522 	tcp->tcp_fuse_rcv_hiwater = 0;
7523 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7524 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7525 
7526 	tcp->tcp_in_ack_unsent = 0;
7527 	tcp->tcp_cork = B_FALSE;
7528 
7529 	PRESERVE(tcp->tcp_squeue_bytes);
7530 
7531 #undef	DONTCARE
7532 #undef	PRESERVE
7533 }
7534 
7535 /*
7536  * Allocate necessary resources and initialize state vector.
7537  * Guaranteed not to fail so that when an error is returned,
7538  * the caller doesn't need to do any additional cleanup.
7539  */
7540 int
7541 tcp_init(tcp_t *tcp, queue_t *q)
7542 {
7543 	int	err;
7544 
7545 	tcp->tcp_rq = q;
7546 	tcp->tcp_wq = WR(q);
7547 	tcp->tcp_state = TCPS_IDLE;
7548 	if ((err = tcp_init_values(tcp)) != 0)
7549 		tcp_timers_stop(tcp);
7550 	return (err);
7551 }
7552 
7553 static int
7554 tcp_init_values(tcp_t *tcp)
7555 {
7556 	int	err;
7557 
7558 	ASSERT((tcp->tcp_family == AF_INET &&
7559 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7560 	    (tcp->tcp_family == AF_INET6 &&
7561 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7562 	    tcp->tcp_ipversion == IPV6_VERSION)));
7563 
7564 	/*
7565 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7566 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7567 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7568 	 * during first few transmissions of a connection as seen in slow
7569 	 * links.
7570 	 */
7571 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
7572 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
7573 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7574 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7575 	    tcp_conn_grace_period;
7576 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
7577 		tcp->tcp_rto = tcp_rexmit_interval_min;
7578 	tcp->tcp_timer_backoff = 0;
7579 	tcp->tcp_ms_we_have_waited = 0;
7580 	tcp->tcp_last_recv_time = lbolt;
7581 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
7582 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7583 
7584 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
7585 
7586 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
7587 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
7588 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
7589 	/*
7590 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7591 	 * passive open.
7592 	 */
7593 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
7594 
7595 	tcp->tcp_naglim = tcp_naglim_def;
7596 
7597 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7598 
7599 	tcp->tcp_mdt_hdr_head = 0;
7600 	tcp->tcp_mdt_hdr_tail = 0;
7601 
7602 	/* Reset fusion-related fields */
7603 	tcp->tcp_fused = B_FALSE;
7604 	tcp->tcp_unfusable = B_FALSE;
7605 	tcp->tcp_fused_sigurg = B_FALSE;
7606 	tcp->tcp_direct_sockfs = B_FALSE;
7607 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7608 	tcp->tcp_loopback_peer = NULL;
7609 	tcp->tcp_fuse_rcv_hiwater = 0;
7610 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7611 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7612 
7613 	/* Initialize the header template */
7614 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7615 		err = tcp_header_init_ipv4(tcp);
7616 	} else {
7617 		err = tcp_header_init_ipv6(tcp);
7618 	}
7619 	if (err)
7620 		return (err);
7621 
7622 	/*
7623 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7624 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7625 	 */
7626 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7627 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
7628 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
7629 
7630 	tcp->tcp_cork = B_FALSE;
7631 	/*
7632 	 * Init the tcp_debug option.  This value determines whether TCP
7633 	 * calls strlog() to print out debug messages.  Doing this
7634 	 * initialization here means that this value is not inherited thru
7635 	 * tcp_reinit().
7636 	 */
7637 	tcp->tcp_debug = tcp_dbg;
7638 
7639 	tcp->tcp_ka_interval = tcp_keepalive_interval;
7640 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
7641 
7642 	return (0);
7643 }
7644 
7645 /*
7646  * Initialize the IPv4 header. Loses any record of any IP options.
7647  */
7648 static int
7649 tcp_header_init_ipv4(tcp_t *tcp)
7650 {
7651 	tcph_t		*tcph;
7652 	uint32_t	sum;
7653 
7654 	/*
7655 	 * This is a simple initialization. If there's
7656 	 * already a template, it should never be too small,
7657 	 * so reuse it.  Otherwise, allocate space for the new one.
7658 	 */
7659 	if (tcp->tcp_iphc == NULL) {
7660 		ASSERT(tcp->tcp_iphc_len == 0);
7661 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7662 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7663 		if (tcp->tcp_iphc == NULL) {
7664 			tcp->tcp_iphc_len = 0;
7665 			return (ENOMEM);
7666 		}
7667 	}
7668 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7669 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
7670 	tcp->tcp_ip6h = NULL;
7671 	tcp->tcp_ipversion = IPV4_VERSION;
7672 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
7673 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
7674 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
7675 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
7676 	tcp->tcp_ipha->ipha_version_and_hdr_length
7677 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
7678 	tcp->tcp_ipha->ipha_ident = 0;
7679 
7680 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
7681 	tcp->tcp_tos = 0;
7682 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
7683 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
7684 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
7685 
7686 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
7687 	tcp->tcp_tcph = tcph;
7688 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
7689 	/*
7690 	 * IP wants our header length in the checksum field to
7691 	 * allow it to perform a single pseudo-header+checksum
7692 	 * calculation on behalf of TCP.
7693 	 * Include the adjustment for a source route once IP_OPTIONS is set.
7694 	 */
7695 	sum = sizeof (tcph_t) + tcp->tcp_sum;
7696 	sum = (sum >> 16) + (sum & 0xFFFF);
7697 	U16_TO_ABE16(sum, tcph->th_sum);
7698 	return (0);
7699 }
7700 
7701 /*
7702  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
7703  */
7704 static int
7705 tcp_header_init_ipv6(tcp_t *tcp)
7706 {
7707 	tcph_t	*tcph;
7708 	uint32_t	sum;
7709 
7710 	/*
7711 	 * This is a simple initialization. If there's
7712 	 * already a template, it should never be too small,
7713 	 * so reuse it. Otherwise, allocate space for the new one.
7714 	 * Ensure that there is enough space to "downgrade" the tcp_t
7715 	 * to an IPv4 tcp_t. This requires having space for a full load
7716 	 * of IPv4 options, as well as a full load of TCP options
7717 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
7718 	 * than a v6 header and a TCP header with a full load of TCP options
7719 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
7720 	 * We want to avoid reallocation in the "downgraded" case when
7721 	 * processing outbound IPv4 options.
7722 	 */
7723 	if (tcp->tcp_iphc == NULL) {
7724 		ASSERT(tcp->tcp_iphc_len == 0);
7725 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7726 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7727 		if (tcp->tcp_iphc == NULL) {
7728 			tcp->tcp_iphc_len = 0;
7729 			return (ENOMEM);
7730 		}
7731 	}
7732 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7733 	tcp->tcp_ipversion = IPV6_VERSION;
7734 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
7735 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
7736 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
7737 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
7738 	tcp->tcp_ipha = NULL;
7739 
7740 	/* Initialize the header template */
7741 
7742 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
7743 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
7744 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
7745 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
7746 
7747 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
7748 	tcp->tcp_tcph = tcph;
7749 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
7750 	/*
7751 	 * IP wants our header length in the checksum field to
7752 	 * allow it to perform a single psuedo-header+checksum
7753 	 * calculation on behalf of TCP.
7754 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
7755 	 */
7756 	sum = sizeof (tcph_t) + tcp->tcp_sum;
7757 	sum = (sum >> 16) + (sum & 0xFFFF);
7758 	U16_TO_ABE16(sum, tcph->th_sum);
7759 	return (0);
7760 }
7761 
7762 /* At minimum we need 4 bytes in the TCP header for the lookup */
7763 #define	ICMP_MIN_TCP_HDR	4
7764 
7765 /*
7766  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
7767  * passed up by IP. The message is always received on the correct tcp_t.
7768  * Assumes that IP has pulled up everything up to and including the ICMP header.
7769  */
7770 void
7771 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
7772 {
7773 	icmph_t *icmph;
7774 	ipha_t	*ipha;
7775 	int	iph_hdr_length;
7776 	tcph_t	*tcph;
7777 	boolean_t ipsec_mctl = B_FALSE;
7778 	boolean_t secure;
7779 	mblk_t *first_mp = mp;
7780 	uint32_t new_mss;
7781 	uint32_t ratio;
7782 	size_t mp_size = MBLKL(mp);
7783 	uint32_t seg_ack;
7784 	uint32_t seg_seq;
7785 
7786 	/* Assume IP provides aligned packets - otherwise toss */
7787 	if (!OK_32PTR(mp->b_rptr)) {
7788 		freemsg(mp);
7789 		return;
7790 	}
7791 
7792 	/*
7793 	 * Since ICMP errors are normal data marked with M_CTL when sent
7794 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
7795 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
7796 	 */
7797 	if ((mp_size == sizeof (ipsec_info_t)) &&
7798 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
7799 		ASSERT(mp->b_cont != NULL);
7800 		mp = mp->b_cont;
7801 		/* IP should have done this */
7802 		ASSERT(OK_32PTR(mp->b_rptr));
7803 		mp_size = MBLKL(mp);
7804 		ipsec_mctl = B_TRUE;
7805 	}
7806 
7807 	/*
7808 	 * Verify that we have a complete outer IP header. If not, drop it.
7809 	 */
7810 	if (mp_size < sizeof (ipha_t)) {
7811 noticmpv4:
7812 		freemsg(first_mp);
7813 		return;
7814 	}
7815 
7816 	ipha = (ipha_t *)mp->b_rptr;
7817 	/*
7818 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
7819 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
7820 	 */
7821 	switch (IPH_HDR_VERSION(ipha)) {
7822 	case IPV6_VERSION:
7823 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
7824 		return;
7825 	case IPV4_VERSION:
7826 		break;
7827 	default:
7828 		goto noticmpv4;
7829 	}
7830 
7831 	/* Skip past the outer IP and ICMP headers */
7832 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7833 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
7834 	/*
7835 	 * If we don't have the correct outer IP header length or if the ULP
7836 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
7837 	 * send it upstream.
7838 	 */
7839 	if (iph_hdr_length < sizeof (ipha_t) ||
7840 	    ipha->ipha_protocol != IPPROTO_ICMP ||
7841 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
7842 		goto noticmpv4;
7843 	}
7844 	ipha = (ipha_t *)&icmph[1];
7845 
7846 	/* Skip past the inner IP and find the ULP header */
7847 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7848 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
7849 	/*
7850 	 * If we don't have the correct inner IP header length or if the ULP
7851 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
7852 	 * bytes of TCP header, drop it.
7853 	 */
7854 	if (iph_hdr_length < sizeof (ipha_t) ||
7855 	    ipha->ipha_protocol != IPPROTO_TCP ||
7856 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
7857 		goto noticmpv4;
7858 	}
7859 
7860 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
7861 		if (ipsec_mctl) {
7862 			secure = ipsec_in_is_secure(first_mp);
7863 		} else {
7864 			secure = B_FALSE;
7865 		}
7866 		if (secure) {
7867 			/*
7868 			 * If we are willing to accept this in clear
7869 			 * we don't have to verify policy.
7870 			 */
7871 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
7872 				if (!tcp_check_policy(tcp, first_mp,
7873 				    ipha, NULL, secure, ipsec_mctl)) {
7874 					/*
7875 					 * tcp_check_policy called
7876 					 * ip_drop_packet() on failure.
7877 					 */
7878 					return;
7879 				}
7880 			}
7881 		}
7882 	} else if (ipsec_mctl) {
7883 		/*
7884 		 * This is a hard_bound connection. IP has already
7885 		 * verified policy. We don't have to do it again.
7886 		 */
7887 		freeb(first_mp);
7888 		first_mp = mp;
7889 		ipsec_mctl = B_FALSE;
7890 	}
7891 
7892 	seg_ack = ABE32_TO_U32(tcph->th_ack);
7893 	seg_seq = ABE32_TO_U32(tcph->th_seq);
7894 	/*
7895 	 * TCP SHOULD check that the TCP sequence number contained in
7896 	 * payload of the ICMP error message is within the range
7897 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
7898 	 */
7899 	if (SEQ_LT(seg_seq, tcp->tcp_suna) ||
7900 		SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
7901 		SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
7902 		/*
7903 		 * If the ICMP message is bogus, should we kill the
7904 		 * connection, or should we just drop the bogus ICMP
7905 		 * message? It would probably make more sense to just
7906 		 * drop the message so that if this one managed to get
7907 		 * in, the real connection should not suffer.
7908 		 */
7909 		goto noticmpv4;
7910 	}
7911 
7912 	switch (icmph->icmph_type) {
7913 	case ICMP_DEST_UNREACHABLE:
7914 		switch (icmph->icmph_code) {
7915 		case ICMP_FRAGMENTATION_NEEDED:
7916 			/*
7917 			 * Reduce the MSS based on the new MTU.  This will
7918 			 * eliminate any fragmentation locally.
7919 			 * N.B.  There may well be some funny side-effects on
7920 			 * the local send policy and the remote receive policy.
7921 			 * Pending further research, we provide
7922 			 * tcp_ignore_path_mtu just in case this proves
7923 			 * disastrous somewhere.
7924 			 *
7925 			 * After updating the MSS, retransmit part of the
7926 			 * dropped segment using the new mss by calling
7927 			 * tcp_wput_data().  Need to adjust all those
7928 			 * params to make sure tcp_wput_data() work properly.
7929 			 */
7930 			if (tcp_ignore_path_mtu)
7931 				break;
7932 
7933 			/*
7934 			 * Decrease the MSS by time stamp options
7935 			 * IP options and IPSEC options. tcp_hdr_len
7936 			 * includes time stamp option and IP option
7937 			 * length.
7938 			 */
7939 
7940 			new_mss = ntohs(icmph->icmph_du_mtu) -
7941 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
7942 
7943 			/*
7944 			 * Only update the MSS if the new one is
7945 			 * smaller than the previous one.  This is
7946 			 * to avoid problems when getting multiple
7947 			 * ICMP errors for the same MTU.
7948 			 */
7949 			if (new_mss >= tcp->tcp_mss)
7950 				break;
7951 
7952 			/*
7953 			 * Stop doing PMTU if new_mss is less than 68
7954 			 * or less than tcp_mss_min.
7955 			 * The value 68 comes from rfc 1191.
7956 			 */
7957 			if (new_mss < MAX(68, tcp_mss_min))
7958 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
7959 				    0;
7960 
7961 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
7962 			ASSERT(ratio >= 1);
7963 			tcp_mss_set(tcp, new_mss);
7964 
7965 			/*
7966 			 * Make sure we have something to
7967 			 * send.
7968 			 */
7969 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
7970 			    (tcp->tcp_xmit_head != NULL)) {
7971 				/*
7972 				 * Shrink tcp_cwnd in
7973 				 * proportion to the old MSS/new MSS.
7974 				 */
7975 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
7976 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
7977 				    (tcp->tcp_unsent == 0)) {
7978 					tcp->tcp_rexmit_max = tcp->tcp_fss;
7979 				} else {
7980 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
7981 				}
7982 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
7983 				tcp->tcp_rexmit = B_TRUE;
7984 				tcp->tcp_dupack_cnt = 0;
7985 				tcp->tcp_snd_burst = TCP_CWND_SS;
7986 				tcp_ss_rexmit(tcp);
7987 			}
7988 			break;
7989 		case ICMP_PORT_UNREACHABLE:
7990 		case ICMP_PROTOCOL_UNREACHABLE:
7991 			switch (tcp->tcp_state) {
7992 			case TCPS_SYN_SENT:
7993 			case TCPS_SYN_RCVD:
7994 				/*
7995 				 * ICMP can snipe away incipient
7996 				 * TCP connections as long as
7997 				 * seq number is same as initial
7998 				 * send seq number.
7999 				 */
8000 				if (seg_seq == tcp->tcp_iss) {
8001 					(void) tcp_clean_death(tcp,
8002 					    ECONNREFUSED, 6);
8003 				}
8004 				break;
8005 			}
8006 			break;
8007 		case ICMP_HOST_UNREACHABLE:
8008 		case ICMP_NET_UNREACHABLE:
8009 			/* Record the error in case we finally time out. */
8010 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8011 				tcp->tcp_client_errno = EHOSTUNREACH;
8012 			else
8013 				tcp->tcp_client_errno = ENETUNREACH;
8014 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8015 				if (tcp->tcp_listener != NULL &&
8016 				    tcp->tcp_listener->tcp_syn_defense) {
8017 					/*
8018 					 * Ditch the half-open connection if we
8019 					 * suspect a SYN attack is under way.
8020 					 */
8021 					tcp_ip_ire_mark_advice(tcp);
8022 					(void) tcp_clean_death(tcp,
8023 					    tcp->tcp_client_errno, 7);
8024 				}
8025 			}
8026 			break;
8027 		default:
8028 			break;
8029 		}
8030 		break;
8031 	case ICMP_SOURCE_QUENCH: {
8032 		/*
8033 		 * use a global boolean to control
8034 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8035 		 * The default is false.
8036 		 */
8037 		if (tcp_icmp_source_quench) {
8038 			/*
8039 			 * Reduce the sending rate as if we got a
8040 			 * retransmit timeout
8041 			 */
8042 			uint32_t npkt;
8043 
8044 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8045 			    tcp->tcp_mss;
8046 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8047 			tcp->tcp_cwnd = tcp->tcp_mss;
8048 			tcp->tcp_cwnd_cnt = 0;
8049 		}
8050 		break;
8051 	}
8052 	}
8053 	freemsg(first_mp);
8054 }
8055 
8056 /*
8057  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8058  * error messages passed up by IP.
8059  * Assumes that IP has pulled up all the extension headers as well
8060  * as the ICMPv6 header.
8061  */
8062 static void
8063 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8064 {
8065 	icmp6_t *icmp6;
8066 	ip6_t	*ip6h;
8067 	uint16_t	iph_hdr_length;
8068 	tcpha_t	*tcpha;
8069 	uint8_t	*nexthdrp;
8070 	uint32_t new_mss;
8071 	uint32_t ratio;
8072 	boolean_t secure;
8073 	mblk_t *first_mp = mp;
8074 	size_t mp_size;
8075 	uint32_t seg_ack;
8076 	uint32_t seg_seq;
8077 
8078 	/*
8079 	 * The caller has determined if this is an IPSEC_IN packet and
8080 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8081 	 */
8082 	if (ipsec_mctl)
8083 		mp = mp->b_cont;
8084 
8085 	mp_size = MBLKL(mp);
8086 
8087 	/*
8088 	 * Verify that we have a complete IP header. If not, send it upstream.
8089 	 */
8090 	if (mp_size < sizeof (ip6_t)) {
8091 noticmpv6:
8092 		freemsg(first_mp);
8093 		return;
8094 	}
8095 
8096 	/*
8097 	 * Verify this is an ICMPV6 packet, else send it upstream.
8098 	 */
8099 	ip6h = (ip6_t *)mp->b_rptr;
8100 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8101 		iph_hdr_length = IPV6_HDR_LEN;
8102 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8103 	    &nexthdrp) ||
8104 	    *nexthdrp != IPPROTO_ICMPV6) {
8105 		goto noticmpv6;
8106 	}
8107 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8108 	ip6h = (ip6_t *)&icmp6[1];
8109 	/*
8110 	 * Verify if we have a complete ICMP and inner IP header.
8111 	 */
8112 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8113 		goto noticmpv6;
8114 
8115 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8116 		goto noticmpv6;
8117 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8118 	/*
8119 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8120 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8121 	 * packet.
8122 	 */
8123 	if ((*nexthdrp != IPPROTO_TCP) ||
8124 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8125 		goto noticmpv6;
8126 	}
8127 
8128 	/*
8129 	 * ICMP errors come on the right queue or come on
8130 	 * listener/global queue for detached connections and
8131 	 * get switched to the right queue. If it comes on the
8132 	 * right queue, policy check has already been done by IP
8133 	 * and thus free the first_mp without verifying the policy.
8134 	 * If it has come for a non-hard bound connection, we need
8135 	 * to verify policy as IP may not have done it.
8136 	 */
8137 	if (!tcp->tcp_hard_bound) {
8138 		if (ipsec_mctl) {
8139 			secure = ipsec_in_is_secure(first_mp);
8140 		} else {
8141 			secure = B_FALSE;
8142 		}
8143 		if (secure) {
8144 			/*
8145 			 * If we are willing to accept this in clear
8146 			 * we don't have to verify policy.
8147 			 */
8148 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8149 				if (!tcp_check_policy(tcp, first_mp,
8150 				    NULL, ip6h, secure, ipsec_mctl)) {
8151 					/*
8152 					 * tcp_check_policy called
8153 					 * ip_drop_packet() on failure.
8154 					 */
8155 					return;
8156 				}
8157 			}
8158 		}
8159 	} else if (ipsec_mctl) {
8160 		/*
8161 		 * This is a hard_bound connection. IP has already
8162 		 * verified policy. We don't have to do it again.
8163 		 */
8164 		freeb(first_mp);
8165 		first_mp = mp;
8166 		ipsec_mctl = B_FALSE;
8167 	}
8168 
8169 	seg_ack = ntohl(tcpha->tha_ack);
8170 	seg_seq = ntohl(tcpha->tha_seq);
8171 	/*
8172 	 * TCP SHOULD check that the TCP sequence number contained in
8173 	 * payload of the ICMP error message is within the range
8174 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8175 	 */
8176 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8177 	    SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8178 		/*
8179 		 * If the ICMP message is bogus, should we kill the
8180 		 * connection, or should we just drop the bogus ICMP
8181 		 * message? It would probably make more sense to just
8182 		 * drop the message so that if this one managed to get
8183 		 * in, the real connection should not suffer.
8184 		 */
8185 		goto noticmpv6;
8186 	}
8187 
8188 	switch (icmp6->icmp6_type) {
8189 	case ICMP6_PACKET_TOO_BIG:
8190 		/*
8191 		 * Reduce the MSS based on the new MTU.  This will
8192 		 * eliminate any fragmentation locally.
8193 		 * N.B.  There may well be some funny side-effects on
8194 		 * the local send policy and the remote receive policy.
8195 		 * Pending further research, we provide
8196 		 * tcp_ignore_path_mtu just in case this proves
8197 		 * disastrous somewhere.
8198 		 *
8199 		 * After updating the MSS, retransmit part of the
8200 		 * dropped segment using the new mss by calling
8201 		 * tcp_wput_data().  Need to adjust all those
8202 		 * params to make sure tcp_wput_data() work properly.
8203 		 */
8204 		if (tcp_ignore_path_mtu)
8205 			break;
8206 
8207 		/*
8208 		 * Decrease the MSS by time stamp options
8209 		 * IP options and IPSEC options. tcp_hdr_len
8210 		 * includes time stamp option and IP option
8211 		 * length.
8212 		 */
8213 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8214 			    tcp->tcp_ipsec_overhead;
8215 
8216 		/*
8217 		 * Only update the MSS if the new one is
8218 		 * smaller than the previous one.  This is
8219 		 * to avoid problems when getting multiple
8220 		 * ICMP errors for the same MTU.
8221 		 */
8222 		if (new_mss >= tcp->tcp_mss)
8223 			break;
8224 
8225 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8226 		ASSERT(ratio >= 1);
8227 		tcp_mss_set(tcp, new_mss);
8228 
8229 		/*
8230 		 * Make sure we have something to
8231 		 * send.
8232 		 */
8233 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8234 		    (tcp->tcp_xmit_head != NULL)) {
8235 			/*
8236 			 * Shrink tcp_cwnd in
8237 			 * proportion to the old MSS/new MSS.
8238 			 */
8239 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8240 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8241 			    (tcp->tcp_unsent == 0)) {
8242 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8243 			} else {
8244 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8245 			}
8246 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8247 			tcp->tcp_rexmit = B_TRUE;
8248 			tcp->tcp_dupack_cnt = 0;
8249 			tcp->tcp_snd_burst = TCP_CWND_SS;
8250 			tcp_ss_rexmit(tcp);
8251 		}
8252 		break;
8253 
8254 	case ICMP6_DST_UNREACH:
8255 		switch (icmp6->icmp6_code) {
8256 		case ICMP6_DST_UNREACH_NOPORT:
8257 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8258 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8259 			    (tcpha->tha_seq == tcp->tcp_iss)) {
8260 				(void) tcp_clean_death(tcp,
8261 				    ECONNREFUSED, 8);
8262 			}
8263 			break;
8264 
8265 		case ICMP6_DST_UNREACH_ADMIN:
8266 		case ICMP6_DST_UNREACH_NOROUTE:
8267 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8268 		case ICMP6_DST_UNREACH_ADDR:
8269 			/* Record the error in case we finally time out. */
8270 			tcp->tcp_client_errno = EHOSTUNREACH;
8271 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8272 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8273 			    (tcpha->tha_seq == tcp->tcp_iss)) {
8274 				if (tcp->tcp_listener != NULL &&
8275 				    tcp->tcp_listener->tcp_syn_defense) {
8276 					/*
8277 					 * Ditch the half-open connection if we
8278 					 * suspect a SYN attack is under way.
8279 					 */
8280 					tcp_ip_ire_mark_advice(tcp);
8281 					(void) tcp_clean_death(tcp,
8282 					    tcp->tcp_client_errno, 9);
8283 				}
8284 			}
8285 
8286 
8287 			break;
8288 		default:
8289 			break;
8290 		}
8291 		break;
8292 
8293 	case ICMP6_PARAM_PROB:
8294 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8295 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8296 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8297 		    (uchar_t *)nexthdrp) {
8298 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8299 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8300 				(void) tcp_clean_death(tcp,
8301 				    ECONNREFUSED, 10);
8302 			}
8303 			break;
8304 		}
8305 		break;
8306 
8307 	case ICMP6_TIME_EXCEEDED:
8308 	default:
8309 		break;
8310 	}
8311 	freemsg(first_mp);
8312 }
8313 
8314 /*
8315  * IP recognizes seven kinds of bind requests:
8316  *
8317  * - A zero-length address binds only to the protocol number.
8318  *
8319  * - A 4-byte address is treated as a request to
8320  * validate that the address is a valid local IPv4
8321  * address, appropriate for an application to bind to.
8322  * IP does the verification, but does not make any note
8323  * of the address at this time.
8324  *
8325  * - A 16-byte address contains is treated as a request
8326  * to validate a local IPv6 address, as the 4-byte
8327  * address case above.
8328  *
8329  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8330  * use it for the inbound fanout of packets.
8331  *
8332  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8333  * use it for the inbound fanout of packets.
8334  *
8335  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8336  * information consisting of local and remote addresses
8337  * and ports.  In this case, the addresses are both
8338  * validated as appropriate for this operation, and, if
8339  * so, the information is retained for use in the
8340  * inbound fanout.
8341  *
8342  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8343  * fanout information, like the 12-byte case above.
8344  *
8345  * IP will also fill in the IRE request mblk with information
8346  * regarding our peer.  In all cases, we notify IP of our protocol
8347  * type by appending a single protocol byte to the bind request.
8348  */
8349 static mblk_t *
8350 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8351 {
8352 	char	*cp;
8353 	mblk_t	*mp;
8354 	struct T_bind_req *tbr;
8355 	ipa_conn_t	*ac;
8356 	ipa6_conn_t	*ac6;
8357 	sin_t		*sin;
8358 	sin6_t		*sin6;
8359 
8360 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
8361 	ASSERT((tcp->tcp_family == AF_INET &&
8362 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8363 	    (tcp->tcp_family == AF_INET6 &&
8364 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8365 	    tcp->tcp_ipversion == IPV6_VERSION)));
8366 
8367 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
8368 	if (!mp)
8369 		return (mp);
8370 	mp->b_datap->db_type = M_PROTO;
8371 	tbr = (struct T_bind_req *)mp->b_rptr;
8372 	tbr->PRIM_type = bind_prim;
8373 	tbr->ADDR_offset = sizeof (*tbr);
8374 	tbr->CONIND_number = 0;
8375 	tbr->ADDR_length = addr_length;
8376 	cp = (char *)&tbr[1];
8377 	switch (addr_length) {
8378 	case sizeof (ipa_conn_t):
8379 		ASSERT(tcp->tcp_family == AF_INET);
8380 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8381 
8382 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8383 		if (mp->b_cont == NULL) {
8384 			freemsg(mp);
8385 			return (NULL);
8386 		}
8387 		mp->b_cont->b_wptr += sizeof (ire_t);
8388 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8389 
8390 		/* cp known to be 32 bit aligned */
8391 		ac = (ipa_conn_t *)cp;
8392 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
8393 		ac->ac_faddr = tcp->tcp_remote;
8394 		ac->ac_fport = tcp->tcp_fport;
8395 		ac->ac_lport = tcp->tcp_lport;
8396 		tcp->tcp_hard_binding = 1;
8397 		break;
8398 
8399 	case sizeof (ipa6_conn_t):
8400 		ASSERT(tcp->tcp_family == AF_INET6);
8401 
8402 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8403 		if (mp->b_cont == NULL) {
8404 			freemsg(mp);
8405 			return (NULL);
8406 		}
8407 		mp->b_cont->b_wptr += sizeof (ire_t);
8408 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8409 
8410 		/* cp known to be 32 bit aligned */
8411 		ac6 = (ipa6_conn_t *)cp;
8412 		if (tcp->tcp_ipversion == IPV4_VERSION) {
8413 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
8414 			    &ac6->ac6_laddr);
8415 		} else {
8416 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
8417 		}
8418 		ac6->ac6_faddr = tcp->tcp_remote_v6;
8419 		ac6->ac6_fport = tcp->tcp_fport;
8420 		ac6->ac6_lport = tcp->tcp_lport;
8421 		tcp->tcp_hard_binding = 1;
8422 		break;
8423 
8424 	case sizeof (sin_t):
8425 		/*
8426 		 * NOTE: IPV6_ADDR_LEN also has same size.
8427 		 * Use family to discriminate.
8428 		 */
8429 		if (tcp->tcp_family == AF_INET) {
8430 			sin = (sin_t *)cp;
8431 
8432 			*sin = sin_null;
8433 			sin->sin_family = AF_INET;
8434 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
8435 			sin->sin_port = tcp->tcp_lport;
8436 			break;
8437 		} else {
8438 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
8439 		}
8440 		break;
8441 
8442 	case sizeof (sin6_t):
8443 		ASSERT(tcp->tcp_family == AF_INET6);
8444 		sin6 = (sin6_t *)cp;
8445 
8446 		*sin6 = sin6_null;
8447 		sin6->sin6_family = AF_INET6;
8448 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
8449 		sin6->sin6_port = tcp->tcp_lport;
8450 		break;
8451 
8452 	case IP_ADDR_LEN:
8453 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8454 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
8455 		break;
8456 
8457 	}
8458 	/* Add protocol number to end */
8459 	cp[addr_length] = (char)IPPROTO_TCP;
8460 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
8461 	return (mp);
8462 }
8463 
8464 /*
8465  * Notify IP that we are having trouble with this connection.  IP should
8466  * blow the IRE away and start over.
8467  */
8468 static void
8469 tcp_ip_notify(tcp_t *tcp)
8470 {
8471 	struct iocblk	*iocp;
8472 	ipid_t	*ipid;
8473 	mblk_t	*mp;
8474 
8475 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8476 	if (tcp->tcp_ipversion == IPV6_VERSION)
8477 		return;
8478 
8479 	mp = mkiocb(IP_IOCTL);
8480 	if (mp == NULL)
8481 		return;
8482 
8483 	iocp = (struct iocblk *)mp->b_rptr;
8484 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8485 
8486 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8487 	if (!mp->b_cont) {
8488 		freeb(mp);
8489 		return;
8490 	}
8491 
8492 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8493 	mp->b_cont->b_wptr += iocp->ioc_count;
8494 	bzero(ipid, sizeof (*ipid));
8495 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8496 	ipid->ipid_ire_type = IRE_CACHE;
8497 	ipid->ipid_addr_offset = sizeof (ipid_t);
8498 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8499 	/*
8500 	 * Note: in the case of source routing we want to blow away the
8501 	 * route to the first source route hop.
8502 	 */
8503 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8504 	    sizeof (tcp->tcp_ipha->ipha_dst));
8505 
8506 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8507 }
8508 
8509 /* Unlink and return any mblk that looks like it contains an ire */
8510 static mblk_t *
8511 tcp_ire_mp(mblk_t *mp)
8512 {
8513 	mblk_t	*prev_mp;
8514 
8515 	for (;;) {
8516 		prev_mp = mp;
8517 		mp = mp->b_cont;
8518 		if (mp == NULL)
8519 			break;
8520 		switch (DB_TYPE(mp)) {
8521 		case IRE_DB_TYPE:
8522 		case IRE_DB_REQ_TYPE:
8523 			if (prev_mp != NULL)
8524 				prev_mp->b_cont = mp->b_cont;
8525 			mp->b_cont = NULL;
8526 			return (mp);
8527 		default:
8528 			break;
8529 		}
8530 	}
8531 	return (mp);
8532 }
8533 
8534 /*
8535  * Timer callback routine for keepalive probe.  We do a fake resend of
8536  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8537  * check to see if we have heard anything from the other end for the last
8538  * RTO period.  If we have, set the timer to expire for another
8539  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8540  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8541  * the timeout if we have not heard from the other side.  If for more than
8542  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8543  * kill the connection unless the keepalive abort threshold is 0.  In
8544  * that case, we will probe "forever."
8545  */
8546 static void
8547 tcp_keepalive_killer(void *arg)
8548 {
8549 	mblk_t	*mp;
8550 	conn_t	*connp = (conn_t *)arg;
8551 	tcp_t  	*tcp = connp->conn_tcp;
8552 	int32_t	firetime;
8553 	int32_t	idletime;
8554 	int32_t	ka_intrvl;
8555 
8556 	tcp->tcp_ka_tid = 0;
8557 
8558 	if (tcp->tcp_fused)
8559 		return;
8560 
8561 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
8562 	ka_intrvl = tcp->tcp_ka_interval;
8563 
8564 	/*
8565 	 * Keepalive probe should only be sent if the application has not
8566 	 * done a close on the connection.
8567 	 */
8568 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8569 		return;
8570 	}
8571 	/* Timer fired too early, restart it. */
8572 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8573 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8574 		    MSEC_TO_TICK(ka_intrvl));
8575 		return;
8576 	}
8577 
8578 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8579 	/*
8580 	 * If we have not heard from the other side for a long
8581 	 * time, kill the connection unless the keepalive abort
8582 	 * threshold is 0.  In that case, we will probe "forever."
8583 	 */
8584 	if (tcp->tcp_ka_abort_thres != 0 &&
8585 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8586 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
8587 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8588 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8589 		return;
8590 	}
8591 
8592 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8593 	    idletime >= ka_intrvl) {
8594 		/* Fake resend of last ACKed byte. */
8595 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8596 
8597 		if (mp1 != NULL) {
8598 			*mp1->b_wptr++ = '\0';
8599 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8600 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8601 			freeb(mp1);
8602 			/*
8603 			 * if allocation failed, fall through to start the
8604 			 * timer back.
8605 			 */
8606 			if (mp != NULL) {
8607 				TCP_RECORD_TRACE(tcp, mp,
8608 				    TCP_TRACE_SEND_PKT);
8609 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8610 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
8611 				if (tcp->tcp_ka_last_intrvl != 0) {
8612 					/*
8613 					 * We should probe again at least
8614 					 * in ka_intrvl, but not more than
8615 					 * tcp_rexmit_interval_max.
8616 					 */
8617 					firetime = MIN(ka_intrvl - 1,
8618 					    tcp->tcp_ka_last_intrvl << 1);
8619 					if (firetime > tcp_rexmit_interval_max)
8620 						firetime =
8621 						    tcp_rexmit_interval_max;
8622 				} else {
8623 					firetime = tcp->tcp_rto;
8624 				}
8625 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8626 				    tcp_keepalive_killer,
8627 				    MSEC_TO_TICK(firetime));
8628 				tcp->tcp_ka_last_intrvl = firetime;
8629 				return;
8630 			}
8631 		}
8632 	} else {
8633 		tcp->tcp_ka_last_intrvl = 0;
8634 	}
8635 
8636 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8637 	if ((firetime = ka_intrvl - idletime) < 0) {
8638 		firetime = ka_intrvl;
8639 	}
8640 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8641 	    MSEC_TO_TICK(firetime));
8642 }
8643 
8644 int
8645 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8646 {
8647 	queue_t	*q = tcp->tcp_rq;
8648 	int32_t	mss = tcp->tcp_mss;
8649 	int	maxpsz;
8650 
8651 	if (TCP_IS_DETACHED(tcp))
8652 		return (mss);
8653 
8654 	if (tcp->tcp_fused) {
8655 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8656 		mss = INFPSZ;
8657 	} else if (tcp->tcp_mdt || tcp->tcp_maxpsz == 0) {
8658 		/*
8659 		 * Set the sd_qn_maxpsz according to the socket send buffer
8660 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8661 		 * instruct the stream head to copyin user data into contiguous
8662 		 * kernel-allocated buffers without breaking it up into smaller
8663 		 * chunks.  We round up the buffer size to the nearest SMSS.
8664 		 */
8665 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8666 		mss = INFPSZ;
8667 	} else {
8668 		/*
8669 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8670 		 * (and a multiple of the mss).  This instructs the stream
8671 		 * head to break down larger than SMSS writes into SMSS-
8672 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8673 		 */
8674 		maxpsz = tcp->tcp_maxpsz * mss;
8675 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8676 			maxpsz = tcp->tcp_xmit_hiwater/2;
8677 			/* Round up to nearest mss */
8678 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8679 		}
8680 	}
8681 	(void) setmaxps(q, maxpsz);
8682 	tcp->tcp_wq->q_maxpsz = maxpsz;
8683 
8684 	if (set_maxblk)
8685 		(void) mi_set_sth_maxblk(q, mss);
8686 
8687 	return (mss);
8688 }
8689 
8690 /*
8691  * Extract option values from a tcp header.  We put any found values into the
8692  * tcpopt struct and return a bitmask saying which options were found.
8693  */
8694 static int
8695 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8696 {
8697 	uchar_t		*endp;
8698 	int		len;
8699 	uint32_t	mss;
8700 	uchar_t		*up = (uchar_t *)tcph;
8701 	int		found = 0;
8702 	int32_t		sack_len;
8703 	tcp_seq		sack_begin, sack_end;
8704 	tcp_t		*tcp;
8705 
8706 	endp = up + TCP_HDR_LENGTH(tcph);
8707 	up += TCP_MIN_HEADER_LENGTH;
8708 	while (up < endp) {
8709 		len = endp - up;
8710 		switch (*up) {
8711 		case TCPOPT_EOL:
8712 			break;
8713 
8714 		case TCPOPT_NOP:
8715 			up++;
8716 			continue;
8717 
8718 		case TCPOPT_MAXSEG:
8719 			if (len < TCPOPT_MAXSEG_LEN ||
8720 			    up[1] != TCPOPT_MAXSEG_LEN)
8721 				break;
8722 
8723 			mss = BE16_TO_U16(up+2);
8724 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8725 			tcpopt->tcp_opt_mss = mss;
8726 			found |= TCP_OPT_MSS_PRESENT;
8727 
8728 			up += TCPOPT_MAXSEG_LEN;
8729 			continue;
8730 
8731 		case TCPOPT_WSCALE:
8732 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8733 				break;
8734 
8735 			if (up[2] > TCP_MAX_WINSHIFT)
8736 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8737 			else
8738 				tcpopt->tcp_opt_wscale = up[2];
8739 			found |= TCP_OPT_WSCALE_PRESENT;
8740 
8741 			up += TCPOPT_WS_LEN;
8742 			continue;
8743 
8744 		case TCPOPT_SACK_PERMITTED:
8745 			if (len < TCPOPT_SACK_OK_LEN ||
8746 			    up[1] != TCPOPT_SACK_OK_LEN)
8747 				break;
8748 			found |= TCP_OPT_SACK_OK_PRESENT;
8749 			up += TCPOPT_SACK_OK_LEN;
8750 			continue;
8751 
8752 		case TCPOPT_SACK:
8753 			if (len <= 2 || up[1] <= 2 || len < up[1])
8754 				break;
8755 
8756 			/* If TCP is not interested in SACK blks... */
8757 			if ((tcp = tcpopt->tcp) == NULL) {
8758 				up += up[1];
8759 				continue;
8760 			}
8761 			sack_len = up[1] - TCPOPT_HEADER_LEN;
8762 			up += TCPOPT_HEADER_LEN;
8763 
8764 			/*
8765 			 * If the list is empty, allocate one and assume
8766 			 * nothing is sack'ed.
8767 			 */
8768 			ASSERT(tcp->tcp_sack_info != NULL);
8769 			if (tcp->tcp_notsack_list == NULL) {
8770 				tcp_notsack_update(&(tcp->tcp_notsack_list),
8771 				    tcp->tcp_suna, tcp->tcp_snxt,
8772 				    &(tcp->tcp_num_notsack_blk),
8773 				    &(tcp->tcp_cnt_notsack_list));
8774 
8775 				/*
8776 				 * Make sure tcp_notsack_list is not NULL.
8777 				 * This happens when kmem_alloc(KM_NOSLEEP)
8778 				 * returns NULL.
8779 				 */
8780 				if (tcp->tcp_notsack_list == NULL) {
8781 					up += sack_len;
8782 					continue;
8783 				}
8784 				tcp->tcp_fack = tcp->tcp_suna;
8785 			}
8786 
8787 			while (sack_len > 0) {
8788 				if (up + 8 > endp) {
8789 					up = endp;
8790 					break;
8791 				}
8792 				sack_begin = BE32_TO_U32(up);
8793 				up += 4;
8794 				sack_end = BE32_TO_U32(up);
8795 				up += 4;
8796 				sack_len -= 8;
8797 				/*
8798 				 * Bounds checking.  Make sure the SACK
8799 				 * info is within tcp_suna and tcp_snxt.
8800 				 * If this SACK blk is out of bound, ignore
8801 				 * it but continue to parse the following
8802 				 * blks.
8803 				 */
8804 				if (SEQ_LEQ(sack_end, sack_begin) ||
8805 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
8806 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
8807 					continue;
8808 				}
8809 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
8810 				    sack_begin, sack_end,
8811 				    &(tcp->tcp_num_notsack_blk),
8812 				    &(tcp->tcp_cnt_notsack_list));
8813 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
8814 					tcp->tcp_fack = sack_end;
8815 				}
8816 			}
8817 			found |= TCP_OPT_SACK_PRESENT;
8818 			continue;
8819 
8820 		case TCPOPT_TSTAMP:
8821 			if (len < TCPOPT_TSTAMP_LEN ||
8822 			    up[1] != TCPOPT_TSTAMP_LEN)
8823 				break;
8824 
8825 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
8826 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
8827 
8828 			found |= TCP_OPT_TSTAMP_PRESENT;
8829 
8830 			up += TCPOPT_TSTAMP_LEN;
8831 			continue;
8832 
8833 		default:
8834 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
8835 				break;
8836 			up += up[1];
8837 			continue;
8838 		}
8839 		break;
8840 	}
8841 	return (found);
8842 }
8843 
8844 /*
8845  * Set the mss associated with a particular tcp based on its current value,
8846  * and a new one passed in. Observe minimums and maximums, and reset
8847  * other state variables that we want to view as multiples of mss.
8848  *
8849  * This function is called in various places mainly because
8850  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
8851  *    other side's SYN/SYN-ACK packet arrives.
8852  * 2) PMTUd may get us a new MSS.
8853  * 3) If the other side stops sending us timestamp option, we need to
8854  *    increase the MSS size to use the extra bytes available.
8855  */
8856 static void
8857 tcp_mss_set(tcp_t *tcp, uint32_t mss)
8858 {
8859 	uint32_t	mss_max;
8860 
8861 	if (tcp->tcp_ipversion == IPV4_VERSION)
8862 		mss_max = tcp_mss_max_ipv4;
8863 	else
8864 		mss_max = tcp_mss_max_ipv6;
8865 
8866 	if (mss < tcp_mss_min)
8867 		mss = tcp_mss_min;
8868 	if (mss > mss_max)
8869 		mss = mss_max;
8870 	/*
8871 	 * Unless naglim has been set by our client to
8872 	 * a non-mss value, force naglim to track mss.
8873 	 * This can help to aggregate small writes.
8874 	 */
8875 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
8876 		tcp->tcp_naglim = mss;
8877 	/*
8878 	 * TCP should be able to buffer at least 4 MSS data for obvious
8879 	 * performance reason.
8880 	 */
8881 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
8882 		tcp->tcp_xmit_hiwater = mss << 2;
8883 
8884 	/*
8885 	 * Check if we need to apply the tcp_init_cwnd here.  If
8886 	 * it is set and the MSS gets bigger (should not happen
8887 	 * normally), we need to adjust the resulting tcp_cwnd properly.
8888 	 * The new tcp_cwnd should not get bigger.
8889 	 */
8890 	if (tcp->tcp_init_cwnd == 0) {
8891 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
8892 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
8893 	} else {
8894 		if (tcp->tcp_mss < mss) {
8895 			tcp->tcp_cwnd = MAX(1,
8896 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
8897 		} else {
8898 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
8899 		}
8900 	}
8901 	tcp->tcp_mss = mss;
8902 	tcp->tcp_cwnd_cnt = 0;
8903 	(void) tcp_maxpsz_set(tcp, B_TRUE);
8904 }
8905 
8906 static int
8907 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8908 {
8909 	tcp_t		*tcp = NULL;
8910 	conn_t		*connp;
8911 	int		err;
8912 	dev_t		conn_dev;
8913 	zoneid_t	zoneid = getzoneid();
8914 
8915 	/*
8916 	 * Special case for install: miniroot needs to be able to access files
8917 	 * via NFS as though it were always in the global zone.
8918 	 */
8919 	if (credp == kcred && nfs_global_client_only != 0)
8920 		zoneid = GLOBAL_ZONEID;
8921 
8922 	if (q->q_ptr != NULL)
8923 		return (0);
8924 
8925 	if (sflag == MODOPEN) {
8926 		/*
8927 		 * This is a special case. The purpose of a modopen
8928 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
8929 		 * through for MIB browsers. Everything else is failed.
8930 		 */
8931 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
8932 
8933 		if (connp == NULL)
8934 			return (ENOMEM);
8935 
8936 		connp->conn_flags |= IPCL_TCPMOD;
8937 		connp->conn_cred = credp;
8938 		connp->conn_zoneid = zoneid;
8939 		q->q_ptr = WR(q)->q_ptr = connp;
8940 		crhold(credp);
8941 		q->q_qinfo = &tcp_mod_rinit;
8942 		WR(q)->q_qinfo = &tcp_mod_winit;
8943 		qprocson(q);
8944 		return (0);
8945 	}
8946 
8947 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
8948 		return (EBUSY);
8949 
8950 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
8951 
8952 	if (flag & SO_ACCEPTOR) {
8953 		q->q_qinfo = &tcp_acceptor_rinit;
8954 		q->q_ptr = (void *)conn_dev;
8955 		WR(q)->q_qinfo = &tcp_acceptor_winit;
8956 		WR(q)->q_ptr = (void *)conn_dev;
8957 		qprocson(q);
8958 		return (0);
8959 	}
8960 
8961 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
8962 	if (connp == NULL) {
8963 		inet_minor_free(ip_minor_arena, conn_dev);
8964 		q->q_ptr = NULL;
8965 		return (ENOSR);
8966 	}
8967 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
8968 	tcp = connp->conn_tcp;
8969 
8970 	q->q_ptr = WR(q)->q_ptr = connp;
8971 	if (getmajor(*devp) == TCP6_MAJ) {
8972 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
8973 		connp->conn_send = ip_output_v6;
8974 		connp->conn_af_isv6 = B_TRUE;
8975 		connp->conn_pkt_isv6 = B_TRUE;
8976 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
8977 		tcp->tcp_ipversion = IPV6_VERSION;
8978 		tcp->tcp_family = AF_INET6;
8979 		tcp->tcp_mss = tcp_mss_def_ipv6;
8980 	} else {
8981 		connp->conn_flags |= IPCL_TCP4;
8982 		connp->conn_send = ip_output;
8983 		connp->conn_af_isv6 = B_FALSE;
8984 		connp->conn_pkt_isv6 = B_FALSE;
8985 		tcp->tcp_ipversion = IPV4_VERSION;
8986 		tcp->tcp_family = AF_INET;
8987 		tcp->tcp_mss = tcp_mss_def_ipv4;
8988 	}
8989 
8990 	/*
8991 	 * TCP keeps a copy of cred for cache locality reasons but
8992 	 * we put a reference only once. If connp->conn_cred
8993 	 * becomes invalid, tcp_cred should also be set to NULL.
8994 	 */
8995 	tcp->tcp_cred = connp->conn_cred = credp;
8996 	crhold(connp->conn_cred);
8997 	tcp->tcp_cpid = curproc->p_pid;
8998 	connp->conn_zoneid = zoneid;
8999 
9000 	connp->conn_dev = conn_dev;
9001 
9002 	ASSERT(q->q_qinfo == &tcp_rinit);
9003 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9004 
9005 	if (flag & SO_SOCKSTR) {
9006 		/*
9007 		 * No need to insert a socket in tcp acceptor hash.
9008 		 * If it was a socket acceptor stream, we dealt with
9009 		 * it above. A socket listener can never accept a
9010 		 * connection and doesn't need acceptor_id.
9011 		 */
9012 		connp->conn_flags |= IPCL_SOCKET;
9013 		tcp->tcp_issocket = 1;
9014 		WR(q)->q_qinfo = &tcp_sock_winit;
9015 	} else {
9016 #ifdef	_ILP32
9017 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9018 #else
9019 		tcp->tcp_acceptor_id = conn_dev;
9020 #endif	/* _ILP32 */
9021 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9022 	}
9023 
9024 	if (tcp_trace)
9025 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9026 
9027 	err = tcp_init(tcp, q);
9028 	if (err != 0) {
9029 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9030 		tcp_acceptor_hash_remove(tcp);
9031 		CONN_DEC_REF(connp);
9032 		q->q_ptr = WR(q)->q_ptr = NULL;
9033 		return (err);
9034 	}
9035 
9036 	RD(q)->q_hiwat = tcp_recv_hiwat;
9037 	tcp->tcp_rwnd = tcp_recv_hiwat;
9038 
9039 	/* Non-zero default values */
9040 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9041 	/*
9042 	 * Put the ref for TCP. Ref for IP was already put
9043 	 * by ipcl_conn_create. Also Make the conn_t globally
9044 	 * visible to walkers
9045 	 */
9046 	mutex_enter(&connp->conn_lock);
9047 	CONN_INC_REF_LOCKED(connp);
9048 	ASSERT(connp->conn_ref == 2);
9049 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9050 	mutex_exit(&connp->conn_lock);
9051 
9052 	qprocson(q);
9053 	return (0);
9054 }
9055 
9056 /*
9057  * Some TCP options can be "set" by requesting them in the option
9058  * buffer. This is needed for XTI feature test though we do not
9059  * allow it in general. We interpret that this mechanism is more
9060  * applicable to OSI protocols and need not be allowed in general.
9061  * This routine filters out options for which it is not allowed (most)
9062  * and lets through those (few) for which it is. [ The XTI interface
9063  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9064  * ever implemented will have to be allowed here ].
9065  */
9066 static boolean_t
9067 tcp_allow_connopt_set(int level, int name)
9068 {
9069 
9070 	switch (level) {
9071 	case IPPROTO_TCP:
9072 		switch (name) {
9073 		case TCP_NODELAY:
9074 			return (B_TRUE);
9075 		default:
9076 			return (B_FALSE);
9077 		}
9078 		/*NOTREACHED*/
9079 	default:
9080 		return (B_FALSE);
9081 	}
9082 	/*NOTREACHED*/
9083 }
9084 
9085 /*
9086  * This routine gets default values of certain options whose default
9087  * values are maintained by protocol specific code
9088  */
9089 /* ARGSUSED */
9090 int
9091 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9092 {
9093 	int32_t	*i1 = (int32_t *)ptr;
9094 
9095 	switch (level) {
9096 	case IPPROTO_TCP:
9097 		switch (name) {
9098 		case TCP_NOTIFY_THRESHOLD:
9099 			*i1 = tcp_ip_notify_interval;
9100 			break;
9101 		case TCP_ABORT_THRESHOLD:
9102 			*i1 = tcp_ip_abort_interval;
9103 			break;
9104 		case TCP_CONN_NOTIFY_THRESHOLD:
9105 			*i1 = tcp_ip_notify_cinterval;
9106 			break;
9107 		case TCP_CONN_ABORT_THRESHOLD:
9108 			*i1 = tcp_ip_abort_cinterval;
9109 			break;
9110 		default:
9111 			return (-1);
9112 		}
9113 		break;
9114 	case IPPROTO_IP:
9115 		switch (name) {
9116 		case IP_TTL:
9117 			*i1 = tcp_ipv4_ttl;
9118 			break;
9119 		default:
9120 			return (-1);
9121 		}
9122 		break;
9123 	case IPPROTO_IPV6:
9124 		switch (name) {
9125 		case IPV6_UNICAST_HOPS:
9126 			*i1 = tcp_ipv6_hoplimit;
9127 			break;
9128 		default:
9129 			return (-1);
9130 		}
9131 		break;
9132 	default:
9133 		return (-1);
9134 	}
9135 	return (sizeof (int));
9136 }
9137 
9138 
9139 /*
9140  * TCP routine to get the values of options.
9141  */
9142 int
9143 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9144 {
9145 	int		*i1 = (int *)ptr;
9146 	conn_t		*connp = Q_TO_CONN(q);
9147 	tcp_t		*tcp = connp->conn_tcp;
9148 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9149 
9150 	switch (level) {
9151 	case SOL_SOCKET:
9152 		switch (name) {
9153 		case SO_LINGER:	{
9154 			struct linger *lgr = (struct linger *)ptr;
9155 
9156 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9157 			lgr->l_linger = tcp->tcp_lingertime;
9158 			}
9159 			return (sizeof (struct linger));
9160 		case SO_DEBUG:
9161 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9162 			break;
9163 		case SO_KEEPALIVE:
9164 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9165 			break;
9166 		case SO_DONTROUTE:
9167 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9168 			break;
9169 		case SO_USELOOPBACK:
9170 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9171 			break;
9172 		case SO_BROADCAST:
9173 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9174 			break;
9175 		case SO_REUSEADDR:
9176 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9177 			break;
9178 		case SO_OOBINLINE:
9179 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9180 			break;
9181 		case SO_DGRAM_ERRIND:
9182 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9183 			break;
9184 		case SO_TYPE:
9185 			*i1 = SOCK_STREAM;
9186 			break;
9187 		case SO_SNDBUF:
9188 			*i1 = tcp->tcp_xmit_hiwater;
9189 			break;
9190 		case SO_RCVBUF:
9191 			*i1 = RD(q)->q_hiwat;
9192 			break;
9193 		case SO_SND_COPYAVOID:
9194 			*i1 = tcp->tcp_snd_zcopy_on ?
9195 			    SO_SND_COPYAVOID : 0;
9196 			break;
9197 		default:
9198 			return (-1);
9199 		}
9200 		break;
9201 	case IPPROTO_TCP:
9202 		switch (name) {
9203 		case TCP_NODELAY:
9204 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9205 			break;
9206 		case TCP_MAXSEG:
9207 			*i1 = tcp->tcp_mss;
9208 			break;
9209 		case TCP_NOTIFY_THRESHOLD:
9210 			*i1 = (int)tcp->tcp_first_timer_threshold;
9211 			break;
9212 		case TCP_ABORT_THRESHOLD:
9213 			*i1 = tcp->tcp_second_timer_threshold;
9214 			break;
9215 		case TCP_CONN_NOTIFY_THRESHOLD:
9216 			*i1 = tcp->tcp_first_ctimer_threshold;
9217 			break;
9218 		case TCP_CONN_ABORT_THRESHOLD:
9219 			*i1 = tcp->tcp_second_ctimer_threshold;
9220 			break;
9221 		case TCP_RECVDSTADDR:
9222 			*i1 = tcp->tcp_recvdstaddr;
9223 			break;
9224 		case TCP_ANONPRIVBIND:
9225 			*i1 = tcp->tcp_anon_priv_bind;
9226 			break;
9227 		case TCP_EXCLBIND:
9228 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9229 			break;
9230 		case TCP_INIT_CWND:
9231 			*i1 = tcp->tcp_init_cwnd;
9232 			break;
9233 		case TCP_KEEPALIVE_THRESHOLD:
9234 			*i1 = tcp->tcp_ka_interval;
9235 			break;
9236 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9237 			*i1 = tcp->tcp_ka_abort_thres;
9238 			break;
9239 		case TCP_CORK:
9240 			*i1 = tcp->tcp_cork;
9241 			break;
9242 		default:
9243 			return (-1);
9244 		}
9245 		break;
9246 	case IPPROTO_IP:
9247 		if (tcp->tcp_family != AF_INET)
9248 			return (-1);
9249 		switch (name) {
9250 		case IP_OPTIONS:
9251 		case T_IP_OPTIONS: {
9252 			/*
9253 			 * This is compatible with BSD in that in only return
9254 			 * the reverse source route with the final destination
9255 			 * as the last entry. The first 4 bytes of the option
9256 			 * will contain the final destination.
9257 			 */
9258 			char	*opt_ptr;
9259 			int	opt_len;
9260 			opt_ptr = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
9261 			opt_len = (char *)tcp->tcp_tcph - opt_ptr;
9262 			/* Caller ensures enough space */
9263 			if (opt_len > 0) {
9264 				/*
9265 				 * TODO: Do we have to handle getsockopt on an
9266 				 * initiator as well?
9267 				 */
9268 				return (tcp_opt_get_user(tcp->tcp_ipha, ptr));
9269 			}
9270 			return (0);
9271 			}
9272 		case IP_TOS:
9273 		case T_IP_TOS:
9274 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9275 			break;
9276 		case IP_TTL:
9277 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9278 			break;
9279 		default:
9280 			return (-1);
9281 		}
9282 		break;
9283 	case IPPROTO_IPV6:
9284 		/*
9285 		 * IPPROTO_IPV6 options are only supported for sockets
9286 		 * that are using IPv6 on the wire.
9287 		 */
9288 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9289 			return (-1);
9290 		}
9291 		switch (name) {
9292 		case IPV6_UNICAST_HOPS:
9293 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9294 			break;	/* goto sizeof (int) option return */
9295 		case IPV6_BOUND_IF:
9296 			/* Zero if not set */
9297 			*i1 = tcp->tcp_bound_if;
9298 			break;	/* goto sizeof (int) option return */
9299 		case IPV6_RECVPKTINFO:
9300 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9301 				*i1 = 1;
9302 			else
9303 				*i1 = 0;
9304 			break;	/* goto sizeof (int) option return */
9305 		case IPV6_RECVTCLASS:
9306 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9307 				*i1 = 1;
9308 			else
9309 				*i1 = 0;
9310 			break;	/* goto sizeof (int) option return */
9311 		case IPV6_RECVHOPLIMIT:
9312 			if (tcp->tcp_ipv6_recvancillary &
9313 			    TCP_IPV6_RECVHOPLIMIT)
9314 				*i1 = 1;
9315 			else
9316 				*i1 = 0;
9317 			break;	/* goto sizeof (int) option return */
9318 		case IPV6_RECVHOPOPTS:
9319 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9320 				*i1 = 1;
9321 			else
9322 				*i1 = 0;
9323 			break;	/* goto sizeof (int) option return */
9324 		case IPV6_RECVDSTOPTS:
9325 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9326 				*i1 = 1;
9327 			else
9328 				*i1 = 0;
9329 			break;	/* goto sizeof (int) option return */
9330 		case _OLD_IPV6_RECVDSTOPTS:
9331 			if (tcp->tcp_ipv6_recvancillary &
9332 			    TCP_OLD_IPV6_RECVDSTOPTS)
9333 				*i1 = 1;
9334 			else
9335 				*i1 = 0;
9336 			break;	/* goto sizeof (int) option return */
9337 		case IPV6_RECVRTHDR:
9338 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9339 				*i1 = 1;
9340 			else
9341 				*i1 = 0;
9342 			break;	/* goto sizeof (int) option return */
9343 		case IPV6_RECVRTHDRDSTOPTS:
9344 			if (tcp->tcp_ipv6_recvancillary &
9345 			    TCP_IPV6_RECVRTDSTOPTS)
9346 				*i1 = 1;
9347 			else
9348 				*i1 = 0;
9349 			break;	/* goto sizeof (int) option return */
9350 		case IPV6_PKTINFO: {
9351 			/* XXX assumes that caller has room for max size! */
9352 			struct in6_pktinfo *pkti;
9353 
9354 			pkti = (struct in6_pktinfo *)ptr;
9355 			if (ipp->ipp_fields & IPPF_IFINDEX)
9356 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9357 			else
9358 				pkti->ipi6_ifindex = 0;
9359 			if (ipp->ipp_fields & IPPF_ADDR)
9360 				pkti->ipi6_addr = ipp->ipp_addr;
9361 			else
9362 				pkti->ipi6_addr = ipv6_all_zeros;
9363 			return (sizeof (struct in6_pktinfo));
9364 		}
9365 		case IPV6_TCLASS:
9366 			if (ipp->ipp_fields & IPPF_TCLASS)
9367 				*i1 = ipp->ipp_tclass;
9368 			else
9369 				*i1 = IPV6_FLOW_TCLASS(
9370 				    IPV6_DEFAULT_VERS_AND_FLOW);
9371 			break;	/* goto sizeof (int) option return */
9372 		case IPV6_NEXTHOP: {
9373 			sin6_t *sin6 = (sin6_t *)ptr;
9374 
9375 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9376 				return (0);
9377 			*sin6 = sin6_null;
9378 			sin6->sin6_family = AF_INET6;
9379 			sin6->sin6_addr = ipp->ipp_nexthop;
9380 			return (sizeof (sin6_t));
9381 		}
9382 		case IPV6_HOPOPTS:
9383 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9384 				return (0);
9385 			bcopy(ipp->ipp_hopopts, ptr, ipp->ipp_hopoptslen);
9386 			return (ipp->ipp_hopoptslen);
9387 		case IPV6_RTHDRDSTOPTS:
9388 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9389 				return (0);
9390 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9391 			return (ipp->ipp_rtdstoptslen);
9392 		case IPV6_RTHDR:
9393 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9394 				return (0);
9395 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9396 			return (ipp->ipp_rthdrlen);
9397 		case IPV6_DSTOPTS:
9398 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9399 				return (0);
9400 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9401 			return (ipp->ipp_dstoptslen);
9402 		case IPV6_SRC_PREFERENCES:
9403 			return (ip6_get_src_preferences(connp,
9404 			    (uint32_t *)ptr));
9405 		case IPV6_PATHMTU: {
9406 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9407 
9408 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9409 				return (-1);
9410 
9411 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9412 				connp->conn_fport, mtuinfo));
9413 		}
9414 		default:
9415 			return (-1);
9416 		}
9417 		break;
9418 	default:
9419 		return (-1);
9420 	}
9421 	return (sizeof (int));
9422 }
9423 
9424 /*
9425  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9426  * Parameters are assumed to be verified by the caller.
9427  */
9428 /* ARGSUSED */
9429 int
9430 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9431     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9432     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9433 {
9434 	tcp_t	*tcp = Q_TO_TCP(q);
9435 	int	*i1 = (int *)invalp;
9436 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9437 	boolean_t checkonly;
9438 	int	reterr;
9439 
9440 	switch (optset_context) {
9441 	case SETFN_OPTCOM_CHECKONLY:
9442 		checkonly = B_TRUE;
9443 		/*
9444 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9445 		 * inlen != 0 implies value supplied and
9446 		 * 	we have to "pretend" to set it.
9447 		 * inlen == 0 implies that there is no
9448 		 * 	value part in T_CHECK request and just validation
9449 		 * done elsewhere should be enough, we just return here.
9450 		 */
9451 		if (inlen == 0) {
9452 			*outlenp = 0;
9453 			return (0);
9454 		}
9455 		break;
9456 	case SETFN_OPTCOM_NEGOTIATE:
9457 		checkonly = B_FALSE;
9458 		break;
9459 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9460 	case SETFN_CONN_NEGOTIATE:
9461 		checkonly = B_FALSE;
9462 		/*
9463 		 * Negotiating local and "association-related" options
9464 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9465 		 * primitives is allowed by XTI, but we choose
9466 		 * to not implement this style negotiation for Internet
9467 		 * protocols (We interpret it is a must for OSI world but
9468 		 * optional for Internet protocols) for all options.
9469 		 * [ Will do only for the few options that enable test
9470 		 * suites that our XTI implementation of this feature
9471 		 * works for transports that do allow it ]
9472 		 */
9473 		if (!tcp_allow_connopt_set(level, name)) {
9474 			*outlenp = 0;
9475 			return (EINVAL);
9476 		}
9477 		break;
9478 	default:
9479 		/*
9480 		 * We should never get here
9481 		 */
9482 		*outlenp = 0;
9483 		return (EINVAL);
9484 	}
9485 
9486 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9487 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9488 
9489 	/*
9490 	 * For TCP, we should have no ancillary data sent down
9491 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9492 	 * has to be zero.
9493 	 */
9494 	ASSERT(thisdg_attrs == NULL);
9495 
9496 	/*
9497 	 * For fixed length options, no sanity check
9498 	 * of passed in length is done. It is assumed *_optcom_req()
9499 	 * routines do the right thing.
9500 	 */
9501 
9502 	switch (level) {
9503 	case SOL_SOCKET:
9504 		switch (name) {
9505 		case SO_LINGER: {
9506 			struct linger *lgr = (struct linger *)invalp;
9507 
9508 			if (!checkonly) {
9509 				if (lgr->l_onoff) {
9510 					tcp->tcp_linger = 1;
9511 					tcp->tcp_lingertime = lgr->l_linger;
9512 				} else {
9513 					tcp->tcp_linger = 0;
9514 					tcp->tcp_lingertime = 0;
9515 				}
9516 				/* struct copy */
9517 				*(struct linger *)outvalp = *lgr;
9518 			} else {
9519 				if (!lgr->l_onoff) {
9520 				    ((struct linger *)outvalp)->l_onoff = 0;
9521 				    ((struct linger *)outvalp)->l_linger = 0;
9522 				} else {
9523 				    /* struct copy */
9524 				    *(struct linger *)outvalp = *lgr;
9525 				}
9526 			}
9527 			*outlenp = sizeof (struct linger);
9528 			return (0);
9529 		}
9530 		case SO_DEBUG:
9531 			if (!checkonly)
9532 				tcp->tcp_debug = onoff;
9533 			break;
9534 		case SO_KEEPALIVE:
9535 			if (checkonly) {
9536 				/* T_CHECK case */
9537 				break;
9538 			}
9539 
9540 			if (!onoff) {
9541 				if (tcp->tcp_ka_enabled) {
9542 					if (tcp->tcp_ka_tid != 0) {
9543 						(void) TCP_TIMER_CANCEL(tcp,
9544 						    tcp->tcp_ka_tid);
9545 						tcp->tcp_ka_tid = 0;
9546 					}
9547 					tcp->tcp_ka_enabled = 0;
9548 				}
9549 				break;
9550 			}
9551 			if (!tcp->tcp_ka_enabled) {
9552 				/* Crank up the keepalive timer */
9553 				tcp->tcp_ka_last_intrvl = 0;
9554 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9555 				    tcp_keepalive_killer,
9556 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
9557 				tcp->tcp_ka_enabled = 1;
9558 			}
9559 			break;
9560 		case SO_DONTROUTE:
9561 			/*
9562 			 * SO_DONTROUTE, SO_USELOOPBACK and SO_BROADCAST are
9563 			 * only of interest to IP.  We track them here only so
9564 			 * that we can report their current value.
9565 			 */
9566 			if (!checkonly) {
9567 				tcp->tcp_dontroute = onoff;
9568 				tcp->tcp_connp->conn_dontroute = onoff;
9569 			}
9570 			break;
9571 		case SO_USELOOPBACK:
9572 			if (!checkonly) {
9573 				tcp->tcp_useloopback = onoff;
9574 				tcp->tcp_connp->conn_loopback = onoff;
9575 			}
9576 			break;
9577 		case SO_BROADCAST:
9578 			if (!checkonly) {
9579 				tcp->tcp_broadcast = onoff;
9580 				tcp->tcp_connp->conn_broadcast = onoff;
9581 			}
9582 			break;
9583 		case SO_REUSEADDR:
9584 			if (!checkonly) {
9585 				tcp->tcp_reuseaddr = onoff;
9586 				tcp->tcp_connp->conn_reuseaddr = onoff;
9587 			}
9588 			break;
9589 		case SO_OOBINLINE:
9590 			if (!checkonly)
9591 				tcp->tcp_oobinline = onoff;
9592 			break;
9593 		case SO_DGRAM_ERRIND:
9594 			if (!checkonly)
9595 				tcp->tcp_dgram_errind = onoff;
9596 			break;
9597 		case SO_SNDBUF: {
9598 			tcp_t *peer_tcp;
9599 
9600 			if (*i1 > tcp_max_buf) {
9601 				*outlenp = 0;
9602 				return (ENOBUFS);
9603 			}
9604 			if (checkonly)
9605 				break;
9606 
9607 			tcp->tcp_xmit_hiwater = *i1;
9608 			if (tcp_snd_lowat_fraction != 0)
9609 				tcp->tcp_xmit_lowater =
9610 				    tcp->tcp_xmit_hiwater /
9611 				    tcp_snd_lowat_fraction;
9612 			(void) tcp_maxpsz_set(tcp, B_TRUE);
9613 			/*
9614 			 * If we are flow-controlled, recheck the condition.
9615 			 * There are apps that increase SO_SNDBUF size when
9616 			 * flow-controlled (EWOULDBLOCK), and expect the flow
9617 			 * control condition to be lifted right away.
9618 			 *
9619 			 * For the fused tcp loopback case, in order to avoid
9620 			 * a race with the peer's tcp_fuse_rrw() we need to
9621 			 * hold its fuse_lock while accessing tcp_flow_stopped.
9622 			 */
9623 			peer_tcp = tcp->tcp_loopback_peer;
9624 			ASSERT(!tcp->tcp_fused || peer_tcp != NULL);
9625 			if (tcp->tcp_fused)
9626 				mutex_enter(&peer_tcp->tcp_fuse_lock);
9627 
9628 			if (tcp->tcp_flow_stopped &&
9629 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
9630 				tcp_clrqfull(tcp);
9631 			}
9632 			if (tcp->tcp_fused)
9633 				mutex_exit(&peer_tcp->tcp_fuse_lock);
9634 			break;
9635 		}
9636 		case SO_RCVBUF:
9637 			if (*i1 > tcp_max_buf) {
9638 				*outlenp = 0;
9639 				return (ENOBUFS);
9640 			}
9641 			/* Silently ignore zero */
9642 			if (!checkonly && *i1 != 0) {
9643 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
9644 				(void) tcp_rwnd_set(tcp, *i1);
9645 			}
9646 			/*
9647 			 * XXX should we return the rwnd here
9648 			 * and tcp_opt_get ?
9649 			 */
9650 			break;
9651 		case SO_SND_COPYAVOID:
9652 			if (!checkonly) {
9653 				/* we only allow enable at most once for now */
9654 				if (tcp->tcp_loopback ||
9655 				    (!tcp->tcp_snd_zcopy_aware &&
9656 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
9657 					*outlenp = 0;
9658 					return (EOPNOTSUPP);
9659 				}
9660 				tcp->tcp_snd_zcopy_aware = 1;
9661 			}
9662 			break;
9663 		default:
9664 			*outlenp = 0;
9665 			return (EINVAL);
9666 		}
9667 		break;
9668 	case IPPROTO_TCP:
9669 		switch (name) {
9670 		case TCP_NODELAY:
9671 			if (!checkonly)
9672 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
9673 			break;
9674 		case TCP_NOTIFY_THRESHOLD:
9675 			if (!checkonly)
9676 				tcp->tcp_first_timer_threshold = *i1;
9677 			break;
9678 		case TCP_ABORT_THRESHOLD:
9679 			if (!checkonly)
9680 				tcp->tcp_second_timer_threshold = *i1;
9681 			break;
9682 		case TCP_CONN_NOTIFY_THRESHOLD:
9683 			if (!checkonly)
9684 				tcp->tcp_first_ctimer_threshold = *i1;
9685 			break;
9686 		case TCP_CONN_ABORT_THRESHOLD:
9687 			if (!checkonly)
9688 				tcp->tcp_second_ctimer_threshold = *i1;
9689 			break;
9690 		case TCP_RECVDSTADDR:
9691 			if (tcp->tcp_state > TCPS_LISTEN)
9692 				return (EOPNOTSUPP);
9693 			if (!checkonly)
9694 				tcp->tcp_recvdstaddr = onoff;
9695 			break;
9696 		case TCP_ANONPRIVBIND:
9697 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
9698 				*outlenp = 0;
9699 				return (reterr);
9700 			}
9701 			if (!checkonly) {
9702 				tcp->tcp_anon_priv_bind = onoff;
9703 			}
9704 			break;
9705 		case TCP_EXCLBIND:
9706 			if (!checkonly)
9707 				tcp->tcp_exclbind = onoff;
9708 			break;	/* goto sizeof (int) option return */
9709 		case TCP_INIT_CWND: {
9710 			uint32_t init_cwnd = *((uint32_t *)invalp);
9711 
9712 			if (checkonly)
9713 				break;
9714 
9715 			/*
9716 			 * Only allow socket with network configuration
9717 			 * privilege to set the initial cwnd to be larger
9718 			 * than allowed by RFC 3390.
9719 			 */
9720 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
9721 				tcp->tcp_init_cwnd = init_cwnd;
9722 				break;
9723 			}
9724 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
9725 				*outlenp = 0;
9726 				return (reterr);
9727 			}
9728 			if (init_cwnd > TCP_MAX_INIT_CWND) {
9729 				*outlenp = 0;
9730 				return (EINVAL);
9731 			}
9732 			tcp->tcp_init_cwnd = init_cwnd;
9733 			break;
9734 		}
9735 		case TCP_KEEPALIVE_THRESHOLD:
9736 			if (checkonly)
9737 				break;
9738 
9739 			if (*i1 < tcp_keepalive_interval_low ||
9740 			    *i1 > tcp_keepalive_interval_high) {
9741 				*outlenp = 0;
9742 				return (EINVAL);
9743 			}
9744 			if (*i1 != tcp->tcp_ka_interval) {
9745 				tcp->tcp_ka_interval = *i1;
9746 				/*
9747 				 * Check if we need to restart the
9748 				 * keepalive timer.
9749 				 */
9750 				if (tcp->tcp_ka_tid != 0) {
9751 					ASSERT(tcp->tcp_ka_enabled);
9752 					(void) TCP_TIMER_CANCEL(tcp,
9753 					    tcp->tcp_ka_tid);
9754 					tcp->tcp_ka_last_intrvl = 0;
9755 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
9756 					    tcp_keepalive_killer,
9757 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
9758 				}
9759 			}
9760 			break;
9761 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9762 			if (!checkonly) {
9763 				if (*i1 < tcp_keepalive_abort_interval_low ||
9764 				    *i1 > tcp_keepalive_abort_interval_high) {
9765 					*outlenp = 0;
9766 					return (EINVAL);
9767 				}
9768 				tcp->tcp_ka_abort_thres = *i1;
9769 			}
9770 			break;
9771 		case TCP_CORK:
9772 			if (!checkonly) {
9773 				/*
9774 				 * if tcp->tcp_cork was set and is now
9775 				 * being unset, we have to make sure that
9776 				 * the remaining data gets sent out. Also
9777 				 * unset tcp->tcp_cork so that tcp_wput_data()
9778 				 * can send data even if it is less than mss
9779 				 */
9780 				if (tcp->tcp_cork && onoff == 0 &&
9781 				    tcp->tcp_unsent > 0) {
9782 					tcp->tcp_cork = B_FALSE;
9783 					tcp_wput_data(tcp, NULL, B_FALSE);
9784 				}
9785 				tcp->tcp_cork = onoff;
9786 			}
9787 			break;
9788 		default:
9789 			*outlenp = 0;
9790 			return (EINVAL);
9791 		}
9792 		break;
9793 	case IPPROTO_IP:
9794 		if (tcp->tcp_family != AF_INET) {
9795 			*outlenp = 0;
9796 			return (ENOPROTOOPT);
9797 		}
9798 		switch (name) {
9799 		case IP_OPTIONS:
9800 		case T_IP_OPTIONS:
9801 			reterr = tcp_opt_set_header(tcp, checkonly,
9802 			    invalp, inlen);
9803 			if (reterr) {
9804 				*outlenp = 0;
9805 				return (reterr);
9806 			}
9807 			/* OK return - copy input buffer into output buffer */
9808 			if (invalp != outvalp) {
9809 				/* don't trust bcopy for identical src/dst */
9810 				bcopy(invalp, outvalp, inlen);
9811 			}
9812 			*outlenp = inlen;
9813 			return (0);
9814 		case IP_TOS:
9815 		case T_IP_TOS:
9816 			if (!checkonly) {
9817 				tcp->tcp_ipha->ipha_type_of_service =
9818 				    (uchar_t)*i1;
9819 				tcp->tcp_tos = (uchar_t)*i1;
9820 			}
9821 			break;
9822 		case IP_TTL:
9823 			if (!checkonly) {
9824 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
9825 				tcp->tcp_ttl = (uchar_t)*i1;
9826 			}
9827 			break;
9828 		case IP_BOUND_IF:
9829 			/* Handled at the IP level */
9830 			return (-EINVAL);
9831 		case IP_SEC_OPT:
9832 			/*
9833 			 * We should not allow policy setting after
9834 			 * we start listening for connections.
9835 			 */
9836 			if (tcp->tcp_state == TCPS_LISTEN) {
9837 				return (EINVAL);
9838 			} else {
9839 				/* Handled at the IP level */
9840 				return (-EINVAL);
9841 			}
9842 		default:
9843 			*outlenp = 0;
9844 			return (EINVAL);
9845 		}
9846 		break;
9847 	case IPPROTO_IPV6: {
9848 		ip6_pkt_t		*ipp;
9849 
9850 		/*
9851 		 * IPPROTO_IPV6 options are only supported for sockets
9852 		 * that are using IPv6 on the wire.
9853 		 */
9854 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9855 			*outlenp = 0;
9856 			return (ENOPROTOOPT);
9857 		}
9858 		/*
9859 		 * Only sticky options; no ancillary data
9860 		 */
9861 		ASSERT(thisdg_attrs == NULL);
9862 		ipp = &tcp->tcp_sticky_ipp;
9863 
9864 		switch (name) {
9865 		case IPV6_UNICAST_HOPS:
9866 			/* -1 means use default */
9867 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
9868 				*outlenp = 0;
9869 				return (EINVAL);
9870 			}
9871 			if (!checkonly) {
9872 				if (*i1 == -1) {
9873 					tcp->tcp_ip6h->ip6_hops =
9874 					    ipp->ipp_unicast_hops =
9875 					    (uint8_t)tcp_ipv6_hoplimit;
9876 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
9877 					/* Pass modified value to IP. */
9878 					*i1 = tcp->tcp_ip6h->ip6_hops;
9879 				} else {
9880 					tcp->tcp_ip6h->ip6_hops =
9881 					    ipp->ipp_unicast_hops =
9882 					    (uint8_t)*i1;
9883 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
9884 				}
9885 				reterr = tcp_build_hdrs(q, tcp);
9886 				if (reterr != 0)
9887 					return (reterr);
9888 			}
9889 			break;
9890 		case IPV6_BOUND_IF:
9891 			if (!checkonly) {
9892 				int error = 0;
9893 
9894 				tcp->tcp_bound_if = *i1;
9895 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
9896 				    B_TRUE, checkonly, level, name, mblk);
9897 				if (error != 0) {
9898 					*outlenp = 0;
9899 					return (error);
9900 				}
9901 			}
9902 			break;
9903 		/*
9904 		 * Set boolean switches for ancillary data delivery
9905 		 */
9906 		case IPV6_RECVPKTINFO:
9907 			if (!checkonly) {
9908 				if (onoff)
9909 					tcp->tcp_ipv6_recvancillary |=
9910 					    TCP_IPV6_RECVPKTINFO;
9911 				else
9912 					tcp->tcp_ipv6_recvancillary &=
9913 					    ~TCP_IPV6_RECVPKTINFO;
9914 				/* Force it to be sent up with the next msg */
9915 				tcp->tcp_recvifindex = 0;
9916 			}
9917 			break;
9918 		case IPV6_RECVTCLASS:
9919 			if (!checkonly) {
9920 				if (onoff)
9921 					tcp->tcp_ipv6_recvancillary |=
9922 					    TCP_IPV6_RECVTCLASS;
9923 				else
9924 					tcp->tcp_ipv6_recvancillary &=
9925 					    ~TCP_IPV6_RECVTCLASS;
9926 			}
9927 			break;
9928 		case IPV6_RECVHOPLIMIT:
9929 			if (!checkonly) {
9930 				if (onoff)
9931 					tcp->tcp_ipv6_recvancillary |=
9932 					    TCP_IPV6_RECVHOPLIMIT;
9933 				else
9934 					tcp->tcp_ipv6_recvancillary &=
9935 					    ~TCP_IPV6_RECVHOPLIMIT;
9936 				/* Force it to be sent up with the next msg */
9937 				tcp->tcp_recvhops = 0xffffffffU;
9938 			}
9939 			break;
9940 		case IPV6_RECVHOPOPTS:
9941 			if (!checkonly) {
9942 				if (onoff)
9943 					tcp->tcp_ipv6_recvancillary |=
9944 					    TCP_IPV6_RECVHOPOPTS;
9945 				else
9946 					tcp->tcp_ipv6_recvancillary &=
9947 					    ~TCP_IPV6_RECVHOPOPTS;
9948 			}
9949 			break;
9950 		case IPV6_RECVDSTOPTS:
9951 			if (!checkonly) {
9952 				if (onoff)
9953 					tcp->tcp_ipv6_recvancillary |=
9954 					    TCP_IPV6_RECVDSTOPTS;
9955 				else
9956 					tcp->tcp_ipv6_recvancillary &=
9957 					    ~TCP_IPV6_RECVDSTOPTS;
9958 			}
9959 			break;
9960 		case _OLD_IPV6_RECVDSTOPTS:
9961 			if (!checkonly) {
9962 				if (onoff)
9963 					tcp->tcp_ipv6_recvancillary |=
9964 					    TCP_OLD_IPV6_RECVDSTOPTS;
9965 				else
9966 					tcp->tcp_ipv6_recvancillary &=
9967 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
9968 			}
9969 			break;
9970 		case IPV6_RECVRTHDR:
9971 			if (!checkonly) {
9972 				if (onoff)
9973 					tcp->tcp_ipv6_recvancillary |=
9974 					    TCP_IPV6_RECVRTHDR;
9975 				else
9976 					tcp->tcp_ipv6_recvancillary &=
9977 					    ~TCP_IPV6_RECVRTHDR;
9978 			}
9979 			break;
9980 		case IPV6_RECVRTHDRDSTOPTS:
9981 			if (!checkonly) {
9982 				if (onoff)
9983 					tcp->tcp_ipv6_recvancillary |=
9984 					    TCP_IPV6_RECVRTDSTOPTS;
9985 				else
9986 					tcp->tcp_ipv6_recvancillary &=
9987 					    ~TCP_IPV6_RECVRTDSTOPTS;
9988 			}
9989 			break;
9990 		case IPV6_PKTINFO:
9991 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
9992 				return (EINVAL);
9993 			if (checkonly)
9994 				break;
9995 
9996 			if (inlen == 0) {
9997 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
9998 			} else {
9999 				struct in6_pktinfo *pkti;
10000 
10001 				pkti = (struct in6_pktinfo *)invalp;
10002 				/*
10003 				 * RFC 3542 states that ipi6_addr must be
10004 				 * the unspecified address when setting the
10005 				 * IPV6_PKTINFO sticky socket option on a
10006 				 * TCP socket.
10007 				 */
10008 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10009 					return (EINVAL);
10010 				/*
10011 				 * ip6_set_pktinfo() validates the source
10012 				 * address and interface index.
10013 				 */
10014 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10015 				    pkti, mblk);
10016 				if (reterr != 0)
10017 					return (reterr);
10018 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10019 				ipp->ipp_addr = pkti->ipi6_addr;
10020 				if (ipp->ipp_ifindex != 0)
10021 					ipp->ipp_fields |= IPPF_IFINDEX;
10022 				else
10023 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10024 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10025 					ipp->ipp_fields |= IPPF_ADDR;
10026 				else
10027 					ipp->ipp_fields &= ~IPPF_ADDR;
10028 			}
10029 			reterr = tcp_build_hdrs(q, tcp);
10030 			if (reterr != 0)
10031 				return (reterr);
10032 			break;
10033 		case IPV6_TCLASS:
10034 			if (inlen != 0 && inlen != sizeof (int))
10035 				return (EINVAL);
10036 			if (checkonly)
10037 				break;
10038 
10039 			if (inlen == 0) {
10040 				ipp->ipp_fields &= ~IPPF_TCLASS;
10041 			} else {
10042 				if (*i1 > 255 || *i1 < -1)
10043 					return (EINVAL);
10044 				if (*i1 == -1) {
10045 					ipp->ipp_tclass = 0;
10046 					*i1 = 0;
10047 				} else {
10048 					ipp->ipp_tclass = *i1;
10049 				}
10050 				ipp->ipp_fields |= IPPF_TCLASS;
10051 			}
10052 			reterr = tcp_build_hdrs(q, tcp);
10053 			if (reterr != 0)
10054 				return (reterr);
10055 			break;
10056 		case IPV6_NEXTHOP:
10057 			/*
10058 			 * IP will verify that the nexthop is reachable
10059 			 * and fail for sticky options.
10060 			 */
10061 			if (inlen != 0 && inlen != sizeof (sin6_t))
10062 				return (EINVAL);
10063 			if (checkonly)
10064 				break;
10065 
10066 			if (inlen == 0) {
10067 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10068 			} else {
10069 				sin6_t *sin6 = (sin6_t *)invalp;
10070 
10071 				if (sin6->sin6_family != AF_INET6)
10072 					return (EAFNOSUPPORT);
10073 				if (IN6_IS_ADDR_V4MAPPED(
10074 				    &sin6->sin6_addr))
10075 					return (EADDRNOTAVAIL);
10076 				ipp->ipp_nexthop = sin6->sin6_addr;
10077 				if (!IN6_IS_ADDR_UNSPECIFIED(
10078 				    &ipp->ipp_nexthop))
10079 					ipp->ipp_fields |= IPPF_NEXTHOP;
10080 				else
10081 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10082 			}
10083 			reterr = tcp_build_hdrs(q, tcp);
10084 			if (reterr != 0)
10085 				return (reterr);
10086 			break;
10087 		case IPV6_HOPOPTS: {
10088 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10089 			/*
10090 			 * Sanity checks - minimum size, size a multiple of
10091 			 * eight bytes, and matching size passed in.
10092 			 */
10093 			if (inlen != 0 &&
10094 			    inlen != (8 * (hopts->ip6h_len + 1)))
10095 				return (EINVAL);
10096 
10097 			if (checkonly)
10098 				break;
10099 
10100 			if (inlen == 0) {
10101 				if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
10102 					kmem_free(ipp->ipp_hopopts,
10103 					    ipp->ipp_hopoptslen);
10104 					ipp->ipp_hopopts = NULL;
10105 					ipp->ipp_hopoptslen = 0;
10106 				}
10107 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10108 			} else {
10109 				reterr = tcp_pkt_set(invalp, inlen,
10110 				    (uchar_t **)&ipp->ipp_hopopts,
10111 				    &ipp->ipp_hopoptslen);
10112 				if (reterr != 0)
10113 					return (reterr);
10114 				ipp->ipp_fields |= IPPF_HOPOPTS;
10115 			}
10116 			reterr = tcp_build_hdrs(q, tcp);
10117 			if (reterr != 0)
10118 				return (reterr);
10119 			break;
10120 		}
10121 		case IPV6_RTHDRDSTOPTS: {
10122 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10123 
10124 			/*
10125 			 * Sanity checks - minimum size, size a multiple of
10126 			 * eight bytes, and matching size passed in.
10127 			 */
10128 			if (inlen != 0 &&
10129 			    inlen != (8 * (dopts->ip6d_len + 1)))
10130 				return (EINVAL);
10131 
10132 			if (checkonly)
10133 				break;
10134 
10135 			if (inlen == 0) {
10136 				if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
10137 					kmem_free(ipp->ipp_rtdstopts,
10138 					    ipp->ipp_rtdstoptslen);
10139 					ipp->ipp_rtdstopts = NULL;
10140 					ipp->ipp_rtdstoptslen = 0;
10141 				}
10142 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10143 			} else {
10144 				reterr = tcp_pkt_set(invalp, inlen,
10145 				    (uchar_t **)&ipp->ipp_rtdstopts,
10146 				    &ipp->ipp_rtdstoptslen);
10147 				if (reterr != 0)
10148 					return (reterr);
10149 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10150 			}
10151 			reterr = tcp_build_hdrs(q, tcp);
10152 			if (reterr != 0)
10153 				return (reterr);
10154 			break;
10155 		}
10156 		case IPV6_DSTOPTS: {
10157 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10158 
10159 			/*
10160 			 * Sanity checks - minimum size, size a multiple of
10161 			 * eight bytes, and matching size passed in.
10162 			 */
10163 			if (inlen != 0 &&
10164 			    inlen != (8 * (dopts->ip6d_len + 1)))
10165 				return (EINVAL);
10166 
10167 			if (checkonly)
10168 				break;
10169 
10170 			if (inlen == 0) {
10171 				if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
10172 					kmem_free(ipp->ipp_dstopts,
10173 					    ipp->ipp_dstoptslen);
10174 					ipp->ipp_dstopts = NULL;
10175 					ipp->ipp_dstoptslen = 0;
10176 				}
10177 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10178 			} else {
10179 				reterr = tcp_pkt_set(invalp, inlen,
10180 				    (uchar_t **)&ipp->ipp_dstopts,
10181 				    &ipp->ipp_dstoptslen);
10182 				if (reterr != 0)
10183 					return (reterr);
10184 				ipp->ipp_fields |= IPPF_DSTOPTS;
10185 			}
10186 			reterr = tcp_build_hdrs(q, tcp);
10187 			if (reterr != 0)
10188 				return (reterr);
10189 			break;
10190 		}
10191 		case IPV6_RTHDR: {
10192 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10193 
10194 			/*
10195 			 * Sanity checks - minimum size, size a multiple of
10196 			 * eight bytes, and matching size passed in.
10197 			 */
10198 			if (inlen != 0 &&
10199 			    inlen != (8 * (rt->ip6r_len + 1)))
10200 				return (EINVAL);
10201 
10202 			if (checkonly)
10203 				break;
10204 
10205 			if (inlen == 0) {
10206 				if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
10207 					kmem_free(ipp->ipp_rthdr,
10208 					    ipp->ipp_rthdrlen);
10209 					ipp->ipp_rthdr = NULL;
10210 					ipp->ipp_rthdrlen = 0;
10211 				}
10212 				ipp->ipp_fields &= ~IPPF_RTHDR;
10213 			} else {
10214 				reterr = tcp_pkt_set(invalp, inlen,
10215 				    (uchar_t **)&ipp->ipp_rthdr,
10216 				    &ipp->ipp_rthdrlen);
10217 				if (reterr != 0)
10218 					return (reterr);
10219 				ipp->ipp_fields |= IPPF_RTHDR;
10220 			}
10221 			reterr = tcp_build_hdrs(q, tcp);
10222 			if (reterr != 0)
10223 				return (reterr);
10224 			break;
10225 		}
10226 		case IPV6_V6ONLY:
10227 			if (!checkonly)
10228 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10229 			break;
10230 		case IPV6_USE_MIN_MTU:
10231 			if (inlen != sizeof (int))
10232 				return (EINVAL);
10233 
10234 			if (*i1 < -1 || *i1 > 1)
10235 				return (EINVAL);
10236 
10237 			if (checkonly)
10238 				break;
10239 
10240 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10241 			ipp->ipp_use_min_mtu = *i1;
10242 			break;
10243 		case IPV6_BOUND_PIF:
10244 			/* Handled at the IP level */
10245 			return (-EINVAL);
10246 		case IPV6_SEC_OPT:
10247 			/*
10248 			 * We should not allow policy setting after
10249 			 * we start listening for connections.
10250 			 */
10251 			if (tcp->tcp_state == TCPS_LISTEN) {
10252 				return (EINVAL);
10253 			} else {
10254 				/* Handled at the IP level */
10255 				return (-EINVAL);
10256 			}
10257 		case IPV6_SRC_PREFERENCES:
10258 			if (inlen != sizeof (uint32_t))
10259 				return (EINVAL);
10260 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10261 			    *(uint32_t *)invalp);
10262 			if (reterr != 0) {
10263 				*outlenp = 0;
10264 				return (reterr);
10265 			}
10266 			break;
10267 		default:
10268 			*outlenp = 0;
10269 			return (EINVAL);
10270 		}
10271 		break;
10272 	}		/* end IPPROTO_IPV6 */
10273 	default:
10274 		*outlenp = 0;
10275 		return (EINVAL);
10276 	}
10277 	/*
10278 	 * Common case of OK return with outval same as inval
10279 	 */
10280 	if (invalp != outvalp) {
10281 		/* don't trust bcopy for identical src/dst */
10282 		(void) bcopy(invalp, outvalp, inlen);
10283 	}
10284 	*outlenp = inlen;
10285 	return (0);
10286 }
10287 
10288 /*
10289  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10290  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10291  * headers, and the maximum size tcp header (to avoid reallocation
10292  * on the fly for additional tcp options).
10293  * Returns failure if can't allocate memory.
10294  */
10295 static int
10296 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
10297 {
10298 	char	*hdrs;
10299 	uint_t	hdrs_len;
10300 	ip6i_t	*ip6i;
10301 	char	buf[TCP_MAX_HDR_LENGTH];
10302 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10303 	in6_addr_t src, dst;
10304 
10305 	/*
10306 	 * save the existing tcp header and source/dest IP addresses
10307 	 */
10308 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10309 	src = tcp->tcp_ip6h->ip6_src;
10310 	dst = tcp->tcp_ip6h->ip6_dst;
10311 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10312 	ASSERT(hdrs_len != 0);
10313 	if (hdrs_len > tcp->tcp_iphc_len) {
10314 		/* Need to reallocate */
10315 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10316 		if (hdrs == NULL)
10317 			return (ENOMEM);
10318 		if (tcp->tcp_iphc != NULL) {
10319 			if (tcp->tcp_hdr_grown) {
10320 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10321 			} else {
10322 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10323 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10324 			}
10325 			tcp->tcp_iphc_len = 0;
10326 		}
10327 		ASSERT(tcp->tcp_iphc_len == 0);
10328 		tcp->tcp_iphc = hdrs;
10329 		tcp->tcp_iphc_len = hdrs_len;
10330 		tcp->tcp_hdr_grown = B_TRUE;
10331 	}
10332 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10333 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10334 
10335 	/* Set header fields not in ipp */
10336 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10337 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10338 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10339 	} else {
10340 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10341 	}
10342 	/*
10343 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10344 	 *
10345 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10346 	 */
10347 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10348 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10349 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10350 
10351 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10352 
10353 	tcp->tcp_ip6h->ip6_src = src;
10354 	tcp->tcp_ip6h->ip6_dst = dst;
10355 
10356 	/*
10357 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10358 	 * the default value for TCP.
10359 	 */
10360 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10361 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
10362 
10363 	/*
10364 	 * If we're setting extension headers after a connection
10365 	 * has been established, and if we have a routing header
10366 	 * among the extension headers, call ip_massage_options_v6 to
10367 	 * manipulate the routing header/ip6_dst set the checksum
10368 	 * difference in the tcp header template.
10369 	 * (This happens in tcp_connect_ipv6 if the routing header
10370 	 * is set prior to the connect.)
10371 	 * Set the tcp_sum to zero first in case we've cleared a
10372 	 * routing header or don't have one at all.
10373 	 */
10374 	tcp->tcp_sum = 0;
10375 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10376 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10377 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10378 		    (uint8_t *)tcp->tcp_tcph);
10379 		if (rth != NULL) {
10380 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10381 			    rth);
10382 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10383 			    (tcp->tcp_sum >> 16));
10384 		}
10385 	}
10386 
10387 	/* Try to get everything in a single mblk */
10388 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
10389 	return (0);
10390 }
10391 
10392 /*
10393  * Set optbuf and optlen for the option.
10394  * Allocate memory (if not already present).
10395  * Otherwise just point optbuf and optlen at invalp and inlen.
10396  * Returns failure if memory can not be allocated.
10397  */
10398 static int
10399 tcp_pkt_set(uchar_t *invalp, uint_t inlen, uchar_t **optbufp, uint_t *optlenp)
10400 {
10401 	uchar_t *optbuf;
10402 
10403 	if (inlen == *optlenp) {
10404 		/* Unchanged length - no need to realocate */
10405 		bcopy(invalp, *optbufp, inlen);
10406 		return (0);
10407 	}
10408 	if (inlen != 0) {
10409 		/* Allocate new buffer before free */
10410 		optbuf = kmem_alloc(inlen, KM_NOSLEEP);
10411 		if (optbuf == NULL)
10412 			return (ENOMEM);
10413 	} else {
10414 		optbuf = NULL;
10415 	}
10416 	/* Free old buffer */
10417 	if (*optlenp != 0)
10418 		kmem_free(*optbufp, *optlenp);
10419 
10420 	bcopy(invalp, optbuf, inlen);
10421 	*optbufp = optbuf;
10422 	*optlenp = inlen;
10423 	return (0);
10424 }
10425 
10426 
10427 /*
10428  * Use the outgoing IP header to create an IP_OPTIONS option the way
10429  * it was passed down from the application.
10430  */
10431 static int
10432 tcp_opt_get_user(ipha_t *ipha, uchar_t *buf)
10433 {
10434 	ipoptp_t	opts;
10435 	uchar_t		*opt;
10436 	uint8_t		optval;
10437 	uint8_t		optlen;
10438 	uint32_t	len = 0;
10439 	uchar_t	*buf1 = buf;
10440 
10441 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
10442 	len += IP_ADDR_LEN;
10443 	bzero(buf1, IP_ADDR_LEN);
10444 
10445 	for (optval = ipoptp_first(&opts, ipha);
10446 	    optval != IPOPT_EOL;
10447 	    optval = ipoptp_next(&opts)) {
10448 		opt = opts.ipoptp_cur;
10449 		optlen = opts.ipoptp_len;
10450 		switch (optval) {
10451 			int	off;
10452 		case IPOPT_SSRR:
10453 		case IPOPT_LSRR:
10454 
10455 			/*
10456 			 * Insert ipha_dst as the first entry in the source
10457 			 * route and move down the entries on step.
10458 			 * The last entry gets placed at buf1.
10459 			 */
10460 			buf[IPOPT_OPTVAL] = optval;
10461 			buf[IPOPT_OLEN] = optlen;
10462 			buf[IPOPT_OFFSET] = optlen;
10463 
10464 			off = optlen - IP_ADDR_LEN;
10465 			if (off < 0) {
10466 				/* No entries in source route */
10467 				break;
10468 			}
10469 			/* Last entry in source route */
10470 			bcopy(opt + off, buf1, IP_ADDR_LEN);
10471 			off -= IP_ADDR_LEN;
10472 
10473 			while (off > 0) {
10474 				bcopy(opt + off,
10475 				    buf + off + IP_ADDR_LEN,
10476 				    IP_ADDR_LEN);
10477 				off -= IP_ADDR_LEN;
10478 			}
10479 			/* ipha_dst into first slot */
10480 			bcopy(&ipha->ipha_dst,
10481 			    buf + off + IP_ADDR_LEN,
10482 			    IP_ADDR_LEN);
10483 			buf += optlen;
10484 			len += optlen;
10485 			break;
10486 		default:
10487 			bcopy(opt, buf, optlen);
10488 			buf += optlen;
10489 			len += optlen;
10490 			break;
10491 		}
10492 	}
10493 done:
10494 	/* Pad the resulting options */
10495 	while (len & 0x3) {
10496 		*buf++ = IPOPT_EOL;
10497 		len++;
10498 	}
10499 	return (len);
10500 }
10501 
10502 /*
10503  * Transfer any source route option from ipha to buf/dst in reversed form.
10504  */
10505 static int
10506 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10507 {
10508 	ipoptp_t	opts;
10509 	uchar_t		*opt;
10510 	uint8_t		optval;
10511 	uint8_t		optlen;
10512 	uint32_t	len = 0;
10513 
10514 	for (optval = ipoptp_first(&opts, ipha);
10515 	    optval != IPOPT_EOL;
10516 	    optval = ipoptp_next(&opts)) {
10517 		opt = opts.ipoptp_cur;
10518 		optlen = opts.ipoptp_len;
10519 		switch (optval) {
10520 			int	off1, off2;
10521 		case IPOPT_SSRR:
10522 		case IPOPT_LSRR:
10523 
10524 			/* Reverse source route */
10525 			/*
10526 			 * First entry should be the next to last one in the
10527 			 * current source route (the last entry is our
10528 			 * address.)
10529 			 * The last entry should be the final destination.
10530 			 */
10531 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10532 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10533 			off1 = IPOPT_MINOFF_SR - 1;
10534 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10535 			if (off2 < 0) {
10536 				/* No entries in source route */
10537 				break;
10538 			}
10539 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10540 			/*
10541 			 * Note: use src since ipha has not had its src
10542 			 * and dst reversed (it is in the state it was
10543 			 * received.
10544 			 */
10545 			bcopy(&ipha->ipha_src, buf + off2,
10546 			    IP_ADDR_LEN);
10547 			off2 -= IP_ADDR_LEN;
10548 
10549 			while (off2 > 0) {
10550 				bcopy(opt + off2, buf + off1,
10551 				    IP_ADDR_LEN);
10552 				off1 += IP_ADDR_LEN;
10553 				off2 -= IP_ADDR_LEN;
10554 			}
10555 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10556 			buf += optlen;
10557 			len += optlen;
10558 			break;
10559 		}
10560 	}
10561 done:
10562 	/* Pad the resulting options */
10563 	while (len & 0x3) {
10564 		*buf++ = IPOPT_EOL;
10565 		len++;
10566 	}
10567 	return (len);
10568 }
10569 
10570 
10571 /*
10572  * Extract and revert a source route from ipha (if any)
10573  * and then update the relevant fields in both tcp_t and the standard header.
10574  */
10575 static void
10576 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
10577 {
10578 	char	buf[TCP_MAX_HDR_LENGTH];
10579 	uint_t	tcph_len;
10580 	int	len;
10581 
10582 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
10583 	len = IPH_HDR_LENGTH(ipha);
10584 	if (len == IP_SIMPLE_HDR_LENGTH)
10585 		/* Nothing to do */
10586 		return;
10587 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
10588 	    (len & 0x3))
10589 		return;
10590 
10591 	tcph_len = tcp->tcp_tcp_hdr_len;
10592 	bcopy(tcp->tcp_tcph, buf, tcph_len);
10593 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
10594 		(tcp->tcp_ipha->ipha_dst & 0xffff);
10595 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
10596 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
10597 	len += IP_SIMPLE_HDR_LENGTH;
10598 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
10599 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
10600 	if ((int)tcp->tcp_sum < 0)
10601 		tcp->tcp_sum--;
10602 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
10603 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
10604 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
10605 	bcopy(buf, tcp->tcp_tcph, tcph_len);
10606 	tcp->tcp_ip_hdr_len = len;
10607 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10608 	    (IP_VERSION << 4) | (len >> 2);
10609 	len += tcph_len;
10610 	tcp->tcp_hdr_len = len;
10611 }
10612 
10613 /*
10614  * Copy the standard header into its new location,
10615  * lay in the new options and then update the relevant
10616  * fields in both tcp_t and the standard header.
10617  */
10618 static int
10619 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
10620 {
10621 	uint_t	tcph_len;
10622 	char	*ip_optp;
10623 	tcph_t	*new_tcph;
10624 
10625 	if (checkonly) {
10626 		/*
10627 		 * do not really set, just pretend to - T_CHECK
10628 		 */
10629 		if (len != 0) {
10630 			/*
10631 			 * there is value supplied, validate it as if
10632 			 * for a real set operation.
10633 			 */
10634 			if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10635 				return (EINVAL);
10636 		}
10637 		return (0);
10638 	}
10639 
10640 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10641 		return (EINVAL);
10642 
10643 	ip_optp = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
10644 	tcph_len = tcp->tcp_tcp_hdr_len;
10645 	new_tcph = (tcph_t *)(ip_optp + len);
10646 	ovbcopy((char *)tcp->tcp_tcph, (char *)new_tcph, tcph_len);
10647 	tcp->tcp_tcph = new_tcph;
10648 	bcopy(ptr, ip_optp, len);
10649 
10650 	len += IP_SIMPLE_HDR_LENGTH;
10651 
10652 	tcp->tcp_ip_hdr_len = len;
10653 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10654 		(IP_VERSION << 4) | (len >> 2);
10655 	len += tcph_len;
10656 	tcp->tcp_hdr_len = len;
10657 	if (!TCP_IS_DETACHED(tcp)) {
10658 		/* Always allocate room for all options. */
10659 		(void) mi_set_sth_wroff(tcp->tcp_rq,
10660 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
10661 	}
10662 	return (0);
10663 }
10664 
10665 /* Get callback routine passed to nd_load by tcp_param_register */
10666 /* ARGSUSED */
10667 static int
10668 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
10669 {
10670 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10671 
10672 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
10673 	return (0);
10674 }
10675 
10676 /*
10677  * Walk through the param array specified registering each element with the
10678  * named dispatch handler.
10679  */
10680 static boolean_t
10681 tcp_param_register(tcpparam_t *tcppa, int cnt)
10682 {
10683 	for (; cnt-- > 0; tcppa++) {
10684 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
10685 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
10686 			    tcp_param_get, tcp_param_set,
10687 			    (caddr_t)tcppa)) {
10688 				nd_free(&tcp_g_nd);
10689 				return (B_FALSE);
10690 			}
10691 		}
10692 	}
10693 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
10694 	    tcp_param_get, tcp_param_set_aligned,
10695 	    (caddr_t)&tcp_wroff_xtra_param)) {
10696 		nd_free(&tcp_g_nd);
10697 		return (B_FALSE);
10698 	}
10699 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
10700 	    tcp_param_get, tcp_param_set_aligned,
10701 	    (caddr_t)&tcp_mdt_head_param)) {
10702 		nd_free(&tcp_g_nd);
10703 		return (B_FALSE);
10704 	}
10705 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
10706 	    tcp_param_get, tcp_param_set_aligned,
10707 	    (caddr_t)&tcp_mdt_tail_param)) {
10708 		nd_free(&tcp_g_nd);
10709 		return (B_FALSE);
10710 	}
10711 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
10712 	    tcp_param_get, tcp_param_set,
10713 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
10714 		nd_free(&tcp_g_nd);
10715 		return (B_FALSE);
10716 	}
10717 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
10718 	    tcp_extra_priv_ports_get, NULL, NULL)) {
10719 		nd_free(&tcp_g_nd);
10720 		return (B_FALSE);
10721 	}
10722 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
10723 	    NULL, tcp_extra_priv_ports_add, NULL)) {
10724 		nd_free(&tcp_g_nd);
10725 		return (B_FALSE);
10726 	}
10727 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
10728 	    NULL, tcp_extra_priv_ports_del, NULL)) {
10729 		nd_free(&tcp_g_nd);
10730 		return (B_FALSE);
10731 	}
10732 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
10733 	    NULL)) {
10734 		nd_free(&tcp_g_nd);
10735 		return (B_FALSE);
10736 	}
10737 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
10738 	    NULL, NULL)) {
10739 		nd_free(&tcp_g_nd);
10740 		return (B_FALSE);
10741 	}
10742 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
10743 	    NULL, NULL)) {
10744 		nd_free(&tcp_g_nd);
10745 		return (B_FALSE);
10746 	}
10747 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
10748 	    NULL, NULL)) {
10749 		nd_free(&tcp_g_nd);
10750 		return (B_FALSE);
10751 	}
10752 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
10753 	    NULL, NULL)) {
10754 		nd_free(&tcp_g_nd);
10755 		return (B_FALSE);
10756 	}
10757 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
10758 	    tcp_host_param_set, NULL)) {
10759 		nd_free(&tcp_g_nd);
10760 		return (B_FALSE);
10761 	}
10762 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
10763 	    tcp_host_param_set_ipv6, NULL)) {
10764 		nd_free(&tcp_g_nd);
10765 		return (B_FALSE);
10766 	}
10767 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
10768 	    NULL)) {
10769 		nd_free(&tcp_g_nd);
10770 		return (B_FALSE);
10771 	}
10772 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
10773 	    tcp_reserved_port_list, NULL, NULL)) {
10774 		nd_free(&tcp_g_nd);
10775 		return (B_FALSE);
10776 	}
10777 	/*
10778 	 * Dummy ndd variables - only to convey obsolescence information
10779 	 * through printing of their name (no get or set routines)
10780 	 * XXX Remove in future releases ?
10781 	 */
10782 	if (!nd_load(&tcp_g_nd,
10783 	    "tcp_close_wait_interval(obsoleted - "
10784 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
10785 		nd_free(&tcp_g_nd);
10786 		return (B_FALSE);
10787 	}
10788 	return (B_TRUE);
10789 }
10790 
10791 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
10792 /* ARGSUSED */
10793 static int
10794 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
10795     cred_t *cr)
10796 {
10797 	long new_value;
10798 	tcpparam_t *tcppa = (tcpparam_t *)cp;
10799 
10800 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10801 	    new_value < tcppa->tcp_param_min ||
10802 	    new_value > tcppa->tcp_param_max) {
10803 		return (EINVAL);
10804 	}
10805 	/*
10806 	 * Need to make sure new_value is a multiple of 4.  If it is not,
10807 	 * round it up.  For future 64 bit requirement, we actually make it
10808 	 * a multiple of 8.
10809 	 */
10810 	if (new_value & 0x7) {
10811 		new_value = (new_value & ~0x7) + 0x8;
10812 	}
10813 	tcppa->tcp_param_val = new_value;
10814 	return (0);
10815 }
10816 
10817 /* Set callback routine passed to nd_load by tcp_param_register */
10818 /* ARGSUSED */
10819 static int
10820 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
10821 {
10822 	long	new_value;
10823 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10824 
10825 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10826 	    new_value < tcppa->tcp_param_min ||
10827 	    new_value > tcppa->tcp_param_max) {
10828 		return (EINVAL);
10829 	}
10830 	tcppa->tcp_param_val = new_value;
10831 	return (0);
10832 }
10833 
10834 /*
10835  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
10836  * is filled, return as much as we can.  The message passed in may be
10837  * multi-part, chained using b_cont.  "start" is the starting sequence
10838  * number for this piece.
10839  */
10840 static mblk_t *
10841 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
10842 {
10843 	uint32_t	end;
10844 	mblk_t		*mp1;
10845 	mblk_t		*mp2;
10846 	mblk_t		*next_mp;
10847 	uint32_t	u1;
10848 
10849 	/* Walk through all the new pieces. */
10850 	do {
10851 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10852 		    (uintptr_t)INT_MAX);
10853 		end = start + (int)(mp->b_wptr - mp->b_rptr);
10854 		next_mp = mp->b_cont;
10855 		if (start == end) {
10856 			/* Empty.  Blast it. */
10857 			freeb(mp);
10858 			continue;
10859 		}
10860 		mp->b_cont = NULL;
10861 		TCP_REASS_SET_SEQ(mp, start);
10862 		TCP_REASS_SET_END(mp, end);
10863 		mp1 = tcp->tcp_reass_tail;
10864 		if (!mp1) {
10865 			tcp->tcp_reass_tail = mp;
10866 			tcp->tcp_reass_head = mp;
10867 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
10868 			UPDATE_MIB(&tcp_mib,
10869 			    tcpInDataUnorderBytes, end - start);
10870 			continue;
10871 		}
10872 		/* New stuff completely beyond tail? */
10873 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
10874 			/* Link it on end. */
10875 			mp1->b_cont = mp;
10876 			tcp->tcp_reass_tail = mp;
10877 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
10878 			UPDATE_MIB(&tcp_mib,
10879 			    tcpInDataUnorderBytes, end - start);
10880 			continue;
10881 		}
10882 		mp1 = tcp->tcp_reass_head;
10883 		u1 = TCP_REASS_SEQ(mp1);
10884 		/* New stuff at the front? */
10885 		if (SEQ_LT(start, u1)) {
10886 			/* Yes... Check for overlap. */
10887 			mp->b_cont = mp1;
10888 			tcp->tcp_reass_head = mp;
10889 			tcp_reass_elim_overlap(tcp, mp);
10890 			continue;
10891 		}
10892 		/*
10893 		 * The new piece fits somewhere between the head and tail.
10894 		 * We find our slot, where mp1 precedes us and mp2 trails.
10895 		 */
10896 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
10897 			u1 = TCP_REASS_SEQ(mp2);
10898 			if (SEQ_LEQ(start, u1))
10899 				break;
10900 		}
10901 		/* Link ourselves in */
10902 		mp->b_cont = mp2;
10903 		mp1->b_cont = mp;
10904 
10905 		/* Trim overlap with following mblk(s) first */
10906 		tcp_reass_elim_overlap(tcp, mp);
10907 
10908 		/* Trim overlap with preceding mblk */
10909 		tcp_reass_elim_overlap(tcp, mp1);
10910 
10911 	} while (start = end, mp = next_mp);
10912 	mp1 = tcp->tcp_reass_head;
10913 	/* Anything ready to go? */
10914 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
10915 		return (NULL);
10916 	/* Eat what we can off the queue */
10917 	for (;;) {
10918 		mp = mp1->b_cont;
10919 		end = TCP_REASS_END(mp1);
10920 		TCP_REASS_SET_SEQ(mp1, 0);
10921 		TCP_REASS_SET_END(mp1, 0);
10922 		if (!mp) {
10923 			tcp->tcp_reass_tail = NULL;
10924 			break;
10925 		}
10926 		if (end != TCP_REASS_SEQ(mp)) {
10927 			mp1->b_cont = NULL;
10928 			break;
10929 		}
10930 		mp1 = mp;
10931 	}
10932 	mp1 = tcp->tcp_reass_head;
10933 	tcp->tcp_reass_head = mp;
10934 	return (mp1);
10935 }
10936 
10937 /* Eliminate any overlap that mp may have over later mblks */
10938 static void
10939 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
10940 {
10941 	uint32_t	end;
10942 	mblk_t		*mp1;
10943 	uint32_t	u1;
10944 
10945 	end = TCP_REASS_END(mp);
10946 	while ((mp1 = mp->b_cont) != NULL) {
10947 		u1 = TCP_REASS_SEQ(mp1);
10948 		if (!SEQ_GT(end, u1))
10949 			break;
10950 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
10951 			mp->b_wptr -= end - u1;
10952 			TCP_REASS_SET_END(mp, u1);
10953 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
10954 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
10955 			break;
10956 		}
10957 		mp->b_cont = mp1->b_cont;
10958 		TCP_REASS_SET_SEQ(mp1, 0);
10959 		TCP_REASS_SET_END(mp1, 0);
10960 		freeb(mp1);
10961 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
10962 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
10963 	}
10964 	if (!mp1)
10965 		tcp->tcp_reass_tail = mp;
10966 }
10967 
10968 /*
10969  * Send up all messages queued on tcp_rcv_list.
10970  */
10971 static uint_t
10972 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
10973 {
10974 	mblk_t *mp;
10975 	uint_t ret = 0;
10976 	uint_t thwin;
10977 #ifdef DEBUG
10978 	uint_t cnt = 0;
10979 #endif
10980 	/* Can't drain on an eager connection */
10981 	if (tcp->tcp_listener != NULL)
10982 		return (ret);
10983 
10984 	/*
10985 	 * Handle two cases here: we are currently fused or we were
10986 	 * previously fused and have some urgent data to be delivered
10987 	 * upstream.  The latter happens because we either ran out of
10988 	 * memory or were detached and therefore sending the SIGURG was
10989 	 * deferred until this point.  In either case we pass control
10990 	 * over to tcp_fuse_rcv_drain() since it may need to complete
10991 	 * some work.
10992 	 */
10993 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
10994 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
10995 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
10996 		    &tcp->tcp_fused_sigurg_mp))
10997 			return (ret);
10998 	}
10999 
11000 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11001 		tcp->tcp_rcv_list = mp->b_next;
11002 		mp->b_next = NULL;
11003 #ifdef DEBUG
11004 		cnt += msgdsize(mp);
11005 #endif
11006 		putnext(q, mp);
11007 	}
11008 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11009 	tcp->tcp_rcv_last_head = NULL;
11010 	tcp->tcp_rcv_last_tail = NULL;
11011 	tcp->tcp_rcv_cnt = 0;
11012 
11013 	/* Learn the latest rwnd information that we sent to the other side. */
11014 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11015 	    << tcp->tcp_rcv_ws;
11016 	/* This is peer's calculated send window (our receive window). */
11017 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11018 	/*
11019 	 * Increase the receive window to max.  But we need to do receiver
11020 	 * SWS avoidance.  This means that we need to check the increase of
11021 	 * of receive window is at least 1 MSS.
11022 	 */
11023 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11024 		/*
11025 		 * If the window that the other side knows is less than max
11026 		 * deferred acks segments, send an update immediately.
11027 		 */
11028 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11029 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11030 			ret = TH_ACK_NEEDED;
11031 		}
11032 		tcp->tcp_rwnd = q->q_hiwat;
11033 	}
11034 	/* No need for the push timer now. */
11035 	if (tcp->tcp_push_tid != 0) {
11036 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11037 		tcp->tcp_push_tid = 0;
11038 	}
11039 	return (ret);
11040 }
11041 
11042 /*
11043  * Queue data on tcp_rcv_list which is a b_next chain.
11044  * tcp_rcv_last_head/tail is the last element of this chain.
11045  * Each element of the chain is a b_cont chain.
11046  *
11047  * M_DATA messages are added to the current element.
11048  * Other messages are added as new (b_next) elements.
11049  */
11050 void
11051 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11052 {
11053 	ASSERT(seg_len == msgdsize(mp));
11054 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11055 
11056 	if (tcp->tcp_rcv_list == NULL) {
11057 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11058 		tcp->tcp_rcv_list = mp;
11059 		tcp->tcp_rcv_last_head = mp;
11060 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11061 		tcp->tcp_rcv_last_tail->b_cont = mp;
11062 	} else {
11063 		tcp->tcp_rcv_last_head->b_next = mp;
11064 		tcp->tcp_rcv_last_head = mp;
11065 	}
11066 
11067 	while (mp->b_cont)
11068 		mp = mp->b_cont;
11069 
11070 	tcp->tcp_rcv_last_tail = mp;
11071 	tcp->tcp_rcv_cnt += seg_len;
11072 	tcp->tcp_rwnd -= seg_len;
11073 }
11074 
11075 /*
11076  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11077  *
11078  * This is the default entry function into TCP on the read side. TCP is
11079  * always entered via squeue i.e. using squeue's for mutual exclusion.
11080  * When classifier does a lookup to find the tcp, it also puts a reference
11081  * on the conn structure associated so the tcp is guaranteed to exist
11082  * when we come here. We still need to check the state because it might
11083  * as well has been closed. The squeue processing function i.e. squeue_enter,
11084  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11085  * CONN_DEC_REF.
11086  *
11087  * Apart from the default entry point, IP also sends packets directly to
11088  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11089  * connections.
11090  */
11091 void
11092 tcp_input(void *arg, mblk_t *mp, void *arg2)
11093 {
11094 	conn_t	*connp = (conn_t *)arg;
11095 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11096 
11097 	/* arg2 is the sqp */
11098 	ASSERT(arg2 != NULL);
11099 	ASSERT(mp != NULL);
11100 
11101 	/*
11102 	 * Don't accept any input on a closed tcp as this TCP logically does
11103 	 * not exist on the system. Don't proceed further with this TCP.
11104 	 * For eg. this packet could trigger another close of this tcp
11105 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11106 	 * tcp_clean_death / tcp_closei_local must be called at most once
11107 	 * on a TCP. In this case we need to refeed the packet into the
11108 	 * classifier and figure out where the packet should go. Need to
11109 	 * preserve the recv_ill somehow. Until we figure that out, for
11110 	 * now just drop the packet if we can't classify the packet.
11111 	 */
11112 	if (tcp->tcp_state == TCPS_CLOSED ||
11113 	    tcp->tcp_state == TCPS_BOUND) {
11114 		conn_t	*new_connp;
11115 
11116 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11117 		if (new_connp != NULL) {
11118 			tcp_reinput(new_connp, mp, arg2);
11119 			return;
11120 		}
11121 		/* We failed to classify. For now just drop the packet */
11122 		freemsg(mp);
11123 		return;
11124 	}
11125 
11126 	if (DB_TYPE(mp) == M_DATA)
11127 		tcp_rput_data(connp, mp, arg2);
11128 	else
11129 		tcp_rput_common(tcp, mp);
11130 }
11131 
11132 /*
11133  * The read side put procedure.
11134  * The packets passed up by ip are assume to be aligned according to
11135  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11136  */
11137 static void
11138 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11139 {
11140 	/*
11141 	 * tcp_rput_data() does not expect M_CTL except for the case
11142 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11143 	 * type. Need to make sure that any other M_CTLs don't make
11144 	 * it to tcp_rput_data since it is not expecting any and doesn't
11145 	 * check for it.
11146 	 */
11147 	if (DB_TYPE(mp) == M_CTL) {
11148 		switch (*(uint32_t *)(mp->b_rptr)) {
11149 		case TCP_IOC_ABORT_CONN:
11150 			/*
11151 			 * Handle connection abort request.
11152 			 */
11153 			tcp_ioctl_abort_handler(tcp, mp);
11154 			return;
11155 		case IPSEC_IN:
11156 			/*
11157 			 * Only secure icmp arrive in TCP and they
11158 			 * don't go through data path.
11159 			 */
11160 			tcp_icmp_error(tcp, mp);
11161 			return;
11162 		case IN_PKTINFO:
11163 			/*
11164 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11165 			 * sockets that are receiving IPv4 traffic. tcp
11166 			 */
11167 			ASSERT(tcp->tcp_family == AF_INET6);
11168 			ASSERT(tcp->tcp_ipv6_recvancillary &
11169 			    TCP_IPV6_RECVPKTINFO);
11170 			tcp_rput_data(tcp->tcp_connp, mp,
11171 			    tcp->tcp_connp->conn_sqp);
11172 			return;
11173 		case MDT_IOC_INFO_UPDATE:
11174 			/*
11175 			 * Handle Multidata information update; the
11176 			 * following routine will free the message.
11177 			 */
11178 			if (tcp->tcp_connp->conn_mdt_ok) {
11179 				tcp_mdt_update(tcp,
11180 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11181 				    B_FALSE);
11182 			}
11183 			freemsg(mp);
11184 			return;
11185 		default:
11186 			break;
11187 		}
11188 	}
11189 
11190 	/* No point processing the message if tcp is already closed */
11191 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11192 		freemsg(mp);
11193 		return;
11194 	}
11195 
11196 	tcp_rput_other(tcp, mp);
11197 }
11198 
11199 
11200 /* The minimum of smoothed mean deviation in RTO calculation. */
11201 #define	TCP_SD_MIN	400
11202 
11203 /*
11204  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11205  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11206  * are the same as those in Appendix A.2 of that paper.
11207  *
11208  * m = new measurement
11209  * sa = smoothed RTT average (8 * average estimates).
11210  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11211  */
11212 static void
11213 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11214 {
11215 	long m = TICK_TO_MSEC(rtt);
11216 	clock_t sa = tcp->tcp_rtt_sa;
11217 	clock_t sv = tcp->tcp_rtt_sd;
11218 	clock_t rto;
11219 
11220 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
11221 	tcp->tcp_rtt_update++;
11222 
11223 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11224 	if (sa != 0) {
11225 		/*
11226 		 * Update average estimator:
11227 		 *	new rtt = 7/8 old rtt + 1/8 Error
11228 		 */
11229 
11230 		/* m is now Error in estimate. */
11231 		m -= sa >> 3;
11232 		if ((sa += m) <= 0) {
11233 			/*
11234 			 * Don't allow the smoothed average to be negative.
11235 			 * We use 0 to denote reinitialization of the
11236 			 * variables.
11237 			 */
11238 			sa = 1;
11239 		}
11240 
11241 		/*
11242 		 * Update deviation estimator:
11243 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11244 		 */
11245 		if (m < 0)
11246 			m = -m;
11247 		m -= sv >> 2;
11248 		sv += m;
11249 	} else {
11250 		/*
11251 		 * This follows BSD's implementation.  So the reinitialized
11252 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11253 		 * link is bandwidth dominated, doubling the window size
11254 		 * during slow start means doubling the RTT.  We want to be
11255 		 * more conservative when we reinitialize our estimates.  3
11256 		 * is just a convenient number.
11257 		 */
11258 		sa = m << 3;
11259 		sv = m << 1;
11260 	}
11261 	if (sv < TCP_SD_MIN) {
11262 		/*
11263 		 * We do not know that if sa captures the delay ACK
11264 		 * effect as in a long train of segments, a receiver
11265 		 * does not delay its ACKs.  So set the minimum of sv
11266 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11267 		 * of BSD DATO.  That means the minimum of mean
11268 		 * deviation is 100 ms.
11269 		 *
11270 		 */
11271 		sv = TCP_SD_MIN;
11272 	}
11273 	tcp->tcp_rtt_sa = sa;
11274 	tcp->tcp_rtt_sd = sv;
11275 	/*
11276 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11277 	 *
11278 	 * Add tcp_rexmit_interval extra in case of extreme environment
11279 	 * where the algorithm fails to work.  The default value of
11280 	 * tcp_rexmit_interval_extra should be 0.
11281 	 *
11282 	 * As we use a finer grained clock than BSD and update
11283 	 * RTO for every ACKs, add in another .25 of RTT to the
11284 	 * deviation of RTO to accomodate burstiness of 1/4 of
11285 	 * window size.
11286 	 */
11287 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
11288 
11289 	if (rto > tcp_rexmit_interval_max) {
11290 		tcp->tcp_rto = tcp_rexmit_interval_max;
11291 	} else if (rto < tcp_rexmit_interval_min) {
11292 		tcp->tcp_rto = tcp_rexmit_interval_min;
11293 	} else {
11294 		tcp->tcp_rto = rto;
11295 	}
11296 
11297 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11298 	tcp->tcp_timer_backoff = 0;
11299 }
11300 
11301 /*
11302  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11303  * send queue which starts at the given seq. no.
11304  *
11305  * Parameters:
11306  *	tcp_t *tcp: the tcp instance pointer.
11307  *	uint32_t seq: the starting seq. no of the requested segment.
11308  *	int32_t *off: after the execution, *off will be the offset to
11309  *		the returned mblk which points to the requested seq no.
11310  *		It is the caller's responsibility to send in a non-null off.
11311  *
11312  * Return:
11313  *	A mblk_t pointer pointing to the requested segment in send queue.
11314  */
11315 static mblk_t *
11316 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11317 {
11318 	int32_t	cnt;
11319 	mblk_t	*mp;
11320 
11321 	/* Defensive coding.  Make sure we don't send incorrect data. */
11322 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
11323 		return (NULL);
11324 
11325 	cnt = seq - tcp->tcp_suna;
11326 	mp = tcp->tcp_xmit_head;
11327 	while (cnt > 0 && mp != NULL) {
11328 		cnt -= mp->b_wptr - mp->b_rptr;
11329 		if (cnt < 0) {
11330 			cnt += mp->b_wptr - mp->b_rptr;
11331 			break;
11332 		}
11333 		mp = mp->b_cont;
11334 	}
11335 	ASSERT(mp != NULL);
11336 	*off = cnt;
11337 	return (mp);
11338 }
11339 
11340 /*
11341  * This function handles all retransmissions if SACK is enabled for this
11342  * connection.  First it calculates how many segments can be retransmitted
11343  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11344  * segments.  A segment is eligible if sack_cnt for that segment is greater
11345  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11346  * all eligible segments, it checks to see if TCP can send some new segments
11347  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11348  *
11349  * Parameters:
11350  *	tcp_t *tcp: the tcp structure of the connection.
11351  *	uint_t *flags: in return, appropriate value will be set for
11352  *	tcp_rput_data().
11353  */
11354 static void
11355 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11356 {
11357 	notsack_blk_t	*notsack_blk;
11358 	int32_t		usable_swnd;
11359 	int32_t		mss;
11360 	uint32_t	seg_len;
11361 	mblk_t		*xmit_mp;
11362 
11363 	ASSERT(tcp->tcp_sack_info != NULL);
11364 	ASSERT(tcp->tcp_notsack_list != NULL);
11365 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11366 
11367 	/* Defensive coding in case there is a bug... */
11368 	if (tcp->tcp_notsack_list == NULL) {
11369 		return;
11370 	}
11371 	notsack_blk = tcp->tcp_notsack_list;
11372 	mss = tcp->tcp_mss;
11373 
11374 	/*
11375 	 * Limit the num of outstanding data in the network to be
11376 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11377 	 */
11378 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11379 
11380 	/* At least retransmit 1 MSS of data. */
11381 	if (usable_swnd <= 0) {
11382 		usable_swnd = mss;
11383 	}
11384 
11385 	/* Make sure no new RTT samples will be taken. */
11386 	tcp->tcp_csuna = tcp->tcp_snxt;
11387 
11388 	notsack_blk = tcp->tcp_notsack_list;
11389 	while (usable_swnd > 0) {
11390 		mblk_t		*snxt_mp, *tmp_mp;
11391 		tcp_seq		begin = tcp->tcp_sack_snxt;
11392 		tcp_seq		end;
11393 		int32_t		off;
11394 
11395 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11396 			if (SEQ_GT(notsack_blk->end, begin) &&
11397 			    (notsack_blk->sack_cnt >=
11398 			    tcp_dupack_fast_retransmit)) {
11399 				end = notsack_blk->end;
11400 				if (SEQ_LT(begin, notsack_blk->begin)) {
11401 					begin = notsack_blk->begin;
11402 				}
11403 				break;
11404 			}
11405 		}
11406 		/*
11407 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11408 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11409 		 * set to tcp_cwnd_ssthresh.
11410 		 */
11411 		if (notsack_blk == NULL) {
11412 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11413 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11414 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11415 				ASSERT(tcp->tcp_cwnd > 0);
11416 				return;
11417 			} else {
11418 				usable_swnd = usable_swnd / mss;
11419 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11420 				    MAX(usable_swnd * mss, mss);
11421 				*flags |= TH_XMIT_NEEDED;
11422 				return;
11423 			}
11424 		}
11425 
11426 		/*
11427 		 * Note that we may send more than usable_swnd allows here
11428 		 * because of round off, but no more than 1 MSS of data.
11429 		 */
11430 		seg_len = end - begin;
11431 		if (seg_len > mss)
11432 			seg_len = mss;
11433 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11434 		ASSERT(snxt_mp != NULL);
11435 		/* This should not happen.  Defensive coding again... */
11436 		if (snxt_mp == NULL) {
11437 			return;
11438 		}
11439 
11440 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11441 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11442 		if (xmit_mp == NULL)
11443 			return;
11444 
11445 		usable_swnd -= seg_len;
11446 		tcp->tcp_pipe += seg_len;
11447 		tcp->tcp_sack_snxt = begin + seg_len;
11448 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
11449 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11450 
11451 		/*
11452 		 * Update the send timestamp to avoid false retransmission.
11453 		 */
11454 		snxt_mp->b_prev = (mblk_t *)lbolt;
11455 
11456 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
11457 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
11458 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
11459 		/*
11460 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11461 		 * This happens when new data sent during fast recovery is
11462 		 * also lost.  If TCP retransmits those new data, it needs
11463 		 * to extend SACK recover phase to avoid starting another
11464 		 * fast retransmit/recovery unnecessarily.
11465 		 */
11466 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11467 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11468 		}
11469 	}
11470 }
11471 
11472 /*
11473  * This function handles policy checking at TCP level for non-hard_bound/
11474  * detached connections.
11475  */
11476 static boolean_t
11477 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
11478     boolean_t secure, boolean_t mctl_present)
11479 {
11480 	ipsec_latch_t *ipl = NULL;
11481 	ipsec_action_t *act = NULL;
11482 	mblk_t *data_mp;
11483 	ipsec_in_t *ii;
11484 	const char *reason;
11485 	kstat_named_t *counter;
11486 
11487 	ASSERT(mctl_present || !secure);
11488 
11489 	ASSERT((ipha == NULL && ip6h != NULL) ||
11490 	    (ip6h == NULL && ipha != NULL));
11491 
11492 	/*
11493 	 * We don't necessarily have an ipsec_in_act action to verify
11494 	 * policy because of assymetrical policy where we have only
11495 	 * outbound policy and no inbound policy (possible with global
11496 	 * policy).
11497 	 */
11498 	if (!secure) {
11499 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
11500 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
11501 			return (B_TRUE);
11502 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
11503 		    "tcp_check_policy", ipha, ip6h, secure);
11504 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11505 		    &ipdrops_tcp_clear, &tcp_dropper);
11506 		return (B_FALSE);
11507 	}
11508 
11509 	/*
11510 	 * We have a secure packet.
11511 	 */
11512 	if (act == NULL) {
11513 		ipsec_log_policy_failure(tcp->tcp_wq,
11514 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
11515 		    secure);
11516 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11517 		    &ipdrops_tcp_secure, &tcp_dropper);
11518 		return (B_FALSE);
11519 	}
11520 
11521 	/*
11522 	 * XXX This whole routine is currently incorrect.  ipl should
11523 	 * be set to the latch pointer, but is currently not set, so
11524 	 * we initialize it to NULL to avoid picking up random garbage.
11525 	 */
11526 	if (ipl == NULL)
11527 		return (B_TRUE);
11528 
11529 	data_mp = first_mp->b_cont;
11530 
11531 	ii = (ipsec_in_t *)first_mp->b_rptr;
11532 
11533 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
11534 	    &counter)) {
11535 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
11536 		return (B_TRUE);
11537 	}
11538 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
11539 	    "tcp inbound policy mismatch: %s, packet dropped\n",
11540 	    reason);
11541 	BUMP_MIB(&ip_mib, ipsecInFailed);
11542 
11543 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
11544 	return (B_FALSE);
11545 }
11546 
11547 /*
11548  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
11549  * retransmission after a timeout.
11550  *
11551  * To limit the number of duplicate segments, we limit the number of segment
11552  * to be sent in one time to tcp_snd_burst, the burst variable.
11553  */
11554 static void
11555 tcp_ss_rexmit(tcp_t *tcp)
11556 {
11557 	uint32_t	snxt;
11558 	uint32_t	smax;
11559 	int32_t		win;
11560 	int32_t		mss;
11561 	int32_t		off;
11562 	int32_t		burst = tcp->tcp_snd_burst;
11563 	mblk_t		*snxt_mp;
11564 
11565 	/*
11566 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
11567 	 * all unack'ed segments.
11568 	 */
11569 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
11570 		smax = tcp->tcp_rexmit_max;
11571 		snxt = tcp->tcp_rexmit_nxt;
11572 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
11573 			snxt = tcp->tcp_suna;
11574 		}
11575 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
11576 		win -= snxt - tcp->tcp_suna;
11577 		mss = tcp->tcp_mss;
11578 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
11579 
11580 		while (SEQ_LT(snxt, smax) && (win > 0) &&
11581 		    (burst > 0) && (snxt_mp != NULL)) {
11582 			mblk_t	*xmit_mp;
11583 			mblk_t	*old_snxt_mp = snxt_mp;
11584 			uint32_t cnt = mss;
11585 
11586 			if (win < cnt) {
11587 				cnt = win;
11588 			}
11589 			if (SEQ_GT(snxt + cnt, smax)) {
11590 				cnt = smax - snxt;
11591 			}
11592 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
11593 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
11594 			if (xmit_mp == NULL)
11595 				return;
11596 
11597 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11598 
11599 			snxt += cnt;
11600 			win -= cnt;
11601 			/*
11602 			 * Update the send timestamp to avoid false
11603 			 * retransmission.
11604 			 */
11605 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
11606 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
11607 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
11608 
11609 			tcp->tcp_rexmit_nxt = snxt;
11610 			burst--;
11611 		}
11612 		/*
11613 		 * If we have transmitted all we have at the time
11614 		 * we started the retranmission, we can leave
11615 		 * the rest of the job to tcp_wput_data().  But we
11616 		 * need to check the send window first.  If the
11617 		 * win is not 0, go on with tcp_wput_data().
11618 		 */
11619 		if (SEQ_LT(snxt, smax) || win == 0) {
11620 			return;
11621 		}
11622 	}
11623 	/* Only call tcp_wput_data() if there is data to be sent. */
11624 	if (tcp->tcp_unsent) {
11625 		tcp_wput_data(tcp, NULL, B_FALSE);
11626 	}
11627 }
11628 
11629 /*
11630  * Process all TCP option in SYN segment.  Note that this function should
11631  * be called after tcp_adapt_ire() is called so that the necessary info
11632  * from IRE is already set in the tcp structure.
11633  *
11634  * This function sets up the correct tcp_mss value according to the
11635  * MSS option value and our header size.  It also sets up the window scale
11636  * and timestamp values, and initialize SACK info blocks.  But it does not
11637  * change receive window size after setting the tcp_mss value.  The caller
11638  * should do the appropriate change.
11639  */
11640 void
11641 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
11642 {
11643 	int options;
11644 	tcp_opt_t tcpopt;
11645 	uint32_t mss_max;
11646 	char *tmp_tcph;
11647 
11648 	tcpopt.tcp = NULL;
11649 	options = tcp_parse_options(tcph, &tcpopt);
11650 
11651 	/*
11652 	 * Process MSS option.  Note that MSS option value does not account
11653 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
11654 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
11655 	 * IPv6.
11656 	 */
11657 	if (!(options & TCP_OPT_MSS_PRESENT)) {
11658 		if (tcp->tcp_ipversion == IPV4_VERSION)
11659 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
11660 		else
11661 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
11662 	} else {
11663 		if (tcp->tcp_ipversion == IPV4_VERSION)
11664 			mss_max = tcp_mss_max_ipv4;
11665 		else
11666 			mss_max = tcp_mss_max_ipv6;
11667 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
11668 			tcpopt.tcp_opt_mss = tcp_mss_min;
11669 		else if (tcpopt.tcp_opt_mss > mss_max)
11670 			tcpopt.tcp_opt_mss = mss_max;
11671 	}
11672 
11673 	/* Process Window Scale option. */
11674 	if (options & TCP_OPT_WSCALE_PRESENT) {
11675 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
11676 		tcp->tcp_snd_ws_ok = B_TRUE;
11677 	} else {
11678 		tcp->tcp_snd_ws = B_FALSE;
11679 		tcp->tcp_snd_ws_ok = B_FALSE;
11680 		tcp->tcp_rcv_ws = B_FALSE;
11681 	}
11682 
11683 	/* Process Timestamp option. */
11684 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
11685 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
11686 		tmp_tcph = (char *)tcp->tcp_tcph;
11687 
11688 		tcp->tcp_snd_ts_ok = B_TRUE;
11689 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
11690 		tcp->tcp_last_rcv_lbolt = lbolt64;
11691 		ASSERT(OK_32PTR(tmp_tcph));
11692 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
11693 
11694 		/* Fill in our template header with basic timestamp option. */
11695 		tmp_tcph += tcp->tcp_tcp_hdr_len;
11696 		tmp_tcph[0] = TCPOPT_NOP;
11697 		tmp_tcph[1] = TCPOPT_NOP;
11698 		tmp_tcph[2] = TCPOPT_TSTAMP;
11699 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
11700 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
11701 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
11702 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
11703 	} else {
11704 		tcp->tcp_snd_ts_ok = B_FALSE;
11705 	}
11706 
11707 	/*
11708 	 * Process SACK options.  If SACK is enabled for this connection,
11709 	 * then allocate the SACK info structure.  Note the following ways
11710 	 * when tcp_snd_sack_ok is set to true.
11711 	 *
11712 	 * For active connection: in tcp_adapt_ire() called in
11713 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
11714 	 * is checked.
11715 	 *
11716 	 * For passive connection: in tcp_adapt_ire() called in
11717 	 * tcp_accept_comm().
11718 	 *
11719 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
11720 	 * That check makes sure that if we did not send a SACK OK option,
11721 	 * we will not enable SACK for this connection even though the other
11722 	 * side sends us SACK OK option.  For active connection, the SACK
11723 	 * info structure has already been allocated.  So we need to free
11724 	 * it if SACK is disabled.
11725 	 */
11726 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
11727 	    (tcp->tcp_snd_sack_ok ||
11728 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
11729 		/* This should be true only in the passive case. */
11730 		if (tcp->tcp_sack_info == NULL) {
11731 			ASSERT(TCP_IS_DETACHED(tcp));
11732 			tcp->tcp_sack_info =
11733 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
11734 		}
11735 		if (tcp->tcp_sack_info == NULL) {
11736 			tcp->tcp_snd_sack_ok = B_FALSE;
11737 		} else {
11738 			tcp->tcp_snd_sack_ok = B_TRUE;
11739 			if (tcp->tcp_snd_ts_ok) {
11740 				tcp->tcp_max_sack_blk = 3;
11741 			} else {
11742 				tcp->tcp_max_sack_blk = 4;
11743 			}
11744 		}
11745 	} else {
11746 		/*
11747 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
11748 		 * no SACK info will be used for this
11749 		 * connection.  This assumes that SACK usage
11750 		 * permission is negotiated.  This may need
11751 		 * to be changed once this is clarified.
11752 		 */
11753 		if (tcp->tcp_sack_info != NULL) {
11754 			ASSERT(tcp->tcp_notsack_list == NULL);
11755 			kmem_cache_free(tcp_sack_info_cache,
11756 			    tcp->tcp_sack_info);
11757 			tcp->tcp_sack_info = NULL;
11758 		}
11759 		tcp->tcp_snd_sack_ok = B_FALSE;
11760 	}
11761 
11762 	/*
11763 	 * Now we know the exact TCP/IP header length, subtract
11764 	 * that from tcp_mss to get our side's MSS.
11765 	 */
11766 	tcp->tcp_mss -= tcp->tcp_hdr_len;
11767 	/*
11768 	 * Here we assume that the other side's header size will be equal to
11769 	 * our header size.  We calculate the real MSS accordingly.  Need to
11770 	 * take into additional stuffs IPsec puts in.
11771 	 *
11772 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
11773 	 */
11774 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
11775 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
11776 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
11777 
11778 	/*
11779 	 * Set MSS to the smaller one of both ends of the connection.
11780 	 * We should not have called tcp_mss_set() before, but our
11781 	 * side of the MSS should have been set to a proper value
11782 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
11783 	 * STREAM head parameters properly.
11784 	 *
11785 	 * If we have a larger-than-16-bit window but the other side
11786 	 * didn't want to do window scale, tcp_rwnd_set() will take
11787 	 * care of that.
11788 	 */
11789 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
11790 }
11791 
11792 /*
11793  * Sends the T_CONN_IND to the listener. The caller calls this
11794  * functions via squeue to get inside the listener's perimeter
11795  * once the 3 way hand shake is done a T_CONN_IND needs to be
11796  * sent. As an optimization, the caller can call this directly
11797  * if listener's perimeter is same as eager's.
11798  */
11799 /* ARGSUSED */
11800 void
11801 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
11802 {
11803 	conn_t			*lconnp = (conn_t *)arg;
11804 	tcp_t			*listener = lconnp->conn_tcp;
11805 	tcp_t			*tcp;
11806 	struct T_conn_ind	*conn_ind;
11807 	ipaddr_t 		*addr_cache;
11808 	boolean_t		need_send_conn_ind = B_FALSE;
11809 
11810 	/* retrieve the eager */
11811 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
11812 	ASSERT(conn_ind->OPT_offset != 0 &&
11813 	    conn_ind->OPT_length == sizeof (intptr_t));
11814 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
11815 		conn_ind->OPT_length);
11816 
11817 	/*
11818 	 * TLI/XTI applications will get confused by
11819 	 * sending eager as an option since it violates
11820 	 * the option semantics. So remove the eager as
11821 	 * option since TLI/XTI app doesn't need it anyway.
11822 	 */
11823 	if (!TCP_IS_SOCKET(listener)) {
11824 		conn_ind->OPT_length = 0;
11825 		conn_ind->OPT_offset = 0;
11826 	}
11827 	if (listener->tcp_state == TCPS_CLOSED ||
11828 	    TCP_IS_DETACHED(listener)) {
11829 		/*
11830 		 * If listener has closed, it would have caused a
11831 		 * a cleanup/blowoff to happen for the eager. We
11832 		 * just need to return.
11833 		 */
11834 		freemsg(mp);
11835 		return;
11836 	}
11837 
11838 
11839 	/*
11840 	 * if the conn_req_q is full defer passing up the
11841 	 * T_CONN_IND until space is availabe after t_accept()
11842 	 * processing
11843 	 */
11844 	mutex_enter(&listener->tcp_eager_lock);
11845 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
11846 		tcp_t *tail;
11847 
11848 		/*
11849 		 * The eager already has an extra ref put in tcp_rput_data
11850 		 * so that it stays till accept comes back even though it
11851 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
11852 		 */
11853 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
11854 		listener->tcp_conn_req_cnt_q0--;
11855 		listener->tcp_conn_req_cnt_q++;
11856 
11857 		/* Move from SYN_RCVD to ESTABLISHED list  */
11858 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
11859 		    tcp->tcp_eager_prev_q0;
11860 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
11861 		    tcp->tcp_eager_next_q0;
11862 		tcp->tcp_eager_prev_q0 = NULL;
11863 		tcp->tcp_eager_next_q0 = NULL;
11864 
11865 		/*
11866 		 * Insert at end of the queue because sockfs
11867 		 * sends down T_CONN_RES in chronological
11868 		 * order. Leaving the older conn indications
11869 		 * at front of the queue helps reducing search
11870 		 * time.
11871 		 */
11872 		tail = listener->tcp_eager_last_q;
11873 		if (tail != NULL)
11874 			tail->tcp_eager_next_q = tcp;
11875 		else
11876 			listener->tcp_eager_next_q = tcp;
11877 		listener->tcp_eager_last_q = tcp;
11878 		tcp->tcp_eager_next_q = NULL;
11879 		/*
11880 		 * Delay sending up the T_conn_ind until we are
11881 		 * done with the eager. Once we have have sent up
11882 		 * the T_conn_ind, the accept can potentially complete
11883 		 * any time and release the refhold we have on the eager.
11884 		 */
11885 		need_send_conn_ind = B_TRUE;
11886 	} else {
11887 		/*
11888 		 * Defer connection on q0 and set deferred
11889 		 * connection bit true
11890 		 */
11891 		tcp->tcp_conn_def_q0 = B_TRUE;
11892 
11893 		/* take tcp out of q0 ... */
11894 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
11895 		    tcp->tcp_eager_next_q0;
11896 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
11897 		    tcp->tcp_eager_prev_q0;
11898 
11899 		/* ... and place it at the end of q0 */
11900 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
11901 		tcp->tcp_eager_next_q0 = listener;
11902 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
11903 		listener->tcp_eager_prev_q0 = tcp;
11904 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
11905 	}
11906 
11907 	/* we have timed out before */
11908 	if (tcp->tcp_syn_rcvd_timeout != 0) {
11909 		tcp->tcp_syn_rcvd_timeout = 0;
11910 		listener->tcp_syn_rcvd_timeout--;
11911 		if (listener->tcp_syn_defense &&
11912 		    listener->tcp_syn_rcvd_timeout <=
11913 		    (tcp_conn_req_max_q0 >> 5) &&
11914 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
11915 			listener->tcp_last_rcv_lbolt)) {
11916 			/*
11917 			 * Turn off the defense mode if we
11918 			 * believe the SYN attack is over.
11919 			 */
11920 			listener->tcp_syn_defense = B_FALSE;
11921 			if (listener->tcp_ip_addr_cache) {
11922 				kmem_free((void *)listener->tcp_ip_addr_cache,
11923 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
11924 				listener->tcp_ip_addr_cache = NULL;
11925 			}
11926 		}
11927 	}
11928 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
11929 	if (addr_cache != NULL) {
11930 		/*
11931 		 * We have finished a 3-way handshake with this
11932 		 * remote host. This proves the IP addr is good.
11933 		 * Cache it!
11934 		 */
11935 		addr_cache[IP_ADDR_CACHE_HASH(
11936 			tcp->tcp_remote)] = tcp->tcp_remote;
11937 	}
11938 	mutex_exit(&listener->tcp_eager_lock);
11939 	if (need_send_conn_ind)
11940 		putnext(listener->tcp_rq, mp);
11941 }
11942 
11943 mblk_t *
11944 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
11945     uint_t *ifindexp, ip6_pkt_t *ippp)
11946 {
11947 	in_pktinfo_t	*pinfo;
11948 	ip6_t		*ip6h;
11949 	uchar_t		*rptr;
11950 	mblk_t		*first_mp = mp;
11951 	boolean_t	mctl_present = B_FALSE;
11952 	uint_t 		ifindex = 0;
11953 	ip6_pkt_t	ipp;
11954 	uint_t		ipvers;
11955 	uint_t		ip_hdr_len;
11956 
11957 	rptr = mp->b_rptr;
11958 	ASSERT(OK_32PTR(rptr));
11959 	ASSERT(tcp != NULL);
11960 	ipp.ipp_fields = 0;
11961 
11962 	switch DB_TYPE(mp) {
11963 	case M_CTL:
11964 		mp = mp->b_cont;
11965 		if (mp == NULL) {
11966 			freemsg(first_mp);
11967 			return (NULL);
11968 		}
11969 		if (DB_TYPE(mp) != M_DATA) {
11970 			freemsg(first_mp);
11971 			return (NULL);
11972 		}
11973 		mctl_present = B_TRUE;
11974 		break;
11975 	case M_DATA:
11976 		break;
11977 	default:
11978 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
11979 		freemsg(mp);
11980 		return (NULL);
11981 	}
11982 	ipvers = IPH_HDR_VERSION(rptr);
11983 	if (ipvers == IPV4_VERSION) {
11984 		if (tcp == NULL) {
11985 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
11986 			goto done;
11987 		}
11988 
11989 		ipp.ipp_fields |= IPPF_HOPLIMIT;
11990 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
11991 
11992 		/*
11993 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
11994 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
11995 		 */
11996 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
11997 		    mctl_present) {
11998 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
11999 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
12000 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
12001 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
12002 				ipp.ipp_fields |= IPPF_IFINDEX;
12003 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
12004 				ifindex = pinfo->in_pkt_ifindex;
12005 			}
12006 			freeb(first_mp);
12007 			mctl_present = B_FALSE;
12008 		}
12009 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12010 	} else {
12011 		ip6h = (ip6_t *)rptr;
12012 
12013 		ASSERT(ipvers == IPV6_VERSION);
12014 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12015 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12016 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12017 
12018 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12019 			uint8_t	nexthdrp;
12020 
12021 			/* Look for ifindex information */
12022 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12023 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12024 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12025 					BUMP_MIB(&ip_mib, tcpInErrs);
12026 					freemsg(first_mp);
12027 					return (NULL);
12028 				}
12029 
12030 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12031 					ASSERT(ip6i->ip6i_ifindex != 0);
12032 					ipp.ipp_fields |= IPPF_IFINDEX;
12033 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12034 					ifindex = ip6i->ip6i_ifindex;
12035 				}
12036 				rptr = (uchar_t *)&ip6i[1];
12037 				mp->b_rptr = rptr;
12038 				if (rptr == mp->b_wptr) {
12039 					mblk_t *mp1;
12040 					mp1 = mp->b_cont;
12041 					freeb(mp);
12042 					mp = mp1;
12043 					rptr = mp->b_rptr;
12044 				}
12045 				if (MBLKL(mp) < IPV6_HDR_LEN +
12046 				    sizeof (tcph_t)) {
12047 					BUMP_MIB(&ip_mib, tcpInErrs);
12048 					freemsg(first_mp);
12049 					return (NULL);
12050 				}
12051 				ip6h = (ip6_t *)rptr;
12052 			}
12053 
12054 			/*
12055 			 * Find any potentially interesting extension headers
12056 			 * as well as the length of the IPv6 + extension
12057 			 * headers.
12058 			 */
12059 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12060 			/* Verify if this is a TCP packet */
12061 			if (nexthdrp != IPPROTO_TCP) {
12062 				BUMP_MIB(&ip_mib, tcpInErrs);
12063 				freemsg(first_mp);
12064 				return (NULL);
12065 			}
12066 		} else {
12067 			ip_hdr_len = IPV6_HDR_LEN;
12068 		}
12069 	}
12070 
12071 done:
12072 	if (ipversp != NULL)
12073 		*ipversp = ipvers;
12074 	if (ip_hdr_lenp != NULL)
12075 		*ip_hdr_lenp = ip_hdr_len;
12076 	if (ippp != NULL)
12077 		*ippp = ipp;
12078 	if (ifindexp != NULL)
12079 		*ifindexp = ifindex;
12080 	if (mctl_present) {
12081 		freeb(first_mp);
12082 	}
12083 	return (mp);
12084 }
12085 
12086 /*
12087  * Handle M_DATA messages from IP. Its called directly from IP via
12088  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12089  * in this path.
12090  *
12091  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12092  * v4 and v6), we are called through tcp_input() and a M_CTL can
12093  * be present for options but tcp_find_pktinfo() deals with it. We
12094  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12095  *
12096  * The first argument is always the connp/tcp to which the mp belongs.
12097  * There are no exceptions to this rule. The caller has already put
12098  * a reference on this connp/tcp and once tcp_rput_data() returns,
12099  * the squeue will do the refrele.
12100  *
12101  * The TH_SYN for the listener directly go to tcp_conn_request via
12102  * squeue.
12103  *
12104  * sqp: NULL = recursive, sqp != NULL means called from squeue
12105  */
12106 void
12107 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12108 {
12109 	int32_t		bytes_acked;
12110 	int32_t		gap;
12111 	mblk_t		*mp1;
12112 	uint_t		flags;
12113 	uint32_t	new_swnd = 0;
12114 	uchar_t		*iphdr;
12115 	uchar_t		*rptr;
12116 	int32_t		rgap;
12117 	uint32_t	seg_ack;
12118 	int		seg_len;
12119 	uint_t		ip_hdr_len;
12120 	uint32_t	seg_seq;
12121 	tcph_t		*tcph;
12122 	int		urp;
12123 	tcp_opt_t	tcpopt;
12124 	uint_t		ipvers;
12125 	ip6_pkt_t	ipp;
12126 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12127 	uint32_t	cwnd;
12128 	uint32_t	add;
12129 	int		npkt;
12130 	int		mss;
12131 	conn_t		*connp = (conn_t *)arg;
12132 	squeue_t	*sqp = (squeue_t *)arg2;
12133 	tcp_t		*tcp = connp->conn_tcp;
12134 
12135 	/*
12136 	 * RST from fused tcp loopback peer should trigger an unfuse.
12137 	 */
12138 	if (tcp->tcp_fused) {
12139 		TCP_STAT(tcp_fusion_aborted);
12140 		tcp_unfuse(tcp);
12141 	}
12142 
12143 	iphdr = mp->b_rptr;
12144 	rptr = mp->b_rptr;
12145 	ASSERT(OK_32PTR(rptr));
12146 
12147 	/*
12148 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12149 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12150 	 * necessary information.
12151 	 */
12152 	if (IPCL_IS_TCP4(connp)) {
12153 		ipvers = IPV4_VERSION;
12154 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12155 	} else {
12156 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12157 		    NULL, &ipp);
12158 		if (mp == NULL) {
12159 			TCP_STAT(tcp_rput_v6_error);
12160 			return;
12161 		}
12162 		iphdr = mp->b_rptr;
12163 		rptr = mp->b_rptr;
12164 	}
12165 	ASSERT(DB_TYPE(mp) == M_DATA);
12166 
12167 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12168 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12169 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12170 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12171 	seg_len = (int)(mp->b_wptr - rptr) -
12172 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12173 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12174 		do {
12175 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12176 			    (uintptr_t)INT_MAX);
12177 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12178 		} while ((mp1 = mp1->b_cont) != NULL &&
12179 		    mp1->b_datap->db_type == M_DATA);
12180 	}
12181 
12182 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12183 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12184 		    seg_len, tcph);
12185 		return;
12186 	}
12187 
12188 	if (sqp != NULL) {
12189 		/*
12190 		 * This is the correct place to update tcp_last_recv_time. Note
12191 		 * that it is also updated for tcp structure that belongs to
12192 		 * global and listener queues which do not really need updating.
12193 		 * But that should not cause any harm.  And it is updated for
12194 		 * all kinds of incoming segments, not only for data segments.
12195 		 */
12196 		tcp->tcp_last_recv_time = lbolt;
12197 	}
12198 
12199 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12200 
12201 	BUMP_LOCAL(tcp->tcp_ibsegs);
12202 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12203 
12204 	if ((flags & TH_URG) && sqp != NULL) {
12205 		/*
12206 		 * TCP can't handle urgent pointers that arrive before
12207 		 * the connection has been accept()ed since it can't
12208 		 * buffer OOB data.  Discard segment if this happens.
12209 		 *
12210 		 * Nor can it reassemble urgent pointers, so discard
12211 		 * if it's not the next segment expected.
12212 		 *
12213 		 * Otherwise, collapse chain into one mblk (discard if
12214 		 * that fails).  This makes sure the headers, retransmitted
12215 		 * data, and new data all are in the same mblk.
12216 		 */
12217 		ASSERT(mp != NULL);
12218 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
12219 			freemsg(mp);
12220 			return;
12221 		}
12222 		/* Update pointers into message */
12223 		iphdr = rptr = mp->b_rptr;
12224 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12225 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12226 			/*
12227 			 * Since we can't handle any data with this urgent
12228 			 * pointer that is out of sequence, we expunge
12229 			 * the data.  This allows us to still register
12230 			 * the urgent mark and generate the M_PCSIG,
12231 			 * which we can do.
12232 			 */
12233 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12234 			seg_len = 0;
12235 		}
12236 	}
12237 
12238 	switch (tcp->tcp_state) {
12239 	case TCPS_SYN_SENT:
12240 		if (flags & TH_ACK) {
12241 			/*
12242 			 * Note that our stack cannot send data before a
12243 			 * connection is established, therefore the
12244 			 * following check is valid.  Otherwise, it has
12245 			 * to be changed.
12246 			 */
12247 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12248 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12249 				freemsg(mp);
12250 				if (flags & TH_RST)
12251 					return;
12252 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12253 				    tcp, seg_ack, 0, TH_RST);
12254 				return;
12255 			}
12256 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12257 		}
12258 		if (flags & TH_RST) {
12259 			freemsg(mp);
12260 			if (flags & TH_ACK)
12261 				(void) tcp_clean_death(tcp,
12262 				    ECONNREFUSED, 13);
12263 			return;
12264 		}
12265 		if (!(flags & TH_SYN)) {
12266 			freemsg(mp);
12267 			return;
12268 		}
12269 
12270 		/* Process all TCP options. */
12271 		tcp_process_options(tcp, tcph);
12272 		/*
12273 		 * The following changes our rwnd to be a multiple of the
12274 		 * MIN(peer MSS, our MSS) for performance reason.
12275 		 */
12276 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12277 		    tcp->tcp_mss));
12278 
12279 		/* Is the other end ECN capable? */
12280 		if (tcp->tcp_ecn_ok) {
12281 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12282 				tcp->tcp_ecn_ok = B_FALSE;
12283 			}
12284 		}
12285 		/*
12286 		 * Clear ECN flags because it may interfere with later
12287 		 * processing.
12288 		 */
12289 		flags &= ~(TH_ECE|TH_CWR);
12290 
12291 		tcp->tcp_irs = seg_seq;
12292 		tcp->tcp_rack = seg_seq;
12293 		tcp->tcp_rnxt = seg_seq + 1;
12294 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12295 		if (!TCP_IS_DETACHED(tcp)) {
12296 			/* Allocate room for SACK options if needed. */
12297 			if (tcp->tcp_snd_sack_ok) {
12298 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12299 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
12300 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12301 			} else {
12302 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12303 				    tcp->tcp_hdr_len +
12304 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12305 			}
12306 		}
12307 		if (flags & TH_ACK) {
12308 			/*
12309 			 * If we can't get the confirmation upstream, pretend
12310 			 * we didn't even see this one.
12311 			 *
12312 			 * XXX: how can we pretend we didn't see it if we
12313 			 * have updated rnxt et. al.
12314 			 *
12315 			 * For loopback we defer sending up the T_CONN_CON
12316 			 * until after some checks below.
12317 			 */
12318 			mp1 = NULL;
12319 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12320 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12321 				freemsg(mp);
12322 				return;
12323 			}
12324 			/* SYN was acked - making progress */
12325 			if (tcp->tcp_ipversion == IPV6_VERSION)
12326 				tcp->tcp_ip_forward_progress = B_TRUE;
12327 
12328 			/* One for the SYN */
12329 			tcp->tcp_suna = tcp->tcp_iss + 1;
12330 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12331 			tcp->tcp_state = TCPS_ESTABLISHED;
12332 
12333 			/*
12334 			 * If SYN was retransmitted, need to reset all
12335 			 * retransmission info.  This is because this
12336 			 * segment will be treated as a dup ACK.
12337 			 */
12338 			if (tcp->tcp_rexmit) {
12339 				tcp->tcp_rexmit = B_FALSE;
12340 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12341 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12342 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12343 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12344 				tcp->tcp_ms_we_have_waited = 0;
12345 
12346 				/*
12347 				 * Set tcp_cwnd back to 1 MSS, per
12348 				 * recommendation from
12349 				 * draft-floyd-incr-init-win-01.txt,
12350 				 * Increasing TCP's Initial Window.
12351 				 */
12352 				tcp->tcp_cwnd = tcp->tcp_mss;
12353 			}
12354 
12355 			tcp->tcp_swl1 = seg_seq;
12356 			tcp->tcp_swl2 = seg_ack;
12357 
12358 			new_swnd = BE16_TO_U16(tcph->th_win);
12359 			tcp->tcp_swnd = new_swnd;
12360 			if (new_swnd > tcp->tcp_max_swnd)
12361 				tcp->tcp_max_swnd = new_swnd;
12362 
12363 			/*
12364 			 * Always send the three-way handshake ack immediately
12365 			 * in order to make the connection complete as soon as
12366 			 * possible on the accepting host.
12367 			 */
12368 			flags |= TH_ACK_NEEDED;
12369 
12370 			/*
12371 			 * Special case for loopback.  At this point we have
12372 			 * received SYN-ACK from the remote endpoint.  In
12373 			 * order to ensure that both endpoints reach the
12374 			 * fused state prior to any data exchange, the final
12375 			 * ACK needs to be sent before we indicate T_CONN_CON
12376 			 * to the module upstream.
12377 			 */
12378 			if (tcp->tcp_loopback) {
12379 				mblk_t *ack_mp;
12380 
12381 				ASSERT(!tcp->tcp_unfusable);
12382 				ASSERT(mp1 != NULL);
12383 				/*
12384 				 * For loopback, we always get a pure SYN-ACK
12385 				 * and only need to send back the final ACK
12386 				 * with no data (this is because the other
12387 				 * tcp is ours and we don't do T/TCP).  This
12388 				 * final ACK triggers the passive side to
12389 				 * perform fusion in ESTABLISHED state.
12390 				 */
12391 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12392 					if (tcp->tcp_ack_tid != 0) {
12393 						(void) TCP_TIMER_CANCEL(tcp,
12394 						    tcp->tcp_ack_tid);
12395 						tcp->tcp_ack_tid = 0;
12396 					}
12397 					TCP_RECORD_TRACE(tcp, ack_mp,
12398 					    TCP_TRACE_SEND_PKT);
12399 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
12400 					BUMP_LOCAL(tcp->tcp_obsegs);
12401 					BUMP_MIB(&tcp_mib, tcpOutAck);
12402 
12403 					/* Send up T_CONN_CON */
12404 					putnext(tcp->tcp_rq, mp1);
12405 
12406 					freemsg(mp);
12407 					return;
12408 				}
12409 				/*
12410 				 * Forget fusion; we need to handle more
12411 				 * complex cases below.  Send the deferred
12412 				 * T_CONN_CON message upstream and proceed
12413 				 * as usual.  Mark this tcp as not capable
12414 				 * of fusion.
12415 				 */
12416 				TCP_STAT(tcp_fusion_unfusable);
12417 				tcp->tcp_unfusable = B_TRUE;
12418 				putnext(tcp->tcp_rq, mp1);
12419 			}
12420 
12421 			/*
12422 			 * Check to see if there is data to be sent.  If
12423 			 * yes, set the transmit flag.  Then check to see
12424 			 * if received data processing needs to be done.
12425 			 * If not, go straight to xmit_check.  This short
12426 			 * cut is OK as we don't support T/TCP.
12427 			 */
12428 			if (tcp->tcp_unsent)
12429 				flags |= TH_XMIT_NEEDED;
12430 
12431 			if (seg_len == 0 && !(flags & TH_URG)) {
12432 				freemsg(mp);
12433 				goto xmit_check;
12434 			}
12435 
12436 			flags &= ~TH_SYN;
12437 			seg_seq++;
12438 			break;
12439 		}
12440 		tcp->tcp_state = TCPS_SYN_RCVD;
12441 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
12442 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
12443 		if (mp1) {
12444 			mblk_setcred(mp1, tcp->tcp_cred);
12445 			DB_CPID(mp1) = tcp->tcp_cpid;
12446 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
12447 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
12448 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12449 		}
12450 		freemsg(mp);
12451 		return;
12452 	case TCPS_SYN_RCVD:
12453 		if (flags & TH_ACK) {
12454 			/*
12455 			 * In this state, a SYN|ACK packet is either bogus
12456 			 * because the other side must be ACKing our SYN which
12457 			 * indicates it has seen the ACK for their SYN and
12458 			 * shouldn't retransmit it or we're crossing SYNs
12459 			 * on active open.
12460 			 */
12461 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
12462 				freemsg(mp);
12463 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
12464 				    tcp, seg_ack, 0, TH_RST);
12465 				return;
12466 			}
12467 			/*
12468 			 * NOTE: RFC 793 pg. 72 says this should be
12469 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
12470 			 * but that would mean we have an ack that ignored
12471 			 * our SYN.
12472 			 */
12473 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
12474 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12475 				freemsg(mp);
12476 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
12477 				    tcp, seg_ack, 0, TH_RST);
12478 				return;
12479 			}
12480 		}
12481 		break;
12482 	case TCPS_LISTEN:
12483 		/*
12484 		 * Only a TLI listener can come through this path when a
12485 		 * acceptor is going back to be a listener and a packet
12486 		 * for the acceptor hits the classifier. For a socket
12487 		 * listener, this can never happen because a listener
12488 		 * can never accept connection on itself and hence a
12489 		 * socket acceptor can not go back to being a listener.
12490 		 */
12491 		ASSERT(!TCP_IS_SOCKET(tcp));
12492 		/*FALLTHRU*/
12493 	case TCPS_CLOSED:
12494 	case TCPS_BOUND: {
12495 		conn_t	*new_connp;
12496 
12497 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
12498 		if (new_connp != NULL) {
12499 			tcp_reinput(new_connp, mp, connp->conn_sqp);
12500 			return;
12501 		}
12502 		/* We failed to classify. For now just drop the packet */
12503 		freemsg(mp);
12504 		return;
12505 	}
12506 	case TCPS_IDLE:
12507 		/*
12508 		 * Handle the case where the tcp_clean_death() has happened
12509 		 * on a connection (application hasn't closed yet) but a packet
12510 		 * was already queued on squeue before tcp_clean_death()
12511 		 * was processed. Calling tcp_clean_death() twice on same
12512 		 * connection can result in weird behaviour.
12513 		 */
12514 		freemsg(mp);
12515 		return;
12516 	default:
12517 		break;
12518 	}
12519 
12520 	/*
12521 	 * Already on the correct queue/perimeter.
12522 	 * If this is a detached connection and not an eager
12523 	 * connection hanging off a listener then new data
12524 	 * (past the FIN) will cause a reset.
12525 	 * We do a special check here where it
12526 	 * is out of the main line, rather than check
12527 	 * if we are detached every time we see new
12528 	 * data down below.
12529 	 */
12530 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
12531 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
12532 		BUMP_MIB(&tcp_mib, tcpInClosed);
12533 		TCP_RECORD_TRACE(tcp,
12534 		    mp, TCP_TRACE_RECV_PKT);
12535 		freemsg(mp);
12536 		tcp_xmit_ctl("new data when detached", tcp,
12537 		    tcp->tcp_snxt, 0, TH_RST);
12538 		(void) tcp_clean_death(tcp, EPROTO, 12);
12539 		return;
12540 	}
12541 
12542 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12543 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
12544 	new_swnd = BE16_TO_U16(tcph->th_win) <<
12545 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
12546 	mss = tcp->tcp_mss;
12547 
12548 	if (tcp->tcp_snd_ts_ok) {
12549 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
12550 			/*
12551 			 * This segment is not acceptable.
12552 			 * Drop it and send back an ACK.
12553 			 */
12554 			freemsg(mp);
12555 			flags |= TH_ACK_NEEDED;
12556 			goto ack_check;
12557 		}
12558 	} else if (tcp->tcp_snd_sack_ok) {
12559 		ASSERT(tcp->tcp_sack_info != NULL);
12560 		tcpopt.tcp = tcp;
12561 		/*
12562 		 * SACK info in already updated in tcp_parse_options.  Ignore
12563 		 * all other TCP options...
12564 		 */
12565 		(void) tcp_parse_options(tcph, &tcpopt);
12566 	}
12567 try_again:;
12568 	gap = seg_seq - tcp->tcp_rnxt;
12569 	rgap = tcp->tcp_rwnd - (gap + seg_len);
12570 	/*
12571 	 * gap is the amount of sequence space between what we expect to see
12572 	 * and what we got for seg_seq.  A positive value for gap means
12573 	 * something got lost.  A negative value means we got some old stuff.
12574 	 */
12575 	if (gap < 0) {
12576 		/* Old stuff present.  Is the SYN in there? */
12577 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
12578 		    (seg_len != 0)) {
12579 			flags &= ~TH_SYN;
12580 			seg_seq++;
12581 			urp--;
12582 			/* Recompute the gaps after noting the SYN. */
12583 			goto try_again;
12584 		}
12585 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
12586 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
12587 		    (seg_len > -gap ? -gap : seg_len));
12588 		/* Remove the old stuff from seg_len. */
12589 		seg_len += gap;
12590 		/*
12591 		 * Anything left?
12592 		 * Make sure to check for unack'd FIN when rest of data
12593 		 * has been previously ack'd.
12594 		 */
12595 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
12596 			/*
12597 			 * Resets are only valid if they lie within our offered
12598 			 * window.  If the RST bit is set, we just ignore this
12599 			 * segment.
12600 			 */
12601 			if (flags & TH_RST) {
12602 				freemsg(mp);
12603 				return;
12604 			}
12605 
12606 			/*
12607 			 * The arriving of dup data packets indicate that we
12608 			 * may have postponed an ack for too long, or the other
12609 			 * side's RTT estimate is out of shape. Start acking
12610 			 * more often.
12611 			 */
12612 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
12613 			    tcp->tcp_rack_cnt >= 1 &&
12614 			    tcp->tcp_rack_abs_max > 2) {
12615 				tcp->tcp_rack_abs_max--;
12616 			}
12617 			tcp->tcp_rack_cur_max = 1;
12618 
12619 			/*
12620 			 * This segment is "unacceptable".  None of its
12621 			 * sequence space lies within our advertized window.
12622 			 *
12623 			 * Adjust seg_len to the original value for tracing.
12624 			 */
12625 			seg_len -= gap;
12626 			if (tcp->tcp_debug) {
12627 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12628 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
12629 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
12630 				    "seg_len %d, rnxt %u, snxt %u, %s",
12631 				    gap, rgap, flags, seg_seq, seg_ack,
12632 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
12633 				    tcp_display(tcp, NULL,
12634 				    DISP_ADDR_AND_PORT));
12635 			}
12636 
12637 			/*
12638 			 * Arrange to send an ACK in response to the
12639 			 * unacceptable segment per RFC 793 page 69. There
12640 			 * is only one small difference between ours and the
12641 			 * acceptability test in the RFC - we accept ACK-only
12642 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
12643 			 * will be generated.
12644 			 *
12645 			 * Note that we have to ACK an ACK-only packet at least
12646 			 * for stacks that send 0-length keep-alives with
12647 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
12648 			 * section 4.2.3.6. As long as we don't ever generate
12649 			 * an unacceptable packet in response to an incoming
12650 			 * packet that is unacceptable, it should not cause
12651 			 * "ACK wars".
12652 			 */
12653 			flags |=  TH_ACK_NEEDED;
12654 
12655 			/*
12656 			 * Continue processing this segment in order to use the
12657 			 * ACK information it contains, but skip all other
12658 			 * sequence-number processing.	Processing the ACK
12659 			 * information is necessary in order to
12660 			 * re-synchronize connections that may have lost
12661 			 * synchronization.
12662 			 *
12663 			 * We clear seg_len and flag fields related to
12664 			 * sequence number processing as they are not
12665 			 * to be trusted for an unacceptable segment.
12666 			 */
12667 			seg_len = 0;
12668 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
12669 			goto process_ack;
12670 		}
12671 
12672 		/* Fix seg_seq, and chew the gap off the front. */
12673 		seg_seq = tcp->tcp_rnxt;
12674 		urp += gap;
12675 		do {
12676 			mblk_t	*mp2;
12677 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
12678 			    (uintptr_t)UINT_MAX);
12679 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
12680 			if (gap > 0) {
12681 				mp->b_rptr = mp->b_wptr - gap;
12682 				break;
12683 			}
12684 			mp2 = mp;
12685 			mp = mp->b_cont;
12686 			freeb(mp2);
12687 		} while (gap < 0);
12688 		/*
12689 		 * If the urgent data has already been acknowledged, we
12690 		 * should ignore TH_URG below
12691 		 */
12692 		if (urp < 0)
12693 			flags &= ~TH_URG;
12694 	}
12695 	/*
12696 	 * rgap is the amount of stuff received out of window.  A negative
12697 	 * value is the amount out of window.
12698 	 */
12699 	if (rgap < 0) {
12700 		mblk_t	*mp2;
12701 
12702 		if (tcp->tcp_rwnd == 0) {
12703 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
12704 		} else {
12705 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
12706 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
12707 		}
12708 
12709 		/*
12710 		 * seg_len does not include the FIN, so if more than
12711 		 * just the FIN is out of window, we act like we don't
12712 		 * see it.  (If just the FIN is out of window, rgap
12713 		 * will be zero and we will go ahead and acknowledge
12714 		 * the FIN.)
12715 		 */
12716 		flags &= ~TH_FIN;
12717 
12718 		/* Fix seg_len and make sure there is something left. */
12719 		seg_len += rgap;
12720 		if (seg_len <= 0) {
12721 			/*
12722 			 * Resets are only valid if they lie within our offered
12723 			 * window.  If the RST bit is set, we just ignore this
12724 			 * segment.
12725 			 */
12726 			if (flags & TH_RST) {
12727 				freemsg(mp);
12728 				return;
12729 			}
12730 
12731 			/* Per RFC 793, we need to send back an ACK. */
12732 			flags |= TH_ACK_NEEDED;
12733 
12734 			/*
12735 			 * Send SIGURG as soon as possible i.e. even
12736 			 * if the TH_URG was delivered in a window probe
12737 			 * packet (which will be unacceptable).
12738 			 *
12739 			 * We generate a signal if none has been generated
12740 			 * for this connection or if this is a new urgent
12741 			 * byte. Also send a zero-length "unmarked" message
12742 			 * to inform SIOCATMARK that this is not the mark.
12743 			 *
12744 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
12745 			 * is sent up. This plus the check for old data
12746 			 * (gap >= 0) handles the wraparound of the sequence
12747 			 * number space without having to always track the
12748 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
12749 			 * this max in its rcv_up variable).
12750 			 *
12751 			 * This prevents duplicate SIGURGS due to a "late"
12752 			 * zero-window probe when the T_EXDATA_IND has already
12753 			 * been sent up.
12754 			 */
12755 			if ((flags & TH_URG) &&
12756 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
12757 			    tcp->tcp_urp_last))) {
12758 				mp1 = allocb(0, BPRI_MED);
12759 				if (mp1 == NULL) {
12760 					freemsg(mp);
12761 					return;
12762 				}
12763 				if (!TCP_IS_DETACHED(tcp) &&
12764 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
12765 				    SIGURG)) {
12766 					/* Try again on the rexmit. */
12767 					freemsg(mp1);
12768 					freemsg(mp);
12769 					return;
12770 				}
12771 				/*
12772 				 * If the next byte would be the mark
12773 				 * then mark with MARKNEXT else mark
12774 				 * with NOTMARKNEXT.
12775 				 */
12776 				if (gap == 0 && urp == 0)
12777 					mp1->b_flag |= MSGMARKNEXT;
12778 				else
12779 					mp1->b_flag |= MSGNOTMARKNEXT;
12780 				freemsg(tcp->tcp_urp_mark_mp);
12781 				tcp->tcp_urp_mark_mp = mp1;
12782 				flags |= TH_SEND_URP_MARK;
12783 				tcp->tcp_urp_last_valid = B_TRUE;
12784 				tcp->tcp_urp_last = urp + seg_seq;
12785 			}
12786 			/*
12787 			 * If this is a zero window probe, continue to
12788 			 * process the ACK part.  But we need to set seg_len
12789 			 * to 0 to avoid data processing.  Otherwise just
12790 			 * drop the segment and send back an ACK.
12791 			 */
12792 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
12793 				flags &= ~(TH_SYN | TH_URG);
12794 				seg_len = 0;
12795 				goto process_ack;
12796 			} else {
12797 				freemsg(mp);
12798 				goto ack_check;
12799 			}
12800 		}
12801 		/* Pitch out of window stuff off the end. */
12802 		rgap = seg_len;
12803 		mp2 = mp;
12804 		do {
12805 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
12806 			    (uintptr_t)INT_MAX);
12807 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
12808 			if (rgap < 0) {
12809 				mp2->b_wptr += rgap;
12810 				if ((mp1 = mp2->b_cont) != NULL) {
12811 					mp2->b_cont = NULL;
12812 					freemsg(mp1);
12813 				}
12814 				break;
12815 			}
12816 		} while ((mp2 = mp2->b_cont) != NULL);
12817 	}
12818 ok:;
12819 	/*
12820 	 * TCP should check ECN info for segments inside the window only.
12821 	 * Therefore the check should be done here.
12822 	 */
12823 	if (tcp->tcp_ecn_ok) {
12824 		if (flags & TH_CWR) {
12825 			tcp->tcp_ecn_echo_on = B_FALSE;
12826 		}
12827 		/*
12828 		 * Note that both ECN_CE and CWR can be set in the
12829 		 * same segment.  In this case, we once again turn
12830 		 * on ECN_ECHO.
12831 		 */
12832 		if (tcp->tcp_ipversion == IPV4_VERSION) {
12833 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
12834 
12835 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
12836 				tcp->tcp_ecn_echo_on = B_TRUE;
12837 			}
12838 		} else {
12839 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
12840 
12841 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
12842 			    htonl(IPH_ECN_CE << 20)) {
12843 				tcp->tcp_ecn_echo_on = B_TRUE;
12844 			}
12845 		}
12846 	}
12847 
12848 	/*
12849 	 * Check whether we can update tcp_ts_recent.  This test is
12850 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
12851 	 * Extensions for High Performance: An Update", Internet Draft.
12852 	 */
12853 	if (tcp->tcp_snd_ts_ok &&
12854 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
12855 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
12856 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12857 		tcp->tcp_last_rcv_lbolt = lbolt64;
12858 	}
12859 
12860 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
12861 		/*
12862 		 * FIN in an out of order segment.  We record this in
12863 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
12864 		 * Clear the FIN so that any check on FIN flag will fail.
12865 		 * Remember that FIN also counts in the sequence number
12866 		 * space.  So we need to ack out of order FIN only segments.
12867 		 */
12868 		if (flags & TH_FIN) {
12869 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
12870 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
12871 			flags &= ~TH_FIN;
12872 			flags |= TH_ACK_NEEDED;
12873 		}
12874 		if (seg_len > 0) {
12875 			/* Fill in the SACK blk list. */
12876 			if (tcp->tcp_snd_sack_ok) {
12877 				ASSERT(tcp->tcp_sack_info != NULL);
12878 				tcp_sack_insert(tcp->tcp_sack_list,
12879 				    seg_seq, seg_seq + seg_len,
12880 				    &(tcp->tcp_num_sack_blk));
12881 			}
12882 
12883 			/*
12884 			 * Attempt reassembly and see if we have something
12885 			 * ready to go.
12886 			 */
12887 			mp = tcp_reass(tcp, mp, seg_seq);
12888 			/* Always ack out of order packets */
12889 			flags |= TH_ACK_NEEDED | TH_PUSH;
12890 			if (mp) {
12891 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
12892 				    (uintptr_t)INT_MAX);
12893 				seg_len = mp->b_cont ? msgdsize(mp) :
12894 					(int)(mp->b_wptr - mp->b_rptr);
12895 				seg_seq = tcp->tcp_rnxt;
12896 				/*
12897 				 * A gap is filled and the seq num and len
12898 				 * of the gap match that of a previously
12899 				 * received FIN, put the FIN flag back in.
12900 				 */
12901 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
12902 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
12903 					flags |= TH_FIN;
12904 					tcp->tcp_valid_bits &=
12905 					    ~TCP_OFO_FIN_VALID;
12906 				}
12907 			} else {
12908 				/*
12909 				 * Keep going even with NULL mp.
12910 				 * There may be a useful ACK or something else
12911 				 * we don't want to miss.
12912 				 *
12913 				 * But TCP should not perform fast retransmit
12914 				 * because of the ack number.  TCP uses
12915 				 * seg_len == 0 to determine if it is a pure
12916 				 * ACK.  And this is not a pure ACK.
12917 				 */
12918 				seg_len = 0;
12919 				ofo_seg = B_TRUE;
12920 			}
12921 		}
12922 	} else if (seg_len > 0) {
12923 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
12924 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
12925 		/*
12926 		 * If an out of order FIN was received before, and the seq
12927 		 * num and len of the new segment match that of the FIN,
12928 		 * put the FIN flag back in.
12929 		 */
12930 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
12931 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
12932 			flags |= TH_FIN;
12933 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
12934 		}
12935 	}
12936 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
12937 	if (flags & TH_RST) {
12938 		freemsg(mp);
12939 		switch (tcp->tcp_state) {
12940 		case TCPS_SYN_RCVD:
12941 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
12942 			break;
12943 		case TCPS_ESTABLISHED:
12944 		case TCPS_FIN_WAIT_1:
12945 		case TCPS_FIN_WAIT_2:
12946 		case TCPS_CLOSE_WAIT:
12947 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
12948 			break;
12949 		case TCPS_CLOSING:
12950 		case TCPS_LAST_ACK:
12951 			(void) tcp_clean_death(tcp, 0, 16);
12952 			break;
12953 		default:
12954 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
12955 			(void) tcp_clean_death(tcp, ENXIO, 17);
12956 			break;
12957 		}
12958 		return;
12959 	}
12960 	if (flags & TH_SYN) {
12961 		/*
12962 		 * See RFC 793, Page 71
12963 		 *
12964 		 * The seq number must be in the window as it should
12965 		 * be "fixed" above.  If it is outside window, it should
12966 		 * be already rejected.  Note that we allow seg_seq to be
12967 		 * rnxt + rwnd because we want to accept 0 window probe.
12968 		 */
12969 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
12970 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
12971 		freemsg(mp);
12972 		/*
12973 		 * If the ACK flag is not set, just use our snxt as the
12974 		 * seq number of the RST segment.
12975 		 */
12976 		if (!(flags & TH_ACK)) {
12977 			seg_ack = tcp->tcp_snxt;
12978 		}
12979 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
12980 		    TH_RST|TH_ACK);
12981 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
12982 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
12983 		return;
12984 	}
12985 	/*
12986 	 * urp could be -1 when the urp field in the packet is 0
12987 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
12988 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
12989 	 */
12990 	if (flags & TH_URG && urp >= 0) {
12991 		if (!tcp->tcp_urp_last_valid ||
12992 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
12993 			/*
12994 			 * If we haven't generated the signal yet for this
12995 			 * urgent pointer value, do it now.  Also, send up a
12996 			 * zero-length M_DATA indicating whether or not this is
12997 			 * the mark. The latter is not needed when a
12998 			 * T_EXDATA_IND is sent up. However, if there are
12999 			 * allocation failures this code relies on the sender
13000 			 * retransmitting and the socket code for determining
13001 			 * the mark should not block waiting for the peer to
13002 			 * transmit. Thus, for simplicity we always send up the
13003 			 * mark indication.
13004 			 */
13005 			mp1 = allocb(0, BPRI_MED);
13006 			if (mp1 == NULL) {
13007 				freemsg(mp);
13008 				return;
13009 			}
13010 			if (!TCP_IS_DETACHED(tcp) &&
13011 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13012 				/* Try again on the rexmit. */
13013 				freemsg(mp1);
13014 				freemsg(mp);
13015 				return;
13016 			}
13017 			/*
13018 			 * Mark with NOTMARKNEXT for now.
13019 			 * The code below will change this to MARKNEXT
13020 			 * if we are at the mark.
13021 			 *
13022 			 * If there are allocation failures (e.g. in dupmsg
13023 			 * below) the next time tcp_rput_data sees the urgent
13024 			 * segment it will send up the MSG*MARKNEXT message.
13025 			 */
13026 			mp1->b_flag |= MSGNOTMARKNEXT;
13027 			freemsg(tcp->tcp_urp_mark_mp);
13028 			tcp->tcp_urp_mark_mp = mp1;
13029 			flags |= TH_SEND_URP_MARK;
13030 #ifdef DEBUG
13031 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13032 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13033 			    "last %x, %s",
13034 			    seg_seq, urp, tcp->tcp_urp_last,
13035 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13036 #endif /* DEBUG */
13037 			tcp->tcp_urp_last_valid = B_TRUE;
13038 			tcp->tcp_urp_last = urp + seg_seq;
13039 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13040 			/*
13041 			 * An allocation failure prevented the previous
13042 			 * tcp_rput_data from sending up the allocated
13043 			 * MSG*MARKNEXT message - send it up this time
13044 			 * around.
13045 			 */
13046 			flags |= TH_SEND_URP_MARK;
13047 		}
13048 
13049 		/*
13050 		 * If the urgent byte is in this segment, make sure that it is
13051 		 * all by itself.  This makes it much easier to deal with the
13052 		 * possibility of an allocation failure on the T_exdata_ind.
13053 		 * Note that seg_len is the number of bytes in the segment, and
13054 		 * urp is the offset into the segment of the urgent byte.
13055 		 * urp < seg_len means that the urgent byte is in this segment.
13056 		 */
13057 		if (urp < seg_len) {
13058 			if (seg_len != 1) {
13059 				uint32_t  tmp_rnxt;
13060 				/*
13061 				 * Break it up and feed it back in.
13062 				 * Re-attach the IP header.
13063 				 */
13064 				mp->b_rptr = iphdr;
13065 				if (urp > 0) {
13066 					/*
13067 					 * There is stuff before the urgent
13068 					 * byte.
13069 					 */
13070 					mp1 = dupmsg(mp);
13071 					if (!mp1) {
13072 						/*
13073 						 * Trim from urgent byte on.
13074 						 * The rest will come back.
13075 						 */
13076 						(void) adjmsg(mp,
13077 						    urp - seg_len);
13078 						tcp_rput_data(connp,
13079 						    mp, NULL);
13080 						return;
13081 					}
13082 					(void) adjmsg(mp1, urp - seg_len);
13083 					/* Feed this piece back in. */
13084 					tmp_rnxt = tcp->tcp_rnxt;
13085 					tcp_rput_data(connp, mp1, NULL);
13086 					/*
13087 					 * If the data passed back in was not
13088 					 * processed (ie: bad ACK) sending
13089 					 * the remainder back in will cause a
13090 					 * loop. In this case, drop the
13091 					 * packet and let the sender try
13092 					 * sending a good packet.
13093 					 */
13094 					if (tmp_rnxt == tcp->tcp_rnxt) {
13095 						freemsg(mp);
13096 						return;
13097 					}
13098 				}
13099 				if (urp != seg_len - 1) {
13100 					uint32_t  tmp_rnxt;
13101 					/*
13102 					 * There is stuff after the urgent
13103 					 * byte.
13104 					 */
13105 					mp1 = dupmsg(mp);
13106 					if (!mp1) {
13107 						/*
13108 						 * Trim everything beyond the
13109 						 * urgent byte.  The rest will
13110 						 * come back.
13111 						 */
13112 						(void) adjmsg(mp,
13113 						    urp + 1 - seg_len);
13114 						tcp_rput_data(connp,
13115 						    mp, NULL);
13116 						return;
13117 					}
13118 					(void) adjmsg(mp1, urp + 1 - seg_len);
13119 					tmp_rnxt = tcp->tcp_rnxt;
13120 					tcp_rput_data(connp, mp1, NULL);
13121 					/*
13122 					 * If the data passed back in was not
13123 					 * processed (ie: bad ACK) sending
13124 					 * the remainder back in will cause a
13125 					 * loop. In this case, drop the
13126 					 * packet and let the sender try
13127 					 * sending a good packet.
13128 					 */
13129 					if (tmp_rnxt == tcp->tcp_rnxt) {
13130 						freemsg(mp);
13131 						return;
13132 					}
13133 				}
13134 				tcp_rput_data(connp, mp, NULL);
13135 				return;
13136 			}
13137 			/*
13138 			 * This segment contains only the urgent byte.  We
13139 			 * have to allocate the T_exdata_ind, if we can.
13140 			 */
13141 			if (!tcp->tcp_urp_mp) {
13142 				struct T_exdata_ind *tei;
13143 				mp1 = allocb(sizeof (struct T_exdata_ind),
13144 				    BPRI_MED);
13145 				if (!mp1) {
13146 					/*
13147 					 * Sigh... It'll be back.
13148 					 * Generate any MSG*MARK message now.
13149 					 */
13150 					freemsg(mp);
13151 					seg_len = 0;
13152 					if (flags & TH_SEND_URP_MARK) {
13153 
13154 
13155 						ASSERT(tcp->tcp_urp_mark_mp);
13156 						tcp->tcp_urp_mark_mp->b_flag &=
13157 							~MSGNOTMARKNEXT;
13158 						tcp->tcp_urp_mark_mp->b_flag |=
13159 							MSGMARKNEXT;
13160 					}
13161 					goto ack_check;
13162 				}
13163 				mp1->b_datap->db_type = M_PROTO;
13164 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13165 				tei->PRIM_type = T_EXDATA_IND;
13166 				tei->MORE_flag = 0;
13167 				mp1->b_wptr = (uchar_t *)&tei[1];
13168 				tcp->tcp_urp_mp = mp1;
13169 #ifdef DEBUG
13170 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13171 				    "tcp_rput: allocated exdata_ind %s",
13172 				    tcp_display(tcp, NULL,
13173 				    DISP_PORT_ONLY));
13174 #endif /* DEBUG */
13175 				/*
13176 				 * There is no need to send a separate MSG*MARK
13177 				 * message since the T_EXDATA_IND will be sent
13178 				 * now.
13179 				 */
13180 				flags &= ~TH_SEND_URP_MARK;
13181 				freemsg(tcp->tcp_urp_mark_mp);
13182 				tcp->tcp_urp_mark_mp = NULL;
13183 			}
13184 			/*
13185 			 * Now we are all set.  On the next putnext upstream,
13186 			 * tcp_urp_mp will be non-NULL and will get prepended
13187 			 * to what has to be this piece containing the urgent
13188 			 * byte.  If for any reason we abort this segment below,
13189 			 * if it comes back, we will have this ready, or it
13190 			 * will get blown off in close.
13191 			 */
13192 		} else if (urp == seg_len) {
13193 			/*
13194 			 * The urgent byte is the next byte after this sequence
13195 			 * number. If there is data it is marked with
13196 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13197 			 * since it is not needed. Otherwise, if the code
13198 			 * above just allocated a zero-length tcp_urp_mark_mp
13199 			 * message, that message is tagged with MSGMARKNEXT.
13200 			 * Sending up these MSGMARKNEXT messages makes
13201 			 * SIOCATMARK work correctly even though
13202 			 * the T_EXDATA_IND will not be sent up until the
13203 			 * urgent byte arrives.
13204 			 */
13205 			if (seg_len != 0) {
13206 				flags |= TH_MARKNEXT_NEEDED;
13207 				freemsg(tcp->tcp_urp_mark_mp);
13208 				tcp->tcp_urp_mark_mp = NULL;
13209 				flags &= ~TH_SEND_URP_MARK;
13210 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13211 				flags |= TH_SEND_URP_MARK;
13212 				tcp->tcp_urp_mark_mp->b_flag &=
13213 					~MSGNOTMARKNEXT;
13214 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13215 			}
13216 #ifdef DEBUG
13217 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13218 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13219 			    seg_len, flags,
13220 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13221 #endif /* DEBUG */
13222 		} else {
13223 			/* Data left until we hit mark */
13224 #ifdef DEBUG
13225 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13226 			    "tcp_rput: URP %d bytes left, %s",
13227 			    urp - seg_len, tcp_display(tcp, NULL,
13228 			    DISP_PORT_ONLY));
13229 #endif /* DEBUG */
13230 		}
13231 	}
13232 
13233 process_ack:
13234 	if (!(flags & TH_ACK)) {
13235 		freemsg(mp);
13236 		goto xmit_check;
13237 	}
13238 	}
13239 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13240 
13241 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13242 		tcp->tcp_ip_forward_progress = B_TRUE;
13243 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13244 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
13245 			/* 3-way handshake complete - pass up the T_CONN_IND */
13246 			tcp_t	*listener = tcp->tcp_listener;
13247 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13248 
13249 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13250 			/*
13251 			 * We are here means eager is fine but it can
13252 			 * get a TH_RST at any point between now and till
13253 			 * accept completes and disappear. We need to
13254 			 * ensure that reference to eager is valid after
13255 			 * we get out of eager's perimeter. So we do
13256 			 * an extra refhold.
13257 			 */
13258 			CONN_INC_REF(connp);
13259 
13260 			/*
13261 			 * The listener also exists because of the refhold
13262 			 * done in tcp_conn_request. Its possible that it
13263 			 * might have closed. We will check that once we
13264 			 * get inside listeners context.
13265 			 */
13266 			CONN_INC_REF(listener->tcp_connp);
13267 			if (listener->tcp_connp->conn_sqp ==
13268 			    connp->conn_sqp) {
13269 				tcp_send_conn_ind(listener->tcp_connp, mp,
13270 				    listener->tcp_connp->conn_sqp);
13271 				CONN_DEC_REF(listener->tcp_connp);
13272 			} else if (!tcp->tcp_loopback) {
13273 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
13274 				    tcp_send_conn_ind,
13275 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
13276 			} else {
13277 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
13278 				    tcp_send_conn_ind, listener->tcp_connp,
13279 				    SQTAG_TCP_CONN_IND);
13280 			}
13281 		}
13282 
13283 		if (tcp->tcp_active_open) {
13284 			/*
13285 			 * We are seeing the final ack in the three way
13286 			 * hand shake of a active open'ed connection
13287 			 * so we must send up a T_CONN_CON
13288 			 */
13289 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13290 				freemsg(mp);
13291 				return;
13292 			}
13293 			/*
13294 			 * Don't fuse the loopback endpoints for
13295 			 * simultaneous active opens.
13296 			 */
13297 			if (tcp->tcp_loopback) {
13298 				TCP_STAT(tcp_fusion_unfusable);
13299 				tcp->tcp_unfusable = B_TRUE;
13300 			}
13301 		}
13302 
13303 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
13304 		bytes_acked--;
13305 		/* SYN was acked - making progress */
13306 		if (tcp->tcp_ipversion == IPV6_VERSION)
13307 			tcp->tcp_ip_forward_progress = B_TRUE;
13308 
13309 		/*
13310 		 * If SYN was retransmitted, need to reset all
13311 		 * retransmission info as this segment will be
13312 		 * treated as a dup ACK.
13313 		 */
13314 		if (tcp->tcp_rexmit) {
13315 			tcp->tcp_rexmit = B_FALSE;
13316 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13317 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
13318 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13319 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13320 			tcp->tcp_ms_we_have_waited = 0;
13321 			tcp->tcp_cwnd = mss;
13322 		}
13323 
13324 		/*
13325 		 * We set the send window to zero here.
13326 		 * This is needed if there is data to be
13327 		 * processed already on the queue.
13328 		 * Later (at swnd_update label), the
13329 		 * "new_swnd > tcp_swnd" condition is satisfied
13330 		 * the XMIT_NEEDED flag is set in the current
13331 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
13332 		 * called if there is already data on queue in
13333 		 * this state.
13334 		 */
13335 		tcp->tcp_swnd = 0;
13336 
13337 		if (new_swnd > tcp->tcp_max_swnd)
13338 			tcp->tcp_max_swnd = new_swnd;
13339 		tcp->tcp_swl1 = seg_seq;
13340 		tcp->tcp_swl2 = seg_ack;
13341 		tcp->tcp_state = TCPS_ESTABLISHED;
13342 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13343 
13344 		/* Fuse when both sides are in ESTABLISHED state */
13345 		if (tcp->tcp_loopback && do_tcp_fusion)
13346 			tcp_fuse(tcp, iphdr, tcph);
13347 
13348 	}
13349 	/* This code follows 4.4BSD-Lite2 mostly. */
13350 	if (bytes_acked < 0)
13351 		goto est;
13352 
13353 	/*
13354 	 * If TCP is ECN capable and the congestion experience bit is
13355 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
13356 	 * done once per window (or more loosely, per RTT).
13357 	 */
13358 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
13359 		tcp->tcp_cwr = B_FALSE;
13360 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
13361 		if (!tcp->tcp_cwr) {
13362 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
13363 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
13364 			tcp->tcp_cwnd = npkt * mss;
13365 			/*
13366 			 * If the cwnd is 0, use the timer to clock out
13367 			 * new segments.  This is required by the ECN spec.
13368 			 */
13369 			if (npkt == 0) {
13370 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13371 				/*
13372 				 * This makes sure that when the ACK comes
13373 				 * back, we will increase tcp_cwnd by 1 MSS.
13374 				 */
13375 				tcp->tcp_cwnd_cnt = 0;
13376 			}
13377 			tcp->tcp_cwr = B_TRUE;
13378 			/*
13379 			 * This marks the end of the current window of in
13380 			 * flight data.  That is why we don't use
13381 			 * tcp_suna + tcp_swnd.  Only data in flight can
13382 			 * provide ECN info.
13383 			 */
13384 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13385 			tcp->tcp_ecn_cwr_sent = B_FALSE;
13386 		}
13387 	}
13388 
13389 	mp1 = tcp->tcp_xmit_head;
13390 	if (bytes_acked == 0) {
13391 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
13392 			int dupack_cnt;
13393 
13394 			BUMP_MIB(&tcp_mib, tcpInDupAck);
13395 			/*
13396 			 * Fast retransmit.  When we have seen exactly three
13397 			 * identical ACKs while we have unacked data
13398 			 * outstanding we take it as a hint that our peer
13399 			 * dropped something.
13400 			 *
13401 			 * If TCP is retransmitting, don't do fast retransmit.
13402 			 */
13403 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
13404 			    ! tcp->tcp_rexmit) {
13405 				/* Do Limited Transmit */
13406 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
13407 				    tcp_dupack_fast_retransmit) {
13408 					/*
13409 					 * RFC 3042
13410 					 *
13411 					 * What we need to do is temporarily
13412 					 * increase tcp_cwnd so that new
13413 					 * data can be sent if it is allowed
13414 					 * by the receive window (tcp_rwnd).
13415 					 * tcp_wput_data() will take care of
13416 					 * the rest.
13417 					 *
13418 					 * If the connection is SACK capable,
13419 					 * only do limited xmit when there
13420 					 * is SACK info.
13421 					 *
13422 					 * Note how tcp_cwnd is incremented.
13423 					 * The first dup ACK will increase
13424 					 * it by 1 MSS.  The second dup ACK
13425 					 * will increase it by 2 MSS.  This
13426 					 * means that only 1 new segment will
13427 					 * be sent for each dup ACK.
13428 					 */
13429 					if (tcp->tcp_unsent > 0 &&
13430 					    (!tcp->tcp_snd_sack_ok ||
13431 					    (tcp->tcp_snd_sack_ok &&
13432 					    tcp->tcp_notsack_list != NULL))) {
13433 						tcp->tcp_cwnd += mss <<
13434 						    (tcp->tcp_dupack_cnt - 1);
13435 						flags |= TH_LIMIT_XMIT;
13436 					}
13437 				} else if (dupack_cnt ==
13438 				    tcp_dupack_fast_retransmit) {
13439 
13440 				/*
13441 				 * If we have reduced tcp_ssthresh
13442 				 * because of ECN, do not reduce it again
13443 				 * unless it is already one window of data
13444 				 * away.  After one window of data, tcp_cwr
13445 				 * should then be cleared.  Note that
13446 				 * for non ECN capable connection, tcp_cwr
13447 				 * should always be false.
13448 				 *
13449 				 * Adjust cwnd since the duplicate
13450 				 * ack indicates that a packet was
13451 				 * dropped (due to congestion.)
13452 				 */
13453 				if (!tcp->tcp_cwr) {
13454 					npkt = ((tcp->tcp_snxt -
13455 					    tcp->tcp_suna) >> 1) / mss;
13456 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13457 					    mss;
13458 					tcp->tcp_cwnd = (npkt +
13459 					    tcp->tcp_dupack_cnt) * mss;
13460 				}
13461 				if (tcp->tcp_ecn_ok) {
13462 					tcp->tcp_cwr = B_TRUE;
13463 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13464 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13465 				}
13466 
13467 				/*
13468 				 * We do Hoe's algorithm.  Refer to her
13469 				 * paper "Improving the Start-up Behavior
13470 				 * of a Congestion Control Scheme for TCP,"
13471 				 * appeared in SIGCOMM'96.
13472 				 *
13473 				 * Save highest seq no we have sent so far.
13474 				 * Be careful about the invisible FIN byte.
13475 				 */
13476 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13477 				    (tcp->tcp_unsent == 0)) {
13478 					tcp->tcp_rexmit_max = tcp->tcp_fss;
13479 				} else {
13480 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
13481 				}
13482 
13483 				/*
13484 				 * Do not allow bursty traffic during.
13485 				 * fast recovery.  Refer to Fall and Floyd's
13486 				 * paper "Simulation-based Comparisons of
13487 				 * Tahoe, Reno and SACK TCP" (in CCR?)
13488 				 * This is a best current practise.
13489 				 */
13490 				tcp->tcp_snd_burst = TCP_CWND_SS;
13491 
13492 				/*
13493 				 * For SACK:
13494 				 * Calculate tcp_pipe, which is the
13495 				 * estimated number of bytes in
13496 				 * network.
13497 				 *
13498 				 * tcp_fack is the highest sack'ed seq num
13499 				 * TCP has received.
13500 				 *
13501 				 * tcp_pipe is explained in the above quoted
13502 				 * Fall and Floyd's paper.  tcp_fack is
13503 				 * explained in Mathis and Mahdavi's
13504 				 * "Forward Acknowledgment: Refining TCP
13505 				 * Congestion Control" in SIGCOMM '96.
13506 				 */
13507 				if (tcp->tcp_snd_sack_ok) {
13508 					ASSERT(tcp->tcp_sack_info != NULL);
13509 					if (tcp->tcp_notsack_list != NULL) {
13510 						tcp->tcp_pipe = tcp->tcp_snxt -
13511 						    tcp->tcp_fack;
13512 						tcp->tcp_sack_snxt = seg_ack;
13513 						flags |= TH_NEED_SACK_REXMIT;
13514 					} else {
13515 						/*
13516 						 * Always initialize tcp_pipe
13517 						 * even though we don't have
13518 						 * any SACK info.  If later
13519 						 * we get SACK info and
13520 						 * tcp_pipe is not initialized,
13521 						 * funny things will happen.
13522 						 */
13523 						tcp->tcp_pipe =
13524 						    tcp->tcp_cwnd_ssthresh;
13525 					}
13526 				} else {
13527 					flags |= TH_REXMIT_NEEDED;
13528 				} /* tcp_snd_sack_ok */
13529 
13530 				} else {
13531 					/*
13532 					 * Here we perform congestion
13533 					 * avoidance, but NOT slow start.
13534 					 * This is known as the Fast
13535 					 * Recovery Algorithm.
13536 					 */
13537 					if (tcp->tcp_snd_sack_ok &&
13538 					    tcp->tcp_notsack_list != NULL) {
13539 						flags |= TH_NEED_SACK_REXMIT;
13540 						tcp->tcp_pipe -= mss;
13541 						if (tcp->tcp_pipe < 0)
13542 							tcp->tcp_pipe = 0;
13543 					} else {
13544 					/*
13545 					 * We know that one more packet has
13546 					 * left the pipe thus we can update
13547 					 * cwnd.
13548 					 */
13549 					cwnd = tcp->tcp_cwnd + mss;
13550 					if (cwnd > tcp->tcp_cwnd_max)
13551 						cwnd = tcp->tcp_cwnd_max;
13552 					tcp->tcp_cwnd = cwnd;
13553 					if (tcp->tcp_unsent > 0)
13554 						flags |= TH_XMIT_NEEDED;
13555 					}
13556 				}
13557 			}
13558 		} else if (tcp->tcp_zero_win_probe) {
13559 			/*
13560 			 * If the window has opened, need to arrange
13561 			 * to send additional data.
13562 			 */
13563 			if (new_swnd != 0) {
13564 				/* tcp_suna != tcp_snxt */
13565 				/* Packet contains a window update */
13566 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
13567 				tcp->tcp_zero_win_probe = 0;
13568 				tcp->tcp_timer_backoff = 0;
13569 				tcp->tcp_ms_we_have_waited = 0;
13570 
13571 				/*
13572 				 * Transmit starting with tcp_suna since
13573 				 * the one byte probe is not ack'ed.
13574 				 * If TCP has sent more than one identical
13575 				 * probe, tcp_rexmit will be set.  That means
13576 				 * tcp_ss_rexmit() will send out the one
13577 				 * byte along with new data.  Otherwise,
13578 				 * fake the retransmission.
13579 				 */
13580 				flags |= TH_XMIT_NEEDED;
13581 				if (!tcp->tcp_rexmit) {
13582 					tcp->tcp_rexmit = B_TRUE;
13583 					tcp->tcp_dupack_cnt = 0;
13584 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13585 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
13586 				}
13587 			}
13588 		}
13589 		goto swnd_update;
13590 	}
13591 
13592 	/*
13593 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
13594 	 * If the ACK value acks something that we have not yet sent, it might
13595 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
13596 	 * other side.
13597 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
13598 	 * state is handled above, so we can always just drop the segment and
13599 	 * send an ACK here.
13600 	 *
13601 	 * Should we send ACKs in response to ACK only segments?
13602 	 */
13603 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13604 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
13605 		/* drop the received segment */
13606 		freemsg(mp);
13607 
13608 		/*
13609 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
13610 		 * greater than 0, check if the number of such
13611 		 * bogus ACks is greater than that count.  If yes,
13612 		 * don't send back any ACK.  This prevents TCP from
13613 		 * getting into an ACK storm if somehow an attacker
13614 		 * successfully spoofs an acceptable segment to our
13615 		 * peer.
13616 		 */
13617 		if (tcp_drop_ack_unsent_cnt > 0 &&
13618 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
13619 			TCP_STAT(tcp_in_ack_unsent_drop);
13620 			return;
13621 		}
13622 		mp = tcp_ack_mp(tcp);
13623 		if (mp != NULL) {
13624 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
13625 			BUMP_LOCAL(tcp->tcp_obsegs);
13626 			BUMP_MIB(&tcp_mib, tcpOutAck);
13627 			tcp_send_data(tcp, tcp->tcp_wq, mp);
13628 		}
13629 		return;
13630 	}
13631 
13632 	/*
13633 	 * TCP gets a new ACK, update the notsack'ed list to delete those
13634 	 * blocks that are covered by this ACK.
13635 	 */
13636 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
13637 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
13638 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
13639 	}
13640 
13641 	/*
13642 	 * If we got an ACK after fast retransmit, check to see
13643 	 * if it is a partial ACK.  If it is not and the congestion
13644 	 * window was inflated to account for the other side's
13645 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
13646 	 */
13647 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
13648 		ASSERT(tcp->tcp_rexmit == B_FALSE);
13649 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
13650 			tcp->tcp_dupack_cnt = 0;
13651 			/*
13652 			 * Restore the orig tcp_cwnd_ssthresh after
13653 			 * fast retransmit phase.
13654 			 */
13655 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
13656 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
13657 			}
13658 			tcp->tcp_rexmit_max = seg_ack;
13659 			tcp->tcp_cwnd_cnt = 0;
13660 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13661 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13662 
13663 			/*
13664 			 * Remove all notsack info to avoid confusion with
13665 			 * the next fast retrasnmit/recovery phase.
13666 			 */
13667 			if (tcp->tcp_snd_sack_ok &&
13668 			    tcp->tcp_notsack_list != NULL) {
13669 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
13670 			}
13671 		} else {
13672 			if (tcp->tcp_snd_sack_ok &&
13673 			    tcp->tcp_notsack_list != NULL) {
13674 				flags |= TH_NEED_SACK_REXMIT;
13675 				tcp->tcp_pipe -= mss;
13676 				if (tcp->tcp_pipe < 0)
13677 					tcp->tcp_pipe = 0;
13678 			} else {
13679 				/*
13680 				 * Hoe's algorithm:
13681 				 *
13682 				 * Retransmit the unack'ed segment and
13683 				 * restart fast recovery.  Note that we
13684 				 * need to scale back tcp_cwnd to the
13685 				 * original value when we started fast
13686 				 * recovery.  This is to prevent overly
13687 				 * aggressive behaviour in sending new
13688 				 * segments.
13689 				 */
13690 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
13691 					tcp_dupack_fast_retransmit * mss;
13692 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
13693 				flags |= TH_REXMIT_NEEDED;
13694 			}
13695 		}
13696 	} else {
13697 		tcp->tcp_dupack_cnt = 0;
13698 		if (tcp->tcp_rexmit) {
13699 			/*
13700 			 * TCP is retranmitting.  If the ACK ack's all
13701 			 * outstanding data, update tcp_rexmit_max and
13702 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
13703 			 * to the correct value.
13704 			 *
13705 			 * Note that SEQ_LEQ() is used.  This is to avoid
13706 			 * unnecessary fast retransmit caused by dup ACKs
13707 			 * received when TCP does slow start retransmission
13708 			 * after a time out.  During this phase, TCP may
13709 			 * send out segments which are already received.
13710 			 * This causes dup ACKs to be sent back.
13711 			 */
13712 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
13713 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
13714 					tcp->tcp_rexmit_nxt = seg_ack;
13715 				}
13716 				if (seg_ack != tcp->tcp_rexmit_max) {
13717 					flags |= TH_XMIT_NEEDED;
13718 				}
13719 			} else {
13720 				tcp->tcp_rexmit = B_FALSE;
13721 				tcp->tcp_xmit_zc_clean = B_FALSE;
13722 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13723 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13724 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13725 			}
13726 			tcp->tcp_ms_we_have_waited = 0;
13727 		}
13728 	}
13729 
13730 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
13731 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
13732 	tcp->tcp_suna = seg_ack;
13733 	if (tcp->tcp_zero_win_probe != 0) {
13734 		tcp->tcp_zero_win_probe = 0;
13735 		tcp->tcp_timer_backoff = 0;
13736 	}
13737 
13738 	/*
13739 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
13740 	 * Note that it cannot be the SYN being ack'ed.  The code flow
13741 	 * will not reach here.
13742 	 */
13743 	if (mp1 == NULL) {
13744 		goto fin_acked;
13745 	}
13746 
13747 	/*
13748 	 * Update the congestion window.
13749 	 *
13750 	 * If TCP is not ECN capable or TCP is ECN capable but the
13751 	 * congestion experience bit is not set, increase the tcp_cwnd as
13752 	 * usual.
13753 	 */
13754 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
13755 		cwnd = tcp->tcp_cwnd;
13756 		add = mss;
13757 
13758 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
13759 			/*
13760 			 * This is to prevent an increase of less than 1 MSS of
13761 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
13762 			 * may send out tinygrams in order to preserve mblk
13763 			 * boundaries.
13764 			 *
13765 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
13766 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
13767 			 * increased by 1 MSS for every RTTs.
13768 			 */
13769 			if (tcp->tcp_cwnd_cnt <= 0) {
13770 				tcp->tcp_cwnd_cnt = cwnd + add;
13771 			} else {
13772 				tcp->tcp_cwnd_cnt -= add;
13773 				add = 0;
13774 			}
13775 		}
13776 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
13777 	}
13778 
13779 	/* See if the latest urgent data has been acknowledged */
13780 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
13781 	    SEQ_GT(seg_ack, tcp->tcp_urg))
13782 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
13783 
13784 	/* Can we update the RTT estimates? */
13785 	if (tcp->tcp_snd_ts_ok) {
13786 		/* Ignore zero timestamp echo-reply. */
13787 		if (tcpopt.tcp_opt_ts_ecr != 0) {
13788 			tcp_set_rto(tcp, (int32_t)lbolt -
13789 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
13790 		}
13791 
13792 		/* If needed, restart the timer. */
13793 		if (tcp->tcp_set_timer == 1) {
13794 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13795 			tcp->tcp_set_timer = 0;
13796 		}
13797 		/*
13798 		 * Update tcp_csuna in case the other side stops sending
13799 		 * us timestamps.
13800 		 */
13801 		tcp->tcp_csuna = tcp->tcp_snxt;
13802 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
13803 		/*
13804 		 * An ACK sequence we haven't seen before, so get the RTT
13805 		 * and update the RTO. But first check if the timestamp is
13806 		 * valid to use.
13807 		 */
13808 		if ((mp1->b_next != NULL) &&
13809 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
13810 			tcp_set_rto(tcp, (int32_t)lbolt -
13811 			    (int32_t)(intptr_t)mp1->b_prev);
13812 		else
13813 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
13814 
13815 		/* Remeber the last sequence to be ACKed */
13816 		tcp->tcp_csuna = seg_ack;
13817 		if (tcp->tcp_set_timer == 1) {
13818 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13819 			tcp->tcp_set_timer = 0;
13820 		}
13821 	} else {
13822 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
13823 	}
13824 
13825 	/* Eat acknowledged bytes off the xmit queue. */
13826 	for (;;) {
13827 		mblk_t	*mp2;
13828 		uchar_t	*wptr;
13829 
13830 		wptr = mp1->b_wptr;
13831 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
13832 		bytes_acked -= (int)(wptr - mp1->b_rptr);
13833 		if (bytes_acked < 0) {
13834 			mp1->b_rptr = wptr + bytes_acked;
13835 			/*
13836 			 * Set a new timestamp if all the bytes timed by the
13837 			 * old timestamp have been ack'ed.
13838 			 */
13839 			if (SEQ_GT(seg_ack,
13840 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
13841 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
13842 				mp1->b_next = NULL;
13843 			}
13844 			break;
13845 		}
13846 		mp1->b_next = NULL;
13847 		mp1->b_prev = NULL;
13848 		mp2 = mp1;
13849 		mp1 = mp1->b_cont;
13850 
13851 		/*
13852 		 * This notification is required for some zero-copy
13853 		 * clients to maintain a copy semantic. After the data
13854 		 * is ack'ed, client is safe to modify or reuse the buffer.
13855 		 */
13856 		if (tcp->tcp_snd_zcopy_aware &&
13857 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
13858 			tcp_zcopy_notify(tcp);
13859 		freeb(mp2);
13860 		if (bytes_acked == 0) {
13861 			if (mp1 == NULL) {
13862 				/* Everything is ack'ed, clear the tail. */
13863 				tcp->tcp_xmit_tail = NULL;
13864 				/*
13865 				 * Cancel the timer unless we are still
13866 				 * waiting for an ACK for the FIN packet.
13867 				 */
13868 				if (tcp->tcp_timer_tid != 0 &&
13869 				    tcp->tcp_snxt == tcp->tcp_suna) {
13870 					(void) TCP_TIMER_CANCEL(tcp,
13871 					    tcp->tcp_timer_tid);
13872 					tcp->tcp_timer_tid = 0;
13873 				}
13874 				goto pre_swnd_update;
13875 			}
13876 			if (mp2 != tcp->tcp_xmit_tail)
13877 				break;
13878 			tcp->tcp_xmit_tail = mp1;
13879 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13880 			    (uintptr_t)INT_MAX);
13881 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
13882 			    mp1->b_rptr);
13883 			break;
13884 		}
13885 		if (mp1 == NULL) {
13886 			/*
13887 			 * More was acked but there is nothing more
13888 			 * outstanding.  This means that the FIN was
13889 			 * just acked or that we're talking to a clown.
13890 			 */
13891 fin_acked:
13892 			ASSERT(tcp->tcp_fin_sent);
13893 			tcp->tcp_xmit_tail = NULL;
13894 			if (tcp->tcp_fin_sent) {
13895 				/* FIN was acked - making progress */
13896 				if (tcp->tcp_ipversion == IPV6_VERSION &&
13897 				    !tcp->tcp_fin_acked)
13898 					tcp->tcp_ip_forward_progress = B_TRUE;
13899 				tcp->tcp_fin_acked = B_TRUE;
13900 				if (tcp->tcp_linger_tid != 0 &&
13901 				    TCP_TIMER_CANCEL(tcp,
13902 					tcp->tcp_linger_tid) >= 0) {
13903 					tcp_stop_lingering(tcp);
13904 				}
13905 			} else {
13906 				/*
13907 				 * We should never get here because
13908 				 * we have already checked that the
13909 				 * number of bytes ack'ed should be
13910 				 * smaller than or equal to what we
13911 				 * have sent so far (it is the
13912 				 * acceptability check of the ACK).
13913 				 * We can only get here if the send
13914 				 * queue is corrupted.
13915 				 *
13916 				 * Terminate the connection and
13917 				 * panic the system.  It is better
13918 				 * for us to panic instead of
13919 				 * continuing to avoid other disaster.
13920 				 */
13921 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
13922 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
13923 				panic("Memory corruption "
13924 				    "detected for connection %s.",
13925 				    tcp_display(tcp, NULL,
13926 					DISP_ADDR_AND_PORT));
13927 				/*NOTREACHED*/
13928 			}
13929 			goto pre_swnd_update;
13930 		}
13931 		ASSERT(mp2 != tcp->tcp_xmit_tail);
13932 	}
13933 	if (tcp->tcp_unsent) {
13934 		flags |= TH_XMIT_NEEDED;
13935 	}
13936 pre_swnd_update:
13937 	tcp->tcp_xmit_head = mp1;
13938 swnd_update:
13939 	/*
13940 	 * The following check is different from most other implementations.
13941 	 * For bi-directional transfer, when segments are dropped, the
13942 	 * "normal" check will not accept a window update in those
13943 	 * retransmitted segemnts.  Failing to do that, TCP may send out
13944 	 * segments which are outside receiver's window.  As TCP accepts
13945 	 * the ack in those retransmitted segments, if the window update in
13946 	 * the same segment is not accepted, TCP will incorrectly calculates
13947 	 * that it can send more segments.  This can create a deadlock
13948 	 * with the receiver if its window becomes zero.
13949 	 */
13950 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
13951 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
13952 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
13953 		/*
13954 		 * The criteria for update is:
13955 		 *
13956 		 * 1. the segment acknowledges some data.  Or
13957 		 * 2. the segment is new, i.e. it has a higher seq num. Or
13958 		 * 3. the segment is not old and the advertised window is
13959 		 * larger than the previous advertised window.
13960 		 */
13961 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
13962 			flags |= TH_XMIT_NEEDED;
13963 		tcp->tcp_swnd = new_swnd;
13964 		if (new_swnd > tcp->tcp_max_swnd)
13965 			tcp->tcp_max_swnd = new_swnd;
13966 		tcp->tcp_swl1 = seg_seq;
13967 		tcp->tcp_swl2 = seg_ack;
13968 	}
13969 est:
13970 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
13971 		switch (tcp->tcp_state) {
13972 		case TCPS_FIN_WAIT_1:
13973 			if (tcp->tcp_fin_acked) {
13974 				tcp->tcp_state = TCPS_FIN_WAIT_2;
13975 				/*
13976 				 * We implement the non-standard BSD/SunOS
13977 				 * FIN_WAIT_2 flushing algorithm.
13978 				 * If there is no user attached to this
13979 				 * TCP endpoint, then this TCP struct
13980 				 * could hang around forever in FIN_WAIT_2
13981 				 * state if the peer forgets to send us
13982 				 * a FIN.  To prevent this, we wait only
13983 				 * 2*MSL (a convenient time value) for
13984 				 * the FIN to arrive.  If it doesn't show up,
13985 				 * we flush the TCP endpoint.  This algorithm,
13986 				 * though a violation of RFC-793, has worked
13987 				 * for over 10 years in BSD systems.
13988 				 * Note: SunOS 4.x waits 675 seconds before
13989 				 * flushing the FIN_WAIT_2 connection.
13990 				 */
13991 				TCP_TIMER_RESTART(tcp,
13992 				    tcp_fin_wait_2_flush_interval);
13993 			}
13994 			break;
13995 		case TCPS_FIN_WAIT_2:
13996 			break;	/* Shutdown hook? */
13997 		case TCPS_LAST_ACK:
13998 			freemsg(mp);
13999 			if (tcp->tcp_fin_acked) {
14000 				(void) tcp_clean_death(tcp, 0, 19);
14001 				return;
14002 			}
14003 			goto xmit_check;
14004 		case TCPS_CLOSING:
14005 			if (tcp->tcp_fin_acked) {
14006 				tcp->tcp_state = TCPS_TIME_WAIT;
14007 				if (!TCP_IS_DETACHED(tcp)) {
14008 					TCP_TIMER_RESTART(tcp,
14009 					    tcp_time_wait_interval);
14010 				} else {
14011 					tcp_time_wait_append(tcp);
14012 					TCP_DBGSTAT(tcp_rput_time_wait);
14013 				}
14014 			}
14015 			/*FALLTHRU*/
14016 		case TCPS_CLOSE_WAIT:
14017 			freemsg(mp);
14018 			goto xmit_check;
14019 		default:
14020 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14021 			break;
14022 		}
14023 	}
14024 	if (flags & TH_FIN) {
14025 		/* Make sure we ack the fin */
14026 		flags |= TH_ACK_NEEDED;
14027 		if (!tcp->tcp_fin_rcvd) {
14028 			tcp->tcp_fin_rcvd = B_TRUE;
14029 			tcp->tcp_rnxt++;
14030 			tcph = tcp->tcp_tcph;
14031 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14032 
14033 			/*
14034 			 * Generate the ordrel_ind at the end unless we
14035 			 * are an eager guy.
14036 			 * In the eager case tcp_rsrv will do this when run
14037 			 * after tcp_accept is done.
14038 			 */
14039 			if (tcp->tcp_listener == NULL &&
14040 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14041 				flags |= TH_ORDREL_NEEDED;
14042 			switch (tcp->tcp_state) {
14043 			case TCPS_SYN_RCVD:
14044 			case TCPS_ESTABLISHED:
14045 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14046 				/* Keepalive? */
14047 				break;
14048 			case TCPS_FIN_WAIT_1:
14049 				if (!tcp->tcp_fin_acked) {
14050 					tcp->tcp_state = TCPS_CLOSING;
14051 					break;
14052 				}
14053 				/* FALLTHRU */
14054 			case TCPS_FIN_WAIT_2:
14055 				tcp->tcp_state = TCPS_TIME_WAIT;
14056 				if (!TCP_IS_DETACHED(tcp)) {
14057 					TCP_TIMER_RESTART(tcp,
14058 					    tcp_time_wait_interval);
14059 				} else {
14060 					tcp_time_wait_append(tcp);
14061 					TCP_DBGSTAT(tcp_rput_time_wait);
14062 				}
14063 				if (seg_len) {
14064 					/*
14065 					 * implies data piggybacked on FIN.
14066 					 * break to handle data.
14067 					 */
14068 					break;
14069 				}
14070 				freemsg(mp);
14071 				goto ack_check;
14072 			}
14073 		}
14074 	}
14075 	if (mp == NULL)
14076 		goto xmit_check;
14077 	if (seg_len == 0) {
14078 		freemsg(mp);
14079 		goto xmit_check;
14080 	}
14081 	if (mp->b_rptr == mp->b_wptr) {
14082 		/*
14083 		 * The header has been consumed, so we remove the
14084 		 * zero-length mblk here.
14085 		 */
14086 		mp1 = mp;
14087 		mp = mp->b_cont;
14088 		freeb(mp1);
14089 	}
14090 	tcph = tcp->tcp_tcph;
14091 	tcp->tcp_rack_cnt++;
14092 	{
14093 		uint32_t cur_max;
14094 
14095 		cur_max = tcp->tcp_rack_cur_max;
14096 		if (tcp->tcp_rack_cnt >= cur_max) {
14097 			/*
14098 			 * We have more unacked data than we should - send
14099 			 * an ACK now.
14100 			 */
14101 			flags |= TH_ACK_NEEDED;
14102 			cur_max++;
14103 			if (cur_max > tcp->tcp_rack_abs_max)
14104 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14105 			else
14106 				tcp->tcp_rack_cur_max = cur_max;
14107 		} else if (TCP_IS_DETACHED(tcp)) {
14108 			/* We don't have an ACK timer for detached TCP. */
14109 			flags |= TH_ACK_NEEDED;
14110 		} else if (seg_len < mss) {
14111 			/*
14112 			 * If we get a segment that is less than an mss, and we
14113 			 * already have unacknowledged data, and the amount
14114 			 * unacknowledged is not a multiple of mss, then we
14115 			 * better generate an ACK now.  Otherwise, this may be
14116 			 * the tail piece of a transaction, and we would rather
14117 			 * wait for the response.
14118 			 */
14119 			uint32_t udif;
14120 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14121 			    (uintptr_t)INT_MAX);
14122 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14123 			if (udif && (udif % mss))
14124 				flags |= TH_ACK_NEEDED;
14125 			else
14126 				flags |= TH_ACK_TIMER_NEEDED;
14127 		} else {
14128 			/* Start delayed ack timer */
14129 			flags |= TH_ACK_TIMER_NEEDED;
14130 		}
14131 	}
14132 	tcp->tcp_rnxt += seg_len;
14133 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14134 
14135 	/* Update SACK list */
14136 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14137 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14138 		    &(tcp->tcp_num_sack_blk));
14139 	}
14140 
14141 	if (tcp->tcp_urp_mp) {
14142 		tcp->tcp_urp_mp->b_cont = mp;
14143 		mp = tcp->tcp_urp_mp;
14144 		tcp->tcp_urp_mp = NULL;
14145 		/* Ready for a new signal. */
14146 		tcp->tcp_urp_last_valid = B_FALSE;
14147 #ifdef DEBUG
14148 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14149 		    "tcp_rput: sending exdata_ind %s",
14150 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14151 #endif /* DEBUG */
14152 	}
14153 
14154 	/*
14155 	 * Check for ancillary data changes compared to last segment.
14156 	 */
14157 	if (tcp->tcp_ipv6_recvancillary != 0) {
14158 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14159 		if (mp == NULL)
14160 			return;
14161 	}
14162 
14163 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14164 		/*
14165 		 * Side queue inbound data until the accept happens.
14166 		 * tcp_accept/tcp_rput drains this when the accept happens.
14167 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14168 		 * T_EXDATA_IND) it is queued on b_next.
14169 		 * XXX Make urgent data use this. Requires:
14170 		 *	Removing tcp_listener check for TH_URG
14171 		 *	Making M_PCPROTO and MARK messages skip the eager case
14172 		 */
14173 		tcp_rcv_enqueue(tcp, mp, seg_len);
14174 	} else {
14175 		if (mp->b_datap->db_type != M_DATA ||
14176 		    (flags & TH_MARKNEXT_NEEDED)) {
14177 			if (tcp->tcp_rcv_list != NULL) {
14178 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14179 			}
14180 			ASSERT(tcp->tcp_rcv_list == NULL ||
14181 			    tcp->tcp_fused_sigurg);
14182 			if (flags & TH_MARKNEXT_NEEDED) {
14183 #ifdef DEBUG
14184 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14185 				    "tcp_rput: sending MSGMARKNEXT %s",
14186 				    tcp_display(tcp, NULL,
14187 				    DISP_PORT_ONLY));
14188 #endif /* DEBUG */
14189 				mp->b_flag |= MSGMARKNEXT;
14190 				flags &= ~TH_MARKNEXT_NEEDED;
14191 			}
14192 			putnext(tcp->tcp_rq, mp);
14193 			if (!canputnext(tcp->tcp_rq))
14194 				tcp->tcp_rwnd -= seg_len;
14195 		} else if (((flags & (TH_PUSH|TH_FIN)) ||
14196 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) &&
14197 		    (sqp != NULL)) {
14198 			if (tcp->tcp_rcv_list != NULL) {
14199 				/*
14200 				 * Enqueue the new segment first and then
14201 				 * call tcp_rcv_drain() to send all data
14202 				 * up.  The other way to do this is to
14203 				 * send all queued data up and then call
14204 				 * putnext() to send the new segment up.
14205 				 * This way can remove the else part later
14206 				 * on.
14207 				 *
14208 				 * We don't this to avoid one more call to
14209 				 * canputnext() as tcp_rcv_drain() needs to
14210 				 * call canputnext().
14211 				 */
14212 				tcp_rcv_enqueue(tcp, mp, seg_len);
14213 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14214 			} else {
14215 				putnext(tcp->tcp_rq, mp);
14216 				if (!canputnext(tcp->tcp_rq))
14217 					tcp->tcp_rwnd -= seg_len;
14218 			}
14219 		} else {
14220 			/*
14221 			 * Enqueue all packets when processing an mblk
14222 			 * from the co queue and also enqueue normal packets.
14223 			 */
14224 			tcp_rcv_enqueue(tcp, mp, seg_len);
14225 		}
14226 		/*
14227 		 * Make sure the timer is running if we have data waiting
14228 		 * for a push bit. This provides resiliency against
14229 		 * implementations that do not correctly generate push bits.
14230 		 */
14231 		if ((sqp != NULL) && tcp->tcp_rcv_list != NULL &&
14232 		    tcp->tcp_push_tid == 0) {
14233 			/*
14234 			 * The connection may be closed at this point, so don't
14235 			 * do anything for a detached tcp.
14236 			 */
14237 			if (!TCP_IS_DETACHED(tcp))
14238 				tcp->tcp_push_tid = TCP_TIMER(tcp,
14239 				    tcp_push_timer,
14240 				    MSEC_TO_TICK(tcp_push_timer_interval));
14241 		}
14242 	}
14243 xmit_check:
14244 	/* Is there anything left to do? */
14245 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14246 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
14247 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
14248 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14249 		goto done;
14250 
14251 	/* Any transmit work to do and a non-zero window? */
14252 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
14253 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
14254 		if (flags & TH_REXMIT_NEEDED) {
14255 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
14256 
14257 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
14258 			if (snd_size > mss)
14259 				snd_size = mss;
14260 			if (snd_size > tcp->tcp_swnd)
14261 				snd_size = tcp->tcp_swnd;
14262 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
14263 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
14264 			    B_TRUE);
14265 
14266 			if (mp1 != NULL) {
14267 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14268 				tcp->tcp_csuna = tcp->tcp_snxt;
14269 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
14270 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
14271 				TCP_RECORD_TRACE(tcp, mp1,
14272 				    TCP_TRACE_SEND_PKT);
14273 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
14274 			}
14275 		}
14276 		if (flags & TH_NEED_SACK_REXMIT) {
14277 			tcp_sack_rxmit(tcp, &flags);
14278 		}
14279 		/*
14280 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
14281 		 * out new segment.  Note that tcp_rexmit should not be
14282 		 * set, otherwise TH_LIMIT_XMIT should not be set.
14283 		 */
14284 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
14285 			if (!tcp->tcp_rexmit) {
14286 				tcp_wput_data(tcp, NULL, B_FALSE);
14287 			} else {
14288 				tcp_ss_rexmit(tcp);
14289 			}
14290 		}
14291 		/*
14292 		 * Adjust tcp_cwnd back to normal value after sending
14293 		 * new data segments.
14294 		 */
14295 		if (flags & TH_LIMIT_XMIT) {
14296 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
14297 			/*
14298 			 * This will restart the timer.  Restarting the
14299 			 * timer is used to avoid a timeout before the
14300 			 * limited transmitted segment's ACK gets back.
14301 			 */
14302 			if (tcp->tcp_xmit_head != NULL)
14303 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14304 		}
14305 
14306 		/* Anything more to do? */
14307 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
14308 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14309 			goto done;
14310 	}
14311 ack_check:
14312 	if (flags & TH_SEND_URP_MARK) {
14313 		ASSERT(tcp->tcp_urp_mark_mp);
14314 		/*
14315 		 * Send up any queued data and then send the mark message
14316 		 */
14317 		if (tcp->tcp_rcv_list != NULL) {
14318 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14319 		}
14320 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14321 
14322 		mp1 = tcp->tcp_urp_mark_mp;
14323 		tcp->tcp_urp_mark_mp = NULL;
14324 #ifdef DEBUG
14325 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14326 		    "tcp_rput: sending zero-length %s %s",
14327 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
14328 		    "MSGNOTMARKNEXT"),
14329 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14330 #endif /* DEBUG */
14331 		putnext(tcp->tcp_rq, mp1);
14332 		flags &= ~TH_SEND_URP_MARK;
14333 	}
14334 	if (flags & TH_ACK_NEEDED) {
14335 		/*
14336 		 * Time to send an ack for some reason.
14337 		 */
14338 		mp1 = tcp_ack_mp(tcp);
14339 
14340 		if (mp1 != NULL) {
14341 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
14342 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
14343 			BUMP_LOCAL(tcp->tcp_obsegs);
14344 			BUMP_MIB(&tcp_mib, tcpOutAck);
14345 		}
14346 		if (tcp->tcp_ack_tid != 0) {
14347 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
14348 			tcp->tcp_ack_tid = 0;
14349 		}
14350 	}
14351 	if (flags & TH_ACK_TIMER_NEEDED) {
14352 		/*
14353 		 * Arrange for deferred ACK or push wait timeout.
14354 		 * Start timer if it is not already running.
14355 		 */
14356 		if (tcp->tcp_ack_tid == 0) {
14357 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
14358 			    MSEC_TO_TICK(tcp->tcp_localnet ?
14359 			    (clock_t)tcp_local_dack_interval :
14360 			    (clock_t)tcp_deferred_ack_interval));
14361 		}
14362 	}
14363 	if (flags & TH_ORDREL_NEEDED) {
14364 		/*
14365 		 * Send up the ordrel_ind unless we are an eager guy.
14366 		 * In the eager case tcp_rsrv will do this when run
14367 		 * after tcp_accept is done.
14368 		 */
14369 		ASSERT(tcp->tcp_listener == NULL);
14370 		if (tcp->tcp_rcv_list != NULL) {
14371 			/*
14372 			 * Push any mblk(s) enqueued from co processing.
14373 			 */
14374 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14375 		}
14376 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14377 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
14378 			tcp->tcp_ordrel_done = B_TRUE;
14379 			putnext(tcp->tcp_rq, mp1);
14380 			if (tcp->tcp_deferred_clean_death) {
14381 				/*
14382 				 * tcp_clean_death was deferred
14383 				 * for T_ORDREL_IND - do it now
14384 				 */
14385 				(void) tcp_clean_death(tcp,
14386 				    tcp->tcp_client_errno, 20);
14387 				tcp->tcp_deferred_clean_death =	B_FALSE;
14388 			}
14389 		} else {
14390 			/*
14391 			 * Run the orderly release in the
14392 			 * service routine.
14393 			 */
14394 			qenable(tcp->tcp_rq);
14395 			/*
14396 			 * Caveat(XXX): The machine may be so
14397 			 * overloaded that tcp_rsrv() is not scheduled
14398 			 * until after the endpoint has transitioned
14399 			 * to TCPS_TIME_WAIT
14400 			 * and tcp_time_wait_interval expires. Then
14401 			 * tcp_timer() will blow away state in tcp_t
14402 			 * and T_ORDREL_IND will never be delivered
14403 			 * upstream. Unlikely but potentially
14404 			 * a problem.
14405 			 */
14406 		}
14407 	}
14408 done:
14409 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14410 }
14411 
14412 /*
14413  * This function does PAWS protection check. Returns B_TRUE if the
14414  * segment passes the PAWS test, else returns B_FALSE.
14415  */
14416 boolean_t
14417 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
14418 {
14419 	uint8_t	flags;
14420 	int	options;
14421 	uint8_t *up;
14422 
14423 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
14424 	/*
14425 	 * If timestamp option is aligned nicely, get values inline,
14426 	 * otherwise call general routine to parse.  Only do that
14427 	 * if timestamp is the only option.
14428 	 */
14429 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
14430 	    TCPOPT_REAL_TS_LEN &&
14431 	    OK_32PTR((up = ((uint8_t *)tcph) +
14432 	    TCP_MIN_HEADER_LENGTH)) &&
14433 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
14434 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
14435 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
14436 
14437 		options = TCP_OPT_TSTAMP_PRESENT;
14438 	} else {
14439 		if (tcp->tcp_snd_sack_ok) {
14440 			tcpoptp->tcp = tcp;
14441 		} else {
14442 			tcpoptp->tcp = NULL;
14443 		}
14444 		options = tcp_parse_options(tcph, tcpoptp);
14445 	}
14446 
14447 	if (options & TCP_OPT_TSTAMP_PRESENT) {
14448 		/*
14449 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
14450 		 * regardless of the timestamp, page 18 RFC 1323.bis.
14451 		 */
14452 		if ((flags & TH_RST) == 0 &&
14453 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
14454 		    tcp->tcp_ts_recent)) {
14455 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
14456 			    PAWS_TIMEOUT)) {
14457 				/* This segment is not acceptable. */
14458 				return (B_FALSE);
14459 			} else {
14460 				/*
14461 				 * Connection has been idle for
14462 				 * too long.  Reset the timestamp
14463 				 * and assume the segment is valid.
14464 				 */
14465 				tcp->tcp_ts_recent =
14466 				    tcpoptp->tcp_opt_ts_val;
14467 			}
14468 		}
14469 	} else {
14470 		/*
14471 		 * If we don't get a timestamp on every packet, we
14472 		 * figure we can't really trust 'em, so we stop sending
14473 		 * and parsing them.
14474 		 */
14475 		tcp->tcp_snd_ts_ok = B_FALSE;
14476 
14477 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14478 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14479 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
14480 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
14481 		if (tcp->tcp_snd_sack_ok) {
14482 			ASSERT(tcp->tcp_sack_info != NULL);
14483 			tcp->tcp_max_sack_blk = 4;
14484 		}
14485 	}
14486 	return (B_TRUE);
14487 }
14488 
14489 /*
14490  * Attach ancillary data to a received TCP segments for the
14491  * ancillary pieces requested by the application that are
14492  * different than they were in the previous data segment.
14493  *
14494  * Save the "current" values once memory allocation is ok so that
14495  * when memory allocation fails we can just wait for the next data segment.
14496  */
14497 static mblk_t *
14498 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
14499 {
14500 	struct T_optdata_ind *todi;
14501 	int optlen;
14502 	uchar_t *optptr;
14503 	struct T_opthdr *toh;
14504 	uint_t addflag;	/* Which pieces to add */
14505 	mblk_t *mp1;
14506 
14507 	optlen = 0;
14508 	addflag = 0;
14509 	/* If app asked for pktinfo and the index has changed ... */
14510 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
14511 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
14512 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
14513 		optlen += sizeof (struct T_opthdr) +
14514 		    sizeof (struct in6_pktinfo);
14515 		addflag |= TCP_IPV6_RECVPKTINFO;
14516 	}
14517 	/* If app asked for hoplimit and it has changed ... */
14518 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
14519 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
14520 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
14521 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14522 		addflag |= TCP_IPV6_RECVHOPLIMIT;
14523 	}
14524 	/* If app asked for tclass and it has changed ... */
14525 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
14526 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
14527 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
14528 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14529 		addflag |= TCP_IPV6_RECVTCLASS;
14530 	}
14531 	/* If app asked for hopbyhop headers and it has changed ... */
14532 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
14533 	    tcp_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
14534 		(ipp->ipp_fields & IPPF_HOPOPTS),
14535 		ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
14536 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
14537 		addflag |= TCP_IPV6_RECVHOPOPTS;
14538 		if (!tcp_allocbuf((void **)&tcp->tcp_hopopts,
14539 		    &tcp->tcp_hopoptslen,
14540 		    (ipp->ipp_fields & IPPF_HOPOPTS),
14541 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
14542 			return (mp);
14543 	}
14544 	/* If app asked for dst headers before routing headers ... */
14545 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
14546 	    tcp_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
14547 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
14548 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
14549 		optlen += sizeof (struct T_opthdr) +
14550 		    ipp->ipp_rtdstoptslen;
14551 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
14552 		if (!tcp_allocbuf((void **)&tcp->tcp_rtdstopts,
14553 		    &tcp->tcp_rtdstoptslen,
14554 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
14555 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
14556 			return (mp);
14557 	}
14558 	/* If app asked for routing headers and it has changed ... */
14559 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
14560 	    tcp_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
14561 		(ipp->ipp_fields & IPPF_RTHDR),
14562 		ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
14563 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
14564 		addflag |= TCP_IPV6_RECVRTHDR;
14565 		if (!tcp_allocbuf((void **)&tcp->tcp_rthdr,
14566 		    &tcp->tcp_rthdrlen,
14567 		    (ipp->ipp_fields & IPPF_RTHDR),
14568 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
14569 			return (mp);
14570 	}
14571 	/* If app asked for dest headers and it has changed ... */
14572 	if ((tcp->tcp_ipv6_recvancillary &
14573 		(TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
14574 	    tcp_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
14575 		(ipp->ipp_fields & IPPF_DSTOPTS),
14576 		ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
14577 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
14578 		addflag |= TCP_IPV6_RECVDSTOPTS;
14579 		if (!tcp_allocbuf((void **)&tcp->tcp_dstopts,
14580 		    &tcp->tcp_dstoptslen,
14581 		    (ipp->ipp_fields & IPPF_DSTOPTS),
14582 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
14583 			return (mp);
14584 	}
14585 
14586 	if (optlen == 0) {
14587 		/* Nothing to add */
14588 		return (mp);
14589 	}
14590 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
14591 	if (mp1 == NULL) {
14592 		/*
14593 		 * Defer sending ancillary data until the next TCP segment
14594 		 * arrives.
14595 		 */
14596 		return (mp);
14597 	}
14598 	mp1->b_cont = mp;
14599 	mp = mp1;
14600 	mp->b_wptr += sizeof (*todi) + optlen;
14601 	mp->b_datap->db_type = M_PROTO;
14602 	todi = (struct T_optdata_ind *)mp->b_rptr;
14603 	todi->PRIM_type = T_OPTDATA_IND;
14604 	todi->DATA_flag = 1;	/* MORE data */
14605 	todi->OPT_length = optlen;
14606 	todi->OPT_offset = sizeof (*todi);
14607 	optptr = (uchar_t *)&todi[1];
14608 	/*
14609 	 * If app asked for pktinfo and the index has changed ...
14610 	 * Note that the local address never changes for the connection.
14611 	 */
14612 	if (addflag & TCP_IPV6_RECVPKTINFO) {
14613 		struct in6_pktinfo *pkti;
14614 
14615 		toh = (struct T_opthdr *)optptr;
14616 		toh->level = IPPROTO_IPV6;
14617 		toh->name = IPV6_PKTINFO;
14618 		toh->len = sizeof (*toh) + sizeof (*pkti);
14619 		toh->status = 0;
14620 		optptr += sizeof (*toh);
14621 		pkti = (struct in6_pktinfo *)optptr;
14622 		if (tcp->tcp_ipversion == IPV6_VERSION)
14623 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
14624 		else
14625 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
14626 			    &pkti->ipi6_addr);
14627 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
14628 		optptr += sizeof (*pkti);
14629 		ASSERT(OK_32PTR(optptr));
14630 		/* Save as "last" value */
14631 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
14632 	}
14633 	/* If app asked for hoplimit and it has changed ... */
14634 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
14635 		toh = (struct T_opthdr *)optptr;
14636 		toh->level = IPPROTO_IPV6;
14637 		toh->name = IPV6_HOPLIMIT;
14638 		toh->len = sizeof (*toh) + sizeof (uint_t);
14639 		toh->status = 0;
14640 		optptr += sizeof (*toh);
14641 		*(uint_t *)optptr = ipp->ipp_hoplimit;
14642 		optptr += sizeof (uint_t);
14643 		ASSERT(OK_32PTR(optptr));
14644 		/* Save as "last" value */
14645 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
14646 	}
14647 	/* If app asked for tclass and it has changed ... */
14648 	if (addflag & TCP_IPV6_RECVTCLASS) {
14649 		toh = (struct T_opthdr *)optptr;
14650 		toh->level = IPPROTO_IPV6;
14651 		toh->name = IPV6_TCLASS;
14652 		toh->len = sizeof (*toh) + sizeof (uint_t);
14653 		toh->status = 0;
14654 		optptr += sizeof (*toh);
14655 		*(uint_t *)optptr = ipp->ipp_tclass;
14656 		optptr += sizeof (uint_t);
14657 		ASSERT(OK_32PTR(optptr));
14658 		/* Save as "last" value */
14659 		tcp->tcp_recvtclass = ipp->ipp_tclass;
14660 	}
14661 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
14662 		toh = (struct T_opthdr *)optptr;
14663 		toh->level = IPPROTO_IPV6;
14664 		toh->name = IPV6_HOPOPTS;
14665 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
14666 		toh->status = 0;
14667 		optptr += sizeof (*toh);
14668 		bcopy(ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
14669 		optptr += ipp->ipp_hopoptslen;
14670 		ASSERT(OK_32PTR(optptr));
14671 		/* Save as last value */
14672 		tcp_savebuf((void **)&tcp->tcp_hopopts,
14673 		    &tcp->tcp_hopoptslen,
14674 		    (ipp->ipp_fields & IPPF_HOPOPTS),
14675 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14676 	}
14677 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
14678 		toh = (struct T_opthdr *)optptr;
14679 		toh->level = IPPROTO_IPV6;
14680 		toh->name = IPV6_RTHDRDSTOPTS;
14681 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
14682 		toh->status = 0;
14683 		optptr += sizeof (*toh);
14684 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
14685 		optptr += ipp->ipp_rtdstoptslen;
14686 		ASSERT(OK_32PTR(optptr));
14687 		/* Save as last value */
14688 		tcp_savebuf((void **)&tcp->tcp_rtdstopts,
14689 		    &tcp->tcp_rtdstoptslen,
14690 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
14691 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
14692 	}
14693 	if (addflag & TCP_IPV6_RECVRTHDR) {
14694 		toh = (struct T_opthdr *)optptr;
14695 		toh->level = IPPROTO_IPV6;
14696 		toh->name = IPV6_RTHDR;
14697 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
14698 		toh->status = 0;
14699 		optptr += sizeof (*toh);
14700 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
14701 		optptr += ipp->ipp_rthdrlen;
14702 		ASSERT(OK_32PTR(optptr));
14703 		/* Save as last value */
14704 		tcp_savebuf((void **)&tcp->tcp_rthdr,
14705 		    &tcp->tcp_rthdrlen,
14706 		    (ipp->ipp_fields & IPPF_RTHDR),
14707 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14708 	}
14709 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
14710 		toh = (struct T_opthdr *)optptr;
14711 		toh->level = IPPROTO_IPV6;
14712 		toh->name = IPV6_DSTOPTS;
14713 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
14714 		toh->status = 0;
14715 		optptr += sizeof (*toh);
14716 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
14717 		optptr += ipp->ipp_dstoptslen;
14718 		ASSERT(OK_32PTR(optptr));
14719 		/* Save as last value */
14720 		tcp_savebuf((void **)&tcp->tcp_dstopts,
14721 		    &tcp->tcp_dstoptslen,
14722 		    (ipp->ipp_fields & IPPF_DSTOPTS),
14723 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14724 	}
14725 	ASSERT(optptr == mp->b_wptr);
14726 	return (mp);
14727 }
14728 
14729 
14730 /*
14731  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
14732  * or a "bad" IRE detected by tcp_adapt_ire.
14733  * We can't tell if the failure was due to the laddr or the faddr
14734  * thus we clear out all addresses and ports.
14735  */
14736 static void
14737 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
14738 {
14739 	queue_t	*q = tcp->tcp_rq;
14740 	tcph_t	*tcph;
14741 	struct T_error_ack *tea;
14742 	conn_t	*connp = tcp->tcp_connp;
14743 
14744 
14745 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
14746 
14747 	if (mp->b_cont) {
14748 		freemsg(mp->b_cont);
14749 		mp->b_cont = NULL;
14750 	}
14751 	tea = (struct T_error_ack *)mp->b_rptr;
14752 	switch (tea->PRIM_type) {
14753 	case T_BIND_ACK:
14754 		/*
14755 		 * Need to unbind with classifier since we were just told that
14756 		 * our bind succeeded.
14757 		 */
14758 		tcp->tcp_hard_bound = B_FALSE;
14759 		tcp->tcp_hard_binding = B_FALSE;
14760 
14761 		ipcl_hash_remove(connp);
14762 		/* Reuse the mblk if possible */
14763 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
14764 			sizeof (*tea));
14765 		mp->b_rptr = mp->b_datap->db_base;
14766 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
14767 		tea = (struct T_error_ack *)mp->b_rptr;
14768 		tea->PRIM_type = T_ERROR_ACK;
14769 		tea->TLI_error = TSYSERR;
14770 		tea->UNIX_error = error;
14771 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
14772 			tea->ERROR_prim = T_CONN_REQ;
14773 		} else {
14774 			tea->ERROR_prim = O_T_BIND_REQ;
14775 		}
14776 		break;
14777 
14778 	case T_ERROR_ACK:
14779 		if (tcp->tcp_state >= TCPS_SYN_SENT)
14780 			tea->ERROR_prim = T_CONN_REQ;
14781 		break;
14782 	default:
14783 		panic("tcp_bind_failed: unexpected TPI type");
14784 		/*NOTREACHED*/
14785 	}
14786 
14787 	tcp->tcp_state = TCPS_IDLE;
14788 	if (tcp->tcp_ipversion == IPV4_VERSION)
14789 		tcp->tcp_ipha->ipha_src = 0;
14790 	else
14791 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
14792 	/*
14793 	 * Copy of the src addr. in tcp_t is needed since
14794 	 * the lookup funcs. can only look at tcp_t
14795 	 */
14796 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
14797 
14798 	tcph = tcp->tcp_tcph;
14799 	tcph->th_lport[0] = 0;
14800 	tcph->th_lport[1] = 0;
14801 	tcp_bind_hash_remove(tcp);
14802 	bzero(&connp->u_port, sizeof (connp->u_port));
14803 	/* blow away saved option results if any */
14804 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
14805 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
14806 
14807 	conn_delete_ire(tcp->tcp_connp, NULL);
14808 	putnext(q, mp);
14809 }
14810 
14811 /*
14812  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
14813  * messages.
14814  */
14815 void
14816 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
14817 {
14818 	mblk_t	*mp1;
14819 	uchar_t	*rptr = mp->b_rptr;
14820 	queue_t	*q = tcp->tcp_rq;
14821 	struct T_error_ack *tea;
14822 	uint32_t mss;
14823 	mblk_t *syn_mp;
14824 	mblk_t *mdti;
14825 	int	retval;
14826 	mblk_t *ire_mp;
14827 
14828 	switch (mp->b_datap->db_type) {
14829 	case M_PROTO:
14830 	case M_PCPROTO:
14831 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
14832 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
14833 			break;
14834 		tea = (struct T_error_ack *)rptr;
14835 		switch (tea->PRIM_type) {
14836 		case T_BIND_ACK:
14837 			/*
14838 			 * Adapt Multidata information, if any.  The
14839 			 * following tcp_mdt_update routine will free
14840 			 * the message.
14841 			 */
14842 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
14843 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
14844 				    b_rptr)->mdt_capab, B_TRUE);
14845 				freemsg(mdti);
14846 			}
14847 
14848 			/* Get the IRE, if we had requested for it */
14849 			ire_mp = tcp_ire_mp(mp);
14850 
14851 			if (tcp->tcp_hard_binding) {
14852 				tcp->tcp_hard_binding = B_FALSE;
14853 				tcp->tcp_hard_bound = B_TRUE;
14854 				CL_INET_CONNECT(tcp);
14855 			} else {
14856 				if (ire_mp != NULL)
14857 					freeb(ire_mp);
14858 				goto after_syn_sent;
14859 			}
14860 
14861 			retval = tcp_adapt_ire(tcp, ire_mp);
14862 			if (ire_mp != NULL)
14863 				freeb(ire_mp);
14864 			if (retval == 0) {
14865 				tcp_bind_failed(tcp, mp,
14866 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
14867 				    ENETUNREACH : EADDRNOTAVAIL));
14868 				return;
14869 			}
14870 			/*
14871 			 * Don't let an endpoint connect to itself.
14872 			 * Also checked in tcp_connect() but that
14873 			 * check can't handle the case when the
14874 			 * local IP address is INADDR_ANY.
14875 			 */
14876 			if (tcp->tcp_ipversion == IPV4_VERSION) {
14877 				if ((tcp->tcp_ipha->ipha_dst ==
14878 				    tcp->tcp_ipha->ipha_src) &&
14879 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
14880 				    tcp->tcp_tcph->th_fport))) {
14881 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
14882 					return;
14883 				}
14884 			} else {
14885 				if (IN6_ARE_ADDR_EQUAL(
14886 				    &tcp->tcp_ip6h->ip6_dst,
14887 				    &tcp->tcp_ip6h->ip6_src) &&
14888 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
14889 				    tcp->tcp_tcph->th_fport))) {
14890 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
14891 					return;
14892 				}
14893 			}
14894 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
14895 			/*
14896 			 * This should not be possible!  Just for
14897 			 * defensive coding...
14898 			 */
14899 			if (tcp->tcp_state != TCPS_SYN_SENT)
14900 				goto after_syn_sent;
14901 
14902 			ASSERT(q == tcp->tcp_rq);
14903 			/*
14904 			 * tcp_adapt_ire() does not adjust
14905 			 * for TCP/IP header length.
14906 			 */
14907 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
14908 
14909 			/*
14910 			 * Just make sure our rwnd is at
14911 			 * least tcp_recv_hiwat_mss * MSS
14912 			 * large, and round up to the nearest
14913 			 * MSS.
14914 			 *
14915 			 * We do the round up here because
14916 			 * we need to get the interface
14917 			 * MTU first before we can do the
14918 			 * round up.
14919 			 */
14920 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
14921 			    tcp_recv_hiwat_minmss * mss);
14922 			q->q_hiwat = tcp->tcp_rwnd;
14923 			tcp_set_ws_value(tcp);
14924 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
14925 			    tcp->tcp_tcph->th_win);
14926 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
14927 				tcp->tcp_snd_ws_ok = B_TRUE;
14928 
14929 			/*
14930 			 * Set tcp_snd_ts_ok to true
14931 			 * so that tcp_xmit_mp will
14932 			 * include the timestamp
14933 			 * option in the SYN segment.
14934 			 */
14935 			if (tcp_tstamp_always ||
14936 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
14937 				tcp->tcp_snd_ts_ok = B_TRUE;
14938 			}
14939 
14940 			/*
14941 			 * tcp_snd_sack_ok can be set in
14942 			 * tcp_adapt_ire() if the sack metric
14943 			 * is set.  So check it here also.
14944 			 */
14945 			if (tcp_sack_permitted == 2 ||
14946 			    tcp->tcp_snd_sack_ok) {
14947 				if (tcp->tcp_sack_info == NULL) {
14948 					tcp->tcp_sack_info =
14949 					kmem_cache_alloc(tcp_sack_info_cache,
14950 					    KM_SLEEP);
14951 				}
14952 				tcp->tcp_snd_sack_ok = B_TRUE;
14953 			}
14954 
14955 			/*
14956 			 * Should we use ECN?  Note that the current
14957 			 * default value (SunOS 5.9) of tcp_ecn_permitted
14958 			 * is 1.  The reason for doing this is that there
14959 			 * are equipments out there that will drop ECN
14960 			 * enabled IP packets.  Setting it to 1 avoids
14961 			 * compatibility problems.
14962 			 */
14963 			if (tcp_ecn_permitted == 2)
14964 				tcp->tcp_ecn_ok = B_TRUE;
14965 
14966 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14967 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
14968 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
14969 			if (syn_mp) {
14970 				cred_t *cr;
14971 				pid_t pid;
14972 
14973 				/*
14974 				 * Obtain the credential from the
14975 				 * thread calling connect(); the credential
14976 				 * lives on in the second mblk which
14977 				 * originated from T_CONN_REQ and is echoed
14978 				 * with the T_BIND_ACK from ip.  If none
14979 				 * can be found, default to the creator
14980 				 * of the socket.
14981 				 */
14982 				if (mp->b_cont == NULL ||
14983 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
14984 					cr = tcp->tcp_cred;
14985 					pid = tcp->tcp_cpid;
14986 				} else {
14987 					pid = DB_CPID(mp->b_cont);
14988 				}
14989 
14990 				TCP_RECORD_TRACE(tcp, syn_mp,
14991 				    TCP_TRACE_SEND_PKT);
14992 				mblk_setcred(syn_mp, cr);
14993 				DB_CPID(syn_mp) = pid;
14994 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
14995 			}
14996 		after_syn_sent:
14997 			/*
14998 			 * A trailer mblk indicates a waiting client upstream.
14999 			 * We complete here the processing begun in
15000 			 * either tcp_bind() or tcp_connect() by passing
15001 			 * upstream the reply message they supplied.
15002 			 */
15003 			mp1 = mp;
15004 			mp = mp->b_cont;
15005 			freeb(mp1);
15006 			if (mp)
15007 				break;
15008 			return;
15009 		case T_ERROR_ACK:
15010 			if (tcp->tcp_debug) {
15011 				(void) strlog(TCP_MOD_ID, 0, 1,
15012 				    SL_TRACE|SL_ERROR,
15013 				    "tcp_rput_other: case T_ERROR_ACK, "
15014 				    "ERROR_prim == %d",
15015 				    tea->ERROR_prim);
15016 			}
15017 			switch (tea->ERROR_prim) {
15018 			case O_T_BIND_REQ:
15019 			case T_BIND_REQ:
15020 				tcp_bind_failed(tcp, mp,
15021 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15022 				    ENETUNREACH : EADDRNOTAVAIL));
15023 				return;
15024 			case T_UNBIND_REQ:
15025 				tcp->tcp_hard_binding = B_FALSE;
15026 				tcp->tcp_hard_bound = B_FALSE;
15027 				if (mp->b_cont) {
15028 					freemsg(mp->b_cont);
15029 					mp->b_cont = NULL;
15030 				}
15031 				if (tcp->tcp_unbind_pending)
15032 					tcp->tcp_unbind_pending = 0;
15033 				else {
15034 					/* From tcp_ip_unbind() - free */
15035 					freemsg(mp);
15036 					return;
15037 				}
15038 				break;
15039 			case T_SVR4_OPTMGMT_REQ:
15040 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15041 					/* T_OPTMGMT_REQ generated by TCP */
15042 					printf("T_SVR4_OPTMGMT_REQ failed "
15043 					    "%d/%d - dropped (cnt %d)\n",
15044 					    tea->TLI_error, tea->UNIX_error,
15045 					    tcp->tcp_drop_opt_ack_cnt);
15046 					freemsg(mp);
15047 					tcp->tcp_drop_opt_ack_cnt--;
15048 					return;
15049 				}
15050 				break;
15051 			}
15052 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15053 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15054 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15055 				    "- dropped (cnt %d)\n",
15056 				    tea->TLI_error, tea->UNIX_error,
15057 				    tcp->tcp_drop_opt_ack_cnt);
15058 				freemsg(mp);
15059 				tcp->tcp_drop_opt_ack_cnt--;
15060 				return;
15061 			}
15062 			break;
15063 		case T_OPTMGMT_ACK:
15064 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15065 				/* T_OPTMGMT_REQ generated by TCP */
15066 				freemsg(mp);
15067 				tcp->tcp_drop_opt_ack_cnt--;
15068 				return;
15069 			}
15070 			break;
15071 		default:
15072 			break;
15073 		}
15074 		break;
15075 	case M_CTL:
15076 		/*
15077 		 * ICMP messages.
15078 		 */
15079 		tcp_icmp_error(tcp, mp);
15080 		return;
15081 	case M_FLUSH:
15082 		if (*rptr & FLUSHR)
15083 			flushq(q, FLUSHDATA);
15084 		break;
15085 	default:
15086 		break;
15087 	}
15088 	/*
15089 	 * Make sure we set this bit before sending the ACK for
15090 	 * bind. Otherwise accept could possibly run and free
15091 	 * this tcp struct.
15092 	 */
15093 	putnext(q, mp);
15094 }
15095 
15096 /*
15097  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15098  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15099  * tcp_rsrv() try again.
15100  */
15101 static void
15102 tcp_ordrel_kick(void *arg)
15103 {
15104 	conn_t 	*connp = (conn_t *)arg;
15105 	tcp_t	*tcp = connp->conn_tcp;
15106 
15107 	tcp->tcp_ordrelid = 0;
15108 	tcp->tcp_timeout = B_FALSE;
15109 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15110 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15111 		qenable(tcp->tcp_rq);
15112 	}
15113 }
15114 
15115 /* ARGSUSED */
15116 static void
15117 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15118 {
15119 	conn_t	*connp = (conn_t *)arg;
15120 	tcp_t	*tcp = connp->conn_tcp;
15121 	queue_t	*q = tcp->tcp_rq;
15122 	uint_t	thwin;
15123 
15124 	freeb(mp);
15125 
15126 	TCP_STAT(tcp_rsrv_calls);
15127 
15128 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15129 		return;
15130 	}
15131 
15132 	if (tcp->tcp_fused) {
15133 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15134 
15135 		ASSERT(tcp->tcp_fused);
15136 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15137 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15138 		ASSERT(!TCP_IS_DETACHED(tcp));
15139 		ASSERT(tcp->tcp_connp->conn_sqp ==
15140 		    peer_tcp->tcp_connp->conn_sqp);
15141 
15142 		/*
15143 		 * Normally we would not get backenabled in synchronous
15144 		 * streams mode, but in case this happens, we need to stop
15145 		 * synchronous streams temporarily to prevent a race with
15146 		 * tcp_fuse_rrw() or tcp_fuse_rinfop().  It is safe to access
15147 		 * tcp_rcv_list here because those entry points will return
15148 		 * right away when synchronous streams is stopped.
15149 		 */
15150 		TCP_FUSE_SYNCSTR_STOP(tcp);
15151 		if (tcp->tcp_rcv_list != NULL)
15152 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15153 
15154 		tcp_clrqfull(peer_tcp);
15155 		TCP_FUSE_SYNCSTR_RESUME(tcp);
15156 		TCP_STAT(tcp_fusion_backenabled);
15157 		return;
15158 	}
15159 
15160 	if (canputnext(q)) {
15161 		tcp->tcp_rwnd = q->q_hiwat;
15162 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15163 		    << tcp->tcp_rcv_ws;
15164 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15165 		/*
15166 		 * Send back a window update immediately if TCP is above
15167 		 * ESTABLISHED state and the increase of the rcv window
15168 		 * that the other side knows is at least 1 MSS after flow
15169 		 * control is lifted.
15170 		 */
15171 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15172 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15173 			tcp_xmit_ctl(NULL, tcp,
15174 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15175 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15176 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
15177 		}
15178 	}
15179 	/* Handle a failure to allocate a T_ORDREL_IND here */
15180 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15181 		ASSERT(tcp->tcp_listener == NULL);
15182 		if (tcp->tcp_rcv_list != NULL) {
15183 			(void) tcp_rcv_drain(q, tcp);
15184 		}
15185 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15186 		mp = mi_tpi_ordrel_ind();
15187 		if (mp) {
15188 			tcp->tcp_ordrel_done = B_TRUE;
15189 			putnext(q, mp);
15190 			if (tcp->tcp_deferred_clean_death) {
15191 				/*
15192 				 * tcp_clean_death was deferred for
15193 				 * T_ORDREL_IND - do it now
15194 				 */
15195 				tcp->tcp_deferred_clean_death = B_FALSE;
15196 				(void) tcp_clean_death(tcp,
15197 				    tcp->tcp_client_errno, 22);
15198 			}
15199 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15200 			/*
15201 			 * If there isn't already a timer running
15202 			 * start one.  Use a 4 second
15203 			 * timer as a fallback since it can't fail.
15204 			 */
15205 			tcp->tcp_timeout = B_TRUE;
15206 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15207 			    MSEC_TO_TICK(4000));
15208 		}
15209 	}
15210 }
15211 
15212 /*
15213  * The read side service routine is called mostly when we get back-enabled as a
15214  * result of flow control relief.  Since we don't actually queue anything in
15215  * TCP, we have no data to send out of here.  What we do is clear the receive
15216  * window, and send out a window update.
15217  * This routine is also called to drive an orderly release message upstream
15218  * if the attempt in tcp_rput failed.
15219  */
15220 static void
15221 tcp_rsrv(queue_t *q)
15222 {
15223 	conn_t *connp = Q_TO_CONN(q);
15224 	tcp_t	*tcp = connp->conn_tcp;
15225 	mblk_t	*mp;
15226 
15227 	/* No code does a putq on the read side */
15228 	ASSERT(q->q_first == NULL);
15229 
15230 	/* Nothing to do for the default queue */
15231 	if (q == tcp_g_q) {
15232 		return;
15233 	}
15234 
15235 	mp = allocb(0, BPRI_HI);
15236 	if (mp == NULL) {
15237 		/*
15238 		 * We are under memory pressure. Return for now and we
15239 		 * we will be called again later.
15240 		 */
15241 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15242 			/*
15243 			 * If there isn't already a timer running
15244 			 * start one.  Use a 4 second
15245 			 * timer as a fallback since it can't fail.
15246 			 */
15247 			tcp->tcp_timeout = B_TRUE;
15248 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15249 			    MSEC_TO_TICK(4000));
15250 		}
15251 		return;
15252 	}
15253 	CONN_INC_REF(connp);
15254 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15255 	    SQTAG_TCP_RSRV);
15256 }
15257 
15258 /*
15259  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15260  * We do not allow the receive window to shrink.  After setting rwnd,
15261  * set the flow control hiwat of the stream.
15262  *
15263  * This function is called in 2 cases:
15264  *
15265  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15266  *    connection (passive open) and in tcp_rput_data() for active connect.
15267  *    This is called after tcp_mss_set() when the desired MSS value is known.
15268  *    This makes sure that our window size is a mutiple of the other side's
15269  *    MSS.
15270  * 2) Handling SO_RCVBUF option.
15271  *
15272  * It is ASSUMED that the requested size is a multiple of the current MSS.
15273  *
15274  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15275  * user requests so.
15276  */
15277 static int
15278 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15279 {
15280 	uint32_t	mss = tcp->tcp_mss;
15281 	uint32_t	old_max_rwnd;
15282 	uint32_t	max_transmittable_rwnd;
15283 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15284 
15285 	if (tcp->tcp_fused) {
15286 		size_t sth_hiwat;
15287 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15288 
15289 		ASSERT(peer_tcp != NULL);
15290 		/*
15291 		 * Record the stream head's high water mark for
15292 		 * this endpoint; this is used for flow-control
15293 		 * purposes in tcp_fuse_output().
15294 		 */
15295 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15296 		if (!tcp_detached)
15297 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
15298 
15299 		/*
15300 		 * In the fusion case, the maxpsz stream head value of
15301 		 * our peer is set according to its send buffer size
15302 		 * and our receive buffer size; since the latter may
15303 		 * have changed we need to update the peer's maxpsz.
15304 		 */
15305 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15306 		return (rwnd);
15307 	}
15308 
15309 	if (tcp_detached)
15310 		old_max_rwnd = tcp->tcp_rwnd;
15311 	else
15312 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
15313 
15314 	/*
15315 	 * Insist on a receive window that is at least
15316 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15317 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15318 	 * and delayed acknowledgement.
15319 	 */
15320 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
15321 
15322 	/*
15323 	 * If window size info has already been exchanged, TCP should not
15324 	 * shrink the window.  Shrinking window is doable if done carefully.
15325 	 * We may add that support later.  But so far there is not a real
15326 	 * need to do that.
15327 	 */
15328 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15329 		/* MSS may have changed, do a round up again. */
15330 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15331 	}
15332 
15333 	/*
15334 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15335 	 * can be applied even before the window scale option is decided.
15336 	 */
15337 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15338 	if (rwnd > max_transmittable_rwnd) {
15339 		rwnd = max_transmittable_rwnd -
15340 		    (max_transmittable_rwnd % mss);
15341 		if (rwnd < mss)
15342 			rwnd = max_transmittable_rwnd;
15343 		/*
15344 		 * If we're over the limit we may have to back down tcp_rwnd.
15345 		 * The increment below won't work for us. So we set all three
15346 		 * here and the increment below will have no effect.
15347 		 */
15348 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15349 	}
15350 	if (tcp->tcp_localnet) {
15351 		tcp->tcp_rack_abs_max =
15352 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
15353 	} else {
15354 		/*
15355 		 * For a remote host on a different subnet (through a router),
15356 		 * we ack every other packet to be conforming to RFC1122.
15357 		 * tcp_deferred_acks_max is default to 2.
15358 		 */
15359 		tcp->tcp_rack_abs_max =
15360 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
15361 	}
15362 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15363 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15364 	else
15365 		tcp->tcp_rack_cur_max = 0;
15366 	/*
15367 	 * Increment the current rwnd by the amount the maximum grew (we
15368 	 * can not overwrite it since we might be in the middle of a
15369 	 * connection.)
15370 	 */
15371 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15372 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15373 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15374 		tcp->tcp_cwnd_max = rwnd;
15375 
15376 	if (tcp_detached)
15377 		return (rwnd);
15378 	/*
15379 	 * We set the maximum receive window into rq->q_hiwat.
15380 	 * This is not actually used for flow control.
15381 	 */
15382 	tcp->tcp_rq->q_hiwat = rwnd;
15383 	/*
15384 	 * Set the Stream head high water mark. This doesn't have to be
15385 	 * here, since we are simply using default values, but we would
15386 	 * prefer to choose these values algorithmically, with a likely
15387 	 * relationship to rwnd.
15388 	 */
15389 	(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd, tcp_sth_rcv_hiwat));
15390 	return (rwnd);
15391 }
15392 
15393 /*
15394  * Return SNMP stuff in buffer in mpdata.
15395  */
15396 int
15397 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15398 {
15399 	mblk_t			*mpdata;
15400 	mblk_t			*mp_conn_ctl = NULL;
15401 	mblk_t			*mp_conn_data;
15402 	mblk_t			*mp6_conn_ctl = NULL;
15403 	mblk_t			*mp6_conn_data;
15404 	mblk_t			*mp_conn_tail = NULL;
15405 	mblk_t			*mp6_conn_tail = NULL;
15406 	struct opthdr		*optp;
15407 	mib2_tcpConnEntry_t	tce;
15408 	mib2_tcp6ConnEntry_t	tce6;
15409 	connf_t			*connfp;
15410 	conn_t			*connp;
15411 	int			i;
15412 	boolean_t 		ispriv;
15413 	zoneid_t 		zoneid;
15414 
15415 	if (mpctl == NULL ||
15416 	    (mpdata = mpctl->b_cont) == NULL ||
15417 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15418 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL) {
15419 		if (mp_conn_ctl != NULL)
15420 			freemsg(mp_conn_ctl);
15421 		if (mp6_conn_ctl != NULL)
15422 			freemsg(mp6_conn_ctl);
15423 		return (0);
15424 	}
15425 
15426 	/* build table of connections -- need count in fixed part */
15427 	mp_conn_data = mp_conn_ctl->b_cont;
15428 	mp6_conn_data = mp6_conn_ctl->b_cont;
15429 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
15430 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
15431 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
15432 	SET_MIB(tcp_mib.tcpMaxConn, -1);
15433 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
15434 
15435 	ispriv =
15436 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15437 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15438 
15439 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15440 
15441 		connfp = &ipcl_globalhash_fanout[i];
15442 
15443 		connp = NULL;
15444 
15445 		while ((connp =
15446 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15447 			tcp_t *tcp;
15448 
15449 			if (connp->conn_zoneid != zoneid)
15450 				continue;	/* not in this zone */
15451 
15452 			tcp = connp->conn_tcp;
15453 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
15454 			tcp->tcp_ibsegs = 0;
15455 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
15456 			tcp->tcp_obsegs = 0;
15457 
15458 			tce6.tcp6ConnState = tce.tcpConnState =
15459 			    tcp_snmp_state(tcp);
15460 			if (tce.tcpConnState == MIB2_TCP_established ||
15461 			    tce.tcpConnState == MIB2_TCP_closeWait)
15462 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
15463 
15464 			/* Create a message to report on IPv6 entries */
15465 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15466 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15467 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15468 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15469 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15470 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15471 			/* Don't want just anybody seeing these... */
15472 			if (ispriv) {
15473 				tce6.tcp6ConnEntryInfo.ce_snxt =
15474 				    tcp->tcp_snxt;
15475 				tce6.tcp6ConnEntryInfo.ce_suna =
15476 				    tcp->tcp_suna;
15477 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15478 				    tcp->tcp_rnxt;
15479 				tce6.tcp6ConnEntryInfo.ce_rack =
15480 				    tcp->tcp_rack;
15481 			} else {
15482 				/*
15483 				 * Netstat, unfortunately, uses this to
15484 				 * get send/receive queue sizes.  How to fix?
15485 				 * Why not compute the difference only?
15486 				 */
15487 				tce6.tcp6ConnEntryInfo.ce_snxt =
15488 				    tcp->tcp_snxt - tcp->tcp_suna;
15489 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
15490 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15491 				    tcp->tcp_rnxt - tcp->tcp_rack;
15492 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
15493 			}
15494 
15495 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15496 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15497 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
15498 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
15499 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
15500 			(void) snmp_append_data2(mp6_conn_data, &mp6_conn_tail,
15501 			    (char *)&tce6, sizeof (tce6));
15502 			}
15503 			/*
15504 			 * Create an IPv4 table entry for IPv4 entries and also
15505 			 * for IPv6 entries which are bound to in6addr_any
15506 			 * but don't have IPV6_V6ONLY set.
15507 			 * (i.e. anything an IPv4 peer could connect to)
15508 			 */
15509 			if (tcp->tcp_ipversion == IPV4_VERSION ||
15510 			    (tcp->tcp_state <= TCPS_LISTEN &&
15511 			    !tcp->tcp_connp->conn_ipv6_v6only &&
15512 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
15513 				if (tcp->tcp_ipversion == IPV6_VERSION) {
15514 					tce.tcpConnRemAddress = INADDR_ANY;
15515 					tce.tcpConnLocalAddress = INADDR_ANY;
15516 				} else {
15517 					tce.tcpConnRemAddress =
15518 					    tcp->tcp_remote;
15519 					tce.tcpConnLocalAddress =
15520 					    tcp->tcp_ip_src;
15521 				}
15522 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
15523 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
15524 				/* Don't want just anybody seeing these... */
15525 				if (ispriv) {
15526 					tce.tcpConnEntryInfo.ce_snxt =
15527 					    tcp->tcp_snxt;
15528 					tce.tcpConnEntryInfo.ce_suna =
15529 					    tcp->tcp_suna;
15530 					tce.tcpConnEntryInfo.ce_rnxt =
15531 					    tcp->tcp_rnxt;
15532 					tce.tcpConnEntryInfo.ce_rack =
15533 					    tcp->tcp_rack;
15534 				} else {
15535 					/*
15536 					 * Netstat, unfortunately, uses this to
15537 					 * get send/receive queue sizes.  How
15538 					 * to fix?
15539 					 * Why not compute the difference only?
15540 					 */
15541 					tce.tcpConnEntryInfo.ce_snxt =
15542 					    tcp->tcp_snxt - tcp->tcp_suna;
15543 					tce.tcpConnEntryInfo.ce_suna = 0;
15544 					tce.tcpConnEntryInfo.ce_rnxt =
15545 					    tcp->tcp_rnxt - tcp->tcp_rack;
15546 					tce.tcpConnEntryInfo.ce_rack = 0;
15547 				}
15548 
15549 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15550 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15551 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
15552 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
15553 				tce.tcpConnEntryInfo.ce_state =
15554 				    tcp->tcp_state;
15555 				(void) snmp_append_data2(mp_conn_data,
15556 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
15557 			}
15558 		}
15559 	}
15560 
15561 	/* fixed length structure for IPv4 and IPv6 counters */
15562 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
15563 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
15564 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
15565 	optp->level = MIB2_TCP;
15566 	optp->name = 0;
15567 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
15568 	optp->len = msgdsize(mpdata);
15569 	qreply(q, mpctl);
15570 
15571 	/* table of connections... */
15572 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
15573 	    sizeof (struct T_optmgmt_ack)];
15574 	optp->level = MIB2_TCP;
15575 	optp->name = MIB2_TCP_CONN;
15576 	optp->len = msgdsize(mp_conn_data);
15577 	qreply(q, mp_conn_ctl);
15578 
15579 	/* table of IPv6 connections... */
15580 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
15581 	    sizeof (struct T_optmgmt_ack)];
15582 	optp->level = MIB2_TCP6;
15583 	optp->name = MIB2_TCP6_CONN;
15584 	optp->len = msgdsize(mp6_conn_data);
15585 	qreply(q, mp6_conn_ctl);
15586 	return (1);
15587 }
15588 
15589 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
15590 /* ARGSUSED */
15591 int
15592 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
15593 {
15594 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
15595 
15596 	switch (level) {
15597 	case MIB2_TCP:
15598 		switch (name) {
15599 		case 13:
15600 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
15601 				return (0);
15602 			/* TODO: delete entry defined by tce */
15603 			return (1);
15604 		default:
15605 			return (0);
15606 		}
15607 	default:
15608 		return (1);
15609 	}
15610 }
15611 
15612 /* Translate TCP state to MIB2 TCP state. */
15613 static int
15614 tcp_snmp_state(tcp_t *tcp)
15615 {
15616 	if (tcp == NULL)
15617 		return (0);
15618 
15619 	switch (tcp->tcp_state) {
15620 	case TCPS_CLOSED:
15621 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
15622 	case TCPS_BOUND:
15623 		return (MIB2_TCP_closed);
15624 	case TCPS_LISTEN:
15625 		return (MIB2_TCP_listen);
15626 	case TCPS_SYN_SENT:
15627 		return (MIB2_TCP_synSent);
15628 	case TCPS_SYN_RCVD:
15629 		return (MIB2_TCP_synReceived);
15630 	case TCPS_ESTABLISHED:
15631 		return (MIB2_TCP_established);
15632 	case TCPS_CLOSE_WAIT:
15633 		return (MIB2_TCP_closeWait);
15634 	case TCPS_FIN_WAIT_1:
15635 		return (MIB2_TCP_finWait1);
15636 	case TCPS_CLOSING:
15637 		return (MIB2_TCP_closing);
15638 	case TCPS_LAST_ACK:
15639 		return (MIB2_TCP_lastAck);
15640 	case TCPS_FIN_WAIT_2:
15641 		return (MIB2_TCP_finWait2);
15642 	case TCPS_TIME_WAIT:
15643 		return (MIB2_TCP_timeWait);
15644 	default:
15645 		return (0);
15646 	}
15647 }
15648 
15649 static char tcp_report_header[] =
15650 	"TCP     " MI_COL_HDRPAD_STR
15651 	"zone dest            snxt     suna     "
15652 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
15653 	"recent   [lport,fport] state";
15654 
15655 /*
15656  * TCP status report triggered via the Named Dispatch mechanism.
15657  */
15658 /* ARGSUSED */
15659 static void
15660 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
15661     cred_t *cr)
15662 {
15663 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
15664 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
15665 	char cflag;
15666 	in6_addr_t	v6dst;
15667 	char buf[80];
15668 	uint_t print_len, buf_len;
15669 
15670 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
15671 	if (buf_len <= 0)
15672 		return;
15673 
15674 	if (hashval >= 0)
15675 		(void) sprintf(hash, "%03d ", hashval);
15676 	else
15677 		hash[0] = '\0';
15678 
15679 	/*
15680 	 * Note that we use the remote address in the tcp_b  structure.
15681 	 * This means that it will print out the real destination address,
15682 	 * not the next hop's address if source routing is used.  This
15683 	 * avoid the confusion on the output because user may not
15684 	 * know that source routing is used for a connection.
15685 	 */
15686 	if (tcp->tcp_ipversion == IPV4_VERSION) {
15687 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
15688 	} else {
15689 		v6dst = tcp->tcp_remote_v6;
15690 	}
15691 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
15692 	/*
15693 	 * the ispriv checks are so that normal users cannot determine
15694 	 * sequence number information using NDD.
15695 	 */
15696 
15697 	if (TCP_IS_DETACHED(tcp))
15698 		cflag = '*';
15699 	else
15700 		cflag = ' ';
15701 	print_len = snprintf((char *)mp->b_wptr, buf_len,
15702 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
15703 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
15704 	    hash,
15705 	    (void *)tcp,
15706 	    tcp->tcp_connp->conn_zoneid,
15707 	    addrbuf,
15708 	    (ispriv) ? tcp->tcp_snxt : 0,
15709 	    (ispriv) ? tcp->tcp_suna : 0,
15710 	    tcp->tcp_swnd,
15711 	    (ispriv) ? tcp->tcp_rnxt : 0,
15712 	    (ispriv) ? tcp->tcp_rack : 0,
15713 	    tcp->tcp_rwnd,
15714 	    tcp->tcp_rto,
15715 	    tcp->tcp_mss,
15716 	    tcp->tcp_snd_ws_ok,
15717 	    tcp->tcp_snd_ws,
15718 	    tcp->tcp_rcv_ws,
15719 	    tcp->tcp_snd_ts_ok,
15720 	    tcp->tcp_ts_recent,
15721 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
15722 	if (print_len < buf_len) {
15723 		((mblk_t *)mp)->b_wptr += print_len;
15724 	} else {
15725 		((mblk_t *)mp)->b_wptr += buf_len;
15726 	}
15727 }
15728 
15729 /*
15730  * TCP status report (for listeners only) triggered via the Named Dispatch
15731  * mechanism.
15732  */
15733 /* ARGSUSED */
15734 static void
15735 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
15736 {
15737 	char addrbuf[INET6_ADDRSTRLEN];
15738 	in6_addr_t	v6dst;
15739 	uint_t print_len, buf_len;
15740 
15741 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
15742 	if (buf_len <= 0)
15743 		return;
15744 
15745 	if (tcp->tcp_ipversion == IPV4_VERSION) {
15746 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
15747 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
15748 	} else {
15749 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
15750 		    addrbuf, sizeof (addrbuf));
15751 	}
15752 	print_len = snprintf((char *)mp->b_wptr, buf_len,
15753 	    "%03d "
15754 	    MI_COL_PTRFMT_STR
15755 	    "%d %s %05u %08u %d/%d/%d%c\n",
15756 	    hashval, (void *)tcp,
15757 	    tcp->tcp_connp->conn_zoneid,
15758 	    addrbuf,
15759 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
15760 	    tcp->tcp_conn_req_seqnum,
15761 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
15762 	    tcp->tcp_conn_req_max,
15763 	    tcp->tcp_syn_defense ? '*' : ' ');
15764 	if (print_len < buf_len) {
15765 		((mblk_t *)mp)->b_wptr += print_len;
15766 	} else {
15767 		((mblk_t *)mp)->b_wptr += buf_len;
15768 	}
15769 }
15770 
15771 /* TCP status report triggered via the Named Dispatch mechanism. */
15772 /* ARGSUSED */
15773 static int
15774 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15775 {
15776 	tcp_t	*tcp;
15777 	int	i;
15778 	conn_t	*connp;
15779 	connf_t	*connfp;
15780 	zoneid_t zoneid;
15781 
15782 	/*
15783 	 * Because of the ndd constraint, at most we can have 64K buffer
15784 	 * to put in all TCP info.  So to be more efficient, just
15785 	 * allocate a 64K buffer here, assuming we need that large buffer.
15786 	 * This may be a problem as any user can read tcp_status.  Therefore
15787 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
15788 	 * This should be OK as normal users should not do this too often.
15789 	 */
15790 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15791 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15792 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15793 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15794 			return (0);
15795 		}
15796 	}
15797 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15798 		/* The following may work even if we cannot get a large buf. */
15799 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15800 		return (0);
15801 	}
15802 
15803 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
15804 
15805 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15806 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15807 
15808 		connfp = &ipcl_globalhash_fanout[i];
15809 
15810 		connp = NULL;
15811 
15812 		while ((connp =
15813 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15814 			tcp = connp->conn_tcp;
15815 			if (zoneid != GLOBAL_ZONEID &&
15816 			    zoneid != connp->conn_zoneid)
15817 				continue;
15818 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
15819 			    cr);
15820 		}
15821 
15822 	}
15823 
15824 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15825 	return (0);
15826 }
15827 
15828 /* TCP status report triggered via the Named Dispatch mechanism. */
15829 /* ARGSUSED */
15830 static int
15831 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15832 {
15833 	tf_t	*tbf;
15834 	tcp_t	*tcp;
15835 	int	i;
15836 	zoneid_t zoneid;
15837 
15838 	/* Refer to comments in tcp_status_report(). */
15839 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15840 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15841 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15842 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15843 			return (0);
15844 		}
15845 	}
15846 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15847 		/* The following may work even if we cannot get a large buf. */
15848 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15849 		return (0);
15850 	}
15851 
15852 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
15853 
15854 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15855 
15856 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
15857 		tbf = &tcp_bind_fanout[i];
15858 		mutex_enter(&tbf->tf_lock);
15859 		for (tcp = tbf->tf_tcp; tcp != NULL;
15860 		    tcp = tcp->tcp_bind_hash) {
15861 			if (zoneid != GLOBAL_ZONEID &&
15862 			    zoneid != tcp->tcp_connp->conn_zoneid)
15863 				continue;
15864 			CONN_INC_REF(tcp->tcp_connp);
15865 			tcp_report_item(mp->b_cont, tcp, i,
15866 			    Q_TO_TCP(q), cr);
15867 			CONN_DEC_REF(tcp->tcp_connp);
15868 		}
15869 		mutex_exit(&tbf->tf_lock);
15870 	}
15871 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15872 	return (0);
15873 }
15874 
15875 /* TCP status report triggered via the Named Dispatch mechanism. */
15876 /* ARGSUSED */
15877 static int
15878 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15879 {
15880 	connf_t	*connfp;
15881 	conn_t	*connp;
15882 	tcp_t	*tcp;
15883 	int	i;
15884 	zoneid_t zoneid;
15885 
15886 	/* Refer to comments in tcp_status_report(). */
15887 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15888 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15889 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15890 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15891 			return (0);
15892 		}
15893 	}
15894 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15895 		/* The following may work even if we cannot get a large buf. */
15896 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15897 		return (0);
15898 	}
15899 
15900 	(void) mi_mpprintf(mp,
15901 	    "    TCP    " MI_COL_HDRPAD_STR
15902 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
15903 
15904 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15905 
15906 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
15907 		connfp =  &ipcl_bind_fanout[i];
15908 		connp = NULL;
15909 		while ((connp =
15910 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15911 			tcp = connp->conn_tcp;
15912 			if (zoneid != GLOBAL_ZONEID &&
15913 			    zoneid != connp->conn_zoneid)
15914 				continue;
15915 			tcp_report_listener(mp->b_cont, tcp, i);
15916 		}
15917 	}
15918 
15919 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15920 	return (0);
15921 }
15922 
15923 /* TCP status report triggered via the Named Dispatch mechanism. */
15924 /* ARGSUSED */
15925 static int
15926 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15927 {
15928 	connf_t	*connfp;
15929 	conn_t	*connp;
15930 	tcp_t	*tcp;
15931 	int	i;
15932 	zoneid_t zoneid;
15933 
15934 	/* Refer to comments in tcp_status_report(). */
15935 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15936 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15937 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15938 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15939 			return (0);
15940 		}
15941 	}
15942 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15943 		/* The following may work even if we cannot get a large buf. */
15944 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15945 		return (0);
15946 	}
15947 
15948 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
15949 	    ipcl_conn_fanout_size);
15950 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
15951 
15952 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15953 
15954 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
15955 		connfp =  &ipcl_conn_fanout[i];
15956 		connp = NULL;
15957 		while ((connp =
15958 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15959 			tcp = connp->conn_tcp;
15960 			if (zoneid != GLOBAL_ZONEID &&
15961 			    zoneid != connp->conn_zoneid)
15962 				continue;
15963 			tcp_report_item(mp->b_cont, tcp, i,
15964 			    Q_TO_TCP(q), cr);
15965 		}
15966 	}
15967 
15968 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15969 	return (0);
15970 }
15971 
15972 /* TCP status report triggered via the Named Dispatch mechanism. */
15973 /* ARGSUSED */
15974 static int
15975 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15976 {
15977 	tf_t	*tf;
15978 	tcp_t	*tcp;
15979 	int	i;
15980 	zoneid_t zoneid;
15981 
15982 	/* Refer to comments in tcp_status_report(). */
15983 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15984 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15985 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15986 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15987 			return (0);
15988 		}
15989 	}
15990 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15991 		/* The following may work even if we cannot get a large buf. */
15992 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15993 		return (0);
15994 	}
15995 
15996 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
15997 
15998 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15999 
16000 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16001 		tf = &tcp_acceptor_fanout[i];
16002 		mutex_enter(&tf->tf_lock);
16003 		for (tcp = tf->tf_tcp; tcp != NULL;
16004 		    tcp = tcp->tcp_acceptor_hash) {
16005 			if (zoneid != GLOBAL_ZONEID &&
16006 			    zoneid != tcp->tcp_connp->conn_zoneid)
16007 				continue;
16008 			tcp_report_item(mp->b_cont, tcp, i,
16009 			    Q_TO_TCP(q), cr);
16010 		}
16011 		mutex_exit(&tf->tf_lock);
16012 	}
16013 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16014 	return (0);
16015 }
16016 
16017 /*
16018  * tcp_timer is the timer service routine.  It handles the retransmission,
16019  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16020  * from the state of the tcp instance what kind of action needs to be done
16021  * at the time it is called.
16022  */
16023 static void
16024 tcp_timer(void *arg)
16025 {
16026 	mblk_t		*mp;
16027 	clock_t		first_threshold;
16028 	clock_t		second_threshold;
16029 	clock_t		ms;
16030 	uint32_t	mss;
16031 	conn_t		*connp = (conn_t *)arg;
16032 	tcp_t		*tcp = connp->conn_tcp;
16033 
16034 	tcp->tcp_timer_tid = 0;
16035 
16036 	if (tcp->tcp_fused)
16037 		return;
16038 
16039 	first_threshold =  tcp->tcp_first_timer_threshold;
16040 	second_threshold = tcp->tcp_second_timer_threshold;
16041 	switch (tcp->tcp_state) {
16042 	case TCPS_IDLE:
16043 	case TCPS_BOUND:
16044 	case TCPS_LISTEN:
16045 		return;
16046 	case TCPS_SYN_RCVD: {
16047 		tcp_t	*listener = tcp->tcp_listener;
16048 
16049 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16050 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16051 			/* it's our first timeout */
16052 			tcp->tcp_syn_rcvd_timeout = 1;
16053 			mutex_enter(&listener->tcp_eager_lock);
16054 			listener->tcp_syn_rcvd_timeout++;
16055 			if (!listener->tcp_syn_defense &&
16056 			    (listener->tcp_syn_rcvd_timeout >
16057 			    (tcp_conn_req_max_q0 >> 2)) &&
16058 			    (tcp_conn_req_max_q0 > 200)) {
16059 				/* We may be under attack. Put on a defense. */
16060 				listener->tcp_syn_defense = B_TRUE;
16061 				cmn_err(CE_WARN, "High TCP connect timeout "
16062 				    "rate! System (port %d) may be under a "
16063 				    "SYN flood attack!",
16064 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16065 
16066 				listener->tcp_ip_addr_cache = kmem_zalloc(
16067 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16068 				    KM_NOSLEEP);
16069 			}
16070 			mutex_exit(&listener->tcp_eager_lock);
16071 		}
16072 	}
16073 		/* FALLTHRU */
16074 	case TCPS_SYN_SENT:
16075 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16076 		second_threshold = tcp->tcp_second_ctimer_threshold;
16077 		break;
16078 	case TCPS_ESTABLISHED:
16079 	case TCPS_FIN_WAIT_1:
16080 	case TCPS_CLOSING:
16081 	case TCPS_CLOSE_WAIT:
16082 	case TCPS_LAST_ACK:
16083 		/* If we have data to rexmit */
16084 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16085 			clock_t	time_to_wait;
16086 
16087 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16088 			if (!tcp->tcp_xmit_head)
16089 				break;
16090 			time_to_wait = lbolt -
16091 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16092 			time_to_wait = tcp->tcp_rto -
16093 			    TICK_TO_MSEC(time_to_wait);
16094 			/*
16095 			 * If the timer fires too early, 1 clock tick earlier,
16096 			 * restart the timer.
16097 			 */
16098 			if (time_to_wait > msec_per_tick) {
16099 				TCP_STAT(tcp_timer_fire_early);
16100 				TCP_TIMER_RESTART(tcp, time_to_wait);
16101 				return;
16102 			}
16103 			/*
16104 			 * When we probe zero windows, we force the swnd open.
16105 			 * If our peer acks with a closed window swnd will be
16106 			 * set to zero by tcp_rput(). As long as we are
16107 			 * receiving acks tcp_rput will
16108 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16109 			 * first and second interval actions.  NOTE: the timer
16110 			 * interval is allowed to continue its exponential
16111 			 * backoff.
16112 			 */
16113 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16114 				if (tcp->tcp_debug) {
16115 					(void) strlog(TCP_MOD_ID, 0, 1,
16116 					    SL_TRACE, "tcp_timer: zero win");
16117 				}
16118 			} else {
16119 				/*
16120 				 * After retransmission, we need to do
16121 				 * slow start.  Set the ssthresh to one
16122 				 * half of current effective window and
16123 				 * cwnd to one MSS.  Also reset
16124 				 * tcp_cwnd_cnt.
16125 				 *
16126 				 * Note that if tcp_ssthresh is reduced because
16127 				 * of ECN, do not reduce it again unless it is
16128 				 * already one window of data away (tcp_cwr
16129 				 * should then be cleared) or this is a
16130 				 * timeout for a retransmitted segment.
16131 				 */
16132 				uint32_t npkt;
16133 
16134 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16135 					npkt = ((tcp->tcp_timer_backoff ?
16136 					    tcp->tcp_cwnd_ssthresh :
16137 					    tcp->tcp_snxt -
16138 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16139 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16140 					    tcp->tcp_mss;
16141 				}
16142 				tcp->tcp_cwnd = tcp->tcp_mss;
16143 				tcp->tcp_cwnd_cnt = 0;
16144 				if (tcp->tcp_ecn_ok) {
16145 					tcp->tcp_cwr = B_TRUE;
16146 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16147 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16148 				}
16149 			}
16150 			break;
16151 		}
16152 		/*
16153 		 * We have something to send yet we cannot send.  The
16154 		 * reason can be:
16155 		 *
16156 		 * 1. Zero send window: we need to do zero window probe.
16157 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16158 		 * segments.
16159 		 * 3. SWS avoidance: receiver may have shrunk window,
16160 		 * reset our knowledge.
16161 		 *
16162 		 * Note that condition 2 can happen with either 1 or
16163 		 * 3.  But 1 and 3 are exclusive.
16164 		 */
16165 		if (tcp->tcp_unsent != 0) {
16166 			if (tcp->tcp_cwnd == 0) {
16167 				/*
16168 				 * Set tcp_cwnd to 1 MSS so that a
16169 				 * new segment can be sent out.  We
16170 				 * are "clocking out" new data when
16171 				 * the network is really congested.
16172 				 */
16173 				ASSERT(tcp->tcp_ecn_ok);
16174 				tcp->tcp_cwnd = tcp->tcp_mss;
16175 			}
16176 			if (tcp->tcp_swnd == 0) {
16177 				/* Extend window for zero window probe */
16178 				tcp->tcp_swnd++;
16179 				tcp->tcp_zero_win_probe = B_TRUE;
16180 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
16181 			} else {
16182 				/*
16183 				 * Handle timeout from sender SWS avoidance.
16184 				 * Reset our knowledge of the max send window
16185 				 * since the receiver might have reduced its
16186 				 * receive buffer.  Avoid setting tcp_max_swnd
16187 				 * to one since that will essentially disable
16188 				 * the SWS checks.
16189 				 *
16190 				 * Note that since we don't have a SWS
16191 				 * state variable, if the timeout is set
16192 				 * for ECN but not for SWS, this
16193 				 * code will also be executed.  This is
16194 				 * fine as tcp_max_swnd is updated
16195 				 * constantly and it will not affect
16196 				 * anything.
16197 				 */
16198 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16199 			}
16200 			tcp_wput_data(tcp, NULL, B_FALSE);
16201 			return;
16202 		}
16203 		/* Is there a FIN that needs to be to re retransmitted? */
16204 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16205 		    !tcp->tcp_fin_acked)
16206 			break;
16207 		/* Nothing to do, return without restarting timer. */
16208 		TCP_STAT(tcp_timer_fire_miss);
16209 		return;
16210 	case TCPS_FIN_WAIT_2:
16211 		/*
16212 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16213 		 * We waited some time for for peer's FIN, but it hasn't
16214 		 * arrived.  We flush the connection now to avoid
16215 		 * case where the peer has rebooted.
16216 		 */
16217 		if (TCP_IS_DETACHED(tcp)) {
16218 			(void) tcp_clean_death(tcp, 0, 23);
16219 		} else {
16220 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
16221 		}
16222 		return;
16223 	case TCPS_TIME_WAIT:
16224 		(void) tcp_clean_death(tcp, 0, 24);
16225 		return;
16226 	default:
16227 		if (tcp->tcp_debug) {
16228 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16229 			    "tcp_timer: strange state (%d) %s",
16230 			    tcp->tcp_state, tcp_display(tcp, NULL,
16231 			    DISP_PORT_ONLY));
16232 		}
16233 		return;
16234 	}
16235 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16236 		/*
16237 		 * For zero window probe, we need to send indefinitely,
16238 		 * unless we have not heard from the other side for some
16239 		 * time...
16240 		 */
16241 		if ((tcp->tcp_zero_win_probe == 0) ||
16242 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16243 		    second_threshold)) {
16244 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
16245 			/*
16246 			 * If TCP is in SYN_RCVD state, send back a
16247 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16248 			 * should be zero in TCPS_SYN_RCVD state.
16249 			 */
16250 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16251 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16252 				    "in SYN_RCVD",
16253 				    tcp, tcp->tcp_snxt,
16254 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16255 			}
16256 			(void) tcp_clean_death(tcp,
16257 			    tcp->tcp_client_errno ?
16258 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16259 			return;
16260 		} else {
16261 			/*
16262 			 * Set tcp_ms_we_have_waited to second_threshold
16263 			 * so that in next timeout, we will do the above
16264 			 * check (lbolt - tcp_last_recv_time).  This is
16265 			 * also to avoid overflow.
16266 			 *
16267 			 * We don't need to decrement tcp_timer_backoff
16268 			 * to avoid overflow because it will be decremented
16269 			 * later if new timeout value is greater than
16270 			 * tcp_rexmit_interval_max.  In the case when
16271 			 * tcp_rexmit_interval_max is greater than
16272 			 * second_threshold, it means that we will wait
16273 			 * longer than second_threshold to send the next
16274 			 * window probe.
16275 			 */
16276 			tcp->tcp_ms_we_have_waited = second_threshold;
16277 		}
16278 	} else if (ms > first_threshold) {
16279 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16280 		    tcp->tcp_xmit_head != NULL) {
16281 			tcp->tcp_xmit_head =
16282 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16283 		}
16284 		/*
16285 		 * We have been retransmitting for too long...  The RTT
16286 		 * we calculated is probably incorrect.  Reinitialize it.
16287 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16288 		 * tcp_rtt_update so that we won't accidentally cache a
16289 		 * bad value.  But only do this if this is not a zero
16290 		 * window probe.
16291 		 */
16292 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16293 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16294 			    (tcp->tcp_rtt_sa >> 5);
16295 			tcp->tcp_rtt_sa = 0;
16296 			tcp_ip_notify(tcp);
16297 			tcp->tcp_rtt_update = 0;
16298 		}
16299 	}
16300 	tcp->tcp_timer_backoff++;
16301 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16302 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16303 	    tcp_rexmit_interval_min) {
16304 		/*
16305 		 * This means the original RTO is tcp_rexmit_interval_min.
16306 		 * So we will use tcp_rexmit_interval_min as the RTO value
16307 		 * and do the backoff.
16308 		 */
16309 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
16310 	} else {
16311 		ms <<= tcp->tcp_timer_backoff;
16312 	}
16313 	if (ms > tcp_rexmit_interval_max) {
16314 		ms = tcp_rexmit_interval_max;
16315 		/*
16316 		 * ms is at max, decrement tcp_timer_backoff to avoid
16317 		 * overflow.
16318 		 */
16319 		tcp->tcp_timer_backoff--;
16320 	}
16321 	tcp->tcp_ms_we_have_waited += ms;
16322 	if (tcp->tcp_zero_win_probe == 0) {
16323 		tcp->tcp_rto = ms;
16324 	}
16325 	TCP_TIMER_RESTART(tcp, ms);
16326 	/*
16327 	 * This is after a timeout and tcp_rto is backed off.  Set
16328 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16329 	 * restart the timer with a correct value.
16330 	 */
16331 	tcp->tcp_set_timer = 1;
16332 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16333 	if (mss > tcp->tcp_mss)
16334 		mss = tcp->tcp_mss;
16335 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16336 		mss = tcp->tcp_swnd;
16337 
16338 	if ((mp = tcp->tcp_xmit_head) != NULL)
16339 		mp->b_prev = (mblk_t *)lbolt;
16340 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16341 	    B_TRUE);
16342 
16343 	/*
16344 	 * When slow start after retransmission begins, start with
16345 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16346 	 * start phase.  tcp_snd_burst controls how many segments
16347 	 * can be sent because of an ack.
16348 	 */
16349 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16350 	tcp->tcp_snd_burst = TCP_CWND_SS;
16351 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16352 	    (tcp->tcp_unsent == 0)) {
16353 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16354 	} else {
16355 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16356 	}
16357 	tcp->tcp_rexmit = B_TRUE;
16358 	tcp->tcp_dupack_cnt = 0;
16359 
16360 	/*
16361 	 * Remove all rexmit SACK blk to start from fresh.
16362 	 */
16363 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16364 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16365 		tcp->tcp_num_notsack_blk = 0;
16366 		tcp->tcp_cnt_notsack_list = 0;
16367 	}
16368 	if (mp == NULL) {
16369 		return;
16370 	}
16371 	/* Attach credentials to retransmitted initial SYNs. */
16372 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16373 		mblk_setcred(mp, tcp->tcp_cred);
16374 		DB_CPID(mp) = tcp->tcp_cpid;
16375 	}
16376 
16377 	tcp->tcp_csuna = tcp->tcp_snxt;
16378 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
16379 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
16380 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
16381 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16382 
16383 }
16384 
16385 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16386 static void
16387 tcp_unbind(tcp_t *tcp, mblk_t *mp)
16388 {
16389 	conn_t	*connp;
16390 
16391 	switch (tcp->tcp_state) {
16392 	case TCPS_BOUND:
16393 	case TCPS_LISTEN:
16394 		break;
16395 	default:
16396 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
16397 		return;
16398 	}
16399 
16400 	/*
16401 	 * Need to clean up all the eagers since after the unbind, segments
16402 	 * will no longer be delivered to this listener stream.
16403 	 */
16404 	mutex_enter(&tcp->tcp_eager_lock);
16405 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16406 		tcp_eager_cleanup(tcp, 0);
16407 	}
16408 	mutex_exit(&tcp->tcp_eager_lock);
16409 
16410 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16411 		tcp->tcp_ipha->ipha_src = 0;
16412 	} else {
16413 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16414 	}
16415 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16416 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16417 	tcp_bind_hash_remove(tcp);
16418 	tcp->tcp_state = TCPS_IDLE;
16419 	tcp->tcp_mdt = B_FALSE;
16420 	/* Send M_FLUSH according to TPI */
16421 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16422 	connp = tcp->tcp_connp;
16423 	connp->conn_mdt_ok = B_FALSE;
16424 	ipcl_hash_remove(connp);
16425 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16426 	mp = mi_tpi_ok_ack_alloc(mp);
16427 	putnext(tcp->tcp_rq, mp);
16428 }
16429 
16430 /*
16431  * Don't let port fall into the privileged range.
16432  * Since the extra privileged ports can be arbitrary we also
16433  * ensure that we exclude those from consideration.
16434  * tcp_g_epriv_ports is not sorted thus we loop over it until
16435  * there are no changes.
16436  *
16437  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16438  * but instead the code relies on:
16439  * - the fact that the address of the array and its size never changes
16440  * - the atomic assignment of the elements of the array
16441  */
16442 static in_port_t
16443 tcp_update_next_port(in_port_t port, boolean_t random)
16444 {
16445 	int i;
16446 
16447 	if (random && tcp_random_anon_port != 0) {
16448 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16449 		    sizeof (in_port_t));
16450 		/*
16451 		 * Unless changed by a sys admin, the smallest anon port
16452 		 * is 32768 and the largest anon port is 65535.  It is
16453 		 * very likely (50%) for the random port to be smaller
16454 		 * than the smallest anon port.  When that happens,
16455 		 * add port % (anon port range) to the smallest anon
16456 		 * port to get the random port.  It should fall into the
16457 		 * valid anon port range.
16458 		 */
16459 		if (port < tcp_smallest_anon_port) {
16460 			port = tcp_smallest_anon_port +
16461 			    port % (tcp_largest_anon_port -
16462 				tcp_smallest_anon_port);
16463 		}
16464 	}
16465 
16466 retry:
16467 	if (port < tcp_smallest_anon_port || port > tcp_largest_anon_port)
16468 		port = (in_port_t)tcp_smallest_anon_port;
16469 
16470 	if (port < tcp_smallest_nonpriv_port)
16471 		port = (in_port_t)tcp_smallest_nonpriv_port;
16472 
16473 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
16474 		if (port == tcp_g_epriv_ports[i]) {
16475 			port++;
16476 			/*
16477 			 * Make sure whether the port is in the
16478 			 * valid range.
16479 			 *
16480 			 * XXX Note that if tcp_g_epriv_ports contains
16481 			 * all the anonymous ports this will be an
16482 			 * infinite loop.
16483 			 */
16484 			goto retry;
16485 		}
16486 	}
16487 	return (port);
16488 }
16489 
16490 /*
16491  * Return the next anonymous port in the priviledged port range for
16492  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16493  * downwards.  This is the same behavior as documented in the userland
16494  * library call rresvport(3N).
16495  */
16496 static in_port_t
16497 tcp_get_next_priv_port(void)
16498 {
16499 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16500 
16501 	if (next_priv_port < tcp_min_anonpriv_port) {
16502 		next_priv_port = IPPORT_RESERVED - 1;
16503 	}
16504 	return (next_priv_port--);
16505 }
16506 
16507 /* The write side r/w procedure. */
16508 
16509 #if CCS_STATS
16510 struct {
16511 	struct {
16512 		int64_t count, bytes;
16513 	} tot, hit;
16514 } wrw_stats;
16515 #endif
16516 
16517 /*
16518  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16519  * messages.
16520  */
16521 /* ARGSUSED */
16522 static void
16523 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16524 {
16525 	conn_t	*connp = (conn_t *)arg;
16526 	tcp_t	*tcp = connp->conn_tcp;
16527 	queue_t	*q = tcp->tcp_wq;
16528 
16529 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16530 	/*
16531 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16532 	 * Once the close starts, streamhead and sockfs will not let any data
16533 	 * packets come down (close ensures that there are no threads using the
16534 	 * queue and no new threads will come down) but since qprocsoff()
16535 	 * hasn't happened yet, a M_FLUSH or some non data message might
16536 	 * get reflected back (in response to our own FLUSHRW) and get
16537 	 * processed after tcp_close() is done. The conn would still be valid
16538 	 * because a ref would have added but we need to check the state
16539 	 * before actually processing the packet.
16540 	 */
16541 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16542 		freemsg(mp);
16543 		return;
16544 	}
16545 
16546 	switch (DB_TYPE(mp)) {
16547 	case M_IOCDATA:
16548 		tcp_wput_iocdata(tcp, mp);
16549 		break;
16550 	case M_FLUSH:
16551 		tcp_wput_flush(tcp, mp);
16552 		break;
16553 	default:
16554 		CALL_IP_WPUT(connp, q, mp);
16555 		break;
16556 	}
16557 }
16558 
16559 /*
16560  * The TCP fast path write put procedure.
16561  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16562  */
16563 /* ARGSUSED */
16564 static void
16565 tcp_output(void *arg, mblk_t *mp, void *arg2)
16566 {
16567 	int		len;
16568 	int		hdrlen;
16569 	int		plen;
16570 	mblk_t		*mp1;
16571 	uchar_t		*rptr;
16572 	uint32_t	snxt;
16573 	tcph_t		*tcph;
16574 	struct datab	*db;
16575 	uint32_t	suna;
16576 	uint32_t	mss;
16577 	ipaddr_t	*dst;
16578 	ipaddr_t	*src;
16579 	uint32_t	sum;
16580 	int		usable;
16581 	conn_t		*connp = (conn_t *)arg;
16582 	tcp_t		*tcp = connp->conn_tcp;
16583 	uint32_t	msize;
16584 
16585 	/*
16586 	 * Try and ASSERT the minimum possible references on the
16587 	 * conn early enough. Since we are executing on write side,
16588 	 * the connection is obviously not detached and that means
16589 	 * there is a ref each for TCP and IP. Since we are behind
16590 	 * the squeue, the minimum references needed are 3. If the
16591 	 * conn is in classifier hash list, there should be an
16592 	 * extra ref for that (we check both the possibilities).
16593 	 */
16594 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16595 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16596 
16597 	/* Bypass tcp protocol for fused tcp loopback */
16598 	if (tcp->tcp_fused) {
16599 		msize = msgdsize(mp);
16600 		mutex_enter(&connp->conn_lock);
16601 		tcp->tcp_squeue_bytes -= msize;
16602 		mutex_exit(&connp->conn_lock);
16603 
16604 		if (tcp_fuse_output(tcp, mp, msize))
16605 			return;
16606 	}
16607 
16608 	mss = tcp->tcp_mss;
16609 	if (tcp->tcp_xmit_zc_clean)
16610 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16611 
16612 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16613 	len = (int)(mp->b_wptr - mp->b_rptr);
16614 
16615 	/*
16616 	 * Criteria for fast path:
16617 	 *
16618 	 *   1. no unsent data
16619 	 *   2. single mblk in request
16620 	 *   3. connection established
16621 	 *   4. data in mblk
16622 	 *   5. len <= mss
16623 	 *   6. no tcp_valid bits
16624 	 */
16625 	if ((tcp->tcp_unsent != 0) ||
16626 	    (tcp->tcp_cork) ||
16627 	    (mp->b_cont != NULL) ||
16628 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16629 	    (len == 0) ||
16630 	    (len > mss) ||
16631 	    (tcp->tcp_valid_bits != 0)) {
16632 		msize = msgdsize(mp);
16633 		mutex_enter(&connp->conn_lock);
16634 		tcp->tcp_squeue_bytes -= msize;
16635 		mutex_exit(&connp->conn_lock);
16636 
16637 		tcp_wput_data(tcp, mp, B_FALSE);
16638 		return;
16639 	}
16640 
16641 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16642 	ASSERT(tcp->tcp_fin_sent == 0);
16643 
16644 	mutex_enter(&connp->conn_lock);
16645 	tcp->tcp_squeue_bytes -= len;
16646 	mutex_exit(&connp->conn_lock);
16647 
16648 	/* queue new packet onto retransmission queue */
16649 	if (tcp->tcp_xmit_head == NULL) {
16650 		tcp->tcp_xmit_head = mp;
16651 	} else {
16652 		tcp->tcp_xmit_last->b_cont = mp;
16653 	}
16654 	tcp->tcp_xmit_last = mp;
16655 	tcp->tcp_xmit_tail = mp;
16656 
16657 	/* find out how much we can send */
16658 	/* BEGIN CSTYLED */
16659 	/*
16660 	 *    un-acked           usable
16661 	 *  |--------------|-----------------|
16662 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
16663 	 */
16664 	/* END CSTYLED */
16665 
16666 	/* start sending from tcp_snxt */
16667 	snxt = tcp->tcp_snxt;
16668 
16669 	/*
16670 	 * Check to see if this connection has been idled for some
16671 	 * time and no ACK is expected.  If it is, we need to slow
16672 	 * start again to get back the connection's "self-clock" as
16673 	 * described in VJ's paper.
16674 	 *
16675 	 * Refer to the comment in tcp_mss_set() for the calculation
16676 	 * of tcp_cwnd after idle.
16677 	 */
16678 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16679 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16680 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
16681 	}
16682 
16683 	usable = tcp->tcp_swnd;		/* tcp window size */
16684 	if (usable > tcp->tcp_cwnd)
16685 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16686 	usable -= snxt;		/* subtract stuff already sent */
16687 	suna = tcp->tcp_suna;
16688 	usable += suna;
16689 	/* usable can be < 0 if the congestion window is smaller */
16690 	if (len > usable) {
16691 		/* Can't send complete M_DATA in one shot */
16692 		goto slow;
16693 	}
16694 
16695 	if (tcp->tcp_flow_stopped &&
16696 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16697 		tcp_clrqfull(tcp);
16698 	}
16699 
16700 	/*
16701 	 * determine if anything to send (Nagle).
16702 	 *
16703 	 *   1. len < tcp_mss (i.e. small)
16704 	 *   2. unacknowledged data present
16705 	 *   3. len < nagle limit
16706 	 *   4. last packet sent < nagle limit (previous packet sent)
16707 	 */
16708 	if ((len < mss) && (snxt != suna) &&
16709 	    (len < (int)tcp->tcp_naglim) &&
16710 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
16711 		/*
16712 		 * This was the first unsent packet and normally
16713 		 * mss < xmit_hiwater so there is no need to worry
16714 		 * about flow control. The next packet will go
16715 		 * through the flow control check in tcp_wput_data().
16716 		 */
16717 		/* leftover work from above */
16718 		tcp->tcp_unsent = len;
16719 		tcp->tcp_xmit_tail_unsent = len;
16720 
16721 		return;
16722 	}
16723 
16724 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
16725 
16726 	if (snxt == suna) {
16727 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16728 	}
16729 
16730 	/* we have always sent something */
16731 	tcp->tcp_rack_cnt = 0;
16732 
16733 	tcp->tcp_snxt = snxt + len;
16734 	tcp->tcp_rack = tcp->tcp_rnxt;
16735 
16736 	if ((mp1 = dupb(mp)) == 0)
16737 		goto no_memory;
16738 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
16739 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
16740 
16741 	/* adjust tcp header information */
16742 	tcph = tcp->tcp_tcph;
16743 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
16744 
16745 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
16746 	sum = (sum >> 16) + (sum & 0xFFFF);
16747 	U16_TO_ABE16(sum, tcph->th_sum);
16748 
16749 	U32_TO_ABE32(snxt, tcph->th_seq);
16750 
16751 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
16752 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
16753 	BUMP_LOCAL(tcp->tcp_obsegs);
16754 
16755 	/* Update the latest receive window size in TCP header. */
16756 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
16757 	    tcph->th_win);
16758 
16759 	tcp->tcp_last_sent_len = (ushort_t)len;
16760 
16761 	plen = len + tcp->tcp_hdr_len;
16762 
16763 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16764 		tcp->tcp_ipha->ipha_length = htons(plen);
16765 	} else {
16766 		tcp->tcp_ip6h->ip6_plen = htons(plen -
16767 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
16768 	}
16769 
16770 	/* see if we need to allocate a mblk for the headers */
16771 	hdrlen = tcp->tcp_hdr_len;
16772 	rptr = mp1->b_rptr - hdrlen;
16773 	db = mp1->b_datap;
16774 	if ((db->db_ref != 2) || rptr < db->db_base ||
16775 	    (!OK_32PTR(rptr))) {
16776 		/* NOTE: we assume allocb returns an OK_32PTR */
16777 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
16778 		    tcp_wroff_xtra, BPRI_MED);
16779 		if (!mp) {
16780 			freemsg(mp1);
16781 			goto no_memory;
16782 		}
16783 		mp->b_cont = mp1;
16784 		mp1 = mp;
16785 		/* Leave room for Link Level header */
16786 		/* hdrlen = tcp->tcp_hdr_len; */
16787 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
16788 		mp1->b_wptr = &rptr[hdrlen];
16789 	}
16790 	mp1->b_rptr = rptr;
16791 
16792 	/* Fill in the timestamp option. */
16793 	if (tcp->tcp_snd_ts_ok) {
16794 		U32_TO_BE32((uint32_t)lbolt,
16795 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
16796 		U32_TO_BE32(tcp->tcp_ts_recent,
16797 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
16798 	} else {
16799 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
16800 	}
16801 
16802 	/* copy header into outgoing packet */
16803 	dst = (ipaddr_t *)rptr;
16804 	src = (ipaddr_t *)tcp->tcp_iphc;
16805 	dst[0] = src[0];
16806 	dst[1] = src[1];
16807 	dst[2] = src[2];
16808 	dst[3] = src[3];
16809 	dst[4] = src[4];
16810 	dst[5] = src[5];
16811 	dst[6] = src[6];
16812 	dst[7] = src[7];
16813 	dst[8] = src[8];
16814 	dst[9] = src[9];
16815 	if (hdrlen -= 40) {
16816 		hdrlen >>= 2;
16817 		dst += 10;
16818 		src += 10;
16819 		do {
16820 			*dst++ = *src++;
16821 		} while (--hdrlen);
16822 	}
16823 
16824 	/*
16825 	 * Set the ECN info in the TCP header.  Note that this
16826 	 * is not the template header.
16827 	 */
16828 	if (tcp->tcp_ecn_ok) {
16829 		SET_ECT(tcp, rptr);
16830 
16831 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
16832 		if (tcp->tcp_ecn_echo_on)
16833 			tcph->th_flags[0] |= TH_ECE;
16834 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
16835 			tcph->th_flags[0] |= TH_CWR;
16836 			tcp->tcp_ecn_cwr_sent = B_TRUE;
16837 		}
16838 	}
16839 
16840 	if (tcp->tcp_ip_forward_progress) {
16841 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
16842 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
16843 		tcp->tcp_ip_forward_progress = B_FALSE;
16844 	}
16845 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
16846 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
16847 	return;
16848 
16849 	/*
16850 	 * If we ran out of memory, we pretend to have sent the packet
16851 	 * and that it was lost on the wire.
16852 	 */
16853 no_memory:
16854 	return;
16855 
16856 slow:
16857 	/* leftover work from above */
16858 	tcp->tcp_unsent = len;
16859 	tcp->tcp_xmit_tail_unsent = len;
16860 	tcp_wput_data(tcp, NULL, B_FALSE);
16861 }
16862 
16863 /*
16864  * The function called through squeue to get behind eager's perimeter to
16865  * finish the accept processing.
16866  */
16867 /* ARGSUSED */
16868 void
16869 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
16870 {
16871 	conn_t			*connp = (conn_t *)arg;
16872 	tcp_t			*tcp = connp->conn_tcp;
16873 	queue_t			*q = tcp->tcp_rq;
16874 	mblk_t			*mp1;
16875 	mblk_t			*stropt_mp = mp;
16876 	struct  stroptions	*stropt;
16877 	uint_t			thwin;
16878 
16879 	/*
16880 	 * Drop the eager's ref on the listener, that was placed when
16881 	 * this eager began life in tcp_conn_request.
16882 	 */
16883 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
16884 
16885 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
16886 		/*
16887 		 * Someone blewoff the eager before we could finish
16888 		 * the accept.
16889 		 *
16890 		 * The only reason eager exists it because we put in
16891 		 * a ref on it when conn ind went up. We need to send
16892 		 * a disconnect indication up while the last reference
16893 		 * on the eager will be dropped by the squeue when we
16894 		 * return.
16895 		 */
16896 		ASSERT(tcp->tcp_listener == NULL);
16897 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
16898 			struct	T_discon_ind	*tdi;
16899 
16900 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
16901 			/*
16902 			 * Let us reuse the incoming mblk to avoid memory
16903 			 * allocation failure problems. We know that the
16904 			 * size of the incoming mblk i.e. stroptions is greater
16905 			 * than sizeof T_discon_ind. So the reallocb below
16906 			 * can't fail.
16907 			 */
16908 			freemsg(mp->b_cont);
16909 			mp->b_cont = NULL;
16910 			ASSERT(DB_REF(mp) == 1);
16911 			mp = reallocb(mp, sizeof (struct T_discon_ind),
16912 			    B_FALSE);
16913 			ASSERT(mp != NULL);
16914 			DB_TYPE(mp) = M_PROTO;
16915 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
16916 			tdi = (struct T_discon_ind *)mp->b_rptr;
16917 			if (tcp->tcp_issocket) {
16918 				tdi->DISCON_reason = ECONNREFUSED;
16919 				tdi->SEQ_number = 0;
16920 			} else {
16921 				tdi->DISCON_reason = ENOPROTOOPT;
16922 				tdi->SEQ_number =
16923 				    tcp->tcp_conn_req_seqnum;
16924 			}
16925 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
16926 			putnext(q, mp);
16927 		} else {
16928 			freemsg(mp);
16929 		}
16930 		if (tcp->tcp_hard_binding) {
16931 			tcp->tcp_hard_binding = B_FALSE;
16932 			tcp->tcp_hard_bound = B_TRUE;
16933 		}
16934 		tcp->tcp_detached = B_FALSE;
16935 		return;
16936 	}
16937 
16938 	mp1 = stropt_mp->b_cont;
16939 	stropt_mp->b_cont = NULL;
16940 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
16941 	stropt = (struct stroptions *)stropt_mp->b_rptr;
16942 
16943 	while (mp1 != NULL) {
16944 		mp = mp1;
16945 		mp1 = mp1->b_cont;
16946 		mp->b_cont = NULL;
16947 		tcp->tcp_drop_opt_ack_cnt++;
16948 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
16949 	}
16950 	mp = NULL;
16951 
16952 	/*
16953 	 * For a loopback connection with tcp_direct_sockfs on, note that
16954 	 * we don't have to protect tcp_rcv_list yet because synchronous
16955 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
16956 	 * possibly race with us.
16957 	 */
16958 
16959 	/*
16960 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
16961 	 * properly.  This is the first time we know of the acceptor'
16962 	 * queue.  So we do it here.
16963 	 */
16964 	if (tcp->tcp_rcv_list == NULL) {
16965 		/*
16966 		 * Recv queue is empty, tcp_rwnd should not have changed.
16967 		 * That means it should be equal to the listener's tcp_rwnd.
16968 		 */
16969 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
16970 	} else {
16971 #ifdef DEBUG
16972 		uint_t cnt = 0;
16973 
16974 		mp1 = tcp->tcp_rcv_list;
16975 		while ((mp = mp1) != NULL) {
16976 			mp1 = mp->b_next;
16977 			cnt += msgdsize(mp);
16978 		}
16979 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
16980 #endif
16981 		/* There is some data, add them back to get the max. */
16982 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
16983 	}
16984 
16985 	stropt->so_flags = SO_HIWAT;
16986 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
16987 
16988 	stropt->so_flags |= SO_MAXBLK;
16989 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
16990 
16991 	/*
16992 	 * This is the first time we run on the correct
16993 	 * queue after tcp_accept. So fix all the q parameters
16994 	 * here.
16995 	 */
16996 	/* Allocate room for SACK options if needed. */
16997 	stropt->so_flags |= SO_WROFF;
16998 	if (tcp->tcp_fused) {
16999 		ASSERT(tcp->tcp_loopback);
17000 		ASSERT(tcp->tcp_loopback_peer != NULL);
17001 		/*
17002 		 * For fused tcp loopback, set the stream head's write
17003 		 * offset value to zero since we won't be needing any room
17004 		 * for TCP/IP headers.  This would also improve performance
17005 		 * since it would reduce the amount of work done by kmem.
17006 		 * Non-fused tcp loopback case is handled separately below.
17007 		 */
17008 		stropt->so_wroff = 0;
17009 		/*
17010 		 * Record the stream head's high water mark for this endpoint;
17011 		 * this is used for flow-control purposes in tcp_fuse_output().
17012 		 */
17013 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17014 		/*
17015 		 * Update the peer's transmit parameters according to
17016 		 * our recently calculated high water mark value.
17017 		 */
17018 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17019 	} else if (tcp->tcp_snd_sack_ok) {
17020 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17021 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17022 	} else {
17023 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17024 		    tcp_wroff_xtra);
17025 	}
17026 
17027 	/* Send the options up */
17028 	putnext(q, stropt_mp);
17029 
17030 	/*
17031 	 * Pass up any data and/or a fin that has been received.
17032 	 *
17033 	 * Adjust receive window in case it had decreased
17034 	 * (because there is data <=> tcp_rcv_list != NULL)
17035 	 * while the connection was detached. Note that
17036 	 * in case the eager was flow-controlled, w/o this
17037 	 * code, the rwnd may never open up again!
17038 	 */
17039 	if (tcp->tcp_rcv_list != NULL) {
17040 		/* We drain directly in case of fused tcp loopback */
17041 		if (!tcp->tcp_fused && canputnext(q)) {
17042 			tcp->tcp_rwnd = q->q_hiwat;
17043 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17044 			    << tcp->tcp_rcv_ws;
17045 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17046 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17047 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17048 				tcp_xmit_ctl(NULL,
17049 				    tcp, (tcp->tcp_swnd == 0) ?
17050 				    tcp->tcp_suna : tcp->tcp_snxt,
17051 				    tcp->tcp_rnxt, TH_ACK);
17052 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17053 			}
17054 
17055 		}
17056 		(void) tcp_rcv_drain(q, tcp);
17057 
17058 		/*
17059 		 * For fused tcp loopback, back-enable peer endpoint
17060 		 * if it's currently flow-controlled.
17061 		 */
17062 		if (tcp->tcp_fused &&
17063 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17064 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17065 
17066 			ASSERT(peer_tcp != NULL);
17067 			ASSERT(peer_tcp->tcp_fused);
17068 
17069 			tcp_clrqfull(peer_tcp);
17070 			TCP_STAT(tcp_fusion_backenabled);
17071 		}
17072 	}
17073 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17074 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17075 		mp = mi_tpi_ordrel_ind();
17076 		if (mp) {
17077 			tcp->tcp_ordrel_done = B_TRUE;
17078 			putnext(q, mp);
17079 			if (tcp->tcp_deferred_clean_death) {
17080 				/*
17081 				 * tcp_clean_death was deferred
17082 				 * for T_ORDREL_IND - do it now
17083 				 */
17084 				(void) tcp_clean_death(tcp,
17085 				    tcp->tcp_client_errno, 21);
17086 				tcp->tcp_deferred_clean_death = B_FALSE;
17087 			}
17088 		} else {
17089 			/*
17090 			 * Run the orderly release in the
17091 			 * service routine.
17092 			 */
17093 			qenable(q);
17094 		}
17095 	}
17096 	if (tcp->tcp_hard_binding) {
17097 		tcp->tcp_hard_binding = B_FALSE;
17098 		tcp->tcp_hard_bound = B_TRUE;
17099 	}
17100 
17101 	tcp->tcp_detached = B_FALSE;
17102 
17103 	/* We can enable synchronous streams now */
17104 	if (tcp->tcp_fused) {
17105 		tcp_fuse_syncstr_enable_pair(tcp);
17106 	}
17107 
17108 	if (tcp->tcp_ka_enabled) {
17109 		tcp->tcp_ka_last_intrvl = 0;
17110 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17111 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17112 	}
17113 
17114 	/*
17115 	 * At this point, eager is fully established and will
17116 	 * have the following references -
17117 	 *
17118 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17119 	 * 1 reference for the squeue which will be dropped by the squeue as
17120 	 *	soon as this function returns.
17121 	 * There will be 1 additonal reference for being in classifier
17122 	 *	hash list provided something bad hasn't happened.
17123 	 */
17124 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17125 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17126 }
17127 
17128 /*
17129  * The function called through squeue to get behind listener's perimeter to
17130  * send a deffered conn_ind.
17131  */
17132 /* ARGSUSED */
17133 void
17134 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17135 {
17136 	conn_t	*connp = (conn_t *)arg;
17137 	tcp_t *listener = connp->conn_tcp;
17138 
17139 	if (listener->tcp_state == TCPS_CLOSED ||
17140 	    TCP_IS_DETACHED(listener)) {
17141 		/*
17142 		 * If listener has closed, it would have caused a
17143 		 * a cleanup/blowoff to happen for the eager.
17144 		 */
17145 		tcp_t *tcp;
17146 		struct T_conn_ind	*conn_ind;
17147 
17148 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
17149 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17150 		    conn_ind->OPT_length);
17151 		/*
17152 		 * We need to drop the ref on eager that was put
17153 		 * tcp_rput_data() before trying to send the conn_ind
17154 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17155 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17156 		 * listener is closed so we drop the ref.
17157 		 */
17158 		CONN_DEC_REF(tcp->tcp_connp);
17159 		freemsg(mp);
17160 		return;
17161 	}
17162 	putnext(listener->tcp_rq, mp);
17163 }
17164 
17165 
17166 /*
17167  * This is the STREAMS entry point for T_CONN_RES coming down on
17168  * Acceptor STREAM when  sockfs listener does accept processing.
17169  * Read the block comment on top pf tcp_conn_request().
17170  */
17171 void
17172 tcp_wput_accept(queue_t *q, mblk_t *mp)
17173 {
17174 	queue_t *rq = RD(q);
17175 	struct T_conn_res *conn_res;
17176 	tcp_t *eager;
17177 	tcp_t *listener;
17178 	struct T_ok_ack *ok;
17179 	t_scalar_t PRIM_type;
17180 	mblk_t *opt_mp;
17181 	conn_t *econnp;
17182 
17183 	ASSERT(DB_TYPE(mp) == M_PROTO);
17184 
17185 	conn_res = (struct T_conn_res *)mp->b_rptr;
17186 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17187 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17188 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17189 		if (mp != NULL)
17190 			putnext(rq, mp);
17191 		return;
17192 	}
17193 	switch (conn_res->PRIM_type) {
17194 	case O_T_CONN_RES:
17195 	case T_CONN_RES:
17196 		/*
17197 		 * We pass up an err ack if allocb fails. This will
17198 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17199 		 * tcp_eager_blowoff to be called. sockfs will then call
17200 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17201 		 * we need to do the allocb up here because we have to
17202 		 * make sure rq->q_qinfo->qi_qclose still points to the
17203 		 * correct function (tcpclose_accept) in case allocb
17204 		 * fails.
17205 		 */
17206 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17207 		if (opt_mp == NULL) {
17208 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17209 			if (mp != NULL)
17210 				putnext(rq, mp);
17211 			return;
17212 		}
17213 
17214 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17215 		    &eager, conn_res->OPT_length);
17216 		PRIM_type = conn_res->PRIM_type;
17217 		mp->b_datap->db_type = M_PCPROTO;
17218 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17219 		ok = (struct T_ok_ack *)mp->b_rptr;
17220 		ok->PRIM_type = T_OK_ACK;
17221 		ok->CORRECT_prim = PRIM_type;
17222 		econnp = eager->tcp_connp;
17223 		econnp->conn_dev = (dev_t)q->q_ptr;
17224 		eager->tcp_rq = rq;
17225 		eager->tcp_wq = q;
17226 		rq->q_ptr = econnp;
17227 		rq->q_qinfo = &tcp_rinit;
17228 		q->q_ptr = econnp;
17229 		q->q_qinfo = &tcp_winit;
17230 		listener = eager->tcp_listener;
17231 		eager->tcp_issocket = B_TRUE;
17232 		eager->tcp_cred = econnp->conn_cred =
17233 		    listener->tcp_connp->conn_cred;
17234 		crhold(econnp->conn_cred);
17235 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17236 
17237 		/* Put the ref for IP */
17238 		CONN_INC_REF(econnp);
17239 
17240 		/*
17241 		 * We should have minimum of 3 references on the conn
17242 		 * at this point. One each for TCP and IP and one for
17243 		 * the T_conn_ind that was sent up when the 3-way handshake
17244 		 * completed. In the normal case we would also have another
17245 		 * reference (making a total of 4) for the conn being in the
17246 		 * classifier hash list. However the eager could have received
17247 		 * an RST subsequently and tcp_closei_local could have removed
17248 		 * the eager from the classifier hash list, hence we can't
17249 		 * assert that reference.
17250 		 */
17251 		ASSERT(econnp->conn_ref >= 3);
17252 
17253 		/*
17254 		 * Send the new local address also up to sockfs. There
17255 		 * should already be enough space in the mp that came
17256 		 * down from soaccept().
17257 		 */
17258 		if (eager->tcp_family == AF_INET) {
17259 			sin_t *sin;
17260 
17261 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17262 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17263 			sin = (sin_t *)mp->b_wptr;
17264 			mp->b_wptr += sizeof (sin_t);
17265 			sin->sin_family = AF_INET;
17266 			sin->sin_port = eager->tcp_lport;
17267 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17268 		} else {
17269 			sin6_t *sin6;
17270 
17271 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17272 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17273 			sin6 = (sin6_t *)mp->b_wptr;
17274 			mp->b_wptr += sizeof (sin6_t);
17275 			sin6->sin6_family = AF_INET6;
17276 			sin6->sin6_port = eager->tcp_lport;
17277 			if (eager->tcp_ipversion == IPV4_VERSION) {
17278 				sin6->sin6_flowinfo = 0;
17279 				IN6_IPADDR_TO_V4MAPPED(
17280 					eager->tcp_ipha->ipha_src,
17281 					    &sin6->sin6_addr);
17282 			} else {
17283 				ASSERT(eager->tcp_ip6h != NULL);
17284 				sin6->sin6_flowinfo =
17285 				    eager->tcp_ip6h->ip6_vcf &
17286 				    ~IPV6_VERS_AND_FLOW_MASK;
17287 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17288 			}
17289 			sin6->sin6_scope_id = 0;
17290 			sin6->__sin6_src_id = 0;
17291 		}
17292 
17293 		putnext(rq, mp);
17294 
17295 		opt_mp->b_datap->db_type = M_SETOPTS;
17296 		opt_mp->b_wptr += sizeof (struct stroptions);
17297 
17298 		/*
17299 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17300 		 * from listener to acceptor. The message is chained on the
17301 		 * bind_mp which tcp_rput_other will send down to IP.
17302 		 */
17303 		if (listener->tcp_bound_if != 0) {
17304 			/* allocate optmgmt req */
17305 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17306 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
17307 			    sizeof (int));
17308 			if (mp != NULL)
17309 				linkb(opt_mp, mp);
17310 		}
17311 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17312 			uint_t on = 1;
17313 
17314 			/* allocate optmgmt req */
17315 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17316 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
17317 			if (mp != NULL)
17318 				linkb(opt_mp, mp);
17319 		}
17320 
17321 
17322 		mutex_enter(&listener->tcp_eager_lock);
17323 
17324 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17325 
17326 			tcp_t *tail;
17327 			tcp_t *tcp;
17328 			mblk_t *mp1;
17329 
17330 			tcp = listener->tcp_eager_prev_q0;
17331 			/*
17332 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
17333 			 * deferred T_conn_ind queue. We need to get to the head
17334 			 * of the queue in order to send up T_conn_ind the same
17335 			 * order as how the 3WHS is completed.
17336 			 */
17337 			while (tcp != listener) {
17338 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
17339 					break;
17340 				else
17341 					tcp = tcp->tcp_eager_prev_q0;
17342 			}
17343 			ASSERT(tcp != listener);
17344 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17345 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17346 			/* Move from q0 to q */
17347 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17348 			listener->tcp_conn_req_cnt_q0--;
17349 			listener->tcp_conn_req_cnt_q++;
17350 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17351 			    tcp->tcp_eager_prev_q0;
17352 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17353 			    tcp->tcp_eager_next_q0;
17354 			tcp->tcp_eager_prev_q0 = NULL;
17355 			tcp->tcp_eager_next_q0 = NULL;
17356 			tcp->tcp_conn_def_q0 = B_FALSE;
17357 
17358 			/*
17359 			 * Insert at end of the queue because sockfs sends
17360 			 * down T_CONN_RES in chronological order. Leaving
17361 			 * the older conn indications at front of the queue
17362 			 * helps reducing search time.
17363 			 */
17364 			tail = listener->tcp_eager_last_q;
17365 			if (tail != NULL) {
17366 				tail->tcp_eager_next_q = tcp;
17367 			} else {
17368 				listener->tcp_eager_next_q = tcp;
17369 			}
17370 			listener->tcp_eager_last_q = tcp;
17371 			tcp->tcp_eager_next_q = NULL;
17372 
17373 			/* Need to get inside the listener perimeter */
17374 			CONN_INC_REF(listener->tcp_connp);
17375 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
17376 			    tcp_send_pending, listener->tcp_connp,
17377 			    SQTAG_TCP_SEND_PENDING);
17378 		}
17379 		tcp_eager_unlink(eager);
17380 		mutex_exit(&listener->tcp_eager_lock);
17381 
17382 		/*
17383 		 * At this point, the eager is detached from the listener
17384 		 * but we still have an extra refs on eager (apart from the
17385 		 * usual tcp references). The ref was placed in tcp_rput_data
17386 		 * before sending the conn_ind in tcp_send_conn_ind.
17387 		 * The ref will be dropped in tcp_accept_finish().
17388 		 */
17389 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
17390 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
17391 		return;
17392 	default:
17393 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17394 		if (mp != NULL)
17395 			putnext(rq, mp);
17396 		return;
17397 	}
17398 }
17399 
17400 void
17401 tcp_wput(queue_t *q, mblk_t *mp)
17402 {
17403 	conn_t	*connp = Q_TO_CONN(q);
17404 	tcp_t	*tcp;
17405 	void (*output_proc)();
17406 	t_scalar_t type;
17407 	uchar_t *rptr;
17408 	struct iocblk	*iocp;
17409 	uint32_t	msize;
17410 
17411 	ASSERT(connp->conn_ref >= 2);
17412 
17413 	switch (DB_TYPE(mp)) {
17414 	case M_DATA:
17415 		tcp = connp->conn_tcp;
17416 		ASSERT(tcp != NULL);
17417 
17418 		msize = msgdsize(mp);
17419 
17420 		mutex_enter(&connp->conn_lock);
17421 		CONN_INC_REF_LOCKED(connp);
17422 
17423 		tcp->tcp_squeue_bytes += msize;
17424 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
17425 			mutex_exit(&connp->conn_lock);
17426 			tcp_setqfull(tcp);
17427 		} else
17428 			mutex_exit(&connp->conn_lock);
17429 
17430 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17431 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
17432 		return;
17433 	case M_PROTO:
17434 	case M_PCPROTO:
17435 		/*
17436 		 * if it is a snmp message, don't get behind the squeue
17437 		 */
17438 		tcp = connp->conn_tcp;
17439 		rptr = mp->b_rptr;
17440 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
17441 			type = ((union T_primitives *)rptr)->type;
17442 		} else {
17443 			if (tcp->tcp_debug) {
17444 				(void) strlog(TCP_MOD_ID, 0, 1,
17445 				    SL_ERROR|SL_TRACE,
17446 				    "tcp_wput_proto, dropping one...");
17447 			}
17448 			freemsg(mp);
17449 			return;
17450 		}
17451 		if (type == T_SVR4_OPTMGMT_REQ) {
17452 			cred_t	*cr = DB_CREDDEF(mp,
17453 			    tcp->tcp_cred);
17454 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
17455 			    cr)) {
17456 				/*
17457 				 * This was a SNMP request
17458 				 */
17459 				return;
17460 			} else {
17461 				output_proc = tcp_wput_proto;
17462 			}
17463 		} else {
17464 			output_proc = tcp_wput_proto;
17465 		}
17466 		break;
17467 	case M_IOCTL:
17468 		/*
17469 		 * Most ioctls can be processed right away without going via
17470 		 * squeues - process them right here. Those that do require
17471 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
17472 		 * are processed by tcp_wput_ioctl().
17473 		 */
17474 		iocp = (struct iocblk *)mp->b_rptr;
17475 		tcp = connp->conn_tcp;
17476 
17477 		switch (iocp->ioc_cmd) {
17478 		case TCP_IOC_ABORT_CONN:
17479 			tcp_ioctl_abort_conn(q, mp);
17480 			return;
17481 		case TI_GETPEERNAME:
17482 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
17483 				iocp->ioc_error = ENOTCONN;
17484 				iocp->ioc_count = 0;
17485 				mp->b_datap->db_type = M_IOCACK;
17486 				qreply(q, mp);
17487 				return;
17488 			}
17489 			/* FALLTHRU */
17490 		case TI_GETMYNAME:
17491 			mi_copyin(q, mp, NULL,
17492 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
17493 			return;
17494 		case ND_SET:
17495 			/* nd_getset does the necessary checks */
17496 		case ND_GET:
17497 			if (!nd_getset(q, tcp_g_nd, mp)) {
17498 				CALL_IP_WPUT(connp, q, mp);
17499 				return;
17500 			}
17501 			qreply(q, mp);
17502 			return;
17503 		case TCP_IOC_DEFAULT_Q:
17504 			/*
17505 			 * Wants to be the default wq. Check the credentials
17506 			 * first, the rest is executed via squeue.
17507 			 */
17508 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
17509 				iocp->ioc_error = EPERM;
17510 				iocp->ioc_count = 0;
17511 				mp->b_datap->db_type = M_IOCACK;
17512 				qreply(q, mp);
17513 				return;
17514 			}
17515 			output_proc = tcp_wput_ioctl;
17516 			break;
17517 		default:
17518 			output_proc = tcp_wput_ioctl;
17519 			break;
17520 		}
17521 		break;
17522 	default:
17523 		output_proc = tcp_wput_nondata;
17524 		break;
17525 	}
17526 
17527 	CONN_INC_REF(connp);
17528 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17529 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
17530 }
17531 
17532 /*
17533  * Initial STREAMS write side put() procedure for sockets. It tries to
17534  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
17535  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
17536  * are handled by tcp_wput() as usual.
17537  *
17538  * All further messages will also be handled by tcp_wput() because we cannot
17539  * be sure that the above short cut is safe later.
17540  */
17541 static void
17542 tcp_wput_sock(queue_t *wq, mblk_t *mp)
17543 {
17544 	conn_t			*connp = Q_TO_CONN(wq);
17545 	tcp_t			*tcp = connp->conn_tcp;
17546 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
17547 
17548 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
17549 	wq->q_qinfo = &tcp_winit;
17550 
17551 	ASSERT(IPCL_IS_TCP(connp));
17552 	ASSERT(TCP_IS_SOCKET(tcp));
17553 
17554 	if (DB_TYPE(mp) == M_PCPROTO &&
17555 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
17556 	    car->PRIM_type == T_CAPABILITY_REQ) {
17557 		tcp_capability_req(tcp, mp);
17558 		return;
17559 	}
17560 
17561 	tcp_wput(wq, mp);
17562 }
17563 
17564 static boolean_t
17565 tcp_zcopy_check(tcp_t *tcp)
17566 {
17567 	conn_t	*connp = tcp->tcp_connp;
17568 	ire_t	*ire;
17569 	boolean_t	zc_enabled = B_FALSE;
17570 
17571 	if (do_tcpzcopy == 2)
17572 		zc_enabled = B_TRUE;
17573 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
17574 	    IPCL_IS_CONNECTED(connp) &&
17575 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
17576 	    connp->conn_dontroute == 0 &&
17577 	    connp->conn_xmit_if_ill == NULL &&
17578 	    connp->conn_nofailover_ill == NULL &&
17579 	    do_tcpzcopy == 1) {
17580 		/*
17581 		 * the checks above  closely resemble the fast path checks
17582 		 * in tcp_send_data().
17583 		 */
17584 		mutex_enter(&connp->conn_lock);
17585 		ire = connp->conn_ire_cache;
17586 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
17587 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17588 			IRE_REFHOLD(ire);
17589 			if (ire->ire_stq != NULL) {
17590 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
17591 
17592 				zc_enabled = ill && (ill->ill_capabilities &
17593 				    ILL_CAPAB_ZEROCOPY) &&
17594 				    (ill->ill_zerocopy_capab->
17595 				    ill_zerocopy_flags != 0);
17596 			}
17597 			IRE_REFRELE(ire);
17598 		}
17599 		mutex_exit(&connp->conn_lock);
17600 	}
17601 	tcp->tcp_snd_zcopy_on = zc_enabled;
17602 	if (!TCP_IS_DETACHED(tcp)) {
17603 		if (zc_enabled) {
17604 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
17605 			TCP_STAT(tcp_zcopy_on);
17606 		} else {
17607 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
17608 			TCP_STAT(tcp_zcopy_off);
17609 		}
17610 	}
17611 	return (zc_enabled);
17612 }
17613 
17614 static mblk_t *
17615 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
17616 {
17617 	if (do_tcpzcopy == 2)
17618 		return (bp);
17619 	else if (tcp->tcp_snd_zcopy_on) {
17620 		tcp->tcp_snd_zcopy_on = B_FALSE;
17621 		if (!TCP_IS_DETACHED(tcp)) {
17622 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
17623 			TCP_STAT(tcp_zcopy_disable);
17624 		}
17625 	}
17626 	return (tcp_zcopy_backoff(tcp, bp, 0));
17627 }
17628 
17629 /*
17630  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
17631  * the original desballoca'ed segmapped mblk.
17632  */
17633 static mblk_t *
17634 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
17635 {
17636 	mblk_t *head, *tail, *nbp;
17637 	if (IS_VMLOANED_MBLK(bp)) {
17638 		TCP_STAT(tcp_zcopy_backoff);
17639 		if ((head = copyb(bp)) == NULL) {
17640 			/* fail to backoff; leave it for the next backoff */
17641 			tcp->tcp_xmit_zc_clean = B_FALSE;
17642 			return (bp);
17643 		}
17644 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
17645 			if (fix_xmitlist)
17646 				tcp_zcopy_notify(tcp);
17647 			else
17648 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
17649 		}
17650 		nbp = bp->b_cont;
17651 		if (fix_xmitlist) {
17652 			head->b_prev = bp->b_prev;
17653 			head->b_next = bp->b_next;
17654 			if (tcp->tcp_xmit_tail == bp)
17655 				tcp->tcp_xmit_tail = head;
17656 		}
17657 		bp->b_next = NULL;
17658 		bp->b_prev = NULL;
17659 		freeb(bp);
17660 	} else {
17661 		head = bp;
17662 		nbp = bp->b_cont;
17663 	}
17664 	tail = head;
17665 	while (nbp) {
17666 		if (IS_VMLOANED_MBLK(nbp)) {
17667 			TCP_STAT(tcp_zcopy_backoff);
17668 			if ((tail->b_cont = copyb(nbp)) == NULL) {
17669 				tcp->tcp_xmit_zc_clean = B_FALSE;
17670 				tail->b_cont = nbp;
17671 				return (head);
17672 			}
17673 			tail = tail->b_cont;
17674 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
17675 				if (fix_xmitlist)
17676 					tcp_zcopy_notify(tcp);
17677 				else
17678 					tail->b_datap->db_struioflag |=
17679 					    STRUIO_ZCNOTIFY;
17680 			}
17681 			bp = nbp;
17682 			nbp = nbp->b_cont;
17683 			if (fix_xmitlist) {
17684 				tail->b_prev = bp->b_prev;
17685 				tail->b_next = bp->b_next;
17686 				if (tcp->tcp_xmit_tail == bp)
17687 					tcp->tcp_xmit_tail = tail;
17688 			}
17689 			bp->b_next = NULL;
17690 			bp->b_prev = NULL;
17691 			freeb(bp);
17692 		} else {
17693 			tail->b_cont = nbp;
17694 			tail = nbp;
17695 			nbp = nbp->b_cont;
17696 		}
17697 	}
17698 	if (fix_xmitlist) {
17699 		tcp->tcp_xmit_last = tail;
17700 		tcp->tcp_xmit_zc_clean = B_TRUE;
17701 	}
17702 	return (head);
17703 }
17704 
17705 static void
17706 tcp_zcopy_notify(tcp_t *tcp)
17707 {
17708 	struct stdata	*stp;
17709 
17710 	if (tcp->tcp_detached)
17711 		return;
17712 	stp = STREAM(tcp->tcp_rq);
17713 	mutex_enter(&stp->sd_lock);
17714 	stp->sd_flag |= STZCNOTIFY;
17715 	cv_broadcast(&stp->sd_zcopy_wait);
17716 	mutex_exit(&stp->sd_lock);
17717 }
17718 
17719 static void
17720 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
17721 {
17722 	ipha_t		*ipha;
17723 	ipaddr_t	src;
17724 	ipaddr_t	dst;
17725 	uint32_t	cksum;
17726 	ire_t		*ire;
17727 	uint16_t	*up;
17728 	ill_t		*ill;
17729 	conn_t		*connp = tcp->tcp_connp;
17730 	uint32_t	hcksum_txflags = 0;
17731 	mblk_t		*ire_fp_mp;
17732 	uint_t		ire_fp_mp_len;
17733 
17734 	ASSERT(DB_TYPE(mp) == M_DATA);
17735 
17736 	ipha = (ipha_t *)mp->b_rptr;
17737 	src = ipha->ipha_src;
17738 	dst = ipha->ipha_dst;
17739 
17740 	/*
17741 	 * Drop off slow path for IPv6 and also if options are present.
17742 	 */
17743 	if (tcp->tcp_ipversion != IPV4_VERSION ||
17744 	    !IPCL_IS_CONNECTED(connp) ||
17745 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
17746 	    connp->conn_dontroute ||
17747 	    connp->conn_xmit_if_ill != NULL ||
17748 	    connp->conn_nofailover_ill != NULL ||
17749 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
17750 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
17751 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
17752 		if (tcp->tcp_snd_zcopy_aware)
17753 			mp = tcp_zcopy_disable(tcp, mp);
17754 		TCP_STAT(tcp_ip_send);
17755 		CALL_IP_WPUT(connp, q, mp);
17756 		return;
17757 	}
17758 
17759 	mutex_enter(&connp->conn_lock);
17760 	ire = connp->conn_ire_cache;
17761 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
17762 	if (ire != NULL && ire->ire_addr == dst &&
17763 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17764 		IRE_REFHOLD(ire);
17765 		mutex_exit(&connp->conn_lock);
17766 	} else {
17767 		boolean_t cached = B_FALSE;
17768 
17769 		/* force a recheck later on */
17770 		tcp->tcp_ire_ill_check_done = B_FALSE;
17771 
17772 		TCP_DBGSTAT(tcp_ire_null1);
17773 		connp->conn_ire_cache = NULL;
17774 		mutex_exit(&connp->conn_lock);
17775 		if (ire != NULL)
17776 			IRE_REFRELE_NOTR(ire);
17777 		ire = ire_cache_lookup(dst, connp->conn_zoneid);
17778 		if (ire == NULL) {
17779 			if (tcp->tcp_snd_zcopy_aware)
17780 				mp = tcp_zcopy_backoff(tcp, mp, 0);
17781 			TCP_STAT(tcp_ire_null);
17782 			CALL_IP_WPUT(connp, q, mp);
17783 			return;
17784 		}
17785 		IRE_REFHOLD_NOTR(ire);
17786 		/*
17787 		 * Since we are inside the squeue, there cannot be another
17788 		 * thread in TCP trying to set the conn_ire_cache now.  The
17789 		 * check for IRE_MARK_CONDEMNED ensures that an interface
17790 		 * unplumb thread has not yet started cleaning up the conns.
17791 		 * Hence we don't need to grab the conn lock.
17792 		 */
17793 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
17794 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
17795 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17796 				connp->conn_ire_cache = ire;
17797 				cached = B_TRUE;
17798 			}
17799 			rw_exit(&ire->ire_bucket->irb_lock);
17800 		}
17801 
17802 		/*
17803 		 * We can continue to use the ire but since it was
17804 		 * not cached, we should drop the extra reference.
17805 		 */
17806 		if (!cached)
17807 			IRE_REFRELE_NOTR(ire);
17808 	}
17809 
17810 	if (ire->ire_flags & RTF_MULTIRT ||
17811 	    ire->ire_stq == NULL ||
17812 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
17813 	    (ire_fp_mp = ire->ire_fp_mp) == NULL ||
17814 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
17815 		if (tcp->tcp_snd_zcopy_aware)
17816 			mp = tcp_zcopy_disable(tcp, mp);
17817 		TCP_STAT(tcp_ip_ire_send);
17818 		IRE_REFRELE(ire);
17819 		CALL_IP_WPUT(connp, q, mp);
17820 		return;
17821 	}
17822 
17823 	ill = ire_to_ill(ire);
17824 	if (connp->conn_outgoing_ill != NULL) {
17825 		ill_t *conn_outgoing_ill = NULL;
17826 		/*
17827 		 * Choose a good ill in the group to send the packets on.
17828 		 */
17829 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
17830 		ill = ire_to_ill(ire);
17831 	}
17832 	ASSERT(ill != NULL);
17833 
17834 	if (!tcp->tcp_ire_ill_check_done) {
17835 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
17836 		tcp->tcp_ire_ill_check_done = B_TRUE;
17837 	}
17838 
17839 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
17840 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
17841 #ifndef _BIG_ENDIAN
17842 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
17843 #endif
17844 
17845 	/*
17846 	 * Check to see if we need to re-enable MDT for this connection
17847 	 * because it was previously disabled due to changes in the ill;
17848 	 * note that by doing it here, this re-enabling only applies when
17849 	 * the packet is not dispatched through CALL_IP_WPUT().
17850 	 *
17851 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
17852 	 * case, since that's how we ended up here.  For IPv6, we do the
17853 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
17854 	 */
17855 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
17856 		/*
17857 		 * Restore MDT for this connection, so that next time around
17858 		 * it is eligible to go through tcp_multisend() path again.
17859 		 */
17860 		TCP_STAT(tcp_mdt_conn_resumed1);
17861 		tcp->tcp_mdt = B_TRUE;
17862 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
17863 		    "interface %s\n", (void *)connp, ill->ill_name));
17864 	}
17865 
17866 	if (tcp->tcp_snd_zcopy_aware) {
17867 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
17868 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
17869 			mp = tcp_zcopy_disable(tcp, mp);
17870 		/*
17871 		 * we shouldn't need to reset ipha as the mp containing
17872 		 * ipha should never be a zero-copy mp.
17873 		 */
17874 	}
17875 
17876 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
17877 		ASSERT(ill->ill_hcksum_capab != NULL);
17878 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
17879 	}
17880 
17881 	/* pseudo-header checksum (do it in parts for IP header checksum) */
17882 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
17883 
17884 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
17885 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
17886 
17887 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
17888 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
17889 
17890 	/* Software checksum? */
17891 	if (DB_CKSUMFLAGS(mp) == 0) {
17892 		TCP_STAT(tcp_out_sw_cksum);
17893 		TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
17894 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
17895 	}
17896 
17897 	ipha->ipha_fragment_offset_and_flags |=
17898 	    (uint32_t)htons(ire->ire_frag_flag);
17899 
17900 	/* Calculate IP header checksum if hardware isn't capable */
17901 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
17902 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
17903 		    ((uint16_t *)ipha)[4]);
17904 	}
17905 
17906 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
17907 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
17908 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
17909 
17910 	UPDATE_OB_PKT_COUNT(ire);
17911 	ire->ire_last_used_time = lbolt;
17912 	BUMP_MIB(&ip_mib, ipOutRequests);
17913 
17914 	if (ILL_POLL_CAPABLE(ill)) {
17915 		/*
17916 		 * Send the packet directly to DLD, where it may be queued
17917 		 * depending on the availability of transmit resources at
17918 		 * the media layer.
17919 		 */
17920 		IP_POLL_ILL_TX(ill, mp);
17921 	} else {
17922 		putnext(ire->ire_stq, mp);
17923 	}
17924 	IRE_REFRELE(ire);
17925 }
17926 
17927 /*
17928  * This handles the case when the receiver has shrunk its win. Per RFC 1122
17929  * if the receiver shrinks the window, i.e. moves the right window to the
17930  * left, the we should not send new data, but should retransmit normally the
17931  * old unacked data between suna and suna + swnd. We might has sent data
17932  * that is now outside the new window, pretend that we didn't send  it.
17933  */
17934 static void
17935 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
17936 {
17937 	uint32_t	snxt = tcp->tcp_snxt;
17938 	mblk_t		*xmit_tail;
17939 	int32_t		offset;
17940 
17941 	ASSERT(shrunk_count > 0);
17942 
17943 	/* Pretend we didn't send the data outside the window */
17944 	snxt -= shrunk_count;
17945 
17946 	/* Get the mblk and the offset in it per the shrunk window */
17947 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
17948 
17949 	ASSERT(xmit_tail != NULL);
17950 
17951 	/* Reset all the values per the now shrunk window */
17952 	tcp->tcp_snxt = snxt;
17953 	tcp->tcp_xmit_tail = xmit_tail;
17954 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
17955 	    offset;
17956 	tcp->tcp_unsent += shrunk_count;
17957 
17958 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
17959 		/*
17960 		 * Make sure the timer is running so that we will probe a zero
17961 		 * window.
17962 		 */
17963 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17964 }
17965 
17966 
17967 /*
17968  * The TCP normal data output path.
17969  * NOTE: the logic of the fast path is duplicated from this function.
17970  */
17971 static void
17972 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
17973 {
17974 	int		len;
17975 	mblk_t		*local_time;
17976 	mblk_t		*mp1;
17977 	uint32_t	snxt;
17978 	int		tail_unsent;
17979 	int		tcpstate;
17980 	int		usable = 0;
17981 	mblk_t		*xmit_tail;
17982 	queue_t		*q = tcp->tcp_wq;
17983 	int32_t		mss;
17984 	int32_t		num_sack_blk = 0;
17985 	int32_t		tcp_hdr_len;
17986 	int32_t		tcp_tcp_hdr_len;
17987 	int		mdt_thres;
17988 	int		rc;
17989 
17990 	tcpstate = tcp->tcp_state;
17991 	if (mp == NULL) {
17992 		/*
17993 		 * tcp_wput_data() with NULL mp should only be called when
17994 		 * there is unsent data.
17995 		 */
17996 		ASSERT(tcp->tcp_unsent > 0);
17997 		/* Really tacky... but we need this for detached closes. */
17998 		len = tcp->tcp_unsent;
17999 		goto data_null;
18000 	}
18001 
18002 #if CCS_STATS
18003 	wrw_stats.tot.count++;
18004 	wrw_stats.tot.bytes += msgdsize(mp);
18005 #endif
18006 	ASSERT(mp->b_datap->db_type == M_DATA);
18007 	/*
18008 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18009 	 * or before a connection attempt has begun.
18010 	 */
18011 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18012 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18013 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18014 #ifdef DEBUG
18015 			cmn_err(CE_WARN,
18016 			    "tcp_wput_data: data after ordrel, %s",
18017 			    tcp_display(tcp, NULL,
18018 			    DISP_ADDR_AND_PORT));
18019 #else
18020 			if (tcp->tcp_debug) {
18021 				(void) strlog(TCP_MOD_ID, 0, 1,
18022 				    SL_TRACE|SL_ERROR,
18023 				    "tcp_wput_data: data after ordrel, %s\n",
18024 				    tcp_display(tcp, NULL,
18025 				    DISP_ADDR_AND_PORT));
18026 			}
18027 #endif /* DEBUG */
18028 		}
18029 		if (tcp->tcp_snd_zcopy_aware &&
18030 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18031 			tcp_zcopy_notify(tcp);
18032 		freemsg(mp);
18033 		if (tcp->tcp_flow_stopped &&
18034 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18035 			tcp_clrqfull(tcp);
18036 		}
18037 		return;
18038 	}
18039 
18040 	/* Strip empties */
18041 	for (;;) {
18042 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18043 		    (uintptr_t)INT_MAX);
18044 		len = (int)(mp->b_wptr - mp->b_rptr);
18045 		if (len > 0)
18046 			break;
18047 		mp1 = mp;
18048 		mp = mp->b_cont;
18049 		freeb(mp1);
18050 		if (!mp) {
18051 			return;
18052 		}
18053 	}
18054 
18055 	/* If we are the first on the list ... */
18056 	if (tcp->tcp_xmit_head == NULL) {
18057 		tcp->tcp_xmit_head = mp;
18058 		tcp->tcp_xmit_tail = mp;
18059 		tcp->tcp_xmit_tail_unsent = len;
18060 	} else {
18061 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18062 		struct datab *dp;
18063 
18064 		mp1 = tcp->tcp_xmit_last;
18065 		if (len < tcp_tx_pull_len &&
18066 		    (dp = mp1->b_datap)->db_ref == 1 &&
18067 		    dp->db_lim - mp1->b_wptr >= len) {
18068 			ASSERT(len > 0);
18069 			ASSERT(!mp1->b_cont);
18070 			if (len == 1) {
18071 				*mp1->b_wptr++ = *mp->b_rptr;
18072 			} else {
18073 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18074 				mp1->b_wptr += len;
18075 			}
18076 			if (mp1 == tcp->tcp_xmit_tail)
18077 				tcp->tcp_xmit_tail_unsent += len;
18078 			mp1->b_cont = mp->b_cont;
18079 			if (tcp->tcp_snd_zcopy_aware &&
18080 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18081 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18082 			freeb(mp);
18083 			mp = mp1;
18084 		} else {
18085 			tcp->tcp_xmit_last->b_cont = mp;
18086 		}
18087 		len += tcp->tcp_unsent;
18088 	}
18089 
18090 	/* Tack on however many more positive length mblks we have */
18091 	if ((mp1 = mp->b_cont) != NULL) {
18092 		do {
18093 			int tlen;
18094 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18095 			    (uintptr_t)INT_MAX);
18096 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18097 			if (tlen <= 0) {
18098 				mp->b_cont = mp1->b_cont;
18099 				freeb(mp1);
18100 			} else {
18101 				len += tlen;
18102 				mp = mp1;
18103 			}
18104 		} while ((mp1 = mp->b_cont) != NULL);
18105 	}
18106 	tcp->tcp_xmit_last = mp;
18107 	tcp->tcp_unsent = len;
18108 
18109 	if (urgent)
18110 		usable = 1;
18111 
18112 data_null:
18113 	snxt = tcp->tcp_snxt;
18114 	xmit_tail = tcp->tcp_xmit_tail;
18115 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18116 
18117 	/*
18118 	 * Note that tcp_mss has been adjusted to take into account the
18119 	 * timestamp option if applicable.  Because SACK options do not
18120 	 * appear in every TCP segments and they are of variable lengths,
18121 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18122 	 * the actual segment length when we need to send a segment which
18123 	 * includes SACK options.
18124 	 */
18125 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18126 		int32_t	opt_len;
18127 
18128 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18129 		    tcp->tcp_num_sack_blk);
18130 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18131 		    2 + TCPOPT_HEADER_LEN;
18132 		mss = tcp->tcp_mss - opt_len;
18133 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18134 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18135 	} else {
18136 		mss = tcp->tcp_mss;
18137 		tcp_hdr_len = tcp->tcp_hdr_len;
18138 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18139 	}
18140 
18141 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18142 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18143 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
18144 	}
18145 	if (tcpstate == TCPS_SYN_RCVD) {
18146 		/*
18147 		 * The three-way connection establishment handshake is not
18148 		 * complete yet. We want to queue the data for transmission
18149 		 * after entering ESTABLISHED state (RFC793). A jump to
18150 		 * "done" label effectively leaves data on the queue.
18151 		 */
18152 		goto done;
18153 	} else {
18154 		int usable_r = tcp->tcp_swnd;
18155 
18156 		/*
18157 		 * In the special case when cwnd is zero, which can only
18158 		 * happen if the connection is ECN capable, return now.
18159 		 * New segments is sent using tcp_timer().  The timer
18160 		 * is set in tcp_rput_data().
18161 		 */
18162 		if (tcp->tcp_cwnd == 0) {
18163 			/*
18164 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18165 			 * finished.
18166 			 */
18167 			ASSERT(tcp->tcp_ecn_ok ||
18168 			    tcp->tcp_state < TCPS_ESTABLISHED);
18169 			return;
18170 		}
18171 
18172 		/* NOTE: trouble if xmitting while SYN not acked? */
18173 		usable_r -= snxt;
18174 		usable_r += tcp->tcp_suna;
18175 
18176 		/*
18177 		 * Check if the receiver has shrunk the window.  If
18178 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18179 		 * cannot be set as there is unsent data, so FIN cannot
18180 		 * be sent out.  Otherwise, we need to take into account
18181 		 * of FIN as it consumes an "invisible" sequence number.
18182 		 */
18183 		ASSERT(tcp->tcp_fin_sent == 0);
18184 		if (usable_r < 0) {
18185 			/*
18186 			 * The receiver has shrunk the window and we have sent
18187 			 * -usable_r date beyond the window, re-adjust.
18188 			 *
18189 			 * If TCP window scaling is enabled, there can be
18190 			 * round down error as the advertised receive window
18191 			 * is actually right shifted n bits.  This means that
18192 			 * the lower n bits info is wiped out.  It will look
18193 			 * like the window is shrunk.  Do a check here to
18194 			 * see if the shrunk amount is actually within the
18195 			 * error in window calculation.  If it is, just
18196 			 * return.  Note that this check is inside the
18197 			 * shrunk window check.  This makes sure that even
18198 			 * though tcp_process_shrunk_swnd() is not called,
18199 			 * we will stop further processing.
18200 			 */
18201 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18202 				tcp_process_shrunk_swnd(tcp, -usable_r);
18203 			}
18204 			return;
18205 		}
18206 
18207 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18208 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18209 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18210 
18211 		/* usable = MIN(usable, unsent) */
18212 		if (usable_r > len)
18213 			usable_r = len;
18214 
18215 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18216 		if (usable_r > 0) {
18217 			usable = usable_r;
18218 		} else {
18219 			/* Bypass all other unnecessary processing. */
18220 			goto done;
18221 		}
18222 	}
18223 
18224 	local_time = (mblk_t *)lbolt;
18225 
18226 	/*
18227 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18228 	 * BSD.  This is more in line with the true intent of Nagle.
18229 	 *
18230 	 * The conditions are:
18231 	 * 1. The amount of unsent data (or amount of data which can be
18232 	 *    sent, whichever is smaller) is less than Nagle limit.
18233 	 * 2. The last sent size is also less than Nagle limit.
18234 	 * 3. There is unack'ed data.
18235 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18236 	 *    Nagle algorithm.  This reduces the probability that urgent
18237 	 *    bytes get "merged" together.
18238 	 * 5. The app has not closed the connection.  This eliminates the
18239 	 *    wait time of the receiving side waiting for the last piece of
18240 	 *    (small) data.
18241 	 *
18242 	 * If all are satisified, exit without sending anything.  Note
18243 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18244 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18245 	 * 4095).
18246 	 */
18247 	if (usable < (int)tcp->tcp_naglim &&
18248 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18249 	    snxt != tcp->tcp_suna &&
18250 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18251 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18252 		goto done;
18253 	}
18254 
18255 	if (tcp->tcp_cork) {
18256 		/*
18257 		 * if the tcp->tcp_cork option is set, then we have to force
18258 		 * TCP not to send partial segment (smaller than MSS bytes).
18259 		 * We are calculating the usable now based on full mss and
18260 		 * will save the rest of remaining data for later.
18261 		 */
18262 		if (usable < mss)
18263 			goto done;
18264 		usable = (usable / mss) * mss;
18265 	}
18266 
18267 	/* Update the latest receive window size in TCP header. */
18268 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18269 	    tcp->tcp_tcph->th_win);
18270 
18271 	/*
18272 	 * Determine if it's worthwhile to attempt MDT, based on:
18273 	 *
18274 	 * 1. Simple TCP/IP{v4,v6} (no options).
18275 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18276 	 * 3. If the TCP connection is in ESTABLISHED state.
18277 	 * 4. The TCP is not detached.
18278 	 *
18279 	 * If any of the above conditions have changed during the
18280 	 * connection, stop using MDT and restore the stream head
18281 	 * parameters accordingly.
18282 	 */
18283 	if (tcp->tcp_mdt &&
18284 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
18285 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
18286 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18287 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
18288 	    tcp->tcp_state != TCPS_ESTABLISHED ||
18289 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
18290 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
18291 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
18292 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
18293 		tcp->tcp_mdt = B_FALSE;
18294 
18295 		/* Anything other than detached is considered pathological */
18296 		if (!TCP_IS_DETACHED(tcp)) {
18297 			TCP_STAT(tcp_mdt_conn_halted1);
18298 			(void) tcp_maxpsz_set(tcp, B_TRUE);
18299 		}
18300 	}
18301 
18302 	/* Use MDT if sendable amount is greater than the threshold */
18303 	if (tcp->tcp_mdt &&
18304 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
18305 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
18306 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
18307 	    (tcp->tcp_valid_bits == 0 ||
18308 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
18309 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
18310 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18311 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18312 		    local_time, mdt_thres);
18313 	} else {
18314 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18315 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18316 		    local_time, INT_MAX);
18317 	}
18318 
18319 	/* Pretend that all we were trying to send really got sent */
18320 	if (rc < 0 && tail_unsent < 0) {
18321 		do {
18322 			xmit_tail = xmit_tail->b_cont;
18323 			xmit_tail->b_prev = local_time;
18324 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
18325 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
18326 			tail_unsent += (int)(xmit_tail->b_wptr -
18327 			    xmit_tail->b_rptr);
18328 		} while (tail_unsent < 0);
18329 	}
18330 done:;
18331 	tcp->tcp_xmit_tail = xmit_tail;
18332 	tcp->tcp_xmit_tail_unsent = tail_unsent;
18333 	len = tcp->tcp_snxt - snxt;
18334 	if (len) {
18335 		/*
18336 		 * If new data was sent, need to update the notsack
18337 		 * list, which is, afterall, data blocks that have
18338 		 * not been sack'ed by the receiver.  New data is
18339 		 * not sack'ed.
18340 		 */
18341 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
18342 			/* len is a negative value. */
18343 			tcp->tcp_pipe -= len;
18344 			tcp_notsack_update(&(tcp->tcp_notsack_list),
18345 			    tcp->tcp_snxt, snxt,
18346 			    &(tcp->tcp_num_notsack_blk),
18347 			    &(tcp->tcp_cnt_notsack_list));
18348 		}
18349 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
18350 		tcp->tcp_rack = tcp->tcp_rnxt;
18351 		tcp->tcp_rack_cnt = 0;
18352 		if ((snxt + len) == tcp->tcp_suna) {
18353 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18354 		}
18355 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
18356 		/*
18357 		 * Didn't send anything. Make sure the timer is running
18358 		 * so that we will probe a zero window.
18359 		 */
18360 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18361 	}
18362 	/* Note that len is the amount we just sent but with a negative sign */
18363 	tcp->tcp_unsent += len;
18364 	if (tcp->tcp_flow_stopped) {
18365 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18366 			tcp_clrqfull(tcp);
18367 		}
18368 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
18369 		tcp_setqfull(tcp);
18370 	}
18371 }
18372 
18373 /*
18374  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
18375  * outgoing TCP header with the template header, as well as other
18376  * options such as time-stamp, ECN and/or SACK.
18377  */
18378 static void
18379 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
18380 {
18381 	tcph_t *tcp_tmpl, *tcp_h;
18382 	uint32_t *dst, *src;
18383 	int hdrlen;
18384 
18385 	ASSERT(OK_32PTR(rptr));
18386 
18387 	/* Template header */
18388 	tcp_tmpl = tcp->tcp_tcph;
18389 
18390 	/* Header of outgoing packet */
18391 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18392 
18393 	/* dst and src are opaque 32-bit fields, used for copying */
18394 	dst = (uint32_t *)rptr;
18395 	src = (uint32_t *)tcp->tcp_iphc;
18396 	hdrlen = tcp->tcp_hdr_len;
18397 
18398 	/* Fill time-stamp option if needed */
18399 	if (tcp->tcp_snd_ts_ok) {
18400 		U32_TO_BE32((uint32_t)now,
18401 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
18402 		U32_TO_BE32(tcp->tcp_ts_recent,
18403 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
18404 	} else {
18405 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18406 	}
18407 
18408 	/*
18409 	 * Copy the template header; is this really more efficient than
18410 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
18411 	 * but perhaps not for other scenarios.
18412 	 */
18413 	dst[0] = src[0];
18414 	dst[1] = src[1];
18415 	dst[2] = src[2];
18416 	dst[3] = src[3];
18417 	dst[4] = src[4];
18418 	dst[5] = src[5];
18419 	dst[6] = src[6];
18420 	dst[7] = src[7];
18421 	dst[8] = src[8];
18422 	dst[9] = src[9];
18423 	if (hdrlen -= 40) {
18424 		hdrlen >>= 2;
18425 		dst += 10;
18426 		src += 10;
18427 		do {
18428 			*dst++ = *src++;
18429 		} while (--hdrlen);
18430 	}
18431 
18432 	/*
18433 	 * Set the ECN info in the TCP header if it is not a zero
18434 	 * window probe.  Zero window probe is only sent in
18435 	 * tcp_wput_data() and tcp_timer().
18436 	 */
18437 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
18438 		SET_ECT(tcp, rptr);
18439 
18440 		if (tcp->tcp_ecn_echo_on)
18441 			tcp_h->th_flags[0] |= TH_ECE;
18442 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18443 			tcp_h->th_flags[0] |= TH_CWR;
18444 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18445 		}
18446 	}
18447 
18448 	/* Fill in SACK options */
18449 	if (num_sack_blk > 0) {
18450 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
18451 		sack_blk_t *tmp;
18452 		int32_t	i;
18453 
18454 		wptr[0] = TCPOPT_NOP;
18455 		wptr[1] = TCPOPT_NOP;
18456 		wptr[2] = TCPOPT_SACK;
18457 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18458 		    sizeof (sack_blk_t);
18459 		wptr += TCPOPT_REAL_SACK_LEN;
18460 
18461 		tmp = tcp->tcp_sack_list;
18462 		for (i = 0; i < num_sack_blk; i++) {
18463 			U32_TO_BE32(tmp[i].begin, wptr);
18464 			wptr += sizeof (tcp_seq);
18465 			U32_TO_BE32(tmp[i].end, wptr);
18466 			wptr += sizeof (tcp_seq);
18467 		}
18468 		tcp_h->th_offset_and_rsrvd[0] +=
18469 		    ((num_sack_blk * 2 + 1) << 4);
18470 	}
18471 }
18472 
18473 /*
18474  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
18475  * the destination address and SAP attribute, and if necessary, the
18476  * hardware checksum offload attribute to a Multidata message.
18477  */
18478 static int
18479 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
18480     const uint32_t start, const uint32_t stuff, const uint32_t end,
18481     const uint32_t flags)
18482 {
18483 	/* Add global destination address & SAP attribute */
18484 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
18485 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
18486 		    "destination address+SAP\n"));
18487 
18488 		if (dlmp != NULL)
18489 			TCP_STAT(tcp_mdt_allocfail);
18490 		return (-1);
18491 	}
18492 
18493 	/* Add global hwcksum attribute */
18494 	if (hwcksum &&
18495 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
18496 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
18497 		    "checksum attribute\n"));
18498 
18499 		TCP_STAT(tcp_mdt_allocfail);
18500 		return (-1);
18501 	}
18502 
18503 	return (0);
18504 }
18505 
18506 /*
18507  * Smaller and private version of pdescinfo_t used specifically for TCP,
18508  * which allows for only two payload spans per packet.
18509  */
18510 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
18511 
18512 /*
18513  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
18514  * scheme, and returns one the following:
18515  *
18516  * -1 = failed allocation.
18517  *  0 = success; burst count reached, or usable send window is too small,
18518  *      and that we'd rather wait until later before sending again.
18519  */
18520 static int
18521 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
18522     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
18523     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
18524     const int mdt_thres)
18525 {
18526 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
18527 	multidata_t	*mmd;
18528 	uint_t		obsegs, obbytes, hdr_frag_sz;
18529 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
18530 	int		num_burst_seg, max_pld;
18531 	pdesc_t		*pkt;
18532 	tcp_pdescinfo_t	tcp_pkt_info;
18533 	pdescinfo_t	*pkt_info;
18534 	int		pbuf_idx, pbuf_idx_nxt;
18535 	int		seg_len, len, spill, af;
18536 	boolean_t	add_buffer, zcopy, clusterwide;
18537 	boolean_t	rconfirm = B_FALSE;
18538 	boolean_t	done = B_FALSE;
18539 	uint32_t	cksum;
18540 	uint32_t	hwcksum_flags;
18541 	ire_t		*ire;
18542 	ill_t		*ill;
18543 	ipha_t		*ipha;
18544 	ip6_t		*ip6h;
18545 	ipaddr_t	src, dst;
18546 	ill_zerocopy_capab_t *zc_cap = NULL;
18547 	uint16_t	*up;
18548 	int		err;
18549 
18550 #ifdef	_BIG_ENDIAN
18551 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
18552 #else
18553 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
18554 #endif
18555 
18556 #define	PREP_NEW_MULTIDATA() {			\
18557 	mmd = NULL;				\
18558 	md_mp = md_hbuf = NULL;			\
18559 	cur_hdr_off = 0;			\
18560 	max_pld = tcp->tcp_mdt_max_pld;		\
18561 	pbuf_idx = pbuf_idx_nxt = -1;		\
18562 	add_buffer = B_TRUE;			\
18563 	zcopy = B_FALSE;			\
18564 }
18565 
18566 #define	PREP_NEW_PBUF() {			\
18567 	md_pbuf = md_pbuf_nxt = NULL;		\
18568 	pbuf_idx = pbuf_idx_nxt = -1;		\
18569 	cur_pld_off = 0;			\
18570 	first_snxt = *snxt;			\
18571 	ASSERT(*tail_unsent > 0);		\
18572 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
18573 }
18574 
18575 	ASSERT(mdt_thres >= mss);
18576 	ASSERT(*usable > 0 && *usable > mdt_thres);
18577 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
18578 	ASSERT(!TCP_IS_DETACHED(tcp));
18579 	ASSERT(tcp->tcp_valid_bits == 0 ||
18580 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
18581 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
18582 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
18583 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18584 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
18585 	ASSERT(tcp->tcp_connp != NULL);
18586 	ASSERT(CONN_IS_MD_FASTPATH(tcp->tcp_connp));
18587 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp));
18588 
18589 	/*
18590 	 * Note that tcp will only declare at most 2 payload spans per
18591 	 * packet, which is much lower than the maximum allowable number
18592 	 * of packet spans per Multidata.  For this reason, we use the
18593 	 * privately declared and smaller descriptor info structure, in
18594 	 * order to save some stack space.
18595 	 */
18596 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
18597 
18598 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
18599 	if (af == AF_INET) {
18600 		dst = tcp->tcp_ipha->ipha_dst;
18601 		src = tcp->tcp_ipha->ipha_src;
18602 		ASSERT(!CLASSD(dst));
18603 	}
18604 	ASSERT(af == AF_INET ||
18605 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
18606 
18607 	obsegs = obbytes = 0;
18608 	num_burst_seg = tcp->tcp_snd_burst;
18609 	md_mp_head = NULL;
18610 	PREP_NEW_MULTIDATA();
18611 
18612 	/*
18613 	 * Before we go on further, make sure there is an IRE that we can
18614 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
18615 	 * in proceeding any further, and we should just hand everything
18616 	 * off to the legacy path.
18617 	 */
18618 	mutex_enter(&tcp->tcp_connp->conn_lock);
18619 	ire = tcp->tcp_connp->conn_ire_cache;
18620 	ASSERT(!(tcp->tcp_connp->conn_state_flags & CONN_INCIPIENT));
18621 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
18622 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
18623 	    &tcp->tcp_ip6h->ip6_dst))) &&
18624 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18625 		IRE_REFHOLD(ire);
18626 		mutex_exit(&tcp->tcp_connp->conn_lock);
18627 	} else {
18628 		boolean_t cached = B_FALSE;
18629 
18630 		/* force a recheck later on */
18631 		tcp->tcp_ire_ill_check_done = B_FALSE;
18632 
18633 		TCP_DBGSTAT(tcp_ire_null1);
18634 		tcp->tcp_connp->conn_ire_cache = NULL;
18635 		mutex_exit(&tcp->tcp_connp->conn_lock);
18636 
18637 		/* Release the old ire */
18638 		if (ire != NULL)
18639 			IRE_REFRELE_NOTR(ire);
18640 
18641 		ire = (af == AF_INET) ?
18642 		    ire_cache_lookup(dst, tcp->tcp_connp->conn_zoneid) :
18643 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18644 		    tcp->tcp_connp->conn_zoneid);
18645 
18646 		if (ire == NULL) {
18647 			TCP_STAT(tcp_ire_null);
18648 			goto legacy_send_no_md;
18649 		}
18650 
18651 		IRE_REFHOLD_NOTR(ire);
18652 		/*
18653 		 * Since we are inside the squeue, there cannot be another
18654 		 * thread in TCP trying to set the conn_ire_cache now. The
18655 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18656 		 * unplumb thread has not yet started cleaning up the conns.
18657 		 * Hence we don't need to grab the conn lock.
18658 		 */
18659 		if (!(tcp->tcp_connp->conn_state_flags & CONN_CLOSING)) {
18660 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18661 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18662 				tcp->tcp_connp->conn_ire_cache = ire;
18663 				cached = B_TRUE;
18664 			}
18665 			rw_exit(&ire->ire_bucket->irb_lock);
18666 		}
18667 
18668 		/*
18669 		 * We can continue to use the ire but since it was not
18670 		 * cached, we should drop the extra reference.
18671 		 */
18672 		if (!cached)
18673 			IRE_REFRELE_NOTR(ire);
18674 	}
18675 
18676 	ASSERT(ire != NULL);
18677 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
18678 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
18679 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
18680 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18681 	/*
18682 	 * If we do support loopback for MDT (which requires modifications
18683 	 * to the receiving paths), the following assertions should go away,
18684 	 * and we would be sending the Multidata to loopback conn later on.
18685 	 */
18686 	ASSERT(!IRE_IS_LOCAL(ire));
18687 	ASSERT(ire->ire_stq != NULL);
18688 
18689 	ill = ire_to_ill(ire);
18690 	ASSERT(ill != NULL);
18691 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
18692 
18693 	if (!tcp->tcp_ire_ill_check_done) {
18694 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18695 		tcp->tcp_ire_ill_check_done = B_TRUE;
18696 	}
18697 
18698 	/*
18699 	 * If the underlying interface conditions have changed, or if the
18700 	 * new interface does not support MDT, go back to legacy path.
18701 	 */
18702 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
18703 		/* don't go through this path anymore for this connection */
18704 		TCP_STAT(tcp_mdt_conn_halted2);
18705 		tcp->tcp_mdt = B_FALSE;
18706 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
18707 		    "interface %s\n", (void *)tcp->tcp_connp, ill->ill_name));
18708 		/* IRE will be released prior to returning */
18709 		goto legacy_send_no_md;
18710 	}
18711 
18712 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
18713 		zc_cap = ill->ill_zerocopy_capab;
18714 
18715 	/* go to legacy path if interface doesn't support zerocopy */
18716 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
18717 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
18718 		/* IRE will be released prior to returning */
18719 		goto legacy_send_no_md;
18720 	}
18721 
18722 	/* does the interface support hardware checksum offload? */
18723 	hwcksum_flags = 0;
18724 	if (ILL_HCKSUM_CAPABLE(ill) &&
18725 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
18726 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
18727 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
18728 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18729 		    HCKSUM_IPHDRCKSUM)
18730 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
18731 
18732 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18733 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
18734 			hwcksum_flags |= HCK_FULLCKSUM;
18735 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18736 		    HCKSUM_INET_PARTIAL)
18737 			hwcksum_flags |= HCK_PARTIALCKSUM;
18738 	}
18739 
18740 	/*
18741 	 * Each header fragment consists of the leading extra space,
18742 	 * followed by the TCP/IP header, and the trailing extra space.
18743 	 * We make sure that each header fragment begins on a 32-bit
18744 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
18745 	 * aligned in tcp_mdt_update).
18746 	 */
18747 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
18748 	    tcp->tcp_mdt_hdr_tail), 4);
18749 
18750 	/* are we starting from the beginning of data block? */
18751 	if (*tail_unsent == 0) {
18752 		*xmit_tail = (*xmit_tail)->b_cont;
18753 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
18754 		*tail_unsent = (int)MBLKL(*xmit_tail);
18755 	}
18756 
18757 	/*
18758 	 * Here we create one or more Multidata messages, each made up of
18759 	 * one header buffer and up to N payload buffers.  This entire
18760 	 * operation is done within two loops:
18761 	 *
18762 	 * The outer loop mostly deals with creating the Multidata message,
18763 	 * as well as the header buffer that gets added to it.  It also
18764 	 * links the Multidata messages together such that all of them can
18765 	 * be sent down to the lower layer in a single putnext call; this
18766 	 * linking behavior depends on the tcp_mdt_chain tunable.
18767 	 *
18768 	 * The inner loop takes an existing Multidata message, and adds
18769 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
18770 	 * packetizes those buffers by filling up the corresponding header
18771 	 * buffer fragments with the proper IP and TCP headers, and by
18772 	 * describing the layout of each packet in the packet descriptors
18773 	 * that get added to the Multidata.
18774 	 */
18775 	do {
18776 		/*
18777 		 * If usable send window is too small, or data blocks in
18778 		 * transmit list are smaller than our threshold (i.e. app
18779 		 * performs large writes followed by small ones), we hand
18780 		 * off the control over to the legacy path.  Note that we'll
18781 		 * get back the control once it encounters a large block.
18782 		 */
18783 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
18784 		    (*xmit_tail)->b_cont != NULL &&
18785 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
18786 			/* send down what we've got so far */
18787 			if (md_mp_head != NULL) {
18788 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
18789 				    obsegs, obbytes, &rconfirm);
18790 			}
18791 			/*
18792 			 * Pass control over to tcp_send(), but tell it to
18793 			 * return to us once a large-size transmission is
18794 			 * possible.
18795 			 */
18796 			TCP_STAT(tcp_mdt_legacy_small);
18797 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
18798 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
18799 			    tail_unsent, xmit_tail, local_time,
18800 			    mdt_thres)) <= 0) {
18801 				/* burst count reached, or alloc failed */
18802 				IRE_REFRELE(ire);
18803 				return (err);
18804 			}
18805 
18806 			/* tcp_send() may have sent everything, so check */
18807 			if (*usable <= 0) {
18808 				IRE_REFRELE(ire);
18809 				return (0);
18810 			}
18811 
18812 			TCP_STAT(tcp_mdt_legacy_ret);
18813 			/*
18814 			 * We may have delivered the Multidata, so make sure
18815 			 * to re-initialize before the next round.
18816 			 */
18817 			md_mp_head = NULL;
18818 			obsegs = obbytes = 0;
18819 			num_burst_seg = tcp->tcp_snd_burst;
18820 			PREP_NEW_MULTIDATA();
18821 
18822 			/* are we starting from the beginning of data block? */
18823 			if (*tail_unsent == 0) {
18824 				*xmit_tail = (*xmit_tail)->b_cont;
18825 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
18826 				    (uintptr_t)INT_MAX);
18827 				*tail_unsent = (int)MBLKL(*xmit_tail);
18828 			}
18829 		}
18830 
18831 		/*
18832 		 * max_pld limits the number of mblks in tcp's transmit
18833 		 * queue that can be added to a Multidata message.  Once
18834 		 * this counter reaches zero, no more additional mblks
18835 		 * can be added to it.  What happens afterwards depends
18836 		 * on whether or not we are set to chain the Multidata
18837 		 * messages.  If we are to link them together, reset
18838 		 * max_pld to its original value (tcp_mdt_max_pld) and
18839 		 * prepare to create a new Multidata message which will
18840 		 * get linked to md_mp_head.  Else, leave it alone and
18841 		 * let the inner loop break on its own.
18842 		 */
18843 		if (tcp_mdt_chain && max_pld == 0)
18844 			PREP_NEW_MULTIDATA();
18845 
18846 		/* adding a payload buffer; re-initialize values */
18847 		if (add_buffer)
18848 			PREP_NEW_PBUF();
18849 
18850 		/*
18851 		 * If we don't have a Multidata, either because we just
18852 		 * (re)entered this outer loop, or after we branched off
18853 		 * to tcp_send above, setup the Multidata and header
18854 		 * buffer to be used.
18855 		 */
18856 		if (md_mp == NULL) {
18857 			int md_hbuflen;
18858 			uint32_t start, stuff;
18859 
18860 			/*
18861 			 * Calculate Multidata header buffer size large enough
18862 			 * to hold all of the headers that can possibly be
18863 			 * sent at this moment.  We'd rather over-estimate
18864 			 * the size than running out of space; this is okay
18865 			 * since this buffer is small anyway.
18866 			 */
18867 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
18868 
18869 			/*
18870 			 * Start and stuff offset for partial hardware
18871 			 * checksum offload; these are currently for IPv4.
18872 			 * For full checksum offload, they are set to zero.
18873 			 */
18874 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
18875 				if (af == AF_INET) {
18876 					start = IP_SIMPLE_HDR_LENGTH;
18877 					stuff = IP_SIMPLE_HDR_LENGTH +
18878 					    TCP_CHECKSUM_OFFSET;
18879 				} else {
18880 					start = IPV6_HDR_LEN;
18881 					stuff = IPV6_HDR_LEN +
18882 					    TCP_CHECKSUM_OFFSET;
18883 				}
18884 			} else {
18885 				start = stuff = 0;
18886 			}
18887 
18888 			/*
18889 			 * Create the header buffer, Multidata, as well as
18890 			 * any necessary attributes (destination address,
18891 			 * SAP and hardware checksum offload) that should
18892 			 * be associated with the Multidata message.
18893 			 */
18894 			ASSERT(cur_hdr_off == 0);
18895 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
18896 			    ((md_hbuf->b_wptr += md_hbuflen),
18897 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
18898 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
18899 			    /* fastpath mblk */
18900 			    (af == AF_INET) ? ire->ire_dlureq_mp :
18901 			    ire->ire_nce->nce_res_mp,
18902 			    /* hardware checksum enabled */
18903 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
18904 			    /* hardware checksum offsets */
18905 			    start, stuff, 0,
18906 			    /* hardware checksum flag */
18907 			    hwcksum_flags) != 0)) {
18908 legacy_send:
18909 				if (md_mp != NULL) {
18910 					/* Unlink message from the chain */
18911 					if (md_mp_head != NULL) {
18912 						err = (intptr_t)rmvb(md_mp_head,
18913 						    md_mp);
18914 						/*
18915 						 * We can't assert that rmvb
18916 						 * did not return -1, since we
18917 						 * may get here before linkb
18918 						 * happens.  We do, however,
18919 						 * check if we just removed the
18920 						 * only element in the list.
18921 						 */
18922 						if (err == 0)
18923 							md_mp_head = NULL;
18924 					}
18925 					/* md_hbuf gets freed automatically */
18926 					TCP_STAT(tcp_mdt_discarded);
18927 					freeb(md_mp);
18928 				} else {
18929 					/* Either allocb or mmd_alloc failed */
18930 					TCP_STAT(tcp_mdt_allocfail);
18931 					if (md_hbuf != NULL)
18932 						freeb(md_hbuf);
18933 				}
18934 
18935 				/* send down what we've got so far */
18936 				if (md_mp_head != NULL) {
18937 					tcp_multisend_data(tcp, ire, ill,
18938 					    md_mp_head, obsegs, obbytes,
18939 					    &rconfirm);
18940 				}
18941 legacy_send_no_md:
18942 				if (ire != NULL)
18943 					IRE_REFRELE(ire);
18944 				/*
18945 				 * Too bad; let the legacy path handle this.
18946 				 * We specify INT_MAX for the threshold, since
18947 				 * we gave up with the Multidata processings
18948 				 * and let the old path have it all.
18949 				 */
18950 				TCP_STAT(tcp_mdt_legacy_all);
18951 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
18952 				    tcp_tcp_hdr_len, num_sack_blk, usable,
18953 				    snxt, tail_unsent, xmit_tail, local_time,
18954 				    INT_MAX));
18955 			}
18956 
18957 			/* link to any existing ones, if applicable */
18958 			TCP_STAT(tcp_mdt_allocd);
18959 			if (md_mp_head == NULL) {
18960 				md_mp_head = md_mp;
18961 			} else if (tcp_mdt_chain) {
18962 				TCP_STAT(tcp_mdt_linked);
18963 				linkb(md_mp_head, md_mp);
18964 			}
18965 		}
18966 
18967 		ASSERT(md_mp_head != NULL);
18968 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
18969 		ASSERT(md_mp != NULL && mmd != NULL);
18970 		ASSERT(md_hbuf != NULL);
18971 
18972 		/*
18973 		 * Packetize the transmittable portion of the data block;
18974 		 * each data block is essentially added to the Multidata
18975 		 * as a payload buffer.  We also deal with adding more
18976 		 * than one payload buffers, which happens when the remaining
18977 		 * packetized portion of the current payload buffer is less
18978 		 * than MSS, while the next data block in transmit queue
18979 		 * has enough data to make up for one.  This "spillover"
18980 		 * case essentially creates a split-packet, where portions
18981 		 * of the packet's payload fragments may span across two
18982 		 * virtually discontiguous address blocks.
18983 		 */
18984 		seg_len = mss;
18985 		do {
18986 			len = seg_len;
18987 
18988 			ASSERT(len > 0);
18989 			ASSERT(max_pld >= 0);
18990 			ASSERT(!add_buffer || cur_pld_off == 0);
18991 
18992 			/*
18993 			 * First time around for this payload buffer; note
18994 			 * in the case of a spillover, the following has
18995 			 * been done prior to adding the split-packet
18996 			 * descriptor to Multidata, and we don't want to
18997 			 * repeat the process.
18998 			 */
18999 			if (add_buffer) {
19000 				ASSERT(mmd != NULL);
19001 				ASSERT(md_pbuf == NULL);
19002 				ASSERT(md_pbuf_nxt == NULL);
19003 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19004 
19005 				/*
19006 				 * Have we reached the limit?  We'd get to
19007 				 * this case when we're not chaining the
19008 				 * Multidata messages together, and since
19009 				 * we're done, terminate this loop.
19010 				 */
19011 				if (max_pld == 0)
19012 					break; /* done */
19013 
19014 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19015 					TCP_STAT(tcp_mdt_allocfail);
19016 					goto legacy_send; /* out_of_mem */
19017 				}
19018 
19019 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19020 				    zc_cap != NULL) {
19021 					if (!ip_md_zcopy_attr(mmd, NULL,
19022 					    zc_cap->ill_zerocopy_flags)) {
19023 						freeb(md_pbuf);
19024 						TCP_STAT(tcp_mdt_allocfail);
19025 						/* out_of_mem */
19026 						goto legacy_send;
19027 					}
19028 					zcopy = B_TRUE;
19029 				}
19030 
19031 				md_pbuf->b_rptr += base_pld_off;
19032 
19033 				/*
19034 				 * Add a payload buffer to the Multidata; this
19035 				 * operation must not fail, or otherwise our
19036 				 * logic in this routine is broken.  There
19037 				 * is no memory allocation done by the
19038 				 * routine, so any returned failure simply
19039 				 * tells us that we've done something wrong.
19040 				 *
19041 				 * A failure tells us that either we're adding
19042 				 * the same payload buffer more than once, or
19043 				 * we're trying to add more buffers than
19044 				 * allowed (max_pld calculation is wrong).
19045 				 * None of the above cases should happen, and
19046 				 * we panic because either there's horrible
19047 				 * heap corruption, and/or programming mistake.
19048 				 */
19049 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19050 				if (pbuf_idx < 0) {
19051 					cmn_err(CE_PANIC, "tcp_multisend: "
19052 					    "payload buffer logic error "
19053 					    "detected for tcp %p mmd %p "
19054 					    "pbuf %p (%d)\n",
19055 					    (void *)tcp, (void *)mmd,
19056 					    (void *)md_pbuf, pbuf_idx);
19057 				}
19058 
19059 				ASSERT(max_pld > 0);
19060 				--max_pld;
19061 				add_buffer = B_FALSE;
19062 			}
19063 
19064 			ASSERT(md_mp_head != NULL);
19065 			ASSERT(md_pbuf != NULL);
19066 			ASSERT(md_pbuf_nxt == NULL);
19067 			ASSERT(pbuf_idx != -1);
19068 			ASSERT(pbuf_idx_nxt == -1);
19069 			ASSERT(*usable > 0);
19070 
19071 			/*
19072 			 * We spillover to the next payload buffer only
19073 			 * if all of the following is true:
19074 			 *
19075 			 *   1. There is not enough data on the current
19076 			 *	payload buffer to make up `len',
19077 			 *   2. We are allowed to send `len',
19078 			 *   3. The next payload buffer length is large
19079 			 *	enough to accomodate `spill'.
19080 			 */
19081 			if ((spill = len - *tail_unsent) > 0 &&
19082 			    *usable >= len &&
19083 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19084 			    max_pld > 0) {
19085 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19086 				if (md_pbuf_nxt == NULL) {
19087 					TCP_STAT(tcp_mdt_allocfail);
19088 					goto legacy_send; /* out_of_mem */
19089 				}
19090 
19091 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19092 				    zc_cap != NULL) {
19093 					if (!ip_md_zcopy_attr(mmd, NULL,
19094 					    zc_cap->ill_zerocopy_flags)) {
19095 						freeb(md_pbuf_nxt);
19096 						TCP_STAT(tcp_mdt_allocfail);
19097 						/* out_of_mem */
19098 						goto legacy_send;
19099 					}
19100 					zcopy = B_TRUE;
19101 				}
19102 
19103 				/*
19104 				 * See comments above on the first call to
19105 				 * mmd_addpldbuf for explanation on the panic.
19106 				 */
19107 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19108 				if (pbuf_idx_nxt < 0) {
19109 					panic("tcp_multisend: "
19110 					    "next payload buffer logic error "
19111 					    "detected for tcp %p mmd %p "
19112 					    "pbuf %p (%d)\n",
19113 					    (void *)tcp, (void *)mmd,
19114 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19115 				}
19116 
19117 				ASSERT(max_pld > 0);
19118 				--max_pld;
19119 			} else if (spill > 0) {
19120 				/*
19121 				 * If there's a spillover, but the following
19122 				 * xmit_tail couldn't give us enough octets
19123 				 * to reach "len", then stop the current
19124 				 * Multidata creation and let the legacy
19125 				 * tcp_send() path take over.  We don't want
19126 				 * to send the tiny segment as part of this
19127 				 * Multidata for performance reasons; instead,
19128 				 * we let the legacy path deal with grouping
19129 				 * it with the subsequent small mblks.
19130 				 */
19131 				if (*usable >= len &&
19132 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19133 					max_pld = 0;
19134 					break;	/* done */
19135 				}
19136 
19137 				/*
19138 				 * We can't spillover, and we are near
19139 				 * the end of the current payload buffer,
19140 				 * so send what's left.
19141 				 */
19142 				ASSERT(*tail_unsent > 0);
19143 				len = *tail_unsent;
19144 			}
19145 
19146 			/* tail_unsent is negated if there is a spillover */
19147 			*tail_unsent -= len;
19148 			*usable -= len;
19149 			ASSERT(*usable >= 0);
19150 
19151 			if (*usable < mss)
19152 				seg_len = *usable;
19153 			/*
19154 			 * Sender SWS avoidance; see comments in tcp_send();
19155 			 * everything else is the same, except that we only
19156 			 * do this here if there is no more data to be sent
19157 			 * following the current xmit_tail.  We don't check
19158 			 * for 1-byte urgent data because we shouldn't get
19159 			 * here if TCP_URG_VALID is set.
19160 			 */
19161 			if (*usable > 0 && *usable < mss &&
19162 			    ((md_pbuf_nxt == NULL &&
19163 			    (*xmit_tail)->b_cont == NULL) ||
19164 			    (md_pbuf_nxt != NULL &&
19165 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19166 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19167 			    (tcp->tcp_unsent -
19168 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19169 			    !tcp->tcp_zero_win_probe) {
19170 				if ((*snxt + len) == tcp->tcp_snxt &&
19171 				    (*snxt + len) == tcp->tcp_suna) {
19172 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19173 				}
19174 				done = B_TRUE;
19175 			}
19176 
19177 			/*
19178 			 * Prime pump for IP's checksumming on our behalf;
19179 			 * include the adjustment for a source route if any.
19180 			 * Do this only for software/partial hardware checksum
19181 			 * offload, as this field gets zeroed out later for
19182 			 * the full hardware checksum offload case.
19183 			 */
19184 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19185 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19186 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19187 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19188 			}
19189 
19190 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19191 			*snxt += len;
19192 
19193 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19194 			/*
19195 			 * We set the PUSH bit only if TCP has no more buffered
19196 			 * data to be transmitted (or if sender SWS avoidance
19197 			 * takes place), as opposed to setting it for every
19198 			 * last packet in the burst.
19199 			 */
19200 			if (done ||
19201 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19202 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19203 
19204 			/*
19205 			 * Set FIN bit if this is our last segment; snxt
19206 			 * already includes its length, and it will not
19207 			 * be adjusted after this point.
19208 			 */
19209 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19210 			    *snxt == tcp->tcp_fss) {
19211 				if (!tcp->tcp_fin_acked) {
19212 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19213 					BUMP_MIB(&tcp_mib, tcpOutControl);
19214 				}
19215 				if (!tcp->tcp_fin_sent) {
19216 					tcp->tcp_fin_sent = B_TRUE;
19217 					/*
19218 					 * tcp state must be ESTABLISHED
19219 					 * in order for us to get here in
19220 					 * the first place.
19221 					 */
19222 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19223 
19224 					/*
19225 					 * Upon returning from this routine,
19226 					 * tcp_wput_data() will set tcp_snxt
19227 					 * to be equal to snxt + tcp_fin_sent.
19228 					 * This is essentially the same as
19229 					 * setting it to tcp_fss + 1.
19230 					 */
19231 				}
19232 			}
19233 
19234 			tcp->tcp_last_sent_len = (ushort_t)len;
19235 
19236 			len += tcp_hdr_len;
19237 			if (tcp->tcp_ipversion == IPV4_VERSION)
19238 				tcp->tcp_ipha->ipha_length = htons(len);
19239 			else
19240 				tcp->tcp_ip6h->ip6_plen = htons(len -
19241 				    ((char *)&tcp->tcp_ip6h[1] -
19242 				    tcp->tcp_iphc));
19243 
19244 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19245 
19246 			/* setup header fragment */
19247 			PDESC_HDR_ADD(pkt_info,
19248 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19249 			    tcp->tcp_mdt_hdr_head,		/* head room */
19250 			    tcp_hdr_len,			/* len */
19251 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19252 
19253 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
19254 			    hdr_frag_sz);
19255 			ASSERT(MBLKIN(md_hbuf,
19256 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
19257 			    PDESC_HDRSIZE(pkt_info)));
19258 
19259 			/* setup first payload fragment */
19260 			PDESC_PLD_INIT(pkt_info);
19261 			PDESC_PLD_SPAN_ADD(pkt_info,
19262 			    pbuf_idx,				/* index */
19263 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
19264 			    tcp->tcp_last_sent_len);		/* len */
19265 
19266 			/* create a split-packet in case of a spillover */
19267 			if (md_pbuf_nxt != NULL) {
19268 				ASSERT(spill > 0);
19269 				ASSERT(pbuf_idx_nxt > pbuf_idx);
19270 				ASSERT(!add_buffer);
19271 
19272 				md_pbuf = md_pbuf_nxt;
19273 				md_pbuf_nxt = NULL;
19274 				pbuf_idx = pbuf_idx_nxt;
19275 				pbuf_idx_nxt = -1;
19276 				cur_pld_off = spill;
19277 
19278 				/* trim out first payload fragment */
19279 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
19280 
19281 				/* setup second payload fragment */
19282 				PDESC_PLD_SPAN_ADD(pkt_info,
19283 				    pbuf_idx,			/* index */
19284 				    md_pbuf->b_rptr,		/* start */
19285 				    spill);			/* len */
19286 
19287 				if ((*xmit_tail)->b_next == NULL) {
19288 					/*
19289 					 * Store the lbolt used for RTT
19290 					 * estimation. We can only record one
19291 					 * timestamp per mblk so we do it when
19292 					 * we reach the end of the payload
19293 					 * buffer.  Also we only take a new
19294 					 * timestamp sample when the previous
19295 					 * timed data from the same mblk has
19296 					 * been ack'ed.
19297 					 */
19298 					(*xmit_tail)->b_prev = local_time;
19299 					(*xmit_tail)->b_next =
19300 					    (mblk_t *)(uintptr_t)first_snxt;
19301 				}
19302 
19303 				first_snxt = *snxt - spill;
19304 
19305 				/*
19306 				 * Advance xmit_tail; usable could be 0 by
19307 				 * the time we got here, but we made sure
19308 				 * above that we would only spillover to
19309 				 * the next data block if usable includes
19310 				 * the spilled-over amount prior to the
19311 				 * subtraction.  Therefore, we are sure
19312 				 * that xmit_tail->b_cont can't be NULL.
19313 				 */
19314 				ASSERT((*xmit_tail)->b_cont != NULL);
19315 				*xmit_tail = (*xmit_tail)->b_cont;
19316 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19317 				    (uintptr_t)INT_MAX);
19318 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
19319 			} else {
19320 				cur_pld_off += tcp->tcp_last_sent_len;
19321 			}
19322 
19323 			/*
19324 			 * Fill in the header using the template header, and
19325 			 * add options such as time-stamp, ECN and/or SACK,
19326 			 * as needed.
19327 			 */
19328 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
19329 			    (clock_t)local_time, num_sack_blk);
19330 
19331 			/* take care of some IP header businesses */
19332 			if (af == AF_INET) {
19333 				ipha = (ipha_t *)pkt_info->hdr_rptr;
19334 
19335 				ASSERT(OK_32PTR((uchar_t *)ipha));
19336 				ASSERT(PDESC_HDRL(pkt_info) >=
19337 				    IP_SIMPLE_HDR_LENGTH);
19338 				ASSERT(ipha->ipha_version_and_hdr_length ==
19339 				    IP_SIMPLE_HDR_VERSION);
19340 
19341 				/*
19342 				 * Assign ident value for current packet; see
19343 				 * related comments in ip_wput_ire() about the
19344 				 * contract private interface with clustering
19345 				 * group.
19346 				 */
19347 				clusterwide = B_FALSE;
19348 				if (cl_inet_ipident != NULL) {
19349 					ASSERT(cl_inet_isclusterwide != NULL);
19350 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19351 					    AF_INET,
19352 					    (uint8_t *)(uintptr_t)src)) {
19353 						ipha->ipha_ident =
19354 						    (*cl_inet_ipident)
19355 						    (IPPROTO_IP, AF_INET,
19356 						    (uint8_t *)(uintptr_t)src,
19357 						    (uint8_t *)(uintptr_t)dst);
19358 						clusterwide = B_TRUE;
19359 					}
19360 				}
19361 
19362 				if (!clusterwide) {
19363 					ipha->ipha_ident = (uint16_t)
19364 					    atomic_add_32_nv(
19365 						&ire->ire_ident, 1);
19366 				}
19367 #ifndef _BIG_ENDIAN
19368 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
19369 				    (ipha->ipha_ident >> 8);
19370 #endif
19371 			} else {
19372 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
19373 
19374 				ASSERT(OK_32PTR((uchar_t *)ip6h));
19375 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
19376 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
19377 				ASSERT(PDESC_HDRL(pkt_info) >=
19378 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
19379 				    TCP_CHECKSUM_SIZE));
19380 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
19381 
19382 				if (tcp->tcp_ip_forward_progress) {
19383 					rconfirm = B_TRUE;
19384 					tcp->tcp_ip_forward_progress = B_FALSE;
19385 				}
19386 			}
19387 
19388 			/* at least one payload span, and at most two */
19389 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
19390 
19391 			/* add the packet descriptor to Multidata */
19392 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
19393 			    KM_NOSLEEP)) == NULL) {
19394 				/*
19395 				 * Any failure other than ENOMEM indicates
19396 				 * that we have passed in invalid pkt_info
19397 				 * or parameters to mmd_addpdesc, which must
19398 				 * not happen.
19399 				 *
19400 				 * EINVAL is a result of failure on boundary
19401 				 * checks against the pkt_info contents.  It
19402 				 * should not happen, and we panic because
19403 				 * either there's horrible heap corruption,
19404 				 * and/or programming mistake.
19405 				 */
19406 				if (err != ENOMEM) {
19407 					cmn_err(CE_PANIC, "tcp_multisend: "
19408 					    "pdesc logic error detected for "
19409 					    "tcp %p mmd %p pinfo %p (%d)\n",
19410 					    (void *)tcp, (void *)mmd,
19411 					    (void *)pkt_info, err);
19412 				}
19413 				TCP_STAT(tcp_mdt_addpdescfail);
19414 				goto legacy_send; /* out_of_mem */
19415 			}
19416 			ASSERT(pkt != NULL);
19417 
19418 			/* calculate IP header and TCP checksums */
19419 			if (af == AF_INET) {
19420 				/* calculate pseudo-header checksum */
19421 				cksum = (dst >> 16) + (dst & 0xFFFF) +
19422 				    (src >> 16) + (src & 0xFFFF);
19423 
19424 				/* offset for TCP header checksum */
19425 				up = IPH_TCPH_CHECKSUMP(ipha,
19426 				    IP_SIMPLE_HDR_LENGTH);
19427 			} else {
19428 				up = (uint16_t *)&ip6h->ip6_src;
19429 
19430 				/* calculate pseudo-header checksum */
19431 				cksum = up[0] + up[1] + up[2] + up[3] +
19432 				    up[4] + up[5] + up[6] + up[7] +
19433 				    up[8] + up[9] + up[10] + up[11] +
19434 				    up[12] + up[13] + up[14] + up[15];
19435 
19436 				/* Fold the initial sum */
19437 				cksum = (cksum & 0xffff) + (cksum >> 16);
19438 
19439 				up = (uint16_t *)(((uchar_t *)ip6h) +
19440 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
19441 			}
19442 
19443 			if (hwcksum_flags & HCK_FULLCKSUM) {
19444 				/* clear checksum field for hardware */
19445 				*up = 0;
19446 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
19447 				uint32_t sum;
19448 
19449 				/* pseudo-header checksumming */
19450 				sum = *up + cksum + IP_TCP_CSUM_COMP;
19451 				sum = (sum & 0xFFFF) + (sum >> 16);
19452 				*up = (sum & 0xFFFF) + (sum >> 16);
19453 			} else {
19454 				/* software checksumming */
19455 				TCP_STAT(tcp_out_sw_cksum);
19456 				TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
19457 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
19458 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
19459 				    cksum + IP_TCP_CSUM_COMP);
19460 				if (*up == 0)
19461 					*up = 0xFFFF;
19462 			}
19463 
19464 			/* IPv4 header checksum */
19465 			if (af == AF_INET) {
19466 				ipha->ipha_fragment_offset_and_flags |=
19467 				    (uint32_t)htons(ire->ire_frag_flag);
19468 
19469 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
19470 					ipha->ipha_hdr_checksum = 0;
19471 				} else {
19472 					IP_HDR_CKSUM(ipha, cksum,
19473 					    ((uint32_t *)ipha)[0],
19474 					    ((uint16_t *)ipha)[4]);
19475 				}
19476 			}
19477 
19478 			/* advance header offset */
19479 			cur_hdr_off += hdr_frag_sz;
19480 
19481 			obbytes += tcp->tcp_last_sent_len;
19482 			++obsegs;
19483 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
19484 		    *tail_unsent > 0);
19485 
19486 		if ((*xmit_tail)->b_next == NULL) {
19487 			/*
19488 			 * Store the lbolt used for RTT estimation. We can only
19489 			 * record one timestamp per mblk so we do it when we
19490 			 * reach the end of the payload buffer. Also we only
19491 			 * take a new timestamp sample when the previous timed
19492 			 * data from the same mblk has been ack'ed.
19493 			 */
19494 			(*xmit_tail)->b_prev = local_time;
19495 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
19496 		}
19497 
19498 		ASSERT(*tail_unsent >= 0);
19499 		if (*tail_unsent > 0) {
19500 			/*
19501 			 * We got here because we broke out of the above
19502 			 * loop due to of one of the following cases:
19503 			 *
19504 			 *   1. len < adjusted MSS (i.e. small),
19505 			 *   2. Sender SWS avoidance,
19506 			 *   3. max_pld is zero.
19507 			 *
19508 			 * We are done for this Multidata, so trim our
19509 			 * last payload buffer (if any) accordingly.
19510 			 */
19511 			if (md_pbuf != NULL)
19512 				md_pbuf->b_wptr -= *tail_unsent;
19513 		} else if (*usable > 0) {
19514 			*xmit_tail = (*xmit_tail)->b_cont;
19515 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19516 			    (uintptr_t)INT_MAX);
19517 			*tail_unsent = (int)MBLKL(*xmit_tail);
19518 			add_buffer = B_TRUE;
19519 		}
19520 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
19521 	    (tcp_mdt_chain || max_pld > 0));
19522 
19523 	/* send everything down */
19524 	tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
19525 	    &rconfirm);
19526 
19527 #undef PREP_NEW_MULTIDATA
19528 #undef PREP_NEW_PBUF
19529 #undef IPVER
19530 
19531 	IRE_REFRELE(ire);
19532 	return (0);
19533 }
19534 
19535 /*
19536  * A wrapper function for sending one or more Multidata messages down to
19537  * the module below ip; this routine does not release the reference of the
19538  * IRE (caller does that).  This routine is analogous to tcp_send_data().
19539  */
19540 static void
19541 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
19542     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
19543 {
19544 	uint64_t delta;
19545 	nce_t *nce;
19546 
19547 	ASSERT(ire != NULL && ill != NULL);
19548 	ASSERT(ire->ire_stq != NULL);
19549 	ASSERT(md_mp_head != NULL);
19550 	ASSERT(rconfirm != NULL);
19551 
19552 	/* adjust MIBs and IRE timestamp */
19553 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
19554 	tcp->tcp_obsegs += obsegs;
19555 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
19556 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
19557 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
19558 
19559 	if (tcp->tcp_ipversion == IPV4_VERSION) {
19560 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
19561 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
19562 	} else {
19563 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
19564 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
19565 	}
19566 
19567 	ire->ire_ob_pkt_count += obsegs;
19568 	if (ire->ire_ipif != NULL)
19569 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
19570 	ire->ire_last_used_time = lbolt;
19571 
19572 	/* send it down */
19573 	putnext(ire->ire_stq, md_mp_head);
19574 
19575 	/* we're done for TCP/IPv4 */
19576 	if (tcp->tcp_ipversion == IPV4_VERSION)
19577 		return;
19578 
19579 	nce = ire->ire_nce;
19580 
19581 	ASSERT(nce != NULL);
19582 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
19583 	ASSERT(nce->nce_state != ND_INCOMPLETE);
19584 
19585 	/* reachability confirmation? */
19586 	if (*rconfirm) {
19587 		nce->nce_last = TICK_TO_MSEC(lbolt64);
19588 		if (nce->nce_state != ND_REACHABLE) {
19589 			mutex_enter(&nce->nce_lock);
19590 			nce->nce_state = ND_REACHABLE;
19591 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
19592 			mutex_exit(&nce->nce_lock);
19593 			(void) untimeout(nce->nce_timeout_id);
19594 			if (ip_debug > 2) {
19595 				/* ip1dbg */
19596 				pr_addr_dbg("tcp_multisend_data: state "
19597 				    "for %s changed to REACHABLE\n",
19598 				    AF_INET6, &ire->ire_addr_v6);
19599 			}
19600 		}
19601 		/* reset transport reachability confirmation */
19602 		*rconfirm = B_FALSE;
19603 	}
19604 
19605 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
19606 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
19607 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
19608 
19609 	if (delta > (uint64_t)ill->ill_reachable_time) {
19610 		mutex_enter(&nce->nce_lock);
19611 		switch (nce->nce_state) {
19612 		case ND_REACHABLE:
19613 		case ND_STALE:
19614 			/*
19615 			 * ND_REACHABLE is identical to ND_STALE in this
19616 			 * specific case. If reachable time has expired for
19617 			 * this neighbor (delta is greater than reachable
19618 			 * time), conceptually, the neighbor cache is no
19619 			 * longer in REACHABLE state, but already in STALE
19620 			 * state.  So the correct transition here is to
19621 			 * ND_DELAY.
19622 			 */
19623 			nce->nce_state = ND_DELAY;
19624 			mutex_exit(&nce->nce_lock);
19625 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
19626 			if (ip_debug > 3) {
19627 				/* ip2dbg */
19628 				pr_addr_dbg("tcp_multisend_data: state "
19629 				    "for %s changed to DELAY\n",
19630 				    AF_INET6, &ire->ire_addr_v6);
19631 			}
19632 			break;
19633 		case ND_DELAY:
19634 		case ND_PROBE:
19635 			mutex_exit(&nce->nce_lock);
19636 			/* Timers have already started */
19637 			break;
19638 		case ND_UNREACHABLE:
19639 			/*
19640 			 * ndp timer has detected that this nce is
19641 			 * unreachable and initiated deleting this nce
19642 			 * and all its associated IREs. This is a race
19643 			 * where we found the ire before it was deleted
19644 			 * and have just sent out a packet using this
19645 			 * unreachable nce.
19646 			 */
19647 			mutex_exit(&nce->nce_lock);
19648 			break;
19649 		default:
19650 			ASSERT(0);
19651 		}
19652 	}
19653 }
19654 
19655 /*
19656  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
19657  * scheme, and returns one of the following:
19658  *
19659  * -1 = failed allocation.
19660  *  0 = success; burst count reached, or usable send window is too small,
19661  *      and that we'd rather wait until later before sending again.
19662  *  1 = success; we are called from tcp_multisend(), and both usable send
19663  *      window and tail_unsent are greater than the MDT threshold, and thus
19664  *      Multidata Transmit should be used instead.
19665  */
19666 static int
19667 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19668     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19669     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19670     const int mdt_thres)
19671 {
19672 	int num_burst_seg = tcp->tcp_snd_burst;
19673 
19674 	for (;;) {
19675 		struct datab	*db;
19676 		tcph_t		*tcph;
19677 		uint32_t	sum;
19678 		mblk_t		*mp, *mp1;
19679 		uchar_t		*rptr;
19680 		int		len;
19681 
19682 		/*
19683 		 * If we're called by tcp_multisend(), and the amount of
19684 		 * sendable data as well as the size of current xmit_tail
19685 		 * is beyond the MDT threshold, return to the caller and
19686 		 * let the large data transmit be done using MDT.
19687 		 */
19688 		if (*usable > 0 && *usable > mdt_thres &&
19689 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
19690 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
19691 			ASSERT(tcp->tcp_mdt);
19692 			return (1);	/* success; do large send */
19693 		}
19694 
19695 		if (num_burst_seg-- == 0)
19696 			break;		/* success; burst count reached */
19697 
19698 		len = mss;
19699 		if (len > *usable) {
19700 			len = *usable;
19701 			if (len <= 0) {
19702 				/* Terminate the loop */
19703 				break;	/* success; too small */
19704 			}
19705 			/*
19706 			 * Sender silly-window avoidance.
19707 			 * Ignore this if we are going to send a
19708 			 * zero window probe out.
19709 			 *
19710 			 * TODO: force data into microscopic window?
19711 			 *	==> (!pushed || (unsent > usable))
19712 			 */
19713 			if (len < (tcp->tcp_max_swnd >> 1) &&
19714 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
19715 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
19716 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
19717 				/*
19718 				 * If the retransmit timer is not running
19719 				 * we start it so that we will retransmit
19720 				 * in the case when the the receiver has
19721 				 * decremented the window.
19722 				 */
19723 				if (*snxt == tcp->tcp_snxt &&
19724 				    *snxt == tcp->tcp_suna) {
19725 					/*
19726 					 * We are not supposed to send
19727 					 * anything.  So let's wait a little
19728 					 * bit longer before breaking SWS
19729 					 * avoidance.
19730 					 *
19731 					 * What should the value be?
19732 					 * Suggestion: MAX(init rexmit time,
19733 					 * tcp->tcp_rto)
19734 					 */
19735 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19736 				}
19737 				break;	/* success; too small */
19738 			}
19739 		}
19740 
19741 		tcph = tcp->tcp_tcph;
19742 
19743 		*usable -= len; /* Approximate - can be adjusted later */
19744 		if (*usable > 0)
19745 			tcph->th_flags[0] = TH_ACK;
19746 		else
19747 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
19748 
19749 		/*
19750 		 * Prime pump for IP's checksumming on our behalf
19751 		 * Include the adjustment for a source route if any.
19752 		 */
19753 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19754 		sum = (sum >> 16) + (sum & 0xFFFF);
19755 		U16_TO_ABE16(sum, tcph->th_sum);
19756 
19757 		U32_TO_ABE32(*snxt, tcph->th_seq);
19758 
19759 		/*
19760 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
19761 		 * set.  For the case when TCP_FSS_VALID is the only valid
19762 		 * bit (normal active close), branch off only when we think
19763 		 * that the FIN flag needs to be set.  Note for this case,
19764 		 * that (snxt + len) may not reflect the actual seg_len,
19765 		 * as len may be further reduced in tcp_xmit_mp().  If len
19766 		 * gets modified, we will end up here again.
19767 		 */
19768 		if (tcp->tcp_valid_bits != 0 &&
19769 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
19770 		    ((*snxt + len) == tcp->tcp_fss))) {
19771 			uchar_t		*prev_rptr;
19772 			uint32_t	prev_snxt = tcp->tcp_snxt;
19773 
19774 			if (*tail_unsent == 0) {
19775 				ASSERT((*xmit_tail)->b_cont != NULL);
19776 				*xmit_tail = (*xmit_tail)->b_cont;
19777 				prev_rptr = (*xmit_tail)->b_rptr;
19778 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
19779 				    (*xmit_tail)->b_rptr);
19780 			} else {
19781 				prev_rptr = (*xmit_tail)->b_rptr;
19782 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
19783 				    *tail_unsent;
19784 			}
19785 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
19786 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
19787 			/* Restore tcp_snxt so we get amount sent right. */
19788 			tcp->tcp_snxt = prev_snxt;
19789 			if (prev_rptr == (*xmit_tail)->b_rptr) {
19790 				/*
19791 				 * If the previous timestamp is still in use,
19792 				 * don't stomp on it.
19793 				 */
19794 				if ((*xmit_tail)->b_next == NULL) {
19795 					(*xmit_tail)->b_prev = local_time;
19796 					(*xmit_tail)->b_next =
19797 					    (mblk_t *)(uintptr_t)(*snxt);
19798 				}
19799 			} else
19800 				(*xmit_tail)->b_rptr = prev_rptr;
19801 
19802 			if (mp == NULL)
19803 				return (-1);
19804 			mp1 = mp->b_cont;
19805 
19806 			tcp->tcp_last_sent_len = (ushort_t)len;
19807 			while (mp1->b_cont) {
19808 				*xmit_tail = (*xmit_tail)->b_cont;
19809 				(*xmit_tail)->b_prev = local_time;
19810 				(*xmit_tail)->b_next =
19811 				    (mblk_t *)(uintptr_t)(*snxt);
19812 				mp1 = mp1->b_cont;
19813 			}
19814 			*snxt += len;
19815 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
19816 			BUMP_LOCAL(tcp->tcp_obsegs);
19817 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
19818 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
19819 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
19820 			tcp_send_data(tcp, q, mp);
19821 			continue;
19822 		}
19823 
19824 		*snxt += len;	/* Adjust later if we don't send all of len */
19825 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
19826 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
19827 
19828 		if (*tail_unsent) {
19829 			/* Are the bytes above us in flight? */
19830 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
19831 			if (rptr != (*xmit_tail)->b_rptr) {
19832 				*tail_unsent -= len;
19833 				tcp->tcp_last_sent_len = (ushort_t)len;
19834 				len += tcp_hdr_len;
19835 				if (tcp->tcp_ipversion == IPV4_VERSION)
19836 					tcp->tcp_ipha->ipha_length = htons(len);
19837 				else
19838 					tcp->tcp_ip6h->ip6_plen =
19839 					    htons(len -
19840 					    ((char *)&tcp->tcp_ip6h[1] -
19841 					    tcp->tcp_iphc));
19842 				mp = dupb(*xmit_tail);
19843 				if (!mp)
19844 					return (-1);	/* out_of_mem */
19845 				mp->b_rptr = rptr;
19846 				/*
19847 				 * If the old timestamp is no longer in use,
19848 				 * sample a new timestamp now.
19849 				 */
19850 				if ((*xmit_tail)->b_next == NULL) {
19851 					(*xmit_tail)->b_prev = local_time;
19852 					(*xmit_tail)->b_next =
19853 					    (mblk_t *)(uintptr_t)(*snxt-len);
19854 				}
19855 				goto must_alloc;
19856 			}
19857 		} else {
19858 			*xmit_tail = (*xmit_tail)->b_cont;
19859 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
19860 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
19861 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
19862 			    (*xmit_tail)->b_rptr);
19863 		}
19864 
19865 		(*xmit_tail)->b_prev = local_time;
19866 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
19867 
19868 		*tail_unsent -= len;
19869 		tcp->tcp_last_sent_len = (ushort_t)len;
19870 
19871 		len += tcp_hdr_len;
19872 		if (tcp->tcp_ipversion == IPV4_VERSION)
19873 			tcp->tcp_ipha->ipha_length = htons(len);
19874 		else
19875 			tcp->tcp_ip6h->ip6_plen = htons(len -
19876 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
19877 
19878 		mp = dupb(*xmit_tail);
19879 		if (!mp)
19880 			return (-1);	/* out_of_mem */
19881 
19882 		len = tcp_hdr_len;
19883 		/*
19884 		 * There are four reasons to allocate a new hdr mblk:
19885 		 *  1) The bytes above us are in use by another packet
19886 		 *  2) We don't have good alignment
19887 		 *  3) The mblk is being shared
19888 		 *  4) We don't have enough room for a header
19889 		 */
19890 		rptr = mp->b_rptr - len;
19891 		if (!OK_32PTR(rptr) ||
19892 		    ((db = mp->b_datap), db->db_ref != 2) ||
19893 		    rptr < db->db_base) {
19894 			/* NOTE: we assume allocb returns an OK_32PTR */
19895 
19896 		must_alloc:;
19897 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
19898 			    tcp_wroff_xtra, BPRI_MED);
19899 			if (!mp1) {
19900 				freemsg(mp);
19901 				return (-1);	/* out_of_mem */
19902 			}
19903 			mp1->b_cont = mp;
19904 			mp = mp1;
19905 			/* Leave room for Link Level header */
19906 			len = tcp_hdr_len;
19907 			rptr = &mp->b_rptr[tcp_wroff_xtra];
19908 			mp->b_wptr = &rptr[len];
19909 		}
19910 
19911 		/*
19912 		 * Fill in the header using the template header, and add
19913 		 * options such as time-stamp, ECN and/or SACK, as needed.
19914 		 */
19915 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
19916 
19917 		mp->b_rptr = rptr;
19918 
19919 		if (*tail_unsent) {
19920 			int spill = *tail_unsent;
19921 
19922 			mp1 = mp->b_cont;
19923 			if (!mp1)
19924 				mp1 = mp;
19925 
19926 			/*
19927 			 * If we're a little short, tack on more mblks until
19928 			 * there is no more spillover.
19929 			 */
19930 			while (spill < 0) {
19931 				mblk_t *nmp;
19932 				int nmpsz;
19933 
19934 				nmp = (*xmit_tail)->b_cont;
19935 				nmpsz = MBLKL(nmp);
19936 
19937 				/*
19938 				 * Excess data in mblk; can we split it?
19939 				 * If MDT is enabled for the connection,
19940 				 * keep on splitting as this is a transient
19941 				 * send path.
19942 				 */
19943 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
19944 					/*
19945 					 * Don't split if stream head was
19946 					 * told to break up larger writes
19947 					 * into smaller ones.
19948 					 */
19949 					if (tcp->tcp_maxpsz > 0)
19950 						break;
19951 
19952 					/*
19953 					 * Next mblk is less than SMSS/2
19954 					 * rounded up to nearest 64-byte;
19955 					 * let it get sent as part of the
19956 					 * next segment.
19957 					 */
19958 					if (tcp->tcp_localnet &&
19959 					    !tcp->tcp_cork &&
19960 					    (nmpsz < roundup((mss >> 1), 64)))
19961 						break;
19962 				}
19963 
19964 				*xmit_tail = nmp;
19965 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
19966 				/* Stash for rtt use later */
19967 				(*xmit_tail)->b_prev = local_time;
19968 				(*xmit_tail)->b_next =
19969 				    (mblk_t *)(uintptr_t)(*snxt - len);
19970 				mp1->b_cont = dupb(*xmit_tail);
19971 				mp1 = mp1->b_cont;
19972 
19973 				spill += nmpsz;
19974 				if (mp1 == NULL) {
19975 					*tail_unsent = spill;
19976 					freemsg(mp);
19977 					return (-1);	/* out_of_mem */
19978 				}
19979 			}
19980 
19981 			/* Trim back any surplus on the last mblk */
19982 			if (spill >= 0) {
19983 				mp1->b_wptr -= spill;
19984 				*tail_unsent = spill;
19985 			} else {
19986 				/*
19987 				 * We did not send everything we could in
19988 				 * order to remain within the b_cont limit.
19989 				 */
19990 				*usable -= spill;
19991 				*snxt += spill;
19992 				tcp->tcp_last_sent_len += spill;
19993 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
19994 				/*
19995 				 * Adjust the checksum
19996 				 */
19997 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19998 				sum += spill;
19999 				sum = (sum >> 16) + (sum & 0xFFFF);
20000 				U16_TO_ABE16(sum, tcph->th_sum);
20001 				if (tcp->tcp_ipversion == IPV4_VERSION) {
20002 					sum = ntohs(
20003 					    ((ipha_t *)rptr)->ipha_length) +
20004 					    spill;
20005 					((ipha_t *)rptr)->ipha_length =
20006 					    htons(sum);
20007 				} else {
20008 					sum = ntohs(
20009 					    ((ip6_t *)rptr)->ip6_plen) +
20010 					    spill;
20011 					((ip6_t *)rptr)->ip6_plen =
20012 					    htons(sum);
20013 				}
20014 				*tail_unsent = 0;
20015 			}
20016 		}
20017 		if (tcp->tcp_ip_forward_progress) {
20018 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20019 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20020 			tcp->tcp_ip_forward_progress = B_FALSE;
20021 		}
20022 
20023 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20024 		tcp_send_data(tcp, q, mp);
20025 		BUMP_LOCAL(tcp->tcp_obsegs);
20026 	}
20027 
20028 	return (0);
20029 }
20030 
20031 /* Unlink and return any mblk that looks like it contains a MDT info */
20032 static mblk_t *
20033 tcp_mdt_info_mp(mblk_t *mp)
20034 {
20035 	mblk_t	*prev_mp;
20036 
20037 	for (;;) {
20038 		prev_mp = mp;
20039 		/* no more to process? */
20040 		if ((mp = mp->b_cont) == NULL)
20041 			break;
20042 
20043 		switch (DB_TYPE(mp)) {
20044 		case M_CTL:
20045 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20046 				continue;
20047 			ASSERT(prev_mp != NULL);
20048 			prev_mp->b_cont = mp->b_cont;
20049 			mp->b_cont = NULL;
20050 			return (mp);
20051 		default:
20052 			break;
20053 		}
20054 	}
20055 	return (mp);
20056 }
20057 
20058 /* MDT info update routine, called when IP notifies us about MDT */
20059 static void
20060 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20061 {
20062 	boolean_t prev_state;
20063 
20064 	/*
20065 	 * IP is telling us to abort MDT on this connection?  We know
20066 	 * this because the capability is only turned off when IP
20067 	 * encounters some pathological cases, e.g. link-layer change
20068 	 * where the new driver doesn't support MDT, or in situation
20069 	 * where MDT usage on the link-layer has been switched off.
20070 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20071 	 * if the link-layer doesn't support MDT, and if it does, it
20072 	 * will indicate that the feature is to be turned on.
20073 	 */
20074 	prev_state = tcp->tcp_mdt;
20075 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20076 	if (!tcp->tcp_mdt && !first) {
20077 		TCP_STAT(tcp_mdt_conn_halted3);
20078 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20079 		    (void *)tcp->tcp_connp));
20080 	}
20081 
20082 	/*
20083 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20084 	 * so disable MDT otherwise.  The checks are done here
20085 	 * and in tcp_wput_data().
20086 	 */
20087 	if (tcp->tcp_mdt &&
20088 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20089 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20090 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20091 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20092 		tcp->tcp_mdt = B_FALSE;
20093 
20094 	if (tcp->tcp_mdt) {
20095 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
20096 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
20097 			    "version (%d), expected version is %d",
20098 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
20099 			tcp->tcp_mdt = B_FALSE;
20100 			return;
20101 		}
20102 
20103 		/*
20104 		 * We need the driver to be able to handle at least three
20105 		 * spans per packet in order for tcp MDT to be utilized.
20106 		 * The first is for the header portion, while the rest are
20107 		 * needed to handle a packet that straddles across two
20108 		 * virtually non-contiguous buffers; a typical tcp packet
20109 		 * therefore consists of only two spans.  Note that we take
20110 		 * a zero as "don't care".
20111 		 */
20112 		if (mdt_capab->ill_mdt_span_limit > 0 &&
20113 		    mdt_capab->ill_mdt_span_limit < 3) {
20114 			tcp->tcp_mdt = B_FALSE;
20115 			return;
20116 		}
20117 
20118 		/* a zero means driver wants default value */
20119 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
20120 		    tcp_mdt_max_pbufs);
20121 		if (tcp->tcp_mdt_max_pld == 0)
20122 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
20123 
20124 		/* ensure 32-bit alignment */
20125 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
20126 		    mdt_capab->ill_mdt_hdr_head), 4);
20127 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
20128 		    mdt_capab->ill_mdt_hdr_tail), 4);
20129 
20130 		if (!first && !prev_state) {
20131 			TCP_STAT(tcp_mdt_conn_resumed2);
20132 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
20133 			    (void *)tcp->tcp_connp));
20134 		}
20135 	}
20136 }
20137 
20138 static void
20139 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
20140 {
20141 	conn_t *connp = tcp->tcp_connp;
20142 
20143 	ASSERT(ire != NULL);
20144 
20145 	/*
20146 	 * We may be in the fastpath here, and although we essentially do
20147 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
20148 	 * we try to keep things as brief as possible.  After all, these
20149 	 * are only best-effort checks, and we do more thorough ones prior
20150 	 * to calling tcp_multisend().
20151 	 */
20152 	if (ip_multidata_outbound && check_mdt &&
20153 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
20154 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
20155 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
20156 	    !(ire->ire_flags & RTF_MULTIRT) &&
20157 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
20158 	    CONN_IS_MD_FASTPATH(connp)) {
20159 		/* Remember the result */
20160 		connp->conn_mdt_ok = B_TRUE;
20161 
20162 		ASSERT(ill->ill_mdt_capab != NULL);
20163 		if (!ill->ill_mdt_capab->ill_mdt_on) {
20164 			/*
20165 			 * If MDT has been previously turned off in the past,
20166 			 * and we currently can do MDT (due to IPQoS policy
20167 			 * removal, etc.) then enable it for this interface.
20168 			 */
20169 			ill->ill_mdt_capab->ill_mdt_on = 1;
20170 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
20171 			    "interface %s\n", (void *)connp, ill->ill_name));
20172 		}
20173 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
20174 	}
20175 
20176 	/*
20177 	 * The goal is to reduce the number of generated tcp segments by
20178 	 * setting the maxpsz multiplier to 0; this will have an affect on
20179 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
20180 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
20181 	 * of outbound segments and incoming ACKs, thus allowing for better
20182 	 * network and system performance.  In contrast the legacy behavior
20183 	 * may result in sending less than SMSS size, because the last mblk
20184 	 * for some packets may have more data than needed to make up SMSS,
20185 	 * and the legacy code refused to "split" it.
20186 	 *
20187 	 * We apply the new behavior on following situations:
20188 	 *
20189 	 *   1) Loopback connections,
20190 	 *   2) Connections in which the remote peer is not on local subnet,
20191 	 *   3) Local subnet connections over the bge interface (see below).
20192 	 *
20193 	 * Ideally, we would like this behavior to apply for interfaces other
20194 	 * than bge.  However, doing so would negatively impact drivers which
20195 	 * perform dynamic mapping and unmapping of DMA resources, which are
20196 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
20197 	 * packet will be generated by tcp).  The bge driver does not suffer
20198 	 * from this, as it copies the mblks into pre-mapped buffers, and
20199 	 * therefore does not require more I/O resources than before.
20200 	 *
20201 	 * Otherwise, this behavior is present on all network interfaces when
20202 	 * the destination endpoint is non-local, since reducing the number
20203 	 * of packets in general is good for the network.
20204 	 *
20205 	 * TODO We need to remove this hard-coded conditional for bge once
20206 	 *	a better "self-tuning" mechanism, or a way to comprehend
20207 	 *	the driver transmit strategy is devised.  Until the solution
20208 	 *	is found and well understood, we live with this hack.
20209 	 */
20210 	if (!tcp_static_maxpsz &&
20211 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
20212 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
20213 		/* override the default value */
20214 		tcp->tcp_maxpsz = 0;
20215 
20216 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
20217 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
20218 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
20219 	}
20220 
20221 	/* set the stream head parameters accordingly */
20222 	(void) tcp_maxpsz_set(tcp, B_TRUE);
20223 }
20224 
20225 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
20226 static void
20227 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
20228 {
20229 	uchar_t	fval = *mp->b_rptr;
20230 	mblk_t	*tail;
20231 	queue_t	*q = tcp->tcp_wq;
20232 
20233 	/* TODO: How should flush interact with urgent data? */
20234 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
20235 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
20236 		/*
20237 		 * Flush only data that has not yet been put on the wire.  If
20238 		 * we flush data that we have already transmitted, life, as we
20239 		 * know it, may come to an end.
20240 		 */
20241 		tail = tcp->tcp_xmit_tail;
20242 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
20243 		tcp->tcp_xmit_tail_unsent = 0;
20244 		tcp->tcp_unsent = 0;
20245 		if (tail->b_wptr != tail->b_rptr)
20246 			tail = tail->b_cont;
20247 		if (tail) {
20248 			mblk_t **excess = &tcp->tcp_xmit_head;
20249 			for (;;) {
20250 				mblk_t *mp1 = *excess;
20251 				if (mp1 == tail)
20252 					break;
20253 				tcp->tcp_xmit_tail = mp1;
20254 				tcp->tcp_xmit_last = mp1;
20255 				excess = &mp1->b_cont;
20256 			}
20257 			*excess = NULL;
20258 			tcp_close_mpp(&tail);
20259 			if (tcp->tcp_snd_zcopy_aware)
20260 				tcp_zcopy_notify(tcp);
20261 		}
20262 		/*
20263 		 * We have no unsent data, so unsent must be less than
20264 		 * tcp_xmit_lowater, so re-enable flow.
20265 		 */
20266 		if (tcp->tcp_flow_stopped) {
20267 			tcp_clrqfull(tcp);
20268 		}
20269 	}
20270 	/*
20271 	 * TODO: you can't just flush these, you have to increase rwnd for one
20272 	 * thing.  For another, how should urgent data interact?
20273 	 */
20274 	if (fval & FLUSHR) {
20275 		*mp->b_rptr = fval & ~FLUSHW;
20276 		/* XXX */
20277 		qreply(q, mp);
20278 		return;
20279 	}
20280 	freemsg(mp);
20281 }
20282 
20283 /*
20284  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
20285  * messages.
20286  */
20287 static void
20288 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
20289 {
20290 	mblk_t	*mp1;
20291 	STRUCT_HANDLE(strbuf, sb);
20292 	uint16_t port;
20293 	queue_t 	*q = tcp->tcp_wq;
20294 	in6_addr_t	v6addr;
20295 	ipaddr_t	v4addr;
20296 	uint32_t	flowinfo = 0;
20297 	int		addrlen;
20298 
20299 	/* Make sure it is one of ours. */
20300 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20301 	case TI_GETMYNAME:
20302 	case TI_GETPEERNAME:
20303 		break;
20304 	default:
20305 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20306 		return;
20307 	}
20308 	switch (mi_copy_state(q, mp, &mp1)) {
20309 	case -1:
20310 		return;
20311 	case MI_COPY_CASE(MI_COPY_IN, 1):
20312 		break;
20313 	case MI_COPY_CASE(MI_COPY_OUT, 1):
20314 		/* Copy out the strbuf. */
20315 		mi_copyout(q, mp);
20316 		return;
20317 	case MI_COPY_CASE(MI_COPY_OUT, 2):
20318 		/* All done. */
20319 		mi_copy_done(q, mp, 0);
20320 		return;
20321 	default:
20322 		mi_copy_done(q, mp, EPROTO);
20323 		return;
20324 	}
20325 	/* Check alignment of the strbuf */
20326 	if (!OK_32PTR(mp1->b_rptr)) {
20327 		mi_copy_done(q, mp, EINVAL);
20328 		return;
20329 	}
20330 
20331 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
20332 	    (void *)mp1->b_rptr);
20333 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
20334 
20335 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
20336 		mi_copy_done(q, mp, EINVAL);
20337 		return;
20338 	}
20339 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20340 	case TI_GETMYNAME:
20341 		if (tcp->tcp_family == AF_INET) {
20342 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20343 				v4addr = tcp->tcp_ipha->ipha_src;
20344 			} else {
20345 				/* can't return an address in this case */
20346 				v4addr = 0;
20347 			}
20348 		} else {
20349 			/* tcp->tcp_family == AF_INET6 */
20350 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20351 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
20352 				    &v6addr);
20353 			} else {
20354 				v6addr = tcp->tcp_ip6h->ip6_src;
20355 			}
20356 		}
20357 		port = tcp->tcp_lport;
20358 		break;
20359 	case TI_GETPEERNAME:
20360 		if (tcp->tcp_family == AF_INET) {
20361 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20362 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
20363 				    v4addr);
20364 			} else {
20365 				/* can't return an address in this case */
20366 				v4addr = 0;
20367 			}
20368 		} else {
20369 			/* tcp->tcp_family == AF_INET6) */
20370 			v6addr = tcp->tcp_remote_v6;
20371 			if (tcp->tcp_ipversion == IPV6_VERSION) {
20372 				/*
20373 				 * No flowinfo if tcp->tcp_ipversion is v4.
20374 				 *
20375 				 * flowinfo was already initialized to zero
20376 				 * where it was declared above, so only
20377 				 * set it if ipversion is v6.
20378 				 */
20379 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
20380 				    ~IPV6_VERS_AND_FLOW_MASK;
20381 			}
20382 		}
20383 		port = tcp->tcp_fport;
20384 		break;
20385 	default:
20386 		mi_copy_done(q, mp, EPROTO);
20387 		return;
20388 	}
20389 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
20390 	if (!mp1)
20391 		return;
20392 
20393 	if (tcp->tcp_family == AF_INET) {
20394 		sin_t *sin;
20395 
20396 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
20397 		sin = (sin_t *)mp1->b_rptr;
20398 		mp1->b_wptr = (uchar_t *)&sin[1];
20399 		*sin = sin_null;
20400 		sin->sin_family = AF_INET;
20401 		sin->sin_addr.s_addr = v4addr;
20402 		sin->sin_port = port;
20403 	} else {
20404 		/* tcp->tcp_family == AF_INET6 */
20405 		sin6_t *sin6;
20406 
20407 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
20408 		sin6 = (sin6_t *)mp1->b_rptr;
20409 		mp1->b_wptr = (uchar_t *)&sin6[1];
20410 		*sin6 = sin6_null;
20411 		sin6->sin6_family = AF_INET6;
20412 		sin6->sin6_flowinfo = flowinfo;
20413 		sin6->sin6_addr = v6addr;
20414 		sin6->sin6_port = port;
20415 	}
20416 	/* Copy out the address */
20417 	mi_copyout(q, mp);
20418 }
20419 
20420 /*
20421  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
20422  * messages.
20423  */
20424 /* ARGSUSED */
20425 static void
20426 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
20427 {
20428 	conn_t 	*connp = (conn_t *)arg;
20429 	tcp_t	*tcp = connp->conn_tcp;
20430 	queue_t	*q = tcp->tcp_wq;
20431 	struct iocblk	*iocp;
20432 
20433 	ASSERT(DB_TYPE(mp) == M_IOCTL);
20434 	/*
20435 	 * Try and ASSERT the minimum possible references on the
20436 	 * conn early enough. Since we are executing on write side,
20437 	 * the connection is obviously not detached and that means
20438 	 * there is a ref each for TCP and IP. Since we are behind
20439 	 * the squeue, the minimum references needed are 3. If the
20440 	 * conn is in classifier hash list, there should be an
20441 	 * extra ref for that (we check both the possibilities).
20442 	 */
20443 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20444 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20445 
20446 	iocp = (struct iocblk *)mp->b_rptr;
20447 	switch (iocp->ioc_cmd) {
20448 	case TCP_IOC_DEFAULT_Q:
20449 		/* Wants to be the default wq. */
20450 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
20451 			iocp->ioc_error = EPERM;
20452 			iocp->ioc_count = 0;
20453 			mp->b_datap->db_type = M_IOCACK;
20454 			qreply(q, mp);
20455 			return;
20456 		}
20457 		tcp_def_q_set(tcp, mp);
20458 		return;
20459 	case _SIOCSOCKFALLBACK:
20460 		/*
20461 		 * Either sockmod is about to be popped and the socket
20462 		 * would now be treated as a plain stream, or a module
20463 		 * is about to be pushed so we could no longer use read-
20464 		 * side synchronous streams for fused loopback tcp.
20465 		 * Drain any queued data and disable direct sockfs
20466 		 * interface from now on.
20467 		 */
20468 		if (!tcp->tcp_issocket) {
20469 			DB_TYPE(mp) = M_IOCNAK;
20470 			iocp->ioc_error = EINVAL;
20471 		} else {
20472 #ifdef	_ILP32
20473 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
20474 #else
20475 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
20476 #endif
20477 			/*
20478 			 * Insert this socket into the acceptor hash.
20479 			 * We might need it for T_CONN_RES message
20480 			 */
20481 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
20482 
20483 			if (tcp->tcp_fused) {
20484 				/*
20485 				 * This is a fused loopback tcp; disable
20486 				 * read-side synchronous streams interface
20487 				 * and drain any queued data.  It is okay
20488 				 * to do this for non-synchronous streams
20489 				 * fused tcp as well.
20490 				 */
20491 				tcp_fuse_disable_pair(tcp, B_FALSE);
20492 			}
20493 			tcp->tcp_issocket = B_FALSE;
20494 			TCP_STAT(tcp_sock_fallback);
20495 
20496 			DB_TYPE(mp) = M_IOCACK;
20497 			iocp->ioc_error = 0;
20498 		}
20499 		iocp->ioc_count = 0;
20500 		iocp->ioc_rval = 0;
20501 		qreply(q, mp);
20502 		return;
20503 	}
20504 	CALL_IP_WPUT(connp, q, mp);
20505 }
20506 
20507 /*
20508  * This routine is called by tcp_wput() to handle all TPI requests.
20509  */
20510 /* ARGSUSED */
20511 static void
20512 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
20513 {
20514 	conn_t 	*connp = (conn_t *)arg;
20515 	tcp_t	*tcp = connp->conn_tcp;
20516 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
20517 	uchar_t *rptr;
20518 	t_scalar_t type;
20519 	int len;
20520 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
20521 
20522 	/*
20523 	 * Try and ASSERT the minimum possible references on the
20524 	 * conn early enough. Since we are executing on write side,
20525 	 * the connection is obviously not detached and that means
20526 	 * there is a ref each for TCP and IP. Since we are behind
20527 	 * the squeue, the minimum references needed are 3. If the
20528 	 * conn is in classifier hash list, there should be an
20529 	 * extra ref for that (we check both the possibilities).
20530 	 */
20531 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20532 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20533 
20534 	rptr = mp->b_rptr;
20535 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
20536 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
20537 		type = ((union T_primitives *)rptr)->type;
20538 		if (type == T_EXDATA_REQ) {
20539 			uint32_t msize = msgdsize(mp->b_cont);
20540 
20541 			len = msize - 1;
20542 			if (len < 0) {
20543 				freemsg(mp);
20544 				return;
20545 			}
20546 			/*
20547 			 * Try to force urgent data out on the wire.
20548 			 * Even if we have unsent data this will
20549 			 * at least send the urgent flag.
20550 			 * XXX does not handle more flag correctly.
20551 			 */
20552 			len += tcp->tcp_unsent;
20553 			len += tcp->tcp_snxt;
20554 			tcp->tcp_urg = len;
20555 			tcp->tcp_valid_bits |= TCP_URG_VALID;
20556 
20557 			/* Bypass tcp protocol for fused tcp loopback */
20558 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
20559 				return;
20560 		} else if (type != T_DATA_REQ) {
20561 			goto non_urgent_data;
20562 		}
20563 		/* TODO: options, flags, ... from user */
20564 		/* Set length to zero for reclamation below */
20565 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
20566 		freeb(mp);
20567 		return;
20568 	} else {
20569 		if (tcp->tcp_debug) {
20570 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20571 			    "tcp_wput_proto, dropping one...");
20572 		}
20573 		freemsg(mp);
20574 		return;
20575 	}
20576 
20577 non_urgent_data:
20578 
20579 	switch ((int)tprim->type) {
20580 	case O_T_BIND_REQ:	/* bind request */
20581 	case T_BIND_REQ:	/* new semantics bind request */
20582 		tcp_bind(tcp, mp);
20583 		break;
20584 	case T_UNBIND_REQ:	/* unbind request */
20585 		tcp_unbind(tcp, mp);
20586 		break;
20587 	case O_T_CONN_RES:	/* old connection response XXX */
20588 	case T_CONN_RES:	/* connection response */
20589 		tcp_accept(tcp, mp);
20590 		break;
20591 	case T_CONN_REQ:	/* connection request */
20592 		tcp_connect(tcp, mp);
20593 		break;
20594 	case T_DISCON_REQ:	/* disconnect request */
20595 		tcp_disconnect(tcp, mp);
20596 		break;
20597 	case T_CAPABILITY_REQ:
20598 		tcp_capability_req(tcp, mp);	/* capability request */
20599 		break;
20600 	case T_INFO_REQ:	/* information request */
20601 		tcp_info_req(tcp, mp);
20602 		break;
20603 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
20604 		/* Only IP is allowed to return meaningful value */
20605 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
20606 		break;
20607 	case T_OPTMGMT_REQ:
20608 		/*
20609 		 * Note:  no support for snmpcom_req() through new
20610 		 * T_OPTMGMT_REQ. See comments in ip.c
20611 		 */
20612 		/* Only IP is allowed to return meaningful value */
20613 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
20614 		break;
20615 
20616 	case T_UNITDATA_REQ:	/* unitdata request */
20617 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
20618 		break;
20619 	case T_ORDREL_REQ:	/* orderly release req */
20620 		freemsg(mp);
20621 
20622 		if (tcp->tcp_fused)
20623 			tcp_unfuse(tcp);
20624 
20625 		if (tcp_xmit_end(tcp) != 0) {
20626 			/*
20627 			 * We were crossing FINs and got a reset from
20628 			 * the other side. Just ignore it.
20629 			 */
20630 			if (tcp->tcp_debug) {
20631 				(void) strlog(TCP_MOD_ID, 0, 1,
20632 				    SL_ERROR|SL_TRACE,
20633 				    "tcp_wput_proto, T_ORDREL_REQ out of "
20634 				    "state %s",
20635 				    tcp_display(tcp, NULL,
20636 				    DISP_ADDR_AND_PORT));
20637 			}
20638 		}
20639 		break;
20640 	case T_ADDR_REQ:
20641 		tcp_addr_req(tcp, mp);
20642 		break;
20643 	default:
20644 		if (tcp->tcp_debug) {
20645 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20646 			    "tcp_wput_proto, bogus TPI msg, type %d",
20647 			    tprim->type);
20648 		}
20649 		/*
20650 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
20651 		 * to recover.
20652 		 */
20653 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
20654 		break;
20655 	}
20656 }
20657 
20658 /*
20659  * The TCP write service routine should never be called...
20660  */
20661 /* ARGSUSED */
20662 static void
20663 tcp_wsrv(queue_t *q)
20664 {
20665 	TCP_STAT(tcp_wsrv_called);
20666 }
20667 
20668 /* Non overlapping byte exchanger */
20669 static void
20670 tcp_xchg(uchar_t *a, uchar_t *b, int len)
20671 {
20672 	uchar_t	uch;
20673 
20674 	while (len-- > 0) {
20675 		uch = a[len];
20676 		a[len] = b[len];
20677 		b[len] = uch;
20678 	}
20679 }
20680 
20681 /*
20682  * Send out a control packet on the tcp connection specified.  This routine
20683  * is typically called where we need a simple ACK or RST generated.
20684  */
20685 static void
20686 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
20687 {
20688 	uchar_t		*rptr;
20689 	tcph_t		*tcph;
20690 	ipha_t		*ipha = NULL;
20691 	ip6_t		*ip6h = NULL;
20692 	uint32_t	sum;
20693 	int		tcp_hdr_len;
20694 	int		tcp_ip_hdr_len;
20695 	mblk_t		*mp;
20696 
20697 	/*
20698 	 * Save sum for use in source route later.
20699 	 */
20700 	ASSERT(tcp != NULL);
20701 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
20702 	tcp_hdr_len = tcp->tcp_hdr_len;
20703 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
20704 
20705 	/* If a text string is passed in with the request, pass it to strlog. */
20706 	if (str != NULL && tcp->tcp_debug) {
20707 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
20708 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
20709 		    str, seq, ack, ctl);
20710 	}
20711 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
20712 	    BPRI_MED);
20713 	if (mp == NULL) {
20714 		return;
20715 	}
20716 	rptr = &mp->b_rptr[tcp_wroff_xtra];
20717 	mp->b_rptr = rptr;
20718 	mp->b_wptr = &rptr[tcp_hdr_len];
20719 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
20720 
20721 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20722 		ipha = (ipha_t *)rptr;
20723 		ipha->ipha_length = htons(tcp_hdr_len);
20724 	} else {
20725 		ip6h = (ip6_t *)rptr;
20726 		ASSERT(tcp != NULL);
20727 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
20728 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20729 	}
20730 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
20731 	tcph->th_flags[0] = (uint8_t)ctl;
20732 	if (ctl & TH_RST) {
20733 		BUMP_MIB(&tcp_mib, tcpOutRsts);
20734 		BUMP_MIB(&tcp_mib, tcpOutControl);
20735 		/*
20736 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
20737 		 */
20738 		if (tcp->tcp_snd_ts_ok &&
20739 		    tcp->tcp_state > TCPS_SYN_SENT) {
20740 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
20741 			*(mp->b_wptr) = TCPOPT_EOL;
20742 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20743 				ipha->ipha_length = htons(tcp_hdr_len -
20744 				    TCPOPT_REAL_TS_LEN);
20745 			} else {
20746 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
20747 				    TCPOPT_REAL_TS_LEN);
20748 			}
20749 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
20750 			sum -= TCPOPT_REAL_TS_LEN;
20751 		}
20752 	}
20753 	if (ctl & TH_ACK) {
20754 		if (tcp->tcp_snd_ts_ok) {
20755 			U32_TO_BE32(lbolt,
20756 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
20757 			U32_TO_BE32(tcp->tcp_ts_recent,
20758 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
20759 		}
20760 
20761 		/* Update the latest receive window size in TCP header. */
20762 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
20763 		    tcph->th_win);
20764 		tcp->tcp_rack = ack;
20765 		tcp->tcp_rack_cnt = 0;
20766 		BUMP_MIB(&tcp_mib, tcpOutAck);
20767 	}
20768 	BUMP_LOCAL(tcp->tcp_obsegs);
20769 	U32_TO_BE32(seq, tcph->th_seq);
20770 	U32_TO_BE32(ack, tcph->th_ack);
20771 	/*
20772 	 * Include the adjustment for a source route if any.
20773 	 */
20774 	sum = (sum >> 16) + (sum & 0xFFFF);
20775 	U16_TO_BE16(sum, tcph->th_sum);
20776 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20777 	tcp_send_data(tcp, tcp->tcp_wq, mp);
20778 }
20779 
20780 /*
20781  * If this routine returns B_TRUE, TCP can generate a RST in response
20782  * to a segment.  If it returns B_FALSE, TCP should not respond.
20783  */
20784 static boolean_t
20785 tcp_send_rst_chk(void)
20786 {
20787 	clock_t	now;
20788 
20789 	/*
20790 	 * TCP needs to protect itself from generating too many RSTs.
20791 	 * This can be a DoS attack by sending us random segments
20792 	 * soliciting RSTs.
20793 	 *
20794 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
20795 	 * in each 1 second interval.  In this way, TCP still generate
20796 	 * RSTs in normal cases but when under attack, the impact is
20797 	 * limited.
20798 	 */
20799 	if (tcp_rst_sent_rate_enabled != 0) {
20800 		now = lbolt;
20801 		/* lbolt can wrap around. */
20802 		if ((tcp_last_rst_intrvl > now) ||
20803 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
20804 			tcp_last_rst_intrvl = now;
20805 			tcp_rst_cnt = 1;
20806 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
20807 			return (B_FALSE);
20808 		}
20809 	}
20810 	return (B_TRUE);
20811 }
20812 
20813 /*
20814  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
20815  */
20816 static void
20817 tcp_ip_ire_mark_advice(tcp_t *tcp)
20818 {
20819 	mblk_t *mp;
20820 	ipic_t *ipic;
20821 
20822 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20823 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
20824 		    &ipic);
20825 	} else {
20826 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
20827 		    &ipic);
20828 	}
20829 	if (mp == NULL)
20830 		return;
20831 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
20832 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
20833 }
20834 
20835 /*
20836  * Return an IP advice ioctl mblk and set ipic to be the pointer
20837  * to the advice structure.
20838  */
20839 static mblk_t *
20840 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
20841 {
20842 	struct iocblk *ioc;
20843 	mblk_t *mp, *mp1;
20844 
20845 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
20846 	if (mp == NULL)
20847 		return (NULL);
20848 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
20849 	*ipic = (ipic_t *)mp->b_rptr;
20850 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
20851 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
20852 
20853 	bcopy(addr, *ipic + 1, addr_len);
20854 
20855 	(*ipic)->ipic_addr_length = addr_len;
20856 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
20857 
20858 	mp1 = mkiocb(IP_IOCTL);
20859 	if (mp1 == NULL) {
20860 		freemsg(mp);
20861 		return (NULL);
20862 	}
20863 	mp1->b_cont = mp;
20864 	ioc = (struct iocblk *)mp1->b_rptr;
20865 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
20866 
20867 	return (mp1);
20868 }
20869 
20870 /*
20871  * Generate a reset based on an inbound packet for which there is no active
20872  * tcp state that we can find.
20873  *
20874  * IPSEC NOTE : Try to send the reply with the same protection as it came
20875  * in.  We still have the ipsec_mp that the packet was attached to. Thus
20876  * the packet will go out at the same level of protection as it came in by
20877  * converting the IPSEC_IN to IPSEC_OUT.
20878  */
20879 static void
20880 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
20881     uint32_t ack, int ctl, uint_t ip_hdr_len)
20882 {
20883 	ipha_t		*ipha = NULL;
20884 	ip6_t		*ip6h = NULL;
20885 	ushort_t	len;
20886 	tcph_t		*tcph;
20887 	int		i;
20888 	mblk_t		*ipsec_mp;
20889 	boolean_t	mctl_present;
20890 	ipic_t		*ipic;
20891 	ipaddr_t	v4addr;
20892 	in6_addr_t	v6addr;
20893 	int		addr_len;
20894 	void		*addr;
20895 	queue_t		*q = tcp_g_q;
20896 	tcp_t		*tcp = Q_TO_TCP(q);
20897 
20898 	if (!tcp_send_rst_chk()) {
20899 		tcp_rst_unsent++;
20900 		freemsg(mp);
20901 		return;
20902 	}
20903 
20904 	if (mp->b_datap->db_type == M_CTL) {
20905 		ipsec_mp = mp;
20906 		mp = mp->b_cont;
20907 		mctl_present = B_TRUE;
20908 	} else {
20909 		ipsec_mp = mp;
20910 		mctl_present = B_FALSE;
20911 	}
20912 
20913 	if (str && q && tcp_dbg) {
20914 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
20915 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
20916 		    "flags 0x%x",
20917 		    str, seq, ack, ctl);
20918 	}
20919 	if (mp->b_datap->db_ref != 1) {
20920 		mblk_t *mp1 = copyb(mp);
20921 		freemsg(mp);
20922 		mp = mp1;
20923 		if (!mp) {
20924 			if (mctl_present)
20925 				freeb(ipsec_mp);
20926 			return;
20927 		} else {
20928 			if (mctl_present) {
20929 				ipsec_mp->b_cont = mp;
20930 			} else {
20931 				ipsec_mp = mp;
20932 			}
20933 		}
20934 	} else if (mp->b_cont) {
20935 		freemsg(mp->b_cont);
20936 		mp->b_cont = NULL;
20937 	}
20938 	/*
20939 	 * We skip reversing source route here.
20940 	 * (for now we replace all IP options with EOL)
20941 	 */
20942 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
20943 		ipha = (ipha_t *)mp->b_rptr;
20944 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
20945 			mp->b_rptr[i] = IPOPT_EOL;
20946 		/*
20947 		 * Make sure that src address isn't flagrantly invalid.
20948 		 * Not all broadcast address checking for the src address
20949 		 * is possible, since we don't know the netmask of the src
20950 		 * addr.  No check for destination address is done, since
20951 		 * IP will not pass up a packet with a broadcast dest
20952 		 * address to TCP.  Similar checks are done below for IPv6.
20953 		 */
20954 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
20955 		    CLASSD(ipha->ipha_src)) {
20956 			freemsg(ipsec_mp);
20957 			BUMP_MIB(&ip_mib, ipInDiscards);
20958 			return;
20959 		}
20960 	} else {
20961 		ip6h = (ip6_t *)mp->b_rptr;
20962 
20963 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
20964 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
20965 			freemsg(ipsec_mp);
20966 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
20967 			return;
20968 		}
20969 
20970 		/* Remove any extension headers assuming partial overlay */
20971 		if (ip_hdr_len > IPV6_HDR_LEN) {
20972 			uint8_t *to;
20973 
20974 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
20975 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
20976 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
20977 			ip_hdr_len = IPV6_HDR_LEN;
20978 			ip6h = (ip6_t *)mp->b_rptr;
20979 			ip6h->ip6_nxt = IPPROTO_TCP;
20980 		}
20981 	}
20982 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
20983 	if (tcph->th_flags[0] & TH_RST) {
20984 		freemsg(ipsec_mp);
20985 		return;
20986 	}
20987 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
20988 	len = ip_hdr_len + sizeof (tcph_t);
20989 	mp->b_wptr = &mp->b_rptr[len];
20990 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
20991 		ipha->ipha_length = htons(len);
20992 		/* Swap addresses */
20993 		v4addr = ipha->ipha_src;
20994 		ipha->ipha_src = ipha->ipha_dst;
20995 		ipha->ipha_dst = v4addr;
20996 		ipha->ipha_ident = 0;
20997 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
20998 		addr_len = IP_ADDR_LEN;
20999 		addr = &v4addr;
21000 	} else {
21001 		/* No ip6i_t in this case */
21002 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
21003 		/* Swap addresses */
21004 		v6addr = ip6h->ip6_src;
21005 		ip6h->ip6_src = ip6h->ip6_dst;
21006 		ip6h->ip6_dst = v6addr;
21007 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21008 		addr_len = IPV6_ADDR_LEN;
21009 		addr = &v6addr;
21010 	}
21011 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21012 	U32_TO_BE32(ack, tcph->th_ack);
21013 	U32_TO_BE32(seq, tcph->th_seq);
21014 	U16_TO_BE16(0, tcph->th_win);
21015 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21016 	tcph->th_flags[0] = (uint8_t)ctl;
21017 	if (ctl & TH_RST) {
21018 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21019 		BUMP_MIB(&tcp_mib, tcpOutControl);
21020 	}
21021 	if (mctl_present) {
21022 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21023 
21024 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21025 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21026 			return;
21027 		}
21028 	}
21029 	/*
21030 	 * NOTE:  one might consider tracing a TCP packet here, but
21031 	 * this function has no active TCP state nd no tcp structure
21032 	 * which has trace buffer.  If we traced here, we would have
21033 	 * to keep a local trace buffer in tcp_record_trace().
21034 	 */
21035 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21036 
21037 	/*
21038 	 * Tell IP to mark the IRE used for this destination temporary.
21039 	 * This way, we can limit our exposure to DoS attack because IP
21040 	 * creates an IRE for each destination.  If there are too many,
21041 	 * the time to do any routing lookup will be extremely long.  And
21042 	 * the lookup can be in interrupt context.
21043 	 *
21044 	 * Note that in normal circumstances, this marking should not
21045 	 * affect anything.  It would be nice if only 1 message is
21046 	 * needed to inform IP that the IRE created for this RST should
21047 	 * not be added to the cache table.  But there is currently
21048 	 * not such communication mechanism between TCP and IP.  So
21049 	 * the best we can do now is to send the advice ioctl to IP
21050 	 * to mark the IRE temporary.
21051 	 */
21052 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21053 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21054 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21055 	}
21056 }
21057 
21058 /*
21059  * Initiate closedown sequence on an active connection.  (May be called as
21060  * writer.)  Return value zero for OK return, non-zero for error return.
21061  */
21062 static int
21063 tcp_xmit_end(tcp_t *tcp)
21064 {
21065 	ipic_t	*ipic;
21066 	mblk_t	*mp;
21067 
21068 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21069 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21070 		/*
21071 		 * Invalid state, only states TCPS_SYN_RCVD,
21072 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21073 		 */
21074 		return (-1);
21075 	}
21076 
21077 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21078 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21079 	/*
21080 	 * If there is nothing more unsent, send the FIN now.
21081 	 * Otherwise, it will go out with the last segment.
21082 	 */
21083 	if (tcp->tcp_unsent == 0) {
21084 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21085 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21086 
21087 		if (mp) {
21088 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21089 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21090 		} else {
21091 			/*
21092 			 * Couldn't allocate msg.  Pretend we got it out.
21093 			 * Wait for rexmit timeout.
21094 			 */
21095 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21096 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21097 		}
21098 
21099 		/*
21100 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21101 		 * changed.
21102 		 */
21103 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21104 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21105 		}
21106 	} else {
21107 		/*
21108 		 * If tcp->tcp_cork is set, then the data will not get sent,
21109 		 * so we have to check that and unset it first.
21110 		 */
21111 		if (tcp->tcp_cork)
21112 			tcp->tcp_cork = B_FALSE;
21113 		tcp_wput_data(tcp, NULL, B_FALSE);
21114 	}
21115 
21116 	/*
21117 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
21118 	 * is 0, don't update the cache.
21119 	 */
21120 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
21121 		return (0);
21122 
21123 	/*
21124 	 * NOTE: should not update if source routes i.e. if tcp_remote if
21125 	 * different from the destination.
21126 	 */
21127 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21128 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
21129 			return (0);
21130 		}
21131 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21132 		    &ipic);
21133 	} else {
21134 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
21135 		    &tcp->tcp_ip6h->ip6_dst))) {
21136 			return (0);
21137 		}
21138 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21139 		    &ipic);
21140 	}
21141 
21142 	/* Record route attributes in the IRE for use by future connections. */
21143 	if (mp == NULL)
21144 		return (0);
21145 
21146 	/*
21147 	 * We do not have a good algorithm to update ssthresh at this time.
21148 	 * So don't do any update.
21149 	 */
21150 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
21151 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
21152 
21153 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21154 	return (0);
21155 }
21156 
21157 /*
21158  * Generate a "no listener here" RST in response to an "unknown" segment.
21159  * Note that we are reusing the incoming mp to construct the outgoing
21160  * RST.
21161  */
21162 void
21163 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len)
21164 {
21165 	uchar_t		*rptr;
21166 	uint32_t	seg_len;
21167 	tcph_t		*tcph;
21168 	uint32_t	seg_seq;
21169 	uint32_t	seg_ack;
21170 	uint_t		flags;
21171 	mblk_t		*ipsec_mp;
21172 	ipha_t 		*ipha;
21173 	ip6_t 		*ip6h;
21174 	boolean_t	mctl_present = B_FALSE;
21175 	boolean_t	check = B_TRUE;
21176 	boolean_t	policy_present;
21177 
21178 	TCP_STAT(tcp_no_listener);
21179 
21180 	ipsec_mp = mp;
21181 
21182 	if (mp->b_datap->db_type == M_CTL) {
21183 		ipsec_in_t *ii;
21184 
21185 		mctl_present = B_TRUE;
21186 		mp = mp->b_cont;
21187 
21188 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21189 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21190 		if (ii->ipsec_in_dont_check) {
21191 			check = B_FALSE;
21192 			if (!ii->ipsec_in_secure) {
21193 				freeb(ipsec_mp);
21194 				mctl_present = B_FALSE;
21195 				ipsec_mp = mp;
21196 			}
21197 		}
21198 	}
21199 
21200 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21201 		policy_present = ipsec_inbound_v4_policy_present;
21202 		ipha = (ipha_t *)mp->b_rptr;
21203 		ip6h = NULL;
21204 	} else {
21205 		policy_present = ipsec_inbound_v6_policy_present;
21206 		ipha = NULL;
21207 		ip6h = (ip6_t *)mp->b_rptr;
21208 	}
21209 
21210 	if (check && policy_present) {
21211 		/*
21212 		 * The conn_t parameter is NULL because we already know
21213 		 * nobody's home.
21214 		 */
21215 		ipsec_mp = ipsec_check_global_policy(
21216 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
21217 		if (ipsec_mp == NULL)
21218 			return;
21219 	}
21220 
21221 
21222 	rptr = mp->b_rptr;
21223 
21224 	tcph = (tcph_t *)&rptr[ip_hdr_len];
21225 	seg_seq = BE32_TO_U32(tcph->th_seq);
21226 	seg_ack = BE32_TO_U32(tcph->th_ack);
21227 	flags = tcph->th_flags[0];
21228 
21229 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
21230 	if (flags & TH_RST) {
21231 		freemsg(ipsec_mp);
21232 	} else if (flags & TH_ACK) {
21233 		tcp_xmit_early_reset("no tcp, reset",
21234 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len);
21235 	} else {
21236 		if (flags & TH_SYN) {
21237 			seg_len++;
21238 		} else {
21239 			/*
21240 			 * Here we violate the RFC.  Note that a normal
21241 			 * TCP will never send a segment without the ACK
21242 			 * flag, except for RST or SYN segment.  This
21243 			 * segment is neither.  Just drop it on the
21244 			 * floor.
21245 			 */
21246 			freemsg(ipsec_mp);
21247 			tcp_rst_unsent++;
21248 			return;
21249 		}
21250 
21251 		tcp_xmit_early_reset("no tcp, reset/ack",
21252 		    ipsec_mp, 0, seg_seq + seg_len,
21253 		    TH_RST | TH_ACK, ip_hdr_len);
21254 	}
21255 }
21256 
21257 /*
21258  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
21259  * ip and tcp header ready to pass down to IP.  If the mp passed in is
21260  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
21261  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
21262  * otherwise it will dup partial mblks.)
21263  * Otherwise, an appropriate ACK packet will be generated.  This
21264  * routine is not usually called to send new data for the first time.  It
21265  * is mostly called out of the timer for retransmits, and to generate ACKs.
21266  *
21267  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
21268  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
21269  * of the original mblk chain will be returned in *offset and *end_mp.
21270  */
21271 static mblk_t *
21272 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
21273     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
21274     boolean_t rexmit)
21275 {
21276 	int	data_length;
21277 	int32_t	off = 0;
21278 	uint_t	flags;
21279 	mblk_t	*mp1;
21280 	mblk_t	*mp2;
21281 	uchar_t	*rptr;
21282 	tcph_t	*tcph;
21283 	int32_t	num_sack_blk = 0;
21284 	int32_t	sack_opt_len = 0;
21285 
21286 	/* Allocate for our maximum TCP header + link-level */
21287 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21288 	    BPRI_MED);
21289 	if (!mp1)
21290 		return (NULL);
21291 	data_length = 0;
21292 
21293 	/*
21294 	 * Note that tcp_mss has been adjusted to take into account the
21295 	 * timestamp option if applicable.  Because SACK options do not
21296 	 * appear in every TCP segments and they are of variable lengths,
21297 	 * they cannot be included in tcp_mss.  Thus we need to calculate
21298 	 * the actual segment length when we need to send a segment which
21299 	 * includes SACK options.
21300 	 */
21301 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21302 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21303 		    tcp->tcp_num_sack_blk);
21304 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21305 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21306 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
21307 			max_to_send -= sack_opt_len;
21308 	}
21309 
21310 	if (offset != NULL) {
21311 		off = *offset;
21312 		/* We use offset as an indicator that end_mp is not NULL. */
21313 		*end_mp = NULL;
21314 	}
21315 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
21316 		/* This could be faster with cooperation from downstream */
21317 		if (mp2 != mp1 && !sendall &&
21318 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
21319 		    max_to_send)
21320 			/*
21321 			 * Don't send the next mblk since the whole mblk
21322 			 * does not fit.
21323 			 */
21324 			break;
21325 		mp2->b_cont = dupb(mp);
21326 		mp2 = mp2->b_cont;
21327 		if (!mp2) {
21328 			freemsg(mp1);
21329 			return (NULL);
21330 		}
21331 		mp2->b_rptr += off;
21332 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
21333 		    (uintptr_t)INT_MAX);
21334 
21335 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
21336 		if (data_length > max_to_send) {
21337 			mp2->b_wptr -= data_length - max_to_send;
21338 			data_length = max_to_send;
21339 			off = mp2->b_wptr - mp->b_rptr;
21340 			break;
21341 		} else {
21342 			off = 0;
21343 		}
21344 	}
21345 	if (offset != NULL) {
21346 		*offset = off;
21347 		*end_mp = mp;
21348 	}
21349 	if (seg_len != NULL) {
21350 		*seg_len = data_length;
21351 	}
21352 
21353 	/* Update the latest receive window size in TCP header. */
21354 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21355 	    tcp->tcp_tcph->th_win);
21356 
21357 	rptr = mp1->b_rptr + tcp_wroff_xtra;
21358 	mp1->b_rptr = rptr;
21359 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
21360 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21361 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21362 	U32_TO_ABE32(seq, tcph->th_seq);
21363 
21364 	/*
21365 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
21366 	 * that this function was called from tcp_wput_data. Thus, when called
21367 	 * to retransmit data the setting of the PUSH bit may appear some
21368 	 * what random in that it might get set when it should not. This
21369 	 * should not pose any performance issues.
21370 	 */
21371 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
21372 	    tcp->tcp_unsent == data_length)) {
21373 		flags = TH_ACK | TH_PUSH;
21374 	} else {
21375 		flags = TH_ACK;
21376 	}
21377 
21378 	if (tcp->tcp_ecn_ok) {
21379 		if (tcp->tcp_ecn_echo_on)
21380 			flags |= TH_ECE;
21381 
21382 		/*
21383 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
21384 		 * There is no TCP flow control for non-data segments, and
21385 		 * only data segment is transmitted reliably.
21386 		 */
21387 		if (data_length > 0 && !rexmit) {
21388 			SET_ECT(tcp, rptr);
21389 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
21390 				flags |= TH_CWR;
21391 				tcp->tcp_ecn_cwr_sent = B_TRUE;
21392 			}
21393 		}
21394 	}
21395 
21396 	if (tcp->tcp_valid_bits) {
21397 		uint32_t u1;
21398 
21399 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
21400 		    seq == tcp->tcp_iss) {
21401 			uchar_t	*wptr;
21402 
21403 			/*
21404 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
21405 			 * TCP can only be in SYN-SENT, SYN-RCVD or
21406 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
21407 			 * our SYN is not ack'ed but the app closes this
21408 			 * TCP connection.
21409 			 */
21410 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
21411 			    tcp->tcp_state == TCPS_SYN_RCVD ||
21412 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
21413 
21414 			/*
21415 			 * Tack on the MSS option.  It is always needed
21416 			 * for both active and passive open.
21417 			 *
21418 			 * MSS option value should be interface MTU - MIN
21419 			 * TCP/IP header according to RFC 793 as it means
21420 			 * the maximum segment size TCP can receive.  But
21421 			 * to get around some broken middle boxes/end hosts
21422 			 * out there, we allow the option value to be the
21423 			 * same as the MSS option size on the peer side.
21424 			 * In this way, the other side will not send
21425 			 * anything larger than they can receive.
21426 			 *
21427 			 * Note that for SYN_SENT state, the ndd param
21428 			 * tcp_use_smss_as_mss_opt has no effect as we
21429 			 * don't know the peer's MSS option value. So
21430 			 * the only case we need to take care of is in
21431 			 * SYN_RCVD state, which is done later.
21432 			 */
21433 			wptr = mp1->b_wptr;
21434 			wptr[0] = TCPOPT_MAXSEG;
21435 			wptr[1] = TCPOPT_MAXSEG_LEN;
21436 			wptr += 2;
21437 			u1 = tcp->tcp_if_mtu -
21438 			    (tcp->tcp_ipversion == IPV4_VERSION ?
21439 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
21440 			    TCP_MIN_HEADER_LENGTH;
21441 			U16_TO_BE16(u1, wptr);
21442 			mp1->b_wptr = wptr + 2;
21443 			/* Update the offset to cover the additional word */
21444 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
21445 
21446 			/*
21447 			 * Note that the following way of filling in
21448 			 * TCP options are not optimal.  Some NOPs can
21449 			 * be saved.  But there is no need at this time
21450 			 * to optimize it.  When it is needed, we will
21451 			 * do it.
21452 			 */
21453 			switch (tcp->tcp_state) {
21454 			case TCPS_SYN_SENT:
21455 				flags = TH_SYN;
21456 
21457 				if (tcp->tcp_snd_ts_ok) {
21458 					uint32_t llbolt = (uint32_t)lbolt;
21459 
21460 					wptr = mp1->b_wptr;
21461 					wptr[0] = TCPOPT_NOP;
21462 					wptr[1] = TCPOPT_NOP;
21463 					wptr[2] = TCPOPT_TSTAMP;
21464 					wptr[3] = TCPOPT_TSTAMP_LEN;
21465 					wptr += 4;
21466 					U32_TO_BE32(llbolt, wptr);
21467 					wptr += 4;
21468 					ASSERT(tcp->tcp_ts_recent == 0);
21469 					U32_TO_BE32(0L, wptr);
21470 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
21471 					tcph->th_offset_and_rsrvd[0] +=
21472 					    (3 << 4);
21473 				}
21474 
21475 				/*
21476 				 * Set up all the bits to tell other side
21477 				 * we are ECN capable.
21478 				 */
21479 				if (tcp->tcp_ecn_ok) {
21480 					flags |= (TH_ECE | TH_CWR);
21481 				}
21482 				break;
21483 			case TCPS_SYN_RCVD:
21484 				flags |= TH_SYN;
21485 
21486 				/*
21487 				 * Reset the MSS option value to be SMSS
21488 				 * We should probably add back the bytes
21489 				 * for timestamp option and IPsec.  We
21490 				 * don't do that as this is a workaround
21491 				 * for broken middle boxes/end hosts, it
21492 				 * is better for us to be more cautious.
21493 				 * They may not take these things into
21494 				 * account in their SMSS calculation.  Thus
21495 				 * the peer's calculated SMSS may be smaller
21496 				 * than what it can be.  This should be OK.
21497 				 */
21498 				if (tcp_use_smss_as_mss_opt) {
21499 					u1 = tcp->tcp_mss;
21500 					U16_TO_BE16(u1, wptr);
21501 				}
21502 
21503 				/*
21504 				 * If the other side is ECN capable, reply
21505 				 * that we are also ECN capable.
21506 				 */
21507 				if (tcp->tcp_ecn_ok)
21508 					flags |= TH_ECE;
21509 				break;
21510 			default:
21511 				/*
21512 				 * The above ASSERT() makes sure that this
21513 				 * must be FIN-WAIT-1 state.  Our SYN has
21514 				 * not been ack'ed so retransmit it.
21515 				 */
21516 				flags |= TH_SYN;
21517 				break;
21518 			}
21519 
21520 			if (tcp->tcp_snd_ws_ok) {
21521 				wptr = mp1->b_wptr;
21522 				wptr[0] =  TCPOPT_NOP;
21523 				wptr[1] =  TCPOPT_WSCALE;
21524 				wptr[2] =  TCPOPT_WS_LEN;
21525 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
21526 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
21527 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
21528 			}
21529 
21530 			if (tcp->tcp_snd_sack_ok) {
21531 				wptr = mp1->b_wptr;
21532 				wptr[0] = TCPOPT_NOP;
21533 				wptr[1] = TCPOPT_NOP;
21534 				wptr[2] = TCPOPT_SACK_PERMITTED;
21535 				wptr[3] = TCPOPT_SACK_OK_LEN;
21536 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
21537 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
21538 			}
21539 
21540 			/* allocb() of adequate mblk assures space */
21541 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
21542 			    (uintptr_t)INT_MAX);
21543 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
21544 			/*
21545 			 * Get IP set to checksum on our behalf
21546 			 * Include the adjustment for a source route if any.
21547 			 */
21548 			u1 += tcp->tcp_sum;
21549 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
21550 			U16_TO_BE16(u1, tcph->th_sum);
21551 			BUMP_MIB(&tcp_mib, tcpOutControl);
21552 		}
21553 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
21554 		    (seq + data_length) == tcp->tcp_fss) {
21555 			if (!tcp->tcp_fin_acked) {
21556 				flags |= TH_FIN;
21557 				BUMP_MIB(&tcp_mib, tcpOutControl);
21558 			}
21559 			if (!tcp->tcp_fin_sent) {
21560 				tcp->tcp_fin_sent = B_TRUE;
21561 				switch (tcp->tcp_state) {
21562 				case TCPS_SYN_RCVD:
21563 				case TCPS_ESTABLISHED:
21564 					tcp->tcp_state = TCPS_FIN_WAIT_1;
21565 					break;
21566 				case TCPS_CLOSE_WAIT:
21567 					tcp->tcp_state = TCPS_LAST_ACK;
21568 					break;
21569 				}
21570 				if (tcp->tcp_suna == tcp->tcp_snxt)
21571 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21572 				tcp->tcp_snxt = tcp->tcp_fss + 1;
21573 			}
21574 		}
21575 		/*
21576 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
21577 		 * is smaller than seq, u1 will become a very huge value.
21578 		 * So the comparison will fail.  Also note that tcp_urp
21579 		 * should be positive, see RFC 793 page 17.
21580 		 */
21581 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
21582 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
21583 		    u1 < (uint32_t)(64 * 1024)) {
21584 			flags |= TH_URG;
21585 			BUMP_MIB(&tcp_mib, tcpOutUrg);
21586 			U32_TO_ABE16(u1, tcph->th_urp);
21587 		}
21588 	}
21589 	tcph->th_flags[0] = (uchar_t)flags;
21590 	tcp->tcp_rack = tcp->tcp_rnxt;
21591 	tcp->tcp_rack_cnt = 0;
21592 
21593 	if (tcp->tcp_snd_ts_ok) {
21594 		if (tcp->tcp_state != TCPS_SYN_SENT) {
21595 			uint32_t llbolt = (uint32_t)lbolt;
21596 
21597 			U32_TO_BE32(llbolt,
21598 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21599 			U32_TO_BE32(tcp->tcp_ts_recent,
21600 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21601 		}
21602 	}
21603 
21604 	if (num_sack_blk > 0) {
21605 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
21606 		sack_blk_t *tmp;
21607 		int32_t	i;
21608 
21609 		wptr[0] = TCPOPT_NOP;
21610 		wptr[1] = TCPOPT_NOP;
21611 		wptr[2] = TCPOPT_SACK;
21612 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
21613 		    sizeof (sack_blk_t);
21614 		wptr += TCPOPT_REAL_SACK_LEN;
21615 
21616 		tmp = tcp->tcp_sack_list;
21617 		for (i = 0; i < num_sack_blk; i++) {
21618 			U32_TO_BE32(tmp[i].begin, wptr);
21619 			wptr += sizeof (tcp_seq);
21620 			U32_TO_BE32(tmp[i].end, wptr);
21621 			wptr += sizeof (tcp_seq);
21622 		}
21623 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
21624 	}
21625 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21626 	data_length += (int)(mp1->b_wptr - rptr);
21627 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21628 		((ipha_t *)rptr)->ipha_length = htons(data_length);
21629 	} else {
21630 		ip6_t *ip6 = (ip6_t *)(rptr +
21631 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
21632 		    sizeof (ip6i_t) : 0));
21633 
21634 		ip6->ip6_plen = htons(data_length -
21635 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21636 	}
21637 
21638 	/*
21639 	 * Prime pump for IP
21640 	 * Include the adjustment for a source route if any.
21641 	 */
21642 	data_length -= tcp->tcp_ip_hdr_len;
21643 	data_length += tcp->tcp_sum;
21644 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
21645 	U16_TO_ABE16(data_length, tcph->th_sum);
21646 	if (tcp->tcp_ip_forward_progress) {
21647 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21648 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
21649 		tcp->tcp_ip_forward_progress = B_FALSE;
21650 	}
21651 	return (mp1);
21652 }
21653 
21654 /* This function handles the push timeout. */
21655 void
21656 tcp_push_timer(void *arg)
21657 {
21658 	conn_t	*connp = (conn_t *)arg;
21659 	tcp_t *tcp = connp->conn_tcp;
21660 
21661 	TCP_DBGSTAT(tcp_push_timer_cnt);
21662 
21663 	ASSERT(tcp->tcp_listener == NULL);
21664 
21665 	/*
21666 	 * We need to stop synchronous streams temporarily to prevent a race
21667 	 * with tcp_fuse_rrw() or tcp_fusion rinfop().  It is safe to access
21668 	 * tcp_rcv_list here because those entry points will return right
21669 	 * away when synchronous streams is stopped.
21670 	 */
21671 	TCP_FUSE_SYNCSTR_STOP(tcp);
21672 	tcp->tcp_push_tid = 0;
21673 	if ((tcp->tcp_rcv_list != NULL) &&
21674 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
21675 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21676 	TCP_FUSE_SYNCSTR_RESUME(tcp);
21677 }
21678 
21679 /*
21680  * This function handles delayed ACK timeout.
21681  */
21682 static void
21683 tcp_ack_timer(void *arg)
21684 {
21685 	conn_t	*connp = (conn_t *)arg;
21686 	tcp_t *tcp = connp->conn_tcp;
21687 	mblk_t *mp;
21688 
21689 	TCP_DBGSTAT(tcp_ack_timer_cnt);
21690 
21691 	tcp->tcp_ack_tid = 0;
21692 
21693 	if (tcp->tcp_fused)
21694 		return;
21695 
21696 	/*
21697 	 * Do not send ACK if there is no outstanding unack'ed data.
21698 	 */
21699 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
21700 		return;
21701 	}
21702 
21703 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
21704 		/*
21705 		 * Make sure we don't allow deferred ACKs to result in
21706 		 * timer-based ACKing.  If we have held off an ACK
21707 		 * when there was more than an mss here, and the timer
21708 		 * goes off, we have to worry about the possibility
21709 		 * that the sender isn't doing slow-start, or is out
21710 		 * of step with us for some other reason.  We fall
21711 		 * permanently back in the direction of
21712 		 * ACK-every-other-packet as suggested in RFC 1122.
21713 		 */
21714 		if (tcp->tcp_rack_abs_max > 2)
21715 			tcp->tcp_rack_abs_max--;
21716 		tcp->tcp_rack_cur_max = 2;
21717 	}
21718 	mp = tcp_ack_mp(tcp);
21719 
21720 	if (mp != NULL) {
21721 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21722 		BUMP_LOCAL(tcp->tcp_obsegs);
21723 		BUMP_MIB(&tcp_mib, tcpOutAck);
21724 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
21725 		tcp_send_data(tcp, tcp->tcp_wq, mp);
21726 	}
21727 }
21728 
21729 
21730 /* Generate an ACK-only (no data) segment for a TCP endpoint */
21731 static mblk_t *
21732 tcp_ack_mp(tcp_t *tcp)
21733 {
21734 	uint32_t	seq_no;
21735 
21736 	/*
21737 	 * There are a few cases to be considered while setting the sequence no.
21738 	 * Essentially, we can come here while processing an unacceptable pkt
21739 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
21740 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
21741 	 * If we are here for a zero window probe, stick with suna. In all
21742 	 * other cases, we check if suna + swnd encompasses snxt and set
21743 	 * the sequence number to snxt, if so. If snxt falls outside the
21744 	 * window (the receiver probably shrunk its window), we will go with
21745 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
21746 	 * receiver.
21747 	 */
21748 	if (tcp->tcp_zero_win_probe) {
21749 		seq_no = tcp->tcp_suna;
21750 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
21751 		ASSERT(tcp->tcp_swnd == 0);
21752 		seq_no = tcp->tcp_snxt;
21753 	} else {
21754 		seq_no = SEQ_GT(tcp->tcp_snxt,
21755 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
21756 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
21757 	}
21758 
21759 	if (tcp->tcp_valid_bits) {
21760 		/*
21761 		 * For the complex case where we have to send some
21762 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
21763 		 */
21764 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
21765 		    NULL, B_FALSE));
21766 	} else {
21767 		/* Generate a simple ACK */
21768 		int	data_length;
21769 		uchar_t	*rptr;
21770 		tcph_t	*tcph;
21771 		mblk_t	*mp1;
21772 		int32_t	tcp_hdr_len;
21773 		int32_t	tcp_tcp_hdr_len;
21774 		int32_t	num_sack_blk = 0;
21775 		int32_t sack_opt_len;
21776 
21777 		/*
21778 		 * Allocate space for TCP + IP headers
21779 		 * and link-level header
21780 		 */
21781 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21782 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21783 			    tcp->tcp_num_sack_blk);
21784 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21785 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21786 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
21787 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
21788 		} else {
21789 			tcp_hdr_len = tcp->tcp_hdr_len;
21790 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
21791 		}
21792 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
21793 		if (!mp1)
21794 			return (NULL);
21795 
21796 		/* Update the latest receive window size in TCP header. */
21797 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21798 		    tcp->tcp_tcph->th_win);
21799 		/* copy in prototype TCP + IP header */
21800 		rptr = mp1->b_rptr + tcp_wroff_xtra;
21801 		mp1->b_rptr = rptr;
21802 		mp1->b_wptr = rptr + tcp_hdr_len;
21803 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21804 
21805 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21806 
21807 		/* Set the TCP sequence number. */
21808 		U32_TO_ABE32(seq_no, tcph->th_seq);
21809 
21810 		/* Set up the TCP flag field. */
21811 		tcph->th_flags[0] = (uchar_t)TH_ACK;
21812 		if (tcp->tcp_ecn_echo_on)
21813 			tcph->th_flags[0] |= TH_ECE;
21814 
21815 		tcp->tcp_rack = tcp->tcp_rnxt;
21816 		tcp->tcp_rack_cnt = 0;
21817 
21818 		/* fill in timestamp option if in use */
21819 		if (tcp->tcp_snd_ts_ok) {
21820 			uint32_t llbolt = (uint32_t)lbolt;
21821 
21822 			U32_TO_BE32(llbolt,
21823 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21824 			U32_TO_BE32(tcp->tcp_ts_recent,
21825 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21826 		}
21827 
21828 		/* Fill in SACK options */
21829 		if (num_sack_blk > 0) {
21830 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
21831 			sack_blk_t *tmp;
21832 			int32_t	i;
21833 
21834 			wptr[0] = TCPOPT_NOP;
21835 			wptr[1] = TCPOPT_NOP;
21836 			wptr[2] = TCPOPT_SACK;
21837 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
21838 			    sizeof (sack_blk_t);
21839 			wptr += TCPOPT_REAL_SACK_LEN;
21840 
21841 			tmp = tcp->tcp_sack_list;
21842 			for (i = 0; i < num_sack_blk; i++) {
21843 				U32_TO_BE32(tmp[i].begin, wptr);
21844 				wptr += sizeof (tcp_seq);
21845 				U32_TO_BE32(tmp[i].end, wptr);
21846 				wptr += sizeof (tcp_seq);
21847 			}
21848 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
21849 			    << 4);
21850 		}
21851 
21852 		if (tcp->tcp_ipversion == IPV4_VERSION) {
21853 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
21854 		} else {
21855 			/* Check for ip6i_t header in sticky hdrs */
21856 			ip6_t *ip6 = (ip6_t *)(rptr +
21857 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
21858 			    sizeof (ip6i_t) : 0));
21859 
21860 			ip6->ip6_plen = htons(tcp_hdr_len -
21861 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21862 		}
21863 
21864 		/*
21865 		 * Prime pump for checksum calculation in IP.  Include the
21866 		 * adjustment for a source route if any.
21867 		 */
21868 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
21869 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
21870 		U16_TO_ABE16(data_length, tcph->th_sum);
21871 
21872 		if (tcp->tcp_ip_forward_progress) {
21873 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21874 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
21875 			tcp->tcp_ip_forward_progress = B_FALSE;
21876 		}
21877 		return (mp1);
21878 	}
21879 }
21880 
21881 /*
21882  * To create a temporary tcp structure for inserting into bind hash list.
21883  * The parameter is assumed to be in network byte order, ready for use.
21884  */
21885 /* ARGSUSED */
21886 static tcp_t *
21887 tcp_alloc_temp_tcp(in_port_t port)
21888 {
21889 	conn_t	*connp;
21890 	tcp_t	*tcp;
21891 
21892 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
21893 	if (connp == NULL)
21894 		return (NULL);
21895 
21896 	tcp = connp->conn_tcp;
21897 
21898 	/*
21899 	 * Only initialize the necessary info in those structures.  Note
21900 	 * that since INADDR_ANY is all 0, we do not need to set
21901 	 * tcp_bound_source to INADDR_ANY here.
21902 	 */
21903 	tcp->tcp_state = TCPS_BOUND;
21904 	tcp->tcp_lport = port;
21905 	tcp->tcp_exclbind = 1;
21906 	tcp->tcp_reserved_port = 1;
21907 
21908 	/* Just for place holding... */
21909 	tcp->tcp_ipversion = IPV4_VERSION;
21910 
21911 	return (tcp);
21912 }
21913 
21914 /*
21915  * To remove a port range specified by lo_port and hi_port from the
21916  * reserved port ranges.  This is one of the three public functions of
21917  * the reserved port interface.  Note that a port range has to be removed
21918  * as a whole.  Ports in a range cannot be removed individually.
21919  *
21920  * Params:
21921  *	in_port_t lo_port: the beginning port of the reserved port range to
21922  *		be deleted.
21923  *	in_port_t hi_port: the ending port of the reserved port range to
21924  *		be deleted.
21925  *
21926  * Return:
21927  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
21928  */
21929 boolean_t
21930 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
21931 {
21932 	int	i, j;
21933 	int	size;
21934 	tcp_t	**temp_tcp_array;
21935 	tcp_t	*tcp;
21936 
21937 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
21938 
21939 	/* First make sure that the port ranage is indeed reserved. */
21940 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
21941 		if (tcp_reserved_port[i].lo_port == lo_port) {
21942 			hi_port = tcp_reserved_port[i].hi_port;
21943 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
21944 			break;
21945 		}
21946 	}
21947 	if (i == tcp_reserved_port_array_size) {
21948 		rw_exit(&tcp_reserved_port_lock);
21949 		return (B_FALSE);
21950 	}
21951 
21952 	/*
21953 	 * Remove the range from the array.  This simple loop is possible
21954 	 * because port ranges are inserted in ascending order.
21955 	 */
21956 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
21957 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
21958 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
21959 		tcp_reserved_port[j].temp_tcp_array =
21960 		    tcp_reserved_port[j+1].temp_tcp_array;
21961 	}
21962 
21963 	/* Remove all the temporary tcp structures. */
21964 	size = hi_port - lo_port + 1;
21965 	while (size > 0) {
21966 		tcp = temp_tcp_array[size - 1];
21967 		ASSERT(tcp != NULL);
21968 		tcp_bind_hash_remove(tcp);
21969 		CONN_DEC_REF(tcp->tcp_connp);
21970 		size--;
21971 	}
21972 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
21973 	tcp_reserved_port_array_size--;
21974 	rw_exit(&tcp_reserved_port_lock);
21975 	return (B_TRUE);
21976 }
21977 
21978 /*
21979  * Macro to remove temporary tcp structure from the bind hash list.  The
21980  * first parameter is the list of tcp to be removed.  The second parameter
21981  * is the number of tcps in the array.
21982  */
21983 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
21984 { \
21985 	while ((num) > 0) { \
21986 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
21987 		tf_t *tbf; \
21988 		tcp_t *tcpnext; \
21989 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
21990 		mutex_enter(&tbf->tf_lock); \
21991 		tcpnext = tcp->tcp_bind_hash; \
21992 		if (tcpnext) { \
21993 			tcpnext->tcp_ptpbhn = \
21994 				tcp->tcp_ptpbhn; \
21995 		} \
21996 		*tcp->tcp_ptpbhn = tcpnext; \
21997 		mutex_exit(&tbf->tf_lock); \
21998 		kmem_free(tcp, sizeof (tcp_t)); \
21999 		(tcp_array)[(num) - 1] = NULL; \
22000 		(num)--; \
22001 	} \
22002 }
22003 
22004 /*
22005  * The public interface for other modules to call to reserve a port range
22006  * in TCP.  The caller passes in how large a port range it wants.  TCP
22007  * will try to find a range and return it via lo_port and hi_port.  This is
22008  * used by NCA's nca_conn_init.
22009  * NCA can only be used in the global zone so this only affects the global
22010  * zone's ports.
22011  *
22012  * Params:
22013  *	int size: the size of the port range to be reserved.
22014  *	in_port_t *lo_port (referenced): returns the beginning port of the
22015  *		reserved port range added.
22016  *	in_port_t *hi_port (referenced): returns the ending port of the
22017  *		reserved port range added.
22018  *
22019  * Return:
22020  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22021  */
22022 boolean_t
22023 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22024 {
22025 	tcp_t		*tcp;
22026 	tcp_t		*tmp_tcp;
22027 	tcp_t		**temp_tcp_array;
22028 	tf_t		*tbf;
22029 	in_port_t	net_port;
22030 	in_port_t	port;
22031 	int32_t		cur_size;
22032 	int		i, j;
22033 	boolean_t	used;
22034 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22035 	zoneid_t	zoneid = GLOBAL_ZONEID;
22036 
22037 	/* Sanity check. */
22038 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22039 		return (B_FALSE);
22040 	}
22041 
22042 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22043 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22044 		rw_exit(&tcp_reserved_port_lock);
22045 		return (B_FALSE);
22046 	}
22047 
22048 	/*
22049 	 * Find the starting port to try.  Since the port ranges are ordered
22050 	 * in the reserved port array, we can do a simple search here.
22051 	 */
22052 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22053 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22054 	for (i = 0; i < tcp_reserved_port_array_size;
22055 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22056 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22057 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22058 			break;
22059 		}
22060 	}
22061 	/* No available port range. */
22062 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22063 		rw_exit(&tcp_reserved_port_lock);
22064 		return (B_FALSE);
22065 	}
22066 
22067 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22068 	if (temp_tcp_array == NULL) {
22069 		rw_exit(&tcp_reserved_port_lock);
22070 		return (B_FALSE);
22071 	}
22072 
22073 	/* Go thru the port range to see if some ports are already bound. */
22074 	for (port = *lo_port, cur_size = 0;
22075 	    cur_size < size && port <= *hi_port;
22076 	    cur_size++, port++) {
22077 		used = B_FALSE;
22078 		net_port = htons(port);
22079 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22080 		mutex_enter(&tbf->tf_lock);
22081 		for (tcp = tbf->tf_tcp; tcp != NULL;
22082 		    tcp = tcp->tcp_bind_hash) {
22083 			if (zoneid == tcp->tcp_connp->conn_zoneid &&
22084 			    net_port == tcp->tcp_lport) {
22085 				/*
22086 				 * A port is already bound.  Search again
22087 				 * starting from port + 1.  Release all
22088 				 * temporary tcps.
22089 				 */
22090 				mutex_exit(&tbf->tf_lock);
22091 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22092 				*lo_port = port + 1;
22093 				cur_size = -1;
22094 				used = B_TRUE;
22095 				break;
22096 			}
22097 		}
22098 		if (!used) {
22099 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22100 				/*
22101 				 * Allocation failure.  Just fail the request.
22102 				 * Need to remove all those temporary tcp
22103 				 * structures.
22104 				 */
22105 				mutex_exit(&tbf->tf_lock);
22106 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22107 				rw_exit(&tcp_reserved_port_lock);
22108 				kmem_free(temp_tcp_array,
22109 				    (hi_port - lo_port + 1) *
22110 				    sizeof (tcp_t *));
22111 				return (B_FALSE);
22112 			}
22113 			temp_tcp_array[cur_size] = tmp_tcp;
22114 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22115 			mutex_exit(&tbf->tf_lock);
22116 		}
22117 	}
22118 
22119 	/*
22120 	 * The current range is not large enough.  We can actually do another
22121 	 * search if this search is done between 2 reserved port ranges.  But
22122 	 * for first release, we just stop here and return saying that no port
22123 	 * range is available.
22124 	 */
22125 	if (cur_size < size) {
22126 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22127 		rw_exit(&tcp_reserved_port_lock);
22128 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
22129 		return (B_FALSE);
22130 	}
22131 	*hi_port = port - 1;
22132 
22133 	/*
22134 	 * Insert range into array in ascending order.  Since this function
22135 	 * must not be called often, we choose to use the simplest method.
22136 	 * The above array should not consume excessive stack space as
22137 	 * the size must be very small.  If in future releases, we find
22138 	 * that we should provide more reserved port ranges, this function
22139 	 * has to be modified to be more efficient.
22140 	 */
22141 	if (tcp_reserved_port_array_size == 0) {
22142 		tcp_reserved_port[0].lo_port = *lo_port;
22143 		tcp_reserved_port[0].hi_port = *hi_port;
22144 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
22145 	} else {
22146 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
22147 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
22148 				tmp_ports[j].lo_port = *lo_port;
22149 				tmp_ports[j].hi_port = *hi_port;
22150 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
22151 				j++;
22152 			}
22153 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
22154 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
22155 			tmp_ports[j].temp_tcp_array =
22156 			    tcp_reserved_port[i].temp_tcp_array;
22157 		}
22158 		if (j == i) {
22159 			tmp_ports[j].lo_port = *lo_port;
22160 			tmp_ports[j].hi_port = *hi_port;
22161 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
22162 		}
22163 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
22164 	}
22165 	tcp_reserved_port_array_size++;
22166 	rw_exit(&tcp_reserved_port_lock);
22167 	return (B_TRUE);
22168 }
22169 
22170 /*
22171  * Check to see if a port is in any reserved port range.
22172  *
22173  * Params:
22174  *	in_port_t port: the port to be verified.
22175  *
22176  * Return:
22177  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
22178  */
22179 boolean_t
22180 tcp_reserved_port_check(in_port_t port)
22181 {
22182 	int i;
22183 
22184 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22185 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22186 		if (port >= tcp_reserved_port[i].lo_port ||
22187 		    port <= tcp_reserved_port[i].hi_port) {
22188 			rw_exit(&tcp_reserved_port_lock);
22189 			return (B_TRUE);
22190 		}
22191 	}
22192 	rw_exit(&tcp_reserved_port_lock);
22193 	return (B_FALSE);
22194 }
22195 
22196 /*
22197  * To list all reserved port ranges.  This is the function to handle
22198  * ndd tcp_reserved_port_list.
22199  */
22200 /* ARGSUSED */
22201 static int
22202 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22203 {
22204 	int i;
22205 
22206 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22207 	if (tcp_reserved_port_array_size > 0)
22208 		(void) mi_mpprintf(mp, "The following ports are reserved:");
22209 	else
22210 		(void) mi_mpprintf(mp, "No port is reserved.");
22211 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22212 		(void) mi_mpprintf(mp, "%d-%d",
22213 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
22214 	}
22215 	rw_exit(&tcp_reserved_port_lock);
22216 	return (0);
22217 }
22218 
22219 /*
22220  * Hash list insertion routine for tcp_t structures.
22221  * Inserts entries with the ones bound to a specific IP address first
22222  * followed by those bound to INADDR_ANY.
22223  */
22224 static void
22225 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
22226 {
22227 	tcp_t	**tcpp;
22228 	tcp_t	*tcpnext;
22229 
22230 	if (tcp->tcp_ptpbhn != NULL) {
22231 		ASSERT(!caller_holds_lock);
22232 		tcp_bind_hash_remove(tcp);
22233 	}
22234 	tcpp = &tbf->tf_tcp;
22235 	if (!caller_holds_lock) {
22236 		mutex_enter(&tbf->tf_lock);
22237 	} else {
22238 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
22239 	}
22240 	tcpnext = tcpp[0];
22241 	if (tcpnext) {
22242 		/*
22243 		 * If the new tcp bound to the INADDR_ANY address
22244 		 * and the first one in the list is not bound to
22245 		 * INADDR_ANY we skip all entries until we find the
22246 		 * first one bound to INADDR_ANY.
22247 		 * This makes sure that applications binding to a
22248 		 * specific address get preference over those binding to
22249 		 * INADDR_ANY.
22250 		 */
22251 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
22252 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
22253 			while ((tcpnext = tcpp[0]) != NULL &&
22254 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
22255 				tcpp = &(tcpnext->tcp_bind_hash);
22256 			if (tcpnext)
22257 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22258 		} else
22259 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22260 	}
22261 	tcp->tcp_bind_hash = tcpnext;
22262 	tcp->tcp_ptpbhn = tcpp;
22263 	tcpp[0] = tcp;
22264 	if (!caller_holds_lock)
22265 		mutex_exit(&tbf->tf_lock);
22266 }
22267 
22268 /*
22269  * Hash list removal routine for tcp_t structures.
22270  */
22271 static void
22272 tcp_bind_hash_remove(tcp_t *tcp)
22273 {
22274 	tcp_t	*tcpnext;
22275 	kmutex_t *lockp;
22276 
22277 	if (tcp->tcp_ptpbhn == NULL)
22278 		return;
22279 
22280 	/*
22281 	 * Extract the lock pointer in case there are concurrent
22282 	 * hash_remove's for this instance.
22283 	 */
22284 	ASSERT(tcp->tcp_lport != 0);
22285 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
22286 
22287 	ASSERT(lockp != NULL);
22288 	mutex_enter(lockp);
22289 	if (tcp->tcp_ptpbhn) {
22290 		tcpnext = tcp->tcp_bind_hash;
22291 		if (tcpnext) {
22292 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
22293 			tcp->tcp_bind_hash = NULL;
22294 		}
22295 		*tcp->tcp_ptpbhn = tcpnext;
22296 		tcp->tcp_ptpbhn = NULL;
22297 	}
22298 	mutex_exit(lockp);
22299 }
22300 
22301 
22302 /*
22303  * Hash list lookup routine for tcp_t structures.
22304  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
22305  */
22306 static tcp_t *
22307 tcp_acceptor_hash_lookup(t_uscalar_t id)
22308 {
22309 	tf_t	*tf;
22310 	tcp_t	*tcp;
22311 
22312 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22313 	mutex_enter(&tf->tf_lock);
22314 	for (tcp = tf->tf_tcp; tcp != NULL;
22315 	    tcp = tcp->tcp_acceptor_hash) {
22316 		if (tcp->tcp_acceptor_id == id) {
22317 			CONN_INC_REF(tcp->tcp_connp);
22318 			mutex_exit(&tf->tf_lock);
22319 			return (tcp);
22320 		}
22321 	}
22322 	mutex_exit(&tf->tf_lock);
22323 	return (NULL);
22324 }
22325 
22326 
22327 /*
22328  * Hash list insertion routine for tcp_t structures.
22329  */
22330 void
22331 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
22332 {
22333 	tf_t	*tf;
22334 	tcp_t	**tcpp;
22335 	tcp_t	*tcpnext;
22336 
22337 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22338 
22339 	if (tcp->tcp_ptpahn != NULL)
22340 		tcp_acceptor_hash_remove(tcp);
22341 	tcpp = &tf->tf_tcp;
22342 	mutex_enter(&tf->tf_lock);
22343 	tcpnext = tcpp[0];
22344 	if (tcpnext)
22345 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
22346 	tcp->tcp_acceptor_hash = tcpnext;
22347 	tcp->tcp_ptpahn = tcpp;
22348 	tcpp[0] = tcp;
22349 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
22350 	mutex_exit(&tf->tf_lock);
22351 }
22352 
22353 /*
22354  * Hash list removal routine for tcp_t structures.
22355  */
22356 static void
22357 tcp_acceptor_hash_remove(tcp_t *tcp)
22358 {
22359 	tcp_t	*tcpnext;
22360 	kmutex_t *lockp;
22361 
22362 	/*
22363 	 * Extract the lock pointer in case there are concurrent
22364 	 * hash_remove's for this instance.
22365 	 */
22366 	lockp = tcp->tcp_acceptor_lockp;
22367 
22368 	if (tcp->tcp_ptpahn == NULL)
22369 		return;
22370 
22371 	ASSERT(lockp != NULL);
22372 	mutex_enter(lockp);
22373 	if (tcp->tcp_ptpahn) {
22374 		tcpnext = tcp->tcp_acceptor_hash;
22375 		if (tcpnext) {
22376 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
22377 			tcp->tcp_acceptor_hash = NULL;
22378 		}
22379 		*tcp->tcp_ptpahn = tcpnext;
22380 		tcp->tcp_ptpahn = NULL;
22381 	}
22382 	mutex_exit(lockp);
22383 	tcp->tcp_acceptor_lockp = NULL;
22384 }
22385 
22386 /* ARGSUSED */
22387 static int
22388 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
22389 {
22390 	int error = 0;
22391 	int retval;
22392 	char *end;
22393 
22394 	tcp_hsp_t *hsp;
22395 	tcp_hsp_t *hspprev;
22396 
22397 	ipaddr_t addr = 0;		/* Address we're looking for */
22398 	in6_addr_t v6addr;		/* Address we're looking for */
22399 	uint32_t hash;			/* Hash of that address */
22400 
22401 	/*
22402 	 * If the following variables are still zero after parsing the input
22403 	 * string, the user didn't specify them and we don't change them in
22404 	 * the HSP.
22405 	 */
22406 
22407 	ipaddr_t mask = 0;		/* Subnet mask */
22408 	in6_addr_t v6mask;
22409 	long sendspace = 0;		/* Send buffer size */
22410 	long recvspace = 0;		/* Receive buffer size */
22411 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
22412 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
22413 
22414 	rw_enter(&tcp_hsp_lock, RW_WRITER);
22415 
22416 	/* Parse and validate address */
22417 	if (af == AF_INET) {
22418 		retval = inet_pton(af, value, &addr);
22419 		if (retval == 1)
22420 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
22421 	} else if (af == AF_INET6) {
22422 		retval = inet_pton(af, value, &v6addr);
22423 	} else {
22424 		error = EINVAL;
22425 		goto done;
22426 	}
22427 	if (retval == 0) {
22428 		error = EINVAL;
22429 		goto done;
22430 	}
22431 
22432 	while ((*value) && *value != ' ')
22433 		value++;
22434 
22435 	/* Parse individual keywords, set variables if found */
22436 	while (*value) {
22437 		/* Skip leading blanks */
22438 
22439 		while (*value == ' ' || *value == '\t')
22440 			value++;
22441 
22442 		/* If at end of string, we're done */
22443 
22444 		if (!*value)
22445 			break;
22446 
22447 		/* We have a word, figure out what it is */
22448 
22449 		if (strncmp("mask", value, 4) == 0) {
22450 			value += 4;
22451 			while (*value == ' ' || *value == '\t')
22452 				value++;
22453 			/* Parse subnet mask */
22454 			if (af == AF_INET) {
22455 				retval = inet_pton(af, value, &mask);
22456 				if (retval == 1) {
22457 					V4MASK_TO_V6(mask, v6mask);
22458 				}
22459 			} else if (af == AF_INET6) {
22460 				retval = inet_pton(af, value, &v6mask);
22461 			}
22462 			if (retval != 1) {
22463 				error = EINVAL;
22464 				goto done;
22465 			}
22466 			while ((*value) && *value != ' ')
22467 				value++;
22468 		} else if (strncmp("sendspace", value, 9) == 0) {
22469 			value += 9;
22470 
22471 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
22472 			    sendspace < TCP_XMIT_HIWATER ||
22473 			    sendspace >= (1L<<30)) {
22474 				error = EINVAL;
22475 				goto done;
22476 			}
22477 			value = end;
22478 		} else if (strncmp("recvspace", value, 9) == 0) {
22479 			value += 9;
22480 
22481 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
22482 			    recvspace < TCP_RECV_HIWATER ||
22483 			    recvspace >= (1L<<30)) {
22484 				error = EINVAL;
22485 				goto done;
22486 			}
22487 			value = end;
22488 		} else if (strncmp("timestamp", value, 9) == 0) {
22489 			value += 9;
22490 
22491 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
22492 			    timestamp < 0 || timestamp > 1) {
22493 				error = EINVAL;
22494 				goto done;
22495 			}
22496 
22497 			/*
22498 			 * We increment timestamp so we know it's been set;
22499 			 * this is undone when we put it in the HSP
22500 			 */
22501 			timestamp++;
22502 			value = end;
22503 		} else if (strncmp("delete", value, 6) == 0) {
22504 			value += 6;
22505 			delete = B_TRUE;
22506 		} else {
22507 			error = EINVAL;
22508 			goto done;
22509 		}
22510 	}
22511 
22512 	/* Hash address for lookup */
22513 
22514 	hash = TCP_HSP_HASH(addr);
22515 
22516 	if (delete) {
22517 		/*
22518 		 * Note that deletes don't return an error if the thing
22519 		 * we're trying to delete isn't there.
22520 		 */
22521 		if (tcp_hsp_hash == NULL)
22522 			goto done;
22523 		hsp = tcp_hsp_hash[hash];
22524 
22525 		if (hsp) {
22526 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
22527 			    &v6addr)) {
22528 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
22529 				mi_free((char *)hsp);
22530 			} else {
22531 				hspprev = hsp;
22532 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
22533 					if (IN6_ARE_ADDR_EQUAL(
22534 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
22535 						hspprev->tcp_hsp_next =
22536 						    hsp->tcp_hsp_next;
22537 						mi_free((char *)hsp);
22538 						break;
22539 					}
22540 					hspprev = hsp;
22541 				}
22542 			}
22543 		}
22544 	} else {
22545 		/*
22546 		 * We're adding/modifying an HSP.  If we haven't already done
22547 		 * so, allocate the hash table.
22548 		 */
22549 
22550 		if (!tcp_hsp_hash) {
22551 			tcp_hsp_hash = (tcp_hsp_t **)
22552 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
22553 			if (!tcp_hsp_hash) {
22554 				error = EINVAL;
22555 				goto done;
22556 			}
22557 		}
22558 
22559 		/* Get head of hash chain */
22560 
22561 		hsp = tcp_hsp_hash[hash];
22562 
22563 		/* Try to find pre-existing hsp on hash chain */
22564 		/* Doesn't handle CIDR prefixes. */
22565 		while (hsp) {
22566 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
22567 				break;
22568 			hsp = hsp->tcp_hsp_next;
22569 		}
22570 
22571 		/*
22572 		 * If we didn't, create one with default values and put it
22573 		 * at head of hash chain
22574 		 */
22575 
22576 		if (!hsp) {
22577 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
22578 			if (!hsp) {
22579 				error = EINVAL;
22580 				goto done;
22581 			}
22582 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
22583 			tcp_hsp_hash[hash] = hsp;
22584 		}
22585 
22586 		/* Set values that the user asked us to change */
22587 
22588 		hsp->tcp_hsp_addr_v6 = v6addr;
22589 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
22590 			hsp->tcp_hsp_vers = IPV4_VERSION;
22591 		else
22592 			hsp->tcp_hsp_vers = IPV6_VERSION;
22593 		hsp->tcp_hsp_subnet_v6 = v6mask;
22594 		if (sendspace > 0)
22595 			hsp->tcp_hsp_sendspace = sendspace;
22596 		if (recvspace > 0)
22597 			hsp->tcp_hsp_recvspace = recvspace;
22598 		if (timestamp > 0)
22599 			hsp->tcp_hsp_tstamp = timestamp - 1;
22600 	}
22601 
22602 done:
22603 	rw_exit(&tcp_hsp_lock);
22604 	return (error);
22605 }
22606 
22607 /* Set callback routine passed to nd_load by tcp_param_register. */
22608 /* ARGSUSED */
22609 static int
22610 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
22611 {
22612 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
22613 }
22614 /* ARGSUSED */
22615 static int
22616 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22617     cred_t *cr)
22618 {
22619 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
22620 }
22621 
22622 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
22623 /* ARGSUSED */
22624 static int
22625 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22626 {
22627 	tcp_hsp_t *hsp;
22628 	int i;
22629 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
22630 
22631 	rw_enter(&tcp_hsp_lock, RW_READER);
22632 	(void) mi_mpprintf(mp,
22633 	    "Hash HSP     " MI_COL_HDRPAD_STR
22634 	    "Address         Subnet Mask     Send       Receive    TStamp");
22635 	if (tcp_hsp_hash) {
22636 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
22637 			hsp = tcp_hsp_hash[i];
22638 			while (hsp) {
22639 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
22640 					(void) inet_ntop(AF_INET,
22641 					    &hsp->tcp_hsp_addr,
22642 					    addrbuf, sizeof (addrbuf));
22643 					(void) inet_ntop(AF_INET,
22644 					    &hsp->tcp_hsp_subnet,
22645 					    subnetbuf, sizeof (subnetbuf));
22646 				} else {
22647 					(void) inet_ntop(AF_INET6,
22648 					    &hsp->tcp_hsp_addr_v6,
22649 					    addrbuf, sizeof (addrbuf));
22650 					(void) inet_ntop(AF_INET6,
22651 					    &hsp->tcp_hsp_subnet_v6,
22652 					    subnetbuf, sizeof (subnetbuf));
22653 				}
22654 				(void) mi_mpprintf(mp,
22655 				    " %03d " MI_COL_PTRFMT_STR
22656 				    "%s %s %010d %010d      %d",
22657 				    i,
22658 				    (void *)hsp,
22659 				    addrbuf,
22660 				    subnetbuf,
22661 				    hsp->tcp_hsp_sendspace,
22662 				    hsp->tcp_hsp_recvspace,
22663 				    hsp->tcp_hsp_tstamp);
22664 
22665 				hsp = hsp->tcp_hsp_next;
22666 			}
22667 		}
22668 	}
22669 	rw_exit(&tcp_hsp_lock);
22670 	return (0);
22671 }
22672 
22673 
22674 /* Data for fast netmask macro used by tcp_hsp_lookup */
22675 
22676 static ipaddr_t netmasks[] = {
22677 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
22678 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
22679 };
22680 
22681 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
22682 
22683 /*
22684  * XXX This routine should go away and instead we should use the metrics
22685  * associated with the routes to determine the default sndspace and rcvspace.
22686  */
22687 static tcp_hsp_t *
22688 tcp_hsp_lookup(ipaddr_t addr)
22689 {
22690 	tcp_hsp_t *hsp = NULL;
22691 
22692 	/* Quick check without acquiring the lock. */
22693 	if (tcp_hsp_hash == NULL)
22694 		return (NULL);
22695 
22696 	rw_enter(&tcp_hsp_lock, RW_READER);
22697 
22698 	/* This routine finds the best-matching HSP for address addr. */
22699 
22700 	if (tcp_hsp_hash) {
22701 		int i;
22702 		ipaddr_t srchaddr;
22703 		tcp_hsp_t *hsp_net;
22704 
22705 		/* We do three passes: host, network, and subnet. */
22706 
22707 		srchaddr = addr;
22708 
22709 		for (i = 1; i <= 3; i++) {
22710 			/* Look for exact match on srchaddr */
22711 
22712 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
22713 			while (hsp) {
22714 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
22715 				    hsp->tcp_hsp_addr == srchaddr)
22716 					break;
22717 				hsp = hsp->tcp_hsp_next;
22718 			}
22719 			ASSERT(hsp == NULL ||
22720 			    hsp->tcp_hsp_vers == IPV4_VERSION);
22721 
22722 			/*
22723 			 * If this is the first pass:
22724 			 *   If we found a match, great, return it.
22725 			 *   If not, search for the network on the second pass.
22726 			 */
22727 
22728 			if (i == 1)
22729 				if (hsp)
22730 					break;
22731 				else
22732 				{
22733 					srchaddr = addr & netmask(addr);
22734 					continue;
22735 				}
22736 
22737 			/*
22738 			 * If this is the second pass:
22739 			 *   If we found a match, but there's a subnet mask,
22740 			 *    save the match but try again using the subnet
22741 			 *    mask on the third pass.
22742 			 *   Otherwise, return whatever we found.
22743 			 */
22744 
22745 			if (i == 2) {
22746 				if (hsp && hsp->tcp_hsp_subnet) {
22747 					hsp_net = hsp;
22748 					srchaddr = addr & hsp->tcp_hsp_subnet;
22749 					continue;
22750 				} else {
22751 					break;
22752 				}
22753 			}
22754 
22755 			/*
22756 			 * This must be the third pass.  If we didn't find
22757 			 * anything, return the saved network HSP instead.
22758 			 */
22759 
22760 			if (!hsp)
22761 				hsp = hsp_net;
22762 		}
22763 	}
22764 
22765 	rw_exit(&tcp_hsp_lock);
22766 	return (hsp);
22767 }
22768 
22769 /*
22770  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
22771  * match lookup.
22772  */
22773 static tcp_hsp_t *
22774 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
22775 {
22776 	tcp_hsp_t *hsp = NULL;
22777 
22778 	/* Quick check without acquiring the lock. */
22779 	if (tcp_hsp_hash == NULL)
22780 		return (NULL);
22781 
22782 	rw_enter(&tcp_hsp_lock, RW_READER);
22783 
22784 	/* This routine finds the best-matching HSP for address addr. */
22785 
22786 	if (tcp_hsp_hash) {
22787 		int i;
22788 		in6_addr_t v6srchaddr;
22789 		tcp_hsp_t *hsp_net;
22790 
22791 		/* We do three passes: host, network, and subnet. */
22792 
22793 		v6srchaddr = *v6addr;
22794 
22795 		for (i = 1; i <= 3; i++) {
22796 			/* Look for exact match on srchaddr */
22797 
22798 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
22799 			    V4_PART_OF_V6(v6srchaddr))];
22800 			while (hsp) {
22801 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
22802 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
22803 				    &v6srchaddr))
22804 					break;
22805 				hsp = hsp->tcp_hsp_next;
22806 			}
22807 
22808 			/*
22809 			 * If this is the first pass:
22810 			 *   If we found a match, great, return it.
22811 			 *   If not, search for the network on the second pass.
22812 			 */
22813 
22814 			if (i == 1)
22815 				if (hsp)
22816 					break;
22817 				else {
22818 					/* Assume a 64 bit mask */
22819 					v6srchaddr.s6_addr32[0] =
22820 					    v6addr->s6_addr32[0];
22821 					v6srchaddr.s6_addr32[1] =
22822 					    v6addr->s6_addr32[1];
22823 					v6srchaddr.s6_addr32[2] = 0;
22824 					v6srchaddr.s6_addr32[3] = 0;
22825 					continue;
22826 				}
22827 
22828 			/*
22829 			 * If this is the second pass:
22830 			 *   If we found a match, but there's a subnet mask,
22831 			 *    save the match but try again using the subnet
22832 			 *    mask on the third pass.
22833 			 *   Otherwise, return whatever we found.
22834 			 */
22835 
22836 			if (i == 2) {
22837 				ASSERT(hsp == NULL ||
22838 				    hsp->tcp_hsp_vers == IPV6_VERSION);
22839 				if (hsp &&
22840 				    !IN6_IS_ADDR_UNSPECIFIED(
22841 				    &hsp->tcp_hsp_subnet_v6)) {
22842 					hsp_net = hsp;
22843 					V6_MASK_COPY(*v6addr,
22844 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
22845 					continue;
22846 				} else {
22847 					break;
22848 				}
22849 			}
22850 
22851 			/*
22852 			 * This must be the third pass.  If we didn't find
22853 			 * anything, return the saved network HSP instead.
22854 			 */
22855 
22856 			if (!hsp)
22857 				hsp = hsp_net;
22858 		}
22859 	}
22860 
22861 	rw_exit(&tcp_hsp_lock);
22862 	return (hsp);
22863 }
22864 
22865 /*
22866  * Type three generator adapted from the random() function in 4.4 BSD:
22867  */
22868 
22869 /*
22870  * Copyright (c) 1983, 1993
22871  *	The Regents of the University of California.  All rights reserved.
22872  *
22873  * Redistribution and use in source and binary forms, with or without
22874  * modification, are permitted provided that the following conditions
22875  * are met:
22876  * 1. Redistributions of source code must retain the above copyright
22877  *    notice, this list of conditions and the following disclaimer.
22878  * 2. Redistributions in binary form must reproduce the above copyright
22879  *    notice, this list of conditions and the following disclaimer in the
22880  *    documentation and/or other materials provided with the distribution.
22881  * 3. All advertising materials mentioning features or use of this software
22882  *    must display the following acknowledgement:
22883  *	This product includes software developed by the University of
22884  *	California, Berkeley and its contributors.
22885  * 4. Neither the name of the University nor the names of its contributors
22886  *    may be used to endorse or promote products derived from this software
22887  *    without specific prior written permission.
22888  *
22889  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22890  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22891  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22892  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22893  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22894  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22895  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22896  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22897  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22898  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
22899  * SUCH DAMAGE.
22900  */
22901 
22902 /* Type 3 -- x**31 + x**3 + 1 */
22903 #define	DEG_3		31
22904 #define	SEP_3		3
22905 
22906 
22907 /* Protected by tcp_random_lock */
22908 static int tcp_randtbl[DEG_3 + 1];
22909 
22910 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
22911 static int *tcp_random_rptr = &tcp_randtbl[1];
22912 
22913 static int *tcp_random_state = &tcp_randtbl[1];
22914 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
22915 
22916 kmutex_t tcp_random_lock;
22917 
22918 void
22919 tcp_random_init(void)
22920 {
22921 	int i;
22922 	hrtime_t hrt;
22923 	time_t wallclock;
22924 	uint64_t result;
22925 
22926 	/*
22927 	 * Use high-res timer and current time for seed.  Gethrtime() returns
22928 	 * a longlong, which may contain resolution down to nanoseconds.
22929 	 * The current time will either be a 32-bit or a 64-bit quantity.
22930 	 * XOR the two together in a 64-bit result variable.
22931 	 * Convert the result to a 32-bit value by multiplying the high-order
22932 	 * 32-bits by the low-order 32-bits.
22933 	 */
22934 
22935 	hrt = gethrtime();
22936 	(void) drv_getparm(TIME, &wallclock);
22937 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
22938 	mutex_enter(&tcp_random_lock);
22939 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
22940 	    (result & 0xffffffff);
22941 
22942 	for (i = 1; i < DEG_3; i++)
22943 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
22944 			+ 12345;
22945 	tcp_random_fptr = &tcp_random_state[SEP_3];
22946 	tcp_random_rptr = &tcp_random_state[0];
22947 	mutex_exit(&tcp_random_lock);
22948 	for (i = 0; i < 10 * DEG_3; i++)
22949 		(void) tcp_random();
22950 }
22951 
22952 /*
22953  * tcp_random: Return a random number in the range [1 - (128K + 1)].
22954  * This range is selected to be approximately centered on TCP_ISS / 2,
22955  * and easy to compute. We get this value by generating a 32-bit random
22956  * number, selecting out the high-order 17 bits, and then adding one so
22957  * that we never return zero.
22958  */
22959 int
22960 tcp_random(void)
22961 {
22962 	int i;
22963 
22964 	mutex_enter(&tcp_random_lock);
22965 	*tcp_random_fptr += *tcp_random_rptr;
22966 
22967 	/*
22968 	 * The high-order bits are more random than the low-order bits,
22969 	 * so we select out the high-order 17 bits and add one so that
22970 	 * we never return zero.
22971 	 */
22972 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
22973 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
22974 		tcp_random_fptr = tcp_random_state;
22975 		++tcp_random_rptr;
22976 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
22977 		tcp_random_rptr = tcp_random_state;
22978 
22979 	mutex_exit(&tcp_random_lock);
22980 	return (i);
22981 }
22982 
22983 /*
22984  * XXX This will go away when TPI is extended to send
22985  * info reqs to sockfs/timod .....
22986  * Given a queue, set the max packet size for the write
22987  * side of the queue below stream head.  This value is
22988  * cached on the stream head.
22989  * Returns 1 on success, 0 otherwise.
22990  */
22991 static int
22992 setmaxps(queue_t *q, int maxpsz)
22993 {
22994 	struct stdata	*stp;
22995 	queue_t		*wq;
22996 	stp = STREAM(q);
22997 
22998 	/*
22999 	 * At this point change of a queue parameter is not allowed
23000 	 * when a multiplexor is sitting on top.
23001 	 */
23002 	if (stp->sd_flag & STPLEX)
23003 		return (0);
23004 
23005 	claimstr(stp->sd_wrq);
23006 	wq = stp->sd_wrq->q_next;
23007 	ASSERT(wq != NULL);
23008 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23009 	releasestr(stp->sd_wrq);
23010 	return (1);
23011 }
23012 
23013 static int
23014 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23015     int *t_errorp, int *sys_errorp)
23016 {
23017 	int error;
23018 	int is_absreq_failure;
23019 	t_scalar_t *opt_lenp;
23020 	t_scalar_t opt_offset;
23021 	int prim_type;
23022 	struct T_conn_req *tcreqp;
23023 	struct T_conn_res *tcresp;
23024 	cred_t *cr;
23025 
23026 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23027 
23028 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23029 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23030 	    prim_type == T_CONN_RES);
23031 
23032 	switch (prim_type) {
23033 	case T_CONN_REQ:
23034 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23035 		opt_offset = tcreqp->OPT_offset;
23036 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23037 		break;
23038 	case O_T_CONN_RES:
23039 	case T_CONN_RES:
23040 		tcresp = (struct T_conn_res *)mp->b_rptr;
23041 		opt_offset = tcresp->OPT_offset;
23042 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23043 		break;
23044 	}
23045 
23046 	*t_errorp = 0;
23047 	*sys_errorp = 0;
23048 	*do_disconnectp = 0;
23049 
23050 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23051 	    opt_offset, cr, &tcp_opt_obj,
23052 	    NULL, &is_absreq_failure);
23053 
23054 	switch (error) {
23055 	case  0:		/* no error */
23056 		ASSERT(is_absreq_failure == 0);
23057 		return (0);
23058 	case ENOPROTOOPT:
23059 		*t_errorp = TBADOPT;
23060 		break;
23061 	case EACCES:
23062 		*t_errorp = TACCES;
23063 		break;
23064 	default:
23065 		*t_errorp = TSYSERR; *sys_errorp = error;
23066 		break;
23067 	}
23068 	if (is_absreq_failure != 0) {
23069 		/*
23070 		 * The connection request should get the local ack
23071 		 * T_OK_ACK and then a T_DISCON_IND.
23072 		 */
23073 		*do_disconnectp = 1;
23074 	}
23075 	return (-1);
23076 }
23077 
23078 /*
23079  * Split this function out so that if the secret changes, I'm okay.
23080  *
23081  * Initialize the tcp_iss_cookie and tcp_iss_key.
23082  */
23083 
23084 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23085 
23086 static void
23087 tcp_iss_key_init(uint8_t *phrase, int len)
23088 {
23089 	struct {
23090 		int32_t current_time;
23091 		uint32_t randnum;
23092 		uint16_t pad;
23093 		uint8_t ether[6];
23094 		uint8_t passwd[PASSWD_SIZE];
23095 	} tcp_iss_cookie;
23096 	time_t t;
23097 
23098 	/*
23099 	 * Start with the current absolute time.
23100 	 */
23101 	(void) drv_getparm(TIME, &t);
23102 	tcp_iss_cookie.current_time = t;
23103 
23104 	/*
23105 	 * XXX - Need a more random number per RFC 1750, not this crap.
23106 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23107 	 */
23108 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23109 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23110 
23111 	/*
23112 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23113 	 * as a good template.
23114 	 */
23115 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23116 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23117 
23118 	/*
23119 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23120 	 */
23121 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23122 
23123 	/*
23124 	 * See 4010593 if this section becomes a problem again,
23125 	 * but the local ethernet address is useful here.
23126 	 */
23127 	(void) localetheraddr(NULL,
23128 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23129 
23130 	/*
23131 	 * Hash 'em all together.  The MD5Final is called per-connection.
23132 	 */
23133 	mutex_enter(&tcp_iss_key_lock);
23134 	MD5Init(&tcp_iss_key);
23135 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
23136 	    sizeof (tcp_iss_cookie));
23137 	mutex_exit(&tcp_iss_key_lock);
23138 }
23139 
23140 /*
23141  * Set the RFC 1948 pass phrase
23142  */
23143 /* ARGSUSED */
23144 static int
23145 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23146     cred_t *cr)
23147 {
23148 	/*
23149 	 * Basically, value contains a new pass phrase.  Pass it along!
23150 	 */
23151 	tcp_iss_key_init((uint8_t *)value, strlen(value));
23152 	return (0);
23153 }
23154 
23155 /* ARGSUSED */
23156 static int
23157 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23158 {
23159 	bzero(buf, sizeof (tcp_sack_info_t));
23160 	return (0);
23161 }
23162 
23163 /* ARGSUSED */
23164 static int
23165 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23166 {
23167 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23168 	return (0);
23169 }
23170 
23171 void
23172 tcp_ddi_init(void)
23173 {
23174 	int i;
23175 
23176 	/* Initialize locks */
23177 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
23178 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23179 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23180 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23181 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23182 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
23183 
23184 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23185 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
23186 		    MUTEX_DEFAULT, NULL);
23187 	}
23188 
23189 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23190 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
23191 		    MUTEX_DEFAULT, NULL);
23192 	}
23193 
23194 	/* TCP's IPsec code calls the packet dropper. */
23195 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
23196 
23197 	if (!tcp_g_nd) {
23198 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
23199 			nd_free(&tcp_g_nd);
23200 		}
23201 	}
23202 
23203 	/*
23204 	 * Note: To really walk the device tree you need the devinfo
23205 	 * pointer to your device which is only available after probe/attach.
23206 	 * The following is safe only because it uses ddi_root_node()
23207 	 */
23208 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23209 	    tcp_opt_obj.odb_opt_arr_cnt);
23210 
23211 	tcp_timercache = kmem_cache_create("tcp_timercache",
23212 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23213 	    NULL, NULL, NULL, NULL, NULL, 0);
23214 
23215 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23216 	    sizeof (tcp_sack_info_t), 0,
23217 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23218 
23219 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23220 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23221 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23222 
23223 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
23224 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
23225 
23226 	ip_squeue_init(tcp_squeue_add);
23227 
23228 	/* Initialize the random number generator */
23229 	tcp_random_init();
23230 
23231 	/*
23232 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23233 	 * by the boot scripts.
23234 	 *
23235 	 * Use NULL name, as the name is caught by the new lockstats.
23236 	 *
23237 	 * Initialize with some random, non-guessable string, like the global
23238 	 * T_INFO_ACK.
23239 	 */
23240 
23241 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23242 	    sizeof (tcp_g_t_info_ack));
23243 
23244 	if ((tcp_kstat = kstat_create(TCP_MOD_NAME, 0, "tcpstat",
23245 		"net", KSTAT_TYPE_NAMED,
23246 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
23247 		KSTAT_FLAG_VIRTUAL)) != NULL) {
23248 		tcp_kstat->ks_data = &tcp_statistics;
23249 		kstat_install(tcp_kstat);
23250 	}
23251 
23252 	tcp_kstat_init();
23253 }
23254 
23255 void
23256 tcp_ddi_destroy(void)
23257 {
23258 	int i;
23259 
23260 	nd_free(&tcp_g_nd);
23261 
23262 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23263 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
23264 	}
23265 
23266 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23267 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
23268 	}
23269 
23270 	mutex_destroy(&tcp_iss_key_lock);
23271 	rw_destroy(&tcp_hsp_lock);
23272 	mutex_destroy(&tcp_g_q_lock);
23273 	mutex_destroy(&tcp_random_lock);
23274 	mutex_destroy(&tcp_epriv_port_lock);
23275 	rw_destroy(&tcp_reserved_port_lock);
23276 
23277 	ip_drop_unregister(&tcp_dropper);
23278 
23279 	kmem_cache_destroy(tcp_timercache);
23280 	kmem_cache_destroy(tcp_sack_info_cache);
23281 	kmem_cache_destroy(tcp_iphc_cache);
23282 
23283 	tcp_kstat_fini();
23284 }
23285 
23286 /*
23287  * Generate ISS, taking into account NDD changes may happen halfway through.
23288  * (If the iss is not zero, set it.)
23289  */
23290 
23291 static void
23292 tcp_iss_init(tcp_t *tcp)
23293 {
23294 	MD5_CTX context;
23295 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
23296 	uint32_t answer[4];
23297 
23298 	tcp_iss_incr_extra += (ISS_INCR >> 1);
23299 	tcp->tcp_iss = tcp_iss_incr_extra;
23300 	switch (tcp_strong_iss) {
23301 	case 2:
23302 		mutex_enter(&tcp_iss_key_lock);
23303 		context = tcp_iss_key;
23304 		mutex_exit(&tcp_iss_key_lock);
23305 		arg.ports = tcp->tcp_ports;
23306 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23307 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
23308 			    &arg.src);
23309 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
23310 			    &arg.dst);
23311 		} else {
23312 			arg.src = tcp->tcp_ip6h->ip6_src;
23313 			arg.dst = tcp->tcp_ip6h->ip6_dst;
23314 		}
23315 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
23316 		MD5Final((uchar_t *)answer, &context);
23317 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
23318 		/*
23319 		 * Now that we've hashed into a unique per-connection sequence
23320 		 * space, add a random increment per strong_iss == 1.  So I
23321 		 * guess we'll have to...
23322 		 */
23323 		/* FALLTHRU */
23324 	case 1:
23325 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
23326 		break;
23327 	default:
23328 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
23329 		break;
23330 	}
23331 	tcp->tcp_valid_bits = TCP_ISS_VALID;
23332 	tcp->tcp_fss = tcp->tcp_iss - 1;
23333 	tcp->tcp_suna = tcp->tcp_iss;
23334 	tcp->tcp_snxt = tcp->tcp_iss + 1;
23335 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23336 	tcp->tcp_csuna = tcp->tcp_snxt;
23337 }
23338 
23339 /*
23340  * Exported routine for extracting active tcp connection status.
23341  *
23342  * This is used by the Solaris Cluster Networking software to
23343  * gather a list of connections that need to be forwarded to
23344  * specific nodes in the cluster when configuration changes occur.
23345  *
23346  * The callback is invoked for each tcp_t structure. Returning
23347  * non-zero from the callback routine terminates the search.
23348  */
23349 int
23350 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
23351 {
23352 	tcp_t *tcp;
23353 	cl_tcp_info_t	cl_tcpi;
23354 	connf_t	*connfp;
23355 	conn_t	*connp;
23356 	int	i;
23357 
23358 	ASSERT(callback != NULL);
23359 
23360 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
23361 
23362 		connfp = &ipcl_globalhash_fanout[i];
23363 		connp = NULL;
23364 
23365 		while ((connp =
23366 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
23367 
23368 			tcp = connp->conn_tcp;
23369 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
23370 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
23371 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
23372 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
23373 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
23374 			/*
23375 			 * The macros tcp_laddr and tcp_faddr give the IPv4
23376 			 * addresses. They are copied implicitly below as
23377 			 * mapped addresses.
23378 			 */
23379 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
23380 			if (tcp->tcp_ipversion == IPV4_VERSION) {
23381 				cl_tcpi.cl_tcpi_faddr =
23382 				    tcp->tcp_ipha->ipha_dst;
23383 			} else {
23384 				cl_tcpi.cl_tcpi_faddr_v6 =
23385 				    tcp->tcp_ip6h->ip6_dst;
23386 			}
23387 
23388 			/*
23389 			 * If the callback returns non-zero
23390 			 * we terminate the traversal.
23391 			 */
23392 			if ((*callback)(&cl_tcpi, arg) != 0) {
23393 				CONN_DEC_REF(tcp->tcp_connp);
23394 				return (1);
23395 			}
23396 		}
23397 	}
23398 
23399 	return (0);
23400 }
23401 
23402 /*
23403  * Macros used for accessing the different types of sockaddr
23404  * structures inside a tcp_ioc_abort_conn_t.
23405  */
23406 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
23407 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
23408 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
23409 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
23410 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
23411 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
23412 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
23413 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
23414 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
23415 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
23416 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
23417 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
23418 
23419 /*
23420  * Return the correct error code to mimic the behavior
23421  * of a connection reset.
23422  */
23423 #define	TCP_AC_GET_ERRCODE(state, err) {	\
23424 		switch ((state)) {		\
23425 		case TCPS_SYN_SENT:		\
23426 		case TCPS_SYN_RCVD:		\
23427 			(err) = ECONNREFUSED;	\
23428 			break;			\
23429 		case TCPS_ESTABLISHED:		\
23430 		case TCPS_FIN_WAIT_1:		\
23431 		case TCPS_FIN_WAIT_2:		\
23432 		case TCPS_CLOSE_WAIT:		\
23433 			(err) = ECONNRESET;	\
23434 			break;			\
23435 		case TCPS_CLOSING:		\
23436 		case TCPS_LAST_ACK:		\
23437 		case TCPS_TIME_WAIT:		\
23438 			(err) = 0;		\
23439 			break;			\
23440 		default:			\
23441 			(err) = ENXIO;		\
23442 		}				\
23443 	}
23444 
23445 /*
23446  * Check if a tcp structure matches the info in acp.
23447  */
23448 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
23449 	(((acp)->ac_local.ss_family == AF_INET) ?		\
23450 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
23451 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
23452 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
23453 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
23454 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
23455 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
23456 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
23457 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
23458 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23459 	(acp)->ac_end >= (tcp)->tcp_state) :		\
23460 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
23461 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
23462 	&(tcp)->tcp_ip_src_v6)) &&				\
23463 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
23464 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
23465 	&(tcp)->tcp_remote_v6)) &&				\
23466 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
23467 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
23468 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
23469 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
23470 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23471 	(acp)->ac_end >= (tcp)->tcp_state))
23472 
23473 #define	TCP_AC_MATCH(acp, tcp)					\
23474 	(((acp)->ac_zoneid == ALL_ZONES ||			\
23475 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
23476 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
23477 
23478 /*
23479  * Build a message containing a tcp_ioc_abort_conn_t structure
23480  * which is filled in with information from acp and tp.
23481  */
23482 static mblk_t *
23483 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
23484 {
23485 	mblk_t *mp;
23486 	tcp_ioc_abort_conn_t *tacp;
23487 
23488 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
23489 	if (mp == NULL)
23490 		return (NULL);
23491 
23492 	mp->b_datap->db_type = M_CTL;
23493 
23494 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
23495 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
23496 		sizeof (uint32_t));
23497 
23498 	tacp->ac_start = acp->ac_start;
23499 	tacp->ac_end = acp->ac_end;
23500 	tacp->ac_zoneid = acp->ac_zoneid;
23501 
23502 	if (acp->ac_local.ss_family == AF_INET) {
23503 		tacp->ac_local.ss_family = AF_INET;
23504 		tacp->ac_remote.ss_family = AF_INET;
23505 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
23506 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
23507 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
23508 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
23509 	} else {
23510 		tacp->ac_local.ss_family = AF_INET6;
23511 		tacp->ac_remote.ss_family = AF_INET6;
23512 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
23513 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
23514 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
23515 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
23516 	}
23517 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
23518 	return (mp);
23519 }
23520 
23521 /*
23522  * Print a tcp_ioc_abort_conn_t structure.
23523  */
23524 static void
23525 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
23526 {
23527 	char lbuf[128];
23528 	char rbuf[128];
23529 	sa_family_t af;
23530 	in_port_t lport, rport;
23531 	ushort_t logflags;
23532 
23533 	af = acp->ac_local.ss_family;
23534 
23535 	if (af == AF_INET) {
23536 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
23537 				lbuf, 128);
23538 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
23539 				rbuf, 128);
23540 		lport = ntohs(TCP_AC_V4LPORT(acp));
23541 		rport = ntohs(TCP_AC_V4RPORT(acp));
23542 	} else {
23543 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
23544 				lbuf, 128);
23545 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
23546 				rbuf, 128);
23547 		lport = ntohs(TCP_AC_V6LPORT(acp));
23548 		rport = ntohs(TCP_AC_V6RPORT(acp));
23549 	}
23550 
23551 	logflags = SL_TRACE | SL_NOTE;
23552 	/*
23553 	 * Don't print this message to the console if the operation was done
23554 	 * to a non-global zone.
23555 	 */
23556 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
23557 		logflags |= SL_CONSOLE;
23558 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
23559 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
23560 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
23561 		acp->ac_start, acp->ac_end);
23562 }
23563 
23564 /*
23565  * Called inside tcp_rput when a message built using
23566  * tcp_ioctl_abort_build_msg is put into a queue.
23567  * Note that when we get here there is no wildcard in acp any more.
23568  */
23569 static void
23570 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
23571 {
23572 	tcp_ioc_abort_conn_t *acp;
23573 
23574 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
23575 	if (tcp->tcp_state <= acp->ac_end) {
23576 		/*
23577 		 * If we get here, we are already on the correct
23578 		 * squeue. This ioctl follows the following path
23579 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
23580 		 * ->tcp_ioctl_abort->squeue_fill (if on a
23581 		 * different squeue)
23582 		 */
23583 		int errcode;
23584 
23585 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
23586 		(void) tcp_clean_death(tcp, errcode, 26);
23587 	}
23588 	freemsg(mp);
23589 }
23590 
23591 /*
23592  * Abort all matching connections on a hash chain.
23593  */
23594 static int
23595 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
23596     boolean_t exact)
23597 {
23598 	int nmatch, err = 0;
23599 	tcp_t *tcp;
23600 	MBLKP mp, last, listhead = NULL;
23601 	conn_t	*tconnp;
23602 	connf_t	*connfp = &ipcl_conn_fanout[index];
23603 
23604 startover:
23605 	nmatch = 0;
23606 
23607 	mutex_enter(&connfp->connf_lock);
23608 	for (tconnp = connfp->connf_head; tconnp != NULL;
23609 	    tconnp = tconnp->conn_next) {
23610 		tcp = tconnp->conn_tcp;
23611 		if (TCP_AC_MATCH(acp, tcp)) {
23612 			CONN_INC_REF(tcp->tcp_connp);
23613 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
23614 			if (mp == NULL) {
23615 				err = ENOMEM;
23616 				CONN_DEC_REF(tcp->tcp_connp);
23617 				break;
23618 			}
23619 			mp->b_prev = (mblk_t *)tcp;
23620 
23621 			if (listhead == NULL) {
23622 				listhead = mp;
23623 				last = mp;
23624 			} else {
23625 				last->b_next = mp;
23626 				last = mp;
23627 			}
23628 			nmatch++;
23629 			if (exact)
23630 				break;
23631 		}
23632 
23633 		/* Avoid holding lock for too long. */
23634 		if (nmatch >= 500)
23635 			break;
23636 	}
23637 	mutex_exit(&connfp->connf_lock);
23638 
23639 	/* Pass mp into the correct tcp */
23640 	while ((mp = listhead) != NULL) {
23641 		listhead = listhead->b_next;
23642 		tcp = (tcp_t *)mp->b_prev;
23643 		mp->b_next = mp->b_prev = NULL;
23644 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
23645 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
23646 	}
23647 
23648 	*count += nmatch;
23649 	if (nmatch >= 500 && err == 0)
23650 		goto startover;
23651 	return (err);
23652 }
23653 
23654 /*
23655  * Abort all connections that matches the attributes specified in acp.
23656  */
23657 static int
23658 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
23659 {
23660 	sa_family_t af;
23661 	uint32_t  ports;
23662 	uint16_t *pports;
23663 	int err = 0, count = 0;
23664 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
23665 	int index = -1;
23666 	ushort_t logflags;
23667 
23668 	af = acp->ac_local.ss_family;
23669 
23670 	if (af == AF_INET) {
23671 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
23672 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
23673 			pports = (uint16_t *)&ports;
23674 			pports[1] = TCP_AC_V4LPORT(acp);
23675 			pports[0] = TCP_AC_V4RPORT(acp);
23676 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
23677 		}
23678 	} else {
23679 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
23680 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
23681 			pports = (uint16_t *)&ports;
23682 			pports[1] = TCP_AC_V6LPORT(acp);
23683 			pports[0] = TCP_AC_V6RPORT(acp);
23684 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
23685 		}
23686 	}
23687 
23688 	/*
23689 	 * For cases where remote addr, local port, and remote port are non-
23690 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
23691 	 */
23692 	if (index != -1) {
23693 		err = tcp_ioctl_abort_bucket(acp, index,
23694 			    &count, exact);
23695 	} else {
23696 		/*
23697 		 * loop through all entries for wildcard case
23698 		 */
23699 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
23700 			err = tcp_ioctl_abort_bucket(acp, index,
23701 			    &count, exact);
23702 			if (err != 0)
23703 				break;
23704 		}
23705 	}
23706 
23707 	logflags = SL_TRACE | SL_NOTE;
23708 	/*
23709 	 * Don't print this message to the console if the operation was done
23710 	 * to a non-global zone.
23711 	 */
23712 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
23713 		logflags |= SL_CONSOLE;
23714 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
23715 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
23716 	if (err == 0 && count == 0)
23717 		err = ENOENT;
23718 	return (err);
23719 }
23720 
23721 /*
23722  * Process the TCP_IOC_ABORT_CONN ioctl request.
23723  */
23724 static void
23725 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
23726 {
23727 	int	err;
23728 	IOCP    iocp;
23729 	MBLKP   mp1;
23730 	sa_family_t laf, raf;
23731 	tcp_ioc_abort_conn_t *acp;
23732 	zone_t *zptr;
23733 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
23734 
23735 	iocp = (IOCP)mp->b_rptr;
23736 
23737 	if ((mp1 = mp->b_cont) == NULL ||
23738 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
23739 		err = EINVAL;
23740 		goto out;
23741 	}
23742 
23743 	/* check permissions */
23744 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
23745 		err = EPERM;
23746 		goto out;
23747 	}
23748 
23749 	if (mp1->b_cont != NULL) {
23750 		freemsg(mp1->b_cont);
23751 		mp1->b_cont = NULL;
23752 	}
23753 
23754 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
23755 	laf = acp->ac_local.ss_family;
23756 	raf = acp->ac_remote.ss_family;
23757 
23758 	/* check that a zone with the supplied zoneid exists */
23759 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
23760 		zptr = zone_find_by_id(zoneid);
23761 		if (zptr != NULL) {
23762 			zone_rele(zptr);
23763 		} else {
23764 			err = EINVAL;
23765 			goto out;
23766 		}
23767 	}
23768 
23769 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
23770 	    acp->ac_start > acp->ac_end || laf != raf ||
23771 	    (laf != AF_INET && laf != AF_INET6)) {
23772 		err = EINVAL;
23773 		goto out;
23774 	}
23775 
23776 	tcp_ioctl_abort_dump(acp);
23777 	err = tcp_ioctl_abort(acp);
23778 
23779 out:
23780 	if (mp1 != NULL) {
23781 		freemsg(mp1);
23782 		mp->b_cont = NULL;
23783 	}
23784 
23785 	if (err != 0)
23786 		miocnak(q, mp, 0, err);
23787 	else
23788 		miocack(q, mp, 0, 0);
23789 }
23790 
23791 /*
23792  * tcp_time_wait_processing() handles processing of incoming packets when
23793  * the tcp is in the TIME_WAIT state.
23794  * A TIME_WAIT tcp that has an associated open TCP stream is never put
23795  * on the time wait list.
23796  */
23797 void
23798 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
23799     uint32_t seg_ack, int seg_len, tcph_t *tcph)
23800 {
23801 	int32_t		bytes_acked;
23802 	int32_t		gap;
23803 	int32_t		rgap;
23804 	tcp_opt_t	tcpopt;
23805 	uint_t		flags;
23806 	uint32_t	new_swnd = 0;
23807 	conn_t		*connp;
23808 
23809 	BUMP_LOCAL(tcp->tcp_ibsegs);
23810 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
23811 
23812 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
23813 	new_swnd = BE16_TO_U16(tcph->th_win) <<
23814 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
23815 	if (tcp->tcp_snd_ts_ok) {
23816 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
23817 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
23818 			    tcp->tcp_rnxt, TH_ACK);
23819 			goto done;
23820 		}
23821 	}
23822 	gap = seg_seq - tcp->tcp_rnxt;
23823 	rgap = tcp->tcp_rwnd - (gap + seg_len);
23824 	if (gap < 0) {
23825 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
23826 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
23827 		    (seg_len > -gap ? -gap : seg_len));
23828 		seg_len += gap;
23829 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
23830 			if (flags & TH_RST) {
23831 				goto done;
23832 			}
23833 			if ((flags & TH_FIN) && seg_len == -1) {
23834 				/*
23835 				 * When TCP receives a duplicate FIN in
23836 				 * TIME_WAIT state, restart the 2 MSL timer.
23837 				 * See page 73 in RFC 793. Make sure this TCP
23838 				 * is already on the TIME_WAIT list. If not,
23839 				 * just restart the timer.
23840 				 */
23841 				if (TCP_IS_DETACHED(tcp)) {
23842 					tcp_time_wait_remove(tcp, NULL);
23843 					tcp_time_wait_append(tcp);
23844 					TCP_DBGSTAT(tcp_rput_time_wait);
23845 				} else {
23846 					ASSERT(tcp != NULL);
23847 					TCP_TIMER_RESTART(tcp,
23848 					    tcp_time_wait_interval);
23849 				}
23850 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
23851 				    tcp->tcp_rnxt, TH_ACK);
23852 				goto done;
23853 			}
23854 			flags |=  TH_ACK_NEEDED;
23855 			seg_len = 0;
23856 			goto process_ack;
23857 		}
23858 
23859 		/* Fix seg_seq, and chew the gap off the front. */
23860 		seg_seq = tcp->tcp_rnxt;
23861 	}
23862 
23863 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
23864 		/*
23865 		 * Make sure that when we accept the connection, pick
23866 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
23867 		 * old connection.
23868 		 *
23869 		 * The next ISS generated is equal to tcp_iss_incr_extra
23870 		 * + ISS_INCR/2 + other components depending on the
23871 		 * value of tcp_strong_iss.  We pre-calculate the new
23872 		 * ISS here and compare with tcp_snxt to determine if
23873 		 * we need to make adjustment to tcp_iss_incr_extra.
23874 		 *
23875 		 * The above calculation is ugly and is a
23876 		 * waste of CPU cycles...
23877 		 */
23878 		uint32_t new_iss = tcp_iss_incr_extra;
23879 		int32_t adj;
23880 
23881 		switch (tcp_strong_iss) {
23882 		case 2: {
23883 			/* Add time and MD5 components. */
23884 			uint32_t answer[4];
23885 			struct {
23886 				uint32_t ports;
23887 				in6_addr_t src;
23888 				in6_addr_t dst;
23889 			} arg;
23890 			MD5_CTX context;
23891 
23892 			mutex_enter(&tcp_iss_key_lock);
23893 			context = tcp_iss_key;
23894 			mutex_exit(&tcp_iss_key_lock);
23895 			arg.ports = tcp->tcp_ports;
23896 			/* We use MAPPED addresses in tcp_iss_init */
23897 			arg.src = tcp->tcp_ip_src_v6;
23898 			if (tcp->tcp_ipversion == IPV4_VERSION) {
23899 				IN6_IPADDR_TO_V4MAPPED(
23900 					tcp->tcp_ipha->ipha_dst,
23901 					    &arg.dst);
23902 			} else {
23903 				arg.dst =
23904 				    tcp->tcp_ip6h->ip6_dst;
23905 			}
23906 			MD5Update(&context, (uchar_t *)&arg,
23907 			    sizeof (arg));
23908 			MD5Final((uchar_t *)answer, &context);
23909 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
23910 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
23911 			break;
23912 		}
23913 		case 1:
23914 			/* Add time component and min random (i.e. 1). */
23915 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
23916 			break;
23917 		default:
23918 			/* Add only time component. */
23919 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
23920 			break;
23921 		}
23922 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
23923 			/*
23924 			 * New ISS not guaranteed to be ISS_INCR/2
23925 			 * ahead of the current tcp_snxt, so add the
23926 			 * difference to tcp_iss_incr_extra.
23927 			 */
23928 			tcp_iss_incr_extra += adj;
23929 		}
23930 		/*
23931 		 * If tcp_clean_death() can not perform the task now,
23932 		 * drop the SYN packet and let the other side re-xmit.
23933 		 * Otherwise pass the SYN packet back in, since the
23934 		 * old tcp state has been cleaned up or freed.
23935 		 */
23936 		if (tcp_clean_death(tcp, 0, 27) == -1)
23937 			goto done;
23938 		/*
23939 		 * We will come back to tcp_rput_data
23940 		 * on the global queue. Packets destined
23941 		 * for the global queue will be checked
23942 		 * with global policy. But the policy for
23943 		 * this packet has already been checked as
23944 		 * this was destined for the detached
23945 		 * connection. We need to bypass policy
23946 		 * check this time by attaching a dummy
23947 		 * ipsec_in with ipsec_in_dont_check set.
23948 		 */
23949 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
23950 		    NULL) {
23951 			TCP_STAT(tcp_time_wait_syn_success);
23952 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
23953 			return;
23954 		}
23955 		goto done;
23956 	}
23957 
23958 	/*
23959 	 * rgap is the amount of stuff received out of window.  A negative
23960 	 * value is the amount out of window.
23961 	 */
23962 	if (rgap < 0) {
23963 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
23964 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
23965 		/* Fix seg_len and make sure there is something left. */
23966 		seg_len += rgap;
23967 		if (seg_len <= 0) {
23968 			if (flags & TH_RST) {
23969 				goto done;
23970 			}
23971 			flags |=  TH_ACK_NEEDED;
23972 			seg_len = 0;
23973 			goto process_ack;
23974 		}
23975 	}
23976 	/*
23977 	 * Check whether we can update tcp_ts_recent.  This test is
23978 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
23979 	 * Extensions for High Performance: An Update", Internet Draft.
23980 	 */
23981 	if (tcp->tcp_snd_ts_ok &&
23982 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
23983 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
23984 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
23985 		tcp->tcp_last_rcv_lbolt = lbolt64;
23986 	}
23987 
23988 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
23989 		/* Always ack out of order packets */
23990 		flags |= TH_ACK_NEEDED;
23991 		seg_len = 0;
23992 	} else if (seg_len > 0) {
23993 		BUMP_MIB(&tcp_mib, tcpInClosed);
23994 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
23995 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
23996 	}
23997 	if (flags & TH_RST) {
23998 		(void) tcp_clean_death(tcp, 0, 28);
23999 		goto done;
24000 	}
24001 	if (flags & TH_SYN) {
24002 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24003 		    TH_RST|TH_ACK);
24004 		/*
24005 		 * Do not delete the TCP structure if it is in
24006 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24007 		 */
24008 		goto done;
24009 	}
24010 process_ack:
24011 	if (flags & TH_ACK) {
24012 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24013 		if (bytes_acked <= 0) {
24014 			if (bytes_acked == 0 && seg_len == 0 &&
24015 			    new_swnd == tcp->tcp_swnd)
24016 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24017 		} else {
24018 			/* Acks something not sent */
24019 			flags |= TH_ACK_NEEDED;
24020 		}
24021 	}
24022 	if (flags & TH_ACK_NEEDED) {
24023 		/*
24024 		 * Time to send an ack for some reason.
24025 		 */
24026 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24027 		    tcp->tcp_rnxt, TH_ACK);
24028 	}
24029 done:
24030 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24031 		DB_CKSUMSTART(mp) = 0;
24032 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24033 		TCP_STAT(tcp_time_wait_syn_fail);
24034 	}
24035 	freemsg(mp);
24036 }
24037 
24038 /*
24039  * Return zero if the buffers are identical in length and content.
24040  * This is used for comparing extension header buffers.
24041  * Note that an extension header would be declared different
24042  * even if all that changed was the next header value in that header i.e.
24043  * what really changed is the next extension header.
24044  */
24045 static boolean_t
24046 tcp_cmpbuf(void *a, uint_t alen, boolean_t b_valid, void *b, uint_t blen)
24047 {
24048 	if (!b_valid)
24049 		blen = 0;
24050 
24051 	if (alen != blen)
24052 		return (B_TRUE);
24053 	if (alen == 0)
24054 		return (B_FALSE);	/* Both zero length */
24055 	return (bcmp(a, b, alen));
24056 }
24057 
24058 /*
24059  * Preallocate memory for tcp_savebuf(). Returns B_TRUE if ok.
24060  * Return B_FALSE if memory allocation fails - don't change any state!
24061  */
24062 static boolean_t
24063 tcp_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24064     void *src, uint_t srclen)
24065 {
24066 	void *dst;
24067 
24068 	if (!src_valid)
24069 		srclen = 0;
24070 
24071 	ASSERT(*dstlenp == 0);
24072 	if (src != NULL && srclen != 0) {
24073 		dst = mi_alloc(srclen, BPRI_MED);
24074 		if (dst == NULL)
24075 			return (B_FALSE);
24076 	} else {
24077 		dst = NULL;
24078 	}
24079 	if (*dstp != NULL) {
24080 		mi_free(*dstp);
24081 		*dstp = NULL;
24082 		*dstlenp = 0;
24083 	}
24084 	*dstp = dst;
24085 	if (dst != NULL)
24086 		*dstlenp = srclen;
24087 	else
24088 		*dstlenp = 0;
24089 	return (B_TRUE);
24090 }
24091 
24092 /*
24093  * Replace what is in *dst, *dstlen with the source.
24094  * Assumes tcp_allocbuf has already been called.
24095  */
24096 static void
24097 tcp_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24098     void *src, uint_t srclen)
24099 {
24100 	if (!src_valid)
24101 		srclen = 0;
24102 
24103 	ASSERT(*dstlenp == srclen);
24104 	if (src != NULL && srclen != 0) {
24105 		bcopy(src, *dstp, srclen);
24106 	}
24107 }
24108 
24109 /*
24110  * Allocate a T_SVR4_OPTMGMT_REQ.
24111  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24112  * that tcp_rput_other can drop the acks.
24113  */
24114 static mblk_t *
24115 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24116 {
24117 	mblk_t *mp;
24118 	struct T_optmgmt_req *tor;
24119 	struct opthdr *oh;
24120 	uint_t size;
24121 	char *optptr;
24122 
24123 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24124 	mp = allocb(size, BPRI_MED);
24125 	if (mp == NULL)
24126 		return (NULL);
24127 
24128 	mp->b_wptr += size;
24129 	mp->b_datap->db_type = M_PROTO;
24130 	tor = (struct T_optmgmt_req *)mp->b_rptr;
24131 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
24132 	tor->MGMT_flags = T_NEGOTIATE;
24133 	tor->OPT_length = sizeof (*oh) + optlen;
24134 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
24135 
24136 	oh = (struct opthdr *)&tor[1];
24137 	oh->level = level;
24138 	oh->name = cmd;
24139 	oh->len = optlen;
24140 	if (optlen != 0) {
24141 		optptr = (char *)&oh[1];
24142 		bcopy(opt, optptr, optlen);
24143 	}
24144 	return (mp);
24145 }
24146 
24147 /*
24148  * TCP Timers Implementation.
24149  */
24150 timeout_id_t
24151 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24152 {
24153 	mblk_t *mp;
24154 	tcp_timer_t *tcpt;
24155 	tcp_t *tcp = connp->conn_tcp;
24156 
24157 	ASSERT(connp->conn_sqp != NULL);
24158 
24159 	TCP_DBGSTAT(tcp_timeout_calls);
24160 
24161 	if (tcp->tcp_timercache == NULL) {
24162 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24163 	} else {
24164 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
24165 		mp = tcp->tcp_timercache;
24166 		tcp->tcp_timercache = mp->b_next;
24167 		mp->b_next = NULL;
24168 		ASSERT(mp->b_wptr == NULL);
24169 	}
24170 
24171 	CONN_INC_REF(connp);
24172 	tcpt = (tcp_timer_t *)mp->b_rptr;
24173 	tcpt->connp = connp;
24174 	tcpt->tcpt_proc = f;
24175 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
24176 	return ((timeout_id_t)mp);
24177 }
24178 
24179 static void
24180 tcp_timer_callback(void *arg)
24181 {
24182 	mblk_t *mp = (mblk_t *)arg;
24183 	tcp_timer_t *tcpt;
24184 	conn_t	*connp;
24185 
24186 	tcpt = (tcp_timer_t *)mp->b_rptr;
24187 	connp = tcpt->connp;
24188 	squeue_fill(connp->conn_sqp, mp,
24189 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
24190 }
24191 
24192 static void
24193 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24194 {
24195 	tcp_timer_t *tcpt;
24196 	conn_t *connp = (conn_t *)arg;
24197 	tcp_t *tcp = connp->conn_tcp;
24198 
24199 	tcpt = (tcp_timer_t *)mp->b_rptr;
24200 	ASSERT(connp == tcpt->connp);
24201 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24202 
24203 	/*
24204 	 * If the TCP has reached the closed state, don't proceed any
24205 	 * further. This TCP logically does not exist on the system.
24206 	 * tcpt_proc could for example access queues, that have already
24207 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24208 	 */
24209 	if (tcp->tcp_state != TCPS_CLOSED) {
24210 		(*tcpt->tcpt_proc)(connp);
24211 	} else {
24212 		tcp->tcp_timer_tid = 0;
24213 	}
24214 	tcp_timer_free(connp->conn_tcp, mp);
24215 }
24216 
24217 /*
24218  * There is potential race with untimeout and the handler firing at the same
24219  * time. The mblock may be freed by the handler while we are trying to use
24220  * it. But since both should execute on the same squeue, this race should not
24221  * occur.
24222  */
24223 clock_t
24224 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24225 {
24226 	mblk_t	*mp = (mblk_t *)id;
24227 	tcp_timer_t *tcpt;
24228 	clock_t delta;
24229 
24230 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
24231 
24232 	if (mp == NULL)
24233 		return (-1);
24234 
24235 	tcpt = (tcp_timer_t *)mp->b_rptr;
24236 	ASSERT(tcpt->connp == connp);
24237 
24238 	delta = untimeout(tcpt->tcpt_tid);
24239 
24240 	if (delta >= 0) {
24241 		TCP_DBGSTAT(tcp_timeout_canceled);
24242 		tcp_timer_free(connp->conn_tcp, mp);
24243 		CONN_DEC_REF(connp);
24244 	}
24245 
24246 	return (delta);
24247 }
24248 
24249 /*
24250  * Allocate space for the timer event. The allocation looks like mblk, but it is
24251  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24252  *
24253  * Dealing with failures: If we can't allocate from the timer cache we try
24254  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24255  * points to b_rptr.
24256  * If we can't allocate anything using allocb_tryhard(), we perform a last
24257  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24258  * save the actual allocation size in b_datap.
24259  */
24260 mblk_t *
24261 tcp_timermp_alloc(int kmflags)
24262 {
24263 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
24264 	    kmflags & ~KM_PANIC);
24265 
24266 	if (mp != NULL) {
24267 		mp->b_next = mp->b_prev = NULL;
24268 		mp->b_rptr = (uchar_t *)(&mp[1]);
24269 		mp->b_wptr = NULL;
24270 		mp->b_datap = NULL;
24271 		mp->b_queue = NULL;
24272 	} else if (kmflags & KM_PANIC) {
24273 		/*
24274 		 * Failed to allocate memory for the timer. Try allocating from
24275 		 * dblock caches.
24276 		 */
24277 		TCP_STAT(tcp_timermp_allocfail);
24278 		mp = allocb_tryhard(sizeof (tcp_timer_t));
24279 		if (mp == NULL) {
24280 			size_t size = 0;
24281 			/*
24282 			 * Memory is really low. Try tryhard allocation.
24283 			 */
24284 			TCP_STAT(tcp_timermp_allocdblfail);
24285 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
24286 			    sizeof (tcp_timer_t), &size, kmflags);
24287 			mp->b_rptr = (uchar_t *)(&mp[1]);
24288 			mp->b_next = mp->b_prev = NULL;
24289 			mp->b_wptr = (uchar_t *)-1;
24290 			mp->b_datap = (dblk_t *)size;
24291 			mp->b_queue = NULL;
24292 		}
24293 		ASSERT(mp->b_wptr != NULL);
24294 	}
24295 	TCP_DBGSTAT(tcp_timermp_alloced);
24296 
24297 	return (mp);
24298 }
24299 
24300 /*
24301  * Free per-tcp timer cache.
24302  * It can only contain entries from tcp_timercache.
24303  */
24304 void
24305 tcp_timermp_free(tcp_t *tcp)
24306 {
24307 	mblk_t *mp;
24308 
24309 	while ((mp = tcp->tcp_timercache) != NULL) {
24310 		ASSERT(mp->b_wptr == NULL);
24311 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
24312 		kmem_cache_free(tcp_timercache, mp);
24313 	}
24314 }
24315 
24316 /*
24317  * Free timer event. Put it on the per-tcp timer cache if there is not too many
24318  * events there already (currently at most two events are cached).
24319  * If the event is not allocated from the timer cache, free it right away.
24320  */
24321 static void
24322 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
24323 {
24324 	mblk_t *mp1 = tcp->tcp_timercache;
24325 
24326 	if (mp->b_wptr != NULL) {
24327 		/*
24328 		 * This allocation is not from a timer cache, free it right
24329 		 * away.
24330 		 */
24331 		if (mp->b_wptr != (uchar_t *)-1)
24332 			freeb(mp);
24333 		else
24334 			kmem_free(mp, (size_t)mp->b_datap);
24335 	} else if (mp1 == NULL || mp1->b_next == NULL) {
24336 		/* Cache this timer block for future allocations */
24337 		mp->b_rptr = (uchar_t *)(&mp[1]);
24338 		mp->b_next = mp1;
24339 		tcp->tcp_timercache = mp;
24340 	} else {
24341 		kmem_cache_free(tcp_timercache, mp);
24342 		TCP_DBGSTAT(tcp_timermp_freed);
24343 	}
24344 }
24345 
24346 /*
24347  * End of TCP Timers implementation.
24348  */
24349 
24350 /*
24351  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
24352  * on the specified backing STREAMS q. Note, the caller may make the
24353  * decision to call based on the tcp_t.tcp_flow_stopped value which
24354  * when check outside the q's lock is only an advisory check ...
24355  */
24356 
24357 void
24358 tcp_setqfull(tcp_t *tcp)
24359 {
24360 	queue_t *q = tcp->tcp_wq;
24361 
24362 	if (!(q->q_flag & QFULL)) {
24363 		mutex_enter(QLOCK(q));
24364 		if (!(q->q_flag & QFULL)) {
24365 			/* still need to set QFULL */
24366 			q->q_flag |= QFULL;
24367 			tcp->tcp_flow_stopped = B_TRUE;
24368 			mutex_exit(QLOCK(q));
24369 			TCP_STAT(tcp_flwctl_on);
24370 		} else {
24371 			mutex_exit(QLOCK(q));
24372 		}
24373 	}
24374 }
24375 
24376 void
24377 tcp_clrqfull(tcp_t *tcp)
24378 {
24379 	queue_t *q = tcp->tcp_wq;
24380 
24381 	if (q->q_flag & QFULL) {
24382 		mutex_enter(QLOCK(q));
24383 		if (q->q_flag & QFULL) {
24384 			q->q_flag &= ~QFULL;
24385 			tcp->tcp_flow_stopped = B_FALSE;
24386 			mutex_exit(QLOCK(q));
24387 			if (q->q_flag & QWANTW)
24388 				qbackenable(q, 0);
24389 		} else {
24390 			mutex_exit(QLOCK(q));
24391 		}
24392 	}
24393 }
24394 
24395 /*
24396  * TCP Kstats implementation
24397  */
24398 static void
24399 tcp_kstat_init(void)
24400 {
24401 	tcp_named_kstat_t template = {
24402 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
24403 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
24404 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
24405 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
24406 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
24407 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
24408 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
24409 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
24410 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
24411 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
24412 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
24413 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
24414 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
24415 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
24416 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
24417 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
24418 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
24419 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
24420 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
24421 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
24422 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
24423 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
24424 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
24425 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
24426 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
24427 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
24428 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
24429 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
24430 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
24431 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
24432 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
24433 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
24434 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
24435 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
24436 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
24437 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
24438 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
24439 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
24440 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
24441 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
24442 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
24443 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
24444 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
24445 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
24446 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
24447 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
24448 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
24449 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
24450 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
24451 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
24452 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
24453 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
24454 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
24455 	};
24456 
24457 	tcp_mibkp = kstat_create(TCP_MOD_NAME, 0, TCP_MOD_NAME,
24458 	    "mib2", KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0);
24459 
24460 	if (tcp_mibkp == NULL)
24461 		return;
24462 
24463 	template.rtoAlgorithm.value.ui32 = 4;
24464 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
24465 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
24466 	template.maxConn.value.i32 = -1;
24467 
24468 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
24469 
24470 	tcp_mibkp->ks_update = tcp_kstat_update;
24471 
24472 	kstat_install(tcp_mibkp);
24473 }
24474 
24475 static void
24476 tcp_kstat_fini(void)
24477 {
24478 
24479 	if (tcp_mibkp != NULL) {
24480 		kstat_delete(tcp_mibkp);
24481 		tcp_mibkp = NULL;
24482 	}
24483 }
24484 
24485 static int
24486 tcp_kstat_update(kstat_t *kp, int rw)
24487 {
24488 	tcp_named_kstat_t	*tcpkp;
24489 	tcp_t			*tcp;
24490 	connf_t			*connfp;
24491 	conn_t			*connp;
24492 	int 			i;
24493 
24494 	if (!kp || !kp->ks_data)
24495 		return (EIO);
24496 
24497 	if (rw == KSTAT_WRITE)
24498 		return (EACCES);
24499 
24500 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
24501 
24502 	tcpkp->currEstab.value.ui32 = 0;
24503 
24504 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24505 		connfp = &ipcl_globalhash_fanout[i];
24506 		connp = NULL;
24507 		while ((connp =
24508 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24509 			tcp = connp->conn_tcp;
24510 			switch (tcp_snmp_state(tcp)) {
24511 			case MIB2_TCP_established:
24512 			case MIB2_TCP_closeWait:
24513 				tcpkp->currEstab.value.ui32++;
24514 				break;
24515 			}
24516 		}
24517 	}
24518 
24519 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
24520 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
24521 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
24522 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
24523 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
24524 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
24525 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
24526 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
24527 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
24528 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
24529 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
24530 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
24531 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
24532 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
24533 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
24534 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
24535 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
24536 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
24537 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
24538 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
24539 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
24540 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
24541 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
24542 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
24543 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
24544 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
24545 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
24546 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
24547 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
24548 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
24549 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
24550 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
24551 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
24552 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
24553 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
24554 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
24555 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
24556 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
24557 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
24558 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
24559 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
24560 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
24561 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
24562 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
24563 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
24564 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
24565 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
24566 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
24567 
24568 	return (0);
24569 }
24570 
24571 void
24572 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
24573 {
24574 	uint16_t	hdr_len;
24575 	ipha_t		*ipha;
24576 	uint8_t		*nexthdrp;
24577 	tcph_t		*tcph;
24578 
24579 	/* Already has an eager */
24580 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24581 		TCP_STAT(tcp_reinput_syn);
24582 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
24583 		    connp, SQTAG_TCP_REINPUT_EAGER);
24584 		return;
24585 	}
24586 
24587 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
24588 	case IPV4_VERSION:
24589 		ipha = (ipha_t *)mp->b_rptr;
24590 		hdr_len = IPH_HDR_LENGTH(ipha);
24591 		break;
24592 	case IPV6_VERSION:
24593 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
24594 		    &hdr_len, &nexthdrp)) {
24595 			CONN_DEC_REF(connp);
24596 			freemsg(mp);
24597 			return;
24598 		}
24599 		break;
24600 	}
24601 
24602 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
24603 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
24604 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
24605 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
24606 	}
24607 
24608 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
24609 	    SQTAG_TCP_REINPUT);
24610 }
24611 
24612 static squeue_func_t
24613 tcp_squeue_switch(int val)
24614 {
24615 	squeue_func_t rval = squeue_fill;
24616 
24617 	switch (val) {
24618 	case 1:
24619 		rval = squeue_enter_nodrain;
24620 		break;
24621 	case 2:
24622 		rval = squeue_enter;
24623 		break;
24624 	default:
24625 		break;
24626 	}
24627 	return (rval);
24628 }
24629 
24630 static void
24631 tcp_squeue_add(squeue_t *sqp)
24632 {
24633 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
24634 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
24635 
24636 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
24637 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
24638 	    sqp, TCP_TIME_WAIT_DELAY);
24639 }
24640