xref: /titanic_50/usr/src/uts/common/inet/tcp/tcp.c (revision afd1ac7b1c9a8cdf273c865aa5e9a14620341443)
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 #include <inet/kssl/ksslapi.h>
98 
99 /*
100  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
101  *
102  * (Read the detailed design doc in PSARC case directory)
103  *
104  * The entire tcp state is contained in tcp_t and conn_t structure
105  * which are allocated in tandem using ipcl_conn_create() and passing
106  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
107  * the references on the tcp_t. The tcp_t structure is never compressed
108  * and packets always land on the correct TCP perimeter from the time
109  * eager is created till the time tcp_t dies (as such the old mentat
110  * TCP global queue is not used for detached state and no IPSEC checking
111  * is required). The global queue is still allocated to send out resets
112  * for connection which have no listeners and IP directly calls
113  * tcp_xmit_listeners_reset() which does any policy check.
114  *
115  * Protection and Synchronisation mechanism:
116  *
117  * The tcp data structure does not use any kind of lock for protecting
118  * its state but instead uses 'squeues' for mutual exclusion from various
119  * read and write side threads. To access a tcp member, the thread should
120  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
121  * squeue_fill). Since the squeues allow a direct function call, caller
122  * can pass any tcp function having prototype of edesc_t as argument
123  * (different from traditional STREAMs model where packets come in only
124  * designated entry points). The list of functions that can be directly
125  * called via squeue are listed before the usual function prototype.
126  *
127  * Referencing:
128  *
129  * TCP is MT-Hot and we use a reference based scheme to make sure that the
130  * tcp structure doesn't disappear when its needed. When the application
131  * creates an outgoing connection or accepts an incoming connection, we
132  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
133  * The IP reference is just a symbolic reference since ip_tcpclose()
134  * looks at tcp structure after tcp_close_output() returns which could
135  * have dropped the last TCP reference. So as long as the connection is
136  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
137  * conn_t. The classifier puts its own reference when the connection is
138  * inserted in listen or connected hash. Anytime a thread needs to enter
139  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
140  * on write side or by doing a classify on read side and then puts a
141  * reference on the conn before doing squeue_enter/tryenter/fill. For
142  * read side, the classifier itself puts the reference under fanout lock
143  * to make sure that tcp can't disappear before it gets processed. The
144  * squeue will drop this reference automatically so the called function
145  * doesn't have to do a DEC_REF.
146  *
147  * Opening a new connection:
148  *
149  * The outgoing connection open is pretty simple. ip_tcpopen() does the
150  * work in creating the conn/tcp structure and initializing it. The
151  * squeue assignment is done based on the CPU the application
152  * is running on. So for outbound connections, processing is always done
153  * on application CPU which might be different from the incoming CPU
154  * being interrupted by the NIC. An optimal way would be to figure out
155  * the NIC <-> CPU binding at listen time, and assign the outgoing
156  * connection to the squeue attached to the CPU that will be interrupted
157  * for incoming packets (we know the NIC based on the bind IP address).
158  * This might seem like a problem if more data is going out but the
159  * fact is that in most cases the transmit is ACK driven transmit where
160  * the outgoing data normally sits on TCP's xmit queue waiting to be
161  * transmitted.
162  *
163  * Accepting a connection:
164  *
165  * This is a more interesting case because of various races involved in
166  * establishing a eager in its own perimeter. Read the meta comment on
167  * top of tcp_conn_request(). But briefly, the squeue is picked by
168  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
169  *
170  * Closing a connection:
171  *
172  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
173  * via squeue to do the close and mark the tcp as detached if the connection
174  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
175  * reference but tcp_close() drop IP's reference always. So if tcp was
176  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
177  * and 1 because it is in classifier's connected hash. This is the condition
178  * we use to determine that its OK to clean up the tcp outside of squeue
179  * when time wait expires (check the ref under fanout and conn_lock and
180  * if it is 2, remove it from fanout hash and kill it).
181  *
182  * Although close just drops the necessary references and marks the
183  * tcp_detached state, tcp_close needs to know the tcp_detached has been
184  * set (under squeue) before letting the STREAM go away (because a
185  * inbound packet might attempt to go up the STREAM while the close
186  * has happened and tcp_detached is not set). So a special lock and
187  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
188  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
189  * tcp_detached.
190  *
191  * Special provisions and fast paths:
192  *
193  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
194  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
195  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
196  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
197  * check to send packets directly to tcp_rput_data via squeue. Everyone
198  * else comes through tcp_input() on the read side.
199  *
200  * We also make special provisions for sockfs by marking tcp_issocket
201  * whenever we have only sockfs on top of TCP. This allows us to skip
202  * putting the tcp in acceptor hash since a sockfs listener can never
203  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
204  * since eager has already been allocated and the accept now happens
205  * on acceptor STREAM. There is a big blob of comment on top of
206  * tcp_conn_request explaining the new accept. When socket is POP'd,
207  * sockfs sends us an ioctl to mark the fact and we go back to old
208  * behaviour. Once tcp_issocket is unset, its never set for the
209  * life of that connection.
210  *
211  * IPsec notes :
212  *
213  * Since a packet is always executed on the correct TCP perimeter
214  * all IPsec processing is defered to IP including checking new
215  * connections and setting IPSEC policies for new connection. The
216  * only exception is tcp_xmit_listeners_reset() which is called
217  * directly from IP and needs to policy check to see if TH_RST
218  * can be sent out.
219  */
220 
221 
222 extern major_t TCP6_MAJ;
223 
224 /*
225  * Values for squeue switch:
226  * 1: squeue_enter_nodrain
227  * 2: squeue_enter
228  * 3: squeue_fill
229  */
230 int tcp_squeue_close = 2;
231 int tcp_squeue_wput = 2;
232 
233 squeue_func_t tcp_squeue_close_proc;
234 squeue_func_t tcp_squeue_wput_proc;
235 
236 /*
237  * This controls how tiny a write must be before we try to copy it
238  * into the the mblk on the tail of the transmit queue.  Not much
239  * speedup is observed for values larger than sixteen.  Zero will
240  * disable the optimisation.
241  */
242 int tcp_tx_pull_len = 16;
243 
244 /*
245  * TCP Statistics.
246  *
247  * How TCP statistics work.
248  *
249  * There are two types of statistics invoked by two macros.
250  *
251  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
252  * supposed to be used in non MT-hot paths of the code.
253  *
254  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
255  * supposed to be used for DEBUG purposes and may be used on a hot path.
256  *
257  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
258  * (use "kstat tcp" to get them).
259  *
260  * There is also additional debugging facility that marks tcp_clean_death()
261  * instances and saves them in tcp_t structure. It is triggered by
262  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
263  * tcp_clean_death() calls that counts the number of times each tag was hit. It
264  * is triggered by TCP_CLD_COUNTERS define.
265  *
266  * How to add new counters.
267  *
268  * 1) Add a field in the tcp_stat structure describing your counter.
269  * 2) Add a line in tcp_statistics with the name of the counter.
270  *
271  *    IMPORTANT!! - make sure that both are in sync !!
272  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
273  *
274  * Please avoid using private counters which are not kstat-exported.
275  *
276  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
277  * in tcp_t structure.
278  *
279  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
280  */
281 
282 #ifndef TCP_DEBUG_COUNTER
283 #ifdef DEBUG
284 #define	TCP_DEBUG_COUNTER 1
285 #else
286 #define	TCP_DEBUG_COUNTER 0
287 #endif
288 #endif
289 
290 #define	TCP_CLD_COUNTERS 0
291 
292 #define	TCP_TAG_CLEAN_DEATH 1
293 #define	TCP_MAX_CLEAN_DEATH_TAG 32
294 
295 #ifdef lint
296 static int _lint_dummy_;
297 #endif
298 
299 #if TCP_CLD_COUNTERS
300 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
301 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
302 #elif defined(lint)
303 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
304 #else
305 #define	TCP_CLD_STAT(x)
306 #endif
307 
308 #if TCP_DEBUG_COUNTER
309 #define	TCP_DBGSTAT(x) atomic_add_64(&(tcp_statistics.x.value.ui64), 1)
310 #elif defined(lint)
311 #define	TCP_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
312 #else
313 #define	TCP_DBGSTAT(x)
314 #endif
315 
316 tcp_stat_t tcp_statistics = {
317 	{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
318 	{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
319 	{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
320 	{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
321 	{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
322 	{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
323 	{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
324 	{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
325 	{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
326 	{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
327 	{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
328 	{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
329 	{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
330 	{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
331 	{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
332 	{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
333 	{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
334 	{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
335 	{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
336 	{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
337 	{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
338 	{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
339 	{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
340 	{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
341 	{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
342 	{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
343 	{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
344 	{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
345 	{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
346 	{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
347 	{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
348 	{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
349 	{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
350 	{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
351 	{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
352 	{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
353 	{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
354 	{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
355 	{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
356 	{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
357 	{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
358 	{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
359 	{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
360 	{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
361 	{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
362 	{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
363 	{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
364 	{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
365 	{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
366 	{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
367 	{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
368 	{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
369 	{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
370 	{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
371 	{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
372 	{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
373 	{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
374 	{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
375 	{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
376 	{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
377 	{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
378 	{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
379 	{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
380 	{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
381 	{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
382 	{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
383 	{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
384 	{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
385 	{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
386 	{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
387 	{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
388 	{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
389 	{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
390 	{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
391 	{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
392 	{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
393 	{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
394 	{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
395 	{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
396 	{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
397 	{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
398 	{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
399 	{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
400 	{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
401 	{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
402 	{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
403 	{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
404 	{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
405 	{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
406 };
407 
408 static kstat_t *tcp_kstat;
409 
410 /*
411  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
412  * tcp write side.
413  */
414 #define	CALL_IP_WPUT(connp, q, mp) {					\
415 	ASSERT(((q)->q_flag & QREADR) == 0);				\
416 	TCP_DBGSTAT(tcp_ip_output);					\
417 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
418 }
419 
420 /* Macros for timestamp comparisons */
421 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
422 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
423 
424 /*
425  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
426  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
427  * by adding three components: a time component which grows by 1 every 4096
428  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
429  * a per-connection component which grows by 125000 for every new connection;
430  * and an "extra" component that grows by a random amount centered
431  * approximately on 64000.  This causes the the ISS generator to cycle every
432  * 4.89 hours if no TCP connections are made, and faster if connections are
433  * made.
434  *
435  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
436  * components: a time component which grows by 250000 every second; and
437  * a per-connection component which grows by 125000 for every new connections.
438  *
439  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
440  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
441  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
442  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
443  * password.
444  */
445 #define	ISS_INCR	250000
446 #define	ISS_NSEC_SHT	12
447 
448 static uint32_t tcp_iss_incr_extra;	/* Incremented for each connection */
449 static kmutex_t tcp_iss_key_lock;
450 static MD5_CTX tcp_iss_key;
451 static sin_t	sin_null;	/* Zero address for quick clears */
452 static sin6_t	sin6_null;	/* Zero address for quick clears */
453 
454 /* Packet dropper for TCP IPsec policy drops. */
455 static ipdropper_t tcp_dropper;
456 
457 /*
458  * This implementation follows the 4.3BSD interpretation of the urgent
459  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
460  * incompatible changes in protocols like telnet and rlogin.
461  */
462 #define	TCP_OLD_URP_INTERPRETATION	1
463 
464 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
465 	(TCP_IS_DETACHED(tcp) && \
466 	    (!(tcp)->tcp_hard_binding))
467 
468 /*
469  * TCP reassembly macros.  We hide starting and ending sequence numbers in
470  * b_next and b_prev of messages on the reassembly queue.  The messages are
471  * chained using b_cont.  These macros are used in tcp_reass() so we don't
472  * have to see the ugly casts and assignments.
473  */
474 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
475 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
476 					(mblk_t *)(uintptr_t)(u))
477 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
478 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
479 					(mblk_t *)(uintptr_t)(u))
480 
481 /*
482  * Implementation of TCP Timers.
483  * =============================
484  *
485  * INTERFACE:
486  *
487  * There are two basic functions dealing with tcp timers:
488  *
489  *	timeout_id_t	tcp_timeout(connp, func, time)
490  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
491  *	TCP_TIMER_RESTART(tcp, intvl)
492  *
493  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
494  * after 'time' ticks passed. The function called by timeout() must adhere to
495  * the same restrictions as a driver soft interrupt handler - it must not sleep
496  * or call other functions that might sleep. The value returned is the opaque
497  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
498  * cancel the request. The call to tcp_timeout() may fail in which case it
499  * returns zero. This is different from the timeout(9F) function which never
500  * fails.
501  *
502  * The call-back function 'func' always receives 'connp' as its single
503  * argument. It is always executed in the squeue corresponding to the tcp
504  * structure. The tcp structure is guaranteed to be present at the time the
505  * call-back is called.
506  *
507  * NOTE: The call-back function 'func' is never called if tcp is in
508  * 	the TCPS_CLOSED state.
509  *
510  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
511  * request. locks acquired by the call-back routine should not be held across
512  * the call to tcp_timeout_cancel() or a deadlock may result.
513  *
514  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
515  * Otherwise, it returns an integer value greater than or equal to 0. In
516  * particular, if the call-back function is already placed on the squeue, it can
517  * not be canceled.
518  *
519  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
520  * 	within squeue context corresponding to the tcp instance. Since the
521  *	call-back is also called via the same squeue, there are no race
522  *	conditions described in untimeout(9F) manual page since all calls are
523  *	strictly serialized.
524  *
525  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
526  *	stored in tcp_timer_tid and starts a new one using
527  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
528  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
529  *	field.
530  *
531  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
532  *	call-back may still be called, so it is possible tcp_timer() will be
533  *	called several times. This should not be a problem since tcp_timer()
534  *	should always check the tcp instance state.
535  *
536  *
537  * IMPLEMENTATION:
538  *
539  * TCP timers are implemented using three-stage process. The call to
540  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
541  * when the timer expires. The tcp_timer_callback() arranges the call of the
542  * tcp_timer_handler() function via squeue corresponding to the tcp
543  * instance. The tcp_timer_handler() calls actual requested timeout call-back
544  * and passes tcp instance as an argument to it. Information is passed between
545  * stages using the tcp_timer_t structure which contains the connp pointer, the
546  * tcp call-back to call and the timeout id returned by the timeout(9F).
547  *
548  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
549  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
550  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
551  * returns the pointer to this mblk.
552  *
553  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
554  * looks like a normal mblk without actual dblk attached to it.
555  *
556  * To optimize performance each tcp instance holds a small cache of timer
557  * mblocks. In the current implementation it caches up to two timer mblocks per
558  * tcp instance. The cache is preserved over tcp frees and is only freed when
559  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
560  * timer processing happens on a corresponding squeue, the cache manipulation
561  * does not require any locks. Experiments show that majority of timer mblocks
562  * allocations are satisfied from the tcp cache and do not involve kmem calls.
563  *
564  * The tcp_timeout() places a refhold on the connp instance which guarantees
565  * that it will be present at the time the call-back function fires. The
566  * tcp_timer_handler() drops the reference after calling the call-back, so the
567  * call-back function does not need to manipulate the references explicitly.
568  */
569 
570 typedef struct tcp_timer_s {
571 	conn_t	*connp;
572 	void 	(*tcpt_proc)(void *);
573 	timeout_id_t   tcpt_tid;
574 } tcp_timer_t;
575 
576 static kmem_cache_t *tcp_timercache;
577 kmem_cache_t	*tcp_sack_info_cache;
578 kmem_cache_t	*tcp_iphc_cache;
579 
580 /*
581  * For scalability, we must not run a timer for every TCP connection
582  * in TIME_WAIT state.  To see why, consider (for time wait interval of
583  * 4 minutes):
584  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
585  *
586  * This list is ordered by time, so you need only delete from the head
587  * until you get to entries which aren't old enough to delete yet.
588  * The list consists of only the detached TIME_WAIT connections.
589  *
590  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
591  * becomes detached TIME_WAIT (either by changing the state and already
592  * being detached or the other way around). This means that the TIME_WAIT
593  * state can be extended (up to doubled) if the connection doesn't become
594  * detached for a long time.
595  *
596  * The list manipulations (including tcp_time_wait_next/prev)
597  * are protected by the tcp_time_wait_lock. The content of the
598  * detached TIME_WAIT connections is protected by the normal perimeters.
599  */
600 
601 typedef struct tcp_squeue_priv_s {
602 	kmutex_t	tcp_time_wait_lock;
603 				/* Protects the next 3 globals */
604 	timeout_id_t	tcp_time_wait_tid;
605 	tcp_t		*tcp_time_wait_head;
606 	tcp_t		*tcp_time_wait_tail;
607 	tcp_t		*tcp_free_list;
608 } tcp_squeue_priv_t;
609 
610 /*
611  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
612  * Running it every 5 seconds seems to give the best results.
613  */
614 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
615 
616 
617 #define	TCP_XMIT_LOWATER	4096
618 #define	TCP_XMIT_HIWATER	49152
619 #define	TCP_RECV_LOWATER	2048
620 #define	TCP_RECV_HIWATER	49152
621 
622 /*
623  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
624  */
625 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
626 
627 #define	TIDUSZ	4096	/* transport interface data unit size */
628 
629 /*
630  * Bind hash list size and has function.  It has to be a power of 2 for
631  * hashing.
632  */
633 #define	TCP_BIND_FANOUT_SIZE	512
634 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
635 /*
636  * Size of listen and acceptor hash list.  It has to be a power of 2 for
637  * hashing.
638  */
639 #define	TCP_FANOUT_SIZE		256
640 
641 #ifdef	_ILP32
642 #define	TCP_ACCEPTOR_HASH(accid)					\
643 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
644 #else
645 #define	TCP_ACCEPTOR_HASH(accid)					\
646 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
647 #endif	/* _ILP32 */
648 
649 #define	IP_ADDR_CACHE_SIZE	2048
650 #define	IP_ADDR_CACHE_HASH(faddr)					\
651 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
652 
653 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
654 #define	TCP_HSP_HASH_SIZE 256
655 
656 #define	TCP_HSP_HASH(addr)					\
657 	(((addr>>24) ^ (addr >>16) ^			\
658 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
659 
660 /*
661  * TCP options struct returned from tcp_parse_options.
662  */
663 typedef struct tcp_opt_s {
664 	uint32_t	tcp_opt_mss;
665 	uint32_t	tcp_opt_wscale;
666 	uint32_t	tcp_opt_ts_val;
667 	uint32_t	tcp_opt_ts_ecr;
668 	tcp_t		*tcp;
669 } tcp_opt_t;
670 
671 /*
672  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
673  */
674 
675 #ifdef _BIG_ENDIAN
676 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
677 	(TCPOPT_TSTAMP << 8) | 10)
678 #else
679 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
680 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
681 #endif
682 
683 /*
684  * Flags returned from tcp_parse_options.
685  */
686 #define	TCP_OPT_MSS_PRESENT	1
687 #define	TCP_OPT_WSCALE_PRESENT	2
688 #define	TCP_OPT_TSTAMP_PRESENT	4
689 #define	TCP_OPT_SACK_OK_PRESENT	8
690 #define	TCP_OPT_SACK_PRESENT	16
691 
692 /* TCP option length */
693 #define	TCPOPT_NOP_LEN		1
694 #define	TCPOPT_MAXSEG_LEN	4
695 #define	TCPOPT_WS_LEN		3
696 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
697 #define	TCPOPT_TSTAMP_LEN	10
698 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
699 #define	TCPOPT_SACK_OK_LEN	2
700 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
701 #define	TCPOPT_REAL_SACK_LEN	4
702 #define	TCPOPT_MAX_SACK_LEN	36
703 #define	TCPOPT_HEADER_LEN	2
704 
705 /* TCP cwnd burst factor. */
706 #define	TCP_CWND_INFINITE	65535
707 #define	TCP_CWND_SS		3
708 #define	TCP_CWND_NORMAL		5
709 
710 /* Maximum TCP initial cwin (start/restart). */
711 #define	TCP_MAX_INIT_CWND	8
712 
713 /*
714  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
715  * either tcp_slow_start_initial or tcp_slow_start_after idle
716  * depending on the caller.  If the upper layer has not used the
717  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
718  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
719  * If the upper layer has changed set the tcp_init_cwnd, just use
720  * it to calculate the tcp_cwnd.
721  */
722 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
723 {									\
724 	if ((tcp)->tcp_init_cwnd == 0) {				\
725 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
726 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
727 	} else {							\
728 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
729 	}								\
730 	tcp->tcp_cwnd_cnt = 0;						\
731 }
732 
733 /* TCP Timer control structure */
734 typedef struct tcpt_s {
735 	pfv_t	tcpt_pfv;	/* The routine we are to call */
736 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
737 } tcpt_t;
738 
739 /* Host Specific Parameter structure */
740 typedef struct tcp_hsp {
741 	struct tcp_hsp	*tcp_hsp_next;
742 	in6_addr_t	tcp_hsp_addr_v6;
743 	in6_addr_t	tcp_hsp_subnet_v6;
744 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
745 	int32_t		tcp_hsp_sendspace;
746 	int32_t		tcp_hsp_recvspace;
747 	int32_t		tcp_hsp_tstamp;
748 } tcp_hsp_t;
749 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
750 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
751 
752 /*
753  * Functions called directly via squeue having a prototype of edesc_t.
754  */
755 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
756 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
757 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
758 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
759 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
760 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
761 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
762 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
763 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
764 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
765 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
766 
767 
768 /* Prototype for TCP functions */
769 static void	tcp_random_init(void);
770 int		tcp_random(void);
771 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
772 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
773 		    tcp_t *eager);
774 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
775 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
776     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
777     boolean_t user_specified);
778 static void	tcp_closei_local(tcp_t *tcp);
779 static void	tcp_close_detached(tcp_t *tcp);
780 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
781 			mblk_t *idmp, mblk_t **defermp);
782 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
783 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
784 		    in_port_t dstport, uint_t srcid);
785 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
786 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
787 		    uint32_t scope_id);
788 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
789 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
790 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
791 static char	*tcp_display(tcp_t *tcp, char *, char);
792 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
793 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
794 static void	tcp_eager_unlink(tcp_t *tcp);
795 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
796 		    int unixerr);
797 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
798 		    int tlierr, int unixerr);
799 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
800 		    cred_t *cr);
801 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
802 		    char *value, caddr_t cp, cred_t *cr);
803 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
804 		    char *value, caddr_t cp, cred_t *cr);
805 static int	tcp_tpistate(tcp_t *tcp);
806 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
807     int caller_holds_lock);
808 static void	tcp_bind_hash_remove(tcp_t *tcp);
809 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id);
810 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
811 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
812 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
813 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
814 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
815 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
816 static int	tcp_header_init_ipv4(tcp_t *tcp);
817 static int	tcp_header_init_ipv6(tcp_t *tcp);
818 int		tcp_init(tcp_t *tcp, queue_t *q);
819 static int	tcp_init_values(tcp_t *tcp);
820 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
821 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
822 		    t_scalar_t addr_length);
823 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
824 static void	tcp_ip_notify(tcp_t *tcp);
825 static mblk_t	*tcp_ire_mp(mblk_t *mp);
826 static void	tcp_iss_init(tcp_t *tcp);
827 static void	tcp_keepalive_killer(void *arg);
828 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
829 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
830 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
831 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
832 static boolean_t tcp_allow_connopt_set(int level, int name);
833 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
834 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
835 static int	tcp_opt_get_user(ipha_t *ipha, uchar_t *ptr);
836 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
837 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
838 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
839 		    mblk_t *mblk);
840 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
841 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
842 		    uchar_t *ptr, uint_t len);
843 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
844 static boolean_t tcp_param_register(tcpparam_t *tcppa, int cnt);
845 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
846 		    caddr_t cp, cred_t *cr);
847 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
848 		    caddr_t cp, cred_t *cr);
849 static void	tcp_iss_key_init(uint8_t *phrase, int len);
850 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
851 		    caddr_t cp, cred_t *cr);
852 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
853 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
854 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
855 static void	tcp_reinit(tcp_t *tcp);
856 static void	tcp_reinit_values(tcp_t *tcp);
857 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
858 		    tcp_t *thisstream, cred_t *cr);
859 
860 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
861 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
862 static boolean_t tcp_send_rst_chk(void);
863 static void	tcp_ss_rexmit(tcp_t *tcp);
864 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
865 static void	tcp_process_options(tcp_t *, tcph_t *);
866 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
867 static void	tcp_rsrv(queue_t *q);
868 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
869 static int	tcp_snmp_state(tcp_t *tcp);
870 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
871 		    cred_t *cr);
872 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
873 		    cred_t *cr);
874 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
875 		    cred_t *cr);
876 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
877 		    cred_t *cr);
878 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
879 		    cred_t *cr);
880 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
881 		    caddr_t cp, cred_t *cr);
882 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
883 		    caddr_t cp, cred_t *cr);
884 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
885 		    cred_t *cr);
886 static void	tcp_timer(void *arg);
887 static void	tcp_timer_callback(void *);
888 static in_port_t tcp_update_next_port(in_port_t port, boolean_t random);
889 static in_port_t tcp_get_next_priv_port(void);
890 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
891 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
892 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
893 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
894 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
895 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
896 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
897 		    const int num_sack_blk, int *usable, uint_t *snxt,
898 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
899 		    const int mdt_thres);
900 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
901 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
902 		    const int num_sack_blk, int *usable, uint_t *snxt,
903 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
904 		    const int mdt_thres);
905 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
906 		    int num_sack_blk);
907 static void	tcp_wsrv(queue_t *q);
908 static int	tcp_xmit_end(tcp_t *tcp);
909 void		tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len);
910 static mblk_t	*tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send,
911 		    int32_t *offset, mblk_t **end_mp, uint32_t seq,
912 		    boolean_t sendall, uint32_t *seg_len, boolean_t rexmit);
913 static void	tcp_ack_timer(void *arg);
914 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
915 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
916 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len);
917 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
918 		    uint32_t ack, int ctl);
919 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr);
920 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr);
921 static int	setmaxps(queue_t *q, int maxpsz);
922 static void	tcp_set_rto(tcp_t *, time_t);
923 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
924 		    boolean_t, boolean_t);
925 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
926 		    boolean_t ipsec_mctl);
927 static boolean_t tcp_cmpbuf(void *a, uint_t alen,
928 		    boolean_t b_valid, void *b, uint_t blen);
929 static boolean_t tcp_allocbuf(void **dstp, uint_t *dstlenp,
930 		    boolean_t src_valid, void *src, uint_t srclen);
931 static void	tcp_savebuf(void **dstp, uint_t *dstlenp,
932 		    boolean_t src_valid, void *src, uint_t srclen);
933 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
934 		    char *opt, int optlen);
935 static int	tcp_pkt_set(uchar_t *, uint_t, uchar_t **, uint_t *);
936 static int	tcp_build_hdrs(queue_t *, tcp_t *);
937 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
938 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
939 		    tcph_t *tcph);
940 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
941 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
942 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
943 boolean_t	tcp_reserved_port_check(in_port_t);
944 static tcp_t	*tcp_alloc_temp_tcp(in_port_t);
945 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
946 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
947 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
948 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
949 		    const boolean_t, const uint32_t, const uint32_t,
950 		    const uint32_t, const uint32_t);
951 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
952 		    const uint_t, const uint_t, boolean_t *);
953 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
954 extern mblk_t	*tcp_timermp_alloc(int);
955 extern void	tcp_timermp_free(tcp_t *);
956 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
957 static void	tcp_stop_lingering(tcp_t *tcp);
958 static void	tcp_close_linger_timeout(void *arg);
959 void		tcp_ddi_init(void);
960 void		tcp_ddi_destroy(void);
961 static void	tcp_kstat_init(void);
962 static void	tcp_kstat_fini(void);
963 static int	tcp_kstat_update(kstat_t *kp, int rw);
964 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
965 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
966 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
967 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
968 			tcph_t *tcph, mblk_t *idmp);
969 static squeue_func_t tcp_squeue_switch(int);
970 
971 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
972 static int	tcp_close(queue_t *, int);
973 static int	tcpclose_accept(queue_t *);
974 static int	tcp_modclose(queue_t *);
975 static void	tcp_wput_mod(queue_t *, mblk_t *);
976 
977 static void	tcp_squeue_add(squeue_t *);
978 static boolean_t tcp_zcopy_check(tcp_t *);
979 static void	tcp_zcopy_notify(tcp_t *);
980 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
981 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
982 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
983 
984 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
985 
986 /*
987  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
988  *
989  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
990  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
991  * (defined in tcp.h) needs to be filled in and passed into the kernel
992  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
993  * structure contains the four-tuple of a TCP connection and a range of TCP
994  * states (specified by ac_start and ac_end). The use of wildcard addresses
995  * and ports is allowed. Connections with a matching four tuple and a state
996  * within the specified range will be aborted. The valid states for the
997  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
998  * inclusive.
999  *
1000  * An application which has its connection aborted by this ioctl will receive
1001  * an error that is dependent on the connection state at the time of the abort.
1002  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1003  * though a RST packet has been received.  If the connection state is equal to
1004  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1005  * and all resources associated with the connection will be freed.
1006  */
1007 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1008 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1009 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1010 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *);
1011 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1012 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1013     boolean_t);
1014 
1015 static struct module_info tcp_rinfo =  {
1016 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1017 };
1018 
1019 static struct module_info tcp_winfo =  {
1020 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1021 };
1022 
1023 /*
1024  * Entry points for TCP as a module. It only allows SNMP requests
1025  * to pass through.
1026  */
1027 struct qinit tcp_mod_rinit = {
1028 	(pfi_t)putnext, NULL, tcp_open, ip_snmpmod_close, NULL, &tcp_rinfo,
1029 };
1030 
1031 struct qinit tcp_mod_winit = {
1032 	(pfi_t)ip_snmpmod_wput, NULL, tcp_open, ip_snmpmod_close, NULL,
1033 	&tcp_rinfo
1034 };
1035 
1036 /*
1037  * Entry points for TCP as a device. The normal case which supports
1038  * the TCP functionality.
1039  */
1040 struct qinit tcp_rinit = {
1041 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
1042 };
1043 
1044 struct qinit tcp_winit = {
1045 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1046 };
1047 
1048 /* Initial entry point for TCP in socket mode. */
1049 struct qinit tcp_sock_winit = {
1050 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1051 };
1052 
1053 /*
1054  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1055  * an accept. Avoid allocating data structures since eager has already
1056  * been created.
1057  */
1058 struct qinit tcp_acceptor_rinit = {
1059 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1060 };
1061 
1062 struct qinit tcp_acceptor_winit = {
1063 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1064 };
1065 
1066 /*
1067  * Entry points for TCP loopback (read side only)
1068  */
1069 struct qinit tcp_loopback_rinit = {
1070 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_open, tcp_close, (pfi_t)0,
1071 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1072 };
1073 
1074 struct streamtab tcpinfo = {
1075 	&tcp_rinit, &tcp_winit
1076 };
1077 
1078 extern squeue_func_t tcp_squeue_wput_proc;
1079 extern squeue_func_t tcp_squeue_timer_proc;
1080 
1081 /* Protected by tcp_g_q_lock */
1082 static queue_t	*tcp_g_q;	/* Default queue used during detached closes */
1083 kmutex_t tcp_g_q_lock;
1084 
1085 /* Protected by tcp_hsp_lock */
1086 /*
1087  * XXX The host param mechanism should go away and instead we should use
1088  * the metrics associated with the routes to determine the default sndspace
1089  * and rcvspace.
1090  */
1091 static tcp_hsp_t	**tcp_hsp_hash;	/* Hash table for HSPs */
1092 krwlock_t tcp_hsp_lock;
1093 
1094 /*
1095  * Extra privileged ports. In host byte order.
1096  * Protected by tcp_epriv_port_lock.
1097  */
1098 #define	TCP_NUM_EPRIV_PORTS	64
1099 static int	tcp_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
1100 static uint16_t	tcp_g_epriv_ports[TCP_NUM_EPRIV_PORTS] = { 2049, 4045 };
1101 kmutex_t tcp_epriv_port_lock;
1102 
1103 /*
1104  * The smallest anonymous port in the priviledged port range which TCP
1105  * looks for free port.  Use in the option TCP_ANONPRIVBIND.
1106  */
1107 static in_port_t tcp_min_anonpriv_port = 512;
1108 
1109 /* Only modified during _init and _fini thus no locking is needed. */
1110 static caddr_t	tcp_g_nd;	/* Head of 'named dispatch' variable list */
1111 
1112 /* Hint not protected by any lock */
1113 static uint_t	tcp_next_port_to_try;
1114 
1115 
1116 /* TCP bind hash list - all tcp_t with state >= BOUND. */
1117 tf_t	tcp_bind_fanout[TCP_BIND_FANOUT_SIZE];
1118 
1119 /* TCP queue hash list - all tcp_t in case they will be an acceptor. */
1120 static tf_t	tcp_acceptor_fanout[TCP_FANOUT_SIZE];
1121 
1122 /*
1123  * TCP has a private interface for other kernel modules to reserve a
1124  * port range for them to use.  Once reserved, TCP will not use any ports
1125  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1126  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1127  * has to be verified.
1128  *
1129  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1130  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1131  * range is [port a, port b] inclusive.  And each port range is between
1132  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1133  *
1134  * Note that the default anonymous port range starts from 32768.  There is
1135  * no port "collision" between that and the reserved port range.  If there
1136  * is port collision (because the default smallest anonymous port is lowered
1137  * or some apps specifically bind to ports in the reserved port range), the
1138  * system may not be able to reserve a port range even there are enough
1139  * unbound ports as a reserved port range contains consecutive ports .
1140  */
1141 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1142 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1143 #define	TCP_SMALLEST_RESERVED_PORT		10240
1144 #define	TCP_LARGEST_RESERVED_PORT		20480
1145 
1146 /* Structure to represent those reserved port ranges. */
1147 typedef struct tcp_rport_s {
1148 	in_port_t	lo_port;
1149 	in_port_t	hi_port;
1150 	tcp_t		**temp_tcp_array;
1151 } tcp_rport_t;
1152 
1153 /* The reserved port array. */
1154 static tcp_rport_t tcp_reserved_port[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
1155 
1156 /* Locks to protect the tcp_reserved_ports array. */
1157 static krwlock_t tcp_reserved_port_lock;
1158 
1159 /* The number of ranges in the array. */
1160 uint32_t tcp_reserved_port_array_size = 0;
1161 
1162 /*
1163  * MIB-2 stuff for SNMP
1164  * Note: tcpInErrs {tcp 15} is accumulated in ip.c
1165  */
1166 mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */
1167 kstat_t		*tcp_mibkp;	/* kstat exporting tcp_mib data */
1168 
1169 boolean_t tcp_icmp_source_quench = B_FALSE;
1170 /*
1171  * Following assumes TPI alignment requirements stay along 32 bit
1172  * boundaries
1173  */
1174 #define	ROUNDUP32(x) \
1175 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1176 
1177 /* Template for response to info request. */
1178 static struct T_info_ack tcp_g_t_info_ack = {
1179 	T_INFO_ACK,		/* PRIM_type */
1180 	0,			/* TSDU_size */
1181 	T_INFINITE,		/* ETSDU_size */
1182 	T_INVALID,		/* CDATA_size */
1183 	T_INVALID,		/* DDATA_size */
1184 	sizeof (sin_t),		/* ADDR_size */
1185 	0,			/* OPT_size - not initialized here */
1186 	TIDUSZ,			/* TIDU_size */
1187 	T_COTS_ORD,		/* SERV_type */
1188 	TCPS_IDLE,		/* CURRENT_state */
1189 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1190 };
1191 
1192 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1193 	T_INFO_ACK,		/* PRIM_type */
1194 	0,			/* TSDU_size */
1195 	T_INFINITE,		/* ETSDU_size */
1196 	T_INVALID,		/* CDATA_size */
1197 	T_INVALID,		/* DDATA_size */
1198 	sizeof (sin6_t),	/* ADDR_size */
1199 	0,			/* OPT_size - not initialized here */
1200 	TIDUSZ,		/* TIDU_size */
1201 	T_COTS_ORD,		/* SERV_type */
1202 	TCPS_IDLE,		/* CURRENT_state */
1203 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1204 };
1205 
1206 #define	MS	1L
1207 #define	SECONDS	(1000 * MS)
1208 #define	MINUTES	(60 * SECONDS)
1209 #define	HOURS	(60 * MINUTES)
1210 #define	DAYS	(24 * HOURS)
1211 
1212 #define	PARAM_MAX (~(uint32_t)0)
1213 
1214 /* Max size IP datagram is 64k - 1 */
1215 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1216 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1217 /* Max of the above */
1218 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1219 
1220 /* Largest TCP port number */
1221 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1222 
1223 /*
1224  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1225  * layer header.  It has to be a multiple of 4.
1226  */
1227 static tcpparam_t tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1228 #define	tcp_wroff_xtra	tcp_wroff_xtra_param.tcp_param_val
1229 
1230 /*
1231  * All of these are alterable, within the min/max values given, at run time.
1232  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1233  * per the TCP spec.
1234  */
1235 /* BEGIN CSTYLED */
1236 tcpparam_t	tcp_param_arr[] = {
1237  /*min		max		value		name */
1238  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1239  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1240  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1241  { 1,		1024,		1,		"tcp_conn_req_min" },
1242  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1243  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1244  { 0,		10,		0,		"tcp_debug" },
1245  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1246  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1247  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1248  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1249  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1250  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1251  { 1,		255,		64,		"tcp_ipv4_ttl"},
1252  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1253  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1254  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1255  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1256  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1257  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1258  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1259  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1260  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1261  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1262  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1263  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1264  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1265  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1266  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1267  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1268  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1269  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1270  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1271  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1272  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1273  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1274  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1275  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1276 /*
1277  * Question:  What default value should I set for tcp_strong_iss?
1278  */
1279  { 0,		2,		1,		"tcp_strong_iss"},
1280  { 0,		65536,		20,		"tcp_rtt_updates"},
1281  { 0,		1,		1,		"tcp_wscale_always"},
1282  { 0,		1,		0,		"tcp_tstamp_always"},
1283  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1284  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1285  { 0,		16,		2,		"tcp_deferred_acks_max"},
1286  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1287  { 1,		4,		4,		"tcp_slow_start_initial"},
1288  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1289  { 0,		2,		2,		"tcp_sack_permitted"},
1290  { 0,		1,		0,		"tcp_trace"},
1291  { 0,		1,		1,		"tcp_compression_enabled"},
1292  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1293  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1294  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1295  { 0,		1,		0,		"tcp_rev_src_routes"},
1296  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1297  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1298  { 0,		16,		8,		"tcp_local_dacks_max"},
1299  { 0,		2,		1,		"tcp_ecn_permitted"},
1300  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1301  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1302  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1303  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1304  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1305 };
1306 /* END CSTYLED */
1307 
1308 /*
1309  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1310  * each header fragment in the header buffer.  Each parameter value has
1311  * to be a multiple of 4 (32-bit aligned).
1312  */
1313 static tcpparam_t tcp_mdt_head_param = { 32, 256, 32, "tcp_mdt_hdr_head_min" };
1314 static tcpparam_t tcp_mdt_tail_param = { 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1315 #define	tcp_mdt_hdr_head_min	tcp_mdt_head_param.tcp_param_val
1316 #define	tcp_mdt_hdr_tail_min	tcp_mdt_tail_param.tcp_param_val
1317 
1318 /*
1319  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1320  * the maximum number of payload buffers associated per Multidata.
1321  */
1322 static tcpparam_t tcp_mdt_max_pbufs_param =
1323 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1324 #define	tcp_mdt_max_pbufs	tcp_mdt_max_pbufs_param.tcp_param_val
1325 
1326 /* Round up the value to the nearest mss. */
1327 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1328 
1329 /*
1330  * Set ECN capable transport (ECT) code point in IP header.
1331  *
1332  * Note that there are 2 ECT code points '01' and '10', which are called
1333  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1334  * point ECT(0) for TCP as described in RFC 2481.
1335  */
1336 #define	SET_ECT(tcp, iph) \
1337 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1338 		/* We need to clear the code point first. */ \
1339 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1340 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1341 	} else { \
1342 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1343 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1344 	}
1345 
1346 /*
1347  * The format argument to pass to tcp_display().
1348  * DISP_PORT_ONLY means that the returned string has only port info.
1349  * DISP_ADDR_AND_PORT means that the returned string also contains the
1350  * remote and local IP address.
1351  */
1352 #define	DISP_PORT_ONLY		1
1353 #define	DISP_ADDR_AND_PORT	2
1354 
1355 /*
1356  * This controls the rate some ndd info report functions can be used
1357  * by non-priviledged users.  It stores the last time such info is
1358  * requested.  When those report functions are called again, this
1359  * is checked with the current time and compare with the ndd param
1360  * tcp_ndd_get_info_interval.
1361  */
1362 static clock_t tcp_last_ndd_get_info_time = 0;
1363 #define	NDD_TOO_QUICK_MSG \
1364 	"ndd get info rate too high for non-priviledged users, try again " \
1365 	"later.\n"
1366 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1367 
1368 #define	IS_VMLOANED_MBLK(mp) \
1369 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1370 
1371 /*
1372  * These two variables control the rate for TCP to generate RSTs in
1373  * response to segments not belonging to any connections.  We limit
1374  * TCP to sent out tcp_rst_sent_rate (ndd param) number of RSTs in
1375  * each 1 second interval.  This is to protect TCP against DoS attack.
1376  */
1377 static clock_t tcp_last_rst_intrvl;
1378 static uint32_t tcp_rst_cnt;
1379 
1380 /* The number of RST not sent because of the rate limit. */
1381 static uint32_t tcp_rst_unsent;
1382 
1383 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1384 boolean_t tcp_mdt_chain = B_TRUE;
1385 
1386 /*
1387  * MDT threshold in the form of effective send MSS multiplier; we take
1388  * the MDT path if the amount of unsent data exceeds the threshold value
1389  * (default threshold is 1*SMSS).
1390  */
1391 uint_t tcp_mdt_smss_threshold = 1;
1392 
1393 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1394 
1395 /*
1396  * Forces all connections to obey the value of the tcp_maxpsz_multiplier
1397  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1398  * determined dynamically during tcp_adapt_ire(), which is the default.
1399  */
1400 boolean_t tcp_static_maxpsz = B_FALSE;
1401 
1402 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1403 uint32_t tcp_random_anon_port = 1;
1404 
1405 /*
1406  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1407  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1408  * data, TCP will not respond with an ACK.  RFC 793 requires that
1409  * TCP responds with an ACK for such a bogus ACK.  By not following
1410  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1411  * an attacker successfully spoofs an acceptable segment to our
1412  * peer; or when our peer is "confused."
1413  */
1414 uint32_t tcp_drop_ack_unsent_cnt = 10;
1415 
1416 /*
1417  * Hook functions to enable cluster networking
1418  * On non-clustered systems these vectors must always be NULL.
1419  */
1420 
1421 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1422 			    uint8_t *laddrp, in_port_t lport) = NULL;
1423 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1424 			    uint8_t *laddrp, in_port_t lport) = NULL;
1425 void (*cl_inet_connect)(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 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1429 			    uint8_t *laddrp, in_port_t lport,
1430 			    uint8_t *faddrp, in_port_t fport) = NULL;
1431 
1432 /*
1433  * The following are defined in ip.c
1434  */
1435 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1436 				uint8_t *laddrp);
1437 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1438 				uint8_t *laddrp, uint8_t *faddrp);
1439 
1440 #define	CL_INET_CONNECT(tcp)		{			\
1441 	if (cl_inet_connect != NULL) {				\
1442 		/*						\
1443 		 * Running in cluster mode - register active connection	\
1444 		 * information						\
1445 		 */							\
1446 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1447 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1448 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1449 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1450 				    (in_port_t)(tcp)->tcp_lport,	\
1451 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1452 				    (in_port_t)(tcp)->tcp_fport);	\
1453 			}						\
1454 		} else {						\
1455 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1456 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1457 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1458 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1459 				    (in_port_t)(tcp)->tcp_lport,	\
1460 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1461 				    (in_port_t)(tcp)->tcp_fport);	\
1462 			}						\
1463 		}							\
1464 	}								\
1465 }
1466 
1467 #define	CL_INET_DISCONNECT(tcp)	{				\
1468 	if (cl_inet_disconnect != NULL) {				\
1469 		/*							\
1470 		 * Running in cluster mode - deregister active		\
1471 		 * connection information				\
1472 		 */							\
1473 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1474 			if ((tcp)->tcp_ip_src != 0) {			\
1475 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1476 				    AF_INET,				\
1477 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1478 				    (in_port_t)(tcp)->tcp_lport,	\
1479 				    (uint8_t *)				\
1480 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1481 				    (in_port_t)(tcp)->tcp_fport);	\
1482 			}						\
1483 		} else {						\
1484 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1485 			    &(tcp)->tcp_ip_src_v6)) {			\
1486 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1487 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1488 				    (in_port_t)(tcp)->tcp_lport,	\
1489 				    (uint8_t *)				\
1490 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1491 				    (in_port_t)(tcp)->tcp_fport);	\
1492 			}						\
1493 		}							\
1494 	}								\
1495 }
1496 
1497 /*
1498  * Cluster networking hook for traversing current connection list.
1499  * This routine is used to extract the current list of live connections
1500  * which must continue to to be dispatched to this node.
1501  */
1502 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1503 
1504 /*
1505  * Figure out the value of window scale opton.  Note that the rwnd is
1506  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1507  * We cannot find the scale value and then do a round up of tcp_rwnd
1508  * because the scale value may not be correct after that.
1509  *
1510  * Set the compiler flag to make this function inline.
1511  */
1512 static void
1513 tcp_set_ws_value(tcp_t *tcp)
1514 {
1515 	int i;
1516 	uint32_t rwnd = tcp->tcp_rwnd;
1517 
1518 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1519 	    i++, rwnd >>= 1)
1520 		;
1521 	tcp->tcp_rcv_ws = i;
1522 }
1523 
1524 /*
1525  * Remove a connection from the list of detached TIME_WAIT connections.
1526  */
1527 static void
1528 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1529 {
1530 	boolean_t	locked = B_FALSE;
1531 
1532 	if (tcp_time_wait == NULL) {
1533 		tcp_time_wait = *((tcp_squeue_priv_t **)
1534 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1535 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1536 		locked = B_TRUE;
1537 	}
1538 
1539 	if (tcp->tcp_time_wait_expire == 0) {
1540 		ASSERT(tcp->tcp_time_wait_next == NULL);
1541 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1542 		if (locked)
1543 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1544 		return;
1545 	}
1546 	ASSERT(TCP_IS_DETACHED(tcp));
1547 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1548 
1549 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1550 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1551 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1552 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1553 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1554 			    NULL;
1555 		} else {
1556 			tcp_time_wait->tcp_time_wait_tail = NULL;
1557 		}
1558 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1559 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1560 		ASSERT(tcp->tcp_time_wait_next == NULL);
1561 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1562 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1563 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1564 	} else {
1565 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1566 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1567 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1568 		    tcp->tcp_time_wait_next;
1569 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1570 		    tcp->tcp_time_wait_prev;
1571 	}
1572 	tcp->tcp_time_wait_next = NULL;
1573 	tcp->tcp_time_wait_prev = NULL;
1574 	tcp->tcp_time_wait_expire = 0;
1575 
1576 	if (locked)
1577 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1578 }
1579 
1580 /*
1581  * Add a connection to the list of detached TIME_WAIT connections
1582  * and set its time to expire.
1583  */
1584 static void
1585 tcp_time_wait_append(tcp_t *tcp)
1586 {
1587 	tcp_squeue_priv_t *tcp_time_wait =
1588 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1589 		SQPRIVATE_TCP));
1590 
1591 	tcp_timers_stop(tcp);
1592 
1593 	/* Freed above */
1594 	ASSERT(tcp->tcp_timer_tid == 0);
1595 	ASSERT(tcp->tcp_ack_tid == 0);
1596 
1597 	/* must have happened at the time of detaching the tcp */
1598 	ASSERT(tcp->tcp_ptpahn == NULL);
1599 	ASSERT(tcp->tcp_flow_stopped == 0);
1600 	ASSERT(tcp->tcp_time_wait_next == NULL);
1601 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1602 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1603 	ASSERT(tcp->tcp_listener == NULL);
1604 
1605 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1606 	/*
1607 	 * The value computed below in tcp->tcp_time_wait_expire may
1608 	 * appear negative or wrap around. That is ok since our
1609 	 * interest is only in the difference between the current lbolt
1610 	 * value and tcp->tcp_time_wait_expire. But the value should not
1611 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1612 	 * The corresponding comparison in tcp_time_wait_collector() uses
1613 	 * modular arithmetic.
1614 	 */
1615 	tcp->tcp_time_wait_expire +=
1616 	    drv_usectohz(tcp_time_wait_interval * 1000);
1617 	if (tcp->tcp_time_wait_expire == 0)
1618 		tcp->tcp_time_wait_expire = 1;
1619 
1620 	ASSERT(TCP_IS_DETACHED(tcp));
1621 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1622 	ASSERT(tcp->tcp_time_wait_next == NULL);
1623 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1624 	TCP_DBGSTAT(tcp_time_wait);
1625 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1626 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1627 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1628 		tcp_time_wait->tcp_time_wait_head = tcp;
1629 	} else {
1630 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1631 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1632 		    TCPS_TIME_WAIT);
1633 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1634 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1635 	}
1636 	tcp_time_wait->tcp_time_wait_tail = tcp;
1637 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1638 }
1639 
1640 /* ARGSUSED */
1641 void
1642 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1643 {
1644 	conn_t	*connp = (conn_t *)arg;
1645 	tcp_t	*tcp = connp->conn_tcp;
1646 
1647 	ASSERT(tcp != NULL);
1648 	if (tcp->tcp_state == TCPS_CLOSED) {
1649 		return;
1650 	}
1651 
1652 	ASSERT((tcp->tcp_family == AF_INET &&
1653 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1654 	    (tcp->tcp_family == AF_INET6 &&
1655 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1656 	    tcp->tcp_ipversion == IPV6_VERSION)));
1657 	ASSERT(!tcp->tcp_listener);
1658 
1659 	TCP_STAT(tcp_time_wait_reap);
1660 	ASSERT(TCP_IS_DETACHED(tcp));
1661 
1662 	/*
1663 	 * Because they have no upstream client to rebind or tcp_close()
1664 	 * them later, we axe the connection here and now.
1665 	 */
1666 	tcp_close_detached(tcp);
1667 }
1668 
1669 void
1670 tcp_cleanup(tcp_t *tcp)
1671 {
1672 	mblk_t		*mp;
1673 	char		*tcp_iphc;
1674 	int		tcp_iphc_len;
1675 	int		tcp_hdr_grown;
1676 	tcp_sack_info_t	*tcp_sack_info;
1677 	conn_t		*connp = tcp->tcp_connp;
1678 
1679 	tcp_bind_hash_remove(tcp);
1680 	tcp_free(tcp);
1681 
1682 	/* Release any SSL context */
1683 	if (tcp->tcp_kssl_ent != NULL) {
1684 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1685 		tcp->tcp_kssl_ent = NULL;
1686 	}
1687 
1688 	if (tcp->tcp_kssl_ctx != NULL) {
1689 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1690 		tcp->tcp_kssl_ctx = NULL;
1691 	}
1692 	tcp->tcp_kssl_pending = B_FALSE;
1693 
1694 	conn_delete_ire(connp, NULL);
1695 	if (connp->conn_flags & IPCL_TCPCONN) {
1696 		if (connp->conn_latch != NULL)
1697 			IPLATCH_REFRELE(connp->conn_latch);
1698 		if (connp->conn_policy != NULL)
1699 			IPPH_REFRELE(connp->conn_policy);
1700 	}
1701 
1702 	/*
1703 	 * Since we will bzero the entire structure, we need to
1704 	 * remove it and reinsert it in global hash list. We
1705 	 * know the walkers can't get to this conn because we
1706 	 * had set CONDEMNED flag earlier and checked reference
1707 	 * under conn_lock so walker won't pick it and when we
1708 	 * go the ipcl_globalhash_remove() below, no walker
1709 	 * can get to it.
1710 	 */
1711 	ipcl_globalhash_remove(connp);
1712 
1713 	/* Save some state */
1714 	mp = tcp->tcp_timercache;
1715 
1716 	tcp_sack_info = tcp->tcp_sack_info;
1717 	tcp_iphc = tcp->tcp_iphc;
1718 	tcp_iphc_len = tcp->tcp_iphc_len;
1719 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1720 
1721 	bzero(connp, sizeof (conn_t));
1722 	bzero(tcp, sizeof (tcp_t));
1723 
1724 	/* restore the state */
1725 	tcp->tcp_timercache = mp;
1726 
1727 	tcp->tcp_sack_info = tcp_sack_info;
1728 	tcp->tcp_iphc = tcp_iphc;
1729 	tcp->tcp_iphc_len = tcp_iphc_len;
1730 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1731 
1732 
1733 	tcp->tcp_connp = connp;
1734 
1735 	connp->conn_tcp = tcp;
1736 	connp->conn_flags = IPCL_TCPCONN;
1737 	connp->conn_state_flags = CONN_INCIPIENT;
1738 	connp->conn_ulp = IPPROTO_TCP;
1739 	connp->conn_ref = 1;
1740 
1741 	ipcl_globalhash_insert(connp);
1742 }
1743 
1744 /*
1745  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1746  * is done forwards from the head.
1747  */
1748 /* ARGSUSED */
1749 void
1750 tcp_time_wait_collector(void *arg)
1751 {
1752 	tcp_t *tcp;
1753 	clock_t now;
1754 	mblk_t *mp;
1755 	conn_t *connp;
1756 	kmutex_t *lock;
1757 
1758 	squeue_t *sqp = (squeue_t *)arg;
1759 	tcp_squeue_priv_t *tcp_time_wait =
1760 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1761 
1762 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1763 	tcp_time_wait->tcp_time_wait_tid = 0;
1764 
1765 	if (tcp_time_wait->tcp_free_list != NULL &&
1766 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1767 		TCP_STAT(tcp_freelist_cleanup);
1768 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1769 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1770 			CONN_DEC_REF(tcp->tcp_connp);
1771 		}
1772 	}
1773 
1774 	/*
1775 	 * In order to reap time waits reliably, we should use a
1776 	 * source of time that is not adjustable by the user -- hence
1777 	 * the call to ddi_get_lbolt().
1778 	 */
1779 	now = ddi_get_lbolt();
1780 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1781 		/*
1782 		 * Compare times using modular arithmetic, since
1783 		 * lbolt can wrapover.
1784 		 */
1785 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1786 			break;
1787 		}
1788 
1789 		tcp_time_wait_remove(tcp, tcp_time_wait);
1790 
1791 		connp = tcp->tcp_connp;
1792 		ASSERT(connp->conn_fanout != NULL);
1793 		lock = &connp->conn_fanout->connf_lock;
1794 		/*
1795 		 * This is essentially a TW reclaim fast path optimization for
1796 		 * performance where the timewait collector checks under the
1797 		 * fanout lock (so that no one else can get access to the
1798 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1799 		 * the classifier hash list. If ref count is indeed 2, we can
1800 		 * just remove the conn under the fanout lock and avoid
1801 		 * cleaning up the conn under the squeue, provided that
1802 		 * clustering callbacks are not enabled. If clustering is
1803 		 * enabled, we need to make the clustering callback before
1804 		 * setting the CONDEMNED flag and after dropping all locks and
1805 		 * so we forego this optimization and fall back to the slow
1806 		 * path. Also please see the comments in tcp_closei_local
1807 		 * regarding the refcnt logic.
1808 		 *
1809 		 * Since we are holding the tcp_time_wait_lock, its better
1810 		 * not to block on the fanout_lock because other connections
1811 		 * can't add themselves to time_wait list. So we do a
1812 		 * tryenter instead of mutex_enter.
1813 		 */
1814 		if (mutex_tryenter(lock)) {
1815 			mutex_enter(&connp->conn_lock);
1816 			if ((connp->conn_ref == 2) &&
1817 			    (cl_inet_disconnect == NULL)) {
1818 				ipcl_hash_remove_locked(connp,
1819 				    connp->conn_fanout);
1820 				/*
1821 				 * Set the CONDEMNED flag now itself so that
1822 				 * the refcnt cannot increase due to any
1823 				 * walker. But we have still not cleaned up
1824 				 * conn_ire_cache. This is still ok since
1825 				 * we are going to clean it up in tcp_cleanup
1826 				 * immediately and any interface unplumb
1827 				 * thread will wait till the ire is blown away
1828 				 */
1829 				connp->conn_state_flags |= CONN_CONDEMNED;
1830 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1831 				mutex_exit(lock);
1832 				mutex_exit(&connp->conn_lock);
1833 				tcp_cleanup(tcp);
1834 				mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1835 				tcp->tcp_time_wait_next =
1836 				    tcp_time_wait->tcp_free_list;
1837 				tcp_time_wait->tcp_free_list = tcp;
1838 				continue;
1839 			} else {
1840 				CONN_INC_REF_LOCKED(connp);
1841 				mutex_exit(lock);
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,
1852 				    SQTAG_TCP_TIMEWAIT);
1853 			}
1854 		} else {
1855 			mutex_enter(&connp->conn_lock);
1856 			CONN_INC_REF_LOCKED(connp);
1857 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1858 			mutex_exit(&connp->conn_lock);
1859 			/*
1860 			 * We can reuse the closemp here since conn has
1861 			 * detached (otherwise we wouldn't even be in
1862 			 * time_wait list).
1863 			 */
1864 			mp = &tcp->tcp_closemp;
1865 			squeue_fill(connp->conn_sqp, mp,
1866 			    tcp_timewait_output, connp, 0);
1867 		}
1868 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1869 	}
1870 
1871 	if (tcp_time_wait->tcp_free_list != NULL)
1872 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1873 
1874 	tcp_time_wait->tcp_time_wait_tid =
1875 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1876 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1877 }
1878 
1879 /*
1880  * Reply to a clients T_CONN_RES TPI message. This function
1881  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1882  * on the acceptor STREAM and processed in tcp_wput_accept().
1883  * Read the block comment on top of tcp_conn_request().
1884  */
1885 static void
1886 tcp_accept(tcp_t *listener, mblk_t *mp)
1887 {
1888 	tcp_t	*acceptor;
1889 	tcp_t	*eager;
1890 	tcp_t   *tcp;
1891 	struct T_conn_res	*tcr;
1892 	t_uscalar_t	acceptor_id;
1893 	t_scalar_t	seqnum;
1894 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1895 	mblk_t	*ok_mp;
1896 	mblk_t	*mp1;
1897 
1898 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1899 		tcp_err_ack(listener, mp, TPROTO, 0);
1900 		return;
1901 	}
1902 	tcr = (struct T_conn_res *)mp->b_rptr;
1903 
1904 	/*
1905 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1906 	 * read side queue of the streams device underneath us i.e. the
1907 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1908 	 * look it up in the queue_hash.  Under LP64 it sends down the
1909 	 * minor_t of the accepting endpoint.
1910 	 *
1911 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1912 	 * fanout hash lock is held.
1913 	 * This prevents any thread from entering the acceptor queue from
1914 	 * below (since it has not been hard bound yet i.e. any inbound
1915 	 * packets will arrive on the listener or default tcp queue and
1916 	 * go through tcp_lookup).
1917 	 * The CONN_INC_REF will prevent the acceptor from closing.
1918 	 *
1919 	 * XXX It is still possible for a tli application to send down data
1920 	 * on the accepting stream while another thread calls t_accept.
1921 	 * This should not be a problem for well-behaved applications since
1922 	 * the T_OK_ACK is sent after the queue swapping is completed.
1923 	 *
1924 	 * If the accepting fd is the same as the listening fd, avoid
1925 	 * queue hash lookup since that will return an eager listener in a
1926 	 * already established state.
1927 	 */
1928 	acceptor_id = tcr->ACCEPTOR_id;
1929 	mutex_enter(&listener->tcp_eager_lock);
1930 	if (listener->tcp_acceptor_id == acceptor_id) {
1931 		eager = listener->tcp_eager_next_q;
1932 		/* only count how many T_CONN_INDs so don't count q0 */
1933 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1934 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1935 			mutex_exit(&listener->tcp_eager_lock);
1936 			tcp_err_ack(listener, mp, TBADF, 0);
1937 			return;
1938 		}
1939 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1940 			/* Throw away all the eagers on q0. */
1941 			tcp_eager_cleanup(listener, 1);
1942 		}
1943 		if (listener->tcp_syn_defense) {
1944 			listener->tcp_syn_defense = B_FALSE;
1945 			if (listener->tcp_ip_addr_cache != NULL) {
1946 				kmem_free(listener->tcp_ip_addr_cache,
1947 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1948 				listener->tcp_ip_addr_cache = NULL;
1949 			}
1950 		}
1951 		/*
1952 		 * Transfer tcp_conn_req_max to the eager so that when
1953 		 * a disconnect occurs we can revert the endpoint to the
1954 		 * listen state.
1955 		 */
1956 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1957 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1958 		/*
1959 		 * Get a reference on the acceptor just like the
1960 		 * tcp_acceptor_hash_lookup below.
1961 		 */
1962 		acceptor = listener;
1963 		CONN_INC_REF(acceptor->tcp_connp);
1964 	} else {
1965 		acceptor = tcp_acceptor_hash_lookup(acceptor_id);
1966 		if (acceptor == NULL) {
1967 			if (listener->tcp_debug) {
1968 				(void) strlog(TCP_MOD_ID, 0, 1,
1969 				    SL_ERROR|SL_TRACE,
1970 				    "tcp_accept: did not find acceptor 0x%x\n",
1971 				    acceptor_id);
1972 			}
1973 			mutex_exit(&listener->tcp_eager_lock);
1974 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1975 			return;
1976 		}
1977 		/*
1978 		 * Verify acceptor state. The acceptable states for an acceptor
1979 		 * include TCPS_IDLE and TCPS_BOUND.
1980 		 */
1981 		switch (acceptor->tcp_state) {
1982 		case TCPS_IDLE:
1983 			/* FALLTHRU */
1984 		case TCPS_BOUND:
1985 			break;
1986 		default:
1987 			CONN_DEC_REF(acceptor->tcp_connp);
1988 			mutex_exit(&listener->tcp_eager_lock);
1989 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
1990 			return;
1991 		}
1992 	}
1993 
1994 	/* The listener must be in TCPS_LISTEN */
1995 	if (listener->tcp_state != TCPS_LISTEN) {
1996 		CONN_DEC_REF(acceptor->tcp_connp);
1997 		mutex_exit(&listener->tcp_eager_lock);
1998 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
1999 		return;
2000 	}
2001 
2002 	/*
2003 	 * Rendezvous with an eager connection request packet hanging off
2004 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2005 	 * tcp structure when the connection packet arrived in
2006 	 * tcp_conn_request().
2007 	 */
2008 	seqnum = tcr->SEQ_number;
2009 	eager = listener;
2010 	do {
2011 		eager = eager->tcp_eager_next_q;
2012 		if (eager == NULL) {
2013 			CONN_DEC_REF(acceptor->tcp_connp);
2014 			mutex_exit(&listener->tcp_eager_lock);
2015 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2016 			return;
2017 		}
2018 	} while (eager->tcp_conn_req_seqnum != seqnum);
2019 	mutex_exit(&listener->tcp_eager_lock);
2020 
2021 	/*
2022 	 * At this point, both acceptor and listener have 2 ref
2023 	 * that they begin with. Acceptor has one additional ref
2024 	 * we placed in lookup while listener has 3 additional
2025 	 * ref for being behind the squeue (tcp_accept() is
2026 	 * done on listener's squeue); being in classifier hash;
2027 	 * and eager's ref on listener.
2028 	 */
2029 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2030 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2031 
2032 	/*
2033 	 * The eager at this point is set in its own squeue and
2034 	 * could easily have been killed (tcp_accept_finish will
2035 	 * deal with that) because of a TH_RST so we can only
2036 	 * ASSERT for a single ref.
2037 	 */
2038 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2039 
2040 	/* Pre allocate the stroptions mblk also */
2041 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2042 	if (opt_mp == NULL) {
2043 		CONN_DEC_REF(acceptor->tcp_connp);
2044 		CONN_DEC_REF(eager->tcp_connp);
2045 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2046 		return;
2047 	}
2048 	DB_TYPE(opt_mp) = M_SETOPTS;
2049 	opt_mp->b_wptr += sizeof (struct stroptions);
2050 
2051 	/*
2052 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2053 	 * from listener to acceptor. The message is chained on opt_mp
2054 	 * which will be sent onto eager's squeue.
2055 	 */
2056 	if (listener->tcp_bound_if != 0) {
2057 		/* allocate optmgmt req */
2058 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2059 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2060 		    sizeof (int));
2061 		if (mp1 != NULL)
2062 			linkb(opt_mp, mp1);
2063 	}
2064 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2065 		uint_t on = 1;
2066 
2067 		/* allocate optmgmt req */
2068 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2069 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2070 		if (mp1 != NULL)
2071 			linkb(opt_mp, mp1);
2072 	}
2073 
2074 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2075 	if ((mp1 = copymsg(mp)) == NULL) {
2076 		CONN_DEC_REF(acceptor->tcp_connp);
2077 		CONN_DEC_REF(eager->tcp_connp);
2078 		freemsg(opt_mp);
2079 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2080 		return;
2081 	}
2082 
2083 	tcr = (struct T_conn_res *)mp1->b_rptr;
2084 
2085 	/*
2086 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2087 	 * which allocates a larger mblk and appends the new
2088 	 * local address to the ok_ack.  The address is copied by
2089 	 * soaccept() for getsockname().
2090 	 */
2091 	{
2092 		int extra;
2093 
2094 		extra = (eager->tcp_family == AF_INET) ?
2095 		    sizeof (sin_t) : sizeof (sin6_t);
2096 
2097 		/*
2098 		 * Try to re-use mp, if possible.  Otherwise, allocate
2099 		 * an mblk and return it as ok_mp.  In any case, mp
2100 		 * is no longer usable upon return.
2101 		 */
2102 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2103 			CONN_DEC_REF(acceptor->tcp_connp);
2104 			CONN_DEC_REF(eager->tcp_connp);
2105 			freemsg(opt_mp);
2106 			/* Original mp has been freed by now, so use mp1 */
2107 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2108 			return;
2109 		}
2110 
2111 		mp = NULL;	/* We should never use mp after this point */
2112 
2113 		switch (extra) {
2114 		case sizeof (sin_t): {
2115 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2116 
2117 				ok_mp->b_wptr += extra;
2118 				sin->sin_family = AF_INET;
2119 				sin->sin_port = eager->tcp_lport;
2120 				sin->sin_addr.s_addr =
2121 				    eager->tcp_ipha->ipha_src;
2122 				break;
2123 			}
2124 		case sizeof (sin6_t): {
2125 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2126 
2127 				ok_mp->b_wptr += extra;
2128 				sin6->sin6_family = AF_INET6;
2129 				sin6->sin6_port = eager->tcp_lport;
2130 				if (eager->tcp_ipversion == IPV4_VERSION) {
2131 					sin6->sin6_flowinfo = 0;
2132 					IN6_IPADDR_TO_V4MAPPED(
2133 					    eager->tcp_ipha->ipha_src,
2134 					    &sin6->sin6_addr);
2135 				} else {
2136 					ASSERT(eager->tcp_ip6h != NULL);
2137 					sin6->sin6_flowinfo =
2138 					    eager->tcp_ip6h->ip6_vcf &
2139 					    ~IPV6_VERS_AND_FLOW_MASK;
2140 					sin6->sin6_addr =
2141 					    eager->tcp_ip6h->ip6_src;
2142 				}
2143 				break;
2144 			}
2145 		default:
2146 			break;
2147 		}
2148 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2149 	}
2150 
2151 	/*
2152 	 * If there are no options we know that the T_CONN_RES will
2153 	 * succeed. However, we can't send the T_OK_ACK upstream until
2154 	 * the tcp_accept_swap is done since it would be dangerous to
2155 	 * let the application start using the new fd prior to the swap.
2156 	 */
2157 	tcp_accept_swap(listener, acceptor, eager);
2158 
2159 	/*
2160 	 * tcp_accept_swap unlinks eager from listener but does not drop
2161 	 * the eager's reference on the listener.
2162 	 */
2163 	ASSERT(eager->tcp_listener == NULL);
2164 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2165 
2166 	/*
2167 	 * The eager is now associated with its own queue. Insert in
2168 	 * the hash so that the connection can be reused for a future
2169 	 * T_CONN_RES.
2170 	 */
2171 	tcp_acceptor_hash_insert(acceptor_id, eager);
2172 
2173 	/*
2174 	 * We now do the processing of options with T_CONN_RES.
2175 	 * We delay till now since we wanted to have queue to pass to
2176 	 * option processing routines that points back to the right
2177 	 * instance structure which does not happen until after
2178 	 * tcp_accept_swap().
2179 	 *
2180 	 * Note:
2181 	 * The sanity of the logic here assumes that whatever options
2182 	 * are appropriate to inherit from listner=>eager are done
2183 	 * before this point, and whatever were to be overridden (or not)
2184 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2185 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2186 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2187 	 * This may not be true at this point in time but can be fixed
2188 	 * independently. This option processing code starts with
2189 	 * the instantiated acceptor instance and the final queue at
2190 	 * this point.
2191 	 */
2192 
2193 	if (tcr->OPT_length != 0) {
2194 		/* Options to process */
2195 		int t_error = 0;
2196 		int sys_error = 0;
2197 		int do_disconnect = 0;
2198 
2199 		if (tcp_conprim_opt_process(eager, mp1,
2200 		    &do_disconnect, &t_error, &sys_error) < 0) {
2201 			eager->tcp_accept_error = 1;
2202 			if (do_disconnect) {
2203 				/*
2204 				 * An option failed which does not allow
2205 				 * connection to be accepted.
2206 				 *
2207 				 * We allow T_CONN_RES to succeed and
2208 				 * put a T_DISCON_IND on the eager queue.
2209 				 */
2210 				ASSERT(t_error == 0 && sys_error == 0);
2211 				eager->tcp_send_discon_ind = 1;
2212 			} else {
2213 				ASSERT(t_error != 0);
2214 				freemsg(ok_mp);
2215 				/*
2216 				 * Original mp was either freed or set
2217 				 * to ok_mp above, so use mp1 instead.
2218 				 */
2219 				tcp_err_ack(listener, mp1, t_error, sys_error);
2220 				goto finish;
2221 			}
2222 		}
2223 		/*
2224 		 * Most likely success in setting options (except if
2225 		 * eager->tcp_send_discon_ind set).
2226 		 * mp1 option buffer represented by OPT_length/offset
2227 		 * potentially modified and contains results of setting
2228 		 * options at this point
2229 		 */
2230 	}
2231 
2232 	/* We no longer need mp1, since all options processing has passed */
2233 	freemsg(mp1);
2234 
2235 	putnext(listener->tcp_rq, ok_mp);
2236 
2237 	mutex_enter(&listener->tcp_eager_lock);
2238 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2239 		tcp_t	*tail;
2240 		mblk_t	*conn_ind;
2241 
2242 		/*
2243 		 * This path should not be executed if listener and
2244 		 * acceptor streams are the same.
2245 		 */
2246 		ASSERT(listener != acceptor);
2247 
2248 		tcp = listener->tcp_eager_prev_q0;
2249 		/*
2250 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2251 		 * deferred T_conn_ind queue. We need to get to the head of
2252 		 * the queue in order to send up T_conn_ind the same order as
2253 		 * how the 3WHS is completed.
2254 		 */
2255 		while (tcp != listener) {
2256 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2257 				break;
2258 			else
2259 				tcp = tcp->tcp_eager_prev_q0;
2260 		}
2261 		ASSERT(tcp != listener);
2262 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2263 		ASSERT(conn_ind != NULL);
2264 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2265 
2266 		/* Move from q0 to q */
2267 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2268 		listener->tcp_conn_req_cnt_q0--;
2269 		listener->tcp_conn_req_cnt_q++;
2270 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2271 		    tcp->tcp_eager_prev_q0;
2272 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2273 		    tcp->tcp_eager_next_q0;
2274 		tcp->tcp_eager_prev_q0 = NULL;
2275 		tcp->tcp_eager_next_q0 = NULL;
2276 		tcp->tcp_conn_def_q0 = B_FALSE;
2277 
2278 		/*
2279 		 * Insert at end of the queue because sockfs sends
2280 		 * down T_CONN_RES in chronological order. Leaving
2281 		 * the older conn indications at front of the queue
2282 		 * helps reducing search time.
2283 		 */
2284 		tail = listener->tcp_eager_last_q;
2285 		if (tail != NULL)
2286 			tail->tcp_eager_next_q = tcp;
2287 		else
2288 			listener->tcp_eager_next_q = tcp;
2289 		listener->tcp_eager_last_q = tcp;
2290 		tcp->tcp_eager_next_q = NULL;
2291 		mutex_exit(&listener->tcp_eager_lock);
2292 		putnext(tcp->tcp_rq, conn_ind);
2293 	} else {
2294 		mutex_exit(&listener->tcp_eager_lock);
2295 	}
2296 
2297 	/*
2298 	 * Done with the acceptor - free it
2299 	 *
2300 	 * Note: from this point on, no access to listener should be made
2301 	 * as listener can be equal to acceptor.
2302 	 */
2303 finish:
2304 	ASSERT(acceptor->tcp_detached);
2305 	acceptor->tcp_rq = tcp_g_q;
2306 	acceptor->tcp_wq = WR(tcp_g_q);
2307 	(void) tcp_clean_death(acceptor, 0, 2);
2308 	CONN_DEC_REF(acceptor->tcp_connp);
2309 
2310 	/*
2311 	 * In case we already received a FIN we have to make tcp_rput send
2312 	 * the ordrel_ind. This will also send up a window update if the window
2313 	 * has opened up.
2314 	 *
2315 	 * In the normal case of a successful connection acceptance
2316 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2317 	 * indication that this was just accepted. This tells tcp_rput to
2318 	 * pass up any data queued in tcp_rcv_list.
2319 	 *
2320 	 * In the fringe case where options sent with T_CONN_RES failed and
2321 	 * we required, we would be indicating a T_DISCON_IND to blow
2322 	 * away this connection.
2323 	 */
2324 
2325 	/*
2326 	 * XXX: we currently have a problem if XTI application closes the
2327 	 * acceptor stream in between. This problem exists in on10-gate also
2328 	 * and is well know but nothing can be done short of major rewrite
2329 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2330 	 * eager same squeue as listener (we can distinguish non socket
2331 	 * listeners at the time of handling a SYN in tcp_conn_request)
2332 	 * and do most of the work that tcp_accept_finish does here itself
2333 	 * and then get behind the acceptor squeue to access the acceptor
2334 	 * queue.
2335 	 */
2336 	/*
2337 	 * We already have a ref on tcp so no need to do one before squeue_fill
2338 	 */
2339 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2340 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2341 }
2342 
2343 /*
2344  * Swap information between the eager and acceptor for a TLI/XTI client.
2345  * The sockfs accept is done on the acceptor stream and control goes
2346  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2347  * called. In either case, both the eager and listener are in their own
2348  * perimeter (squeue) and the code has to deal with potential race.
2349  *
2350  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2351  */
2352 static void
2353 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2354 {
2355 	conn_t	*econnp, *aconnp;
2356 
2357 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2358 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2359 	ASSERT(!eager->tcp_hard_bound);
2360 	ASSERT(!TCP_IS_SOCKET(acceptor));
2361 	ASSERT(!TCP_IS_SOCKET(eager));
2362 	ASSERT(!TCP_IS_SOCKET(listener));
2363 
2364 	acceptor->tcp_detached = B_TRUE;
2365 	/*
2366 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2367 	 * the acceptor id.
2368 	 */
2369 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2370 
2371 	/* remove eager from listen list... */
2372 	mutex_enter(&listener->tcp_eager_lock);
2373 	tcp_eager_unlink(eager);
2374 	ASSERT(eager->tcp_eager_next_q == NULL &&
2375 	    eager->tcp_eager_last_q == NULL);
2376 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2377 	    eager->tcp_eager_prev_q0 == NULL);
2378 	mutex_exit(&listener->tcp_eager_lock);
2379 	eager->tcp_rq = acceptor->tcp_rq;
2380 	eager->tcp_wq = acceptor->tcp_wq;
2381 
2382 	econnp = eager->tcp_connp;
2383 	aconnp = acceptor->tcp_connp;
2384 
2385 	eager->tcp_rq->q_ptr = econnp;
2386 	eager->tcp_wq->q_ptr = econnp;
2387 	eager->tcp_detached = B_FALSE;
2388 
2389 	ASSERT(eager->tcp_ack_tid == 0);
2390 
2391 	econnp->conn_dev = aconnp->conn_dev;
2392 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2393 	econnp->conn_zoneid = aconnp->conn_zoneid;
2394 	aconnp->conn_cred = NULL;
2395 
2396 	/* Do the IPC initialization */
2397 	CONN_INC_REF(econnp);
2398 
2399 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2400 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2401 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2402 	econnp->conn_ulp = aconnp->conn_ulp;
2403 
2404 	/* Done with old IPC. Drop its ref on its connp */
2405 	CONN_DEC_REF(aconnp);
2406 }
2407 
2408 
2409 /*
2410  * Adapt to the information, such as rtt and rtt_sd, provided from the
2411  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2412  *
2413  * Checks for multicast and broadcast destination address.
2414  * Returns zero on failure; non-zero if ok.
2415  *
2416  * Note that the MSS calculation here is based on the info given in
2417  * the IRE.  We do not do any calculation based on TCP options.  They
2418  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2419  * knows which options to use.
2420  *
2421  * Note on how TCP gets its parameters for a connection.
2422  *
2423  * When a tcp_t structure is allocated, it gets all the default parameters.
2424  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2425  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2426  * default.  But if there is an associated tcp_host_param, it will override
2427  * the metrics.
2428  *
2429  * An incoming SYN with a multicast or broadcast destination address, is dropped
2430  * in 1 of 2 places.
2431  *
2432  * 1. If the packet was received over the wire it is dropped in
2433  * ip_rput_process_broadcast()
2434  *
2435  * 2. If the packet was received through internal IP loopback, i.e. the packet
2436  * was generated and received on the same machine, it is dropped in
2437  * ip_wput_local()
2438  *
2439  * An incoming SYN with a multicast or broadcast source address is always
2440  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2441  * reject an attempt to connect to a broadcast or multicast (destination)
2442  * address.
2443  */
2444 static int
2445 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2446 {
2447 	tcp_hsp_t	*hsp;
2448 	ire_t		*ire;
2449 	ire_t		*sire = NULL;
2450 	iulp_t		*ire_uinfo;
2451 	uint32_t	mss_max;
2452 	uint32_t	mss;
2453 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2454 	conn_t		*connp = tcp->tcp_connp;
2455 	boolean_t	ire_cacheable = B_FALSE;
2456 	zoneid_t	zoneid = connp->conn_zoneid;
2457 	ill_t		*ill = NULL;
2458 	boolean_t	incoming = (ire_mp == NULL);
2459 
2460 	ASSERT(connp->conn_ire_cache == NULL);
2461 
2462 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2463 
2464 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2465 			BUMP_MIB(&ip_mib, ipInDiscards);
2466 			return (0);
2467 		}
2468 
2469 		ire = ire_cache_lookup(tcp->tcp_connp->conn_rem, zoneid);
2470 		if (ire != NULL) {
2471 			ire_cacheable = B_TRUE;
2472 			ire_uinfo = (ire_mp != NULL) ?
2473 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2474 			    &ire->ire_uinfo;
2475 
2476 		} else {
2477 			if (ire_mp == NULL) {
2478 				ire = ire_ftable_lookup(
2479 				    tcp->tcp_connp->conn_rem,
2480 				    0, 0, 0, NULL, &sire, zoneid, 0,
2481 				    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT));
2482 				if (ire == NULL)
2483 					return (0);
2484 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2485 				    &ire->ire_uinfo;
2486 			} else {
2487 				ire = (ire_t *)ire_mp->b_rptr;
2488 				ire_uinfo =
2489 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2490 			}
2491 		}
2492 		ASSERT(ire != NULL);
2493 		ASSERT(ire_uinfo != NULL);
2494 
2495 		if ((ire->ire_src_addr == INADDR_ANY) ||
2496 		    (ire->ire_type & IRE_BROADCAST)) {
2497 			/*
2498 			 * ire->ire_mp is non null when ire_mp passed in is used
2499 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2500 			 */
2501 			if (ire->ire_mp == NULL)
2502 				ire_refrele(ire);
2503 			if (sire != NULL)
2504 				ire_refrele(sire);
2505 			return (0);
2506 		}
2507 
2508 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2509 			ipaddr_t src_addr;
2510 
2511 			/*
2512 			 * ip_bind_connected() has stored the correct source
2513 			 * address in conn_src.
2514 			 */
2515 			src_addr = tcp->tcp_connp->conn_src;
2516 			tcp->tcp_ipha->ipha_src = src_addr;
2517 			/*
2518 			 * Copy of the src addr. in tcp_t is needed
2519 			 * for the lookup funcs.
2520 			 */
2521 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2522 		}
2523 		/*
2524 		 * Set the fragment bit so that IP will tell us if the MTU
2525 		 * should change. IP tells us the latest setting of
2526 		 * ip_path_mtu_discovery through ire_frag_flag.
2527 		 */
2528 		if (ip_path_mtu_discovery) {
2529 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2530 			    htons(IPH_DF);
2531 		}
2532 		tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2533 	} else {
2534 		/*
2535 		 * For incoming connection ire_mp = NULL
2536 		 * For outgoing connection ire_mp != NULL
2537 		 * Technically we should check conn_incoming_ill
2538 		 * when ire_mp is NULL and conn_outgoing_ill when
2539 		 * ire_mp is non-NULL. But this is performance
2540 		 * critical path and for IPV*_BOUND_IF, outgoing
2541 		 * and incoming ill are always set to the same value.
2542 		 */
2543 		ill_t	*dst_ill = NULL;
2544 		ipif_t  *dst_ipif = NULL;
2545 		int match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT;
2546 
2547 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2548 
2549 		if (connp->conn_outgoing_ill != NULL) {
2550 			/* Outgoing or incoming path */
2551 			int   err;
2552 
2553 			dst_ill = conn_get_held_ill(connp,
2554 			    &connp->conn_outgoing_ill, &err);
2555 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2556 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2557 				return (0);
2558 			}
2559 			match_flags |= MATCH_IRE_ILL;
2560 			dst_ipif = dst_ill->ill_ipif;
2561 		}
2562 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2563 		    0, 0, dst_ipif, zoneid, match_flags);
2564 
2565 		if (ire != NULL) {
2566 			ire_cacheable = B_TRUE;
2567 			ire_uinfo = (ire_mp != NULL) ?
2568 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2569 			    &ire->ire_uinfo;
2570 		} else {
2571 			if (ire_mp == NULL) {
2572 				ire = ire_ftable_lookup_v6(
2573 				    &tcp->tcp_connp->conn_remv6,
2574 				    0, 0, 0, dst_ipif, &sire, zoneid,
2575 				    0, match_flags);
2576 				if (ire == NULL) {
2577 					if (dst_ill != NULL)
2578 						ill_refrele(dst_ill);
2579 					return (0);
2580 				}
2581 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2582 				    &ire->ire_uinfo;
2583 			} else {
2584 				ire = (ire_t *)ire_mp->b_rptr;
2585 				ire_uinfo =
2586 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2587 			}
2588 		}
2589 		if (dst_ill != NULL)
2590 			ill_refrele(dst_ill);
2591 
2592 		ASSERT(ire != NULL);
2593 		ASSERT(ire_uinfo != NULL);
2594 
2595 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2596 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2597 			/*
2598 			 * ire->ire_mp is non null when ire_mp passed in is used
2599 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2600 			 */
2601 			if (ire->ire_mp == NULL)
2602 				ire_refrele(ire);
2603 			if (sire != NULL)
2604 				ire_refrele(sire);
2605 			return (0);
2606 		}
2607 
2608 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2609 			in6_addr_t	src_addr;
2610 
2611 			/*
2612 			 * ip_bind_connected_v6() has stored the correct source
2613 			 * address per IPv6 addr. selection policy in
2614 			 * conn_src_v6.
2615 			 */
2616 			src_addr = tcp->tcp_connp->conn_srcv6;
2617 
2618 			tcp->tcp_ip6h->ip6_src = src_addr;
2619 			/*
2620 			 * Copy of the src addr. in tcp_t is needed
2621 			 * for the lookup funcs.
2622 			 */
2623 			tcp->tcp_ip_src_v6 = src_addr;
2624 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2625 			    &connp->conn_srcv6));
2626 		}
2627 		tcp->tcp_localnet =
2628 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2629 	}
2630 
2631 	/*
2632 	 * This allows applications to fail quickly when connections are made
2633 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2634 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2635 	 */
2636 	if ((ire->ire_flags & RTF_REJECT) &&
2637 	    (ire->ire_flags & RTF_PRIVATE))
2638 		goto error;
2639 
2640 	/*
2641 	 * Make use of the cached rtt and rtt_sd values to calculate the
2642 	 * initial RTO.  Note that they are already initialized in
2643 	 * tcp_init_values().
2644 	 */
2645 	if (ire_uinfo->iulp_rtt != 0) {
2646 		clock_t	rto;
2647 
2648 		tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2649 		tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2650 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2651 		    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
2652 
2653 		if (rto > tcp_rexmit_interval_max) {
2654 			tcp->tcp_rto = tcp_rexmit_interval_max;
2655 		} else if (rto < tcp_rexmit_interval_min) {
2656 			tcp->tcp_rto = tcp_rexmit_interval_min;
2657 		} else {
2658 			tcp->tcp_rto = rto;
2659 		}
2660 	}
2661 	if (ire_uinfo->iulp_ssthresh != 0)
2662 		tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2663 	else
2664 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2665 	if (ire_uinfo->iulp_spipe > 0) {
2666 		tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2667 		    tcp_max_buf);
2668 		if (tcp_snd_lowat_fraction != 0)
2669 			tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2670 			    tcp_snd_lowat_fraction;
2671 		(void) tcp_maxpsz_set(tcp, B_TRUE);
2672 	}
2673 	/*
2674 	 * Note that up till now, acceptor always inherits receive
2675 	 * window from the listener.  But if there is a metrics associated
2676 	 * with a host, we should use that instead of inheriting it from
2677 	 * listener.  Thus we need to pass this info back to the caller.
2678 	 */
2679 	if (ire_uinfo->iulp_rpipe > 0) {
2680 		tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
2681 	} else {
2682 		/*
2683 		 * For passive open, set tcp_rwnd to 0 so that the caller
2684 		 * knows that there is no rpipe metric for this connection.
2685 		 */
2686 		if (tcp_detached)
2687 			tcp->tcp_rwnd = 0;
2688 	}
2689 	if (ire_uinfo->iulp_rtomax > 0) {
2690 		tcp->tcp_second_timer_threshold = ire_uinfo->iulp_rtomax;
2691 	}
2692 
2693 	/*
2694 	 * Use the metric option settings, iulp_tstamp_ok and iulp_wscale_ok,
2695 	 * only for active open.  What this means is that if the other side
2696 	 * uses timestamp or window scale option, TCP will also use those
2697 	 * options.  That is for passive open.  If the application sets a
2698 	 * large window, window scale is enabled regardless of the value in
2699 	 * iulp_wscale_ok.  This is the behavior since 2.6.  So we keep it.
2700 	 * The only case left in passive open processing is the check for SACK.
2701 	 *
2702 	 * For ECN, it should probably be like SACK.  But the current
2703 	 * value is binary, so we treat it like the other cases.  The
2704 	 * metric only controls active open.  For passive open, the ndd
2705 	 * param, tcp_ecn_permitted, controls the behavior.
2706 	 */
2707 	if (!tcp_detached) {
2708 		/*
2709 		 * The if check means that the following can only be turned
2710 		 * on by the metrics only IRE, but not off.
2711 		 */
2712 		if (ire_uinfo->iulp_tstamp_ok)
2713 			tcp->tcp_snd_ts_ok = B_TRUE;
2714 		if (ire_uinfo->iulp_wscale_ok)
2715 			tcp->tcp_snd_ws_ok = B_TRUE;
2716 		if (ire_uinfo->iulp_sack == 2)
2717 			tcp->tcp_snd_sack_ok = B_TRUE;
2718 		if (ire_uinfo->iulp_ecn_ok)
2719 			tcp->tcp_ecn_ok = B_TRUE;
2720 	} else {
2721 		/*
2722 		 * Passive open.
2723 		 *
2724 		 * As above, the if check means that SACK can only be
2725 		 * turned on by the metric only IRE.
2726 		 */
2727 		if (ire_uinfo->iulp_sack > 0) {
2728 			tcp->tcp_snd_sack_ok = B_TRUE;
2729 		}
2730 	}
2731 
2732 	/*
2733 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2734 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2735 	 * length of all those options exceeds 28 bytes.  But because
2736 	 * of the tcp_mss_min check below, we may not have a problem if
2737 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2738 	 * the negative problem still exists.  And the check defeats PMTUd.
2739 	 * In fact, if PMTUd finds that the MSS should be smaller than
2740 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2741 	 * value.
2742 	 *
2743 	 * We do not deal with that now.  All those problems related to
2744 	 * PMTUd will be fixed later.
2745 	 */
2746 	ASSERT(ire->ire_max_frag != 0);
2747 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2748 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2749 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2750 			mss = MIN(mss, IPV6_MIN_MTU);
2751 		}
2752 	}
2753 
2754 	/* Sanity check for MSS value. */
2755 	if (tcp->tcp_ipversion == IPV4_VERSION)
2756 		mss_max = tcp_mss_max_ipv4;
2757 	else
2758 		mss_max = tcp_mss_max_ipv6;
2759 
2760 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2761 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2762 		/*
2763 		 * After receiving an ICMPv6 "packet too big" message with a
2764 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2765 		 * will insert a 8-byte fragment header in every packet; we
2766 		 * reduce the MSS by that amount here.
2767 		 */
2768 		mss -= sizeof (ip6_frag_t);
2769 	}
2770 
2771 	if (tcp->tcp_ipsec_overhead == 0)
2772 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2773 
2774 	mss -= tcp->tcp_ipsec_overhead;
2775 
2776 	if (mss < tcp_mss_min)
2777 		mss = tcp_mss_min;
2778 	if (mss > mss_max)
2779 		mss = mss_max;
2780 
2781 	/* Note that this is the maximum MSS, excluding all options. */
2782 	tcp->tcp_mss = mss;
2783 
2784 	/*
2785 	 * Initialize the ISS here now that we have the full connection ID.
2786 	 * The RFC 1948 method of initial sequence number generation requires
2787 	 * knowledge of the full connection ID before setting the ISS.
2788 	 */
2789 
2790 	tcp_iss_init(tcp);
2791 
2792 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2793 		tcp->tcp_loopback = B_TRUE;
2794 
2795 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2796 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
2797 	} else {
2798 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
2799 	}
2800 
2801 	if (hsp != NULL) {
2802 		/* Only modify if we're going to make them bigger */
2803 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2804 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2805 			if (tcp_snd_lowat_fraction != 0)
2806 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2807 					tcp_snd_lowat_fraction;
2808 		}
2809 
2810 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2811 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2812 		}
2813 
2814 		/* Copy timestamp flag only for active open */
2815 		if (!tcp_detached)
2816 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2817 	}
2818 
2819 	if (sire != NULL)
2820 		IRE_REFRELE(sire);
2821 
2822 	/*
2823 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2824 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2825 	 */
2826 	if (tcp->tcp_loopback ||
2827 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2828 		/*
2829 		 * For incoming, see if this tcp may be MDT-capable.  For
2830 		 * outgoing, this process has been taken care of through
2831 		 * tcp_rput_other.
2832 		 */
2833 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2834 		tcp->tcp_ire_ill_check_done = B_TRUE;
2835 	}
2836 
2837 	mutex_enter(&connp->conn_lock);
2838 	/*
2839 	 * Make sure that conn is not marked incipient
2840 	 * for incoming connections. A blind
2841 	 * removal of incipient flag is cheaper than
2842 	 * check and removal.
2843 	 */
2844 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2845 
2846 	/* Must not cache forwarding table routes. */
2847 	if (ire_cacheable) {
2848 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2849 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2850 			connp->conn_ire_cache = ire;
2851 			IRE_UNTRACE_REF(ire);
2852 			rw_exit(&ire->ire_bucket->irb_lock);
2853 			mutex_exit(&connp->conn_lock);
2854 			return (1);
2855 		}
2856 		rw_exit(&ire->ire_bucket->irb_lock);
2857 	}
2858 	mutex_exit(&connp->conn_lock);
2859 
2860 	if (ire->ire_mp == NULL)
2861 		ire_refrele(ire);
2862 	return (1);
2863 
2864 error:
2865 	if (ire->ire_mp == NULL)
2866 		ire_refrele(ire);
2867 	if (sire != NULL)
2868 		ire_refrele(sire);
2869 	return (0);
2870 }
2871 
2872 /*
2873  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2874  * O_T_BIND_REQ/T_BIND_REQ message.
2875  */
2876 static void
2877 tcp_bind(tcp_t *tcp, mblk_t *mp)
2878 {
2879 	sin_t	*sin;
2880 	sin6_t	*sin6;
2881 	mblk_t	*mp1;
2882 	in_port_t requested_port;
2883 	in_port_t allocated_port;
2884 	struct T_bind_req *tbr;
2885 	boolean_t	bind_to_req_port_only;
2886 	boolean_t	backlog_update = B_FALSE;
2887 	boolean_t	user_specified;
2888 	in6_addr_t	v6addr;
2889 	ipaddr_t	v4addr;
2890 	uint_t	origipversion;
2891 	int	err;
2892 	queue_t *q = tcp->tcp_wq;
2893 
2894 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2895 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2896 		if (tcp->tcp_debug) {
2897 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2898 			    "tcp_bind: bad req, len %u",
2899 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2900 		}
2901 		tcp_err_ack(tcp, mp, TPROTO, 0);
2902 		return;
2903 	}
2904 	/* Make sure the largest address fits */
2905 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
2906 	if (mp1 == NULL) {
2907 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2908 		return;
2909 	}
2910 	mp = mp1;
2911 	tbr = (struct T_bind_req *)mp->b_rptr;
2912 	if (tcp->tcp_state >= TCPS_BOUND) {
2913 		if ((tcp->tcp_state == TCPS_BOUND ||
2914 		    tcp->tcp_state == TCPS_LISTEN) &&
2915 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
2916 		    tbr->CONIND_number > 0) {
2917 			/*
2918 			 * Handle listen() increasing CONIND_number.
2919 			 * This is more "liberal" then what the TPI spec
2920 			 * requires but is needed to avoid a t_unbind
2921 			 * when handling listen() since the port number
2922 			 * might be "stolen" between the unbind and bind.
2923 			 */
2924 			backlog_update = B_TRUE;
2925 			goto do_bind;
2926 		}
2927 		if (tcp->tcp_debug) {
2928 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2929 			    "tcp_bind: bad state, %d", tcp->tcp_state);
2930 		}
2931 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
2932 		return;
2933 	}
2934 	origipversion = tcp->tcp_ipversion;
2935 
2936 	switch (tbr->ADDR_length) {
2937 	case 0:			/* request for a generic port */
2938 		tbr->ADDR_offset = sizeof (struct T_bind_req);
2939 		if (tcp->tcp_family == AF_INET) {
2940 			tbr->ADDR_length = sizeof (sin_t);
2941 			sin = (sin_t *)&tbr[1];
2942 			*sin = sin_null;
2943 			sin->sin_family = AF_INET;
2944 			mp->b_wptr = (uchar_t *)&sin[1];
2945 			tcp->tcp_ipversion = IPV4_VERSION;
2946 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
2947 		} else {
2948 			ASSERT(tcp->tcp_family == AF_INET6);
2949 			tbr->ADDR_length = sizeof (sin6_t);
2950 			sin6 = (sin6_t *)&tbr[1];
2951 			*sin6 = sin6_null;
2952 			sin6->sin6_family = AF_INET6;
2953 			mp->b_wptr = (uchar_t *)&sin6[1];
2954 			tcp->tcp_ipversion = IPV6_VERSION;
2955 			V6_SET_ZERO(v6addr);
2956 		}
2957 		requested_port = 0;
2958 		break;
2959 
2960 	case sizeof (sin_t):	/* Complete IPv4 address */
2961 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
2962 		    sizeof (sin_t));
2963 		if (sin == NULL || !OK_32PTR((char *)sin)) {
2964 			if (tcp->tcp_debug) {
2965 				(void) strlog(TCP_MOD_ID, 0, 1,
2966 				    SL_ERROR|SL_TRACE,
2967 				    "tcp_bind: bad address parameter, "
2968 				    "offset %d, len %d",
2969 				    tbr->ADDR_offset, tbr->ADDR_length);
2970 			}
2971 			tcp_err_ack(tcp, mp, TPROTO, 0);
2972 			return;
2973 		}
2974 		/*
2975 		 * With sockets sockfs will accept bogus sin_family in
2976 		 * bind() and replace it with the family used in the socket
2977 		 * call.
2978 		 */
2979 		if (sin->sin_family != AF_INET ||
2980 		    tcp->tcp_family != AF_INET) {
2981 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
2982 			return;
2983 		}
2984 		requested_port = ntohs(sin->sin_port);
2985 		tcp->tcp_ipversion = IPV4_VERSION;
2986 		v4addr = sin->sin_addr.s_addr;
2987 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
2988 		break;
2989 
2990 	case sizeof (sin6_t): /* Complete IPv6 address */
2991 		sin6 = (sin6_t *)mi_offset_param(mp,
2992 		    tbr->ADDR_offset, sizeof (sin6_t));
2993 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
2994 			if (tcp->tcp_debug) {
2995 				(void) strlog(TCP_MOD_ID, 0, 1,
2996 				    SL_ERROR|SL_TRACE,
2997 				    "tcp_bind: bad IPv6 address parameter, "
2998 				    "offset %d, len %d", tbr->ADDR_offset,
2999 				    tbr->ADDR_length);
3000 			}
3001 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3002 			return;
3003 		}
3004 		if (sin6->sin6_family != AF_INET6 ||
3005 		    tcp->tcp_family != AF_INET6) {
3006 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3007 			return;
3008 		}
3009 		requested_port = ntohs(sin6->sin6_port);
3010 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3011 		    IPV4_VERSION : IPV6_VERSION;
3012 		v6addr = sin6->sin6_addr;
3013 		break;
3014 
3015 	default:
3016 		if (tcp->tcp_debug) {
3017 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3018 			    "tcp_bind: bad address length, %d",
3019 			    tbr->ADDR_length);
3020 		}
3021 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3022 		return;
3023 	}
3024 	tcp->tcp_bound_source_v6 = v6addr;
3025 
3026 	/* Check for change in ipversion */
3027 	if (origipversion != tcp->tcp_ipversion) {
3028 		ASSERT(tcp->tcp_family == AF_INET6);
3029 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3030 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3031 		if (err) {
3032 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3033 			return;
3034 		}
3035 	}
3036 
3037 	/*
3038 	 * Initialize family specific fields. Copy of the src addr.
3039 	 * in tcp_t is needed for the lookup funcs.
3040 	 */
3041 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3042 		tcp->tcp_ip6h->ip6_src = v6addr;
3043 	} else {
3044 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3045 	}
3046 	tcp->tcp_ip_src_v6 = v6addr;
3047 
3048 	/*
3049 	 * For O_T_BIND_REQ:
3050 	 * Verify that the target port/addr is available, or choose
3051 	 * another.
3052 	 * For  T_BIND_REQ:
3053 	 * Verify that the target port/addr is available or fail.
3054 	 * In both cases when it succeeds the tcp is inserted in the
3055 	 * bind hash table. This ensures that the operation is atomic
3056 	 * under the lock on the hash bucket.
3057 	 */
3058 	bind_to_req_port_only = requested_port != 0 &&
3059 	    tbr->PRIM_type != O_T_BIND_REQ;
3060 	/*
3061 	 * Get a valid port (within the anonymous range and should not
3062 	 * be a privileged one) to use if the user has not given a port.
3063 	 * If multiple threads are here, they may all start with
3064 	 * with the same initial port. But, it should be fine as long as
3065 	 * tcp_bindi will ensure that no two threads will be assigned
3066 	 * the same port.
3067 	 *
3068 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3069 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3070 	 * unless TCP_ANONPRIVBIND option is set.
3071 	 */
3072 	if (requested_port == 0) {
3073 		requested_port = tcp->tcp_anon_priv_bind ?
3074 		    tcp_get_next_priv_port() :
3075 		    tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
3076 		user_specified = B_FALSE;
3077 	} else {
3078 		int i;
3079 		boolean_t priv = B_FALSE;
3080 		/*
3081 		 * If the requested_port is in the well-known privileged range,
3082 		 * verify that the stream was opened by a privileged user.
3083 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3084 		 * but instead the code relies on:
3085 		 * - the fact that the address of the array and its size never
3086 		 *   changes
3087 		 * - the atomic assignment of the elements of the array
3088 		 */
3089 		if (requested_port < tcp_smallest_nonpriv_port) {
3090 			priv = B_TRUE;
3091 		} else {
3092 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3093 				if (requested_port ==
3094 				    tcp_g_epriv_ports[i]) {
3095 					priv = B_TRUE;
3096 					break;
3097 				}
3098 			}
3099 		}
3100 		if (priv) {
3101 			cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
3102 
3103 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3104 				if (tcp->tcp_debug) {
3105 					(void) strlog(TCP_MOD_ID, 0, 1,
3106 					    SL_ERROR|SL_TRACE,
3107 					    "tcp_bind: no priv for port %d",
3108 					    requested_port);
3109 				}
3110 				tcp_err_ack(tcp, mp, TACCES, 0);
3111 				return;
3112 			}
3113 		}
3114 		user_specified = B_TRUE;
3115 	}
3116 
3117 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3118 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3119 
3120 	if (allocated_port == 0) {
3121 		if (bind_to_req_port_only) {
3122 			if (tcp->tcp_debug) {
3123 				(void) strlog(TCP_MOD_ID, 0, 1,
3124 				    SL_ERROR|SL_TRACE,
3125 				    "tcp_bind: requested addr busy");
3126 			}
3127 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3128 		} else {
3129 			/* If we are out of ports, fail the bind. */
3130 			if (tcp->tcp_debug) {
3131 				(void) strlog(TCP_MOD_ID, 0, 1,
3132 				    SL_ERROR|SL_TRACE,
3133 				    "tcp_bind: out of ports?");
3134 			}
3135 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3136 		}
3137 		return;
3138 	}
3139 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3140 do_bind:
3141 	if (!backlog_update) {
3142 		if (tcp->tcp_family == AF_INET)
3143 			sin->sin_port = htons(allocated_port);
3144 		else
3145 			sin6->sin6_port = htons(allocated_port);
3146 	}
3147 	if (tcp->tcp_family == AF_INET) {
3148 		if (tbr->CONIND_number != 0) {
3149 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3150 			    sizeof (sin_t));
3151 		} else {
3152 			/* Just verify the local IP address */
3153 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3154 		}
3155 	} else {
3156 		if (tbr->CONIND_number != 0) {
3157 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3158 			    sizeof (sin6_t));
3159 		} else {
3160 			/* Just verify the local IP address */
3161 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3162 			    IPV6_ADDR_LEN);
3163 		}
3164 	}
3165 	if (!mp1) {
3166 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3167 		return;
3168 	}
3169 
3170 	tbr->PRIM_type = T_BIND_ACK;
3171 	mp->b_datap->db_type = M_PCPROTO;
3172 
3173 	/* Chain in the reply mp for tcp_rput() */
3174 	mp1->b_cont = mp;
3175 	mp = mp1;
3176 
3177 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3178 	if (tcp->tcp_conn_req_max) {
3179 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
3180 			tcp->tcp_conn_req_max = tcp_conn_req_min;
3181 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
3182 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
3183 		/*
3184 		 * If this is a listener, do not reset the eager list
3185 		 * and other stuffs.  Note that we don't check if the
3186 		 * existing eager list meets the new tcp_conn_req_max
3187 		 * requirement.
3188 		 */
3189 		if (tcp->tcp_state != TCPS_LISTEN) {
3190 			tcp->tcp_state = TCPS_LISTEN;
3191 			/* Initialize the chain. Don't need the eager_lock */
3192 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3193 			tcp->tcp_second_ctimer_threshold =
3194 			    tcp_ip_abort_linterval;
3195 		}
3196 	}
3197 
3198 	/*
3199 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3200 	 * processing continues in tcp_rput_other().
3201 	 */
3202 	if (tcp->tcp_family == AF_INET6) {
3203 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3204 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3205 	} else {
3206 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3207 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3208 	}
3209 	/*
3210 	 * If the bind cannot complete immediately
3211 	 * IP will arrange to call tcp_rput_other
3212 	 * when the bind completes.
3213 	 */
3214 	if (mp != NULL) {
3215 		tcp_rput_other(tcp, mp);
3216 	} else {
3217 		/*
3218 		 * Bind will be resumed later. Need to ensure
3219 		 * that conn doesn't disappear when that happens.
3220 		 * This will be decremented in ip_resume_tcp_bind().
3221 		 */
3222 		CONN_INC_REF(tcp->tcp_connp);
3223 	}
3224 }
3225 
3226 
3227 /*
3228  * If the "bind_to_req_port_only" parameter is set, if the requested port
3229  * number is available, return it, If not return 0
3230  *
3231  * If "bind_to_req_port_only" parameter is not set and
3232  * If the requested port number is available, return it.  If not, return
3233  * the first anonymous port we happen across.  If no anonymous ports are
3234  * available, return 0. addr is the requested local address, if any.
3235  *
3236  * In either case, when succeeding update the tcp_t to record the port number
3237  * and insert it in the bind hash table.
3238  *
3239  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3240  * without setting SO_REUSEADDR. This is needed so that they
3241  * can be viewed as two independent transport protocols.
3242  */
3243 static in_port_t
3244 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3245     int reuseaddr, boolean_t quick_connect,
3246     boolean_t bind_to_req_port_only, boolean_t user_specified)
3247 {
3248 	/* number of times we have run around the loop */
3249 	int count = 0;
3250 	/* maximum number of times to run around the loop */
3251 	int loopmax;
3252 	zoneid_t zoneid = tcp->tcp_connp->conn_zoneid;
3253 
3254 	/*
3255 	 * Lookup for free addresses is done in a loop and "loopmax"
3256 	 * influences how long we spin in the loop
3257 	 */
3258 	if (bind_to_req_port_only) {
3259 		/*
3260 		 * If the requested port is busy, don't bother to look
3261 		 * for a new one. Setting loop maximum count to 1 has
3262 		 * that effect.
3263 		 */
3264 		loopmax = 1;
3265 	} else {
3266 		/*
3267 		 * If the requested port is busy, look for a free one
3268 		 * in the anonymous port range.
3269 		 * Set loopmax appropriately so that one does not look
3270 		 * forever in the case all of the anonymous ports are in use.
3271 		 */
3272 		if (tcp->tcp_anon_priv_bind) {
3273 			/*
3274 			 * loopmax =
3275 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3276 			 */
3277 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
3278 		} else {
3279 			loopmax = (tcp_largest_anon_port -
3280 			    tcp_smallest_anon_port + 1);
3281 		}
3282 	}
3283 	do {
3284 		uint16_t	lport;
3285 		tf_t		*tbf;
3286 		tcp_t		*ltcp;
3287 
3288 		lport = htons(port);
3289 
3290 		/*
3291 		 * Ensure that the tcp_t is not currently in the bind hash.
3292 		 * Hold the lock on the hash bucket to ensure that
3293 		 * the duplicate check plus the insertion is an atomic
3294 		 * operation.
3295 		 *
3296 		 * This function does an inline lookup on the bind hash list
3297 		 * Make sure that we access only members of tcp_t
3298 		 * and that we don't look at tcp_tcp, since we are not
3299 		 * doing a CONN_INC_REF.
3300 		 */
3301 		tcp_bind_hash_remove(tcp);
3302 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
3303 		mutex_enter(&tbf->tf_lock);
3304 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3305 		    ltcp = ltcp->tcp_bind_hash) {
3306 			if (lport != ltcp->tcp_lport ||
3307 			    ltcp->tcp_connp->conn_zoneid != zoneid) {
3308 				continue;
3309 			}
3310 
3311 			/*
3312 			 * If TCP_EXCLBIND is set for either the bound or
3313 			 * binding endpoint, the semantics of bind
3314 			 * is changed according to the following.
3315 			 *
3316 			 * spec = specified address (v4 or v6)
3317 			 * unspec = unspecified address (v4 or v6)
3318 			 * A = specified addresses are different for endpoints
3319 			 *
3320 			 * bound	bind to		allowed
3321 			 * -------------------------------------
3322 			 * unspec	unspec		no
3323 			 * unspec	spec		no
3324 			 * spec		unspec		no
3325 			 * spec		spec		yes if A
3326 			 *
3327 			 * Note:
3328 			 *
3329 			 * 1. Because of TLI semantics, an endpoint can go
3330 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3331 			 * TCPS_BOUND, depending on whether it is originally
3332 			 * a listener or not.  That is why we need to check
3333 			 * for states greater than or equal to TCPS_BOUND
3334 			 * here.
3335 			 *
3336 			 * 2. Ideally, we should only check for state equals
3337 			 * to TCPS_LISTEN. And the following check should be
3338 			 * added.
3339 			 *
3340 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3341 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3342 			 *		...
3343 			 * }
3344 			 *
3345 			 * The semantics will be changed to this.  If the
3346 			 * endpoint on the list is in state not equal to
3347 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3348 			 * set, let the bind succeed.
3349 			 *
3350 			 * But because of (1), we cannot do that now.  If
3351 			 * in future, we can change this going back semantics,
3352 			 * we can add the above check.
3353 			 */
3354 			if (ltcp->tcp_exclbind || tcp->tcp_exclbind) {
3355 				if (V6_OR_V4_INADDR_ANY(
3356 				    ltcp->tcp_bound_source_v6) ||
3357 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3358 				    IN6_ARE_ADDR_EQUAL(laddr,
3359 				    &ltcp->tcp_bound_source_v6)) {
3360 					break;
3361 				}
3362 				continue;
3363 			}
3364 
3365 			/*
3366 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3367 			 * have disjoint port number spaces, if *_EXCLBIND
3368 			 * is not set and only if the application binds to a
3369 			 * specific port. We use the same autoassigned port
3370 			 * number space for IPv4 and IPv6 sockets.
3371 			 */
3372 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3373 			    bind_to_req_port_only)
3374 				continue;
3375 
3376 			/*
3377 			 * Ideally, we should make sure that the source
3378 			 * address, remote address, and remote port in the
3379 			 * four tuple for this tcp-connection is unique.
3380 			 * However, trying to find out the local source
3381 			 * address would require too much code duplication
3382 			 * with IP, since IP needs needs to have that code
3383 			 * to support userland TCP implementations.
3384 			 */
3385 			if (quick_connect &&
3386 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3387 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3388 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3389 				    &ltcp->tcp_remote_v6)))
3390 				continue;
3391 
3392 			if (!reuseaddr) {
3393 				/*
3394 				 * No socket option SO_REUSEADDR.
3395 				 * If existing port is bound to
3396 				 * a non-wildcard IP address
3397 				 * and the requesting stream is
3398 				 * bound to a distinct
3399 				 * different IP addresses
3400 				 * (non-wildcard, also), keep
3401 				 * going.
3402 				 */
3403 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3404 				    !V6_OR_V4_INADDR_ANY(
3405 				    ltcp->tcp_bound_source_v6) &&
3406 				    !IN6_ARE_ADDR_EQUAL(laddr,
3407 					&ltcp->tcp_bound_source_v6))
3408 					continue;
3409 				if (ltcp->tcp_state >= TCPS_BOUND) {
3410 					/*
3411 					 * This port is being used and
3412 					 * its state is >= TCPS_BOUND,
3413 					 * so we can't bind to it.
3414 					 */
3415 					break;
3416 				}
3417 			} else {
3418 				/*
3419 				 * socket option SO_REUSEADDR is set on the
3420 				 * binding tcp_t.
3421 				 *
3422 				 * If two streams are bound to
3423 				 * same IP address or both addr
3424 				 * and bound source are wildcards
3425 				 * (INADDR_ANY), we want to stop
3426 				 * searching.
3427 				 * We have found a match of IP source
3428 				 * address and source port, which is
3429 				 * refused regardless of the
3430 				 * SO_REUSEADDR setting, so we break.
3431 				 */
3432 				if (IN6_ARE_ADDR_EQUAL(laddr,
3433 				    &ltcp->tcp_bound_source_v6) &&
3434 				    (ltcp->tcp_state == TCPS_LISTEN ||
3435 					ltcp->tcp_state == TCPS_BOUND))
3436 					break;
3437 			}
3438 		}
3439 		if (ltcp != NULL) {
3440 			/* The port number is busy */
3441 			mutex_exit(&tbf->tf_lock);
3442 		} else {
3443 			/*
3444 			 * This port is ours. Insert in fanout and mark as
3445 			 * bound to prevent others from getting the port
3446 			 * number.
3447 			 */
3448 			tcp->tcp_state = TCPS_BOUND;
3449 			tcp->tcp_lport = htons(port);
3450 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3451 
3452 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
3453 			    tcp->tcp_lport)] == tbf);
3454 			tcp_bind_hash_insert(tbf, tcp, 1);
3455 
3456 			mutex_exit(&tbf->tf_lock);
3457 
3458 			/*
3459 			 * We don't want tcp_next_port_to_try to "inherit"
3460 			 * a port number supplied by the user in a bind.
3461 			 */
3462 			if (user_specified)
3463 				return (port);
3464 
3465 			/*
3466 			 * This is the only place where tcp_next_port_to_try
3467 			 * is updated. After the update, it may or may not
3468 			 * be in the valid range.
3469 			 */
3470 			if (!tcp->tcp_anon_priv_bind)
3471 				tcp_next_port_to_try = port + 1;
3472 			return (port);
3473 		}
3474 
3475 		if (tcp->tcp_anon_priv_bind) {
3476 			port = tcp_get_next_priv_port();
3477 		} else {
3478 			if (count == 0 && user_specified) {
3479 				/*
3480 				 * We may have to return an anonymous port. So
3481 				 * get one to start with.
3482 				 */
3483 				port =
3484 				    tcp_update_next_port(tcp_next_port_to_try,
3485 					B_TRUE);
3486 				user_specified = B_FALSE;
3487 			} else {
3488 				port = tcp_update_next_port(port + 1, B_FALSE);
3489 			}
3490 		}
3491 
3492 		/*
3493 		 * Don't let this loop run forever in the case where
3494 		 * all of the anonymous ports are in use.
3495 		 */
3496 	} while (++count < loopmax);
3497 	return (0);
3498 }
3499 
3500 /*
3501  * We are dying for some reason.  Try to do it gracefully.  (May be called
3502  * as writer.)
3503  *
3504  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3505  * done by a service procedure).
3506  * TBD - Should the return value distinguish between the tcp_t being
3507  * freed and it being reinitialized?
3508  */
3509 static int
3510 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3511 {
3512 	mblk_t	*mp;
3513 	queue_t	*q;
3514 
3515 	TCP_CLD_STAT(tag);
3516 
3517 #if TCP_TAG_CLEAN_DEATH
3518 	tcp->tcp_cleandeathtag = tag;
3519 #endif
3520 
3521 	if (tcp->tcp_linger_tid != 0 &&
3522 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3523 		tcp_stop_lingering(tcp);
3524 	}
3525 
3526 	ASSERT(tcp != NULL);
3527 	ASSERT((tcp->tcp_family == AF_INET &&
3528 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3529 	    (tcp->tcp_family == AF_INET6 &&
3530 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3531 	    tcp->tcp_ipversion == IPV6_VERSION)));
3532 
3533 	if (TCP_IS_DETACHED(tcp)) {
3534 		if (tcp->tcp_hard_binding) {
3535 			/*
3536 			 * Its an eager that we are dealing with. We close the
3537 			 * eager but in case a conn_ind has already gone to the
3538 			 * listener, let tcp_accept_finish() send a discon_ind
3539 			 * to the listener and drop the last reference. If the
3540 			 * listener doesn't even know about the eager i.e. the
3541 			 * conn_ind hasn't gone up, blow away the eager and drop
3542 			 * the last reference as well. If the conn_ind has gone
3543 			 * up, state should be BOUND. tcp_accept_finish
3544 			 * will figure out that the connection has received a
3545 			 * RST and will send a DISCON_IND to the application.
3546 			 */
3547 			tcp_closei_local(tcp);
3548 			if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
3549 				CONN_DEC_REF(tcp->tcp_connp);
3550 			} else {
3551 				tcp->tcp_state = TCPS_BOUND;
3552 			}
3553 		} else {
3554 			tcp_close_detached(tcp);
3555 		}
3556 		return (0);
3557 	}
3558 
3559 	TCP_STAT(tcp_clean_death_nondetached);
3560 
3561 	/*
3562 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3563 	 * is run) postpone cleaning up the endpoint until service routine
3564 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3565 	 * client_errno since tcp_close uses the client_errno field.
3566 	 */
3567 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3568 		if (err != 0)
3569 			tcp->tcp_client_errno = err;
3570 
3571 		tcp->tcp_deferred_clean_death = B_TRUE;
3572 		return (-1);
3573 	}
3574 
3575 	q = tcp->tcp_rq;
3576 
3577 	/* Trash all inbound data */
3578 	flushq(q, FLUSHALL);
3579 
3580 	/*
3581 	 * If we are at least part way open and there is error
3582 	 * (err==0 implies no error)
3583 	 * notify our client by a T_DISCON_IND.
3584 	 */
3585 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3586 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3587 		    !TCP_IS_SOCKET(tcp)) {
3588 			/*
3589 			 * Send M_FLUSH according to TPI. Because sockets will
3590 			 * (and must) ignore FLUSHR we do that only for TPI
3591 			 * endpoints and sockets in STREAMS mode.
3592 			 */
3593 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3594 		}
3595 		if (tcp->tcp_debug) {
3596 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3597 			    "tcp_clean_death: discon err %d", err);
3598 		}
3599 		mp = mi_tpi_discon_ind(NULL, err, 0);
3600 		if (mp != NULL) {
3601 			putnext(q, mp);
3602 		} else {
3603 			if (tcp->tcp_debug) {
3604 				(void) strlog(TCP_MOD_ID, 0, 1,
3605 				    SL_ERROR|SL_TRACE,
3606 				    "tcp_clean_death, sending M_ERROR");
3607 			}
3608 			(void) putnextctl1(q, M_ERROR, EPROTO);
3609 		}
3610 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3611 			/* SYN_SENT or SYN_RCVD */
3612 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3613 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3614 			/* ESTABLISHED or CLOSE_WAIT */
3615 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3616 		}
3617 	}
3618 
3619 	tcp_reinit(tcp);
3620 	return (-1);
3621 }
3622 
3623 /*
3624  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3625  * to expire, stop the wait and finish the close.
3626  */
3627 static void
3628 tcp_stop_lingering(tcp_t *tcp)
3629 {
3630 	clock_t	delta = 0;
3631 
3632 	tcp->tcp_linger_tid = 0;
3633 	if (tcp->tcp_state > TCPS_LISTEN) {
3634 		tcp_acceptor_hash_remove(tcp);
3635 		if (tcp->tcp_flow_stopped) {
3636 			tcp_clrqfull(tcp);
3637 		}
3638 
3639 		if (tcp->tcp_timer_tid != 0) {
3640 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3641 			tcp->tcp_timer_tid = 0;
3642 		}
3643 		/*
3644 		 * Need to cancel those timers which will not be used when
3645 		 * TCP is detached.  This has to be done before the tcp_wq
3646 		 * is set to the global queue.
3647 		 */
3648 		tcp_timers_stop(tcp);
3649 
3650 
3651 		tcp->tcp_detached = B_TRUE;
3652 		tcp->tcp_rq = tcp_g_q;
3653 		tcp->tcp_wq = WR(tcp_g_q);
3654 
3655 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3656 			tcp_time_wait_append(tcp);
3657 			TCP_DBGSTAT(tcp_detach_time_wait);
3658 			goto finish;
3659 		}
3660 
3661 		/*
3662 		 * If delta is zero the timer event wasn't executed and was
3663 		 * successfully canceled. In this case we need to restart it
3664 		 * with the minimal delta possible.
3665 		 */
3666 		if (delta >= 0) {
3667 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3668 			    delta ? delta : 1);
3669 		}
3670 	} else {
3671 		tcp_closei_local(tcp);
3672 		CONN_DEC_REF(tcp->tcp_connp);
3673 	}
3674 finish:
3675 	/* Signal closing thread that it can complete close */
3676 	mutex_enter(&tcp->tcp_closelock);
3677 	tcp->tcp_detached = B_TRUE;
3678 	tcp->tcp_rq = tcp_g_q;
3679 	tcp->tcp_wq = WR(tcp_g_q);
3680 	tcp->tcp_closed = 1;
3681 	cv_signal(&tcp->tcp_closecv);
3682 	mutex_exit(&tcp->tcp_closelock);
3683 }
3684 
3685 /*
3686  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3687  * expires.
3688  */
3689 static void
3690 tcp_close_linger_timeout(void *arg)
3691 {
3692 	conn_t	*connp = (conn_t *)arg;
3693 	tcp_t 	*tcp = connp->conn_tcp;
3694 
3695 	tcp->tcp_client_errno = ETIMEDOUT;
3696 	tcp_stop_lingering(tcp);
3697 }
3698 
3699 static int
3700 tcp_close(queue_t *q, int flags)
3701 {
3702 	conn_t		*connp = Q_TO_CONN(q);
3703 	tcp_t		*tcp = connp->conn_tcp;
3704 	mblk_t 		*mp = &tcp->tcp_closemp;
3705 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3706 
3707 	ASSERT(WR(q)->q_next == NULL);
3708 	ASSERT(connp->conn_ref >= 2);
3709 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
3710 
3711 	/*
3712 	 * We are being closed as /dev/tcp or /dev/tcp6.
3713 	 *
3714 	 * Mark the conn as closing. ill_pending_mp_add will not
3715 	 * add any mp to the pending mp list, after this conn has
3716 	 * started closing. Same for sq_pending_mp_add
3717 	 */
3718 	mutex_enter(&connp->conn_lock);
3719 	connp->conn_state_flags |= CONN_CLOSING;
3720 	if (connp->conn_oper_pending_ill != NULL)
3721 		conn_ioctl_cleanup_reqd = B_TRUE;
3722 	CONN_INC_REF_LOCKED(connp);
3723 	mutex_exit(&connp->conn_lock);
3724 	tcp->tcp_closeflags = (uint8_t)flags;
3725 	ASSERT(connp->conn_ref >= 3);
3726 
3727 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
3728 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
3729 
3730 	mutex_enter(&tcp->tcp_closelock);
3731 
3732 	while (!tcp->tcp_closed)
3733 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3734 	mutex_exit(&tcp->tcp_closelock);
3735 	/*
3736 	 * In the case of listener streams that have eagers in the q or q0
3737 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3738 	 * tcp_wq of the eagers point to our queues. By waiting for the
3739 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3740 	 * up their queue pointers and also dropped their references to us.
3741 	 */
3742 	if (tcp->tcp_wait_for_eagers) {
3743 		mutex_enter(&connp->conn_lock);
3744 		while (connp->conn_ref != 1) {
3745 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3746 		}
3747 		mutex_exit(&connp->conn_lock);
3748 	}
3749 	/*
3750 	 * ioctl cleanup. The mp is queued in the
3751 	 * ill_pending_mp or in the sq_pending_mp.
3752 	 */
3753 	if (conn_ioctl_cleanup_reqd)
3754 		conn_ioctl_cleanup(connp);
3755 
3756 	qprocsoff(q);
3757 	inet_minor_free(ip_minor_arena, connp->conn_dev);
3758 
3759 	ASSERT(connp->conn_cred != NULL);
3760 	crfree(connp->conn_cred);
3761 	tcp->tcp_cred = connp->conn_cred = NULL;
3762 	tcp->tcp_cpid = -1;
3763 
3764 	/*
3765 	 * Drop IP's reference on the conn. This is the last reference
3766 	 * on the connp if the state was less than established. If the
3767 	 * connection has gone into timewait state, then we will have
3768 	 * one ref for the TCP and one more ref (total of two) for the
3769 	 * classifier connected hash list (a timewait connections stays
3770 	 * in connected hash till closed).
3771 	 *
3772 	 * We can't assert the references because there might be other
3773 	 * transient reference places because of some walkers or queued
3774 	 * packets in squeue for the timewait state.
3775 	 */
3776 	CONN_DEC_REF(connp);
3777 	q->q_ptr = WR(q)->q_ptr = NULL;
3778 	return (0);
3779 }
3780 
3781 static int
3782 tcpclose_accept(queue_t *q)
3783 {
3784 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3785 
3786 	/*
3787 	 * We had opened an acceptor STREAM for sockfs which is
3788 	 * now being closed due to some error.
3789 	 */
3790 	qprocsoff(q);
3791 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
3792 	q->q_ptr = WR(q)->q_ptr = NULL;
3793 	return (0);
3794 }
3795 
3796 
3797 /*
3798  * Called by streams close routine via squeues when our client blows off her
3799  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3800  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3801  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3802  * acked.
3803  *
3804  * NOTE: tcp_close potentially returns error when lingering.
3805  * However, the stream head currently does not pass these errors
3806  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3807  * errors to the application (from tsleep()) and not errors
3808  * like ECONNRESET caused by receiving a reset packet.
3809  */
3810 
3811 /* ARGSUSED */
3812 static void
3813 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3814 {
3815 	char	*msg;
3816 	conn_t	*connp = (conn_t *)arg;
3817 	tcp_t	*tcp = connp->conn_tcp;
3818 	clock_t	delta = 0;
3819 
3820 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3821 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3822 
3823 	/* Cancel any pending timeout */
3824 	if (tcp->tcp_ordrelid != 0) {
3825 		if (tcp->tcp_timeout) {
3826 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
3827 		}
3828 		tcp->tcp_ordrelid = 0;
3829 		tcp->tcp_timeout = B_FALSE;
3830 	}
3831 
3832 	mutex_enter(&tcp->tcp_eager_lock);
3833 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3834 		/* Cleanup for listener */
3835 		tcp_eager_cleanup(tcp, 0);
3836 		tcp->tcp_wait_for_eagers = 1;
3837 	}
3838 	mutex_exit(&tcp->tcp_eager_lock);
3839 
3840 	connp->conn_mdt_ok = B_FALSE;
3841 	tcp->tcp_mdt = B_FALSE;
3842 
3843 	msg = NULL;
3844 	switch (tcp->tcp_state) {
3845 	case TCPS_CLOSED:
3846 	case TCPS_IDLE:
3847 	case TCPS_BOUND:
3848 	case TCPS_LISTEN:
3849 		break;
3850 	case TCPS_SYN_SENT:
3851 		msg = "tcp_close, during connect";
3852 		break;
3853 	case TCPS_SYN_RCVD:
3854 		/*
3855 		 * Close during the connect 3-way handshake
3856 		 * but here there may or may not be pending data
3857 		 * already on queue. Process almost same as in
3858 		 * the ESTABLISHED state.
3859 		 */
3860 		/* FALLTHRU */
3861 	default:
3862 		if (tcp->tcp_fused)
3863 			tcp_unfuse(tcp);
3864 
3865 		/*
3866 		 * If SO_LINGER has set a zero linger time, abort the
3867 		 * connection with a reset.
3868 		 */
3869 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3870 			msg = "tcp_close, zero lingertime";
3871 			break;
3872 		}
3873 
3874 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3875 		/*
3876 		 * Abort connection if there is unread data queued.
3877 		 */
3878 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3879 			msg = "tcp_close, unread data";
3880 			break;
3881 		}
3882 		/*
3883 		 * tcp_hard_bound is now cleared thus all packets go through
3884 		 * tcp_lookup. This fact is used by tcp_detach below.
3885 		 *
3886 		 * We have done a qwait() above which could have possibly
3887 		 * drained more messages in turn causing transition to a
3888 		 * different state. Check whether we have to do the rest
3889 		 * of the processing or not.
3890 		 */
3891 		if (tcp->tcp_state <= TCPS_LISTEN)
3892 			break;
3893 
3894 		/*
3895 		 * Transmit the FIN before detaching the tcp_t.
3896 		 * After tcp_detach returns this queue/perimeter
3897 		 * no longer owns the tcp_t thus others can modify it.
3898 		 */
3899 		(void) tcp_xmit_end(tcp);
3900 
3901 		/*
3902 		 * If lingering on close then wait until the fin is acked,
3903 		 * the SO_LINGER time passes, or a reset is sent/received.
3904 		 */
3905 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3906 		    !(tcp->tcp_fin_acked) &&
3907 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3908 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3909 				tcp->tcp_client_errno = EWOULDBLOCK;
3910 			} else if (tcp->tcp_client_errno == 0) {
3911 
3912 				ASSERT(tcp->tcp_linger_tid == 0);
3913 
3914 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3915 				    tcp_close_linger_timeout,
3916 				    tcp->tcp_lingertime * hz);
3917 
3918 				/* tcp_close_linger_timeout will finish close */
3919 				if (tcp->tcp_linger_tid == 0)
3920 					tcp->tcp_client_errno = ENOSR;
3921 				else
3922 					return;
3923 			}
3924 
3925 			/*
3926 			 * Check if we need to detach or just close
3927 			 * the instance.
3928 			 */
3929 			if (tcp->tcp_state <= TCPS_LISTEN)
3930 				break;
3931 		}
3932 
3933 		/*
3934 		 * Make sure that no other thread will access the tcp_rq of
3935 		 * this instance (through lookups etc.) as tcp_rq will go
3936 		 * away shortly.
3937 		 */
3938 		tcp_acceptor_hash_remove(tcp);
3939 
3940 		if (tcp->tcp_flow_stopped) {
3941 			tcp_clrqfull(tcp);
3942 		}
3943 
3944 		if (tcp->tcp_timer_tid != 0) {
3945 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3946 			tcp->tcp_timer_tid = 0;
3947 		}
3948 		/*
3949 		 * Need to cancel those timers which will not be used when
3950 		 * TCP is detached.  This has to be done before the tcp_wq
3951 		 * is set to the global queue.
3952 		 */
3953 		tcp_timers_stop(tcp);
3954 
3955 		tcp->tcp_detached = B_TRUE;
3956 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3957 			tcp_time_wait_append(tcp);
3958 			TCP_DBGSTAT(tcp_detach_time_wait);
3959 			ASSERT(connp->conn_ref >= 3);
3960 			goto finish;
3961 		}
3962 
3963 		/*
3964 		 * If delta is zero the timer event wasn't executed and was
3965 		 * successfully canceled. In this case we need to restart it
3966 		 * with the minimal delta possible.
3967 		 */
3968 		if (delta >= 0)
3969 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3970 			    delta ? delta : 1);
3971 
3972 		ASSERT(connp->conn_ref >= 3);
3973 		goto finish;
3974 	}
3975 
3976 	/* Detach did not complete. Still need to remove q from stream. */
3977 	if (msg) {
3978 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3979 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3980 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3981 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3982 		    tcp->tcp_state == TCPS_SYN_RCVD)
3983 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3984 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3985 	}
3986 
3987 	tcp_closei_local(tcp);
3988 	CONN_DEC_REF(connp);
3989 	ASSERT(connp->conn_ref >= 2);
3990 
3991 finish:
3992 	/*
3993 	 * Although packets are always processed on the correct
3994 	 * tcp's perimeter and access is serialized via squeue's,
3995 	 * IP still needs a queue when sending packets in time_wait
3996 	 * state so use WR(tcp_g_q) till ip_output() can be
3997 	 * changed to deal with just connp. For read side, we
3998 	 * could have set tcp_rq to NULL but there are some cases
3999 	 * in tcp_rput_data() from early days of this code which
4000 	 * do a putnext without checking if tcp is closed. Those
4001 	 * need to be identified before both tcp_rq and tcp_wq
4002 	 * can be set to NULL and tcp_q_q can disappear forever.
4003 	 */
4004 	mutex_enter(&tcp->tcp_closelock);
4005 	/*
4006 	 * Don't change the queues in the case of a listener that has
4007 	 * eagers in its q or q0. It could surprise the eagers.
4008 	 * Instead wait for the eagers outside the squeue.
4009 	 */
4010 	if (!tcp->tcp_wait_for_eagers) {
4011 		tcp->tcp_detached = B_TRUE;
4012 		tcp->tcp_rq = tcp_g_q;
4013 		tcp->tcp_wq = WR(tcp_g_q);
4014 	}
4015 
4016 	/* Signal tcp_close() to finish closing. */
4017 	tcp->tcp_closed = 1;
4018 	cv_signal(&tcp->tcp_closecv);
4019 	mutex_exit(&tcp->tcp_closelock);
4020 }
4021 
4022 
4023 /*
4024  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4025  * Some stream heads get upset if they see these later on as anything but NULL.
4026  */
4027 static void
4028 tcp_close_mpp(mblk_t **mpp)
4029 {
4030 	mblk_t	*mp;
4031 
4032 	if ((mp = *mpp) != NULL) {
4033 		do {
4034 			mp->b_next = NULL;
4035 			mp->b_prev = NULL;
4036 		} while ((mp = mp->b_cont) != NULL);
4037 
4038 		mp = *mpp;
4039 		*mpp = NULL;
4040 		freemsg(mp);
4041 	}
4042 }
4043 
4044 /* Do detached close. */
4045 static void
4046 tcp_close_detached(tcp_t *tcp)
4047 {
4048 	if (tcp->tcp_fused)
4049 		tcp_unfuse(tcp);
4050 
4051 	/*
4052 	 * Clustering code serializes TCP disconnect callbacks and
4053 	 * cluster tcp list walks by blocking a TCP disconnect callback
4054 	 * if a cluster tcp list walk is in progress. This ensures
4055 	 * accurate accounting of TCPs in the cluster code even though
4056 	 * the TCP list walk itself is not atomic.
4057 	 */
4058 	tcp_closei_local(tcp);
4059 	CONN_DEC_REF(tcp->tcp_connp);
4060 }
4061 
4062 /*
4063  * Stop all TCP timers, and free the timer mblks if requested.
4064  */
4065 void
4066 tcp_timers_stop(tcp_t *tcp)
4067 {
4068 	if (tcp->tcp_timer_tid != 0) {
4069 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4070 		tcp->tcp_timer_tid = 0;
4071 	}
4072 	if (tcp->tcp_ka_tid != 0) {
4073 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4074 		tcp->tcp_ka_tid = 0;
4075 	}
4076 	if (tcp->tcp_ack_tid != 0) {
4077 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4078 		tcp->tcp_ack_tid = 0;
4079 	}
4080 	if (tcp->tcp_push_tid != 0) {
4081 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4082 		tcp->tcp_push_tid = 0;
4083 	}
4084 }
4085 
4086 /*
4087  * The tcp_t is going away. Remove it from all lists and set it
4088  * to TCPS_CLOSED. The freeing up of memory is deferred until
4089  * tcp_inactive. This is needed since a thread in tcp_rput might have
4090  * done a CONN_INC_REF on this structure before it was removed from the
4091  * hashes.
4092  */
4093 static void
4094 tcp_closei_local(tcp_t *tcp)
4095 {
4096 	ire_t 	*ire;
4097 	conn_t	*connp = tcp->tcp_connp;
4098 
4099 	if (!TCP_IS_SOCKET(tcp))
4100 		tcp_acceptor_hash_remove(tcp);
4101 
4102 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
4103 	tcp->tcp_ibsegs = 0;
4104 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
4105 	tcp->tcp_obsegs = 0;
4106 
4107 	/*
4108 	 * If we are an eager connection hanging off a listener that
4109 	 * hasn't formally accepted the connection yet, get off his
4110 	 * list and blow off any data that we have accumulated.
4111 	 */
4112 	if (tcp->tcp_listener != NULL) {
4113 		tcp_t	*listener = tcp->tcp_listener;
4114 		mutex_enter(&listener->tcp_eager_lock);
4115 		/*
4116 		 * tcp_eager_conn_ind == NULL means that the
4117 		 * conn_ind has already gone to listener. At
4118 		 * this point, eager will be closed but we
4119 		 * leave it in listeners eager list so that
4120 		 * if listener decides to close without doing
4121 		 * accept, we can clean this up. In tcp_wput_accept
4122 		 * we take case of the case of accept on closed
4123 		 * eager.
4124 		 */
4125 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4126 			tcp_eager_unlink(tcp);
4127 			mutex_exit(&listener->tcp_eager_lock);
4128 			/*
4129 			 * We don't want to have any pointers to the
4130 			 * listener queue, after we have released our
4131 			 * reference on the listener
4132 			 */
4133 			tcp->tcp_rq = tcp_g_q;
4134 			tcp->tcp_wq = WR(tcp_g_q);
4135 			CONN_DEC_REF(listener->tcp_connp);
4136 		} else {
4137 			mutex_exit(&listener->tcp_eager_lock);
4138 		}
4139 	}
4140 
4141 	/* Stop all the timers */
4142 	tcp_timers_stop(tcp);
4143 
4144 	if (tcp->tcp_state == TCPS_LISTEN) {
4145 		if (tcp->tcp_ip_addr_cache) {
4146 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4147 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4148 			tcp->tcp_ip_addr_cache = NULL;
4149 		}
4150 	}
4151 	if (tcp->tcp_flow_stopped)
4152 		tcp_clrqfull(tcp);
4153 
4154 	tcp_bind_hash_remove(tcp);
4155 	/*
4156 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4157 	 * is trying to remove this tcp from the time wait list, we will
4158 	 * block in tcp_time_wait_remove while trying to acquire the
4159 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4160 	 * requires the ipcl_hash_remove to be ordered after the
4161 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4162 	 */
4163 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4164 		tcp_time_wait_remove(tcp, NULL);
4165 	CL_INET_DISCONNECT(tcp);
4166 	ipcl_hash_remove(connp);
4167 
4168 	/*
4169 	 * Delete the cached ire in conn_ire_cache and also mark
4170 	 * the conn as CONDEMNED
4171 	 */
4172 	mutex_enter(&connp->conn_lock);
4173 	connp->conn_state_flags |= CONN_CONDEMNED;
4174 	ire = connp->conn_ire_cache;
4175 	connp->conn_ire_cache = NULL;
4176 	mutex_exit(&connp->conn_lock);
4177 	if (ire != NULL)
4178 		IRE_REFRELE_NOTR(ire);
4179 
4180 	/* Need to cleanup any pending ioctls */
4181 	ASSERT(tcp->tcp_time_wait_next == NULL);
4182 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4183 	ASSERT(tcp->tcp_time_wait_expire == 0);
4184 	tcp->tcp_state = TCPS_CLOSED;
4185 
4186 	/* Release any SSL context */
4187 	if (tcp->tcp_kssl_ent != NULL) {
4188 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4189 		tcp->tcp_kssl_ent = NULL;
4190 	}
4191 	if (tcp->tcp_kssl_ctx != NULL) {
4192 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4193 		tcp->tcp_kssl_ctx = NULL;
4194 	}
4195 	tcp->tcp_kssl_pending = B_FALSE;
4196 }
4197 
4198 /*
4199  * tcp is dying (called from ipcl_conn_destroy and error cases).
4200  * Free the tcp_t in either case.
4201  */
4202 void
4203 tcp_free(tcp_t *tcp)
4204 {
4205 	mblk_t	*mp;
4206 	ip6_pkt_t	*ipp;
4207 
4208 	ASSERT(tcp != NULL);
4209 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4210 
4211 	tcp->tcp_rq = NULL;
4212 	tcp->tcp_wq = NULL;
4213 
4214 	tcp_close_mpp(&tcp->tcp_xmit_head);
4215 	tcp_close_mpp(&tcp->tcp_reass_head);
4216 	if (tcp->tcp_rcv_list != NULL) {
4217 		/* Free b_next chain */
4218 		tcp_close_mpp(&tcp->tcp_rcv_list);
4219 	}
4220 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4221 		freemsg(mp);
4222 	}
4223 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4224 		freemsg(mp);
4225 	}
4226 
4227 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4228 		freeb(tcp->tcp_fused_sigurg_mp);
4229 		tcp->tcp_fused_sigurg_mp = NULL;
4230 	}
4231 
4232 	if (tcp->tcp_sack_info != NULL) {
4233 		if (tcp->tcp_notsack_list != NULL) {
4234 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4235 		}
4236 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4237 	}
4238 
4239 	if (tcp->tcp_hopopts != NULL) {
4240 		mi_free(tcp->tcp_hopopts);
4241 		tcp->tcp_hopopts = NULL;
4242 		tcp->tcp_hopoptslen = 0;
4243 	}
4244 	ASSERT(tcp->tcp_hopoptslen == 0);
4245 	if (tcp->tcp_dstopts != NULL) {
4246 		mi_free(tcp->tcp_dstopts);
4247 		tcp->tcp_dstopts = NULL;
4248 		tcp->tcp_dstoptslen = 0;
4249 	}
4250 	ASSERT(tcp->tcp_dstoptslen == 0);
4251 	if (tcp->tcp_rtdstopts != NULL) {
4252 		mi_free(tcp->tcp_rtdstopts);
4253 		tcp->tcp_rtdstopts = NULL;
4254 		tcp->tcp_rtdstoptslen = 0;
4255 	}
4256 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4257 	if (tcp->tcp_rthdr != NULL) {
4258 		mi_free(tcp->tcp_rthdr);
4259 		tcp->tcp_rthdr = NULL;
4260 		tcp->tcp_rthdrlen = 0;
4261 	}
4262 	ASSERT(tcp->tcp_rthdrlen == 0);
4263 
4264 	ipp = &tcp->tcp_sticky_ipp;
4265 	if ((ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS |
4266 	    IPPF_DSTOPTS | IPPF_RTHDR)) != 0) {
4267 		if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
4268 			kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
4269 			ipp->ipp_hopopts = NULL;
4270 			ipp->ipp_hopoptslen = 0;
4271 		}
4272 		if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
4273 			kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
4274 			ipp->ipp_rtdstopts = NULL;
4275 			ipp->ipp_rtdstoptslen = 0;
4276 		}
4277 		if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
4278 			kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
4279 			ipp->ipp_dstopts = NULL;
4280 			ipp->ipp_dstoptslen = 0;
4281 		}
4282 		if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
4283 			kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
4284 			ipp->ipp_rthdr = NULL;
4285 			ipp->ipp_rthdrlen = 0;
4286 		}
4287 		ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS |
4288 		    IPPF_DSTOPTS | IPPF_RTHDR);
4289 	}
4290 
4291 	/*
4292 	 * Free memory associated with the tcp/ip header template.
4293 	 */
4294 
4295 	if (tcp->tcp_iphc != NULL)
4296 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4297 
4298 	/*
4299 	 * Following is really a blowing away a union.
4300 	 * It happens to have exactly two members of identical size
4301 	 * the following code is enough.
4302 	 */
4303 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4304 
4305 	if (tcp->tcp_tracebuf != NULL) {
4306 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4307 		tcp->tcp_tracebuf = NULL;
4308 	}
4309 }
4310 
4311 
4312 /*
4313  * Put a connection confirmation message upstream built from the
4314  * address information within 'iph' and 'tcph'.  Report our success or failure.
4315  */
4316 static boolean_t
4317 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4318     mblk_t **defermp)
4319 {
4320 	sin_t	sin;
4321 	sin6_t	sin6;
4322 	mblk_t	*mp;
4323 	char	*optp = NULL;
4324 	int	optlen = 0;
4325 	cred_t	*cr;
4326 
4327 	if (defermp != NULL)
4328 		*defermp = NULL;
4329 
4330 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4331 		/*
4332 		 * Return in T_CONN_CON results of option negotiation through
4333 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4334 		 * negotiation, then what is received from remote end needs
4335 		 * to be taken into account but there is no such thing (yet?)
4336 		 * in our TCP/IP.
4337 		 * Note: We do not use mi_offset_param() here as
4338 		 * tcp_opts_conn_req contents do not directly come from
4339 		 * an application and are either generated in kernel or
4340 		 * from user input that was already verified.
4341 		 */
4342 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4343 		optp = (char *)(mp->b_rptr +
4344 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4345 		optlen = (int)
4346 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4347 	}
4348 
4349 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4350 		ipha_t *ipha = (ipha_t *)iphdr;
4351 
4352 		/* packet is IPv4 */
4353 		if (tcp->tcp_family == AF_INET) {
4354 			sin = sin_null;
4355 			sin.sin_addr.s_addr = ipha->ipha_src;
4356 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4357 			sin.sin_family = AF_INET;
4358 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4359 			    (int)sizeof (sin_t), optp, optlen);
4360 		} else {
4361 			sin6 = sin6_null;
4362 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4363 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4364 			sin6.sin6_family = AF_INET6;
4365 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4366 			    (int)sizeof (sin6_t), optp, optlen);
4367 
4368 		}
4369 	} else {
4370 		ip6_t	*ip6h = (ip6_t *)iphdr;
4371 
4372 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4373 		ASSERT(tcp->tcp_family == AF_INET6);
4374 		sin6 = sin6_null;
4375 		sin6.sin6_addr = ip6h->ip6_src;
4376 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4377 		sin6.sin6_family = AF_INET6;
4378 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4379 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4380 		    (int)sizeof (sin6_t), optp, optlen);
4381 	}
4382 
4383 	if (!mp)
4384 		return (B_FALSE);
4385 
4386 	if ((cr = DB_CRED(idmp)) != NULL) {
4387 		mblk_setcred(mp, cr);
4388 		DB_CPID(mp) = DB_CPID(idmp);
4389 	}
4390 
4391 	if (defermp == NULL)
4392 		putnext(tcp->tcp_rq, mp);
4393 	else
4394 		*defermp = mp;
4395 
4396 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4397 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4398 	return (B_TRUE);
4399 }
4400 
4401 /*
4402  * Defense for the SYN attack -
4403  * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
4404  *    one that doesn't have the dontdrop bit set.
4405  * 2. Don't drop a SYN request before its first timeout. This gives every
4406  *    request at least til the first timeout to complete its 3-way handshake.
4407  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4408  *    requests currently on the queue that has timed out. This will be used
4409  *    as an indicator of whether an attack is under way, so that appropriate
4410  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4411  *    either when eager goes into ESTABLISHED, or gets freed up.)
4412  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4413  *    # of timeout drops back to <= q0len/32 => SYN alert off
4414  */
4415 static boolean_t
4416 tcp_drop_q0(tcp_t *tcp)
4417 {
4418 	tcp_t	*eager;
4419 
4420 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4421 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4422 	/*
4423 	 * New one is added after next_q0 so prev_q0 points to the oldest
4424 	 * Also do not drop any established connections that are deferred on
4425 	 * q0 due to q being full
4426 	 */
4427 
4428 	eager = tcp->tcp_eager_prev_q0;
4429 	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
4430 		eager = eager->tcp_eager_prev_q0;
4431 		if (eager == tcp) {
4432 			eager = tcp->tcp_eager_prev_q0;
4433 			break;
4434 		}
4435 	}
4436 	if (eager->tcp_syn_rcvd_timeout == 0)
4437 		return (B_FALSE);
4438 
4439 	if (tcp->tcp_debug) {
4440 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4441 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4442 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
4443 		    tcp->tcp_conn_req_cnt_q0,
4444 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4445 	}
4446 
4447 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
4448 
4449 	/*
4450 	 * need to do refhold here because the selected eager could
4451 	 * be removed by someone else if we release the eager lock.
4452 	 */
4453 	CONN_INC_REF(eager->tcp_connp);
4454 	mutex_exit(&tcp->tcp_eager_lock);
4455 
4456 	/* Mark the IRE created for this SYN request temporary */
4457 	tcp_ip_ire_mark_advice(eager);
4458 	(void) tcp_clean_death(eager, ETIMEDOUT, 5);
4459 	CONN_DEC_REF(eager->tcp_connp);
4460 
4461 	mutex_enter(&tcp->tcp_eager_lock);
4462 	return (B_TRUE);
4463 }
4464 
4465 int
4466 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4467     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4468 {
4469 	tcp_t 		*ltcp = lconnp->conn_tcp;
4470 	tcp_t		*tcp = connp->conn_tcp;
4471 	mblk_t		*tpi_mp;
4472 	ipha_t		*ipha;
4473 	ip6_t		*ip6h;
4474 	sin6_t 		sin6;
4475 	in6_addr_t 	v6dst;
4476 	int		err;
4477 	int		ifindex = 0;
4478 	cred_t		*cr;
4479 
4480 	if (ipvers == IPV4_VERSION) {
4481 		ipha = (ipha_t *)mp->b_rptr;
4482 
4483 		connp->conn_send = ip_output;
4484 		connp->conn_recv = tcp_input;
4485 
4486 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4487 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4488 
4489 		sin6 = sin6_null;
4490 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4491 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4492 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4493 		sin6.sin6_family = AF_INET6;
4494 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4495 		    lconnp->conn_zoneid);
4496 		if (tcp->tcp_recvdstaddr) {
4497 			sin6_t	sin6d;
4498 
4499 			sin6d = sin6_null;
4500 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4501 			    &sin6d.sin6_addr);
4502 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4503 			sin6d.sin6_family = AF_INET;
4504 			tpi_mp = mi_tpi_extconn_ind(NULL,
4505 			    (char *)&sin6d, sizeof (sin6_t),
4506 			    (char *)&tcp,
4507 			    (t_scalar_t)sizeof (intptr_t),
4508 			    (char *)&sin6d, sizeof (sin6_t),
4509 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4510 		} else {
4511 			tpi_mp = mi_tpi_conn_ind(NULL,
4512 			    (char *)&sin6, sizeof (sin6_t),
4513 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4514 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4515 		}
4516 	} else {
4517 		ip6h = (ip6_t *)mp->b_rptr;
4518 
4519 		connp->conn_send = ip_output_v6;
4520 		connp->conn_recv = tcp_input;
4521 
4522 		connp->conn_srcv6 = ip6h->ip6_dst;
4523 		connp->conn_remv6 = ip6h->ip6_src;
4524 
4525 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4526 		ifindex = (int)DB_CKSUMSTUFF(mp);
4527 		DB_CKSUMSTUFF(mp) = 0;
4528 
4529 		sin6 = sin6_null;
4530 		sin6.sin6_addr = ip6h->ip6_src;
4531 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4532 		sin6.sin6_family = AF_INET6;
4533 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4534 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4535 		    lconnp->conn_zoneid);
4536 
4537 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4538 			/* Pass up the scope_id of remote addr */
4539 			sin6.sin6_scope_id = ifindex;
4540 		} else {
4541 			sin6.sin6_scope_id = 0;
4542 		}
4543 		if (tcp->tcp_recvdstaddr) {
4544 			sin6_t	sin6d;
4545 
4546 			sin6d = sin6_null;
4547 			sin6.sin6_addr = ip6h->ip6_dst;
4548 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4549 			sin6d.sin6_family = AF_INET;
4550 			tpi_mp = mi_tpi_extconn_ind(NULL,
4551 			    (char *)&sin6d, sizeof (sin6_t),
4552 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4553 			    (char *)&sin6d, sizeof (sin6_t),
4554 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4555 		} else {
4556 			tpi_mp = mi_tpi_conn_ind(NULL,
4557 			    (char *)&sin6, sizeof (sin6_t),
4558 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4559 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4560 		}
4561 	}
4562 
4563 	if (tpi_mp == NULL)
4564 		return (ENOMEM);
4565 
4566 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4567 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4568 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4569 	connp->conn_fully_bound = B_FALSE;
4570 
4571 	if (tcp_trace)
4572 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4573 
4574 	/* Inherit information from the "parent" */
4575 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4576 	tcp->tcp_family = ltcp->tcp_family;
4577 	tcp->tcp_wq = ltcp->tcp_wq;
4578 	tcp->tcp_rq = ltcp->tcp_rq;
4579 	tcp->tcp_mss = tcp_mss_def_ipv6;
4580 	tcp->tcp_detached = B_TRUE;
4581 	if ((err = tcp_init_values(tcp)) != 0) {
4582 		freemsg(tpi_mp);
4583 		return (err);
4584 	}
4585 
4586 	if (ipvers == IPV4_VERSION) {
4587 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4588 			freemsg(tpi_mp);
4589 			return (err);
4590 		}
4591 		ASSERT(tcp->tcp_ipha != NULL);
4592 	} else {
4593 		/* ifindex must be already set */
4594 		ASSERT(ifindex != 0);
4595 
4596 		if (ltcp->tcp_bound_if != 0) {
4597 			/*
4598 			 * Set newtcp's bound_if equal to
4599 			 * listener's value. If ifindex is
4600 			 * not the same as ltcp->tcp_bound_if,
4601 			 * it must be a packet for the ipmp group
4602 			 * of interfaces
4603 			 */
4604 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4605 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4606 			tcp->tcp_bound_if = ifindex;
4607 		}
4608 
4609 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4610 		tcp->tcp_recvifindex = 0;
4611 		tcp->tcp_recvhops = 0xffffffffU;
4612 		ASSERT(tcp->tcp_ip6h != NULL);
4613 	}
4614 
4615 	tcp->tcp_lport = ltcp->tcp_lport;
4616 
4617 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4618 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4619 			/*
4620 			 * Listener had options of some sort; eager inherits.
4621 			 * Free up the eager template and allocate one
4622 			 * of the right size.
4623 			 */
4624 			if (tcp->tcp_hdr_grown) {
4625 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4626 			} else {
4627 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4628 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4629 			}
4630 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4631 			    KM_NOSLEEP);
4632 			if (tcp->tcp_iphc == NULL) {
4633 				tcp->tcp_iphc_len = 0;
4634 				freemsg(tpi_mp);
4635 				return (ENOMEM);
4636 			}
4637 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4638 			tcp->tcp_hdr_grown = B_TRUE;
4639 		}
4640 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4641 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4642 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4643 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4644 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4645 
4646 		/*
4647 		 * Copy the IP+TCP header template from listener to eager
4648 		 */
4649 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4650 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4651 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4652 			    IPPROTO_RAW) {
4653 				tcp->tcp_ip6h =
4654 				    (ip6_t *)(tcp->tcp_iphc +
4655 					sizeof (ip6i_t));
4656 			} else {
4657 				tcp->tcp_ip6h =
4658 				    (ip6_t *)(tcp->tcp_iphc);
4659 			}
4660 			tcp->tcp_ipha = NULL;
4661 		} else {
4662 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4663 			tcp->tcp_ip6h = NULL;
4664 		}
4665 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4666 		    tcp->tcp_ip_hdr_len);
4667 	} else {
4668 		/*
4669 		 * only valid case when ipversion of listener and
4670 		 * eager differ is when listener is IPv6 and
4671 		 * eager is IPv4.
4672 		 * Eager header template has been initialized to the
4673 		 * maximum v4 header sizes, which includes space for
4674 		 * TCP and IP options.
4675 		 */
4676 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4677 		    (tcp->tcp_ipversion == IPV4_VERSION));
4678 		ASSERT(tcp->tcp_iphc_len >=
4679 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4680 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4681 		/* copy IP header fields individually */
4682 		tcp->tcp_ipha->ipha_ttl =
4683 		    ltcp->tcp_ip6h->ip6_hops;
4684 		bcopy(ltcp->tcp_tcph->th_lport,
4685 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4686 	}
4687 
4688 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4689 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4690 	    sizeof (in_port_t));
4691 
4692 	if (ltcp->tcp_lport == 0) {
4693 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4694 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4695 		    sizeof (in_port_t));
4696 	}
4697 
4698 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4699 		ASSERT(ipha != NULL);
4700 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4701 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4702 
4703 		/* Source routing option copyover (reverse it) */
4704 		if (tcp_rev_src_routes)
4705 			tcp_opt_reverse(tcp, ipha);
4706 	} else {
4707 		ASSERT(ip6h != NULL);
4708 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4709 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4710 	}
4711 
4712 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4713 	/*
4714 	 * If the SYN contains a credential, it's a loopback packet; attach
4715 	 * the credential to the TPI message.
4716 	 */
4717 	if ((cr = DB_CRED(idmp)) != NULL) {
4718 		mblk_setcred(tpi_mp, cr);
4719 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4720 	}
4721 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4722 
4723 	/* Inherit the listener's SSL protection state */
4724 
4725 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4726 		kssl_hold_ent(tcp->tcp_kssl_ent);
4727 		tcp->tcp_kssl_pending = B_TRUE;
4728 	}
4729 
4730 	return (0);
4731 }
4732 
4733 
4734 int
4735 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4736     tcph_t *tcph, mblk_t *idmp)
4737 {
4738 	tcp_t 		*ltcp = lconnp->conn_tcp;
4739 	tcp_t		*tcp = connp->conn_tcp;
4740 	sin_t		sin;
4741 	mblk_t		*tpi_mp = NULL;
4742 	int		err;
4743 	cred_t		*cr;
4744 
4745 	sin = sin_null;
4746 	sin.sin_addr.s_addr = ipha->ipha_src;
4747 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4748 	sin.sin_family = AF_INET;
4749 	if (ltcp->tcp_recvdstaddr) {
4750 		sin_t	sind;
4751 
4752 		sind = sin_null;
4753 		sind.sin_addr.s_addr = ipha->ipha_dst;
4754 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4755 		sind.sin_family = AF_INET;
4756 		tpi_mp = mi_tpi_extconn_ind(NULL,
4757 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4758 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4759 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4760 	} else {
4761 		tpi_mp = mi_tpi_conn_ind(NULL,
4762 		    (char *)&sin, sizeof (sin_t),
4763 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4764 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4765 	}
4766 
4767 	if (tpi_mp == NULL) {
4768 		return (ENOMEM);
4769 	}
4770 
4771 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4772 	connp->conn_send = ip_output;
4773 	connp->conn_recv = tcp_input;
4774 	connp->conn_fully_bound = B_FALSE;
4775 
4776 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4777 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4778 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4779 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4780 
4781 	if (tcp_trace) {
4782 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4783 	}
4784 
4785 	/* Inherit information from the "parent" */
4786 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4787 	tcp->tcp_family = ltcp->tcp_family;
4788 	tcp->tcp_wq = ltcp->tcp_wq;
4789 	tcp->tcp_rq = ltcp->tcp_rq;
4790 	tcp->tcp_mss = tcp_mss_def_ipv4;
4791 	tcp->tcp_detached = B_TRUE;
4792 	if ((err = tcp_init_values(tcp)) != 0) {
4793 		freemsg(tpi_mp);
4794 		return (err);
4795 	}
4796 
4797 	/*
4798 	 * Let's make sure that eager tcp template has enough space to
4799 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4800 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4801 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4802 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4803 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4804 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4805 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4806 	 */
4807 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4808 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4809 
4810 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4811 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4812 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4813 	tcp->tcp_ttl = ltcp->tcp_ttl;
4814 	tcp->tcp_tos = ltcp->tcp_tos;
4815 
4816 	/* Copy the IP+TCP header template from listener to eager */
4817 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4818 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4819 	tcp->tcp_ip6h = NULL;
4820 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4821 	    tcp->tcp_ip_hdr_len);
4822 
4823 	/* Initialize the IP addresses and Ports */
4824 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4825 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4826 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4827 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4828 
4829 	/* Source routing option copyover (reverse it) */
4830 	if (tcp_rev_src_routes)
4831 		tcp_opt_reverse(tcp, ipha);
4832 
4833 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4834 
4835 	/*
4836 	 * If the SYN contains a credential, it's a loopback packet; attach
4837 	 * the credential to the TPI message.
4838 	 */
4839 	if ((cr = DB_CRED(idmp)) != NULL) {
4840 		mblk_setcred(tpi_mp, cr);
4841 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4842 	}
4843 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4844 
4845 	/* Inherit the listener's SSL protection state */
4846 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4847 		kssl_hold_ent(tcp->tcp_kssl_ent);
4848 		tcp->tcp_kssl_pending = B_TRUE;
4849 	}
4850 
4851 	return (0);
4852 }
4853 
4854 /*
4855  * sets up conn for ipsec.
4856  * if the first mblk is M_CTL it is consumed and mpp is updated.
4857  * in case of error mpp is freed.
4858  */
4859 conn_t *
4860 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4861 {
4862 	conn_t 		*connp = tcp->tcp_connp;
4863 	conn_t 		*econnp;
4864 	squeue_t 	*new_sqp;
4865 	mblk_t 		*first_mp = *mpp;
4866 	mblk_t		*mp = *mpp;
4867 	boolean_t	mctl_present = B_FALSE;
4868 	uint_t		ipvers;
4869 
4870 	econnp = tcp_get_conn(sqp);
4871 	if (econnp == NULL) {
4872 		freemsg(first_mp);
4873 		return (NULL);
4874 	}
4875 	if (DB_TYPE(mp) == M_CTL) {
4876 		if (mp->b_cont == NULL ||
4877 		    mp->b_cont->b_datap->db_type != M_DATA) {
4878 			freemsg(first_mp);
4879 			return (NULL);
4880 		}
4881 		mp = mp->b_cont;
4882 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4883 			freemsg(first_mp);
4884 			return (NULL);
4885 		}
4886 
4887 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4888 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4889 		mctl_present = B_TRUE;
4890 	} else {
4891 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4892 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4893 	}
4894 
4895 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4896 	DB_CKSUMSTART(mp) = 0;
4897 
4898 	ASSERT(OK_32PTR(mp->b_rptr));
4899 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4900 	if (ipvers == IPV4_VERSION) {
4901 		uint16_t  	*up;
4902 		uint32_t	ports;
4903 		ipha_t		*ipha;
4904 
4905 		ipha = (ipha_t *)mp->b_rptr;
4906 		up = (uint16_t *)((uchar_t *)ipha +
4907 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4908 		ports = *(uint32_t *)up;
4909 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4910 		    ipha->ipha_dst, ipha->ipha_src, ports);
4911 	} else {
4912 		uint16_t  	*up;
4913 		uint32_t	ports;
4914 		uint16_t	ip_hdr_len;
4915 		uint8_t		*nexthdrp;
4916 		ip6_t 		*ip6h;
4917 		tcph_t		*tcph;
4918 
4919 		ip6h = (ip6_t *)mp->b_rptr;
4920 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4921 			ip_hdr_len = IPV6_HDR_LEN;
4922 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4923 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4924 			CONN_DEC_REF(econnp);
4925 			freemsg(first_mp);
4926 			return (NULL);
4927 		}
4928 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4929 		up = (uint16_t *)tcph->th_lport;
4930 		ports = *(uint32_t *)up;
4931 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4932 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4933 	}
4934 
4935 	/*
4936 	 * The caller already ensured that there is a sqp present.
4937 	 */
4938 	econnp->conn_sqp = new_sqp;
4939 
4940 	if (connp->conn_policy != NULL) {
4941 		ipsec_in_t *ii;
4942 		ii = (ipsec_in_t *)(first_mp->b_rptr);
4943 		ASSERT(ii->ipsec_in_policy == NULL);
4944 		IPPH_REFHOLD(connp->conn_policy);
4945 		ii->ipsec_in_policy = connp->conn_policy;
4946 
4947 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
4948 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
4949 			CONN_DEC_REF(econnp);
4950 			freemsg(first_mp);
4951 			return (NULL);
4952 		}
4953 	}
4954 
4955 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
4956 		CONN_DEC_REF(econnp);
4957 		freemsg(first_mp);
4958 		return (NULL);
4959 	}
4960 
4961 	/*
4962 	 * If we know we have some policy, pass the "IPSEC"
4963 	 * options size TCP uses this adjust the MSS.
4964 	 */
4965 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
4966 	if (mctl_present) {
4967 		freeb(first_mp);
4968 		*mpp = mp;
4969 	}
4970 
4971 	return (econnp);
4972 }
4973 
4974 /*
4975  * tcp_get_conn/tcp_free_conn
4976  *
4977  * tcp_get_conn is used to get a clean tcp connection structure.
4978  * It tries to reuse the connections put on the freelist by the
4979  * time_wait_collector failing which it goes to kmem_cache. This
4980  * way has two benefits compared to just allocating from and
4981  * freeing to kmem_cache.
4982  * 1) The time_wait_collector can free (which includes the cleanup)
4983  * outside the squeue. So when the interrupt comes, we have a clean
4984  * connection sitting in the freelist. Obviously, this buys us
4985  * performance.
4986  *
4987  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
4988  * has multiple disadvantages - tying up the squeue during alloc, and the
4989  * fact that IPSec policy initialization has to happen here which
4990  * requires us sending a M_CTL and checking for it i.e. real ugliness.
4991  * But allocating the conn/tcp in IP land is also not the best since
4992  * we can't check the 'q' and 'q0' which are protected by squeue and
4993  * blindly allocate memory which might have to be freed here if we are
4994  * not allowed to accept the connection. By using the freelist and
4995  * putting the conn/tcp back in freelist, we don't pay a penalty for
4996  * allocating memory without checking 'q/q0' and freeing it if we can't
4997  * accept the connection.
4998  *
4999  * Care should be taken to put the conn back in the same squeue's freelist
5000  * from which it was allocated. Best results are obtained if conn is
5001  * allocated from listener's squeue and freed to the same. Time wait
5002  * collector will free up the freelist is the connection ends up sitting
5003  * there for too long.
5004  */
5005 void *
5006 tcp_get_conn(void *arg)
5007 {
5008 	tcp_t			*tcp = NULL;
5009 	conn_t			*connp = NULL;
5010 	squeue_t		*sqp = (squeue_t *)arg;
5011 	tcp_squeue_priv_t 	*tcp_time_wait;
5012 
5013 	tcp_time_wait =
5014 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5015 
5016 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5017 	tcp = tcp_time_wait->tcp_free_list;
5018 	if (tcp != NULL) {
5019 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5020 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5021 		tcp->tcp_time_wait_next = NULL;
5022 		connp = tcp->tcp_connp;
5023 		connp->conn_flags |= IPCL_REUSED;
5024 		return ((void *)connp);
5025 	}
5026 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5027 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
5028 		return (NULL);
5029 	return ((void *)connp);
5030 }
5031 
5032 /* BEGIN CSTYLED */
5033 /*
5034  *
5035  * The sockfs ACCEPT path:
5036  * =======================
5037  *
5038  * The eager is now established in its own perimeter as soon as SYN is
5039  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5040  * completes the accept processing on the acceptor STREAM. The sending
5041  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5042  * listener but a TLI/XTI listener completes the accept processing
5043  * on the listener perimeter.
5044  *
5045  * Common control flow for 3 way handshake:
5046  * ----------------------------------------
5047  *
5048  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5049  *					-> tcp_conn_request()
5050  *
5051  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5052  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5053  *
5054  * Sockfs ACCEPT Path:
5055  * -------------------
5056  *
5057  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5058  * as STREAM entry point)
5059  *
5060  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5061  *
5062  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5063  * association (we are not behind eager's squeue but sockfs is protecting us
5064  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5065  * is changed to point at tcp_wput().
5066  *
5067  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5068  * listener (done on listener's perimeter).
5069  *
5070  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5071  * accept.
5072  *
5073  * TLI/XTI client ACCEPT path:
5074  * ---------------------------
5075  *
5076  * soaccept() sends T_CONN_RES on the listener STREAM.
5077  *
5078  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5079  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5080  *
5081  * Locks:
5082  * ======
5083  *
5084  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5085  * and listeners->tcp_eager_next_q.
5086  *
5087  * Referencing:
5088  * ============
5089  *
5090  * 1) We start out in tcp_conn_request by eager placing a ref on
5091  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5092  *
5093  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5094  * doing so we place a ref on the eager. This ref is finally dropped at the
5095  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5096  * reference is dropped by the squeue framework.
5097  *
5098  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5099  *
5100  * The reference must be released by the same entity that added the reference
5101  * In the above scheme, the eager is the entity that adds and releases the
5102  * references. Note that tcp_accept_finish executes in the squeue of the eager
5103  * (albeit after it is attached to the acceptor stream). Though 1. executes
5104  * in the listener's squeue, the eager is nascent at this point and the
5105  * reference can be considered to have been added on behalf of the eager.
5106  *
5107  * Eager getting a Reset or listener closing:
5108  * ==========================================
5109  *
5110  * Once the listener and eager are linked, the listener never does the unlink.
5111  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5112  * a message on all eager perimeter. The eager then does the unlink, clears
5113  * any pointers to the listener's queue and drops the reference to the
5114  * listener. The listener waits in tcp_close outside the squeue until its
5115  * refcount has dropped to 1. This ensures that the listener has waited for
5116  * all eagers to clear their association with the listener.
5117  *
5118  * Similarly, if eager decides to go away, it can unlink itself and close.
5119  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5120  * the reference to eager is still valid because of the extra ref we put
5121  * in tcp_send_conn_ind.
5122  *
5123  * Listener can always locate the eager under the protection
5124  * of the listener->tcp_eager_lock, and then do a refhold
5125  * on the eager during the accept processing.
5126  *
5127  * The acceptor stream accesses the eager in the accept processing
5128  * based on the ref placed on eager before sending T_conn_ind.
5129  * The only entity that can negate this refhold is a listener close
5130  * which is mutually exclusive with an active acceptor stream.
5131  *
5132  * Eager's reference on the listener
5133  * ===================================
5134  *
5135  * If the accept happens (even on a closed eager) the eager drops its
5136  * reference on the listener at the start of tcp_accept_finish. If the
5137  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5138  * the reference is dropped in tcp_closei_local. If the listener closes,
5139  * the reference is dropped in tcp_eager_kill. In all cases the reference
5140  * is dropped while executing in the eager's context (squeue).
5141  */
5142 /* END CSTYLED */
5143 
5144 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5145 
5146 /*
5147  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5148  * tcp_rput_data will not see any SYN packets.
5149  */
5150 /* ARGSUSED */
5151 void
5152 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5153 {
5154 	tcph_t		*tcph;
5155 	uint32_t	seg_seq;
5156 	tcp_t		*eager;
5157 	uint_t		ipvers;
5158 	ipha_t		*ipha;
5159 	ip6_t		*ip6h;
5160 	int		err;
5161 	conn_t		*econnp = NULL;
5162 	squeue_t	*new_sqp;
5163 	mblk_t		*mp1;
5164 	uint_t 		ip_hdr_len;
5165 	conn_t		*connp = (conn_t *)arg;
5166 	tcp_t		*tcp = connp->conn_tcp;
5167 	ire_t		*ire;
5168 
5169 	if (tcp->tcp_state != TCPS_LISTEN)
5170 		goto error2;
5171 
5172 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5173 
5174 	mutex_enter(&tcp->tcp_eager_lock);
5175 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5176 		mutex_exit(&tcp->tcp_eager_lock);
5177 		TCP_STAT(tcp_listendrop);
5178 		BUMP_MIB(&tcp_mib, tcpListenDrop);
5179 		if (tcp->tcp_debug) {
5180 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5181 			    "tcp_conn_request: listen backlog (max=%d) "
5182 			    "overflow (%d pending) on %s",
5183 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5184 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5185 		}
5186 		goto error2;
5187 	}
5188 
5189 	if (tcp->tcp_conn_req_cnt_q0 >=
5190 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
5191 		/*
5192 		 * Q0 is full. Drop a pending half-open req from the queue
5193 		 * to make room for the new SYN req. Also mark the time we
5194 		 * drop a SYN.
5195 		 *
5196 		 * A more aggressive defense against SYN attack will
5197 		 * be to set the "tcp_syn_defense" flag now.
5198 		 */
5199 		TCP_STAT(tcp_listendropq0);
5200 		tcp->tcp_last_rcv_lbolt = lbolt64;
5201 		if (!tcp_drop_q0(tcp)) {
5202 			mutex_exit(&tcp->tcp_eager_lock);
5203 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
5204 			if (tcp->tcp_debug) {
5205 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5206 				    "tcp_conn_request: listen half-open queue "
5207 				    "(max=%d) full (%d pending) on %s",
5208 				    tcp_conn_req_max_q0,
5209 				    tcp->tcp_conn_req_cnt_q0,
5210 				    tcp_display(tcp, NULL,
5211 				    DISP_PORT_ONLY));
5212 			}
5213 			goto error2;
5214 		}
5215 	}
5216 	mutex_exit(&tcp->tcp_eager_lock);
5217 
5218 	/*
5219 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5220 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5221 	 * link local address.  If IPSec is enabled, db_struioflag has
5222 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5223 	 * otherwise an error case if neither of them is set.
5224 	 */
5225 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5226 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5227 		DB_CKSUMSTART(mp) = 0;
5228 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5229 		econnp = (conn_t *)tcp_get_conn(arg2);
5230 		if (econnp == NULL)
5231 			goto error2;
5232 		econnp->conn_sqp = new_sqp;
5233 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5234 		/*
5235 		 * mp is updated in tcp_get_ipsec_conn().
5236 		 */
5237 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5238 		if (econnp == NULL) {
5239 			/*
5240 			 * mp freed by tcp_get_ipsec_conn.
5241 			 */
5242 			return;
5243 		}
5244 	} else {
5245 		goto error2;
5246 	}
5247 
5248 	ASSERT(DB_TYPE(mp) == M_DATA);
5249 
5250 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5251 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5252 	ASSERT(OK_32PTR(mp->b_rptr));
5253 	if (ipvers == IPV4_VERSION) {
5254 		ipha = (ipha_t *)mp->b_rptr;
5255 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5256 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5257 	} else {
5258 		ip6h = (ip6_t *)mp->b_rptr;
5259 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5260 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5261 	}
5262 
5263 	if (tcp->tcp_family == AF_INET) {
5264 		ASSERT(ipvers == IPV4_VERSION);
5265 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5266 	} else {
5267 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5268 	}
5269 
5270 	if (err)
5271 		goto error3;
5272 
5273 	eager = econnp->conn_tcp;
5274 
5275 	/* Inherit various TCP parameters from the listener */
5276 	eager->tcp_naglim = tcp->tcp_naglim;
5277 	eager->tcp_first_timer_threshold =
5278 	    tcp->tcp_first_timer_threshold;
5279 	eager->tcp_second_timer_threshold =
5280 	    tcp->tcp_second_timer_threshold;
5281 
5282 	eager->tcp_first_ctimer_threshold =
5283 	    tcp->tcp_first_ctimer_threshold;
5284 	eager->tcp_second_ctimer_threshold =
5285 	    tcp->tcp_second_ctimer_threshold;
5286 
5287 	/*
5288 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5289 	 * zone id before the accept is completed in tcp_wput_accept().
5290 	 */
5291 	econnp->conn_zoneid = connp->conn_zoneid;
5292 
5293 	eager->tcp_hard_binding = B_TRUE;
5294 
5295 	tcp_bind_hash_insert(&tcp_bind_fanout[
5296 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5297 
5298 	CL_INET_CONNECT(eager);
5299 
5300 	/*
5301 	 * No need to check for multicast destination since ip will only pass
5302 	 * up multicasts to those that have expressed interest
5303 	 * TODO: what about rejecting broadcasts?
5304 	 * Also check that source is not a multicast or broadcast address.
5305 	 */
5306 	eager->tcp_state = TCPS_SYN_RCVD;
5307 
5308 
5309 	/*
5310 	 * There should be no ire in the mp as we are being called after
5311 	 * receiving the SYN.
5312 	 */
5313 	ASSERT(tcp_ire_mp(mp) == NULL);
5314 
5315 	/*
5316 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5317 	 */
5318 
5319 	if (tcp_adapt_ire(eager, NULL) == 0) {
5320 		/* Undo the bind_hash_insert */
5321 		tcp_bind_hash_remove(eager);
5322 		goto error3;
5323 	}
5324 
5325 	/* Process all TCP options. */
5326 	tcp_process_options(eager, tcph);
5327 
5328 	/* Is the other end ECN capable? */
5329 	if (tcp_ecn_permitted >= 1 &&
5330 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5331 		eager->tcp_ecn_ok = B_TRUE;
5332 	}
5333 
5334 	/*
5335 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5336 	 * window size changed via SO_RCVBUF option.  First round up the
5337 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5338 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5339 	 * setting.
5340 	 *
5341 	 * Note if there is a rpipe metric associated with the remote host,
5342 	 * we should not inherit receive window size from listener.
5343 	 */
5344 	eager->tcp_rwnd = MSS_ROUNDUP(
5345 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5346 	    eager->tcp_rwnd), eager->tcp_mss);
5347 	if (eager->tcp_snd_ws_ok)
5348 		tcp_set_ws_value(eager);
5349 	/*
5350 	 * Note that this is the only place tcp_rwnd_set() is called for
5351 	 * accepting a connection.  We need to call it here instead of
5352 	 * after the 3-way handshake because we need to tell the other
5353 	 * side our rwnd in the SYN-ACK segment.
5354 	 */
5355 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5356 
5357 	/*
5358 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5359 	 * via soaccept()->soinheritoptions() which essentially applies
5360 	 * all the listener options to the new STREAM. The options that we
5361 	 * need to take care of are:
5362 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5363 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5364 	 * SO_SNDBUF, SO_RCVBUF.
5365 	 *
5366 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5367 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5368 	 *		tcp_maxpsz_set() gets called later from
5369 	 *		tcp_accept_finish(), the option takes effect.
5370 	 *
5371 	 */
5372 	/* Set the TCP options */
5373 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5374 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5375 	eager->tcp_oobinline = tcp->tcp_oobinline;
5376 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5377 	eager->tcp_broadcast = tcp->tcp_broadcast;
5378 	eager->tcp_useloopback = tcp->tcp_useloopback;
5379 	eager->tcp_dontroute = tcp->tcp_dontroute;
5380 	eager->tcp_linger = tcp->tcp_linger;
5381 	eager->tcp_lingertime = tcp->tcp_lingertime;
5382 	if (tcp->tcp_ka_enabled)
5383 		eager->tcp_ka_enabled = 1;
5384 
5385 	/* Set the IP options */
5386 	econnp->conn_broadcast = connp->conn_broadcast;
5387 	econnp->conn_loopback = connp->conn_loopback;
5388 	econnp->conn_dontroute = connp->conn_dontroute;
5389 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5390 
5391 	/* Put a ref on the listener for the eager. */
5392 	CONN_INC_REF(connp);
5393 	mutex_enter(&tcp->tcp_eager_lock);
5394 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5395 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5396 	tcp->tcp_eager_next_q0 = eager;
5397 	eager->tcp_eager_prev_q0 = tcp;
5398 
5399 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5400 	eager->tcp_listener = tcp;
5401 	eager->tcp_saved_listener = tcp;
5402 
5403 	/*
5404 	 * Tag this detached tcp vector for later retrieval
5405 	 * by our listener client in tcp_accept().
5406 	 */
5407 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5408 	tcp->tcp_conn_req_cnt_q0++;
5409 	if (++tcp->tcp_conn_req_seqnum == -1) {
5410 		/*
5411 		 * -1 is "special" and defined in TPI as something
5412 		 * that should never be used in T_CONN_IND
5413 		 */
5414 		++tcp->tcp_conn_req_seqnum;
5415 	}
5416 	mutex_exit(&tcp->tcp_eager_lock);
5417 
5418 	if (tcp->tcp_syn_defense) {
5419 		/* Don't drop the SYN that comes from a good IP source */
5420 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5421 		if (addr_cache != NULL && eager->tcp_remote ==
5422 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5423 			eager->tcp_dontdrop = B_TRUE;
5424 		}
5425 	}
5426 
5427 	/*
5428 	 * We need to insert the eager in its own perimeter but as soon
5429 	 * as we do that, we expose the eager to the classifier and
5430 	 * should not touch any field outside the eager's perimeter.
5431 	 * So do all the work necessary before inserting the eager
5432 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5433 	 * will succeed but undo everything if it fails.
5434 	 */
5435 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5436 	eager->tcp_irs = seg_seq;
5437 	eager->tcp_rack = seg_seq;
5438 	eager->tcp_rnxt = seg_seq + 1;
5439 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5440 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
5441 	eager->tcp_state = TCPS_SYN_RCVD;
5442 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5443 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5444 	if (mp1 == NULL)
5445 		goto error1;
5446 	mblk_setcred(mp1, tcp->tcp_cred);
5447 	DB_CPID(mp1) = tcp->tcp_cpid;
5448 
5449 	/*
5450 	 * We need to start the rto timer. In normal case, we start
5451 	 * the timer after sending the packet on the wire (or at
5452 	 * least believing that packet was sent by waiting for
5453 	 * CALL_IP_WPUT() to return). Since this is the first packet
5454 	 * being sent on the wire for the eager, our initial tcp_rto
5455 	 * is at least tcp_rexmit_interval_min which is a fairly
5456 	 * large value to allow the algorithm to adjust slowly to large
5457 	 * fluctuations of RTT during first few transmissions.
5458 	 *
5459 	 * Starting the timer first and then sending the packet in this
5460 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5461 	 * is of the order of several 100ms and starting the timer
5462 	 * first and then sending the packet will result in difference
5463 	 * of few micro seconds.
5464 	 *
5465 	 * Without this optimization, we are forced to hold the fanout
5466 	 * lock across the ipcl_bind_insert() and sending the packet
5467 	 * so that we don't race against an incoming packet (maybe RST)
5468 	 * for this eager.
5469 	 */
5470 
5471 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5472 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5473 
5474 
5475 	/*
5476 	 * Insert the eager in its own perimeter now. We are ready to deal
5477 	 * with any packets on eager.
5478 	 */
5479 	if (eager->tcp_ipversion == IPV4_VERSION) {
5480 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5481 			goto error;
5482 		}
5483 	} else {
5484 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5485 			goto error;
5486 		}
5487 	}
5488 
5489 	/* mark conn as fully-bound */
5490 	econnp->conn_fully_bound = B_TRUE;
5491 
5492 	/* Send the SYN-ACK */
5493 	tcp_send_data(eager, eager->tcp_wq, mp1);
5494 	freemsg(mp);
5495 
5496 	return;
5497 error:
5498 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
5499 	freemsg(mp1);
5500 error1:
5501 	/* Undo what we did above */
5502 	mutex_enter(&tcp->tcp_eager_lock);
5503 	tcp_eager_unlink(eager);
5504 	mutex_exit(&tcp->tcp_eager_lock);
5505 	/* Drop eager's reference on the listener */
5506 	CONN_DEC_REF(connp);
5507 
5508 	/*
5509 	 * Delete the cached ire in conn_ire_cache and also mark
5510 	 * the conn as CONDEMNED
5511 	 */
5512 	mutex_enter(&econnp->conn_lock);
5513 	econnp->conn_state_flags |= CONN_CONDEMNED;
5514 	ire = econnp->conn_ire_cache;
5515 	econnp->conn_ire_cache = NULL;
5516 	mutex_exit(&econnp->conn_lock);
5517 	if (ire != NULL)
5518 		IRE_REFRELE_NOTR(ire);
5519 
5520 	/*
5521 	 * tcp_accept_comm inserts the eager to the bind_hash
5522 	 * we need to remove it from the hash if ipcl_conn_insert
5523 	 * fails.
5524 	 */
5525 	tcp_bind_hash_remove(eager);
5526 	/* Drop the eager ref placed in tcp_open_detached */
5527 	CONN_DEC_REF(econnp);
5528 
5529 	/*
5530 	 * If a connection already exists, send the mp to that connections so
5531 	 * that it can be appropriately dealt with.
5532 	 */
5533 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
5534 		if (!IPCL_IS_CONNECTED(econnp)) {
5535 			/*
5536 			 * Something bad happened. ipcl_conn_insert()
5537 			 * failed because a connection already existed
5538 			 * in connected hash but we can't find it
5539 			 * anymore (someone blew it away). Just
5540 			 * free this message and hopefully remote
5541 			 * will retransmit at which time the SYN can be
5542 			 * treated as a new connection or dealth with
5543 			 * a TH_RST if a connection already exists.
5544 			 */
5545 			freemsg(mp);
5546 		} else {
5547 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
5548 			    econnp, SQTAG_TCP_CONN_REQ);
5549 		}
5550 	} else {
5551 		/* Nobody wants this packet */
5552 		freemsg(mp);
5553 	}
5554 	return;
5555 error2:
5556 	freemsg(mp);
5557 	return;
5558 error3:
5559 	CONN_DEC_REF(econnp);
5560 	freemsg(mp);
5561 }
5562 
5563 /*
5564  * In an ideal case of vertical partition in NUMA architecture, its
5565  * beneficial to have the listener and all the incoming connections
5566  * tied to the same squeue. The other constraint is that incoming
5567  * connections should be tied to the squeue attached to interrupted
5568  * CPU for obvious locality reason so this leaves the listener to
5569  * be tied to the same squeue. Our only problem is that when listener
5570  * is binding, the CPU that will get interrupted by the NIC whose
5571  * IP address the listener is binding to is not even known. So
5572  * the code below allows us to change that binding at the time the
5573  * CPU is interrupted by virtue of incoming connection's squeue.
5574  *
5575  * This is usefull only in case of a listener bound to a specific IP
5576  * address. For other kind of listeners, they get bound the
5577  * very first time and there is no attempt to rebind them.
5578  */
5579 void
5580 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5581 {
5582 	conn_t		*connp = (conn_t *)arg;
5583 	squeue_t	*sqp = (squeue_t *)arg2;
5584 	squeue_t	*new_sqp;
5585 	uint32_t	conn_flags;
5586 
5587 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5588 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5589 	} else {
5590 		goto done;
5591 	}
5592 
5593 	if (connp->conn_fanout == NULL)
5594 		goto done;
5595 
5596 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5597 		mutex_enter(&connp->conn_fanout->connf_lock);
5598 		mutex_enter(&connp->conn_lock);
5599 		/*
5600 		 * No one from read or write side can access us now
5601 		 * except for already queued packets on this squeue.
5602 		 * But since we haven't changed the squeue yet, they
5603 		 * can't execute. If they are processed after we have
5604 		 * changed the squeue, they are sent back to the
5605 		 * correct squeue down below.
5606 		 */
5607 		if (connp->conn_sqp != new_sqp) {
5608 			while (connp->conn_sqp != new_sqp)
5609 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5610 		}
5611 
5612 		do {
5613 			conn_flags = connp->conn_flags;
5614 			conn_flags |= IPCL_FULLY_BOUND;
5615 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5616 			    conn_flags);
5617 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5618 
5619 		mutex_exit(&connp->conn_fanout->connf_lock);
5620 		mutex_exit(&connp->conn_lock);
5621 	}
5622 
5623 done:
5624 	if (connp->conn_sqp != sqp) {
5625 		CONN_INC_REF(connp);
5626 		squeue_fill(connp->conn_sqp, mp,
5627 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
5628 	} else {
5629 		tcp_conn_request(connp, mp, sqp);
5630 	}
5631 }
5632 
5633 /*
5634  * Successful connect request processing begins when our client passes
5635  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5636  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5637  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
5638  *   upstream <- tcp_rput()                <- IP
5639  * After various error checks are completed, tcp_connect() lays
5640  * the target address and port into the composite header template,
5641  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5642  * request followed by an IRE request, and passes the three mblk message
5643  * down to IP looking like this:
5644  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5645  * Processing continues in tcp_rput() when we receive the following message:
5646  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5647  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5648  * to fire off the connection request, and then passes the T_OK_ACK mblk
5649  * upstream that we filled in below.  There are, of course, numerous
5650  * error conditions along the way which truncate the processing described
5651  * above.
5652  */
5653 static void
5654 tcp_connect(tcp_t *tcp, mblk_t *mp)
5655 {
5656 	sin_t		*sin;
5657 	sin6_t		*sin6;
5658 	queue_t		*q = tcp->tcp_wq;
5659 	struct T_conn_req	*tcr;
5660 	ipaddr_t	*dstaddrp;
5661 	in_port_t	dstport;
5662 	uint_t		srcid;
5663 
5664 	tcr = (struct T_conn_req *)mp->b_rptr;
5665 
5666 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5667 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5668 		tcp_err_ack(tcp, mp, TPROTO, 0);
5669 		return;
5670 	}
5671 
5672 	/*
5673 	 * Determine packet type based on type of address passed in
5674 	 * the request should contain an IPv4 or IPv6 address.
5675 	 * Make sure that address family matches the type of
5676 	 * family of the the address passed down
5677 	 */
5678 	switch (tcr->DEST_length) {
5679 	default:
5680 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5681 		return;
5682 
5683 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5684 		/*
5685 		 * XXX: The check for valid DEST_length was not there
5686 		 * in earlier releases and some buggy
5687 		 * TLI apps (e.g Sybase) got away with not feeding
5688 		 * in sin_zero part of address.
5689 		 * We allow that bug to keep those buggy apps humming.
5690 		 * Test suites require the check on DEST_length.
5691 		 * We construct a new mblk with valid DEST_length
5692 		 * free the original so the rest of the code does
5693 		 * not have to keep track of this special shorter
5694 		 * length address case.
5695 		 */
5696 		mblk_t *nmp;
5697 		struct T_conn_req *ntcr;
5698 		sin_t *nsin;
5699 
5700 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5701 		    tcr->OPT_length, BPRI_HI);
5702 		if (nmp == NULL) {
5703 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5704 			return;
5705 		}
5706 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5707 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5708 		ntcr->PRIM_type = T_CONN_REQ;
5709 		ntcr->DEST_length = sizeof (sin_t);
5710 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5711 
5712 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5713 		*nsin = sin_null;
5714 		/* Get pointer to shorter address to copy from original mp */
5715 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5716 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5717 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5718 			freemsg(nmp);
5719 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5720 			return;
5721 		}
5722 		nsin->sin_family = sin->sin_family;
5723 		nsin->sin_port = sin->sin_port;
5724 		nsin->sin_addr = sin->sin_addr;
5725 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5726 		nmp->b_wptr = (uchar_t *)&nsin[1];
5727 		if (tcr->OPT_length != 0) {
5728 			ntcr->OPT_length = tcr->OPT_length;
5729 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5730 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5731 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5732 			    tcr->OPT_length);
5733 			nmp->b_wptr += tcr->OPT_length;
5734 		}
5735 		freemsg(mp);	/* original mp freed */
5736 		mp = nmp;	/* re-initialize original variables */
5737 		tcr = ntcr;
5738 	}
5739 	/* FALLTHRU */
5740 
5741 	case sizeof (sin_t):
5742 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5743 		    sizeof (sin_t));
5744 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5745 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5746 			return;
5747 		}
5748 		if (tcp->tcp_family != AF_INET ||
5749 		    sin->sin_family != AF_INET) {
5750 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5751 			return;
5752 		}
5753 		if (sin->sin_port == 0) {
5754 			tcp_err_ack(tcp, mp, TBADADDR, 0);
5755 			return;
5756 		}
5757 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
5758 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5759 			return;
5760 		}
5761 
5762 		break;
5763 
5764 	case sizeof (sin6_t):
5765 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
5766 		    sizeof (sin6_t));
5767 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
5768 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5769 			return;
5770 		}
5771 		if (tcp->tcp_family != AF_INET6 ||
5772 		    sin6->sin6_family != AF_INET6) {
5773 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5774 			return;
5775 		}
5776 		if (sin6->sin6_port == 0) {
5777 			tcp_err_ack(tcp, mp, TBADADDR, 0);
5778 			return;
5779 		}
5780 		break;
5781 	}
5782 	/*
5783 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5784 	 * should key on their sequence number and cut them loose.
5785 	 */
5786 
5787 	/*
5788 	 * If options passed in, feed it for verification and handling
5789 	 */
5790 	if (tcr->OPT_length != 0) {
5791 		mblk_t	*ok_mp;
5792 		mblk_t	*discon_mp;
5793 		mblk_t  *conn_opts_mp;
5794 		int t_error, sys_error, do_disconnect;
5795 
5796 		conn_opts_mp = NULL;
5797 
5798 		if (tcp_conprim_opt_process(tcp, mp,
5799 			&do_disconnect, &t_error, &sys_error) < 0) {
5800 			if (do_disconnect) {
5801 				ASSERT(t_error == 0 && sys_error == 0);
5802 				discon_mp = mi_tpi_discon_ind(NULL,
5803 				    ECONNREFUSED, 0);
5804 				if (!discon_mp) {
5805 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5806 					    TSYSERR, ENOMEM);
5807 					return;
5808 				}
5809 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5810 				if (!ok_mp) {
5811 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5812 					    TSYSERR, ENOMEM);
5813 					return;
5814 				}
5815 				qreply(q, ok_mp);
5816 				qreply(q, discon_mp); /* no flush! */
5817 			} else {
5818 				ASSERT(t_error != 0);
5819 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5820 				    sys_error);
5821 			}
5822 			return;
5823 		}
5824 		/*
5825 		 * Success in setting options, the mp option buffer represented
5826 		 * by OPT_length/offset has been potentially modified and
5827 		 * contains results of option processing. We copy it in
5828 		 * another mp to save it for potentially influencing returning
5829 		 * it in T_CONN_CONN.
5830 		 */
5831 		if (tcr->OPT_length != 0) { /* there are resulting options */
5832 			conn_opts_mp = copyb(mp);
5833 			if (!conn_opts_mp) {
5834 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5835 				    TSYSERR, ENOMEM);
5836 				return;
5837 			}
5838 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5839 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5840 			/*
5841 			 * Note:
5842 			 * These resulting option negotiation can include any
5843 			 * end-to-end negotiation options but there no such
5844 			 * thing (yet?) in our TCP/IP.
5845 			 */
5846 		}
5847 	}
5848 
5849 	/*
5850 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
5851 	 * make sure that the template IP header in the tcp structure is an
5852 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
5853 	 * need to this before we call tcp_bindi() so that the port lookup
5854 	 * code will look for ports in the correct port space (IPv4 and
5855 	 * IPv6 have separate port spaces).
5856 	 */
5857 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
5858 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
5859 		int err = 0;
5860 
5861 		err = tcp_header_init_ipv4(tcp);
5862 		if (err != 0) {
5863 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
5864 			goto connect_failed;
5865 		}
5866 		if (tcp->tcp_lport != 0)
5867 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
5868 	}
5869 
5870 	switch (tcp->tcp_state) {
5871 	case TCPS_IDLE:
5872 		/*
5873 		 * We support quick connect, refer to comments in
5874 		 * tcp_connect_*()
5875 		 */
5876 		/* FALLTHRU */
5877 	case TCPS_BOUND:
5878 	case TCPS_LISTEN:
5879 		if (tcp->tcp_family == AF_INET6) {
5880 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
5881 				tcp_connect_ipv6(tcp, mp,
5882 				    &sin6->sin6_addr,
5883 				    sin6->sin6_port, sin6->sin6_flowinfo,
5884 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
5885 				return;
5886 			}
5887 			/*
5888 			 * Destination adress is mapped IPv6 address.
5889 			 * Source bound address should be unspecified or
5890 			 * IPv6 mapped address as well.
5891 			 */
5892 			if (!IN6_IS_ADDR_UNSPECIFIED(
5893 			    &tcp->tcp_bound_source_v6) &&
5894 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
5895 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
5896 				    EADDRNOTAVAIL);
5897 				break;
5898 			}
5899 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
5900 			dstport = sin6->sin6_port;
5901 			srcid = sin6->__sin6_src_id;
5902 		} else {
5903 			dstaddrp = &sin->sin_addr.s_addr;
5904 			dstport = sin->sin_port;
5905 			srcid = 0;
5906 		}
5907 
5908 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
5909 		return;
5910 	default:
5911 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
5912 		break;
5913 	}
5914 	/*
5915 	 * Note: Code below is the "failure" case
5916 	 */
5917 	/* return error ack and blow away saved option results if any */
5918 connect_failed:
5919 	if (mp != NULL)
5920 		putnext(tcp->tcp_rq, mp);
5921 	else {
5922 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5923 		    TSYSERR, ENOMEM);
5924 	}
5925 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
5926 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
5927 }
5928 
5929 /*
5930  * Handle connect to IPv4 destinations, including connections for AF_INET6
5931  * sockets connecting to IPv4 mapped IPv6 destinations.
5932  */
5933 static void
5934 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
5935     uint_t srcid)
5936 {
5937 	tcph_t	*tcph;
5938 	mblk_t	*mp1;
5939 	ipaddr_t dstaddr = *dstaddrp;
5940 	int32_t	oldstate;
5941 	uint16_t lport;
5942 
5943 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
5944 
5945 	/* Check for attempt to connect to INADDR_ANY */
5946 	if (dstaddr == INADDR_ANY)  {
5947 		/*
5948 		 * SunOS 4.x and 4.3 BSD allow an application
5949 		 * to connect a TCP socket to INADDR_ANY.
5950 		 * When they do this, the kernel picks the
5951 		 * address of one interface and uses it
5952 		 * instead.  The kernel usually ends up
5953 		 * picking the address of the loopback
5954 		 * interface.  This is an undocumented feature.
5955 		 * However, we provide the same thing here
5956 		 * in order to have source and binary
5957 		 * compatibility with SunOS 4.x.
5958 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
5959 		 * generate the T_CONN_CON.
5960 		 */
5961 		dstaddr = htonl(INADDR_LOOPBACK);
5962 		*dstaddrp = dstaddr;
5963 	}
5964 
5965 	/* Handle __sin6_src_id if socket not bound to an IP address */
5966 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
5967 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
5968 		    tcp->tcp_connp->conn_zoneid);
5969 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
5970 		    tcp->tcp_ipha->ipha_src);
5971 	}
5972 
5973 	/*
5974 	 * Don't let an endpoint connect to itself.  Note that
5975 	 * the test here does not catch the case where the
5976 	 * source IP addr was left unspecified by the user. In
5977 	 * this case, the source addr is set in tcp_adapt_ire()
5978 	 * using the reply to the T_BIND message that we send
5979 	 * down to IP here and the check is repeated in tcp_rput_other.
5980 	 */
5981 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
5982 	    dstport == tcp->tcp_lport) {
5983 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
5984 		goto failed;
5985 	}
5986 
5987 	tcp->tcp_ipha->ipha_dst = dstaddr;
5988 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
5989 
5990 	/*
5991 	 * Massage a source route if any putting the first hop
5992 	 * in iph_dst. Compute a starting value for the checksum which
5993 	 * takes into account that the original iph_dst should be
5994 	 * included in the checksum but that ip will include the
5995 	 * first hop in the source route in the tcp checksum.
5996 	 */
5997 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
5998 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
5999 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6000 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6001 	if ((int)tcp->tcp_sum < 0)
6002 		tcp->tcp_sum--;
6003 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6004 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6005 	    (tcp->tcp_sum >> 16));
6006 	tcph = tcp->tcp_tcph;
6007 	*(uint16_t *)tcph->th_fport = dstport;
6008 	tcp->tcp_fport = dstport;
6009 
6010 	oldstate = tcp->tcp_state;
6011 	/*
6012 	 * At this point the remote destination address and remote port fields
6013 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6014 	 * have to see which state tcp was in so we can take apropriate action.
6015 	 */
6016 	if (oldstate == TCPS_IDLE) {
6017 		/*
6018 		 * We support a quick connect capability here, allowing
6019 		 * clients to transition directly from IDLE to SYN_SENT
6020 		 * tcp_bindi will pick an unused port, insert the connection
6021 		 * in the bind hash and transition to BOUND state.
6022 		 */
6023 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
6024 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6025 		    B_FALSE, B_FALSE);
6026 		if (lport == 0) {
6027 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6028 			goto failed;
6029 		}
6030 	}
6031 	tcp->tcp_state = TCPS_SYN_SENT;
6032 
6033 	/*
6034 	 * TODO: allow data with connect requests
6035 	 * by unlinking M_DATA trailers here and
6036 	 * linking them in behind the T_OK_ACK mblk.
6037 	 * The tcp_rput() bind ack handler would then
6038 	 * feed them to tcp_wput_data() rather than call
6039 	 * tcp_timer().
6040 	 */
6041 	mp = mi_tpi_ok_ack_alloc(mp);
6042 	if (!mp) {
6043 		tcp->tcp_state = oldstate;
6044 		goto failed;
6045 	}
6046 	if (tcp->tcp_family == AF_INET) {
6047 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6048 		    sizeof (ipa_conn_t));
6049 	} else {
6050 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6051 		    sizeof (ipa6_conn_t));
6052 	}
6053 	if (mp1) {
6054 		/* Hang onto the T_OK_ACK for later. */
6055 		linkb(mp1, mp);
6056 		if (tcp->tcp_family == AF_INET)
6057 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6058 		else {
6059 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6060 			    &tcp->tcp_sticky_ipp);
6061 		}
6062 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6063 		tcp->tcp_active_open = 1;
6064 		/*
6065 		 * If the bind cannot complete immediately
6066 		 * IP will arrange to call tcp_rput_other
6067 		 * when the bind completes.
6068 		 */
6069 		if (mp1 != NULL)
6070 			tcp_rput_other(tcp, mp1);
6071 		return;
6072 	}
6073 	/* Error case */
6074 	tcp->tcp_state = oldstate;
6075 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6076 
6077 failed:
6078 	/* return error ack and blow away saved option results if any */
6079 	if (mp != NULL)
6080 		putnext(tcp->tcp_rq, mp);
6081 	else {
6082 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6083 		    TSYSERR, ENOMEM);
6084 	}
6085 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6086 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6087 
6088 }
6089 
6090 /*
6091  * Handle connect to IPv6 destinations.
6092  */
6093 static void
6094 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6095     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6096 {
6097 	tcph_t	*tcph;
6098 	mblk_t	*mp1;
6099 	ip6_rthdr_t *rth;
6100 	int32_t  oldstate;
6101 	uint16_t lport;
6102 
6103 	ASSERT(tcp->tcp_family == AF_INET6);
6104 
6105 	/*
6106 	 * If we're here, it means that the destination address is a native
6107 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6108 	 * reason why it might not be IPv6 is if the socket was bound to an
6109 	 * IPv4-mapped IPv6 address.
6110 	 */
6111 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6112 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6113 		goto failed;
6114 	}
6115 
6116 	/*
6117 	 * Interpret a zero destination to mean loopback.
6118 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6119 	 * generate the T_CONN_CON.
6120 	 */
6121 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6122 		*dstaddrp = ipv6_loopback;
6123 	}
6124 
6125 	/* Handle __sin6_src_id if socket not bound to an IP address */
6126 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6127 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6128 		    tcp->tcp_connp->conn_zoneid);
6129 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6130 	}
6131 
6132 	/*
6133 	 * Take care of the scope_id now and add ip6i_t
6134 	 * if ip6i_t is not already allocated through TCP
6135 	 * sticky options. At this point tcp_ip6h does not
6136 	 * have dst info, thus use dstaddrp.
6137 	 */
6138 	if (scope_id != 0 &&
6139 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6140 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6141 		ip6i_t  *ip6i;
6142 
6143 		ipp->ipp_ifindex = scope_id;
6144 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6145 
6146 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6147 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6148 			/* Already allocated */
6149 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6150 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6151 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6152 		} else {
6153 			int reterr;
6154 
6155 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6156 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6157 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6158 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6159 			if (reterr != 0)
6160 				goto failed;
6161 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6162 		}
6163 	}
6164 
6165 	/*
6166 	 * Don't let an endpoint connect to itself.  Note that
6167 	 * the test here does not catch the case where the
6168 	 * source IP addr was left unspecified by the user. In
6169 	 * this case, the source addr is set in tcp_adapt_ire()
6170 	 * using the reply to the T_BIND message that we send
6171 	 * down to IP here and the check is repeated in tcp_rput_other.
6172 	 */
6173 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6174 	    (dstport == tcp->tcp_lport)) {
6175 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6176 		goto failed;
6177 	}
6178 
6179 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6180 	tcp->tcp_remote_v6 = *dstaddrp;
6181 	tcp->tcp_ip6h->ip6_vcf =
6182 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6183 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6184 
6185 
6186 	/*
6187 	 * Massage a routing header (if present) putting the first hop
6188 	 * in ip6_dst. Compute a starting value for the checksum which
6189 	 * takes into account that the original ip6_dst should be
6190 	 * included in the checksum but that ip will include the
6191 	 * first hop in the source route in the tcp checksum.
6192 	 */
6193 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6194 	if (rth != NULL) {
6195 
6196 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
6197 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6198 		    (tcp->tcp_sum >> 16));
6199 	} else {
6200 		tcp->tcp_sum = 0;
6201 	}
6202 
6203 	tcph = tcp->tcp_tcph;
6204 	*(uint16_t *)tcph->th_fport = dstport;
6205 	tcp->tcp_fport = dstport;
6206 
6207 	oldstate = tcp->tcp_state;
6208 	/*
6209 	 * At this point the remote destination address and remote port fields
6210 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6211 	 * have to see which state tcp was in so we can take apropriate action.
6212 	 */
6213 	if (oldstate == TCPS_IDLE) {
6214 		/*
6215 		 * We support a quick connect capability here, allowing
6216 		 * clients to transition directly from IDLE to SYN_SENT
6217 		 * tcp_bindi will pick an unused port, insert the connection
6218 		 * in the bind hash and transition to BOUND state.
6219 		 */
6220 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
6221 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6222 		    B_FALSE, B_FALSE);
6223 		if (lport == 0) {
6224 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6225 			goto failed;
6226 		}
6227 	}
6228 	tcp->tcp_state = TCPS_SYN_SENT;
6229 	/*
6230 	 * TODO: allow data with connect requests
6231 	 * by unlinking M_DATA trailers here and
6232 	 * linking them in behind the T_OK_ACK mblk.
6233 	 * The tcp_rput() bind ack handler would then
6234 	 * feed them to tcp_wput_data() rather than call
6235 	 * tcp_timer().
6236 	 */
6237 	mp = mi_tpi_ok_ack_alloc(mp);
6238 	if (!mp) {
6239 		tcp->tcp_state = oldstate;
6240 		goto failed;
6241 	}
6242 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6243 	if (mp1) {
6244 		/* Hang onto the T_OK_ACK for later. */
6245 		linkb(mp1, mp);
6246 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6247 		    &tcp->tcp_sticky_ipp);
6248 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6249 		tcp->tcp_active_open = 1;
6250 		/* ip_bind_v6() may return ACK or ERROR */
6251 		if (mp1 != NULL)
6252 			tcp_rput_other(tcp, mp1);
6253 		return;
6254 	}
6255 	/* Error case */
6256 	tcp->tcp_state = oldstate;
6257 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6258 
6259 failed:
6260 	/* return error ack and blow away saved option results if any */
6261 	if (mp != NULL)
6262 		putnext(tcp->tcp_rq, mp);
6263 	else {
6264 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6265 		    TSYSERR, ENOMEM);
6266 	}
6267 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6268 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6269 }
6270 
6271 /*
6272  * We need a stream q for detached closing tcp connections
6273  * to use.  Our client hereby indicates that this q is the
6274  * one to use.
6275  */
6276 static void
6277 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6278 {
6279 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6280 	queue_t	*q = tcp->tcp_wq;
6281 
6282 	mp->b_datap->db_type = M_IOCACK;
6283 	iocp->ioc_count = 0;
6284 	mutex_enter(&tcp_g_q_lock);
6285 	if (tcp_g_q != NULL) {
6286 		mutex_exit(&tcp_g_q_lock);
6287 		iocp->ioc_error = EALREADY;
6288 	} else {
6289 		mblk_t *mp1;
6290 
6291 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6292 		if (mp1 == NULL) {
6293 			mutex_exit(&tcp_g_q_lock);
6294 			iocp->ioc_error = ENOMEM;
6295 		} else {
6296 			tcp_g_q = tcp->tcp_rq;
6297 			mutex_exit(&tcp_g_q_lock);
6298 			iocp->ioc_error = 0;
6299 			iocp->ioc_rval = 0;
6300 			/*
6301 			 * We are passing tcp_sticky_ipp as NULL
6302 			 * as it is not useful for tcp_default queue
6303 			 */
6304 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6305 			if (mp1 != NULL)
6306 				tcp_rput_other(tcp, mp1);
6307 		}
6308 	}
6309 	qreply(q, mp);
6310 }
6311 
6312 /*
6313  * Our client hereby directs us to reject the connection request
6314  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6315  * of sending the appropriate RST, not an ICMP error.
6316  */
6317 static void
6318 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6319 {
6320 	tcp_t	*ltcp = NULL;
6321 	t_scalar_t seqnum;
6322 	conn_t	*connp;
6323 
6324 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6325 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6326 		tcp_err_ack(tcp, mp, TPROTO, 0);
6327 		return;
6328 	}
6329 
6330 	/*
6331 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6332 	 * when the stream is in BOUND state. Do not send a reset,
6333 	 * since the destination IP address is not valid, and it can
6334 	 * be the initialized value of all zeros (broadcast address).
6335 	 *
6336 	 * If TCP has sent down a bind request to IP and has not
6337 	 * received the reply, reject the request.  Otherwise, TCP
6338 	 * will be confused.
6339 	 */
6340 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6341 		if (tcp->tcp_debug) {
6342 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6343 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6344 		}
6345 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6346 		return;
6347 	}
6348 
6349 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6350 
6351 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6352 
6353 		/*
6354 		 * According to TPI, for non-listeners, ignore seqnum
6355 		 * and disconnect.
6356 		 * Following interpretation of -1 seqnum is historical
6357 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6358 		 * a valid seqnum should not be -1).
6359 		 *
6360 		 *	-1 means disconnect everything
6361 		 *	regardless even on a listener.
6362 		 */
6363 
6364 		int old_state = tcp->tcp_state;
6365 
6366 		/*
6367 		 * The connection can't be on the tcp_time_wait_head list
6368 		 * since it is not detached.
6369 		 */
6370 		ASSERT(tcp->tcp_time_wait_next == NULL);
6371 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6372 		ASSERT(tcp->tcp_time_wait_expire == 0);
6373 		ltcp = NULL;
6374 		/*
6375 		 * If it used to be a listener, check to make sure no one else
6376 		 * has taken the port before switching back to LISTEN state.
6377 		 */
6378 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6379 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6380 			    tcp->tcp_ipha->ipha_src,
6381 			    tcp->tcp_connp->conn_zoneid);
6382 			if (connp != NULL)
6383 				ltcp = connp->conn_tcp;
6384 		} else {
6385 			/* Allow tcp_bound_if listeners? */
6386 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6387 			    &tcp->tcp_ip6h->ip6_src, 0,
6388 			    tcp->tcp_connp->conn_zoneid);
6389 			if (connp != NULL)
6390 				ltcp = connp->conn_tcp;
6391 		}
6392 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6393 			tcp->tcp_state = TCPS_LISTEN;
6394 		} else if (old_state > TCPS_BOUND) {
6395 			tcp->tcp_conn_req_max = 0;
6396 			tcp->tcp_state = TCPS_BOUND;
6397 		}
6398 		if (ltcp != NULL)
6399 			CONN_DEC_REF(ltcp->tcp_connp);
6400 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6401 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
6402 		} else if (old_state == TCPS_ESTABLISHED ||
6403 		    old_state == TCPS_CLOSE_WAIT) {
6404 			BUMP_MIB(&tcp_mib, tcpEstabResets);
6405 		}
6406 
6407 		if (tcp->tcp_fused)
6408 			tcp_unfuse(tcp);
6409 
6410 		mutex_enter(&tcp->tcp_eager_lock);
6411 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6412 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6413 			tcp_eager_cleanup(tcp, 0);
6414 		}
6415 		mutex_exit(&tcp->tcp_eager_lock);
6416 
6417 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6418 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6419 
6420 		tcp_reinit(tcp);
6421 
6422 		if (old_state >= TCPS_ESTABLISHED) {
6423 			/* Send M_FLUSH according to TPI */
6424 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6425 		}
6426 		mp = mi_tpi_ok_ack_alloc(mp);
6427 		if (mp)
6428 			putnext(tcp->tcp_rq, mp);
6429 		return;
6430 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6431 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6432 		return;
6433 	}
6434 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6435 		/* Send M_FLUSH according to TPI */
6436 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6437 	}
6438 	mp = mi_tpi_ok_ack_alloc(mp);
6439 	if (mp)
6440 		putnext(tcp->tcp_rq, mp);
6441 }
6442 
6443 /*
6444  * Diagnostic routine used to return a string associated with the tcp state.
6445  * Note that if the caller does not supply a buffer, it will use an internal
6446  * static string.  This means that if multiple threads call this function at
6447  * the same time, output can be corrupted...  Note also that this function
6448  * does not check the size of the supplied buffer.  The caller has to make
6449  * sure that it is big enough.
6450  */
6451 static char *
6452 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6453 {
6454 	char		buf1[30];
6455 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6456 	char		*buf;
6457 	char		*cp;
6458 	in6_addr_t	local, remote;
6459 	char		local_addrbuf[INET6_ADDRSTRLEN];
6460 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6461 
6462 	if (sup_buf != NULL)
6463 		buf = sup_buf;
6464 	else
6465 		buf = priv_buf;
6466 
6467 	if (tcp == NULL)
6468 		return ("NULL_TCP");
6469 	switch (tcp->tcp_state) {
6470 	case TCPS_CLOSED:
6471 		cp = "TCP_CLOSED";
6472 		break;
6473 	case TCPS_IDLE:
6474 		cp = "TCP_IDLE";
6475 		break;
6476 	case TCPS_BOUND:
6477 		cp = "TCP_BOUND";
6478 		break;
6479 	case TCPS_LISTEN:
6480 		cp = "TCP_LISTEN";
6481 		break;
6482 	case TCPS_SYN_SENT:
6483 		cp = "TCP_SYN_SENT";
6484 		break;
6485 	case TCPS_SYN_RCVD:
6486 		cp = "TCP_SYN_RCVD";
6487 		break;
6488 	case TCPS_ESTABLISHED:
6489 		cp = "TCP_ESTABLISHED";
6490 		break;
6491 	case TCPS_CLOSE_WAIT:
6492 		cp = "TCP_CLOSE_WAIT";
6493 		break;
6494 	case TCPS_FIN_WAIT_1:
6495 		cp = "TCP_FIN_WAIT_1";
6496 		break;
6497 	case TCPS_CLOSING:
6498 		cp = "TCP_CLOSING";
6499 		break;
6500 	case TCPS_LAST_ACK:
6501 		cp = "TCP_LAST_ACK";
6502 		break;
6503 	case TCPS_FIN_WAIT_2:
6504 		cp = "TCP_FIN_WAIT_2";
6505 		break;
6506 	case TCPS_TIME_WAIT:
6507 		cp = "TCP_TIME_WAIT";
6508 		break;
6509 	default:
6510 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6511 		cp = buf1;
6512 		break;
6513 	}
6514 	switch (format) {
6515 	case DISP_ADDR_AND_PORT:
6516 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6517 			/*
6518 			 * Note that we use the remote address in the tcp_b
6519 			 * structure.  This means that it will print out
6520 			 * the real destination address, not the next hop's
6521 			 * address if source routing is used.
6522 			 */
6523 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6524 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6525 
6526 		} else {
6527 			local = tcp->tcp_ip_src_v6;
6528 			remote = tcp->tcp_remote_v6;
6529 		}
6530 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6531 		    sizeof (local_addrbuf));
6532 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6533 		    sizeof (remote_addrbuf));
6534 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6535 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6536 		    ntohs(tcp->tcp_fport), cp);
6537 		break;
6538 	case DISP_PORT_ONLY:
6539 	default:
6540 		(void) mi_sprintf(buf, "[%u, %u] %s",
6541 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6542 		break;
6543 	}
6544 
6545 	return (buf);
6546 }
6547 
6548 /*
6549  * Called via squeue to get on to eager's perimeter to send a
6550  * TH_RST. The listener wants the eager to disappear either
6551  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
6552  * being called.
6553  */
6554 /* ARGSUSED */
6555 void
6556 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6557 {
6558 	conn_t	*econnp = (conn_t *)arg;
6559 	tcp_t	*eager = econnp->conn_tcp;
6560 	tcp_t	*listener = eager->tcp_listener;
6561 
6562 	/*
6563 	 * We could be called because listener is closing. Since
6564 	 * the eager is using listener's queue's, its not safe.
6565 	 * Better use the default queue just to send the TH_RST
6566 	 * out.
6567 	 */
6568 	eager->tcp_rq = tcp_g_q;
6569 	eager->tcp_wq = WR(tcp_g_q);
6570 
6571 	if (eager->tcp_state > TCPS_LISTEN) {
6572 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6573 		    eager, eager->tcp_snxt, 0, TH_RST);
6574 	}
6575 
6576 	/* We are here because listener wants this eager gone */
6577 	if (listener != NULL) {
6578 		mutex_enter(&listener->tcp_eager_lock);
6579 		tcp_eager_unlink(eager);
6580 		if (eager->tcp_conn.tcp_eager_conn_ind == NULL) {
6581 			/*
6582 			 * The eager has sent a conn_ind up to the
6583 			 * listener but listener decides to close
6584 			 * instead. We need to drop the extra ref
6585 			 * placed on eager in tcp_rput_data() before
6586 			 * sending the conn_ind to listener.
6587 			 */
6588 			CONN_DEC_REF(econnp);
6589 		}
6590 		mutex_exit(&listener->tcp_eager_lock);
6591 		CONN_DEC_REF(listener->tcp_connp);
6592 	}
6593 
6594 	if (eager->tcp_state > TCPS_BOUND)
6595 		tcp_close_detached(eager);
6596 }
6597 
6598 /*
6599  * Reset any eager connection hanging off this listener marked
6600  * with 'seqnum' and then reclaim it's resources.
6601  */
6602 static boolean_t
6603 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6604 {
6605 	tcp_t	*eager;
6606 	mblk_t 	*mp;
6607 
6608 	TCP_STAT(tcp_eager_blowoff_calls);
6609 	eager = listener;
6610 	mutex_enter(&listener->tcp_eager_lock);
6611 	do {
6612 		eager = eager->tcp_eager_next_q;
6613 		if (eager == NULL) {
6614 			mutex_exit(&listener->tcp_eager_lock);
6615 			return (B_FALSE);
6616 		}
6617 	} while (eager->tcp_conn_req_seqnum != seqnum);
6618 	CONN_INC_REF(eager->tcp_connp);
6619 	mutex_exit(&listener->tcp_eager_lock);
6620 	mp = &eager->tcp_closemp;
6621 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6622 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
6623 	return (B_TRUE);
6624 }
6625 
6626 /*
6627  * Reset any eager connection hanging off this listener
6628  * and then reclaim it's resources.
6629  */
6630 static void
6631 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6632 {
6633 	tcp_t	*eager;
6634 	mblk_t	*mp;
6635 
6636 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6637 
6638 	if (!q0_only) {
6639 		/* First cleanup q */
6640 		TCP_STAT(tcp_eager_blowoff_q);
6641 		eager = listener->tcp_eager_next_q;
6642 		while (eager != NULL) {
6643 			CONN_INC_REF(eager->tcp_connp);
6644 			mp = &eager->tcp_closemp;
6645 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
6646 			    tcp_eager_kill, eager->tcp_connp,
6647 			    SQTAG_TCP_EAGER_CLEANUP);
6648 			eager = eager->tcp_eager_next_q;
6649 		}
6650 	}
6651 	/* Then cleanup q0 */
6652 	TCP_STAT(tcp_eager_blowoff_q0);
6653 	eager = listener->tcp_eager_next_q0;
6654 	while (eager != listener) {
6655 		CONN_INC_REF(eager->tcp_connp);
6656 		mp = &eager->tcp_closemp;
6657 		squeue_fill(eager->tcp_connp->conn_sqp, mp,
6658 		    tcp_eager_kill, eager->tcp_connp,
6659 		    SQTAG_TCP_EAGER_CLEANUP_Q0);
6660 		eager = eager->tcp_eager_next_q0;
6661 	}
6662 }
6663 
6664 /*
6665  * If we are an eager connection hanging off a listener that hasn't
6666  * formally accepted the connection yet, get off his list and blow off
6667  * any data that we have accumulated.
6668  */
6669 static void
6670 tcp_eager_unlink(tcp_t *tcp)
6671 {
6672 	tcp_t	*listener = tcp->tcp_listener;
6673 
6674 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6675 	ASSERT(listener != NULL);
6676 	if (tcp->tcp_eager_next_q0 != NULL) {
6677 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6678 
6679 		/* Remove the eager tcp from q0 */
6680 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6681 		    tcp->tcp_eager_prev_q0;
6682 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6683 		    tcp->tcp_eager_next_q0;
6684 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6685 		listener->tcp_conn_req_cnt_q0--;
6686 
6687 		tcp->tcp_eager_next_q0 = NULL;
6688 		tcp->tcp_eager_prev_q0 = NULL;
6689 
6690 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6691 			/* we have timed out before */
6692 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6693 			listener->tcp_syn_rcvd_timeout--;
6694 		}
6695 	} else {
6696 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6697 		tcp_t	*prev = NULL;
6698 
6699 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6700 			if (tcpp[0] == tcp) {
6701 				if (listener->tcp_eager_last_q == tcp) {
6702 					/*
6703 					 * If we are unlinking the last
6704 					 * element on the list, adjust
6705 					 * tail pointer. Set tail pointer
6706 					 * to nil when list is empty.
6707 					 */
6708 					ASSERT(tcp->tcp_eager_next_q == NULL);
6709 					if (listener->tcp_eager_last_q ==
6710 					    listener->tcp_eager_next_q) {
6711 						listener->tcp_eager_last_q =
6712 						NULL;
6713 					} else {
6714 						/*
6715 						 * We won't get here if there
6716 						 * is only one eager in the
6717 						 * list.
6718 						 */
6719 						ASSERT(prev != NULL);
6720 						listener->tcp_eager_last_q =
6721 						    prev;
6722 					}
6723 				}
6724 				tcpp[0] = tcp->tcp_eager_next_q;
6725 				tcp->tcp_eager_next_q = NULL;
6726 				tcp->tcp_eager_last_q = NULL;
6727 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6728 				listener->tcp_conn_req_cnt_q--;
6729 				break;
6730 			}
6731 			prev = tcpp[0];
6732 		}
6733 	}
6734 	tcp->tcp_listener = NULL;
6735 }
6736 
6737 /* Shorthand to generate and send TPI error acks to our client */
6738 static void
6739 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6740 {
6741 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6742 		putnext(tcp->tcp_rq, mp);
6743 }
6744 
6745 /* Shorthand to generate and send TPI error acks to our client */
6746 static void
6747 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6748     int t_error, int sys_error)
6749 {
6750 	struct T_error_ack	*teackp;
6751 
6752 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6753 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6754 		teackp = (struct T_error_ack *)mp->b_rptr;
6755 		teackp->ERROR_prim = primitive;
6756 		teackp->TLI_error = t_error;
6757 		teackp->UNIX_error = sys_error;
6758 		putnext(tcp->tcp_rq, mp);
6759 	}
6760 }
6761 
6762 /*
6763  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6764  * but instead the code relies on:
6765  * - the fact that the address of the array and its size never changes
6766  * - the atomic assignment of the elements of the array
6767  */
6768 /* ARGSUSED */
6769 static int
6770 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6771 {
6772 	int i;
6773 
6774 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6775 		if (tcp_g_epriv_ports[i] != 0)
6776 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
6777 	}
6778 	return (0);
6779 }
6780 
6781 /*
6782  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6783  * threads from changing it at the same time.
6784  */
6785 /* ARGSUSED */
6786 static int
6787 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6788     cred_t *cr)
6789 {
6790 	long	new_value;
6791 	int	i;
6792 
6793 	/*
6794 	 * Fail the request if the new value does not lie within the
6795 	 * port number limits.
6796 	 */
6797 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6798 	    new_value <= 0 || new_value >= 65536) {
6799 		return (EINVAL);
6800 	}
6801 
6802 	mutex_enter(&tcp_epriv_port_lock);
6803 	/* Check if the value is already in the list */
6804 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6805 		if (new_value == tcp_g_epriv_ports[i]) {
6806 			mutex_exit(&tcp_epriv_port_lock);
6807 			return (EEXIST);
6808 		}
6809 	}
6810 	/* Find an empty slot */
6811 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6812 		if (tcp_g_epriv_ports[i] == 0)
6813 			break;
6814 	}
6815 	if (i == tcp_g_num_epriv_ports) {
6816 		mutex_exit(&tcp_epriv_port_lock);
6817 		return (EOVERFLOW);
6818 	}
6819 	/* Set the new value */
6820 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
6821 	mutex_exit(&tcp_epriv_port_lock);
6822 	return (0);
6823 }
6824 
6825 /*
6826  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6827  * threads from changing it at the same time.
6828  */
6829 /* ARGSUSED */
6830 static int
6831 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6832     cred_t *cr)
6833 {
6834 	long	new_value;
6835 	int	i;
6836 
6837 	/*
6838 	 * Fail the request if the new value does not lie within the
6839 	 * port number limits.
6840 	 */
6841 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
6842 	    new_value >= 65536) {
6843 		return (EINVAL);
6844 	}
6845 
6846 	mutex_enter(&tcp_epriv_port_lock);
6847 	/* Check that the value is already in the list */
6848 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6849 		if (tcp_g_epriv_ports[i] == new_value)
6850 			break;
6851 	}
6852 	if (i == tcp_g_num_epriv_ports) {
6853 		mutex_exit(&tcp_epriv_port_lock);
6854 		return (ESRCH);
6855 	}
6856 	/* Clear the value */
6857 	tcp_g_epriv_ports[i] = 0;
6858 	mutex_exit(&tcp_epriv_port_lock);
6859 	return (0);
6860 }
6861 
6862 /* Return the TPI/TLI equivalent of our current tcp_state */
6863 static int
6864 tcp_tpistate(tcp_t *tcp)
6865 {
6866 	switch (tcp->tcp_state) {
6867 	case TCPS_IDLE:
6868 		return (TS_UNBND);
6869 	case TCPS_LISTEN:
6870 		/*
6871 		 * Return whether there are outstanding T_CONN_IND waiting
6872 		 * for the matching T_CONN_RES. Therefore don't count q0.
6873 		 */
6874 		if (tcp->tcp_conn_req_cnt_q > 0)
6875 			return (TS_WRES_CIND);
6876 		else
6877 			return (TS_IDLE);
6878 	case TCPS_BOUND:
6879 		return (TS_IDLE);
6880 	case TCPS_SYN_SENT:
6881 		return (TS_WCON_CREQ);
6882 	case TCPS_SYN_RCVD:
6883 		/*
6884 		 * Note: assumption: this has to the active open SYN_RCVD.
6885 		 * The passive instance is detached in SYN_RCVD stage of
6886 		 * incoming connection processing so we cannot get request
6887 		 * for T_info_ack on it.
6888 		 */
6889 		return (TS_WACK_CRES);
6890 	case TCPS_ESTABLISHED:
6891 		return (TS_DATA_XFER);
6892 	case TCPS_CLOSE_WAIT:
6893 		return (TS_WREQ_ORDREL);
6894 	case TCPS_FIN_WAIT_1:
6895 		return (TS_WIND_ORDREL);
6896 	case TCPS_FIN_WAIT_2:
6897 		return (TS_WIND_ORDREL);
6898 
6899 	case TCPS_CLOSING:
6900 	case TCPS_LAST_ACK:
6901 	case TCPS_TIME_WAIT:
6902 	case TCPS_CLOSED:
6903 		/*
6904 		 * Following TS_WACK_DREQ7 is a rendition of "not
6905 		 * yet TS_IDLE" TPI state. There is no best match to any
6906 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6907 		 * choose a value chosen that will map to TLI/XTI level
6908 		 * state of TSTATECHNG (state is process of changing) which
6909 		 * captures what this dummy state represents.
6910 		 */
6911 		return (TS_WACK_DREQ7);
6912 	default:
6913 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6914 		    tcp->tcp_state, tcp_display(tcp, NULL,
6915 		    DISP_PORT_ONLY));
6916 		return (TS_UNBND);
6917 	}
6918 }
6919 
6920 static void
6921 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
6922 {
6923 	if (tcp->tcp_family == AF_INET6)
6924 		*tia = tcp_g_t_info_ack_v6;
6925 	else
6926 		*tia = tcp_g_t_info_ack;
6927 	tia->CURRENT_state = tcp_tpistate(tcp);
6928 	tia->OPT_size = tcp_max_optsize;
6929 	if (tcp->tcp_mss == 0) {
6930 		/* Not yet set - tcp_open does not set mss */
6931 		if (tcp->tcp_ipversion == IPV4_VERSION)
6932 			tia->TIDU_size = tcp_mss_def_ipv4;
6933 		else
6934 			tia->TIDU_size = tcp_mss_def_ipv6;
6935 	} else {
6936 		tia->TIDU_size = tcp->tcp_mss;
6937 	}
6938 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
6939 }
6940 
6941 /*
6942  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
6943  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
6944  * tcp_g_t_info_ack.  The current state of the stream is copied from
6945  * tcp_state.
6946  */
6947 static void
6948 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
6949 {
6950 	t_uscalar_t		cap_bits1;
6951 	struct T_capability_ack	*tcap;
6952 
6953 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
6954 		freemsg(mp);
6955 		return;
6956 	}
6957 
6958 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
6959 
6960 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
6961 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
6962 	if (mp == NULL)
6963 		return;
6964 
6965 	tcap = (struct T_capability_ack *)mp->b_rptr;
6966 	tcap->CAP_bits1 = 0;
6967 
6968 	if (cap_bits1 & TC1_INFO) {
6969 		tcp_copy_info(&tcap->INFO_ack, tcp);
6970 		tcap->CAP_bits1 |= TC1_INFO;
6971 	}
6972 
6973 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
6974 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
6975 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
6976 	}
6977 
6978 	putnext(tcp->tcp_rq, mp);
6979 }
6980 
6981 /*
6982  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
6983  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
6984  * The current state of the stream is copied from tcp_state.
6985  */
6986 static void
6987 tcp_info_req(tcp_t *tcp, mblk_t *mp)
6988 {
6989 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
6990 	    T_INFO_ACK);
6991 	if (!mp) {
6992 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6993 		return;
6994 	}
6995 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
6996 	putnext(tcp->tcp_rq, mp);
6997 }
6998 
6999 /* Respond to the TPI addr request */
7000 static void
7001 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7002 {
7003 	sin_t	*sin;
7004 	mblk_t	*ackmp;
7005 	struct T_addr_ack *taa;
7006 
7007 	/* Make it large enough for worst case */
7008 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7009 	    2 * sizeof (sin6_t), 1);
7010 	if (ackmp == NULL) {
7011 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7012 		return;
7013 	}
7014 
7015 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7016 		tcp_addr_req_ipv6(tcp, ackmp);
7017 		return;
7018 	}
7019 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7020 
7021 	bzero(taa, sizeof (struct T_addr_ack));
7022 	ackmp->b_wptr = (uchar_t *)&taa[1];
7023 
7024 	taa->PRIM_type = T_ADDR_ACK;
7025 	ackmp->b_datap->db_type = M_PCPROTO;
7026 
7027 	/*
7028 	 * Note: Following code assumes 32 bit alignment of basic
7029 	 * data structures like sin_t and struct T_addr_ack.
7030 	 */
7031 	if (tcp->tcp_state >= TCPS_BOUND) {
7032 		/*
7033 		 * Fill in local address
7034 		 */
7035 		taa->LOCADDR_length = sizeof (sin_t);
7036 		taa->LOCADDR_offset = sizeof (*taa);
7037 
7038 		sin = (sin_t *)&taa[1];
7039 
7040 		/* Fill zeroes and then intialize non-zero fields */
7041 		*sin = sin_null;
7042 
7043 		sin->sin_family = AF_INET;
7044 
7045 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7046 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7047 
7048 		ackmp->b_wptr = (uchar_t *)&sin[1];
7049 
7050 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7051 			/*
7052 			 * Fill in Remote address
7053 			 */
7054 			taa->REMADDR_length = sizeof (sin_t);
7055 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7056 						taa->LOCADDR_length);
7057 
7058 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7059 			*sin = sin_null;
7060 			sin->sin_family = AF_INET;
7061 			sin->sin_addr.s_addr = tcp->tcp_remote;
7062 			sin->sin_port = tcp->tcp_fport;
7063 
7064 			ackmp->b_wptr = (uchar_t *)&sin[1];
7065 		}
7066 	}
7067 	putnext(tcp->tcp_rq, ackmp);
7068 }
7069 
7070 /* Assumes that tcp_addr_req gets enough space and alignment */
7071 static void
7072 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7073 {
7074 	sin6_t	*sin6;
7075 	struct T_addr_ack *taa;
7076 
7077 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7078 	ASSERT(OK_32PTR(ackmp->b_rptr));
7079 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7080 	    2 * sizeof (sin6_t));
7081 
7082 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7083 
7084 	bzero(taa, sizeof (struct T_addr_ack));
7085 	ackmp->b_wptr = (uchar_t *)&taa[1];
7086 
7087 	taa->PRIM_type = T_ADDR_ACK;
7088 	ackmp->b_datap->db_type = M_PCPROTO;
7089 
7090 	/*
7091 	 * Note: Following code assumes 32 bit alignment of basic
7092 	 * data structures like sin6_t and struct T_addr_ack.
7093 	 */
7094 	if (tcp->tcp_state >= TCPS_BOUND) {
7095 		/*
7096 		 * Fill in local address
7097 		 */
7098 		taa->LOCADDR_length = sizeof (sin6_t);
7099 		taa->LOCADDR_offset = sizeof (*taa);
7100 
7101 		sin6 = (sin6_t *)&taa[1];
7102 		*sin6 = sin6_null;
7103 
7104 		sin6->sin6_family = AF_INET6;
7105 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7106 		sin6->sin6_port = tcp->tcp_lport;
7107 
7108 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7109 
7110 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7111 			/*
7112 			 * Fill in Remote address
7113 			 */
7114 			taa->REMADDR_length = sizeof (sin6_t);
7115 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7116 						taa->LOCADDR_length);
7117 
7118 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7119 			*sin6 = sin6_null;
7120 			sin6->sin6_family = AF_INET6;
7121 			sin6->sin6_flowinfo =
7122 			    tcp->tcp_ip6h->ip6_vcf &
7123 			    ~IPV6_VERS_AND_FLOW_MASK;
7124 			sin6->sin6_addr = tcp->tcp_remote_v6;
7125 			sin6->sin6_port = tcp->tcp_fport;
7126 
7127 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7128 		}
7129 	}
7130 	putnext(tcp->tcp_rq, ackmp);
7131 }
7132 
7133 /*
7134  * Handle reinitialization of a tcp structure.
7135  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7136  */
7137 static void
7138 tcp_reinit(tcp_t *tcp)
7139 {
7140 	mblk_t	*mp;
7141 	int 	err;
7142 
7143 	TCP_STAT(tcp_reinit_calls);
7144 
7145 	/* tcp_reinit should never be called for detached tcp_t's */
7146 	ASSERT(tcp->tcp_listener == NULL);
7147 	ASSERT((tcp->tcp_family == AF_INET &&
7148 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7149 	    (tcp->tcp_family == AF_INET6 &&
7150 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7151 	    tcp->tcp_ipversion == IPV6_VERSION)));
7152 
7153 	/* Cancel outstanding timers */
7154 	tcp_timers_stop(tcp);
7155 
7156 	/*
7157 	 * Reset everything in the state vector, after updating global
7158 	 * MIB data from instance counters.
7159 	 */
7160 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
7161 	tcp->tcp_ibsegs = 0;
7162 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
7163 	tcp->tcp_obsegs = 0;
7164 
7165 	tcp_close_mpp(&tcp->tcp_xmit_head);
7166 	if (tcp->tcp_snd_zcopy_aware)
7167 		tcp_zcopy_notify(tcp);
7168 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7169 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7170 	if (tcp->tcp_flow_stopped &&
7171 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7172 		tcp_clrqfull(tcp);
7173 	}
7174 	tcp_close_mpp(&tcp->tcp_reass_head);
7175 	tcp->tcp_reass_tail = NULL;
7176 	if (tcp->tcp_rcv_list != NULL) {
7177 		/* Free b_next chain */
7178 		tcp_close_mpp(&tcp->tcp_rcv_list);
7179 		tcp->tcp_rcv_last_head = NULL;
7180 		tcp->tcp_rcv_last_tail = NULL;
7181 		tcp->tcp_rcv_cnt = 0;
7182 	}
7183 	tcp->tcp_rcv_last_tail = NULL;
7184 
7185 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7186 		freemsg(mp);
7187 		tcp->tcp_urp_mp = NULL;
7188 	}
7189 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7190 		freemsg(mp);
7191 		tcp->tcp_urp_mark_mp = NULL;
7192 	}
7193 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7194 		freeb(tcp->tcp_fused_sigurg_mp);
7195 		tcp->tcp_fused_sigurg_mp = NULL;
7196 	}
7197 
7198 	/*
7199 	 * Following is a union with two members which are
7200 	 * identical types and size so the following cleanup
7201 	 * is enough.
7202 	 */
7203 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7204 
7205 	CL_INET_DISCONNECT(tcp);
7206 
7207 	/*
7208 	 * The connection can't be on the tcp_time_wait_head list
7209 	 * since it is not detached.
7210 	 */
7211 	ASSERT(tcp->tcp_time_wait_next == NULL);
7212 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7213 	ASSERT(tcp->tcp_time_wait_expire == 0);
7214 
7215 	if (tcp->tcp_kssl_pending) {
7216 		tcp->tcp_kssl_pending = B_FALSE;
7217 
7218 		/* Don't reset if the initialized by bind. */
7219 		if (tcp->tcp_kssl_ent != NULL) {
7220 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7221 			    KSSL_NO_PROXY);
7222 		}
7223 	}
7224 	if (tcp->tcp_kssl_ctx != NULL) {
7225 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7226 		tcp->tcp_kssl_ctx = NULL;
7227 	}
7228 
7229 	/*
7230 	 * Reset/preserve other values
7231 	 */
7232 	tcp_reinit_values(tcp);
7233 	ipcl_hash_remove(tcp->tcp_connp);
7234 	conn_delete_ire(tcp->tcp_connp, NULL);
7235 
7236 	if (tcp->tcp_conn_req_max != 0) {
7237 		/*
7238 		 * This is the case when a TLI program uses the same
7239 		 * transport end point to accept a connection.  This
7240 		 * makes the TCP both a listener and acceptor.  When
7241 		 * this connection is closed, we need to set the state
7242 		 * back to TCPS_LISTEN.  Make sure that the eager list
7243 		 * is reinitialized.
7244 		 *
7245 		 * Note that this stream is still bound to the four
7246 		 * tuples of the previous connection in IP.  If a new
7247 		 * SYN with different foreign address comes in, IP will
7248 		 * not find it and will send it to the global queue.  In
7249 		 * the global queue, TCP will do a tcp_lookup_listener()
7250 		 * to find this stream.  This works because this stream
7251 		 * is only removed from connected hash.
7252 		 *
7253 		 */
7254 		tcp->tcp_state = TCPS_LISTEN;
7255 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7256 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7257 		if (tcp->tcp_family == AF_INET6) {
7258 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7259 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7260 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7261 		} else {
7262 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7263 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7264 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7265 		}
7266 	} else {
7267 		tcp->tcp_state = TCPS_BOUND;
7268 	}
7269 
7270 	/*
7271 	 * Initialize to default values
7272 	 * Can't fail since enough header template space already allocated
7273 	 * at open().
7274 	 */
7275 	err = tcp_init_values(tcp);
7276 	ASSERT(err == 0);
7277 	/* Restore state in tcp_tcph */
7278 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7279 	if (tcp->tcp_ipversion == IPV4_VERSION)
7280 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7281 	else
7282 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7283 	/*
7284 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7285 	 * since the lookup funcs can only lookup on tcp_t
7286 	 */
7287 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7288 
7289 	ASSERT(tcp->tcp_ptpbhn != NULL);
7290 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
7291 	tcp->tcp_rwnd = tcp_recv_hiwat;
7292 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7293 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
7294 }
7295 
7296 /*
7297  * Force values to zero that need be zero.
7298  * Do not touch values asociated with the BOUND or LISTEN state
7299  * since the connection will end up in that state after the reinit.
7300  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7301  * structure!
7302  */
7303 static void
7304 tcp_reinit_values(tcp)
7305 	tcp_t *tcp;
7306 {
7307 #ifndef	lint
7308 #define	DONTCARE(x)
7309 #define	PRESERVE(x)
7310 #else
7311 #define	DONTCARE(x)	((x) = (x))
7312 #define	PRESERVE(x)	((x) = (x))
7313 #endif	/* lint */
7314 
7315 	PRESERVE(tcp->tcp_bind_hash);
7316 	PRESERVE(tcp->tcp_ptpbhn);
7317 	PRESERVE(tcp->tcp_acceptor_hash);
7318 	PRESERVE(tcp->tcp_ptpahn);
7319 
7320 	/* Should be ASSERT NULL on these with new code! */
7321 	ASSERT(tcp->tcp_time_wait_next == NULL);
7322 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7323 	ASSERT(tcp->tcp_time_wait_expire == 0);
7324 	PRESERVE(tcp->tcp_state);
7325 	PRESERVE(tcp->tcp_rq);
7326 	PRESERVE(tcp->tcp_wq);
7327 
7328 	ASSERT(tcp->tcp_xmit_head == NULL);
7329 	ASSERT(tcp->tcp_xmit_last == NULL);
7330 	ASSERT(tcp->tcp_unsent == 0);
7331 	ASSERT(tcp->tcp_xmit_tail == NULL);
7332 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7333 
7334 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7335 	tcp->tcp_suna = 0;			/* Displayed in mib */
7336 	tcp->tcp_swnd = 0;
7337 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7338 
7339 	ASSERT(tcp->tcp_ibsegs == 0);
7340 	ASSERT(tcp->tcp_obsegs == 0);
7341 
7342 	if (tcp->tcp_iphc != NULL) {
7343 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7344 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7345 	}
7346 
7347 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7348 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7349 	DONTCARE(tcp->tcp_ipha);
7350 	DONTCARE(tcp->tcp_ip6h);
7351 	DONTCARE(tcp->tcp_ip_hdr_len);
7352 	DONTCARE(tcp->tcp_tcph);
7353 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7354 	tcp->tcp_valid_bits = 0;
7355 
7356 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7357 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7358 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7359 	tcp->tcp_last_rcv_lbolt = 0;
7360 
7361 	tcp->tcp_init_cwnd = 0;
7362 
7363 	tcp->tcp_urp_last_valid = 0;
7364 	tcp->tcp_hard_binding = 0;
7365 	tcp->tcp_hard_bound = 0;
7366 	PRESERVE(tcp->tcp_cred);
7367 	PRESERVE(tcp->tcp_cpid);
7368 	PRESERVE(tcp->tcp_exclbind);
7369 
7370 	tcp->tcp_fin_acked = 0;
7371 	tcp->tcp_fin_rcvd = 0;
7372 	tcp->tcp_fin_sent = 0;
7373 	tcp->tcp_ordrel_done = 0;
7374 
7375 	tcp->tcp_debug = 0;
7376 	tcp->tcp_dontroute = 0;
7377 	tcp->tcp_broadcast = 0;
7378 
7379 	tcp->tcp_useloopback = 0;
7380 	tcp->tcp_reuseaddr = 0;
7381 	tcp->tcp_oobinline = 0;
7382 	tcp->tcp_dgram_errind = 0;
7383 
7384 	tcp->tcp_detached = 0;
7385 	tcp->tcp_bind_pending = 0;
7386 	tcp->tcp_unbind_pending = 0;
7387 	tcp->tcp_deferred_clean_death = 0;
7388 
7389 	tcp->tcp_snd_ws_ok = B_FALSE;
7390 	tcp->tcp_snd_ts_ok = B_FALSE;
7391 	tcp->tcp_linger = 0;
7392 	tcp->tcp_ka_enabled = 0;
7393 	tcp->tcp_zero_win_probe = 0;
7394 
7395 	tcp->tcp_loopback = 0;
7396 	tcp->tcp_localnet = 0;
7397 	tcp->tcp_syn_defense = 0;
7398 	tcp->tcp_set_timer = 0;
7399 
7400 	tcp->tcp_active_open = 0;
7401 	ASSERT(tcp->tcp_timeout == B_FALSE);
7402 	tcp->tcp_rexmit = B_FALSE;
7403 	tcp->tcp_xmit_zc_clean = B_FALSE;
7404 
7405 	tcp->tcp_snd_sack_ok = B_FALSE;
7406 	PRESERVE(tcp->tcp_recvdstaddr);
7407 	tcp->tcp_hwcksum = B_FALSE;
7408 
7409 	tcp->tcp_ire_ill_check_done = B_FALSE;
7410 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7411 
7412 	tcp->tcp_mdt = B_FALSE;
7413 	tcp->tcp_mdt_hdr_head = 0;
7414 	tcp->tcp_mdt_hdr_tail = 0;
7415 
7416 	tcp->tcp_conn_def_q0 = 0;
7417 	tcp->tcp_ip_forward_progress = B_FALSE;
7418 	tcp->tcp_anon_priv_bind = 0;
7419 	tcp->tcp_ecn_ok = B_FALSE;
7420 
7421 	tcp->tcp_cwr = B_FALSE;
7422 	tcp->tcp_ecn_echo_on = B_FALSE;
7423 
7424 	if (tcp->tcp_sack_info != NULL) {
7425 		if (tcp->tcp_notsack_list != NULL) {
7426 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7427 		}
7428 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7429 		tcp->tcp_sack_info = NULL;
7430 	}
7431 
7432 	tcp->tcp_rcv_ws = 0;
7433 	tcp->tcp_snd_ws = 0;
7434 	tcp->tcp_ts_recent = 0;
7435 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7436 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7437 	tcp->tcp_if_mtu = 0;
7438 
7439 	ASSERT(tcp->tcp_reass_head == NULL);
7440 	ASSERT(tcp->tcp_reass_tail == NULL);
7441 
7442 	tcp->tcp_cwnd_cnt = 0;
7443 
7444 	ASSERT(tcp->tcp_rcv_list == NULL);
7445 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7446 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7447 	ASSERT(tcp->tcp_rcv_cnt == 0);
7448 
7449 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7450 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7451 	tcp->tcp_csuna = 0;
7452 
7453 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7454 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7455 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7456 	tcp->tcp_rtt_update = 0;
7457 
7458 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7459 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7460 
7461 	tcp->tcp_rack = 0;			/* Displayed in mib */
7462 	tcp->tcp_rack_cnt = 0;
7463 	tcp->tcp_rack_cur_max = 0;
7464 	tcp->tcp_rack_abs_max = 0;
7465 
7466 	tcp->tcp_max_swnd = 0;
7467 
7468 	ASSERT(tcp->tcp_listener == NULL);
7469 
7470 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7471 
7472 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7473 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7474 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7475 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7476 
7477 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7478 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7479 	PRESERVE(tcp->tcp_conn_req_max);
7480 	PRESERVE(tcp->tcp_conn_req_seqnum);
7481 
7482 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7483 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7484 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7485 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7486 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7487 
7488 	tcp->tcp_lingertime = 0;
7489 
7490 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7491 	ASSERT(tcp->tcp_urp_mp == NULL);
7492 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7493 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7494 
7495 	ASSERT(tcp->tcp_eager_next_q == NULL);
7496 	ASSERT(tcp->tcp_eager_last_q == NULL);
7497 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7498 	    tcp->tcp_eager_prev_q0 == NULL) ||
7499 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7500 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7501 
7502 	tcp->tcp_client_errno = 0;
7503 
7504 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7505 
7506 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7507 
7508 	PRESERVE(tcp->tcp_bound_source_v6);
7509 	tcp->tcp_last_sent_len = 0;
7510 	tcp->tcp_dupack_cnt = 0;
7511 
7512 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7513 	PRESERVE(tcp->tcp_lport);
7514 
7515 	PRESERVE(tcp->tcp_acceptor_lockp);
7516 
7517 	ASSERT(tcp->tcp_ordrelid == 0);
7518 	PRESERVE(tcp->tcp_acceptor_id);
7519 	DONTCARE(tcp->tcp_ipsec_overhead);
7520 
7521 	/*
7522 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
7523 	 * in tcp structure and now tracing), Re-initialize all
7524 	 * members of tcp_traceinfo.
7525 	 */
7526 	if (tcp->tcp_tracebuf != NULL) {
7527 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
7528 	}
7529 
7530 	PRESERVE(tcp->tcp_family);
7531 	if (tcp->tcp_family == AF_INET6) {
7532 		tcp->tcp_ipversion = IPV6_VERSION;
7533 		tcp->tcp_mss = tcp_mss_def_ipv6;
7534 	} else {
7535 		tcp->tcp_ipversion = IPV4_VERSION;
7536 		tcp->tcp_mss = tcp_mss_def_ipv4;
7537 	}
7538 
7539 	tcp->tcp_bound_if = 0;
7540 	tcp->tcp_ipv6_recvancillary = 0;
7541 	tcp->tcp_recvifindex = 0;
7542 	tcp->tcp_recvhops = 0;
7543 	tcp->tcp_closed = 0;
7544 	tcp->tcp_cleandeathtag = 0;
7545 	if (tcp->tcp_hopopts != NULL) {
7546 		mi_free(tcp->tcp_hopopts);
7547 		tcp->tcp_hopopts = NULL;
7548 		tcp->tcp_hopoptslen = 0;
7549 	}
7550 	ASSERT(tcp->tcp_hopoptslen == 0);
7551 	if (tcp->tcp_dstopts != NULL) {
7552 		mi_free(tcp->tcp_dstopts);
7553 		tcp->tcp_dstopts = NULL;
7554 		tcp->tcp_dstoptslen = 0;
7555 	}
7556 	ASSERT(tcp->tcp_dstoptslen == 0);
7557 	if (tcp->tcp_rtdstopts != NULL) {
7558 		mi_free(tcp->tcp_rtdstopts);
7559 		tcp->tcp_rtdstopts = NULL;
7560 		tcp->tcp_rtdstoptslen = 0;
7561 	}
7562 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7563 	if (tcp->tcp_rthdr != NULL) {
7564 		mi_free(tcp->tcp_rthdr);
7565 		tcp->tcp_rthdr = NULL;
7566 		tcp->tcp_rthdrlen = 0;
7567 	}
7568 	ASSERT(tcp->tcp_rthdrlen == 0);
7569 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7570 
7571 	/* Reset fusion-related fields */
7572 	tcp->tcp_fused = B_FALSE;
7573 	tcp->tcp_unfusable = B_FALSE;
7574 	tcp->tcp_fused_sigurg = B_FALSE;
7575 	tcp->tcp_direct_sockfs = B_FALSE;
7576 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7577 	tcp->tcp_loopback_peer = NULL;
7578 	tcp->tcp_fuse_rcv_hiwater = 0;
7579 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7580 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7581 
7582 	tcp->tcp_in_ack_unsent = 0;
7583 	tcp->tcp_cork = B_FALSE;
7584 
7585 	PRESERVE(tcp->tcp_squeue_bytes);
7586 
7587 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7588 	ASSERT(!tcp->tcp_kssl_pending);
7589 	PRESERVE(tcp->tcp_kssl_ent);
7590 
7591 #undef	DONTCARE
7592 #undef	PRESERVE
7593 }
7594 
7595 /*
7596  * Allocate necessary resources and initialize state vector.
7597  * Guaranteed not to fail so that when an error is returned,
7598  * the caller doesn't need to do any additional cleanup.
7599  */
7600 int
7601 tcp_init(tcp_t *tcp, queue_t *q)
7602 {
7603 	int	err;
7604 
7605 	tcp->tcp_rq = q;
7606 	tcp->tcp_wq = WR(q);
7607 	tcp->tcp_state = TCPS_IDLE;
7608 	if ((err = tcp_init_values(tcp)) != 0)
7609 		tcp_timers_stop(tcp);
7610 	return (err);
7611 }
7612 
7613 static int
7614 tcp_init_values(tcp_t *tcp)
7615 {
7616 	int	err;
7617 
7618 	ASSERT((tcp->tcp_family == AF_INET &&
7619 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7620 	    (tcp->tcp_family == AF_INET6 &&
7621 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7622 	    tcp->tcp_ipversion == IPV6_VERSION)));
7623 
7624 	/*
7625 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7626 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7627 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7628 	 * during first few transmissions of a connection as seen in slow
7629 	 * links.
7630 	 */
7631 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
7632 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
7633 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7634 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7635 	    tcp_conn_grace_period;
7636 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
7637 		tcp->tcp_rto = tcp_rexmit_interval_min;
7638 	tcp->tcp_timer_backoff = 0;
7639 	tcp->tcp_ms_we_have_waited = 0;
7640 	tcp->tcp_last_recv_time = lbolt;
7641 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
7642 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7643 
7644 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
7645 
7646 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
7647 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
7648 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
7649 	/*
7650 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7651 	 * passive open.
7652 	 */
7653 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
7654 
7655 	tcp->tcp_naglim = tcp_naglim_def;
7656 
7657 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7658 
7659 	tcp->tcp_mdt_hdr_head = 0;
7660 	tcp->tcp_mdt_hdr_tail = 0;
7661 
7662 	/* Reset fusion-related fields */
7663 	tcp->tcp_fused = B_FALSE;
7664 	tcp->tcp_unfusable = B_FALSE;
7665 	tcp->tcp_fused_sigurg = B_FALSE;
7666 	tcp->tcp_direct_sockfs = B_FALSE;
7667 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7668 	tcp->tcp_loopback_peer = NULL;
7669 	tcp->tcp_fuse_rcv_hiwater = 0;
7670 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7671 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7672 
7673 	/* Initialize the header template */
7674 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7675 		err = tcp_header_init_ipv4(tcp);
7676 	} else {
7677 		err = tcp_header_init_ipv6(tcp);
7678 	}
7679 	if (err)
7680 		return (err);
7681 
7682 	/*
7683 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7684 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7685 	 */
7686 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7687 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
7688 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
7689 
7690 	tcp->tcp_cork = B_FALSE;
7691 	/*
7692 	 * Init the tcp_debug option.  This value determines whether TCP
7693 	 * calls strlog() to print out debug messages.  Doing this
7694 	 * initialization here means that this value is not inherited thru
7695 	 * tcp_reinit().
7696 	 */
7697 	tcp->tcp_debug = tcp_dbg;
7698 
7699 	tcp->tcp_ka_interval = tcp_keepalive_interval;
7700 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
7701 
7702 	return (0);
7703 }
7704 
7705 /*
7706  * Initialize the IPv4 header. Loses any record of any IP options.
7707  */
7708 static int
7709 tcp_header_init_ipv4(tcp_t *tcp)
7710 {
7711 	tcph_t		*tcph;
7712 	uint32_t	sum;
7713 
7714 	/*
7715 	 * This is a simple initialization. If there's
7716 	 * already a template, it should never be too small,
7717 	 * so reuse it.  Otherwise, allocate space for the new one.
7718 	 */
7719 	if (tcp->tcp_iphc == NULL) {
7720 		ASSERT(tcp->tcp_iphc_len == 0);
7721 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7722 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7723 		if (tcp->tcp_iphc == NULL) {
7724 			tcp->tcp_iphc_len = 0;
7725 			return (ENOMEM);
7726 		}
7727 	}
7728 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7729 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
7730 	tcp->tcp_ip6h = NULL;
7731 	tcp->tcp_ipversion = IPV4_VERSION;
7732 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
7733 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
7734 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
7735 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
7736 	tcp->tcp_ipha->ipha_version_and_hdr_length
7737 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
7738 	tcp->tcp_ipha->ipha_ident = 0;
7739 
7740 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
7741 	tcp->tcp_tos = 0;
7742 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
7743 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
7744 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
7745 
7746 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
7747 	tcp->tcp_tcph = tcph;
7748 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
7749 	/*
7750 	 * IP wants our header length in the checksum field to
7751 	 * allow it to perform a single pseudo-header+checksum
7752 	 * calculation on behalf of TCP.
7753 	 * Include the adjustment for a source route once IP_OPTIONS is set.
7754 	 */
7755 	sum = sizeof (tcph_t) + tcp->tcp_sum;
7756 	sum = (sum >> 16) + (sum & 0xFFFF);
7757 	U16_TO_ABE16(sum, tcph->th_sum);
7758 	return (0);
7759 }
7760 
7761 /*
7762  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
7763  */
7764 static int
7765 tcp_header_init_ipv6(tcp_t *tcp)
7766 {
7767 	tcph_t	*tcph;
7768 	uint32_t	sum;
7769 
7770 	/*
7771 	 * This is a simple initialization. If there's
7772 	 * already a template, it should never be too small,
7773 	 * so reuse it. Otherwise, allocate space for the new one.
7774 	 * Ensure that there is enough space to "downgrade" the tcp_t
7775 	 * to an IPv4 tcp_t. This requires having space for a full load
7776 	 * of IPv4 options, as well as a full load of TCP options
7777 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
7778 	 * than a v6 header and a TCP header with a full load of TCP options
7779 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
7780 	 * We want to avoid reallocation in the "downgraded" case when
7781 	 * processing outbound IPv4 options.
7782 	 */
7783 	if (tcp->tcp_iphc == NULL) {
7784 		ASSERT(tcp->tcp_iphc_len == 0);
7785 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7786 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7787 		if (tcp->tcp_iphc == NULL) {
7788 			tcp->tcp_iphc_len = 0;
7789 			return (ENOMEM);
7790 		}
7791 	}
7792 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7793 	tcp->tcp_ipversion = IPV6_VERSION;
7794 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
7795 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
7796 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
7797 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
7798 	tcp->tcp_ipha = NULL;
7799 
7800 	/* Initialize the header template */
7801 
7802 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
7803 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
7804 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
7805 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
7806 
7807 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
7808 	tcp->tcp_tcph = tcph;
7809 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
7810 	/*
7811 	 * IP wants our header length in the checksum field to
7812 	 * allow it to perform a single psuedo-header+checksum
7813 	 * calculation on behalf of TCP.
7814 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
7815 	 */
7816 	sum = sizeof (tcph_t) + tcp->tcp_sum;
7817 	sum = (sum >> 16) + (sum & 0xFFFF);
7818 	U16_TO_ABE16(sum, tcph->th_sum);
7819 	return (0);
7820 }
7821 
7822 /* At minimum we need 4 bytes in the TCP header for the lookup */
7823 #define	ICMP_MIN_TCP_HDR	4
7824 
7825 /*
7826  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
7827  * passed up by IP. The message is always received on the correct tcp_t.
7828  * Assumes that IP has pulled up everything up to and including the ICMP header.
7829  */
7830 void
7831 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
7832 {
7833 	icmph_t *icmph;
7834 	ipha_t	*ipha;
7835 	int	iph_hdr_length;
7836 	tcph_t	*tcph;
7837 	boolean_t ipsec_mctl = B_FALSE;
7838 	boolean_t secure;
7839 	mblk_t *first_mp = mp;
7840 	uint32_t new_mss;
7841 	uint32_t ratio;
7842 	size_t mp_size = MBLKL(mp);
7843 	uint32_t seg_ack;
7844 	uint32_t seg_seq;
7845 
7846 	/* Assume IP provides aligned packets - otherwise toss */
7847 	if (!OK_32PTR(mp->b_rptr)) {
7848 		freemsg(mp);
7849 		return;
7850 	}
7851 
7852 	/*
7853 	 * Since ICMP errors are normal data marked with M_CTL when sent
7854 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
7855 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
7856 	 */
7857 	if ((mp_size == sizeof (ipsec_info_t)) &&
7858 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
7859 		ASSERT(mp->b_cont != NULL);
7860 		mp = mp->b_cont;
7861 		/* IP should have done this */
7862 		ASSERT(OK_32PTR(mp->b_rptr));
7863 		mp_size = MBLKL(mp);
7864 		ipsec_mctl = B_TRUE;
7865 	}
7866 
7867 	/*
7868 	 * Verify that we have a complete outer IP header. If not, drop it.
7869 	 */
7870 	if (mp_size < sizeof (ipha_t)) {
7871 noticmpv4:
7872 		freemsg(first_mp);
7873 		return;
7874 	}
7875 
7876 	ipha = (ipha_t *)mp->b_rptr;
7877 	/*
7878 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
7879 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
7880 	 */
7881 	switch (IPH_HDR_VERSION(ipha)) {
7882 	case IPV6_VERSION:
7883 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
7884 		return;
7885 	case IPV4_VERSION:
7886 		break;
7887 	default:
7888 		goto noticmpv4;
7889 	}
7890 
7891 	/* Skip past the outer IP and ICMP headers */
7892 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7893 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
7894 	/*
7895 	 * If we don't have the correct outer IP header length or if the ULP
7896 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
7897 	 * send it upstream.
7898 	 */
7899 	if (iph_hdr_length < sizeof (ipha_t) ||
7900 	    ipha->ipha_protocol != IPPROTO_ICMP ||
7901 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
7902 		goto noticmpv4;
7903 	}
7904 	ipha = (ipha_t *)&icmph[1];
7905 
7906 	/* Skip past the inner IP and find the ULP header */
7907 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7908 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
7909 	/*
7910 	 * If we don't have the correct inner IP header length or if the ULP
7911 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
7912 	 * bytes of TCP header, drop it.
7913 	 */
7914 	if (iph_hdr_length < sizeof (ipha_t) ||
7915 	    ipha->ipha_protocol != IPPROTO_TCP ||
7916 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
7917 		goto noticmpv4;
7918 	}
7919 
7920 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
7921 		if (ipsec_mctl) {
7922 			secure = ipsec_in_is_secure(first_mp);
7923 		} else {
7924 			secure = B_FALSE;
7925 		}
7926 		if (secure) {
7927 			/*
7928 			 * If we are willing to accept this in clear
7929 			 * we don't have to verify policy.
7930 			 */
7931 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
7932 				if (!tcp_check_policy(tcp, first_mp,
7933 				    ipha, NULL, secure, ipsec_mctl)) {
7934 					/*
7935 					 * tcp_check_policy called
7936 					 * ip_drop_packet() on failure.
7937 					 */
7938 					return;
7939 				}
7940 			}
7941 		}
7942 	} else if (ipsec_mctl) {
7943 		/*
7944 		 * This is a hard_bound connection. IP has already
7945 		 * verified policy. We don't have to do it again.
7946 		 */
7947 		freeb(first_mp);
7948 		first_mp = mp;
7949 		ipsec_mctl = B_FALSE;
7950 	}
7951 
7952 	seg_ack = ABE32_TO_U32(tcph->th_ack);
7953 	seg_seq = ABE32_TO_U32(tcph->th_seq);
7954 	/*
7955 	 * TCP SHOULD check that the TCP sequence number contained in
7956 	 * payload of the ICMP error message is within the range
7957 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
7958 	 */
7959 	if (SEQ_LT(seg_seq, tcp->tcp_suna) ||
7960 		SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
7961 		SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
7962 		/*
7963 		 * If the ICMP message is bogus, should we kill the
7964 		 * connection, or should we just drop the bogus ICMP
7965 		 * message? It would probably make more sense to just
7966 		 * drop the message so that if this one managed to get
7967 		 * in, the real connection should not suffer.
7968 		 */
7969 		goto noticmpv4;
7970 	}
7971 
7972 	switch (icmph->icmph_type) {
7973 	case ICMP_DEST_UNREACHABLE:
7974 		switch (icmph->icmph_code) {
7975 		case ICMP_FRAGMENTATION_NEEDED:
7976 			/*
7977 			 * Reduce the MSS based on the new MTU.  This will
7978 			 * eliminate any fragmentation locally.
7979 			 * N.B.  There may well be some funny side-effects on
7980 			 * the local send policy and the remote receive policy.
7981 			 * Pending further research, we provide
7982 			 * tcp_ignore_path_mtu just in case this proves
7983 			 * disastrous somewhere.
7984 			 *
7985 			 * After updating the MSS, retransmit part of the
7986 			 * dropped segment using the new mss by calling
7987 			 * tcp_wput_data().  Need to adjust all those
7988 			 * params to make sure tcp_wput_data() work properly.
7989 			 */
7990 			if (tcp_ignore_path_mtu)
7991 				break;
7992 
7993 			/*
7994 			 * Decrease the MSS by time stamp options
7995 			 * IP options and IPSEC options. tcp_hdr_len
7996 			 * includes time stamp option and IP option
7997 			 * length.
7998 			 */
7999 
8000 			new_mss = ntohs(icmph->icmph_du_mtu) -
8001 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8002 
8003 			/*
8004 			 * Only update the MSS if the new one is
8005 			 * smaller than the previous one.  This is
8006 			 * to avoid problems when getting multiple
8007 			 * ICMP errors for the same MTU.
8008 			 */
8009 			if (new_mss >= tcp->tcp_mss)
8010 				break;
8011 
8012 			/*
8013 			 * Stop doing PMTU if new_mss is less than 68
8014 			 * or less than tcp_mss_min.
8015 			 * The value 68 comes from rfc 1191.
8016 			 */
8017 			if (new_mss < MAX(68, tcp_mss_min))
8018 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8019 				    0;
8020 
8021 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8022 			ASSERT(ratio >= 1);
8023 			tcp_mss_set(tcp, new_mss);
8024 
8025 			/*
8026 			 * Make sure we have something to
8027 			 * send.
8028 			 */
8029 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8030 			    (tcp->tcp_xmit_head != NULL)) {
8031 				/*
8032 				 * Shrink tcp_cwnd in
8033 				 * proportion to the old MSS/new MSS.
8034 				 */
8035 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8036 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8037 				    (tcp->tcp_unsent == 0)) {
8038 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8039 				} else {
8040 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8041 				}
8042 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8043 				tcp->tcp_rexmit = B_TRUE;
8044 				tcp->tcp_dupack_cnt = 0;
8045 				tcp->tcp_snd_burst = TCP_CWND_SS;
8046 				tcp_ss_rexmit(tcp);
8047 			}
8048 			break;
8049 		case ICMP_PORT_UNREACHABLE:
8050 		case ICMP_PROTOCOL_UNREACHABLE:
8051 			switch (tcp->tcp_state) {
8052 			case TCPS_SYN_SENT:
8053 			case TCPS_SYN_RCVD:
8054 				/*
8055 				 * ICMP can snipe away incipient
8056 				 * TCP connections as long as
8057 				 * seq number is same as initial
8058 				 * send seq number.
8059 				 */
8060 				if (seg_seq == tcp->tcp_iss) {
8061 					(void) tcp_clean_death(tcp,
8062 					    ECONNREFUSED, 6);
8063 				}
8064 				break;
8065 			}
8066 			break;
8067 		case ICMP_HOST_UNREACHABLE:
8068 		case ICMP_NET_UNREACHABLE:
8069 			/* Record the error in case we finally time out. */
8070 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8071 				tcp->tcp_client_errno = EHOSTUNREACH;
8072 			else
8073 				tcp->tcp_client_errno = ENETUNREACH;
8074 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8075 				if (tcp->tcp_listener != NULL &&
8076 				    tcp->tcp_listener->tcp_syn_defense) {
8077 					/*
8078 					 * Ditch the half-open connection if we
8079 					 * suspect a SYN attack is under way.
8080 					 */
8081 					tcp_ip_ire_mark_advice(tcp);
8082 					(void) tcp_clean_death(tcp,
8083 					    tcp->tcp_client_errno, 7);
8084 				}
8085 			}
8086 			break;
8087 		default:
8088 			break;
8089 		}
8090 		break;
8091 	case ICMP_SOURCE_QUENCH: {
8092 		/*
8093 		 * use a global boolean to control
8094 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8095 		 * The default is false.
8096 		 */
8097 		if (tcp_icmp_source_quench) {
8098 			/*
8099 			 * Reduce the sending rate as if we got a
8100 			 * retransmit timeout
8101 			 */
8102 			uint32_t npkt;
8103 
8104 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8105 			    tcp->tcp_mss;
8106 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8107 			tcp->tcp_cwnd = tcp->tcp_mss;
8108 			tcp->tcp_cwnd_cnt = 0;
8109 		}
8110 		break;
8111 	}
8112 	}
8113 	freemsg(first_mp);
8114 }
8115 
8116 /*
8117  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8118  * error messages passed up by IP.
8119  * Assumes that IP has pulled up all the extension headers as well
8120  * as the ICMPv6 header.
8121  */
8122 static void
8123 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8124 {
8125 	icmp6_t *icmp6;
8126 	ip6_t	*ip6h;
8127 	uint16_t	iph_hdr_length;
8128 	tcpha_t	*tcpha;
8129 	uint8_t	*nexthdrp;
8130 	uint32_t new_mss;
8131 	uint32_t ratio;
8132 	boolean_t secure;
8133 	mblk_t *first_mp = mp;
8134 	size_t mp_size;
8135 	uint32_t seg_ack;
8136 	uint32_t seg_seq;
8137 
8138 	/*
8139 	 * The caller has determined if this is an IPSEC_IN packet and
8140 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8141 	 */
8142 	if (ipsec_mctl)
8143 		mp = mp->b_cont;
8144 
8145 	mp_size = MBLKL(mp);
8146 
8147 	/*
8148 	 * Verify that we have a complete IP header. If not, send it upstream.
8149 	 */
8150 	if (mp_size < sizeof (ip6_t)) {
8151 noticmpv6:
8152 		freemsg(first_mp);
8153 		return;
8154 	}
8155 
8156 	/*
8157 	 * Verify this is an ICMPV6 packet, else send it upstream.
8158 	 */
8159 	ip6h = (ip6_t *)mp->b_rptr;
8160 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8161 		iph_hdr_length = IPV6_HDR_LEN;
8162 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8163 	    &nexthdrp) ||
8164 	    *nexthdrp != IPPROTO_ICMPV6) {
8165 		goto noticmpv6;
8166 	}
8167 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8168 	ip6h = (ip6_t *)&icmp6[1];
8169 	/*
8170 	 * Verify if we have a complete ICMP and inner IP header.
8171 	 */
8172 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8173 		goto noticmpv6;
8174 
8175 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8176 		goto noticmpv6;
8177 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8178 	/*
8179 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8180 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8181 	 * packet.
8182 	 */
8183 	if ((*nexthdrp != IPPROTO_TCP) ||
8184 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8185 		goto noticmpv6;
8186 	}
8187 
8188 	/*
8189 	 * ICMP errors come on the right queue or come on
8190 	 * listener/global queue for detached connections and
8191 	 * get switched to the right queue. If it comes on the
8192 	 * right queue, policy check has already been done by IP
8193 	 * and thus free the first_mp without verifying the policy.
8194 	 * If it has come for a non-hard bound connection, we need
8195 	 * to verify policy as IP may not have done it.
8196 	 */
8197 	if (!tcp->tcp_hard_bound) {
8198 		if (ipsec_mctl) {
8199 			secure = ipsec_in_is_secure(first_mp);
8200 		} else {
8201 			secure = B_FALSE;
8202 		}
8203 		if (secure) {
8204 			/*
8205 			 * If we are willing to accept this in clear
8206 			 * we don't have to verify policy.
8207 			 */
8208 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8209 				if (!tcp_check_policy(tcp, first_mp,
8210 				    NULL, ip6h, secure, ipsec_mctl)) {
8211 					/*
8212 					 * tcp_check_policy called
8213 					 * ip_drop_packet() on failure.
8214 					 */
8215 					return;
8216 				}
8217 			}
8218 		}
8219 	} else if (ipsec_mctl) {
8220 		/*
8221 		 * This is a hard_bound connection. IP has already
8222 		 * verified policy. We don't have to do it again.
8223 		 */
8224 		freeb(first_mp);
8225 		first_mp = mp;
8226 		ipsec_mctl = B_FALSE;
8227 	}
8228 
8229 	seg_ack = ntohl(tcpha->tha_ack);
8230 	seg_seq = ntohl(tcpha->tha_seq);
8231 	/*
8232 	 * TCP SHOULD check that the TCP sequence number contained in
8233 	 * payload of the ICMP error message is within the range
8234 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8235 	 */
8236 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8237 	    SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8238 		/*
8239 		 * If the ICMP message is bogus, should we kill the
8240 		 * connection, or should we just drop the bogus ICMP
8241 		 * message? It would probably make more sense to just
8242 		 * drop the message so that if this one managed to get
8243 		 * in, the real connection should not suffer.
8244 		 */
8245 		goto noticmpv6;
8246 	}
8247 
8248 	switch (icmp6->icmp6_type) {
8249 	case ICMP6_PACKET_TOO_BIG:
8250 		/*
8251 		 * Reduce the MSS based on the new MTU.  This will
8252 		 * eliminate any fragmentation locally.
8253 		 * N.B.  There may well be some funny side-effects on
8254 		 * the local send policy and the remote receive policy.
8255 		 * Pending further research, we provide
8256 		 * tcp_ignore_path_mtu just in case this proves
8257 		 * disastrous somewhere.
8258 		 *
8259 		 * After updating the MSS, retransmit part of the
8260 		 * dropped segment using the new mss by calling
8261 		 * tcp_wput_data().  Need to adjust all those
8262 		 * params to make sure tcp_wput_data() work properly.
8263 		 */
8264 		if (tcp_ignore_path_mtu)
8265 			break;
8266 
8267 		/*
8268 		 * Decrease the MSS by time stamp options
8269 		 * IP options and IPSEC options. tcp_hdr_len
8270 		 * includes time stamp option and IP option
8271 		 * length.
8272 		 */
8273 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8274 			    tcp->tcp_ipsec_overhead;
8275 
8276 		/*
8277 		 * Only update the MSS if the new one is
8278 		 * smaller than the previous one.  This is
8279 		 * to avoid problems when getting multiple
8280 		 * ICMP errors for the same MTU.
8281 		 */
8282 		if (new_mss >= tcp->tcp_mss)
8283 			break;
8284 
8285 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8286 		ASSERT(ratio >= 1);
8287 		tcp_mss_set(tcp, new_mss);
8288 
8289 		/*
8290 		 * Make sure we have something to
8291 		 * send.
8292 		 */
8293 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8294 		    (tcp->tcp_xmit_head != NULL)) {
8295 			/*
8296 			 * Shrink tcp_cwnd in
8297 			 * proportion to the old MSS/new MSS.
8298 			 */
8299 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8300 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8301 			    (tcp->tcp_unsent == 0)) {
8302 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8303 			} else {
8304 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8305 			}
8306 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8307 			tcp->tcp_rexmit = B_TRUE;
8308 			tcp->tcp_dupack_cnt = 0;
8309 			tcp->tcp_snd_burst = TCP_CWND_SS;
8310 			tcp_ss_rexmit(tcp);
8311 		}
8312 		break;
8313 
8314 	case ICMP6_DST_UNREACH:
8315 		switch (icmp6->icmp6_code) {
8316 		case ICMP6_DST_UNREACH_NOPORT:
8317 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8318 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8319 			    (tcpha->tha_seq == tcp->tcp_iss)) {
8320 				(void) tcp_clean_death(tcp,
8321 				    ECONNREFUSED, 8);
8322 			}
8323 			break;
8324 
8325 		case ICMP6_DST_UNREACH_ADMIN:
8326 		case ICMP6_DST_UNREACH_NOROUTE:
8327 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8328 		case ICMP6_DST_UNREACH_ADDR:
8329 			/* Record the error in case we finally time out. */
8330 			tcp->tcp_client_errno = EHOSTUNREACH;
8331 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8332 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8333 			    (tcpha->tha_seq == tcp->tcp_iss)) {
8334 				if (tcp->tcp_listener != NULL &&
8335 				    tcp->tcp_listener->tcp_syn_defense) {
8336 					/*
8337 					 * Ditch the half-open connection if we
8338 					 * suspect a SYN attack is under way.
8339 					 */
8340 					tcp_ip_ire_mark_advice(tcp);
8341 					(void) tcp_clean_death(tcp,
8342 					    tcp->tcp_client_errno, 9);
8343 				}
8344 			}
8345 
8346 
8347 			break;
8348 		default:
8349 			break;
8350 		}
8351 		break;
8352 
8353 	case ICMP6_PARAM_PROB:
8354 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8355 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8356 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8357 		    (uchar_t *)nexthdrp) {
8358 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8359 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8360 				(void) tcp_clean_death(tcp,
8361 				    ECONNREFUSED, 10);
8362 			}
8363 			break;
8364 		}
8365 		break;
8366 
8367 	case ICMP6_TIME_EXCEEDED:
8368 	default:
8369 		break;
8370 	}
8371 	freemsg(first_mp);
8372 }
8373 
8374 /*
8375  * IP recognizes seven kinds of bind requests:
8376  *
8377  * - A zero-length address binds only to the protocol number.
8378  *
8379  * - A 4-byte address is treated as a request to
8380  * validate that the address is a valid local IPv4
8381  * address, appropriate for an application to bind to.
8382  * IP does the verification, but does not make any note
8383  * of the address at this time.
8384  *
8385  * - A 16-byte address contains is treated as a request
8386  * to validate a local IPv6 address, as the 4-byte
8387  * address case above.
8388  *
8389  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8390  * use it for the inbound fanout of packets.
8391  *
8392  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8393  * use it for the inbound fanout of packets.
8394  *
8395  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8396  * information consisting of local and remote addresses
8397  * and ports.  In this case, the addresses are both
8398  * validated as appropriate for this operation, and, if
8399  * so, the information is retained for use in the
8400  * inbound fanout.
8401  *
8402  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8403  * fanout information, like the 12-byte case above.
8404  *
8405  * IP will also fill in the IRE request mblk with information
8406  * regarding our peer.  In all cases, we notify IP of our protocol
8407  * type by appending a single protocol byte to the bind request.
8408  */
8409 static mblk_t *
8410 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8411 {
8412 	char	*cp;
8413 	mblk_t	*mp;
8414 	struct T_bind_req *tbr;
8415 	ipa_conn_t	*ac;
8416 	ipa6_conn_t	*ac6;
8417 	sin_t		*sin;
8418 	sin6_t		*sin6;
8419 
8420 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
8421 	ASSERT((tcp->tcp_family == AF_INET &&
8422 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8423 	    (tcp->tcp_family == AF_INET6 &&
8424 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8425 	    tcp->tcp_ipversion == IPV6_VERSION)));
8426 
8427 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
8428 	if (!mp)
8429 		return (mp);
8430 	mp->b_datap->db_type = M_PROTO;
8431 	tbr = (struct T_bind_req *)mp->b_rptr;
8432 	tbr->PRIM_type = bind_prim;
8433 	tbr->ADDR_offset = sizeof (*tbr);
8434 	tbr->CONIND_number = 0;
8435 	tbr->ADDR_length = addr_length;
8436 	cp = (char *)&tbr[1];
8437 	switch (addr_length) {
8438 	case sizeof (ipa_conn_t):
8439 		ASSERT(tcp->tcp_family == AF_INET);
8440 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8441 
8442 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8443 		if (mp->b_cont == NULL) {
8444 			freemsg(mp);
8445 			return (NULL);
8446 		}
8447 		mp->b_cont->b_wptr += sizeof (ire_t);
8448 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8449 
8450 		/* cp known to be 32 bit aligned */
8451 		ac = (ipa_conn_t *)cp;
8452 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
8453 		ac->ac_faddr = tcp->tcp_remote;
8454 		ac->ac_fport = tcp->tcp_fport;
8455 		ac->ac_lport = tcp->tcp_lport;
8456 		tcp->tcp_hard_binding = 1;
8457 		break;
8458 
8459 	case sizeof (ipa6_conn_t):
8460 		ASSERT(tcp->tcp_family == AF_INET6);
8461 
8462 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8463 		if (mp->b_cont == NULL) {
8464 			freemsg(mp);
8465 			return (NULL);
8466 		}
8467 		mp->b_cont->b_wptr += sizeof (ire_t);
8468 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8469 
8470 		/* cp known to be 32 bit aligned */
8471 		ac6 = (ipa6_conn_t *)cp;
8472 		if (tcp->tcp_ipversion == IPV4_VERSION) {
8473 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
8474 			    &ac6->ac6_laddr);
8475 		} else {
8476 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
8477 		}
8478 		ac6->ac6_faddr = tcp->tcp_remote_v6;
8479 		ac6->ac6_fport = tcp->tcp_fport;
8480 		ac6->ac6_lport = tcp->tcp_lport;
8481 		tcp->tcp_hard_binding = 1;
8482 		break;
8483 
8484 	case sizeof (sin_t):
8485 		/*
8486 		 * NOTE: IPV6_ADDR_LEN also has same size.
8487 		 * Use family to discriminate.
8488 		 */
8489 		if (tcp->tcp_family == AF_INET) {
8490 			sin = (sin_t *)cp;
8491 
8492 			*sin = sin_null;
8493 			sin->sin_family = AF_INET;
8494 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
8495 			sin->sin_port = tcp->tcp_lport;
8496 			break;
8497 		} else {
8498 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
8499 		}
8500 		break;
8501 
8502 	case sizeof (sin6_t):
8503 		ASSERT(tcp->tcp_family == AF_INET6);
8504 		sin6 = (sin6_t *)cp;
8505 
8506 		*sin6 = sin6_null;
8507 		sin6->sin6_family = AF_INET6;
8508 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
8509 		sin6->sin6_port = tcp->tcp_lport;
8510 		break;
8511 
8512 	case IP_ADDR_LEN:
8513 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8514 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
8515 		break;
8516 
8517 	}
8518 	/* Add protocol number to end */
8519 	cp[addr_length] = (char)IPPROTO_TCP;
8520 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
8521 	return (mp);
8522 }
8523 
8524 /*
8525  * Notify IP that we are having trouble with this connection.  IP should
8526  * blow the IRE away and start over.
8527  */
8528 static void
8529 tcp_ip_notify(tcp_t *tcp)
8530 {
8531 	struct iocblk	*iocp;
8532 	ipid_t	*ipid;
8533 	mblk_t	*mp;
8534 
8535 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8536 	if (tcp->tcp_ipversion == IPV6_VERSION)
8537 		return;
8538 
8539 	mp = mkiocb(IP_IOCTL);
8540 	if (mp == NULL)
8541 		return;
8542 
8543 	iocp = (struct iocblk *)mp->b_rptr;
8544 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8545 
8546 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8547 	if (!mp->b_cont) {
8548 		freeb(mp);
8549 		return;
8550 	}
8551 
8552 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8553 	mp->b_cont->b_wptr += iocp->ioc_count;
8554 	bzero(ipid, sizeof (*ipid));
8555 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8556 	ipid->ipid_ire_type = IRE_CACHE;
8557 	ipid->ipid_addr_offset = sizeof (ipid_t);
8558 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8559 	/*
8560 	 * Note: in the case of source routing we want to blow away the
8561 	 * route to the first source route hop.
8562 	 */
8563 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8564 	    sizeof (tcp->tcp_ipha->ipha_dst));
8565 
8566 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8567 }
8568 
8569 /* Unlink and return any mblk that looks like it contains an ire */
8570 static mblk_t *
8571 tcp_ire_mp(mblk_t *mp)
8572 {
8573 	mblk_t	*prev_mp;
8574 
8575 	for (;;) {
8576 		prev_mp = mp;
8577 		mp = mp->b_cont;
8578 		if (mp == NULL)
8579 			break;
8580 		switch (DB_TYPE(mp)) {
8581 		case IRE_DB_TYPE:
8582 		case IRE_DB_REQ_TYPE:
8583 			if (prev_mp != NULL)
8584 				prev_mp->b_cont = mp->b_cont;
8585 			mp->b_cont = NULL;
8586 			return (mp);
8587 		default:
8588 			break;
8589 		}
8590 	}
8591 	return (mp);
8592 }
8593 
8594 /*
8595  * Timer callback routine for keepalive probe.  We do a fake resend of
8596  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8597  * check to see if we have heard anything from the other end for the last
8598  * RTO period.  If we have, set the timer to expire for another
8599  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8600  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8601  * the timeout if we have not heard from the other side.  If for more than
8602  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8603  * kill the connection unless the keepalive abort threshold is 0.  In
8604  * that case, we will probe "forever."
8605  */
8606 static void
8607 tcp_keepalive_killer(void *arg)
8608 {
8609 	mblk_t	*mp;
8610 	conn_t	*connp = (conn_t *)arg;
8611 	tcp_t  	*tcp = connp->conn_tcp;
8612 	int32_t	firetime;
8613 	int32_t	idletime;
8614 	int32_t	ka_intrvl;
8615 
8616 	tcp->tcp_ka_tid = 0;
8617 
8618 	if (tcp->tcp_fused)
8619 		return;
8620 
8621 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
8622 	ka_intrvl = tcp->tcp_ka_interval;
8623 
8624 	/*
8625 	 * Keepalive probe should only be sent if the application has not
8626 	 * done a close on the connection.
8627 	 */
8628 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8629 		return;
8630 	}
8631 	/* Timer fired too early, restart it. */
8632 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8633 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8634 		    MSEC_TO_TICK(ka_intrvl));
8635 		return;
8636 	}
8637 
8638 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8639 	/*
8640 	 * If we have not heard from the other side for a long
8641 	 * time, kill the connection unless the keepalive abort
8642 	 * threshold is 0.  In that case, we will probe "forever."
8643 	 */
8644 	if (tcp->tcp_ka_abort_thres != 0 &&
8645 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8646 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
8647 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8648 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8649 		return;
8650 	}
8651 
8652 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8653 	    idletime >= ka_intrvl) {
8654 		/* Fake resend of last ACKed byte. */
8655 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8656 
8657 		if (mp1 != NULL) {
8658 			*mp1->b_wptr++ = '\0';
8659 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8660 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8661 			freeb(mp1);
8662 			/*
8663 			 * if allocation failed, fall through to start the
8664 			 * timer back.
8665 			 */
8666 			if (mp != NULL) {
8667 				TCP_RECORD_TRACE(tcp, mp,
8668 				    TCP_TRACE_SEND_PKT);
8669 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8670 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
8671 				if (tcp->tcp_ka_last_intrvl != 0) {
8672 					/*
8673 					 * We should probe again at least
8674 					 * in ka_intrvl, but not more than
8675 					 * tcp_rexmit_interval_max.
8676 					 */
8677 					firetime = MIN(ka_intrvl - 1,
8678 					    tcp->tcp_ka_last_intrvl << 1);
8679 					if (firetime > tcp_rexmit_interval_max)
8680 						firetime =
8681 						    tcp_rexmit_interval_max;
8682 				} else {
8683 					firetime = tcp->tcp_rto;
8684 				}
8685 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8686 				    tcp_keepalive_killer,
8687 				    MSEC_TO_TICK(firetime));
8688 				tcp->tcp_ka_last_intrvl = firetime;
8689 				return;
8690 			}
8691 		}
8692 	} else {
8693 		tcp->tcp_ka_last_intrvl = 0;
8694 	}
8695 
8696 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8697 	if ((firetime = ka_intrvl - idletime) < 0) {
8698 		firetime = ka_intrvl;
8699 	}
8700 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8701 	    MSEC_TO_TICK(firetime));
8702 }
8703 
8704 int
8705 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8706 {
8707 	queue_t	*q = tcp->tcp_rq;
8708 	int32_t	mss = tcp->tcp_mss;
8709 	int	maxpsz;
8710 
8711 	if (TCP_IS_DETACHED(tcp))
8712 		return (mss);
8713 
8714 	if (tcp->tcp_fused) {
8715 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8716 		mss = INFPSZ;
8717 	} else if (tcp->tcp_mdt || tcp->tcp_maxpsz == 0) {
8718 		/*
8719 		 * Set the sd_qn_maxpsz according to the socket send buffer
8720 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8721 		 * instruct the stream head to copyin user data into contiguous
8722 		 * kernel-allocated buffers without breaking it up into smaller
8723 		 * chunks.  We round up the buffer size to the nearest SMSS.
8724 		 */
8725 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8726 		if (tcp->tcp_kssl_ctx == NULL)
8727 			mss = INFPSZ;
8728 		else
8729 			mss = SSL3_MAX_RECORD_LEN;
8730 	} else {
8731 		/*
8732 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8733 		 * (and a multiple of the mss).  This instructs the stream
8734 		 * head to break down larger than SMSS writes into SMSS-
8735 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8736 		 */
8737 		maxpsz = tcp->tcp_maxpsz * mss;
8738 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8739 			maxpsz = tcp->tcp_xmit_hiwater/2;
8740 			/* Round up to nearest mss */
8741 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8742 		}
8743 	}
8744 	(void) setmaxps(q, maxpsz);
8745 	tcp->tcp_wq->q_maxpsz = maxpsz;
8746 
8747 	if (set_maxblk)
8748 		(void) mi_set_sth_maxblk(q, mss);
8749 
8750 	return (mss);
8751 }
8752 
8753 /*
8754  * Extract option values from a tcp header.  We put any found values into the
8755  * tcpopt struct and return a bitmask saying which options were found.
8756  */
8757 static int
8758 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8759 {
8760 	uchar_t		*endp;
8761 	int		len;
8762 	uint32_t	mss;
8763 	uchar_t		*up = (uchar_t *)tcph;
8764 	int		found = 0;
8765 	int32_t		sack_len;
8766 	tcp_seq		sack_begin, sack_end;
8767 	tcp_t		*tcp;
8768 
8769 	endp = up + TCP_HDR_LENGTH(tcph);
8770 	up += TCP_MIN_HEADER_LENGTH;
8771 	while (up < endp) {
8772 		len = endp - up;
8773 		switch (*up) {
8774 		case TCPOPT_EOL:
8775 			break;
8776 
8777 		case TCPOPT_NOP:
8778 			up++;
8779 			continue;
8780 
8781 		case TCPOPT_MAXSEG:
8782 			if (len < TCPOPT_MAXSEG_LEN ||
8783 			    up[1] != TCPOPT_MAXSEG_LEN)
8784 				break;
8785 
8786 			mss = BE16_TO_U16(up+2);
8787 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8788 			tcpopt->tcp_opt_mss = mss;
8789 			found |= TCP_OPT_MSS_PRESENT;
8790 
8791 			up += TCPOPT_MAXSEG_LEN;
8792 			continue;
8793 
8794 		case TCPOPT_WSCALE:
8795 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8796 				break;
8797 
8798 			if (up[2] > TCP_MAX_WINSHIFT)
8799 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8800 			else
8801 				tcpopt->tcp_opt_wscale = up[2];
8802 			found |= TCP_OPT_WSCALE_PRESENT;
8803 
8804 			up += TCPOPT_WS_LEN;
8805 			continue;
8806 
8807 		case TCPOPT_SACK_PERMITTED:
8808 			if (len < TCPOPT_SACK_OK_LEN ||
8809 			    up[1] != TCPOPT_SACK_OK_LEN)
8810 				break;
8811 			found |= TCP_OPT_SACK_OK_PRESENT;
8812 			up += TCPOPT_SACK_OK_LEN;
8813 			continue;
8814 
8815 		case TCPOPT_SACK:
8816 			if (len <= 2 || up[1] <= 2 || len < up[1])
8817 				break;
8818 
8819 			/* If TCP is not interested in SACK blks... */
8820 			if ((tcp = tcpopt->tcp) == NULL) {
8821 				up += up[1];
8822 				continue;
8823 			}
8824 			sack_len = up[1] - TCPOPT_HEADER_LEN;
8825 			up += TCPOPT_HEADER_LEN;
8826 
8827 			/*
8828 			 * If the list is empty, allocate one and assume
8829 			 * nothing is sack'ed.
8830 			 */
8831 			ASSERT(tcp->tcp_sack_info != NULL);
8832 			if (tcp->tcp_notsack_list == NULL) {
8833 				tcp_notsack_update(&(tcp->tcp_notsack_list),
8834 				    tcp->tcp_suna, tcp->tcp_snxt,
8835 				    &(tcp->tcp_num_notsack_blk),
8836 				    &(tcp->tcp_cnt_notsack_list));
8837 
8838 				/*
8839 				 * Make sure tcp_notsack_list is not NULL.
8840 				 * This happens when kmem_alloc(KM_NOSLEEP)
8841 				 * returns NULL.
8842 				 */
8843 				if (tcp->tcp_notsack_list == NULL) {
8844 					up += sack_len;
8845 					continue;
8846 				}
8847 				tcp->tcp_fack = tcp->tcp_suna;
8848 			}
8849 
8850 			while (sack_len > 0) {
8851 				if (up + 8 > endp) {
8852 					up = endp;
8853 					break;
8854 				}
8855 				sack_begin = BE32_TO_U32(up);
8856 				up += 4;
8857 				sack_end = BE32_TO_U32(up);
8858 				up += 4;
8859 				sack_len -= 8;
8860 				/*
8861 				 * Bounds checking.  Make sure the SACK
8862 				 * info is within tcp_suna and tcp_snxt.
8863 				 * If this SACK blk is out of bound, ignore
8864 				 * it but continue to parse the following
8865 				 * blks.
8866 				 */
8867 				if (SEQ_LEQ(sack_end, sack_begin) ||
8868 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
8869 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
8870 					continue;
8871 				}
8872 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
8873 				    sack_begin, sack_end,
8874 				    &(tcp->tcp_num_notsack_blk),
8875 				    &(tcp->tcp_cnt_notsack_list));
8876 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
8877 					tcp->tcp_fack = sack_end;
8878 				}
8879 			}
8880 			found |= TCP_OPT_SACK_PRESENT;
8881 			continue;
8882 
8883 		case TCPOPT_TSTAMP:
8884 			if (len < TCPOPT_TSTAMP_LEN ||
8885 			    up[1] != TCPOPT_TSTAMP_LEN)
8886 				break;
8887 
8888 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
8889 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
8890 
8891 			found |= TCP_OPT_TSTAMP_PRESENT;
8892 
8893 			up += TCPOPT_TSTAMP_LEN;
8894 			continue;
8895 
8896 		default:
8897 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
8898 				break;
8899 			up += up[1];
8900 			continue;
8901 		}
8902 		break;
8903 	}
8904 	return (found);
8905 }
8906 
8907 /*
8908  * Set the mss associated with a particular tcp based on its current value,
8909  * and a new one passed in. Observe minimums and maximums, and reset
8910  * other state variables that we want to view as multiples of mss.
8911  *
8912  * This function is called in various places mainly because
8913  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
8914  *    other side's SYN/SYN-ACK packet arrives.
8915  * 2) PMTUd may get us a new MSS.
8916  * 3) If the other side stops sending us timestamp option, we need to
8917  *    increase the MSS size to use the extra bytes available.
8918  */
8919 static void
8920 tcp_mss_set(tcp_t *tcp, uint32_t mss)
8921 {
8922 	uint32_t	mss_max;
8923 
8924 	if (tcp->tcp_ipversion == IPV4_VERSION)
8925 		mss_max = tcp_mss_max_ipv4;
8926 	else
8927 		mss_max = tcp_mss_max_ipv6;
8928 
8929 	if (mss < tcp_mss_min)
8930 		mss = tcp_mss_min;
8931 	if (mss > mss_max)
8932 		mss = mss_max;
8933 	/*
8934 	 * Unless naglim has been set by our client to
8935 	 * a non-mss value, force naglim to track mss.
8936 	 * This can help to aggregate small writes.
8937 	 */
8938 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
8939 		tcp->tcp_naglim = mss;
8940 	/*
8941 	 * TCP should be able to buffer at least 4 MSS data for obvious
8942 	 * performance reason.
8943 	 */
8944 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
8945 		tcp->tcp_xmit_hiwater = mss << 2;
8946 
8947 	/*
8948 	 * Check if we need to apply the tcp_init_cwnd here.  If
8949 	 * it is set and the MSS gets bigger (should not happen
8950 	 * normally), we need to adjust the resulting tcp_cwnd properly.
8951 	 * The new tcp_cwnd should not get bigger.
8952 	 */
8953 	if (tcp->tcp_init_cwnd == 0) {
8954 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
8955 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
8956 	} else {
8957 		if (tcp->tcp_mss < mss) {
8958 			tcp->tcp_cwnd = MAX(1,
8959 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
8960 		} else {
8961 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
8962 		}
8963 	}
8964 	tcp->tcp_mss = mss;
8965 	tcp->tcp_cwnd_cnt = 0;
8966 	(void) tcp_maxpsz_set(tcp, B_TRUE);
8967 }
8968 
8969 static int
8970 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8971 {
8972 	tcp_t		*tcp = NULL;
8973 	conn_t		*connp;
8974 	int		err;
8975 	dev_t		conn_dev;
8976 	zoneid_t	zoneid = getzoneid();
8977 
8978 	/*
8979 	 * Special case for install: miniroot needs to be able to access files
8980 	 * via NFS as though it were always in the global zone.
8981 	 */
8982 	if (credp == kcred && nfs_global_client_only != 0)
8983 		zoneid = GLOBAL_ZONEID;
8984 
8985 	if (q->q_ptr != NULL)
8986 		return (0);
8987 
8988 	if (sflag == MODOPEN) {
8989 		/*
8990 		 * This is a special case. The purpose of a modopen
8991 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
8992 		 * through for MIB browsers. Everything else is failed.
8993 		 */
8994 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
8995 
8996 		if (connp == NULL)
8997 			return (ENOMEM);
8998 
8999 		connp->conn_flags |= IPCL_TCPMOD;
9000 		connp->conn_cred = credp;
9001 		connp->conn_zoneid = zoneid;
9002 		q->q_ptr = WR(q)->q_ptr = connp;
9003 		crhold(credp);
9004 		q->q_qinfo = &tcp_mod_rinit;
9005 		WR(q)->q_qinfo = &tcp_mod_winit;
9006 		qprocson(q);
9007 		return (0);
9008 	}
9009 
9010 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
9011 		return (EBUSY);
9012 
9013 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9014 
9015 	if (flag & SO_ACCEPTOR) {
9016 		q->q_qinfo = &tcp_acceptor_rinit;
9017 		q->q_ptr = (void *)conn_dev;
9018 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9019 		WR(q)->q_ptr = (void *)conn_dev;
9020 		qprocson(q);
9021 		return (0);
9022 	}
9023 
9024 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9025 	if (connp == NULL) {
9026 		inet_minor_free(ip_minor_arena, conn_dev);
9027 		q->q_ptr = NULL;
9028 		return (ENOSR);
9029 	}
9030 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9031 	tcp = connp->conn_tcp;
9032 
9033 	q->q_ptr = WR(q)->q_ptr = connp;
9034 	if (getmajor(*devp) == TCP6_MAJ) {
9035 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9036 		connp->conn_send = ip_output_v6;
9037 		connp->conn_af_isv6 = B_TRUE;
9038 		connp->conn_pkt_isv6 = B_TRUE;
9039 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9040 		tcp->tcp_ipversion = IPV6_VERSION;
9041 		tcp->tcp_family = AF_INET6;
9042 		tcp->tcp_mss = tcp_mss_def_ipv6;
9043 	} else {
9044 		connp->conn_flags |= IPCL_TCP4;
9045 		connp->conn_send = ip_output;
9046 		connp->conn_af_isv6 = B_FALSE;
9047 		connp->conn_pkt_isv6 = B_FALSE;
9048 		tcp->tcp_ipversion = IPV4_VERSION;
9049 		tcp->tcp_family = AF_INET;
9050 		tcp->tcp_mss = tcp_mss_def_ipv4;
9051 	}
9052 
9053 	/*
9054 	 * TCP keeps a copy of cred for cache locality reasons but
9055 	 * we put a reference only once. If connp->conn_cred
9056 	 * becomes invalid, tcp_cred should also be set to NULL.
9057 	 */
9058 	tcp->tcp_cred = connp->conn_cred = credp;
9059 	crhold(connp->conn_cred);
9060 	tcp->tcp_cpid = curproc->p_pid;
9061 	connp->conn_zoneid = zoneid;
9062 
9063 	connp->conn_dev = conn_dev;
9064 
9065 	ASSERT(q->q_qinfo == &tcp_rinit);
9066 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9067 
9068 	if (flag & SO_SOCKSTR) {
9069 		/*
9070 		 * No need to insert a socket in tcp acceptor hash.
9071 		 * If it was a socket acceptor stream, we dealt with
9072 		 * it above. A socket listener can never accept a
9073 		 * connection and doesn't need acceptor_id.
9074 		 */
9075 		connp->conn_flags |= IPCL_SOCKET;
9076 		tcp->tcp_issocket = 1;
9077 		WR(q)->q_qinfo = &tcp_sock_winit;
9078 	} else {
9079 #ifdef	_ILP32
9080 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9081 #else
9082 		tcp->tcp_acceptor_id = conn_dev;
9083 #endif	/* _ILP32 */
9084 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9085 	}
9086 
9087 	if (tcp_trace)
9088 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9089 
9090 	err = tcp_init(tcp, q);
9091 	if (err != 0) {
9092 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9093 		tcp_acceptor_hash_remove(tcp);
9094 		CONN_DEC_REF(connp);
9095 		q->q_ptr = WR(q)->q_ptr = NULL;
9096 		return (err);
9097 	}
9098 
9099 	RD(q)->q_hiwat = tcp_recv_hiwat;
9100 	tcp->tcp_rwnd = tcp_recv_hiwat;
9101 
9102 	/* Non-zero default values */
9103 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9104 	/*
9105 	 * Put the ref for TCP. Ref for IP was already put
9106 	 * by ipcl_conn_create. Also Make the conn_t globally
9107 	 * visible to walkers
9108 	 */
9109 	mutex_enter(&connp->conn_lock);
9110 	CONN_INC_REF_LOCKED(connp);
9111 	ASSERT(connp->conn_ref == 2);
9112 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9113 	mutex_exit(&connp->conn_lock);
9114 
9115 	qprocson(q);
9116 	return (0);
9117 }
9118 
9119 /*
9120  * Some TCP options can be "set" by requesting them in the option
9121  * buffer. This is needed for XTI feature test though we do not
9122  * allow it in general. We interpret that this mechanism is more
9123  * applicable to OSI protocols and need not be allowed in general.
9124  * This routine filters out options for which it is not allowed (most)
9125  * and lets through those (few) for which it is. [ The XTI interface
9126  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9127  * ever implemented will have to be allowed here ].
9128  */
9129 static boolean_t
9130 tcp_allow_connopt_set(int level, int name)
9131 {
9132 
9133 	switch (level) {
9134 	case IPPROTO_TCP:
9135 		switch (name) {
9136 		case TCP_NODELAY:
9137 			return (B_TRUE);
9138 		default:
9139 			return (B_FALSE);
9140 		}
9141 		/*NOTREACHED*/
9142 	default:
9143 		return (B_FALSE);
9144 	}
9145 	/*NOTREACHED*/
9146 }
9147 
9148 /*
9149  * This routine gets default values of certain options whose default
9150  * values are maintained by protocol specific code
9151  */
9152 /* ARGSUSED */
9153 int
9154 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9155 {
9156 	int32_t	*i1 = (int32_t *)ptr;
9157 
9158 	switch (level) {
9159 	case IPPROTO_TCP:
9160 		switch (name) {
9161 		case TCP_NOTIFY_THRESHOLD:
9162 			*i1 = tcp_ip_notify_interval;
9163 			break;
9164 		case TCP_ABORT_THRESHOLD:
9165 			*i1 = tcp_ip_abort_interval;
9166 			break;
9167 		case TCP_CONN_NOTIFY_THRESHOLD:
9168 			*i1 = tcp_ip_notify_cinterval;
9169 			break;
9170 		case TCP_CONN_ABORT_THRESHOLD:
9171 			*i1 = tcp_ip_abort_cinterval;
9172 			break;
9173 		default:
9174 			return (-1);
9175 		}
9176 		break;
9177 	case IPPROTO_IP:
9178 		switch (name) {
9179 		case IP_TTL:
9180 			*i1 = tcp_ipv4_ttl;
9181 			break;
9182 		default:
9183 			return (-1);
9184 		}
9185 		break;
9186 	case IPPROTO_IPV6:
9187 		switch (name) {
9188 		case IPV6_UNICAST_HOPS:
9189 			*i1 = tcp_ipv6_hoplimit;
9190 			break;
9191 		default:
9192 			return (-1);
9193 		}
9194 		break;
9195 	default:
9196 		return (-1);
9197 	}
9198 	return (sizeof (int));
9199 }
9200 
9201 
9202 /*
9203  * TCP routine to get the values of options.
9204  */
9205 int
9206 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9207 {
9208 	int		*i1 = (int *)ptr;
9209 	conn_t		*connp = Q_TO_CONN(q);
9210 	tcp_t		*tcp = connp->conn_tcp;
9211 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9212 
9213 	switch (level) {
9214 	case SOL_SOCKET:
9215 		switch (name) {
9216 		case SO_LINGER:	{
9217 			struct linger *lgr = (struct linger *)ptr;
9218 
9219 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9220 			lgr->l_linger = tcp->tcp_lingertime;
9221 			}
9222 			return (sizeof (struct linger));
9223 		case SO_DEBUG:
9224 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9225 			break;
9226 		case SO_KEEPALIVE:
9227 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9228 			break;
9229 		case SO_DONTROUTE:
9230 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9231 			break;
9232 		case SO_USELOOPBACK:
9233 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9234 			break;
9235 		case SO_BROADCAST:
9236 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9237 			break;
9238 		case SO_REUSEADDR:
9239 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9240 			break;
9241 		case SO_OOBINLINE:
9242 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9243 			break;
9244 		case SO_DGRAM_ERRIND:
9245 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9246 			break;
9247 		case SO_TYPE:
9248 			*i1 = SOCK_STREAM;
9249 			break;
9250 		case SO_SNDBUF:
9251 			*i1 = tcp->tcp_xmit_hiwater;
9252 			break;
9253 		case SO_RCVBUF:
9254 			*i1 = RD(q)->q_hiwat;
9255 			break;
9256 		case SO_SND_COPYAVOID:
9257 			*i1 = tcp->tcp_snd_zcopy_on ?
9258 			    SO_SND_COPYAVOID : 0;
9259 			break;
9260 		default:
9261 			return (-1);
9262 		}
9263 		break;
9264 	case IPPROTO_TCP:
9265 		switch (name) {
9266 		case TCP_NODELAY:
9267 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9268 			break;
9269 		case TCP_MAXSEG:
9270 			*i1 = tcp->tcp_mss;
9271 			break;
9272 		case TCP_NOTIFY_THRESHOLD:
9273 			*i1 = (int)tcp->tcp_first_timer_threshold;
9274 			break;
9275 		case TCP_ABORT_THRESHOLD:
9276 			*i1 = tcp->tcp_second_timer_threshold;
9277 			break;
9278 		case TCP_CONN_NOTIFY_THRESHOLD:
9279 			*i1 = tcp->tcp_first_ctimer_threshold;
9280 			break;
9281 		case TCP_CONN_ABORT_THRESHOLD:
9282 			*i1 = tcp->tcp_second_ctimer_threshold;
9283 			break;
9284 		case TCP_RECVDSTADDR:
9285 			*i1 = tcp->tcp_recvdstaddr;
9286 			break;
9287 		case TCP_ANONPRIVBIND:
9288 			*i1 = tcp->tcp_anon_priv_bind;
9289 			break;
9290 		case TCP_EXCLBIND:
9291 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9292 			break;
9293 		case TCP_INIT_CWND:
9294 			*i1 = tcp->tcp_init_cwnd;
9295 			break;
9296 		case TCP_KEEPALIVE_THRESHOLD:
9297 			*i1 = tcp->tcp_ka_interval;
9298 			break;
9299 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9300 			*i1 = tcp->tcp_ka_abort_thres;
9301 			break;
9302 		case TCP_CORK:
9303 			*i1 = tcp->tcp_cork;
9304 			break;
9305 		default:
9306 			return (-1);
9307 		}
9308 		break;
9309 	case IPPROTO_IP:
9310 		if (tcp->tcp_family != AF_INET)
9311 			return (-1);
9312 		switch (name) {
9313 		case IP_OPTIONS:
9314 		case T_IP_OPTIONS: {
9315 			/*
9316 			 * This is compatible with BSD in that in only return
9317 			 * the reverse source route with the final destination
9318 			 * as the last entry. The first 4 bytes of the option
9319 			 * will contain the final destination.
9320 			 */
9321 			char	*opt_ptr;
9322 			int	opt_len;
9323 			opt_ptr = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
9324 			opt_len = (char *)tcp->tcp_tcph - opt_ptr;
9325 			/* Caller ensures enough space */
9326 			if (opt_len > 0) {
9327 				/*
9328 				 * TODO: Do we have to handle getsockopt on an
9329 				 * initiator as well?
9330 				 */
9331 				return (tcp_opt_get_user(tcp->tcp_ipha, ptr));
9332 			}
9333 			return (0);
9334 			}
9335 		case IP_TOS:
9336 		case T_IP_TOS:
9337 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9338 			break;
9339 		case IP_TTL:
9340 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9341 			break;
9342 		default:
9343 			return (-1);
9344 		}
9345 		break;
9346 	case IPPROTO_IPV6:
9347 		/*
9348 		 * IPPROTO_IPV6 options are only supported for sockets
9349 		 * that are using IPv6 on the wire.
9350 		 */
9351 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9352 			return (-1);
9353 		}
9354 		switch (name) {
9355 		case IPV6_UNICAST_HOPS:
9356 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9357 			break;	/* goto sizeof (int) option return */
9358 		case IPV6_BOUND_IF:
9359 			/* Zero if not set */
9360 			*i1 = tcp->tcp_bound_if;
9361 			break;	/* goto sizeof (int) option return */
9362 		case IPV6_RECVPKTINFO:
9363 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9364 				*i1 = 1;
9365 			else
9366 				*i1 = 0;
9367 			break;	/* goto sizeof (int) option return */
9368 		case IPV6_RECVTCLASS:
9369 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9370 				*i1 = 1;
9371 			else
9372 				*i1 = 0;
9373 			break;	/* goto sizeof (int) option return */
9374 		case IPV6_RECVHOPLIMIT:
9375 			if (tcp->tcp_ipv6_recvancillary &
9376 			    TCP_IPV6_RECVHOPLIMIT)
9377 				*i1 = 1;
9378 			else
9379 				*i1 = 0;
9380 			break;	/* goto sizeof (int) option return */
9381 		case IPV6_RECVHOPOPTS:
9382 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9383 				*i1 = 1;
9384 			else
9385 				*i1 = 0;
9386 			break;	/* goto sizeof (int) option return */
9387 		case IPV6_RECVDSTOPTS:
9388 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9389 				*i1 = 1;
9390 			else
9391 				*i1 = 0;
9392 			break;	/* goto sizeof (int) option return */
9393 		case _OLD_IPV6_RECVDSTOPTS:
9394 			if (tcp->tcp_ipv6_recvancillary &
9395 			    TCP_OLD_IPV6_RECVDSTOPTS)
9396 				*i1 = 1;
9397 			else
9398 				*i1 = 0;
9399 			break;	/* goto sizeof (int) option return */
9400 		case IPV6_RECVRTHDR:
9401 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9402 				*i1 = 1;
9403 			else
9404 				*i1 = 0;
9405 			break;	/* goto sizeof (int) option return */
9406 		case IPV6_RECVRTHDRDSTOPTS:
9407 			if (tcp->tcp_ipv6_recvancillary &
9408 			    TCP_IPV6_RECVRTDSTOPTS)
9409 				*i1 = 1;
9410 			else
9411 				*i1 = 0;
9412 			break;	/* goto sizeof (int) option return */
9413 		case IPV6_PKTINFO: {
9414 			/* XXX assumes that caller has room for max size! */
9415 			struct in6_pktinfo *pkti;
9416 
9417 			pkti = (struct in6_pktinfo *)ptr;
9418 			if (ipp->ipp_fields & IPPF_IFINDEX)
9419 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9420 			else
9421 				pkti->ipi6_ifindex = 0;
9422 			if (ipp->ipp_fields & IPPF_ADDR)
9423 				pkti->ipi6_addr = ipp->ipp_addr;
9424 			else
9425 				pkti->ipi6_addr = ipv6_all_zeros;
9426 			return (sizeof (struct in6_pktinfo));
9427 		}
9428 		case IPV6_TCLASS:
9429 			if (ipp->ipp_fields & IPPF_TCLASS)
9430 				*i1 = ipp->ipp_tclass;
9431 			else
9432 				*i1 = IPV6_FLOW_TCLASS(
9433 				    IPV6_DEFAULT_VERS_AND_FLOW);
9434 			break;	/* goto sizeof (int) option return */
9435 		case IPV6_NEXTHOP: {
9436 			sin6_t *sin6 = (sin6_t *)ptr;
9437 
9438 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9439 				return (0);
9440 			*sin6 = sin6_null;
9441 			sin6->sin6_family = AF_INET6;
9442 			sin6->sin6_addr = ipp->ipp_nexthop;
9443 			return (sizeof (sin6_t));
9444 		}
9445 		case IPV6_HOPOPTS:
9446 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9447 				return (0);
9448 			bcopy(ipp->ipp_hopopts, ptr, ipp->ipp_hopoptslen);
9449 			return (ipp->ipp_hopoptslen);
9450 		case IPV6_RTHDRDSTOPTS:
9451 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9452 				return (0);
9453 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9454 			return (ipp->ipp_rtdstoptslen);
9455 		case IPV6_RTHDR:
9456 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9457 				return (0);
9458 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9459 			return (ipp->ipp_rthdrlen);
9460 		case IPV6_DSTOPTS:
9461 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9462 				return (0);
9463 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9464 			return (ipp->ipp_dstoptslen);
9465 		case IPV6_SRC_PREFERENCES:
9466 			return (ip6_get_src_preferences(connp,
9467 			    (uint32_t *)ptr));
9468 		case IPV6_PATHMTU: {
9469 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9470 
9471 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9472 				return (-1);
9473 
9474 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9475 				connp->conn_fport, mtuinfo));
9476 		}
9477 		default:
9478 			return (-1);
9479 		}
9480 		break;
9481 	default:
9482 		return (-1);
9483 	}
9484 	return (sizeof (int));
9485 }
9486 
9487 /*
9488  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9489  * Parameters are assumed to be verified by the caller.
9490  */
9491 /* ARGSUSED */
9492 int
9493 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9494     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9495     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9496 {
9497 	tcp_t	*tcp = Q_TO_TCP(q);
9498 	int	*i1 = (int *)invalp;
9499 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9500 	boolean_t checkonly;
9501 	int	reterr;
9502 
9503 	switch (optset_context) {
9504 	case SETFN_OPTCOM_CHECKONLY:
9505 		checkonly = B_TRUE;
9506 		/*
9507 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9508 		 * inlen != 0 implies value supplied and
9509 		 * 	we have to "pretend" to set it.
9510 		 * inlen == 0 implies that there is no
9511 		 * 	value part in T_CHECK request and just validation
9512 		 * done elsewhere should be enough, we just return here.
9513 		 */
9514 		if (inlen == 0) {
9515 			*outlenp = 0;
9516 			return (0);
9517 		}
9518 		break;
9519 	case SETFN_OPTCOM_NEGOTIATE:
9520 		checkonly = B_FALSE;
9521 		break;
9522 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9523 	case SETFN_CONN_NEGOTIATE:
9524 		checkonly = B_FALSE;
9525 		/*
9526 		 * Negotiating local and "association-related" options
9527 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9528 		 * primitives is allowed by XTI, but we choose
9529 		 * to not implement this style negotiation for Internet
9530 		 * protocols (We interpret it is a must for OSI world but
9531 		 * optional for Internet protocols) for all options.
9532 		 * [ Will do only for the few options that enable test
9533 		 * suites that our XTI implementation of this feature
9534 		 * works for transports that do allow it ]
9535 		 */
9536 		if (!tcp_allow_connopt_set(level, name)) {
9537 			*outlenp = 0;
9538 			return (EINVAL);
9539 		}
9540 		break;
9541 	default:
9542 		/*
9543 		 * We should never get here
9544 		 */
9545 		*outlenp = 0;
9546 		return (EINVAL);
9547 	}
9548 
9549 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9550 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9551 
9552 	/*
9553 	 * For TCP, we should have no ancillary data sent down
9554 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9555 	 * has to be zero.
9556 	 */
9557 	ASSERT(thisdg_attrs == NULL);
9558 
9559 	/*
9560 	 * For fixed length options, no sanity check
9561 	 * of passed in length is done. It is assumed *_optcom_req()
9562 	 * routines do the right thing.
9563 	 */
9564 
9565 	switch (level) {
9566 	case SOL_SOCKET:
9567 		switch (name) {
9568 		case SO_LINGER: {
9569 			struct linger *lgr = (struct linger *)invalp;
9570 
9571 			if (!checkonly) {
9572 				if (lgr->l_onoff) {
9573 					tcp->tcp_linger = 1;
9574 					tcp->tcp_lingertime = lgr->l_linger;
9575 				} else {
9576 					tcp->tcp_linger = 0;
9577 					tcp->tcp_lingertime = 0;
9578 				}
9579 				/* struct copy */
9580 				*(struct linger *)outvalp = *lgr;
9581 			} else {
9582 				if (!lgr->l_onoff) {
9583 				    ((struct linger *)outvalp)->l_onoff = 0;
9584 				    ((struct linger *)outvalp)->l_linger = 0;
9585 				} else {
9586 				    /* struct copy */
9587 				    *(struct linger *)outvalp = *lgr;
9588 				}
9589 			}
9590 			*outlenp = sizeof (struct linger);
9591 			return (0);
9592 		}
9593 		case SO_DEBUG:
9594 			if (!checkonly)
9595 				tcp->tcp_debug = onoff;
9596 			break;
9597 		case SO_KEEPALIVE:
9598 			if (checkonly) {
9599 				/* T_CHECK case */
9600 				break;
9601 			}
9602 
9603 			if (!onoff) {
9604 				if (tcp->tcp_ka_enabled) {
9605 					if (tcp->tcp_ka_tid != 0) {
9606 						(void) TCP_TIMER_CANCEL(tcp,
9607 						    tcp->tcp_ka_tid);
9608 						tcp->tcp_ka_tid = 0;
9609 					}
9610 					tcp->tcp_ka_enabled = 0;
9611 				}
9612 				break;
9613 			}
9614 			if (!tcp->tcp_ka_enabled) {
9615 				/* Crank up the keepalive timer */
9616 				tcp->tcp_ka_last_intrvl = 0;
9617 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9618 				    tcp_keepalive_killer,
9619 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
9620 				tcp->tcp_ka_enabled = 1;
9621 			}
9622 			break;
9623 		case SO_DONTROUTE:
9624 			/*
9625 			 * SO_DONTROUTE, SO_USELOOPBACK and SO_BROADCAST are
9626 			 * only of interest to IP.  We track them here only so
9627 			 * that we can report their current value.
9628 			 */
9629 			if (!checkonly) {
9630 				tcp->tcp_dontroute = onoff;
9631 				tcp->tcp_connp->conn_dontroute = onoff;
9632 			}
9633 			break;
9634 		case SO_USELOOPBACK:
9635 			if (!checkonly) {
9636 				tcp->tcp_useloopback = onoff;
9637 				tcp->tcp_connp->conn_loopback = onoff;
9638 			}
9639 			break;
9640 		case SO_BROADCAST:
9641 			if (!checkonly) {
9642 				tcp->tcp_broadcast = onoff;
9643 				tcp->tcp_connp->conn_broadcast = onoff;
9644 			}
9645 			break;
9646 		case SO_REUSEADDR:
9647 			if (!checkonly) {
9648 				tcp->tcp_reuseaddr = onoff;
9649 				tcp->tcp_connp->conn_reuseaddr = onoff;
9650 			}
9651 			break;
9652 		case SO_OOBINLINE:
9653 			if (!checkonly)
9654 				tcp->tcp_oobinline = onoff;
9655 			break;
9656 		case SO_DGRAM_ERRIND:
9657 			if (!checkonly)
9658 				tcp->tcp_dgram_errind = onoff;
9659 			break;
9660 		case SO_SNDBUF: {
9661 			tcp_t *peer_tcp;
9662 
9663 			if (*i1 > tcp_max_buf) {
9664 				*outlenp = 0;
9665 				return (ENOBUFS);
9666 			}
9667 			if (checkonly)
9668 				break;
9669 
9670 			tcp->tcp_xmit_hiwater = *i1;
9671 			if (tcp_snd_lowat_fraction != 0)
9672 				tcp->tcp_xmit_lowater =
9673 				    tcp->tcp_xmit_hiwater /
9674 				    tcp_snd_lowat_fraction;
9675 			(void) tcp_maxpsz_set(tcp, B_TRUE);
9676 			/*
9677 			 * If we are flow-controlled, recheck the condition.
9678 			 * There are apps that increase SO_SNDBUF size when
9679 			 * flow-controlled (EWOULDBLOCK), and expect the flow
9680 			 * control condition to be lifted right away.
9681 			 *
9682 			 * For the fused tcp loopback case, in order to avoid
9683 			 * a race with the peer's tcp_fuse_rrw() we need to
9684 			 * hold its fuse_lock while accessing tcp_flow_stopped.
9685 			 */
9686 			peer_tcp = tcp->tcp_loopback_peer;
9687 			ASSERT(!tcp->tcp_fused || peer_tcp != NULL);
9688 			if (tcp->tcp_fused)
9689 				mutex_enter(&peer_tcp->tcp_fuse_lock);
9690 
9691 			if (tcp->tcp_flow_stopped &&
9692 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
9693 				tcp_clrqfull(tcp);
9694 			}
9695 			if (tcp->tcp_fused)
9696 				mutex_exit(&peer_tcp->tcp_fuse_lock);
9697 			break;
9698 		}
9699 		case SO_RCVBUF:
9700 			if (*i1 > tcp_max_buf) {
9701 				*outlenp = 0;
9702 				return (ENOBUFS);
9703 			}
9704 			/* Silently ignore zero */
9705 			if (!checkonly && *i1 != 0) {
9706 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
9707 				(void) tcp_rwnd_set(tcp, *i1);
9708 			}
9709 			/*
9710 			 * XXX should we return the rwnd here
9711 			 * and tcp_opt_get ?
9712 			 */
9713 			break;
9714 		case SO_SND_COPYAVOID:
9715 			if (!checkonly) {
9716 				/* we only allow enable at most once for now */
9717 				if (tcp->tcp_loopback ||
9718 				    (!tcp->tcp_snd_zcopy_aware &&
9719 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
9720 					*outlenp = 0;
9721 					return (EOPNOTSUPP);
9722 				}
9723 				tcp->tcp_snd_zcopy_aware = 1;
9724 			}
9725 			break;
9726 		default:
9727 			*outlenp = 0;
9728 			return (EINVAL);
9729 		}
9730 		break;
9731 	case IPPROTO_TCP:
9732 		switch (name) {
9733 		case TCP_NODELAY:
9734 			if (!checkonly)
9735 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
9736 			break;
9737 		case TCP_NOTIFY_THRESHOLD:
9738 			if (!checkonly)
9739 				tcp->tcp_first_timer_threshold = *i1;
9740 			break;
9741 		case TCP_ABORT_THRESHOLD:
9742 			if (!checkonly)
9743 				tcp->tcp_second_timer_threshold = *i1;
9744 			break;
9745 		case TCP_CONN_NOTIFY_THRESHOLD:
9746 			if (!checkonly)
9747 				tcp->tcp_first_ctimer_threshold = *i1;
9748 			break;
9749 		case TCP_CONN_ABORT_THRESHOLD:
9750 			if (!checkonly)
9751 				tcp->tcp_second_ctimer_threshold = *i1;
9752 			break;
9753 		case TCP_RECVDSTADDR:
9754 			if (tcp->tcp_state > TCPS_LISTEN)
9755 				return (EOPNOTSUPP);
9756 			if (!checkonly)
9757 				tcp->tcp_recvdstaddr = onoff;
9758 			break;
9759 		case TCP_ANONPRIVBIND:
9760 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
9761 				*outlenp = 0;
9762 				return (reterr);
9763 			}
9764 			if (!checkonly) {
9765 				tcp->tcp_anon_priv_bind = onoff;
9766 			}
9767 			break;
9768 		case TCP_EXCLBIND:
9769 			if (!checkonly)
9770 				tcp->tcp_exclbind = onoff;
9771 			break;	/* goto sizeof (int) option return */
9772 		case TCP_INIT_CWND: {
9773 			uint32_t init_cwnd = *((uint32_t *)invalp);
9774 
9775 			if (checkonly)
9776 				break;
9777 
9778 			/*
9779 			 * Only allow socket with network configuration
9780 			 * privilege to set the initial cwnd to be larger
9781 			 * than allowed by RFC 3390.
9782 			 */
9783 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
9784 				tcp->tcp_init_cwnd = init_cwnd;
9785 				break;
9786 			}
9787 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
9788 				*outlenp = 0;
9789 				return (reterr);
9790 			}
9791 			if (init_cwnd > TCP_MAX_INIT_CWND) {
9792 				*outlenp = 0;
9793 				return (EINVAL);
9794 			}
9795 			tcp->tcp_init_cwnd = init_cwnd;
9796 			break;
9797 		}
9798 		case TCP_KEEPALIVE_THRESHOLD:
9799 			if (checkonly)
9800 				break;
9801 
9802 			if (*i1 < tcp_keepalive_interval_low ||
9803 			    *i1 > tcp_keepalive_interval_high) {
9804 				*outlenp = 0;
9805 				return (EINVAL);
9806 			}
9807 			if (*i1 != tcp->tcp_ka_interval) {
9808 				tcp->tcp_ka_interval = *i1;
9809 				/*
9810 				 * Check if we need to restart the
9811 				 * keepalive timer.
9812 				 */
9813 				if (tcp->tcp_ka_tid != 0) {
9814 					ASSERT(tcp->tcp_ka_enabled);
9815 					(void) TCP_TIMER_CANCEL(tcp,
9816 					    tcp->tcp_ka_tid);
9817 					tcp->tcp_ka_last_intrvl = 0;
9818 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
9819 					    tcp_keepalive_killer,
9820 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
9821 				}
9822 			}
9823 			break;
9824 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9825 			if (!checkonly) {
9826 				if (*i1 < tcp_keepalive_abort_interval_low ||
9827 				    *i1 > tcp_keepalive_abort_interval_high) {
9828 					*outlenp = 0;
9829 					return (EINVAL);
9830 				}
9831 				tcp->tcp_ka_abort_thres = *i1;
9832 			}
9833 			break;
9834 		case TCP_CORK:
9835 			if (!checkonly) {
9836 				/*
9837 				 * if tcp->tcp_cork was set and is now
9838 				 * being unset, we have to make sure that
9839 				 * the remaining data gets sent out. Also
9840 				 * unset tcp->tcp_cork so that tcp_wput_data()
9841 				 * can send data even if it is less than mss
9842 				 */
9843 				if (tcp->tcp_cork && onoff == 0 &&
9844 				    tcp->tcp_unsent > 0) {
9845 					tcp->tcp_cork = B_FALSE;
9846 					tcp_wput_data(tcp, NULL, B_FALSE);
9847 				}
9848 				tcp->tcp_cork = onoff;
9849 			}
9850 			break;
9851 		default:
9852 			*outlenp = 0;
9853 			return (EINVAL);
9854 		}
9855 		break;
9856 	case IPPROTO_IP:
9857 		if (tcp->tcp_family != AF_INET) {
9858 			*outlenp = 0;
9859 			return (ENOPROTOOPT);
9860 		}
9861 		switch (name) {
9862 		case IP_OPTIONS:
9863 		case T_IP_OPTIONS:
9864 			reterr = tcp_opt_set_header(tcp, checkonly,
9865 			    invalp, inlen);
9866 			if (reterr) {
9867 				*outlenp = 0;
9868 				return (reterr);
9869 			}
9870 			/* OK return - copy input buffer into output buffer */
9871 			if (invalp != outvalp) {
9872 				/* don't trust bcopy for identical src/dst */
9873 				bcopy(invalp, outvalp, inlen);
9874 			}
9875 			*outlenp = inlen;
9876 			return (0);
9877 		case IP_TOS:
9878 		case T_IP_TOS:
9879 			if (!checkonly) {
9880 				tcp->tcp_ipha->ipha_type_of_service =
9881 				    (uchar_t)*i1;
9882 				tcp->tcp_tos = (uchar_t)*i1;
9883 			}
9884 			break;
9885 		case IP_TTL:
9886 			if (!checkonly) {
9887 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
9888 				tcp->tcp_ttl = (uchar_t)*i1;
9889 			}
9890 			break;
9891 		case IP_BOUND_IF:
9892 			/* Handled at the IP level */
9893 			return (-EINVAL);
9894 		case IP_SEC_OPT:
9895 			/*
9896 			 * We should not allow policy setting after
9897 			 * we start listening for connections.
9898 			 */
9899 			if (tcp->tcp_state == TCPS_LISTEN) {
9900 				return (EINVAL);
9901 			} else {
9902 				/* Handled at the IP level */
9903 				return (-EINVAL);
9904 			}
9905 		default:
9906 			*outlenp = 0;
9907 			return (EINVAL);
9908 		}
9909 		break;
9910 	case IPPROTO_IPV6: {
9911 		ip6_pkt_t		*ipp;
9912 
9913 		/*
9914 		 * IPPROTO_IPV6 options are only supported for sockets
9915 		 * that are using IPv6 on the wire.
9916 		 */
9917 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9918 			*outlenp = 0;
9919 			return (ENOPROTOOPT);
9920 		}
9921 		/*
9922 		 * Only sticky options; no ancillary data
9923 		 */
9924 		ASSERT(thisdg_attrs == NULL);
9925 		ipp = &tcp->tcp_sticky_ipp;
9926 
9927 		switch (name) {
9928 		case IPV6_UNICAST_HOPS:
9929 			/* -1 means use default */
9930 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
9931 				*outlenp = 0;
9932 				return (EINVAL);
9933 			}
9934 			if (!checkonly) {
9935 				if (*i1 == -1) {
9936 					tcp->tcp_ip6h->ip6_hops =
9937 					    ipp->ipp_unicast_hops =
9938 					    (uint8_t)tcp_ipv6_hoplimit;
9939 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
9940 					/* Pass modified value to IP. */
9941 					*i1 = tcp->tcp_ip6h->ip6_hops;
9942 				} else {
9943 					tcp->tcp_ip6h->ip6_hops =
9944 					    ipp->ipp_unicast_hops =
9945 					    (uint8_t)*i1;
9946 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
9947 				}
9948 				reterr = tcp_build_hdrs(q, tcp);
9949 				if (reterr != 0)
9950 					return (reterr);
9951 			}
9952 			break;
9953 		case IPV6_BOUND_IF:
9954 			if (!checkonly) {
9955 				int error = 0;
9956 
9957 				tcp->tcp_bound_if = *i1;
9958 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
9959 				    B_TRUE, checkonly, level, name, mblk);
9960 				if (error != 0) {
9961 					*outlenp = 0;
9962 					return (error);
9963 				}
9964 			}
9965 			break;
9966 		/*
9967 		 * Set boolean switches for ancillary data delivery
9968 		 */
9969 		case IPV6_RECVPKTINFO:
9970 			if (!checkonly) {
9971 				if (onoff)
9972 					tcp->tcp_ipv6_recvancillary |=
9973 					    TCP_IPV6_RECVPKTINFO;
9974 				else
9975 					tcp->tcp_ipv6_recvancillary &=
9976 					    ~TCP_IPV6_RECVPKTINFO;
9977 				/* Force it to be sent up with the next msg */
9978 				tcp->tcp_recvifindex = 0;
9979 			}
9980 			break;
9981 		case IPV6_RECVTCLASS:
9982 			if (!checkonly) {
9983 				if (onoff)
9984 					tcp->tcp_ipv6_recvancillary |=
9985 					    TCP_IPV6_RECVTCLASS;
9986 				else
9987 					tcp->tcp_ipv6_recvancillary &=
9988 					    ~TCP_IPV6_RECVTCLASS;
9989 			}
9990 			break;
9991 		case IPV6_RECVHOPLIMIT:
9992 			if (!checkonly) {
9993 				if (onoff)
9994 					tcp->tcp_ipv6_recvancillary |=
9995 					    TCP_IPV6_RECVHOPLIMIT;
9996 				else
9997 					tcp->tcp_ipv6_recvancillary &=
9998 					    ~TCP_IPV6_RECVHOPLIMIT;
9999 				/* Force it to be sent up with the next msg */
10000 				tcp->tcp_recvhops = 0xffffffffU;
10001 			}
10002 			break;
10003 		case IPV6_RECVHOPOPTS:
10004 			if (!checkonly) {
10005 				if (onoff)
10006 					tcp->tcp_ipv6_recvancillary |=
10007 					    TCP_IPV6_RECVHOPOPTS;
10008 				else
10009 					tcp->tcp_ipv6_recvancillary &=
10010 					    ~TCP_IPV6_RECVHOPOPTS;
10011 			}
10012 			break;
10013 		case IPV6_RECVDSTOPTS:
10014 			if (!checkonly) {
10015 				if (onoff)
10016 					tcp->tcp_ipv6_recvancillary |=
10017 					    TCP_IPV6_RECVDSTOPTS;
10018 				else
10019 					tcp->tcp_ipv6_recvancillary &=
10020 					    ~TCP_IPV6_RECVDSTOPTS;
10021 			}
10022 			break;
10023 		case _OLD_IPV6_RECVDSTOPTS:
10024 			if (!checkonly) {
10025 				if (onoff)
10026 					tcp->tcp_ipv6_recvancillary |=
10027 					    TCP_OLD_IPV6_RECVDSTOPTS;
10028 				else
10029 					tcp->tcp_ipv6_recvancillary &=
10030 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10031 			}
10032 			break;
10033 		case IPV6_RECVRTHDR:
10034 			if (!checkonly) {
10035 				if (onoff)
10036 					tcp->tcp_ipv6_recvancillary |=
10037 					    TCP_IPV6_RECVRTHDR;
10038 				else
10039 					tcp->tcp_ipv6_recvancillary &=
10040 					    ~TCP_IPV6_RECVRTHDR;
10041 			}
10042 			break;
10043 		case IPV6_RECVRTHDRDSTOPTS:
10044 			if (!checkonly) {
10045 				if (onoff)
10046 					tcp->tcp_ipv6_recvancillary |=
10047 					    TCP_IPV6_RECVRTDSTOPTS;
10048 				else
10049 					tcp->tcp_ipv6_recvancillary &=
10050 					    ~TCP_IPV6_RECVRTDSTOPTS;
10051 			}
10052 			break;
10053 		case IPV6_PKTINFO:
10054 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10055 				return (EINVAL);
10056 			if (checkonly)
10057 				break;
10058 
10059 			if (inlen == 0) {
10060 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10061 			} else {
10062 				struct in6_pktinfo *pkti;
10063 
10064 				pkti = (struct in6_pktinfo *)invalp;
10065 				/*
10066 				 * RFC 3542 states that ipi6_addr must be
10067 				 * the unspecified address when setting the
10068 				 * IPV6_PKTINFO sticky socket option on a
10069 				 * TCP socket.
10070 				 */
10071 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10072 					return (EINVAL);
10073 				/*
10074 				 * ip6_set_pktinfo() validates the source
10075 				 * address and interface index.
10076 				 */
10077 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10078 				    pkti, mblk);
10079 				if (reterr != 0)
10080 					return (reterr);
10081 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10082 				ipp->ipp_addr = pkti->ipi6_addr;
10083 				if (ipp->ipp_ifindex != 0)
10084 					ipp->ipp_fields |= IPPF_IFINDEX;
10085 				else
10086 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10087 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10088 					ipp->ipp_fields |= IPPF_ADDR;
10089 				else
10090 					ipp->ipp_fields &= ~IPPF_ADDR;
10091 			}
10092 			reterr = tcp_build_hdrs(q, tcp);
10093 			if (reterr != 0)
10094 				return (reterr);
10095 			break;
10096 		case IPV6_TCLASS:
10097 			if (inlen != 0 && inlen != sizeof (int))
10098 				return (EINVAL);
10099 			if (checkonly)
10100 				break;
10101 
10102 			if (inlen == 0) {
10103 				ipp->ipp_fields &= ~IPPF_TCLASS;
10104 			} else {
10105 				if (*i1 > 255 || *i1 < -1)
10106 					return (EINVAL);
10107 				if (*i1 == -1) {
10108 					ipp->ipp_tclass = 0;
10109 					*i1 = 0;
10110 				} else {
10111 					ipp->ipp_tclass = *i1;
10112 				}
10113 				ipp->ipp_fields |= IPPF_TCLASS;
10114 			}
10115 			reterr = tcp_build_hdrs(q, tcp);
10116 			if (reterr != 0)
10117 				return (reterr);
10118 			break;
10119 		case IPV6_NEXTHOP:
10120 			/*
10121 			 * IP will verify that the nexthop is reachable
10122 			 * and fail for sticky options.
10123 			 */
10124 			if (inlen != 0 && inlen != sizeof (sin6_t))
10125 				return (EINVAL);
10126 			if (checkonly)
10127 				break;
10128 
10129 			if (inlen == 0) {
10130 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10131 			} else {
10132 				sin6_t *sin6 = (sin6_t *)invalp;
10133 
10134 				if (sin6->sin6_family != AF_INET6)
10135 					return (EAFNOSUPPORT);
10136 				if (IN6_IS_ADDR_V4MAPPED(
10137 				    &sin6->sin6_addr))
10138 					return (EADDRNOTAVAIL);
10139 				ipp->ipp_nexthop = sin6->sin6_addr;
10140 				if (!IN6_IS_ADDR_UNSPECIFIED(
10141 				    &ipp->ipp_nexthop))
10142 					ipp->ipp_fields |= IPPF_NEXTHOP;
10143 				else
10144 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10145 			}
10146 			reterr = tcp_build_hdrs(q, tcp);
10147 			if (reterr != 0)
10148 				return (reterr);
10149 			break;
10150 		case IPV6_HOPOPTS: {
10151 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10152 			/*
10153 			 * Sanity checks - minimum size, size a multiple of
10154 			 * eight bytes, and matching size passed in.
10155 			 */
10156 			if (inlen != 0 &&
10157 			    inlen != (8 * (hopts->ip6h_len + 1)))
10158 				return (EINVAL);
10159 
10160 			if (checkonly)
10161 				break;
10162 
10163 			if (inlen == 0) {
10164 				if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
10165 					kmem_free(ipp->ipp_hopopts,
10166 					    ipp->ipp_hopoptslen);
10167 					ipp->ipp_hopopts = NULL;
10168 					ipp->ipp_hopoptslen = 0;
10169 				}
10170 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10171 			} else {
10172 				reterr = tcp_pkt_set(invalp, inlen,
10173 				    (uchar_t **)&ipp->ipp_hopopts,
10174 				    &ipp->ipp_hopoptslen);
10175 				if (reterr != 0)
10176 					return (reterr);
10177 				ipp->ipp_fields |= IPPF_HOPOPTS;
10178 			}
10179 			reterr = tcp_build_hdrs(q, tcp);
10180 			if (reterr != 0)
10181 				return (reterr);
10182 			break;
10183 		}
10184 		case IPV6_RTHDRDSTOPTS: {
10185 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10186 
10187 			/*
10188 			 * Sanity checks - minimum size, size a multiple of
10189 			 * eight bytes, and matching size passed in.
10190 			 */
10191 			if (inlen != 0 &&
10192 			    inlen != (8 * (dopts->ip6d_len + 1)))
10193 				return (EINVAL);
10194 
10195 			if (checkonly)
10196 				break;
10197 
10198 			if (inlen == 0) {
10199 				if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
10200 					kmem_free(ipp->ipp_rtdstopts,
10201 					    ipp->ipp_rtdstoptslen);
10202 					ipp->ipp_rtdstopts = NULL;
10203 					ipp->ipp_rtdstoptslen = 0;
10204 				}
10205 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10206 			} else {
10207 				reterr = tcp_pkt_set(invalp, inlen,
10208 				    (uchar_t **)&ipp->ipp_rtdstopts,
10209 				    &ipp->ipp_rtdstoptslen);
10210 				if (reterr != 0)
10211 					return (reterr);
10212 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10213 			}
10214 			reterr = tcp_build_hdrs(q, tcp);
10215 			if (reterr != 0)
10216 				return (reterr);
10217 			break;
10218 		}
10219 		case IPV6_DSTOPTS: {
10220 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10221 
10222 			/*
10223 			 * Sanity checks - minimum size, size a multiple of
10224 			 * eight bytes, and matching size passed in.
10225 			 */
10226 			if (inlen != 0 &&
10227 			    inlen != (8 * (dopts->ip6d_len + 1)))
10228 				return (EINVAL);
10229 
10230 			if (checkonly)
10231 				break;
10232 
10233 			if (inlen == 0) {
10234 				if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
10235 					kmem_free(ipp->ipp_dstopts,
10236 					    ipp->ipp_dstoptslen);
10237 					ipp->ipp_dstopts = NULL;
10238 					ipp->ipp_dstoptslen = 0;
10239 				}
10240 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10241 			} else {
10242 				reterr = tcp_pkt_set(invalp, inlen,
10243 				    (uchar_t **)&ipp->ipp_dstopts,
10244 				    &ipp->ipp_dstoptslen);
10245 				if (reterr != 0)
10246 					return (reterr);
10247 				ipp->ipp_fields |= IPPF_DSTOPTS;
10248 			}
10249 			reterr = tcp_build_hdrs(q, tcp);
10250 			if (reterr != 0)
10251 				return (reterr);
10252 			break;
10253 		}
10254 		case IPV6_RTHDR: {
10255 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10256 
10257 			/*
10258 			 * Sanity checks - minimum size, size a multiple of
10259 			 * eight bytes, and matching size passed in.
10260 			 */
10261 			if (inlen != 0 &&
10262 			    inlen != (8 * (rt->ip6r_len + 1)))
10263 				return (EINVAL);
10264 
10265 			if (checkonly)
10266 				break;
10267 
10268 			if (inlen == 0) {
10269 				if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
10270 					kmem_free(ipp->ipp_rthdr,
10271 					    ipp->ipp_rthdrlen);
10272 					ipp->ipp_rthdr = NULL;
10273 					ipp->ipp_rthdrlen = 0;
10274 				}
10275 				ipp->ipp_fields &= ~IPPF_RTHDR;
10276 			} else {
10277 				reterr = tcp_pkt_set(invalp, inlen,
10278 				    (uchar_t **)&ipp->ipp_rthdr,
10279 				    &ipp->ipp_rthdrlen);
10280 				if (reterr != 0)
10281 					return (reterr);
10282 				ipp->ipp_fields |= IPPF_RTHDR;
10283 			}
10284 			reterr = tcp_build_hdrs(q, tcp);
10285 			if (reterr != 0)
10286 				return (reterr);
10287 			break;
10288 		}
10289 		case IPV6_V6ONLY:
10290 			if (!checkonly)
10291 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10292 			break;
10293 		case IPV6_USE_MIN_MTU:
10294 			if (inlen != sizeof (int))
10295 				return (EINVAL);
10296 
10297 			if (*i1 < -1 || *i1 > 1)
10298 				return (EINVAL);
10299 
10300 			if (checkonly)
10301 				break;
10302 
10303 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10304 			ipp->ipp_use_min_mtu = *i1;
10305 			break;
10306 		case IPV6_BOUND_PIF:
10307 			/* Handled at the IP level */
10308 			return (-EINVAL);
10309 		case IPV6_SEC_OPT:
10310 			/*
10311 			 * We should not allow policy setting after
10312 			 * we start listening for connections.
10313 			 */
10314 			if (tcp->tcp_state == TCPS_LISTEN) {
10315 				return (EINVAL);
10316 			} else {
10317 				/* Handled at the IP level */
10318 				return (-EINVAL);
10319 			}
10320 		case IPV6_SRC_PREFERENCES:
10321 			if (inlen != sizeof (uint32_t))
10322 				return (EINVAL);
10323 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10324 			    *(uint32_t *)invalp);
10325 			if (reterr != 0) {
10326 				*outlenp = 0;
10327 				return (reterr);
10328 			}
10329 			break;
10330 		default:
10331 			*outlenp = 0;
10332 			return (EINVAL);
10333 		}
10334 		break;
10335 	}		/* end IPPROTO_IPV6 */
10336 	default:
10337 		*outlenp = 0;
10338 		return (EINVAL);
10339 	}
10340 	/*
10341 	 * Common case of OK return with outval same as inval
10342 	 */
10343 	if (invalp != outvalp) {
10344 		/* don't trust bcopy for identical src/dst */
10345 		(void) bcopy(invalp, outvalp, inlen);
10346 	}
10347 	*outlenp = inlen;
10348 	return (0);
10349 }
10350 
10351 /*
10352  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10353  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10354  * headers, and the maximum size tcp header (to avoid reallocation
10355  * on the fly for additional tcp options).
10356  * Returns failure if can't allocate memory.
10357  */
10358 static int
10359 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
10360 {
10361 	char	*hdrs;
10362 	uint_t	hdrs_len;
10363 	ip6i_t	*ip6i;
10364 	char	buf[TCP_MAX_HDR_LENGTH];
10365 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10366 	in6_addr_t src, dst;
10367 
10368 	/*
10369 	 * save the existing tcp header and source/dest IP addresses
10370 	 */
10371 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10372 	src = tcp->tcp_ip6h->ip6_src;
10373 	dst = tcp->tcp_ip6h->ip6_dst;
10374 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10375 	ASSERT(hdrs_len != 0);
10376 	if (hdrs_len > tcp->tcp_iphc_len) {
10377 		/* Need to reallocate */
10378 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10379 		if (hdrs == NULL)
10380 			return (ENOMEM);
10381 		if (tcp->tcp_iphc != NULL) {
10382 			if (tcp->tcp_hdr_grown) {
10383 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10384 			} else {
10385 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10386 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10387 			}
10388 			tcp->tcp_iphc_len = 0;
10389 		}
10390 		ASSERT(tcp->tcp_iphc_len == 0);
10391 		tcp->tcp_iphc = hdrs;
10392 		tcp->tcp_iphc_len = hdrs_len;
10393 		tcp->tcp_hdr_grown = B_TRUE;
10394 	}
10395 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10396 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10397 
10398 	/* Set header fields not in ipp */
10399 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10400 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10401 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10402 	} else {
10403 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10404 	}
10405 	/*
10406 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10407 	 *
10408 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10409 	 */
10410 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10411 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10412 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10413 
10414 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10415 
10416 	tcp->tcp_ip6h->ip6_src = src;
10417 	tcp->tcp_ip6h->ip6_dst = dst;
10418 
10419 	/*
10420 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10421 	 * the default value for TCP.
10422 	 */
10423 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10424 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
10425 
10426 	/*
10427 	 * If we're setting extension headers after a connection
10428 	 * has been established, and if we have a routing header
10429 	 * among the extension headers, call ip_massage_options_v6 to
10430 	 * manipulate the routing header/ip6_dst set the checksum
10431 	 * difference in the tcp header template.
10432 	 * (This happens in tcp_connect_ipv6 if the routing header
10433 	 * is set prior to the connect.)
10434 	 * Set the tcp_sum to zero first in case we've cleared a
10435 	 * routing header or don't have one at all.
10436 	 */
10437 	tcp->tcp_sum = 0;
10438 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10439 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10440 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10441 		    (uint8_t *)tcp->tcp_tcph);
10442 		if (rth != NULL) {
10443 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10444 			    rth);
10445 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10446 			    (tcp->tcp_sum >> 16));
10447 		}
10448 	}
10449 
10450 	/* Try to get everything in a single mblk */
10451 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
10452 	return (0);
10453 }
10454 
10455 /*
10456  * Set optbuf and optlen for the option.
10457  * Allocate memory (if not already present).
10458  * Otherwise just point optbuf and optlen at invalp and inlen.
10459  * Returns failure if memory can not be allocated.
10460  */
10461 static int
10462 tcp_pkt_set(uchar_t *invalp, uint_t inlen, uchar_t **optbufp, uint_t *optlenp)
10463 {
10464 	uchar_t *optbuf;
10465 
10466 	if (inlen == *optlenp) {
10467 		/* Unchanged length - no need to realocate */
10468 		bcopy(invalp, *optbufp, inlen);
10469 		return (0);
10470 	}
10471 	if (inlen != 0) {
10472 		/* Allocate new buffer before free */
10473 		optbuf = kmem_alloc(inlen, KM_NOSLEEP);
10474 		if (optbuf == NULL)
10475 			return (ENOMEM);
10476 	} else {
10477 		optbuf = NULL;
10478 	}
10479 	/* Free old buffer */
10480 	if (*optlenp != 0)
10481 		kmem_free(*optbufp, *optlenp);
10482 
10483 	bcopy(invalp, optbuf, inlen);
10484 	*optbufp = optbuf;
10485 	*optlenp = inlen;
10486 	return (0);
10487 }
10488 
10489 
10490 /*
10491  * Use the outgoing IP header to create an IP_OPTIONS option the way
10492  * it was passed down from the application.
10493  */
10494 static int
10495 tcp_opt_get_user(ipha_t *ipha, uchar_t *buf)
10496 {
10497 	ipoptp_t	opts;
10498 	uchar_t		*opt;
10499 	uint8_t		optval;
10500 	uint8_t		optlen;
10501 	uint32_t	len = 0;
10502 	uchar_t	*buf1 = buf;
10503 
10504 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
10505 	len += IP_ADDR_LEN;
10506 	bzero(buf1, IP_ADDR_LEN);
10507 
10508 	for (optval = ipoptp_first(&opts, ipha);
10509 	    optval != IPOPT_EOL;
10510 	    optval = ipoptp_next(&opts)) {
10511 		opt = opts.ipoptp_cur;
10512 		optlen = opts.ipoptp_len;
10513 		switch (optval) {
10514 			int	off;
10515 		case IPOPT_SSRR:
10516 		case IPOPT_LSRR:
10517 
10518 			/*
10519 			 * Insert ipha_dst as the first entry in the source
10520 			 * route and move down the entries on step.
10521 			 * The last entry gets placed at buf1.
10522 			 */
10523 			buf[IPOPT_OPTVAL] = optval;
10524 			buf[IPOPT_OLEN] = optlen;
10525 			buf[IPOPT_OFFSET] = optlen;
10526 
10527 			off = optlen - IP_ADDR_LEN;
10528 			if (off < 0) {
10529 				/* No entries in source route */
10530 				break;
10531 			}
10532 			/* Last entry in source route */
10533 			bcopy(opt + off, buf1, IP_ADDR_LEN);
10534 			off -= IP_ADDR_LEN;
10535 
10536 			while (off > 0) {
10537 				bcopy(opt + off,
10538 				    buf + off + IP_ADDR_LEN,
10539 				    IP_ADDR_LEN);
10540 				off -= IP_ADDR_LEN;
10541 			}
10542 			/* ipha_dst into first slot */
10543 			bcopy(&ipha->ipha_dst,
10544 			    buf + off + IP_ADDR_LEN,
10545 			    IP_ADDR_LEN);
10546 			buf += optlen;
10547 			len += optlen;
10548 			break;
10549 		default:
10550 			bcopy(opt, buf, optlen);
10551 			buf += optlen;
10552 			len += optlen;
10553 			break;
10554 		}
10555 	}
10556 done:
10557 	/* Pad the resulting options */
10558 	while (len & 0x3) {
10559 		*buf++ = IPOPT_EOL;
10560 		len++;
10561 	}
10562 	return (len);
10563 }
10564 
10565 /*
10566  * Transfer any source route option from ipha to buf/dst in reversed form.
10567  */
10568 static int
10569 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10570 {
10571 	ipoptp_t	opts;
10572 	uchar_t		*opt;
10573 	uint8_t		optval;
10574 	uint8_t		optlen;
10575 	uint32_t	len = 0;
10576 
10577 	for (optval = ipoptp_first(&opts, ipha);
10578 	    optval != IPOPT_EOL;
10579 	    optval = ipoptp_next(&opts)) {
10580 		opt = opts.ipoptp_cur;
10581 		optlen = opts.ipoptp_len;
10582 		switch (optval) {
10583 			int	off1, off2;
10584 		case IPOPT_SSRR:
10585 		case IPOPT_LSRR:
10586 
10587 			/* Reverse source route */
10588 			/*
10589 			 * First entry should be the next to last one in the
10590 			 * current source route (the last entry is our
10591 			 * address.)
10592 			 * The last entry should be the final destination.
10593 			 */
10594 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10595 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10596 			off1 = IPOPT_MINOFF_SR - 1;
10597 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10598 			if (off2 < 0) {
10599 				/* No entries in source route */
10600 				break;
10601 			}
10602 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10603 			/*
10604 			 * Note: use src since ipha has not had its src
10605 			 * and dst reversed (it is in the state it was
10606 			 * received.
10607 			 */
10608 			bcopy(&ipha->ipha_src, buf + off2,
10609 			    IP_ADDR_LEN);
10610 			off2 -= IP_ADDR_LEN;
10611 
10612 			while (off2 > 0) {
10613 				bcopy(opt + off2, buf + off1,
10614 				    IP_ADDR_LEN);
10615 				off1 += IP_ADDR_LEN;
10616 				off2 -= IP_ADDR_LEN;
10617 			}
10618 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10619 			buf += optlen;
10620 			len += optlen;
10621 			break;
10622 		}
10623 	}
10624 done:
10625 	/* Pad the resulting options */
10626 	while (len & 0x3) {
10627 		*buf++ = IPOPT_EOL;
10628 		len++;
10629 	}
10630 	return (len);
10631 }
10632 
10633 
10634 /*
10635  * Extract and revert a source route from ipha (if any)
10636  * and then update the relevant fields in both tcp_t and the standard header.
10637  */
10638 static void
10639 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
10640 {
10641 	char	buf[TCP_MAX_HDR_LENGTH];
10642 	uint_t	tcph_len;
10643 	int	len;
10644 
10645 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
10646 	len = IPH_HDR_LENGTH(ipha);
10647 	if (len == IP_SIMPLE_HDR_LENGTH)
10648 		/* Nothing to do */
10649 		return;
10650 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
10651 	    (len & 0x3))
10652 		return;
10653 
10654 	tcph_len = tcp->tcp_tcp_hdr_len;
10655 	bcopy(tcp->tcp_tcph, buf, tcph_len);
10656 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
10657 		(tcp->tcp_ipha->ipha_dst & 0xffff);
10658 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
10659 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
10660 	len += IP_SIMPLE_HDR_LENGTH;
10661 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
10662 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
10663 	if ((int)tcp->tcp_sum < 0)
10664 		tcp->tcp_sum--;
10665 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
10666 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
10667 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
10668 	bcopy(buf, tcp->tcp_tcph, tcph_len);
10669 	tcp->tcp_ip_hdr_len = len;
10670 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10671 	    (IP_VERSION << 4) | (len >> 2);
10672 	len += tcph_len;
10673 	tcp->tcp_hdr_len = len;
10674 }
10675 
10676 /*
10677  * Copy the standard header into its new location,
10678  * lay in the new options and then update the relevant
10679  * fields in both tcp_t and the standard header.
10680  */
10681 static int
10682 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
10683 {
10684 	uint_t	tcph_len;
10685 	char	*ip_optp;
10686 	tcph_t	*new_tcph;
10687 
10688 	if (checkonly) {
10689 		/*
10690 		 * do not really set, just pretend to - T_CHECK
10691 		 */
10692 		if (len != 0) {
10693 			/*
10694 			 * there is value supplied, validate it as if
10695 			 * for a real set operation.
10696 			 */
10697 			if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10698 				return (EINVAL);
10699 		}
10700 		return (0);
10701 	}
10702 
10703 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10704 		return (EINVAL);
10705 
10706 	ip_optp = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
10707 	tcph_len = tcp->tcp_tcp_hdr_len;
10708 	new_tcph = (tcph_t *)(ip_optp + len);
10709 	ovbcopy((char *)tcp->tcp_tcph, (char *)new_tcph, tcph_len);
10710 	tcp->tcp_tcph = new_tcph;
10711 	bcopy(ptr, ip_optp, len);
10712 
10713 	len += IP_SIMPLE_HDR_LENGTH;
10714 
10715 	tcp->tcp_ip_hdr_len = len;
10716 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10717 		(IP_VERSION << 4) | (len >> 2);
10718 	len += tcph_len;
10719 	tcp->tcp_hdr_len = len;
10720 	if (!TCP_IS_DETACHED(tcp)) {
10721 		/* Always allocate room for all options. */
10722 		(void) mi_set_sth_wroff(tcp->tcp_rq,
10723 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
10724 	}
10725 	return (0);
10726 }
10727 
10728 /* Get callback routine passed to nd_load by tcp_param_register */
10729 /* ARGSUSED */
10730 static int
10731 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
10732 {
10733 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10734 
10735 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
10736 	return (0);
10737 }
10738 
10739 /*
10740  * Walk through the param array specified registering each element with the
10741  * named dispatch handler.
10742  */
10743 static boolean_t
10744 tcp_param_register(tcpparam_t *tcppa, int cnt)
10745 {
10746 	for (; cnt-- > 0; tcppa++) {
10747 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
10748 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
10749 			    tcp_param_get, tcp_param_set,
10750 			    (caddr_t)tcppa)) {
10751 				nd_free(&tcp_g_nd);
10752 				return (B_FALSE);
10753 			}
10754 		}
10755 	}
10756 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
10757 	    tcp_param_get, tcp_param_set_aligned,
10758 	    (caddr_t)&tcp_wroff_xtra_param)) {
10759 		nd_free(&tcp_g_nd);
10760 		return (B_FALSE);
10761 	}
10762 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
10763 	    tcp_param_get, tcp_param_set_aligned,
10764 	    (caddr_t)&tcp_mdt_head_param)) {
10765 		nd_free(&tcp_g_nd);
10766 		return (B_FALSE);
10767 	}
10768 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
10769 	    tcp_param_get, tcp_param_set_aligned,
10770 	    (caddr_t)&tcp_mdt_tail_param)) {
10771 		nd_free(&tcp_g_nd);
10772 		return (B_FALSE);
10773 	}
10774 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
10775 	    tcp_param_get, tcp_param_set,
10776 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
10777 		nd_free(&tcp_g_nd);
10778 		return (B_FALSE);
10779 	}
10780 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
10781 	    tcp_extra_priv_ports_get, NULL, NULL)) {
10782 		nd_free(&tcp_g_nd);
10783 		return (B_FALSE);
10784 	}
10785 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
10786 	    NULL, tcp_extra_priv_ports_add, NULL)) {
10787 		nd_free(&tcp_g_nd);
10788 		return (B_FALSE);
10789 	}
10790 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
10791 	    NULL, tcp_extra_priv_ports_del, NULL)) {
10792 		nd_free(&tcp_g_nd);
10793 		return (B_FALSE);
10794 	}
10795 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
10796 	    NULL)) {
10797 		nd_free(&tcp_g_nd);
10798 		return (B_FALSE);
10799 	}
10800 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
10801 	    NULL, NULL)) {
10802 		nd_free(&tcp_g_nd);
10803 		return (B_FALSE);
10804 	}
10805 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
10806 	    NULL, NULL)) {
10807 		nd_free(&tcp_g_nd);
10808 		return (B_FALSE);
10809 	}
10810 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
10811 	    NULL, NULL)) {
10812 		nd_free(&tcp_g_nd);
10813 		return (B_FALSE);
10814 	}
10815 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
10816 	    NULL, NULL)) {
10817 		nd_free(&tcp_g_nd);
10818 		return (B_FALSE);
10819 	}
10820 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
10821 	    tcp_host_param_set, NULL)) {
10822 		nd_free(&tcp_g_nd);
10823 		return (B_FALSE);
10824 	}
10825 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
10826 	    tcp_host_param_set_ipv6, NULL)) {
10827 		nd_free(&tcp_g_nd);
10828 		return (B_FALSE);
10829 	}
10830 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
10831 	    NULL)) {
10832 		nd_free(&tcp_g_nd);
10833 		return (B_FALSE);
10834 	}
10835 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
10836 	    tcp_reserved_port_list, NULL, NULL)) {
10837 		nd_free(&tcp_g_nd);
10838 		return (B_FALSE);
10839 	}
10840 	/*
10841 	 * Dummy ndd variables - only to convey obsolescence information
10842 	 * through printing of their name (no get or set routines)
10843 	 * XXX Remove in future releases ?
10844 	 */
10845 	if (!nd_load(&tcp_g_nd,
10846 	    "tcp_close_wait_interval(obsoleted - "
10847 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
10848 		nd_free(&tcp_g_nd);
10849 		return (B_FALSE);
10850 	}
10851 	return (B_TRUE);
10852 }
10853 
10854 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
10855 /* ARGSUSED */
10856 static int
10857 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
10858     cred_t *cr)
10859 {
10860 	long new_value;
10861 	tcpparam_t *tcppa = (tcpparam_t *)cp;
10862 
10863 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10864 	    new_value < tcppa->tcp_param_min ||
10865 	    new_value > tcppa->tcp_param_max) {
10866 		return (EINVAL);
10867 	}
10868 	/*
10869 	 * Need to make sure new_value is a multiple of 4.  If it is not,
10870 	 * round it up.  For future 64 bit requirement, we actually make it
10871 	 * a multiple of 8.
10872 	 */
10873 	if (new_value & 0x7) {
10874 		new_value = (new_value & ~0x7) + 0x8;
10875 	}
10876 	tcppa->tcp_param_val = new_value;
10877 	return (0);
10878 }
10879 
10880 /* Set callback routine passed to nd_load by tcp_param_register */
10881 /* ARGSUSED */
10882 static int
10883 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
10884 {
10885 	long	new_value;
10886 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10887 
10888 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10889 	    new_value < tcppa->tcp_param_min ||
10890 	    new_value > tcppa->tcp_param_max) {
10891 		return (EINVAL);
10892 	}
10893 	tcppa->tcp_param_val = new_value;
10894 	return (0);
10895 }
10896 
10897 /*
10898  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
10899  * is filled, return as much as we can.  The message passed in may be
10900  * multi-part, chained using b_cont.  "start" is the starting sequence
10901  * number for this piece.
10902  */
10903 static mblk_t *
10904 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
10905 {
10906 	uint32_t	end;
10907 	mblk_t		*mp1;
10908 	mblk_t		*mp2;
10909 	mblk_t		*next_mp;
10910 	uint32_t	u1;
10911 
10912 	/* Walk through all the new pieces. */
10913 	do {
10914 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10915 		    (uintptr_t)INT_MAX);
10916 		end = start + (int)(mp->b_wptr - mp->b_rptr);
10917 		next_mp = mp->b_cont;
10918 		if (start == end) {
10919 			/* Empty.  Blast it. */
10920 			freeb(mp);
10921 			continue;
10922 		}
10923 		mp->b_cont = NULL;
10924 		TCP_REASS_SET_SEQ(mp, start);
10925 		TCP_REASS_SET_END(mp, end);
10926 		mp1 = tcp->tcp_reass_tail;
10927 		if (!mp1) {
10928 			tcp->tcp_reass_tail = mp;
10929 			tcp->tcp_reass_head = mp;
10930 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
10931 			UPDATE_MIB(&tcp_mib,
10932 			    tcpInDataUnorderBytes, end - start);
10933 			continue;
10934 		}
10935 		/* New stuff completely beyond tail? */
10936 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
10937 			/* Link it on end. */
10938 			mp1->b_cont = mp;
10939 			tcp->tcp_reass_tail = mp;
10940 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
10941 			UPDATE_MIB(&tcp_mib,
10942 			    tcpInDataUnorderBytes, end - start);
10943 			continue;
10944 		}
10945 		mp1 = tcp->tcp_reass_head;
10946 		u1 = TCP_REASS_SEQ(mp1);
10947 		/* New stuff at the front? */
10948 		if (SEQ_LT(start, u1)) {
10949 			/* Yes... Check for overlap. */
10950 			mp->b_cont = mp1;
10951 			tcp->tcp_reass_head = mp;
10952 			tcp_reass_elim_overlap(tcp, mp);
10953 			continue;
10954 		}
10955 		/*
10956 		 * The new piece fits somewhere between the head and tail.
10957 		 * We find our slot, where mp1 precedes us and mp2 trails.
10958 		 */
10959 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
10960 			u1 = TCP_REASS_SEQ(mp2);
10961 			if (SEQ_LEQ(start, u1))
10962 				break;
10963 		}
10964 		/* Link ourselves in */
10965 		mp->b_cont = mp2;
10966 		mp1->b_cont = mp;
10967 
10968 		/* Trim overlap with following mblk(s) first */
10969 		tcp_reass_elim_overlap(tcp, mp);
10970 
10971 		/* Trim overlap with preceding mblk */
10972 		tcp_reass_elim_overlap(tcp, mp1);
10973 
10974 	} while (start = end, mp = next_mp);
10975 	mp1 = tcp->tcp_reass_head;
10976 	/* Anything ready to go? */
10977 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
10978 		return (NULL);
10979 	/* Eat what we can off the queue */
10980 	for (;;) {
10981 		mp = mp1->b_cont;
10982 		end = TCP_REASS_END(mp1);
10983 		TCP_REASS_SET_SEQ(mp1, 0);
10984 		TCP_REASS_SET_END(mp1, 0);
10985 		if (!mp) {
10986 			tcp->tcp_reass_tail = NULL;
10987 			break;
10988 		}
10989 		if (end != TCP_REASS_SEQ(mp)) {
10990 			mp1->b_cont = NULL;
10991 			break;
10992 		}
10993 		mp1 = mp;
10994 	}
10995 	mp1 = tcp->tcp_reass_head;
10996 	tcp->tcp_reass_head = mp;
10997 	return (mp1);
10998 }
10999 
11000 /* Eliminate any overlap that mp may have over later mblks */
11001 static void
11002 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11003 {
11004 	uint32_t	end;
11005 	mblk_t		*mp1;
11006 	uint32_t	u1;
11007 
11008 	end = TCP_REASS_END(mp);
11009 	while ((mp1 = mp->b_cont) != NULL) {
11010 		u1 = TCP_REASS_SEQ(mp1);
11011 		if (!SEQ_GT(end, u1))
11012 			break;
11013 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11014 			mp->b_wptr -= end - u1;
11015 			TCP_REASS_SET_END(mp, u1);
11016 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
11017 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
11018 			break;
11019 		}
11020 		mp->b_cont = mp1->b_cont;
11021 		TCP_REASS_SET_SEQ(mp1, 0);
11022 		TCP_REASS_SET_END(mp1, 0);
11023 		freeb(mp1);
11024 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
11025 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
11026 	}
11027 	if (!mp1)
11028 		tcp->tcp_reass_tail = mp;
11029 }
11030 
11031 /*
11032  * Send up all messages queued on tcp_rcv_list.
11033  */
11034 static uint_t
11035 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11036 {
11037 	mblk_t *mp;
11038 	uint_t ret = 0;
11039 	uint_t thwin;
11040 #ifdef DEBUG
11041 	uint_t cnt = 0;
11042 #endif
11043 	/* Can't drain on an eager connection */
11044 	if (tcp->tcp_listener != NULL)
11045 		return (ret);
11046 
11047 	/*
11048 	 * Handle two cases here: we are currently fused or we were
11049 	 * previously fused and have some urgent data to be delivered
11050 	 * upstream.  The latter happens because we either ran out of
11051 	 * memory or were detached and therefore sending the SIGURG was
11052 	 * deferred until this point.  In either case we pass control
11053 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11054 	 * some work.
11055 	 */
11056 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11057 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11058 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11059 		    &tcp->tcp_fused_sigurg_mp))
11060 			return (ret);
11061 	}
11062 
11063 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11064 		tcp->tcp_rcv_list = mp->b_next;
11065 		mp->b_next = NULL;
11066 #ifdef DEBUG
11067 		cnt += msgdsize(mp);
11068 #endif
11069 		/* Does this need SSL processing first? */
11070 		if ((tcp->tcp_kssl_ctx  != NULL) && (DB_TYPE(mp) == M_DATA)) {
11071 			tcp_kssl_input(tcp, mp);
11072 			continue;
11073 		}
11074 		putnext(q, mp);
11075 	}
11076 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11077 	tcp->tcp_rcv_last_head = NULL;
11078 	tcp->tcp_rcv_last_tail = NULL;
11079 	tcp->tcp_rcv_cnt = 0;
11080 
11081 	/* Learn the latest rwnd information that we sent to the other side. */
11082 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11083 	    << tcp->tcp_rcv_ws;
11084 	/* This is peer's calculated send window (our receive window). */
11085 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11086 	/*
11087 	 * Increase the receive window to max.  But we need to do receiver
11088 	 * SWS avoidance.  This means that we need to check the increase of
11089 	 * of receive window is at least 1 MSS.
11090 	 */
11091 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11092 		/*
11093 		 * If the window that the other side knows is less than max
11094 		 * deferred acks segments, send an update immediately.
11095 		 */
11096 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11097 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11098 			ret = TH_ACK_NEEDED;
11099 		}
11100 		tcp->tcp_rwnd = q->q_hiwat;
11101 	}
11102 	/* No need for the push timer now. */
11103 	if (tcp->tcp_push_tid != 0) {
11104 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11105 		tcp->tcp_push_tid = 0;
11106 	}
11107 	return (ret);
11108 }
11109 
11110 /*
11111  * Queue data on tcp_rcv_list which is a b_next chain.
11112  * tcp_rcv_last_head/tail is the last element of this chain.
11113  * Each element of the chain is a b_cont chain.
11114  *
11115  * M_DATA messages are added to the current element.
11116  * Other messages are added as new (b_next) elements.
11117  */
11118 void
11119 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11120 {
11121 	ASSERT(seg_len == msgdsize(mp));
11122 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11123 
11124 	if (tcp->tcp_rcv_list == NULL) {
11125 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11126 		tcp->tcp_rcv_list = mp;
11127 		tcp->tcp_rcv_last_head = mp;
11128 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11129 		tcp->tcp_rcv_last_tail->b_cont = mp;
11130 	} else {
11131 		tcp->tcp_rcv_last_head->b_next = mp;
11132 		tcp->tcp_rcv_last_head = mp;
11133 	}
11134 
11135 	while (mp->b_cont)
11136 		mp = mp->b_cont;
11137 
11138 	tcp->tcp_rcv_last_tail = mp;
11139 	tcp->tcp_rcv_cnt += seg_len;
11140 	tcp->tcp_rwnd -= seg_len;
11141 }
11142 
11143 /*
11144  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11145  *
11146  * This is the default entry function into TCP on the read side. TCP is
11147  * always entered via squeue i.e. using squeue's for mutual exclusion.
11148  * When classifier does a lookup to find the tcp, it also puts a reference
11149  * on the conn structure associated so the tcp is guaranteed to exist
11150  * when we come here. We still need to check the state because it might
11151  * as well has been closed. The squeue processing function i.e. squeue_enter,
11152  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11153  * CONN_DEC_REF.
11154  *
11155  * Apart from the default entry point, IP also sends packets directly to
11156  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11157  * connections.
11158  */
11159 void
11160 tcp_input(void *arg, mblk_t *mp, void *arg2)
11161 {
11162 	conn_t	*connp = (conn_t *)arg;
11163 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11164 
11165 	/* arg2 is the sqp */
11166 	ASSERT(arg2 != NULL);
11167 	ASSERT(mp != NULL);
11168 
11169 	/*
11170 	 * Don't accept any input on a closed tcp as this TCP logically does
11171 	 * not exist on the system. Don't proceed further with this TCP.
11172 	 * For eg. this packet could trigger another close of this tcp
11173 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11174 	 * tcp_clean_death / tcp_closei_local must be called at most once
11175 	 * on a TCP. In this case we need to refeed the packet into the
11176 	 * classifier and figure out where the packet should go. Need to
11177 	 * preserve the recv_ill somehow. Until we figure that out, for
11178 	 * now just drop the packet if we can't classify the packet.
11179 	 */
11180 	if (tcp->tcp_state == TCPS_CLOSED ||
11181 	    tcp->tcp_state == TCPS_BOUND) {
11182 		conn_t	*new_connp;
11183 
11184 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11185 		if (new_connp != NULL) {
11186 			tcp_reinput(new_connp, mp, arg2);
11187 			return;
11188 		}
11189 		/* We failed to classify. For now just drop the packet */
11190 		freemsg(mp);
11191 		return;
11192 	}
11193 
11194 	if (DB_TYPE(mp) == M_DATA)
11195 		tcp_rput_data(connp, mp, arg2);
11196 	else
11197 		tcp_rput_common(tcp, mp);
11198 }
11199 
11200 /*
11201  * The read side put procedure.
11202  * The packets passed up by ip are assume to be aligned according to
11203  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11204  */
11205 static void
11206 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11207 {
11208 	/*
11209 	 * tcp_rput_data() does not expect M_CTL except for the case
11210 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11211 	 * type. Need to make sure that any other M_CTLs don't make
11212 	 * it to tcp_rput_data since it is not expecting any and doesn't
11213 	 * check for it.
11214 	 */
11215 	if (DB_TYPE(mp) == M_CTL) {
11216 		switch (*(uint32_t *)(mp->b_rptr)) {
11217 		case TCP_IOC_ABORT_CONN:
11218 			/*
11219 			 * Handle connection abort request.
11220 			 */
11221 			tcp_ioctl_abort_handler(tcp, mp);
11222 			return;
11223 		case IPSEC_IN:
11224 			/*
11225 			 * Only secure icmp arrive in TCP and they
11226 			 * don't go through data path.
11227 			 */
11228 			tcp_icmp_error(tcp, mp);
11229 			return;
11230 		case IN_PKTINFO:
11231 			/*
11232 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11233 			 * sockets that are receiving IPv4 traffic. tcp
11234 			 */
11235 			ASSERT(tcp->tcp_family == AF_INET6);
11236 			ASSERT(tcp->tcp_ipv6_recvancillary &
11237 			    TCP_IPV6_RECVPKTINFO);
11238 			tcp_rput_data(tcp->tcp_connp, mp,
11239 			    tcp->tcp_connp->conn_sqp);
11240 			return;
11241 		case MDT_IOC_INFO_UPDATE:
11242 			/*
11243 			 * Handle Multidata information update; the
11244 			 * following routine will free the message.
11245 			 */
11246 			if (tcp->tcp_connp->conn_mdt_ok) {
11247 				tcp_mdt_update(tcp,
11248 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11249 				    B_FALSE);
11250 			}
11251 			freemsg(mp);
11252 			return;
11253 		default:
11254 			break;
11255 		}
11256 	}
11257 
11258 	/* No point processing the message if tcp is already closed */
11259 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11260 		freemsg(mp);
11261 		return;
11262 	}
11263 
11264 	tcp_rput_other(tcp, mp);
11265 }
11266 
11267 
11268 /* The minimum of smoothed mean deviation in RTO calculation. */
11269 #define	TCP_SD_MIN	400
11270 
11271 /*
11272  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11273  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11274  * are the same as those in Appendix A.2 of that paper.
11275  *
11276  * m = new measurement
11277  * sa = smoothed RTT average (8 * average estimates).
11278  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11279  */
11280 static void
11281 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11282 {
11283 	long m = TICK_TO_MSEC(rtt);
11284 	clock_t sa = tcp->tcp_rtt_sa;
11285 	clock_t sv = tcp->tcp_rtt_sd;
11286 	clock_t rto;
11287 
11288 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
11289 	tcp->tcp_rtt_update++;
11290 
11291 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11292 	if (sa != 0) {
11293 		/*
11294 		 * Update average estimator:
11295 		 *	new rtt = 7/8 old rtt + 1/8 Error
11296 		 */
11297 
11298 		/* m is now Error in estimate. */
11299 		m -= sa >> 3;
11300 		if ((sa += m) <= 0) {
11301 			/*
11302 			 * Don't allow the smoothed average to be negative.
11303 			 * We use 0 to denote reinitialization of the
11304 			 * variables.
11305 			 */
11306 			sa = 1;
11307 		}
11308 
11309 		/*
11310 		 * Update deviation estimator:
11311 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11312 		 */
11313 		if (m < 0)
11314 			m = -m;
11315 		m -= sv >> 2;
11316 		sv += m;
11317 	} else {
11318 		/*
11319 		 * This follows BSD's implementation.  So the reinitialized
11320 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11321 		 * link is bandwidth dominated, doubling the window size
11322 		 * during slow start means doubling the RTT.  We want to be
11323 		 * more conservative when we reinitialize our estimates.  3
11324 		 * is just a convenient number.
11325 		 */
11326 		sa = m << 3;
11327 		sv = m << 1;
11328 	}
11329 	if (sv < TCP_SD_MIN) {
11330 		/*
11331 		 * We do not know that if sa captures the delay ACK
11332 		 * effect as in a long train of segments, a receiver
11333 		 * does not delay its ACKs.  So set the minimum of sv
11334 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11335 		 * of BSD DATO.  That means the minimum of mean
11336 		 * deviation is 100 ms.
11337 		 *
11338 		 */
11339 		sv = TCP_SD_MIN;
11340 	}
11341 	tcp->tcp_rtt_sa = sa;
11342 	tcp->tcp_rtt_sd = sv;
11343 	/*
11344 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11345 	 *
11346 	 * Add tcp_rexmit_interval extra in case of extreme environment
11347 	 * where the algorithm fails to work.  The default value of
11348 	 * tcp_rexmit_interval_extra should be 0.
11349 	 *
11350 	 * As we use a finer grained clock than BSD and update
11351 	 * RTO for every ACKs, add in another .25 of RTT to the
11352 	 * deviation of RTO to accomodate burstiness of 1/4 of
11353 	 * window size.
11354 	 */
11355 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
11356 
11357 	if (rto > tcp_rexmit_interval_max) {
11358 		tcp->tcp_rto = tcp_rexmit_interval_max;
11359 	} else if (rto < tcp_rexmit_interval_min) {
11360 		tcp->tcp_rto = tcp_rexmit_interval_min;
11361 	} else {
11362 		tcp->tcp_rto = rto;
11363 	}
11364 
11365 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11366 	tcp->tcp_timer_backoff = 0;
11367 }
11368 
11369 /*
11370  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11371  * send queue which starts at the given seq. no.
11372  *
11373  * Parameters:
11374  *	tcp_t *tcp: the tcp instance pointer.
11375  *	uint32_t seq: the starting seq. no of the requested segment.
11376  *	int32_t *off: after the execution, *off will be the offset to
11377  *		the returned mblk which points to the requested seq no.
11378  *		It is the caller's responsibility to send in a non-null off.
11379  *
11380  * Return:
11381  *	A mblk_t pointer pointing to the requested segment in send queue.
11382  */
11383 static mblk_t *
11384 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11385 {
11386 	int32_t	cnt;
11387 	mblk_t	*mp;
11388 
11389 	/* Defensive coding.  Make sure we don't send incorrect data. */
11390 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
11391 		return (NULL);
11392 
11393 	cnt = seq - tcp->tcp_suna;
11394 	mp = tcp->tcp_xmit_head;
11395 	while (cnt > 0 && mp != NULL) {
11396 		cnt -= mp->b_wptr - mp->b_rptr;
11397 		if (cnt < 0) {
11398 			cnt += mp->b_wptr - mp->b_rptr;
11399 			break;
11400 		}
11401 		mp = mp->b_cont;
11402 	}
11403 	ASSERT(mp != NULL);
11404 	*off = cnt;
11405 	return (mp);
11406 }
11407 
11408 /*
11409  * This function handles all retransmissions if SACK is enabled for this
11410  * connection.  First it calculates how many segments can be retransmitted
11411  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11412  * segments.  A segment is eligible if sack_cnt for that segment is greater
11413  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11414  * all eligible segments, it checks to see if TCP can send some new segments
11415  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11416  *
11417  * Parameters:
11418  *	tcp_t *tcp: the tcp structure of the connection.
11419  *	uint_t *flags: in return, appropriate value will be set for
11420  *	tcp_rput_data().
11421  */
11422 static void
11423 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11424 {
11425 	notsack_blk_t	*notsack_blk;
11426 	int32_t		usable_swnd;
11427 	int32_t		mss;
11428 	uint32_t	seg_len;
11429 	mblk_t		*xmit_mp;
11430 
11431 	ASSERT(tcp->tcp_sack_info != NULL);
11432 	ASSERT(tcp->tcp_notsack_list != NULL);
11433 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11434 
11435 	/* Defensive coding in case there is a bug... */
11436 	if (tcp->tcp_notsack_list == NULL) {
11437 		return;
11438 	}
11439 	notsack_blk = tcp->tcp_notsack_list;
11440 	mss = tcp->tcp_mss;
11441 
11442 	/*
11443 	 * Limit the num of outstanding data in the network to be
11444 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11445 	 */
11446 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11447 
11448 	/* At least retransmit 1 MSS of data. */
11449 	if (usable_swnd <= 0) {
11450 		usable_swnd = mss;
11451 	}
11452 
11453 	/* Make sure no new RTT samples will be taken. */
11454 	tcp->tcp_csuna = tcp->tcp_snxt;
11455 
11456 	notsack_blk = tcp->tcp_notsack_list;
11457 	while (usable_swnd > 0) {
11458 		mblk_t		*snxt_mp, *tmp_mp;
11459 		tcp_seq		begin = tcp->tcp_sack_snxt;
11460 		tcp_seq		end;
11461 		int32_t		off;
11462 
11463 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11464 			if (SEQ_GT(notsack_blk->end, begin) &&
11465 			    (notsack_blk->sack_cnt >=
11466 			    tcp_dupack_fast_retransmit)) {
11467 				end = notsack_blk->end;
11468 				if (SEQ_LT(begin, notsack_blk->begin)) {
11469 					begin = notsack_blk->begin;
11470 				}
11471 				break;
11472 			}
11473 		}
11474 		/*
11475 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11476 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11477 		 * set to tcp_cwnd_ssthresh.
11478 		 */
11479 		if (notsack_blk == NULL) {
11480 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11481 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11482 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11483 				ASSERT(tcp->tcp_cwnd > 0);
11484 				return;
11485 			} else {
11486 				usable_swnd = usable_swnd / mss;
11487 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11488 				    MAX(usable_swnd * mss, mss);
11489 				*flags |= TH_XMIT_NEEDED;
11490 				return;
11491 			}
11492 		}
11493 
11494 		/*
11495 		 * Note that we may send more than usable_swnd allows here
11496 		 * because of round off, but no more than 1 MSS of data.
11497 		 */
11498 		seg_len = end - begin;
11499 		if (seg_len > mss)
11500 			seg_len = mss;
11501 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11502 		ASSERT(snxt_mp != NULL);
11503 		/* This should not happen.  Defensive coding again... */
11504 		if (snxt_mp == NULL) {
11505 			return;
11506 		}
11507 
11508 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11509 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11510 		if (xmit_mp == NULL)
11511 			return;
11512 
11513 		usable_swnd -= seg_len;
11514 		tcp->tcp_pipe += seg_len;
11515 		tcp->tcp_sack_snxt = begin + seg_len;
11516 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
11517 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11518 
11519 		/*
11520 		 * Update the send timestamp to avoid false retransmission.
11521 		 */
11522 		snxt_mp->b_prev = (mblk_t *)lbolt;
11523 
11524 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
11525 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
11526 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
11527 		/*
11528 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11529 		 * This happens when new data sent during fast recovery is
11530 		 * also lost.  If TCP retransmits those new data, it needs
11531 		 * to extend SACK recover phase to avoid starting another
11532 		 * fast retransmit/recovery unnecessarily.
11533 		 */
11534 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11535 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11536 		}
11537 	}
11538 }
11539 
11540 /*
11541  * This function handles policy checking at TCP level for non-hard_bound/
11542  * detached connections.
11543  */
11544 static boolean_t
11545 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
11546     boolean_t secure, boolean_t mctl_present)
11547 {
11548 	ipsec_latch_t *ipl = NULL;
11549 	ipsec_action_t *act = NULL;
11550 	mblk_t *data_mp;
11551 	ipsec_in_t *ii;
11552 	const char *reason;
11553 	kstat_named_t *counter;
11554 
11555 	ASSERT(mctl_present || !secure);
11556 
11557 	ASSERT((ipha == NULL && ip6h != NULL) ||
11558 	    (ip6h == NULL && ipha != NULL));
11559 
11560 	/*
11561 	 * We don't necessarily have an ipsec_in_act action to verify
11562 	 * policy because of assymetrical policy where we have only
11563 	 * outbound policy and no inbound policy (possible with global
11564 	 * policy).
11565 	 */
11566 	if (!secure) {
11567 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
11568 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
11569 			return (B_TRUE);
11570 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
11571 		    "tcp_check_policy", ipha, ip6h, secure);
11572 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11573 		    &ipdrops_tcp_clear, &tcp_dropper);
11574 		return (B_FALSE);
11575 	}
11576 
11577 	/*
11578 	 * We have a secure packet.
11579 	 */
11580 	if (act == NULL) {
11581 		ipsec_log_policy_failure(tcp->tcp_wq,
11582 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
11583 		    secure);
11584 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11585 		    &ipdrops_tcp_secure, &tcp_dropper);
11586 		return (B_FALSE);
11587 	}
11588 
11589 	/*
11590 	 * XXX This whole routine is currently incorrect.  ipl should
11591 	 * be set to the latch pointer, but is currently not set, so
11592 	 * we initialize it to NULL to avoid picking up random garbage.
11593 	 */
11594 	if (ipl == NULL)
11595 		return (B_TRUE);
11596 
11597 	data_mp = first_mp->b_cont;
11598 
11599 	ii = (ipsec_in_t *)first_mp->b_rptr;
11600 
11601 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
11602 	    &counter)) {
11603 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
11604 		return (B_TRUE);
11605 	}
11606 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
11607 	    "tcp inbound policy mismatch: %s, packet dropped\n",
11608 	    reason);
11609 	BUMP_MIB(&ip_mib, ipsecInFailed);
11610 
11611 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
11612 	return (B_FALSE);
11613 }
11614 
11615 /*
11616  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
11617  * retransmission after a timeout.
11618  *
11619  * To limit the number of duplicate segments, we limit the number of segment
11620  * to be sent in one time to tcp_snd_burst, the burst variable.
11621  */
11622 static void
11623 tcp_ss_rexmit(tcp_t *tcp)
11624 {
11625 	uint32_t	snxt;
11626 	uint32_t	smax;
11627 	int32_t		win;
11628 	int32_t		mss;
11629 	int32_t		off;
11630 	int32_t		burst = tcp->tcp_snd_burst;
11631 	mblk_t		*snxt_mp;
11632 
11633 	/*
11634 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
11635 	 * all unack'ed segments.
11636 	 */
11637 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
11638 		smax = tcp->tcp_rexmit_max;
11639 		snxt = tcp->tcp_rexmit_nxt;
11640 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
11641 			snxt = tcp->tcp_suna;
11642 		}
11643 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
11644 		win -= snxt - tcp->tcp_suna;
11645 		mss = tcp->tcp_mss;
11646 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
11647 
11648 		while (SEQ_LT(snxt, smax) && (win > 0) &&
11649 		    (burst > 0) && (snxt_mp != NULL)) {
11650 			mblk_t	*xmit_mp;
11651 			mblk_t	*old_snxt_mp = snxt_mp;
11652 			uint32_t cnt = mss;
11653 
11654 			if (win < cnt) {
11655 				cnt = win;
11656 			}
11657 			if (SEQ_GT(snxt + cnt, smax)) {
11658 				cnt = smax - snxt;
11659 			}
11660 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
11661 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
11662 			if (xmit_mp == NULL)
11663 				return;
11664 
11665 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11666 
11667 			snxt += cnt;
11668 			win -= cnt;
11669 			/*
11670 			 * Update the send timestamp to avoid false
11671 			 * retransmission.
11672 			 */
11673 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
11674 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
11675 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
11676 
11677 			tcp->tcp_rexmit_nxt = snxt;
11678 			burst--;
11679 		}
11680 		/*
11681 		 * If we have transmitted all we have at the time
11682 		 * we started the retranmission, we can leave
11683 		 * the rest of the job to tcp_wput_data().  But we
11684 		 * need to check the send window first.  If the
11685 		 * win is not 0, go on with tcp_wput_data().
11686 		 */
11687 		if (SEQ_LT(snxt, smax) || win == 0) {
11688 			return;
11689 		}
11690 	}
11691 	/* Only call tcp_wput_data() if there is data to be sent. */
11692 	if (tcp->tcp_unsent) {
11693 		tcp_wput_data(tcp, NULL, B_FALSE);
11694 	}
11695 }
11696 
11697 /*
11698  * Process all TCP option in SYN segment.  Note that this function should
11699  * be called after tcp_adapt_ire() is called so that the necessary info
11700  * from IRE is already set in the tcp structure.
11701  *
11702  * This function sets up the correct tcp_mss value according to the
11703  * MSS option value and our header size.  It also sets up the window scale
11704  * and timestamp values, and initialize SACK info blocks.  But it does not
11705  * change receive window size after setting the tcp_mss value.  The caller
11706  * should do the appropriate change.
11707  */
11708 void
11709 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
11710 {
11711 	int options;
11712 	tcp_opt_t tcpopt;
11713 	uint32_t mss_max;
11714 	char *tmp_tcph;
11715 
11716 	tcpopt.tcp = NULL;
11717 	options = tcp_parse_options(tcph, &tcpopt);
11718 
11719 	/*
11720 	 * Process MSS option.  Note that MSS option value does not account
11721 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
11722 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
11723 	 * IPv6.
11724 	 */
11725 	if (!(options & TCP_OPT_MSS_PRESENT)) {
11726 		if (tcp->tcp_ipversion == IPV4_VERSION)
11727 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
11728 		else
11729 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
11730 	} else {
11731 		if (tcp->tcp_ipversion == IPV4_VERSION)
11732 			mss_max = tcp_mss_max_ipv4;
11733 		else
11734 			mss_max = tcp_mss_max_ipv6;
11735 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
11736 			tcpopt.tcp_opt_mss = tcp_mss_min;
11737 		else if (tcpopt.tcp_opt_mss > mss_max)
11738 			tcpopt.tcp_opt_mss = mss_max;
11739 	}
11740 
11741 	/* Process Window Scale option. */
11742 	if (options & TCP_OPT_WSCALE_PRESENT) {
11743 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
11744 		tcp->tcp_snd_ws_ok = B_TRUE;
11745 	} else {
11746 		tcp->tcp_snd_ws = B_FALSE;
11747 		tcp->tcp_snd_ws_ok = B_FALSE;
11748 		tcp->tcp_rcv_ws = B_FALSE;
11749 	}
11750 
11751 	/* Process Timestamp option. */
11752 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
11753 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
11754 		tmp_tcph = (char *)tcp->tcp_tcph;
11755 
11756 		tcp->tcp_snd_ts_ok = B_TRUE;
11757 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
11758 		tcp->tcp_last_rcv_lbolt = lbolt64;
11759 		ASSERT(OK_32PTR(tmp_tcph));
11760 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
11761 
11762 		/* Fill in our template header with basic timestamp option. */
11763 		tmp_tcph += tcp->tcp_tcp_hdr_len;
11764 		tmp_tcph[0] = TCPOPT_NOP;
11765 		tmp_tcph[1] = TCPOPT_NOP;
11766 		tmp_tcph[2] = TCPOPT_TSTAMP;
11767 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
11768 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
11769 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
11770 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
11771 	} else {
11772 		tcp->tcp_snd_ts_ok = B_FALSE;
11773 	}
11774 
11775 	/*
11776 	 * Process SACK options.  If SACK is enabled for this connection,
11777 	 * then allocate the SACK info structure.  Note the following ways
11778 	 * when tcp_snd_sack_ok is set to true.
11779 	 *
11780 	 * For active connection: in tcp_adapt_ire() called in
11781 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
11782 	 * is checked.
11783 	 *
11784 	 * For passive connection: in tcp_adapt_ire() called in
11785 	 * tcp_accept_comm().
11786 	 *
11787 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
11788 	 * That check makes sure that if we did not send a SACK OK option,
11789 	 * we will not enable SACK for this connection even though the other
11790 	 * side sends us SACK OK option.  For active connection, the SACK
11791 	 * info structure has already been allocated.  So we need to free
11792 	 * it if SACK is disabled.
11793 	 */
11794 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
11795 	    (tcp->tcp_snd_sack_ok ||
11796 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
11797 		/* This should be true only in the passive case. */
11798 		if (tcp->tcp_sack_info == NULL) {
11799 			ASSERT(TCP_IS_DETACHED(tcp));
11800 			tcp->tcp_sack_info =
11801 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
11802 		}
11803 		if (tcp->tcp_sack_info == NULL) {
11804 			tcp->tcp_snd_sack_ok = B_FALSE;
11805 		} else {
11806 			tcp->tcp_snd_sack_ok = B_TRUE;
11807 			if (tcp->tcp_snd_ts_ok) {
11808 				tcp->tcp_max_sack_blk = 3;
11809 			} else {
11810 				tcp->tcp_max_sack_blk = 4;
11811 			}
11812 		}
11813 	} else {
11814 		/*
11815 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
11816 		 * no SACK info will be used for this
11817 		 * connection.  This assumes that SACK usage
11818 		 * permission is negotiated.  This may need
11819 		 * to be changed once this is clarified.
11820 		 */
11821 		if (tcp->tcp_sack_info != NULL) {
11822 			ASSERT(tcp->tcp_notsack_list == NULL);
11823 			kmem_cache_free(tcp_sack_info_cache,
11824 			    tcp->tcp_sack_info);
11825 			tcp->tcp_sack_info = NULL;
11826 		}
11827 		tcp->tcp_snd_sack_ok = B_FALSE;
11828 	}
11829 
11830 	/*
11831 	 * Now we know the exact TCP/IP header length, subtract
11832 	 * that from tcp_mss to get our side's MSS.
11833 	 */
11834 	tcp->tcp_mss -= tcp->tcp_hdr_len;
11835 	/*
11836 	 * Here we assume that the other side's header size will be equal to
11837 	 * our header size.  We calculate the real MSS accordingly.  Need to
11838 	 * take into additional stuffs IPsec puts in.
11839 	 *
11840 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
11841 	 */
11842 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
11843 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
11844 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
11845 
11846 	/*
11847 	 * Set MSS to the smaller one of both ends of the connection.
11848 	 * We should not have called tcp_mss_set() before, but our
11849 	 * side of the MSS should have been set to a proper value
11850 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
11851 	 * STREAM head parameters properly.
11852 	 *
11853 	 * If we have a larger-than-16-bit window but the other side
11854 	 * didn't want to do window scale, tcp_rwnd_set() will take
11855 	 * care of that.
11856 	 */
11857 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
11858 }
11859 
11860 /*
11861  * Sends the T_CONN_IND to the listener. The caller calls this
11862  * functions via squeue to get inside the listener's perimeter
11863  * once the 3 way hand shake is done a T_CONN_IND needs to be
11864  * sent. As an optimization, the caller can call this directly
11865  * if listener's perimeter is same as eager's.
11866  */
11867 /* ARGSUSED */
11868 void
11869 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
11870 {
11871 	conn_t			*lconnp = (conn_t *)arg;
11872 	tcp_t			*listener = lconnp->conn_tcp;
11873 	tcp_t			*tcp;
11874 	struct T_conn_ind	*conn_ind;
11875 	ipaddr_t 		*addr_cache;
11876 	boolean_t		need_send_conn_ind = B_FALSE;
11877 
11878 	/* retrieve the eager */
11879 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
11880 	ASSERT(conn_ind->OPT_offset != 0 &&
11881 	    conn_ind->OPT_length == sizeof (intptr_t));
11882 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
11883 		conn_ind->OPT_length);
11884 
11885 	/*
11886 	 * TLI/XTI applications will get confused by
11887 	 * sending eager as an option since it violates
11888 	 * the option semantics. So remove the eager as
11889 	 * option since TLI/XTI app doesn't need it anyway.
11890 	 */
11891 	if (!TCP_IS_SOCKET(listener)) {
11892 		conn_ind->OPT_length = 0;
11893 		conn_ind->OPT_offset = 0;
11894 	}
11895 	if (listener->tcp_state == TCPS_CLOSED ||
11896 	    TCP_IS_DETACHED(listener)) {
11897 		/*
11898 		 * If listener has closed, it would have caused a
11899 		 * a cleanup/blowoff to happen for the eager. We
11900 		 * just need to return.
11901 		 */
11902 		freemsg(mp);
11903 		return;
11904 	}
11905 
11906 
11907 	/*
11908 	 * if the conn_req_q is full defer passing up the
11909 	 * T_CONN_IND until space is availabe after t_accept()
11910 	 * processing
11911 	 */
11912 	mutex_enter(&listener->tcp_eager_lock);
11913 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
11914 		tcp_t *tail;
11915 
11916 		/*
11917 		 * The eager already has an extra ref put in tcp_rput_data
11918 		 * so that it stays till accept comes back even though it
11919 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
11920 		 */
11921 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
11922 		listener->tcp_conn_req_cnt_q0--;
11923 		listener->tcp_conn_req_cnt_q++;
11924 
11925 		/* Move from SYN_RCVD to ESTABLISHED list  */
11926 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
11927 		    tcp->tcp_eager_prev_q0;
11928 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
11929 		    tcp->tcp_eager_next_q0;
11930 		tcp->tcp_eager_prev_q0 = NULL;
11931 		tcp->tcp_eager_next_q0 = NULL;
11932 
11933 		/*
11934 		 * Insert at end of the queue because sockfs
11935 		 * sends down T_CONN_RES in chronological
11936 		 * order. Leaving the older conn indications
11937 		 * at front of the queue helps reducing search
11938 		 * time.
11939 		 */
11940 		tail = listener->tcp_eager_last_q;
11941 		if (tail != NULL)
11942 			tail->tcp_eager_next_q = tcp;
11943 		else
11944 			listener->tcp_eager_next_q = tcp;
11945 		listener->tcp_eager_last_q = tcp;
11946 		tcp->tcp_eager_next_q = NULL;
11947 		/*
11948 		 * Delay sending up the T_conn_ind until we are
11949 		 * done with the eager. Once we have have sent up
11950 		 * the T_conn_ind, the accept can potentially complete
11951 		 * any time and release the refhold we have on the eager.
11952 		 */
11953 		need_send_conn_ind = B_TRUE;
11954 	} else {
11955 		/*
11956 		 * Defer connection on q0 and set deferred
11957 		 * connection bit true
11958 		 */
11959 		tcp->tcp_conn_def_q0 = B_TRUE;
11960 
11961 		/* take tcp out of q0 ... */
11962 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
11963 		    tcp->tcp_eager_next_q0;
11964 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
11965 		    tcp->tcp_eager_prev_q0;
11966 
11967 		/* ... and place it at the end of q0 */
11968 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
11969 		tcp->tcp_eager_next_q0 = listener;
11970 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
11971 		listener->tcp_eager_prev_q0 = tcp;
11972 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
11973 	}
11974 
11975 	/* we have timed out before */
11976 	if (tcp->tcp_syn_rcvd_timeout != 0) {
11977 		tcp->tcp_syn_rcvd_timeout = 0;
11978 		listener->tcp_syn_rcvd_timeout--;
11979 		if (listener->tcp_syn_defense &&
11980 		    listener->tcp_syn_rcvd_timeout <=
11981 		    (tcp_conn_req_max_q0 >> 5) &&
11982 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
11983 			listener->tcp_last_rcv_lbolt)) {
11984 			/*
11985 			 * Turn off the defense mode if we
11986 			 * believe the SYN attack is over.
11987 			 */
11988 			listener->tcp_syn_defense = B_FALSE;
11989 			if (listener->tcp_ip_addr_cache) {
11990 				kmem_free((void *)listener->tcp_ip_addr_cache,
11991 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
11992 				listener->tcp_ip_addr_cache = NULL;
11993 			}
11994 		}
11995 	}
11996 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
11997 	if (addr_cache != NULL) {
11998 		/*
11999 		 * We have finished a 3-way handshake with this
12000 		 * remote host. This proves the IP addr is good.
12001 		 * Cache it!
12002 		 */
12003 		addr_cache[IP_ADDR_CACHE_HASH(
12004 			tcp->tcp_remote)] = tcp->tcp_remote;
12005 	}
12006 	mutex_exit(&listener->tcp_eager_lock);
12007 	if (need_send_conn_ind)
12008 		putnext(listener->tcp_rq, mp);
12009 }
12010 
12011 mblk_t *
12012 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12013     uint_t *ifindexp, ip6_pkt_t *ippp)
12014 {
12015 	in_pktinfo_t	*pinfo;
12016 	ip6_t		*ip6h;
12017 	uchar_t		*rptr;
12018 	mblk_t		*first_mp = mp;
12019 	boolean_t	mctl_present = B_FALSE;
12020 	uint_t 		ifindex = 0;
12021 	ip6_pkt_t	ipp;
12022 	uint_t		ipvers;
12023 	uint_t		ip_hdr_len;
12024 
12025 	rptr = mp->b_rptr;
12026 	ASSERT(OK_32PTR(rptr));
12027 	ASSERT(tcp != NULL);
12028 	ipp.ipp_fields = 0;
12029 
12030 	switch DB_TYPE(mp) {
12031 	case M_CTL:
12032 		mp = mp->b_cont;
12033 		if (mp == NULL) {
12034 			freemsg(first_mp);
12035 			return (NULL);
12036 		}
12037 		if (DB_TYPE(mp) != M_DATA) {
12038 			freemsg(first_mp);
12039 			return (NULL);
12040 		}
12041 		mctl_present = B_TRUE;
12042 		break;
12043 	case M_DATA:
12044 		break;
12045 	default:
12046 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12047 		freemsg(mp);
12048 		return (NULL);
12049 	}
12050 	ipvers = IPH_HDR_VERSION(rptr);
12051 	if (ipvers == IPV4_VERSION) {
12052 		if (tcp == NULL) {
12053 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12054 			goto done;
12055 		}
12056 
12057 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12058 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12059 
12060 		/*
12061 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12062 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12063 		 */
12064 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12065 		    mctl_present) {
12066 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
12067 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
12068 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
12069 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
12070 				ipp.ipp_fields |= IPPF_IFINDEX;
12071 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
12072 				ifindex = pinfo->in_pkt_ifindex;
12073 			}
12074 			freeb(first_mp);
12075 			mctl_present = B_FALSE;
12076 		}
12077 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12078 	} else {
12079 		ip6h = (ip6_t *)rptr;
12080 
12081 		ASSERT(ipvers == IPV6_VERSION);
12082 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12083 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12084 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12085 
12086 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12087 			uint8_t	nexthdrp;
12088 
12089 			/* Look for ifindex information */
12090 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12091 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12092 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12093 					BUMP_MIB(&ip_mib, tcpInErrs);
12094 					freemsg(first_mp);
12095 					return (NULL);
12096 				}
12097 
12098 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12099 					ASSERT(ip6i->ip6i_ifindex != 0);
12100 					ipp.ipp_fields |= IPPF_IFINDEX;
12101 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12102 					ifindex = ip6i->ip6i_ifindex;
12103 				}
12104 				rptr = (uchar_t *)&ip6i[1];
12105 				mp->b_rptr = rptr;
12106 				if (rptr == mp->b_wptr) {
12107 					mblk_t *mp1;
12108 					mp1 = mp->b_cont;
12109 					freeb(mp);
12110 					mp = mp1;
12111 					rptr = mp->b_rptr;
12112 				}
12113 				if (MBLKL(mp) < IPV6_HDR_LEN +
12114 				    sizeof (tcph_t)) {
12115 					BUMP_MIB(&ip_mib, tcpInErrs);
12116 					freemsg(first_mp);
12117 					return (NULL);
12118 				}
12119 				ip6h = (ip6_t *)rptr;
12120 			}
12121 
12122 			/*
12123 			 * Find any potentially interesting extension headers
12124 			 * as well as the length of the IPv6 + extension
12125 			 * headers.
12126 			 */
12127 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12128 			/* Verify if this is a TCP packet */
12129 			if (nexthdrp != IPPROTO_TCP) {
12130 				BUMP_MIB(&ip_mib, tcpInErrs);
12131 				freemsg(first_mp);
12132 				return (NULL);
12133 			}
12134 		} else {
12135 			ip_hdr_len = IPV6_HDR_LEN;
12136 		}
12137 	}
12138 
12139 done:
12140 	if (ipversp != NULL)
12141 		*ipversp = ipvers;
12142 	if (ip_hdr_lenp != NULL)
12143 		*ip_hdr_lenp = ip_hdr_len;
12144 	if (ippp != NULL)
12145 		*ippp = ipp;
12146 	if (ifindexp != NULL)
12147 		*ifindexp = ifindex;
12148 	if (mctl_present) {
12149 		freeb(first_mp);
12150 	}
12151 	return (mp);
12152 }
12153 
12154 /*
12155  * Handle M_DATA messages from IP. Its called directly from IP via
12156  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12157  * in this path.
12158  *
12159  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12160  * v4 and v6), we are called through tcp_input() and a M_CTL can
12161  * be present for options but tcp_find_pktinfo() deals with it. We
12162  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12163  *
12164  * The first argument is always the connp/tcp to which the mp belongs.
12165  * There are no exceptions to this rule. The caller has already put
12166  * a reference on this connp/tcp and once tcp_rput_data() returns,
12167  * the squeue will do the refrele.
12168  *
12169  * The TH_SYN for the listener directly go to tcp_conn_request via
12170  * squeue.
12171  *
12172  * sqp: NULL = recursive, sqp != NULL means called from squeue
12173  */
12174 void
12175 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12176 {
12177 	int32_t		bytes_acked;
12178 	int32_t		gap;
12179 	mblk_t		*mp1;
12180 	uint_t		flags;
12181 	uint32_t	new_swnd = 0;
12182 	uchar_t		*iphdr;
12183 	uchar_t		*rptr;
12184 	int32_t		rgap;
12185 	uint32_t	seg_ack;
12186 	int		seg_len;
12187 	uint_t		ip_hdr_len;
12188 	uint32_t	seg_seq;
12189 	tcph_t		*tcph;
12190 	int		urp;
12191 	tcp_opt_t	tcpopt;
12192 	uint_t		ipvers;
12193 	ip6_pkt_t	ipp;
12194 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12195 	uint32_t	cwnd;
12196 	uint32_t	add;
12197 	int		npkt;
12198 	int		mss;
12199 	conn_t		*connp = (conn_t *)arg;
12200 	squeue_t	*sqp = (squeue_t *)arg2;
12201 	tcp_t		*tcp = connp->conn_tcp;
12202 
12203 	/*
12204 	 * RST from fused tcp loopback peer should trigger an unfuse.
12205 	 */
12206 	if (tcp->tcp_fused) {
12207 		TCP_STAT(tcp_fusion_aborted);
12208 		tcp_unfuse(tcp);
12209 	}
12210 
12211 	iphdr = mp->b_rptr;
12212 	rptr = mp->b_rptr;
12213 	ASSERT(OK_32PTR(rptr));
12214 
12215 	/*
12216 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12217 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12218 	 * necessary information.
12219 	 */
12220 	if (IPCL_IS_TCP4(connp)) {
12221 		ipvers = IPV4_VERSION;
12222 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12223 	} else {
12224 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12225 		    NULL, &ipp);
12226 		if (mp == NULL) {
12227 			TCP_STAT(tcp_rput_v6_error);
12228 			return;
12229 		}
12230 		iphdr = mp->b_rptr;
12231 		rptr = mp->b_rptr;
12232 	}
12233 	ASSERT(DB_TYPE(mp) == M_DATA);
12234 
12235 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12236 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12237 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12238 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12239 	seg_len = (int)(mp->b_wptr - rptr) -
12240 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12241 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12242 		do {
12243 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12244 			    (uintptr_t)INT_MAX);
12245 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12246 		} while ((mp1 = mp1->b_cont) != NULL &&
12247 		    mp1->b_datap->db_type == M_DATA);
12248 	}
12249 
12250 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12251 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12252 		    seg_len, tcph);
12253 		return;
12254 	}
12255 
12256 	if (sqp != NULL) {
12257 		/*
12258 		 * This is the correct place to update tcp_last_recv_time. Note
12259 		 * that it is also updated for tcp structure that belongs to
12260 		 * global and listener queues which do not really need updating.
12261 		 * But that should not cause any harm.  And it is updated for
12262 		 * all kinds of incoming segments, not only for data segments.
12263 		 */
12264 		tcp->tcp_last_recv_time = lbolt;
12265 	}
12266 
12267 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12268 
12269 	BUMP_LOCAL(tcp->tcp_ibsegs);
12270 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12271 
12272 	if ((flags & TH_URG) && sqp != NULL) {
12273 		/*
12274 		 * TCP can't handle urgent pointers that arrive before
12275 		 * the connection has been accept()ed since it can't
12276 		 * buffer OOB data.  Discard segment if this happens.
12277 		 *
12278 		 * Nor can it reassemble urgent pointers, so discard
12279 		 * if it's not the next segment expected.
12280 		 *
12281 		 * Otherwise, collapse chain into one mblk (discard if
12282 		 * that fails).  This makes sure the headers, retransmitted
12283 		 * data, and new data all are in the same mblk.
12284 		 */
12285 		ASSERT(mp != NULL);
12286 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
12287 			freemsg(mp);
12288 			return;
12289 		}
12290 		/* Update pointers into message */
12291 		iphdr = rptr = mp->b_rptr;
12292 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12293 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12294 			/*
12295 			 * Since we can't handle any data with this urgent
12296 			 * pointer that is out of sequence, we expunge
12297 			 * the data.  This allows us to still register
12298 			 * the urgent mark and generate the M_PCSIG,
12299 			 * which we can do.
12300 			 */
12301 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12302 			seg_len = 0;
12303 		}
12304 	}
12305 
12306 	switch (tcp->tcp_state) {
12307 	case TCPS_SYN_SENT:
12308 		if (flags & TH_ACK) {
12309 			/*
12310 			 * Note that our stack cannot send data before a
12311 			 * connection is established, therefore the
12312 			 * following check is valid.  Otherwise, it has
12313 			 * to be changed.
12314 			 */
12315 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12316 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12317 				freemsg(mp);
12318 				if (flags & TH_RST)
12319 					return;
12320 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12321 				    tcp, seg_ack, 0, TH_RST);
12322 				return;
12323 			}
12324 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12325 		}
12326 		if (flags & TH_RST) {
12327 			freemsg(mp);
12328 			if (flags & TH_ACK)
12329 				(void) tcp_clean_death(tcp,
12330 				    ECONNREFUSED, 13);
12331 			return;
12332 		}
12333 		if (!(flags & TH_SYN)) {
12334 			freemsg(mp);
12335 			return;
12336 		}
12337 
12338 		/* Process all TCP options. */
12339 		tcp_process_options(tcp, tcph);
12340 		/*
12341 		 * The following changes our rwnd to be a multiple of the
12342 		 * MIN(peer MSS, our MSS) for performance reason.
12343 		 */
12344 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12345 		    tcp->tcp_mss));
12346 
12347 		/* Is the other end ECN capable? */
12348 		if (tcp->tcp_ecn_ok) {
12349 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12350 				tcp->tcp_ecn_ok = B_FALSE;
12351 			}
12352 		}
12353 		/*
12354 		 * Clear ECN flags because it may interfere with later
12355 		 * processing.
12356 		 */
12357 		flags &= ~(TH_ECE|TH_CWR);
12358 
12359 		tcp->tcp_irs = seg_seq;
12360 		tcp->tcp_rack = seg_seq;
12361 		tcp->tcp_rnxt = seg_seq + 1;
12362 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12363 		if (!TCP_IS_DETACHED(tcp)) {
12364 			/* Allocate room for SACK options if needed. */
12365 			if (tcp->tcp_snd_sack_ok) {
12366 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12367 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
12368 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12369 			} else {
12370 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12371 				    tcp->tcp_hdr_len +
12372 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12373 			}
12374 		}
12375 		if (flags & TH_ACK) {
12376 			/*
12377 			 * If we can't get the confirmation upstream, pretend
12378 			 * we didn't even see this one.
12379 			 *
12380 			 * XXX: how can we pretend we didn't see it if we
12381 			 * have updated rnxt et. al.
12382 			 *
12383 			 * For loopback we defer sending up the T_CONN_CON
12384 			 * until after some checks below.
12385 			 */
12386 			mp1 = NULL;
12387 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12388 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12389 				freemsg(mp);
12390 				return;
12391 			}
12392 			/* SYN was acked - making progress */
12393 			if (tcp->tcp_ipversion == IPV6_VERSION)
12394 				tcp->tcp_ip_forward_progress = B_TRUE;
12395 
12396 			/* One for the SYN */
12397 			tcp->tcp_suna = tcp->tcp_iss + 1;
12398 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12399 			tcp->tcp_state = TCPS_ESTABLISHED;
12400 
12401 			/*
12402 			 * If SYN was retransmitted, need to reset all
12403 			 * retransmission info.  This is because this
12404 			 * segment will be treated as a dup ACK.
12405 			 */
12406 			if (tcp->tcp_rexmit) {
12407 				tcp->tcp_rexmit = B_FALSE;
12408 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12409 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12410 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12411 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12412 				tcp->tcp_ms_we_have_waited = 0;
12413 
12414 				/*
12415 				 * Set tcp_cwnd back to 1 MSS, per
12416 				 * recommendation from
12417 				 * draft-floyd-incr-init-win-01.txt,
12418 				 * Increasing TCP's Initial Window.
12419 				 */
12420 				tcp->tcp_cwnd = tcp->tcp_mss;
12421 			}
12422 
12423 			tcp->tcp_swl1 = seg_seq;
12424 			tcp->tcp_swl2 = seg_ack;
12425 
12426 			new_swnd = BE16_TO_U16(tcph->th_win);
12427 			tcp->tcp_swnd = new_swnd;
12428 			if (new_swnd > tcp->tcp_max_swnd)
12429 				tcp->tcp_max_swnd = new_swnd;
12430 
12431 			/*
12432 			 * Always send the three-way handshake ack immediately
12433 			 * in order to make the connection complete as soon as
12434 			 * possible on the accepting host.
12435 			 */
12436 			flags |= TH_ACK_NEEDED;
12437 
12438 			/*
12439 			 * Special case for loopback.  At this point we have
12440 			 * received SYN-ACK from the remote endpoint.  In
12441 			 * order to ensure that both endpoints reach the
12442 			 * fused state prior to any data exchange, the final
12443 			 * ACK needs to be sent before we indicate T_CONN_CON
12444 			 * to the module upstream.
12445 			 */
12446 			if (tcp->tcp_loopback) {
12447 				mblk_t *ack_mp;
12448 
12449 				ASSERT(!tcp->tcp_unfusable);
12450 				ASSERT(mp1 != NULL);
12451 				/*
12452 				 * For loopback, we always get a pure SYN-ACK
12453 				 * and only need to send back the final ACK
12454 				 * with no data (this is because the other
12455 				 * tcp is ours and we don't do T/TCP).  This
12456 				 * final ACK triggers the passive side to
12457 				 * perform fusion in ESTABLISHED state.
12458 				 */
12459 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12460 					if (tcp->tcp_ack_tid != 0) {
12461 						(void) TCP_TIMER_CANCEL(tcp,
12462 						    tcp->tcp_ack_tid);
12463 						tcp->tcp_ack_tid = 0;
12464 					}
12465 					TCP_RECORD_TRACE(tcp, ack_mp,
12466 					    TCP_TRACE_SEND_PKT);
12467 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
12468 					BUMP_LOCAL(tcp->tcp_obsegs);
12469 					BUMP_MIB(&tcp_mib, tcpOutAck);
12470 
12471 					/* Send up T_CONN_CON */
12472 					putnext(tcp->tcp_rq, mp1);
12473 
12474 					freemsg(mp);
12475 					return;
12476 				}
12477 				/*
12478 				 * Forget fusion; we need to handle more
12479 				 * complex cases below.  Send the deferred
12480 				 * T_CONN_CON message upstream and proceed
12481 				 * as usual.  Mark this tcp as not capable
12482 				 * of fusion.
12483 				 */
12484 				TCP_STAT(tcp_fusion_unfusable);
12485 				tcp->tcp_unfusable = B_TRUE;
12486 				putnext(tcp->tcp_rq, mp1);
12487 			}
12488 
12489 			/*
12490 			 * Check to see if there is data to be sent.  If
12491 			 * yes, set the transmit flag.  Then check to see
12492 			 * if received data processing needs to be done.
12493 			 * If not, go straight to xmit_check.  This short
12494 			 * cut is OK as we don't support T/TCP.
12495 			 */
12496 			if (tcp->tcp_unsent)
12497 				flags |= TH_XMIT_NEEDED;
12498 
12499 			if (seg_len == 0 && !(flags & TH_URG)) {
12500 				freemsg(mp);
12501 				goto xmit_check;
12502 			}
12503 
12504 			flags &= ~TH_SYN;
12505 			seg_seq++;
12506 			break;
12507 		}
12508 		tcp->tcp_state = TCPS_SYN_RCVD;
12509 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
12510 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
12511 		if (mp1) {
12512 			mblk_setcred(mp1, tcp->tcp_cred);
12513 			DB_CPID(mp1) = tcp->tcp_cpid;
12514 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
12515 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
12516 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12517 		}
12518 		freemsg(mp);
12519 		return;
12520 	case TCPS_SYN_RCVD:
12521 		if (flags & TH_ACK) {
12522 			/*
12523 			 * In this state, a SYN|ACK packet is either bogus
12524 			 * because the other side must be ACKing our SYN which
12525 			 * indicates it has seen the ACK for their SYN and
12526 			 * shouldn't retransmit it or we're crossing SYNs
12527 			 * on active open.
12528 			 */
12529 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
12530 				freemsg(mp);
12531 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
12532 				    tcp, seg_ack, 0, TH_RST);
12533 				return;
12534 			}
12535 			/*
12536 			 * NOTE: RFC 793 pg. 72 says this should be
12537 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
12538 			 * but that would mean we have an ack that ignored
12539 			 * our SYN.
12540 			 */
12541 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
12542 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12543 				freemsg(mp);
12544 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
12545 				    tcp, seg_ack, 0, TH_RST);
12546 				return;
12547 			}
12548 		}
12549 		break;
12550 	case TCPS_LISTEN:
12551 		/*
12552 		 * Only a TLI listener can come through this path when a
12553 		 * acceptor is going back to be a listener and a packet
12554 		 * for the acceptor hits the classifier. For a socket
12555 		 * listener, this can never happen because a listener
12556 		 * can never accept connection on itself and hence a
12557 		 * socket acceptor can not go back to being a listener.
12558 		 */
12559 		ASSERT(!TCP_IS_SOCKET(tcp));
12560 		/*FALLTHRU*/
12561 	case TCPS_CLOSED:
12562 	case TCPS_BOUND: {
12563 		conn_t	*new_connp;
12564 
12565 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
12566 		if (new_connp != NULL) {
12567 			tcp_reinput(new_connp, mp, connp->conn_sqp);
12568 			return;
12569 		}
12570 		/* We failed to classify. For now just drop the packet */
12571 		freemsg(mp);
12572 		return;
12573 	}
12574 	case TCPS_IDLE:
12575 		/*
12576 		 * Handle the case where the tcp_clean_death() has happened
12577 		 * on a connection (application hasn't closed yet) but a packet
12578 		 * was already queued on squeue before tcp_clean_death()
12579 		 * was processed. Calling tcp_clean_death() twice on same
12580 		 * connection can result in weird behaviour.
12581 		 */
12582 		freemsg(mp);
12583 		return;
12584 	default:
12585 		break;
12586 	}
12587 
12588 	/*
12589 	 * Already on the correct queue/perimeter.
12590 	 * If this is a detached connection and not an eager
12591 	 * connection hanging off a listener then new data
12592 	 * (past the FIN) will cause a reset.
12593 	 * We do a special check here where it
12594 	 * is out of the main line, rather than check
12595 	 * if we are detached every time we see new
12596 	 * data down below.
12597 	 */
12598 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
12599 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
12600 		BUMP_MIB(&tcp_mib, tcpInClosed);
12601 		TCP_RECORD_TRACE(tcp,
12602 		    mp, TCP_TRACE_RECV_PKT);
12603 
12604 		freemsg(mp);
12605 		/*
12606 		 * This could be an SSL closure alert. We're detached so just
12607 		 * acknowledge it this last time.
12608 		 */
12609 		if (tcp->tcp_kssl_ctx != NULL) {
12610 			kssl_release_ctx(tcp->tcp_kssl_ctx);
12611 			tcp->tcp_kssl_ctx = NULL;
12612 
12613 			tcp->tcp_rnxt += seg_len;
12614 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12615 			flags |= TH_ACK_NEEDED;
12616 			goto ack_check;
12617 		}
12618 
12619 		tcp_xmit_ctl("new data when detached", tcp,
12620 		    tcp->tcp_snxt, 0, TH_RST);
12621 		(void) tcp_clean_death(tcp, EPROTO, 12);
12622 		return;
12623 	}
12624 
12625 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12626 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
12627 	new_swnd = BE16_TO_U16(tcph->th_win) <<
12628 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
12629 	mss = tcp->tcp_mss;
12630 
12631 	if (tcp->tcp_snd_ts_ok) {
12632 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
12633 			/*
12634 			 * This segment is not acceptable.
12635 			 * Drop it and send back an ACK.
12636 			 */
12637 			freemsg(mp);
12638 			flags |= TH_ACK_NEEDED;
12639 			goto ack_check;
12640 		}
12641 	} else if (tcp->tcp_snd_sack_ok) {
12642 		ASSERT(tcp->tcp_sack_info != NULL);
12643 		tcpopt.tcp = tcp;
12644 		/*
12645 		 * SACK info in already updated in tcp_parse_options.  Ignore
12646 		 * all other TCP options...
12647 		 */
12648 		(void) tcp_parse_options(tcph, &tcpopt);
12649 	}
12650 try_again:;
12651 	gap = seg_seq - tcp->tcp_rnxt;
12652 	rgap = tcp->tcp_rwnd - (gap + seg_len);
12653 	/*
12654 	 * gap is the amount of sequence space between what we expect to see
12655 	 * and what we got for seg_seq.  A positive value for gap means
12656 	 * something got lost.  A negative value means we got some old stuff.
12657 	 */
12658 	if (gap < 0) {
12659 		/* Old stuff present.  Is the SYN in there? */
12660 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
12661 		    (seg_len != 0)) {
12662 			flags &= ~TH_SYN;
12663 			seg_seq++;
12664 			urp--;
12665 			/* Recompute the gaps after noting the SYN. */
12666 			goto try_again;
12667 		}
12668 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
12669 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
12670 		    (seg_len > -gap ? -gap : seg_len));
12671 		/* Remove the old stuff from seg_len. */
12672 		seg_len += gap;
12673 		/*
12674 		 * Anything left?
12675 		 * Make sure to check for unack'd FIN when rest of data
12676 		 * has been previously ack'd.
12677 		 */
12678 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
12679 			/*
12680 			 * Resets are only valid if they lie within our offered
12681 			 * window.  If the RST bit is set, we just ignore this
12682 			 * segment.
12683 			 */
12684 			if (flags & TH_RST) {
12685 				freemsg(mp);
12686 				return;
12687 			}
12688 
12689 			/*
12690 			 * The arriving of dup data packets indicate that we
12691 			 * may have postponed an ack for too long, or the other
12692 			 * side's RTT estimate is out of shape. Start acking
12693 			 * more often.
12694 			 */
12695 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
12696 			    tcp->tcp_rack_cnt >= 1 &&
12697 			    tcp->tcp_rack_abs_max > 2) {
12698 				tcp->tcp_rack_abs_max--;
12699 			}
12700 			tcp->tcp_rack_cur_max = 1;
12701 
12702 			/*
12703 			 * This segment is "unacceptable".  None of its
12704 			 * sequence space lies within our advertized window.
12705 			 *
12706 			 * Adjust seg_len to the original value for tracing.
12707 			 */
12708 			seg_len -= gap;
12709 			if (tcp->tcp_debug) {
12710 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12711 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
12712 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
12713 				    "seg_len %d, rnxt %u, snxt %u, %s",
12714 				    gap, rgap, flags, seg_seq, seg_ack,
12715 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
12716 				    tcp_display(tcp, NULL,
12717 				    DISP_ADDR_AND_PORT));
12718 			}
12719 
12720 			/*
12721 			 * Arrange to send an ACK in response to the
12722 			 * unacceptable segment per RFC 793 page 69. There
12723 			 * is only one small difference between ours and the
12724 			 * acceptability test in the RFC - we accept ACK-only
12725 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
12726 			 * will be generated.
12727 			 *
12728 			 * Note that we have to ACK an ACK-only packet at least
12729 			 * for stacks that send 0-length keep-alives with
12730 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
12731 			 * section 4.2.3.6. As long as we don't ever generate
12732 			 * an unacceptable packet in response to an incoming
12733 			 * packet that is unacceptable, it should not cause
12734 			 * "ACK wars".
12735 			 */
12736 			flags |=  TH_ACK_NEEDED;
12737 
12738 			/*
12739 			 * Continue processing this segment in order to use the
12740 			 * ACK information it contains, but skip all other
12741 			 * sequence-number processing.	Processing the ACK
12742 			 * information is necessary in order to
12743 			 * re-synchronize connections that may have lost
12744 			 * synchronization.
12745 			 *
12746 			 * We clear seg_len and flag fields related to
12747 			 * sequence number processing as they are not
12748 			 * to be trusted for an unacceptable segment.
12749 			 */
12750 			seg_len = 0;
12751 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
12752 			goto process_ack;
12753 		}
12754 
12755 		/* Fix seg_seq, and chew the gap off the front. */
12756 		seg_seq = tcp->tcp_rnxt;
12757 		urp += gap;
12758 		do {
12759 			mblk_t	*mp2;
12760 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
12761 			    (uintptr_t)UINT_MAX);
12762 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
12763 			if (gap > 0) {
12764 				mp->b_rptr = mp->b_wptr - gap;
12765 				break;
12766 			}
12767 			mp2 = mp;
12768 			mp = mp->b_cont;
12769 			freeb(mp2);
12770 		} while (gap < 0);
12771 		/*
12772 		 * If the urgent data has already been acknowledged, we
12773 		 * should ignore TH_URG below
12774 		 */
12775 		if (urp < 0)
12776 			flags &= ~TH_URG;
12777 	}
12778 	/*
12779 	 * rgap is the amount of stuff received out of window.  A negative
12780 	 * value is the amount out of window.
12781 	 */
12782 	if (rgap < 0) {
12783 		mblk_t	*mp2;
12784 
12785 		if (tcp->tcp_rwnd == 0) {
12786 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
12787 		} else {
12788 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
12789 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
12790 		}
12791 
12792 		/*
12793 		 * seg_len does not include the FIN, so if more than
12794 		 * just the FIN is out of window, we act like we don't
12795 		 * see it.  (If just the FIN is out of window, rgap
12796 		 * will be zero and we will go ahead and acknowledge
12797 		 * the FIN.)
12798 		 */
12799 		flags &= ~TH_FIN;
12800 
12801 		/* Fix seg_len and make sure there is something left. */
12802 		seg_len += rgap;
12803 		if (seg_len <= 0) {
12804 			/*
12805 			 * Resets are only valid if they lie within our offered
12806 			 * window.  If the RST bit is set, we just ignore this
12807 			 * segment.
12808 			 */
12809 			if (flags & TH_RST) {
12810 				freemsg(mp);
12811 				return;
12812 			}
12813 
12814 			/* Per RFC 793, we need to send back an ACK. */
12815 			flags |= TH_ACK_NEEDED;
12816 
12817 			/*
12818 			 * Send SIGURG as soon as possible i.e. even
12819 			 * if the TH_URG was delivered in a window probe
12820 			 * packet (which will be unacceptable).
12821 			 *
12822 			 * We generate a signal if none has been generated
12823 			 * for this connection or if this is a new urgent
12824 			 * byte. Also send a zero-length "unmarked" message
12825 			 * to inform SIOCATMARK that this is not the mark.
12826 			 *
12827 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
12828 			 * is sent up. This plus the check for old data
12829 			 * (gap >= 0) handles the wraparound of the sequence
12830 			 * number space without having to always track the
12831 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
12832 			 * this max in its rcv_up variable).
12833 			 *
12834 			 * This prevents duplicate SIGURGS due to a "late"
12835 			 * zero-window probe when the T_EXDATA_IND has already
12836 			 * been sent up.
12837 			 */
12838 			if ((flags & TH_URG) &&
12839 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
12840 			    tcp->tcp_urp_last))) {
12841 				mp1 = allocb(0, BPRI_MED);
12842 				if (mp1 == NULL) {
12843 					freemsg(mp);
12844 					return;
12845 				}
12846 				if (!TCP_IS_DETACHED(tcp) &&
12847 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
12848 				    SIGURG)) {
12849 					/* Try again on the rexmit. */
12850 					freemsg(mp1);
12851 					freemsg(mp);
12852 					return;
12853 				}
12854 				/*
12855 				 * If the next byte would be the mark
12856 				 * then mark with MARKNEXT else mark
12857 				 * with NOTMARKNEXT.
12858 				 */
12859 				if (gap == 0 && urp == 0)
12860 					mp1->b_flag |= MSGMARKNEXT;
12861 				else
12862 					mp1->b_flag |= MSGNOTMARKNEXT;
12863 				freemsg(tcp->tcp_urp_mark_mp);
12864 				tcp->tcp_urp_mark_mp = mp1;
12865 				flags |= TH_SEND_URP_MARK;
12866 				tcp->tcp_urp_last_valid = B_TRUE;
12867 				tcp->tcp_urp_last = urp + seg_seq;
12868 			}
12869 			/*
12870 			 * If this is a zero window probe, continue to
12871 			 * process the ACK part.  But we need to set seg_len
12872 			 * to 0 to avoid data processing.  Otherwise just
12873 			 * drop the segment and send back an ACK.
12874 			 */
12875 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
12876 				flags &= ~(TH_SYN | TH_URG);
12877 				seg_len = 0;
12878 				goto process_ack;
12879 			} else {
12880 				freemsg(mp);
12881 				goto ack_check;
12882 			}
12883 		}
12884 		/* Pitch out of window stuff off the end. */
12885 		rgap = seg_len;
12886 		mp2 = mp;
12887 		do {
12888 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
12889 			    (uintptr_t)INT_MAX);
12890 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
12891 			if (rgap < 0) {
12892 				mp2->b_wptr += rgap;
12893 				if ((mp1 = mp2->b_cont) != NULL) {
12894 					mp2->b_cont = NULL;
12895 					freemsg(mp1);
12896 				}
12897 				break;
12898 			}
12899 		} while ((mp2 = mp2->b_cont) != NULL);
12900 	}
12901 ok:;
12902 	/*
12903 	 * TCP should check ECN info for segments inside the window only.
12904 	 * Therefore the check should be done here.
12905 	 */
12906 	if (tcp->tcp_ecn_ok) {
12907 		if (flags & TH_CWR) {
12908 			tcp->tcp_ecn_echo_on = B_FALSE;
12909 		}
12910 		/*
12911 		 * Note that both ECN_CE and CWR can be set in the
12912 		 * same segment.  In this case, we once again turn
12913 		 * on ECN_ECHO.
12914 		 */
12915 		if (tcp->tcp_ipversion == IPV4_VERSION) {
12916 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
12917 
12918 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
12919 				tcp->tcp_ecn_echo_on = B_TRUE;
12920 			}
12921 		} else {
12922 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
12923 
12924 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
12925 			    htonl(IPH_ECN_CE << 20)) {
12926 				tcp->tcp_ecn_echo_on = B_TRUE;
12927 			}
12928 		}
12929 	}
12930 
12931 	/*
12932 	 * Check whether we can update tcp_ts_recent.  This test is
12933 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
12934 	 * Extensions for High Performance: An Update", Internet Draft.
12935 	 */
12936 	if (tcp->tcp_snd_ts_ok &&
12937 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
12938 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
12939 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12940 		tcp->tcp_last_rcv_lbolt = lbolt64;
12941 	}
12942 
12943 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
12944 		/*
12945 		 * FIN in an out of order segment.  We record this in
12946 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
12947 		 * Clear the FIN so that any check on FIN flag will fail.
12948 		 * Remember that FIN also counts in the sequence number
12949 		 * space.  So we need to ack out of order FIN only segments.
12950 		 */
12951 		if (flags & TH_FIN) {
12952 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
12953 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
12954 			flags &= ~TH_FIN;
12955 			flags |= TH_ACK_NEEDED;
12956 		}
12957 		if (seg_len > 0) {
12958 			/* Fill in the SACK blk list. */
12959 			if (tcp->tcp_snd_sack_ok) {
12960 				ASSERT(tcp->tcp_sack_info != NULL);
12961 				tcp_sack_insert(tcp->tcp_sack_list,
12962 				    seg_seq, seg_seq + seg_len,
12963 				    &(tcp->tcp_num_sack_blk));
12964 			}
12965 
12966 			/*
12967 			 * Attempt reassembly and see if we have something
12968 			 * ready to go.
12969 			 */
12970 			mp = tcp_reass(tcp, mp, seg_seq);
12971 			/* Always ack out of order packets */
12972 			flags |= TH_ACK_NEEDED | TH_PUSH;
12973 			if (mp) {
12974 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
12975 				    (uintptr_t)INT_MAX);
12976 				seg_len = mp->b_cont ? msgdsize(mp) :
12977 					(int)(mp->b_wptr - mp->b_rptr);
12978 				seg_seq = tcp->tcp_rnxt;
12979 				/*
12980 				 * A gap is filled and the seq num and len
12981 				 * of the gap match that of a previously
12982 				 * received FIN, put the FIN flag back in.
12983 				 */
12984 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
12985 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
12986 					flags |= TH_FIN;
12987 					tcp->tcp_valid_bits &=
12988 					    ~TCP_OFO_FIN_VALID;
12989 				}
12990 			} else {
12991 				/*
12992 				 * Keep going even with NULL mp.
12993 				 * There may be a useful ACK or something else
12994 				 * we don't want to miss.
12995 				 *
12996 				 * But TCP should not perform fast retransmit
12997 				 * because of the ack number.  TCP uses
12998 				 * seg_len == 0 to determine if it is a pure
12999 				 * ACK.  And this is not a pure ACK.
13000 				 */
13001 				seg_len = 0;
13002 				ofo_seg = B_TRUE;
13003 			}
13004 		}
13005 	} else if (seg_len > 0) {
13006 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
13007 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
13008 		/*
13009 		 * If an out of order FIN was received before, and the seq
13010 		 * num and len of the new segment match that of the FIN,
13011 		 * put the FIN flag back in.
13012 		 */
13013 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13014 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13015 			flags |= TH_FIN;
13016 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13017 		}
13018 	}
13019 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13020 	if (flags & TH_RST) {
13021 		freemsg(mp);
13022 		switch (tcp->tcp_state) {
13023 		case TCPS_SYN_RCVD:
13024 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13025 			break;
13026 		case TCPS_ESTABLISHED:
13027 		case TCPS_FIN_WAIT_1:
13028 		case TCPS_FIN_WAIT_2:
13029 		case TCPS_CLOSE_WAIT:
13030 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13031 			break;
13032 		case TCPS_CLOSING:
13033 		case TCPS_LAST_ACK:
13034 			(void) tcp_clean_death(tcp, 0, 16);
13035 			break;
13036 		default:
13037 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13038 			(void) tcp_clean_death(tcp, ENXIO, 17);
13039 			break;
13040 		}
13041 		return;
13042 	}
13043 	if (flags & TH_SYN) {
13044 		/*
13045 		 * See RFC 793, Page 71
13046 		 *
13047 		 * The seq number must be in the window as it should
13048 		 * be "fixed" above.  If it is outside window, it should
13049 		 * be already rejected.  Note that we allow seg_seq to be
13050 		 * rnxt + rwnd because we want to accept 0 window probe.
13051 		 */
13052 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13053 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13054 		freemsg(mp);
13055 		/*
13056 		 * If the ACK flag is not set, just use our snxt as the
13057 		 * seq number of the RST segment.
13058 		 */
13059 		if (!(flags & TH_ACK)) {
13060 			seg_ack = tcp->tcp_snxt;
13061 		}
13062 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13063 		    TH_RST|TH_ACK);
13064 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13065 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13066 		return;
13067 	}
13068 	/*
13069 	 * urp could be -1 when the urp field in the packet is 0
13070 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13071 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13072 	 */
13073 	if (flags & TH_URG && urp >= 0) {
13074 		if (!tcp->tcp_urp_last_valid ||
13075 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13076 			/*
13077 			 * If we haven't generated the signal yet for this
13078 			 * urgent pointer value, do it now.  Also, send up a
13079 			 * zero-length M_DATA indicating whether or not this is
13080 			 * the mark. The latter is not needed when a
13081 			 * T_EXDATA_IND is sent up. However, if there are
13082 			 * allocation failures this code relies on the sender
13083 			 * retransmitting and the socket code for determining
13084 			 * the mark should not block waiting for the peer to
13085 			 * transmit. Thus, for simplicity we always send up the
13086 			 * mark indication.
13087 			 */
13088 			mp1 = allocb(0, BPRI_MED);
13089 			if (mp1 == NULL) {
13090 				freemsg(mp);
13091 				return;
13092 			}
13093 			if (!TCP_IS_DETACHED(tcp) &&
13094 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13095 				/* Try again on the rexmit. */
13096 				freemsg(mp1);
13097 				freemsg(mp);
13098 				return;
13099 			}
13100 			/*
13101 			 * Mark with NOTMARKNEXT for now.
13102 			 * The code below will change this to MARKNEXT
13103 			 * if we are at the mark.
13104 			 *
13105 			 * If there are allocation failures (e.g. in dupmsg
13106 			 * below) the next time tcp_rput_data sees the urgent
13107 			 * segment it will send up the MSG*MARKNEXT message.
13108 			 */
13109 			mp1->b_flag |= MSGNOTMARKNEXT;
13110 			freemsg(tcp->tcp_urp_mark_mp);
13111 			tcp->tcp_urp_mark_mp = mp1;
13112 			flags |= TH_SEND_URP_MARK;
13113 #ifdef DEBUG
13114 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13115 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13116 			    "last %x, %s",
13117 			    seg_seq, urp, tcp->tcp_urp_last,
13118 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13119 #endif /* DEBUG */
13120 			tcp->tcp_urp_last_valid = B_TRUE;
13121 			tcp->tcp_urp_last = urp + seg_seq;
13122 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13123 			/*
13124 			 * An allocation failure prevented the previous
13125 			 * tcp_rput_data from sending up the allocated
13126 			 * MSG*MARKNEXT message - send it up this time
13127 			 * around.
13128 			 */
13129 			flags |= TH_SEND_URP_MARK;
13130 		}
13131 
13132 		/*
13133 		 * If the urgent byte is in this segment, make sure that it is
13134 		 * all by itself.  This makes it much easier to deal with the
13135 		 * possibility of an allocation failure on the T_exdata_ind.
13136 		 * Note that seg_len is the number of bytes in the segment, and
13137 		 * urp is the offset into the segment of the urgent byte.
13138 		 * urp < seg_len means that the urgent byte is in this segment.
13139 		 */
13140 		if (urp < seg_len) {
13141 			if (seg_len != 1) {
13142 				uint32_t  tmp_rnxt;
13143 				/*
13144 				 * Break it up and feed it back in.
13145 				 * Re-attach the IP header.
13146 				 */
13147 				mp->b_rptr = iphdr;
13148 				if (urp > 0) {
13149 					/*
13150 					 * There is stuff before the urgent
13151 					 * byte.
13152 					 */
13153 					mp1 = dupmsg(mp);
13154 					if (!mp1) {
13155 						/*
13156 						 * Trim from urgent byte on.
13157 						 * The rest will come back.
13158 						 */
13159 						(void) adjmsg(mp,
13160 						    urp - seg_len);
13161 						tcp_rput_data(connp,
13162 						    mp, NULL);
13163 						return;
13164 					}
13165 					(void) adjmsg(mp1, urp - seg_len);
13166 					/* Feed this piece back in. */
13167 					tmp_rnxt = tcp->tcp_rnxt;
13168 					tcp_rput_data(connp, mp1, NULL);
13169 					/*
13170 					 * If the data passed back in was not
13171 					 * processed (ie: bad ACK) sending
13172 					 * the remainder back in will cause a
13173 					 * loop. In this case, drop the
13174 					 * packet and let the sender try
13175 					 * sending a good packet.
13176 					 */
13177 					if (tmp_rnxt == tcp->tcp_rnxt) {
13178 						freemsg(mp);
13179 						return;
13180 					}
13181 				}
13182 				if (urp != seg_len - 1) {
13183 					uint32_t  tmp_rnxt;
13184 					/*
13185 					 * There is stuff after the urgent
13186 					 * byte.
13187 					 */
13188 					mp1 = dupmsg(mp);
13189 					if (!mp1) {
13190 						/*
13191 						 * Trim everything beyond the
13192 						 * urgent byte.  The rest will
13193 						 * come back.
13194 						 */
13195 						(void) adjmsg(mp,
13196 						    urp + 1 - seg_len);
13197 						tcp_rput_data(connp,
13198 						    mp, NULL);
13199 						return;
13200 					}
13201 					(void) adjmsg(mp1, urp + 1 - seg_len);
13202 					tmp_rnxt = tcp->tcp_rnxt;
13203 					tcp_rput_data(connp, mp1, NULL);
13204 					/*
13205 					 * If the data passed back in was not
13206 					 * processed (ie: bad ACK) sending
13207 					 * the remainder back in will cause a
13208 					 * loop. In this case, drop the
13209 					 * packet and let the sender try
13210 					 * sending a good packet.
13211 					 */
13212 					if (tmp_rnxt == tcp->tcp_rnxt) {
13213 						freemsg(mp);
13214 						return;
13215 					}
13216 				}
13217 				tcp_rput_data(connp, mp, NULL);
13218 				return;
13219 			}
13220 			/*
13221 			 * This segment contains only the urgent byte.  We
13222 			 * have to allocate the T_exdata_ind, if we can.
13223 			 */
13224 			if (!tcp->tcp_urp_mp) {
13225 				struct T_exdata_ind *tei;
13226 				mp1 = allocb(sizeof (struct T_exdata_ind),
13227 				    BPRI_MED);
13228 				if (!mp1) {
13229 					/*
13230 					 * Sigh... It'll be back.
13231 					 * Generate any MSG*MARK message now.
13232 					 */
13233 					freemsg(mp);
13234 					seg_len = 0;
13235 					if (flags & TH_SEND_URP_MARK) {
13236 
13237 
13238 						ASSERT(tcp->tcp_urp_mark_mp);
13239 						tcp->tcp_urp_mark_mp->b_flag &=
13240 							~MSGNOTMARKNEXT;
13241 						tcp->tcp_urp_mark_mp->b_flag |=
13242 							MSGMARKNEXT;
13243 					}
13244 					goto ack_check;
13245 				}
13246 				mp1->b_datap->db_type = M_PROTO;
13247 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13248 				tei->PRIM_type = T_EXDATA_IND;
13249 				tei->MORE_flag = 0;
13250 				mp1->b_wptr = (uchar_t *)&tei[1];
13251 				tcp->tcp_urp_mp = mp1;
13252 #ifdef DEBUG
13253 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13254 				    "tcp_rput: allocated exdata_ind %s",
13255 				    tcp_display(tcp, NULL,
13256 				    DISP_PORT_ONLY));
13257 #endif /* DEBUG */
13258 				/*
13259 				 * There is no need to send a separate MSG*MARK
13260 				 * message since the T_EXDATA_IND will be sent
13261 				 * now.
13262 				 */
13263 				flags &= ~TH_SEND_URP_MARK;
13264 				freemsg(tcp->tcp_urp_mark_mp);
13265 				tcp->tcp_urp_mark_mp = NULL;
13266 			}
13267 			/*
13268 			 * Now we are all set.  On the next putnext upstream,
13269 			 * tcp_urp_mp will be non-NULL and will get prepended
13270 			 * to what has to be this piece containing the urgent
13271 			 * byte.  If for any reason we abort this segment below,
13272 			 * if it comes back, we will have this ready, or it
13273 			 * will get blown off in close.
13274 			 */
13275 		} else if (urp == seg_len) {
13276 			/*
13277 			 * The urgent byte is the next byte after this sequence
13278 			 * number. If there is data it is marked with
13279 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13280 			 * since it is not needed. Otherwise, if the code
13281 			 * above just allocated a zero-length tcp_urp_mark_mp
13282 			 * message, that message is tagged with MSGMARKNEXT.
13283 			 * Sending up these MSGMARKNEXT messages makes
13284 			 * SIOCATMARK work correctly even though
13285 			 * the T_EXDATA_IND will not be sent up until the
13286 			 * urgent byte arrives.
13287 			 */
13288 			if (seg_len != 0) {
13289 				flags |= TH_MARKNEXT_NEEDED;
13290 				freemsg(tcp->tcp_urp_mark_mp);
13291 				tcp->tcp_urp_mark_mp = NULL;
13292 				flags &= ~TH_SEND_URP_MARK;
13293 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13294 				flags |= TH_SEND_URP_MARK;
13295 				tcp->tcp_urp_mark_mp->b_flag &=
13296 					~MSGNOTMARKNEXT;
13297 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13298 			}
13299 #ifdef DEBUG
13300 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13301 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13302 			    seg_len, flags,
13303 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13304 #endif /* DEBUG */
13305 		} else {
13306 			/* Data left until we hit mark */
13307 #ifdef DEBUG
13308 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13309 			    "tcp_rput: URP %d bytes left, %s",
13310 			    urp - seg_len, tcp_display(tcp, NULL,
13311 			    DISP_PORT_ONLY));
13312 #endif /* DEBUG */
13313 		}
13314 	}
13315 
13316 process_ack:
13317 	if (!(flags & TH_ACK)) {
13318 		freemsg(mp);
13319 		goto xmit_check;
13320 	}
13321 	}
13322 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13323 
13324 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13325 		tcp->tcp_ip_forward_progress = B_TRUE;
13326 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13327 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13328 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13329 			/* 3-way handshake complete - pass up the T_CONN_IND */
13330 			tcp_t	*listener = tcp->tcp_listener;
13331 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13332 
13333 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13334 			/*
13335 			 * We are here means eager is fine but it can
13336 			 * get a TH_RST at any point between now and till
13337 			 * accept completes and disappear. We need to
13338 			 * ensure that reference to eager is valid after
13339 			 * we get out of eager's perimeter. So we do
13340 			 * an extra refhold.
13341 			 */
13342 			CONN_INC_REF(connp);
13343 
13344 			/*
13345 			 * The listener also exists because of the refhold
13346 			 * done in tcp_conn_request. Its possible that it
13347 			 * might have closed. We will check that once we
13348 			 * get inside listeners context.
13349 			 */
13350 			CONN_INC_REF(listener->tcp_connp);
13351 			if (listener->tcp_connp->conn_sqp ==
13352 			    connp->conn_sqp) {
13353 				tcp_send_conn_ind(listener->tcp_connp, mp,
13354 				    listener->tcp_connp->conn_sqp);
13355 				CONN_DEC_REF(listener->tcp_connp);
13356 			} else if (!tcp->tcp_loopback) {
13357 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
13358 				    tcp_send_conn_ind,
13359 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
13360 			} else {
13361 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
13362 				    tcp_send_conn_ind, listener->tcp_connp,
13363 				    SQTAG_TCP_CONN_IND);
13364 			}
13365 		}
13366 
13367 		if (tcp->tcp_active_open) {
13368 			/*
13369 			 * We are seeing the final ack in the three way
13370 			 * hand shake of a active open'ed connection
13371 			 * so we must send up a T_CONN_CON
13372 			 */
13373 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13374 				freemsg(mp);
13375 				return;
13376 			}
13377 			/*
13378 			 * Don't fuse the loopback endpoints for
13379 			 * simultaneous active opens.
13380 			 */
13381 			if (tcp->tcp_loopback) {
13382 				TCP_STAT(tcp_fusion_unfusable);
13383 				tcp->tcp_unfusable = B_TRUE;
13384 			}
13385 		}
13386 
13387 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
13388 		bytes_acked--;
13389 		/* SYN was acked - making progress */
13390 		if (tcp->tcp_ipversion == IPV6_VERSION)
13391 			tcp->tcp_ip_forward_progress = B_TRUE;
13392 
13393 		/*
13394 		 * If SYN was retransmitted, need to reset all
13395 		 * retransmission info as this segment will be
13396 		 * treated as a dup ACK.
13397 		 */
13398 		if (tcp->tcp_rexmit) {
13399 			tcp->tcp_rexmit = B_FALSE;
13400 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13401 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
13402 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13403 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13404 			tcp->tcp_ms_we_have_waited = 0;
13405 			tcp->tcp_cwnd = mss;
13406 		}
13407 
13408 		/*
13409 		 * We set the send window to zero here.
13410 		 * This is needed if there is data to be
13411 		 * processed already on the queue.
13412 		 * Later (at swnd_update label), the
13413 		 * "new_swnd > tcp_swnd" condition is satisfied
13414 		 * the XMIT_NEEDED flag is set in the current
13415 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
13416 		 * called if there is already data on queue in
13417 		 * this state.
13418 		 */
13419 		tcp->tcp_swnd = 0;
13420 
13421 		if (new_swnd > tcp->tcp_max_swnd)
13422 			tcp->tcp_max_swnd = new_swnd;
13423 		tcp->tcp_swl1 = seg_seq;
13424 		tcp->tcp_swl2 = seg_ack;
13425 		tcp->tcp_state = TCPS_ESTABLISHED;
13426 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13427 
13428 		/* Fuse when both sides are in ESTABLISHED state */
13429 		if (tcp->tcp_loopback && do_tcp_fusion)
13430 			tcp_fuse(tcp, iphdr, tcph);
13431 
13432 	}
13433 	/* This code follows 4.4BSD-Lite2 mostly. */
13434 	if (bytes_acked < 0)
13435 		goto est;
13436 
13437 	/*
13438 	 * If TCP is ECN capable and the congestion experience bit is
13439 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
13440 	 * done once per window (or more loosely, per RTT).
13441 	 */
13442 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
13443 		tcp->tcp_cwr = B_FALSE;
13444 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
13445 		if (!tcp->tcp_cwr) {
13446 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
13447 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
13448 			tcp->tcp_cwnd = npkt * mss;
13449 			/*
13450 			 * If the cwnd is 0, use the timer to clock out
13451 			 * new segments.  This is required by the ECN spec.
13452 			 */
13453 			if (npkt == 0) {
13454 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13455 				/*
13456 				 * This makes sure that when the ACK comes
13457 				 * back, we will increase tcp_cwnd by 1 MSS.
13458 				 */
13459 				tcp->tcp_cwnd_cnt = 0;
13460 			}
13461 			tcp->tcp_cwr = B_TRUE;
13462 			/*
13463 			 * This marks the end of the current window of in
13464 			 * flight data.  That is why we don't use
13465 			 * tcp_suna + tcp_swnd.  Only data in flight can
13466 			 * provide ECN info.
13467 			 */
13468 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13469 			tcp->tcp_ecn_cwr_sent = B_FALSE;
13470 		}
13471 	}
13472 
13473 	mp1 = tcp->tcp_xmit_head;
13474 	if (bytes_acked == 0) {
13475 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
13476 			int dupack_cnt;
13477 
13478 			BUMP_MIB(&tcp_mib, tcpInDupAck);
13479 			/*
13480 			 * Fast retransmit.  When we have seen exactly three
13481 			 * identical ACKs while we have unacked data
13482 			 * outstanding we take it as a hint that our peer
13483 			 * dropped something.
13484 			 *
13485 			 * If TCP is retransmitting, don't do fast retransmit.
13486 			 */
13487 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
13488 			    ! tcp->tcp_rexmit) {
13489 				/* Do Limited Transmit */
13490 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
13491 				    tcp_dupack_fast_retransmit) {
13492 					/*
13493 					 * RFC 3042
13494 					 *
13495 					 * What we need to do is temporarily
13496 					 * increase tcp_cwnd so that new
13497 					 * data can be sent if it is allowed
13498 					 * by the receive window (tcp_rwnd).
13499 					 * tcp_wput_data() will take care of
13500 					 * the rest.
13501 					 *
13502 					 * If the connection is SACK capable,
13503 					 * only do limited xmit when there
13504 					 * is SACK info.
13505 					 *
13506 					 * Note how tcp_cwnd is incremented.
13507 					 * The first dup ACK will increase
13508 					 * it by 1 MSS.  The second dup ACK
13509 					 * will increase it by 2 MSS.  This
13510 					 * means that only 1 new segment will
13511 					 * be sent for each dup ACK.
13512 					 */
13513 					if (tcp->tcp_unsent > 0 &&
13514 					    (!tcp->tcp_snd_sack_ok ||
13515 					    (tcp->tcp_snd_sack_ok &&
13516 					    tcp->tcp_notsack_list != NULL))) {
13517 						tcp->tcp_cwnd += mss <<
13518 						    (tcp->tcp_dupack_cnt - 1);
13519 						flags |= TH_LIMIT_XMIT;
13520 					}
13521 				} else if (dupack_cnt ==
13522 				    tcp_dupack_fast_retransmit) {
13523 
13524 				/*
13525 				 * If we have reduced tcp_ssthresh
13526 				 * because of ECN, do not reduce it again
13527 				 * unless it is already one window of data
13528 				 * away.  After one window of data, tcp_cwr
13529 				 * should then be cleared.  Note that
13530 				 * for non ECN capable connection, tcp_cwr
13531 				 * should always be false.
13532 				 *
13533 				 * Adjust cwnd since the duplicate
13534 				 * ack indicates that a packet was
13535 				 * dropped (due to congestion.)
13536 				 */
13537 				if (!tcp->tcp_cwr) {
13538 					npkt = ((tcp->tcp_snxt -
13539 					    tcp->tcp_suna) >> 1) / mss;
13540 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13541 					    mss;
13542 					tcp->tcp_cwnd = (npkt +
13543 					    tcp->tcp_dupack_cnt) * mss;
13544 				}
13545 				if (tcp->tcp_ecn_ok) {
13546 					tcp->tcp_cwr = B_TRUE;
13547 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13548 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13549 				}
13550 
13551 				/*
13552 				 * We do Hoe's algorithm.  Refer to her
13553 				 * paper "Improving the Start-up Behavior
13554 				 * of a Congestion Control Scheme for TCP,"
13555 				 * appeared in SIGCOMM'96.
13556 				 *
13557 				 * Save highest seq no we have sent so far.
13558 				 * Be careful about the invisible FIN byte.
13559 				 */
13560 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13561 				    (tcp->tcp_unsent == 0)) {
13562 					tcp->tcp_rexmit_max = tcp->tcp_fss;
13563 				} else {
13564 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
13565 				}
13566 
13567 				/*
13568 				 * Do not allow bursty traffic during.
13569 				 * fast recovery.  Refer to Fall and Floyd's
13570 				 * paper "Simulation-based Comparisons of
13571 				 * Tahoe, Reno and SACK TCP" (in CCR?)
13572 				 * This is a best current practise.
13573 				 */
13574 				tcp->tcp_snd_burst = TCP_CWND_SS;
13575 
13576 				/*
13577 				 * For SACK:
13578 				 * Calculate tcp_pipe, which is the
13579 				 * estimated number of bytes in
13580 				 * network.
13581 				 *
13582 				 * tcp_fack is the highest sack'ed seq num
13583 				 * TCP has received.
13584 				 *
13585 				 * tcp_pipe is explained in the above quoted
13586 				 * Fall and Floyd's paper.  tcp_fack is
13587 				 * explained in Mathis and Mahdavi's
13588 				 * "Forward Acknowledgment: Refining TCP
13589 				 * Congestion Control" in SIGCOMM '96.
13590 				 */
13591 				if (tcp->tcp_snd_sack_ok) {
13592 					ASSERT(tcp->tcp_sack_info != NULL);
13593 					if (tcp->tcp_notsack_list != NULL) {
13594 						tcp->tcp_pipe = tcp->tcp_snxt -
13595 						    tcp->tcp_fack;
13596 						tcp->tcp_sack_snxt = seg_ack;
13597 						flags |= TH_NEED_SACK_REXMIT;
13598 					} else {
13599 						/*
13600 						 * Always initialize tcp_pipe
13601 						 * even though we don't have
13602 						 * any SACK info.  If later
13603 						 * we get SACK info and
13604 						 * tcp_pipe is not initialized,
13605 						 * funny things will happen.
13606 						 */
13607 						tcp->tcp_pipe =
13608 						    tcp->tcp_cwnd_ssthresh;
13609 					}
13610 				} else {
13611 					flags |= TH_REXMIT_NEEDED;
13612 				} /* tcp_snd_sack_ok */
13613 
13614 				} else {
13615 					/*
13616 					 * Here we perform congestion
13617 					 * avoidance, but NOT slow start.
13618 					 * This is known as the Fast
13619 					 * Recovery Algorithm.
13620 					 */
13621 					if (tcp->tcp_snd_sack_ok &&
13622 					    tcp->tcp_notsack_list != NULL) {
13623 						flags |= TH_NEED_SACK_REXMIT;
13624 						tcp->tcp_pipe -= mss;
13625 						if (tcp->tcp_pipe < 0)
13626 							tcp->tcp_pipe = 0;
13627 					} else {
13628 					/*
13629 					 * We know that one more packet has
13630 					 * left the pipe thus we can update
13631 					 * cwnd.
13632 					 */
13633 					cwnd = tcp->tcp_cwnd + mss;
13634 					if (cwnd > tcp->tcp_cwnd_max)
13635 						cwnd = tcp->tcp_cwnd_max;
13636 					tcp->tcp_cwnd = cwnd;
13637 					if (tcp->tcp_unsent > 0)
13638 						flags |= TH_XMIT_NEEDED;
13639 					}
13640 				}
13641 			}
13642 		} else if (tcp->tcp_zero_win_probe) {
13643 			/*
13644 			 * If the window has opened, need to arrange
13645 			 * to send additional data.
13646 			 */
13647 			if (new_swnd != 0) {
13648 				/* tcp_suna != tcp_snxt */
13649 				/* Packet contains a window update */
13650 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
13651 				tcp->tcp_zero_win_probe = 0;
13652 				tcp->tcp_timer_backoff = 0;
13653 				tcp->tcp_ms_we_have_waited = 0;
13654 
13655 				/*
13656 				 * Transmit starting with tcp_suna since
13657 				 * the one byte probe is not ack'ed.
13658 				 * If TCP has sent more than one identical
13659 				 * probe, tcp_rexmit will be set.  That means
13660 				 * tcp_ss_rexmit() will send out the one
13661 				 * byte along with new data.  Otherwise,
13662 				 * fake the retransmission.
13663 				 */
13664 				flags |= TH_XMIT_NEEDED;
13665 				if (!tcp->tcp_rexmit) {
13666 					tcp->tcp_rexmit = B_TRUE;
13667 					tcp->tcp_dupack_cnt = 0;
13668 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13669 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
13670 				}
13671 			}
13672 		}
13673 		goto swnd_update;
13674 	}
13675 
13676 	/*
13677 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
13678 	 * If the ACK value acks something that we have not yet sent, it might
13679 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
13680 	 * other side.
13681 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
13682 	 * state is handled above, so we can always just drop the segment and
13683 	 * send an ACK here.
13684 	 *
13685 	 * Should we send ACKs in response to ACK only segments?
13686 	 */
13687 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13688 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
13689 		/* drop the received segment */
13690 		freemsg(mp);
13691 
13692 		/*
13693 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
13694 		 * greater than 0, check if the number of such
13695 		 * bogus ACks is greater than that count.  If yes,
13696 		 * don't send back any ACK.  This prevents TCP from
13697 		 * getting into an ACK storm if somehow an attacker
13698 		 * successfully spoofs an acceptable segment to our
13699 		 * peer.
13700 		 */
13701 		if (tcp_drop_ack_unsent_cnt > 0 &&
13702 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
13703 			TCP_STAT(tcp_in_ack_unsent_drop);
13704 			return;
13705 		}
13706 		mp = tcp_ack_mp(tcp);
13707 		if (mp != NULL) {
13708 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
13709 			BUMP_LOCAL(tcp->tcp_obsegs);
13710 			BUMP_MIB(&tcp_mib, tcpOutAck);
13711 			tcp_send_data(tcp, tcp->tcp_wq, mp);
13712 		}
13713 		return;
13714 	}
13715 
13716 	/*
13717 	 * TCP gets a new ACK, update the notsack'ed list to delete those
13718 	 * blocks that are covered by this ACK.
13719 	 */
13720 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
13721 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
13722 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
13723 	}
13724 
13725 	/*
13726 	 * If we got an ACK after fast retransmit, check to see
13727 	 * if it is a partial ACK.  If it is not and the congestion
13728 	 * window was inflated to account for the other side's
13729 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
13730 	 */
13731 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
13732 		ASSERT(tcp->tcp_rexmit == B_FALSE);
13733 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
13734 			tcp->tcp_dupack_cnt = 0;
13735 			/*
13736 			 * Restore the orig tcp_cwnd_ssthresh after
13737 			 * fast retransmit phase.
13738 			 */
13739 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
13740 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
13741 			}
13742 			tcp->tcp_rexmit_max = seg_ack;
13743 			tcp->tcp_cwnd_cnt = 0;
13744 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13745 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13746 
13747 			/*
13748 			 * Remove all notsack info to avoid confusion with
13749 			 * the next fast retrasnmit/recovery phase.
13750 			 */
13751 			if (tcp->tcp_snd_sack_ok &&
13752 			    tcp->tcp_notsack_list != NULL) {
13753 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
13754 			}
13755 		} else {
13756 			if (tcp->tcp_snd_sack_ok &&
13757 			    tcp->tcp_notsack_list != NULL) {
13758 				flags |= TH_NEED_SACK_REXMIT;
13759 				tcp->tcp_pipe -= mss;
13760 				if (tcp->tcp_pipe < 0)
13761 					tcp->tcp_pipe = 0;
13762 			} else {
13763 				/*
13764 				 * Hoe's algorithm:
13765 				 *
13766 				 * Retransmit the unack'ed segment and
13767 				 * restart fast recovery.  Note that we
13768 				 * need to scale back tcp_cwnd to the
13769 				 * original value when we started fast
13770 				 * recovery.  This is to prevent overly
13771 				 * aggressive behaviour in sending new
13772 				 * segments.
13773 				 */
13774 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
13775 					tcp_dupack_fast_retransmit * mss;
13776 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
13777 				flags |= TH_REXMIT_NEEDED;
13778 			}
13779 		}
13780 	} else {
13781 		tcp->tcp_dupack_cnt = 0;
13782 		if (tcp->tcp_rexmit) {
13783 			/*
13784 			 * TCP is retranmitting.  If the ACK ack's all
13785 			 * outstanding data, update tcp_rexmit_max and
13786 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
13787 			 * to the correct value.
13788 			 *
13789 			 * Note that SEQ_LEQ() is used.  This is to avoid
13790 			 * unnecessary fast retransmit caused by dup ACKs
13791 			 * received when TCP does slow start retransmission
13792 			 * after a time out.  During this phase, TCP may
13793 			 * send out segments which are already received.
13794 			 * This causes dup ACKs to be sent back.
13795 			 */
13796 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
13797 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
13798 					tcp->tcp_rexmit_nxt = seg_ack;
13799 				}
13800 				if (seg_ack != tcp->tcp_rexmit_max) {
13801 					flags |= TH_XMIT_NEEDED;
13802 				}
13803 			} else {
13804 				tcp->tcp_rexmit = B_FALSE;
13805 				tcp->tcp_xmit_zc_clean = B_FALSE;
13806 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13807 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13808 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13809 			}
13810 			tcp->tcp_ms_we_have_waited = 0;
13811 		}
13812 	}
13813 
13814 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
13815 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
13816 	tcp->tcp_suna = seg_ack;
13817 	if (tcp->tcp_zero_win_probe != 0) {
13818 		tcp->tcp_zero_win_probe = 0;
13819 		tcp->tcp_timer_backoff = 0;
13820 	}
13821 
13822 	/*
13823 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
13824 	 * Note that it cannot be the SYN being ack'ed.  The code flow
13825 	 * will not reach here.
13826 	 */
13827 	if (mp1 == NULL) {
13828 		goto fin_acked;
13829 	}
13830 
13831 	/*
13832 	 * Update the congestion window.
13833 	 *
13834 	 * If TCP is not ECN capable or TCP is ECN capable but the
13835 	 * congestion experience bit is not set, increase the tcp_cwnd as
13836 	 * usual.
13837 	 */
13838 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
13839 		cwnd = tcp->tcp_cwnd;
13840 		add = mss;
13841 
13842 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
13843 			/*
13844 			 * This is to prevent an increase of less than 1 MSS of
13845 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
13846 			 * may send out tinygrams in order to preserve mblk
13847 			 * boundaries.
13848 			 *
13849 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
13850 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
13851 			 * increased by 1 MSS for every RTTs.
13852 			 */
13853 			if (tcp->tcp_cwnd_cnt <= 0) {
13854 				tcp->tcp_cwnd_cnt = cwnd + add;
13855 			} else {
13856 				tcp->tcp_cwnd_cnt -= add;
13857 				add = 0;
13858 			}
13859 		}
13860 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
13861 	}
13862 
13863 	/* See if the latest urgent data has been acknowledged */
13864 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
13865 	    SEQ_GT(seg_ack, tcp->tcp_urg))
13866 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
13867 
13868 	/* Can we update the RTT estimates? */
13869 	if (tcp->tcp_snd_ts_ok) {
13870 		/* Ignore zero timestamp echo-reply. */
13871 		if (tcpopt.tcp_opt_ts_ecr != 0) {
13872 			tcp_set_rto(tcp, (int32_t)lbolt -
13873 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
13874 		}
13875 
13876 		/* If needed, restart the timer. */
13877 		if (tcp->tcp_set_timer == 1) {
13878 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13879 			tcp->tcp_set_timer = 0;
13880 		}
13881 		/*
13882 		 * Update tcp_csuna in case the other side stops sending
13883 		 * us timestamps.
13884 		 */
13885 		tcp->tcp_csuna = tcp->tcp_snxt;
13886 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
13887 		/*
13888 		 * An ACK sequence we haven't seen before, so get the RTT
13889 		 * and update the RTO. But first check if the timestamp is
13890 		 * valid to use.
13891 		 */
13892 		if ((mp1->b_next != NULL) &&
13893 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
13894 			tcp_set_rto(tcp, (int32_t)lbolt -
13895 			    (int32_t)(intptr_t)mp1->b_prev);
13896 		else
13897 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
13898 
13899 		/* Remeber the last sequence to be ACKed */
13900 		tcp->tcp_csuna = seg_ack;
13901 		if (tcp->tcp_set_timer == 1) {
13902 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13903 			tcp->tcp_set_timer = 0;
13904 		}
13905 	} else {
13906 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
13907 	}
13908 
13909 	/* Eat acknowledged bytes off the xmit queue. */
13910 	for (;;) {
13911 		mblk_t	*mp2;
13912 		uchar_t	*wptr;
13913 
13914 		wptr = mp1->b_wptr;
13915 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
13916 		bytes_acked -= (int)(wptr - mp1->b_rptr);
13917 		if (bytes_acked < 0) {
13918 			mp1->b_rptr = wptr + bytes_acked;
13919 			/*
13920 			 * Set a new timestamp if all the bytes timed by the
13921 			 * old timestamp have been ack'ed.
13922 			 */
13923 			if (SEQ_GT(seg_ack,
13924 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
13925 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
13926 				mp1->b_next = NULL;
13927 			}
13928 			break;
13929 		}
13930 		mp1->b_next = NULL;
13931 		mp1->b_prev = NULL;
13932 		mp2 = mp1;
13933 		mp1 = mp1->b_cont;
13934 
13935 		/*
13936 		 * This notification is required for some zero-copy
13937 		 * clients to maintain a copy semantic. After the data
13938 		 * is ack'ed, client is safe to modify or reuse the buffer.
13939 		 */
13940 		if (tcp->tcp_snd_zcopy_aware &&
13941 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
13942 			tcp_zcopy_notify(tcp);
13943 		freeb(mp2);
13944 		if (bytes_acked == 0) {
13945 			if (mp1 == NULL) {
13946 				/* Everything is ack'ed, clear the tail. */
13947 				tcp->tcp_xmit_tail = NULL;
13948 				/*
13949 				 * Cancel the timer unless we are still
13950 				 * waiting for an ACK for the FIN packet.
13951 				 */
13952 				if (tcp->tcp_timer_tid != 0 &&
13953 				    tcp->tcp_snxt == tcp->tcp_suna) {
13954 					(void) TCP_TIMER_CANCEL(tcp,
13955 					    tcp->tcp_timer_tid);
13956 					tcp->tcp_timer_tid = 0;
13957 				}
13958 				goto pre_swnd_update;
13959 			}
13960 			if (mp2 != tcp->tcp_xmit_tail)
13961 				break;
13962 			tcp->tcp_xmit_tail = mp1;
13963 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13964 			    (uintptr_t)INT_MAX);
13965 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
13966 			    mp1->b_rptr);
13967 			break;
13968 		}
13969 		if (mp1 == NULL) {
13970 			/*
13971 			 * More was acked but there is nothing more
13972 			 * outstanding.  This means that the FIN was
13973 			 * just acked or that we're talking to a clown.
13974 			 */
13975 fin_acked:
13976 			ASSERT(tcp->tcp_fin_sent);
13977 			tcp->tcp_xmit_tail = NULL;
13978 			if (tcp->tcp_fin_sent) {
13979 				/* FIN was acked - making progress */
13980 				if (tcp->tcp_ipversion == IPV6_VERSION &&
13981 				    !tcp->tcp_fin_acked)
13982 					tcp->tcp_ip_forward_progress = B_TRUE;
13983 				tcp->tcp_fin_acked = B_TRUE;
13984 				if (tcp->tcp_linger_tid != 0 &&
13985 				    TCP_TIMER_CANCEL(tcp,
13986 					tcp->tcp_linger_tid) >= 0) {
13987 					tcp_stop_lingering(tcp);
13988 				}
13989 			} else {
13990 				/*
13991 				 * We should never get here because
13992 				 * we have already checked that the
13993 				 * number of bytes ack'ed should be
13994 				 * smaller than or equal to what we
13995 				 * have sent so far (it is the
13996 				 * acceptability check of the ACK).
13997 				 * We can only get here if the send
13998 				 * queue is corrupted.
13999 				 *
14000 				 * Terminate the connection and
14001 				 * panic the system.  It is better
14002 				 * for us to panic instead of
14003 				 * continuing to avoid other disaster.
14004 				 */
14005 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14006 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14007 				panic("Memory corruption "
14008 				    "detected for connection %s.",
14009 				    tcp_display(tcp, NULL,
14010 					DISP_ADDR_AND_PORT));
14011 				/*NOTREACHED*/
14012 			}
14013 			goto pre_swnd_update;
14014 		}
14015 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14016 	}
14017 	if (tcp->tcp_unsent) {
14018 		flags |= TH_XMIT_NEEDED;
14019 	}
14020 pre_swnd_update:
14021 	tcp->tcp_xmit_head = mp1;
14022 swnd_update:
14023 	/*
14024 	 * The following check is different from most other implementations.
14025 	 * For bi-directional transfer, when segments are dropped, the
14026 	 * "normal" check will not accept a window update in those
14027 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14028 	 * segments which are outside receiver's window.  As TCP accepts
14029 	 * the ack in those retransmitted segments, if the window update in
14030 	 * the same segment is not accepted, TCP will incorrectly calculates
14031 	 * that it can send more segments.  This can create a deadlock
14032 	 * with the receiver if its window becomes zero.
14033 	 */
14034 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14035 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14036 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14037 		/*
14038 		 * The criteria for update is:
14039 		 *
14040 		 * 1. the segment acknowledges some data.  Or
14041 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14042 		 * 3. the segment is not old and the advertised window is
14043 		 * larger than the previous advertised window.
14044 		 */
14045 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14046 			flags |= TH_XMIT_NEEDED;
14047 		tcp->tcp_swnd = new_swnd;
14048 		if (new_swnd > tcp->tcp_max_swnd)
14049 			tcp->tcp_max_swnd = new_swnd;
14050 		tcp->tcp_swl1 = seg_seq;
14051 		tcp->tcp_swl2 = seg_ack;
14052 	}
14053 est:
14054 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14055 
14056 		switch (tcp->tcp_state) {
14057 		case TCPS_FIN_WAIT_1:
14058 			if (tcp->tcp_fin_acked) {
14059 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14060 				/*
14061 				 * We implement the non-standard BSD/SunOS
14062 				 * FIN_WAIT_2 flushing algorithm.
14063 				 * If there is no user attached to this
14064 				 * TCP endpoint, then this TCP struct
14065 				 * could hang around forever in FIN_WAIT_2
14066 				 * state if the peer forgets to send us
14067 				 * a FIN.  To prevent this, we wait only
14068 				 * 2*MSL (a convenient time value) for
14069 				 * the FIN to arrive.  If it doesn't show up,
14070 				 * we flush the TCP endpoint.  This algorithm,
14071 				 * though a violation of RFC-793, has worked
14072 				 * for over 10 years in BSD systems.
14073 				 * Note: SunOS 4.x waits 675 seconds before
14074 				 * flushing the FIN_WAIT_2 connection.
14075 				 */
14076 				TCP_TIMER_RESTART(tcp,
14077 				    tcp_fin_wait_2_flush_interval);
14078 			}
14079 			break;
14080 		case TCPS_FIN_WAIT_2:
14081 			break;	/* Shutdown hook? */
14082 		case TCPS_LAST_ACK:
14083 			freemsg(mp);
14084 			if (tcp->tcp_fin_acked) {
14085 				(void) tcp_clean_death(tcp, 0, 19);
14086 				return;
14087 			}
14088 			goto xmit_check;
14089 		case TCPS_CLOSING:
14090 			if (tcp->tcp_fin_acked) {
14091 				tcp->tcp_state = TCPS_TIME_WAIT;
14092 				if (!TCP_IS_DETACHED(tcp)) {
14093 					TCP_TIMER_RESTART(tcp,
14094 					    tcp_time_wait_interval);
14095 				} else {
14096 					tcp_time_wait_append(tcp);
14097 					TCP_DBGSTAT(tcp_rput_time_wait);
14098 				}
14099 			}
14100 			/*FALLTHRU*/
14101 		case TCPS_CLOSE_WAIT:
14102 			freemsg(mp);
14103 			goto xmit_check;
14104 		default:
14105 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14106 			break;
14107 		}
14108 	}
14109 	if (flags & TH_FIN) {
14110 		/* Make sure we ack the fin */
14111 		flags |= TH_ACK_NEEDED;
14112 		if (!tcp->tcp_fin_rcvd) {
14113 			tcp->tcp_fin_rcvd = B_TRUE;
14114 			tcp->tcp_rnxt++;
14115 			tcph = tcp->tcp_tcph;
14116 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14117 
14118 			/*
14119 			 * Generate the ordrel_ind at the end unless we
14120 			 * are an eager guy.
14121 			 * In the eager case tcp_rsrv will do this when run
14122 			 * after tcp_accept is done.
14123 			 */
14124 			if (tcp->tcp_listener == NULL &&
14125 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14126 				flags |= TH_ORDREL_NEEDED;
14127 			switch (tcp->tcp_state) {
14128 			case TCPS_SYN_RCVD:
14129 			case TCPS_ESTABLISHED:
14130 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14131 				/* Keepalive? */
14132 				break;
14133 			case TCPS_FIN_WAIT_1:
14134 				if (!tcp->tcp_fin_acked) {
14135 					tcp->tcp_state = TCPS_CLOSING;
14136 					break;
14137 				}
14138 				/* FALLTHRU */
14139 			case TCPS_FIN_WAIT_2:
14140 				tcp->tcp_state = TCPS_TIME_WAIT;
14141 				if (!TCP_IS_DETACHED(tcp)) {
14142 					TCP_TIMER_RESTART(tcp,
14143 					    tcp_time_wait_interval);
14144 				} else {
14145 					tcp_time_wait_append(tcp);
14146 					TCP_DBGSTAT(tcp_rput_time_wait);
14147 				}
14148 				if (seg_len) {
14149 					/*
14150 					 * implies data piggybacked on FIN.
14151 					 * break to handle data.
14152 					 */
14153 					break;
14154 				}
14155 				freemsg(mp);
14156 				goto ack_check;
14157 			}
14158 		}
14159 	}
14160 	if (mp == NULL)
14161 		goto xmit_check;
14162 	if (seg_len == 0) {
14163 		freemsg(mp);
14164 		goto xmit_check;
14165 	}
14166 	if (mp->b_rptr == mp->b_wptr) {
14167 		/*
14168 		 * The header has been consumed, so we remove the
14169 		 * zero-length mblk here.
14170 		 */
14171 		mp1 = mp;
14172 		mp = mp->b_cont;
14173 		freeb(mp1);
14174 	}
14175 	tcph = tcp->tcp_tcph;
14176 	tcp->tcp_rack_cnt++;
14177 	{
14178 		uint32_t cur_max;
14179 
14180 		cur_max = tcp->tcp_rack_cur_max;
14181 		if (tcp->tcp_rack_cnt >= cur_max) {
14182 			/*
14183 			 * We have more unacked data than we should - send
14184 			 * an ACK now.
14185 			 */
14186 			flags |= TH_ACK_NEEDED;
14187 			cur_max++;
14188 			if (cur_max > tcp->tcp_rack_abs_max)
14189 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14190 			else
14191 				tcp->tcp_rack_cur_max = cur_max;
14192 		} else if (TCP_IS_DETACHED(tcp)) {
14193 			/* We don't have an ACK timer for detached TCP. */
14194 			flags |= TH_ACK_NEEDED;
14195 		} else if (seg_len < mss) {
14196 			/*
14197 			 * If we get a segment that is less than an mss, and we
14198 			 * already have unacknowledged data, and the amount
14199 			 * unacknowledged is not a multiple of mss, then we
14200 			 * better generate an ACK now.  Otherwise, this may be
14201 			 * the tail piece of a transaction, and we would rather
14202 			 * wait for the response.
14203 			 */
14204 			uint32_t udif;
14205 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14206 			    (uintptr_t)INT_MAX);
14207 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14208 			if (udif && (udif % mss))
14209 				flags |= TH_ACK_NEEDED;
14210 			else
14211 				flags |= TH_ACK_TIMER_NEEDED;
14212 		} else {
14213 			/* Start delayed ack timer */
14214 			flags |= TH_ACK_TIMER_NEEDED;
14215 		}
14216 	}
14217 	tcp->tcp_rnxt += seg_len;
14218 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14219 
14220 	/* Update SACK list */
14221 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14222 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14223 		    &(tcp->tcp_num_sack_blk));
14224 	}
14225 
14226 	if (tcp->tcp_urp_mp) {
14227 		tcp->tcp_urp_mp->b_cont = mp;
14228 		mp = tcp->tcp_urp_mp;
14229 		tcp->tcp_urp_mp = NULL;
14230 		/* Ready for a new signal. */
14231 		tcp->tcp_urp_last_valid = B_FALSE;
14232 #ifdef DEBUG
14233 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14234 		    "tcp_rput: sending exdata_ind %s",
14235 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14236 #endif /* DEBUG */
14237 	}
14238 
14239 	/*
14240 	 * Check for ancillary data changes compared to last segment.
14241 	 */
14242 	if (tcp->tcp_ipv6_recvancillary != 0) {
14243 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14244 		if (mp == NULL)
14245 			return;
14246 	}
14247 
14248 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14249 		/*
14250 		 * Side queue inbound data until the accept happens.
14251 		 * tcp_accept/tcp_rput drains this when the accept happens.
14252 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14253 		 * T_EXDATA_IND) it is queued on b_next.
14254 		 * XXX Make urgent data use this. Requires:
14255 		 *	Removing tcp_listener check for TH_URG
14256 		 *	Making M_PCPROTO and MARK messages skip the eager case
14257 		 */
14258 
14259 		if (tcp->tcp_kssl_pending) {
14260 			tcp_kssl_input(tcp, mp);
14261 		} else {
14262 			tcp_rcv_enqueue(tcp, mp, seg_len);
14263 		}
14264 	} else {
14265 		if (mp->b_datap->db_type != M_DATA ||
14266 		    (flags & TH_MARKNEXT_NEEDED)) {
14267 			if (tcp->tcp_rcv_list != NULL) {
14268 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14269 			}
14270 			ASSERT(tcp->tcp_rcv_list == NULL ||
14271 			    tcp->tcp_fused_sigurg);
14272 			if (flags & TH_MARKNEXT_NEEDED) {
14273 #ifdef DEBUG
14274 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14275 				    "tcp_rput: sending MSGMARKNEXT %s",
14276 				    tcp_display(tcp, NULL,
14277 				    DISP_PORT_ONLY));
14278 #endif /* DEBUG */
14279 				mp->b_flag |= MSGMARKNEXT;
14280 				flags &= ~TH_MARKNEXT_NEEDED;
14281 			}
14282 
14283 			/* Does this need SSL processing first? */
14284 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14285 			    (DB_TYPE(mp) == M_DATA)) {
14286 				tcp_kssl_input(tcp, mp);
14287 			} else {
14288 				putnext(tcp->tcp_rq, mp);
14289 				if (!canputnext(tcp->tcp_rq))
14290 					tcp->tcp_rwnd -= seg_len;
14291 			}
14292 		} else if (((flags & (TH_PUSH|TH_FIN)) ||
14293 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) &&
14294 		    (sqp != NULL)) {
14295 			if (tcp->tcp_rcv_list != NULL) {
14296 				/*
14297 				 * Enqueue the new segment first and then
14298 				 * call tcp_rcv_drain() to send all data
14299 				 * up.  The other way to do this is to
14300 				 * send all queued data up and then call
14301 				 * putnext() to send the new segment up.
14302 				 * This way can remove the else part later
14303 				 * on.
14304 				 *
14305 				 * We don't this to avoid one more call to
14306 				 * canputnext() as tcp_rcv_drain() needs to
14307 				 * call canputnext().
14308 				 */
14309 				tcp_rcv_enqueue(tcp, mp, seg_len);
14310 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14311 			} else {
14312 				/* Does this need SSL processing first? */
14313 				if ((tcp->tcp_kssl_ctx  != NULL) &&
14314 				    (DB_TYPE(mp) == M_DATA)) {
14315 					tcp_kssl_input(tcp, mp);
14316 				} else {
14317 					putnext(tcp->tcp_rq, mp);
14318 					if (!canputnext(tcp->tcp_rq))
14319 						tcp->tcp_rwnd -= seg_len;
14320 				}
14321 			}
14322 		} else {
14323 			/*
14324 			 * Enqueue all packets when processing an mblk
14325 			 * from the co queue and also enqueue normal packets.
14326 			 */
14327 			tcp_rcv_enqueue(tcp, mp, seg_len);
14328 		}
14329 		/*
14330 		 * Make sure the timer is running if we have data waiting
14331 		 * for a push bit. This provides resiliency against
14332 		 * implementations that do not correctly generate push bits.
14333 		 */
14334 		if ((sqp != NULL) && tcp->tcp_rcv_list != NULL &&
14335 		    tcp->tcp_push_tid == 0) {
14336 			/*
14337 			 * The connection may be closed at this point, so don't
14338 			 * do anything for a detached tcp.
14339 			 */
14340 			if (!TCP_IS_DETACHED(tcp))
14341 				tcp->tcp_push_tid = TCP_TIMER(tcp,
14342 				    tcp_push_timer,
14343 				    MSEC_TO_TICK(tcp_push_timer_interval));
14344 		}
14345 	}
14346 xmit_check:
14347 	/* Is there anything left to do? */
14348 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14349 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
14350 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
14351 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14352 		goto done;
14353 
14354 	/* Any transmit work to do and a non-zero window? */
14355 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
14356 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
14357 		if (flags & TH_REXMIT_NEEDED) {
14358 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
14359 
14360 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
14361 			if (snd_size > mss)
14362 				snd_size = mss;
14363 			if (snd_size > tcp->tcp_swnd)
14364 				snd_size = tcp->tcp_swnd;
14365 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
14366 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
14367 			    B_TRUE);
14368 
14369 			if (mp1 != NULL) {
14370 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14371 				tcp->tcp_csuna = tcp->tcp_snxt;
14372 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
14373 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
14374 				TCP_RECORD_TRACE(tcp, mp1,
14375 				    TCP_TRACE_SEND_PKT);
14376 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
14377 			}
14378 		}
14379 		if (flags & TH_NEED_SACK_REXMIT) {
14380 			tcp_sack_rxmit(tcp, &flags);
14381 		}
14382 		/*
14383 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
14384 		 * out new segment.  Note that tcp_rexmit should not be
14385 		 * set, otherwise TH_LIMIT_XMIT should not be set.
14386 		 */
14387 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
14388 			if (!tcp->tcp_rexmit) {
14389 				tcp_wput_data(tcp, NULL, B_FALSE);
14390 			} else {
14391 				tcp_ss_rexmit(tcp);
14392 			}
14393 		}
14394 		/*
14395 		 * Adjust tcp_cwnd back to normal value after sending
14396 		 * new data segments.
14397 		 */
14398 		if (flags & TH_LIMIT_XMIT) {
14399 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
14400 			/*
14401 			 * This will restart the timer.  Restarting the
14402 			 * timer is used to avoid a timeout before the
14403 			 * limited transmitted segment's ACK gets back.
14404 			 */
14405 			if (tcp->tcp_xmit_head != NULL)
14406 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14407 		}
14408 
14409 		/* Anything more to do? */
14410 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
14411 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14412 			goto done;
14413 	}
14414 ack_check:
14415 	if (flags & TH_SEND_URP_MARK) {
14416 		ASSERT(tcp->tcp_urp_mark_mp);
14417 		/*
14418 		 * Send up any queued data and then send the mark message
14419 		 */
14420 		if (tcp->tcp_rcv_list != NULL) {
14421 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14422 		}
14423 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14424 
14425 		mp1 = tcp->tcp_urp_mark_mp;
14426 		tcp->tcp_urp_mark_mp = NULL;
14427 #ifdef DEBUG
14428 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14429 		    "tcp_rput: sending zero-length %s %s",
14430 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
14431 		    "MSGNOTMARKNEXT"),
14432 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14433 #endif /* DEBUG */
14434 		putnext(tcp->tcp_rq, mp1);
14435 		flags &= ~TH_SEND_URP_MARK;
14436 	}
14437 	if (flags & TH_ACK_NEEDED) {
14438 		/*
14439 		 * Time to send an ack for some reason.
14440 		 */
14441 		mp1 = tcp_ack_mp(tcp);
14442 
14443 		if (mp1 != NULL) {
14444 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
14445 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
14446 			BUMP_LOCAL(tcp->tcp_obsegs);
14447 			BUMP_MIB(&tcp_mib, tcpOutAck);
14448 		}
14449 		if (tcp->tcp_ack_tid != 0) {
14450 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
14451 			tcp->tcp_ack_tid = 0;
14452 		}
14453 	}
14454 	if (flags & TH_ACK_TIMER_NEEDED) {
14455 		/*
14456 		 * Arrange for deferred ACK or push wait timeout.
14457 		 * Start timer if it is not already running.
14458 		 */
14459 		if (tcp->tcp_ack_tid == 0) {
14460 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
14461 			    MSEC_TO_TICK(tcp->tcp_localnet ?
14462 			    (clock_t)tcp_local_dack_interval :
14463 			    (clock_t)tcp_deferred_ack_interval));
14464 		}
14465 	}
14466 	if (flags & TH_ORDREL_NEEDED) {
14467 		/*
14468 		 * Send up the ordrel_ind unless we are an eager guy.
14469 		 * In the eager case tcp_rsrv will do this when run
14470 		 * after tcp_accept is done.
14471 		 */
14472 		ASSERT(tcp->tcp_listener == NULL);
14473 		if (tcp->tcp_rcv_list != NULL) {
14474 			/*
14475 			 * Push any mblk(s) enqueued from co processing.
14476 			 */
14477 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14478 		}
14479 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14480 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
14481 			tcp->tcp_ordrel_done = B_TRUE;
14482 			putnext(tcp->tcp_rq, mp1);
14483 			if (tcp->tcp_deferred_clean_death) {
14484 				/*
14485 				 * tcp_clean_death was deferred
14486 				 * for T_ORDREL_IND - do it now
14487 				 */
14488 				(void) tcp_clean_death(tcp,
14489 				    tcp->tcp_client_errno, 20);
14490 				tcp->tcp_deferred_clean_death =	B_FALSE;
14491 			}
14492 		} else {
14493 			/*
14494 			 * Run the orderly release in the
14495 			 * service routine.
14496 			 */
14497 			qenable(tcp->tcp_rq);
14498 			/*
14499 			 * Caveat(XXX): The machine may be so
14500 			 * overloaded that tcp_rsrv() is not scheduled
14501 			 * until after the endpoint has transitioned
14502 			 * to TCPS_TIME_WAIT
14503 			 * and tcp_time_wait_interval expires. Then
14504 			 * tcp_timer() will blow away state in tcp_t
14505 			 * and T_ORDREL_IND will never be delivered
14506 			 * upstream. Unlikely but potentially
14507 			 * a problem.
14508 			 */
14509 		}
14510 	}
14511 done:
14512 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14513 }
14514 
14515 /*
14516  * This function does PAWS protection check. Returns B_TRUE if the
14517  * segment passes the PAWS test, else returns B_FALSE.
14518  */
14519 boolean_t
14520 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
14521 {
14522 	uint8_t	flags;
14523 	int	options;
14524 	uint8_t *up;
14525 
14526 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
14527 	/*
14528 	 * If timestamp option is aligned nicely, get values inline,
14529 	 * otherwise call general routine to parse.  Only do that
14530 	 * if timestamp is the only option.
14531 	 */
14532 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
14533 	    TCPOPT_REAL_TS_LEN &&
14534 	    OK_32PTR((up = ((uint8_t *)tcph) +
14535 	    TCP_MIN_HEADER_LENGTH)) &&
14536 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
14537 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
14538 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
14539 
14540 		options = TCP_OPT_TSTAMP_PRESENT;
14541 	} else {
14542 		if (tcp->tcp_snd_sack_ok) {
14543 			tcpoptp->tcp = tcp;
14544 		} else {
14545 			tcpoptp->tcp = NULL;
14546 		}
14547 		options = tcp_parse_options(tcph, tcpoptp);
14548 	}
14549 
14550 	if (options & TCP_OPT_TSTAMP_PRESENT) {
14551 		/*
14552 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
14553 		 * regardless of the timestamp, page 18 RFC 1323.bis.
14554 		 */
14555 		if ((flags & TH_RST) == 0 &&
14556 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
14557 		    tcp->tcp_ts_recent)) {
14558 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
14559 			    PAWS_TIMEOUT)) {
14560 				/* This segment is not acceptable. */
14561 				return (B_FALSE);
14562 			} else {
14563 				/*
14564 				 * Connection has been idle for
14565 				 * too long.  Reset the timestamp
14566 				 * and assume the segment is valid.
14567 				 */
14568 				tcp->tcp_ts_recent =
14569 				    tcpoptp->tcp_opt_ts_val;
14570 			}
14571 		}
14572 	} else {
14573 		/*
14574 		 * If we don't get a timestamp on every packet, we
14575 		 * figure we can't really trust 'em, so we stop sending
14576 		 * and parsing them.
14577 		 */
14578 		tcp->tcp_snd_ts_ok = B_FALSE;
14579 
14580 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14581 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14582 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
14583 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
14584 		if (tcp->tcp_snd_sack_ok) {
14585 			ASSERT(tcp->tcp_sack_info != NULL);
14586 			tcp->tcp_max_sack_blk = 4;
14587 		}
14588 	}
14589 	return (B_TRUE);
14590 }
14591 
14592 /*
14593  * Attach ancillary data to a received TCP segments for the
14594  * ancillary pieces requested by the application that are
14595  * different than they were in the previous data segment.
14596  *
14597  * Save the "current" values once memory allocation is ok so that
14598  * when memory allocation fails we can just wait for the next data segment.
14599  */
14600 static mblk_t *
14601 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
14602 {
14603 	struct T_optdata_ind *todi;
14604 	int optlen;
14605 	uchar_t *optptr;
14606 	struct T_opthdr *toh;
14607 	uint_t addflag;	/* Which pieces to add */
14608 	mblk_t *mp1;
14609 
14610 	optlen = 0;
14611 	addflag = 0;
14612 	/* If app asked for pktinfo and the index has changed ... */
14613 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
14614 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
14615 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
14616 		optlen += sizeof (struct T_opthdr) +
14617 		    sizeof (struct in6_pktinfo);
14618 		addflag |= TCP_IPV6_RECVPKTINFO;
14619 	}
14620 	/* If app asked for hoplimit and it has changed ... */
14621 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
14622 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
14623 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
14624 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14625 		addflag |= TCP_IPV6_RECVHOPLIMIT;
14626 	}
14627 	/* If app asked for tclass and it has changed ... */
14628 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
14629 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
14630 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
14631 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14632 		addflag |= TCP_IPV6_RECVTCLASS;
14633 	}
14634 	/* If app asked for hopbyhop headers and it has changed ... */
14635 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
14636 	    tcp_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
14637 		(ipp->ipp_fields & IPPF_HOPOPTS),
14638 		ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
14639 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
14640 		addflag |= TCP_IPV6_RECVHOPOPTS;
14641 		if (!tcp_allocbuf((void **)&tcp->tcp_hopopts,
14642 		    &tcp->tcp_hopoptslen,
14643 		    (ipp->ipp_fields & IPPF_HOPOPTS),
14644 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
14645 			return (mp);
14646 	}
14647 	/* If app asked for dst headers before routing headers ... */
14648 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
14649 	    tcp_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
14650 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
14651 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
14652 		optlen += sizeof (struct T_opthdr) +
14653 		    ipp->ipp_rtdstoptslen;
14654 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
14655 		if (!tcp_allocbuf((void **)&tcp->tcp_rtdstopts,
14656 		    &tcp->tcp_rtdstoptslen,
14657 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
14658 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
14659 			return (mp);
14660 	}
14661 	/* If app asked for routing headers and it has changed ... */
14662 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
14663 	    tcp_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
14664 		(ipp->ipp_fields & IPPF_RTHDR),
14665 		ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
14666 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
14667 		addflag |= TCP_IPV6_RECVRTHDR;
14668 		if (!tcp_allocbuf((void **)&tcp->tcp_rthdr,
14669 		    &tcp->tcp_rthdrlen,
14670 		    (ipp->ipp_fields & IPPF_RTHDR),
14671 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
14672 			return (mp);
14673 	}
14674 	/* If app asked for dest headers and it has changed ... */
14675 	if ((tcp->tcp_ipv6_recvancillary &
14676 		(TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
14677 	    tcp_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
14678 		(ipp->ipp_fields & IPPF_DSTOPTS),
14679 		ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
14680 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
14681 		addflag |= TCP_IPV6_RECVDSTOPTS;
14682 		if (!tcp_allocbuf((void **)&tcp->tcp_dstopts,
14683 		    &tcp->tcp_dstoptslen,
14684 		    (ipp->ipp_fields & IPPF_DSTOPTS),
14685 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
14686 			return (mp);
14687 	}
14688 
14689 	if (optlen == 0) {
14690 		/* Nothing to add */
14691 		return (mp);
14692 	}
14693 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
14694 	if (mp1 == NULL) {
14695 		/*
14696 		 * Defer sending ancillary data until the next TCP segment
14697 		 * arrives.
14698 		 */
14699 		return (mp);
14700 	}
14701 	mp1->b_cont = mp;
14702 	mp = mp1;
14703 	mp->b_wptr += sizeof (*todi) + optlen;
14704 	mp->b_datap->db_type = M_PROTO;
14705 	todi = (struct T_optdata_ind *)mp->b_rptr;
14706 	todi->PRIM_type = T_OPTDATA_IND;
14707 	todi->DATA_flag = 1;	/* MORE data */
14708 	todi->OPT_length = optlen;
14709 	todi->OPT_offset = sizeof (*todi);
14710 	optptr = (uchar_t *)&todi[1];
14711 	/*
14712 	 * If app asked for pktinfo and the index has changed ...
14713 	 * Note that the local address never changes for the connection.
14714 	 */
14715 	if (addflag & TCP_IPV6_RECVPKTINFO) {
14716 		struct in6_pktinfo *pkti;
14717 
14718 		toh = (struct T_opthdr *)optptr;
14719 		toh->level = IPPROTO_IPV6;
14720 		toh->name = IPV6_PKTINFO;
14721 		toh->len = sizeof (*toh) + sizeof (*pkti);
14722 		toh->status = 0;
14723 		optptr += sizeof (*toh);
14724 		pkti = (struct in6_pktinfo *)optptr;
14725 		if (tcp->tcp_ipversion == IPV6_VERSION)
14726 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
14727 		else
14728 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
14729 			    &pkti->ipi6_addr);
14730 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
14731 		optptr += sizeof (*pkti);
14732 		ASSERT(OK_32PTR(optptr));
14733 		/* Save as "last" value */
14734 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
14735 	}
14736 	/* If app asked for hoplimit and it has changed ... */
14737 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
14738 		toh = (struct T_opthdr *)optptr;
14739 		toh->level = IPPROTO_IPV6;
14740 		toh->name = IPV6_HOPLIMIT;
14741 		toh->len = sizeof (*toh) + sizeof (uint_t);
14742 		toh->status = 0;
14743 		optptr += sizeof (*toh);
14744 		*(uint_t *)optptr = ipp->ipp_hoplimit;
14745 		optptr += sizeof (uint_t);
14746 		ASSERT(OK_32PTR(optptr));
14747 		/* Save as "last" value */
14748 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
14749 	}
14750 	/* If app asked for tclass and it has changed ... */
14751 	if (addflag & TCP_IPV6_RECVTCLASS) {
14752 		toh = (struct T_opthdr *)optptr;
14753 		toh->level = IPPROTO_IPV6;
14754 		toh->name = IPV6_TCLASS;
14755 		toh->len = sizeof (*toh) + sizeof (uint_t);
14756 		toh->status = 0;
14757 		optptr += sizeof (*toh);
14758 		*(uint_t *)optptr = ipp->ipp_tclass;
14759 		optptr += sizeof (uint_t);
14760 		ASSERT(OK_32PTR(optptr));
14761 		/* Save as "last" value */
14762 		tcp->tcp_recvtclass = ipp->ipp_tclass;
14763 	}
14764 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
14765 		toh = (struct T_opthdr *)optptr;
14766 		toh->level = IPPROTO_IPV6;
14767 		toh->name = IPV6_HOPOPTS;
14768 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
14769 		toh->status = 0;
14770 		optptr += sizeof (*toh);
14771 		bcopy(ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
14772 		optptr += ipp->ipp_hopoptslen;
14773 		ASSERT(OK_32PTR(optptr));
14774 		/* Save as last value */
14775 		tcp_savebuf((void **)&tcp->tcp_hopopts,
14776 		    &tcp->tcp_hopoptslen,
14777 		    (ipp->ipp_fields & IPPF_HOPOPTS),
14778 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14779 	}
14780 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
14781 		toh = (struct T_opthdr *)optptr;
14782 		toh->level = IPPROTO_IPV6;
14783 		toh->name = IPV6_RTHDRDSTOPTS;
14784 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
14785 		toh->status = 0;
14786 		optptr += sizeof (*toh);
14787 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
14788 		optptr += ipp->ipp_rtdstoptslen;
14789 		ASSERT(OK_32PTR(optptr));
14790 		/* Save as last value */
14791 		tcp_savebuf((void **)&tcp->tcp_rtdstopts,
14792 		    &tcp->tcp_rtdstoptslen,
14793 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
14794 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
14795 	}
14796 	if (addflag & TCP_IPV6_RECVRTHDR) {
14797 		toh = (struct T_opthdr *)optptr;
14798 		toh->level = IPPROTO_IPV6;
14799 		toh->name = IPV6_RTHDR;
14800 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
14801 		toh->status = 0;
14802 		optptr += sizeof (*toh);
14803 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
14804 		optptr += ipp->ipp_rthdrlen;
14805 		ASSERT(OK_32PTR(optptr));
14806 		/* Save as last value */
14807 		tcp_savebuf((void **)&tcp->tcp_rthdr,
14808 		    &tcp->tcp_rthdrlen,
14809 		    (ipp->ipp_fields & IPPF_RTHDR),
14810 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14811 	}
14812 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
14813 		toh = (struct T_opthdr *)optptr;
14814 		toh->level = IPPROTO_IPV6;
14815 		toh->name = IPV6_DSTOPTS;
14816 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
14817 		toh->status = 0;
14818 		optptr += sizeof (*toh);
14819 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
14820 		optptr += ipp->ipp_dstoptslen;
14821 		ASSERT(OK_32PTR(optptr));
14822 		/* Save as last value */
14823 		tcp_savebuf((void **)&tcp->tcp_dstopts,
14824 		    &tcp->tcp_dstoptslen,
14825 		    (ipp->ipp_fields & IPPF_DSTOPTS),
14826 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14827 	}
14828 	ASSERT(optptr == mp->b_wptr);
14829 	return (mp);
14830 }
14831 
14832 
14833 /*
14834  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
14835  * or a "bad" IRE detected by tcp_adapt_ire.
14836  * We can't tell if the failure was due to the laddr or the faddr
14837  * thus we clear out all addresses and ports.
14838  */
14839 static void
14840 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
14841 {
14842 	queue_t	*q = tcp->tcp_rq;
14843 	tcph_t	*tcph;
14844 	struct T_error_ack *tea;
14845 	conn_t	*connp = tcp->tcp_connp;
14846 
14847 
14848 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
14849 
14850 	if (mp->b_cont) {
14851 		freemsg(mp->b_cont);
14852 		mp->b_cont = NULL;
14853 	}
14854 	tea = (struct T_error_ack *)mp->b_rptr;
14855 	switch (tea->PRIM_type) {
14856 	case T_BIND_ACK:
14857 		/*
14858 		 * Need to unbind with classifier since we were just told that
14859 		 * our bind succeeded.
14860 		 */
14861 		tcp->tcp_hard_bound = B_FALSE;
14862 		tcp->tcp_hard_binding = B_FALSE;
14863 
14864 		ipcl_hash_remove(connp);
14865 		/* Reuse the mblk if possible */
14866 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
14867 			sizeof (*tea));
14868 		mp->b_rptr = mp->b_datap->db_base;
14869 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
14870 		tea = (struct T_error_ack *)mp->b_rptr;
14871 		tea->PRIM_type = T_ERROR_ACK;
14872 		tea->TLI_error = TSYSERR;
14873 		tea->UNIX_error = error;
14874 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
14875 			tea->ERROR_prim = T_CONN_REQ;
14876 		} else {
14877 			tea->ERROR_prim = O_T_BIND_REQ;
14878 		}
14879 		break;
14880 
14881 	case T_ERROR_ACK:
14882 		if (tcp->tcp_state >= TCPS_SYN_SENT)
14883 			tea->ERROR_prim = T_CONN_REQ;
14884 		break;
14885 	default:
14886 		panic("tcp_bind_failed: unexpected TPI type");
14887 		/*NOTREACHED*/
14888 	}
14889 
14890 	tcp->tcp_state = TCPS_IDLE;
14891 	if (tcp->tcp_ipversion == IPV4_VERSION)
14892 		tcp->tcp_ipha->ipha_src = 0;
14893 	else
14894 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
14895 	/*
14896 	 * Copy of the src addr. in tcp_t is needed since
14897 	 * the lookup funcs. can only look at tcp_t
14898 	 */
14899 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
14900 
14901 	tcph = tcp->tcp_tcph;
14902 	tcph->th_lport[0] = 0;
14903 	tcph->th_lport[1] = 0;
14904 	tcp_bind_hash_remove(tcp);
14905 	bzero(&connp->u_port, sizeof (connp->u_port));
14906 	/* blow away saved option results if any */
14907 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
14908 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
14909 
14910 	conn_delete_ire(tcp->tcp_connp, NULL);
14911 	putnext(q, mp);
14912 }
14913 
14914 /*
14915  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
14916  * messages.
14917  */
14918 void
14919 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
14920 {
14921 	mblk_t	*mp1;
14922 	uchar_t	*rptr = mp->b_rptr;
14923 	queue_t	*q = tcp->tcp_rq;
14924 	struct T_error_ack *tea;
14925 	uint32_t mss;
14926 	mblk_t *syn_mp;
14927 	mblk_t *mdti;
14928 	int	retval;
14929 	mblk_t *ire_mp;
14930 
14931 	switch (mp->b_datap->db_type) {
14932 	case M_PROTO:
14933 	case M_PCPROTO:
14934 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
14935 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
14936 			break;
14937 		tea = (struct T_error_ack *)rptr;
14938 		switch (tea->PRIM_type) {
14939 		case T_BIND_ACK:
14940 			/*
14941 			 * Adapt Multidata information, if any.  The
14942 			 * following tcp_mdt_update routine will free
14943 			 * the message.
14944 			 */
14945 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
14946 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
14947 				    b_rptr)->mdt_capab, B_TRUE);
14948 				freemsg(mdti);
14949 			}
14950 
14951 			/* Get the IRE, if we had requested for it */
14952 			ire_mp = tcp_ire_mp(mp);
14953 
14954 			if (tcp->tcp_hard_binding) {
14955 				tcp->tcp_hard_binding = B_FALSE;
14956 				tcp->tcp_hard_bound = B_TRUE;
14957 				CL_INET_CONNECT(tcp);
14958 			} else {
14959 				if (ire_mp != NULL)
14960 					freeb(ire_mp);
14961 				goto after_syn_sent;
14962 			}
14963 
14964 			retval = tcp_adapt_ire(tcp, ire_mp);
14965 			if (ire_mp != NULL)
14966 				freeb(ire_mp);
14967 			if (retval == 0) {
14968 				tcp_bind_failed(tcp, mp,
14969 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
14970 				    ENETUNREACH : EADDRNOTAVAIL));
14971 				return;
14972 			}
14973 			/*
14974 			 * Don't let an endpoint connect to itself.
14975 			 * Also checked in tcp_connect() but that
14976 			 * check can't handle the case when the
14977 			 * local IP address is INADDR_ANY.
14978 			 */
14979 			if (tcp->tcp_ipversion == IPV4_VERSION) {
14980 				if ((tcp->tcp_ipha->ipha_dst ==
14981 				    tcp->tcp_ipha->ipha_src) &&
14982 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
14983 				    tcp->tcp_tcph->th_fport))) {
14984 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
14985 					return;
14986 				}
14987 			} else {
14988 				if (IN6_ARE_ADDR_EQUAL(
14989 				    &tcp->tcp_ip6h->ip6_dst,
14990 				    &tcp->tcp_ip6h->ip6_src) &&
14991 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
14992 				    tcp->tcp_tcph->th_fport))) {
14993 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
14994 					return;
14995 				}
14996 			}
14997 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
14998 			/*
14999 			 * This should not be possible!  Just for
15000 			 * defensive coding...
15001 			 */
15002 			if (tcp->tcp_state != TCPS_SYN_SENT)
15003 				goto after_syn_sent;
15004 
15005 			ASSERT(q == tcp->tcp_rq);
15006 			/*
15007 			 * tcp_adapt_ire() does not adjust
15008 			 * for TCP/IP header length.
15009 			 */
15010 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15011 
15012 			/*
15013 			 * Just make sure our rwnd is at
15014 			 * least tcp_recv_hiwat_mss * MSS
15015 			 * large, and round up to the nearest
15016 			 * MSS.
15017 			 *
15018 			 * We do the round up here because
15019 			 * we need to get the interface
15020 			 * MTU first before we can do the
15021 			 * round up.
15022 			 */
15023 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15024 			    tcp_recv_hiwat_minmss * mss);
15025 			q->q_hiwat = tcp->tcp_rwnd;
15026 			tcp_set_ws_value(tcp);
15027 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15028 			    tcp->tcp_tcph->th_win);
15029 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
15030 				tcp->tcp_snd_ws_ok = B_TRUE;
15031 
15032 			/*
15033 			 * Set tcp_snd_ts_ok to true
15034 			 * so that tcp_xmit_mp will
15035 			 * include the timestamp
15036 			 * option in the SYN segment.
15037 			 */
15038 			if (tcp_tstamp_always ||
15039 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
15040 				tcp->tcp_snd_ts_ok = B_TRUE;
15041 			}
15042 
15043 			/*
15044 			 * tcp_snd_sack_ok can be set in
15045 			 * tcp_adapt_ire() if the sack metric
15046 			 * is set.  So check it here also.
15047 			 */
15048 			if (tcp_sack_permitted == 2 ||
15049 			    tcp->tcp_snd_sack_ok) {
15050 				if (tcp->tcp_sack_info == NULL) {
15051 					tcp->tcp_sack_info =
15052 					kmem_cache_alloc(tcp_sack_info_cache,
15053 					    KM_SLEEP);
15054 				}
15055 				tcp->tcp_snd_sack_ok = B_TRUE;
15056 			}
15057 
15058 			/*
15059 			 * Should we use ECN?  Note that the current
15060 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15061 			 * is 1.  The reason for doing this is that there
15062 			 * are equipments out there that will drop ECN
15063 			 * enabled IP packets.  Setting it to 1 avoids
15064 			 * compatibility problems.
15065 			 */
15066 			if (tcp_ecn_permitted == 2)
15067 				tcp->tcp_ecn_ok = B_TRUE;
15068 
15069 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15070 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15071 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15072 			if (syn_mp) {
15073 				cred_t *cr;
15074 				pid_t pid;
15075 
15076 				/*
15077 				 * Obtain the credential from the
15078 				 * thread calling connect(); the credential
15079 				 * lives on in the second mblk which
15080 				 * originated from T_CONN_REQ and is echoed
15081 				 * with the T_BIND_ACK from ip.  If none
15082 				 * can be found, default to the creator
15083 				 * of the socket.
15084 				 */
15085 				if (mp->b_cont == NULL ||
15086 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15087 					cr = tcp->tcp_cred;
15088 					pid = tcp->tcp_cpid;
15089 				} else {
15090 					pid = DB_CPID(mp->b_cont);
15091 				}
15092 
15093 				TCP_RECORD_TRACE(tcp, syn_mp,
15094 				    TCP_TRACE_SEND_PKT);
15095 				mblk_setcred(syn_mp, cr);
15096 				DB_CPID(syn_mp) = pid;
15097 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15098 			}
15099 		after_syn_sent:
15100 			/*
15101 			 * A trailer mblk indicates a waiting client upstream.
15102 			 * We complete here the processing begun in
15103 			 * either tcp_bind() or tcp_connect() by passing
15104 			 * upstream the reply message they supplied.
15105 			 */
15106 			mp1 = mp;
15107 			mp = mp->b_cont;
15108 			freeb(mp1);
15109 			if (mp)
15110 				break;
15111 			return;
15112 		case T_ERROR_ACK:
15113 			if (tcp->tcp_debug) {
15114 				(void) strlog(TCP_MOD_ID, 0, 1,
15115 				    SL_TRACE|SL_ERROR,
15116 				    "tcp_rput_other: case T_ERROR_ACK, "
15117 				    "ERROR_prim == %d",
15118 				    tea->ERROR_prim);
15119 			}
15120 			switch (tea->ERROR_prim) {
15121 			case O_T_BIND_REQ:
15122 			case T_BIND_REQ:
15123 				tcp_bind_failed(tcp, mp,
15124 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15125 				    ENETUNREACH : EADDRNOTAVAIL));
15126 				return;
15127 			case T_UNBIND_REQ:
15128 				tcp->tcp_hard_binding = B_FALSE;
15129 				tcp->tcp_hard_bound = B_FALSE;
15130 				if (mp->b_cont) {
15131 					freemsg(mp->b_cont);
15132 					mp->b_cont = NULL;
15133 				}
15134 				if (tcp->tcp_unbind_pending)
15135 					tcp->tcp_unbind_pending = 0;
15136 				else {
15137 					/* From tcp_ip_unbind() - free */
15138 					freemsg(mp);
15139 					return;
15140 				}
15141 				break;
15142 			case T_SVR4_OPTMGMT_REQ:
15143 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15144 					/* T_OPTMGMT_REQ generated by TCP */
15145 					printf("T_SVR4_OPTMGMT_REQ failed "
15146 					    "%d/%d - dropped (cnt %d)\n",
15147 					    tea->TLI_error, tea->UNIX_error,
15148 					    tcp->tcp_drop_opt_ack_cnt);
15149 					freemsg(mp);
15150 					tcp->tcp_drop_opt_ack_cnt--;
15151 					return;
15152 				}
15153 				break;
15154 			}
15155 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15156 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15157 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15158 				    "- dropped (cnt %d)\n",
15159 				    tea->TLI_error, tea->UNIX_error,
15160 				    tcp->tcp_drop_opt_ack_cnt);
15161 				freemsg(mp);
15162 				tcp->tcp_drop_opt_ack_cnt--;
15163 				return;
15164 			}
15165 			break;
15166 		case T_OPTMGMT_ACK:
15167 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15168 				/* T_OPTMGMT_REQ generated by TCP */
15169 				freemsg(mp);
15170 				tcp->tcp_drop_opt_ack_cnt--;
15171 				return;
15172 			}
15173 			break;
15174 		default:
15175 			break;
15176 		}
15177 		break;
15178 	case M_CTL:
15179 		/*
15180 		 * ICMP messages.
15181 		 */
15182 		tcp_icmp_error(tcp, mp);
15183 		return;
15184 	case M_FLUSH:
15185 		if (*rptr & FLUSHR)
15186 			flushq(q, FLUSHDATA);
15187 		break;
15188 	default:
15189 		break;
15190 	}
15191 	/*
15192 	 * Make sure we set this bit before sending the ACK for
15193 	 * bind. Otherwise accept could possibly run and free
15194 	 * this tcp struct.
15195 	 */
15196 	putnext(q, mp);
15197 }
15198 
15199 /*
15200  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15201  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15202  * tcp_rsrv() try again.
15203  */
15204 static void
15205 tcp_ordrel_kick(void *arg)
15206 {
15207 	conn_t 	*connp = (conn_t *)arg;
15208 	tcp_t	*tcp = connp->conn_tcp;
15209 
15210 	tcp->tcp_ordrelid = 0;
15211 	tcp->tcp_timeout = B_FALSE;
15212 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15213 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15214 		qenable(tcp->tcp_rq);
15215 	}
15216 }
15217 
15218 /* ARGSUSED */
15219 static void
15220 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15221 {
15222 	conn_t	*connp = (conn_t *)arg;
15223 	tcp_t	*tcp = connp->conn_tcp;
15224 	queue_t	*q = tcp->tcp_rq;
15225 	uint_t	thwin;
15226 
15227 	freeb(mp);
15228 
15229 	TCP_STAT(tcp_rsrv_calls);
15230 
15231 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15232 		return;
15233 	}
15234 
15235 	if (tcp->tcp_fused) {
15236 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15237 
15238 		ASSERT(tcp->tcp_fused);
15239 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15240 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15241 		ASSERT(!TCP_IS_DETACHED(tcp));
15242 		ASSERT(tcp->tcp_connp->conn_sqp ==
15243 		    peer_tcp->tcp_connp->conn_sqp);
15244 
15245 		/*
15246 		 * Normally we would not get backenabled in synchronous
15247 		 * streams mode, but in case this happens, we need to stop
15248 		 * synchronous streams temporarily to prevent a race with
15249 		 * tcp_fuse_rrw() or tcp_fuse_rinfop().  It is safe to access
15250 		 * tcp_rcv_list here because those entry points will return
15251 		 * right away when synchronous streams is stopped.
15252 		 */
15253 		TCP_FUSE_SYNCSTR_STOP(tcp);
15254 		if (tcp->tcp_rcv_list != NULL)
15255 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15256 
15257 		tcp_clrqfull(peer_tcp);
15258 		TCP_FUSE_SYNCSTR_RESUME(tcp);
15259 		TCP_STAT(tcp_fusion_backenabled);
15260 		return;
15261 	}
15262 
15263 	if (canputnext(q)) {
15264 		tcp->tcp_rwnd = q->q_hiwat;
15265 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15266 		    << tcp->tcp_rcv_ws;
15267 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15268 		/*
15269 		 * Send back a window update immediately if TCP is above
15270 		 * ESTABLISHED state and the increase of the rcv window
15271 		 * that the other side knows is at least 1 MSS after flow
15272 		 * control is lifted.
15273 		 */
15274 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15275 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15276 			tcp_xmit_ctl(NULL, tcp,
15277 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15278 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15279 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
15280 		}
15281 	}
15282 	/* Handle a failure to allocate a T_ORDREL_IND here */
15283 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15284 		ASSERT(tcp->tcp_listener == NULL);
15285 		if (tcp->tcp_rcv_list != NULL) {
15286 			(void) tcp_rcv_drain(q, tcp);
15287 		}
15288 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15289 		mp = mi_tpi_ordrel_ind();
15290 		if (mp) {
15291 			tcp->tcp_ordrel_done = B_TRUE;
15292 			putnext(q, mp);
15293 			if (tcp->tcp_deferred_clean_death) {
15294 				/*
15295 				 * tcp_clean_death was deferred for
15296 				 * T_ORDREL_IND - do it now
15297 				 */
15298 				tcp->tcp_deferred_clean_death = B_FALSE;
15299 				(void) tcp_clean_death(tcp,
15300 				    tcp->tcp_client_errno, 22);
15301 			}
15302 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15303 			/*
15304 			 * If there isn't already a timer running
15305 			 * start one.  Use a 4 second
15306 			 * timer as a fallback since it can't fail.
15307 			 */
15308 			tcp->tcp_timeout = B_TRUE;
15309 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15310 			    MSEC_TO_TICK(4000));
15311 		}
15312 	}
15313 }
15314 
15315 /*
15316  * The read side service routine is called mostly when we get back-enabled as a
15317  * result of flow control relief.  Since we don't actually queue anything in
15318  * TCP, we have no data to send out of here.  What we do is clear the receive
15319  * window, and send out a window update.
15320  * This routine is also called to drive an orderly release message upstream
15321  * if the attempt in tcp_rput failed.
15322  */
15323 static void
15324 tcp_rsrv(queue_t *q)
15325 {
15326 	conn_t *connp = Q_TO_CONN(q);
15327 	tcp_t	*tcp = connp->conn_tcp;
15328 	mblk_t	*mp;
15329 
15330 	/* No code does a putq on the read side */
15331 	ASSERT(q->q_first == NULL);
15332 
15333 	/* Nothing to do for the default queue */
15334 	if (q == tcp_g_q) {
15335 		return;
15336 	}
15337 
15338 	mp = allocb(0, BPRI_HI);
15339 	if (mp == NULL) {
15340 		/*
15341 		 * We are under memory pressure. Return for now and we
15342 		 * we will be called again later.
15343 		 */
15344 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15345 			/*
15346 			 * If there isn't already a timer running
15347 			 * start one.  Use a 4 second
15348 			 * timer as a fallback since it can't fail.
15349 			 */
15350 			tcp->tcp_timeout = B_TRUE;
15351 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15352 			    MSEC_TO_TICK(4000));
15353 		}
15354 		return;
15355 	}
15356 	CONN_INC_REF(connp);
15357 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15358 	    SQTAG_TCP_RSRV);
15359 }
15360 
15361 /*
15362  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15363  * We do not allow the receive window to shrink.  After setting rwnd,
15364  * set the flow control hiwat of the stream.
15365  *
15366  * This function is called in 2 cases:
15367  *
15368  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15369  *    connection (passive open) and in tcp_rput_data() for active connect.
15370  *    This is called after tcp_mss_set() when the desired MSS value is known.
15371  *    This makes sure that our window size is a mutiple of the other side's
15372  *    MSS.
15373  * 2) Handling SO_RCVBUF option.
15374  *
15375  * It is ASSUMED that the requested size is a multiple of the current MSS.
15376  *
15377  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15378  * user requests so.
15379  */
15380 static int
15381 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15382 {
15383 	uint32_t	mss = tcp->tcp_mss;
15384 	uint32_t	old_max_rwnd;
15385 	uint32_t	max_transmittable_rwnd;
15386 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15387 
15388 	if (tcp->tcp_fused) {
15389 		size_t sth_hiwat;
15390 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15391 
15392 		ASSERT(peer_tcp != NULL);
15393 		/*
15394 		 * Record the stream head's high water mark for
15395 		 * this endpoint; this is used for flow-control
15396 		 * purposes in tcp_fuse_output().
15397 		 */
15398 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15399 		if (!tcp_detached)
15400 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
15401 
15402 		/*
15403 		 * In the fusion case, the maxpsz stream head value of
15404 		 * our peer is set according to its send buffer size
15405 		 * and our receive buffer size; since the latter may
15406 		 * have changed we need to update the peer's maxpsz.
15407 		 */
15408 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15409 		return (rwnd);
15410 	}
15411 
15412 	if (tcp_detached)
15413 		old_max_rwnd = tcp->tcp_rwnd;
15414 	else
15415 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
15416 
15417 	/*
15418 	 * Insist on a receive window that is at least
15419 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15420 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15421 	 * and delayed acknowledgement.
15422 	 */
15423 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
15424 
15425 	/*
15426 	 * If window size info has already been exchanged, TCP should not
15427 	 * shrink the window.  Shrinking window is doable if done carefully.
15428 	 * We may add that support later.  But so far there is not a real
15429 	 * need to do that.
15430 	 */
15431 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15432 		/* MSS may have changed, do a round up again. */
15433 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15434 	}
15435 
15436 	/*
15437 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15438 	 * can be applied even before the window scale option is decided.
15439 	 */
15440 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15441 	if (rwnd > max_transmittable_rwnd) {
15442 		rwnd = max_transmittable_rwnd -
15443 		    (max_transmittable_rwnd % mss);
15444 		if (rwnd < mss)
15445 			rwnd = max_transmittable_rwnd;
15446 		/*
15447 		 * If we're over the limit we may have to back down tcp_rwnd.
15448 		 * The increment below won't work for us. So we set all three
15449 		 * here and the increment below will have no effect.
15450 		 */
15451 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15452 	}
15453 	if (tcp->tcp_localnet) {
15454 		tcp->tcp_rack_abs_max =
15455 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
15456 	} else {
15457 		/*
15458 		 * For a remote host on a different subnet (through a router),
15459 		 * we ack every other packet to be conforming to RFC1122.
15460 		 * tcp_deferred_acks_max is default to 2.
15461 		 */
15462 		tcp->tcp_rack_abs_max =
15463 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
15464 	}
15465 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15466 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15467 	else
15468 		tcp->tcp_rack_cur_max = 0;
15469 	/*
15470 	 * Increment the current rwnd by the amount the maximum grew (we
15471 	 * can not overwrite it since we might be in the middle of a
15472 	 * connection.)
15473 	 */
15474 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15475 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15476 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15477 		tcp->tcp_cwnd_max = rwnd;
15478 
15479 	if (tcp_detached)
15480 		return (rwnd);
15481 	/*
15482 	 * We set the maximum receive window into rq->q_hiwat.
15483 	 * This is not actually used for flow control.
15484 	 */
15485 	tcp->tcp_rq->q_hiwat = rwnd;
15486 	/*
15487 	 * Set the Stream head high water mark. This doesn't have to be
15488 	 * here, since we are simply using default values, but we would
15489 	 * prefer to choose these values algorithmically, with a likely
15490 	 * relationship to rwnd.
15491 	 */
15492 	(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd, tcp_sth_rcv_hiwat));
15493 	return (rwnd);
15494 }
15495 
15496 /*
15497  * Return SNMP stuff in buffer in mpdata.
15498  */
15499 int
15500 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15501 {
15502 	mblk_t			*mpdata;
15503 	mblk_t			*mp_conn_ctl = NULL;
15504 	mblk_t			*mp_conn_data;
15505 	mblk_t			*mp6_conn_ctl = NULL;
15506 	mblk_t			*mp6_conn_data;
15507 	mblk_t			*mp_conn_tail = NULL;
15508 	mblk_t			*mp6_conn_tail = NULL;
15509 	struct opthdr		*optp;
15510 	mib2_tcpConnEntry_t	tce;
15511 	mib2_tcp6ConnEntry_t	tce6;
15512 	connf_t			*connfp;
15513 	conn_t			*connp;
15514 	int			i;
15515 	boolean_t 		ispriv;
15516 	zoneid_t 		zoneid;
15517 
15518 	if (mpctl == NULL ||
15519 	    (mpdata = mpctl->b_cont) == NULL ||
15520 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15521 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL) {
15522 		if (mp_conn_ctl != NULL)
15523 			freemsg(mp_conn_ctl);
15524 		if (mp6_conn_ctl != NULL)
15525 			freemsg(mp6_conn_ctl);
15526 		return (0);
15527 	}
15528 
15529 	/* build table of connections -- need count in fixed part */
15530 	mp_conn_data = mp_conn_ctl->b_cont;
15531 	mp6_conn_data = mp6_conn_ctl->b_cont;
15532 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
15533 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
15534 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
15535 	SET_MIB(tcp_mib.tcpMaxConn, -1);
15536 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
15537 
15538 	ispriv =
15539 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15540 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15541 
15542 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15543 
15544 		connfp = &ipcl_globalhash_fanout[i];
15545 
15546 		connp = NULL;
15547 
15548 		while ((connp =
15549 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15550 			tcp_t *tcp;
15551 
15552 			if (connp->conn_zoneid != zoneid)
15553 				continue;	/* not in this zone */
15554 
15555 			tcp = connp->conn_tcp;
15556 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
15557 			tcp->tcp_ibsegs = 0;
15558 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
15559 			tcp->tcp_obsegs = 0;
15560 
15561 			tce6.tcp6ConnState = tce.tcpConnState =
15562 			    tcp_snmp_state(tcp);
15563 			if (tce.tcpConnState == MIB2_TCP_established ||
15564 			    tce.tcpConnState == MIB2_TCP_closeWait)
15565 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
15566 
15567 			/* Create a message to report on IPv6 entries */
15568 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15569 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15570 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15571 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15572 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15573 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15574 			/* Don't want just anybody seeing these... */
15575 			if (ispriv) {
15576 				tce6.tcp6ConnEntryInfo.ce_snxt =
15577 				    tcp->tcp_snxt;
15578 				tce6.tcp6ConnEntryInfo.ce_suna =
15579 				    tcp->tcp_suna;
15580 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15581 				    tcp->tcp_rnxt;
15582 				tce6.tcp6ConnEntryInfo.ce_rack =
15583 				    tcp->tcp_rack;
15584 			} else {
15585 				/*
15586 				 * Netstat, unfortunately, uses this to
15587 				 * get send/receive queue sizes.  How to fix?
15588 				 * Why not compute the difference only?
15589 				 */
15590 				tce6.tcp6ConnEntryInfo.ce_snxt =
15591 				    tcp->tcp_snxt - tcp->tcp_suna;
15592 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
15593 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15594 				    tcp->tcp_rnxt - tcp->tcp_rack;
15595 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
15596 			}
15597 
15598 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15599 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15600 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
15601 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
15602 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
15603 			(void) snmp_append_data2(mp6_conn_data, &mp6_conn_tail,
15604 			    (char *)&tce6, sizeof (tce6));
15605 			}
15606 			/*
15607 			 * Create an IPv4 table entry for IPv4 entries and also
15608 			 * for IPv6 entries which are bound to in6addr_any
15609 			 * but don't have IPV6_V6ONLY set.
15610 			 * (i.e. anything an IPv4 peer could connect to)
15611 			 */
15612 			if (tcp->tcp_ipversion == IPV4_VERSION ||
15613 			    (tcp->tcp_state <= TCPS_LISTEN &&
15614 			    !tcp->tcp_connp->conn_ipv6_v6only &&
15615 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
15616 				if (tcp->tcp_ipversion == IPV6_VERSION) {
15617 					tce.tcpConnRemAddress = INADDR_ANY;
15618 					tce.tcpConnLocalAddress = INADDR_ANY;
15619 				} else {
15620 					tce.tcpConnRemAddress =
15621 					    tcp->tcp_remote;
15622 					tce.tcpConnLocalAddress =
15623 					    tcp->tcp_ip_src;
15624 				}
15625 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
15626 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
15627 				/* Don't want just anybody seeing these... */
15628 				if (ispriv) {
15629 					tce.tcpConnEntryInfo.ce_snxt =
15630 					    tcp->tcp_snxt;
15631 					tce.tcpConnEntryInfo.ce_suna =
15632 					    tcp->tcp_suna;
15633 					tce.tcpConnEntryInfo.ce_rnxt =
15634 					    tcp->tcp_rnxt;
15635 					tce.tcpConnEntryInfo.ce_rack =
15636 					    tcp->tcp_rack;
15637 				} else {
15638 					/*
15639 					 * Netstat, unfortunately, uses this to
15640 					 * get send/receive queue sizes.  How
15641 					 * to fix?
15642 					 * Why not compute the difference only?
15643 					 */
15644 					tce.tcpConnEntryInfo.ce_snxt =
15645 					    tcp->tcp_snxt - tcp->tcp_suna;
15646 					tce.tcpConnEntryInfo.ce_suna = 0;
15647 					tce.tcpConnEntryInfo.ce_rnxt =
15648 					    tcp->tcp_rnxt - tcp->tcp_rack;
15649 					tce.tcpConnEntryInfo.ce_rack = 0;
15650 				}
15651 
15652 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15653 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15654 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
15655 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
15656 				tce.tcpConnEntryInfo.ce_state =
15657 				    tcp->tcp_state;
15658 				(void) snmp_append_data2(mp_conn_data,
15659 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
15660 			}
15661 		}
15662 	}
15663 
15664 	/* fixed length structure for IPv4 and IPv6 counters */
15665 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
15666 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
15667 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
15668 	optp->level = MIB2_TCP;
15669 	optp->name = 0;
15670 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
15671 	optp->len = msgdsize(mpdata);
15672 	qreply(q, mpctl);
15673 
15674 	/* table of connections... */
15675 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
15676 	    sizeof (struct T_optmgmt_ack)];
15677 	optp->level = MIB2_TCP;
15678 	optp->name = MIB2_TCP_CONN;
15679 	optp->len = msgdsize(mp_conn_data);
15680 	qreply(q, mp_conn_ctl);
15681 
15682 	/* table of IPv6 connections... */
15683 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
15684 	    sizeof (struct T_optmgmt_ack)];
15685 	optp->level = MIB2_TCP6;
15686 	optp->name = MIB2_TCP6_CONN;
15687 	optp->len = msgdsize(mp6_conn_data);
15688 	qreply(q, mp6_conn_ctl);
15689 	return (1);
15690 }
15691 
15692 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
15693 /* ARGSUSED */
15694 int
15695 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
15696 {
15697 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
15698 
15699 	switch (level) {
15700 	case MIB2_TCP:
15701 		switch (name) {
15702 		case 13:
15703 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
15704 				return (0);
15705 			/* TODO: delete entry defined by tce */
15706 			return (1);
15707 		default:
15708 			return (0);
15709 		}
15710 	default:
15711 		return (1);
15712 	}
15713 }
15714 
15715 /* Translate TCP state to MIB2 TCP state. */
15716 static int
15717 tcp_snmp_state(tcp_t *tcp)
15718 {
15719 	if (tcp == NULL)
15720 		return (0);
15721 
15722 	switch (tcp->tcp_state) {
15723 	case TCPS_CLOSED:
15724 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
15725 	case TCPS_BOUND:
15726 		return (MIB2_TCP_closed);
15727 	case TCPS_LISTEN:
15728 		return (MIB2_TCP_listen);
15729 	case TCPS_SYN_SENT:
15730 		return (MIB2_TCP_synSent);
15731 	case TCPS_SYN_RCVD:
15732 		return (MIB2_TCP_synReceived);
15733 	case TCPS_ESTABLISHED:
15734 		return (MIB2_TCP_established);
15735 	case TCPS_CLOSE_WAIT:
15736 		return (MIB2_TCP_closeWait);
15737 	case TCPS_FIN_WAIT_1:
15738 		return (MIB2_TCP_finWait1);
15739 	case TCPS_CLOSING:
15740 		return (MIB2_TCP_closing);
15741 	case TCPS_LAST_ACK:
15742 		return (MIB2_TCP_lastAck);
15743 	case TCPS_FIN_WAIT_2:
15744 		return (MIB2_TCP_finWait2);
15745 	case TCPS_TIME_WAIT:
15746 		return (MIB2_TCP_timeWait);
15747 	default:
15748 		return (0);
15749 	}
15750 }
15751 
15752 static char tcp_report_header[] =
15753 	"TCP     " MI_COL_HDRPAD_STR
15754 	"zone dest            snxt     suna     "
15755 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
15756 	"recent   [lport,fport] state";
15757 
15758 /*
15759  * TCP status report triggered via the Named Dispatch mechanism.
15760  */
15761 /* ARGSUSED */
15762 static void
15763 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
15764     cred_t *cr)
15765 {
15766 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
15767 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
15768 	char cflag;
15769 	in6_addr_t	v6dst;
15770 	char buf[80];
15771 	uint_t print_len, buf_len;
15772 
15773 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
15774 	if (buf_len <= 0)
15775 		return;
15776 
15777 	if (hashval >= 0)
15778 		(void) sprintf(hash, "%03d ", hashval);
15779 	else
15780 		hash[0] = '\0';
15781 
15782 	/*
15783 	 * Note that we use the remote address in the tcp_b  structure.
15784 	 * This means that it will print out the real destination address,
15785 	 * not the next hop's address if source routing is used.  This
15786 	 * avoid the confusion on the output because user may not
15787 	 * know that source routing is used for a connection.
15788 	 */
15789 	if (tcp->tcp_ipversion == IPV4_VERSION) {
15790 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
15791 	} else {
15792 		v6dst = tcp->tcp_remote_v6;
15793 	}
15794 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
15795 	/*
15796 	 * the ispriv checks are so that normal users cannot determine
15797 	 * sequence number information using NDD.
15798 	 */
15799 
15800 	if (TCP_IS_DETACHED(tcp))
15801 		cflag = '*';
15802 	else
15803 		cflag = ' ';
15804 	print_len = snprintf((char *)mp->b_wptr, buf_len,
15805 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
15806 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
15807 	    hash,
15808 	    (void *)tcp,
15809 	    tcp->tcp_connp->conn_zoneid,
15810 	    addrbuf,
15811 	    (ispriv) ? tcp->tcp_snxt : 0,
15812 	    (ispriv) ? tcp->tcp_suna : 0,
15813 	    tcp->tcp_swnd,
15814 	    (ispriv) ? tcp->tcp_rnxt : 0,
15815 	    (ispriv) ? tcp->tcp_rack : 0,
15816 	    tcp->tcp_rwnd,
15817 	    tcp->tcp_rto,
15818 	    tcp->tcp_mss,
15819 	    tcp->tcp_snd_ws_ok,
15820 	    tcp->tcp_snd_ws,
15821 	    tcp->tcp_rcv_ws,
15822 	    tcp->tcp_snd_ts_ok,
15823 	    tcp->tcp_ts_recent,
15824 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
15825 	if (print_len < buf_len) {
15826 		((mblk_t *)mp)->b_wptr += print_len;
15827 	} else {
15828 		((mblk_t *)mp)->b_wptr += buf_len;
15829 	}
15830 }
15831 
15832 /*
15833  * TCP status report (for listeners only) triggered via the Named Dispatch
15834  * mechanism.
15835  */
15836 /* ARGSUSED */
15837 static void
15838 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
15839 {
15840 	char addrbuf[INET6_ADDRSTRLEN];
15841 	in6_addr_t	v6dst;
15842 	uint_t print_len, buf_len;
15843 
15844 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
15845 	if (buf_len <= 0)
15846 		return;
15847 
15848 	if (tcp->tcp_ipversion == IPV4_VERSION) {
15849 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
15850 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
15851 	} else {
15852 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
15853 		    addrbuf, sizeof (addrbuf));
15854 	}
15855 	print_len = snprintf((char *)mp->b_wptr, buf_len,
15856 	    "%03d "
15857 	    MI_COL_PTRFMT_STR
15858 	    "%d %s %05u %08u %d/%d/%d%c\n",
15859 	    hashval, (void *)tcp,
15860 	    tcp->tcp_connp->conn_zoneid,
15861 	    addrbuf,
15862 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
15863 	    tcp->tcp_conn_req_seqnum,
15864 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
15865 	    tcp->tcp_conn_req_max,
15866 	    tcp->tcp_syn_defense ? '*' : ' ');
15867 	if (print_len < buf_len) {
15868 		((mblk_t *)mp)->b_wptr += print_len;
15869 	} else {
15870 		((mblk_t *)mp)->b_wptr += buf_len;
15871 	}
15872 }
15873 
15874 /* TCP status report triggered via the Named Dispatch mechanism. */
15875 /* ARGSUSED */
15876 static int
15877 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15878 {
15879 	tcp_t	*tcp;
15880 	int	i;
15881 	conn_t	*connp;
15882 	connf_t	*connfp;
15883 	zoneid_t zoneid;
15884 
15885 	/*
15886 	 * Because of the ndd constraint, at most we can have 64K buffer
15887 	 * to put in all TCP info.  So to be more efficient, just
15888 	 * allocate a 64K buffer here, assuming we need that large buffer.
15889 	 * This may be a problem as any user can read tcp_status.  Therefore
15890 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
15891 	 * This should be OK as normal users should not do this too often.
15892 	 */
15893 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15894 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15895 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15896 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15897 			return (0);
15898 		}
15899 	}
15900 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15901 		/* The following may work even if we cannot get a large buf. */
15902 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15903 		return (0);
15904 	}
15905 
15906 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
15907 
15908 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15909 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15910 
15911 		connfp = &ipcl_globalhash_fanout[i];
15912 
15913 		connp = NULL;
15914 
15915 		while ((connp =
15916 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15917 			tcp = connp->conn_tcp;
15918 			if (zoneid != GLOBAL_ZONEID &&
15919 			    zoneid != connp->conn_zoneid)
15920 				continue;
15921 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
15922 			    cr);
15923 		}
15924 
15925 	}
15926 
15927 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15928 	return (0);
15929 }
15930 
15931 /* TCP status report triggered via the Named Dispatch mechanism. */
15932 /* ARGSUSED */
15933 static int
15934 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15935 {
15936 	tf_t	*tbf;
15937 	tcp_t	*tcp;
15938 	int	i;
15939 	zoneid_t zoneid;
15940 
15941 	/* Refer to comments in tcp_status_report(). */
15942 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15943 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15944 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15945 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15946 			return (0);
15947 		}
15948 	}
15949 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15950 		/* The following may work even if we cannot get a large buf. */
15951 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15952 		return (0);
15953 	}
15954 
15955 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
15956 
15957 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15958 
15959 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
15960 		tbf = &tcp_bind_fanout[i];
15961 		mutex_enter(&tbf->tf_lock);
15962 		for (tcp = tbf->tf_tcp; tcp != NULL;
15963 		    tcp = tcp->tcp_bind_hash) {
15964 			if (zoneid != GLOBAL_ZONEID &&
15965 			    zoneid != tcp->tcp_connp->conn_zoneid)
15966 				continue;
15967 			CONN_INC_REF(tcp->tcp_connp);
15968 			tcp_report_item(mp->b_cont, tcp, i,
15969 			    Q_TO_TCP(q), cr);
15970 			CONN_DEC_REF(tcp->tcp_connp);
15971 		}
15972 		mutex_exit(&tbf->tf_lock);
15973 	}
15974 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15975 	return (0);
15976 }
15977 
15978 /* TCP status report triggered via the Named Dispatch mechanism. */
15979 /* ARGSUSED */
15980 static int
15981 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15982 {
15983 	connf_t	*connfp;
15984 	conn_t	*connp;
15985 	tcp_t	*tcp;
15986 	int	i;
15987 	zoneid_t zoneid;
15988 
15989 	/* Refer to comments in tcp_status_report(). */
15990 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15991 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15992 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15993 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15994 			return (0);
15995 		}
15996 	}
15997 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15998 		/* The following may work even if we cannot get a large buf. */
15999 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16000 		return (0);
16001 	}
16002 
16003 	(void) mi_mpprintf(mp,
16004 	    "    TCP    " MI_COL_HDRPAD_STR
16005 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16006 
16007 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16008 
16009 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
16010 		connfp =  &ipcl_bind_fanout[i];
16011 		connp = NULL;
16012 		while ((connp =
16013 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16014 			tcp = connp->conn_tcp;
16015 			if (zoneid != GLOBAL_ZONEID &&
16016 			    zoneid != connp->conn_zoneid)
16017 				continue;
16018 			tcp_report_listener(mp->b_cont, tcp, i);
16019 		}
16020 	}
16021 
16022 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16023 	return (0);
16024 }
16025 
16026 /* TCP status report triggered via the Named Dispatch mechanism. */
16027 /* ARGSUSED */
16028 static int
16029 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16030 {
16031 	connf_t	*connfp;
16032 	conn_t	*connp;
16033 	tcp_t	*tcp;
16034 	int	i;
16035 	zoneid_t zoneid;
16036 
16037 	/* Refer to comments in tcp_status_report(). */
16038 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16039 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16040 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16041 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16042 			return (0);
16043 		}
16044 	}
16045 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16046 		/* The following may work even if we cannot get a large buf. */
16047 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16048 		return (0);
16049 	}
16050 
16051 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16052 	    ipcl_conn_fanout_size);
16053 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16054 
16055 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16056 
16057 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
16058 		connfp =  &ipcl_conn_fanout[i];
16059 		connp = NULL;
16060 		while ((connp =
16061 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16062 			tcp = connp->conn_tcp;
16063 			if (zoneid != GLOBAL_ZONEID &&
16064 			    zoneid != connp->conn_zoneid)
16065 				continue;
16066 			tcp_report_item(mp->b_cont, tcp, i,
16067 			    Q_TO_TCP(q), cr);
16068 		}
16069 	}
16070 
16071 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16072 	return (0);
16073 }
16074 
16075 /* TCP status report triggered via the Named Dispatch mechanism. */
16076 /* ARGSUSED */
16077 static int
16078 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16079 {
16080 	tf_t	*tf;
16081 	tcp_t	*tcp;
16082 	int	i;
16083 	zoneid_t zoneid;
16084 
16085 	/* Refer to comments in tcp_status_report(). */
16086 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16087 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16088 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16089 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16090 			return (0);
16091 		}
16092 	}
16093 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16094 		/* The following may work even if we cannot get a large buf. */
16095 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16096 		return (0);
16097 	}
16098 
16099 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16100 
16101 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16102 
16103 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16104 		tf = &tcp_acceptor_fanout[i];
16105 		mutex_enter(&tf->tf_lock);
16106 		for (tcp = tf->tf_tcp; tcp != NULL;
16107 		    tcp = tcp->tcp_acceptor_hash) {
16108 			if (zoneid != GLOBAL_ZONEID &&
16109 			    zoneid != tcp->tcp_connp->conn_zoneid)
16110 				continue;
16111 			tcp_report_item(mp->b_cont, tcp, i,
16112 			    Q_TO_TCP(q), cr);
16113 		}
16114 		mutex_exit(&tf->tf_lock);
16115 	}
16116 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16117 	return (0);
16118 }
16119 
16120 /*
16121  * tcp_timer is the timer service routine.  It handles the retransmission,
16122  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16123  * from the state of the tcp instance what kind of action needs to be done
16124  * at the time it is called.
16125  */
16126 static void
16127 tcp_timer(void *arg)
16128 {
16129 	mblk_t		*mp;
16130 	clock_t		first_threshold;
16131 	clock_t		second_threshold;
16132 	clock_t		ms;
16133 	uint32_t	mss;
16134 	conn_t		*connp = (conn_t *)arg;
16135 	tcp_t		*tcp = connp->conn_tcp;
16136 
16137 	tcp->tcp_timer_tid = 0;
16138 
16139 	if (tcp->tcp_fused)
16140 		return;
16141 
16142 	first_threshold =  tcp->tcp_first_timer_threshold;
16143 	second_threshold = tcp->tcp_second_timer_threshold;
16144 	switch (tcp->tcp_state) {
16145 	case TCPS_IDLE:
16146 	case TCPS_BOUND:
16147 	case TCPS_LISTEN:
16148 		return;
16149 	case TCPS_SYN_RCVD: {
16150 		tcp_t	*listener = tcp->tcp_listener;
16151 
16152 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16153 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16154 			/* it's our first timeout */
16155 			tcp->tcp_syn_rcvd_timeout = 1;
16156 			mutex_enter(&listener->tcp_eager_lock);
16157 			listener->tcp_syn_rcvd_timeout++;
16158 			if (!listener->tcp_syn_defense &&
16159 			    (listener->tcp_syn_rcvd_timeout >
16160 			    (tcp_conn_req_max_q0 >> 2)) &&
16161 			    (tcp_conn_req_max_q0 > 200)) {
16162 				/* We may be under attack. Put on a defense. */
16163 				listener->tcp_syn_defense = B_TRUE;
16164 				cmn_err(CE_WARN, "High TCP connect timeout "
16165 				    "rate! System (port %d) may be under a "
16166 				    "SYN flood attack!",
16167 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16168 
16169 				listener->tcp_ip_addr_cache = kmem_zalloc(
16170 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16171 				    KM_NOSLEEP);
16172 			}
16173 			mutex_exit(&listener->tcp_eager_lock);
16174 		}
16175 	}
16176 		/* FALLTHRU */
16177 	case TCPS_SYN_SENT:
16178 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16179 		second_threshold = tcp->tcp_second_ctimer_threshold;
16180 		break;
16181 	case TCPS_ESTABLISHED:
16182 	case TCPS_FIN_WAIT_1:
16183 	case TCPS_CLOSING:
16184 	case TCPS_CLOSE_WAIT:
16185 	case TCPS_LAST_ACK:
16186 		/* If we have data to rexmit */
16187 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16188 			clock_t	time_to_wait;
16189 
16190 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16191 			if (!tcp->tcp_xmit_head)
16192 				break;
16193 			time_to_wait = lbolt -
16194 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16195 			time_to_wait = tcp->tcp_rto -
16196 			    TICK_TO_MSEC(time_to_wait);
16197 			/*
16198 			 * If the timer fires too early, 1 clock tick earlier,
16199 			 * restart the timer.
16200 			 */
16201 			if (time_to_wait > msec_per_tick) {
16202 				TCP_STAT(tcp_timer_fire_early);
16203 				TCP_TIMER_RESTART(tcp, time_to_wait);
16204 				return;
16205 			}
16206 			/*
16207 			 * When we probe zero windows, we force the swnd open.
16208 			 * If our peer acks with a closed window swnd will be
16209 			 * set to zero by tcp_rput(). As long as we are
16210 			 * receiving acks tcp_rput will
16211 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16212 			 * first and second interval actions.  NOTE: the timer
16213 			 * interval is allowed to continue its exponential
16214 			 * backoff.
16215 			 */
16216 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16217 				if (tcp->tcp_debug) {
16218 					(void) strlog(TCP_MOD_ID, 0, 1,
16219 					    SL_TRACE, "tcp_timer: zero win");
16220 				}
16221 			} else {
16222 				/*
16223 				 * After retransmission, we need to do
16224 				 * slow start.  Set the ssthresh to one
16225 				 * half of current effective window and
16226 				 * cwnd to one MSS.  Also reset
16227 				 * tcp_cwnd_cnt.
16228 				 *
16229 				 * Note that if tcp_ssthresh is reduced because
16230 				 * of ECN, do not reduce it again unless it is
16231 				 * already one window of data away (tcp_cwr
16232 				 * should then be cleared) or this is a
16233 				 * timeout for a retransmitted segment.
16234 				 */
16235 				uint32_t npkt;
16236 
16237 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16238 					npkt = ((tcp->tcp_timer_backoff ?
16239 					    tcp->tcp_cwnd_ssthresh :
16240 					    tcp->tcp_snxt -
16241 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16242 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16243 					    tcp->tcp_mss;
16244 				}
16245 				tcp->tcp_cwnd = tcp->tcp_mss;
16246 				tcp->tcp_cwnd_cnt = 0;
16247 				if (tcp->tcp_ecn_ok) {
16248 					tcp->tcp_cwr = B_TRUE;
16249 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16250 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16251 				}
16252 			}
16253 			break;
16254 		}
16255 		/*
16256 		 * We have something to send yet we cannot send.  The
16257 		 * reason can be:
16258 		 *
16259 		 * 1. Zero send window: we need to do zero window probe.
16260 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16261 		 * segments.
16262 		 * 3. SWS avoidance: receiver may have shrunk window,
16263 		 * reset our knowledge.
16264 		 *
16265 		 * Note that condition 2 can happen with either 1 or
16266 		 * 3.  But 1 and 3 are exclusive.
16267 		 */
16268 		if (tcp->tcp_unsent != 0) {
16269 			if (tcp->tcp_cwnd == 0) {
16270 				/*
16271 				 * Set tcp_cwnd to 1 MSS so that a
16272 				 * new segment can be sent out.  We
16273 				 * are "clocking out" new data when
16274 				 * the network is really congested.
16275 				 */
16276 				ASSERT(tcp->tcp_ecn_ok);
16277 				tcp->tcp_cwnd = tcp->tcp_mss;
16278 			}
16279 			if (tcp->tcp_swnd == 0) {
16280 				/* Extend window for zero window probe */
16281 				tcp->tcp_swnd++;
16282 				tcp->tcp_zero_win_probe = B_TRUE;
16283 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
16284 			} else {
16285 				/*
16286 				 * Handle timeout from sender SWS avoidance.
16287 				 * Reset our knowledge of the max send window
16288 				 * since the receiver might have reduced its
16289 				 * receive buffer.  Avoid setting tcp_max_swnd
16290 				 * to one since that will essentially disable
16291 				 * the SWS checks.
16292 				 *
16293 				 * Note that since we don't have a SWS
16294 				 * state variable, if the timeout is set
16295 				 * for ECN but not for SWS, this
16296 				 * code will also be executed.  This is
16297 				 * fine as tcp_max_swnd is updated
16298 				 * constantly and it will not affect
16299 				 * anything.
16300 				 */
16301 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16302 			}
16303 			tcp_wput_data(tcp, NULL, B_FALSE);
16304 			return;
16305 		}
16306 		/* Is there a FIN that needs to be to re retransmitted? */
16307 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16308 		    !tcp->tcp_fin_acked)
16309 			break;
16310 		/* Nothing to do, return without restarting timer. */
16311 		TCP_STAT(tcp_timer_fire_miss);
16312 		return;
16313 	case TCPS_FIN_WAIT_2:
16314 		/*
16315 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16316 		 * We waited some time for for peer's FIN, but it hasn't
16317 		 * arrived.  We flush the connection now to avoid
16318 		 * case where the peer has rebooted.
16319 		 */
16320 		if (TCP_IS_DETACHED(tcp)) {
16321 			(void) tcp_clean_death(tcp, 0, 23);
16322 		} else {
16323 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
16324 		}
16325 		return;
16326 	case TCPS_TIME_WAIT:
16327 		(void) tcp_clean_death(tcp, 0, 24);
16328 		return;
16329 	default:
16330 		if (tcp->tcp_debug) {
16331 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16332 			    "tcp_timer: strange state (%d) %s",
16333 			    tcp->tcp_state, tcp_display(tcp, NULL,
16334 			    DISP_PORT_ONLY));
16335 		}
16336 		return;
16337 	}
16338 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16339 		/*
16340 		 * For zero window probe, we need to send indefinitely,
16341 		 * unless we have not heard from the other side for some
16342 		 * time...
16343 		 */
16344 		if ((tcp->tcp_zero_win_probe == 0) ||
16345 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16346 		    second_threshold)) {
16347 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
16348 			/*
16349 			 * If TCP is in SYN_RCVD state, send back a
16350 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16351 			 * should be zero in TCPS_SYN_RCVD state.
16352 			 */
16353 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16354 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16355 				    "in SYN_RCVD",
16356 				    tcp, tcp->tcp_snxt,
16357 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16358 			}
16359 			(void) tcp_clean_death(tcp,
16360 			    tcp->tcp_client_errno ?
16361 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16362 			return;
16363 		} else {
16364 			/*
16365 			 * Set tcp_ms_we_have_waited to second_threshold
16366 			 * so that in next timeout, we will do the above
16367 			 * check (lbolt - tcp_last_recv_time).  This is
16368 			 * also to avoid overflow.
16369 			 *
16370 			 * We don't need to decrement tcp_timer_backoff
16371 			 * to avoid overflow because it will be decremented
16372 			 * later if new timeout value is greater than
16373 			 * tcp_rexmit_interval_max.  In the case when
16374 			 * tcp_rexmit_interval_max is greater than
16375 			 * second_threshold, it means that we will wait
16376 			 * longer than second_threshold to send the next
16377 			 * window probe.
16378 			 */
16379 			tcp->tcp_ms_we_have_waited = second_threshold;
16380 		}
16381 	} else if (ms > first_threshold) {
16382 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16383 		    tcp->tcp_xmit_head != NULL) {
16384 			tcp->tcp_xmit_head =
16385 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16386 		}
16387 		/*
16388 		 * We have been retransmitting for too long...  The RTT
16389 		 * we calculated is probably incorrect.  Reinitialize it.
16390 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16391 		 * tcp_rtt_update so that we won't accidentally cache a
16392 		 * bad value.  But only do this if this is not a zero
16393 		 * window probe.
16394 		 */
16395 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16396 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16397 			    (tcp->tcp_rtt_sa >> 5);
16398 			tcp->tcp_rtt_sa = 0;
16399 			tcp_ip_notify(tcp);
16400 			tcp->tcp_rtt_update = 0;
16401 		}
16402 	}
16403 	tcp->tcp_timer_backoff++;
16404 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16405 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16406 	    tcp_rexmit_interval_min) {
16407 		/*
16408 		 * This means the original RTO is tcp_rexmit_interval_min.
16409 		 * So we will use tcp_rexmit_interval_min as the RTO value
16410 		 * and do the backoff.
16411 		 */
16412 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
16413 	} else {
16414 		ms <<= tcp->tcp_timer_backoff;
16415 	}
16416 	if (ms > tcp_rexmit_interval_max) {
16417 		ms = tcp_rexmit_interval_max;
16418 		/*
16419 		 * ms is at max, decrement tcp_timer_backoff to avoid
16420 		 * overflow.
16421 		 */
16422 		tcp->tcp_timer_backoff--;
16423 	}
16424 	tcp->tcp_ms_we_have_waited += ms;
16425 	if (tcp->tcp_zero_win_probe == 0) {
16426 		tcp->tcp_rto = ms;
16427 	}
16428 	TCP_TIMER_RESTART(tcp, ms);
16429 	/*
16430 	 * This is after a timeout and tcp_rto is backed off.  Set
16431 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16432 	 * restart the timer with a correct value.
16433 	 */
16434 	tcp->tcp_set_timer = 1;
16435 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16436 	if (mss > tcp->tcp_mss)
16437 		mss = tcp->tcp_mss;
16438 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16439 		mss = tcp->tcp_swnd;
16440 
16441 	if ((mp = tcp->tcp_xmit_head) != NULL)
16442 		mp->b_prev = (mblk_t *)lbolt;
16443 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16444 	    B_TRUE);
16445 
16446 	/*
16447 	 * When slow start after retransmission begins, start with
16448 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16449 	 * start phase.  tcp_snd_burst controls how many segments
16450 	 * can be sent because of an ack.
16451 	 */
16452 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16453 	tcp->tcp_snd_burst = TCP_CWND_SS;
16454 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16455 	    (tcp->tcp_unsent == 0)) {
16456 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16457 	} else {
16458 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16459 	}
16460 	tcp->tcp_rexmit = B_TRUE;
16461 	tcp->tcp_dupack_cnt = 0;
16462 
16463 	/*
16464 	 * Remove all rexmit SACK blk to start from fresh.
16465 	 */
16466 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16467 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16468 		tcp->tcp_num_notsack_blk = 0;
16469 		tcp->tcp_cnt_notsack_list = 0;
16470 	}
16471 	if (mp == NULL) {
16472 		return;
16473 	}
16474 	/* Attach credentials to retransmitted initial SYNs. */
16475 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16476 		mblk_setcred(mp, tcp->tcp_cred);
16477 		DB_CPID(mp) = tcp->tcp_cpid;
16478 	}
16479 
16480 	tcp->tcp_csuna = tcp->tcp_snxt;
16481 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
16482 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
16483 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
16484 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16485 
16486 }
16487 
16488 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16489 static void
16490 tcp_unbind(tcp_t *tcp, mblk_t *mp)
16491 {
16492 	conn_t	*connp;
16493 
16494 	switch (tcp->tcp_state) {
16495 	case TCPS_BOUND:
16496 	case TCPS_LISTEN:
16497 		break;
16498 	default:
16499 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
16500 		return;
16501 	}
16502 
16503 	/*
16504 	 * Need to clean up all the eagers since after the unbind, segments
16505 	 * will no longer be delivered to this listener stream.
16506 	 */
16507 	mutex_enter(&tcp->tcp_eager_lock);
16508 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16509 		tcp_eager_cleanup(tcp, 0);
16510 	}
16511 	mutex_exit(&tcp->tcp_eager_lock);
16512 
16513 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16514 		tcp->tcp_ipha->ipha_src = 0;
16515 	} else {
16516 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16517 	}
16518 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16519 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16520 	tcp_bind_hash_remove(tcp);
16521 	tcp->tcp_state = TCPS_IDLE;
16522 	tcp->tcp_mdt = B_FALSE;
16523 	/* Send M_FLUSH according to TPI */
16524 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16525 	connp = tcp->tcp_connp;
16526 	connp->conn_mdt_ok = B_FALSE;
16527 	ipcl_hash_remove(connp);
16528 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16529 	mp = mi_tpi_ok_ack_alloc(mp);
16530 	putnext(tcp->tcp_rq, mp);
16531 }
16532 
16533 /*
16534  * Don't let port fall into the privileged range.
16535  * Since the extra privileged ports can be arbitrary we also
16536  * ensure that we exclude those from consideration.
16537  * tcp_g_epriv_ports is not sorted thus we loop over it until
16538  * there are no changes.
16539  *
16540  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16541  * but instead the code relies on:
16542  * - the fact that the address of the array and its size never changes
16543  * - the atomic assignment of the elements of the array
16544  */
16545 static in_port_t
16546 tcp_update_next_port(in_port_t port, boolean_t random)
16547 {
16548 	int i;
16549 
16550 	if (random && tcp_random_anon_port != 0) {
16551 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16552 		    sizeof (in_port_t));
16553 		/*
16554 		 * Unless changed by a sys admin, the smallest anon port
16555 		 * is 32768 and the largest anon port is 65535.  It is
16556 		 * very likely (50%) for the random port to be smaller
16557 		 * than the smallest anon port.  When that happens,
16558 		 * add port % (anon port range) to the smallest anon
16559 		 * port to get the random port.  It should fall into the
16560 		 * valid anon port range.
16561 		 */
16562 		if (port < tcp_smallest_anon_port) {
16563 			port = tcp_smallest_anon_port +
16564 			    port % (tcp_largest_anon_port -
16565 				tcp_smallest_anon_port);
16566 		}
16567 	}
16568 
16569 retry:
16570 	if (port < tcp_smallest_anon_port || port > tcp_largest_anon_port)
16571 		port = (in_port_t)tcp_smallest_anon_port;
16572 
16573 	if (port < tcp_smallest_nonpriv_port)
16574 		port = (in_port_t)tcp_smallest_nonpriv_port;
16575 
16576 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
16577 		if (port == tcp_g_epriv_ports[i]) {
16578 			port++;
16579 			/*
16580 			 * Make sure whether the port is in the
16581 			 * valid range.
16582 			 *
16583 			 * XXX Note that if tcp_g_epriv_ports contains
16584 			 * all the anonymous ports this will be an
16585 			 * infinite loop.
16586 			 */
16587 			goto retry;
16588 		}
16589 	}
16590 	return (port);
16591 }
16592 
16593 /*
16594  * Return the next anonymous port in the priviledged port range for
16595  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16596  * downwards.  This is the same behavior as documented in the userland
16597  * library call rresvport(3N).
16598  */
16599 static in_port_t
16600 tcp_get_next_priv_port(void)
16601 {
16602 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16603 
16604 	if (next_priv_port < tcp_min_anonpriv_port) {
16605 		next_priv_port = IPPORT_RESERVED - 1;
16606 	}
16607 	return (next_priv_port--);
16608 }
16609 
16610 /* The write side r/w procedure. */
16611 
16612 #if CCS_STATS
16613 struct {
16614 	struct {
16615 		int64_t count, bytes;
16616 	} tot, hit;
16617 } wrw_stats;
16618 #endif
16619 
16620 /*
16621  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16622  * messages.
16623  */
16624 /* ARGSUSED */
16625 static void
16626 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16627 {
16628 	conn_t	*connp = (conn_t *)arg;
16629 	tcp_t	*tcp = connp->conn_tcp;
16630 	queue_t	*q = tcp->tcp_wq;
16631 
16632 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16633 	/*
16634 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16635 	 * Once the close starts, streamhead and sockfs will not let any data
16636 	 * packets come down (close ensures that there are no threads using the
16637 	 * queue and no new threads will come down) but since qprocsoff()
16638 	 * hasn't happened yet, a M_FLUSH or some non data message might
16639 	 * get reflected back (in response to our own FLUSHRW) and get
16640 	 * processed after tcp_close() is done. The conn would still be valid
16641 	 * because a ref would have added but we need to check the state
16642 	 * before actually processing the packet.
16643 	 */
16644 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16645 		freemsg(mp);
16646 		return;
16647 	}
16648 
16649 	switch (DB_TYPE(mp)) {
16650 	case M_IOCDATA:
16651 		tcp_wput_iocdata(tcp, mp);
16652 		break;
16653 	case M_FLUSH:
16654 		tcp_wput_flush(tcp, mp);
16655 		break;
16656 	default:
16657 		CALL_IP_WPUT(connp, q, mp);
16658 		break;
16659 	}
16660 }
16661 
16662 /*
16663  * The TCP fast path write put procedure.
16664  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16665  */
16666 /* ARGSUSED */
16667 void
16668 tcp_output(void *arg, mblk_t *mp, void *arg2)
16669 {
16670 	int		len;
16671 	int		hdrlen;
16672 	int		plen;
16673 	mblk_t		*mp1;
16674 	uchar_t		*rptr;
16675 	uint32_t	snxt;
16676 	tcph_t		*tcph;
16677 	struct datab	*db;
16678 	uint32_t	suna;
16679 	uint32_t	mss;
16680 	ipaddr_t	*dst;
16681 	ipaddr_t	*src;
16682 	uint32_t	sum;
16683 	int		usable;
16684 	conn_t		*connp = (conn_t *)arg;
16685 	tcp_t		*tcp = connp->conn_tcp;
16686 	uint32_t	msize;
16687 
16688 	/*
16689 	 * Try and ASSERT the minimum possible references on the
16690 	 * conn early enough. Since we are executing on write side,
16691 	 * the connection is obviously not detached and that means
16692 	 * there is a ref each for TCP and IP. Since we are behind
16693 	 * the squeue, the minimum references needed are 3. If the
16694 	 * conn is in classifier hash list, there should be an
16695 	 * extra ref for that (we check both the possibilities).
16696 	 */
16697 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16698 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16699 
16700 	/* Bypass tcp protocol for fused tcp loopback */
16701 	if (tcp->tcp_fused) {
16702 		msize = msgdsize(mp);
16703 		mutex_enter(&connp->conn_lock);
16704 		tcp->tcp_squeue_bytes -= msize;
16705 		mutex_exit(&connp->conn_lock);
16706 
16707 		if (tcp_fuse_output(tcp, mp, msize))
16708 			return;
16709 	}
16710 
16711 	mss = tcp->tcp_mss;
16712 	if (tcp->tcp_xmit_zc_clean)
16713 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16714 
16715 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16716 	len = (int)(mp->b_wptr - mp->b_rptr);
16717 
16718 	/*
16719 	 * Criteria for fast path:
16720 	 *
16721 	 *   1. no unsent data
16722 	 *   2. single mblk in request
16723 	 *   3. connection established
16724 	 *   4. data in mblk
16725 	 *   5. len <= mss
16726 	 *   6. no tcp_valid bits
16727 	 */
16728 	if ((tcp->tcp_unsent != 0) ||
16729 	    (tcp->tcp_cork) ||
16730 	    (mp->b_cont != NULL) ||
16731 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16732 	    (len == 0) ||
16733 	    (len > mss) ||
16734 	    (tcp->tcp_valid_bits != 0)) {
16735 		msize = msgdsize(mp);
16736 		mutex_enter(&connp->conn_lock);
16737 		tcp->tcp_squeue_bytes -= msize;
16738 		mutex_exit(&connp->conn_lock);
16739 
16740 		tcp_wput_data(tcp, mp, B_FALSE);
16741 		return;
16742 	}
16743 
16744 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16745 	ASSERT(tcp->tcp_fin_sent == 0);
16746 
16747 	mutex_enter(&connp->conn_lock);
16748 	tcp->tcp_squeue_bytes -= len;
16749 	mutex_exit(&connp->conn_lock);
16750 
16751 	/* queue new packet onto retransmission queue */
16752 	if (tcp->tcp_xmit_head == NULL) {
16753 		tcp->tcp_xmit_head = mp;
16754 	} else {
16755 		tcp->tcp_xmit_last->b_cont = mp;
16756 	}
16757 	tcp->tcp_xmit_last = mp;
16758 	tcp->tcp_xmit_tail = mp;
16759 
16760 	/* find out how much we can send */
16761 	/* BEGIN CSTYLED */
16762 	/*
16763 	 *    un-acked           usable
16764 	 *  |--------------|-----------------|
16765 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
16766 	 */
16767 	/* END CSTYLED */
16768 
16769 	/* start sending from tcp_snxt */
16770 	snxt = tcp->tcp_snxt;
16771 
16772 	/*
16773 	 * Check to see if this connection has been idled for some
16774 	 * time and no ACK is expected.  If it is, we need to slow
16775 	 * start again to get back the connection's "self-clock" as
16776 	 * described in VJ's paper.
16777 	 *
16778 	 * Refer to the comment in tcp_mss_set() for the calculation
16779 	 * of tcp_cwnd after idle.
16780 	 */
16781 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16782 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16783 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
16784 	}
16785 
16786 	usable = tcp->tcp_swnd;		/* tcp window size */
16787 	if (usable > tcp->tcp_cwnd)
16788 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16789 	usable -= snxt;		/* subtract stuff already sent */
16790 	suna = tcp->tcp_suna;
16791 	usable += suna;
16792 	/* usable can be < 0 if the congestion window is smaller */
16793 	if (len > usable) {
16794 		/* Can't send complete M_DATA in one shot */
16795 		goto slow;
16796 	}
16797 
16798 	if (tcp->tcp_flow_stopped &&
16799 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16800 		tcp_clrqfull(tcp);
16801 	}
16802 
16803 	/*
16804 	 * determine if anything to send (Nagle).
16805 	 *
16806 	 *   1. len < tcp_mss (i.e. small)
16807 	 *   2. unacknowledged data present
16808 	 *   3. len < nagle limit
16809 	 *   4. last packet sent < nagle limit (previous packet sent)
16810 	 */
16811 	if ((len < mss) && (snxt != suna) &&
16812 	    (len < (int)tcp->tcp_naglim) &&
16813 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
16814 		/*
16815 		 * This was the first unsent packet and normally
16816 		 * mss < xmit_hiwater so there is no need to worry
16817 		 * about flow control. The next packet will go
16818 		 * through the flow control check in tcp_wput_data().
16819 		 */
16820 		/* leftover work from above */
16821 		tcp->tcp_unsent = len;
16822 		tcp->tcp_xmit_tail_unsent = len;
16823 
16824 		return;
16825 	}
16826 
16827 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
16828 
16829 	if (snxt == suna) {
16830 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16831 	}
16832 
16833 	/* we have always sent something */
16834 	tcp->tcp_rack_cnt = 0;
16835 
16836 	tcp->tcp_snxt = snxt + len;
16837 	tcp->tcp_rack = tcp->tcp_rnxt;
16838 
16839 	if ((mp1 = dupb(mp)) == 0)
16840 		goto no_memory;
16841 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
16842 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
16843 
16844 	/* adjust tcp header information */
16845 	tcph = tcp->tcp_tcph;
16846 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
16847 
16848 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
16849 	sum = (sum >> 16) + (sum & 0xFFFF);
16850 	U16_TO_ABE16(sum, tcph->th_sum);
16851 
16852 	U32_TO_ABE32(snxt, tcph->th_seq);
16853 
16854 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
16855 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
16856 	BUMP_LOCAL(tcp->tcp_obsegs);
16857 
16858 	/* Update the latest receive window size in TCP header. */
16859 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
16860 	    tcph->th_win);
16861 
16862 	tcp->tcp_last_sent_len = (ushort_t)len;
16863 
16864 	plen = len + tcp->tcp_hdr_len;
16865 
16866 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16867 		tcp->tcp_ipha->ipha_length = htons(plen);
16868 	} else {
16869 		tcp->tcp_ip6h->ip6_plen = htons(plen -
16870 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
16871 	}
16872 
16873 	/* see if we need to allocate a mblk for the headers */
16874 	hdrlen = tcp->tcp_hdr_len;
16875 	rptr = mp1->b_rptr - hdrlen;
16876 	db = mp1->b_datap;
16877 	if ((db->db_ref != 2) || rptr < db->db_base ||
16878 	    (!OK_32PTR(rptr))) {
16879 		/* NOTE: we assume allocb returns an OK_32PTR */
16880 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
16881 		    tcp_wroff_xtra, BPRI_MED);
16882 		if (!mp) {
16883 			freemsg(mp1);
16884 			goto no_memory;
16885 		}
16886 		mp->b_cont = mp1;
16887 		mp1 = mp;
16888 		/* Leave room for Link Level header */
16889 		/* hdrlen = tcp->tcp_hdr_len; */
16890 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
16891 		mp1->b_wptr = &rptr[hdrlen];
16892 	}
16893 	mp1->b_rptr = rptr;
16894 
16895 	/* Fill in the timestamp option. */
16896 	if (tcp->tcp_snd_ts_ok) {
16897 		U32_TO_BE32((uint32_t)lbolt,
16898 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
16899 		U32_TO_BE32(tcp->tcp_ts_recent,
16900 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
16901 	} else {
16902 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
16903 	}
16904 
16905 	/* copy header into outgoing packet */
16906 	dst = (ipaddr_t *)rptr;
16907 	src = (ipaddr_t *)tcp->tcp_iphc;
16908 	dst[0] = src[0];
16909 	dst[1] = src[1];
16910 	dst[2] = src[2];
16911 	dst[3] = src[3];
16912 	dst[4] = src[4];
16913 	dst[5] = src[5];
16914 	dst[6] = src[6];
16915 	dst[7] = src[7];
16916 	dst[8] = src[8];
16917 	dst[9] = src[9];
16918 	if (hdrlen -= 40) {
16919 		hdrlen >>= 2;
16920 		dst += 10;
16921 		src += 10;
16922 		do {
16923 			*dst++ = *src++;
16924 		} while (--hdrlen);
16925 	}
16926 
16927 	/*
16928 	 * Set the ECN info in the TCP header.  Note that this
16929 	 * is not the template header.
16930 	 */
16931 	if (tcp->tcp_ecn_ok) {
16932 		SET_ECT(tcp, rptr);
16933 
16934 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
16935 		if (tcp->tcp_ecn_echo_on)
16936 			tcph->th_flags[0] |= TH_ECE;
16937 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
16938 			tcph->th_flags[0] |= TH_CWR;
16939 			tcp->tcp_ecn_cwr_sent = B_TRUE;
16940 		}
16941 	}
16942 
16943 	if (tcp->tcp_ip_forward_progress) {
16944 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
16945 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
16946 		tcp->tcp_ip_forward_progress = B_FALSE;
16947 	}
16948 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
16949 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
16950 	return;
16951 
16952 	/*
16953 	 * If we ran out of memory, we pretend to have sent the packet
16954 	 * and that it was lost on the wire.
16955 	 */
16956 no_memory:
16957 	return;
16958 
16959 slow:
16960 	/* leftover work from above */
16961 	tcp->tcp_unsent = len;
16962 	tcp->tcp_xmit_tail_unsent = len;
16963 	tcp_wput_data(tcp, NULL, B_FALSE);
16964 }
16965 
16966 /*
16967  * The function called through squeue to get behind eager's perimeter to
16968  * finish the accept processing.
16969  */
16970 /* ARGSUSED */
16971 void
16972 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
16973 {
16974 	conn_t			*connp = (conn_t *)arg;
16975 	tcp_t			*tcp = connp->conn_tcp;
16976 	queue_t			*q = tcp->tcp_rq;
16977 	mblk_t			*mp1;
16978 	mblk_t			*stropt_mp = mp;
16979 	struct  stroptions	*stropt;
16980 	uint_t			thwin;
16981 
16982 	/*
16983 	 * Drop the eager's ref on the listener, that was placed when
16984 	 * this eager began life in tcp_conn_request.
16985 	 */
16986 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
16987 
16988 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
16989 		/*
16990 		 * Someone blewoff the eager before we could finish
16991 		 * the accept.
16992 		 *
16993 		 * The only reason eager exists it because we put in
16994 		 * a ref on it when conn ind went up. We need to send
16995 		 * a disconnect indication up while the last reference
16996 		 * on the eager will be dropped by the squeue when we
16997 		 * return.
16998 		 */
16999 		ASSERT(tcp->tcp_listener == NULL);
17000 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17001 			struct	T_discon_ind	*tdi;
17002 
17003 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17004 			/*
17005 			 * Let us reuse the incoming mblk to avoid memory
17006 			 * allocation failure problems. We know that the
17007 			 * size of the incoming mblk i.e. stroptions is greater
17008 			 * than sizeof T_discon_ind. So the reallocb below
17009 			 * can't fail.
17010 			 */
17011 			freemsg(mp->b_cont);
17012 			mp->b_cont = NULL;
17013 			ASSERT(DB_REF(mp) == 1);
17014 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17015 			    B_FALSE);
17016 			ASSERT(mp != NULL);
17017 			DB_TYPE(mp) = M_PROTO;
17018 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17019 			tdi = (struct T_discon_ind *)mp->b_rptr;
17020 			if (tcp->tcp_issocket) {
17021 				tdi->DISCON_reason = ECONNREFUSED;
17022 				tdi->SEQ_number = 0;
17023 			} else {
17024 				tdi->DISCON_reason = ENOPROTOOPT;
17025 				tdi->SEQ_number =
17026 				    tcp->tcp_conn_req_seqnum;
17027 			}
17028 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17029 			putnext(q, mp);
17030 		} else {
17031 			freemsg(mp);
17032 		}
17033 		if (tcp->tcp_hard_binding) {
17034 			tcp->tcp_hard_binding = B_FALSE;
17035 			tcp->tcp_hard_bound = B_TRUE;
17036 		}
17037 		tcp->tcp_detached = B_FALSE;
17038 		return;
17039 	}
17040 
17041 	mp1 = stropt_mp->b_cont;
17042 	stropt_mp->b_cont = NULL;
17043 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17044 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17045 
17046 	while (mp1 != NULL) {
17047 		mp = mp1;
17048 		mp1 = mp1->b_cont;
17049 		mp->b_cont = NULL;
17050 		tcp->tcp_drop_opt_ack_cnt++;
17051 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17052 	}
17053 	mp = NULL;
17054 
17055 	/*
17056 	 * For a loopback connection with tcp_direct_sockfs on, note that
17057 	 * we don't have to protect tcp_rcv_list yet because synchronous
17058 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17059 	 * possibly race with us.
17060 	 */
17061 
17062 	/*
17063 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17064 	 * properly.  This is the first time we know of the acceptor'
17065 	 * queue.  So we do it here.
17066 	 */
17067 	if (tcp->tcp_rcv_list == NULL) {
17068 		/*
17069 		 * Recv queue is empty, tcp_rwnd should not have changed.
17070 		 * That means it should be equal to the listener's tcp_rwnd.
17071 		 */
17072 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17073 	} else {
17074 #ifdef DEBUG
17075 		uint_t cnt = 0;
17076 
17077 		mp1 = tcp->tcp_rcv_list;
17078 		while ((mp = mp1) != NULL) {
17079 			mp1 = mp->b_next;
17080 			cnt += msgdsize(mp);
17081 		}
17082 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17083 #endif
17084 		/* There is some data, add them back to get the max. */
17085 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17086 	}
17087 
17088 	stropt->so_flags = SO_HIWAT;
17089 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
17090 
17091 	stropt->so_flags |= SO_MAXBLK;
17092 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17093 
17094 	/*
17095 	 * This is the first time we run on the correct
17096 	 * queue after tcp_accept. So fix all the q parameters
17097 	 * here.
17098 	 */
17099 	/* Allocate room for SACK options if needed. */
17100 	stropt->so_flags |= SO_WROFF;
17101 	if (tcp->tcp_fused) {
17102 		ASSERT(tcp->tcp_loopback);
17103 		ASSERT(tcp->tcp_loopback_peer != NULL);
17104 		/*
17105 		 * For fused tcp loopback, set the stream head's write
17106 		 * offset value to zero since we won't be needing any room
17107 		 * for TCP/IP headers.  This would also improve performance
17108 		 * since it would reduce the amount of work done by kmem.
17109 		 * Non-fused tcp loopback case is handled separately below.
17110 		 */
17111 		stropt->so_wroff = 0;
17112 		/*
17113 		 * Record the stream head's high water mark for this endpoint;
17114 		 * this is used for flow-control purposes in tcp_fuse_output().
17115 		 */
17116 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17117 		/*
17118 		 * Update the peer's transmit parameters according to
17119 		 * our recently calculated high water mark value.
17120 		 */
17121 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17122 	} else if (tcp->tcp_snd_sack_ok) {
17123 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17124 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17125 	} else {
17126 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17127 		    tcp_wroff_xtra);
17128 	}
17129 
17130 	/*
17131 	 * If this is endpoint is handling SSL, then reserve extra
17132 	 * offset and space at the end.
17133 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17134 	 * overriding the previous setting. The extra cost of signing and
17135 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17136 	 * instead of a single contiguous one by the stream head
17137 	 * largely outweighs the statistical reduction of ACKs, when
17138 	 * applicable. The peer will also save on decyption and verification
17139 	 * costs.
17140 	 */
17141 	if (tcp->tcp_kssl_ctx != NULL) {
17142 		stropt->so_wroff += SSL3_WROFFSET;
17143 
17144 		stropt->so_flags |= SO_TAIL;
17145 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
17146 
17147 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
17148 	}
17149 
17150 	/* Send the options up */
17151 	putnext(q, stropt_mp);
17152 
17153 	/*
17154 	 * Pass up any data and/or a fin that has been received.
17155 	 *
17156 	 * Adjust receive window in case it had decreased
17157 	 * (because there is data <=> tcp_rcv_list != NULL)
17158 	 * while the connection was detached. Note that
17159 	 * in case the eager was flow-controlled, w/o this
17160 	 * code, the rwnd may never open up again!
17161 	 */
17162 	if (tcp->tcp_rcv_list != NULL) {
17163 		/* We drain directly in case of fused tcp loopback */
17164 		if (!tcp->tcp_fused && canputnext(q)) {
17165 			tcp->tcp_rwnd = q->q_hiwat;
17166 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17167 			    << tcp->tcp_rcv_ws;
17168 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17169 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17170 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17171 				tcp_xmit_ctl(NULL,
17172 				    tcp, (tcp->tcp_swnd == 0) ?
17173 				    tcp->tcp_suna : tcp->tcp_snxt,
17174 				    tcp->tcp_rnxt, TH_ACK);
17175 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17176 			}
17177 
17178 		}
17179 		(void) tcp_rcv_drain(q, tcp);
17180 
17181 		/*
17182 		 * For fused tcp loopback, back-enable peer endpoint
17183 		 * if it's currently flow-controlled.
17184 		 */
17185 		if (tcp->tcp_fused &&
17186 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17187 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17188 
17189 			ASSERT(peer_tcp != NULL);
17190 			ASSERT(peer_tcp->tcp_fused);
17191 
17192 			tcp_clrqfull(peer_tcp);
17193 			TCP_STAT(tcp_fusion_backenabled);
17194 		}
17195 	}
17196 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17197 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17198 		mp = mi_tpi_ordrel_ind();
17199 		if (mp) {
17200 			tcp->tcp_ordrel_done = B_TRUE;
17201 			putnext(q, mp);
17202 			if (tcp->tcp_deferred_clean_death) {
17203 				/*
17204 				 * tcp_clean_death was deferred
17205 				 * for T_ORDREL_IND - do it now
17206 				 */
17207 				(void) tcp_clean_death(tcp,
17208 				    tcp->tcp_client_errno, 21);
17209 				tcp->tcp_deferred_clean_death = B_FALSE;
17210 			}
17211 		} else {
17212 			/*
17213 			 * Run the orderly release in the
17214 			 * service routine.
17215 			 */
17216 			qenable(q);
17217 		}
17218 	}
17219 	if (tcp->tcp_hard_binding) {
17220 		tcp->tcp_hard_binding = B_FALSE;
17221 		tcp->tcp_hard_bound = B_TRUE;
17222 	}
17223 
17224 	tcp->tcp_detached = B_FALSE;
17225 
17226 	/* We can enable synchronous streams now */
17227 	if (tcp->tcp_fused) {
17228 		tcp_fuse_syncstr_enable_pair(tcp);
17229 	}
17230 
17231 	if (tcp->tcp_ka_enabled) {
17232 		tcp->tcp_ka_last_intrvl = 0;
17233 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17234 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17235 	}
17236 
17237 	/*
17238 	 * At this point, eager is fully established and will
17239 	 * have the following references -
17240 	 *
17241 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17242 	 * 1 reference for the squeue which will be dropped by the squeue as
17243 	 *	soon as this function returns.
17244 	 * There will be 1 additonal reference for being in classifier
17245 	 *	hash list provided something bad hasn't happened.
17246 	 */
17247 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17248 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17249 }
17250 
17251 /*
17252  * The function called through squeue to get behind listener's perimeter to
17253  * send a deffered conn_ind.
17254  */
17255 /* ARGSUSED */
17256 void
17257 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17258 {
17259 	conn_t	*connp = (conn_t *)arg;
17260 	tcp_t *listener = connp->conn_tcp;
17261 
17262 	if (listener->tcp_state == TCPS_CLOSED ||
17263 	    TCP_IS_DETACHED(listener)) {
17264 		/*
17265 		 * If listener has closed, it would have caused a
17266 		 * a cleanup/blowoff to happen for the eager.
17267 		 */
17268 		tcp_t *tcp;
17269 		struct T_conn_ind	*conn_ind;
17270 
17271 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
17272 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17273 		    conn_ind->OPT_length);
17274 		/*
17275 		 * We need to drop the ref on eager that was put
17276 		 * tcp_rput_data() before trying to send the conn_ind
17277 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17278 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17279 		 * listener is closed so we drop the ref.
17280 		 */
17281 		CONN_DEC_REF(tcp->tcp_connp);
17282 		freemsg(mp);
17283 		return;
17284 	}
17285 	putnext(listener->tcp_rq, mp);
17286 }
17287 
17288 
17289 /*
17290  * This is the STREAMS entry point for T_CONN_RES coming down on
17291  * Acceptor STREAM when  sockfs listener does accept processing.
17292  * Read the block comment on top pf tcp_conn_request().
17293  */
17294 void
17295 tcp_wput_accept(queue_t *q, mblk_t *mp)
17296 {
17297 	queue_t *rq = RD(q);
17298 	struct T_conn_res *conn_res;
17299 	tcp_t *eager;
17300 	tcp_t *listener;
17301 	struct T_ok_ack *ok;
17302 	t_scalar_t PRIM_type;
17303 	mblk_t *opt_mp;
17304 	conn_t *econnp;
17305 
17306 	ASSERT(DB_TYPE(mp) == M_PROTO);
17307 
17308 	conn_res = (struct T_conn_res *)mp->b_rptr;
17309 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17310 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17311 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17312 		if (mp != NULL)
17313 			putnext(rq, mp);
17314 		return;
17315 	}
17316 	switch (conn_res->PRIM_type) {
17317 	case O_T_CONN_RES:
17318 	case T_CONN_RES:
17319 		/*
17320 		 * We pass up an err ack if allocb fails. This will
17321 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17322 		 * tcp_eager_blowoff to be called. sockfs will then call
17323 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17324 		 * we need to do the allocb up here because we have to
17325 		 * make sure rq->q_qinfo->qi_qclose still points to the
17326 		 * correct function (tcpclose_accept) in case allocb
17327 		 * fails.
17328 		 */
17329 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17330 		if (opt_mp == NULL) {
17331 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17332 			if (mp != NULL)
17333 				putnext(rq, mp);
17334 			return;
17335 		}
17336 
17337 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17338 		    &eager, conn_res->OPT_length);
17339 		PRIM_type = conn_res->PRIM_type;
17340 		mp->b_datap->db_type = M_PCPROTO;
17341 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17342 		ok = (struct T_ok_ack *)mp->b_rptr;
17343 		ok->PRIM_type = T_OK_ACK;
17344 		ok->CORRECT_prim = PRIM_type;
17345 		econnp = eager->tcp_connp;
17346 		econnp->conn_dev = (dev_t)q->q_ptr;
17347 		eager->tcp_rq = rq;
17348 		eager->tcp_wq = q;
17349 		rq->q_ptr = econnp;
17350 		rq->q_qinfo = &tcp_rinit;
17351 		q->q_ptr = econnp;
17352 		q->q_qinfo = &tcp_winit;
17353 		listener = eager->tcp_listener;
17354 		eager->tcp_issocket = B_TRUE;
17355 		eager->tcp_cred = econnp->conn_cred =
17356 		    listener->tcp_connp->conn_cred;
17357 		crhold(econnp->conn_cred);
17358 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17359 
17360 		/* Put the ref for IP */
17361 		CONN_INC_REF(econnp);
17362 
17363 		/*
17364 		 * We should have minimum of 3 references on the conn
17365 		 * at this point. One each for TCP and IP and one for
17366 		 * the T_conn_ind that was sent up when the 3-way handshake
17367 		 * completed. In the normal case we would also have another
17368 		 * reference (making a total of 4) for the conn being in the
17369 		 * classifier hash list. However the eager could have received
17370 		 * an RST subsequently and tcp_closei_local could have removed
17371 		 * the eager from the classifier hash list, hence we can't
17372 		 * assert that reference.
17373 		 */
17374 		ASSERT(econnp->conn_ref >= 3);
17375 
17376 		/*
17377 		 * Send the new local address also up to sockfs. There
17378 		 * should already be enough space in the mp that came
17379 		 * down from soaccept().
17380 		 */
17381 		if (eager->tcp_family == AF_INET) {
17382 			sin_t *sin;
17383 
17384 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17385 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17386 			sin = (sin_t *)mp->b_wptr;
17387 			mp->b_wptr += sizeof (sin_t);
17388 			sin->sin_family = AF_INET;
17389 			sin->sin_port = eager->tcp_lport;
17390 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17391 		} else {
17392 			sin6_t *sin6;
17393 
17394 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17395 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17396 			sin6 = (sin6_t *)mp->b_wptr;
17397 			mp->b_wptr += sizeof (sin6_t);
17398 			sin6->sin6_family = AF_INET6;
17399 			sin6->sin6_port = eager->tcp_lport;
17400 			if (eager->tcp_ipversion == IPV4_VERSION) {
17401 				sin6->sin6_flowinfo = 0;
17402 				IN6_IPADDR_TO_V4MAPPED(
17403 					eager->tcp_ipha->ipha_src,
17404 					    &sin6->sin6_addr);
17405 			} else {
17406 				ASSERT(eager->tcp_ip6h != NULL);
17407 				sin6->sin6_flowinfo =
17408 				    eager->tcp_ip6h->ip6_vcf &
17409 				    ~IPV6_VERS_AND_FLOW_MASK;
17410 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17411 			}
17412 			sin6->sin6_scope_id = 0;
17413 			sin6->__sin6_src_id = 0;
17414 		}
17415 
17416 		putnext(rq, mp);
17417 
17418 		opt_mp->b_datap->db_type = M_SETOPTS;
17419 		opt_mp->b_wptr += sizeof (struct stroptions);
17420 
17421 		/*
17422 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17423 		 * from listener to acceptor. The message is chained on the
17424 		 * bind_mp which tcp_rput_other will send down to IP.
17425 		 */
17426 		if (listener->tcp_bound_if != 0) {
17427 			/* allocate optmgmt req */
17428 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17429 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
17430 			    sizeof (int));
17431 			if (mp != NULL)
17432 				linkb(opt_mp, mp);
17433 		}
17434 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17435 			uint_t on = 1;
17436 
17437 			/* allocate optmgmt req */
17438 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17439 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
17440 			if (mp != NULL)
17441 				linkb(opt_mp, mp);
17442 		}
17443 
17444 
17445 		mutex_enter(&listener->tcp_eager_lock);
17446 
17447 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17448 
17449 			tcp_t *tail;
17450 			tcp_t *tcp;
17451 			mblk_t *mp1;
17452 
17453 			tcp = listener->tcp_eager_prev_q0;
17454 			/*
17455 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
17456 			 * deferred T_conn_ind queue. We need to get to the head
17457 			 * of the queue in order to send up T_conn_ind the same
17458 			 * order as how the 3WHS is completed.
17459 			 */
17460 			while (tcp != listener) {
17461 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17462 				    !tcp->tcp_kssl_pending)
17463 					break;
17464 				else
17465 					tcp = tcp->tcp_eager_prev_q0;
17466 			}
17467 			/* None of the pending eagers can be sent up now */
17468 			if (tcp == listener)
17469 				goto no_more_eagers;
17470 
17471 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17472 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17473 			/* Move from q0 to q */
17474 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17475 			listener->tcp_conn_req_cnt_q0--;
17476 			listener->tcp_conn_req_cnt_q++;
17477 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17478 			    tcp->tcp_eager_prev_q0;
17479 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17480 			    tcp->tcp_eager_next_q0;
17481 			tcp->tcp_eager_prev_q0 = NULL;
17482 			tcp->tcp_eager_next_q0 = NULL;
17483 			tcp->tcp_conn_def_q0 = B_FALSE;
17484 
17485 			/*
17486 			 * Insert at end of the queue because sockfs sends
17487 			 * down T_CONN_RES in chronological order. Leaving
17488 			 * the older conn indications at front of the queue
17489 			 * helps reducing search time.
17490 			 */
17491 			tail = listener->tcp_eager_last_q;
17492 			if (tail != NULL) {
17493 				tail->tcp_eager_next_q = tcp;
17494 			} else {
17495 				listener->tcp_eager_next_q = tcp;
17496 			}
17497 			listener->tcp_eager_last_q = tcp;
17498 			tcp->tcp_eager_next_q = NULL;
17499 
17500 			/* Need to get inside the listener perimeter */
17501 			CONN_INC_REF(listener->tcp_connp);
17502 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
17503 			    tcp_send_pending, listener->tcp_connp,
17504 			    SQTAG_TCP_SEND_PENDING);
17505 		}
17506 no_more_eagers:
17507 		tcp_eager_unlink(eager);
17508 		mutex_exit(&listener->tcp_eager_lock);
17509 
17510 		/*
17511 		 * At this point, the eager is detached from the listener
17512 		 * but we still have an extra refs on eager (apart from the
17513 		 * usual tcp references). The ref was placed in tcp_rput_data
17514 		 * before sending the conn_ind in tcp_send_conn_ind.
17515 		 * The ref will be dropped in tcp_accept_finish().
17516 		 */
17517 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
17518 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
17519 		return;
17520 	default:
17521 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17522 		if (mp != NULL)
17523 			putnext(rq, mp);
17524 		return;
17525 	}
17526 }
17527 
17528 void
17529 tcp_wput(queue_t *q, mblk_t *mp)
17530 {
17531 	conn_t	*connp = Q_TO_CONN(q);
17532 	tcp_t	*tcp;
17533 	void (*output_proc)();
17534 	t_scalar_t type;
17535 	uchar_t *rptr;
17536 	struct iocblk	*iocp;
17537 	uint32_t	msize;
17538 
17539 	ASSERT(connp->conn_ref >= 2);
17540 
17541 	switch (DB_TYPE(mp)) {
17542 	case M_DATA:
17543 		tcp = connp->conn_tcp;
17544 		ASSERT(tcp != NULL);
17545 
17546 		msize = msgdsize(mp);
17547 
17548 		mutex_enter(&connp->conn_lock);
17549 		CONN_INC_REF_LOCKED(connp);
17550 
17551 		tcp->tcp_squeue_bytes += msize;
17552 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
17553 			mutex_exit(&connp->conn_lock);
17554 			tcp_setqfull(tcp);
17555 		} else
17556 			mutex_exit(&connp->conn_lock);
17557 
17558 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17559 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
17560 		return;
17561 	case M_PROTO:
17562 	case M_PCPROTO:
17563 		/*
17564 		 * if it is a snmp message, don't get behind the squeue
17565 		 */
17566 		tcp = connp->conn_tcp;
17567 		rptr = mp->b_rptr;
17568 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
17569 			type = ((union T_primitives *)rptr)->type;
17570 		} else {
17571 			if (tcp->tcp_debug) {
17572 				(void) strlog(TCP_MOD_ID, 0, 1,
17573 				    SL_ERROR|SL_TRACE,
17574 				    "tcp_wput_proto, dropping one...");
17575 			}
17576 			freemsg(mp);
17577 			return;
17578 		}
17579 		if (type == T_SVR4_OPTMGMT_REQ) {
17580 			cred_t	*cr = DB_CREDDEF(mp,
17581 			    tcp->tcp_cred);
17582 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
17583 			    cr)) {
17584 				/*
17585 				 * This was a SNMP request
17586 				 */
17587 				return;
17588 			} else {
17589 				output_proc = tcp_wput_proto;
17590 			}
17591 		} else {
17592 			output_proc = tcp_wput_proto;
17593 		}
17594 		break;
17595 	case M_IOCTL:
17596 		/*
17597 		 * Most ioctls can be processed right away without going via
17598 		 * squeues - process them right here. Those that do require
17599 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
17600 		 * are processed by tcp_wput_ioctl().
17601 		 */
17602 		iocp = (struct iocblk *)mp->b_rptr;
17603 		tcp = connp->conn_tcp;
17604 
17605 		switch (iocp->ioc_cmd) {
17606 		case TCP_IOC_ABORT_CONN:
17607 			tcp_ioctl_abort_conn(q, mp);
17608 			return;
17609 		case TI_GETPEERNAME:
17610 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
17611 				iocp->ioc_error = ENOTCONN;
17612 				iocp->ioc_count = 0;
17613 				mp->b_datap->db_type = M_IOCACK;
17614 				qreply(q, mp);
17615 				return;
17616 			}
17617 			/* FALLTHRU */
17618 		case TI_GETMYNAME:
17619 			mi_copyin(q, mp, NULL,
17620 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
17621 			return;
17622 		case ND_SET:
17623 			/* nd_getset does the necessary checks */
17624 		case ND_GET:
17625 			if (!nd_getset(q, tcp_g_nd, mp)) {
17626 				CALL_IP_WPUT(connp, q, mp);
17627 				return;
17628 			}
17629 			qreply(q, mp);
17630 			return;
17631 		case TCP_IOC_DEFAULT_Q:
17632 			/*
17633 			 * Wants to be the default wq. Check the credentials
17634 			 * first, the rest is executed via squeue.
17635 			 */
17636 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
17637 				iocp->ioc_error = EPERM;
17638 				iocp->ioc_count = 0;
17639 				mp->b_datap->db_type = M_IOCACK;
17640 				qreply(q, mp);
17641 				return;
17642 			}
17643 			output_proc = tcp_wput_ioctl;
17644 			break;
17645 		default:
17646 			output_proc = tcp_wput_ioctl;
17647 			break;
17648 		}
17649 		break;
17650 	default:
17651 		output_proc = tcp_wput_nondata;
17652 		break;
17653 	}
17654 
17655 	CONN_INC_REF(connp);
17656 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17657 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
17658 }
17659 
17660 /*
17661  * Initial STREAMS write side put() procedure for sockets. It tries to
17662  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
17663  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
17664  * are handled by tcp_wput() as usual.
17665  *
17666  * All further messages will also be handled by tcp_wput() because we cannot
17667  * be sure that the above short cut is safe later.
17668  */
17669 static void
17670 tcp_wput_sock(queue_t *wq, mblk_t *mp)
17671 {
17672 	conn_t			*connp = Q_TO_CONN(wq);
17673 	tcp_t			*tcp = connp->conn_tcp;
17674 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
17675 
17676 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
17677 	wq->q_qinfo = &tcp_winit;
17678 
17679 	ASSERT(IPCL_IS_TCP(connp));
17680 	ASSERT(TCP_IS_SOCKET(tcp));
17681 
17682 	if (DB_TYPE(mp) == M_PCPROTO &&
17683 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
17684 	    car->PRIM_type == T_CAPABILITY_REQ) {
17685 		tcp_capability_req(tcp, mp);
17686 		return;
17687 	}
17688 
17689 	tcp_wput(wq, mp);
17690 }
17691 
17692 static boolean_t
17693 tcp_zcopy_check(tcp_t *tcp)
17694 {
17695 	conn_t	*connp = tcp->tcp_connp;
17696 	ire_t	*ire;
17697 	boolean_t	zc_enabled = B_FALSE;
17698 
17699 	if (do_tcpzcopy == 2)
17700 		zc_enabled = B_TRUE;
17701 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
17702 	    IPCL_IS_CONNECTED(connp) &&
17703 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
17704 	    connp->conn_dontroute == 0 &&
17705 	    connp->conn_xmit_if_ill == NULL &&
17706 	    connp->conn_nofailover_ill == NULL &&
17707 	    do_tcpzcopy == 1) {
17708 		/*
17709 		 * the checks above  closely resemble the fast path checks
17710 		 * in tcp_send_data().
17711 		 */
17712 		mutex_enter(&connp->conn_lock);
17713 		ire = connp->conn_ire_cache;
17714 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
17715 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17716 			IRE_REFHOLD(ire);
17717 			if (ire->ire_stq != NULL) {
17718 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
17719 
17720 				zc_enabled = ill && (ill->ill_capabilities &
17721 				    ILL_CAPAB_ZEROCOPY) &&
17722 				    (ill->ill_zerocopy_capab->
17723 				    ill_zerocopy_flags != 0);
17724 			}
17725 			IRE_REFRELE(ire);
17726 		}
17727 		mutex_exit(&connp->conn_lock);
17728 	}
17729 	tcp->tcp_snd_zcopy_on = zc_enabled;
17730 	if (!TCP_IS_DETACHED(tcp)) {
17731 		if (zc_enabled) {
17732 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
17733 			TCP_STAT(tcp_zcopy_on);
17734 		} else {
17735 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
17736 			TCP_STAT(tcp_zcopy_off);
17737 		}
17738 	}
17739 	return (zc_enabled);
17740 }
17741 
17742 static mblk_t *
17743 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
17744 {
17745 	if (do_tcpzcopy == 2)
17746 		return (bp);
17747 	else if (tcp->tcp_snd_zcopy_on) {
17748 		tcp->tcp_snd_zcopy_on = B_FALSE;
17749 		if (!TCP_IS_DETACHED(tcp)) {
17750 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
17751 			TCP_STAT(tcp_zcopy_disable);
17752 		}
17753 	}
17754 	return (tcp_zcopy_backoff(tcp, bp, 0));
17755 }
17756 
17757 /*
17758  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
17759  * the original desballoca'ed segmapped mblk.
17760  */
17761 static mblk_t *
17762 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
17763 {
17764 	mblk_t *head, *tail, *nbp;
17765 	if (IS_VMLOANED_MBLK(bp)) {
17766 		TCP_STAT(tcp_zcopy_backoff);
17767 		if ((head = copyb(bp)) == NULL) {
17768 			/* fail to backoff; leave it for the next backoff */
17769 			tcp->tcp_xmit_zc_clean = B_FALSE;
17770 			return (bp);
17771 		}
17772 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
17773 			if (fix_xmitlist)
17774 				tcp_zcopy_notify(tcp);
17775 			else
17776 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
17777 		}
17778 		nbp = bp->b_cont;
17779 		if (fix_xmitlist) {
17780 			head->b_prev = bp->b_prev;
17781 			head->b_next = bp->b_next;
17782 			if (tcp->tcp_xmit_tail == bp)
17783 				tcp->tcp_xmit_tail = head;
17784 		}
17785 		bp->b_next = NULL;
17786 		bp->b_prev = NULL;
17787 		freeb(bp);
17788 	} else {
17789 		head = bp;
17790 		nbp = bp->b_cont;
17791 	}
17792 	tail = head;
17793 	while (nbp) {
17794 		if (IS_VMLOANED_MBLK(nbp)) {
17795 			TCP_STAT(tcp_zcopy_backoff);
17796 			if ((tail->b_cont = copyb(nbp)) == NULL) {
17797 				tcp->tcp_xmit_zc_clean = B_FALSE;
17798 				tail->b_cont = nbp;
17799 				return (head);
17800 			}
17801 			tail = tail->b_cont;
17802 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
17803 				if (fix_xmitlist)
17804 					tcp_zcopy_notify(tcp);
17805 				else
17806 					tail->b_datap->db_struioflag |=
17807 					    STRUIO_ZCNOTIFY;
17808 			}
17809 			bp = nbp;
17810 			nbp = nbp->b_cont;
17811 			if (fix_xmitlist) {
17812 				tail->b_prev = bp->b_prev;
17813 				tail->b_next = bp->b_next;
17814 				if (tcp->tcp_xmit_tail == bp)
17815 					tcp->tcp_xmit_tail = tail;
17816 			}
17817 			bp->b_next = NULL;
17818 			bp->b_prev = NULL;
17819 			freeb(bp);
17820 		} else {
17821 			tail->b_cont = nbp;
17822 			tail = nbp;
17823 			nbp = nbp->b_cont;
17824 		}
17825 	}
17826 	if (fix_xmitlist) {
17827 		tcp->tcp_xmit_last = tail;
17828 		tcp->tcp_xmit_zc_clean = B_TRUE;
17829 	}
17830 	return (head);
17831 }
17832 
17833 static void
17834 tcp_zcopy_notify(tcp_t *tcp)
17835 {
17836 	struct stdata	*stp;
17837 
17838 	if (tcp->tcp_detached)
17839 		return;
17840 	stp = STREAM(tcp->tcp_rq);
17841 	mutex_enter(&stp->sd_lock);
17842 	stp->sd_flag |= STZCNOTIFY;
17843 	cv_broadcast(&stp->sd_zcopy_wait);
17844 	mutex_exit(&stp->sd_lock);
17845 }
17846 
17847 static void
17848 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
17849 {
17850 	ipha_t		*ipha;
17851 	ipaddr_t	src;
17852 	ipaddr_t	dst;
17853 	uint32_t	cksum;
17854 	ire_t		*ire;
17855 	uint16_t	*up;
17856 	ill_t		*ill;
17857 	conn_t		*connp = tcp->tcp_connp;
17858 	uint32_t	hcksum_txflags = 0;
17859 	mblk_t		*ire_fp_mp;
17860 	uint_t		ire_fp_mp_len;
17861 
17862 	ASSERT(DB_TYPE(mp) == M_DATA);
17863 
17864 	ipha = (ipha_t *)mp->b_rptr;
17865 	src = ipha->ipha_src;
17866 	dst = ipha->ipha_dst;
17867 
17868 	/*
17869 	 * Drop off slow path for IPv6 and also if options are present.
17870 	 */
17871 	if (tcp->tcp_ipversion != IPV4_VERSION ||
17872 	    !IPCL_IS_CONNECTED(connp) ||
17873 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
17874 	    connp->conn_dontroute ||
17875 	    connp->conn_xmit_if_ill != NULL ||
17876 	    connp->conn_nofailover_ill != NULL ||
17877 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
17878 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
17879 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
17880 		if (tcp->tcp_snd_zcopy_aware)
17881 			mp = tcp_zcopy_disable(tcp, mp);
17882 		TCP_STAT(tcp_ip_send);
17883 		CALL_IP_WPUT(connp, q, mp);
17884 		return;
17885 	}
17886 
17887 	mutex_enter(&connp->conn_lock);
17888 	ire = connp->conn_ire_cache;
17889 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
17890 	if (ire != NULL && ire->ire_addr == dst &&
17891 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17892 		IRE_REFHOLD(ire);
17893 		mutex_exit(&connp->conn_lock);
17894 	} else {
17895 		boolean_t cached = B_FALSE;
17896 
17897 		/* force a recheck later on */
17898 		tcp->tcp_ire_ill_check_done = B_FALSE;
17899 
17900 		TCP_DBGSTAT(tcp_ire_null1);
17901 		connp->conn_ire_cache = NULL;
17902 		mutex_exit(&connp->conn_lock);
17903 		if (ire != NULL)
17904 			IRE_REFRELE_NOTR(ire);
17905 		ire = ire_cache_lookup(dst, connp->conn_zoneid);
17906 		if (ire == NULL) {
17907 			if (tcp->tcp_snd_zcopy_aware)
17908 				mp = tcp_zcopy_backoff(tcp, mp, 0);
17909 			TCP_STAT(tcp_ire_null);
17910 			CALL_IP_WPUT(connp, q, mp);
17911 			return;
17912 		}
17913 		IRE_REFHOLD_NOTR(ire);
17914 		/*
17915 		 * Since we are inside the squeue, there cannot be another
17916 		 * thread in TCP trying to set the conn_ire_cache now.  The
17917 		 * check for IRE_MARK_CONDEMNED ensures that an interface
17918 		 * unplumb thread has not yet started cleaning up the conns.
17919 		 * Hence we don't need to grab the conn lock.
17920 		 */
17921 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
17922 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
17923 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17924 				connp->conn_ire_cache = ire;
17925 				cached = B_TRUE;
17926 			}
17927 			rw_exit(&ire->ire_bucket->irb_lock);
17928 		}
17929 
17930 		/*
17931 		 * We can continue to use the ire but since it was
17932 		 * not cached, we should drop the extra reference.
17933 		 */
17934 		if (!cached)
17935 			IRE_REFRELE_NOTR(ire);
17936 	}
17937 
17938 	if (ire->ire_flags & RTF_MULTIRT ||
17939 	    ire->ire_stq == NULL ||
17940 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
17941 	    (ire_fp_mp = ire->ire_fp_mp) == NULL ||
17942 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
17943 		if (tcp->tcp_snd_zcopy_aware)
17944 			mp = tcp_zcopy_disable(tcp, mp);
17945 		TCP_STAT(tcp_ip_ire_send);
17946 		IRE_REFRELE(ire);
17947 		CALL_IP_WPUT(connp, q, mp);
17948 		return;
17949 	}
17950 
17951 	ill = ire_to_ill(ire);
17952 	if (connp->conn_outgoing_ill != NULL) {
17953 		ill_t *conn_outgoing_ill = NULL;
17954 		/*
17955 		 * Choose a good ill in the group to send the packets on.
17956 		 */
17957 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
17958 		ill = ire_to_ill(ire);
17959 	}
17960 	ASSERT(ill != NULL);
17961 
17962 	if (!tcp->tcp_ire_ill_check_done) {
17963 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
17964 		tcp->tcp_ire_ill_check_done = B_TRUE;
17965 	}
17966 
17967 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
17968 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
17969 #ifndef _BIG_ENDIAN
17970 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
17971 #endif
17972 
17973 	/*
17974 	 * Check to see if we need to re-enable MDT for this connection
17975 	 * because it was previously disabled due to changes in the ill;
17976 	 * note that by doing it here, this re-enabling only applies when
17977 	 * the packet is not dispatched through CALL_IP_WPUT().
17978 	 *
17979 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
17980 	 * case, since that's how we ended up here.  For IPv6, we do the
17981 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
17982 	 */
17983 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
17984 		/*
17985 		 * Restore MDT for this connection, so that next time around
17986 		 * it is eligible to go through tcp_multisend() path again.
17987 		 */
17988 		TCP_STAT(tcp_mdt_conn_resumed1);
17989 		tcp->tcp_mdt = B_TRUE;
17990 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
17991 		    "interface %s\n", (void *)connp, ill->ill_name));
17992 	}
17993 
17994 	if (tcp->tcp_snd_zcopy_aware) {
17995 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
17996 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
17997 			mp = tcp_zcopy_disable(tcp, mp);
17998 		/*
17999 		 * we shouldn't need to reset ipha as the mp containing
18000 		 * ipha should never be a zero-copy mp.
18001 		 */
18002 	}
18003 
18004 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18005 		ASSERT(ill->ill_hcksum_capab != NULL);
18006 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18007 	}
18008 
18009 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18010 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18011 
18012 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18013 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18014 
18015 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18016 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18017 
18018 	/* Software checksum? */
18019 	if (DB_CKSUMFLAGS(mp) == 0) {
18020 		TCP_STAT(tcp_out_sw_cksum);
18021 		TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
18022 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18023 	}
18024 
18025 	ipha->ipha_fragment_offset_and_flags |=
18026 	    (uint32_t)htons(ire->ire_frag_flag);
18027 
18028 	/* Calculate IP header checksum if hardware isn't capable */
18029 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18030 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18031 		    ((uint16_t *)ipha)[4]);
18032 	}
18033 
18034 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18035 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18036 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18037 
18038 	UPDATE_OB_PKT_COUNT(ire);
18039 	ire->ire_last_used_time = lbolt;
18040 	BUMP_MIB(&ip_mib, ipOutRequests);
18041 
18042 	if (ILL_POLL_CAPABLE(ill)) {
18043 		/*
18044 		 * Send the packet directly to DLD, where it may be queued
18045 		 * depending on the availability of transmit resources at
18046 		 * the media layer.
18047 		 */
18048 		IP_POLL_ILL_TX(ill, mp);
18049 	} else {
18050 		putnext(ire->ire_stq, mp);
18051 	}
18052 	IRE_REFRELE(ire);
18053 }
18054 
18055 /*
18056  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18057  * if the receiver shrinks the window, i.e. moves the right window to the
18058  * left, the we should not send new data, but should retransmit normally the
18059  * old unacked data between suna and suna + swnd. We might has sent data
18060  * that is now outside the new window, pretend that we didn't send  it.
18061  */
18062 static void
18063 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18064 {
18065 	uint32_t	snxt = tcp->tcp_snxt;
18066 	mblk_t		*xmit_tail;
18067 	int32_t		offset;
18068 
18069 	ASSERT(shrunk_count > 0);
18070 
18071 	/* Pretend we didn't send the data outside the window */
18072 	snxt -= shrunk_count;
18073 
18074 	/* Get the mblk and the offset in it per the shrunk window */
18075 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18076 
18077 	ASSERT(xmit_tail != NULL);
18078 
18079 	/* Reset all the values per the now shrunk window */
18080 	tcp->tcp_snxt = snxt;
18081 	tcp->tcp_xmit_tail = xmit_tail;
18082 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18083 	    offset;
18084 	tcp->tcp_unsent += shrunk_count;
18085 
18086 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18087 		/*
18088 		 * Make sure the timer is running so that we will probe a zero
18089 		 * window.
18090 		 */
18091 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18092 }
18093 
18094 
18095 /*
18096  * The TCP normal data output path.
18097  * NOTE: the logic of the fast path is duplicated from this function.
18098  */
18099 static void
18100 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18101 {
18102 	int		len;
18103 	mblk_t		*local_time;
18104 	mblk_t		*mp1;
18105 	uint32_t	snxt;
18106 	int		tail_unsent;
18107 	int		tcpstate;
18108 	int		usable = 0;
18109 	mblk_t		*xmit_tail;
18110 	queue_t		*q = tcp->tcp_wq;
18111 	int32_t		mss;
18112 	int32_t		num_sack_blk = 0;
18113 	int32_t		tcp_hdr_len;
18114 	int32_t		tcp_tcp_hdr_len;
18115 	int		mdt_thres;
18116 	int		rc;
18117 
18118 	tcpstate = tcp->tcp_state;
18119 	if (mp == NULL) {
18120 		/*
18121 		 * tcp_wput_data() with NULL mp should only be called when
18122 		 * there is unsent data.
18123 		 */
18124 		ASSERT(tcp->tcp_unsent > 0);
18125 		/* Really tacky... but we need this for detached closes. */
18126 		len = tcp->tcp_unsent;
18127 		goto data_null;
18128 	}
18129 
18130 #if CCS_STATS
18131 	wrw_stats.tot.count++;
18132 	wrw_stats.tot.bytes += msgdsize(mp);
18133 #endif
18134 	ASSERT(mp->b_datap->db_type == M_DATA);
18135 	/*
18136 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18137 	 * or before a connection attempt has begun.
18138 	 */
18139 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18140 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18141 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18142 #ifdef DEBUG
18143 			cmn_err(CE_WARN,
18144 			    "tcp_wput_data: data after ordrel, %s",
18145 			    tcp_display(tcp, NULL,
18146 			    DISP_ADDR_AND_PORT));
18147 #else
18148 			if (tcp->tcp_debug) {
18149 				(void) strlog(TCP_MOD_ID, 0, 1,
18150 				    SL_TRACE|SL_ERROR,
18151 				    "tcp_wput_data: data after ordrel, %s\n",
18152 				    tcp_display(tcp, NULL,
18153 				    DISP_ADDR_AND_PORT));
18154 			}
18155 #endif /* DEBUG */
18156 		}
18157 		if (tcp->tcp_snd_zcopy_aware &&
18158 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18159 			tcp_zcopy_notify(tcp);
18160 		freemsg(mp);
18161 		if (tcp->tcp_flow_stopped &&
18162 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18163 			tcp_clrqfull(tcp);
18164 		}
18165 		return;
18166 	}
18167 
18168 	/* Strip empties */
18169 	for (;;) {
18170 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18171 		    (uintptr_t)INT_MAX);
18172 		len = (int)(mp->b_wptr - mp->b_rptr);
18173 		if (len > 0)
18174 			break;
18175 		mp1 = mp;
18176 		mp = mp->b_cont;
18177 		freeb(mp1);
18178 		if (!mp) {
18179 			return;
18180 		}
18181 	}
18182 
18183 	/* If we are the first on the list ... */
18184 	if (tcp->tcp_xmit_head == NULL) {
18185 		tcp->tcp_xmit_head = mp;
18186 		tcp->tcp_xmit_tail = mp;
18187 		tcp->tcp_xmit_tail_unsent = len;
18188 	} else {
18189 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18190 		struct datab *dp;
18191 
18192 		mp1 = tcp->tcp_xmit_last;
18193 		if (len < tcp_tx_pull_len &&
18194 		    (dp = mp1->b_datap)->db_ref == 1 &&
18195 		    dp->db_lim - mp1->b_wptr >= len) {
18196 			ASSERT(len > 0);
18197 			ASSERT(!mp1->b_cont);
18198 			if (len == 1) {
18199 				*mp1->b_wptr++ = *mp->b_rptr;
18200 			} else {
18201 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18202 				mp1->b_wptr += len;
18203 			}
18204 			if (mp1 == tcp->tcp_xmit_tail)
18205 				tcp->tcp_xmit_tail_unsent += len;
18206 			mp1->b_cont = mp->b_cont;
18207 			if (tcp->tcp_snd_zcopy_aware &&
18208 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18209 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18210 			freeb(mp);
18211 			mp = mp1;
18212 		} else {
18213 			tcp->tcp_xmit_last->b_cont = mp;
18214 		}
18215 		len += tcp->tcp_unsent;
18216 	}
18217 
18218 	/* Tack on however many more positive length mblks we have */
18219 	if ((mp1 = mp->b_cont) != NULL) {
18220 		do {
18221 			int tlen;
18222 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18223 			    (uintptr_t)INT_MAX);
18224 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18225 			if (tlen <= 0) {
18226 				mp->b_cont = mp1->b_cont;
18227 				freeb(mp1);
18228 			} else {
18229 				len += tlen;
18230 				mp = mp1;
18231 			}
18232 		} while ((mp1 = mp->b_cont) != NULL);
18233 	}
18234 	tcp->tcp_xmit_last = mp;
18235 	tcp->tcp_unsent = len;
18236 
18237 	if (urgent)
18238 		usable = 1;
18239 
18240 data_null:
18241 	snxt = tcp->tcp_snxt;
18242 	xmit_tail = tcp->tcp_xmit_tail;
18243 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18244 
18245 	/*
18246 	 * Note that tcp_mss has been adjusted to take into account the
18247 	 * timestamp option if applicable.  Because SACK options do not
18248 	 * appear in every TCP segments and they are of variable lengths,
18249 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18250 	 * the actual segment length when we need to send a segment which
18251 	 * includes SACK options.
18252 	 */
18253 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18254 		int32_t	opt_len;
18255 
18256 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18257 		    tcp->tcp_num_sack_blk);
18258 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18259 		    2 + TCPOPT_HEADER_LEN;
18260 		mss = tcp->tcp_mss - opt_len;
18261 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18262 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18263 	} else {
18264 		mss = tcp->tcp_mss;
18265 		tcp_hdr_len = tcp->tcp_hdr_len;
18266 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18267 	}
18268 
18269 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18270 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18271 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
18272 	}
18273 	if (tcpstate == TCPS_SYN_RCVD) {
18274 		/*
18275 		 * The three-way connection establishment handshake is not
18276 		 * complete yet. We want to queue the data for transmission
18277 		 * after entering ESTABLISHED state (RFC793). A jump to
18278 		 * "done" label effectively leaves data on the queue.
18279 		 */
18280 		goto done;
18281 	} else {
18282 		int usable_r = tcp->tcp_swnd;
18283 
18284 		/*
18285 		 * In the special case when cwnd is zero, which can only
18286 		 * happen if the connection is ECN capable, return now.
18287 		 * New segments is sent using tcp_timer().  The timer
18288 		 * is set in tcp_rput_data().
18289 		 */
18290 		if (tcp->tcp_cwnd == 0) {
18291 			/*
18292 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18293 			 * finished.
18294 			 */
18295 			ASSERT(tcp->tcp_ecn_ok ||
18296 			    tcp->tcp_state < TCPS_ESTABLISHED);
18297 			return;
18298 		}
18299 
18300 		/* NOTE: trouble if xmitting while SYN not acked? */
18301 		usable_r -= snxt;
18302 		usable_r += tcp->tcp_suna;
18303 
18304 		/*
18305 		 * Check if the receiver has shrunk the window.  If
18306 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18307 		 * cannot be set as there is unsent data, so FIN cannot
18308 		 * be sent out.  Otherwise, we need to take into account
18309 		 * of FIN as it consumes an "invisible" sequence number.
18310 		 */
18311 		ASSERT(tcp->tcp_fin_sent == 0);
18312 		if (usable_r < 0) {
18313 			/*
18314 			 * The receiver has shrunk the window and we have sent
18315 			 * -usable_r date beyond the window, re-adjust.
18316 			 *
18317 			 * If TCP window scaling is enabled, there can be
18318 			 * round down error as the advertised receive window
18319 			 * is actually right shifted n bits.  This means that
18320 			 * the lower n bits info is wiped out.  It will look
18321 			 * like the window is shrunk.  Do a check here to
18322 			 * see if the shrunk amount is actually within the
18323 			 * error in window calculation.  If it is, just
18324 			 * return.  Note that this check is inside the
18325 			 * shrunk window check.  This makes sure that even
18326 			 * though tcp_process_shrunk_swnd() is not called,
18327 			 * we will stop further processing.
18328 			 */
18329 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18330 				tcp_process_shrunk_swnd(tcp, -usable_r);
18331 			}
18332 			return;
18333 		}
18334 
18335 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18336 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18337 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18338 
18339 		/* usable = MIN(usable, unsent) */
18340 		if (usable_r > len)
18341 			usable_r = len;
18342 
18343 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18344 		if (usable_r > 0) {
18345 			usable = usable_r;
18346 		} else {
18347 			/* Bypass all other unnecessary processing. */
18348 			goto done;
18349 		}
18350 	}
18351 
18352 	local_time = (mblk_t *)lbolt;
18353 
18354 	/*
18355 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18356 	 * BSD.  This is more in line with the true intent of Nagle.
18357 	 *
18358 	 * The conditions are:
18359 	 * 1. The amount of unsent data (or amount of data which can be
18360 	 *    sent, whichever is smaller) is less than Nagle limit.
18361 	 * 2. The last sent size is also less than Nagle limit.
18362 	 * 3. There is unack'ed data.
18363 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18364 	 *    Nagle algorithm.  This reduces the probability that urgent
18365 	 *    bytes get "merged" together.
18366 	 * 5. The app has not closed the connection.  This eliminates the
18367 	 *    wait time of the receiving side waiting for the last piece of
18368 	 *    (small) data.
18369 	 *
18370 	 * If all are satisified, exit without sending anything.  Note
18371 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18372 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18373 	 * 4095).
18374 	 */
18375 	if (usable < (int)tcp->tcp_naglim &&
18376 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18377 	    snxt != tcp->tcp_suna &&
18378 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18379 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18380 		goto done;
18381 	}
18382 
18383 	if (tcp->tcp_cork) {
18384 		/*
18385 		 * if the tcp->tcp_cork option is set, then we have to force
18386 		 * TCP not to send partial segment (smaller than MSS bytes).
18387 		 * We are calculating the usable now based on full mss and
18388 		 * will save the rest of remaining data for later.
18389 		 */
18390 		if (usable < mss)
18391 			goto done;
18392 		usable = (usable / mss) * mss;
18393 	}
18394 
18395 	/* Update the latest receive window size in TCP header. */
18396 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18397 	    tcp->tcp_tcph->th_win);
18398 
18399 	/*
18400 	 * Determine if it's worthwhile to attempt MDT, based on:
18401 	 *
18402 	 * 1. Simple TCP/IP{v4,v6} (no options).
18403 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18404 	 * 3. If the TCP connection is in ESTABLISHED state.
18405 	 * 4. The TCP is not detached.
18406 	 *
18407 	 * If any of the above conditions have changed during the
18408 	 * connection, stop using MDT and restore the stream head
18409 	 * parameters accordingly.
18410 	 */
18411 	if (tcp->tcp_mdt &&
18412 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
18413 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
18414 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18415 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
18416 	    tcp->tcp_state != TCPS_ESTABLISHED ||
18417 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
18418 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
18419 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
18420 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
18421 		tcp->tcp_mdt = B_FALSE;
18422 
18423 		/* Anything other than detached is considered pathological */
18424 		if (!TCP_IS_DETACHED(tcp)) {
18425 			TCP_STAT(tcp_mdt_conn_halted1);
18426 			(void) tcp_maxpsz_set(tcp, B_TRUE);
18427 		}
18428 	}
18429 
18430 	/* Use MDT if sendable amount is greater than the threshold */
18431 	if (tcp->tcp_mdt &&
18432 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
18433 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
18434 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
18435 	    (tcp->tcp_valid_bits == 0 ||
18436 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
18437 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
18438 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18439 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18440 		    local_time, mdt_thres);
18441 	} else {
18442 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18443 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18444 		    local_time, INT_MAX);
18445 	}
18446 
18447 	/* Pretend that all we were trying to send really got sent */
18448 	if (rc < 0 && tail_unsent < 0) {
18449 		do {
18450 			xmit_tail = xmit_tail->b_cont;
18451 			xmit_tail->b_prev = local_time;
18452 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
18453 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
18454 			tail_unsent += (int)(xmit_tail->b_wptr -
18455 			    xmit_tail->b_rptr);
18456 		} while (tail_unsent < 0);
18457 	}
18458 done:;
18459 	tcp->tcp_xmit_tail = xmit_tail;
18460 	tcp->tcp_xmit_tail_unsent = tail_unsent;
18461 	len = tcp->tcp_snxt - snxt;
18462 	if (len) {
18463 		/*
18464 		 * If new data was sent, need to update the notsack
18465 		 * list, which is, afterall, data blocks that have
18466 		 * not been sack'ed by the receiver.  New data is
18467 		 * not sack'ed.
18468 		 */
18469 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
18470 			/* len is a negative value. */
18471 			tcp->tcp_pipe -= len;
18472 			tcp_notsack_update(&(tcp->tcp_notsack_list),
18473 			    tcp->tcp_snxt, snxt,
18474 			    &(tcp->tcp_num_notsack_blk),
18475 			    &(tcp->tcp_cnt_notsack_list));
18476 		}
18477 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
18478 		tcp->tcp_rack = tcp->tcp_rnxt;
18479 		tcp->tcp_rack_cnt = 0;
18480 		if ((snxt + len) == tcp->tcp_suna) {
18481 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18482 		}
18483 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
18484 		/*
18485 		 * Didn't send anything. Make sure the timer is running
18486 		 * so that we will probe a zero window.
18487 		 */
18488 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18489 	}
18490 	/* Note that len is the amount we just sent but with a negative sign */
18491 	tcp->tcp_unsent += len;
18492 	if (tcp->tcp_flow_stopped) {
18493 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18494 			tcp_clrqfull(tcp);
18495 		}
18496 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
18497 		tcp_setqfull(tcp);
18498 	}
18499 }
18500 
18501 /*
18502  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
18503  * outgoing TCP header with the template header, as well as other
18504  * options such as time-stamp, ECN and/or SACK.
18505  */
18506 static void
18507 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
18508 {
18509 	tcph_t *tcp_tmpl, *tcp_h;
18510 	uint32_t *dst, *src;
18511 	int hdrlen;
18512 
18513 	ASSERT(OK_32PTR(rptr));
18514 
18515 	/* Template header */
18516 	tcp_tmpl = tcp->tcp_tcph;
18517 
18518 	/* Header of outgoing packet */
18519 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18520 
18521 	/* dst and src are opaque 32-bit fields, used for copying */
18522 	dst = (uint32_t *)rptr;
18523 	src = (uint32_t *)tcp->tcp_iphc;
18524 	hdrlen = tcp->tcp_hdr_len;
18525 
18526 	/* Fill time-stamp option if needed */
18527 	if (tcp->tcp_snd_ts_ok) {
18528 		U32_TO_BE32((uint32_t)now,
18529 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
18530 		U32_TO_BE32(tcp->tcp_ts_recent,
18531 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
18532 	} else {
18533 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18534 	}
18535 
18536 	/*
18537 	 * Copy the template header; is this really more efficient than
18538 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
18539 	 * but perhaps not for other scenarios.
18540 	 */
18541 	dst[0] = src[0];
18542 	dst[1] = src[1];
18543 	dst[2] = src[2];
18544 	dst[3] = src[3];
18545 	dst[4] = src[4];
18546 	dst[5] = src[5];
18547 	dst[6] = src[6];
18548 	dst[7] = src[7];
18549 	dst[8] = src[8];
18550 	dst[9] = src[9];
18551 	if (hdrlen -= 40) {
18552 		hdrlen >>= 2;
18553 		dst += 10;
18554 		src += 10;
18555 		do {
18556 			*dst++ = *src++;
18557 		} while (--hdrlen);
18558 	}
18559 
18560 	/*
18561 	 * Set the ECN info in the TCP header if it is not a zero
18562 	 * window probe.  Zero window probe is only sent in
18563 	 * tcp_wput_data() and tcp_timer().
18564 	 */
18565 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
18566 		SET_ECT(tcp, rptr);
18567 
18568 		if (tcp->tcp_ecn_echo_on)
18569 			tcp_h->th_flags[0] |= TH_ECE;
18570 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18571 			tcp_h->th_flags[0] |= TH_CWR;
18572 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18573 		}
18574 	}
18575 
18576 	/* Fill in SACK options */
18577 	if (num_sack_blk > 0) {
18578 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
18579 		sack_blk_t *tmp;
18580 		int32_t	i;
18581 
18582 		wptr[0] = TCPOPT_NOP;
18583 		wptr[1] = TCPOPT_NOP;
18584 		wptr[2] = TCPOPT_SACK;
18585 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18586 		    sizeof (sack_blk_t);
18587 		wptr += TCPOPT_REAL_SACK_LEN;
18588 
18589 		tmp = tcp->tcp_sack_list;
18590 		for (i = 0; i < num_sack_blk; i++) {
18591 			U32_TO_BE32(tmp[i].begin, wptr);
18592 			wptr += sizeof (tcp_seq);
18593 			U32_TO_BE32(tmp[i].end, wptr);
18594 			wptr += sizeof (tcp_seq);
18595 		}
18596 		tcp_h->th_offset_and_rsrvd[0] +=
18597 		    ((num_sack_blk * 2 + 1) << 4);
18598 	}
18599 }
18600 
18601 /*
18602  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
18603  * the destination address and SAP attribute, and if necessary, the
18604  * hardware checksum offload attribute to a Multidata message.
18605  */
18606 static int
18607 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
18608     const uint32_t start, const uint32_t stuff, const uint32_t end,
18609     const uint32_t flags)
18610 {
18611 	/* Add global destination address & SAP attribute */
18612 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
18613 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
18614 		    "destination address+SAP\n"));
18615 
18616 		if (dlmp != NULL)
18617 			TCP_STAT(tcp_mdt_allocfail);
18618 		return (-1);
18619 	}
18620 
18621 	/* Add global hwcksum attribute */
18622 	if (hwcksum &&
18623 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
18624 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
18625 		    "checksum attribute\n"));
18626 
18627 		TCP_STAT(tcp_mdt_allocfail);
18628 		return (-1);
18629 	}
18630 
18631 	return (0);
18632 }
18633 
18634 /*
18635  * Smaller and private version of pdescinfo_t used specifically for TCP,
18636  * which allows for only two payload spans per packet.
18637  */
18638 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
18639 
18640 /*
18641  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
18642  * scheme, and returns one the following:
18643  *
18644  * -1 = failed allocation.
18645  *  0 = success; burst count reached, or usable send window is too small,
18646  *      and that we'd rather wait until later before sending again.
18647  */
18648 static int
18649 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
18650     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
18651     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
18652     const int mdt_thres)
18653 {
18654 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
18655 	multidata_t	*mmd;
18656 	uint_t		obsegs, obbytes, hdr_frag_sz;
18657 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
18658 	int		num_burst_seg, max_pld;
18659 	pdesc_t		*pkt;
18660 	tcp_pdescinfo_t	tcp_pkt_info;
18661 	pdescinfo_t	*pkt_info;
18662 	int		pbuf_idx, pbuf_idx_nxt;
18663 	int		seg_len, len, spill, af;
18664 	boolean_t	add_buffer, zcopy, clusterwide;
18665 	boolean_t	rconfirm = B_FALSE;
18666 	boolean_t	done = B_FALSE;
18667 	uint32_t	cksum;
18668 	uint32_t	hwcksum_flags;
18669 	ire_t		*ire;
18670 	ill_t		*ill;
18671 	ipha_t		*ipha;
18672 	ip6_t		*ip6h;
18673 	ipaddr_t	src, dst;
18674 	ill_zerocopy_capab_t *zc_cap = NULL;
18675 	uint16_t	*up;
18676 	int		err;
18677 
18678 #ifdef	_BIG_ENDIAN
18679 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
18680 #else
18681 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
18682 #endif
18683 
18684 #define	PREP_NEW_MULTIDATA() {			\
18685 	mmd = NULL;				\
18686 	md_mp = md_hbuf = NULL;			\
18687 	cur_hdr_off = 0;			\
18688 	max_pld = tcp->tcp_mdt_max_pld;		\
18689 	pbuf_idx = pbuf_idx_nxt = -1;		\
18690 	add_buffer = B_TRUE;			\
18691 	zcopy = B_FALSE;			\
18692 }
18693 
18694 #define	PREP_NEW_PBUF() {			\
18695 	md_pbuf = md_pbuf_nxt = NULL;		\
18696 	pbuf_idx = pbuf_idx_nxt = -1;		\
18697 	cur_pld_off = 0;			\
18698 	first_snxt = *snxt;			\
18699 	ASSERT(*tail_unsent > 0);		\
18700 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
18701 }
18702 
18703 	ASSERT(mdt_thres >= mss);
18704 	ASSERT(*usable > 0 && *usable > mdt_thres);
18705 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
18706 	ASSERT(!TCP_IS_DETACHED(tcp));
18707 	ASSERT(tcp->tcp_valid_bits == 0 ||
18708 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
18709 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
18710 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
18711 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18712 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
18713 	ASSERT(tcp->tcp_connp != NULL);
18714 	ASSERT(CONN_IS_MD_FASTPATH(tcp->tcp_connp));
18715 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp));
18716 
18717 	/*
18718 	 * Note that tcp will only declare at most 2 payload spans per
18719 	 * packet, which is much lower than the maximum allowable number
18720 	 * of packet spans per Multidata.  For this reason, we use the
18721 	 * privately declared and smaller descriptor info structure, in
18722 	 * order to save some stack space.
18723 	 */
18724 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
18725 
18726 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
18727 	if (af == AF_INET) {
18728 		dst = tcp->tcp_ipha->ipha_dst;
18729 		src = tcp->tcp_ipha->ipha_src;
18730 		ASSERT(!CLASSD(dst));
18731 	}
18732 	ASSERT(af == AF_INET ||
18733 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
18734 
18735 	obsegs = obbytes = 0;
18736 	num_burst_seg = tcp->tcp_snd_burst;
18737 	md_mp_head = NULL;
18738 	PREP_NEW_MULTIDATA();
18739 
18740 	/*
18741 	 * Before we go on further, make sure there is an IRE that we can
18742 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
18743 	 * in proceeding any further, and we should just hand everything
18744 	 * off to the legacy path.
18745 	 */
18746 	mutex_enter(&tcp->tcp_connp->conn_lock);
18747 	ire = tcp->tcp_connp->conn_ire_cache;
18748 	ASSERT(!(tcp->tcp_connp->conn_state_flags & CONN_INCIPIENT));
18749 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
18750 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
18751 	    &tcp->tcp_ip6h->ip6_dst))) &&
18752 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18753 		IRE_REFHOLD(ire);
18754 		mutex_exit(&tcp->tcp_connp->conn_lock);
18755 	} else {
18756 		boolean_t cached = B_FALSE;
18757 
18758 		/* force a recheck later on */
18759 		tcp->tcp_ire_ill_check_done = B_FALSE;
18760 
18761 		TCP_DBGSTAT(tcp_ire_null1);
18762 		tcp->tcp_connp->conn_ire_cache = NULL;
18763 		mutex_exit(&tcp->tcp_connp->conn_lock);
18764 
18765 		/* Release the old ire */
18766 		if (ire != NULL)
18767 			IRE_REFRELE_NOTR(ire);
18768 
18769 		ire = (af == AF_INET) ?
18770 		    ire_cache_lookup(dst, tcp->tcp_connp->conn_zoneid) :
18771 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18772 		    tcp->tcp_connp->conn_zoneid);
18773 
18774 		if (ire == NULL) {
18775 			TCP_STAT(tcp_ire_null);
18776 			goto legacy_send_no_md;
18777 		}
18778 
18779 		IRE_REFHOLD_NOTR(ire);
18780 		/*
18781 		 * Since we are inside the squeue, there cannot be another
18782 		 * thread in TCP trying to set the conn_ire_cache now. The
18783 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18784 		 * unplumb thread has not yet started cleaning up the conns.
18785 		 * Hence we don't need to grab the conn lock.
18786 		 */
18787 		if (!(tcp->tcp_connp->conn_state_flags & CONN_CLOSING)) {
18788 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18789 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18790 				tcp->tcp_connp->conn_ire_cache = ire;
18791 				cached = B_TRUE;
18792 			}
18793 			rw_exit(&ire->ire_bucket->irb_lock);
18794 		}
18795 
18796 		/*
18797 		 * We can continue to use the ire but since it was not
18798 		 * cached, we should drop the extra reference.
18799 		 */
18800 		if (!cached)
18801 			IRE_REFRELE_NOTR(ire);
18802 	}
18803 
18804 	ASSERT(ire != NULL);
18805 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
18806 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
18807 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
18808 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18809 	/*
18810 	 * If we do support loopback for MDT (which requires modifications
18811 	 * to the receiving paths), the following assertions should go away,
18812 	 * and we would be sending the Multidata to loopback conn later on.
18813 	 */
18814 	ASSERT(!IRE_IS_LOCAL(ire));
18815 	ASSERT(ire->ire_stq != NULL);
18816 
18817 	ill = ire_to_ill(ire);
18818 	ASSERT(ill != NULL);
18819 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
18820 
18821 	if (!tcp->tcp_ire_ill_check_done) {
18822 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18823 		tcp->tcp_ire_ill_check_done = B_TRUE;
18824 	}
18825 
18826 	/*
18827 	 * If the underlying interface conditions have changed, or if the
18828 	 * new interface does not support MDT, go back to legacy path.
18829 	 */
18830 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
18831 		/* don't go through this path anymore for this connection */
18832 		TCP_STAT(tcp_mdt_conn_halted2);
18833 		tcp->tcp_mdt = B_FALSE;
18834 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
18835 		    "interface %s\n", (void *)tcp->tcp_connp, ill->ill_name));
18836 		/* IRE will be released prior to returning */
18837 		goto legacy_send_no_md;
18838 	}
18839 
18840 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
18841 		zc_cap = ill->ill_zerocopy_capab;
18842 
18843 	/* go to legacy path if interface doesn't support zerocopy */
18844 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
18845 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
18846 		/* IRE will be released prior to returning */
18847 		goto legacy_send_no_md;
18848 	}
18849 
18850 	/* does the interface support hardware checksum offload? */
18851 	hwcksum_flags = 0;
18852 	if (ILL_HCKSUM_CAPABLE(ill) &&
18853 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
18854 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
18855 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
18856 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18857 		    HCKSUM_IPHDRCKSUM)
18858 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
18859 
18860 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18861 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
18862 			hwcksum_flags |= HCK_FULLCKSUM;
18863 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18864 		    HCKSUM_INET_PARTIAL)
18865 			hwcksum_flags |= HCK_PARTIALCKSUM;
18866 	}
18867 
18868 	/*
18869 	 * Each header fragment consists of the leading extra space,
18870 	 * followed by the TCP/IP header, and the trailing extra space.
18871 	 * We make sure that each header fragment begins on a 32-bit
18872 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
18873 	 * aligned in tcp_mdt_update).
18874 	 */
18875 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
18876 	    tcp->tcp_mdt_hdr_tail), 4);
18877 
18878 	/* are we starting from the beginning of data block? */
18879 	if (*tail_unsent == 0) {
18880 		*xmit_tail = (*xmit_tail)->b_cont;
18881 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
18882 		*tail_unsent = (int)MBLKL(*xmit_tail);
18883 	}
18884 
18885 	/*
18886 	 * Here we create one or more Multidata messages, each made up of
18887 	 * one header buffer and up to N payload buffers.  This entire
18888 	 * operation is done within two loops:
18889 	 *
18890 	 * The outer loop mostly deals with creating the Multidata message,
18891 	 * as well as the header buffer that gets added to it.  It also
18892 	 * links the Multidata messages together such that all of them can
18893 	 * be sent down to the lower layer in a single putnext call; this
18894 	 * linking behavior depends on the tcp_mdt_chain tunable.
18895 	 *
18896 	 * The inner loop takes an existing Multidata message, and adds
18897 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
18898 	 * packetizes those buffers by filling up the corresponding header
18899 	 * buffer fragments with the proper IP and TCP headers, and by
18900 	 * describing the layout of each packet in the packet descriptors
18901 	 * that get added to the Multidata.
18902 	 */
18903 	do {
18904 		/*
18905 		 * If usable send window is too small, or data blocks in
18906 		 * transmit list are smaller than our threshold (i.e. app
18907 		 * performs large writes followed by small ones), we hand
18908 		 * off the control over to the legacy path.  Note that we'll
18909 		 * get back the control once it encounters a large block.
18910 		 */
18911 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
18912 		    (*xmit_tail)->b_cont != NULL &&
18913 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
18914 			/* send down what we've got so far */
18915 			if (md_mp_head != NULL) {
18916 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
18917 				    obsegs, obbytes, &rconfirm);
18918 			}
18919 			/*
18920 			 * Pass control over to tcp_send(), but tell it to
18921 			 * return to us once a large-size transmission is
18922 			 * possible.
18923 			 */
18924 			TCP_STAT(tcp_mdt_legacy_small);
18925 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
18926 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
18927 			    tail_unsent, xmit_tail, local_time,
18928 			    mdt_thres)) <= 0) {
18929 				/* burst count reached, or alloc failed */
18930 				IRE_REFRELE(ire);
18931 				return (err);
18932 			}
18933 
18934 			/* tcp_send() may have sent everything, so check */
18935 			if (*usable <= 0) {
18936 				IRE_REFRELE(ire);
18937 				return (0);
18938 			}
18939 
18940 			TCP_STAT(tcp_mdt_legacy_ret);
18941 			/*
18942 			 * We may have delivered the Multidata, so make sure
18943 			 * to re-initialize before the next round.
18944 			 */
18945 			md_mp_head = NULL;
18946 			obsegs = obbytes = 0;
18947 			num_burst_seg = tcp->tcp_snd_burst;
18948 			PREP_NEW_MULTIDATA();
18949 
18950 			/* are we starting from the beginning of data block? */
18951 			if (*tail_unsent == 0) {
18952 				*xmit_tail = (*xmit_tail)->b_cont;
18953 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
18954 				    (uintptr_t)INT_MAX);
18955 				*tail_unsent = (int)MBLKL(*xmit_tail);
18956 			}
18957 		}
18958 
18959 		/*
18960 		 * max_pld limits the number of mblks in tcp's transmit
18961 		 * queue that can be added to a Multidata message.  Once
18962 		 * this counter reaches zero, no more additional mblks
18963 		 * can be added to it.  What happens afterwards depends
18964 		 * on whether or not we are set to chain the Multidata
18965 		 * messages.  If we are to link them together, reset
18966 		 * max_pld to its original value (tcp_mdt_max_pld) and
18967 		 * prepare to create a new Multidata message which will
18968 		 * get linked to md_mp_head.  Else, leave it alone and
18969 		 * let the inner loop break on its own.
18970 		 */
18971 		if (tcp_mdt_chain && max_pld == 0)
18972 			PREP_NEW_MULTIDATA();
18973 
18974 		/* adding a payload buffer; re-initialize values */
18975 		if (add_buffer)
18976 			PREP_NEW_PBUF();
18977 
18978 		/*
18979 		 * If we don't have a Multidata, either because we just
18980 		 * (re)entered this outer loop, or after we branched off
18981 		 * to tcp_send above, setup the Multidata and header
18982 		 * buffer to be used.
18983 		 */
18984 		if (md_mp == NULL) {
18985 			int md_hbuflen;
18986 			uint32_t start, stuff;
18987 
18988 			/*
18989 			 * Calculate Multidata header buffer size large enough
18990 			 * to hold all of the headers that can possibly be
18991 			 * sent at this moment.  We'd rather over-estimate
18992 			 * the size than running out of space; this is okay
18993 			 * since this buffer is small anyway.
18994 			 */
18995 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
18996 
18997 			/*
18998 			 * Start and stuff offset for partial hardware
18999 			 * checksum offload; these are currently for IPv4.
19000 			 * For full checksum offload, they are set to zero.
19001 			 */
19002 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19003 				if (af == AF_INET) {
19004 					start = IP_SIMPLE_HDR_LENGTH;
19005 					stuff = IP_SIMPLE_HDR_LENGTH +
19006 					    TCP_CHECKSUM_OFFSET;
19007 				} else {
19008 					start = IPV6_HDR_LEN;
19009 					stuff = IPV6_HDR_LEN +
19010 					    TCP_CHECKSUM_OFFSET;
19011 				}
19012 			} else {
19013 				start = stuff = 0;
19014 			}
19015 
19016 			/*
19017 			 * Create the header buffer, Multidata, as well as
19018 			 * any necessary attributes (destination address,
19019 			 * SAP and hardware checksum offload) that should
19020 			 * be associated with the Multidata message.
19021 			 */
19022 			ASSERT(cur_hdr_off == 0);
19023 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19024 			    ((md_hbuf->b_wptr += md_hbuflen),
19025 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19026 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19027 			    /* fastpath mblk */
19028 			    (af == AF_INET) ? ire->ire_dlureq_mp :
19029 			    ire->ire_nce->nce_res_mp,
19030 			    /* hardware checksum enabled */
19031 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19032 			    /* hardware checksum offsets */
19033 			    start, stuff, 0,
19034 			    /* hardware checksum flag */
19035 			    hwcksum_flags) != 0)) {
19036 legacy_send:
19037 				if (md_mp != NULL) {
19038 					/* Unlink message from the chain */
19039 					if (md_mp_head != NULL) {
19040 						err = (intptr_t)rmvb(md_mp_head,
19041 						    md_mp);
19042 						/*
19043 						 * We can't assert that rmvb
19044 						 * did not return -1, since we
19045 						 * may get here before linkb
19046 						 * happens.  We do, however,
19047 						 * check if we just removed the
19048 						 * only element in the list.
19049 						 */
19050 						if (err == 0)
19051 							md_mp_head = NULL;
19052 					}
19053 					/* md_hbuf gets freed automatically */
19054 					TCP_STAT(tcp_mdt_discarded);
19055 					freeb(md_mp);
19056 				} else {
19057 					/* Either allocb or mmd_alloc failed */
19058 					TCP_STAT(tcp_mdt_allocfail);
19059 					if (md_hbuf != NULL)
19060 						freeb(md_hbuf);
19061 				}
19062 
19063 				/* send down what we've got so far */
19064 				if (md_mp_head != NULL) {
19065 					tcp_multisend_data(tcp, ire, ill,
19066 					    md_mp_head, obsegs, obbytes,
19067 					    &rconfirm);
19068 				}
19069 legacy_send_no_md:
19070 				if (ire != NULL)
19071 					IRE_REFRELE(ire);
19072 				/*
19073 				 * Too bad; let the legacy path handle this.
19074 				 * We specify INT_MAX for the threshold, since
19075 				 * we gave up with the Multidata processings
19076 				 * and let the old path have it all.
19077 				 */
19078 				TCP_STAT(tcp_mdt_legacy_all);
19079 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19080 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19081 				    snxt, tail_unsent, xmit_tail, local_time,
19082 				    INT_MAX));
19083 			}
19084 
19085 			/* link to any existing ones, if applicable */
19086 			TCP_STAT(tcp_mdt_allocd);
19087 			if (md_mp_head == NULL) {
19088 				md_mp_head = md_mp;
19089 			} else if (tcp_mdt_chain) {
19090 				TCP_STAT(tcp_mdt_linked);
19091 				linkb(md_mp_head, md_mp);
19092 			}
19093 		}
19094 
19095 		ASSERT(md_mp_head != NULL);
19096 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19097 		ASSERT(md_mp != NULL && mmd != NULL);
19098 		ASSERT(md_hbuf != NULL);
19099 
19100 		/*
19101 		 * Packetize the transmittable portion of the data block;
19102 		 * each data block is essentially added to the Multidata
19103 		 * as a payload buffer.  We also deal with adding more
19104 		 * than one payload buffers, which happens when the remaining
19105 		 * packetized portion of the current payload buffer is less
19106 		 * than MSS, while the next data block in transmit queue
19107 		 * has enough data to make up for one.  This "spillover"
19108 		 * case essentially creates a split-packet, where portions
19109 		 * of the packet's payload fragments may span across two
19110 		 * virtually discontiguous address blocks.
19111 		 */
19112 		seg_len = mss;
19113 		do {
19114 			len = seg_len;
19115 
19116 			ASSERT(len > 0);
19117 			ASSERT(max_pld >= 0);
19118 			ASSERT(!add_buffer || cur_pld_off == 0);
19119 
19120 			/*
19121 			 * First time around for this payload buffer; note
19122 			 * in the case of a spillover, the following has
19123 			 * been done prior to adding the split-packet
19124 			 * descriptor to Multidata, and we don't want to
19125 			 * repeat the process.
19126 			 */
19127 			if (add_buffer) {
19128 				ASSERT(mmd != NULL);
19129 				ASSERT(md_pbuf == NULL);
19130 				ASSERT(md_pbuf_nxt == NULL);
19131 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19132 
19133 				/*
19134 				 * Have we reached the limit?  We'd get to
19135 				 * this case when we're not chaining the
19136 				 * Multidata messages together, and since
19137 				 * we're done, terminate this loop.
19138 				 */
19139 				if (max_pld == 0)
19140 					break; /* done */
19141 
19142 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19143 					TCP_STAT(tcp_mdt_allocfail);
19144 					goto legacy_send; /* out_of_mem */
19145 				}
19146 
19147 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19148 				    zc_cap != NULL) {
19149 					if (!ip_md_zcopy_attr(mmd, NULL,
19150 					    zc_cap->ill_zerocopy_flags)) {
19151 						freeb(md_pbuf);
19152 						TCP_STAT(tcp_mdt_allocfail);
19153 						/* out_of_mem */
19154 						goto legacy_send;
19155 					}
19156 					zcopy = B_TRUE;
19157 				}
19158 
19159 				md_pbuf->b_rptr += base_pld_off;
19160 
19161 				/*
19162 				 * Add a payload buffer to the Multidata; this
19163 				 * operation must not fail, or otherwise our
19164 				 * logic in this routine is broken.  There
19165 				 * is no memory allocation done by the
19166 				 * routine, so any returned failure simply
19167 				 * tells us that we've done something wrong.
19168 				 *
19169 				 * A failure tells us that either we're adding
19170 				 * the same payload buffer more than once, or
19171 				 * we're trying to add more buffers than
19172 				 * allowed (max_pld calculation is wrong).
19173 				 * None of the above cases should happen, and
19174 				 * we panic because either there's horrible
19175 				 * heap corruption, and/or programming mistake.
19176 				 */
19177 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19178 				if (pbuf_idx < 0) {
19179 					cmn_err(CE_PANIC, "tcp_multisend: "
19180 					    "payload buffer logic error "
19181 					    "detected for tcp %p mmd %p "
19182 					    "pbuf %p (%d)\n",
19183 					    (void *)tcp, (void *)mmd,
19184 					    (void *)md_pbuf, pbuf_idx);
19185 				}
19186 
19187 				ASSERT(max_pld > 0);
19188 				--max_pld;
19189 				add_buffer = B_FALSE;
19190 			}
19191 
19192 			ASSERT(md_mp_head != NULL);
19193 			ASSERT(md_pbuf != NULL);
19194 			ASSERT(md_pbuf_nxt == NULL);
19195 			ASSERT(pbuf_idx != -1);
19196 			ASSERT(pbuf_idx_nxt == -1);
19197 			ASSERT(*usable > 0);
19198 
19199 			/*
19200 			 * We spillover to the next payload buffer only
19201 			 * if all of the following is true:
19202 			 *
19203 			 *   1. There is not enough data on the current
19204 			 *	payload buffer to make up `len',
19205 			 *   2. We are allowed to send `len',
19206 			 *   3. The next payload buffer length is large
19207 			 *	enough to accomodate `spill'.
19208 			 */
19209 			if ((spill = len - *tail_unsent) > 0 &&
19210 			    *usable >= len &&
19211 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19212 			    max_pld > 0) {
19213 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19214 				if (md_pbuf_nxt == NULL) {
19215 					TCP_STAT(tcp_mdt_allocfail);
19216 					goto legacy_send; /* out_of_mem */
19217 				}
19218 
19219 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19220 				    zc_cap != NULL) {
19221 					if (!ip_md_zcopy_attr(mmd, NULL,
19222 					    zc_cap->ill_zerocopy_flags)) {
19223 						freeb(md_pbuf_nxt);
19224 						TCP_STAT(tcp_mdt_allocfail);
19225 						/* out_of_mem */
19226 						goto legacy_send;
19227 					}
19228 					zcopy = B_TRUE;
19229 				}
19230 
19231 				/*
19232 				 * See comments above on the first call to
19233 				 * mmd_addpldbuf for explanation on the panic.
19234 				 */
19235 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19236 				if (pbuf_idx_nxt < 0) {
19237 					panic("tcp_multisend: "
19238 					    "next payload buffer logic error "
19239 					    "detected for tcp %p mmd %p "
19240 					    "pbuf %p (%d)\n",
19241 					    (void *)tcp, (void *)mmd,
19242 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19243 				}
19244 
19245 				ASSERT(max_pld > 0);
19246 				--max_pld;
19247 			} else if (spill > 0) {
19248 				/*
19249 				 * If there's a spillover, but the following
19250 				 * xmit_tail couldn't give us enough octets
19251 				 * to reach "len", then stop the current
19252 				 * Multidata creation and let the legacy
19253 				 * tcp_send() path take over.  We don't want
19254 				 * to send the tiny segment as part of this
19255 				 * Multidata for performance reasons; instead,
19256 				 * we let the legacy path deal with grouping
19257 				 * it with the subsequent small mblks.
19258 				 */
19259 				if (*usable >= len &&
19260 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19261 					max_pld = 0;
19262 					break;	/* done */
19263 				}
19264 
19265 				/*
19266 				 * We can't spillover, and we are near
19267 				 * the end of the current payload buffer,
19268 				 * so send what's left.
19269 				 */
19270 				ASSERT(*tail_unsent > 0);
19271 				len = *tail_unsent;
19272 			}
19273 
19274 			/* tail_unsent is negated if there is a spillover */
19275 			*tail_unsent -= len;
19276 			*usable -= len;
19277 			ASSERT(*usable >= 0);
19278 
19279 			if (*usable < mss)
19280 				seg_len = *usable;
19281 			/*
19282 			 * Sender SWS avoidance; see comments in tcp_send();
19283 			 * everything else is the same, except that we only
19284 			 * do this here if there is no more data to be sent
19285 			 * following the current xmit_tail.  We don't check
19286 			 * for 1-byte urgent data because we shouldn't get
19287 			 * here if TCP_URG_VALID is set.
19288 			 */
19289 			if (*usable > 0 && *usable < mss &&
19290 			    ((md_pbuf_nxt == NULL &&
19291 			    (*xmit_tail)->b_cont == NULL) ||
19292 			    (md_pbuf_nxt != NULL &&
19293 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19294 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19295 			    (tcp->tcp_unsent -
19296 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19297 			    !tcp->tcp_zero_win_probe) {
19298 				if ((*snxt + len) == tcp->tcp_snxt &&
19299 				    (*snxt + len) == tcp->tcp_suna) {
19300 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19301 				}
19302 				done = B_TRUE;
19303 			}
19304 
19305 			/*
19306 			 * Prime pump for IP's checksumming on our behalf;
19307 			 * include the adjustment for a source route if any.
19308 			 * Do this only for software/partial hardware checksum
19309 			 * offload, as this field gets zeroed out later for
19310 			 * the full hardware checksum offload case.
19311 			 */
19312 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19313 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19314 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19315 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19316 			}
19317 
19318 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19319 			*snxt += len;
19320 
19321 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19322 			/*
19323 			 * We set the PUSH bit only if TCP has no more buffered
19324 			 * data to be transmitted (or if sender SWS avoidance
19325 			 * takes place), as opposed to setting it for every
19326 			 * last packet in the burst.
19327 			 */
19328 			if (done ||
19329 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19330 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19331 
19332 			/*
19333 			 * Set FIN bit if this is our last segment; snxt
19334 			 * already includes its length, and it will not
19335 			 * be adjusted after this point.
19336 			 */
19337 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19338 			    *snxt == tcp->tcp_fss) {
19339 				if (!tcp->tcp_fin_acked) {
19340 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19341 					BUMP_MIB(&tcp_mib, tcpOutControl);
19342 				}
19343 				if (!tcp->tcp_fin_sent) {
19344 					tcp->tcp_fin_sent = B_TRUE;
19345 					/*
19346 					 * tcp state must be ESTABLISHED
19347 					 * in order for us to get here in
19348 					 * the first place.
19349 					 */
19350 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19351 
19352 					/*
19353 					 * Upon returning from this routine,
19354 					 * tcp_wput_data() will set tcp_snxt
19355 					 * to be equal to snxt + tcp_fin_sent.
19356 					 * This is essentially the same as
19357 					 * setting it to tcp_fss + 1.
19358 					 */
19359 				}
19360 			}
19361 
19362 			tcp->tcp_last_sent_len = (ushort_t)len;
19363 
19364 			len += tcp_hdr_len;
19365 			if (tcp->tcp_ipversion == IPV4_VERSION)
19366 				tcp->tcp_ipha->ipha_length = htons(len);
19367 			else
19368 				tcp->tcp_ip6h->ip6_plen = htons(len -
19369 				    ((char *)&tcp->tcp_ip6h[1] -
19370 				    tcp->tcp_iphc));
19371 
19372 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19373 
19374 			/* setup header fragment */
19375 			PDESC_HDR_ADD(pkt_info,
19376 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19377 			    tcp->tcp_mdt_hdr_head,		/* head room */
19378 			    tcp_hdr_len,			/* len */
19379 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19380 
19381 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
19382 			    hdr_frag_sz);
19383 			ASSERT(MBLKIN(md_hbuf,
19384 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
19385 			    PDESC_HDRSIZE(pkt_info)));
19386 
19387 			/* setup first payload fragment */
19388 			PDESC_PLD_INIT(pkt_info);
19389 			PDESC_PLD_SPAN_ADD(pkt_info,
19390 			    pbuf_idx,				/* index */
19391 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
19392 			    tcp->tcp_last_sent_len);		/* len */
19393 
19394 			/* create a split-packet in case of a spillover */
19395 			if (md_pbuf_nxt != NULL) {
19396 				ASSERT(spill > 0);
19397 				ASSERT(pbuf_idx_nxt > pbuf_idx);
19398 				ASSERT(!add_buffer);
19399 
19400 				md_pbuf = md_pbuf_nxt;
19401 				md_pbuf_nxt = NULL;
19402 				pbuf_idx = pbuf_idx_nxt;
19403 				pbuf_idx_nxt = -1;
19404 				cur_pld_off = spill;
19405 
19406 				/* trim out first payload fragment */
19407 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
19408 
19409 				/* setup second payload fragment */
19410 				PDESC_PLD_SPAN_ADD(pkt_info,
19411 				    pbuf_idx,			/* index */
19412 				    md_pbuf->b_rptr,		/* start */
19413 				    spill);			/* len */
19414 
19415 				if ((*xmit_tail)->b_next == NULL) {
19416 					/*
19417 					 * Store the lbolt used for RTT
19418 					 * estimation. We can only record one
19419 					 * timestamp per mblk so we do it when
19420 					 * we reach the end of the payload
19421 					 * buffer.  Also we only take a new
19422 					 * timestamp sample when the previous
19423 					 * timed data from the same mblk has
19424 					 * been ack'ed.
19425 					 */
19426 					(*xmit_tail)->b_prev = local_time;
19427 					(*xmit_tail)->b_next =
19428 					    (mblk_t *)(uintptr_t)first_snxt;
19429 				}
19430 
19431 				first_snxt = *snxt - spill;
19432 
19433 				/*
19434 				 * Advance xmit_tail; usable could be 0 by
19435 				 * the time we got here, but we made sure
19436 				 * above that we would only spillover to
19437 				 * the next data block if usable includes
19438 				 * the spilled-over amount prior to the
19439 				 * subtraction.  Therefore, we are sure
19440 				 * that xmit_tail->b_cont can't be NULL.
19441 				 */
19442 				ASSERT((*xmit_tail)->b_cont != NULL);
19443 				*xmit_tail = (*xmit_tail)->b_cont;
19444 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19445 				    (uintptr_t)INT_MAX);
19446 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
19447 			} else {
19448 				cur_pld_off += tcp->tcp_last_sent_len;
19449 			}
19450 
19451 			/*
19452 			 * Fill in the header using the template header, and
19453 			 * add options such as time-stamp, ECN and/or SACK,
19454 			 * as needed.
19455 			 */
19456 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
19457 			    (clock_t)local_time, num_sack_blk);
19458 
19459 			/* take care of some IP header businesses */
19460 			if (af == AF_INET) {
19461 				ipha = (ipha_t *)pkt_info->hdr_rptr;
19462 
19463 				ASSERT(OK_32PTR((uchar_t *)ipha));
19464 				ASSERT(PDESC_HDRL(pkt_info) >=
19465 				    IP_SIMPLE_HDR_LENGTH);
19466 				ASSERT(ipha->ipha_version_and_hdr_length ==
19467 				    IP_SIMPLE_HDR_VERSION);
19468 
19469 				/*
19470 				 * Assign ident value for current packet; see
19471 				 * related comments in ip_wput_ire() about the
19472 				 * contract private interface with clustering
19473 				 * group.
19474 				 */
19475 				clusterwide = B_FALSE;
19476 				if (cl_inet_ipident != NULL) {
19477 					ASSERT(cl_inet_isclusterwide != NULL);
19478 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19479 					    AF_INET,
19480 					    (uint8_t *)(uintptr_t)src)) {
19481 						ipha->ipha_ident =
19482 						    (*cl_inet_ipident)
19483 						    (IPPROTO_IP, AF_INET,
19484 						    (uint8_t *)(uintptr_t)src,
19485 						    (uint8_t *)(uintptr_t)dst);
19486 						clusterwide = B_TRUE;
19487 					}
19488 				}
19489 
19490 				if (!clusterwide) {
19491 					ipha->ipha_ident = (uint16_t)
19492 					    atomic_add_32_nv(
19493 						&ire->ire_ident, 1);
19494 				}
19495 #ifndef _BIG_ENDIAN
19496 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
19497 				    (ipha->ipha_ident >> 8);
19498 #endif
19499 			} else {
19500 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
19501 
19502 				ASSERT(OK_32PTR((uchar_t *)ip6h));
19503 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
19504 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
19505 				ASSERT(PDESC_HDRL(pkt_info) >=
19506 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
19507 				    TCP_CHECKSUM_SIZE));
19508 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
19509 
19510 				if (tcp->tcp_ip_forward_progress) {
19511 					rconfirm = B_TRUE;
19512 					tcp->tcp_ip_forward_progress = B_FALSE;
19513 				}
19514 			}
19515 
19516 			/* at least one payload span, and at most two */
19517 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
19518 
19519 			/* add the packet descriptor to Multidata */
19520 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
19521 			    KM_NOSLEEP)) == NULL) {
19522 				/*
19523 				 * Any failure other than ENOMEM indicates
19524 				 * that we have passed in invalid pkt_info
19525 				 * or parameters to mmd_addpdesc, which must
19526 				 * not happen.
19527 				 *
19528 				 * EINVAL is a result of failure on boundary
19529 				 * checks against the pkt_info contents.  It
19530 				 * should not happen, and we panic because
19531 				 * either there's horrible heap corruption,
19532 				 * and/or programming mistake.
19533 				 */
19534 				if (err != ENOMEM) {
19535 					cmn_err(CE_PANIC, "tcp_multisend: "
19536 					    "pdesc logic error detected for "
19537 					    "tcp %p mmd %p pinfo %p (%d)\n",
19538 					    (void *)tcp, (void *)mmd,
19539 					    (void *)pkt_info, err);
19540 				}
19541 				TCP_STAT(tcp_mdt_addpdescfail);
19542 				goto legacy_send; /* out_of_mem */
19543 			}
19544 			ASSERT(pkt != NULL);
19545 
19546 			/* calculate IP header and TCP checksums */
19547 			if (af == AF_INET) {
19548 				/* calculate pseudo-header checksum */
19549 				cksum = (dst >> 16) + (dst & 0xFFFF) +
19550 				    (src >> 16) + (src & 0xFFFF);
19551 
19552 				/* offset for TCP header checksum */
19553 				up = IPH_TCPH_CHECKSUMP(ipha,
19554 				    IP_SIMPLE_HDR_LENGTH);
19555 			} else {
19556 				up = (uint16_t *)&ip6h->ip6_src;
19557 
19558 				/* calculate pseudo-header checksum */
19559 				cksum = up[0] + up[1] + up[2] + up[3] +
19560 				    up[4] + up[5] + up[6] + up[7] +
19561 				    up[8] + up[9] + up[10] + up[11] +
19562 				    up[12] + up[13] + up[14] + up[15];
19563 
19564 				/* Fold the initial sum */
19565 				cksum = (cksum & 0xffff) + (cksum >> 16);
19566 
19567 				up = (uint16_t *)(((uchar_t *)ip6h) +
19568 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
19569 			}
19570 
19571 			if (hwcksum_flags & HCK_FULLCKSUM) {
19572 				/* clear checksum field for hardware */
19573 				*up = 0;
19574 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
19575 				uint32_t sum;
19576 
19577 				/* pseudo-header checksumming */
19578 				sum = *up + cksum + IP_TCP_CSUM_COMP;
19579 				sum = (sum & 0xFFFF) + (sum >> 16);
19580 				*up = (sum & 0xFFFF) + (sum >> 16);
19581 			} else {
19582 				/* software checksumming */
19583 				TCP_STAT(tcp_out_sw_cksum);
19584 				TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
19585 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
19586 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
19587 				    cksum + IP_TCP_CSUM_COMP);
19588 				if (*up == 0)
19589 					*up = 0xFFFF;
19590 			}
19591 
19592 			/* IPv4 header checksum */
19593 			if (af == AF_INET) {
19594 				ipha->ipha_fragment_offset_and_flags |=
19595 				    (uint32_t)htons(ire->ire_frag_flag);
19596 
19597 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
19598 					ipha->ipha_hdr_checksum = 0;
19599 				} else {
19600 					IP_HDR_CKSUM(ipha, cksum,
19601 					    ((uint32_t *)ipha)[0],
19602 					    ((uint16_t *)ipha)[4]);
19603 				}
19604 			}
19605 
19606 			/* advance header offset */
19607 			cur_hdr_off += hdr_frag_sz;
19608 
19609 			obbytes += tcp->tcp_last_sent_len;
19610 			++obsegs;
19611 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
19612 		    *tail_unsent > 0);
19613 
19614 		if ((*xmit_tail)->b_next == NULL) {
19615 			/*
19616 			 * Store the lbolt used for RTT estimation. We can only
19617 			 * record one timestamp per mblk so we do it when we
19618 			 * reach the end of the payload buffer. Also we only
19619 			 * take a new timestamp sample when the previous timed
19620 			 * data from the same mblk has been ack'ed.
19621 			 */
19622 			(*xmit_tail)->b_prev = local_time;
19623 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
19624 		}
19625 
19626 		ASSERT(*tail_unsent >= 0);
19627 		if (*tail_unsent > 0) {
19628 			/*
19629 			 * We got here because we broke out of the above
19630 			 * loop due to of one of the following cases:
19631 			 *
19632 			 *   1. len < adjusted MSS (i.e. small),
19633 			 *   2. Sender SWS avoidance,
19634 			 *   3. max_pld is zero.
19635 			 *
19636 			 * We are done for this Multidata, so trim our
19637 			 * last payload buffer (if any) accordingly.
19638 			 */
19639 			if (md_pbuf != NULL)
19640 				md_pbuf->b_wptr -= *tail_unsent;
19641 		} else if (*usable > 0) {
19642 			*xmit_tail = (*xmit_tail)->b_cont;
19643 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19644 			    (uintptr_t)INT_MAX);
19645 			*tail_unsent = (int)MBLKL(*xmit_tail);
19646 			add_buffer = B_TRUE;
19647 		}
19648 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
19649 	    (tcp_mdt_chain || max_pld > 0));
19650 
19651 	/* send everything down */
19652 	tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
19653 	    &rconfirm);
19654 
19655 #undef PREP_NEW_MULTIDATA
19656 #undef PREP_NEW_PBUF
19657 #undef IPVER
19658 
19659 	IRE_REFRELE(ire);
19660 	return (0);
19661 }
19662 
19663 /*
19664  * A wrapper function for sending one or more Multidata messages down to
19665  * the module below ip; this routine does not release the reference of the
19666  * IRE (caller does that).  This routine is analogous to tcp_send_data().
19667  */
19668 static void
19669 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
19670     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
19671 {
19672 	uint64_t delta;
19673 	nce_t *nce;
19674 
19675 	ASSERT(ire != NULL && ill != NULL);
19676 	ASSERT(ire->ire_stq != NULL);
19677 	ASSERT(md_mp_head != NULL);
19678 	ASSERT(rconfirm != NULL);
19679 
19680 	/* adjust MIBs and IRE timestamp */
19681 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
19682 	tcp->tcp_obsegs += obsegs;
19683 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
19684 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
19685 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
19686 
19687 	if (tcp->tcp_ipversion == IPV4_VERSION) {
19688 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
19689 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
19690 	} else {
19691 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
19692 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
19693 	}
19694 
19695 	ire->ire_ob_pkt_count += obsegs;
19696 	if (ire->ire_ipif != NULL)
19697 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
19698 	ire->ire_last_used_time = lbolt;
19699 
19700 	/* send it down */
19701 	putnext(ire->ire_stq, md_mp_head);
19702 
19703 	/* we're done for TCP/IPv4 */
19704 	if (tcp->tcp_ipversion == IPV4_VERSION)
19705 		return;
19706 
19707 	nce = ire->ire_nce;
19708 
19709 	ASSERT(nce != NULL);
19710 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
19711 	ASSERT(nce->nce_state != ND_INCOMPLETE);
19712 
19713 	/* reachability confirmation? */
19714 	if (*rconfirm) {
19715 		nce->nce_last = TICK_TO_MSEC(lbolt64);
19716 		if (nce->nce_state != ND_REACHABLE) {
19717 			mutex_enter(&nce->nce_lock);
19718 			nce->nce_state = ND_REACHABLE;
19719 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
19720 			mutex_exit(&nce->nce_lock);
19721 			(void) untimeout(nce->nce_timeout_id);
19722 			if (ip_debug > 2) {
19723 				/* ip1dbg */
19724 				pr_addr_dbg("tcp_multisend_data: state "
19725 				    "for %s changed to REACHABLE\n",
19726 				    AF_INET6, &ire->ire_addr_v6);
19727 			}
19728 		}
19729 		/* reset transport reachability confirmation */
19730 		*rconfirm = B_FALSE;
19731 	}
19732 
19733 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
19734 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
19735 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
19736 
19737 	if (delta > (uint64_t)ill->ill_reachable_time) {
19738 		mutex_enter(&nce->nce_lock);
19739 		switch (nce->nce_state) {
19740 		case ND_REACHABLE:
19741 		case ND_STALE:
19742 			/*
19743 			 * ND_REACHABLE is identical to ND_STALE in this
19744 			 * specific case. If reachable time has expired for
19745 			 * this neighbor (delta is greater than reachable
19746 			 * time), conceptually, the neighbor cache is no
19747 			 * longer in REACHABLE state, but already in STALE
19748 			 * state.  So the correct transition here is to
19749 			 * ND_DELAY.
19750 			 */
19751 			nce->nce_state = ND_DELAY;
19752 			mutex_exit(&nce->nce_lock);
19753 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
19754 			if (ip_debug > 3) {
19755 				/* ip2dbg */
19756 				pr_addr_dbg("tcp_multisend_data: state "
19757 				    "for %s changed to DELAY\n",
19758 				    AF_INET6, &ire->ire_addr_v6);
19759 			}
19760 			break;
19761 		case ND_DELAY:
19762 		case ND_PROBE:
19763 			mutex_exit(&nce->nce_lock);
19764 			/* Timers have already started */
19765 			break;
19766 		case ND_UNREACHABLE:
19767 			/*
19768 			 * ndp timer has detected that this nce is
19769 			 * unreachable and initiated deleting this nce
19770 			 * and all its associated IREs. This is a race
19771 			 * where we found the ire before it was deleted
19772 			 * and have just sent out a packet using this
19773 			 * unreachable nce.
19774 			 */
19775 			mutex_exit(&nce->nce_lock);
19776 			break;
19777 		default:
19778 			ASSERT(0);
19779 		}
19780 	}
19781 }
19782 
19783 /*
19784  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
19785  * scheme, and returns one of the following:
19786  *
19787  * -1 = failed allocation.
19788  *  0 = success; burst count reached, or usable send window is too small,
19789  *      and that we'd rather wait until later before sending again.
19790  *  1 = success; we are called from tcp_multisend(), and both usable send
19791  *      window and tail_unsent are greater than the MDT threshold, and thus
19792  *      Multidata Transmit should be used instead.
19793  */
19794 static int
19795 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19796     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19797     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19798     const int mdt_thres)
19799 {
19800 	int num_burst_seg = tcp->tcp_snd_burst;
19801 
19802 	for (;;) {
19803 		struct datab	*db;
19804 		tcph_t		*tcph;
19805 		uint32_t	sum;
19806 		mblk_t		*mp, *mp1;
19807 		uchar_t		*rptr;
19808 		int		len;
19809 
19810 		/*
19811 		 * If we're called by tcp_multisend(), and the amount of
19812 		 * sendable data as well as the size of current xmit_tail
19813 		 * is beyond the MDT threshold, return to the caller and
19814 		 * let the large data transmit be done using MDT.
19815 		 */
19816 		if (*usable > 0 && *usable > mdt_thres &&
19817 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
19818 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
19819 			ASSERT(tcp->tcp_mdt);
19820 			return (1);	/* success; do large send */
19821 		}
19822 
19823 		if (num_burst_seg-- == 0)
19824 			break;		/* success; burst count reached */
19825 
19826 		len = mss;
19827 		if (len > *usable) {
19828 			len = *usable;
19829 			if (len <= 0) {
19830 				/* Terminate the loop */
19831 				break;	/* success; too small */
19832 			}
19833 			/*
19834 			 * Sender silly-window avoidance.
19835 			 * Ignore this if we are going to send a
19836 			 * zero window probe out.
19837 			 *
19838 			 * TODO: force data into microscopic window?
19839 			 *	==> (!pushed || (unsent > usable))
19840 			 */
19841 			if (len < (tcp->tcp_max_swnd >> 1) &&
19842 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
19843 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
19844 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
19845 				/*
19846 				 * If the retransmit timer is not running
19847 				 * we start it so that we will retransmit
19848 				 * in the case when the the receiver has
19849 				 * decremented the window.
19850 				 */
19851 				if (*snxt == tcp->tcp_snxt &&
19852 				    *snxt == tcp->tcp_suna) {
19853 					/*
19854 					 * We are not supposed to send
19855 					 * anything.  So let's wait a little
19856 					 * bit longer before breaking SWS
19857 					 * avoidance.
19858 					 *
19859 					 * What should the value be?
19860 					 * Suggestion: MAX(init rexmit time,
19861 					 * tcp->tcp_rto)
19862 					 */
19863 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19864 				}
19865 				break;	/* success; too small */
19866 			}
19867 		}
19868 
19869 		tcph = tcp->tcp_tcph;
19870 
19871 		*usable -= len; /* Approximate - can be adjusted later */
19872 		if (*usable > 0)
19873 			tcph->th_flags[0] = TH_ACK;
19874 		else
19875 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
19876 
19877 		/*
19878 		 * Prime pump for IP's checksumming on our behalf
19879 		 * Include the adjustment for a source route if any.
19880 		 */
19881 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19882 		sum = (sum >> 16) + (sum & 0xFFFF);
19883 		U16_TO_ABE16(sum, tcph->th_sum);
19884 
19885 		U32_TO_ABE32(*snxt, tcph->th_seq);
19886 
19887 		/*
19888 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
19889 		 * set.  For the case when TCP_FSS_VALID is the only valid
19890 		 * bit (normal active close), branch off only when we think
19891 		 * that the FIN flag needs to be set.  Note for this case,
19892 		 * that (snxt + len) may not reflect the actual seg_len,
19893 		 * as len may be further reduced in tcp_xmit_mp().  If len
19894 		 * gets modified, we will end up here again.
19895 		 */
19896 		if (tcp->tcp_valid_bits != 0 &&
19897 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
19898 		    ((*snxt + len) == tcp->tcp_fss))) {
19899 			uchar_t		*prev_rptr;
19900 			uint32_t	prev_snxt = tcp->tcp_snxt;
19901 
19902 			if (*tail_unsent == 0) {
19903 				ASSERT((*xmit_tail)->b_cont != NULL);
19904 				*xmit_tail = (*xmit_tail)->b_cont;
19905 				prev_rptr = (*xmit_tail)->b_rptr;
19906 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
19907 				    (*xmit_tail)->b_rptr);
19908 			} else {
19909 				prev_rptr = (*xmit_tail)->b_rptr;
19910 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
19911 				    *tail_unsent;
19912 			}
19913 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
19914 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
19915 			/* Restore tcp_snxt so we get amount sent right. */
19916 			tcp->tcp_snxt = prev_snxt;
19917 			if (prev_rptr == (*xmit_tail)->b_rptr) {
19918 				/*
19919 				 * If the previous timestamp is still in use,
19920 				 * don't stomp on it.
19921 				 */
19922 				if ((*xmit_tail)->b_next == NULL) {
19923 					(*xmit_tail)->b_prev = local_time;
19924 					(*xmit_tail)->b_next =
19925 					    (mblk_t *)(uintptr_t)(*snxt);
19926 				}
19927 			} else
19928 				(*xmit_tail)->b_rptr = prev_rptr;
19929 
19930 			if (mp == NULL)
19931 				return (-1);
19932 			mp1 = mp->b_cont;
19933 
19934 			tcp->tcp_last_sent_len = (ushort_t)len;
19935 			while (mp1->b_cont) {
19936 				*xmit_tail = (*xmit_tail)->b_cont;
19937 				(*xmit_tail)->b_prev = local_time;
19938 				(*xmit_tail)->b_next =
19939 				    (mblk_t *)(uintptr_t)(*snxt);
19940 				mp1 = mp1->b_cont;
19941 			}
19942 			*snxt += len;
19943 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
19944 			BUMP_LOCAL(tcp->tcp_obsegs);
19945 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
19946 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
19947 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
19948 			tcp_send_data(tcp, q, mp);
19949 			continue;
19950 		}
19951 
19952 		*snxt += len;	/* Adjust later if we don't send all of len */
19953 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
19954 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
19955 
19956 		if (*tail_unsent) {
19957 			/* Are the bytes above us in flight? */
19958 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
19959 			if (rptr != (*xmit_tail)->b_rptr) {
19960 				*tail_unsent -= len;
19961 				tcp->tcp_last_sent_len = (ushort_t)len;
19962 				len += tcp_hdr_len;
19963 				if (tcp->tcp_ipversion == IPV4_VERSION)
19964 					tcp->tcp_ipha->ipha_length = htons(len);
19965 				else
19966 					tcp->tcp_ip6h->ip6_plen =
19967 					    htons(len -
19968 					    ((char *)&tcp->tcp_ip6h[1] -
19969 					    tcp->tcp_iphc));
19970 				mp = dupb(*xmit_tail);
19971 				if (!mp)
19972 					return (-1);	/* out_of_mem */
19973 				mp->b_rptr = rptr;
19974 				/*
19975 				 * If the old timestamp is no longer in use,
19976 				 * sample a new timestamp now.
19977 				 */
19978 				if ((*xmit_tail)->b_next == NULL) {
19979 					(*xmit_tail)->b_prev = local_time;
19980 					(*xmit_tail)->b_next =
19981 					    (mblk_t *)(uintptr_t)(*snxt-len);
19982 				}
19983 				goto must_alloc;
19984 			}
19985 		} else {
19986 			*xmit_tail = (*xmit_tail)->b_cont;
19987 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
19988 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
19989 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
19990 			    (*xmit_tail)->b_rptr);
19991 		}
19992 
19993 		(*xmit_tail)->b_prev = local_time;
19994 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
19995 
19996 		*tail_unsent -= len;
19997 		tcp->tcp_last_sent_len = (ushort_t)len;
19998 
19999 		len += tcp_hdr_len;
20000 		if (tcp->tcp_ipversion == IPV4_VERSION)
20001 			tcp->tcp_ipha->ipha_length = htons(len);
20002 		else
20003 			tcp->tcp_ip6h->ip6_plen = htons(len -
20004 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20005 
20006 		mp = dupb(*xmit_tail);
20007 		if (!mp)
20008 			return (-1);	/* out_of_mem */
20009 
20010 		len = tcp_hdr_len;
20011 		/*
20012 		 * There are four reasons to allocate a new hdr mblk:
20013 		 *  1) The bytes above us are in use by another packet
20014 		 *  2) We don't have good alignment
20015 		 *  3) The mblk is being shared
20016 		 *  4) We don't have enough room for a header
20017 		 */
20018 		rptr = mp->b_rptr - len;
20019 		if (!OK_32PTR(rptr) ||
20020 		    ((db = mp->b_datap), db->db_ref != 2) ||
20021 		    rptr < db->db_base) {
20022 			/* NOTE: we assume allocb returns an OK_32PTR */
20023 
20024 		must_alloc:;
20025 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20026 			    tcp_wroff_xtra, BPRI_MED);
20027 			if (!mp1) {
20028 				freemsg(mp);
20029 				return (-1);	/* out_of_mem */
20030 			}
20031 			mp1->b_cont = mp;
20032 			mp = mp1;
20033 			/* Leave room for Link Level header */
20034 			len = tcp_hdr_len;
20035 			rptr = &mp->b_rptr[tcp_wroff_xtra];
20036 			mp->b_wptr = &rptr[len];
20037 		}
20038 
20039 		/*
20040 		 * Fill in the header using the template header, and add
20041 		 * options such as time-stamp, ECN and/or SACK, as needed.
20042 		 */
20043 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20044 
20045 		mp->b_rptr = rptr;
20046 
20047 		if (*tail_unsent) {
20048 			int spill = *tail_unsent;
20049 
20050 			mp1 = mp->b_cont;
20051 			if (!mp1)
20052 				mp1 = mp;
20053 
20054 			/*
20055 			 * If we're a little short, tack on more mblks until
20056 			 * there is no more spillover.
20057 			 */
20058 			while (spill < 0) {
20059 				mblk_t *nmp;
20060 				int nmpsz;
20061 
20062 				nmp = (*xmit_tail)->b_cont;
20063 				nmpsz = MBLKL(nmp);
20064 
20065 				/*
20066 				 * Excess data in mblk; can we split it?
20067 				 * If MDT is enabled for the connection,
20068 				 * keep on splitting as this is a transient
20069 				 * send path.
20070 				 */
20071 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
20072 					/*
20073 					 * Don't split if stream head was
20074 					 * told to break up larger writes
20075 					 * into smaller ones.
20076 					 */
20077 					if (tcp->tcp_maxpsz > 0)
20078 						break;
20079 
20080 					/*
20081 					 * Next mblk is less than SMSS/2
20082 					 * rounded up to nearest 64-byte;
20083 					 * let it get sent as part of the
20084 					 * next segment.
20085 					 */
20086 					if (tcp->tcp_localnet &&
20087 					    !tcp->tcp_cork &&
20088 					    (nmpsz < roundup((mss >> 1), 64)))
20089 						break;
20090 				}
20091 
20092 				*xmit_tail = nmp;
20093 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
20094 				/* Stash for rtt use later */
20095 				(*xmit_tail)->b_prev = local_time;
20096 				(*xmit_tail)->b_next =
20097 				    (mblk_t *)(uintptr_t)(*snxt - len);
20098 				mp1->b_cont = dupb(*xmit_tail);
20099 				mp1 = mp1->b_cont;
20100 
20101 				spill += nmpsz;
20102 				if (mp1 == NULL) {
20103 					*tail_unsent = spill;
20104 					freemsg(mp);
20105 					return (-1);	/* out_of_mem */
20106 				}
20107 			}
20108 
20109 			/* Trim back any surplus on the last mblk */
20110 			if (spill >= 0) {
20111 				mp1->b_wptr -= spill;
20112 				*tail_unsent = spill;
20113 			} else {
20114 				/*
20115 				 * We did not send everything we could in
20116 				 * order to remain within the b_cont limit.
20117 				 */
20118 				*usable -= spill;
20119 				*snxt += spill;
20120 				tcp->tcp_last_sent_len += spill;
20121 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
20122 				/*
20123 				 * Adjust the checksum
20124 				 */
20125 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20126 				sum += spill;
20127 				sum = (sum >> 16) + (sum & 0xFFFF);
20128 				U16_TO_ABE16(sum, tcph->th_sum);
20129 				if (tcp->tcp_ipversion == IPV4_VERSION) {
20130 					sum = ntohs(
20131 					    ((ipha_t *)rptr)->ipha_length) +
20132 					    spill;
20133 					((ipha_t *)rptr)->ipha_length =
20134 					    htons(sum);
20135 				} else {
20136 					sum = ntohs(
20137 					    ((ip6_t *)rptr)->ip6_plen) +
20138 					    spill;
20139 					((ip6_t *)rptr)->ip6_plen =
20140 					    htons(sum);
20141 				}
20142 				*tail_unsent = 0;
20143 			}
20144 		}
20145 		if (tcp->tcp_ip_forward_progress) {
20146 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20147 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20148 			tcp->tcp_ip_forward_progress = B_FALSE;
20149 		}
20150 
20151 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20152 		tcp_send_data(tcp, q, mp);
20153 		BUMP_LOCAL(tcp->tcp_obsegs);
20154 	}
20155 
20156 	return (0);
20157 }
20158 
20159 /* Unlink and return any mblk that looks like it contains a MDT info */
20160 static mblk_t *
20161 tcp_mdt_info_mp(mblk_t *mp)
20162 {
20163 	mblk_t	*prev_mp;
20164 
20165 	for (;;) {
20166 		prev_mp = mp;
20167 		/* no more to process? */
20168 		if ((mp = mp->b_cont) == NULL)
20169 			break;
20170 
20171 		switch (DB_TYPE(mp)) {
20172 		case M_CTL:
20173 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20174 				continue;
20175 			ASSERT(prev_mp != NULL);
20176 			prev_mp->b_cont = mp->b_cont;
20177 			mp->b_cont = NULL;
20178 			return (mp);
20179 		default:
20180 			break;
20181 		}
20182 	}
20183 	return (mp);
20184 }
20185 
20186 /* MDT info update routine, called when IP notifies us about MDT */
20187 static void
20188 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20189 {
20190 	boolean_t prev_state;
20191 
20192 	/*
20193 	 * IP is telling us to abort MDT on this connection?  We know
20194 	 * this because the capability is only turned off when IP
20195 	 * encounters some pathological cases, e.g. link-layer change
20196 	 * where the new driver doesn't support MDT, or in situation
20197 	 * where MDT usage on the link-layer has been switched off.
20198 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20199 	 * if the link-layer doesn't support MDT, and if it does, it
20200 	 * will indicate that the feature is to be turned on.
20201 	 */
20202 	prev_state = tcp->tcp_mdt;
20203 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20204 	if (!tcp->tcp_mdt && !first) {
20205 		TCP_STAT(tcp_mdt_conn_halted3);
20206 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20207 		    (void *)tcp->tcp_connp));
20208 	}
20209 
20210 	/*
20211 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20212 	 * so disable MDT otherwise.  The checks are done here
20213 	 * and in tcp_wput_data().
20214 	 */
20215 	if (tcp->tcp_mdt &&
20216 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20217 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20218 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20219 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20220 		tcp->tcp_mdt = B_FALSE;
20221 
20222 	if (tcp->tcp_mdt) {
20223 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
20224 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
20225 			    "version (%d), expected version is %d",
20226 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
20227 			tcp->tcp_mdt = B_FALSE;
20228 			return;
20229 		}
20230 
20231 		/*
20232 		 * We need the driver to be able to handle at least three
20233 		 * spans per packet in order for tcp MDT to be utilized.
20234 		 * The first is for the header portion, while the rest are
20235 		 * needed to handle a packet that straddles across two
20236 		 * virtually non-contiguous buffers; a typical tcp packet
20237 		 * therefore consists of only two spans.  Note that we take
20238 		 * a zero as "don't care".
20239 		 */
20240 		if (mdt_capab->ill_mdt_span_limit > 0 &&
20241 		    mdt_capab->ill_mdt_span_limit < 3) {
20242 			tcp->tcp_mdt = B_FALSE;
20243 			return;
20244 		}
20245 
20246 		/* a zero means driver wants default value */
20247 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
20248 		    tcp_mdt_max_pbufs);
20249 		if (tcp->tcp_mdt_max_pld == 0)
20250 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
20251 
20252 		/* ensure 32-bit alignment */
20253 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
20254 		    mdt_capab->ill_mdt_hdr_head), 4);
20255 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
20256 		    mdt_capab->ill_mdt_hdr_tail), 4);
20257 
20258 		if (!first && !prev_state) {
20259 			TCP_STAT(tcp_mdt_conn_resumed2);
20260 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
20261 			    (void *)tcp->tcp_connp));
20262 		}
20263 	}
20264 }
20265 
20266 static void
20267 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
20268 {
20269 	conn_t *connp = tcp->tcp_connp;
20270 
20271 	ASSERT(ire != NULL);
20272 
20273 	/*
20274 	 * We may be in the fastpath here, and although we essentially do
20275 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
20276 	 * we try to keep things as brief as possible.  After all, these
20277 	 * are only best-effort checks, and we do more thorough ones prior
20278 	 * to calling tcp_multisend().
20279 	 */
20280 	if (ip_multidata_outbound && check_mdt &&
20281 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
20282 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
20283 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
20284 	    !(ire->ire_flags & RTF_MULTIRT) &&
20285 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
20286 	    CONN_IS_MD_FASTPATH(connp)) {
20287 		/* Remember the result */
20288 		connp->conn_mdt_ok = B_TRUE;
20289 
20290 		ASSERT(ill->ill_mdt_capab != NULL);
20291 		if (!ill->ill_mdt_capab->ill_mdt_on) {
20292 			/*
20293 			 * If MDT has been previously turned off in the past,
20294 			 * and we currently can do MDT (due to IPQoS policy
20295 			 * removal, etc.) then enable it for this interface.
20296 			 */
20297 			ill->ill_mdt_capab->ill_mdt_on = 1;
20298 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
20299 			    "interface %s\n", (void *)connp, ill->ill_name));
20300 		}
20301 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
20302 	}
20303 
20304 	/*
20305 	 * The goal is to reduce the number of generated tcp segments by
20306 	 * setting the maxpsz multiplier to 0; this will have an affect on
20307 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
20308 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
20309 	 * of outbound segments and incoming ACKs, thus allowing for better
20310 	 * network and system performance.  In contrast the legacy behavior
20311 	 * may result in sending less than SMSS size, because the last mblk
20312 	 * for some packets may have more data than needed to make up SMSS,
20313 	 * and the legacy code refused to "split" it.
20314 	 *
20315 	 * We apply the new behavior on following situations:
20316 	 *
20317 	 *   1) Loopback connections,
20318 	 *   2) Connections in which the remote peer is not on local subnet,
20319 	 *   3) Local subnet connections over the bge interface (see below).
20320 	 *
20321 	 * Ideally, we would like this behavior to apply for interfaces other
20322 	 * than bge.  However, doing so would negatively impact drivers which
20323 	 * perform dynamic mapping and unmapping of DMA resources, which are
20324 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
20325 	 * packet will be generated by tcp).  The bge driver does not suffer
20326 	 * from this, as it copies the mblks into pre-mapped buffers, and
20327 	 * therefore does not require more I/O resources than before.
20328 	 *
20329 	 * Otherwise, this behavior is present on all network interfaces when
20330 	 * the destination endpoint is non-local, since reducing the number
20331 	 * of packets in general is good for the network.
20332 	 *
20333 	 * TODO We need to remove this hard-coded conditional for bge once
20334 	 *	a better "self-tuning" mechanism, or a way to comprehend
20335 	 *	the driver transmit strategy is devised.  Until the solution
20336 	 *	is found and well understood, we live with this hack.
20337 	 */
20338 	if (!tcp_static_maxpsz &&
20339 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
20340 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
20341 		/* override the default value */
20342 		tcp->tcp_maxpsz = 0;
20343 
20344 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
20345 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
20346 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
20347 	}
20348 
20349 	/* set the stream head parameters accordingly */
20350 	(void) tcp_maxpsz_set(tcp, B_TRUE);
20351 }
20352 
20353 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
20354 static void
20355 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
20356 {
20357 	uchar_t	fval = *mp->b_rptr;
20358 	mblk_t	*tail;
20359 	queue_t	*q = tcp->tcp_wq;
20360 
20361 	/* TODO: How should flush interact with urgent data? */
20362 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
20363 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
20364 		/*
20365 		 * Flush only data that has not yet been put on the wire.  If
20366 		 * we flush data that we have already transmitted, life, as we
20367 		 * know it, may come to an end.
20368 		 */
20369 		tail = tcp->tcp_xmit_tail;
20370 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
20371 		tcp->tcp_xmit_tail_unsent = 0;
20372 		tcp->tcp_unsent = 0;
20373 		if (tail->b_wptr != tail->b_rptr)
20374 			tail = tail->b_cont;
20375 		if (tail) {
20376 			mblk_t **excess = &tcp->tcp_xmit_head;
20377 			for (;;) {
20378 				mblk_t *mp1 = *excess;
20379 				if (mp1 == tail)
20380 					break;
20381 				tcp->tcp_xmit_tail = mp1;
20382 				tcp->tcp_xmit_last = mp1;
20383 				excess = &mp1->b_cont;
20384 			}
20385 			*excess = NULL;
20386 			tcp_close_mpp(&tail);
20387 			if (tcp->tcp_snd_zcopy_aware)
20388 				tcp_zcopy_notify(tcp);
20389 		}
20390 		/*
20391 		 * We have no unsent data, so unsent must be less than
20392 		 * tcp_xmit_lowater, so re-enable flow.
20393 		 */
20394 		if (tcp->tcp_flow_stopped) {
20395 			tcp_clrqfull(tcp);
20396 		}
20397 	}
20398 	/*
20399 	 * TODO: you can't just flush these, you have to increase rwnd for one
20400 	 * thing.  For another, how should urgent data interact?
20401 	 */
20402 	if (fval & FLUSHR) {
20403 		*mp->b_rptr = fval & ~FLUSHW;
20404 		/* XXX */
20405 		qreply(q, mp);
20406 		return;
20407 	}
20408 	freemsg(mp);
20409 }
20410 
20411 /*
20412  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
20413  * messages.
20414  */
20415 static void
20416 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
20417 {
20418 	mblk_t	*mp1;
20419 	STRUCT_HANDLE(strbuf, sb);
20420 	uint16_t port;
20421 	queue_t 	*q = tcp->tcp_wq;
20422 	in6_addr_t	v6addr;
20423 	ipaddr_t	v4addr;
20424 	uint32_t	flowinfo = 0;
20425 	int		addrlen;
20426 
20427 	/* Make sure it is one of ours. */
20428 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20429 	case TI_GETMYNAME:
20430 	case TI_GETPEERNAME:
20431 		break;
20432 	default:
20433 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20434 		return;
20435 	}
20436 	switch (mi_copy_state(q, mp, &mp1)) {
20437 	case -1:
20438 		return;
20439 	case MI_COPY_CASE(MI_COPY_IN, 1):
20440 		break;
20441 	case MI_COPY_CASE(MI_COPY_OUT, 1):
20442 		/* Copy out the strbuf. */
20443 		mi_copyout(q, mp);
20444 		return;
20445 	case MI_COPY_CASE(MI_COPY_OUT, 2):
20446 		/* All done. */
20447 		mi_copy_done(q, mp, 0);
20448 		return;
20449 	default:
20450 		mi_copy_done(q, mp, EPROTO);
20451 		return;
20452 	}
20453 	/* Check alignment of the strbuf */
20454 	if (!OK_32PTR(mp1->b_rptr)) {
20455 		mi_copy_done(q, mp, EINVAL);
20456 		return;
20457 	}
20458 
20459 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
20460 	    (void *)mp1->b_rptr);
20461 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
20462 
20463 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
20464 		mi_copy_done(q, mp, EINVAL);
20465 		return;
20466 	}
20467 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20468 	case TI_GETMYNAME:
20469 		if (tcp->tcp_family == AF_INET) {
20470 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20471 				v4addr = tcp->tcp_ipha->ipha_src;
20472 			} else {
20473 				/* can't return an address in this case */
20474 				v4addr = 0;
20475 			}
20476 		} else {
20477 			/* tcp->tcp_family == AF_INET6 */
20478 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20479 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
20480 				    &v6addr);
20481 			} else {
20482 				v6addr = tcp->tcp_ip6h->ip6_src;
20483 			}
20484 		}
20485 		port = tcp->tcp_lport;
20486 		break;
20487 	case TI_GETPEERNAME:
20488 		if (tcp->tcp_family == AF_INET) {
20489 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20490 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
20491 				    v4addr);
20492 			} else {
20493 				/* can't return an address in this case */
20494 				v4addr = 0;
20495 			}
20496 		} else {
20497 			/* tcp->tcp_family == AF_INET6) */
20498 			v6addr = tcp->tcp_remote_v6;
20499 			if (tcp->tcp_ipversion == IPV6_VERSION) {
20500 				/*
20501 				 * No flowinfo if tcp->tcp_ipversion is v4.
20502 				 *
20503 				 * flowinfo was already initialized to zero
20504 				 * where it was declared above, so only
20505 				 * set it if ipversion is v6.
20506 				 */
20507 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
20508 				    ~IPV6_VERS_AND_FLOW_MASK;
20509 			}
20510 		}
20511 		port = tcp->tcp_fport;
20512 		break;
20513 	default:
20514 		mi_copy_done(q, mp, EPROTO);
20515 		return;
20516 	}
20517 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
20518 	if (!mp1)
20519 		return;
20520 
20521 	if (tcp->tcp_family == AF_INET) {
20522 		sin_t *sin;
20523 
20524 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
20525 		sin = (sin_t *)mp1->b_rptr;
20526 		mp1->b_wptr = (uchar_t *)&sin[1];
20527 		*sin = sin_null;
20528 		sin->sin_family = AF_INET;
20529 		sin->sin_addr.s_addr = v4addr;
20530 		sin->sin_port = port;
20531 	} else {
20532 		/* tcp->tcp_family == AF_INET6 */
20533 		sin6_t *sin6;
20534 
20535 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
20536 		sin6 = (sin6_t *)mp1->b_rptr;
20537 		mp1->b_wptr = (uchar_t *)&sin6[1];
20538 		*sin6 = sin6_null;
20539 		sin6->sin6_family = AF_INET6;
20540 		sin6->sin6_flowinfo = flowinfo;
20541 		sin6->sin6_addr = v6addr;
20542 		sin6->sin6_port = port;
20543 	}
20544 	/* Copy out the address */
20545 	mi_copyout(q, mp);
20546 }
20547 
20548 /*
20549  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
20550  * messages.
20551  */
20552 /* ARGSUSED */
20553 static void
20554 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
20555 {
20556 	conn_t 	*connp = (conn_t *)arg;
20557 	tcp_t	*tcp = connp->conn_tcp;
20558 	queue_t	*q = tcp->tcp_wq;
20559 	struct iocblk	*iocp;
20560 
20561 	ASSERT(DB_TYPE(mp) == M_IOCTL);
20562 	/*
20563 	 * Try and ASSERT the minimum possible references on the
20564 	 * conn early enough. Since we are executing on write side,
20565 	 * the connection is obviously not detached and that means
20566 	 * there is a ref each for TCP and IP. Since we are behind
20567 	 * the squeue, the minimum references needed are 3. If the
20568 	 * conn is in classifier hash list, there should be an
20569 	 * extra ref for that (we check both the possibilities).
20570 	 */
20571 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20572 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20573 
20574 	iocp = (struct iocblk *)mp->b_rptr;
20575 	switch (iocp->ioc_cmd) {
20576 	case TCP_IOC_DEFAULT_Q:
20577 		/* Wants to be the default wq. */
20578 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
20579 			iocp->ioc_error = EPERM;
20580 			iocp->ioc_count = 0;
20581 			mp->b_datap->db_type = M_IOCACK;
20582 			qreply(q, mp);
20583 			return;
20584 		}
20585 		tcp_def_q_set(tcp, mp);
20586 		return;
20587 	case _SIOCSOCKFALLBACK:
20588 		/*
20589 		 * Either sockmod is about to be popped and the socket
20590 		 * would now be treated as a plain stream, or a module
20591 		 * is about to be pushed so we could no longer use read-
20592 		 * side synchronous streams for fused loopback tcp.
20593 		 * Drain any queued data and disable direct sockfs
20594 		 * interface from now on.
20595 		 */
20596 		if (!tcp->tcp_issocket) {
20597 			DB_TYPE(mp) = M_IOCNAK;
20598 			iocp->ioc_error = EINVAL;
20599 		} else {
20600 #ifdef	_ILP32
20601 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
20602 #else
20603 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
20604 #endif
20605 			/*
20606 			 * Insert this socket into the acceptor hash.
20607 			 * We might need it for T_CONN_RES message
20608 			 */
20609 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
20610 
20611 			if (tcp->tcp_fused) {
20612 				/*
20613 				 * This is a fused loopback tcp; disable
20614 				 * read-side synchronous streams interface
20615 				 * and drain any queued data.  It is okay
20616 				 * to do this for non-synchronous streams
20617 				 * fused tcp as well.
20618 				 */
20619 				tcp_fuse_disable_pair(tcp, B_FALSE);
20620 			}
20621 			tcp->tcp_issocket = B_FALSE;
20622 			TCP_STAT(tcp_sock_fallback);
20623 
20624 			DB_TYPE(mp) = M_IOCACK;
20625 			iocp->ioc_error = 0;
20626 		}
20627 		iocp->ioc_count = 0;
20628 		iocp->ioc_rval = 0;
20629 		qreply(q, mp);
20630 		return;
20631 	}
20632 	CALL_IP_WPUT(connp, q, mp);
20633 }
20634 
20635 /*
20636  * This routine is called by tcp_wput() to handle all TPI requests.
20637  */
20638 /* ARGSUSED */
20639 static void
20640 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
20641 {
20642 	conn_t 	*connp = (conn_t *)arg;
20643 	tcp_t	*tcp = connp->conn_tcp;
20644 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
20645 	uchar_t *rptr;
20646 	t_scalar_t type;
20647 	int len;
20648 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
20649 
20650 	/*
20651 	 * Try and ASSERT the minimum possible references on the
20652 	 * conn early enough. Since we are executing on write side,
20653 	 * the connection is obviously not detached and that means
20654 	 * there is a ref each for TCP and IP. Since we are behind
20655 	 * the squeue, the minimum references needed are 3. If the
20656 	 * conn is in classifier hash list, there should be an
20657 	 * extra ref for that (we check both the possibilities).
20658 	 */
20659 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20660 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20661 
20662 	rptr = mp->b_rptr;
20663 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
20664 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
20665 		type = ((union T_primitives *)rptr)->type;
20666 		if (type == T_EXDATA_REQ) {
20667 			uint32_t msize = msgdsize(mp->b_cont);
20668 
20669 			len = msize - 1;
20670 			if (len < 0) {
20671 				freemsg(mp);
20672 				return;
20673 			}
20674 			/*
20675 			 * Try to force urgent data out on the wire.
20676 			 * Even if we have unsent data this will
20677 			 * at least send the urgent flag.
20678 			 * XXX does not handle more flag correctly.
20679 			 */
20680 			len += tcp->tcp_unsent;
20681 			len += tcp->tcp_snxt;
20682 			tcp->tcp_urg = len;
20683 			tcp->tcp_valid_bits |= TCP_URG_VALID;
20684 
20685 			/* Bypass tcp protocol for fused tcp loopback */
20686 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
20687 				return;
20688 		} else if (type != T_DATA_REQ) {
20689 			goto non_urgent_data;
20690 		}
20691 		/* TODO: options, flags, ... from user */
20692 		/* Set length to zero for reclamation below */
20693 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
20694 		freeb(mp);
20695 		return;
20696 	} else {
20697 		if (tcp->tcp_debug) {
20698 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20699 			    "tcp_wput_proto, dropping one...");
20700 		}
20701 		freemsg(mp);
20702 		return;
20703 	}
20704 
20705 non_urgent_data:
20706 
20707 	switch ((int)tprim->type) {
20708 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
20709 		/*
20710 		 * save the kssl_ent_t from the next block, and convert this
20711 		 * back to a normal bind_req.
20712 		 */
20713 		if (mp->b_cont != NULL) {
20714 		    ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
20715 
20716 			if (tcp->tcp_kssl_ent != NULL) {
20717 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
20718 				    KSSL_NO_PROXY);
20719 				tcp->tcp_kssl_ent = NULL;
20720 			}
20721 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
20722 			    sizeof (kssl_ent_t));
20723 			kssl_hold_ent(tcp->tcp_kssl_ent);
20724 			freemsg(mp->b_cont);
20725 			mp->b_cont = NULL;
20726 		}
20727 		tprim->type = T_BIND_REQ;
20728 
20729 	/* FALLTHROUGH */
20730 	case O_T_BIND_REQ:	/* bind request */
20731 	case T_BIND_REQ:	/* new semantics bind request */
20732 		tcp_bind(tcp, mp);
20733 		break;
20734 	case T_UNBIND_REQ:	/* unbind request */
20735 		tcp_unbind(tcp, mp);
20736 		break;
20737 	case O_T_CONN_RES:	/* old connection response XXX */
20738 	case T_CONN_RES:	/* connection response */
20739 		tcp_accept(tcp, mp);
20740 		break;
20741 	case T_CONN_REQ:	/* connection request */
20742 		tcp_connect(tcp, mp);
20743 		break;
20744 	case T_DISCON_REQ:	/* disconnect request */
20745 		tcp_disconnect(tcp, mp);
20746 		break;
20747 	case T_CAPABILITY_REQ:
20748 		tcp_capability_req(tcp, mp);	/* capability request */
20749 		break;
20750 	case T_INFO_REQ:	/* information request */
20751 		tcp_info_req(tcp, mp);
20752 		break;
20753 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
20754 		/* Only IP is allowed to return meaningful value */
20755 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
20756 		break;
20757 	case T_OPTMGMT_REQ:
20758 		/*
20759 		 * Note:  no support for snmpcom_req() through new
20760 		 * T_OPTMGMT_REQ. See comments in ip.c
20761 		 */
20762 		/* Only IP is allowed to return meaningful value */
20763 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
20764 		break;
20765 
20766 	case T_UNITDATA_REQ:	/* unitdata request */
20767 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
20768 		break;
20769 	case T_ORDREL_REQ:	/* orderly release req */
20770 		freemsg(mp);
20771 
20772 		if (tcp->tcp_fused)
20773 			tcp_unfuse(tcp);
20774 
20775 		if (tcp_xmit_end(tcp) != 0) {
20776 			/*
20777 			 * We were crossing FINs and got a reset from
20778 			 * the other side. Just ignore it.
20779 			 */
20780 			if (tcp->tcp_debug) {
20781 				(void) strlog(TCP_MOD_ID, 0, 1,
20782 				    SL_ERROR|SL_TRACE,
20783 				    "tcp_wput_proto, T_ORDREL_REQ out of "
20784 				    "state %s",
20785 				    tcp_display(tcp, NULL,
20786 				    DISP_ADDR_AND_PORT));
20787 			}
20788 		}
20789 		break;
20790 	case T_ADDR_REQ:
20791 		tcp_addr_req(tcp, mp);
20792 		break;
20793 	default:
20794 		if (tcp->tcp_debug) {
20795 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20796 			    "tcp_wput_proto, bogus TPI msg, type %d",
20797 			    tprim->type);
20798 		}
20799 		/*
20800 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
20801 		 * to recover.
20802 		 */
20803 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
20804 		break;
20805 	}
20806 }
20807 
20808 /*
20809  * The TCP write service routine should never be called...
20810  */
20811 /* ARGSUSED */
20812 static void
20813 tcp_wsrv(queue_t *q)
20814 {
20815 	TCP_STAT(tcp_wsrv_called);
20816 }
20817 
20818 /* Non overlapping byte exchanger */
20819 static void
20820 tcp_xchg(uchar_t *a, uchar_t *b, int len)
20821 {
20822 	uchar_t	uch;
20823 
20824 	while (len-- > 0) {
20825 		uch = a[len];
20826 		a[len] = b[len];
20827 		b[len] = uch;
20828 	}
20829 }
20830 
20831 /*
20832  * Send out a control packet on the tcp connection specified.  This routine
20833  * is typically called where we need a simple ACK or RST generated.
20834  */
20835 static void
20836 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
20837 {
20838 	uchar_t		*rptr;
20839 	tcph_t		*tcph;
20840 	ipha_t		*ipha = NULL;
20841 	ip6_t		*ip6h = NULL;
20842 	uint32_t	sum;
20843 	int		tcp_hdr_len;
20844 	int		tcp_ip_hdr_len;
20845 	mblk_t		*mp;
20846 
20847 	/*
20848 	 * Save sum for use in source route later.
20849 	 */
20850 	ASSERT(tcp != NULL);
20851 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
20852 	tcp_hdr_len = tcp->tcp_hdr_len;
20853 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
20854 
20855 	/* If a text string is passed in with the request, pass it to strlog. */
20856 	if (str != NULL && tcp->tcp_debug) {
20857 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
20858 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
20859 		    str, seq, ack, ctl);
20860 	}
20861 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
20862 	    BPRI_MED);
20863 	if (mp == NULL) {
20864 		return;
20865 	}
20866 	rptr = &mp->b_rptr[tcp_wroff_xtra];
20867 	mp->b_rptr = rptr;
20868 	mp->b_wptr = &rptr[tcp_hdr_len];
20869 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
20870 
20871 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20872 		ipha = (ipha_t *)rptr;
20873 		ipha->ipha_length = htons(tcp_hdr_len);
20874 	} else {
20875 		ip6h = (ip6_t *)rptr;
20876 		ASSERT(tcp != NULL);
20877 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
20878 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20879 	}
20880 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
20881 	tcph->th_flags[0] = (uint8_t)ctl;
20882 	if (ctl & TH_RST) {
20883 		BUMP_MIB(&tcp_mib, tcpOutRsts);
20884 		BUMP_MIB(&tcp_mib, tcpOutControl);
20885 		/*
20886 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
20887 		 */
20888 		if (tcp->tcp_snd_ts_ok &&
20889 		    tcp->tcp_state > TCPS_SYN_SENT) {
20890 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
20891 			*(mp->b_wptr) = TCPOPT_EOL;
20892 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20893 				ipha->ipha_length = htons(tcp_hdr_len -
20894 				    TCPOPT_REAL_TS_LEN);
20895 			} else {
20896 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
20897 				    TCPOPT_REAL_TS_LEN);
20898 			}
20899 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
20900 			sum -= TCPOPT_REAL_TS_LEN;
20901 		}
20902 	}
20903 	if (ctl & TH_ACK) {
20904 		if (tcp->tcp_snd_ts_ok) {
20905 			U32_TO_BE32(lbolt,
20906 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
20907 			U32_TO_BE32(tcp->tcp_ts_recent,
20908 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
20909 		}
20910 
20911 		/* Update the latest receive window size in TCP header. */
20912 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
20913 		    tcph->th_win);
20914 		tcp->tcp_rack = ack;
20915 		tcp->tcp_rack_cnt = 0;
20916 		BUMP_MIB(&tcp_mib, tcpOutAck);
20917 	}
20918 	BUMP_LOCAL(tcp->tcp_obsegs);
20919 	U32_TO_BE32(seq, tcph->th_seq);
20920 	U32_TO_BE32(ack, tcph->th_ack);
20921 	/*
20922 	 * Include the adjustment for a source route if any.
20923 	 */
20924 	sum = (sum >> 16) + (sum & 0xFFFF);
20925 	U16_TO_BE16(sum, tcph->th_sum);
20926 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20927 	tcp_send_data(tcp, tcp->tcp_wq, mp);
20928 }
20929 
20930 /*
20931  * If this routine returns B_TRUE, TCP can generate a RST in response
20932  * to a segment.  If it returns B_FALSE, TCP should not respond.
20933  */
20934 static boolean_t
20935 tcp_send_rst_chk(void)
20936 {
20937 	clock_t	now;
20938 
20939 	/*
20940 	 * TCP needs to protect itself from generating too many RSTs.
20941 	 * This can be a DoS attack by sending us random segments
20942 	 * soliciting RSTs.
20943 	 *
20944 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
20945 	 * in each 1 second interval.  In this way, TCP still generate
20946 	 * RSTs in normal cases but when under attack, the impact is
20947 	 * limited.
20948 	 */
20949 	if (tcp_rst_sent_rate_enabled != 0) {
20950 		now = lbolt;
20951 		/* lbolt can wrap around. */
20952 		if ((tcp_last_rst_intrvl > now) ||
20953 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
20954 			tcp_last_rst_intrvl = now;
20955 			tcp_rst_cnt = 1;
20956 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
20957 			return (B_FALSE);
20958 		}
20959 	}
20960 	return (B_TRUE);
20961 }
20962 
20963 /*
20964  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
20965  */
20966 static void
20967 tcp_ip_ire_mark_advice(tcp_t *tcp)
20968 {
20969 	mblk_t *mp;
20970 	ipic_t *ipic;
20971 
20972 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20973 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
20974 		    &ipic);
20975 	} else {
20976 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
20977 		    &ipic);
20978 	}
20979 	if (mp == NULL)
20980 		return;
20981 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
20982 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
20983 }
20984 
20985 /*
20986  * Return an IP advice ioctl mblk and set ipic to be the pointer
20987  * to the advice structure.
20988  */
20989 static mblk_t *
20990 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
20991 {
20992 	struct iocblk *ioc;
20993 	mblk_t *mp, *mp1;
20994 
20995 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
20996 	if (mp == NULL)
20997 		return (NULL);
20998 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
20999 	*ipic = (ipic_t *)mp->b_rptr;
21000 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21001 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21002 
21003 	bcopy(addr, *ipic + 1, addr_len);
21004 
21005 	(*ipic)->ipic_addr_length = addr_len;
21006 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21007 
21008 	mp1 = mkiocb(IP_IOCTL);
21009 	if (mp1 == NULL) {
21010 		freemsg(mp);
21011 		return (NULL);
21012 	}
21013 	mp1->b_cont = mp;
21014 	ioc = (struct iocblk *)mp1->b_rptr;
21015 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
21016 
21017 	return (mp1);
21018 }
21019 
21020 /*
21021  * Generate a reset based on an inbound packet for which there is no active
21022  * tcp state that we can find.
21023  *
21024  * IPSEC NOTE : Try to send the reply with the same protection as it came
21025  * in.  We still have the ipsec_mp that the packet was attached to. Thus
21026  * the packet will go out at the same level of protection as it came in by
21027  * converting the IPSEC_IN to IPSEC_OUT.
21028  */
21029 static void
21030 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
21031     uint32_t ack, int ctl, uint_t ip_hdr_len)
21032 {
21033 	ipha_t		*ipha = NULL;
21034 	ip6_t		*ip6h = NULL;
21035 	ushort_t	len;
21036 	tcph_t		*tcph;
21037 	int		i;
21038 	mblk_t		*ipsec_mp;
21039 	boolean_t	mctl_present;
21040 	ipic_t		*ipic;
21041 	ipaddr_t	v4addr;
21042 	in6_addr_t	v6addr;
21043 	int		addr_len;
21044 	void		*addr;
21045 	queue_t		*q = tcp_g_q;
21046 	tcp_t		*tcp = Q_TO_TCP(q);
21047 
21048 	if (!tcp_send_rst_chk()) {
21049 		tcp_rst_unsent++;
21050 		freemsg(mp);
21051 		return;
21052 	}
21053 
21054 	if (mp->b_datap->db_type == M_CTL) {
21055 		ipsec_mp = mp;
21056 		mp = mp->b_cont;
21057 		mctl_present = B_TRUE;
21058 	} else {
21059 		ipsec_mp = mp;
21060 		mctl_present = B_FALSE;
21061 	}
21062 
21063 	if (str && q && tcp_dbg) {
21064 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21065 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
21066 		    "flags 0x%x",
21067 		    str, seq, ack, ctl);
21068 	}
21069 	if (mp->b_datap->db_ref != 1) {
21070 		mblk_t *mp1 = copyb(mp);
21071 		freemsg(mp);
21072 		mp = mp1;
21073 		if (!mp) {
21074 			if (mctl_present)
21075 				freeb(ipsec_mp);
21076 			return;
21077 		} else {
21078 			if (mctl_present) {
21079 				ipsec_mp->b_cont = mp;
21080 			} else {
21081 				ipsec_mp = mp;
21082 			}
21083 		}
21084 	} else if (mp->b_cont) {
21085 		freemsg(mp->b_cont);
21086 		mp->b_cont = NULL;
21087 	}
21088 	/*
21089 	 * We skip reversing source route here.
21090 	 * (for now we replace all IP options with EOL)
21091 	 */
21092 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21093 		ipha = (ipha_t *)mp->b_rptr;
21094 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
21095 			mp->b_rptr[i] = IPOPT_EOL;
21096 		/*
21097 		 * Make sure that src address isn't flagrantly invalid.
21098 		 * Not all broadcast address checking for the src address
21099 		 * is possible, since we don't know the netmask of the src
21100 		 * addr.  No check for destination address is done, since
21101 		 * IP will not pass up a packet with a broadcast dest
21102 		 * address to TCP.  Similar checks are done below for IPv6.
21103 		 */
21104 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
21105 		    CLASSD(ipha->ipha_src)) {
21106 			freemsg(ipsec_mp);
21107 			BUMP_MIB(&ip_mib, ipInDiscards);
21108 			return;
21109 		}
21110 	} else {
21111 		ip6h = (ip6_t *)mp->b_rptr;
21112 
21113 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
21114 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
21115 			freemsg(ipsec_mp);
21116 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
21117 			return;
21118 		}
21119 
21120 		/* Remove any extension headers assuming partial overlay */
21121 		if (ip_hdr_len > IPV6_HDR_LEN) {
21122 			uint8_t *to;
21123 
21124 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
21125 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
21126 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
21127 			ip_hdr_len = IPV6_HDR_LEN;
21128 			ip6h = (ip6_t *)mp->b_rptr;
21129 			ip6h->ip6_nxt = IPPROTO_TCP;
21130 		}
21131 	}
21132 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
21133 	if (tcph->th_flags[0] & TH_RST) {
21134 		freemsg(ipsec_mp);
21135 		return;
21136 	}
21137 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
21138 	len = ip_hdr_len + sizeof (tcph_t);
21139 	mp->b_wptr = &mp->b_rptr[len];
21140 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21141 		ipha->ipha_length = htons(len);
21142 		/* Swap addresses */
21143 		v4addr = ipha->ipha_src;
21144 		ipha->ipha_src = ipha->ipha_dst;
21145 		ipha->ipha_dst = v4addr;
21146 		ipha->ipha_ident = 0;
21147 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
21148 		addr_len = IP_ADDR_LEN;
21149 		addr = &v4addr;
21150 	} else {
21151 		/* No ip6i_t in this case */
21152 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
21153 		/* Swap addresses */
21154 		v6addr = ip6h->ip6_src;
21155 		ip6h->ip6_src = ip6h->ip6_dst;
21156 		ip6h->ip6_dst = v6addr;
21157 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21158 		addr_len = IPV6_ADDR_LEN;
21159 		addr = &v6addr;
21160 	}
21161 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21162 	U32_TO_BE32(ack, tcph->th_ack);
21163 	U32_TO_BE32(seq, tcph->th_seq);
21164 	U16_TO_BE16(0, tcph->th_win);
21165 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21166 	tcph->th_flags[0] = (uint8_t)ctl;
21167 	if (ctl & TH_RST) {
21168 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21169 		BUMP_MIB(&tcp_mib, tcpOutControl);
21170 	}
21171 	if (mctl_present) {
21172 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21173 
21174 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21175 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21176 			return;
21177 		}
21178 	}
21179 	/*
21180 	 * NOTE:  one might consider tracing a TCP packet here, but
21181 	 * this function has no active TCP state nd no tcp structure
21182 	 * which has trace buffer.  If we traced here, we would have
21183 	 * to keep a local trace buffer in tcp_record_trace().
21184 	 */
21185 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21186 
21187 	/*
21188 	 * Tell IP to mark the IRE used for this destination temporary.
21189 	 * This way, we can limit our exposure to DoS attack because IP
21190 	 * creates an IRE for each destination.  If there are too many,
21191 	 * the time to do any routing lookup will be extremely long.  And
21192 	 * the lookup can be in interrupt context.
21193 	 *
21194 	 * Note that in normal circumstances, this marking should not
21195 	 * affect anything.  It would be nice if only 1 message is
21196 	 * needed to inform IP that the IRE created for this RST should
21197 	 * not be added to the cache table.  But there is currently
21198 	 * not such communication mechanism between TCP and IP.  So
21199 	 * the best we can do now is to send the advice ioctl to IP
21200 	 * to mark the IRE temporary.
21201 	 */
21202 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21203 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21204 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21205 	}
21206 }
21207 
21208 /*
21209  * Initiate closedown sequence on an active connection.  (May be called as
21210  * writer.)  Return value zero for OK return, non-zero for error return.
21211  */
21212 static int
21213 tcp_xmit_end(tcp_t *tcp)
21214 {
21215 	ipic_t	*ipic;
21216 	mblk_t	*mp;
21217 
21218 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21219 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21220 		/*
21221 		 * Invalid state, only states TCPS_SYN_RCVD,
21222 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21223 		 */
21224 		return (-1);
21225 	}
21226 
21227 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21228 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21229 	/*
21230 	 * If there is nothing more unsent, send the FIN now.
21231 	 * Otherwise, it will go out with the last segment.
21232 	 */
21233 	if (tcp->tcp_unsent == 0) {
21234 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21235 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21236 
21237 		if (mp) {
21238 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21239 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21240 		} else {
21241 			/*
21242 			 * Couldn't allocate msg.  Pretend we got it out.
21243 			 * Wait for rexmit timeout.
21244 			 */
21245 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21246 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21247 		}
21248 
21249 		/*
21250 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21251 		 * changed.
21252 		 */
21253 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21254 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21255 		}
21256 	} else {
21257 		/*
21258 		 * If tcp->tcp_cork is set, then the data will not get sent,
21259 		 * so we have to check that and unset it first.
21260 		 */
21261 		if (tcp->tcp_cork)
21262 			tcp->tcp_cork = B_FALSE;
21263 		tcp_wput_data(tcp, NULL, B_FALSE);
21264 	}
21265 
21266 	/*
21267 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
21268 	 * is 0, don't update the cache.
21269 	 */
21270 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
21271 		return (0);
21272 
21273 	/*
21274 	 * NOTE: should not update if source routes i.e. if tcp_remote if
21275 	 * different from the destination.
21276 	 */
21277 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21278 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
21279 			return (0);
21280 		}
21281 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21282 		    &ipic);
21283 	} else {
21284 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
21285 		    &tcp->tcp_ip6h->ip6_dst))) {
21286 			return (0);
21287 		}
21288 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21289 		    &ipic);
21290 	}
21291 
21292 	/* Record route attributes in the IRE for use by future connections. */
21293 	if (mp == NULL)
21294 		return (0);
21295 
21296 	/*
21297 	 * We do not have a good algorithm to update ssthresh at this time.
21298 	 * So don't do any update.
21299 	 */
21300 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
21301 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
21302 
21303 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21304 	return (0);
21305 }
21306 
21307 /*
21308  * Generate a "no listener here" RST in response to an "unknown" segment.
21309  * Note that we are reusing the incoming mp to construct the outgoing
21310  * RST.
21311  */
21312 void
21313 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len)
21314 {
21315 	uchar_t		*rptr;
21316 	uint32_t	seg_len;
21317 	tcph_t		*tcph;
21318 	uint32_t	seg_seq;
21319 	uint32_t	seg_ack;
21320 	uint_t		flags;
21321 	mblk_t		*ipsec_mp;
21322 	ipha_t 		*ipha;
21323 	ip6_t 		*ip6h;
21324 	boolean_t	mctl_present = B_FALSE;
21325 	boolean_t	check = B_TRUE;
21326 	boolean_t	policy_present;
21327 
21328 	TCP_STAT(tcp_no_listener);
21329 
21330 	ipsec_mp = mp;
21331 
21332 	if (mp->b_datap->db_type == M_CTL) {
21333 		ipsec_in_t *ii;
21334 
21335 		mctl_present = B_TRUE;
21336 		mp = mp->b_cont;
21337 
21338 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21339 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21340 		if (ii->ipsec_in_dont_check) {
21341 			check = B_FALSE;
21342 			if (!ii->ipsec_in_secure) {
21343 				freeb(ipsec_mp);
21344 				mctl_present = B_FALSE;
21345 				ipsec_mp = mp;
21346 			}
21347 		}
21348 	}
21349 
21350 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21351 		policy_present = ipsec_inbound_v4_policy_present;
21352 		ipha = (ipha_t *)mp->b_rptr;
21353 		ip6h = NULL;
21354 	} else {
21355 		policy_present = ipsec_inbound_v6_policy_present;
21356 		ipha = NULL;
21357 		ip6h = (ip6_t *)mp->b_rptr;
21358 	}
21359 
21360 	if (check && policy_present) {
21361 		/*
21362 		 * The conn_t parameter is NULL because we already know
21363 		 * nobody's home.
21364 		 */
21365 		ipsec_mp = ipsec_check_global_policy(
21366 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
21367 		if (ipsec_mp == NULL)
21368 			return;
21369 	}
21370 
21371 
21372 	rptr = mp->b_rptr;
21373 
21374 	tcph = (tcph_t *)&rptr[ip_hdr_len];
21375 	seg_seq = BE32_TO_U32(tcph->th_seq);
21376 	seg_ack = BE32_TO_U32(tcph->th_ack);
21377 	flags = tcph->th_flags[0];
21378 
21379 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
21380 	if (flags & TH_RST) {
21381 		freemsg(ipsec_mp);
21382 	} else if (flags & TH_ACK) {
21383 		tcp_xmit_early_reset("no tcp, reset",
21384 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len);
21385 	} else {
21386 		if (flags & TH_SYN) {
21387 			seg_len++;
21388 		} else {
21389 			/*
21390 			 * Here we violate the RFC.  Note that a normal
21391 			 * TCP will never send a segment without the ACK
21392 			 * flag, except for RST or SYN segment.  This
21393 			 * segment is neither.  Just drop it on the
21394 			 * floor.
21395 			 */
21396 			freemsg(ipsec_mp);
21397 			tcp_rst_unsent++;
21398 			return;
21399 		}
21400 
21401 		tcp_xmit_early_reset("no tcp, reset/ack",
21402 		    ipsec_mp, 0, seg_seq + seg_len,
21403 		    TH_RST | TH_ACK, ip_hdr_len);
21404 	}
21405 }
21406 
21407 /*
21408  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
21409  * ip and tcp header ready to pass down to IP.  If the mp passed in is
21410  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
21411  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
21412  * otherwise it will dup partial mblks.)
21413  * Otherwise, an appropriate ACK packet will be generated.  This
21414  * routine is not usually called to send new data for the first time.  It
21415  * is mostly called out of the timer for retransmits, and to generate ACKs.
21416  *
21417  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
21418  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
21419  * of the original mblk chain will be returned in *offset and *end_mp.
21420  */
21421 static mblk_t *
21422 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
21423     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
21424     boolean_t rexmit)
21425 {
21426 	int	data_length;
21427 	int32_t	off = 0;
21428 	uint_t	flags;
21429 	mblk_t	*mp1;
21430 	mblk_t	*mp2;
21431 	uchar_t	*rptr;
21432 	tcph_t	*tcph;
21433 	int32_t	num_sack_blk = 0;
21434 	int32_t	sack_opt_len = 0;
21435 
21436 	/* Allocate for our maximum TCP header + link-level */
21437 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21438 	    BPRI_MED);
21439 	if (!mp1)
21440 		return (NULL);
21441 	data_length = 0;
21442 
21443 	/*
21444 	 * Note that tcp_mss has been adjusted to take into account the
21445 	 * timestamp option if applicable.  Because SACK options do not
21446 	 * appear in every TCP segments and they are of variable lengths,
21447 	 * they cannot be included in tcp_mss.  Thus we need to calculate
21448 	 * the actual segment length when we need to send a segment which
21449 	 * includes SACK options.
21450 	 */
21451 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21452 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21453 		    tcp->tcp_num_sack_blk);
21454 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21455 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21456 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
21457 			max_to_send -= sack_opt_len;
21458 	}
21459 
21460 	if (offset != NULL) {
21461 		off = *offset;
21462 		/* We use offset as an indicator that end_mp is not NULL. */
21463 		*end_mp = NULL;
21464 	}
21465 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
21466 		/* This could be faster with cooperation from downstream */
21467 		if (mp2 != mp1 && !sendall &&
21468 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
21469 		    max_to_send)
21470 			/*
21471 			 * Don't send the next mblk since the whole mblk
21472 			 * does not fit.
21473 			 */
21474 			break;
21475 		mp2->b_cont = dupb(mp);
21476 		mp2 = mp2->b_cont;
21477 		if (!mp2) {
21478 			freemsg(mp1);
21479 			return (NULL);
21480 		}
21481 		mp2->b_rptr += off;
21482 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
21483 		    (uintptr_t)INT_MAX);
21484 
21485 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
21486 		if (data_length > max_to_send) {
21487 			mp2->b_wptr -= data_length - max_to_send;
21488 			data_length = max_to_send;
21489 			off = mp2->b_wptr - mp->b_rptr;
21490 			break;
21491 		} else {
21492 			off = 0;
21493 		}
21494 	}
21495 	if (offset != NULL) {
21496 		*offset = off;
21497 		*end_mp = mp;
21498 	}
21499 	if (seg_len != NULL) {
21500 		*seg_len = data_length;
21501 	}
21502 
21503 	/* Update the latest receive window size in TCP header. */
21504 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21505 	    tcp->tcp_tcph->th_win);
21506 
21507 	rptr = mp1->b_rptr + tcp_wroff_xtra;
21508 	mp1->b_rptr = rptr;
21509 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
21510 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21511 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21512 	U32_TO_ABE32(seq, tcph->th_seq);
21513 
21514 	/*
21515 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
21516 	 * that this function was called from tcp_wput_data. Thus, when called
21517 	 * to retransmit data the setting of the PUSH bit may appear some
21518 	 * what random in that it might get set when it should not. This
21519 	 * should not pose any performance issues.
21520 	 */
21521 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
21522 	    tcp->tcp_unsent == data_length)) {
21523 		flags = TH_ACK | TH_PUSH;
21524 	} else {
21525 		flags = TH_ACK;
21526 	}
21527 
21528 	if (tcp->tcp_ecn_ok) {
21529 		if (tcp->tcp_ecn_echo_on)
21530 			flags |= TH_ECE;
21531 
21532 		/*
21533 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
21534 		 * There is no TCP flow control for non-data segments, and
21535 		 * only data segment is transmitted reliably.
21536 		 */
21537 		if (data_length > 0 && !rexmit) {
21538 			SET_ECT(tcp, rptr);
21539 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
21540 				flags |= TH_CWR;
21541 				tcp->tcp_ecn_cwr_sent = B_TRUE;
21542 			}
21543 		}
21544 	}
21545 
21546 	if (tcp->tcp_valid_bits) {
21547 		uint32_t u1;
21548 
21549 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
21550 		    seq == tcp->tcp_iss) {
21551 			uchar_t	*wptr;
21552 
21553 			/*
21554 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
21555 			 * TCP can only be in SYN-SENT, SYN-RCVD or
21556 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
21557 			 * our SYN is not ack'ed but the app closes this
21558 			 * TCP connection.
21559 			 */
21560 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
21561 			    tcp->tcp_state == TCPS_SYN_RCVD ||
21562 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
21563 
21564 			/*
21565 			 * Tack on the MSS option.  It is always needed
21566 			 * for both active and passive open.
21567 			 *
21568 			 * MSS option value should be interface MTU - MIN
21569 			 * TCP/IP header according to RFC 793 as it means
21570 			 * the maximum segment size TCP can receive.  But
21571 			 * to get around some broken middle boxes/end hosts
21572 			 * out there, we allow the option value to be the
21573 			 * same as the MSS option size on the peer side.
21574 			 * In this way, the other side will not send
21575 			 * anything larger than they can receive.
21576 			 *
21577 			 * Note that for SYN_SENT state, the ndd param
21578 			 * tcp_use_smss_as_mss_opt has no effect as we
21579 			 * don't know the peer's MSS option value. So
21580 			 * the only case we need to take care of is in
21581 			 * SYN_RCVD state, which is done later.
21582 			 */
21583 			wptr = mp1->b_wptr;
21584 			wptr[0] = TCPOPT_MAXSEG;
21585 			wptr[1] = TCPOPT_MAXSEG_LEN;
21586 			wptr += 2;
21587 			u1 = tcp->tcp_if_mtu -
21588 			    (tcp->tcp_ipversion == IPV4_VERSION ?
21589 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
21590 			    TCP_MIN_HEADER_LENGTH;
21591 			U16_TO_BE16(u1, wptr);
21592 			mp1->b_wptr = wptr + 2;
21593 			/* Update the offset to cover the additional word */
21594 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
21595 
21596 			/*
21597 			 * Note that the following way of filling in
21598 			 * TCP options are not optimal.  Some NOPs can
21599 			 * be saved.  But there is no need at this time
21600 			 * to optimize it.  When it is needed, we will
21601 			 * do it.
21602 			 */
21603 			switch (tcp->tcp_state) {
21604 			case TCPS_SYN_SENT:
21605 				flags = TH_SYN;
21606 
21607 				if (tcp->tcp_snd_ts_ok) {
21608 					uint32_t llbolt = (uint32_t)lbolt;
21609 
21610 					wptr = mp1->b_wptr;
21611 					wptr[0] = TCPOPT_NOP;
21612 					wptr[1] = TCPOPT_NOP;
21613 					wptr[2] = TCPOPT_TSTAMP;
21614 					wptr[3] = TCPOPT_TSTAMP_LEN;
21615 					wptr += 4;
21616 					U32_TO_BE32(llbolt, wptr);
21617 					wptr += 4;
21618 					ASSERT(tcp->tcp_ts_recent == 0);
21619 					U32_TO_BE32(0L, wptr);
21620 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
21621 					tcph->th_offset_and_rsrvd[0] +=
21622 					    (3 << 4);
21623 				}
21624 
21625 				/*
21626 				 * Set up all the bits to tell other side
21627 				 * we are ECN capable.
21628 				 */
21629 				if (tcp->tcp_ecn_ok) {
21630 					flags |= (TH_ECE | TH_CWR);
21631 				}
21632 				break;
21633 			case TCPS_SYN_RCVD:
21634 				flags |= TH_SYN;
21635 
21636 				/*
21637 				 * Reset the MSS option value to be SMSS
21638 				 * We should probably add back the bytes
21639 				 * for timestamp option and IPsec.  We
21640 				 * don't do that as this is a workaround
21641 				 * for broken middle boxes/end hosts, it
21642 				 * is better for us to be more cautious.
21643 				 * They may not take these things into
21644 				 * account in their SMSS calculation.  Thus
21645 				 * the peer's calculated SMSS may be smaller
21646 				 * than what it can be.  This should be OK.
21647 				 */
21648 				if (tcp_use_smss_as_mss_opt) {
21649 					u1 = tcp->tcp_mss;
21650 					U16_TO_BE16(u1, wptr);
21651 				}
21652 
21653 				/*
21654 				 * If the other side is ECN capable, reply
21655 				 * that we are also ECN capable.
21656 				 */
21657 				if (tcp->tcp_ecn_ok)
21658 					flags |= TH_ECE;
21659 				break;
21660 			default:
21661 				/*
21662 				 * The above ASSERT() makes sure that this
21663 				 * must be FIN-WAIT-1 state.  Our SYN has
21664 				 * not been ack'ed so retransmit it.
21665 				 */
21666 				flags |= TH_SYN;
21667 				break;
21668 			}
21669 
21670 			if (tcp->tcp_snd_ws_ok) {
21671 				wptr = mp1->b_wptr;
21672 				wptr[0] =  TCPOPT_NOP;
21673 				wptr[1] =  TCPOPT_WSCALE;
21674 				wptr[2] =  TCPOPT_WS_LEN;
21675 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
21676 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
21677 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
21678 			}
21679 
21680 			if (tcp->tcp_snd_sack_ok) {
21681 				wptr = mp1->b_wptr;
21682 				wptr[0] = TCPOPT_NOP;
21683 				wptr[1] = TCPOPT_NOP;
21684 				wptr[2] = TCPOPT_SACK_PERMITTED;
21685 				wptr[3] = TCPOPT_SACK_OK_LEN;
21686 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
21687 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
21688 			}
21689 
21690 			/* allocb() of adequate mblk assures space */
21691 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
21692 			    (uintptr_t)INT_MAX);
21693 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
21694 			/*
21695 			 * Get IP set to checksum on our behalf
21696 			 * Include the adjustment for a source route if any.
21697 			 */
21698 			u1 += tcp->tcp_sum;
21699 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
21700 			U16_TO_BE16(u1, tcph->th_sum);
21701 			BUMP_MIB(&tcp_mib, tcpOutControl);
21702 		}
21703 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
21704 		    (seq + data_length) == tcp->tcp_fss) {
21705 			if (!tcp->tcp_fin_acked) {
21706 				flags |= TH_FIN;
21707 				BUMP_MIB(&tcp_mib, tcpOutControl);
21708 			}
21709 			if (!tcp->tcp_fin_sent) {
21710 				tcp->tcp_fin_sent = B_TRUE;
21711 				switch (tcp->tcp_state) {
21712 				case TCPS_SYN_RCVD:
21713 				case TCPS_ESTABLISHED:
21714 					tcp->tcp_state = TCPS_FIN_WAIT_1;
21715 					break;
21716 				case TCPS_CLOSE_WAIT:
21717 					tcp->tcp_state = TCPS_LAST_ACK;
21718 					break;
21719 				}
21720 				if (tcp->tcp_suna == tcp->tcp_snxt)
21721 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21722 				tcp->tcp_snxt = tcp->tcp_fss + 1;
21723 			}
21724 		}
21725 		/*
21726 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
21727 		 * is smaller than seq, u1 will become a very huge value.
21728 		 * So the comparison will fail.  Also note that tcp_urp
21729 		 * should be positive, see RFC 793 page 17.
21730 		 */
21731 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
21732 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
21733 		    u1 < (uint32_t)(64 * 1024)) {
21734 			flags |= TH_URG;
21735 			BUMP_MIB(&tcp_mib, tcpOutUrg);
21736 			U32_TO_ABE16(u1, tcph->th_urp);
21737 		}
21738 	}
21739 	tcph->th_flags[0] = (uchar_t)flags;
21740 	tcp->tcp_rack = tcp->tcp_rnxt;
21741 	tcp->tcp_rack_cnt = 0;
21742 
21743 	if (tcp->tcp_snd_ts_ok) {
21744 		if (tcp->tcp_state != TCPS_SYN_SENT) {
21745 			uint32_t llbolt = (uint32_t)lbolt;
21746 
21747 			U32_TO_BE32(llbolt,
21748 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21749 			U32_TO_BE32(tcp->tcp_ts_recent,
21750 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21751 		}
21752 	}
21753 
21754 	if (num_sack_blk > 0) {
21755 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
21756 		sack_blk_t *tmp;
21757 		int32_t	i;
21758 
21759 		wptr[0] = TCPOPT_NOP;
21760 		wptr[1] = TCPOPT_NOP;
21761 		wptr[2] = TCPOPT_SACK;
21762 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
21763 		    sizeof (sack_blk_t);
21764 		wptr += TCPOPT_REAL_SACK_LEN;
21765 
21766 		tmp = tcp->tcp_sack_list;
21767 		for (i = 0; i < num_sack_blk; i++) {
21768 			U32_TO_BE32(tmp[i].begin, wptr);
21769 			wptr += sizeof (tcp_seq);
21770 			U32_TO_BE32(tmp[i].end, wptr);
21771 			wptr += sizeof (tcp_seq);
21772 		}
21773 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
21774 	}
21775 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21776 	data_length += (int)(mp1->b_wptr - rptr);
21777 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21778 		((ipha_t *)rptr)->ipha_length = htons(data_length);
21779 	} else {
21780 		ip6_t *ip6 = (ip6_t *)(rptr +
21781 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
21782 		    sizeof (ip6i_t) : 0));
21783 
21784 		ip6->ip6_plen = htons(data_length -
21785 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21786 	}
21787 
21788 	/*
21789 	 * Prime pump for IP
21790 	 * Include the adjustment for a source route if any.
21791 	 */
21792 	data_length -= tcp->tcp_ip_hdr_len;
21793 	data_length += tcp->tcp_sum;
21794 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
21795 	U16_TO_ABE16(data_length, tcph->th_sum);
21796 	if (tcp->tcp_ip_forward_progress) {
21797 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21798 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
21799 		tcp->tcp_ip_forward_progress = B_FALSE;
21800 	}
21801 	return (mp1);
21802 }
21803 
21804 /* This function handles the push timeout. */
21805 void
21806 tcp_push_timer(void *arg)
21807 {
21808 	conn_t	*connp = (conn_t *)arg;
21809 	tcp_t *tcp = connp->conn_tcp;
21810 
21811 	TCP_DBGSTAT(tcp_push_timer_cnt);
21812 
21813 	ASSERT(tcp->tcp_listener == NULL);
21814 
21815 	/*
21816 	 * We need to stop synchronous streams temporarily to prevent a race
21817 	 * with tcp_fuse_rrw() or tcp_fusion rinfop().  It is safe to access
21818 	 * tcp_rcv_list here because those entry points will return right
21819 	 * away when synchronous streams is stopped.
21820 	 */
21821 	TCP_FUSE_SYNCSTR_STOP(tcp);
21822 	tcp->tcp_push_tid = 0;
21823 	if ((tcp->tcp_rcv_list != NULL) &&
21824 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
21825 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21826 	TCP_FUSE_SYNCSTR_RESUME(tcp);
21827 }
21828 
21829 /*
21830  * This function handles delayed ACK timeout.
21831  */
21832 static void
21833 tcp_ack_timer(void *arg)
21834 {
21835 	conn_t	*connp = (conn_t *)arg;
21836 	tcp_t *tcp = connp->conn_tcp;
21837 	mblk_t *mp;
21838 
21839 	TCP_DBGSTAT(tcp_ack_timer_cnt);
21840 
21841 	tcp->tcp_ack_tid = 0;
21842 
21843 	if (tcp->tcp_fused)
21844 		return;
21845 
21846 	/*
21847 	 * Do not send ACK if there is no outstanding unack'ed data.
21848 	 */
21849 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
21850 		return;
21851 	}
21852 
21853 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
21854 		/*
21855 		 * Make sure we don't allow deferred ACKs to result in
21856 		 * timer-based ACKing.  If we have held off an ACK
21857 		 * when there was more than an mss here, and the timer
21858 		 * goes off, we have to worry about the possibility
21859 		 * that the sender isn't doing slow-start, or is out
21860 		 * of step with us for some other reason.  We fall
21861 		 * permanently back in the direction of
21862 		 * ACK-every-other-packet as suggested in RFC 1122.
21863 		 */
21864 		if (tcp->tcp_rack_abs_max > 2)
21865 			tcp->tcp_rack_abs_max--;
21866 		tcp->tcp_rack_cur_max = 2;
21867 	}
21868 	mp = tcp_ack_mp(tcp);
21869 
21870 	if (mp != NULL) {
21871 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21872 		BUMP_LOCAL(tcp->tcp_obsegs);
21873 		BUMP_MIB(&tcp_mib, tcpOutAck);
21874 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
21875 		tcp_send_data(tcp, tcp->tcp_wq, mp);
21876 	}
21877 }
21878 
21879 
21880 /* Generate an ACK-only (no data) segment for a TCP endpoint */
21881 static mblk_t *
21882 tcp_ack_mp(tcp_t *tcp)
21883 {
21884 	uint32_t	seq_no;
21885 
21886 	/*
21887 	 * There are a few cases to be considered while setting the sequence no.
21888 	 * Essentially, we can come here while processing an unacceptable pkt
21889 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
21890 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
21891 	 * If we are here for a zero window probe, stick with suna. In all
21892 	 * other cases, we check if suna + swnd encompasses snxt and set
21893 	 * the sequence number to snxt, if so. If snxt falls outside the
21894 	 * window (the receiver probably shrunk its window), we will go with
21895 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
21896 	 * receiver.
21897 	 */
21898 	if (tcp->tcp_zero_win_probe) {
21899 		seq_no = tcp->tcp_suna;
21900 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
21901 		ASSERT(tcp->tcp_swnd == 0);
21902 		seq_no = tcp->tcp_snxt;
21903 	} else {
21904 		seq_no = SEQ_GT(tcp->tcp_snxt,
21905 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
21906 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
21907 	}
21908 
21909 	if (tcp->tcp_valid_bits) {
21910 		/*
21911 		 * For the complex case where we have to send some
21912 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
21913 		 */
21914 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
21915 		    NULL, B_FALSE));
21916 	} else {
21917 		/* Generate a simple ACK */
21918 		int	data_length;
21919 		uchar_t	*rptr;
21920 		tcph_t	*tcph;
21921 		mblk_t	*mp1;
21922 		int32_t	tcp_hdr_len;
21923 		int32_t	tcp_tcp_hdr_len;
21924 		int32_t	num_sack_blk = 0;
21925 		int32_t sack_opt_len;
21926 
21927 		/*
21928 		 * Allocate space for TCP + IP headers
21929 		 * and link-level header
21930 		 */
21931 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21932 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21933 			    tcp->tcp_num_sack_blk);
21934 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21935 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21936 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
21937 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
21938 		} else {
21939 			tcp_hdr_len = tcp->tcp_hdr_len;
21940 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
21941 		}
21942 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
21943 		if (!mp1)
21944 			return (NULL);
21945 
21946 		/* Update the latest receive window size in TCP header. */
21947 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21948 		    tcp->tcp_tcph->th_win);
21949 		/* copy in prototype TCP + IP header */
21950 		rptr = mp1->b_rptr + tcp_wroff_xtra;
21951 		mp1->b_rptr = rptr;
21952 		mp1->b_wptr = rptr + tcp_hdr_len;
21953 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21954 
21955 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21956 
21957 		/* Set the TCP sequence number. */
21958 		U32_TO_ABE32(seq_no, tcph->th_seq);
21959 
21960 		/* Set up the TCP flag field. */
21961 		tcph->th_flags[0] = (uchar_t)TH_ACK;
21962 		if (tcp->tcp_ecn_echo_on)
21963 			tcph->th_flags[0] |= TH_ECE;
21964 
21965 		tcp->tcp_rack = tcp->tcp_rnxt;
21966 		tcp->tcp_rack_cnt = 0;
21967 
21968 		/* fill in timestamp option if in use */
21969 		if (tcp->tcp_snd_ts_ok) {
21970 			uint32_t llbolt = (uint32_t)lbolt;
21971 
21972 			U32_TO_BE32(llbolt,
21973 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21974 			U32_TO_BE32(tcp->tcp_ts_recent,
21975 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21976 		}
21977 
21978 		/* Fill in SACK options */
21979 		if (num_sack_blk > 0) {
21980 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
21981 			sack_blk_t *tmp;
21982 			int32_t	i;
21983 
21984 			wptr[0] = TCPOPT_NOP;
21985 			wptr[1] = TCPOPT_NOP;
21986 			wptr[2] = TCPOPT_SACK;
21987 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
21988 			    sizeof (sack_blk_t);
21989 			wptr += TCPOPT_REAL_SACK_LEN;
21990 
21991 			tmp = tcp->tcp_sack_list;
21992 			for (i = 0; i < num_sack_blk; i++) {
21993 				U32_TO_BE32(tmp[i].begin, wptr);
21994 				wptr += sizeof (tcp_seq);
21995 				U32_TO_BE32(tmp[i].end, wptr);
21996 				wptr += sizeof (tcp_seq);
21997 			}
21998 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
21999 			    << 4);
22000 		}
22001 
22002 		if (tcp->tcp_ipversion == IPV4_VERSION) {
22003 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
22004 		} else {
22005 			/* Check for ip6i_t header in sticky hdrs */
22006 			ip6_t *ip6 = (ip6_t *)(rptr +
22007 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22008 			    sizeof (ip6i_t) : 0));
22009 
22010 			ip6->ip6_plen = htons(tcp_hdr_len -
22011 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22012 		}
22013 
22014 		/*
22015 		 * Prime pump for checksum calculation in IP.  Include the
22016 		 * adjustment for a source route if any.
22017 		 */
22018 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
22019 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
22020 		U16_TO_ABE16(data_length, tcph->th_sum);
22021 
22022 		if (tcp->tcp_ip_forward_progress) {
22023 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22024 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22025 			tcp->tcp_ip_forward_progress = B_FALSE;
22026 		}
22027 		return (mp1);
22028 	}
22029 }
22030 
22031 /*
22032  * To create a temporary tcp structure for inserting into bind hash list.
22033  * The parameter is assumed to be in network byte order, ready for use.
22034  */
22035 /* ARGSUSED */
22036 static tcp_t *
22037 tcp_alloc_temp_tcp(in_port_t port)
22038 {
22039 	conn_t	*connp;
22040 	tcp_t	*tcp;
22041 
22042 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
22043 	if (connp == NULL)
22044 		return (NULL);
22045 
22046 	tcp = connp->conn_tcp;
22047 
22048 	/*
22049 	 * Only initialize the necessary info in those structures.  Note
22050 	 * that since INADDR_ANY is all 0, we do not need to set
22051 	 * tcp_bound_source to INADDR_ANY here.
22052 	 */
22053 	tcp->tcp_state = TCPS_BOUND;
22054 	tcp->tcp_lport = port;
22055 	tcp->tcp_exclbind = 1;
22056 	tcp->tcp_reserved_port = 1;
22057 
22058 	/* Just for place holding... */
22059 	tcp->tcp_ipversion = IPV4_VERSION;
22060 
22061 	return (tcp);
22062 }
22063 
22064 /*
22065  * To remove a port range specified by lo_port and hi_port from the
22066  * reserved port ranges.  This is one of the three public functions of
22067  * the reserved port interface.  Note that a port range has to be removed
22068  * as a whole.  Ports in a range cannot be removed individually.
22069  *
22070  * Params:
22071  *	in_port_t lo_port: the beginning port of the reserved port range to
22072  *		be deleted.
22073  *	in_port_t hi_port: the ending port of the reserved port range to
22074  *		be deleted.
22075  *
22076  * Return:
22077  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
22078  */
22079 boolean_t
22080 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
22081 {
22082 	int	i, j;
22083 	int	size;
22084 	tcp_t	**temp_tcp_array;
22085 	tcp_t	*tcp;
22086 
22087 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22088 
22089 	/* First make sure that the port ranage is indeed reserved. */
22090 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22091 		if (tcp_reserved_port[i].lo_port == lo_port) {
22092 			hi_port = tcp_reserved_port[i].hi_port;
22093 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
22094 			break;
22095 		}
22096 	}
22097 	if (i == tcp_reserved_port_array_size) {
22098 		rw_exit(&tcp_reserved_port_lock);
22099 		return (B_FALSE);
22100 	}
22101 
22102 	/*
22103 	 * Remove the range from the array.  This simple loop is possible
22104 	 * because port ranges are inserted in ascending order.
22105 	 */
22106 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
22107 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
22108 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
22109 		tcp_reserved_port[j].temp_tcp_array =
22110 		    tcp_reserved_port[j+1].temp_tcp_array;
22111 	}
22112 
22113 	/* Remove all the temporary tcp structures. */
22114 	size = hi_port - lo_port + 1;
22115 	while (size > 0) {
22116 		tcp = temp_tcp_array[size - 1];
22117 		ASSERT(tcp != NULL);
22118 		tcp_bind_hash_remove(tcp);
22119 		CONN_DEC_REF(tcp->tcp_connp);
22120 		size--;
22121 	}
22122 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
22123 	tcp_reserved_port_array_size--;
22124 	rw_exit(&tcp_reserved_port_lock);
22125 	return (B_TRUE);
22126 }
22127 
22128 /*
22129  * Macro to remove temporary tcp structure from the bind hash list.  The
22130  * first parameter is the list of tcp to be removed.  The second parameter
22131  * is the number of tcps in the array.
22132  */
22133 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
22134 { \
22135 	while ((num) > 0) { \
22136 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
22137 		tf_t *tbf; \
22138 		tcp_t *tcpnext; \
22139 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
22140 		mutex_enter(&tbf->tf_lock); \
22141 		tcpnext = tcp->tcp_bind_hash; \
22142 		if (tcpnext) { \
22143 			tcpnext->tcp_ptpbhn = \
22144 				tcp->tcp_ptpbhn; \
22145 		} \
22146 		*tcp->tcp_ptpbhn = tcpnext; \
22147 		mutex_exit(&tbf->tf_lock); \
22148 		kmem_free(tcp, sizeof (tcp_t)); \
22149 		(tcp_array)[(num) - 1] = NULL; \
22150 		(num)--; \
22151 	} \
22152 }
22153 
22154 /*
22155  * The public interface for other modules to call to reserve a port range
22156  * in TCP.  The caller passes in how large a port range it wants.  TCP
22157  * will try to find a range and return it via lo_port and hi_port.  This is
22158  * used by NCA's nca_conn_init.
22159  * NCA can only be used in the global zone so this only affects the global
22160  * zone's ports.
22161  *
22162  * Params:
22163  *	int size: the size of the port range to be reserved.
22164  *	in_port_t *lo_port (referenced): returns the beginning port of the
22165  *		reserved port range added.
22166  *	in_port_t *hi_port (referenced): returns the ending port of the
22167  *		reserved port range added.
22168  *
22169  * Return:
22170  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22171  */
22172 boolean_t
22173 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22174 {
22175 	tcp_t		*tcp;
22176 	tcp_t		*tmp_tcp;
22177 	tcp_t		**temp_tcp_array;
22178 	tf_t		*tbf;
22179 	in_port_t	net_port;
22180 	in_port_t	port;
22181 	int32_t		cur_size;
22182 	int		i, j;
22183 	boolean_t	used;
22184 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22185 	zoneid_t	zoneid = GLOBAL_ZONEID;
22186 
22187 	/* Sanity check. */
22188 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22189 		return (B_FALSE);
22190 	}
22191 
22192 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22193 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22194 		rw_exit(&tcp_reserved_port_lock);
22195 		return (B_FALSE);
22196 	}
22197 
22198 	/*
22199 	 * Find the starting port to try.  Since the port ranges are ordered
22200 	 * in the reserved port array, we can do a simple search here.
22201 	 */
22202 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22203 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22204 	for (i = 0; i < tcp_reserved_port_array_size;
22205 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22206 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22207 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22208 			break;
22209 		}
22210 	}
22211 	/* No available port range. */
22212 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22213 		rw_exit(&tcp_reserved_port_lock);
22214 		return (B_FALSE);
22215 	}
22216 
22217 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22218 	if (temp_tcp_array == NULL) {
22219 		rw_exit(&tcp_reserved_port_lock);
22220 		return (B_FALSE);
22221 	}
22222 
22223 	/* Go thru the port range to see if some ports are already bound. */
22224 	for (port = *lo_port, cur_size = 0;
22225 	    cur_size < size && port <= *hi_port;
22226 	    cur_size++, port++) {
22227 		used = B_FALSE;
22228 		net_port = htons(port);
22229 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22230 		mutex_enter(&tbf->tf_lock);
22231 		for (tcp = tbf->tf_tcp; tcp != NULL;
22232 		    tcp = tcp->tcp_bind_hash) {
22233 			if (zoneid == tcp->tcp_connp->conn_zoneid &&
22234 			    net_port == tcp->tcp_lport) {
22235 				/*
22236 				 * A port is already bound.  Search again
22237 				 * starting from port + 1.  Release all
22238 				 * temporary tcps.
22239 				 */
22240 				mutex_exit(&tbf->tf_lock);
22241 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22242 				*lo_port = port + 1;
22243 				cur_size = -1;
22244 				used = B_TRUE;
22245 				break;
22246 			}
22247 		}
22248 		if (!used) {
22249 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22250 				/*
22251 				 * Allocation failure.  Just fail the request.
22252 				 * Need to remove all those temporary tcp
22253 				 * structures.
22254 				 */
22255 				mutex_exit(&tbf->tf_lock);
22256 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22257 				rw_exit(&tcp_reserved_port_lock);
22258 				kmem_free(temp_tcp_array,
22259 				    (hi_port - lo_port + 1) *
22260 				    sizeof (tcp_t *));
22261 				return (B_FALSE);
22262 			}
22263 			temp_tcp_array[cur_size] = tmp_tcp;
22264 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22265 			mutex_exit(&tbf->tf_lock);
22266 		}
22267 	}
22268 
22269 	/*
22270 	 * The current range is not large enough.  We can actually do another
22271 	 * search if this search is done between 2 reserved port ranges.  But
22272 	 * for first release, we just stop here and return saying that no port
22273 	 * range is available.
22274 	 */
22275 	if (cur_size < size) {
22276 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22277 		rw_exit(&tcp_reserved_port_lock);
22278 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
22279 		return (B_FALSE);
22280 	}
22281 	*hi_port = port - 1;
22282 
22283 	/*
22284 	 * Insert range into array in ascending order.  Since this function
22285 	 * must not be called often, we choose to use the simplest method.
22286 	 * The above array should not consume excessive stack space as
22287 	 * the size must be very small.  If in future releases, we find
22288 	 * that we should provide more reserved port ranges, this function
22289 	 * has to be modified to be more efficient.
22290 	 */
22291 	if (tcp_reserved_port_array_size == 0) {
22292 		tcp_reserved_port[0].lo_port = *lo_port;
22293 		tcp_reserved_port[0].hi_port = *hi_port;
22294 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
22295 	} else {
22296 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
22297 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
22298 				tmp_ports[j].lo_port = *lo_port;
22299 				tmp_ports[j].hi_port = *hi_port;
22300 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
22301 				j++;
22302 			}
22303 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
22304 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
22305 			tmp_ports[j].temp_tcp_array =
22306 			    tcp_reserved_port[i].temp_tcp_array;
22307 		}
22308 		if (j == i) {
22309 			tmp_ports[j].lo_port = *lo_port;
22310 			tmp_ports[j].hi_port = *hi_port;
22311 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
22312 		}
22313 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
22314 	}
22315 	tcp_reserved_port_array_size++;
22316 	rw_exit(&tcp_reserved_port_lock);
22317 	return (B_TRUE);
22318 }
22319 
22320 /*
22321  * Check to see if a port is in any reserved port range.
22322  *
22323  * Params:
22324  *	in_port_t port: the port to be verified.
22325  *
22326  * Return:
22327  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
22328  */
22329 boolean_t
22330 tcp_reserved_port_check(in_port_t port)
22331 {
22332 	int i;
22333 
22334 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22335 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22336 		if (port >= tcp_reserved_port[i].lo_port ||
22337 		    port <= tcp_reserved_port[i].hi_port) {
22338 			rw_exit(&tcp_reserved_port_lock);
22339 			return (B_TRUE);
22340 		}
22341 	}
22342 	rw_exit(&tcp_reserved_port_lock);
22343 	return (B_FALSE);
22344 }
22345 
22346 /*
22347  * To list all reserved port ranges.  This is the function to handle
22348  * ndd tcp_reserved_port_list.
22349  */
22350 /* ARGSUSED */
22351 static int
22352 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22353 {
22354 	int i;
22355 
22356 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22357 	if (tcp_reserved_port_array_size > 0)
22358 		(void) mi_mpprintf(mp, "The following ports are reserved:");
22359 	else
22360 		(void) mi_mpprintf(mp, "No port is reserved.");
22361 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22362 		(void) mi_mpprintf(mp, "%d-%d",
22363 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
22364 	}
22365 	rw_exit(&tcp_reserved_port_lock);
22366 	return (0);
22367 }
22368 
22369 /*
22370  * Hash list insertion routine for tcp_t structures.
22371  * Inserts entries with the ones bound to a specific IP address first
22372  * followed by those bound to INADDR_ANY.
22373  */
22374 static void
22375 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
22376 {
22377 	tcp_t	**tcpp;
22378 	tcp_t	*tcpnext;
22379 
22380 	if (tcp->tcp_ptpbhn != NULL) {
22381 		ASSERT(!caller_holds_lock);
22382 		tcp_bind_hash_remove(tcp);
22383 	}
22384 	tcpp = &tbf->tf_tcp;
22385 	if (!caller_holds_lock) {
22386 		mutex_enter(&tbf->tf_lock);
22387 	} else {
22388 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
22389 	}
22390 	tcpnext = tcpp[0];
22391 	if (tcpnext) {
22392 		/*
22393 		 * If the new tcp bound to the INADDR_ANY address
22394 		 * and the first one in the list is not bound to
22395 		 * INADDR_ANY we skip all entries until we find the
22396 		 * first one bound to INADDR_ANY.
22397 		 * This makes sure that applications binding to a
22398 		 * specific address get preference over those binding to
22399 		 * INADDR_ANY.
22400 		 */
22401 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
22402 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
22403 			while ((tcpnext = tcpp[0]) != NULL &&
22404 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
22405 				tcpp = &(tcpnext->tcp_bind_hash);
22406 			if (tcpnext)
22407 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22408 		} else
22409 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22410 	}
22411 	tcp->tcp_bind_hash = tcpnext;
22412 	tcp->tcp_ptpbhn = tcpp;
22413 	tcpp[0] = tcp;
22414 	if (!caller_holds_lock)
22415 		mutex_exit(&tbf->tf_lock);
22416 }
22417 
22418 /*
22419  * Hash list removal routine for tcp_t structures.
22420  */
22421 static void
22422 tcp_bind_hash_remove(tcp_t *tcp)
22423 {
22424 	tcp_t	*tcpnext;
22425 	kmutex_t *lockp;
22426 
22427 	if (tcp->tcp_ptpbhn == NULL)
22428 		return;
22429 
22430 	/*
22431 	 * Extract the lock pointer in case there are concurrent
22432 	 * hash_remove's for this instance.
22433 	 */
22434 	ASSERT(tcp->tcp_lport != 0);
22435 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
22436 
22437 	ASSERT(lockp != NULL);
22438 	mutex_enter(lockp);
22439 	if (tcp->tcp_ptpbhn) {
22440 		tcpnext = tcp->tcp_bind_hash;
22441 		if (tcpnext) {
22442 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
22443 			tcp->tcp_bind_hash = NULL;
22444 		}
22445 		*tcp->tcp_ptpbhn = tcpnext;
22446 		tcp->tcp_ptpbhn = NULL;
22447 	}
22448 	mutex_exit(lockp);
22449 }
22450 
22451 
22452 /*
22453  * Hash list lookup routine for tcp_t structures.
22454  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
22455  */
22456 static tcp_t *
22457 tcp_acceptor_hash_lookup(t_uscalar_t id)
22458 {
22459 	tf_t	*tf;
22460 	tcp_t	*tcp;
22461 
22462 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22463 	mutex_enter(&tf->tf_lock);
22464 	for (tcp = tf->tf_tcp; tcp != NULL;
22465 	    tcp = tcp->tcp_acceptor_hash) {
22466 		if (tcp->tcp_acceptor_id == id) {
22467 			CONN_INC_REF(tcp->tcp_connp);
22468 			mutex_exit(&tf->tf_lock);
22469 			return (tcp);
22470 		}
22471 	}
22472 	mutex_exit(&tf->tf_lock);
22473 	return (NULL);
22474 }
22475 
22476 
22477 /*
22478  * Hash list insertion routine for tcp_t structures.
22479  */
22480 void
22481 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
22482 {
22483 	tf_t	*tf;
22484 	tcp_t	**tcpp;
22485 	tcp_t	*tcpnext;
22486 
22487 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22488 
22489 	if (tcp->tcp_ptpahn != NULL)
22490 		tcp_acceptor_hash_remove(tcp);
22491 	tcpp = &tf->tf_tcp;
22492 	mutex_enter(&tf->tf_lock);
22493 	tcpnext = tcpp[0];
22494 	if (tcpnext)
22495 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
22496 	tcp->tcp_acceptor_hash = tcpnext;
22497 	tcp->tcp_ptpahn = tcpp;
22498 	tcpp[0] = tcp;
22499 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
22500 	mutex_exit(&tf->tf_lock);
22501 }
22502 
22503 /*
22504  * Hash list removal routine for tcp_t structures.
22505  */
22506 static void
22507 tcp_acceptor_hash_remove(tcp_t *tcp)
22508 {
22509 	tcp_t	*tcpnext;
22510 	kmutex_t *lockp;
22511 
22512 	/*
22513 	 * Extract the lock pointer in case there are concurrent
22514 	 * hash_remove's for this instance.
22515 	 */
22516 	lockp = tcp->tcp_acceptor_lockp;
22517 
22518 	if (tcp->tcp_ptpahn == NULL)
22519 		return;
22520 
22521 	ASSERT(lockp != NULL);
22522 	mutex_enter(lockp);
22523 	if (tcp->tcp_ptpahn) {
22524 		tcpnext = tcp->tcp_acceptor_hash;
22525 		if (tcpnext) {
22526 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
22527 			tcp->tcp_acceptor_hash = NULL;
22528 		}
22529 		*tcp->tcp_ptpahn = tcpnext;
22530 		tcp->tcp_ptpahn = NULL;
22531 	}
22532 	mutex_exit(lockp);
22533 	tcp->tcp_acceptor_lockp = NULL;
22534 }
22535 
22536 /* ARGSUSED */
22537 static int
22538 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
22539 {
22540 	int error = 0;
22541 	int retval;
22542 	char *end;
22543 
22544 	tcp_hsp_t *hsp;
22545 	tcp_hsp_t *hspprev;
22546 
22547 	ipaddr_t addr = 0;		/* Address we're looking for */
22548 	in6_addr_t v6addr;		/* Address we're looking for */
22549 	uint32_t hash;			/* Hash of that address */
22550 
22551 	/*
22552 	 * If the following variables are still zero after parsing the input
22553 	 * string, the user didn't specify them and we don't change them in
22554 	 * the HSP.
22555 	 */
22556 
22557 	ipaddr_t mask = 0;		/* Subnet mask */
22558 	in6_addr_t v6mask;
22559 	long sendspace = 0;		/* Send buffer size */
22560 	long recvspace = 0;		/* Receive buffer size */
22561 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
22562 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
22563 
22564 	rw_enter(&tcp_hsp_lock, RW_WRITER);
22565 
22566 	/* Parse and validate address */
22567 	if (af == AF_INET) {
22568 		retval = inet_pton(af, value, &addr);
22569 		if (retval == 1)
22570 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
22571 	} else if (af == AF_INET6) {
22572 		retval = inet_pton(af, value, &v6addr);
22573 	} else {
22574 		error = EINVAL;
22575 		goto done;
22576 	}
22577 	if (retval == 0) {
22578 		error = EINVAL;
22579 		goto done;
22580 	}
22581 
22582 	while ((*value) && *value != ' ')
22583 		value++;
22584 
22585 	/* Parse individual keywords, set variables if found */
22586 	while (*value) {
22587 		/* Skip leading blanks */
22588 
22589 		while (*value == ' ' || *value == '\t')
22590 			value++;
22591 
22592 		/* If at end of string, we're done */
22593 
22594 		if (!*value)
22595 			break;
22596 
22597 		/* We have a word, figure out what it is */
22598 
22599 		if (strncmp("mask", value, 4) == 0) {
22600 			value += 4;
22601 			while (*value == ' ' || *value == '\t')
22602 				value++;
22603 			/* Parse subnet mask */
22604 			if (af == AF_INET) {
22605 				retval = inet_pton(af, value, &mask);
22606 				if (retval == 1) {
22607 					V4MASK_TO_V6(mask, v6mask);
22608 				}
22609 			} else if (af == AF_INET6) {
22610 				retval = inet_pton(af, value, &v6mask);
22611 			}
22612 			if (retval != 1) {
22613 				error = EINVAL;
22614 				goto done;
22615 			}
22616 			while ((*value) && *value != ' ')
22617 				value++;
22618 		} else if (strncmp("sendspace", value, 9) == 0) {
22619 			value += 9;
22620 
22621 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
22622 			    sendspace < TCP_XMIT_HIWATER ||
22623 			    sendspace >= (1L<<30)) {
22624 				error = EINVAL;
22625 				goto done;
22626 			}
22627 			value = end;
22628 		} else if (strncmp("recvspace", value, 9) == 0) {
22629 			value += 9;
22630 
22631 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
22632 			    recvspace < TCP_RECV_HIWATER ||
22633 			    recvspace >= (1L<<30)) {
22634 				error = EINVAL;
22635 				goto done;
22636 			}
22637 			value = end;
22638 		} else if (strncmp("timestamp", value, 9) == 0) {
22639 			value += 9;
22640 
22641 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
22642 			    timestamp < 0 || timestamp > 1) {
22643 				error = EINVAL;
22644 				goto done;
22645 			}
22646 
22647 			/*
22648 			 * We increment timestamp so we know it's been set;
22649 			 * this is undone when we put it in the HSP
22650 			 */
22651 			timestamp++;
22652 			value = end;
22653 		} else if (strncmp("delete", value, 6) == 0) {
22654 			value += 6;
22655 			delete = B_TRUE;
22656 		} else {
22657 			error = EINVAL;
22658 			goto done;
22659 		}
22660 	}
22661 
22662 	/* Hash address for lookup */
22663 
22664 	hash = TCP_HSP_HASH(addr);
22665 
22666 	if (delete) {
22667 		/*
22668 		 * Note that deletes don't return an error if the thing
22669 		 * we're trying to delete isn't there.
22670 		 */
22671 		if (tcp_hsp_hash == NULL)
22672 			goto done;
22673 		hsp = tcp_hsp_hash[hash];
22674 
22675 		if (hsp) {
22676 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
22677 			    &v6addr)) {
22678 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
22679 				mi_free((char *)hsp);
22680 			} else {
22681 				hspprev = hsp;
22682 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
22683 					if (IN6_ARE_ADDR_EQUAL(
22684 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
22685 						hspprev->tcp_hsp_next =
22686 						    hsp->tcp_hsp_next;
22687 						mi_free((char *)hsp);
22688 						break;
22689 					}
22690 					hspprev = hsp;
22691 				}
22692 			}
22693 		}
22694 	} else {
22695 		/*
22696 		 * We're adding/modifying an HSP.  If we haven't already done
22697 		 * so, allocate the hash table.
22698 		 */
22699 
22700 		if (!tcp_hsp_hash) {
22701 			tcp_hsp_hash = (tcp_hsp_t **)
22702 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
22703 			if (!tcp_hsp_hash) {
22704 				error = EINVAL;
22705 				goto done;
22706 			}
22707 		}
22708 
22709 		/* Get head of hash chain */
22710 
22711 		hsp = tcp_hsp_hash[hash];
22712 
22713 		/* Try to find pre-existing hsp on hash chain */
22714 		/* Doesn't handle CIDR prefixes. */
22715 		while (hsp) {
22716 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
22717 				break;
22718 			hsp = hsp->tcp_hsp_next;
22719 		}
22720 
22721 		/*
22722 		 * If we didn't, create one with default values and put it
22723 		 * at head of hash chain
22724 		 */
22725 
22726 		if (!hsp) {
22727 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
22728 			if (!hsp) {
22729 				error = EINVAL;
22730 				goto done;
22731 			}
22732 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
22733 			tcp_hsp_hash[hash] = hsp;
22734 		}
22735 
22736 		/* Set values that the user asked us to change */
22737 
22738 		hsp->tcp_hsp_addr_v6 = v6addr;
22739 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
22740 			hsp->tcp_hsp_vers = IPV4_VERSION;
22741 		else
22742 			hsp->tcp_hsp_vers = IPV6_VERSION;
22743 		hsp->tcp_hsp_subnet_v6 = v6mask;
22744 		if (sendspace > 0)
22745 			hsp->tcp_hsp_sendspace = sendspace;
22746 		if (recvspace > 0)
22747 			hsp->tcp_hsp_recvspace = recvspace;
22748 		if (timestamp > 0)
22749 			hsp->tcp_hsp_tstamp = timestamp - 1;
22750 	}
22751 
22752 done:
22753 	rw_exit(&tcp_hsp_lock);
22754 	return (error);
22755 }
22756 
22757 /* Set callback routine passed to nd_load by tcp_param_register. */
22758 /* ARGSUSED */
22759 static int
22760 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
22761 {
22762 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
22763 }
22764 /* ARGSUSED */
22765 static int
22766 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22767     cred_t *cr)
22768 {
22769 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
22770 }
22771 
22772 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
22773 /* ARGSUSED */
22774 static int
22775 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22776 {
22777 	tcp_hsp_t *hsp;
22778 	int i;
22779 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
22780 
22781 	rw_enter(&tcp_hsp_lock, RW_READER);
22782 	(void) mi_mpprintf(mp,
22783 	    "Hash HSP     " MI_COL_HDRPAD_STR
22784 	    "Address         Subnet Mask     Send       Receive    TStamp");
22785 	if (tcp_hsp_hash) {
22786 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
22787 			hsp = tcp_hsp_hash[i];
22788 			while (hsp) {
22789 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
22790 					(void) inet_ntop(AF_INET,
22791 					    &hsp->tcp_hsp_addr,
22792 					    addrbuf, sizeof (addrbuf));
22793 					(void) inet_ntop(AF_INET,
22794 					    &hsp->tcp_hsp_subnet,
22795 					    subnetbuf, sizeof (subnetbuf));
22796 				} else {
22797 					(void) inet_ntop(AF_INET6,
22798 					    &hsp->tcp_hsp_addr_v6,
22799 					    addrbuf, sizeof (addrbuf));
22800 					(void) inet_ntop(AF_INET6,
22801 					    &hsp->tcp_hsp_subnet_v6,
22802 					    subnetbuf, sizeof (subnetbuf));
22803 				}
22804 				(void) mi_mpprintf(mp,
22805 				    " %03d " MI_COL_PTRFMT_STR
22806 				    "%s %s %010d %010d      %d",
22807 				    i,
22808 				    (void *)hsp,
22809 				    addrbuf,
22810 				    subnetbuf,
22811 				    hsp->tcp_hsp_sendspace,
22812 				    hsp->tcp_hsp_recvspace,
22813 				    hsp->tcp_hsp_tstamp);
22814 
22815 				hsp = hsp->tcp_hsp_next;
22816 			}
22817 		}
22818 	}
22819 	rw_exit(&tcp_hsp_lock);
22820 	return (0);
22821 }
22822 
22823 
22824 /* Data for fast netmask macro used by tcp_hsp_lookup */
22825 
22826 static ipaddr_t netmasks[] = {
22827 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
22828 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
22829 };
22830 
22831 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
22832 
22833 /*
22834  * XXX This routine should go away and instead we should use the metrics
22835  * associated with the routes to determine the default sndspace and rcvspace.
22836  */
22837 static tcp_hsp_t *
22838 tcp_hsp_lookup(ipaddr_t addr)
22839 {
22840 	tcp_hsp_t *hsp = NULL;
22841 
22842 	/* Quick check without acquiring the lock. */
22843 	if (tcp_hsp_hash == NULL)
22844 		return (NULL);
22845 
22846 	rw_enter(&tcp_hsp_lock, RW_READER);
22847 
22848 	/* This routine finds the best-matching HSP for address addr. */
22849 
22850 	if (tcp_hsp_hash) {
22851 		int i;
22852 		ipaddr_t srchaddr;
22853 		tcp_hsp_t *hsp_net;
22854 
22855 		/* We do three passes: host, network, and subnet. */
22856 
22857 		srchaddr = addr;
22858 
22859 		for (i = 1; i <= 3; i++) {
22860 			/* Look for exact match on srchaddr */
22861 
22862 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
22863 			while (hsp) {
22864 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
22865 				    hsp->tcp_hsp_addr == srchaddr)
22866 					break;
22867 				hsp = hsp->tcp_hsp_next;
22868 			}
22869 			ASSERT(hsp == NULL ||
22870 			    hsp->tcp_hsp_vers == IPV4_VERSION);
22871 
22872 			/*
22873 			 * If this is the first pass:
22874 			 *   If we found a match, great, return it.
22875 			 *   If not, search for the network on the second pass.
22876 			 */
22877 
22878 			if (i == 1)
22879 				if (hsp)
22880 					break;
22881 				else
22882 				{
22883 					srchaddr = addr & netmask(addr);
22884 					continue;
22885 				}
22886 
22887 			/*
22888 			 * If this is the second pass:
22889 			 *   If we found a match, but there's a subnet mask,
22890 			 *    save the match but try again using the subnet
22891 			 *    mask on the third pass.
22892 			 *   Otherwise, return whatever we found.
22893 			 */
22894 
22895 			if (i == 2) {
22896 				if (hsp && hsp->tcp_hsp_subnet) {
22897 					hsp_net = hsp;
22898 					srchaddr = addr & hsp->tcp_hsp_subnet;
22899 					continue;
22900 				} else {
22901 					break;
22902 				}
22903 			}
22904 
22905 			/*
22906 			 * This must be the third pass.  If we didn't find
22907 			 * anything, return the saved network HSP instead.
22908 			 */
22909 
22910 			if (!hsp)
22911 				hsp = hsp_net;
22912 		}
22913 	}
22914 
22915 	rw_exit(&tcp_hsp_lock);
22916 	return (hsp);
22917 }
22918 
22919 /*
22920  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
22921  * match lookup.
22922  */
22923 static tcp_hsp_t *
22924 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
22925 {
22926 	tcp_hsp_t *hsp = NULL;
22927 
22928 	/* Quick check without acquiring the lock. */
22929 	if (tcp_hsp_hash == NULL)
22930 		return (NULL);
22931 
22932 	rw_enter(&tcp_hsp_lock, RW_READER);
22933 
22934 	/* This routine finds the best-matching HSP for address addr. */
22935 
22936 	if (tcp_hsp_hash) {
22937 		int i;
22938 		in6_addr_t v6srchaddr;
22939 		tcp_hsp_t *hsp_net;
22940 
22941 		/* We do three passes: host, network, and subnet. */
22942 
22943 		v6srchaddr = *v6addr;
22944 
22945 		for (i = 1; i <= 3; i++) {
22946 			/* Look for exact match on srchaddr */
22947 
22948 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
22949 			    V4_PART_OF_V6(v6srchaddr))];
22950 			while (hsp) {
22951 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
22952 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
22953 				    &v6srchaddr))
22954 					break;
22955 				hsp = hsp->tcp_hsp_next;
22956 			}
22957 
22958 			/*
22959 			 * If this is the first pass:
22960 			 *   If we found a match, great, return it.
22961 			 *   If not, search for the network on the second pass.
22962 			 */
22963 
22964 			if (i == 1)
22965 				if (hsp)
22966 					break;
22967 				else {
22968 					/* Assume a 64 bit mask */
22969 					v6srchaddr.s6_addr32[0] =
22970 					    v6addr->s6_addr32[0];
22971 					v6srchaddr.s6_addr32[1] =
22972 					    v6addr->s6_addr32[1];
22973 					v6srchaddr.s6_addr32[2] = 0;
22974 					v6srchaddr.s6_addr32[3] = 0;
22975 					continue;
22976 				}
22977 
22978 			/*
22979 			 * If this is the second pass:
22980 			 *   If we found a match, but there's a subnet mask,
22981 			 *    save the match but try again using the subnet
22982 			 *    mask on the third pass.
22983 			 *   Otherwise, return whatever we found.
22984 			 */
22985 
22986 			if (i == 2) {
22987 				ASSERT(hsp == NULL ||
22988 				    hsp->tcp_hsp_vers == IPV6_VERSION);
22989 				if (hsp &&
22990 				    !IN6_IS_ADDR_UNSPECIFIED(
22991 				    &hsp->tcp_hsp_subnet_v6)) {
22992 					hsp_net = hsp;
22993 					V6_MASK_COPY(*v6addr,
22994 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
22995 					continue;
22996 				} else {
22997 					break;
22998 				}
22999 			}
23000 
23001 			/*
23002 			 * This must be the third pass.  If we didn't find
23003 			 * anything, return the saved network HSP instead.
23004 			 */
23005 
23006 			if (!hsp)
23007 				hsp = hsp_net;
23008 		}
23009 	}
23010 
23011 	rw_exit(&tcp_hsp_lock);
23012 	return (hsp);
23013 }
23014 
23015 /*
23016  * Type three generator adapted from the random() function in 4.4 BSD:
23017  */
23018 
23019 /*
23020  * Copyright (c) 1983, 1993
23021  *	The Regents of the University of California.  All rights reserved.
23022  *
23023  * Redistribution and use in source and binary forms, with or without
23024  * modification, are permitted provided that the following conditions
23025  * are met:
23026  * 1. Redistributions of source code must retain the above copyright
23027  *    notice, this list of conditions and the following disclaimer.
23028  * 2. Redistributions in binary form must reproduce the above copyright
23029  *    notice, this list of conditions and the following disclaimer in the
23030  *    documentation and/or other materials provided with the distribution.
23031  * 3. All advertising materials mentioning features or use of this software
23032  *    must display the following acknowledgement:
23033  *	This product includes software developed by the University of
23034  *	California, Berkeley and its contributors.
23035  * 4. Neither the name of the University nor the names of its contributors
23036  *    may be used to endorse or promote products derived from this software
23037  *    without specific prior written permission.
23038  *
23039  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23040  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23041  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23042  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23043  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23044  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23045  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23046  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23047  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23048  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23049  * SUCH DAMAGE.
23050  */
23051 
23052 /* Type 3 -- x**31 + x**3 + 1 */
23053 #define	DEG_3		31
23054 #define	SEP_3		3
23055 
23056 
23057 /* Protected by tcp_random_lock */
23058 static int tcp_randtbl[DEG_3 + 1];
23059 
23060 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23061 static int *tcp_random_rptr = &tcp_randtbl[1];
23062 
23063 static int *tcp_random_state = &tcp_randtbl[1];
23064 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23065 
23066 kmutex_t tcp_random_lock;
23067 
23068 void
23069 tcp_random_init(void)
23070 {
23071 	int i;
23072 	hrtime_t hrt;
23073 	time_t wallclock;
23074 	uint64_t result;
23075 
23076 	/*
23077 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23078 	 * a longlong, which may contain resolution down to nanoseconds.
23079 	 * The current time will either be a 32-bit or a 64-bit quantity.
23080 	 * XOR the two together in a 64-bit result variable.
23081 	 * Convert the result to a 32-bit value by multiplying the high-order
23082 	 * 32-bits by the low-order 32-bits.
23083 	 */
23084 
23085 	hrt = gethrtime();
23086 	(void) drv_getparm(TIME, &wallclock);
23087 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23088 	mutex_enter(&tcp_random_lock);
23089 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23090 	    (result & 0xffffffff);
23091 
23092 	for (i = 1; i < DEG_3; i++)
23093 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23094 			+ 12345;
23095 	tcp_random_fptr = &tcp_random_state[SEP_3];
23096 	tcp_random_rptr = &tcp_random_state[0];
23097 	mutex_exit(&tcp_random_lock);
23098 	for (i = 0; i < 10 * DEG_3; i++)
23099 		(void) tcp_random();
23100 }
23101 
23102 /*
23103  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23104  * This range is selected to be approximately centered on TCP_ISS / 2,
23105  * and easy to compute. We get this value by generating a 32-bit random
23106  * number, selecting out the high-order 17 bits, and then adding one so
23107  * that we never return zero.
23108  */
23109 int
23110 tcp_random(void)
23111 {
23112 	int i;
23113 
23114 	mutex_enter(&tcp_random_lock);
23115 	*tcp_random_fptr += *tcp_random_rptr;
23116 
23117 	/*
23118 	 * The high-order bits are more random than the low-order bits,
23119 	 * so we select out the high-order 17 bits and add one so that
23120 	 * we never return zero.
23121 	 */
23122 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23123 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23124 		tcp_random_fptr = tcp_random_state;
23125 		++tcp_random_rptr;
23126 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23127 		tcp_random_rptr = tcp_random_state;
23128 
23129 	mutex_exit(&tcp_random_lock);
23130 	return (i);
23131 }
23132 
23133 /*
23134  * XXX This will go away when TPI is extended to send
23135  * info reqs to sockfs/timod .....
23136  * Given a queue, set the max packet size for the write
23137  * side of the queue below stream head.  This value is
23138  * cached on the stream head.
23139  * Returns 1 on success, 0 otherwise.
23140  */
23141 static int
23142 setmaxps(queue_t *q, int maxpsz)
23143 {
23144 	struct stdata	*stp;
23145 	queue_t		*wq;
23146 	stp = STREAM(q);
23147 
23148 	/*
23149 	 * At this point change of a queue parameter is not allowed
23150 	 * when a multiplexor is sitting on top.
23151 	 */
23152 	if (stp->sd_flag & STPLEX)
23153 		return (0);
23154 
23155 	claimstr(stp->sd_wrq);
23156 	wq = stp->sd_wrq->q_next;
23157 	ASSERT(wq != NULL);
23158 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23159 	releasestr(stp->sd_wrq);
23160 	return (1);
23161 }
23162 
23163 static int
23164 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23165     int *t_errorp, int *sys_errorp)
23166 {
23167 	int error;
23168 	int is_absreq_failure;
23169 	t_scalar_t *opt_lenp;
23170 	t_scalar_t opt_offset;
23171 	int prim_type;
23172 	struct T_conn_req *tcreqp;
23173 	struct T_conn_res *tcresp;
23174 	cred_t *cr;
23175 
23176 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23177 
23178 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23179 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23180 	    prim_type == T_CONN_RES);
23181 
23182 	switch (prim_type) {
23183 	case T_CONN_REQ:
23184 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23185 		opt_offset = tcreqp->OPT_offset;
23186 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23187 		break;
23188 	case O_T_CONN_RES:
23189 	case T_CONN_RES:
23190 		tcresp = (struct T_conn_res *)mp->b_rptr;
23191 		opt_offset = tcresp->OPT_offset;
23192 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23193 		break;
23194 	}
23195 
23196 	*t_errorp = 0;
23197 	*sys_errorp = 0;
23198 	*do_disconnectp = 0;
23199 
23200 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23201 	    opt_offset, cr, &tcp_opt_obj,
23202 	    NULL, &is_absreq_failure);
23203 
23204 	switch (error) {
23205 	case  0:		/* no error */
23206 		ASSERT(is_absreq_failure == 0);
23207 		return (0);
23208 	case ENOPROTOOPT:
23209 		*t_errorp = TBADOPT;
23210 		break;
23211 	case EACCES:
23212 		*t_errorp = TACCES;
23213 		break;
23214 	default:
23215 		*t_errorp = TSYSERR; *sys_errorp = error;
23216 		break;
23217 	}
23218 	if (is_absreq_failure != 0) {
23219 		/*
23220 		 * The connection request should get the local ack
23221 		 * T_OK_ACK and then a T_DISCON_IND.
23222 		 */
23223 		*do_disconnectp = 1;
23224 	}
23225 	return (-1);
23226 }
23227 
23228 /*
23229  * Split this function out so that if the secret changes, I'm okay.
23230  *
23231  * Initialize the tcp_iss_cookie and tcp_iss_key.
23232  */
23233 
23234 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23235 
23236 static void
23237 tcp_iss_key_init(uint8_t *phrase, int len)
23238 {
23239 	struct {
23240 		int32_t current_time;
23241 		uint32_t randnum;
23242 		uint16_t pad;
23243 		uint8_t ether[6];
23244 		uint8_t passwd[PASSWD_SIZE];
23245 	} tcp_iss_cookie;
23246 	time_t t;
23247 
23248 	/*
23249 	 * Start with the current absolute time.
23250 	 */
23251 	(void) drv_getparm(TIME, &t);
23252 	tcp_iss_cookie.current_time = t;
23253 
23254 	/*
23255 	 * XXX - Need a more random number per RFC 1750, not this crap.
23256 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23257 	 */
23258 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23259 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23260 
23261 	/*
23262 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23263 	 * as a good template.
23264 	 */
23265 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23266 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23267 
23268 	/*
23269 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23270 	 */
23271 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23272 
23273 	/*
23274 	 * See 4010593 if this section becomes a problem again,
23275 	 * but the local ethernet address is useful here.
23276 	 */
23277 	(void) localetheraddr(NULL,
23278 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23279 
23280 	/*
23281 	 * Hash 'em all together.  The MD5Final is called per-connection.
23282 	 */
23283 	mutex_enter(&tcp_iss_key_lock);
23284 	MD5Init(&tcp_iss_key);
23285 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
23286 	    sizeof (tcp_iss_cookie));
23287 	mutex_exit(&tcp_iss_key_lock);
23288 }
23289 
23290 /*
23291  * Set the RFC 1948 pass phrase
23292  */
23293 /* ARGSUSED */
23294 static int
23295 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23296     cred_t *cr)
23297 {
23298 	/*
23299 	 * Basically, value contains a new pass phrase.  Pass it along!
23300 	 */
23301 	tcp_iss_key_init((uint8_t *)value, strlen(value));
23302 	return (0);
23303 }
23304 
23305 /* ARGSUSED */
23306 static int
23307 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23308 {
23309 	bzero(buf, sizeof (tcp_sack_info_t));
23310 	return (0);
23311 }
23312 
23313 /* ARGSUSED */
23314 static int
23315 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23316 {
23317 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23318 	return (0);
23319 }
23320 
23321 void
23322 tcp_ddi_init(void)
23323 {
23324 	int i;
23325 
23326 	/* Initialize locks */
23327 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
23328 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23329 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23330 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23331 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23332 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
23333 
23334 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23335 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
23336 		    MUTEX_DEFAULT, NULL);
23337 	}
23338 
23339 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23340 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
23341 		    MUTEX_DEFAULT, NULL);
23342 	}
23343 
23344 	/* TCP's IPsec code calls the packet dropper. */
23345 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
23346 
23347 	if (!tcp_g_nd) {
23348 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
23349 			nd_free(&tcp_g_nd);
23350 		}
23351 	}
23352 
23353 	/*
23354 	 * Note: To really walk the device tree you need the devinfo
23355 	 * pointer to your device which is only available after probe/attach.
23356 	 * The following is safe only because it uses ddi_root_node()
23357 	 */
23358 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23359 	    tcp_opt_obj.odb_opt_arr_cnt);
23360 
23361 	tcp_timercache = kmem_cache_create("tcp_timercache",
23362 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23363 	    NULL, NULL, NULL, NULL, NULL, 0);
23364 
23365 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23366 	    sizeof (tcp_sack_info_t), 0,
23367 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23368 
23369 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23370 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23371 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23372 
23373 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
23374 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
23375 
23376 	ip_squeue_init(tcp_squeue_add);
23377 
23378 	/* Initialize the random number generator */
23379 	tcp_random_init();
23380 
23381 	/*
23382 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23383 	 * by the boot scripts.
23384 	 *
23385 	 * Use NULL name, as the name is caught by the new lockstats.
23386 	 *
23387 	 * Initialize with some random, non-guessable string, like the global
23388 	 * T_INFO_ACK.
23389 	 */
23390 
23391 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23392 	    sizeof (tcp_g_t_info_ack));
23393 
23394 	if ((tcp_kstat = kstat_create(TCP_MOD_NAME, 0, "tcpstat",
23395 		"net", KSTAT_TYPE_NAMED,
23396 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
23397 		KSTAT_FLAG_VIRTUAL)) != NULL) {
23398 		tcp_kstat->ks_data = &tcp_statistics;
23399 		kstat_install(tcp_kstat);
23400 	}
23401 
23402 	tcp_kstat_init();
23403 }
23404 
23405 void
23406 tcp_ddi_destroy(void)
23407 {
23408 	int i;
23409 
23410 	nd_free(&tcp_g_nd);
23411 
23412 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23413 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
23414 	}
23415 
23416 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23417 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
23418 	}
23419 
23420 	mutex_destroy(&tcp_iss_key_lock);
23421 	rw_destroy(&tcp_hsp_lock);
23422 	mutex_destroy(&tcp_g_q_lock);
23423 	mutex_destroy(&tcp_random_lock);
23424 	mutex_destroy(&tcp_epriv_port_lock);
23425 	rw_destroy(&tcp_reserved_port_lock);
23426 
23427 	ip_drop_unregister(&tcp_dropper);
23428 
23429 	kmem_cache_destroy(tcp_timercache);
23430 	kmem_cache_destroy(tcp_sack_info_cache);
23431 	kmem_cache_destroy(tcp_iphc_cache);
23432 
23433 	tcp_kstat_fini();
23434 }
23435 
23436 /*
23437  * Generate ISS, taking into account NDD changes may happen halfway through.
23438  * (If the iss is not zero, set it.)
23439  */
23440 
23441 static void
23442 tcp_iss_init(tcp_t *tcp)
23443 {
23444 	MD5_CTX context;
23445 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
23446 	uint32_t answer[4];
23447 
23448 	tcp_iss_incr_extra += (ISS_INCR >> 1);
23449 	tcp->tcp_iss = tcp_iss_incr_extra;
23450 	switch (tcp_strong_iss) {
23451 	case 2:
23452 		mutex_enter(&tcp_iss_key_lock);
23453 		context = tcp_iss_key;
23454 		mutex_exit(&tcp_iss_key_lock);
23455 		arg.ports = tcp->tcp_ports;
23456 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23457 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
23458 			    &arg.src);
23459 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
23460 			    &arg.dst);
23461 		} else {
23462 			arg.src = tcp->tcp_ip6h->ip6_src;
23463 			arg.dst = tcp->tcp_ip6h->ip6_dst;
23464 		}
23465 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
23466 		MD5Final((uchar_t *)answer, &context);
23467 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
23468 		/*
23469 		 * Now that we've hashed into a unique per-connection sequence
23470 		 * space, add a random increment per strong_iss == 1.  So I
23471 		 * guess we'll have to...
23472 		 */
23473 		/* FALLTHRU */
23474 	case 1:
23475 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
23476 		break;
23477 	default:
23478 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
23479 		break;
23480 	}
23481 	tcp->tcp_valid_bits = TCP_ISS_VALID;
23482 	tcp->tcp_fss = tcp->tcp_iss - 1;
23483 	tcp->tcp_suna = tcp->tcp_iss;
23484 	tcp->tcp_snxt = tcp->tcp_iss + 1;
23485 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23486 	tcp->tcp_csuna = tcp->tcp_snxt;
23487 }
23488 
23489 /*
23490  * Exported routine for extracting active tcp connection status.
23491  *
23492  * This is used by the Solaris Cluster Networking software to
23493  * gather a list of connections that need to be forwarded to
23494  * specific nodes in the cluster when configuration changes occur.
23495  *
23496  * The callback is invoked for each tcp_t structure. Returning
23497  * non-zero from the callback routine terminates the search.
23498  */
23499 int
23500 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
23501 {
23502 	tcp_t *tcp;
23503 	cl_tcp_info_t	cl_tcpi;
23504 	connf_t	*connfp;
23505 	conn_t	*connp;
23506 	int	i;
23507 
23508 	ASSERT(callback != NULL);
23509 
23510 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
23511 
23512 		connfp = &ipcl_globalhash_fanout[i];
23513 		connp = NULL;
23514 
23515 		while ((connp =
23516 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
23517 
23518 			tcp = connp->conn_tcp;
23519 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
23520 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
23521 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
23522 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
23523 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
23524 			/*
23525 			 * The macros tcp_laddr and tcp_faddr give the IPv4
23526 			 * addresses. They are copied implicitly below as
23527 			 * mapped addresses.
23528 			 */
23529 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
23530 			if (tcp->tcp_ipversion == IPV4_VERSION) {
23531 				cl_tcpi.cl_tcpi_faddr =
23532 				    tcp->tcp_ipha->ipha_dst;
23533 			} else {
23534 				cl_tcpi.cl_tcpi_faddr_v6 =
23535 				    tcp->tcp_ip6h->ip6_dst;
23536 			}
23537 
23538 			/*
23539 			 * If the callback returns non-zero
23540 			 * we terminate the traversal.
23541 			 */
23542 			if ((*callback)(&cl_tcpi, arg) != 0) {
23543 				CONN_DEC_REF(tcp->tcp_connp);
23544 				return (1);
23545 			}
23546 		}
23547 	}
23548 
23549 	return (0);
23550 }
23551 
23552 /*
23553  * Macros used for accessing the different types of sockaddr
23554  * structures inside a tcp_ioc_abort_conn_t.
23555  */
23556 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
23557 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
23558 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
23559 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
23560 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
23561 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
23562 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
23563 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
23564 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
23565 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
23566 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
23567 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
23568 
23569 /*
23570  * Return the correct error code to mimic the behavior
23571  * of a connection reset.
23572  */
23573 #define	TCP_AC_GET_ERRCODE(state, err) {	\
23574 		switch ((state)) {		\
23575 		case TCPS_SYN_SENT:		\
23576 		case TCPS_SYN_RCVD:		\
23577 			(err) = ECONNREFUSED;	\
23578 			break;			\
23579 		case TCPS_ESTABLISHED:		\
23580 		case TCPS_FIN_WAIT_1:		\
23581 		case TCPS_FIN_WAIT_2:		\
23582 		case TCPS_CLOSE_WAIT:		\
23583 			(err) = ECONNRESET;	\
23584 			break;			\
23585 		case TCPS_CLOSING:		\
23586 		case TCPS_LAST_ACK:		\
23587 		case TCPS_TIME_WAIT:		\
23588 			(err) = 0;		\
23589 			break;			\
23590 		default:			\
23591 			(err) = ENXIO;		\
23592 		}				\
23593 	}
23594 
23595 /*
23596  * Check if a tcp structure matches the info in acp.
23597  */
23598 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
23599 	(((acp)->ac_local.ss_family == AF_INET) ?		\
23600 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
23601 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
23602 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
23603 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
23604 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
23605 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
23606 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
23607 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
23608 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23609 	(acp)->ac_end >= (tcp)->tcp_state) :		\
23610 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
23611 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
23612 	&(tcp)->tcp_ip_src_v6)) &&				\
23613 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
23614 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
23615 	&(tcp)->tcp_remote_v6)) &&				\
23616 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
23617 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
23618 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
23619 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
23620 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23621 	(acp)->ac_end >= (tcp)->tcp_state))
23622 
23623 #define	TCP_AC_MATCH(acp, tcp)					\
23624 	(((acp)->ac_zoneid == ALL_ZONES ||			\
23625 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
23626 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
23627 
23628 /*
23629  * Build a message containing a tcp_ioc_abort_conn_t structure
23630  * which is filled in with information from acp and tp.
23631  */
23632 static mblk_t *
23633 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
23634 {
23635 	mblk_t *mp;
23636 	tcp_ioc_abort_conn_t *tacp;
23637 
23638 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
23639 	if (mp == NULL)
23640 		return (NULL);
23641 
23642 	mp->b_datap->db_type = M_CTL;
23643 
23644 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
23645 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
23646 		sizeof (uint32_t));
23647 
23648 	tacp->ac_start = acp->ac_start;
23649 	tacp->ac_end = acp->ac_end;
23650 	tacp->ac_zoneid = acp->ac_zoneid;
23651 
23652 	if (acp->ac_local.ss_family == AF_INET) {
23653 		tacp->ac_local.ss_family = AF_INET;
23654 		tacp->ac_remote.ss_family = AF_INET;
23655 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
23656 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
23657 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
23658 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
23659 	} else {
23660 		tacp->ac_local.ss_family = AF_INET6;
23661 		tacp->ac_remote.ss_family = AF_INET6;
23662 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
23663 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
23664 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
23665 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
23666 	}
23667 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
23668 	return (mp);
23669 }
23670 
23671 /*
23672  * Print a tcp_ioc_abort_conn_t structure.
23673  */
23674 static void
23675 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
23676 {
23677 	char lbuf[128];
23678 	char rbuf[128];
23679 	sa_family_t af;
23680 	in_port_t lport, rport;
23681 	ushort_t logflags;
23682 
23683 	af = acp->ac_local.ss_family;
23684 
23685 	if (af == AF_INET) {
23686 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
23687 				lbuf, 128);
23688 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
23689 				rbuf, 128);
23690 		lport = ntohs(TCP_AC_V4LPORT(acp));
23691 		rport = ntohs(TCP_AC_V4RPORT(acp));
23692 	} else {
23693 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
23694 				lbuf, 128);
23695 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
23696 				rbuf, 128);
23697 		lport = ntohs(TCP_AC_V6LPORT(acp));
23698 		rport = ntohs(TCP_AC_V6RPORT(acp));
23699 	}
23700 
23701 	logflags = SL_TRACE | SL_NOTE;
23702 	/*
23703 	 * Don't print this message to the console if the operation was done
23704 	 * to a non-global zone.
23705 	 */
23706 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
23707 		logflags |= SL_CONSOLE;
23708 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
23709 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
23710 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
23711 		acp->ac_start, acp->ac_end);
23712 }
23713 
23714 /*
23715  * Called inside tcp_rput when a message built using
23716  * tcp_ioctl_abort_build_msg is put into a queue.
23717  * Note that when we get here there is no wildcard in acp any more.
23718  */
23719 static void
23720 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
23721 {
23722 	tcp_ioc_abort_conn_t *acp;
23723 
23724 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
23725 	if (tcp->tcp_state <= acp->ac_end) {
23726 		/*
23727 		 * If we get here, we are already on the correct
23728 		 * squeue. This ioctl follows the following path
23729 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
23730 		 * ->tcp_ioctl_abort->squeue_fill (if on a
23731 		 * different squeue)
23732 		 */
23733 		int errcode;
23734 
23735 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
23736 		(void) tcp_clean_death(tcp, errcode, 26);
23737 	}
23738 	freemsg(mp);
23739 }
23740 
23741 /*
23742  * Abort all matching connections on a hash chain.
23743  */
23744 static int
23745 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
23746     boolean_t exact)
23747 {
23748 	int nmatch, err = 0;
23749 	tcp_t *tcp;
23750 	MBLKP mp, last, listhead = NULL;
23751 	conn_t	*tconnp;
23752 	connf_t	*connfp = &ipcl_conn_fanout[index];
23753 
23754 startover:
23755 	nmatch = 0;
23756 
23757 	mutex_enter(&connfp->connf_lock);
23758 	for (tconnp = connfp->connf_head; tconnp != NULL;
23759 	    tconnp = tconnp->conn_next) {
23760 		tcp = tconnp->conn_tcp;
23761 		if (TCP_AC_MATCH(acp, tcp)) {
23762 			CONN_INC_REF(tcp->tcp_connp);
23763 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
23764 			if (mp == NULL) {
23765 				err = ENOMEM;
23766 				CONN_DEC_REF(tcp->tcp_connp);
23767 				break;
23768 			}
23769 			mp->b_prev = (mblk_t *)tcp;
23770 
23771 			if (listhead == NULL) {
23772 				listhead = mp;
23773 				last = mp;
23774 			} else {
23775 				last->b_next = mp;
23776 				last = mp;
23777 			}
23778 			nmatch++;
23779 			if (exact)
23780 				break;
23781 		}
23782 
23783 		/* Avoid holding lock for too long. */
23784 		if (nmatch >= 500)
23785 			break;
23786 	}
23787 	mutex_exit(&connfp->connf_lock);
23788 
23789 	/* Pass mp into the correct tcp */
23790 	while ((mp = listhead) != NULL) {
23791 		listhead = listhead->b_next;
23792 		tcp = (tcp_t *)mp->b_prev;
23793 		mp->b_next = mp->b_prev = NULL;
23794 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
23795 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
23796 	}
23797 
23798 	*count += nmatch;
23799 	if (nmatch >= 500 && err == 0)
23800 		goto startover;
23801 	return (err);
23802 }
23803 
23804 /*
23805  * Abort all connections that matches the attributes specified in acp.
23806  */
23807 static int
23808 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
23809 {
23810 	sa_family_t af;
23811 	uint32_t  ports;
23812 	uint16_t *pports;
23813 	int err = 0, count = 0;
23814 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
23815 	int index = -1;
23816 	ushort_t logflags;
23817 
23818 	af = acp->ac_local.ss_family;
23819 
23820 	if (af == AF_INET) {
23821 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
23822 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
23823 			pports = (uint16_t *)&ports;
23824 			pports[1] = TCP_AC_V4LPORT(acp);
23825 			pports[0] = TCP_AC_V4RPORT(acp);
23826 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
23827 		}
23828 	} else {
23829 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
23830 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
23831 			pports = (uint16_t *)&ports;
23832 			pports[1] = TCP_AC_V6LPORT(acp);
23833 			pports[0] = TCP_AC_V6RPORT(acp);
23834 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
23835 		}
23836 	}
23837 
23838 	/*
23839 	 * For cases where remote addr, local port, and remote port are non-
23840 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
23841 	 */
23842 	if (index != -1) {
23843 		err = tcp_ioctl_abort_bucket(acp, index,
23844 			    &count, exact);
23845 	} else {
23846 		/*
23847 		 * loop through all entries for wildcard case
23848 		 */
23849 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
23850 			err = tcp_ioctl_abort_bucket(acp, index,
23851 			    &count, exact);
23852 			if (err != 0)
23853 				break;
23854 		}
23855 	}
23856 
23857 	logflags = SL_TRACE | SL_NOTE;
23858 	/*
23859 	 * Don't print this message to the console if the operation was done
23860 	 * to a non-global zone.
23861 	 */
23862 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
23863 		logflags |= SL_CONSOLE;
23864 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
23865 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
23866 	if (err == 0 && count == 0)
23867 		err = ENOENT;
23868 	return (err);
23869 }
23870 
23871 /*
23872  * Process the TCP_IOC_ABORT_CONN ioctl request.
23873  */
23874 static void
23875 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
23876 {
23877 	int	err;
23878 	IOCP    iocp;
23879 	MBLKP   mp1;
23880 	sa_family_t laf, raf;
23881 	tcp_ioc_abort_conn_t *acp;
23882 	zone_t *zptr;
23883 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
23884 
23885 	iocp = (IOCP)mp->b_rptr;
23886 
23887 	if ((mp1 = mp->b_cont) == NULL ||
23888 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
23889 		err = EINVAL;
23890 		goto out;
23891 	}
23892 
23893 	/* check permissions */
23894 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
23895 		err = EPERM;
23896 		goto out;
23897 	}
23898 
23899 	if (mp1->b_cont != NULL) {
23900 		freemsg(mp1->b_cont);
23901 		mp1->b_cont = NULL;
23902 	}
23903 
23904 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
23905 	laf = acp->ac_local.ss_family;
23906 	raf = acp->ac_remote.ss_family;
23907 
23908 	/* check that a zone with the supplied zoneid exists */
23909 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
23910 		zptr = zone_find_by_id(zoneid);
23911 		if (zptr != NULL) {
23912 			zone_rele(zptr);
23913 		} else {
23914 			err = EINVAL;
23915 			goto out;
23916 		}
23917 	}
23918 
23919 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
23920 	    acp->ac_start > acp->ac_end || laf != raf ||
23921 	    (laf != AF_INET && laf != AF_INET6)) {
23922 		err = EINVAL;
23923 		goto out;
23924 	}
23925 
23926 	tcp_ioctl_abort_dump(acp);
23927 	err = tcp_ioctl_abort(acp);
23928 
23929 out:
23930 	if (mp1 != NULL) {
23931 		freemsg(mp1);
23932 		mp->b_cont = NULL;
23933 	}
23934 
23935 	if (err != 0)
23936 		miocnak(q, mp, 0, err);
23937 	else
23938 		miocack(q, mp, 0, 0);
23939 }
23940 
23941 /*
23942  * tcp_time_wait_processing() handles processing of incoming packets when
23943  * the tcp is in the TIME_WAIT state.
23944  * A TIME_WAIT tcp that has an associated open TCP stream is never put
23945  * on the time wait list.
23946  */
23947 void
23948 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
23949     uint32_t seg_ack, int seg_len, tcph_t *tcph)
23950 {
23951 	int32_t		bytes_acked;
23952 	int32_t		gap;
23953 	int32_t		rgap;
23954 	tcp_opt_t	tcpopt;
23955 	uint_t		flags;
23956 	uint32_t	new_swnd = 0;
23957 	conn_t		*connp;
23958 
23959 	BUMP_LOCAL(tcp->tcp_ibsegs);
23960 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
23961 
23962 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
23963 	new_swnd = BE16_TO_U16(tcph->th_win) <<
23964 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
23965 	if (tcp->tcp_snd_ts_ok) {
23966 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
23967 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
23968 			    tcp->tcp_rnxt, TH_ACK);
23969 			goto done;
23970 		}
23971 	}
23972 	gap = seg_seq - tcp->tcp_rnxt;
23973 	rgap = tcp->tcp_rwnd - (gap + seg_len);
23974 	if (gap < 0) {
23975 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
23976 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
23977 		    (seg_len > -gap ? -gap : seg_len));
23978 		seg_len += gap;
23979 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
23980 			if (flags & TH_RST) {
23981 				goto done;
23982 			}
23983 			if ((flags & TH_FIN) && seg_len == -1) {
23984 				/*
23985 				 * When TCP receives a duplicate FIN in
23986 				 * TIME_WAIT state, restart the 2 MSL timer.
23987 				 * See page 73 in RFC 793. Make sure this TCP
23988 				 * is already on the TIME_WAIT list. If not,
23989 				 * just restart the timer.
23990 				 */
23991 				if (TCP_IS_DETACHED(tcp)) {
23992 					tcp_time_wait_remove(tcp, NULL);
23993 					tcp_time_wait_append(tcp);
23994 					TCP_DBGSTAT(tcp_rput_time_wait);
23995 				} else {
23996 					ASSERT(tcp != NULL);
23997 					TCP_TIMER_RESTART(tcp,
23998 					    tcp_time_wait_interval);
23999 				}
24000 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24001 				    tcp->tcp_rnxt, TH_ACK);
24002 				goto done;
24003 			}
24004 			flags |=  TH_ACK_NEEDED;
24005 			seg_len = 0;
24006 			goto process_ack;
24007 		}
24008 
24009 		/* Fix seg_seq, and chew the gap off the front. */
24010 		seg_seq = tcp->tcp_rnxt;
24011 	}
24012 
24013 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24014 		/*
24015 		 * Make sure that when we accept the connection, pick
24016 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24017 		 * old connection.
24018 		 *
24019 		 * The next ISS generated is equal to tcp_iss_incr_extra
24020 		 * + ISS_INCR/2 + other components depending on the
24021 		 * value of tcp_strong_iss.  We pre-calculate the new
24022 		 * ISS here and compare with tcp_snxt to determine if
24023 		 * we need to make adjustment to tcp_iss_incr_extra.
24024 		 *
24025 		 * The above calculation is ugly and is a
24026 		 * waste of CPU cycles...
24027 		 */
24028 		uint32_t new_iss = tcp_iss_incr_extra;
24029 		int32_t adj;
24030 
24031 		switch (tcp_strong_iss) {
24032 		case 2: {
24033 			/* Add time and MD5 components. */
24034 			uint32_t answer[4];
24035 			struct {
24036 				uint32_t ports;
24037 				in6_addr_t src;
24038 				in6_addr_t dst;
24039 			} arg;
24040 			MD5_CTX context;
24041 
24042 			mutex_enter(&tcp_iss_key_lock);
24043 			context = tcp_iss_key;
24044 			mutex_exit(&tcp_iss_key_lock);
24045 			arg.ports = tcp->tcp_ports;
24046 			/* We use MAPPED addresses in tcp_iss_init */
24047 			arg.src = tcp->tcp_ip_src_v6;
24048 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24049 				IN6_IPADDR_TO_V4MAPPED(
24050 					tcp->tcp_ipha->ipha_dst,
24051 					    &arg.dst);
24052 			} else {
24053 				arg.dst =
24054 				    tcp->tcp_ip6h->ip6_dst;
24055 			}
24056 			MD5Update(&context, (uchar_t *)&arg,
24057 			    sizeof (arg));
24058 			MD5Final((uchar_t *)answer, &context);
24059 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24060 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24061 			break;
24062 		}
24063 		case 1:
24064 			/* Add time component and min random (i.e. 1). */
24065 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24066 			break;
24067 		default:
24068 			/* Add only time component. */
24069 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24070 			break;
24071 		}
24072 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24073 			/*
24074 			 * New ISS not guaranteed to be ISS_INCR/2
24075 			 * ahead of the current tcp_snxt, so add the
24076 			 * difference to tcp_iss_incr_extra.
24077 			 */
24078 			tcp_iss_incr_extra += adj;
24079 		}
24080 		/*
24081 		 * If tcp_clean_death() can not perform the task now,
24082 		 * drop the SYN packet and let the other side re-xmit.
24083 		 * Otherwise pass the SYN packet back in, since the
24084 		 * old tcp state has been cleaned up or freed.
24085 		 */
24086 		if (tcp_clean_death(tcp, 0, 27) == -1)
24087 			goto done;
24088 		/*
24089 		 * We will come back to tcp_rput_data
24090 		 * on the global queue. Packets destined
24091 		 * for the global queue will be checked
24092 		 * with global policy. But the policy for
24093 		 * this packet has already been checked as
24094 		 * this was destined for the detached
24095 		 * connection. We need to bypass policy
24096 		 * check this time by attaching a dummy
24097 		 * ipsec_in with ipsec_in_dont_check set.
24098 		 */
24099 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
24100 		    NULL) {
24101 			TCP_STAT(tcp_time_wait_syn_success);
24102 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24103 			return;
24104 		}
24105 		goto done;
24106 	}
24107 
24108 	/*
24109 	 * rgap is the amount of stuff received out of window.  A negative
24110 	 * value is the amount out of window.
24111 	 */
24112 	if (rgap < 0) {
24113 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
24114 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
24115 		/* Fix seg_len and make sure there is something left. */
24116 		seg_len += rgap;
24117 		if (seg_len <= 0) {
24118 			if (flags & TH_RST) {
24119 				goto done;
24120 			}
24121 			flags |=  TH_ACK_NEEDED;
24122 			seg_len = 0;
24123 			goto process_ack;
24124 		}
24125 	}
24126 	/*
24127 	 * Check whether we can update tcp_ts_recent.  This test is
24128 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24129 	 * Extensions for High Performance: An Update", Internet Draft.
24130 	 */
24131 	if (tcp->tcp_snd_ts_ok &&
24132 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24133 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24134 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24135 		tcp->tcp_last_rcv_lbolt = lbolt64;
24136 	}
24137 
24138 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24139 		/* Always ack out of order packets */
24140 		flags |= TH_ACK_NEEDED;
24141 		seg_len = 0;
24142 	} else if (seg_len > 0) {
24143 		BUMP_MIB(&tcp_mib, tcpInClosed);
24144 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
24145 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
24146 	}
24147 	if (flags & TH_RST) {
24148 		(void) tcp_clean_death(tcp, 0, 28);
24149 		goto done;
24150 	}
24151 	if (flags & TH_SYN) {
24152 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24153 		    TH_RST|TH_ACK);
24154 		/*
24155 		 * Do not delete the TCP structure if it is in
24156 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24157 		 */
24158 		goto done;
24159 	}
24160 process_ack:
24161 	if (flags & TH_ACK) {
24162 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24163 		if (bytes_acked <= 0) {
24164 			if (bytes_acked == 0 && seg_len == 0 &&
24165 			    new_swnd == tcp->tcp_swnd)
24166 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24167 		} else {
24168 			/* Acks something not sent */
24169 			flags |= TH_ACK_NEEDED;
24170 		}
24171 	}
24172 	if (flags & TH_ACK_NEEDED) {
24173 		/*
24174 		 * Time to send an ack for some reason.
24175 		 */
24176 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24177 		    tcp->tcp_rnxt, TH_ACK);
24178 	}
24179 done:
24180 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24181 		DB_CKSUMSTART(mp) = 0;
24182 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24183 		TCP_STAT(tcp_time_wait_syn_fail);
24184 	}
24185 	freemsg(mp);
24186 }
24187 
24188 /*
24189  * Return zero if the buffers are identical in length and content.
24190  * This is used for comparing extension header buffers.
24191  * Note that an extension header would be declared different
24192  * even if all that changed was the next header value in that header i.e.
24193  * what really changed is the next extension header.
24194  */
24195 static boolean_t
24196 tcp_cmpbuf(void *a, uint_t alen, boolean_t b_valid, void *b, uint_t blen)
24197 {
24198 	if (!b_valid)
24199 		blen = 0;
24200 
24201 	if (alen != blen)
24202 		return (B_TRUE);
24203 	if (alen == 0)
24204 		return (B_FALSE);	/* Both zero length */
24205 	return (bcmp(a, b, alen));
24206 }
24207 
24208 /*
24209  * Preallocate memory for tcp_savebuf(). Returns B_TRUE if ok.
24210  * Return B_FALSE if memory allocation fails - don't change any state!
24211  */
24212 static boolean_t
24213 tcp_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24214     void *src, uint_t srclen)
24215 {
24216 	void *dst;
24217 
24218 	if (!src_valid)
24219 		srclen = 0;
24220 
24221 	ASSERT(*dstlenp == 0);
24222 	if (src != NULL && srclen != 0) {
24223 		dst = mi_alloc(srclen, BPRI_MED);
24224 		if (dst == NULL)
24225 			return (B_FALSE);
24226 	} else {
24227 		dst = NULL;
24228 	}
24229 	if (*dstp != NULL) {
24230 		mi_free(*dstp);
24231 		*dstp = NULL;
24232 		*dstlenp = 0;
24233 	}
24234 	*dstp = dst;
24235 	if (dst != NULL)
24236 		*dstlenp = srclen;
24237 	else
24238 		*dstlenp = 0;
24239 	return (B_TRUE);
24240 }
24241 
24242 /*
24243  * Replace what is in *dst, *dstlen with the source.
24244  * Assumes tcp_allocbuf has already been called.
24245  */
24246 static void
24247 tcp_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24248     void *src, uint_t srclen)
24249 {
24250 	if (!src_valid)
24251 		srclen = 0;
24252 
24253 	ASSERT(*dstlenp == srclen);
24254 	if (src != NULL && srclen != 0) {
24255 		bcopy(src, *dstp, srclen);
24256 	}
24257 }
24258 
24259 /*
24260  * Allocate a T_SVR4_OPTMGMT_REQ.
24261  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24262  * that tcp_rput_other can drop the acks.
24263  */
24264 static mblk_t *
24265 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24266 {
24267 	mblk_t *mp;
24268 	struct T_optmgmt_req *tor;
24269 	struct opthdr *oh;
24270 	uint_t size;
24271 	char *optptr;
24272 
24273 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24274 	mp = allocb(size, BPRI_MED);
24275 	if (mp == NULL)
24276 		return (NULL);
24277 
24278 	mp->b_wptr += size;
24279 	mp->b_datap->db_type = M_PROTO;
24280 	tor = (struct T_optmgmt_req *)mp->b_rptr;
24281 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
24282 	tor->MGMT_flags = T_NEGOTIATE;
24283 	tor->OPT_length = sizeof (*oh) + optlen;
24284 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
24285 
24286 	oh = (struct opthdr *)&tor[1];
24287 	oh->level = level;
24288 	oh->name = cmd;
24289 	oh->len = optlen;
24290 	if (optlen != 0) {
24291 		optptr = (char *)&oh[1];
24292 		bcopy(opt, optptr, optlen);
24293 	}
24294 	return (mp);
24295 }
24296 
24297 /*
24298  * TCP Timers Implementation.
24299  */
24300 timeout_id_t
24301 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24302 {
24303 	mblk_t *mp;
24304 	tcp_timer_t *tcpt;
24305 	tcp_t *tcp = connp->conn_tcp;
24306 
24307 	ASSERT(connp->conn_sqp != NULL);
24308 
24309 	TCP_DBGSTAT(tcp_timeout_calls);
24310 
24311 	if (tcp->tcp_timercache == NULL) {
24312 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24313 	} else {
24314 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
24315 		mp = tcp->tcp_timercache;
24316 		tcp->tcp_timercache = mp->b_next;
24317 		mp->b_next = NULL;
24318 		ASSERT(mp->b_wptr == NULL);
24319 	}
24320 
24321 	CONN_INC_REF(connp);
24322 	tcpt = (tcp_timer_t *)mp->b_rptr;
24323 	tcpt->connp = connp;
24324 	tcpt->tcpt_proc = f;
24325 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
24326 	return ((timeout_id_t)mp);
24327 }
24328 
24329 static void
24330 tcp_timer_callback(void *arg)
24331 {
24332 	mblk_t *mp = (mblk_t *)arg;
24333 	tcp_timer_t *tcpt;
24334 	conn_t	*connp;
24335 
24336 	tcpt = (tcp_timer_t *)mp->b_rptr;
24337 	connp = tcpt->connp;
24338 	squeue_fill(connp->conn_sqp, mp,
24339 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
24340 }
24341 
24342 static void
24343 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24344 {
24345 	tcp_timer_t *tcpt;
24346 	conn_t *connp = (conn_t *)arg;
24347 	tcp_t *tcp = connp->conn_tcp;
24348 
24349 	tcpt = (tcp_timer_t *)mp->b_rptr;
24350 	ASSERT(connp == tcpt->connp);
24351 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24352 
24353 	/*
24354 	 * If the TCP has reached the closed state, don't proceed any
24355 	 * further. This TCP logically does not exist on the system.
24356 	 * tcpt_proc could for example access queues, that have already
24357 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24358 	 */
24359 	if (tcp->tcp_state != TCPS_CLOSED) {
24360 		(*tcpt->tcpt_proc)(connp);
24361 	} else {
24362 		tcp->tcp_timer_tid = 0;
24363 	}
24364 	tcp_timer_free(connp->conn_tcp, mp);
24365 }
24366 
24367 /*
24368  * There is potential race with untimeout and the handler firing at the same
24369  * time. The mblock may be freed by the handler while we are trying to use
24370  * it. But since both should execute on the same squeue, this race should not
24371  * occur.
24372  */
24373 clock_t
24374 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24375 {
24376 	mblk_t	*mp = (mblk_t *)id;
24377 	tcp_timer_t *tcpt;
24378 	clock_t delta;
24379 
24380 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
24381 
24382 	if (mp == NULL)
24383 		return (-1);
24384 
24385 	tcpt = (tcp_timer_t *)mp->b_rptr;
24386 	ASSERT(tcpt->connp == connp);
24387 
24388 	delta = untimeout(tcpt->tcpt_tid);
24389 
24390 	if (delta >= 0) {
24391 		TCP_DBGSTAT(tcp_timeout_canceled);
24392 		tcp_timer_free(connp->conn_tcp, mp);
24393 		CONN_DEC_REF(connp);
24394 	}
24395 
24396 	return (delta);
24397 }
24398 
24399 /*
24400  * Allocate space for the timer event. The allocation looks like mblk, but it is
24401  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24402  *
24403  * Dealing with failures: If we can't allocate from the timer cache we try
24404  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24405  * points to b_rptr.
24406  * If we can't allocate anything using allocb_tryhard(), we perform a last
24407  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24408  * save the actual allocation size in b_datap.
24409  */
24410 mblk_t *
24411 tcp_timermp_alloc(int kmflags)
24412 {
24413 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
24414 	    kmflags & ~KM_PANIC);
24415 
24416 	if (mp != NULL) {
24417 		mp->b_next = mp->b_prev = NULL;
24418 		mp->b_rptr = (uchar_t *)(&mp[1]);
24419 		mp->b_wptr = NULL;
24420 		mp->b_datap = NULL;
24421 		mp->b_queue = NULL;
24422 	} else if (kmflags & KM_PANIC) {
24423 		/*
24424 		 * Failed to allocate memory for the timer. Try allocating from
24425 		 * dblock caches.
24426 		 */
24427 		TCP_STAT(tcp_timermp_allocfail);
24428 		mp = allocb_tryhard(sizeof (tcp_timer_t));
24429 		if (mp == NULL) {
24430 			size_t size = 0;
24431 			/*
24432 			 * Memory is really low. Try tryhard allocation.
24433 			 */
24434 			TCP_STAT(tcp_timermp_allocdblfail);
24435 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
24436 			    sizeof (tcp_timer_t), &size, kmflags);
24437 			mp->b_rptr = (uchar_t *)(&mp[1]);
24438 			mp->b_next = mp->b_prev = NULL;
24439 			mp->b_wptr = (uchar_t *)-1;
24440 			mp->b_datap = (dblk_t *)size;
24441 			mp->b_queue = NULL;
24442 		}
24443 		ASSERT(mp->b_wptr != NULL);
24444 	}
24445 	TCP_DBGSTAT(tcp_timermp_alloced);
24446 
24447 	return (mp);
24448 }
24449 
24450 /*
24451  * Free per-tcp timer cache.
24452  * It can only contain entries from tcp_timercache.
24453  */
24454 void
24455 tcp_timermp_free(tcp_t *tcp)
24456 {
24457 	mblk_t *mp;
24458 
24459 	while ((mp = tcp->tcp_timercache) != NULL) {
24460 		ASSERT(mp->b_wptr == NULL);
24461 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
24462 		kmem_cache_free(tcp_timercache, mp);
24463 	}
24464 }
24465 
24466 /*
24467  * Free timer event. Put it on the per-tcp timer cache if there is not too many
24468  * events there already (currently at most two events are cached).
24469  * If the event is not allocated from the timer cache, free it right away.
24470  */
24471 static void
24472 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
24473 {
24474 	mblk_t *mp1 = tcp->tcp_timercache;
24475 
24476 	if (mp->b_wptr != NULL) {
24477 		/*
24478 		 * This allocation is not from a timer cache, free it right
24479 		 * away.
24480 		 */
24481 		if (mp->b_wptr != (uchar_t *)-1)
24482 			freeb(mp);
24483 		else
24484 			kmem_free(mp, (size_t)mp->b_datap);
24485 	} else if (mp1 == NULL || mp1->b_next == NULL) {
24486 		/* Cache this timer block for future allocations */
24487 		mp->b_rptr = (uchar_t *)(&mp[1]);
24488 		mp->b_next = mp1;
24489 		tcp->tcp_timercache = mp;
24490 	} else {
24491 		kmem_cache_free(tcp_timercache, mp);
24492 		TCP_DBGSTAT(tcp_timermp_freed);
24493 	}
24494 }
24495 
24496 /*
24497  * End of TCP Timers implementation.
24498  */
24499 
24500 /*
24501  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
24502  * on the specified backing STREAMS q. Note, the caller may make the
24503  * decision to call based on the tcp_t.tcp_flow_stopped value which
24504  * when check outside the q's lock is only an advisory check ...
24505  */
24506 
24507 void
24508 tcp_setqfull(tcp_t *tcp)
24509 {
24510 	queue_t *q = tcp->tcp_wq;
24511 
24512 	if (!(q->q_flag & QFULL)) {
24513 		mutex_enter(QLOCK(q));
24514 		if (!(q->q_flag & QFULL)) {
24515 			/* still need to set QFULL */
24516 			q->q_flag |= QFULL;
24517 			tcp->tcp_flow_stopped = B_TRUE;
24518 			mutex_exit(QLOCK(q));
24519 			TCP_STAT(tcp_flwctl_on);
24520 		} else {
24521 			mutex_exit(QLOCK(q));
24522 		}
24523 	}
24524 }
24525 
24526 void
24527 tcp_clrqfull(tcp_t *tcp)
24528 {
24529 	queue_t *q = tcp->tcp_wq;
24530 
24531 	if (q->q_flag & QFULL) {
24532 		mutex_enter(QLOCK(q));
24533 		if (q->q_flag & QFULL) {
24534 			q->q_flag &= ~QFULL;
24535 			tcp->tcp_flow_stopped = B_FALSE;
24536 			mutex_exit(QLOCK(q));
24537 			if (q->q_flag & QWANTW)
24538 				qbackenable(q, 0);
24539 		} else {
24540 			mutex_exit(QLOCK(q));
24541 		}
24542 	}
24543 }
24544 
24545 /*
24546  * TCP Kstats implementation
24547  */
24548 static void
24549 tcp_kstat_init(void)
24550 {
24551 	tcp_named_kstat_t template = {
24552 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
24553 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
24554 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
24555 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
24556 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
24557 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
24558 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
24559 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
24560 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
24561 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
24562 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
24563 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
24564 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
24565 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
24566 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
24567 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
24568 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
24569 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
24570 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
24571 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
24572 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
24573 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
24574 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
24575 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
24576 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
24577 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
24578 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
24579 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
24580 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
24581 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
24582 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
24583 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
24584 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
24585 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
24586 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
24587 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
24588 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
24589 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
24590 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
24591 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
24592 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
24593 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
24594 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
24595 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
24596 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
24597 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
24598 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
24599 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
24600 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
24601 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
24602 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
24603 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
24604 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
24605 	};
24606 
24607 	tcp_mibkp = kstat_create(TCP_MOD_NAME, 0, TCP_MOD_NAME,
24608 	    "mib2", KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0);
24609 
24610 	if (tcp_mibkp == NULL)
24611 		return;
24612 
24613 	template.rtoAlgorithm.value.ui32 = 4;
24614 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
24615 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
24616 	template.maxConn.value.i32 = -1;
24617 
24618 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
24619 
24620 	tcp_mibkp->ks_update = tcp_kstat_update;
24621 
24622 	kstat_install(tcp_mibkp);
24623 }
24624 
24625 static void
24626 tcp_kstat_fini(void)
24627 {
24628 
24629 	if (tcp_mibkp != NULL) {
24630 		kstat_delete(tcp_mibkp);
24631 		tcp_mibkp = NULL;
24632 	}
24633 }
24634 
24635 static int
24636 tcp_kstat_update(kstat_t *kp, int rw)
24637 {
24638 	tcp_named_kstat_t	*tcpkp;
24639 	tcp_t			*tcp;
24640 	connf_t			*connfp;
24641 	conn_t			*connp;
24642 	int 			i;
24643 
24644 	if (!kp || !kp->ks_data)
24645 		return (EIO);
24646 
24647 	if (rw == KSTAT_WRITE)
24648 		return (EACCES);
24649 
24650 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
24651 
24652 	tcpkp->currEstab.value.ui32 = 0;
24653 
24654 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24655 		connfp = &ipcl_globalhash_fanout[i];
24656 		connp = NULL;
24657 		while ((connp =
24658 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24659 			tcp = connp->conn_tcp;
24660 			switch (tcp_snmp_state(tcp)) {
24661 			case MIB2_TCP_established:
24662 			case MIB2_TCP_closeWait:
24663 				tcpkp->currEstab.value.ui32++;
24664 				break;
24665 			}
24666 		}
24667 	}
24668 
24669 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
24670 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
24671 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
24672 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
24673 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
24674 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
24675 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
24676 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
24677 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
24678 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
24679 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
24680 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
24681 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
24682 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
24683 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
24684 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
24685 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
24686 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
24687 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
24688 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
24689 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
24690 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
24691 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
24692 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
24693 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
24694 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
24695 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
24696 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
24697 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
24698 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
24699 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
24700 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
24701 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
24702 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
24703 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
24704 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
24705 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
24706 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
24707 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
24708 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
24709 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
24710 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
24711 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
24712 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
24713 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
24714 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
24715 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
24716 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
24717 
24718 	return (0);
24719 }
24720 
24721 void
24722 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
24723 {
24724 	uint16_t	hdr_len;
24725 	ipha_t		*ipha;
24726 	uint8_t		*nexthdrp;
24727 	tcph_t		*tcph;
24728 
24729 	/* Already has an eager */
24730 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24731 		TCP_STAT(tcp_reinput_syn);
24732 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
24733 		    connp, SQTAG_TCP_REINPUT_EAGER);
24734 		return;
24735 	}
24736 
24737 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
24738 	case IPV4_VERSION:
24739 		ipha = (ipha_t *)mp->b_rptr;
24740 		hdr_len = IPH_HDR_LENGTH(ipha);
24741 		break;
24742 	case IPV6_VERSION:
24743 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
24744 		    &hdr_len, &nexthdrp)) {
24745 			CONN_DEC_REF(connp);
24746 			freemsg(mp);
24747 			return;
24748 		}
24749 		break;
24750 	}
24751 
24752 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
24753 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
24754 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
24755 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
24756 	}
24757 
24758 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
24759 	    SQTAG_TCP_REINPUT);
24760 }
24761 
24762 static squeue_func_t
24763 tcp_squeue_switch(int val)
24764 {
24765 	squeue_func_t rval = squeue_fill;
24766 
24767 	switch (val) {
24768 	case 1:
24769 		rval = squeue_enter_nodrain;
24770 		break;
24771 	case 2:
24772 		rval = squeue_enter;
24773 		break;
24774 	default:
24775 		break;
24776 	}
24777 	return (rval);
24778 }
24779 
24780 static void
24781 tcp_squeue_add(squeue_t *sqp)
24782 {
24783 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
24784 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
24785 
24786 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
24787 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
24788 	    sqp, TCP_TIME_WAIT_DELAY);
24789 }
24790