xref: /titanic_52/usr/src/uts/common/inet/tcp/tcp.c (revision 6451fdbca2f79129a3a09d2fe3f6dd4d062bebff)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 const char tcp_version[] = "%Z%%M%	%I%	%E% SMI";
31 
32 #include <sys/types.h>
33 #include <sys/stream.h>
34 #include <sys/strsun.h>
35 #include <sys/strsubr.h>
36 #include <sys/stropts.h>
37 #include <sys/strlog.h>
38 #include <sys/strsun.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/timod.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/suntpi.h>
45 #include <sys/xti_inet.h>
46 #include <sys/cmn_err.h>
47 #include <sys/debug.h>
48 #include <sys/vtrace.h>
49 #include <sys/kmem.h>
50 #include <sys/ethernet.h>
51 #include <sys/cpuvar.h>
52 #include <sys/dlpi.h>
53 #include <sys/multidata.h>
54 #include <sys/multidata_impl.h>
55 #include <sys/pattr.h>
56 #include <sys/policy.h>
57 #include <sys/zone.h>
58 
59 #include <sys/errno.h>
60 #include <sys/signal.h>
61 #include <sys/socket.h>
62 #include <sys/sockio.h>
63 #include <sys/isa_defs.h>
64 #include <sys/md5.h>
65 #include <sys/random.h>
66 #include <netinet/in.h>
67 #include <netinet/tcp.h>
68 #include <netinet/ip6.h>
69 #include <netinet/icmp6.h>
70 #include <net/if.h>
71 #include <net/route.h>
72 #include <inet/ipsec_impl.h>
73 
74 #include <inet/common.h>
75 #include <inet/ip.h>
76 #include <inet/ip_impl.h>
77 #include <inet/ip6.h>
78 #include <inet/ip_ndp.h>
79 #include <inet/mi.h>
80 #include <inet/mib2.h>
81 #include <inet/nd.h>
82 #include <inet/optcom.h>
83 #include <inet/snmpcom.h>
84 #include <inet/kstatcom.h>
85 #include <inet/tcp.h>
86 #include <inet/tcp_impl.h>
87 #include <net/pfkeyv2.h>
88 #include <inet/ipsec_info.h>
89 #include <inet/ipdrop.h>
90 #include <inet/tcp_trace.h>
91 
92 #include <inet/ipclassifier.h>
93 #include <inet/ip_ire.h>
94 #include <inet/ip_if.h>
95 #include <inet/ipp_common.h>
96 #include <sys/squeue.h>
97 
98 /*
99  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
100  *
101  * (Read the detailed design doc in PSARC case directory)
102  *
103  * The entire tcp state is contained in tcp_t and conn_t structure
104  * which are allocated in tandem using ipcl_conn_create() and passing
105  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
106  * the references on the tcp_t. The tcp_t structure is never compressed
107  * and packets always land on the correct TCP perimeter from the time
108  * eager is created till the time tcp_t dies (as such the old mentat
109  * TCP global queue is not used for detached state and no IPSEC checking
110  * is required). The global queue is still allocated to send out resets
111  * for connection which have no listeners and IP directly calls
112  * tcp_xmit_listeners_reset() which does any policy check.
113  *
114  * Protection and Synchronisation mechanism:
115  *
116  * The tcp data structure does not use any kind of lock for protecting
117  * its state but instead uses 'squeues' for mutual exclusion from various
118  * read and write side threads. To access a tcp member, the thread should
119  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
120  * squeue_fill). Since the squeues allow a direct function call, caller
121  * can pass any tcp function having prototype of edesc_t as argument
122  * (different from traditional STREAMs model where packets come in only
123  * designated entry points). The list of functions that can be directly
124  * called via squeue are listed before the usual function prototype.
125  *
126  * Referencing:
127  *
128  * TCP is MT-Hot and we use a reference based scheme to make sure that the
129  * tcp structure doesn't disappear when its needed. When the application
130  * creates an outgoing connection or accepts an incoming connection, we
131  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
132  * The IP reference is just a symbolic reference since ip_tcpclose()
133  * looks at tcp structure after tcp_close_output() returns which could
134  * have dropped the last TCP reference. So as long as the connection is
135  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
136  * conn_t. The classifier puts its own reference when the connection is
137  * inserted in listen or connected hash. Anytime a thread needs to enter
138  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
139  * on write side or by doing a classify on read side and then puts a
140  * reference on the conn before doing squeue_enter/tryenter/fill. For
141  * read side, the classifier itself puts the reference under fanout lock
142  * to make sure that tcp can't disappear before it gets processed. The
143  * squeue will drop this reference automatically so the called function
144  * doesn't have to do a DEC_REF.
145  *
146  * Opening a new connection:
147  *
148  * The outgoing connection open is pretty simple. ip_tcpopen() does the
149  * work in creating the conn/tcp structure and initializing it. The
150  * squeue assignment is done based on the CPU the application
151  * is running on. So for outbound connections, processing is always done
152  * on application CPU which might be different from the incoming CPU
153  * being interrupted by the NIC. An optimal way would be to figure out
154  * the NIC <-> CPU binding at listen time, and assign the outgoing
155  * connection to the squeue attached to the CPU that will be interrupted
156  * for incoming packets (we know the NIC based on the bind IP address).
157  * This might seem like a problem if more data is going out but the
158  * fact is that in most cases the transmit is ACK driven transmit where
159  * the outgoing data normally sits on TCP's xmit queue waiting to be
160  * transmitted.
161  *
162  * Accepting a connection:
163  *
164  * This is a more interesting case because of various races involved in
165  * establishing a eager in its own perimeter. Read the meta comment on
166  * top of tcp_conn_request(). But briefly, the squeue is picked by
167  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
168  *
169  * Closing a connection:
170  *
171  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
172  * via squeue to do the close and mark the tcp as detached if the connection
173  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
174  * reference but tcp_close() drop IP's reference always. So if tcp was
175  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
176  * and 1 because it is in classifier's connected hash. This is the condition
177  * we use to determine that its OK to clean up the tcp outside of squeue
178  * when time wait expires (check the ref under fanout and conn_lock and
179  * if it is 2, remove it from fanout hash and kill it).
180  *
181  * Although close just drops the necessary references and marks the
182  * tcp_detached state, tcp_close needs to know the tcp_detached has been
183  * set (under squeue) before letting the STREAM go away (because a
184  * inbound packet might attempt to go up the STREAM while the close
185  * has happened and tcp_detached is not set). So a special lock and
186  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
187  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
188  * tcp_detached.
189  *
190  * Special provisions and fast paths:
191  *
192  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
193  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
194  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
195  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
196  * check to send packets directly to tcp_rput_data via squeue. Everyone
197  * else comes through tcp_input() on the read side.
198  *
199  * We also make special provisions for sockfs by marking tcp_issocket
200  * whenever we have only sockfs on top of TCP. This allows us to skip
201  * putting the tcp in acceptor hash since a sockfs listener can never
202  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
203  * since eager has already been allocated and the accept now happens
204  * on acceptor STREAM. There is a big blob of comment on top of
205  * tcp_conn_request explaining the new accept. When socket is POP'd,
206  * sockfs sends us an ioctl to mark the fact and we go back to old
207  * behaviour. Once tcp_issocket is unset, its never set for the
208  * life of that connection.
209  *
210  * IPsec notes :
211  *
212  * Since a packet is always executed on the correct TCP perimeter
213  * all IPsec processing is defered to IP including checking new
214  * connections and setting IPSEC policies for new connection. The
215  * only exception is tcp_xmit_listeners_reset() which is called
216  * directly from IP and needs to policy check to see if TH_RST
217  * can be sent out.
218  */
219 
220 
221 extern major_t TCP6_MAJ;
222 
223 /*
224  * Values for squeue switch:
225  * 1: squeue_enter_nodrain
226  * 2: squeue_enter
227  * 3: squeue_fill
228  */
229 int tcp_squeue_close = 2;
230 int tcp_squeue_wput = 2;
231 
232 squeue_func_t tcp_squeue_close_proc;
233 squeue_func_t tcp_squeue_wput_proc;
234 
235 /*
236  * This controls how tiny a write must be before we try to copy it
237  * into the the mblk on the tail of the transmit queue.  Not much
238  * speedup is observed for values larger than sixteen.  Zero will
239  * disable the optimisation.
240  */
241 int tcp_tx_pull_len = 16;
242 
243 /*
244  * TCP Statistics.
245  *
246  * How TCP statistics work.
247  *
248  * There are two types of statistics invoked by two macros.
249  *
250  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
251  * supposed to be used in non MT-hot paths of the code.
252  *
253  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
254  * supposed to be used for DEBUG purposes and may be used on a hot path.
255  *
256  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
257  * (use "kstat tcp" to get them).
258  *
259  * There is also additional debugging facility that marks tcp_clean_death()
260  * instances and saves them in tcp_t structure. It is triggered by
261  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
262  * tcp_clean_death() calls that counts the number of times each tag was hit. It
263  * is triggered by TCP_CLD_COUNTERS define.
264  *
265  * How to add new counters.
266  *
267  * 1) Add a field in the tcp_stat structure describing your counter.
268  * 2) Add a line in tcp_statistics with the name of the counter.
269  *
270  *    IMPORTANT!! - make sure that both are in sync !!
271  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
272  *
273  * Please avoid using private counters which are not kstat-exported.
274  *
275  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
276  * in tcp_t structure.
277  *
278  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
279  */
280 
281 #ifndef TCP_DEBUG_COUNTER
282 #ifdef DEBUG
283 #define	TCP_DEBUG_COUNTER 1
284 #else
285 #define	TCP_DEBUG_COUNTER 0
286 #endif
287 #endif
288 
289 #define	TCP_CLD_COUNTERS 0
290 
291 #define	TCP_TAG_CLEAN_DEATH 1
292 #define	TCP_MAX_CLEAN_DEATH_TAG 32
293 
294 #ifdef lint
295 static int _lint_dummy_;
296 #endif
297 
298 #if TCP_CLD_COUNTERS
299 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
300 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
301 #elif defined(lint)
302 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
303 #else
304 #define	TCP_CLD_STAT(x)
305 #endif
306 
307 #if TCP_DEBUG_COUNTER
308 #define	TCP_DBGSTAT(x) atomic_add_64(&(tcp_statistics.x.value.ui64), 1)
309 #elif defined(lint)
310 #define	TCP_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
311 #else
312 #define	TCP_DBGSTAT(x)
313 #endif
314 
315 tcp_stat_t tcp_statistics = {
316 	{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
317 	{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
318 	{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
319 	{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
320 	{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
321 	{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
322 	{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
323 	{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
324 	{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
325 	{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
326 	{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
327 	{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
328 	{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
329 	{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
330 	{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
331 	{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
332 	{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
333 	{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
334 	{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
335 	{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
336 	{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
337 	{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
338 	{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
339 	{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
340 	{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
341 	{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
342 	{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
343 	{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
344 	{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
345 	{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
346 	{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
347 	{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
348 	{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
349 	{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
350 	{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
351 	{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
352 	{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
353 	{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
354 	{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
355 	{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
356 	{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
357 	{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
358 	{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
359 	{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
360 	{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
361 	{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
362 	{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
363 	{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
364 	{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
365 	{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
366 	{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
367 	{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
368 	{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
369 	{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
370 	{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
371 	{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
372 	{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
373 	{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
374 	{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
375 	{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
376 	{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
377 	{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
378 	{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
379 	{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
380 	{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
381 	{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
382 	{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
383 	{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
384 	{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
385 	{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
386 	{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
387 	{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
388 	{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
389 	{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
390 	{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
391 	{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
392 	{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
393 	{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
394 	{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
395 	{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
396 	{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
397 	{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
398 	{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
399 	{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
400 	{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
401 	{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
402 	{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
403 	{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
404 	{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
405 };
406 
407 static kstat_t *tcp_kstat;
408 
409 /*
410  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
411  * tcp write side.
412  */
413 #define	CALL_IP_WPUT(connp, q, mp) {					\
414 	ASSERT(((q)->q_flag & QREADR) == 0);				\
415 	TCP_DBGSTAT(tcp_ip_output);					\
416 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
417 }
418 
419 /* Macros for timestamp comparisons */
420 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
421 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
422 
423 /*
424  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
425  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
426  * by adding three components: a time component which grows by 1 every 4096
427  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
428  * a per-connection component which grows by 125000 for every new connection;
429  * and an "extra" component that grows by a random amount centered
430  * approximately on 64000.  This causes the the ISS generator to cycle every
431  * 4.89 hours if no TCP connections are made, and faster if connections are
432  * made.
433  *
434  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
435  * components: a time component which grows by 250000 every second; and
436  * a per-connection component which grows by 125000 for every new connections.
437  *
438  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
439  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
440  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
441  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
442  * password.
443  */
444 #define	ISS_INCR	250000
445 #define	ISS_NSEC_SHT	12
446 
447 static uint32_t tcp_iss_incr_extra;	/* Incremented for each connection */
448 static kmutex_t tcp_iss_key_lock;
449 static MD5_CTX tcp_iss_key;
450 static sin_t	sin_null;	/* Zero address for quick clears */
451 static sin6_t	sin6_null;	/* Zero address for quick clears */
452 
453 /* Packet dropper for TCP IPsec policy drops. */
454 static ipdropper_t tcp_dropper;
455 
456 /*
457  * This implementation follows the 4.3BSD interpretation of the urgent
458  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
459  * incompatible changes in protocols like telnet and rlogin.
460  */
461 #define	TCP_OLD_URP_INTERPRETATION	1
462 
463 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
464 	(TCP_IS_DETACHED(tcp) && \
465 	    (!(tcp)->tcp_hard_binding))
466 
467 /*
468  * TCP reassembly macros.  We hide starting and ending sequence numbers in
469  * b_next and b_prev of messages on the reassembly queue.  The messages are
470  * chained using b_cont.  These macros are used in tcp_reass() so we don't
471  * have to see the ugly casts and assignments.
472  */
473 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
474 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
475 					(mblk_t *)(uintptr_t)(u))
476 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
477 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
478 					(mblk_t *)(uintptr_t)(u))
479 
480 /*
481  * Implementation of TCP Timers.
482  * =============================
483  *
484  * INTERFACE:
485  *
486  * There are two basic functions dealing with tcp timers:
487  *
488  *	timeout_id_t	tcp_timeout(connp, func, time)
489  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
490  *	TCP_TIMER_RESTART(tcp, intvl)
491  *
492  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
493  * after 'time' ticks passed. The function called by timeout() must adhere to
494  * the same restrictions as a driver soft interrupt handler - it must not sleep
495  * or call other functions that might sleep. The value returned is the opaque
496  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
497  * cancel the request. The call to tcp_timeout() may fail in which case it
498  * returns zero. This is different from the timeout(9F) function which never
499  * fails.
500  *
501  * The call-back function 'func' always receives 'connp' as its single
502  * argument. It is always executed in the squeue corresponding to the tcp
503  * structure. The tcp structure is guaranteed to be present at the time the
504  * call-back is called.
505  *
506  * NOTE: The call-back function 'func' is never called if tcp is in
507  * 	the TCPS_CLOSED state.
508  *
509  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
510  * request. locks acquired by the call-back routine should not be held across
511  * the call to tcp_timeout_cancel() or a deadlock may result.
512  *
513  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
514  * Otherwise, it returns an integer value greater than or equal to 0. In
515  * particular, if the call-back function is already placed on the squeue, it can
516  * not be canceled.
517  *
518  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
519  * 	within squeue context corresponding to the tcp instance. Since the
520  *	call-back is also called via the same squeue, there are no race
521  *	conditions described in untimeout(9F) manual page since all calls are
522  *	strictly serialized.
523  *
524  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
525  *	stored in tcp_timer_tid and starts a new one using
526  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
527  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
528  *	field.
529  *
530  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
531  *	call-back may still be called, so it is possible tcp_timer() will be
532  *	called several times. This should not be a problem since tcp_timer()
533  *	should always check the tcp instance state.
534  *
535  *
536  * IMPLEMENTATION:
537  *
538  * TCP timers are implemented using three-stage process. The call to
539  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
540  * when the timer expires. The tcp_timer_callback() arranges the call of the
541  * tcp_timer_handler() function via squeue corresponding to the tcp
542  * instance. The tcp_timer_handler() calls actual requested timeout call-back
543  * and passes tcp instance as an argument to it. Information is passed between
544  * stages using the tcp_timer_t structure which contains the connp pointer, the
545  * tcp call-back to call and the timeout id returned by the timeout(9F).
546  *
547  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
548  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
549  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
550  * returns the pointer to this mblk.
551  *
552  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
553  * looks like a normal mblk without actual dblk attached to it.
554  *
555  * To optimize performance each tcp instance holds a small cache of timer
556  * mblocks. In the current implementation it caches up to two timer mblocks per
557  * tcp instance. The cache is preserved over tcp frees and is only freed when
558  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
559  * timer processing happens on a corresponding squeue, the cache manipulation
560  * does not require any locks. Experiments show that majority of timer mblocks
561  * allocations are satisfied from the tcp cache and do not involve kmem calls.
562  *
563  * The tcp_timeout() places a refhold on the connp instance which guarantees
564  * that it will be present at the time the call-back function fires. The
565  * tcp_timer_handler() drops the reference after calling the call-back, so the
566  * call-back function does not need to manipulate the references explicitly.
567  */
568 
569 typedef struct tcp_timer_s {
570 	conn_t	*connp;
571 	void 	(*tcpt_proc)(void *);
572 	timeout_id_t   tcpt_tid;
573 } tcp_timer_t;
574 
575 static kmem_cache_t *tcp_timercache;
576 kmem_cache_t	*tcp_sack_info_cache;
577 kmem_cache_t	*tcp_iphc_cache;
578 
579 /*
580  * For scalability, we must not run a timer for every TCP connection
581  * in TIME_WAIT state.  To see why, consider (for time wait interval of
582  * 4 minutes):
583  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
584  *
585  * This list is ordered by time, so you need only delete from the head
586  * until you get to entries which aren't old enough to delete yet.
587  * The list consists of only the detached TIME_WAIT connections.
588  *
589  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
590  * becomes detached TIME_WAIT (either by changing the state and already
591  * being detached or the other way around). This means that the TIME_WAIT
592  * state can be extended (up to doubled) if the connection doesn't become
593  * detached for a long time.
594  *
595  * The list manipulations (including tcp_time_wait_next/prev)
596  * are protected by the tcp_time_wait_lock. The content of the
597  * detached TIME_WAIT connections is protected by the normal perimeters.
598  */
599 
600 typedef struct tcp_squeue_priv_s {
601 	kmutex_t	tcp_time_wait_lock;
602 				/* Protects the next 3 globals */
603 	timeout_id_t	tcp_time_wait_tid;
604 	tcp_t		*tcp_time_wait_head;
605 	tcp_t		*tcp_time_wait_tail;
606 	tcp_t		*tcp_free_list;
607 } tcp_squeue_priv_t;
608 
609 /*
610  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
611  * Running it every 5 seconds seems to give the best results.
612  */
613 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
614 
615 
616 #define	TCP_XMIT_LOWATER	4096
617 #define	TCP_XMIT_HIWATER	49152
618 #define	TCP_RECV_LOWATER	2048
619 #define	TCP_RECV_HIWATER	49152
620 
621 /*
622  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
623  */
624 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
625 
626 #define	TIDUSZ	4096	/* transport interface data unit size */
627 
628 /*
629  * Bind hash list size and has function.  It has to be a power of 2 for
630  * hashing.
631  */
632 #define	TCP_BIND_FANOUT_SIZE	512
633 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
634 /*
635  * Size of listen and acceptor hash list.  It has to be a power of 2 for
636  * hashing.
637  */
638 #define	TCP_FANOUT_SIZE		256
639 
640 #ifdef	_ILP32
641 #define	TCP_ACCEPTOR_HASH(accid)					\
642 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
643 #else
644 #define	TCP_ACCEPTOR_HASH(accid)					\
645 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
646 #endif	/* _ILP32 */
647 
648 #define	IP_ADDR_CACHE_SIZE	2048
649 #define	IP_ADDR_CACHE_HASH(faddr)					\
650 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
651 
652 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
653 #define	TCP_HSP_HASH_SIZE 256
654 
655 #define	TCP_HSP_HASH(addr)					\
656 	(((addr>>24) ^ (addr >>16) ^			\
657 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
658 
659 /*
660  * TCP options struct returned from tcp_parse_options.
661  */
662 typedef struct tcp_opt_s {
663 	uint32_t	tcp_opt_mss;
664 	uint32_t	tcp_opt_wscale;
665 	uint32_t	tcp_opt_ts_val;
666 	uint32_t	tcp_opt_ts_ecr;
667 	tcp_t		*tcp;
668 } tcp_opt_t;
669 
670 /*
671  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
672  */
673 
674 #ifdef _BIG_ENDIAN
675 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
676 	(TCPOPT_TSTAMP << 8) | 10)
677 #else
678 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
679 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
680 #endif
681 
682 /*
683  * Flags returned from tcp_parse_options.
684  */
685 #define	TCP_OPT_MSS_PRESENT	1
686 #define	TCP_OPT_WSCALE_PRESENT	2
687 #define	TCP_OPT_TSTAMP_PRESENT	4
688 #define	TCP_OPT_SACK_OK_PRESENT	8
689 #define	TCP_OPT_SACK_PRESENT	16
690 
691 /* TCP option length */
692 #define	TCPOPT_NOP_LEN		1
693 #define	TCPOPT_MAXSEG_LEN	4
694 #define	TCPOPT_WS_LEN		3
695 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
696 #define	TCPOPT_TSTAMP_LEN	10
697 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
698 #define	TCPOPT_SACK_OK_LEN	2
699 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
700 #define	TCPOPT_REAL_SACK_LEN	4
701 #define	TCPOPT_MAX_SACK_LEN	36
702 #define	TCPOPT_HEADER_LEN	2
703 
704 /* TCP cwnd burst factor. */
705 #define	TCP_CWND_INFINITE	65535
706 #define	TCP_CWND_SS		3
707 #define	TCP_CWND_NORMAL		5
708 
709 /* Maximum TCP initial cwin (start/restart). */
710 #define	TCP_MAX_INIT_CWND	8
711 
712 /*
713  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
714  * either tcp_slow_start_initial or tcp_slow_start_after idle
715  * depending on the caller.  If the upper layer has not used the
716  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
717  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
718  * If the upper layer has changed set the tcp_init_cwnd, just use
719  * it to calculate the tcp_cwnd.
720  */
721 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
722 {									\
723 	if ((tcp)->tcp_init_cwnd == 0) {				\
724 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
725 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
726 	} else {							\
727 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
728 	}								\
729 	tcp->tcp_cwnd_cnt = 0;						\
730 }
731 
732 /* TCP Timer control structure */
733 typedef struct tcpt_s {
734 	pfv_t	tcpt_pfv;	/* The routine we are to call */
735 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
736 } tcpt_t;
737 
738 /* Host Specific Parameter structure */
739 typedef struct tcp_hsp {
740 	struct tcp_hsp	*tcp_hsp_next;
741 	in6_addr_t	tcp_hsp_addr_v6;
742 	in6_addr_t	tcp_hsp_subnet_v6;
743 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
744 	int32_t		tcp_hsp_sendspace;
745 	int32_t		tcp_hsp_recvspace;
746 	int32_t		tcp_hsp_tstamp;
747 } tcp_hsp_t;
748 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
749 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
750 
751 /*
752  * Functions called directly via squeue having a prototype of edesc_t.
753  */
754 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
755 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
756 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
757 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
758 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
759 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
760 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
761 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
762 static void	tcp_output(void *arg, mblk_t *mp, void *arg2);
763 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
764 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
765 
766 
767 /* Prototype for TCP functions */
768 static void	tcp_random_init(void);
769 int		tcp_random(void);
770 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
771 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
772 		    tcp_t *eager);
773 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
774 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
775     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
776     boolean_t user_specified);
777 static void	tcp_closei_local(tcp_t *tcp);
778 static void	tcp_close_detached(tcp_t *tcp);
779 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
780 			mblk_t *idmp, mblk_t **defermp);
781 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
782 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
783 		    in_port_t dstport, uint_t srcid);
784 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
785 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
786 		    uint32_t scope_id);
787 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
788 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
789 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
790 static char	*tcp_display(tcp_t *tcp, char *, char);
791 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
792 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
793 static void	tcp_eager_unlink(tcp_t *tcp);
794 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
795 		    int unixerr);
796 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
797 		    int tlierr, int unixerr);
798 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
799 		    cred_t *cr);
800 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
801 		    char *value, caddr_t cp, cred_t *cr);
802 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
803 		    char *value, caddr_t cp, cred_t *cr);
804 static int	tcp_tpistate(tcp_t *tcp);
805 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
806     int caller_holds_lock);
807 static void	tcp_bind_hash_remove(tcp_t *tcp);
808 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id);
809 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
810 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
811 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
812 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
813 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
814 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
815 static int	tcp_header_init_ipv4(tcp_t *tcp);
816 static int	tcp_header_init_ipv6(tcp_t *tcp);
817 int		tcp_init(tcp_t *tcp, queue_t *q);
818 static int	tcp_init_values(tcp_t *tcp);
819 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
820 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
821 		    t_scalar_t addr_length);
822 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
823 static void	tcp_ip_notify(tcp_t *tcp);
824 static mblk_t	*tcp_ire_mp(mblk_t *mp);
825 static void	tcp_iss_init(tcp_t *tcp);
826 static void	tcp_keepalive_killer(void *arg);
827 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
828 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
829 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
830 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
831 static boolean_t tcp_allow_connopt_set(int level, int name);
832 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
833 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
834 static int	tcp_opt_get_user(ipha_t *ipha, uchar_t *ptr);
835 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
836 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
837 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
838 		    mblk_t *mblk);
839 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
840 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
841 		    uchar_t *ptr, uint_t len);
842 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
843 static boolean_t tcp_param_register(tcpparam_t *tcppa, int cnt);
844 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
845 		    caddr_t cp, cred_t *cr);
846 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
847 		    caddr_t cp, cred_t *cr);
848 static void	tcp_iss_key_init(uint8_t *phrase, int len);
849 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
850 		    caddr_t cp, cred_t *cr);
851 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
852 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
853 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
854 static void	tcp_reinit(tcp_t *tcp);
855 static void	tcp_reinit_values(tcp_t *tcp);
856 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
857 		    tcp_t *thisstream, cred_t *cr);
858 
859 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
860 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
861 static boolean_t tcp_send_rst_chk(void);
862 static void	tcp_ss_rexmit(tcp_t *tcp);
863 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
864 static void	tcp_process_options(tcp_t *, tcph_t *);
865 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
866 static void	tcp_rsrv(queue_t *q);
867 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
868 static int	tcp_snmp_state(tcp_t *tcp);
869 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
870 		    cred_t *cr);
871 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
872 		    cred_t *cr);
873 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
874 		    cred_t *cr);
875 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
876 		    cred_t *cr);
877 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
878 		    cred_t *cr);
879 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
880 		    caddr_t cp, cred_t *cr);
881 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
882 		    caddr_t cp, cred_t *cr);
883 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
884 		    cred_t *cr);
885 static void	tcp_timer(void *arg);
886 static void	tcp_timer_callback(void *);
887 static in_port_t tcp_update_next_port(in_port_t port, boolean_t random);
888 static in_port_t tcp_get_next_priv_port(void);
889 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
890 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
891 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
892 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
893 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
894 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
895 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
896 		    const int num_sack_blk, int *usable, uint_t *snxt,
897 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
898 		    const int mdt_thres);
899 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
900 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
901 		    const int num_sack_blk, int *usable, uint_t *snxt,
902 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
903 		    const int mdt_thres);
904 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
905 		    int num_sack_blk);
906 static void	tcp_wsrv(queue_t *q);
907 static int	tcp_xmit_end(tcp_t *tcp);
908 void		tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len);
909 static mblk_t	*tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send,
910 		    int32_t *offset, mblk_t **end_mp, uint32_t seq,
911 		    boolean_t sendall, uint32_t *seg_len, boolean_t rexmit);
912 static void	tcp_ack_timer(void *arg);
913 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
914 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
915 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len);
916 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
917 		    uint32_t ack, int ctl);
918 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr);
919 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr);
920 static int	setmaxps(queue_t *q, int maxpsz);
921 static void	tcp_set_rto(tcp_t *, time_t);
922 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
923 		    boolean_t, boolean_t);
924 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
925 		    boolean_t ipsec_mctl);
926 static boolean_t tcp_cmpbuf(void *a, uint_t alen,
927 		    boolean_t b_valid, void *b, uint_t blen);
928 static boolean_t tcp_allocbuf(void **dstp, uint_t *dstlenp,
929 		    boolean_t src_valid, void *src, uint_t srclen);
930 static void	tcp_savebuf(void **dstp, uint_t *dstlenp,
931 		    boolean_t src_valid, void *src, uint_t srclen);
932 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
933 		    char *opt, int optlen);
934 static int	tcp_pkt_set(uchar_t *, uint_t, uchar_t **, uint_t *);
935 static int	tcp_build_hdrs(queue_t *, tcp_t *);
936 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
937 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
938 		    tcph_t *tcph);
939 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
940 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
941 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
942 boolean_t	tcp_reserved_port_check(in_port_t);
943 static tcp_t	*tcp_alloc_temp_tcp(in_port_t);
944 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
945 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
946 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
947 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
948 		    const boolean_t, const uint32_t, const uint32_t,
949 		    const uint32_t, const uint32_t);
950 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
951 		    const uint_t, const uint_t, boolean_t *);
952 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
953 extern mblk_t	*tcp_timermp_alloc(int);
954 extern void	tcp_timermp_free(tcp_t *);
955 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
956 static void	tcp_stop_lingering(tcp_t *tcp);
957 static void	tcp_close_linger_timeout(void *arg);
958 void		tcp_ddi_init(void);
959 void		tcp_ddi_destroy(void);
960 static void	tcp_kstat_init(void);
961 static void	tcp_kstat_fini(void);
962 static int	tcp_kstat_update(kstat_t *kp, int rw);
963 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
964 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
965 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
966 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
967 			tcph_t *tcph, mblk_t *idmp);
968 static squeue_func_t tcp_squeue_switch(int);
969 
970 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
971 static int	tcp_close(queue_t *, int);
972 static int	tcpclose_accept(queue_t *);
973 static int	tcp_modclose(queue_t *);
974 static void	tcp_wput_mod(queue_t *, mblk_t *);
975 
976 static void	tcp_squeue_add(squeue_t *);
977 static boolean_t tcp_zcopy_check(tcp_t *);
978 static void	tcp_zcopy_notify(tcp_t *);
979 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
980 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
981 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
982 
983 /*
984  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
985  *
986  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
987  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
988  * (defined in tcp.h) needs to be filled in and passed into the kernel
989  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
990  * structure contains the four-tuple of a TCP connection and a range of TCP
991  * states (specified by ac_start and ac_end). The use of wildcard addresses
992  * and ports is allowed. Connections with a matching four tuple and a state
993  * within the specified range will be aborted. The valid states for the
994  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
995  * inclusive.
996  *
997  * An application which has its connection aborted by this ioctl will receive
998  * an error that is dependent on the connection state at the time of the abort.
999  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1000  * though a RST packet has been received.  If the connection state is equal to
1001  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1002  * and all resources associated with the connection will be freed.
1003  */
1004 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1005 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1006 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1007 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *);
1008 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1009 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1010     boolean_t);
1011 
1012 static struct module_info tcp_rinfo =  {
1013 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1014 };
1015 
1016 static struct module_info tcp_winfo =  {
1017 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1018 };
1019 
1020 /*
1021  * Entry points for TCP as a module. It only allows SNMP requests
1022  * to pass through.
1023  */
1024 struct qinit tcp_mod_rinit = {
1025 	(pfi_t)putnext, NULL, tcp_open, ip_snmpmod_close, NULL, &tcp_rinfo,
1026 };
1027 
1028 struct qinit tcp_mod_winit = {
1029 	(pfi_t)ip_snmpmod_wput, NULL, tcp_open, ip_snmpmod_close, NULL,
1030 	&tcp_rinfo
1031 };
1032 
1033 /*
1034  * Entry points for TCP as a device. The normal case which supports
1035  * the TCP functionality.
1036  */
1037 struct qinit tcp_rinit = {
1038 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
1039 };
1040 
1041 struct qinit tcp_winit = {
1042 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1043 };
1044 
1045 /* Initial entry point for TCP in socket mode. */
1046 struct qinit tcp_sock_winit = {
1047 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1048 };
1049 
1050 /*
1051  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1052  * an accept. Avoid allocating data structures since eager has already
1053  * been created.
1054  */
1055 struct qinit tcp_acceptor_rinit = {
1056 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1057 };
1058 
1059 struct qinit tcp_acceptor_winit = {
1060 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1061 };
1062 
1063 /*
1064  * Entry points for TCP loopback (read side only)
1065  */
1066 struct qinit tcp_loopback_rinit = {
1067 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_open, tcp_close, (pfi_t)0,
1068 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1069 };
1070 
1071 struct streamtab tcpinfo = {
1072 	&tcp_rinit, &tcp_winit
1073 };
1074 
1075 extern squeue_func_t tcp_squeue_wput_proc;
1076 extern squeue_func_t tcp_squeue_timer_proc;
1077 
1078 /* Protected by tcp_g_q_lock */
1079 static queue_t	*tcp_g_q;	/* Default queue used during detached closes */
1080 kmutex_t tcp_g_q_lock;
1081 
1082 /* Protected by tcp_hsp_lock */
1083 /*
1084  * XXX The host param mechanism should go away and instead we should use
1085  * the metrics associated with the routes to determine the default sndspace
1086  * and rcvspace.
1087  */
1088 static tcp_hsp_t	**tcp_hsp_hash;	/* Hash table for HSPs */
1089 krwlock_t tcp_hsp_lock;
1090 
1091 /*
1092  * Extra privileged ports. In host byte order.
1093  * Protected by tcp_epriv_port_lock.
1094  */
1095 #define	TCP_NUM_EPRIV_PORTS	64
1096 static int	tcp_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
1097 static uint16_t	tcp_g_epriv_ports[TCP_NUM_EPRIV_PORTS] = { 2049, 4045 };
1098 kmutex_t tcp_epriv_port_lock;
1099 
1100 /*
1101  * The smallest anonymous port in the priviledged port range which TCP
1102  * looks for free port.  Use in the option TCP_ANONPRIVBIND.
1103  */
1104 static in_port_t tcp_min_anonpriv_port = 512;
1105 
1106 /* Only modified during _init and _fini thus no locking is needed. */
1107 static caddr_t	tcp_g_nd;	/* Head of 'named dispatch' variable list */
1108 
1109 /* Hint not protected by any lock */
1110 static uint_t	tcp_next_port_to_try;
1111 
1112 
1113 /* TCP bind hash list - all tcp_t with state >= BOUND. */
1114 static tf_t	tcp_bind_fanout[TCP_BIND_FANOUT_SIZE];
1115 
1116 /* TCP queue hash list - all tcp_t in case they will be an acceptor. */
1117 static tf_t	tcp_acceptor_fanout[TCP_FANOUT_SIZE];
1118 
1119 /*
1120  * TCP has a private interface for other kernel modules to reserve a
1121  * port range for them to use.  Once reserved, TCP will not use any ports
1122  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1123  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1124  * has to be verified.
1125  *
1126  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1127  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1128  * range is [port a, port b] inclusive.  And each port range is between
1129  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1130  *
1131  * Note that the default anonymous port range starts from 32768.  There is
1132  * no port "collision" between that and the reserved port range.  If there
1133  * is port collision (because the default smallest anonymous port is lowered
1134  * or some apps specifically bind to ports in the reserved port range), the
1135  * system may not be able to reserve a port range even there are enough
1136  * unbound ports as a reserved port range contains consecutive ports .
1137  */
1138 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1139 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1140 #define	TCP_SMALLEST_RESERVED_PORT		10240
1141 #define	TCP_LARGEST_RESERVED_PORT		20480
1142 
1143 /* Structure to represent those reserved port ranges. */
1144 typedef struct tcp_rport_s {
1145 	in_port_t	lo_port;
1146 	in_port_t	hi_port;
1147 	tcp_t		**temp_tcp_array;
1148 } tcp_rport_t;
1149 
1150 /* The reserved port array. */
1151 static tcp_rport_t tcp_reserved_port[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
1152 
1153 /* Locks to protect the tcp_reserved_ports array. */
1154 static krwlock_t tcp_reserved_port_lock;
1155 
1156 /* The number of ranges in the array. */
1157 uint32_t tcp_reserved_port_array_size = 0;
1158 
1159 /*
1160  * MIB-2 stuff for SNMP
1161  * Note: tcpInErrs {tcp 15} is accumulated in ip.c
1162  */
1163 mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */
1164 kstat_t		*tcp_mibkp;	/* kstat exporting tcp_mib data */
1165 
1166 boolean_t tcp_icmp_source_quench = B_FALSE;
1167 /*
1168  * Following assumes TPI alignment requirements stay along 32 bit
1169  * boundaries
1170  */
1171 #define	ROUNDUP32(x) \
1172 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1173 
1174 /* Template for response to info request. */
1175 static struct T_info_ack tcp_g_t_info_ack = {
1176 	T_INFO_ACK,		/* PRIM_type */
1177 	0,			/* TSDU_size */
1178 	T_INFINITE,		/* ETSDU_size */
1179 	T_INVALID,		/* CDATA_size */
1180 	T_INVALID,		/* DDATA_size */
1181 	sizeof (sin_t),		/* ADDR_size */
1182 	0,			/* OPT_size - not initialized here */
1183 	TIDUSZ,			/* TIDU_size */
1184 	T_COTS_ORD,		/* SERV_type */
1185 	TCPS_IDLE,		/* CURRENT_state */
1186 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1187 };
1188 
1189 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1190 	T_INFO_ACK,		/* PRIM_type */
1191 	0,			/* TSDU_size */
1192 	T_INFINITE,		/* ETSDU_size */
1193 	T_INVALID,		/* CDATA_size */
1194 	T_INVALID,		/* DDATA_size */
1195 	sizeof (sin6_t),	/* ADDR_size */
1196 	0,			/* OPT_size - not initialized here */
1197 	TIDUSZ,		/* TIDU_size */
1198 	T_COTS_ORD,		/* SERV_type */
1199 	TCPS_IDLE,		/* CURRENT_state */
1200 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1201 };
1202 
1203 #define	MS	1L
1204 #define	SECONDS	(1000 * MS)
1205 #define	MINUTES	(60 * SECONDS)
1206 #define	HOURS	(60 * MINUTES)
1207 #define	DAYS	(24 * HOURS)
1208 
1209 #define	PARAM_MAX (~(uint32_t)0)
1210 
1211 /* Max size IP datagram is 64k - 1 */
1212 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1213 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1214 /* Max of the above */
1215 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1216 
1217 /* Largest TCP port number */
1218 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1219 
1220 /*
1221  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1222  * layer header.  It has to be a multiple of 4.
1223  */
1224 static tcpparam_t tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1225 #define	tcp_wroff_xtra	tcp_wroff_xtra_param.tcp_param_val
1226 
1227 /*
1228  * All of these are alterable, within the min/max values given, at run time.
1229  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1230  * per the TCP spec.
1231  */
1232 /* BEGIN CSTYLED */
1233 tcpparam_t	tcp_param_arr[] = {
1234  /*min		max		value		name */
1235  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1236  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1237  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1238  { 1,		1024,		1,		"tcp_conn_req_min" },
1239  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1240  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1241  { 0,		10,		0,		"tcp_debug" },
1242  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1243  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1244  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1245  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1246  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1247  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1248  { 1,		255,		64,		"tcp_ipv4_ttl"},
1249  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1250  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1251  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1252  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1253  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1254  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1255  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1256  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1257  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1258  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1259  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1260  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1261  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1262  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1263  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1264  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1265  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1266  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1267  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1268  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1269  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1270  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1271  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1272  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1273 /*
1274  * Question:  What default value should I set for tcp_strong_iss?
1275  */
1276  { 0,		2,		1,		"tcp_strong_iss"},
1277  { 0,		65536,		20,		"tcp_rtt_updates"},
1278  { 0,		1,		1,		"tcp_wscale_always"},
1279  { 0,		1,		0,		"tcp_tstamp_always"},
1280  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1281  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1282  { 0,		16,		2,		"tcp_deferred_acks_max"},
1283  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1284  { 1,		4,		4,		"tcp_slow_start_initial"},
1285  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1286  { 0,		2,		2,		"tcp_sack_permitted"},
1287  { 0,		1,		0,		"tcp_trace"},
1288  { 0,		1,		1,		"tcp_compression_enabled"},
1289  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1290  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1291  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1292  { 0,		1,		0,		"tcp_rev_src_routes"},
1293  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1294  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1295  { 0,		16,		8,		"tcp_local_dacks_max"},
1296  { 0,		2,		1,		"tcp_ecn_permitted"},
1297  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1298  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1299  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1300  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1301  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1302 };
1303 /* END CSTYLED */
1304 
1305 /*
1306  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1307  * each header fragment in the header buffer.  Each parameter value has
1308  * to be a multiple of 4 (32-bit aligned).
1309  */
1310 static tcpparam_t tcp_mdt_head_param = { 32, 256, 32, "tcp_mdt_hdr_head_min" };
1311 static tcpparam_t tcp_mdt_tail_param = { 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1312 #define	tcp_mdt_hdr_head_min	tcp_mdt_head_param.tcp_param_val
1313 #define	tcp_mdt_hdr_tail_min	tcp_mdt_tail_param.tcp_param_val
1314 
1315 /*
1316  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1317  * the maximum number of payload buffers associated per Multidata.
1318  */
1319 static tcpparam_t tcp_mdt_max_pbufs_param =
1320 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1321 #define	tcp_mdt_max_pbufs	tcp_mdt_max_pbufs_param.tcp_param_val
1322 
1323 /* Round up the value to the nearest mss. */
1324 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1325 
1326 /*
1327  * Set ECN capable transport (ECT) code point in IP header.
1328  *
1329  * Note that there are 2 ECT code points '01' and '10', which are called
1330  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1331  * point ECT(0) for TCP as described in RFC 2481.
1332  */
1333 #define	SET_ECT(tcp, iph) \
1334 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1335 		/* We need to clear the code point first. */ \
1336 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1337 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1338 	} else { \
1339 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1340 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1341 	}
1342 
1343 /*
1344  * The format argument to pass to tcp_display().
1345  * DISP_PORT_ONLY means that the returned string has only port info.
1346  * DISP_ADDR_AND_PORT means that the returned string also contains the
1347  * remote and local IP address.
1348  */
1349 #define	DISP_PORT_ONLY		1
1350 #define	DISP_ADDR_AND_PORT	2
1351 
1352 /*
1353  * This controls the rate some ndd info report functions can be used
1354  * by non-priviledged users.  It stores the last time such info is
1355  * requested.  When those report functions are called again, this
1356  * is checked with the current time and compare with the ndd param
1357  * tcp_ndd_get_info_interval.
1358  */
1359 static clock_t tcp_last_ndd_get_info_time = 0;
1360 #define	NDD_TOO_QUICK_MSG \
1361 	"ndd get info rate too high for non-priviledged users, try again " \
1362 	"later.\n"
1363 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1364 
1365 #define	IS_VMLOANED_MBLK(mp) \
1366 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1367 
1368 /*
1369  * These two variables control the rate for TCP to generate RSTs in
1370  * response to segments not belonging to any connections.  We limit
1371  * TCP to sent out tcp_rst_sent_rate (ndd param) number of RSTs in
1372  * each 1 second interval.  This is to protect TCP against DoS attack.
1373  */
1374 static clock_t tcp_last_rst_intrvl;
1375 static uint32_t tcp_rst_cnt;
1376 
1377 /* The number of RST not sent because of the rate limit. */
1378 static uint32_t tcp_rst_unsent;
1379 
1380 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1381 boolean_t tcp_mdt_chain = B_TRUE;
1382 
1383 /*
1384  * MDT threshold in the form of effective send MSS multiplier; we take
1385  * the MDT path if the amount of unsent data exceeds the threshold value
1386  * (default threshold is 1*SMSS).
1387  */
1388 uint_t tcp_mdt_smss_threshold = 1;
1389 
1390 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1391 
1392 /*
1393  * Forces all connections to obey the value of the tcp_maxpsz_multiplier
1394  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1395  * determined dynamically during tcp_adapt_ire(), which is the default.
1396  */
1397 boolean_t tcp_static_maxpsz = B_FALSE;
1398 
1399 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1400 uint32_t tcp_random_anon_port = 1;
1401 
1402 /*
1403  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1404  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1405  * data, TCP will not respond with an ACK.  RFC 793 requires that
1406  * TCP responds with an ACK for such a bogus ACK.  By not following
1407  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1408  * an attacker successfully spoofs an acceptable segment to our
1409  * peer; or when our peer is "confused."
1410  */
1411 uint32_t tcp_drop_ack_unsent_cnt = 10;
1412 
1413 /*
1414  * Hook functions to enable cluster networking
1415  * On non-clustered systems these vectors must always be NULL.
1416  */
1417 
1418 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1419 			    uint8_t *laddrp, in_port_t lport) = NULL;
1420 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1421 			    uint8_t *laddrp, in_port_t lport) = NULL;
1422 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1423 			    uint8_t *laddrp, in_port_t lport,
1424 			    uint8_t *faddrp, in_port_t fport) = NULL;
1425 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1426 			    uint8_t *laddrp, in_port_t lport,
1427 			    uint8_t *faddrp, in_port_t fport) = NULL;
1428 
1429 /*
1430  * The following are defined in ip.c
1431  */
1432 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1433 				uint8_t *laddrp);
1434 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1435 				uint8_t *laddrp, uint8_t *faddrp);
1436 
1437 #define	CL_INET_CONNECT(tcp)		{			\
1438 	if (cl_inet_connect != NULL) {				\
1439 		/*						\
1440 		 * Running in cluster mode - register active connection	\
1441 		 * information						\
1442 		 */							\
1443 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1444 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1445 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1446 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1447 				    (in_port_t)(tcp)->tcp_lport,	\
1448 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1449 				    (in_port_t)(tcp)->tcp_fport);	\
1450 			}						\
1451 		} else {						\
1452 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1453 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1454 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1455 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1456 				    (in_port_t)(tcp)->tcp_lport,	\
1457 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1458 				    (in_port_t)(tcp)->tcp_fport);	\
1459 			}						\
1460 		}							\
1461 	}								\
1462 }
1463 
1464 #define	CL_INET_DISCONNECT(tcp)	{				\
1465 	if (cl_inet_disconnect != NULL) {				\
1466 		/*							\
1467 		 * Running in cluster mode - deregister active		\
1468 		 * connection information				\
1469 		 */							\
1470 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1471 			if ((tcp)->tcp_ip_src != 0) {			\
1472 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1473 				    AF_INET,				\
1474 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1475 				    (in_port_t)(tcp)->tcp_lport,	\
1476 				    (uint8_t *)				\
1477 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1478 				    (in_port_t)(tcp)->tcp_fport);	\
1479 			}						\
1480 		} else {						\
1481 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1482 			    &(tcp)->tcp_ip_src_v6)) {			\
1483 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1484 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1485 				    (in_port_t)(tcp)->tcp_lport,	\
1486 				    (uint8_t *)				\
1487 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1488 				    (in_port_t)(tcp)->tcp_fport);	\
1489 			}						\
1490 		}							\
1491 	}								\
1492 }
1493 
1494 /*
1495  * Cluster networking hook for traversing current connection list.
1496  * This routine is used to extract the current list of live connections
1497  * which must continue to to be dispatched to this node.
1498  */
1499 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1500 
1501 /*
1502  * Figure out the value of window scale opton.  Note that the rwnd is
1503  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1504  * We cannot find the scale value and then do a round up of tcp_rwnd
1505  * because the scale value may not be correct after that.
1506  *
1507  * Set the compiler flag to make this function inline.
1508  */
1509 static void
1510 tcp_set_ws_value(tcp_t *tcp)
1511 {
1512 	int i;
1513 	uint32_t rwnd = tcp->tcp_rwnd;
1514 
1515 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1516 	    i++, rwnd >>= 1)
1517 		;
1518 	tcp->tcp_rcv_ws = i;
1519 }
1520 
1521 /*
1522  * Remove a connection from the list of detached TIME_WAIT connections.
1523  */
1524 static void
1525 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1526 {
1527 	boolean_t	locked = B_FALSE;
1528 
1529 	if (tcp_time_wait == NULL) {
1530 		tcp_time_wait = *((tcp_squeue_priv_t **)
1531 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1532 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1533 		locked = B_TRUE;
1534 	}
1535 
1536 	if (tcp->tcp_time_wait_expire == 0) {
1537 		ASSERT(tcp->tcp_time_wait_next == NULL);
1538 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1539 		if (locked)
1540 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1541 		return;
1542 	}
1543 	ASSERT(TCP_IS_DETACHED(tcp));
1544 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1545 
1546 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1547 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1548 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1549 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1550 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1551 			    NULL;
1552 		} else {
1553 			tcp_time_wait->tcp_time_wait_tail = NULL;
1554 		}
1555 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1556 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1557 		ASSERT(tcp->tcp_time_wait_next == NULL);
1558 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1559 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1560 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1561 	} else {
1562 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1563 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1564 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1565 		    tcp->tcp_time_wait_next;
1566 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1567 		    tcp->tcp_time_wait_prev;
1568 	}
1569 	tcp->tcp_time_wait_next = NULL;
1570 	tcp->tcp_time_wait_prev = NULL;
1571 	tcp->tcp_time_wait_expire = 0;
1572 
1573 	if (locked)
1574 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1575 }
1576 
1577 /*
1578  * Add a connection to the list of detached TIME_WAIT connections
1579  * and set its time to expire.
1580  */
1581 static void
1582 tcp_time_wait_append(tcp_t *tcp)
1583 {
1584 	tcp_squeue_priv_t *tcp_time_wait =
1585 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1586 		SQPRIVATE_TCP));
1587 
1588 	tcp_timers_stop(tcp);
1589 
1590 	/* Freed above */
1591 	ASSERT(tcp->tcp_timer_tid == 0);
1592 	ASSERT(tcp->tcp_ack_tid == 0);
1593 
1594 	/* must have happened at the time of detaching the tcp */
1595 	ASSERT(tcp->tcp_ptpahn == NULL);
1596 	ASSERT(tcp->tcp_flow_stopped == 0);
1597 	ASSERT(tcp->tcp_time_wait_next == NULL);
1598 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1599 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1600 	ASSERT(tcp->tcp_listener == NULL);
1601 
1602 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1603 	/*
1604 	 * The value computed below in tcp->tcp_time_wait_expire may
1605 	 * appear negative or wrap around. That is ok since our
1606 	 * interest is only in the difference between the current lbolt
1607 	 * value and tcp->tcp_time_wait_expire. But the value should not
1608 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1609 	 * The corresponding comparison in tcp_time_wait_collector() uses
1610 	 * modular arithmetic.
1611 	 */
1612 	tcp->tcp_time_wait_expire +=
1613 	    drv_usectohz(tcp_time_wait_interval * 1000);
1614 	if (tcp->tcp_time_wait_expire == 0)
1615 		tcp->tcp_time_wait_expire = 1;
1616 
1617 	ASSERT(TCP_IS_DETACHED(tcp));
1618 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1619 	ASSERT(tcp->tcp_time_wait_next == NULL);
1620 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1621 	TCP_DBGSTAT(tcp_time_wait);
1622 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1623 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1624 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1625 		tcp_time_wait->tcp_time_wait_head = tcp;
1626 	} else {
1627 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1628 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1629 		    TCPS_TIME_WAIT);
1630 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1631 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1632 	}
1633 	tcp_time_wait->tcp_time_wait_tail = tcp;
1634 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1635 }
1636 
1637 /* ARGSUSED */
1638 void
1639 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1640 {
1641 	conn_t	*connp = (conn_t *)arg;
1642 	tcp_t	*tcp = connp->conn_tcp;
1643 
1644 	ASSERT(tcp != NULL);
1645 	if (tcp->tcp_state == TCPS_CLOSED) {
1646 		return;
1647 	}
1648 
1649 	ASSERT((tcp->tcp_family == AF_INET &&
1650 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1651 	    (tcp->tcp_family == AF_INET6 &&
1652 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1653 	    tcp->tcp_ipversion == IPV6_VERSION)));
1654 	ASSERT(!tcp->tcp_listener);
1655 
1656 	TCP_STAT(tcp_time_wait_reap);
1657 	ASSERT(TCP_IS_DETACHED(tcp));
1658 
1659 	/*
1660 	 * Because they have no upstream client to rebind or tcp_close()
1661 	 * them later, we axe the connection here and now.
1662 	 */
1663 	tcp_close_detached(tcp);
1664 }
1665 
1666 void
1667 tcp_cleanup(tcp_t *tcp)
1668 {
1669 	mblk_t		*mp;
1670 	char		*tcp_iphc;
1671 	int		tcp_iphc_len;
1672 	int		tcp_hdr_grown;
1673 	tcp_sack_info_t	*tcp_sack_info;
1674 	conn_t		*connp = tcp->tcp_connp;
1675 
1676 	tcp_bind_hash_remove(tcp);
1677 	tcp_free(tcp);
1678 
1679 	conn_delete_ire(connp, NULL);
1680 	if (connp->conn_flags & IPCL_TCPCONN) {
1681 		if (connp->conn_latch != NULL)
1682 			IPLATCH_REFRELE(connp->conn_latch);
1683 		if (connp->conn_policy != NULL)
1684 			IPPH_REFRELE(connp->conn_policy);
1685 	}
1686 
1687 	/*
1688 	 * Since we will bzero the entire structure, we need to
1689 	 * remove it and reinsert it in global hash list. We
1690 	 * know the walkers can't get to this conn because we
1691 	 * had set CONDEMNED flag earlier and checked reference
1692 	 * under conn_lock so walker won't pick it and when we
1693 	 * go the ipcl_globalhash_remove() below, no walker
1694 	 * can get to it.
1695 	 */
1696 	ipcl_globalhash_remove(connp);
1697 
1698 	/* Save some state */
1699 	mp = tcp->tcp_timercache;
1700 
1701 	tcp_sack_info = tcp->tcp_sack_info;
1702 	tcp_iphc = tcp->tcp_iphc;
1703 	tcp_iphc_len = tcp->tcp_iphc_len;
1704 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1705 
1706 	bzero(connp, sizeof (conn_t));
1707 	bzero(tcp, sizeof (tcp_t));
1708 
1709 	/* restore the state */
1710 	tcp->tcp_timercache = mp;
1711 
1712 	tcp->tcp_sack_info = tcp_sack_info;
1713 	tcp->tcp_iphc = tcp_iphc;
1714 	tcp->tcp_iphc_len = tcp_iphc_len;
1715 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1716 
1717 
1718 	tcp->tcp_connp = connp;
1719 
1720 	connp->conn_tcp = tcp;
1721 	connp->conn_flags = IPCL_TCPCONN;
1722 	connp->conn_state_flags = CONN_INCIPIENT;
1723 	connp->conn_ulp = IPPROTO_TCP;
1724 	connp->conn_ref = 1;
1725 
1726 	ipcl_globalhash_insert(connp);
1727 }
1728 
1729 /*
1730  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1731  * is done forwards from the head.
1732  */
1733 /* ARGSUSED */
1734 void
1735 tcp_time_wait_collector(void *arg)
1736 {
1737 	tcp_t *tcp;
1738 	clock_t now;
1739 	mblk_t *mp;
1740 	conn_t *connp;
1741 	kmutex_t *lock;
1742 
1743 	squeue_t *sqp = (squeue_t *)arg;
1744 	tcp_squeue_priv_t *tcp_time_wait =
1745 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1746 
1747 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1748 	tcp_time_wait->tcp_time_wait_tid = 0;
1749 
1750 	if (tcp_time_wait->tcp_free_list != NULL &&
1751 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1752 		TCP_STAT(tcp_freelist_cleanup);
1753 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1754 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1755 			CONN_DEC_REF(tcp->tcp_connp);
1756 		}
1757 	}
1758 
1759 	/*
1760 	 * In order to reap time waits reliably, we should use a
1761 	 * source of time that is not adjustable by the user -- hence
1762 	 * the call to ddi_get_lbolt().
1763 	 */
1764 	now = ddi_get_lbolt();
1765 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1766 		/*
1767 		 * Compare times using modular arithmetic, since
1768 		 * lbolt can wrapover.
1769 		 */
1770 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1771 			break;
1772 		}
1773 
1774 		tcp_time_wait_remove(tcp, tcp_time_wait);
1775 
1776 		connp = tcp->tcp_connp;
1777 		ASSERT(connp->conn_fanout != NULL);
1778 		lock = &connp->conn_fanout->connf_lock;
1779 		/*
1780 		 * This is essentially a TW reclaim fast path optimization for
1781 		 * performance where the timewait collector checks under the
1782 		 * fanout lock (so that no one else can get access to the
1783 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1784 		 * the classifier hash list. If ref count is indeed 2, we can
1785 		 * just remove the conn under the fanout lock and avoid
1786 		 * cleaning up the conn under the squeue, provided that
1787 		 * clustering callbacks are not enabled. If clustering is
1788 		 * enabled, we need to make the clustering callback before
1789 		 * setting the CONDEMNED flag and after dropping all locks and
1790 		 * so we forego this optimization and fall back to the slow
1791 		 * path. Also please see the comments in tcp_closei_local
1792 		 * regarding the refcnt logic.
1793 		 *
1794 		 * Since we are holding the tcp_time_wait_lock, its better
1795 		 * not to block on the fanout_lock because other connections
1796 		 * can't add themselves to time_wait list. So we do a
1797 		 * tryenter instead of mutex_enter.
1798 		 */
1799 		if (mutex_tryenter(lock)) {
1800 			mutex_enter(&connp->conn_lock);
1801 			if ((connp->conn_ref == 2) &&
1802 			    (cl_inet_disconnect == NULL)) {
1803 				ipcl_hash_remove_locked(connp,
1804 				    connp->conn_fanout);
1805 				/*
1806 				 * Set the CONDEMNED flag now itself so that
1807 				 * the refcnt cannot increase due to any
1808 				 * walker. But we have still not cleaned up
1809 				 * conn_ire_cache. This is still ok since
1810 				 * we are going to clean it up in tcp_cleanup
1811 				 * immediately and any interface unplumb
1812 				 * thread will wait till the ire is blown away
1813 				 */
1814 				connp->conn_state_flags |= CONN_CONDEMNED;
1815 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1816 				mutex_exit(lock);
1817 				mutex_exit(&connp->conn_lock);
1818 				tcp_cleanup(tcp);
1819 				mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1820 				tcp->tcp_time_wait_next =
1821 				    tcp_time_wait->tcp_free_list;
1822 				tcp_time_wait->tcp_free_list = tcp;
1823 				continue;
1824 			} else {
1825 				CONN_INC_REF_LOCKED(connp);
1826 				mutex_exit(lock);
1827 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1828 				mutex_exit(&connp->conn_lock);
1829 				/*
1830 				 * We can reuse the closemp here since conn has
1831 				 * detached (otherwise we wouldn't even be in
1832 				 * time_wait list).
1833 				 */
1834 				mp = &tcp->tcp_closemp;
1835 				squeue_fill(connp->conn_sqp, mp,
1836 				    tcp_timewait_output, connp,
1837 				    SQTAG_TCP_TIMEWAIT);
1838 			}
1839 		} else {
1840 			mutex_enter(&connp->conn_lock);
1841 			CONN_INC_REF_LOCKED(connp);
1842 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1843 			mutex_exit(&connp->conn_lock);
1844 			/*
1845 			 * We can reuse the closemp here since conn has
1846 			 * detached (otherwise we wouldn't even be in
1847 			 * time_wait list).
1848 			 */
1849 			mp = &tcp->tcp_closemp;
1850 			squeue_fill(connp->conn_sqp, mp,
1851 			    tcp_timewait_output, connp, 0);
1852 		}
1853 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1854 	}
1855 
1856 	if (tcp_time_wait->tcp_free_list != NULL)
1857 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1858 
1859 	tcp_time_wait->tcp_time_wait_tid =
1860 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1861 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1862 }
1863 
1864 /*
1865  * Reply to a clients T_CONN_RES TPI message. This function
1866  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1867  * on the acceptor STREAM and processed in tcp_wput_accept().
1868  * Read the block comment on top of tcp_conn_request().
1869  */
1870 static void
1871 tcp_accept(tcp_t *listener, mblk_t *mp)
1872 {
1873 	tcp_t	*acceptor;
1874 	tcp_t	*eager;
1875 	tcp_t   *tcp;
1876 	struct T_conn_res	*tcr;
1877 	t_uscalar_t	acceptor_id;
1878 	t_scalar_t	seqnum;
1879 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1880 	mblk_t	*ok_mp;
1881 	mblk_t	*mp1;
1882 
1883 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1884 		tcp_err_ack(listener, mp, TPROTO, 0);
1885 		return;
1886 	}
1887 	tcr = (struct T_conn_res *)mp->b_rptr;
1888 
1889 	/*
1890 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1891 	 * read side queue of the streams device underneath us i.e. the
1892 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1893 	 * look it up in the queue_hash.  Under LP64 it sends down the
1894 	 * minor_t of the accepting endpoint.
1895 	 *
1896 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1897 	 * fanout hash lock is held.
1898 	 * This prevents any thread from entering the acceptor queue from
1899 	 * below (since it has not been hard bound yet i.e. any inbound
1900 	 * packets will arrive on the listener or default tcp queue and
1901 	 * go through tcp_lookup).
1902 	 * The CONN_INC_REF will prevent the acceptor from closing.
1903 	 *
1904 	 * XXX It is still possible for a tli application to send down data
1905 	 * on the accepting stream while another thread calls t_accept.
1906 	 * This should not be a problem for well-behaved applications since
1907 	 * the T_OK_ACK is sent after the queue swapping is completed.
1908 	 *
1909 	 * If the accepting fd is the same as the listening fd, avoid
1910 	 * queue hash lookup since that will return an eager listener in a
1911 	 * already established state.
1912 	 */
1913 	acceptor_id = tcr->ACCEPTOR_id;
1914 	mutex_enter(&listener->tcp_eager_lock);
1915 	if (listener->tcp_acceptor_id == acceptor_id) {
1916 		eager = listener->tcp_eager_next_q;
1917 		/* only count how many T_CONN_INDs so don't count q0 */
1918 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1919 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1920 			mutex_exit(&listener->tcp_eager_lock);
1921 			tcp_err_ack(listener, mp, TBADF, 0);
1922 			return;
1923 		}
1924 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1925 			/* Throw away all the eagers on q0. */
1926 			tcp_eager_cleanup(listener, 1);
1927 		}
1928 		if (listener->tcp_syn_defense) {
1929 			listener->tcp_syn_defense = B_FALSE;
1930 			if (listener->tcp_ip_addr_cache != NULL) {
1931 				kmem_free(listener->tcp_ip_addr_cache,
1932 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1933 				listener->tcp_ip_addr_cache = NULL;
1934 			}
1935 		}
1936 		/*
1937 		 * Transfer tcp_conn_req_max to the eager so that when
1938 		 * a disconnect occurs we can revert the endpoint to the
1939 		 * listen state.
1940 		 */
1941 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1942 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1943 		/*
1944 		 * Get a reference on the acceptor just like the
1945 		 * tcp_acceptor_hash_lookup below.
1946 		 */
1947 		acceptor = listener;
1948 		CONN_INC_REF(acceptor->tcp_connp);
1949 	} else {
1950 		acceptor = tcp_acceptor_hash_lookup(acceptor_id);
1951 		if (acceptor == NULL) {
1952 			if (listener->tcp_debug) {
1953 				(void) strlog(TCP_MOD_ID, 0, 1,
1954 				    SL_ERROR|SL_TRACE,
1955 				    "tcp_accept: did not find acceptor 0x%x\n",
1956 				    acceptor_id);
1957 			}
1958 			mutex_exit(&listener->tcp_eager_lock);
1959 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1960 			return;
1961 		}
1962 		/*
1963 		 * Verify acceptor state. The acceptable states for an acceptor
1964 		 * include TCPS_IDLE and TCPS_BOUND.
1965 		 */
1966 		switch (acceptor->tcp_state) {
1967 		case TCPS_IDLE:
1968 			/* FALLTHRU */
1969 		case TCPS_BOUND:
1970 			break;
1971 		default:
1972 			CONN_DEC_REF(acceptor->tcp_connp);
1973 			mutex_exit(&listener->tcp_eager_lock);
1974 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
1975 			return;
1976 		}
1977 	}
1978 
1979 	/* The listener must be in TCPS_LISTEN */
1980 	if (listener->tcp_state != TCPS_LISTEN) {
1981 		CONN_DEC_REF(acceptor->tcp_connp);
1982 		mutex_exit(&listener->tcp_eager_lock);
1983 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
1984 		return;
1985 	}
1986 
1987 	/*
1988 	 * Rendezvous with an eager connection request packet hanging off
1989 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
1990 	 * tcp structure when the connection packet arrived in
1991 	 * tcp_conn_request().
1992 	 */
1993 	seqnum = tcr->SEQ_number;
1994 	eager = listener;
1995 	do {
1996 		eager = eager->tcp_eager_next_q;
1997 		if (eager == NULL) {
1998 			CONN_DEC_REF(acceptor->tcp_connp);
1999 			mutex_exit(&listener->tcp_eager_lock);
2000 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2001 			return;
2002 		}
2003 	} while (eager->tcp_conn_req_seqnum != seqnum);
2004 	mutex_exit(&listener->tcp_eager_lock);
2005 
2006 	/*
2007 	 * At this point, both acceptor and listener have 2 ref
2008 	 * that they begin with. Acceptor has one additional ref
2009 	 * we placed in lookup while listener has 3 additional
2010 	 * ref for being behind the squeue (tcp_accept() is
2011 	 * done on listener's squeue); being in classifier hash;
2012 	 * and eager's ref on listener.
2013 	 */
2014 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2015 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2016 
2017 	/*
2018 	 * The eager at this point is set in its own squeue and
2019 	 * could easily have been killed (tcp_accept_finish will
2020 	 * deal with that) because of a TH_RST so we can only
2021 	 * ASSERT for a single ref.
2022 	 */
2023 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2024 
2025 	/* Pre allocate the stroptions mblk also */
2026 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2027 	if (opt_mp == NULL) {
2028 		CONN_DEC_REF(acceptor->tcp_connp);
2029 		CONN_DEC_REF(eager->tcp_connp);
2030 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2031 		return;
2032 	}
2033 	DB_TYPE(opt_mp) = M_SETOPTS;
2034 	opt_mp->b_wptr += sizeof (struct stroptions);
2035 
2036 	/*
2037 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2038 	 * from listener to acceptor. The message is chained on opt_mp
2039 	 * which will be sent onto eager's squeue.
2040 	 */
2041 	if (listener->tcp_bound_if != 0) {
2042 		/* allocate optmgmt req */
2043 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2044 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2045 		    sizeof (int));
2046 		if (mp1 != NULL)
2047 			linkb(opt_mp, mp1);
2048 	}
2049 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2050 		uint_t on = 1;
2051 
2052 		/* allocate optmgmt req */
2053 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2054 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2055 		if (mp1 != NULL)
2056 			linkb(opt_mp, mp1);
2057 	}
2058 
2059 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2060 	if ((mp1 = copymsg(mp)) == NULL) {
2061 		CONN_DEC_REF(acceptor->tcp_connp);
2062 		CONN_DEC_REF(eager->tcp_connp);
2063 		freemsg(opt_mp);
2064 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2065 		return;
2066 	}
2067 
2068 	tcr = (struct T_conn_res *)mp1->b_rptr;
2069 
2070 	/*
2071 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2072 	 * which allocates a larger mblk and appends the new
2073 	 * local address to the ok_ack.  The address is copied by
2074 	 * soaccept() for getsockname().
2075 	 */
2076 	{
2077 		int extra;
2078 
2079 		extra = (eager->tcp_family == AF_INET) ?
2080 		    sizeof (sin_t) : sizeof (sin6_t);
2081 
2082 		/*
2083 		 * Try to re-use mp, if possible.  Otherwise, allocate
2084 		 * an mblk and return it as ok_mp.  In any case, mp
2085 		 * is no longer usable upon return.
2086 		 */
2087 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2088 			CONN_DEC_REF(acceptor->tcp_connp);
2089 			CONN_DEC_REF(eager->tcp_connp);
2090 			freemsg(opt_mp);
2091 			/* Original mp has been freed by now, so use mp1 */
2092 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2093 			return;
2094 		}
2095 
2096 		mp = NULL;	/* We should never use mp after this point */
2097 
2098 		switch (extra) {
2099 		case sizeof (sin_t): {
2100 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2101 
2102 				ok_mp->b_wptr += extra;
2103 				sin->sin_family = AF_INET;
2104 				sin->sin_port = eager->tcp_lport;
2105 				sin->sin_addr.s_addr =
2106 				    eager->tcp_ipha->ipha_src;
2107 				break;
2108 			}
2109 		case sizeof (sin6_t): {
2110 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2111 
2112 				ok_mp->b_wptr += extra;
2113 				sin6->sin6_family = AF_INET6;
2114 				sin6->sin6_port = eager->tcp_lport;
2115 				if (eager->tcp_ipversion == IPV4_VERSION) {
2116 					sin6->sin6_flowinfo = 0;
2117 					IN6_IPADDR_TO_V4MAPPED(
2118 					    eager->tcp_ipha->ipha_src,
2119 					    &sin6->sin6_addr);
2120 				} else {
2121 					ASSERT(eager->tcp_ip6h != NULL);
2122 					sin6->sin6_flowinfo =
2123 					    eager->tcp_ip6h->ip6_vcf &
2124 					    ~IPV6_VERS_AND_FLOW_MASK;
2125 					sin6->sin6_addr =
2126 					    eager->tcp_ip6h->ip6_src;
2127 				}
2128 				break;
2129 			}
2130 		default:
2131 			break;
2132 		}
2133 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2134 	}
2135 
2136 	/*
2137 	 * If there are no options we know that the T_CONN_RES will
2138 	 * succeed. However, we can't send the T_OK_ACK upstream until
2139 	 * the tcp_accept_swap is done since it would be dangerous to
2140 	 * let the application start using the new fd prior to the swap.
2141 	 */
2142 	tcp_accept_swap(listener, acceptor, eager);
2143 
2144 	/*
2145 	 * tcp_accept_swap unlinks eager from listener but does not drop
2146 	 * the eager's reference on the listener.
2147 	 */
2148 	ASSERT(eager->tcp_listener == NULL);
2149 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2150 
2151 	/*
2152 	 * The eager is now associated with its own queue. Insert in
2153 	 * the hash so that the connection can be reused for a future
2154 	 * T_CONN_RES.
2155 	 */
2156 	tcp_acceptor_hash_insert(acceptor_id, eager);
2157 
2158 	/*
2159 	 * We now do the processing of options with T_CONN_RES.
2160 	 * We delay till now since we wanted to have queue to pass to
2161 	 * option processing routines that points back to the right
2162 	 * instance structure which does not happen until after
2163 	 * tcp_accept_swap().
2164 	 *
2165 	 * Note:
2166 	 * The sanity of the logic here assumes that whatever options
2167 	 * are appropriate to inherit from listner=>eager are done
2168 	 * before this point, and whatever were to be overridden (or not)
2169 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2170 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2171 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2172 	 * This may not be true at this point in time but can be fixed
2173 	 * independently. This option processing code starts with
2174 	 * the instantiated acceptor instance and the final queue at
2175 	 * this point.
2176 	 */
2177 
2178 	if (tcr->OPT_length != 0) {
2179 		/* Options to process */
2180 		int t_error = 0;
2181 		int sys_error = 0;
2182 		int do_disconnect = 0;
2183 
2184 		if (tcp_conprim_opt_process(eager, mp1,
2185 		    &do_disconnect, &t_error, &sys_error) < 0) {
2186 			eager->tcp_accept_error = 1;
2187 			if (do_disconnect) {
2188 				/*
2189 				 * An option failed which does not allow
2190 				 * connection to be accepted.
2191 				 *
2192 				 * We allow T_CONN_RES to succeed and
2193 				 * put a T_DISCON_IND on the eager queue.
2194 				 */
2195 				ASSERT(t_error == 0 && sys_error == 0);
2196 				eager->tcp_send_discon_ind = 1;
2197 			} else {
2198 				ASSERT(t_error != 0);
2199 				freemsg(ok_mp);
2200 				/*
2201 				 * Original mp was either freed or set
2202 				 * to ok_mp above, so use mp1 instead.
2203 				 */
2204 				tcp_err_ack(listener, mp1, t_error, sys_error);
2205 				goto finish;
2206 			}
2207 		}
2208 		/*
2209 		 * Most likely success in setting options (except if
2210 		 * eager->tcp_send_discon_ind set).
2211 		 * mp1 option buffer represented by OPT_length/offset
2212 		 * potentially modified and contains results of setting
2213 		 * options at this point
2214 		 */
2215 	}
2216 
2217 	/* We no longer need mp1, since all options processing has passed */
2218 	freemsg(mp1);
2219 
2220 	putnext(listener->tcp_rq, ok_mp);
2221 
2222 	mutex_enter(&listener->tcp_eager_lock);
2223 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2224 		tcp_t	*tail;
2225 		mblk_t	*conn_ind;
2226 
2227 		/*
2228 		 * This path should not be executed if listener and
2229 		 * acceptor streams are the same.
2230 		 */
2231 		ASSERT(listener != acceptor);
2232 
2233 		tcp = listener->tcp_eager_prev_q0;
2234 		/*
2235 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2236 		 * deferred T_conn_ind queue. We need to get to the head of
2237 		 * the queue in order to send up T_conn_ind the same order as
2238 		 * how the 3WHS is completed.
2239 		 */
2240 		while (tcp != listener) {
2241 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2242 				break;
2243 			else
2244 				tcp = tcp->tcp_eager_prev_q0;
2245 		}
2246 		ASSERT(tcp != listener);
2247 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2248 		ASSERT(conn_ind != NULL);
2249 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2250 
2251 		/* Move from q0 to q */
2252 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2253 		listener->tcp_conn_req_cnt_q0--;
2254 		listener->tcp_conn_req_cnt_q++;
2255 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2256 		    tcp->tcp_eager_prev_q0;
2257 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2258 		    tcp->tcp_eager_next_q0;
2259 		tcp->tcp_eager_prev_q0 = NULL;
2260 		tcp->tcp_eager_next_q0 = NULL;
2261 		tcp->tcp_conn_def_q0 = B_FALSE;
2262 
2263 		/*
2264 		 * Insert at end of the queue because sockfs sends
2265 		 * down T_CONN_RES in chronological order. Leaving
2266 		 * the older conn indications at front of the queue
2267 		 * helps reducing search time.
2268 		 */
2269 		tail = listener->tcp_eager_last_q;
2270 		if (tail != NULL)
2271 			tail->tcp_eager_next_q = tcp;
2272 		else
2273 			listener->tcp_eager_next_q = tcp;
2274 		listener->tcp_eager_last_q = tcp;
2275 		tcp->tcp_eager_next_q = NULL;
2276 		mutex_exit(&listener->tcp_eager_lock);
2277 		putnext(tcp->tcp_rq, conn_ind);
2278 	} else {
2279 		mutex_exit(&listener->tcp_eager_lock);
2280 	}
2281 
2282 	/*
2283 	 * Done with the acceptor - free it
2284 	 *
2285 	 * Note: from this point on, no access to listener should be made
2286 	 * as listener can be equal to acceptor.
2287 	 */
2288 finish:
2289 	ASSERT(acceptor->tcp_detached);
2290 	acceptor->tcp_rq = tcp_g_q;
2291 	acceptor->tcp_wq = WR(tcp_g_q);
2292 	(void) tcp_clean_death(acceptor, 0, 2);
2293 	CONN_DEC_REF(acceptor->tcp_connp);
2294 
2295 	/*
2296 	 * In case we already received a FIN we have to make tcp_rput send
2297 	 * the ordrel_ind. This will also send up a window update if the window
2298 	 * has opened up.
2299 	 *
2300 	 * In the normal case of a successful connection acceptance
2301 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2302 	 * indication that this was just accepted. This tells tcp_rput to
2303 	 * pass up any data queued in tcp_rcv_list.
2304 	 *
2305 	 * In the fringe case where options sent with T_CONN_RES failed and
2306 	 * we required, we would be indicating a T_DISCON_IND to blow
2307 	 * away this connection.
2308 	 */
2309 
2310 	/*
2311 	 * XXX: we currently have a problem if XTI application closes the
2312 	 * acceptor stream in between. This problem exists in on10-gate also
2313 	 * and is well know but nothing can be done short of major rewrite
2314 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2315 	 * eager same squeue as listener (we can distinguish non socket
2316 	 * listeners at the time of handling a SYN in tcp_conn_request)
2317 	 * and do most of the work that tcp_accept_finish does here itself
2318 	 * and then get behind the acceptor squeue to access the acceptor
2319 	 * queue.
2320 	 */
2321 	/*
2322 	 * We already have a ref on tcp so no need to do one before squeue_fill
2323 	 */
2324 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2325 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2326 }
2327 
2328 /*
2329  * Swap information between the eager and acceptor for a TLI/XTI client.
2330  * The sockfs accept is done on the acceptor stream and control goes
2331  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2332  * called. In either case, both the eager and listener are in their own
2333  * perimeter (squeue) and the code has to deal with potential race.
2334  *
2335  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2336  */
2337 static void
2338 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2339 {
2340 	conn_t	*econnp, *aconnp;
2341 
2342 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2343 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2344 	ASSERT(!eager->tcp_hard_bound);
2345 	ASSERT(!TCP_IS_SOCKET(acceptor));
2346 	ASSERT(!TCP_IS_SOCKET(eager));
2347 	ASSERT(!TCP_IS_SOCKET(listener));
2348 
2349 	acceptor->tcp_detached = B_TRUE;
2350 	/*
2351 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2352 	 * the acceptor id.
2353 	 */
2354 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2355 
2356 	/* remove eager from listen list... */
2357 	mutex_enter(&listener->tcp_eager_lock);
2358 	tcp_eager_unlink(eager);
2359 	ASSERT(eager->tcp_eager_next_q == NULL &&
2360 	    eager->tcp_eager_last_q == NULL);
2361 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2362 	    eager->tcp_eager_prev_q0 == NULL);
2363 	mutex_exit(&listener->tcp_eager_lock);
2364 	eager->tcp_rq = acceptor->tcp_rq;
2365 	eager->tcp_wq = acceptor->tcp_wq;
2366 
2367 	econnp = eager->tcp_connp;
2368 	aconnp = acceptor->tcp_connp;
2369 
2370 	eager->tcp_rq->q_ptr = econnp;
2371 	eager->tcp_wq->q_ptr = econnp;
2372 	eager->tcp_detached = B_FALSE;
2373 
2374 	ASSERT(eager->tcp_ack_tid == 0);
2375 
2376 	econnp->conn_dev = aconnp->conn_dev;
2377 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2378 	econnp->conn_zoneid = aconnp->conn_zoneid;
2379 	aconnp->conn_cred = NULL;
2380 
2381 	/* Do the IPC initialization */
2382 	CONN_INC_REF(econnp);
2383 
2384 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2385 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2386 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2387 	econnp->conn_ulp = aconnp->conn_ulp;
2388 
2389 	/* Done with old IPC. Drop its ref on its connp */
2390 	CONN_DEC_REF(aconnp);
2391 }
2392 
2393 
2394 /*
2395  * Adapt to the information, such as rtt and rtt_sd, provided from the
2396  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2397  *
2398  * Checks for multicast and broadcast destination address.
2399  * Returns zero on failure; non-zero if ok.
2400  *
2401  * Note that the MSS calculation here is based on the info given in
2402  * the IRE.  We do not do any calculation based on TCP options.  They
2403  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2404  * knows which options to use.
2405  *
2406  * Note on how TCP gets its parameters for a connection.
2407  *
2408  * When a tcp_t structure is allocated, it gets all the default parameters.
2409  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2410  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2411  * default.  But if there is an associated tcp_host_param, it will override
2412  * the metrics.
2413  *
2414  * An incoming SYN with a multicast or broadcast destination address, is dropped
2415  * in 1 of 2 places.
2416  *
2417  * 1. If the packet was received over the wire it is dropped in
2418  * ip_rput_process_broadcast()
2419  *
2420  * 2. If the packet was received through internal IP loopback, i.e. the packet
2421  * was generated and received on the same machine, it is dropped in
2422  * ip_wput_local()
2423  *
2424  * An incoming SYN with a multicast or broadcast source address is always
2425  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2426  * reject an attempt to connect to a broadcast or multicast (destination)
2427  * address.
2428  */
2429 static int
2430 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2431 {
2432 	tcp_hsp_t	*hsp;
2433 	ire_t		*ire;
2434 	ire_t		*sire = NULL;
2435 	iulp_t		*ire_uinfo;
2436 	uint32_t	mss_max;
2437 	uint32_t	mss;
2438 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2439 	conn_t		*connp = tcp->tcp_connp;
2440 	boolean_t	ire_cacheable = B_FALSE;
2441 	zoneid_t	zoneid = connp->conn_zoneid;
2442 	ill_t		*ill = NULL;
2443 	boolean_t	incoming = (ire_mp == NULL);
2444 
2445 	ASSERT(connp->conn_ire_cache == NULL);
2446 
2447 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2448 
2449 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2450 			BUMP_MIB(&ip_mib, ipInDiscards);
2451 			return (0);
2452 		}
2453 
2454 		ire = ire_cache_lookup(tcp->tcp_connp->conn_rem, zoneid);
2455 		if (ire != NULL) {
2456 			ire_cacheable = B_TRUE;
2457 			ire_uinfo = (ire_mp != NULL) ?
2458 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2459 			    &ire->ire_uinfo;
2460 
2461 		} else {
2462 			if (ire_mp == NULL) {
2463 				ire = ire_ftable_lookup(
2464 				    tcp->tcp_connp->conn_rem,
2465 				    0, 0, 0, NULL, &sire, zoneid, 0,
2466 				    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT));
2467 				if (ire == NULL)
2468 					return (0);
2469 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2470 				    &ire->ire_uinfo;
2471 			} else {
2472 				ire = (ire_t *)ire_mp->b_rptr;
2473 				ire_uinfo =
2474 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2475 			}
2476 		}
2477 		ASSERT(ire != NULL);
2478 		ASSERT(ire_uinfo != NULL);
2479 
2480 		if ((ire->ire_src_addr == INADDR_ANY) ||
2481 		    (ire->ire_type & IRE_BROADCAST)) {
2482 			/*
2483 			 * ire->ire_mp is non null when ire_mp passed in is used
2484 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2485 			 */
2486 			if (ire->ire_mp == NULL)
2487 				ire_refrele(ire);
2488 			if (sire != NULL)
2489 				ire_refrele(sire);
2490 			return (0);
2491 		}
2492 
2493 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2494 			ipaddr_t src_addr;
2495 
2496 			/*
2497 			 * ip_bind_connected() has stored the correct source
2498 			 * address in conn_src.
2499 			 */
2500 			src_addr = tcp->tcp_connp->conn_src;
2501 			tcp->tcp_ipha->ipha_src = src_addr;
2502 			/*
2503 			 * Copy of the src addr. in tcp_t is needed
2504 			 * for the lookup funcs.
2505 			 */
2506 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2507 		}
2508 		/*
2509 		 * Set the fragment bit so that IP will tell us if the MTU
2510 		 * should change. IP tells us the latest setting of
2511 		 * ip_path_mtu_discovery through ire_frag_flag.
2512 		 */
2513 		if (ip_path_mtu_discovery) {
2514 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2515 			    htons(IPH_DF);
2516 		}
2517 		tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2518 	} else {
2519 		/*
2520 		 * For incoming connection ire_mp = NULL
2521 		 * For outgoing connection ire_mp != NULL
2522 		 * Technically we should check conn_incoming_ill
2523 		 * when ire_mp is NULL and conn_outgoing_ill when
2524 		 * ire_mp is non-NULL. But this is performance
2525 		 * critical path and for IPV*_BOUND_IF, outgoing
2526 		 * and incoming ill are always set to the same value.
2527 		 */
2528 		ill_t	*dst_ill = NULL;
2529 		ipif_t  *dst_ipif = NULL;
2530 		int match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT;
2531 
2532 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2533 
2534 		if (connp->conn_outgoing_ill != NULL) {
2535 			/* Outgoing or incoming path */
2536 			int   err;
2537 
2538 			dst_ill = conn_get_held_ill(connp,
2539 			    &connp->conn_outgoing_ill, &err);
2540 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2541 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2542 				return (0);
2543 			}
2544 			match_flags |= MATCH_IRE_ILL;
2545 			dst_ipif = dst_ill->ill_ipif;
2546 		}
2547 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2548 		    0, 0, dst_ipif, zoneid, match_flags);
2549 
2550 		if (ire != NULL) {
2551 			ire_cacheable = B_TRUE;
2552 			ire_uinfo = (ire_mp != NULL) ?
2553 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2554 			    &ire->ire_uinfo;
2555 		} else {
2556 			if (ire_mp == NULL) {
2557 				ire = ire_ftable_lookup_v6(
2558 				    &tcp->tcp_connp->conn_remv6,
2559 				    0, 0, 0, dst_ipif, &sire, zoneid,
2560 				    0, match_flags);
2561 				if (ire == NULL) {
2562 					if (dst_ill != NULL)
2563 						ill_refrele(dst_ill);
2564 					return (0);
2565 				}
2566 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2567 				    &ire->ire_uinfo;
2568 			} else {
2569 				ire = (ire_t *)ire_mp->b_rptr;
2570 				ire_uinfo =
2571 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2572 			}
2573 		}
2574 		if (dst_ill != NULL)
2575 			ill_refrele(dst_ill);
2576 
2577 		ASSERT(ire != NULL);
2578 		ASSERT(ire_uinfo != NULL);
2579 
2580 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2581 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2582 			/*
2583 			 * ire->ire_mp is non null when ire_mp passed in is used
2584 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2585 			 */
2586 			if (ire->ire_mp == NULL)
2587 				ire_refrele(ire);
2588 			if (sire != NULL)
2589 				ire_refrele(sire);
2590 			return (0);
2591 		}
2592 
2593 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2594 			in6_addr_t	src_addr;
2595 
2596 			/*
2597 			 * ip_bind_connected_v6() has stored the correct source
2598 			 * address per IPv6 addr. selection policy in
2599 			 * conn_src_v6.
2600 			 */
2601 			src_addr = tcp->tcp_connp->conn_srcv6;
2602 
2603 			tcp->tcp_ip6h->ip6_src = src_addr;
2604 			/*
2605 			 * Copy of the src addr. in tcp_t is needed
2606 			 * for the lookup funcs.
2607 			 */
2608 			tcp->tcp_ip_src_v6 = src_addr;
2609 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2610 			    &connp->conn_srcv6));
2611 		}
2612 		tcp->tcp_localnet =
2613 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2614 	}
2615 
2616 	/*
2617 	 * This allows applications to fail quickly when connections are made
2618 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2619 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2620 	 */
2621 	if ((ire->ire_flags & RTF_REJECT) &&
2622 	    (ire->ire_flags & RTF_PRIVATE))
2623 		goto error;
2624 
2625 	/*
2626 	 * Make use of the cached rtt and rtt_sd values to calculate the
2627 	 * initial RTO.  Note that they are already initialized in
2628 	 * tcp_init_values().
2629 	 */
2630 	if (ire_uinfo->iulp_rtt != 0) {
2631 		clock_t	rto;
2632 
2633 		tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2634 		tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2635 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2636 		    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
2637 
2638 		if (rto > tcp_rexmit_interval_max) {
2639 			tcp->tcp_rto = tcp_rexmit_interval_max;
2640 		} else if (rto < tcp_rexmit_interval_min) {
2641 			tcp->tcp_rto = tcp_rexmit_interval_min;
2642 		} else {
2643 			tcp->tcp_rto = rto;
2644 		}
2645 	}
2646 	if (ire_uinfo->iulp_ssthresh != 0)
2647 		tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2648 	else
2649 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2650 	if (ire_uinfo->iulp_spipe > 0) {
2651 		tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2652 		    tcp_max_buf);
2653 		if (tcp_snd_lowat_fraction != 0)
2654 			tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2655 			    tcp_snd_lowat_fraction;
2656 		(void) tcp_maxpsz_set(tcp, B_TRUE);
2657 	}
2658 	/*
2659 	 * Note that up till now, acceptor always inherits receive
2660 	 * window from the listener.  But if there is a metrics associated
2661 	 * with a host, we should use that instead of inheriting it from
2662 	 * listener.  Thus we need to pass this info back to the caller.
2663 	 */
2664 	if (ire_uinfo->iulp_rpipe > 0) {
2665 		tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
2666 	} else {
2667 		/*
2668 		 * For passive open, set tcp_rwnd to 0 so that the caller
2669 		 * knows that there is no rpipe metric for this connection.
2670 		 */
2671 		if (tcp_detached)
2672 			tcp->tcp_rwnd = 0;
2673 	}
2674 	if (ire_uinfo->iulp_rtomax > 0) {
2675 		tcp->tcp_second_timer_threshold = ire_uinfo->iulp_rtomax;
2676 	}
2677 
2678 	/*
2679 	 * Use the metric option settings, iulp_tstamp_ok and iulp_wscale_ok,
2680 	 * only for active open.  What this means is that if the other side
2681 	 * uses timestamp or window scale option, TCP will also use those
2682 	 * options.  That is for passive open.  If the application sets a
2683 	 * large window, window scale is enabled regardless of the value in
2684 	 * iulp_wscale_ok.  This is the behavior since 2.6.  So we keep it.
2685 	 * The only case left in passive open processing is the check for SACK.
2686 	 *
2687 	 * For ECN, it should probably be like SACK.  But the current
2688 	 * value is binary, so we treat it like the other cases.  The
2689 	 * metric only controls active open.  For passive open, the ndd
2690 	 * param, tcp_ecn_permitted, controls the behavior.
2691 	 */
2692 	if (!tcp_detached) {
2693 		/*
2694 		 * The if check means that the following can only be turned
2695 		 * on by the metrics only IRE, but not off.
2696 		 */
2697 		if (ire_uinfo->iulp_tstamp_ok)
2698 			tcp->tcp_snd_ts_ok = B_TRUE;
2699 		if (ire_uinfo->iulp_wscale_ok)
2700 			tcp->tcp_snd_ws_ok = B_TRUE;
2701 		if (ire_uinfo->iulp_sack == 2)
2702 			tcp->tcp_snd_sack_ok = B_TRUE;
2703 		if (ire_uinfo->iulp_ecn_ok)
2704 			tcp->tcp_ecn_ok = B_TRUE;
2705 	} else {
2706 		/*
2707 		 * Passive open.
2708 		 *
2709 		 * As above, the if check means that SACK can only be
2710 		 * turned on by the metric only IRE.
2711 		 */
2712 		if (ire_uinfo->iulp_sack > 0) {
2713 			tcp->tcp_snd_sack_ok = B_TRUE;
2714 		}
2715 	}
2716 
2717 	/*
2718 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2719 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2720 	 * length of all those options exceeds 28 bytes.  But because
2721 	 * of the tcp_mss_min check below, we may not have a problem if
2722 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2723 	 * the negative problem still exists.  And the check defeats PMTUd.
2724 	 * In fact, if PMTUd finds that the MSS should be smaller than
2725 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2726 	 * value.
2727 	 *
2728 	 * We do not deal with that now.  All those problems related to
2729 	 * PMTUd will be fixed later.
2730 	 */
2731 	ASSERT(ire->ire_max_frag != 0);
2732 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2733 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2734 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2735 			mss = MIN(mss, IPV6_MIN_MTU);
2736 		}
2737 	}
2738 
2739 	/* Sanity check for MSS value. */
2740 	if (tcp->tcp_ipversion == IPV4_VERSION)
2741 		mss_max = tcp_mss_max_ipv4;
2742 	else
2743 		mss_max = tcp_mss_max_ipv6;
2744 
2745 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2746 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2747 		/*
2748 		 * After receiving an ICMPv6 "packet too big" message with a
2749 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2750 		 * will insert a 8-byte fragment header in every packet; we
2751 		 * reduce the MSS by that amount here.
2752 		 */
2753 		mss -= sizeof (ip6_frag_t);
2754 	}
2755 
2756 	if (tcp->tcp_ipsec_overhead == 0)
2757 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2758 
2759 	mss -= tcp->tcp_ipsec_overhead;
2760 
2761 	if (mss < tcp_mss_min)
2762 		mss = tcp_mss_min;
2763 	if (mss > mss_max)
2764 		mss = mss_max;
2765 
2766 	/* Note that this is the maximum MSS, excluding all options. */
2767 	tcp->tcp_mss = mss;
2768 
2769 	/*
2770 	 * Initialize the ISS here now that we have the full connection ID.
2771 	 * The RFC 1948 method of initial sequence number generation requires
2772 	 * knowledge of the full connection ID before setting the ISS.
2773 	 */
2774 
2775 	tcp_iss_init(tcp);
2776 
2777 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2778 		tcp->tcp_loopback = B_TRUE;
2779 
2780 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2781 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
2782 	} else {
2783 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
2784 	}
2785 
2786 	if (hsp != NULL) {
2787 		/* Only modify if we're going to make them bigger */
2788 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2789 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2790 			if (tcp_snd_lowat_fraction != 0)
2791 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2792 					tcp_snd_lowat_fraction;
2793 		}
2794 
2795 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2796 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2797 		}
2798 
2799 		/* Copy timestamp flag only for active open */
2800 		if (!tcp_detached)
2801 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2802 	}
2803 
2804 	if (sire != NULL)
2805 		IRE_REFRELE(sire);
2806 
2807 	/*
2808 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2809 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2810 	 */
2811 	if (tcp->tcp_loopback ||
2812 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2813 		/*
2814 		 * For incoming, see if this tcp may be MDT-capable.  For
2815 		 * outgoing, this process has been taken care of through
2816 		 * tcp_rput_other.
2817 		 */
2818 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2819 		tcp->tcp_ire_ill_check_done = B_TRUE;
2820 	}
2821 
2822 	mutex_enter(&connp->conn_lock);
2823 	/*
2824 	 * Make sure that conn is not marked incipient
2825 	 * for incoming connections. A blind
2826 	 * removal of incipient flag is cheaper than
2827 	 * check and removal.
2828 	 */
2829 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2830 
2831 	/* Must not cache forwarding table routes. */
2832 	if (ire_cacheable) {
2833 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2834 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2835 			connp->conn_ire_cache = ire;
2836 			IRE_UNTRACE_REF(ire);
2837 			rw_exit(&ire->ire_bucket->irb_lock);
2838 			mutex_exit(&connp->conn_lock);
2839 			return (1);
2840 		}
2841 		rw_exit(&ire->ire_bucket->irb_lock);
2842 	}
2843 	mutex_exit(&connp->conn_lock);
2844 
2845 	if (ire->ire_mp == NULL)
2846 		ire_refrele(ire);
2847 	return (1);
2848 
2849 error:
2850 	if (ire->ire_mp == NULL)
2851 		ire_refrele(ire);
2852 	if (sire != NULL)
2853 		ire_refrele(sire);
2854 	return (0);
2855 }
2856 
2857 /*
2858  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2859  * O_T_BIND_REQ/T_BIND_REQ message.
2860  */
2861 static void
2862 tcp_bind(tcp_t *tcp, mblk_t *mp)
2863 {
2864 	sin_t	*sin;
2865 	sin6_t	*sin6;
2866 	mblk_t	*mp1;
2867 	in_port_t requested_port;
2868 	in_port_t allocated_port;
2869 	struct T_bind_req *tbr;
2870 	boolean_t	bind_to_req_port_only;
2871 	boolean_t	backlog_update = B_FALSE;
2872 	boolean_t	user_specified;
2873 	in6_addr_t	v6addr;
2874 	ipaddr_t	v4addr;
2875 	uint_t	origipversion;
2876 	int	err;
2877 	queue_t *q = tcp->tcp_wq;
2878 
2879 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2880 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2881 		if (tcp->tcp_debug) {
2882 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2883 			    "tcp_bind: bad req, len %u",
2884 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2885 		}
2886 		tcp_err_ack(tcp, mp, TPROTO, 0);
2887 		return;
2888 	}
2889 	/* Make sure the largest address fits */
2890 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
2891 	if (mp1 == NULL) {
2892 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2893 		return;
2894 	}
2895 	mp = mp1;
2896 	tbr = (struct T_bind_req *)mp->b_rptr;
2897 	if (tcp->tcp_state >= TCPS_BOUND) {
2898 		if ((tcp->tcp_state == TCPS_BOUND ||
2899 		    tcp->tcp_state == TCPS_LISTEN) &&
2900 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
2901 		    tbr->CONIND_number > 0) {
2902 			/*
2903 			 * Handle listen() increasing CONIND_number.
2904 			 * This is more "liberal" then what the TPI spec
2905 			 * requires but is needed to avoid a t_unbind
2906 			 * when handling listen() since the port number
2907 			 * might be "stolen" between the unbind and bind.
2908 			 */
2909 			backlog_update = B_TRUE;
2910 			goto do_bind;
2911 		}
2912 		if (tcp->tcp_debug) {
2913 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2914 			    "tcp_bind: bad state, %d", tcp->tcp_state);
2915 		}
2916 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
2917 		return;
2918 	}
2919 	origipversion = tcp->tcp_ipversion;
2920 
2921 	switch (tbr->ADDR_length) {
2922 	case 0:			/* request for a generic port */
2923 		tbr->ADDR_offset = sizeof (struct T_bind_req);
2924 		if (tcp->tcp_family == AF_INET) {
2925 			tbr->ADDR_length = sizeof (sin_t);
2926 			sin = (sin_t *)&tbr[1];
2927 			*sin = sin_null;
2928 			sin->sin_family = AF_INET;
2929 			mp->b_wptr = (uchar_t *)&sin[1];
2930 			tcp->tcp_ipversion = IPV4_VERSION;
2931 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
2932 		} else {
2933 			ASSERT(tcp->tcp_family == AF_INET6);
2934 			tbr->ADDR_length = sizeof (sin6_t);
2935 			sin6 = (sin6_t *)&tbr[1];
2936 			*sin6 = sin6_null;
2937 			sin6->sin6_family = AF_INET6;
2938 			mp->b_wptr = (uchar_t *)&sin6[1];
2939 			tcp->tcp_ipversion = IPV6_VERSION;
2940 			V6_SET_ZERO(v6addr);
2941 		}
2942 		requested_port = 0;
2943 		break;
2944 
2945 	case sizeof (sin_t):	/* Complete IPv4 address */
2946 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
2947 		    sizeof (sin_t));
2948 		if (sin == NULL || !OK_32PTR((char *)sin)) {
2949 			if (tcp->tcp_debug) {
2950 				(void) strlog(TCP_MOD_ID, 0, 1,
2951 				    SL_ERROR|SL_TRACE,
2952 				    "tcp_bind: bad address parameter, "
2953 				    "offset %d, len %d",
2954 				    tbr->ADDR_offset, tbr->ADDR_length);
2955 			}
2956 			tcp_err_ack(tcp, mp, TPROTO, 0);
2957 			return;
2958 		}
2959 		/*
2960 		 * With sockets sockfs will accept bogus sin_family in
2961 		 * bind() and replace it with the family used in the socket
2962 		 * call.
2963 		 */
2964 		if (sin->sin_family != AF_INET ||
2965 		    tcp->tcp_family != AF_INET) {
2966 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
2967 			return;
2968 		}
2969 		requested_port = ntohs(sin->sin_port);
2970 		tcp->tcp_ipversion = IPV4_VERSION;
2971 		v4addr = sin->sin_addr.s_addr;
2972 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
2973 		break;
2974 
2975 	case sizeof (sin6_t): /* Complete IPv6 address */
2976 		sin6 = (sin6_t *)mi_offset_param(mp,
2977 		    tbr->ADDR_offset, sizeof (sin6_t));
2978 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
2979 			if (tcp->tcp_debug) {
2980 				(void) strlog(TCP_MOD_ID, 0, 1,
2981 				    SL_ERROR|SL_TRACE,
2982 				    "tcp_bind: bad IPv6 address parameter, "
2983 				    "offset %d, len %d", tbr->ADDR_offset,
2984 				    tbr->ADDR_length);
2985 			}
2986 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2987 			return;
2988 		}
2989 		if (sin6->sin6_family != AF_INET6 ||
2990 		    tcp->tcp_family != AF_INET6) {
2991 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
2992 			return;
2993 		}
2994 		requested_port = ntohs(sin6->sin6_port);
2995 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
2996 		    IPV4_VERSION : IPV6_VERSION;
2997 		v6addr = sin6->sin6_addr;
2998 		break;
2999 
3000 	default:
3001 		if (tcp->tcp_debug) {
3002 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3003 			    "tcp_bind: bad address length, %d",
3004 			    tbr->ADDR_length);
3005 		}
3006 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3007 		return;
3008 	}
3009 	tcp->tcp_bound_source_v6 = v6addr;
3010 
3011 	/* Check for change in ipversion */
3012 	if (origipversion != tcp->tcp_ipversion) {
3013 		ASSERT(tcp->tcp_family == AF_INET6);
3014 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3015 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3016 		if (err) {
3017 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3018 			return;
3019 		}
3020 	}
3021 
3022 	/*
3023 	 * Initialize family specific fields. Copy of the src addr.
3024 	 * in tcp_t is needed for the lookup funcs.
3025 	 */
3026 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3027 		tcp->tcp_ip6h->ip6_src = v6addr;
3028 	} else {
3029 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3030 	}
3031 	tcp->tcp_ip_src_v6 = v6addr;
3032 
3033 	/*
3034 	 * For O_T_BIND_REQ:
3035 	 * Verify that the target port/addr is available, or choose
3036 	 * another.
3037 	 * For  T_BIND_REQ:
3038 	 * Verify that the target port/addr is available or fail.
3039 	 * In both cases when it succeeds the tcp is inserted in the
3040 	 * bind hash table. This ensures that the operation is atomic
3041 	 * under the lock on the hash bucket.
3042 	 */
3043 	bind_to_req_port_only = requested_port != 0 &&
3044 	    tbr->PRIM_type != O_T_BIND_REQ;
3045 	/*
3046 	 * Get a valid port (within the anonymous range and should not
3047 	 * be a privileged one) to use if the user has not given a port.
3048 	 * If multiple threads are here, they may all start with
3049 	 * with the same initial port. But, it should be fine as long as
3050 	 * tcp_bindi will ensure that no two threads will be assigned
3051 	 * the same port.
3052 	 *
3053 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3054 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3055 	 * unless TCP_ANONPRIVBIND option is set.
3056 	 */
3057 	if (requested_port == 0) {
3058 		requested_port = tcp->tcp_anon_priv_bind ?
3059 		    tcp_get_next_priv_port() :
3060 		    tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
3061 		user_specified = B_FALSE;
3062 	} else {
3063 		int i;
3064 		boolean_t priv = B_FALSE;
3065 		/*
3066 		 * If the requested_port is in the well-known privileged range,
3067 		 * verify that the stream was opened by a privileged user.
3068 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3069 		 * but instead the code relies on:
3070 		 * - the fact that the address of the array and its size never
3071 		 *   changes
3072 		 * - the atomic assignment of the elements of the array
3073 		 */
3074 		if (requested_port < tcp_smallest_nonpriv_port) {
3075 			priv = B_TRUE;
3076 		} else {
3077 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3078 				if (requested_port ==
3079 				    tcp_g_epriv_ports[i]) {
3080 					priv = B_TRUE;
3081 					break;
3082 				}
3083 			}
3084 		}
3085 		if (priv) {
3086 			cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
3087 
3088 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3089 				if (tcp->tcp_debug) {
3090 					(void) strlog(TCP_MOD_ID, 0, 1,
3091 					    SL_ERROR|SL_TRACE,
3092 					    "tcp_bind: no priv for port %d",
3093 					    requested_port);
3094 				}
3095 				tcp_err_ack(tcp, mp, TACCES, 0);
3096 				return;
3097 			}
3098 		}
3099 		user_specified = B_TRUE;
3100 	}
3101 
3102 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3103 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3104 
3105 	if (allocated_port == 0) {
3106 		if (bind_to_req_port_only) {
3107 			if (tcp->tcp_debug) {
3108 				(void) strlog(TCP_MOD_ID, 0, 1,
3109 				    SL_ERROR|SL_TRACE,
3110 				    "tcp_bind: requested addr busy");
3111 			}
3112 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3113 		} else {
3114 			/* If we are out of ports, fail the bind. */
3115 			if (tcp->tcp_debug) {
3116 				(void) strlog(TCP_MOD_ID, 0, 1,
3117 				    SL_ERROR|SL_TRACE,
3118 				    "tcp_bind: out of ports?");
3119 			}
3120 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3121 		}
3122 		return;
3123 	}
3124 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3125 do_bind:
3126 	if (!backlog_update) {
3127 		if (tcp->tcp_family == AF_INET)
3128 			sin->sin_port = htons(allocated_port);
3129 		else
3130 			sin6->sin6_port = htons(allocated_port);
3131 	}
3132 	if (tcp->tcp_family == AF_INET) {
3133 		if (tbr->CONIND_number != 0) {
3134 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3135 			    sizeof (sin_t));
3136 		} else {
3137 			/* Just verify the local IP address */
3138 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3139 		}
3140 	} else {
3141 		if (tbr->CONIND_number != 0) {
3142 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3143 			    sizeof (sin6_t));
3144 		} else {
3145 			/* Just verify the local IP address */
3146 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3147 			    IPV6_ADDR_LEN);
3148 		}
3149 	}
3150 	if (!mp1) {
3151 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3152 		return;
3153 	}
3154 
3155 	tbr->PRIM_type = T_BIND_ACK;
3156 	mp->b_datap->db_type = M_PCPROTO;
3157 
3158 	/* Chain in the reply mp for tcp_rput() */
3159 	mp1->b_cont = mp;
3160 	mp = mp1;
3161 
3162 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3163 	if (tcp->tcp_conn_req_max) {
3164 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
3165 			tcp->tcp_conn_req_max = tcp_conn_req_min;
3166 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
3167 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
3168 		/*
3169 		 * If this is a listener, do not reset the eager list
3170 		 * and other stuffs.  Note that we don't check if the
3171 		 * existing eager list meets the new tcp_conn_req_max
3172 		 * requirement.
3173 		 */
3174 		if (tcp->tcp_state != TCPS_LISTEN) {
3175 			tcp->tcp_state = TCPS_LISTEN;
3176 			/* Initialize the chain. Don't need the eager_lock */
3177 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3178 			tcp->tcp_second_ctimer_threshold =
3179 			    tcp_ip_abort_linterval;
3180 		}
3181 	}
3182 
3183 	/*
3184 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3185 	 * processing continues in tcp_rput_other().
3186 	 */
3187 	if (tcp->tcp_family == AF_INET6) {
3188 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3189 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3190 	} else {
3191 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3192 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3193 	}
3194 	/*
3195 	 * If the bind cannot complete immediately
3196 	 * IP will arrange to call tcp_rput_other
3197 	 * when the bind completes.
3198 	 */
3199 	if (mp != NULL) {
3200 		tcp_rput_other(tcp, mp);
3201 	} else {
3202 		/*
3203 		 * Bind will be resumed later. Need to ensure
3204 		 * that conn doesn't disappear when that happens.
3205 		 * This will be decremented in ip_resume_tcp_bind().
3206 		 */
3207 		CONN_INC_REF(tcp->tcp_connp);
3208 	}
3209 }
3210 
3211 
3212 /*
3213  * If the "bind_to_req_port_only" parameter is set, if the requested port
3214  * number is available, return it, If not return 0
3215  *
3216  * If "bind_to_req_port_only" parameter is not set and
3217  * If the requested port number is available, return it.  If not, return
3218  * the first anonymous port we happen across.  If no anonymous ports are
3219  * available, return 0. addr is the requested local address, if any.
3220  *
3221  * In either case, when succeeding update the tcp_t to record the port number
3222  * and insert it in the bind hash table.
3223  *
3224  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3225  * without setting SO_REUSEADDR. This is needed so that they
3226  * can be viewed as two independent transport protocols.
3227  */
3228 static in_port_t
3229 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3230     int reuseaddr, boolean_t quick_connect,
3231     boolean_t bind_to_req_port_only, boolean_t user_specified)
3232 {
3233 	/* number of times we have run around the loop */
3234 	int count = 0;
3235 	/* maximum number of times to run around the loop */
3236 	int loopmax;
3237 	zoneid_t zoneid = tcp->tcp_connp->conn_zoneid;
3238 
3239 	/*
3240 	 * Lookup for free addresses is done in a loop and "loopmax"
3241 	 * influences how long we spin in the loop
3242 	 */
3243 	if (bind_to_req_port_only) {
3244 		/*
3245 		 * If the requested port is busy, don't bother to look
3246 		 * for a new one. Setting loop maximum count to 1 has
3247 		 * that effect.
3248 		 */
3249 		loopmax = 1;
3250 	} else {
3251 		/*
3252 		 * If the requested port is busy, look for a free one
3253 		 * in the anonymous port range.
3254 		 * Set loopmax appropriately so that one does not look
3255 		 * forever in the case all of the anonymous ports are in use.
3256 		 */
3257 		if (tcp->tcp_anon_priv_bind) {
3258 			/*
3259 			 * loopmax =
3260 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3261 			 */
3262 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
3263 		} else {
3264 			loopmax = (tcp_largest_anon_port -
3265 			    tcp_smallest_anon_port + 1);
3266 		}
3267 	}
3268 	do {
3269 		uint16_t	lport;
3270 		tf_t		*tbf;
3271 		tcp_t		*ltcp;
3272 
3273 		lport = htons(port);
3274 
3275 		/*
3276 		 * Ensure that the tcp_t is not currently in the bind hash.
3277 		 * Hold the lock on the hash bucket to ensure that
3278 		 * the duplicate check plus the insertion is an atomic
3279 		 * operation.
3280 		 *
3281 		 * This function does an inline lookup on the bind hash list
3282 		 * Make sure that we access only members of tcp_t
3283 		 * and that we don't look at tcp_tcp, since we are not
3284 		 * doing a CONN_INC_REF.
3285 		 */
3286 		tcp_bind_hash_remove(tcp);
3287 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
3288 		mutex_enter(&tbf->tf_lock);
3289 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3290 		    ltcp = ltcp->tcp_bind_hash) {
3291 			if (lport != ltcp->tcp_lport ||
3292 			    ltcp->tcp_connp->conn_zoneid != zoneid) {
3293 				continue;
3294 			}
3295 
3296 			/*
3297 			 * If TCP_EXCLBIND is set for either the bound or
3298 			 * binding endpoint, the semantics of bind
3299 			 * is changed according to the following.
3300 			 *
3301 			 * spec = specified address (v4 or v6)
3302 			 * unspec = unspecified address (v4 or v6)
3303 			 * A = specified addresses are different for endpoints
3304 			 *
3305 			 * bound	bind to		allowed
3306 			 * -------------------------------------
3307 			 * unspec	unspec		no
3308 			 * unspec	spec		no
3309 			 * spec		unspec		no
3310 			 * spec		spec		yes if A
3311 			 *
3312 			 * Note:
3313 			 *
3314 			 * 1. Because of TLI semantics, an endpoint can go
3315 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3316 			 * TCPS_BOUND, depending on whether it is originally
3317 			 * a listener or not.  That is why we need to check
3318 			 * for states greater than or equal to TCPS_BOUND
3319 			 * here.
3320 			 *
3321 			 * 2. Ideally, we should only check for state equals
3322 			 * to TCPS_LISTEN. And the following check should be
3323 			 * added.
3324 			 *
3325 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3326 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3327 			 *		...
3328 			 * }
3329 			 *
3330 			 * The semantics will be changed to this.  If the
3331 			 * endpoint on the list is in state not equal to
3332 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3333 			 * set, let the bind succeed.
3334 			 *
3335 			 * But because of (1), we cannot do that now.  If
3336 			 * in future, we can change this going back semantics,
3337 			 * we can add the above check.
3338 			 */
3339 			if (ltcp->tcp_exclbind || tcp->tcp_exclbind) {
3340 				if (V6_OR_V4_INADDR_ANY(
3341 				    ltcp->tcp_bound_source_v6) ||
3342 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3343 				    IN6_ARE_ADDR_EQUAL(laddr,
3344 				    &ltcp->tcp_bound_source_v6)) {
3345 					break;
3346 				}
3347 				continue;
3348 			}
3349 
3350 			/*
3351 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3352 			 * have disjoint port number spaces, if *_EXCLBIND
3353 			 * is not set and only if the application binds to a
3354 			 * specific port. We use the same autoassigned port
3355 			 * number space for IPv4 and IPv6 sockets.
3356 			 */
3357 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3358 			    bind_to_req_port_only)
3359 				continue;
3360 
3361 			/*
3362 			 * Ideally, we should make sure that the source
3363 			 * address, remote address, and remote port in the
3364 			 * four tuple for this tcp-connection is unique.
3365 			 * However, trying to find out the local source
3366 			 * address would require too much code duplication
3367 			 * with IP, since IP needs needs to have that code
3368 			 * to support userland TCP implementations.
3369 			 */
3370 			if (quick_connect &&
3371 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3372 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3373 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3374 				    &ltcp->tcp_remote_v6)))
3375 				continue;
3376 
3377 			if (!reuseaddr) {
3378 				/*
3379 				 * No socket option SO_REUSEADDR.
3380 				 * If existing port is bound to
3381 				 * a non-wildcard IP address
3382 				 * and the requesting stream is
3383 				 * bound to a distinct
3384 				 * different IP addresses
3385 				 * (non-wildcard, also), keep
3386 				 * going.
3387 				 */
3388 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3389 				    !V6_OR_V4_INADDR_ANY(
3390 				    ltcp->tcp_bound_source_v6) &&
3391 				    !IN6_ARE_ADDR_EQUAL(laddr,
3392 					&ltcp->tcp_bound_source_v6))
3393 					continue;
3394 				if (ltcp->tcp_state >= TCPS_BOUND) {
3395 					/*
3396 					 * This port is being used and
3397 					 * its state is >= TCPS_BOUND,
3398 					 * so we can't bind to it.
3399 					 */
3400 					break;
3401 				}
3402 			} else {
3403 				/*
3404 				 * socket option SO_REUSEADDR is set on the
3405 				 * binding tcp_t.
3406 				 *
3407 				 * If two streams are bound to
3408 				 * same IP address or both addr
3409 				 * and bound source are wildcards
3410 				 * (INADDR_ANY), we want to stop
3411 				 * searching.
3412 				 * We have found a match of IP source
3413 				 * address and source port, which is
3414 				 * refused regardless of the
3415 				 * SO_REUSEADDR setting, so we break.
3416 				 */
3417 				if (IN6_ARE_ADDR_EQUAL(laddr,
3418 				    &ltcp->tcp_bound_source_v6) &&
3419 				    (ltcp->tcp_state == TCPS_LISTEN ||
3420 					ltcp->tcp_state == TCPS_BOUND))
3421 					break;
3422 			}
3423 		}
3424 		if (ltcp != NULL) {
3425 			/* The port number is busy */
3426 			mutex_exit(&tbf->tf_lock);
3427 		} else {
3428 			/*
3429 			 * This port is ours. Insert in fanout and mark as
3430 			 * bound to prevent others from getting the port
3431 			 * number.
3432 			 */
3433 			tcp->tcp_state = TCPS_BOUND;
3434 			tcp->tcp_lport = htons(port);
3435 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3436 
3437 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
3438 			    tcp->tcp_lport)] == tbf);
3439 			tcp_bind_hash_insert(tbf, tcp, 1);
3440 
3441 			mutex_exit(&tbf->tf_lock);
3442 
3443 			/*
3444 			 * We don't want tcp_next_port_to_try to "inherit"
3445 			 * a port number supplied by the user in a bind.
3446 			 */
3447 			if (user_specified)
3448 				return (port);
3449 
3450 			/*
3451 			 * This is the only place where tcp_next_port_to_try
3452 			 * is updated. After the update, it may or may not
3453 			 * be in the valid range.
3454 			 */
3455 			if (!tcp->tcp_anon_priv_bind)
3456 				tcp_next_port_to_try = port + 1;
3457 			return (port);
3458 		}
3459 
3460 		if (tcp->tcp_anon_priv_bind) {
3461 			port = tcp_get_next_priv_port();
3462 		} else {
3463 			if (count == 0 && user_specified) {
3464 				/*
3465 				 * We may have to return an anonymous port. So
3466 				 * get one to start with.
3467 				 */
3468 				port =
3469 				    tcp_update_next_port(tcp_next_port_to_try,
3470 					B_TRUE);
3471 				user_specified = B_FALSE;
3472 			} else {
3473 				port = tcp_update_next_port(port + 1, B_FALSE);
3474 			}
3475 		}
3476 
3477 		/*
3478 		 * Don't let this loop run forever in the case where
3479 		 * all of the anonymous ports are in use.
3480 		 */
3481 	} while (++count < loopmax);
3482 	return (0);
3483 }
3484 
3485 /*
3486  * We are dying for some reason.  Try to do it gracefully.  (May be called
3487  * as writer.)
3488  *
3489  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3490  * done by a service procedure).
3491  * TBD - Should the return value distinguish between the tcp_t being
3492  * freed and it being reinitialized?
3493  */
3494 static int
3495 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3496 {
3497 	mblk_t	*mp;
3498 	queue_t	*q;
3499 
3500 	TCP_CLD_STAT(tag);
3501 
3502 #if TCP_TAG_CLEAN_DEATH
3503 	tcp->tcp_cleandeathtag = tag;
3504 #endif
3505 
3506 	if (tcp->tcp_linger_tid != 0 &&
3507 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3508 		tcp_stop_lingering(tcp);
3509 	}
3510 
3511 	ASSERT(tcp != NULL);
3512 	ASSERT((tcp->tcp_family == AF_INET &&
3513 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3514 	    (tcp->tcp_family == AF_INET6 &&
3515 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3516 	    tcp->tcp_ipversion == IPV6_VERSION)));
3517 
3518 	if (TCP_IS_DETACHED(tcp)) {
3519 		if (tcp->tcp_hard_binding) {
3520 			/*
3521 			 * Its an eager that we are dealing with. We close the
3522 			 * eager but in case a conn_ind has already gone to the
3523 			 * listener, let tcp_accept_finish() send a discon_ind
3524 			 * to the listener and drop the last reference. If the
3525 			 * listener doesn't even know about the eager i.e. the
3526 			 * conn_ind hasn't gone up, blow away the eager and drop
3527 			 * the last reference as well. If the conn_ind has gone
3528 			 * up, state should be BOUND. tcp_accept_finish
3529 			 * will figure out that the connection has received a
3530 			 * RST and will send a DISCON_IND to the application.
3531 			 */
3532 			tcp_closei_local(tcp);
3533 			if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
3534 				CONN_DEC_REF(tcp->tcp_connp);
3535 			} else {
3536 				tcp->tcp_state = TCPS_BOUND;
3537 			}
3538 		} else {
3539 			tcp_close_detached(tcp);
3540 		}
3541 		return (0);
3542 	}
3543 
3544 	TCP_STAT(tcp_clean_death_nondetached);
3545 
3546 	/*
3547 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3548 	 * is run) postpone cleaning up the endpoint until service routine
3549 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3550 	 * client_errno since tcp_close uses the client_errno field.
3551 	 */
3552 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3553 		if (err != 0)
3554 			tcp->tcp_client_errno = err;
3555 
3556 		tcp->tcp_deferred_clean_death = B_TRUE;
3557 		return (-1);
3558 	}
3559 
3560 	q = tcp->tcp_rq;
3561 
3562 	/* Trash all inbound data */
3563 	flushq(q, FLUSHALL);
3564 
3565 	/*
3566 	 * If we are at least part way open and there is error
3567 	 * (err==0 implies no error)
3568 	 * notify our client by a T_DISCON_IND.
3569 	 */
3570 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3571 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3572 		    !TCP_IS_SOCKET(tcp)) {
3573 			/*
3574 			 * Send M_FLUSH according to TPI. Because sockets will
3575 			 * (and must) ignore FLUSHR we do that only for TPI
3576 			 * endpoints and sockets in STREAMS mode.
3577 			 */
3578 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3579 		}
3580 		if (tcp->tcp_debug) {
3581 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3582 			    "tcp_clean_death: discon err %d", err);
3583 		}
3584 		mp = mi_tpi_discon_ind(NULL, err, 0);
3585 		if (mp != NULL) {
3586 			putnext(q, mp);
3587 		} else {
3588 			if (tcp->tcp_debug) {
3589 				(void) strlog(TCP_MOD_ID, 0, 1,
3590 				    SL_ERROR|SL_TRACE,
3591 				    "tcp_clean_death, sending M_ERROR");
3592 			}
3593 			(void) putnextctl1(q, M_ERROR, EPROTO);
3594 		}
3595 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3596 			/* SYN_SENT or SYN_RCVD */
3597 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3598 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3599 			/* ESTABLISHED or CLOSE_WAIT */
3600 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3601 		}
3602 	}
3603 
3604 	tcp_reinit(tcp);
3605 	return (-1);
3606 }
3607 
3608 /*
3609  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3610  * to expire, stop the wait and finish the close.
3611  */
3612 static void
3613 tcp_stop_lingering(tcp_t *tcp)
3614 {
3615 	clock_t	delta = 0;
3616 
3617 	tcp->tcp_linger_tid = 0;
3618 	if (tcp->tcp_state > TCPS_LISTEN) {
3619 		tcp_acceptor_hash_remove(tcp);
3620 		if (tcp->tcp_flow_stopped) {
3621 			tcp_clrqfull(tcp);
3622 		}
3623 
3624 		if (tcp->tcp_timer_tid != 0) {
3625 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3626 			tcp->tcp_timer_tid = 0;
3627 		}
3628 		/*
3629 		 * Need to cancel those timers which will not be used when
3630 		 * TCP is detached.  This has to be done before the tcp_wq
3631 		 * is set to the global queue.
3632 		 */
3633 		tcp_timers_stop(tcp);
3634 
3635 
3636 		tcp->tcp_detached = B_TRUE;
3637 		tcp->tcp_rq = tcp_g_q;
3638 		tcp->tcp_wq = WR(tcp_g_q);
3639 
3640 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3641 			tcp_time_wait_append(tcp);
3642 			TCP_DBGSTAT(tcp_detach_time_wait);
3643 			goto finish;
3644 		}
3645 
3646 		/*
3647 		 * If delta is zero the timer event wasn't executed and was
3648 		 * successfully canceled. In this case we need to restart it
3649 		 * with the minimal delta possible.
3650 		 */
3651 		if (delta >= 0) {
3652 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3653 			    delta ? delta : 1);
3654 		}
3655 	} else {
3656 		tcp_closei_local(tcp);
3657 		CONN_DEC_REF(tcp->tcp_connp);
3658 	}
3659 finish:
3660 	/* Signal closing thread that it can complete close */
3661 	mutex_enter(&tcp->tcp_closelock);
3662 	tcp->tcp_detached = B_TRUE;
3663 	tcp->tcp_rq = tcp_g_q;
3664 	tcp->tcp_wq = WR(tcp_g_q);
3665 	tcp->tcp_closed = 1;
3666 	cv_signal(&tcp->tcp_closecv);
3667 	mutex_exit(&tcp->tcp_closelock);
3668 }
3669 
3670 /*
3671  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3672  * expires.
3673  */
3674 static void
3675 tcp_close_linger_timeout(void *arg)
3676 {
3677 	conn_t	*connp = (conn_t *)arg;
3678 	tcp_t 	*tcp = connp->conn_tcp;
3679 
3680 	tcp->tcp_client_errno = ETIMEDOUT;
3681 	tcp_stop_lingering(tcp);
3682 }
3683 
3684 static int
3685 tcp_close(queue_t *q, int flags)
3686 {
3687 	conn_t		*connp = Q_TO_CONN(q);
3688 	tcp_t		*tcp = connp->conn_tcp;
3689 	mblk_t 		*mp = &tcp->tcp_closemp;
3690 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3691 
3692 	ASSERT(WR(q)->q_next == NULL);
3693 	ASSERT(connp->conn_ref >= 2);
3694 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
3695 
3696 	/*
3697 	 * We are being closed as /dev/tcp or /dev/tcp6.
3698 	 *
3699 	 * Mark the conn as closing. ill_pending_mp_add will not
3700 	 * add any mp to the pending mp list, after this conn has
3701 	 * started closing. Same for sq_pending_mp_add
3702 	 */
3703 	mutex_enter(&connp->conn_lock);
3704 	connp->conn_state_flags |= CONN_CLOSING;
3705 	if (connp->conn_oper_pending_ill != NULL)
3706 		conn_ioctl_cleanup_reqd = B_TRUE;
3707 	CONN_INC_REF_LOCKED(connp);
3708 	mutex_exit(&connp->conn_lock);
3709 	tcp->tcp_closeflags = (uint8_t)flags;
3710 	ASSERT(connp->conn_ref >= 3);
3711 
3712 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
3713 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
3714 
3715 	mutex_enter(&tcp->tcp_closelock);
3716 	while (!tcp->tcp_closed)
3717 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3718 	mutex_exit(&tcp->tcp_closelock);
3719 	/*
3720 	 * In the case of listener streams that have eagers in the q or q0
3721 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3722 	 * tcp_wq of the eagers point to our queues. By waiting for the
3723 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3724 	 * up their queue pointers and also dropped their references to us.
3725 	 */
3726 	if (tcp->tcp_wait_for_eagers) {
3727 		mutex_enter(&connp->conn_lock);
3728 		while (connp->conn_ref != 1) {
3729 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3730 		}
3731 		mutex_exit(&connp->conn_lock);
3732 	}
3733 	/*
3734 	 * ioctl cleanup. The mp is queued in the
3735 	 * ill_pending_mp or in the sq_pending_mp.
3736 	 */
3737 	if (conn_ioctl_cleanup_reqd)
3738 		conn_ioctl_cleanup(connp);
3739 
3740 	qprocsoff(q);
3741 	inet_minor_free(ip_minor_arena, connp->conn_dev);
3742 
3743 	ASSERT(connp->conn_cred != NULL);
3744 	crfree(connp->conn_cred);
3745 	tcp->tcp_cred = connp->conn_cred = NULL;
3746 	tcp->tcp_cpid = -1;
3747 
3748 	/*
3749 	 * Drop IP's reference on the conn. This is the last reference
3750 	 * on the connp if the state was less than established. If the
3751 	 * connection has gone into timewait state, then we will have
3752 	 * one ref for the TCP and one more ref (total of two) for the
3753 	 * classifier connected hash list (a timewait connections stays
3754 	 * in connected hash till closed).
3755 	 *
3756 	 * We can't assert the references because there might be other
3757 	 * transient reference places because of some walkers or queued
3758 	 * packets in squeue for the timewait state.
3759 	 */
3760 	CONN_DEC_REF(connp);
3761 	q->q_ptr = WR(q)->q_ptr = NULL;
3762 	return (0);
3763 }
3764 
3765 static int
3766 tcpclose_accept(queue_t *q)
3767 {
3768 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3769 
3770 	/*
3771 	 * We had opened an acceptor STREAM for sockfs which is
3772 	 * now being closed due to some error.
3773 	 */
3774 	qprocsoff(q);
3775 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
3776 	q->q_ptr = WR(q)->q_ptr = NULL;
3777 	return (0);
3778 }
3779 
3780 
3781 /*
3782  * Called by streams close routine via squeues when our client blows off her
3783  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3784  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3785  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3786  * acked.
3787  *
3788  * NOTE: tcp_close potentially returns error when lingering.
3789  * However, the stream head currently does not pass these errors
3790  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3791  * errors to the application (from tsleep()) and not errors
3792  * like ECONNRESET caused by receiving a reset packet.
3793  */
3794 
3795 /* ARGSUSED */
3796 static void
3797 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3798 {
3799 	char	*msg;
3800 	conn_t	*connp = (conn_t *)arg;
3801 	tcp_t	*tcp = connp->conn_tcp;
3802 	clock_t	delta = 0;
3803 
3804 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3805 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3806 
3807 	/* Cancel any pending timeout */
3808 	if (tcp->tcp_ordrelid != 0) {
3809 		if (tcp->tcp_timeout) {
3810 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
3811 		}
3812 		tcp->tcp_ordrelid = 0;
3813 		tcp->tcp_timeout = B_FALSE;
3814 	}
3815 
3816 	mutex_enter(&tcp->tcp_eager_lock);
3817 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3818 		/* Cleanup for listener */
3819 		tcp_eager_cleanup(tcp, 0);
3820 		tcp->tcp_wait_for_eagers = 1;
3821 	}
3822 	mutex_exit(&tcp->tcp_eager_lock);
3823 
3824 	connp->conn_mdt_ok = B_FALSE;
3825 	tcp->tcp_mdt = B_FALSE;
3826 
3827 	msg = NULL;
3828 	switch (tcp->tcp_state) {
3829 	case TCPS_CLOSED:
3830 	case TCPS_IDLE:
3831 	case TCPS_BOUND:
3832 	case TCPS_LISTEN:
3833 		break;
3834 	case TCPS_SYN_SENT:
3835 		msg = "tcp_close, during connect";
3836 		break;
3837 	case TCPS_SYN_RCVD:
3838 		/*
3839 		 * Close during the connect 3-way handshake
3840 		 * but here there may or may not be pending data
3841 		 * already on queue. Process almost same as in
3842 		 * the ESTABLISHED state.
3843 		 */
3844 		/* FALLTHRU */
3845 	default:
3846 		if (tcp->tcp_fused)
3847 			tcp_unfuse(tcp);
3848 
3849 		/*
3850 		 * If SO_LINGER has set a zero linger time, abort the
3851 		 * connection with a reset.
3852 		 */
3853 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3854 			msg = "tcp_close, zero lingertime";
3855 			break;
3856 		}
3857 
3858 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3859 		/*
3860 		 * Abort connection if there is unread data queued.
3861 		 */
3862 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3863 			msg = "tcp_close, unread data";
3864 			break;
3865 		}
3866 		/*
3867 		 * tcp_hard_bound is now cleared thus all packets go through
3868 		 * tcp_lookup. This fact is used by tcp_detach below.
3869 		 *
3870 		 * We have done a qwait() above which could have possibly
3871 		 * drained more messages in turn causing transition to a
3872 		 * different state. Check whether we have to do the rest
3873 		 * of the processing or not.
3874 		 */
3875 		if (tcp->tcp_state <= TCPS_LISTEN)
3876 			break;
3877 
3878 		/*
3879 		 * Transmit the FIN before detaching the tcp_t.
3880 		 * After tcp_detach returns this queue/perimeter
3881 		 * no longer owns the tcp_t thus others can modify it.
3882 		 */
3883 		(void) tcp_xmit_end(tcp);
3884 
3885 		/*
3886 		 * If lingering on close then wait until the fin is acked,
3887 		 * the SO_LINGER time passes, or a reset is sent/received.
3888 		 */
3889 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3890 		    !(tcp->tcp_fin_acked) &&
3891 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3892 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3893 				tcp->tcp_client_errno = EWOULDBLOCK;
3894 			} else if (tcp->tcp_client_errno == 0) {
3895 
3896 				ASSERT(tcp->tcp_linger_tid == 0);
3897 
3898 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3899 				    tcp_close_linger_timeout,
3900 				    tcp->tcp_lingertime * hz);
3901 
3902 				/* tcp_close_linger_timeout will finish close */
3903 				if (tcp->tcp_linger_tid == 0)
3904 					tcp->tcp_client_errno = ENOSR;
3905 				else
3906 					return;
3907 			}
3908 
3909 			/*
3910 			 * Check if we need to detach or just close
3911 			 * the instance.
3912 			 */
3913 			if (tcp->tcp_state <= TCPS_LISTEN)
3914 				break;
3915 		}
3916 
3917 		/*
3918 		 * Make sure that no other thread will access the tcp_rq of
3919 		 * this instance (through lookups etc.) as tcp_rq will go
3920 		 * away shortly.
3921 		 */
3922 		tcp_acceptor_hash_remove(tcp);
3923 
3924 		if (tcp->tcp_flow_stopped) {
3925 			tcp_clrqfull(tcp);
3926 		}
3927 
3928 		if (tcp->tcp_timer_tid != 0) {
3929 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3930 			tcp->tcp_timer_tid = 0;
3931 		}
3932 		/*
3933 		 * Need to cancel those timers which will not be used when
3934 		 * TCP is detached.  This has to be done before the tcp_wq
3935 		 * is set to the global queue.
3936 		 */
3937 		tcp_timers_stop(tcp);
3938 
3939 		tcp->tcp_detached = B_TRUE;
3940 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3941 			tcp_time_wait_append(tcp);
3942 			TCP_DBGSTAT(tcp_detach_time_wait);
3943 			ASSERT(connp->conn_ref >= 3);
3944 			goto finish;
3945 		}
3946 
3947 		/*
3948 		 * If delta is zero the timer event wasn't executed and was
3949 		 * successfully canceled. In this case we need to restart it
3950 		 * with the minimal delta possible.
3951 		 */
3952 		if (delta >= 0)
3953 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3954 			    delta ? delta : 1);
3955 
3956 		ASSERT(connp->conn_ref >= 3);
3957 		goto finish;
3958 	}
3959 
3960 	/* Detach did not complete. Still need to remove q from stream. */
3961 	if (msg) {
3962 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3963 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3964 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3965 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3966 		    tcp->tcp_state == TCPS_SYN_RCVD)
3967 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3968 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3969 	}
3970 
3971 	tcp_closei_local(tcp);
3972 	CONN_DEC_REF(connp);
3973 	ASSERT(connp->conn_ref >= 2);
3974 
3975 finish:
3976 	/*
3977 	 * Although packets are always processed on the correct
3978 	 * tcp's perimeter and access is serialized via squeue's,
3979 	 * IP still needs a queue when sending packets in time_wait
3980 	 * state so use WR(tcp_g_q) till ip_output() can be
3981 	 * changed to deal with just connp. For read side, we
3982 	 * could have set tcp_rq to NULL but there are some cases
3983 	 * in tcp_rput_data() from early days of this code which
3984 	 * do a putnext without checking if tcp is closed. Those
3985 	 * need to be identified before both tcp_rq and tcp_wq
3986 	 * can be set to NULL and tcp_q_q can disappear forever.
3987 	 */
3988 	mutex_enter(&tcp->tcp_closelock);
3989 	/*
3990 	 * Don't change the queues in the case of a listener that has
3991 	 * eagers in its q or q0. It could surprise the eagers.
3992 	 * Instead wait for the eagers outside the squeue.
3993 	 */
3994 	if (!tcp->tcp_wait_for_eagers) {
3995 		tcp->tcp_detached = B_TRUE;
3996 		tcp->tcp_rq = tcp_g_q;
3997 		tcp->tcp_wq = WR(tcp_g_q);
3998 	}
3999 	/* Signal tcp_close() to finish closing. */
4000 	tcp->tcp_closed = 1;
4001 	cv_signal(&tcp->tcp_closecv);
4002 	mutex_exit(&tcp->tcp_closelock);
4003 }
4004 
4005 
4006 /*
4007  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4008  * Some stream heads get upset if they see these later on as anything but NULL.
4009  */
4010 static void
4011 tcp_close_mpp(mblk_t **mpp)
4012 {
4013 	mblk_t	*mp;
4014 
4015 	if ((mp = *mpp) != NULL) {
4016 		do {
4017 			mp->b_next = NULL;
4018 			mp->b_prev = NULL;
4019 		} while ((mp = mp->b_cont) != NULL);
4020 
4021 		mp = *mpp;
4022 		*mpp = NULL;
4023 		freemsg(mp);
4024 	}
4025 }
4026 
4027 /* Do detached close. */
4028 static void
4029 tcp_close_detached(tcp_t *tcp)
4030 {
4031 	if (tcp->tcp_fused)
4032 		tcp_unfuse(tcp);
4033 
4034 	/*
4035 	 * Clustering code serializes TCP disconnect callbacks and
4036 	 * cluster tcp list walks by blocking a TCP disconnect callback
4037 	 * if a cluster tcp list walk is in progress. This ensures
4038 	 * accurate accounting of TCPs in the cluster code even though
4039 	 * the TCP list walk itself is not atomic.
4040 	 */
4041 	tcp_closei_local(tcp);
4042 	CONN_DEC_REF(tcp->tcp_connp);
4043 }
4044 
4045 /*
4046  * Stop all TCP timers, and free the timer mblks if requested.
4047  */
4048 void
4049 tcp_timers_stop(tcp_t *tcp)
4050 {
4051 	if (tcp->tcp_timer_tid != 0) {
4052 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4053 		tcp->tcp_timer_tid = 0;
4054 	}
4055 	if (tcp->tcp_ka_tid != 0) {
4056 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4057 		tcp->tcp_ka_tid = 0;
4058 	}
4059 	if (tcp->tcp_ack_tid != 0) {
4060 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4061 		tcp->tcp_ack_tid = 0;
4062 	}
4063 	if (tcp->tcp_push_tid != 0) {
4064 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4065 		tcp->tcp_push_tid = 0;
4066 	}
4067 }
4068 
4069 /*
4070  * The tcp_t is going away. Remove it from all lists and set it
4071  * to TCPS_CLOSED. The freeing up of memory is deferred until
4072  * tcp_inactive. This is needed since a thread in tcp_rput might have
4073  * done a CONN_INC_REF on this structure before it was removed from the
4074  * hashes.
4075  */
4076 static void
4077 tcp_closei_local(tcp_t *tcp)
4078 {
4079 	ire_t 	*ire;
4080 	conn_t	*connp = tcp->tcp_connp;
4081 
4082 	if (!TCP_IS_SOCKET(tcp))
4083 		tcp_acceptor_hash_remove(tcp);
4084 
4085 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
4086 	tcp->tcp_ibsegs = 0;
4087 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
4088 	tcp->tcp_obsegs = 0;
4089 	/*
4090 	 * If we are an eager connection hanging off a listener that
4091 	 * hasn't formally accepted the connection yet, get off his
4092 	 * list and blow off any data that we have accumulated.
4093 	 */
4094 	if (tcp->tcp_listener != NULL) {
4095 		tcp_t	*listener = tcp->tcp_listener;
4096 		mutex_enter(&listener->tcp_eager_lock);
4097 		/*
4098 		 * tcp_eager_conn_ind == NULL means that the
4099 		 * conn_ind has already gone to listener. At
4100 		 * this point, eager will be closed but we
4101 		 * leave it in listeners eager list so that
4102 		 * if listener decides to close without doing
4103 		 * accept, we can clean this up. In tcp_wput_accept
4104 		 * we take case of the case of accept on closed
4105 		 * eager.
4106 		 */
4107 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4108 			tcp_eager_unlink(tcp);
4109 			mutex_exit(&listener->tcp_eager_lock);
4110 			/*
4111 			 * We don't want to have any pointers to the
4112 			 * listener queue, after we have released our
4113 			 * reference on the listener
4114 			 */
4115 			tcp->tcp_rq = tcp_g_q;
4116 			tcp->tcp_wq = WR(tcp_g_q);
4117 			CONN_DEC_REF(listener->tcp_connp);
4118 		} else {
4119 			mutex_exit(&listener->tcp_eager_lock);
4120 		}
4121 	}
4122 
4123 	/* Stop all the timers */
4124 	tcp_timers_stop(tcp);
4125 
4126 	if (tcp->tcp_state == TCPS_LISTEN) {
4127 		if (tcp->tcp_ip_addr_cache) {
4128 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4129 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4130 			tcp->tcp_ip_addr_cache = NULL;
4131 		}
4132 	}
4133 	if (tcp->tcp_flow_stopped)
4134 		tcp_clrqfull(tcp);
4135 
4136 	tcp_bind_hash_remove(tcp);
4137 	/*
4138 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4139 	 * is trying to remove this tcp from the time wait list, we will
4140 	 * block in tcp_time_wait_remove while trying to acquire the
4141 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4142 	 * requires the ipcl_hash_remove to be ordered after the
4143 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4144 	 */
4145 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4146 		tcp_time_wait_remove(tcp, NULL);
4147 	CL_INET_DISCONNECT(tcp);
4148 	ipcl_hash_remove(connp);
4149 
4150 	/*
4151 	 * Delete the cached ire in conn_ire_cache and also mark
4152 	 * the conn as CONDEMNED
4153 	 */
4154 	mutex_enter(&connp->conn_lock);
4155 	connp->conn_state_flags |= CONN_CONDEMNED;
4156 	ire = connp->conn_ire_cache;
4157 	connp->conn_ire_cache = NULL;
4158 	mutex_exit(&connp->conn_lock);
4159 	if (ire != NULL)
4160 		IRE_REFRELE_NOTR(ire);
4161 
4162 	/* Need to cleanup any pending ioctls */
4163 	ASSERT(tcp->tcp_time_wait_next == NULL);
4164 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4165 	ASSERT(tcp->tcp_time_wait_expire == 0);
4166 	tcp->tcp_state = TCPS_CLOSED;
4167 }
4168 
4169 /*
4170  * tcp is dying (called from ipcl_conn_destroy and error cases).
4171  * Free the tcp_t in either case.
4172  */
4173 void
4174 tcp_free(tcp_t *tcp)
4175 {
4176 	mblk_t	*mp;
4177 	ip6_pkt_t	*ipp;
4178 
4179 	ASSERT(tcp != NULL);
4180 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4181 
4182 	tcp->tcp_rq = NULL;
4183 	tcp->tcp_wq = NULL;
4184 
4185 	tcp_close_mpp(&tcp->tcp_xmit_head);
4186 	tcp_close_mpp(&tcp->tcp_reass_head);
4187 	if (tcp->tcp_rcv_list != NULL) {
4188 		/* Free b_next chain */
4189 		tcp_close_mpp(&tcp->tcp_rcv_list);
4190 	}
4191 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4192 		freemsg(mp);
4193 	}
4194 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4195 		freemsg(mp);
4196 	}
4197 
4198 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4199 		freeb(tcp->tcp_fused_sigurg_mp);
4200 		tcp->tcp_fused_sigurg_mp = NULL;
4201 	}
4202 
4203 	if (tcp->tcp_sack_info != NULL) {
4204 		if (tcp->tcp_notsack_list != NULL) {
4205 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4206 		}
4207 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4208 	}
4209 
4210 	if (tcp->tcp_hopopts != NULL) {
4211 		mi_free(tcp->tcp_hopopts);
4212 		tcp->tcp_hopopts = NULL;
4213 		tcp->tcp_hopoptslen = 0;
4214 	}
4215 	ASSERT(tcp->tcp_hopoptslen == 0);
4216 	if (tcp->tcp_dstopts != NULL) {
4217 		mi_free(tcp->tcp_dstopts);
4218 		tcp->tcp_dstopts = NULL;
4219 		tcp->tcp_dstoptslen = 0;
4220 	}
4221 	ASSERT(tcp->tcp_dstoptslen == 0);
4222 	if (tcp->tcp_rtdstopts != NULL) {
4223 		mi_free(tcp->tcp_rtdstopts);
4224 		tcp->tcp_rtdstopts = NULL;
4225 		tcp->tcp_rtdstoptslen = 0;
4226 	}
4227 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4228 	if (tcp->tcp_rthdr != NULL) {
4229 		mi_free(tcp->tcp_rthdr);
4230 		tcp->tcp_rthdr = NULL;
4231 		tcp->tcp_rthdrlen = 0;
4232 	}
4233 	ASSERT(tcp->tcp_rthdrlen == 0);
4234 
4235 	ipp = &tcp->tcp_sticky_ipp;
4236 	if ((ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS |
4237 	    IPPF_DSTOPTS | IPPF_RTHDR)) != 0) {
4238 		if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
4239 			kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
4240 			ipp->ipp_hopopts = NULL;
4241 			ipp->ipp_hopoptslen = 0;
4242 		}
4243 		if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
4244 			kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
4245 			ipp->ipp_rtdstopts = NULL;
4246 			ipp->ipp_rtdstoptslen = 0;
4247 		}
4248 		if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
4249 			kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
4250 			ipp->ipp_dstopts = NULL;
4251 			ipp->ipp_dstoptslen = 0;
4252 		}
4253 		if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
4254 			kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
4255 			ipp->ipp_rthdr = NULL;
4256 			ipp->ipp_rthdrlen = 0;
4257 		}
4258 		ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS |
4259 		    IPPF_DSTOPTS | IPPF_RTHDR);
4260 	}
4261 
4262 	/*
4263 	 * Free memory associated with the tcp/ip header template.
4264 	 */
4265 
4266 	if (tcp->tcp_iphc != NULL)
4267 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4268 
4269 	/*
4270 	 * Following is really a blowing away a union.
4271 	 * It happens to have exactly two members of identical size
4272 	 * the following code is enough.
4273 	 */
4274 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4275 
4276 	if (tcp->tcp_tracebuf != NULL) {
4277 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4278 		tcp->tcp_tracebuf = NULL;
4279 	}
4280 }
4281 
4282 
4283 /*
4284  * Put a connection confirmation message upstream built from the
4285  * address information within 'iph' and 'tcph'.  Report our success or failure.
4286  */
4287 static boolean_t
4288 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4289     mblk_t **defermp)
4290 {
4291 	sin_t	sin;
4292 	sin6_t	sin6;
4293 	mblk_t	*mp;
4294 	char	*optp = NULL;
4295 	int	optlen = 0;
4296 	cred_t	*cr;
4297 
4298 	if (defermp != NULL)
4299 		*defermp = NULL;
4300 
4301 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4302 		/*
4303 		 * Return in T_CONN_CON results of option negotiation through
4304 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4305 		 * negotiation, then what is received from remote end needs
4306 		 * to be taken into account but there is no such thing (yet?)
4307 		 * in our TCP/IP.
4308 		 * Note: We do not use mi_offset_param() here as
4309 		 * tcp_opts_conn_req contents do not directly come from
4310 		 * an application and are either generated in kernel or
4311 		 * from user input that was already verified.
4312 		 */
4313 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4314 		optp = (char *)(mp->b_rptr +
4315 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4316 		optlen = (int)
4317 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4318 	}
4319 
4320 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4321 		ipha_t *ipha = (ipha_t *)iphdr;
4322 
4323 		/* packet is IPv4 */
4324 		if (tcp->tcp_family == AF_INET) {
4325 			sin = sin_null;
4326 			sin.sin_addr.s_addr = ipha->ipha_src;
4327 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4328 			sin.sin_family = AF_INET;
4329 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4330 			    (int)sizeof (sin_t), optp, optlen);
4331 		} else {
4332 			sin6 = sin6_null;
4333 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4334 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4335 			sin6.sin6_family = AF_INET6;
4336 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4337 			    (int)sizeof (sin6_t), optp, optlen);
4338 
4339 		}
4340 	} else {
4341 		ip6_t	*ip6h = (ip6_t *)iphdr;
4342 
4343 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4344 		ASSERT(tcp->tcp_family == AF_INET6);
4345 		sin6 = sin6_null;
4346 		sin6.sin6_addr = ip6h->ip6_src;
4347 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4348 		sin6.sin6_family = AF_INET6;
4349 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4350 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4351 		    (int)sizeof (sin6_t), optp, optlen);
4352 	}
4353 
4354 	if (!mp)
4355 		return (B_FALSE);
4356 
4357 	if ((cr = DB_CRED(idmp)) != NULL) {
4358 		mblk_setcred(mp, cr);
4359 		DB_CPID(mp) = DB_CPID(idmp);
4360 	}
4361 
4362 	if (defermp == NULL)
4363 		putnext(tcp->tcp_rq, mp);
4364 	else
4365 		*defermp = mp;
4366 
4367 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4368 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4369 	return (B_TRUE);
4370 }
4371 
4372 /*
4373  * Defense for the SYN attack -
4374  * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
4375  *    one that doesn't have the dontdrop bit set.
4376  * 2. Don't drop a SYN request before its first timeout. This gives every
4377  *    request at least til the first timeout to complete its 3-way handshake.
4378  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4379  *    requests currently on the queue that has timed out. This will be used
4380  *    as an indicator of whether an attack is under way, so that appropriate
4381  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4382  *    either when eager goes into ESTABLISHED, or gets freed up.)
4383  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4384  *    # of timeout drops back to <= q0len/32 => SYN alert off
4385  */
4386 static boolean_t
4387 tcp_drop_q0(tcp_t *tcp)
4388 {
4389 	tcp_t	*eager;
4390 
4391 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4392 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4393 	/*
4394 	 * New one is added after next_q0 so prev_q0 points to the oldest
4395 	 * Also do not drop any established connections that are deferred on
4396 	 * q0 due to q being full
4397 	 */
4398 
4399 	eager = tcp->tcp_eager_prev_q0;
4400 	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
4401 		eager = eager->tcp_eager_prev_q0;
4402 		if (eager == tcp) {
4403 			eager = tcp->tcp_eager_prev_q0;
4404 			break;
4405 		}
4406 	}
4407 	if (eager->tcp_syn_rcvd_timeout == 0)
4408 		return (B_FALSE);
4409 
4410 	if (tcp->tcp_debug) {
4411 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4412 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4413 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
4414 		    tcp->tcp_conn_req_cnt_q0,
4415 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4416 	}
4417 
4418 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
4419 
4420 	/*
4421 	 * need to do refhold here because the selected eager could
4422 	 * be removed by someone else if we release the eager lock.
4423 	 */
4424 	CONN_INC_REF(eager->tcp_connp);
4425 	mutex_exit(&tcp->tcp_eager_lock);
4426 
4427 	/* Mark the IRE created for this SYN request temporary */
4428 	tcp_ip_ire_mark_advice(eager);
4429 	(void) tcp_clean_death(eager, ETIMEDOUT, 5);
4430 	CONN_DEC_REF(eager->tcp_connp);
4431 
4432 	mutex_enter(&tcp->tcp_eager_lock);
4433 	return (B_TRUE);
4434 }
4435 
4436 int
4437 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4438     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4439 {
4440 	tcp_t 		*ltcp = lconnp->conn_tcp;
4441 	tcp_t		*tcp = connp->conn_tcp;
4442 	mblk_t		*tpi_mp;
4443 	ipha_t		*ipha;
4444 	ip6_t		*ip6h;
4445 	sin6_t 		sin6;
4446 	in6_addr_t 	v6dst;
4447 	int		err;
4448 	int		ifindex = 0;
4449 	cred_t		*cr;
4450 
4451 	if (ipvers == IPV4_VERSION) {
4452 		ipha = (ipha_t *)mp->b_rptr;
4453 
4454 		connp->conn_send = ip_output;
4455 		connp->conn_recv = tcp_input;
4456 
4457 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4458 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4459 
4460 		sin6 = sin6_null;
4461 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4462 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4463 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4464 		sin6.sin6_family = AF_INET6;
4465 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4466 		    lconnp->conn_zoneid);
4467 		if (tcp->tcp_recvdstaddr) {
4468 			sin6_t	sin6d;
4469 
4470 			sin6d = sin6_null;
4471 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4472 			    &sin6d.sin6_addr);
4473 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4474 			sin6d.sin6_family = AF_INET;
4475 			tpi_mp = mi_tpi_extconn_ind(NULL,
4476 			    (char *)&sin6d, sizeof (sin6_t),
4477 			    (char *)&tcp,
4478 			    (t_scalar_t)sizeof (intptr_t),
4479 			    (char *)&sin6d, sizeof (sin6_t),
4480 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4481 		} else {
4482 			tpi_mp = mi_tpi_conn_ind(NULL,
4483 			    (char *)&sin6, sizeof (sin6_t),
4484 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4485 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4486 		}
4487 	} else {
4488 		ip6h = (ip6_t *)mp->b_rptr;
4489 
4490 		connp->conn_send = ip_output_v6;
4491 		connp->conn_recv = tcp_input;
4492 
4493 		connp->conn_srcv6 = ip6h->ip6_dst;
4494 		connp->conn_remv6 = ip6h->ip6_src;
4495 
4496 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4497 		ifindex = (int)DB_CKSUMSTUFF(mp);
4498 		DB_CKSUMSTUFF(mp) = 0;
4499 
4500 		sin6 = sin6_null;
4501 		sin6.sin6_addr = ip6h->ip6_src;
4502 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4503 		sin6.sin6_family = AF_INET6;
4504 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4505 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4506 		    lconnp->conn_zoneid);
4507 
4508 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4509 			/* Pass up the scope_id of remote addr */
4510 			sin6.sin6_scope_id = ifindex;
4511 		} else {
4512 			sin6.sin6_scope_id = 0;
4513 		}
4514 		if (tcp->tcp_recvdstaddr) {
4515 			sin6_t	sin6d;
4516 
4517 			sin6d = sin6_null;
4518 			sin6.sin6_addr = ip6h->ip6_dst;
4519 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4520 			sin6d.sin6_family = AF_INET;
4521 			tpi_mp = mi_tpi_extconn_ind(NULL,
4522 			    (char *)&sin6d, sizeof (sin6_t),
4523 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4524 			    (char *)&sin6d, sizeof (sin6_t),
4525 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4526 		} else {
4527 			tpi_mp = mi_tpi_conn_ind(NULL,
4528 			    (char *)&sin6, sizeof (sin6_t),
4529 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4530 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4531 		}
4532 	}
4533 
4534 	if (tpi_mp == NULL)
4535 		return (ENOMEM);
4536 
4537 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4538 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4539 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4540 	connp->conn_fully_bound = B_FALSE;
4541 
4542 	if (tcp_trace)
4543 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4544 
4545 	/* Inherit information from the "parent" */
4546 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4547 	tcp->tcp_family = ltcp->tcp_family;
4548 	tcp->tcp_wq = ltcp->tcp_wq;
4549 	tcp->tcp_rq = ltcp->tcp_rq;
4550 	tcp->tcp_mss = tcp_mss_def_ipv6;
4551 	tcp->tcp_detached = B_TRUE;
4552 	if ((err = tcp_init_values(tcp)) != 0) {
4553 		freemsg(tpi_mp);
4554 		return (err);
4555 	}
4556 
4557 	if (ipvers == IPV4_VERSION) {
4558 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4559 			freemsg(tpi_mp);
4560 			return (err);
4561 		}
4562 		ASSERT(tcp->tcp_ipha != NULL);
4563 	} else {
4564 		/* ifindex must be already set */
4565 		ASSERT(ifindex != 0);
4566 
4567 		if (ltcp->tcp_bound_if != 0) {
4568 			/*
4569 			 * Set newtcp's bound_if equal to
4570 			 * listener's value. If ifindex is
4571 			 * not the same as ltcp->tcp_bound_if,
4572 			 * it must be a packet for the ipmp group
4573 			 * of interfaces
4574 			 */
4575 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4576 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4577 			tcp->tcp_bound_if = ifindex;
4578 		}
4579 
4580 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4581 		tcp->tcp_recvifindex = 0;
4582 		tcp->tcp_recvhops = 0xffffffffU;
4583 		ASSERT(tcp->tcp_ip6h != NULL);
4584 	}
4585 
4586 	tcp->tcp_lport = ltcp->tcp_lport;
4587 
4588 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4589 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4590 			/*
4591 			 * Listener had options of some sort; eager inherits.
4592 			 * Free up the eager template and allocate one
4593 			 * of the right size.
4594 			 */
4595 			if (tcp->tcp_hdr_grown) {
4596 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4597 			} else {
4598 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4599 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4600 			}
4601 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4602 			    KM_NOSLEEP);
4603 			if (tcp->tcp_iphc == NULL) {
4604 				tcp->tcp_iphc_len = 0;
4605 				freemsg(tpi_mp);
4606 				return (ENOMEM);
4607 			}
4608 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4609 			tcp->tcp_hdr_grown = B_TRUE;
4610 		}
4611 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4612 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4613 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4614 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4615 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4616 
4617 		/*
4618 		 * Copy the IP+TCP header template from listener to eager
4619 		 */
4620 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4621 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4622 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4623 			    IPPROTO_RAW) {
4624 				tcp->tcp_ip6h =
4625 				    (ip6_t *)(tcp->tcp_iphc +
4626 					sizeof (ip6i_t));
4627 			} else {
4628 				tcp->tcp_ip6h =
4629 				    (ip6_t *)(tcp->tcp_iphc);
4630 			}
4631 			tcp->tcp_ipha = NULL;
4632 		} else {
4633 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4634 			tcp->tcp_ip6h = NULL;
4635 		}
4636 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4637 		    tcp->tcp_ip_hdr_len);
4638 	} else {
4639 		/*
4640 		 * only valid case when ipversion of listener and
4641 		 * eager differ is when listener is IPv6 and
4642 		 * eager is IPv4.
4643 		 * Eager header template has been initialized to the
4644 		 * maximum v4 header sizes, which includes space for
4645 		 * TCP and IP options.
4646 		 */
4647 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4648 		    (tcp->tcp_ipversion == IPV4_VERSION));
4649 		ASSERT(tcp->tcp_iphc_len >=
4650 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4651 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4652 		/* copy IP header fields individually */
4653 		tcp->tcp_ipha->ipha_ttl =
4654 		    ltcp->tcp_ip6h->ip6_hops;
4655 		bcopy(ltcp->tcp_tcph->th_lport,
4656 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4657 	}
4658 
4659 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4660 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4661 	    sizeof (in_port_t));
4662 
4663 	if (ltcp->tcp_lport == 0) {
4664 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4665 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4666 		    sizeof (in_port_t));
4667 	}
4668 
4669 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4670 		ASSERT(ipha != NULL);
4671 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4672 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4673 
4674 		/* Source routing option copyover (reverse it) */
4675 		if (tcp_rev_src_routes)
4676 			tcp_opt_reverse(tcp, ipha);
4677 	} else {
4678 		ASSERT(ip6h != NULL);
4679 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4680 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4681 	}
4682 
4683 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4684 	/*
4685 	 * If the SYN contains a credential, it's a loopback packet; attach
4686 	 * the credential to the TPI message.
4687 	 */
4688 	if ((cr = DB_CRED(idmp)) != NULL) {
4689 		mblk_setcred(tpi_mp, cr);
4690 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4691 	}
4692 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4693 
4694 	return (0);
4695 }
4696 
4697 
4698 int
4699 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4700     tcph_t *tcph, mblk_t *idmp)
4701 {
4702 	tcp_t 		*ltcp = lconnp->conn_tcp;
4703 	tcp_t		*tcp = connp->conn_tcp;
4704 	sin_t		sin;
4705 	mblk_t		*tpi_mp = NULL;
4706 	int		err;
4707 	cred_t		*cr;
4708 
4709 	sin = sin_null;
4710 	sin.sin_addr.s_addr = ipha->ipha_src;
4711 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4712 	sin.sin_family = AF_INET;
4713 	if (ltcp->tcp_recvdstaddr) {
4714 		sin_t	sind;
4715 
4716 		sind = sin_null;
4717 		sind.sin_addr.s_addr = ipha->ipha_dst;
4718 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4719 		sind.sin_family = AF_INET;
4720 		tpi_mp = mi_tpi_extconn_ind(NULL,
4721 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4722 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4723 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4724 	} else {
4725 		tpi_mp = mi_tpi_conn_ind(NULL,
4726 		    (char *)&sin, sizeof (sin_t),
4727 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4728 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4729 	}
4730 
4731 	if (tpi_mp == NULL) {
4732 		return (ENOMEM);
4733 	}
4734 
4735 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4736 	connp->conn_send = ip_output;
4737 	connp->conn_recv = tcp_input;
4738 	connp->conn_fully_bound = B_FALSE;
4739 
4740 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4741 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4742 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4743 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4744 
4745 	if (tcp_trace) {
4746 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4747 	}
4748 
4749 	/* Inherit information from the "parent" */
4750 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4751 	tcp->tcp_family = ltcp->tcp_family;
4752 	tcp->tcp_wq = ltcp->tcp_wq;
4753 	tcp->tcp_rq = ltcp->tcp_rq;
4754 	tcp->tcp_mss = tcp_mss_def_ipv4;
4755 	tcp->tcp_detached = B_TRUE;
4756 	if ((err = tcp_init_values(tcp)) != 0) {
4757 		freemsg(tpi_mp);
4758 		return (err);
4759 	}
4760 
4761 	/*
4762 	 * Let's make sure that eager tcp template has enough space to
4763 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4764 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4765 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4766 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4767 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4768 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4769 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4770 	 */
4771 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4772 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4773 
4774 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4775 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4776 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4777 	tcp->tcp_ttl = ltcp->tcp_ttl;
4778 	tcp->tcp_tos = ltcp->tcp_tos;
4779 
4780 	/* Copy the IP+TCP header template from listener to eager */
4781 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4782 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4783 	tcp->tcp_ip6h = NULL;
4784 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4785 	    tcp->tcp_ip_hdr_len);
4786 
4787 	/* Initialize the IP addresses and Ports */
4788 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4789 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4790 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4791 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4792 
4793 	/* Source routing option copyover (reverse it) */
4794 	if (tcp_rev_src_routes)
4795 		tcp_opt_reverse(tcp, ipha);
4796 
4797 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4798 
4799 	/*
4800 	 * If the SYN contains a credential, it's a loopback packet; attach
4801 	 * the credential to the TPI message.
4802 	 */
4803 	if ((cr = DB_CRED(idmp)) != NULL) {
4804 		mblk_setcred(tpi_mp, cr);
4805 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4806 	}
4807 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4808 
4809 	return (0);
4810 }
4811 
4812 /*
4813  * sets up conn for ipsec.
4814  * if the first mblk is M_CTL it is consumed and mpp is updated.
4815  * in case of error mpp is freed.
4816  */
4817 conn_t *
4818 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4819 {
4820 	conn_t 		*connp = tcp->tcp_connp;
4821 	conn_t 		*econnp;
4822 	squeue_t 	*new_sqp;
4823 	mblk_t 		*first_mp = *mpp;
4824 	mblk_t		*mp = *mpp;
4825 	boolean_t	mctl_present = B_FALSE;
4826 	uint_t		ipvers;
4827 
4828 	econnp = tcp_get_conn(sqp);
4829 	if (econnp == NULL) {
4830 		freemsg(first_mp);
4831 		return (NULL);
4832 	}
4833 	if (DB_TYPE(mp) == M_CTL) {
4834 		if (mp->b_cont == NULL ||
4835 		    mp->b_cont->b_datap->db_type != M_DATA) {
4836 			freemsg(first_mp);
4837 			return (NULL);
4838 		}
4839 		mp = mp->b_cont;
4840 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4841 			freemsg(first_mp);
4842 			return (NULL);
4843 		}
4844 
4845 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4846 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4847 		mctl_present = B_TRUE;
4848 	} else {
4849 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4850 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4851 	}
4852 
4853 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4854 	DB_CKSUMSTART(mp) = 0;
4855 
4856 	ASSERT(OK_32PTR(mp->b_rptr));
4857 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4858 	if (ipvers == IPV4_VERSION) {
4859 		uint16_t  	*up;
4860 		uint32_t	ports;
4861 		ipha_t		*ipha;
4862 
4863 		ipha = (ipha_t *)mp->b_rptr;
4864 		up = (uint16_t *)((uchar_t *)ipha +
4865 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4866 		ports = *(uint32_t *)up;
4867 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4868 		    ipha->ipha_dst, ipha->ipha_src, ports);
4869 	} else {
4870 		uint16_t  	*up;
4871 		uint32_t	ports;
4872 		uint16_t	ip_hdr_len;
4873 		uint8_t		*nexthdrp;
4874 		ip6_t 		*ip6h;
4875 		tcph_t		*tcph;
4876 
4877 		ip6h = (ip6_t *)mp->b_rptr;
4878 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4879 			ip_hdr_len = IPV6_HDR_LEN;
4880 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4881 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4882 			CONN_DEC_REF(econnp);
4883 			freemsg(first_mp);
4884 			return (NULL);
4885 		}
4886 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4887 		up = (uint16_t *)tcph->th_lport;
4888 		ports = *(uint32_t *)up;
4889 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4890 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4891 	}
4892 
4893 	/*
4894 	 * The caller already ensured that there is a sqp present.
4895 	 */
4896 	econnp->conn_sqp = new_sqp;
4897 
4898 	if (connp->conn_policy != NULL) {
4899 		ipsec_in_t *ii;
4900 		ii = (ipsec_in_t *)(first_mp->b_rptr);
4901 		ASSERT(ii->ipsec_in_policy == NULL);
4902 		IPPH_REFHOLD(connp->conn_policy);
4903 		ii->ipsec_in_policy = connp->conn_policy;
4904 
4905 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
4906 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
4907 			CONN_DEC_REF(econnp);
4908 			freemsg(first_mp);
4909 			return (NULL);
4910 		}
4911 	}
4912 
4913 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
4914 		CONN_DEC_REF(econnp);
4915 		freemsg(first_mp);
4916 		return (NULL);
4917 	}
4918 
4919 	/*
4920 	 * If we know we have some policy, pass the "IPSEC"
4921 	 * options size TCP uses this adjust the MSS.
4922 	 */
4923 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
4924 	if (mctl_present) {
4925 		freeb(first_mp);
4926 		*mpp = mp;
4927 	}
4928 
4929 	return (econnp);
4930 }
4931 
4932 /*
4933  * tcp_get_conn/tcp_free_conn
4934  *
4935  * tcp_get_conn is used to get a clean tcp connection structure.
4936  * It tries to reuse the connections put on the freelist by the
4937  * time_wait_collector failing which it goes to kmem_cache. This
4938  * way has two benefits compared to just allocating from and
4939  * freeing to kmem_cache.
4940  * 1) The time_wait_collector can free (which includes the cleanup)
4941  * outside the squeue. So when the interrupt comes, we have a clean
4942  * connection sitting in the freelist. Obviously, this buys us
4943  * performance.
4944  *
4945  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
4946  * has multiple disadvantages - tying up the squeue during alloc, and the
4947  * fact that IPSec policy initialization has to happen here which
4948  * requires us sending a M_CTL and checking for it i.e. real ugliness.
4949  * But allocating the conn/tcp in IP land is also not the best since
4950  * we can't check the 'q' and 'q0' which are protected by squeue and
4951  * blindly allocate memory which might have to be freed here if we are
4952  * not allowed to accept the connection. By using the freelist and
4953  * putting the conn/tcp back in freelist, we don't pay a penalty for
4954  * allocating memory without checking 'q/q0' and freeing it if we can't
4955  * accept the connection.
4956  *
4957  * Care should be taken to put the conn back in the same squeue's freelist
4958  * from which it was allocated. Best results are obtained if conn is
4959  * allocated from listener's squeue and freed to the same. Time wait
4960  * collector will free up the freelist is the connection ends up sitting
4961  * there for too long.
4962  */
4963 void *
4964 tcp_get_conn(void *arg)
4965 {
4966 	tcp_t			*tcp = NULL;
4967 	conn_t			*connp = NULL;
4968 	squeue_t		*sqp = (squeue_t *)arg;
4969 	tcp_squeue_priv_t 	*tcp_time_wait;
4970 
4971 	tcp_time_wait =
4972 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
4973 
4974 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
4975 	tcp = tcp_time_wait->tcp_free_list;
4976 	if (tcp != NULL) {
4977 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
4978 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4979 		tcp->tcp_time_wait_next = NULL;
4980 		connp = tcp->tcp_connp;
4981 		connp->conn_flags |= IPCL_REUSED;
4982 		return ((void *)connp);
4983 	}
4984 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4985 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
4986 		return (NULL);
4987 	return ((void *)connp);
4988 }
4989 
4990 /* BEGIN CSTYLED */
4991 /*
4992  *
4993  * The sockfs ACCEPT path:
4994  * =======================
4995  *
4996  * The eager is now established in its own perimeter as soon as SYN is
4997  * received in tcp_conn_request(). When sockfs receives conn_ind, it
4998  * completes the accept processing on the acceptor STREAM. The sending
4999  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5000  * listener but a TLI/XTI listener completes the accept processing
5001  * on the listener perimeter.
5002  *
5003  * Common control flow for 3 way handshake:
5004  * ----------------------------------------
5005  *
5006  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5007  *					-> tcp_conn_request()
5008  *
5009  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5010  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5011  *
5012  * Sockfs ACCEPT Path:
5013  * -------------------
5014  *
5015  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5016  * as STREAM entry point)
5017  *
5018  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5019  *
5020  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5021  * association (we are not behind eager's squeue but sockfs is protecting us
5022  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5023  * is changed to point at tcp_wput().
5024  *
5025  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5026  * listener (done on listener's perimeter).
5027  *
5028  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5029  * accept.
5030  *
5031  * TLI/XTI client ACCEPT path:
5032  * ---------------------------
5033  *
5034  * soaccept() sends T_CONN_RES on the listener STREAM.
5035  *
5036  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5037  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5038  *
5039  * Locks:
5040  * ======
5041  *
5042  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5043  * and listeners->tcp_eager_next_q.
5044  *
5045  * Referencing:
5046  * ============
5047  *
5048  * 1) We start out in tcp_conn_request by eager placing a ref on
5049  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5050  *
5051  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5052  * doing so we place a ref on the eager. This ref is finally dropped at the
5053  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5054  * reference is dropped by the squeue framework.
5055  *
5056  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5057  *
5058  * The reference must be released by the same entity that added the reference
5059  * In the above scheme, the eager is the entity that adds and releases the
5060  * references. Note that tcp_accept_finish executes in the squeue of the eager
5061  * (albeit after it is attached to the acceptor stream). Though 1. executes
5062  * in the listener's squeue, the eager is nascent at this point and the
5063  * reference can be considered to have been added on behalf of the eager.
5064  *
5065  * Eager getting a Reset or listener closing:
5066  * ==========================================
5067  *
5068  * Once the listener and eager are linked, the listener never does the unlink.
5069  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5070  * a message on all eager perimeter. The eager then does the unlink, clears
5071  * any pointers to the listener's queue and drops the reference to the
5072  * listener. The listener waits in tcp_close outside the squeue until its
5073  * refcount has dropped to 1. This ensures that the listener has waited for
5074  * all eagers to clear their association with the listener.
5075  *
5076  * Similarly, if eager decides to go away, it can unlink itself and close.
5077  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5078  * the reference to eager is still valid because of the extra ref we put
5079  * in tcp_send_conn_ind.
5080  *
5081  * Listener can always locate the eager under the protection
5082  * of the listener->tcp_eager_lock, and then do a refhold
5083  * on the eager during the accept processing.
5084  *
5085  * The acceptor stream accesses the eager in the accept processing
5086  * based on the ref placed on eager before sending T_conn_ind.
5087  * The only entity that can negate this refhold is a listener close
5088  * which is mutually exclusive with an active acceptor stream.
5089  *
5090  * Eager's reference on the listener
5091  * ===================================
5092  *
5093  * If the accept happens (even on a closed eager) the eager drops its
5094  * reference on the listener at the start of tcp_accept_finish. If the
5095  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5096  * the reference is dropped in tcp_closei_local. If the listener closes,
5097  * the reference is dropped in tcp_eager_kill. In all cases the reference
5098  * is dropped while executing in the eager's context (squeue).
5099  */
5100 /* END CSTYLED */
5101 
5102 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5103 
5104 /*
5105  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5106  * tcp_rput_data will not see any SYN packets.
5107  */
5108 /* ARGSUSED */
5109 void
5110 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5111 {
5112 	tcph_t		*tcph;
5113 	uint32_t	seg_seq;
5114 	tcp_t		*eager;
5115 	uint_t		ipvers;
5116 	ipha_t		*ipha;
5117 	ip6_t		*ip6h;
5118 	int		err;
5119 	conn_t		*econnp = NULL;
5120 	squeue_t	*new_sqp;
5121 	mblk_t		*mp1;
5122 	uint_t 		ip_hdr_len;
5123 	conn_t		*connp = (conn_t *)arg;
5124 	tcp_t		*tcp = connp->conn_tcp;
5125 	ire_t		*ire;
5126 
5127 	if (tcp->tcp_state != TCPS_LISTEN)
5128 		goto error2;
5129 
5130 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5131 
5132 	mutex_enter(&tcp->tcp_eager_lock);
5133 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5134 		mutex_exit(&tcp->tcp_eager_lock);
5135 		TCP_STAT(tcp_listendrop);
5136 		BUMP_MIB(&tcp_mib, tcpListenDrop);
5137 		if (tcp->tcp_debug) {
5138 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5139 			    "tcp_conn_request: listen backlog (max=%d) "
5140 			    "overflow (%d pending) on %s",
5141 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5142 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5143 		}
5144 		goto error2;
5145 	}
5146 
5147 	if (tcp->tcp_conn_req_cnt_q0 >=
5148 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
5149 		/*
5150 		 * Q0 is full. Drop a pending half-open req from the queue
5151 		 * to make room for the new SYN req. Also mark the time we
5152 		 * drop a SYN.
5153 		 *
5154 		 * A more aggressive defense against SYN attack will
5155 		 * be to set the "tcp_syn_defense" flag now.
5156 		 */
5157 		TCP_STAT(tcp_listendropq0);
5158 		tcp->tcp_last_rcv_lbolt = lbolt64;
5159 		if (!tcp_drop_q0(tcp)) {
5160 			mutex_exit(&tcp->tcp_eager_lock);
5161 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
5162 			if (tcp->tcp_debug) {
5163 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5164 				    "tcp_conn_request: listen half-open queue "
5165 				    "(max=%d) full (%d pending) on %s",
5166 				    tcp_conn_req_max_q0,
5167 				    tcp->tcp_conn_req_cnt_q0,
5168 				    tcp_display(tcp, NULL,
5169 				    DISP_PORT_ONLY));
5170 			}
5171 			goto error2;
5172 		}
5173 	}
5174 	mutex_exit(&tcp->tcp_eager_lock);
5175 
5176 	/*
5177 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5178 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5179 	 * link local address.  If IPSec is enabled, db_struioflag has
5180 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5181 	 * otherwise an error case if neither of them is set.
5182 	 */
5183 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5184 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5185 		DB_CKSUMSTART(mp) = 0;
5186 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5187 		econnp = (conn_t *)tcp_get_conn(arg2);
5188 		if (econnp == NULL)
5189 			goto error2;
5190 		econnp->conn_sqp = new_sqp;
5191 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5192 		/*
5193 		 * mp is updated in tcp_get_ipsec_conn().
5194 		 */
5195 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5196 		if (econnp == NULL) {
5197 			/*
5198 			 * mp freed by tcp_get_ipsec_conn.
5199 			 */
5200 			return;
5201 		}
5202 	} else {
5203 		goto error2;
5204 	}
5205 
5206 	ASSERT(DB_TYPE(mp) == M_DATA);
5207 
5208 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5209 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5210 	ASSERT(OK_32PTR(mp->b_rptr));
5211 	if (ipvers == IPV4_VERSION) {
5212 		ipha = (ipha_t *)mp->b_rptr;
5213 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5214 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5215 	} else {
5216 		ip6h = (ip6_t *)mp->b_rptr;
5217 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5218 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5219 	}
5220 
5221 	if (tcp->tcp_family == AF_INET) {
5222 		ASSERT(ipvers == IPV4_VERSION);
5223 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5224 	} else {
5225 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5226 	}
5227 
5228 	if (err)
5229 		goto error3;
5230 
5231 	eager = econnp->conn_tcp;
5232 
5233 	/* Inherit various TCP parameters from the listener */
5234 	eager->tcp_naglim = tcp->tcp_naglim;
5235 	eager->tcp_first_timer_threshold =
5236 	    tcp->tcp_first_timer_threshold;
5237 	eager->tcp_second_timer_threshold =
5238 	    tcp->tcp_second_timer_threshold;
5239 
5240 	eager->tcp_first_ctimer_threshold =
5241 	    tcp->tcp_first_ctimer_threshold;
5242 	eager->tcp_second_ctimer_threshold =
5243 	    tcp->tcp_second_ctimer_threshold;
5244 
5245 	/*
5246 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5247 	 * zone id before the accept is completed in tcp_wput_accept().
5248 	 */
5249 	econnp->conn_zoneid = connp->conn_zoneid;
5250 
5251 	eager->tcp_hard_binding = B_TRUE;
5252 
5253 	tcp_bind_hash_insert(&tcp_bind_fanout[
5254 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5255 
5256 	CL_INET_CONNECT(eager);
5257 
5258 	/*
5259 	 * No need to check for multicast destination since ip will only pass
5260 	 * up multicasts to those that have expressed interest
5261 	 * TODO: what about rejecting broadcasts?
5262 	 * Also check that source is not a multicast or broadcast address.
5263 	 */
5264 	eager->tcp_state = TCPS_SYN_RCVD;
5265 
5266 
5267 	/*
5268 	 * There should be no ire in the mp as we are being called after
5269 	 * receiving the SYN.
5270 	 */
5271 	ASSERT(tcp_ire_mp(mp) == NULL);
5272 
5273 	/*
5274 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5275 	 */
5276 
5277 	if (tcp_adapt_ire(eager, NULL) == 0) {
5278 		/* Undo the bind_hash_insert */
5279 		tcp_bind_hash_remove(eager);
5280 		goto error3;
5281 	}
5282 
5283 	/* Process all TCP options. */
5284 	tcp_process_options(eager, tcph);
5285 
5286 	/* Is the other end ECN capable? */
5287 	if (tcp_ecn_permitted >= 1 &&
5288 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5289 		eager->tcp_ecn_ok = B_TRUE;
5290 	}
5291 
5292 	/*
5293 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5294 	 * window size changed via SO_RCVBUF option.  First round up the
5295 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5296 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5297 	 * setting.
5298 	 *
5299 	 * Note if there is a rpipe metric associated with the remote host,
5300 	 * we should not inherit receive window size from listener.
5301 	 */
5302 	eager->tcp_rwnd = MSS_ROUNDUP(
5303 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5304 	    eager->tcp_rwnd), eager->tcp_mss);
5305 	if (eager->tcp_snd_ws_ok)
5306 		tcp_set_ws_value(eager);
5307 	/*
5308 	 * Note that this is the only place tcp_rwnd_set() is called for
5309 	 * accepting a connection.  We need to call it here instead of
5310 	 * after the 3-way handshake because we need to tell the other
5311 	 * side our rwnd in the SYN-ACK segment.
5312 	 */
5313 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5314 
5315 	/*
5316 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5317 	 * via soaccept()->soinheritoptions() which essentially applies
5318 	 * all the listener options to the new STREAM. The options that we
5319 	 * need to take care of are:
5320 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5321 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5322 	 * SO_SNDBUF, SO_RCVBUF.
5323 	 *
5324 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5325 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5326 	 *		tcp_maxpsz_set() gets called later from
5327 	 *		tcp_accept_finish(), the option takes effect.
5328 	 *
5329 	 */
5330 	/* Set the TCP options */
5331 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5332 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5333 	eager->tcp_oobinline = tcp->tcp_oobinline;
5334 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5335 	eager->tcp_broadcast = tcp->tcp_broadcast;
5336 	eager->tcp_useloopback = tcp->tcp_useloopback;
5337 	eager->tcp_dontroute = tcp->tcp_dontroute;
5338 	eager->tcp_linger = tcp->tcp_linger;
5339 	eager->tcp_lingertime = tcp->tcp_lingertime;
5340 	if (tcp->tcp_ka_enabled)
5341 		eager->tcp_ka_enabled = 1;
5342 
5343 	/* Set the IP options */
5344 	econnp->conn_broadcast = connp->conn_broadcast;
5345 	econnp->conn_loopback = connp->conn_loopback;
5346 	econnp->conn_dontroute = connp->conn_dontroute;
5347 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5348 
5349 	/* Put a ref on the listener for the eager. */
5350 	CONN_INC_REF(connp);
5351 	mutex_enter(&tcp->tcp_eager_lock);
5352 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5353 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5354 	tcp->tcp_eager_next_q0 = eager;
5355 	eager->tcp_eager_prev_q0 = tcp;
5356 
5357 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5358 	eager->tcp_listener = tcp;
5359 	eager->tcp_saved_listener = tcp;
5360 
5361 	/*
5362 	 * Tag this detached tcp vector for later retrieval
5363 	 * by our listener client in tcp_accept().
5364 	 */
5365 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5366 	tcp->tcp_conn_req_cnt_q0++;
5367 	if (++tcp->tcp_conn_req_seqnum == -1) {
5368 		/*
5369 		 * -1 is "special" and defined in TPI as something
5370 		 * that should never be used in T_CONN_IND
5371 		 */
5372 		++tcp->tcp_conn_req_seqnum;
5373 	}
5374 	mutex_exit(&tcp->tcp_eager_lock);
5375 
5376 	if (tcp->tcp_syn_defense) {
5377 		/* Don't drop the SYN that comes from a good IP source */
5378 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5379 		if (addr_cache != NULL && eager->tcp_remote ==
5380 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5381 			eager->tcp_dontdrop = B_TRUE;
5382 		}
5383 	}
5384 
5385 	/*
5386 	 * We need to insert the eager in its own perimeter but as soon
5387 	 * as we do that, we expose the eager to the classifier and
5388 	 * should not touch any field outside the eager's perimeter.
5389 	 * So do all the work necessary before inserting the eager
5390 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5391 	 * will succeed but undo everything if it fails.
5392 	 */
5393 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5394 	eager->tcp_irs = seg_seq;
5395 	eager->tcp_rack = seg_seq;
5396 	eager->tcp_rnxt = seg_seq + 1;
5397 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5398 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
5399 	eager->tcp_state = TCPS_SYN_RCVD;
5400 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5401 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5402 	if (mp1 == NULL)
5403 		goto error1;
5404 	mblk_setcred(mp1, tcp->tcp_cred);
5405 	DB_CPID(mp1) = tcp->tcp_cpid;
5406 
5407 	/*
5408 	 * We need to start the rto timer. In normal case, we start
5409 	 * the timer after sending the packet on the wire (or at
5410 	 * least believing that packet was sent by waiting for
5411 	 * CALL_IP_WPUT() to return). Since this is the first packet
5412 	 * being sent on the wire for the eager, our initial tcp_rto
5413 	 * is at least tcp_rexmit_interval_min which is a fairly
5414 	 * large value to allow the algorithm to adjust slowly to large
5415 	 * fluctuations of RTT during first few transmissions.
5416 	 *
5417 	 * Starting the timer first and then sending the packet in this
5418 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5419 	 * is of the order of several 100ms and starting the timer
5420 	 * first and then sending the packet will result in difference
5421 	 * of few micro seconds.
5422 	 *
5423 	 * Without this optimization, we are forced to hold the fanout
5424 	 * lock across the ipcl_bind_insert() and sending the packet
5425 	 * so that we don't race against an incoming packet (maybe RST)
5426 	 * for this eager.
5427 	 */
5428 
5429 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5430 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5431 
5432 
5433 	/*
5434 	 * Insert the eager in its own perimeter now. We are ready to deal
5435 	 * with any packets on eager.
5436 	 */
5437 	if (eager->tcp_ipversion == IPV4_VERSION) {
5438 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5439 			goto error;
5440 		}
5441 	} else {
5442 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5443 			goto error;
5444 		}
5445 	}
5446 
5447 	/* mark conn as fully-bound */
5448 	econnp->conn_fully_bound = B_TRUE;
5449 
5450 	/* Send the SYN-ACK */
5451 	tcp_send_data(eager, eager->tcp_wq, mp1);
5452 	freemsg(mp);
5453 
5454 	return;
5455 error:
5456 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
5457 	freemsg(mp1);
5458 error1:
5459 	/* Undo what we did above */
5460 	mutex_enter(&tcp->tcp_eager_lock);
5461 	tcp_eager_unlink(eager);
5462 	mutex_exit(&tcp->tcp_eager_lock);
5463 	/* Drop eager's reference on the listener */
5464 	CONN_DEC_REF(connp);
5465 
5466 	/*
5467 	 * Delete the cached ire in conn_ire_cache and also mark
5468 	 * the conn as CONDEMNED
5469 	 */
5470 	mutex_enter(&econnp->conn_lock);
5471 	econnp->conn_state_flags |= CONN_CONDEMNED;
5472 	ire = econnp->conn_ire_cache;
5473 	econnp->conn_ire_cache = NULL;
5474 	mutex_exit(&econnp->conn_lock);
5475 	if (ire != NULL)
5476 		IRE_REFRELE_NOTR(ire);
5477 
5478 	/*
5479 	 * tcp_accept_comm inserts the eager to the bind_hash
5480 	 * we need to remove it from the hash if ipcl_conn_insert
5481 	 * fails.
5482 	 */
5483 	tcp_bind_hash_remove(eager);
5484 	/* Drop the eager ref placed in tcp_open_detached */
5485 	CONN_DEC_REF(econnp);
5486 
5487 	/*
5488 	 * If a connection already exists, send the mp to that connections so
5489 	 * that it can be appropriately dealt with.
5490 	 */
5491 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
5492 		if (!IPCL_IS_CONNECTED(econnp)) {
5493 			/*
5494 			 * Something bad happened. ipcl_conn_insert()
5495 			 * failed because a connection already existed
5496 			 * in connected hash but we can't find it
5497 			 * anymore (someone blew it away). Just
5498 			 * free this message and hopefully remote
5499 			 * will retransmit at which time the SYN can be
5500 			 * treated as a new connection or dealth with
5501 			 * a TH_RST if a connection already exists.
5502 			 */
5503 			freemsg(mp);
5504 		} else {
5505 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
5506 			    econnp, SQTAG_TCP_CONN_REQ);
5507 		}
5508 	} else {
5509 		/* Nobody wants this packet */
5510 		freemsg(mp);
5511 	}
5512 	return;
5513 error2:
5514 	freemsg(mp);
5515 	return;
5516 error3:
5517 	CONN_DEC_REF(econnp);
5518 	freemsg(mp);
5519 }
5520 
5521 /*
5522  * In an ideal case of vertical partition in NUMA architecture, its
5523  * beneficial to have the listener and all the incoming connections
5524  * tied to the same squeue. The other constraint is that incoming
5525  * connections should be tied to the squeue attached to interrupted
5526  * CPU for obvious locality reason so this leaves the listener to
5527  * be tied to the same squeue. Our only problem is that when listener
5528  * is binding, the CPU that will get interrupted by the NIC whose
5529  * IP address the listener is binding to is not even known. So
5530  * the code below allows us to change that binding at the time the
5531  * CPU is interrupted by virtue of incoming connection's squeue.
5532  *
5533  * This is usefull only in case of a listener bound to a specific IP
5534  * address. For other kind of listeners, they get bound the
5535  * very first time and there is no attempt to rebind them.
5536  */
5537 void
5538 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5539 {
5540 	conn_t		*connp = (conn_t *)arg;
5541 	squeue_t	*sqp = (squeue_t *)arg2;
5542 	squeue_t	*new_sqp;
5543 	uint32_t	conn_flags;
5544 
5545 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5546 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5547 	} else {
5548 		goto done;
5549 	}
5550 
5551 	if (connp->conn_fanout == NULL)
5552 		goto done;
5553 
5554 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5555 		mutex_enter(&connp->conn_fanout->connf_lock);
5556 		mutex_enter(&connp->conn_lock);
5557 		/*
5558 		 * No one from read or write side can access us now
5559 		 * except for already queued packets on this squeue.
5560 		 * But since we haven't changed the squeue yet, they
5561 		 * can't execute. If they are processed after we have
5562 		 * changed the squeue, they are sent back to the
5563 		 * correct squeue down below.
5564 		 */
5565 		if (connp->conn_sqp != new_sqp) {
5566 			while (connp->conn_sqp != new_sqp)
5567 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5568 		}
5569 
5570 		do {
5571 			conn_flags = connp->conn_flags;
5572 			conn_flags |= IPCL_FULLY_BOUND;
5573 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5574 			    conn_flags);
5575 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5576 
5577 		mutex_exit(&connp->conn_fanout->connf_lock);
5578 		mutex_exit(&connp->conn_lock);
5579 	}
5580 
5581 done:
5582 	if (connp->conn_sqp != sqp) {
5583 		CONN_INC_REF(connp);
5584 		squeue_fill(connp->conn_sqp, mp,
5585 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
5586 	} else {
5587 		tcp_conn_request(connp, mp, sqp);
5588 	}
5589 }
5590 
5591 /*
5592  * Successful connect request processing begins when our client passes
5593  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5594  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5595  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
5596  *   upstream <- tcp_rput()                <- IP
5597  * After various error checks are completed, tcp_connect() lays
5598  * the target address and port into the composite header template,
5599  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5600  * request followed by an IRE request, and passes the three mblk message
5601  * down to IP looking like this:
5602  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5603  * Processing continues in tcp_rput() when we receive the following message:
5604  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5605  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5606  * to fire off the connection request, and then passes the T_OK_ACK mblk
5607  * upstream that we filled in below.  There are, of course, numerous
5608  * error conditions along the way which truncate the processing described
5609  * above.
5610  */
5611 static void
5612 tcp_connect(tcp_t *tcp, mblk_t *mp)
5613 {
5614 	sin_t		*sin;
5615 	sin6_t		*sin6;
5616 	queue_t		*q = tcp->tcp_wq;
5617 	struct T_conn_req	*tcr;
5618 	ipaddr_t	*dstaddrp;
5619 	in_port_t	dstport;
5620 	uint_t		srcid;
5621 
5622 	tcr = (struct T_conn_req *)mp->b_rptr;
5623 
5624 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5625 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5626 		tcp_err_ack(tcp, mp, TPROTO, 0);
5627 		return;
5628 	}
5629 
5630 	/*
5631 	 * Determine packet type based on type of address passed in
5632 	 * the request should contain an IPv4 or IPv6 address.
5633 	 * Make sure that address family matches the type of
5634 	 * family of the the address passed down
5635 	 */
5636 	switch (tcr->DEST_length) {
5637 	default:
5638 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5639 		return;
5640 
5641 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5642 		/*
5643 		 * XXX: The check for valid DEST_length was not there
5644 		 * in earlier releases and some buggy
5645 		 * TLI apps (e.g Sybase) got away with not feeding
5646 		 * in sin_zero part of address.
5647 		 * We allow that bug to keep those buggy apps humming.
5648 		 * Test suites require the check on DEST_length.
5649 		 * We construct a new mblk with valid DEST_length
5650 		 * free the original so the rest of the code does
5651 		 * not have to keep track of this special shorter
5652 		 * length address case.
5653 		 */
5654 		mblk_t *nmp;
5655 		struct T_conn_req *ntcr;
5656 		sin_t *nsin;
5657 
5658 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5659 		    tcr->OPT_length, BPRI_HI);
5660 		if (nmp == NULL) {
5661 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5662 			return;
5663 		}
5664 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5665 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5666 		ntcr->PRIM_type = T_CONN_REQ;
5667 		ntcr->DEST_length = sizeof (sin_t);
5668 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5669 
5670 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5671 		*nsin = sin_null;
5672 		/* Get pointer to shorter address to copy from original mp */
5673 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5674 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5675 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5676 			freemsg(nmp);
5677 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5678 			return;
5679 		}
5680 		nsin->sin_family = sin->sin_family;
5681 		nsin->sin_port = sin->sin_port;
5682 		nsin->sin_addr = sin->sin_addr;
5683 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5684 		nmp->b_wptr = (uchar_t *)&nsin[1];
5685 		if (tcr->OPT_length != 0) {
5686 			ntcr->OPT_length = tcr->OPT_length;
5687 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5688 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5689 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5690 			    tcr->OPT_length);
5691 			nmp->b_wptr += tcr->OPT_length;
5692 		}
5693 		freemsg(mp);	/* original mp freed */
5694 		mp = nmp;	/* re-initialize original variables */
5695 		tcr = ntcr;
5696 	}
5697 	/* FALLTHRU */
5698 
5699 	case sizeof (sin_t):
5700 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5701 		    sizeof (sin_t));
5702 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5703 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5704 			return;
5705 		}
5706 		if (tcp->tcp_family != AF_INET ||
5707 		    sin->sin_family != AF_INET) {
5708 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5709 			return;
5710 		}
5711 		if (sin->sin_port == 0) {
5712 			tcp_err_ack(tcp, mp, TBADADDR, 0);
5713 			return;
5714 		}
5715 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
5716 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5717 			return;
5718 		}
5719 
5720 		break;
5721 
5722 	case sizeof (sin6_t):
5723 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
5724 		    sizeof (sin6_t));
5725 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
5726 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5727 			return;
5728 		}
5729 		if (tcp->tcp_family != AF_INET6 ||
5730 		    sin6->sin6_family != AF_INET6) {
5731 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5732 			return;
5733 		}
5734 		if (sin6->sin6_port == 0) {
5735 			tcp_err_ack(tcp, mp, TBADADDR, 0);
5736 			return;
5737 		}
5738 		break;
5739 	}
5740 	/*
5741 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5742 	 * should key on their sequence number and cut them loose.
5743 	 */
5744 
5745 	/*
5746 	 * If options passed in, feed it for verification and handling
5747 	 */
5748 	if (tcr->OPT_length != 0) {
5749 		mblk_t	*ok_mp;
5750 		mblk_t	*discon_mp;
5751 		mblk_t  *conn_opts_mp;
5752 		int t_error, sys_error, do_disconnect;
5753 
5754 		conn_opts_mp = NULL;
5755 
5756 		if (tcp_conprim_opt_process(tcp, mp,
5757 			&do_disconnect, &t_error, &sys_error) < 0) {
5758 			if (do_disconnect) {
5759 				ASSERT(t_error == 0 && sys_error == 0);
5760 				discon_mp = mi_tpi_discon_ind(NULL,
5761 				    ECONNREFUSED, 0);
5762 				if (!discon_mp) {
5763 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5764 					    TSYSERR, ENOMEM);
5765 					return;
5766 				}
5767 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5768 				if (!ok_mp) {
5769 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5770 					    TSYSERR, ENOMEM);
5771 					return;
5772 				}
5773 				qreply(q, ok_mp);
5774 				qreply(q, discon_mp); /* no flush! */
5775 			} else {
5776 				ASSERT(t_error != 0);
5777 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5778 				    sys_error);
5779 			}
5780 			return;
5781 		}
5782 		/*
5783 		 * Success in setting options, the mp option buffer represented
5784 		 * by OPT_length/offset has been potentially modified and
5785 		 * contains results of option processing. We copy it in
5786 		 * another mp to save it for potentially influencing returning
5787 		 * it in T_CONN_CONN.
5788 		 */
5789 		if (tcr->OPT_length != 0) { /* there are resulting options */
5790 			conn_opts_mp = copyb(mp);
5791 			if (!conn_opts_mp) {
5792 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5793 				    TSYSERR, ENOMEM);
5794 				return;
5795 			}
5796 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5797 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5798 			/*
5799 			 * Note:
5800 			 * These resulting option negotiation can include any
5801 			 * end-to-end negotiation options but there no such
5802 			 * thing (yet?) in our TCP/IP.
5803 			 */
5804 		}
5805 	}
5806 
5807 	/*
5808 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
5809 	 * make sure that the template IP header in the tcp structure is an
5810 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
5811 	 * need to this before we call tcp_bindi() so that the port lookup
5812 	 * code will look for ports in the correct port space (IPv4 and
5813 	 * IPv6 have separate port spaces).
5814 	 */
5815 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
5816 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
5817 		int err = 0;
5818 
5819 		err = tcp_header_init_ipv4(tcp);
5820 		if (err != 0) {
5821 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
5822 			goto connect_failed;
5823 		}
5824 		if (tcp->tcp_lport != 0)
5825 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
5826 	}
5827 
5828 	switch (tcp->tcp_state) {
5829 	case TCPS_IDLE:
5830 		/*
5831 		 * We support quick connect, refer to comments in
5832 		 * tcp_connect_*()
5833 		 */
5834 		/* FALLTHRU */
5835 	case TCPS_BOUND:
5836 	case TCPS_LISTEN:
5837 		if (tcp->tcp_family == AF_INET6) {
5838 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
5839 				tcp_connect_ipv6(tcp, mp,
5840 				    &sin6->sin6_addr,
5841 				    sin6->sin6_port, sin6->sin6_flowinfo,
5842 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
5843 				return;
5844 			}
5845 			/*
5846 			 * Destination adress is mapped IPv6 address.
5847 			 * Source bound address should be unspecified or
5848 			 * IPv6 mapped address as well.
5849 			 */
5850 			if (!IN6_IS_ADDR_UNSPECIFIED(
5851 			    &tcp->tcp_bound_source_v6) &&
5852 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
5853 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
5854 				    EADDRNOTAVAIL);
5855 				break;
5856 			}
5857 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
5858 			dstport = sin6->sin6_port;
5859 			srcid = sin6->__sin6_src_id;
5860 		} else {
5861 			dstaddrp = &sin->sin_addr.s_addr;
5862 			dstport = sin->sin_port;
5863 			srcid = 0;
5864 		}
5865 
5866 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
5867 		return;
5868 	default:
5869 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
5870 		break;
5871 	}
5872 	/*
5873 	 * Note: Code below is the "failure" case
5874 	 */
5875 	/* return error ack and blow away saved option results if any */
5876 connect_failed:
5877 	if (mp != NULL)
5878 		putnext(tcp->tcp_rq, mp);
5879 	else {
5880 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5881 		    TSYSERR, ENOMEM);
5882 	}
5883 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
5884 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
5885 }
5886 
5887 /*
5888  * Handle connect to IPv4 destinations, including connections for AF_INET6
5889  * sockets connecting to IPv4 mapped IPv6 destinations.
5890  */
5891 static void
5892 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
5893     uint_t srcid)
5894 {
5895 	tcph_t	*tcph;
5896 	mblk_t	*mp1;
5897 	ipaddr_t dstaddr = *dstaddrp;
5898 	int32_t	oldstate;
5899 	uint16_t lport;
5900 
5901 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
5902 
5903 	/* Check for attempt to connect to INADDR_ANY */
5904 	if (dstaddr == INADDR_ANY)  {
5905 		/*
5906 		 * SunOS 4.x and 4.3 BSD allow an application
5907 		 * to connect a TCP socket to INADDR_ANY.
5908 		 * When they do this, the kernel picks the
5909 		 * address of one interface and uses it
5910 		 * instead.  The kernel usually ends up
5911 		 * picking the address of the loopback
5912 		 * interface.  This is an undocumented feature.
5913 		 * However, we provide the same thing here
5914 		 * in order to have source and binary
5915 		 * compatibility with SunOS 4.x.
5916 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
5917 		 * generate the T_CONN_CON.
5918 		 */
5919 		dstaddr = htonl(INADDR_LOOPBACK);
5920 		*dstaddrp = dstaddr;
5921 	}
5922 
5923 	/* Handle __sin6_src_id if socket not bound to an IP address */
5924 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
5925 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
5926 		    tcp->tcp_connp->conn_zoneid);
5927 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
5928 		    tcp->tcp_ipha->ipha_src);
5929 	}
5930 
5931 	/*
5932 	 * Don't let an endpoint connect to itself.  Note that
5933 	 * the test here does not catch the case where the
5934 	 * source IP addr was left unspecified by the user. In
5935 	 * this case, the source addr is set in tcp_adapt_ire()
5936 	 * using the reply to the T_BIND message that we send
5937 	 * down to IP here and the check is repeated in tcp_rput_other.
5938 	 */
5939 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
5940 	    dstport == tcp->tcp_lport) {
5941 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
5942 		goto failed;
5943 	}
5944 
5945 	tcp->tcp_ipha->ipha_dst = dstaddr;
5946 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
5947 
5948 	/*
5949 	 * Massage a source route if any putting the first hop
5950 	 * in iph_dst. Compute a starting value for the checksum which
5951 	 * takes into account that the original iph_dst should be
5952 	 * included in the checksum but that ip will include the
5953 	 * first hop in the source route in the tcp checksum.
5954 	 */
5955 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
5956 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
5957 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
5958 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
5959 	if ((int)tcp->tcp_sum < 0)
5960 		tcp->tcp_sum--;
5961 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
5962 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
5963 	    (tcp->tcp_sum >> 16));
5964 	tcph = tcp->tcp_tcph;
5965 	*(uint16_t *)tcph->th_fport = dstport;
5966 	tcp->tcp_fport = dstport;
5967 
5968 	oldstate = tcp->tcp_state;
5969 	/*
5970 	 * At this point the remote destination address and remote port fields
5971 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5972 	 * have to see which state tcp was in so we can take apropriate action.
5973 	 */
5974 	if (oldstate == TCPS_IDLE) {
5975 		/*
5976 		 * We support a quick connect capability here, allowing
5977 		 * clients to transition directly from IDLE to SYN_SENT
5978 		 * tcp_bindi will pick an unused port, insert the connection
5979 		 * in the bind hash and transition to BOUND state.
5980 		 */
5981 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
5982 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
5983 		    B_FALSE, B_FALSE);
5984 		if (lport == 0) {
5985 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
5986 			goto failed;
5987 		}
5988 	}
5989 	tcp->tcp_state = TCPS_SYN_SENT;
5990 
5991 	/*
5992 	 * TODO: allow data with connect requests
5993 	 * by unlinking M_DATA trailers here and
5994 	 * linking them in behind the T_OK_ACK mblk.
5995 	 * The tcp_rput() bind ack handler would then
5996 	 * feed them to tcp_wput_data() rather than call
5997 	 * tcp_timer().
5998 	 */
5999 	mp = mi_tpi_ok_ack_alloc(mp);
6000 	if (!mp) {
6001 		tcp->tcp_state = oldstate;
6002 		goto failed;
6003 	}
6004 	if (tcp->tcp_family == AF_INET) {
6005 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6006 		    sizeof (ipa_conn_t));
6007 	} else {
6008 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6009 		    sizeof (ipa6_conn_t));
6010 	}
6011 	if (mp1) {
6012 		/* Hang onto the T_OK_ACK for later. */
6013 		linkb(mp1, mp);
6014 		if (tcp->tcp_family == AF_INET)
6015 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6016 		else {
6017 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6018 			    &tcp->tcp_sticky_ipp);
6019 		}
6020 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6021 		tcp->tcp_active_open = 1;
6022 		/*
6023 		 * If the bind cannot complete immediately
6024 		 * IP will arrange to call tcp_rput_other
6025 		 * when the bind completes.
6026 		 */
6027 		if (mp1 != NULL)
6028 			tcp_rput_other(tcp, mp1);
6029 		return;
6030 	}
6031 	/* Error case */
6032 	tcp->tcp_state = oldstate;
6033 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6034 
6035 failed:
6036 	/* return error ack and blow away saved option results if any */
6037 	if (mp != NULL)
6038 		putnext(tcp->tcp_rq, mp);
6039 	else {
6040 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6041 		    TSYSERR, ENOMEM);
6042 	}
6043 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6044 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6045 
6046 }
6047 
6048 /*
6049  * Handle connect to IPv6 destinations.
6050  */
6051 static void
6052 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6053     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6054 {
6055 	tcph_t	*tcph;
6056 	mblk_t	*mp1;
6057 	ip6_rthdr_t *rth;
6058 	int32_t  oldstate;
6059 	uint16_t lport;
6060 
6061 	ASSERT(tcp->tcp_family == AF_INET6);
6062 
6063 	/*
6064 	 * If we're here, it means that the destination address is a native
6065 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6066 	 * reason why it might not be IPv6 is if the socket was bound to an
6067 	 * IPv4-mapped IPv6 address.
6068 	 */
6069 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6070 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6071 		goto failed;
6072 	}
6073 
6074 	/*
6075 	 * Interpret a zero destination to mean loopback.
6076 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6077 	 * generate the T_CONN_CON.
6078 	 */
6079 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6080 		*dstaddrp = ipv6_loopback;
6081 	}
6082 
6083 	/* Handle __sin6_src_id if socket not bound to an IP address */
6084 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6085 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6086 		    tcp->tcp_connp->conn_zoneid);
6087 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6088 	}
6089 
6090 	/*
6091 	 * Take care of the scope_id now and add ip6i_t
6092 	 * if ip6i_t is not already allocated through TCP
6093 	 * sticky options. At this point tcp_ip6h does not
6094 	 * have dst info, thus use dstaddrp.
6095 	 */
6096 	if (scope_id != 0 &&
6097 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6098 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6099 		ip6i_t  *ip6i;
6100 
6101 		ipp->ipp_ifindex = scope_id;
6102 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6103 
6104 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6105 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6106 			/* Already allocated */
6107 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6108 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6109 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6110 		} else {
6111 			int reterr;
6112 
6113 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6114 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6115 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6116 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6117 			if (reterr != 0)
6118 				goto failed;
6119 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6120 		}
6121 	}
6122 
6123 	/*
6124 	 * Don't let an endpoint connect to itself.  Note that
6125 	 * the test here does not catch the case where the
6126 	 * source IP addr was left unspecified by the user. In
6127 	 * this case, the source addr is set in tcp_adapt_ire()
6128 	 * using the reply to the T_BIND message that we send
6129 	 * down to IP here and the check is repeated in tcp_rput_other.
6130 	 */
6131 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6132 	    (dstport == tcp->tcp_lport)) {
6133 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6134 		goto failed;
6135 	}
6136 
6137 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6138 	tcp->tcp_remote_v6 = *dstaddrp;
6139 	tcp->tcp_ip6h->ip6_vcf =
6140 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6141 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6142 
6143 
6144 	/*
6145 	 * Massage a routing header (if present) putting the first hop
6146 	 * in ip6_dst. Compute a starting value for the checksum which
6147 	 * takes into account that the original ip6_dst should be
6148 	 * included in the checksum but that ip will include the
6149 	 * first hop in the source route in the tcp checksum.
6150 	 */
6151 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6152 	if (rth != NULL) {
6153 
6154 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
6155 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6156 		    (tcp->tcp_sum >> 16));
6157 	} else {
6158 		tcp->tcp_sum = 0;
6159 	}
6160 
6161 	tcph = tcp->tcp_tcph;
6162 	*(uint16_t *)tcph->th_fport = dstport;
6163 	tcp->tcp_fport = dstport;
6164 
6165 	oldstate = tcp->tcp_state;
6166 	/*
6167 	 * At this point the remote destination address and remote port fields
6168 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6169 	 * have to see which state tcp was in so we can take apropriate action.
6170 	 */
6171 	if (oldstate == TCPS_IDLE) {
6172 		/*
6173 		 * We support a quick connect capability here, allowing
6174 		 * clients to transition directly from IDLE to SYN_SENT
6175 		 * tcp_bindi will pick an unused port, insert the connection
6176 		 * in the bind hash and transition to BOUND state.
6177 		 */
6178 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
6179 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6180 		    B_FALSE, B_FALSE);
6181 		if (lport == 0) {
6182 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6183 			goto failed;
6184 		}
6185 	}
6186 	tcp->tcp_state = TCPS_SYN_SENT;
6187 	/*
6188 	 * TODO: allow data with connect requests
6189 	 * by unlinking M_DATA trailers here and
6190 	 * linking them in behind the T_OK_ACK mblk.
6191 	 * The tcp_rput() bind ack handler would then
6192 	 * feed them to tcp_wput_data() rather than call
6193 	 * tcp_timer().
6194 	 */
6195 	mp = mi_tpi_ok_ack_alloc(mp);
6196 	if (!mp) {
6197 		tcp->tcp_state = oldstate;
6198 		goto failed;
6199 	}
6200 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6201 	if (mp1) {
6202 		/* Hang onto the T_OK_ACK for later. */
6203 		linkb(mp1, mp);
6204 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6205 		    &tcp->tcp_sticky_ipp);
6206 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6207 		tcp->tcp_active_open = 1;
6208 		/* ip_bind_v6() may return ACK or ERROR */
6209 		if (mp1 != NULL)
6210 			tcp_rput_other(tcp, mp1);
6211 		return;
6212 	}
6213 	/* Error case */
6214 	tcp->tcp_state = oldstate;
6215 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6216 
6217 failed:
6218 	/* return error ack and blow away saved option results if any */
6219 	if (mp != NULL)
6220 		putnext(tcp->tcp_rq, mp);
6221 	else {
6222 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6223 		    TSYSERR, ENOMEM);
6224 	}
6225 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6226 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6227 }
6228 
6229 /*
6230  * We need a stream q for detached closing tcp connections
6231  * to use.  Our client hereby indicates that this q is the
6232  * one to use.
6233  */
6234 static void
6235 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6236 {
6237 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6238 	queue_t	*q = tcp->tcp_wq;
6239 
6240 	mp->b_datap->db_type = M_IOCACK;
6241 	iocp->ioc_count = 0;
6242 	mutex_enter(&tcp_g_q_lock);
6243 	if (tcp_g_q != NULL) {
6244 		mutex_exit(&tcp_g_q_lock);
6245 		iocp->ioc_error = EALREADY;
6246 	} else {
6247 		mblk_t *mp1;
6248 
6249 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6250 		if (mp1 == NULL) {
6251 			mutex_exit(&tcp_g_q_lock);
6252 			iocp->ioc_error = ENOMEM;
6253 		} else {
6254 			tcp_g_q = tcp->tcp_rq;
6255 			mutex_exit(&tcp_g_q_lock);
6256 			iocp->ioc_error = 0;
6257 			iocp->ioc_rval = 0;
6258 			/*
6259 			 * We are passing tcp_sticky_ipp as NULL
6260 			 * as it is not useful for tcp_default queue
6261 			 */
6262 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6263 			if (mp1 != NULL)
6264 				tcp_rput_other(tcp, mp1);
6265 		}
6266 	}
6267 	qreply(q, mp);
6268 }
6269 
6270 /*
6271  * Our client hereby directs us to reject the connection request
6272  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6273  * of sending the appropriate RST, not an ICMP error.
6274  */
6275 static void
6276 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6277 {
6278 	tcp_t	*ltcp = NULL;
6279 	t_scalar_t seqnum;
6280 	conn_t	*connp;
6281 
6282 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6283 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6284 		tcp_err_ack(tcp, mp, TPROTO, 0);
6285 		return;
6286 	}
6287 
6288 	/*
6289 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6290 	 * when the stream is in BOUND state. Do not send a reset,
6291 	 * since the destination IP address is not valid, and it can
6292 	 * be the initialized value of all zeros (broadcast address).
6293 	 *
6294 	 * If TCP has sent down a bind request to IP and has not
6295 	 * received the reply, reject the request.  Otherwise, TCP
6296 	 * will be confused.
6297 	 */
6298 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6299 		if (tcp->tcp_debug) {
6300 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6301 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6302 		}
6303 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6304 		return;
6305 	}
6306 
6307 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6308 
6309 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6310 
6311 		/*
6312 		 * According to TPI, for non-listeners, ignore seqnum
6313 		 * and disconnect.
6314 		 * Following interpretation of -1 seqnum is historical
6315 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6316 		 * a valid seqnum should not be -1).
6317 		 *
6318 		 *	-1 means disconnect everything
6319 		 *	regardless even on a listener.
6320 		 */
6321 
6322 		int old_state = tcp->tcp_state;
6323 
6324 		/*
6325 		 * The connection can't be on the tcp_time_wait_head list
6326 		 * since it is not detached.
6327 		 */
6328 		ASSERT(tcp->tcp_time_wait_next == NULL);
6329 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6330 		ASSERT(tcp->tcp_time_wait_expire == 0);
6331 		ltcp = NULL;
6332 		/*
6333 		 * If it used to be a listener, check to make sure no one else
6334 		 * has taken the port before switching back to LISTEN state.
6335 		 */
6336 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6337 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6338 			    tcp->tcp_ipha->ipha_src,
6339 			    tcp->tcp_connp->conn_zoneid);
6340 			if (connp != NULL)
6341 				ltcp = connp->conn_tcp;
6342 		} else {
6343 			/* Allow tcp_bound_if listeners? */
6344 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6345 			    &tcp->tcp_ip6h->ip6_src, 0,
6346 			    tcp->tcp_connp->conn_zoneid);
6347 			if (connp != NULL)
6348 				ltcp = connp->conn_tcp;
6349 		}
6350 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6351 			tcp->tcp_state = TCPS_LISTEN;
6352 		} else if (old_state > TCPS_BOUND) {
6353 			tcp->tcp_conn_req_max = 0;
6354 			tcp->tcp_state = TCPS_BOUND;
6355 		}
6356 		if (ltcp != NULL)
6357 			CONN_DEC_REF(ltcp->tcp_connp);
6358 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6359 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
6360 		} else if (old_state == TCPS_ESTABLISHED ||
6361 		    old_state == TCPS_CLOSE_WAIT) {
6362 			BUMP_MIB(&tcp_mib, tcpEstabResets);
6363 		}
6364 
6365 		if (tcp->tcp_fused)
6366 			tcp_unfuse(tcp);
6367 
6368 		mutex_enter(&tcp->tcp_eager_lock);
6369 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6370 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6371 			tcp_eager_cleanup(tcp, 0);
6372 		}
6373 		mutex_exit(&tcp->tcp_eager_lock);
6374 
6375 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6376 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6377 
6378 		tcp_reinit(tcp);
6379 
6380 		if (old_state >= TCPS_ESTABLISHED) {
6381 			/* Send M_FLUSH according to TPI */
6382 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6383 		}
6384 		mp = mi_tpi_ok_ack_alloc(mp);
6385 		if (mp)
6386 			putnext(tcp->tcp_rq, mp);
6387 		return;
6388 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6389 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6390 		return;
6391 	}
6392 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6393 		/* Send M_FLUSH according to TPI */
6394 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6395 	}
6396 	mp = mi_tpi_ok_ack_alloc(mp);
6397 	if (mp)
6398 		putnext(tcp->tcp_rq, mp);
6399 }
6400 
6401 /*
6402  * Diagnostic routine used to return a string associated with the tcp state.
6403  * Note that if the caller does not supply a buffer, it will use an internal
6404  * static string.  This means that if multiple threads call this function at
6405  * the same time, output can be corrupted...  Note also that this function
6406  * does not check the size of the supplied buffer.  The caller has to make
6407  * sure that it is big enough.
6408  */
6409 static char *
6410 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6411 {
6412 	char		buf1[30];
6413 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6414 	char		*buf;
6415 	char		*cp;
6416 	in6_addr_t	local, remote;
6417 	char		local_addrbuf[INET6_ADDRSTRLEN];
6418 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6419 
6420 	if (sup_buf != NULL)
6421 		buf = sup_buf;
6422 	else
6423 		buf = priv_buf;
6424 
6425 	if (tcp == NULL)
6426 		return ("NULL_TCP");
6427 	switch (tcp->tcp_state) {
6428 	case TCPS_CLOSED:
6429 		cp = "TCP_CLOSED";
6430 		break;
6431 	case TCPS_IDLE:
6432 		cp = "TCP_IDLE";
6433 		break;
6434 	case TCPS_BOUND:
6435 		cp = "TCP_BOUND";
6436 		break;
6437 	case TCPS_LISTEN:
6438 		cp = "TCP_LISTEN";
6439 		break;
6440 	case TCPS_SYN_SENT:
6441 		cp = "TCP_SYN_SENT";
6442 		break;
6443 	case TCPS_SYN_RCVD:
6444 		cp = "TCP_SYN_RCVD";
6445 		break;
6446 	case TCPS_ESTABLISHED:
6447 		cp = "TCP_ESTABLISHED";
6448 		break;
6449 	case TCPS_CLOSE_WAIT:
6450 		cp = "TCP_CLOSE_WAIT";
6451 		break;
6452 	case TCPS_FIN_WAIT_1:
6453 		cp = "TCP_FIN_WAIT_1";
6454 		break;
6455 	case TCPS_CLOSING:
6456 		cp = "TCP_CLOSING";
6457 		break;
6458 	case TCPS_LAST_ACK:
6459 		cp = "TCP_LAST_ACK";
6460 		break;
6461 	case TCPS_FIN_WAIT_2:
6462 		cp = "TCP_FIN_WAIT_2";
6463 		break;
6464 	case TCPS_TIME_WAIT:
6465 		cp = "TCP_TIME_WAIT";
6466 		break;
6467 	default:
6468 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6469 		cp = buf1;
6470 		break;
6471 	}
6472 	switch (format) {
6473 	case DISP_ADDR_AND_PORT:
6474 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6475 			/*
6476 			 * Note that we use the remote address in the tcp_b
6477 			 * structure.  This means that it will print out
6478 			 * the real destination address, not the next hop's
6479 			 * address if source routing is used.
6480 			 */
6481 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6482 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6483 
6484 		} else {
6485 			local = tcp->tcp_ip_src_v6;
6486 			remote = tcp->tcp_remote_v6;
6487 		}
6488 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6489 		    sizeof (local_addrbuf));
6490 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6491 		    sizeof (remote_addrbuf));
6492 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6493 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6494 		    ntohs(tcp->tcp_fport), cp);
6495 		break;
6496 	case DISP_PORT_ONLY:
6497 	default:
6498 		(void) mi_sprintf(buf, "[%u, %u] %s",
6499 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6500 		break;
6501 	}
6502 
6503 	return (buf);
6504 }
6505 
6506 /*
6507  * Called via squeue to get on to eager's perimeter to send a
6508  * TH_RST. The listener wants the eager to disappear either
6509  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
6510  * being called.
6511  */
6512 /* ARGSUSED */
6513 void
6514 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6515 {
6516 	conn_t	*econnp = (conn_t *)arg;
6517 	tcp_t	*eager = econnp->conn_tcp;
6518 	tcp_t	*listener = eager->tcp_listener;
6519 
6520 	/*
6521 	 * We could be called because listener is closing. Since
6522 	 * the eager is using listener's queue's, its not safe.
6523 	 * Better use the default queue just to send the TH_RST
6524 	 * out.
6525 	 */
6526 	eager->tcp_rq = tcp_g_q;
6527 	eager->tcp_wq = WR(tcp_g_q);
6528 
6529 	if (eager->tcp_state > TCPS_LISTEN) {
6530 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6531 		    eager, eager->tcp_snxt, 0, TH_RST);
6532 	}
6533 
6534 	/* We are here because listener wants this eager gone */
6535 	if (listener != NULL) {
6536 		mutex_enter(&listener->tcp_eager_lock);
6537 		tcp_eager_unlink(eager);
6538 		if (eager->tcp_conn.tcp_eager_conn_ind == NULL) {
6539 			/*
6540 			 * The eager has sent a conn_ind up to the
6541 			 * listener but listener decides to close
6542 			 * instead. We need to drop the extra ref
6543 			 * placed on eager in tcp_rput_data() before
6544 			 * sending the conn_ind to listener.
6545 			 */
6546 			CONN_DEC_REF(econnp);
6547 		}
6548 		mutex_exit(&listener->tcp_eager_lock);
6549 		CONN_DEC_REF(listener->tcp_connp);
6550 	}
6551 
6552 	if (eager->tcp_state > TCPS_BOUND)
6553 		tcp_close_detached(eager);
6554 }
6555 
6556 /*
6557  * Reset any eager connection hanging off this listener marked
6558  * with 'seqnum' and then reclaim it's resources.
6559  */
6560 static boolean_t
6561 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6562 {
6563 	tcp_t	*eager;
6564 	mblk_t 	*mp;
6565 
6566 	TCP_STAT(tcp_eager_blowoff_calls);
6567 	eager = listener;
6568 	mutex_enter(&listener->tcp_eager_lock);
6569 	do {
6570 		eager = eager->tcp_eager_next_q;
6571 		if (eager == NULL) {
6572 			mutex_exit(&listener->tcp_eager_lock);
6573 			return (B_FALSE);
6574 		}
6575 	} while (eager->tcp_conn_req_seqnum != seqnum);
6576 	CONN_INC_REF(eager->tcp_connp);
6577 	mutex_exit(&listener->tcp_eager_lock);
6578 	mp = &eager->tcp_closemp;
6579 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6580 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
6581 	return (B_TRUE);
6582 }
6583 
6584 /*
6585  * Reset any eager connection hanging off this listener
6586  * and then reclaim it's resources.
6587  */
6588 static void
6589 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6590 {
6591 	tcp_t	*eager;
6592 	mblk_t	*mp;
6593 
6594 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6595 
6596 	if (!q0_only) {
6597 		/* First cleanup q */
6598 		TCP_STAT(tcp_eager_blowoff_q);
6599 		eager = listener->tcp_eager_next_q;
6600 		while (eager != NULL) {
6601 			CONN_INC_REF(eager->tcp_connp);
6602 			mp = &eager->tcp_closemp;
6603 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
6604 			    tcp_eager_kill, eager->tcp_connp,
6605 			    SQTAG_TCP_EAGER_CLEANUP);
6606 			eager = eager->tcp_eager_next_q;
6607 		}
6608 	}
6609 	/* Then cleanup q0 */
6610 	TCP_STAT(tcp_eager_blowoff_q0);
6611 	eager = listener->tcp_eager_next_q0;
6612 	while (eager != listener) {
6613 		CONN_INC_REF(eager->tcp_connp);
6614 		mp = &eager->tcp_closemp;
6615 		squeue_fill(eager->tcp_connp->conn_sqp, mp,
6616 		    tcp_eager_kill, eager->tcp_connp,
6617 		    SQTAG_TCP_EAGER_CLEANUP_Q0);
6618 		eager = eager->tcp_eager_next_q0;
6619 	}
6620 }
6621 
6622 /*
6623  * If we are an eager connection hanging off a listener that hasn't
6624  * formally accepted the connection yet, get off his list and blow off
6625  * any data that we have accumulated.
6626  */
6627 static void
6628 tcp_eager_unlink(tcp_t *tcp)
6629 {
6630 	tcp_t	*listener = tcp->tcp_listener;
6631 
6632 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6633 	ASSERT(listener != NULL);
6634 	if (tcp->tcp_eager_next_q0 != NULL) {
6635 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6636 
6637 		/* Remove the eager tcp from q0 */
6638 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6639 		    tcp->tcp_eager_prev_q0;
6640 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6641 		    tcp->tcp_eager_next_q0;
6642 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6643 		listener->tcp_conn_req_cnt_q0--;
6644 
6645 		tcp->tcp_eager_next_q0 = NULL;
6646 		tcp->tcp_eager_prev_q0 = NULL;
6647 
6648 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6649 			/* we have timed out before */
6650 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6651 			listener->tcp_syn_rcvd_timeout--;
6652 		}
6653 	} else {
6654 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6655 		tcp_t	*prev = NULL;
6656 
6657 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6658 			if (tcpp[0] == tcp) {
6659 				if (listener->tcp_eager_last_q == tcp) {
6660 					/*
6661 					 * If we are unlinking the last
6662 					 * element on the list, adjust
6663 					 * tail pointer. Set tail pointer
6664 					 * to nil when list is empty.
6665 					 */
6666 					ASSERT(tcp->tcp_eager_next_q == NULL);
6667 					if (listener->tcp_eager_last_q ==
6668 					    listener->tcp_eager_next_q) {
6669 						listener->tcp_eager_last_q =
6670 						NULL;
6671 					} else {
6672 						/*
6673 						 * We won't get here if there
6674 						 * is only one eager in the
6675 						 * list.
6676 						 */
6677 						ASSERT(prev != NULL);
6678 						listener->tcp_eager_last_q =
6679 						    prev;
6680 					}
6681 				}
6682 				tcpp[0] = tcp->tcp_eager_next_q;
6683 				tcp->tcp_eager_next_q = NULL;
6684 				tcp->tcp_eager_last_q = NULL;
6685 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6686 				listener->tcp_conn_req_cnt_q--;
6687 				break;
6688 			}
6689 			prev = tcpp[0];
6690 		}
6691 	}
6692 	tcp->tcp_listener = NULL;
6693 }
6694 
6695 /* Shorthand to generate and send TPI error acks to our client */
6696 static void
6697 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6698 {
6699 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6700 		putnext(tcp->tcp_rq, mp);
6701 }
6702 
6703 /* Shorthand to generate and send TPI error acks to our client */
6704 static void
6705 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6706     int t_error, int sys_error)
6707 {
6708 	struct T_error_ack	*teackp;
6709 
6710 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6711 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6712 		teackp = (struct T_error_ack *)mp->b_rptr;
6713 		teackp->ERROR_prim = primitive;
6714 		teackp->TLI_error = t_error;
6715 		teackp->UNIX_error = sys_error;
6716 		putnext(tcp->tcp_rq, mp);
6717 	}
6718 }
6719 
6720 /*
6721  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6722  * but instead the code relies on:
6723  * - the fact that the address of the array and its size never changes
6724  * - the atomic assignment of the elements of the array
6725  */
6726 /* ARGSUSED */
6727 static int
6728 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6729 {
6730 	int i;
6731 
6732 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6733 		if (tcp_g_epriv_ports[i] != 0)
6734 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
6735 	}
6736 	return (0);
6737 }
6738 
6739 /*
6740  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6741  * threads from changing it at the same time.
6742  */
6743 /* ARGSUSED */
6744 static int
6745 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6746     cred_t *cr)
6747 {
6748 	long	new_value;
6749 	int	i;
6750 
6751 	/*
6752 	 * Fail the request if the new value does not lie within the
6753 	 * port number limits.
6754 	 */
6755 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6756 	    new_value <= 0 || new_value >= 65536) {
6757 		return (EINVAL);
6758 	}
6759 
6760 	mutex_enter(&tcp_epriv_port_lock);
6761 	/* Check if the value is already in the list */
6762 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6763 		if (new_value == tcp_g_epriv_ports[i]) {
6764 			mutex_exit(&tcp_epriv_port_lock);
6765 			return (EEXIST);
6766 		}
6767 	}
6768 	/* Find an empty slot */
6769 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6770 		if (tcp_g_epriv_ports[i] == 0)
6771 			break;
6772 	}
6773 	if (i == tcp_g_num_epriv_ports) {
6774 		mutex_exit(&tcp_epriv_port_lock);
6775 		return (EOVERFLOW);
6776 	}
6777 	/* Set the new value */
6778 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
6779 	mutex_exit(&tcp_epriv_port_lock);
6780 	return (0);
6781 }
6782 
6783 /*
6784  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6785  * threads from changing it at the same time.
6786  */
6787 /* ARGSUSED */
6788 static int
6789 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6790     cred_t *cr)
6791 {
6792 	long	new_value;
6793 	int	i;
6794 
6795 	/*
6796 	 * Fail the request if the new value does not lie within the
6797 	 * port number limits.
6798 	 */
6799 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
6800 	    new_value >= 65536) {
6801 		return (EINVAL);
6802 	}
6803 
6804 	mutex_enter(&tcp_epriv_port_lock);
6805 	/* Check that the value is already in the list */
6806 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6807 		if (tcp_g_epriv_ports[i] == new_value)
6808 			break;
6809 	}
6810 	if (i == tcp_g_num_epriv_ports) {
6811 		mutex_exit(&tcp_epriv_port_lock);
6812 		return (ESRCH);
6813 	}
6814 	/* Clear the value */
6815 	tcp_g_epriv_ports[i] = 0;
6816 	mutex_exit(&tcp_epriv_port_lock);
6817 	return (0);
6818 }
6819 
6820 /* Return the TPI/TLI equivalent of our current tcp_state */
6821 static int
6822 tcp_tpistate(tcp_t *tcp)
6823 {
6824 	switch (tcp->tcp_state) {
6825 	case TCPS_IDLE:
6826 		return (TS_UNBND);
6827 	case TCPS_LISTEN:
6828 		/*
6829 		 * Return whether there are outstanding T_CONN_IND waiting
6830 		 * for the matching T_CONN_RES. Therefore don't count q0.
6831 		 */
6832 		if (tcp->tcp_conn_req_cnt_q > 0)
6833 			return (TS_WRES_CIND);
6834 		else
6835 			return (TS_IDLE);
6836 	case TCPS_BOUND:
6837 		return (TS_IDLE);
6838 	case TCPS_SYN_SENT:
6839 		return (TS_WCON_CREQ);
6840 	case TCPS_SYN_RCVD:
6841 		/*
6842 		 * Note: assumption: this has to the active open SYN_RCVD.
6843 		 * The passive instance is detached in SYN_RCVD stage of
6844 		 * incoming connection processing so we cannot get request
6845 		 * for T_info_ack on it.
6846 		 */
6847 		return (TS_WACK_CRES);
6848 	case TCPS_ESTABLISHED:
6849 		return (TS_DATA_XFER);
6850 	case TCPS_CLOSE_WAIT:
6851 		return (TS_WREQ_ORDREL);
6852 	case TCPS_FIN_WAIT_1:
6853 		return (TS_WIND_ORDREL);
6854 	case TCPS_FIN_WAIT_2:
6855 		return (TS_WIND_ORDREL);
6856 
6857 	case TCPS_CLOSING:
6858 	case TCPS_LAST_ACK:
6859 	case TCPS_TIME_WAIT:
6860 	case TCPS_CLOSED:
6861 		/*
6862 		 * Following TS_WACK_DREQ7 is a rendition of "not
6863 		 * yet TS_IDLE" TPI state. There is no best match to any
6864 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6865 		 * choose a value chosen that will map to TLI/XTI level
6866 		 * state of TSTATECHNG (state is process of changing) which
6867 		 * captures what this dummy state represents.
6868 		 */
6869 		return (TS_WACK_DREQ7);
6870 	default:
6871 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6872 		    tcp->tcp_state, tcp_display(tcp, NULL,
6873 		    DISP_PORT_ONLY));
6874 		return (TS_UNBND);
6875 	}
6876 }
6877 
6878 static void
6879 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
6880 {
6881 	if (tcp->tcp_family == AF_INET6)
6882 		*tia = tcp_g_t_info_ack_v6;
6883 	else
6884 		*tia = tcp_g_t_info_ack;
6885 	tia->CURRENT_state = tcp_tpistate(tcp);
6886 	tia->OPT_size = tcp_max_optsize;
6887 	if (tcp->tcp_mss == 0) {
6888 		/* Not yet set - tcp_open does not set mss */
6889 		if (tcp->tcp_ipversion == IPV4_VERSION)
6890 			tia->TIDU_size = tcp_mss_def_ipv4;
6891 		else
6892 			tia->TIDU_size = tcp_mss_def_ipv6;
6893 	} else {
6894 		tia->TIDU_size = tcp->tcp_mss;
6895 	}
6896 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
6897 }
6898 
6899 /*
6900  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
6901  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
6902  * tcp_g_t_info_ack.  The current state of the stream is copied from
6903  * tcp_state.
6904  */
6905 static void
6906 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
6907 {
6908 	t_uscalar_t		cap_bits1;
6909 	struct T_capability_ack	*tcap;
6910 
6911 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
6912 		freemsg(mp);
6913 		return;
6914 	}
6915 
6916 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
6917 
6918 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
6919 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
6920 	if (mp == NULL)
6921 		return;
6922 
6923 	tcap = (struct T_capability_ack *)mp->b_rptr;
6924 	tcap->CAP_bits1 = 0;
6925 
6926 	if (cap_bits1 & TC1_INFO) {
6927 		tcp_copy_info(&tcap->INFO_ack, tcp);
6928 		tcap->CAP_bits1 |= TC1_INFO;
6929 	}
6930 
6931 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
6932 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
6933 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
6934 	}
6935 
6936 	putnext(tcp->tcp_rq, mp);
6937 }
6938 
6939 /*
6940  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
6941  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
6942  * The current state of the stream is copied from tcp_state.
6943  */
6944 static void
6945 tcp_info_req(tcp_t *tcp, mblk_t *mp)
6946 {
6947 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
6948 	    T_INFO_ACK);
6949 	if (!mp) {
6950 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6951 		return;
6952 	}
6953 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
6954 	putnext(tcp->tcp_rq, mp);
6955 }
6956 
6957 /* Respond to the TPI addr request */
6958 static void
6959 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
6960 {
6961 	sin_t	*sin;
6962 	mblk_t	*ackmp;
6963 	struct T_addr_ack *taa;
6964 
6965 	/* Make it large enough for worst case */
6966 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
6967 	    2 * sizeof (sin6_t), 1);
6968 	if (ackmp == NULL) {
6969 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6970 		return;
6971 	}
6972 
6973 	if (tcp->tcp_ipversion == IPV6_VERSION) {
6974 		tcp_addr_req_ipv6(tcp, ackmp);
6975 		return;
6976 	}
6977 	taa = (struct T_addr_ack *)ackmp->b_rptr;
6978 
6979 	bzero(taa, sizeof (struct T_addr_ack));
6980 	ackmp->b_wptr = (uchar_t *)&taa[1];
6981 
6982 	taa->PRIM_type = T_ADDR_ACK;
6983 	ackmp->b_datap->db_type = M_PCPROTO;
6984 
6985 	/*
6986 	 * Note: Following code assumes 32 bit alignment of basic
6987 	 * data structures like sin_t and struct T_addr_ack.
6988 	 */
6989 	if (tcp->tcp_state >= TCPS_BOUND) {
6990 		/*
6991 		 * Fill in local address
6992 		 */
6993 		taa->LOCADDR_length = sizeof (sin_t);
6994 		taa->LOCADDR_offset = sizeof (*taa);
6995 
6996 		sin = (sin_t *)&taa[1];
6997 
6998 		/* Fill zeroes and then intialize non-zero fields */
6999 		*sin = sin_null;
7000 
7001 		sin->sin_family = AF_INET;
7002 
7003 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7004 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7005 
7006 		ackmp->b_wptr = (uchar_t *)&sin[1];
7007 
7008 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7009 			/*
7010 			 * Fill in Remote address
7011 			 */
7012 			taa->REMADDR_length = sizeof (sin_t);
7013 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7014 						taa->LOCADDR_length);
7015 
7016 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7017 			*sin = sin_null;
7018 			sin->sin_family = AF_INET;
7019 			sin->sin_addr.s_addr = tcp->tcp_remote;
7020 			sin->sin_port = tcp->tcp_fport;
7021 
7022 			ackmp->b_wptr = (uchar_t *)&sin[1];
7023 		}
7024 	}
7025 	putnext(tcp->tcp_rq, ackmp);
7026 }
7027 
7028 /* Assumes that tcp_addr_req gets enough space and alignment */
7029 static void
7030 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7031 {
7032 	sin6_t	*sin6;
7033 	struct T_addr_ack *taa;
7034 
7035 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7036 	ASSERT(OK_32PTR(ackmp->b_rptr));
7037 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7038 	    2 * sizeof (sin6_t));
7039 
7040 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7041 
7042 	bzero(taa, sizeof (struct T_addr_ack));
7043 	ackmp->b_wptr = (uchar_t *)&taa[1];
7044 
7045 	taa->PRIM_type = T_ADDR_ACK;
7046 	ackmp->b_datap->db_type = M_PCPROTO;
7047 
7048 	/*
7049 	 * Note: Following code assumes 32 bit alignment of basic
7050 	 * data structures like sin6_t and struct T_addr_ack.
7051 	 */
7052 	if (tcp->tcp_state >= TCPS_BOUND) {
7053 		/*
7054 		 * Fill in local address
7055 		 */
7056 		taa->LOCADDR_length = sizeof (sin6_t);
7057 		taa->LOCADDR_offset = sizeof (*taa);
7058 
7059 		sin6 = (sin6_t *)&taa[1];
7060 		*sin6 = sin6_null;
7061 
7062 		sin6->sin6_family = AF_INET6;
7063 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7064 		sin6->sin6_port = tcp->tcp_lport;
7065 
7066 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7067 
7068 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7069 			/*
7070 			 * Fill in Remote address
7071 			 */
7072 			taa->REMADDR_length = sizeof (sin6_t);
7073 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7074 						taa->LOCADDR_length);
7075 
7076 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7077 			*sin6 = sin6_null;
7078 			sin6->sin6_family = AF_INET6;
7079 			sin6->sin6_flowinfo =
7080 			    tcp->tcp_ip6h->ip6_vcf &
7081 			    ~IPV6_VERS_AND_FLOW_MASK;
7082 			sin6->sin6_addr = tcp->tcp_remote_v6;
7083 			sin6->sin6_port = tcp->tcp_fport;
7084 
7085 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7086 		}
7087 	}
7088 	putnext(tcp->tcp_rq, ackmp);
7089 }
7090 
7091 /*
7092  * Handle reinitialization of a tcp structure.
7093  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7094  */
7095 static void
7096 tcp_reinit(tcp_t *tcp)
7097 {
7098 	mblk_t	*mp;
7099 	int 	err;
7100 
7101 	TCP_STAT(tcp_reinit_calls);
7102 
7103 	/* tcp_reinit should never be called for detached tcp_t's */
7104 	ASSERT(tcp->tcp_listener == NULL);
7105 	ASSERT((tcp->tcp_family == AF_INET &&
7106 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7107 	    (tcp->tcp_family == AF_INET6 &&
7108 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7109 	    tcp->tcp_ipversion == IPV6_VERSION)));
7110 
7111 	/* Cancel outstanding timers */
7112 	tcp_timers_stop(tcp);
7113 
7114 	/*
7115 	 * Reset everything in the state vector, after updating global
7116 	 * MIB data from instance counters.
7117 	 */
7118 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
7119 	tcp->tcp_ibsegs = 0;
7120 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
7121 	tcp->tcp_obsegs = 0;
7122 
7123 	tcp_close_mpp(&tcp->tcp_xmit_head);
7124 	if (tcp->tcp_snd_zcopy_aware)
7125 		tcp_zcopy_notify(tcp);
7126 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7127 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7128 	if (tcp->tcp_flow_stopped &&
7129 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7130 		tcp_clrqfull(tcp);
7131 	}
7132 	tcp_close_mpp(&tcp->tcp_reass_head);
7133 	tcp->tcp_reass_tail = NULL;
7134 	if (tcp->tcp_rcv_list != NULL) {
7135 		/* Free b_next chain */
7136 		tcp_close_mpp(&tcp->tcp_rcv_list);
7137 		tcp->tcp_rcv_last_head = NULL;
7138 		tcp->tcp_rcv_last_tail = NULL;
7139 		tcp->tcp_rcv_cnt = 0;
7140 	}
7141 	tcp->tcp_rcv_last_tail = NULL;
7142 
7143 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7144 		freemsg(mp);
7145 		tcp->tcp_urp_mp = NULL;
7146 	}
7147 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7148 		freemsg(mp);
7149 		tcp->tcp_urp_mark_mp = NULL;
7150 	}
7151 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7152 		freeb(tcp->tcp_fused_sigurg_mp);
7153 		tcp->tcp_fused_sigurg_mp = NULL;
7154 	}
7155 
7156 	/*
7157 	 * Following is a union with two members which are
7158 	 * identical types and size so the following cleanup
7159 	 * is enough.
7160 	 */
7161 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7162 
7163 	CL_INET_DISCONNECT(tcp);
7164 
7165 	/*
7166 	 * The connection can't be on the tcp_time_wait_head list
7167 	 * since it is not detached.
7168 	 */
7169 	ASSERT(tcp->tcp_time_wait_next == NULL);
7170 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7171 	ASSERT(tcp->tcp_time_wait_expire == 0);
7172 
7173 	/*
7174 	 * Reset/preserve other values
7175 	 */
7176 	tcp_reinit_values(tcp);
7177 	ipcl_hash_remove(tcp->tcp_connp);
7178 	conn_delete_ire(tcp->tcp_connp, NULL);
7179 
7180 	if (tcp->tcp_conn_req_max != 0) {
7181 		/*
7182 		 * This is the case when a TLI program uses the same
7183 		 * transport end point to accept a connection.  This
7184 		 * makes the TCP both a listener and acceptor.  When
7185 		 * this connection is closed, we need to set the state
7186 		 * back to TCPS_LISTEN.  Make sure that the eager list
7187 		 * is reinitialized.
7188 		 *
7189 		 * Note that this stream is still bound to the four
7190 		 * tuples of the previous connection in IP.  If a new
7191 		 * SYN with different foreign address comes in, IP will
7192 		 * not find it and will send it to the global queue.  In
7193 		 * the global queue, TCP will do a tcp_lookup_listener()
7194 		 * to find this stream.  This works because this stream
7195 		 * is only removed from connected hash.
7196 		 *
7197 		 */
7198 		tcp->tcp_state = TCPS_LISTEN;
7199 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7200 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7201 		if (tcp->tcp_family == AF_INET6) {
7202 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7203 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7204 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7205 		} else {
7206 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7207 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7208 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7209 		}
7210 	} else {
7211 		tcp->tcp_state = TCPS_BOUND;
7212 	}
7213 
7214 	/*
7215 	 * Initialize to default values
7216 	 * Can't fail since enough header template space already allocated
7217 	 * at open().
7218 	 */
7219 	err = tcp_init_values(tcp);
7220 	ASSERT(err == 0);
7221 	/* Restore state in tcp_tcph */
7222 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7223 	if (tcp->tcp_ipversion == IPV4_VERSION)
7224 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7225 	else
7226 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7227 	/*
7228 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7229 	 * since the lookup funcs can only lookup on tcp_t
7230 	 */
7231 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7232 
7233 	ASSERT(tcp->tcp_ptpbhn != NULL);
7234 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
7235 	tcp->tcp_rwnd = tcp_recv_hiwat;
7236 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7237 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
7238 }
7239 
7240 /*
7241  * Force values to zero that need be zero.
7242  * Do not touch values asociated with the BOUND or LISTEN state
7243  * since the connection will end up in that state after the reinit.
7244  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7245  * structure!
7246  */
7247 static void
7248 tcp_reinit_values(tcp)
7249 	tcp_t *tcp;
7250 {
7251 #ifndef	lint
7252 #define	DONTCARE(x)
7253 #define	PRESERVE(x)
7254 #else
7255 #define	DONTCARE(x)	((x) = (x))
7256 #define	PRESERVE(x)	((x) = (x))
7257 #endif	/* lint */
7258 
7259 	PRESERVE(tcp->tcp_bind_hash);
7260 	PRESERVE(tcp->tcp_ptpbhn);
7261 	PRESERVE(tcp->tcp_acceptor_hash);
7262 	PRESERVE(tcp->tcp_ptpahn);
7263 
7264 	/* Should be ASSERT NULL on these with new code! */
7265 	ASSERT(tcp->tcp_time_wait_next == NULL);
7266 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7267 	ASSERT(tcp->tcp_time_wait_expire == 0);
7268 	PRESERVE(tcp->tcp_state);
7269 	PRESERVE(tcp->tcp_rq);
7270 	PRESERVE(tcp->tcp_wq);
7271 
7272 	ASSERT(tcp->tcp_xmit_head == NULL);
7273 	ASSERT(tcp->tcp_xmit_last == NULL);
7274 	ASSERT(tcp->tcp_unsent == 0);
7275 	ASSERT(tcp->tcp_xmit_tail == NULL);
7276 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7277 
7278 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7279 	tcp->tcp_suna = 0;			/* Displayed in mib */
7280 	tcp->tcp_swnd = 0;
7281 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7282 
7283 	ASSERT(tcp->tcp_ibsegs == 0);
7284 	ASSERT(tcp->tcp_obsegs == 0);
7285 
7286 	if (tcp->tcp_iphc != NULL) {
7287 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7288 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7289 	}
7290 
7291 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7292 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7293 	DONTCARE(tcp->tcp_ipha);
7294 	DONTCARE(tcp->tcp_ip6h);
7295 	DONTCARE(tcp->tcp_ip_hdr_len);
7296 	DONTCARE(tcp->tcp_tcph);
7297 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7298 	tcp->tcp_valid_bits = 0;
7299 
7300 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7301 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7302 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7303 	tcp->tcp_last_rcv_lbolt = 0;
7304 
7305 	tcp->tcp_init_cwnd = 0;
7306 
7307 	tcp->tcp_urp_last_valid = 0;
7308 	tcp->tcp_hard_binding = 0;
7309 	tcp->tcp_hard_bound = 0;
7310 	PRESERVE(tcp->tcp_cred);
7311 	PRESERVE(tcp->tcp_cpid);
7312 	PRESERVE(tcp->tcp_exclbind);
7313 
7314 	tcp->tcp_fin_acked = 0;
7315 	tcp->tcp_fin_rcvd = 0;
7316 	tcp->tcp_fin_sent = 0;
7317 	tcp->tcp_ordrel_done = 0;
7318 
7319 	tcp->tcp_debug = 0;
7320 	tcp->tcp_dontroute = 0;
7321 	tcp->tcp_broadcast = 0;
7322 
7323 	tcp->tcp_useloopback = 0;
7324 	tcp->tcp_reuseaddr = 0;
7325 	tcp->tcp_oobinline = 0;
7326 	tcp->tcp_dgram_errind = 0;
7327 
7328 	tcp->tcp_detached = 0;
7329 	tcp->tcp_bind_pending = 0;
7330 	tcp->tcp_unbind_pending = 0;
7331 	tcp->tcp_deferred_clean_death = 0;
7332 
7333 	tcp->tcp_snd_ws_ok = B_FALSE;
7334 	tcp->tcp_snd_ts_ok = B_FALSE;
7335 	tcp->tcp_linger = 0;
7336 	tcp->tcp_ka_enabled = 0;
7337 	tcp->tcp_zero_win_probe = 0;
7338 
7339 	tcp->tcp_loopback = 0;
7340 	tcp->tcp_localnet = 0;
7341 	tcp->tcp_syn_defense = 0;
7342 	tcp->tcp_set_timer = 0;
7343 
7344 	tcp->tcp_active_open = 0;
7345 	ASSERT(tcp->tcp_timeout == B_FALSE);
7346 	tcp->tcp_rexmit = B_FALSE;
7347 	tcp->tcp_xmit_zc_clean = B_FALSE;
7348 
7349 	tcp->tcp_snd_sack_ok = B_FALSE;
7350 	PRESERVE(tcp->tcp_recvdstaddr);
7351 	tcp->tcp_hwcksum = B_FALSE;
7352 
7353 	tcp->tcp_ire_ill_check_done = B_FALSE;
7354 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7355 
7356 	tcp->tcp_mdt = B_FALSE;
7357 	tcp->tcp_mdt_hdr_head = 0;
7358 	tcp->tcp_mdt_hdr_tail = 0;
7359 
7360 	tcp->tcp_conn_def_q0 = 0;
7361 	tcp->tcp_ip_forward_progress = B_FALSE;
7362 	tcp->tcp_anon_priv_bind = 0;
7363 	tcp->tcp_ecn_ok = B_FALSE;
7364 
7365 	tcp->tcp_cwr = B_FALSE;
7366 	tcp->tcp_ecn_echo_on = B_FALSE;
7367 
7368 	if (tcp->tcp_sack_info != NULL) {
7369 		if (tcp->tcp_notsack_list != NULL) {
7370 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7371 		}
7372 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7373 		tcp->tcp_sack_info = NULL;
7374 	}
7375 
7376 	tcp->tcp_rcv_ws = 0;
7377 	tcp->tcp_snd_ws = 0;
7378 	tcp->tcp_ts_recent = 0;
7379 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7380 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7381 	tcp->tcp_if_mtu = 0;
7382 
7383 	ASSERT(tcp->tcp_reass_head == NULL);
7384 	ASSERT(tcp->tcp_reass_tail == NULL);
7385 
7386 	tcp->tcp_cwnd_cnt = 0;
7387 
7388 	ASSERT(tcp->tcp_rcv_list == NULL);
7389 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7390 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7391 	ASSERT(tcp->tcp_rcv_cnt == 0);
7392 
7393 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7394 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7395 	tcp->tcp_csuna = 0;
7396 
7397 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7398 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7399 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7400 	tcp->tcp_rtt_update = 0;
7401 
7402 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7403 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7404 
7405 	tcp->tcp_rack = 0;			/* Displayed in mib */
7406 	tcp->tcp_rack_cnt = 0;
7407 	tcp->tcp_rack_cur_max = 0;
7408 	tcp->tcp_rack_abs_max = 0;
7409 
7410 	tcp->tcp_max_swnd = 0;
7411 
7412 	ASSERT(tcp->tcp_listener == NULL);
7413 
7414 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7415 
7416 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7417 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7418 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7419 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7420 
7421 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7422 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7423 	PRESERVE(tcp->tcp_conn_req_max);
7424 	PRESERVE(tcp->tcp_conn_req_seqnum);
7425 
7426 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7427 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7428 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7429 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7430 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7431 
7432 	tcp->tcp_lingertime = 0;
7433 
7434 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7435 	ASSERT(tcp->tcp_urp_mp == NULL);
7436 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7437 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7438 
7439 	ASSERT(tcp->tcp_eager_next_q == NULL);
7440 	ASSERT(tcp->tcp_eager_last_q == NULL);
7441 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7442 	    tcp->tcp_eager_prev_q0 == NULL) ||
7443 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7444 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7445 
7446 	tcp->tcp_client_errno = 0;
7447 
7448 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7449 
7450 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7451 
7452 	PRESERVE(tcp->tcp_bound_source_v6);
7453 	tcp->tcp_last_sent_len = 0;
7454 	tcp->tcp_dupack_cnt = 0;
7455 
7456 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7457 	PRESERVE(tcp->tcp_lport);
7458 
7459 	PRESERVE(tcp->tcp_acceptor_lockp);
7460 
7461 	ASSERT(tcp->tcp_ordrelid == 0);
7462 	PRESERVE(tcp->tcp_acceptor_id);
7463 	DONTCARE(tcp->tcp_ipsec_overhead);
7464 
7465 	/*
7466 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
7467 	 * in tcp structure and now tracing), Re-initialize all
7468 	 * members of tcp_traceinfo.
7469 	 */
7470 	if (tcp->tcp_tracebuf != NULL) {
7471 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
7472 	}
7473 
7474 	PRESERVE(tcp->tcp_family);
7475 	if (tcp->tcp_family == AF_INET6) {
7476 		tcp->tcp_ipversion = IPV6_VERSION;
7477 		tcp->tcp_mss = tcp_mss_def_ipv6;
7478 	} else {
7479 		tcp->tcp_ipversion = IPV4_VERSION;
7480 		tcp->tcp_mss = tcp_mss_def_ipv4;
7481 	}
7482 
7483 	tcp->tcp_bound_if = 0;
7484 	tcp->tcp_ipv6_recvancillary = 0;
7485 	tcp->tcp_recvifindex = 0;
7486 	tcp->tcp_recvhops = 0;
7487 	tcp->tcp_closed = 0;
7488 	tcp->tcp_cleandeathtag = 0;
7489 	if (tcp->tcp_hopopts != NULL) {
7490 		mi_free(tcp->tcp_hopopts);
7491 		tcp->tcp_hopopts = NULL;
7492 		tcp->tcp_hopoptslen = 0;
7493 	}
7494 	ASSERT(tcp->tcp_hopoptslen == 0);
7495 	if (tcp->tcp_dstopts != NULL) {
7496 		mi_free(tcp->tcp_dstopts);
7497 		tcp->tcp_dstopts = NULL;
7498 		tcp->tcp_dstoptslen = 0;
7499 	}
7500 	ASSERT(tcp->tcp_dstoptslen == 0);
7501 	if (tcp->tcp_rtdstopts != NULL) {
7502 		mi_free(tcp->tcp_rtdstopts);
7503 		tcp->tcp_rtdstopts = NULL;
7504 		tcp->tcp_rtdstoptslen = 0;
7505 	}
7506 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7507 	if (tcp->tcp_rthdr != NULL) {
7508 		mi_free(tcp->tcp_rthdr);
7509 		tcp->tcp_rthdr = NULL;
7510 		tcp->tcp_rthdrlen = 0;
7511 	}
7512 	ASSERT(tcp->tcp_rthdrlen == 0);
7513 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7514 
7515 	/* Reset fusion-related fields */
7516 	tcp->tcp_fused = B_FALSE;
7517 	tcp->tcp_unfusable = B_FALSE;
7518 	tcp->tcp_fused_sigurg = B_FALSE;
7519 	tcp->tcp_direct_sockfs = B_FALSE;
7520 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7521 	tcp->tcp_loopback_peer = NULL;
7522 	tcp->tcp_fuse_rcv_hiwater = 0;
7523 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7524 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7525 
7526 	tcp->tcp_in_ack_unsent = 0;
7527 	tcp->tcp_cork = B_FALSE;
7528 
7529 	PRESERVE(tcp->tcp_squeue_bytes);
7530 
7531 #undef	DONTCARE
7532 #undef	PRESERVE
7533 }
7534 
7535 /*
7536  * Allocate necessary resources and initialize state vector.
7537  * Guaranteed not to fail so that when an error is returned,
7538  * the caller doesn't need to do any additional cleanup.
7539  */
7540 int
7541 tcp_init(tcp_t *tcp, queue_t *q)
7542 {
7543 	int	err;
7544 
7545 	tcp->tcp_rq = q;
7546 	tcp->tcp_wq = WR(q);
7547 	tcp->tcp_state = TCPS_IDLE;
7548 	if ((err = tcp_init_values(tcp)) != 0)
7549 		tcp_timers_stop(tcp);
7550 	return (err);
7551 }
7552 
7553 static int
7554 tcp_init_values(tcp_t *tcp)
7555 {
7556 	int	err;
7557 
7558 	ASSERT((tcp->tcp_family == AF_INET &&
7559 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7560 	    (tcp->tcp_family == AF_INET6 &&
7561 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7562 	    tcp->tcp_ipversion == IPV6_VERSION)));
7563 
7564 	/*
7565 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7566 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7567 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7568 	 * during first few transmissions of a connection as seen in slow
7569 	 * links.
7570 	 */
7571 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
7572 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
7573 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7574 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7575 	    tcp_conn_grace_period;
7576 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
7577 		tcp->tcp_rto = tcp_rexmit_interval_min;
7578 	tcp->tcp_timer_backoff = 0;
7579 	tcp->tcp_ms_we_have_waited = 0;
7580 	tcp->tcp_last_recv_time = lbolt;
7581 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
7582 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7583 
7584 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
7585 
7586 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
7587 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
7588 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
7589 	/*
7590 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7591 	 * passive open.
7592 	 */
7593 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
7594 
7595 	tcp->tcp_naglim = tcp_naglim_def;
7596 
7597 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7598 
7599 	tcp->tcp_mdt_hdr_head = 0;
7600 	tcp->tcp_mdt_hdr_tail = 0;
7601 
7602 	/* Reset fusion-related fields */
7603 	tcp->tcp_fused = B_FALSE;
7604 	tcp->tcp_unfusable = B_FALSE;
7605 	tcp->tcp_fused_sigurg = B_FALSE;
7606 	tcp->tcp_direct_sockfs = B_FALSE;
7607 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7608 	tcp->tcp_loopback_peer = NULL;
7609 	tcp->tcp_fuse_rcv_hiwater = 0;
7610 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7611 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7612 
7613 	/* Initialize the header template */
7614 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7615 		err = tcp_header_init_ipv4(tcp);
7616 	} else {
7617 		err = tcp_header_init_ipv6(tcp);
7618 	}
7619 	if (err)
7620 		return (err);
7621 
7622 	/*
7623 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7624 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7625 	 */
7626 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7627 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
7628 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
7629 
7630 	tcp->tcp_cork = B_FALSE;
7631 	/*
7632 	 * Init the tcp_debug option.  This value determines whether TCP
7633 	 * calls strlog() to print out debug messages.  Doing this
7634 	 * initialization here means that this value is not inherited thru
7635 	 * tcp_reinit().
7636 	 */
7637 	tcp->tcp_debug = tcp_dbg;
7638 
7639 	tcp->tcp_ka_interval = tcp_keepalive_interval;
7640 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
7641 
7642 	return (0);
7643 }
7644 
7645 /*
7646  * Initialize the IPv4 header. Loses any record of any IP options.
7647  */
7648 static int
7649 tcp_header_init_ipv4(tcp_t *tcp)
7650 {
7651 	tcph_t		*tcph;
7652 	uint32_t	sum;
7653 
7654 	/*
7655 	 * This is a simple initialization. If there's
7656 	 * already a template, it should never be too small,
7657 	 * so reuse it.  Otherwise, allocate space for the new one.
7658 	 */
7659 	if (tcp->tcp_iphc == NULL) {
7660 		ASSERT(tcp->tcp_iphc_len == 0);
7661 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7662 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7663 		if (tcp->tcp_iphc == NULL) {
7664 			tcp->tcp_iphc_len = 0;
7665 			return (ENOMEM);
7666 		}
7667 	}
7668 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7669 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
7670 	tcp->tcp_ip6h = NULL;
7671 	tcp->tcp_ipversion = IPV4_VERSION;
7672 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
7673 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
7674 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
7675 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
7676 	tcp->tcp_ipha->ipha_version_and_hdr_length
7677 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
7678 	tcp->tcp_ipha->ipha_ident = 0;
7679 
7680 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
7681 	tcp->tcp_tos = 0;
7682 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
7683 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
7684 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
7685 
7686 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
7687 	tcp->tcp_tcph = tcph;
7688 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
7689 	/*
7690 	 * IP wants our header length in the checksum field to
7691 	 * allow it to perform a single pseudo-header+checksum
7692 	 * calculation on behalf of TCP.
7693 	 * Include the adjustment for a source route once IP_OPTIONS is set.
7694 	 */
7695 	sum = sizeof (tcph_t) + tcp->tcp_sum;
7696 	sum = (sum >> 16) + (sum & 0xFFFF);
7697 	U16_TO_ABE16(sum, tcph->th_sum);
7698 	return (0);
7699 }
7700 
7701 /*
7702  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
7703  */
7704 static int
7705 tcp_header_init_ipv6(tcp_t *tcp)
7706 {
7707 	tcph_t	*tcph;
7708 	uint32_t	sum;
7709 
7710 	/*
7711 	 * This is a simple initialization. If there's
7712 	 * already a template, it should never be too small,
7713 	 * so reuse it. Otherwise, allocate space for the new one.
7714 	 * Ensure that there is enough space to "downgrade" the tcp_t
7715 	 * to an IPv4 tcp_t. This requires having space for a full load
7716 	 * of IPv4 options, as well as a full load of TCP options
7717 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
7718 	 * than a v6 header and a TCP header with a full load of TCP options
7719 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
7720 	 * We want to avoid reallocation in the "downgraded" case when
7721 	 * processing outbound IPv4 options.
7722 	 */
7723 	if (tcp->tcp_iphc == NULL) {
7724 		ASSERT(tcp->tcp_iphc_len == 0);
7725 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7726 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7727 		if (tcp->tcp_iphc == NULL) {
7728 			tcp->tcp_iphc_len = 0;
7729 			return (ENOMEM);
7730 		}
7731 	}
7732 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7733 	tcp->tcp_ipversion = IPV6_VERSION;
7734 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
7735 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
7736 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
7737 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
7738 	tcp->tcp_ipha = NULL;
7739 
7740 	/* Initialize the header template */
7741 
7742 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
7743 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
7744 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
7745 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
7746 
7747 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
7748 	tcp->tcp_tcph = tcph;
7749 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
7750 	/*
7751 	 * IP wants our header length in the checksum field to
7752 	 * allow it to perform a single psuedo-header+checksum
7753 	 * calculation on behalf of TCP.
7754 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
7755 	 */
7756 	sum = sizeof (tcph_t) + tcp->tcp_sum;
7757 	sum = (sum >> 16) + (sum & 0xFFFF);
7758 	U16_TO_ABE16(sum, tcph->th_sum);
7759 	return (0);
7760 }
7761 
7762 /* At minimum we need 4 bytes in the TCP header for the lookup */
7763 #define	ICMP_MIN_TCP_HDR	4
7764 
7765 /*
7766  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
7767  * passed up by IP. The message is always received on the correct tcp_t.
7768  * Assumes that IP has pulled up everything up to and including the ICMP header.
7769  */
7770 void
7771 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
7772 {
7773 	icmph_t *icmph;
7774 	ipha_t	*ipha;
7775 	int	iph_hdr_length;
7776 	tcph_t	*tcph;
7777 	boolean_t ipsec_mctl = B_FALSE;
7778 	boolean_t secure;
7779 	mblk_t *first_mp = mp;
7780 	uint32_t new_mss;
7781 	uint32_t ratio;
7782 	size_t mp_size = MBLKL(mp);
7783 	uint32_t seg_ack;
7784 	uint32_t seg_seq;
7785 
7786 	/* Assume IP provides aligned packets - otherwise toss */
7787 	if (!OK_32PTR(mp->b_rptr)) {
7788 		freemsg(mp);
7789 		return;
7790 	}
7791 
7792 	/*
7793 	 * Since ICMP errors are normal data marked with M_CTL when sent
7794 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
7795 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
7796 	 */
7797 	if ((mp_size == sizeof (ipsec_info_t)) &&
7798 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
7799 		ASSERT(mp->b_cont != NULL);
7800 		mp = mp->b_cont;
7801 		/* IP should have done this */
7802 		ASSERT(OK_32PTR(mp->b_rptr));
7803 		mp_size = MBLKL(mp);
7804 		ipsec_mctl = B_TRUE;
7805 	}
7806 
7807 	/*
7808 	 * Verify that we have a complete outer IP header. If not, drop it.
7809 	 */
7810 	if (mp_size < sizeof (ipha_t)) {
7811 noticmpv4:
7812 		freemsg(first_mp);
7813 		return;
7814 	}
7815 
7816 	ipha = (ipha_t *)mp->b_rptr;
7817 	/*
7818 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
7819 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
7820 	 */
7821 	switch (IPH_HDR_VERSION(ipha)) {
7822 	case IPV6_VERSION:
7823 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
7824 		return;
7825 	case IPV4_VERSION:
7826 		break;
7827 	default:
7828 		goto noticmpv4;
7829 	}
7830 
7831 	/* Skip past the outer IP and ICMP headers */
7832 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7833 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
7834 	/*
7835 	 * If we don't have the correct outer IP header length or if the ULP
7836 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
7837 	 * send it upstream.
7838 	 */
7839 	if (iph_hdr_length < sizeof (ipha_t) ||
7840 	    ipha->ipha_protocol != IPPROTO_ICMP ||
7841 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
7842 		goto noticmpv4;
7843 	}
7844 	ipha = (ipha_t *)&icmph[1];
7845 
7846 	/* Skip past the inner IP and find the ULP header */
7847 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7848 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
7849 	/*
7850 	 * If we don't have the correct inner IP header length or if the ULP
7851 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
7852 	 * bytes of TCP header, drop it.
7853 	 */
7854 	if (iph_hdr_length < sizeof (ipha_t) ||
7855 	    ipha->ipha_protocol != IPPROTO_TCP ||
7856 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
7857 		goto noticmpv4;
7858 	}
7859 
7860 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
7861 		if (ipsec_mctl) {
7862 			secure = ipsec_in_is_secure(first_mp);
7863 		} else {
7864 			secure = B_FALSE;
7865 		}
7866 		if (secure) {
7867 			/*
7868 			 * If we are willing to accept this in clear
7869 			 * we don't have to verify policy.
7870 			 */
7871 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
7872 				if (!tcp_check_policy(tcp, first_mp,
7873 				    ipha, NULL, secure, ipsec_mctl)) {
7874 					/*
7875 					 * tcp_check_policy called
7876 					 * ip_drop_packet() on failure.
7877 					 */
7878 					return;
7879 				}
7880 			}
7881 		}
7882 	} else if (ipsec_mctl) {
7883 		/*
7884 		 * This is a hard_bound connection. IP has already
7885 		 * verified policy. We don't have to do it again.
7886 		 */
7887 		freeb(first_mp);
7888 		first_mp = mp;
7889 		ipsec_mctl = B_FALSE;
7890 	}
7891 
7892 	seg_ack = ABE32_TO_U32(tcph->th_ack);
7893 	seg_seq = ABE32_TO_U32(tcph->th_seq);
7894 	/*
7895 	 * TCP SHOULD check that the TCP sequence number contained in
7896 	 * payload of the ICMP error message is within the range
7897 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
7898 	 */
7899 	if (SEQ_LT(seg_seq, tcp->tcp_suna) ||
7900 		SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
7901 		SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
7902 		/*
7903 		 * If the ICMP message is bogus, should we kill the
7904 		 * connection, or should we just drop the bogus ICMP
7905 		 * message? It would probably make more sense to just
7906 		 * drop the message so that if this one managed to get
7907 		 * in, the real connection should not suffer.
7908 		 */
7909 		goto noticmpv4;
7910 	}
7911 
7912 	switch (icmph->icmph_type) {
7913 	case ICMP_DEST_UNREACHABLE:
7914 		switch (icmph->icmph_code) {
7915 		case ICMP_FRAGMENTATION_NEEDED:
7916 			/*
7917 			 * Reduce the MSS based on the new MTU.  This will
7918 			 * eliminate any fragmentation locally.
7919 			 * N.B.  There may well be some funny side-effects on
7920 			 * the local send policy and the remote receive policy.
7921 			 * Pending further research, we provide
7922 			 * tcp_ignore_path_mtu just in case this proves
7923 			 * disastrous somewhere.
7924 			 *
7925 			 * After updating the MSS, retransmit part of the
7926 			 * dropped segment using the new mss by calling
7927 			 * tcp_wput_data().  Need to adjust all those
7928 			 * params to make sure tcp_wput_data() work properly.
7929 			 */
7930 			if (tcp_ignore_path_mtu)
7931 				break;
7932 
7933 			/*
7934 			 * Decrease the MSS by time stamp options
7935 			 * IP options and IPSEC options. tcp_hdr_len
7936 			 * includes time stamp option and IP option
7937 			 * length.
7938 			 */
7939 
7940 			new_mss = ntohs(icmph->icmph_du_mtu) -
7941 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
7942 
7943 			/*
7944 			 * Only update the MSS if the new one is
7945 			 * smaller than the previous one.  This is
7946 			 * to avoid problems when getting multiple
7947 			 * ICMP errors for the same MTU.
7948 			 */
7949 			if (new_mss >= tcp->tcp_mss)
7950 				break;
7951 
7952 			/*
7953 			 * Stop doing PMTU if new_mss is less than 68
7954 			 * or less than tcp_mss_min.
7955 			 * The value 68 comes from rfc 1191.
7956 			 */
7957 			if (new_mss < MAX(68, tcp_mss_min))
7958 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
7959 				    0;
7960 
7961 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
7962 			ASSERT(ratio >= 1);
7963 			tcp_mss_set(tcp, new_mss);
7964 
7965 			/*
7966 			 * Make sure we have something to
7967 			 * send.
7968 			 */
7969 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
7970 			    (tcp->tcp_xmit_head != NULL)) {
7971 				/*
7972 				 * Shrink tcp_cwnd in
7973 				 * proportion to the old MSS/new MSS.
7974 				 */
7975 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
7976 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
7977 				    (tcp->tcp_unsent == 0)) {
7978 					tcp->tcp_rexmit_max = tcp->tcp_fss;
7979 				} else {
7980 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
7981 				}
7982 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
7983 				tcp->tcp_rexmit = B_TRUE;
7984 				tcp->tcp_dupack_cnt = 0;
7985 				tcp->tcp_snd_burst = TCP_CWND_SS;
7986 				tcp_ss_rexmit(tcp);
7987 			}
7988 			break;
7989 		case ICMP_PORT_UNREACHABLE:
7990 		case ICMP_PROTOCOL_UNREACHABLE:
7991 			switch (tcp->tcp_state) {
7992 			case TCPS_SYN_SENT:
7993 			case TCPS_SYN_RCVD:
7994 				/*
7995 				 * ICMP can snipe away incipient
7996 				 * TCP connections as long as
7997 				 * seq number is same as initial
7998 				 * send seq number.
7999 				 */
8000 				if (seg_seq == tcp->tcp_iss) {
8001 					(void) tcp_clean_death(tcp,
8002 					    ECONNREFUSED, 6);
8003 				}
8004 				break;
8005 			}
8006 			break;
8007 		case ICMP_HOST_UNREACHABLE:
8008 		case ICMP_NET_UNREACHABLE:
8009 			/* Record the error in case we finally time out. */
8010 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8011 				tcp->tcp_client_errno = EHOSTUNREACH;
8012 			else
8013 				tcp->tcp_client_errno = ENETUNREACH;
8014 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8015 				if (tcp->tcp_listener != NULL &&
8016 				    tcp->tcp_listener->tcp_syn_defense) {
8017 					/*
8018 					 * Ditch the half-open connection if we
8019 					 * suspect a SYN attack is under way.
8020 					 */
8021 					tcp_ip_ire_mark_advice(tcp);
8022 					(void) tcp_clean_death(tcp,
8023 					    tcp->tcp_client_errno, 7);
8024 				}
8025 			}
8026 			break;
8027 		default:
8028 			break;
8029 		}
8030 		break;
8031 	case ICMP_SOURCE_QUENCH: {
8032 		/*
8033 		 * use a global boolean to control
8034 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8035 		 * The default is false.
8036 		 */
8037 		if (tcp_icmp_source_quench) {
8038 			/*
8039 			 * Reduce the sending rate as if we got a
8040 			 * retransmit timeout
8041 			 */
8042 			uint32_t npkt;
8043 
8044 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8045 			    tcp->tcp_mss;
8046 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8047 			tcp->tcp_cwnd = tcp->tcp_mss;
8048 			tcp->tcp_cwnd_cnt = 0;
8049 		}
8050 		break;
8051 	}
8052 	}
8053 	freemsg(first_mp);
8054 }
8055 
8056 /*
8057  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8058  * error messages passed up by IP.
8059  * Assumes that IP has pulled up all the extension headers as well
8060  * as the ICMPv6 header.
8061  */
8062 static void
8063 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8064 {
8065 	icmp6_t *icmp6;
8066 	ip6_t	*ip6h;
8067 	uint16_t	iph_hdr_length;
8068 	tcpha_t	*tcpha;
8069 	uint8_t	*nexthdrp;
8070 	uint32_t new_mss;
8071 	uint32_t ratio;
8072 	boolean_t secure;
8073 	mblk_t *first_mp = mp;
8074 	size_t mp_size;
8075 	uint32_t seg_ack;
8076 	uint32_t seg_seq;
8077 
8078 	/*
8079 	 * The caller has determined if this is an IPSEC_IN packet and
8080 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8081 	 */
8082 	if (ipsec_mctl)
8083 		mp = mp->b_cont;
8084 
8085 	mp_size = MBLKL(mp);
8086 
8087 	/*
8088 	 * Verify that we have a complete IP header. If not, send it upstream.
8089 	 */
8090 	if (mp_size < sizeof (ip6_t)) {
8091 noticmpv6:
8092 		freemsg(first_mp);
8093 		return;
8094 	}
8095 
8096 	/*
8097 	 * Verify this is an ICMPV6 packet, else send it upstream.
8098 	 */
8099 	ip6h = (ip6_t *)mp->b_rptr;
8100 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8101 		iph_hdr_length = IPV6_HDR_LEN;
8102 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8103 	    &nexthdrp) ||
8104 	    *nexthdrp != IPPROTO_ICMPV6) {
8105 		goto noticmpv6;
8106 	}
8107 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8108 	ip6h = (ip6_t *)&icmp6[1];
8109 	/*
8110 	 * Verify if we have a complete ICMP and inner IP header.
8111 	 */
8112 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8113 		goto noticmpv6;
8114 
8115 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8116 		goto noticmpv6;
8117 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8118 	/*
8119 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8120 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8121 	 * packet.
8122 	 */
8123 	if ((*nexthdrp != IPPROTO_TCP) ||
8124 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8125 		goto noticmpv6;
8126 	}
8127 
8128 	/*
8129 	 * ICMP errors come on the right queue or come on
8130 	 * listener/global queue for detached connections and
8131 	 * get switched to the right queue. If it comes on the
8132 	 * right queue, policy check has already been done by IP
8133 	 * and thus free the first_mp without verifying the policy.
8134 	 * If it has come for a non-hard bound connection, we need
8135 	 * to verify policy as IP may not have done it.
8136 	 */
8137 	if (!tcp->tcp_hard_bound) {
8138 		if (ipsec_mctl) {
8139 			secure = ipsec_in_is_secure(first_mp);
8140 		} else {
8141 			secure = B_FALSE;
8142 		}
8143 		if (secure) {
8144 			/*
8145 			 * If we are willing to accept this in clear
8146 			 * we don't have to verify policy.
8147 			 */
8148 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8149 				if (!tcp_check_policy(tcp, first_mp,
8150 				    NULL, ip6h, secure, ipsec_mctl)) {
8151 					/*
8152 					 * tcp_check_policy called
8153 					 * ip_drop_packet() on failure.
8154 					 */
8155 					return;
8156 				}
8157 			}
8158 		}
8159 	} else if (ipsec_mctl) {
8160 		/*
8161 		 * This is a hard_bound connection. IP has already
8162 		 * verified policy. We don't have to do it again.
8163 		 */
8164 		freeb(first_mp);
8165 		first_mp = mp;
8166 		ipsec_mctl = B_FALSE;
8167 	}
8168 
8169 	seg_ack = ntohl(tcpha->tha_ack);
8170 	seg_seq = ntohl(tcpha->tha_seq);
8171 	/*
8172 	 * TCP SHOULD check that the TCP sequence number contained in
8173 	 * payload of the ICMP error message is within the range
8174 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8175 	 */
8176 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8177 	    SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8178 		/*
8179 		 * If the ICMP message is bogus, should we kill the
8180 		 * connection, or should we just drop the bogus ICMP
8181 		 * message? It would probably make more sense to just
8182 		 * drop the message so that if this one managed to get
8183 		 * in, the real connection should not suffer.
8184 		 */
8185 		goto noticmpv6;
8186 	}
8187 
8188 	switch (icmp6->icmp6_type) {
8189 	case ICMP6_PACKET_TOO_BIG:
8190 		/*
8191 		 * Reduce the MSS based on the new MTU.  This will
8192 		 * eliminate any fragmentation locally.
8193 		 * N.B.  There may well be some funny side-effects on
8194 		 * the local send policy and the remote receive policy.
8195 		 * Pending further research, we provide
8196 		 * tcp_ignore_path_mtu just in case this proves
8197 		 * disastrous somewhere.
8198 		 *
8199 		 * After updating the MSS, retransmit part of the
8200 		 * dropped segment using the new mss by calling
8201 		 * tcp_wput_data().  Need to adjust all those
8202 		 * params to make sure tcp_wput_data() work properly.
8203 		 */
8204 		if (tcp_ignore_path_mtu)
8205 			break;
8206 
8207 		/*
8208 		 * Decrease the MSS by time stamp options
8209 		 * IP options and IPSEC options. tcp_hdr_len
8210 		 * includes time stamp option and IP option
8211 		 * length.
8212 		 */
8213 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8214 			    tcp->tcp_ipsec_overhead;
8215 
8216 		/*
8217 		 * Only update the MSS if the new one is
8218 		 * smaller than the previous one.  This is
8219 		 * to avoid problems when getting multiple
8220 		 * ICMP errors for the same MTU.
8221 		 */
8222 		if (new_mss >= tcp->tcp_mss)
8223 			break;
8224 
8225 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8226 		ASSERT(ratio >= 1);
8227 		tcp_mss_set(tcp, new_mss);
8228 
8229 		/*
8230 		 * Make sure we have something to
8231 		 * send.
8232 		 */
8233 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8234 		    (tcp->tcp_xmit_head != NULL)) {
8235 			/*
8236 			 * Shrink tcp_cwnd in
8237 			 * proportion to the old MSS/new MSS.
8238 			 */
8239 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8240 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8241 			    (tcp->tcp_unsent == 0)) {
8242 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8243 			} else {
8244 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8245 			}
8246 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8247 			tcp->tcp_rexmit = B_TRUE;
8248 			tcp->tcp_dupack_cnt = 0;
8249 			tcp->tcp_snd_burst = TCP_CWND_SS;
8250 			tcp_ss_rexmit(tcp);
8251 		}
8252 		break;
8253 
8254 	case ICMP6_DST_UNREACH:
8255 		switch (icmp6->icmp6_code) {
8256 		case ICMP6_DST_UNREACH_NOPORT:
8257 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8258 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8259 			    (tcpha->tha_seq == tcp->tcp_iss)) {
8260 				(void) tcp_clean_death(tcp,
8261 				    ECONNREFUSED, 8);
8262 			}
8263 			break;
8264 
8265 		case ICMP6_DST_UNREACH_ADMIN:
8266 		case ICMP6_DST_UNREACH_NOROUTE:
8267 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8268 		case ICMP6_DST_UNREACH_ADDR:
8269 			/* Record the error in case we finally time out. */
8270 			tcp->tcp_client_errno = EHOSTUNREACH;
8271 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8272 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8273 			    (tcpha->tha_seq == tcp->tcp_iss)) {
8274 				if (tcp->tcp_listener != NULL &&
8275 				    tcp->tcp_listener->tcp_syn_defense) {
8276 					/*
8277 					 * Ditch the half-open connection if we
8278 					 * suspect a SYN attack is under way.
8279 					 */
8280 					tcp_ip_ire_mark_advice(tcp);
8281 					(void) tcp_clean_death(tcp,
8282 					    tcp->tcp_client_errno, 9);
8283 				}
8284 			}
8285 
8286 
8287 			break;
8288 		default:
8289 			break;
8290 		}
8291 		break;
8292 
8293 	case ICMP6_PARAM_PROB:
8294 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8295 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8296 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8297 		    (uchar_t *)nexthdrp) {
8298 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8299 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8300 				(void) tcp_clean_death(tcp,
8301 				    ECONNREFUSED, 10);
8302 			}
8303 			break;
8304 		}
8305 		break;
8306 
8307 	case ICMP6_TIME_EXCEEDED:
8308 	default:
8309 		break;
8310 	}
8311 	freemsg(first_mp);
8312 }
8313 
8314 /*
8315  * IP recognizes seven kinds of bind requests:
8316  *
8317  * - A zero-length address binds only to the protocol number.
8318  *
8319  * - A 4-byte address is treated as a request to
8320  * validate that the address is a valid local IPv4
8321  * address, appropriate for an application to bind to.
8322  * IP does the verification, but does not make any note
8323  * of the address at this time.
8324  *
8325  * - A 16-byte address contains is treated as a request
8326  * to validate a local IPv6 address, as the 4-byte
8327  * address case above.
8328  *
8329  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8330  * use it for the inbound fanout of packets.
8331  *
8332  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8333  * use it for the inbound fanout of packets.
8334  *
8335  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8336  * information consisting of local and remote addresses
8337  * and ports.  In this case, the addresses are both
8338  * validated as appropriate for this operation, and, if
8339  * so, the information is retained for use in the
8340  * inbound fanout.
8341  *
8342  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8343  * fanout information, like the 12-byte case above.
8344  *
8345  * IP will also fill in the IRE request mblk with information
8346  * regarding our peer.  In all cases, we notify IP of our protocol
8347  * type by appending a single protocol byte to the bind request.
8348  */
8349 static mblk_t *
8350 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8351 {
8352 	char	*cp;
8353 	mblk_t	*mp;
8354 	struct T_bind_req *tbr;
8355 	ipa_conn_t	*ac;
8356 	ipa6_conn_t	*ac6;
8357 	sin_t		*sin;
8358 	sin6_t		*sin6;
8359 
8360 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
8361 	ASSERT((tcp->tcp_family == AF_INET &&
8362 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8363 	    (tcp->tcp_family == AF_INET6 &&
8364 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8365 	    tcp->tcp_ipversion == IPV6_VERSION)));
8366 
8367 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
8368 	if (!mp)
8369 		return (mp);
8370 	mp->b_datap->db_type = M_PROTO;
8371 	tbr = (struct T_bind_req *)mp->b_rptr;
8372 	tbr->PRIM_type = bind_prim;
8373 	tbr->ADDR_offset = sizeof (*tbr);
8374 	tbr->CONIND_number = 0;
8375 	tbr->ADDR_length = addr_length;
8376 	cp = (char *)&tbr[1];
8377 	switch (addr_length) {
8378 	case sizeof (ipa_conn_t):
8379 		ASSERT(tcp->tcp_family == AF_INET);
8380 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8381 
8382 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8383 		if (mp->b_cont == NULL) {
8384 			freemsg(mp);
8385 			return (NULL);
8386 		}
8387 		mp->b_cont->b_wptr += sizeof (ire_t);
8388 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8389 
8390 		/* cp known to be 32 bit aligned */
8391 		ac = (ipa_conn_t *)cp;
8392 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
8393 		ac->ac_faddr = tcp->tcp_remote;
8394 		ac->ac_fport = tcp->tcp_fport;
8395 		ac->ac_lport = tcp->tcp_lport;
8396 		tcp->tcp_hard_binding = 1;
8397 		break;
8398 
8399 	case sizeof (ipa6_conn_t):
8400 		ASSERT(tcp->tcp_family == AF_INET6);
8401 
8402 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8403 		if (mp->b_cont == NULL) {
8404 			freemsg(mp);
8405 			return (NULL);
8406 		}
8407 		mp->b_cont->b_wptr += sizeof (ire_t);
8408 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8409 
8410 		/* cp known to be 32 bit aligned */
8411 		ac6 = (ipa6_conn_t *)cp;
8412 		if (tcp->tcp_ipversion == IPV4_VERSION) {
8413 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
8414 			    &ac6->ac6_laddr);
8415 		} else {
8416 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
8417 		}
8418 		ac6->ac6_faddr = tcp->tcp_remote_v6;
8419 		ac6->ac6_fport = tcp->tcp_fport;
8420 		ac6->ac6_lport = tcp->tcp_lport;
8421 		tcp->tcp_hard_binding = 1;
8422 		break;
8423 
8424 	case sizeof (sin_t):
8425 		/*
8426 		 * NOTE: IPV6_ADDR_LEN also has same size.
8427 		 * Use family to discriminate.
8428 		 */
8429 		if (tcp->tcp_family == AF_INET) {
8430 			sin = (sin_t *)cp;
8431 
8432 			*sin = sin_null;
8433 			sin->sin_family = AF_INET;
8434 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
8435 			sin->sin_port = tcp->tcp_lport;
8436 			break;
8437 		} else {
8438 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
8439 		}
8440 		break;
8441 
8442 	case sizeof (sin6_t):
8443 		ASSERT(tcp->tcp_family == AF_INET6);
8444 		sin6 = (sin6_t *)cp;
8445 
8446 		*sin6 = sin6_null;
8447 		sin6->sin6_family = AF_INET6;
8448 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
8449 		sin6->sin6_port = tcp->tcp_lport;
8450 		break;
8451 
8452 	case IP_ADDR_LEN:
8453 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8454 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
8455 		break;
8456 
8457 	}
8458 	/* Add protocol number to end */
8459 	cp[addr_length] = (char)IPPROTO_TCP;
8460 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
8461 	return (mp);
8462 }
8463 
8464 /*
8465  * Notify IP that we are having trouble with this connection.  IP should
8466  * blow the IRE away and start over.
8467  */
8468 static void
8469 tcp_ip_notify(tcp_t *tcp)
8470 {
8471 	struct iocblk	*iocp;
8472 	ipid_t	*ipid;
8473 	mblk_t	*mp;
8474 
8475 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8476 	if (tcp->tcp_ipversion == IPV6_VERSION)
8477 		return;
8478 
8479 	mp = mkiocb(IP_IOCTL);
8480 	if (mp == NULL)
8481 		return;
8482 
8483 	iocp = (struct iocblk *)mp->b_rptr;
8484 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8485 
8486 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8487 	if (!mp->b_cont) {
8488 		freeb(mp);
8489 		return;
8490 	}
8491 
8492 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8493 	mp->b_cont->b_wptr += iocp->ioc_count;
8494 	bzero(ipid, sizeof (*ipid));
8495 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8496 	ipid->ipid_ire_type = IRE_CACHE;
8497 	ipid->ipid_addr_offset = sizeof (ipid_t);
8498 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8499 	/*
8500 	 * Note: in the case of source routing we want to blow away the
8501 	 * route to the first source route hop.
8502 	 */
8503 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8504 	    sizeof (tcp->tcp_ipha->ipha_dst));
8505 
8506 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8507 }
8508 
8509 /* Unlink and return any mblk that looks like it contains an ire */
8510 static mblk_t *
8511 tcp_ire_mp(mblk_t *mp)
8512 {
8513 	mblk_t	*prev_mp;
8514 
8515 	for (;;) {
8516 		prev_mp = mp;
8517 		mp = mp->b_cont;
8518 		if (mp == NULL)
8519 			break;
8520 		switch (DB_TYPE(mp)) {
8521 		case IRE_DB_TYPE:
8522 		case IRE_DB_REQ_TYPE:
8523 			if (prev_mp != NULL)
8524 				prev_mp->b_cont = mp->b_cont;
8525 			mp->b_cont = NULL;
8526 			return (mp);
8527 		default:
8528 			break;
8529 		}
8530 	}
8531 	return (mp);
8532 }
8533 
8534 /*
8535  * Timer callback routine for keepalive probe.  We do a fake resend of
8536  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8537  * check to see if we have heard anything from the other end for the last
8538  * RTO period.  If we have, set the timer to expire for another
8539  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8540  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8541  * the timeout if we have not heard from the other side.  If for more than
8542  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8543  * kill the connection unless the keepalive abort threshold is 0.  In
8544  * that case, we will probe "forever."
8545  */
8546 static void
8547 tcp_keepalive_killer(void *arg)
8548 {
8549 	mblk_t	*mp;
8550 	conn_t	*connp = (conn_t *)arg;
8551 	tcp_t  	*tcp = connp->conn_tcp;
8552 	int32_t	firetime;
8553 	int32_t	idletime;
8554 	int32_t	ka_intrvl;
8555 
8556 	tcp->tcp_ka_tid = 0;
8557 
8558 	if (tcp->tcp_fused)
8559 		return;
8560 
8561 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
8562 	ka_intrvl = tcp->tcp_ka_interval;
8563 
8564 	/*
8565 	 * Keepalive probe should only be sent if the application has not
8566 	 * done a close on the connection.
8567 	 */
8568 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8569 		return;
8570 	}
8571 	/* Timer fired too early, restart it. */
8572 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8573 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8574 		    MSEC_TO_TICK(ka_intrvl));
8575 		return;
8576 	}
8577 
8578 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8579 	/*
8580 	 * If we have not heard from the other side for a long
8581 	 * time, kill the connection unless the keepalive abort
8582 	 * threshold is 0.  In that case, we will probe "forever."
8583 	 */
8584 	if (tcp->tcp_ka_abort_thres != 0 &&
8585 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8586 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
8587 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8588 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8589 		return;
8590 	}
8591 
8592 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8593 	    idletime >= ka_intrvl) {
8594 		/* Fake resend of last ACKed byte. */
8595 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8596 
8597 		if (mp1 != NULL) {
8598 			*mp1->b_wptr++ = '\0';
8599 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8600 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8601 			freeb(mp1);
8602 			/*
8603 			 * if allocation failed, fall through to start the
8604 			 * timer back.
8605 			 */
8606 			if (mp != NULL) {
8607 				TCP_RECORD_TRACE(tcp, mp,
8608 				    TCP_TRACE_SEND_PKT);
8609 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8610 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
8611 				if (tcp->tcp_ka_last_intrvl != 0) {
8612 					/*
8613 					 * We should probe again at least
8614 					 * in ka_intrvl, but not more than
8615 					 * tcp_rexmit_interval_max.
8616 					 */
8617 					firetime = MIN(ka_intrvl - 1,
8618 					    tcp->tcp_ka_last_intrvl << 1);
8619 					if (firetime > tcp_rexmit_interval_max)
8620 						firetime =
8621 						    tcp_rexmit_interval_max;
8622 				} else {
8623 					firetime = tcp->tcp_rto;
8624 				}
8625 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8626 				    tcp_keepalive_killer,
8627 				    MSEC_TO_TICK(firetime));
8628 				tcp->tcp_ka_last_intrvl = firetime;
8629 				return;
8630 			}
8631 		}
8632 	} else {
8633 		tcp->tcp_ka_last_intrvl = 0;
8634 	}
8635 
8636 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8637 	if ((firetime = ka_intrvl - idletime) < 0) {
8638 		firetime = ka_intrvl;
8639 	}
8640 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8641 	    MSEC_TO_TICK(firetime));
8642 }
8643 
8644 int
8645 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8646 {
8647 	queue_t	*q = tcp->tcp_rq;
8648 	int32_t	mss = tcp->tcp_mss;
8649 	int	maxpsz;
8650 
8651 	if (TCP_IS_DETACHED(tcp))
8652 		return (mss);
8653 
8654 	if (tcp->tcp_fused) {
8655 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8656 		mss = INFPSZ;
8657 	} else if (tcp->tcp_mdt || tcp->tcp_maxpsz == 0) {
8658 		/*
8659 		 * Set the sd_qn_maxpsz according to the socket send buffer
8660 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8661 		 * instruct the stream head to copyin user data into contiguous
8662 		 * kernel-allocated buffers without breaking it up into smaller
8663 		 * chunks.  We round up the buffer size to the nearest SMSS.
8664 		 */
8665 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8666 		mss = INFPSZ;
8667 	} else {
8668 		/*
8669 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8670 		 * (and a multiple of the mss).  This instructs the stream
8671 		 * head to break down larger than SMSS writes into SMSS-
8672 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8673 		 */
8674 		maxpsz = tcp->tcp_maxpsz * mss;
8675 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8676 			maxpsz = tcp->tcp_xmit_hiwater/2;
8677 			/* Round up to nearest mss */
8678 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8679 		}
8680 	}
8681 	(void) setmaxps(q, maxpsz);
8682 	tcp->tcp_wq->q_maxpsz = maxpsz;
8683 
8684 	if (set_maxblk)
8685 		(void) mi_set_sth_maxblk(q, mss);
8686 
8687 	return (mss);
8688 }
8689 
8690 /*
8691  * Extract option values from a tcp header.  We put any found values into the
8692  * tcpopt struct and return a bitmask saying which options were found.
8693  */
8694 static int
8695 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8696 {
8697 	uchar_t		*endp;
8698 	int		len;
8699 	uint32_t	mss;
8700 	uchar_t		*up = (uchar_t *)tcph;
8701 	int		found = 0;
8702 	int32_t		sack_len;
8703 	tcp_seq		sack_begin, sack_end;
8704 	tcp_t		*tcp;
8705 
8706 	endp = up + TCP_HDR_LENGTH(tcph);
8707 	up += TCP_MIN_HEADER_LENGTH;
8708 	while (up < endp) {
8709 		len = endp - up;
8710 		switch (*up) {
8711 		case TCPOPT_EOL:
8712 			break;
8713 
8714 		case TCPOPT_NOP:
8715 			up++;
8716 			continue;
8717 
8718 		case TCPOPT_MAXSEG:
8719 			if (len < TCPOPT_MAXSEG_LEN ||
8720 			    up[1] != TCPOPT_MAXSEG_LEN)
8721 				break;
8722 
8723 			mss = BE16_TO_U16(up+2);
8724 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8725 			tcpopt->tcp_opt_mss = mss;
8726 			found |= TCP_OPT_MSS_PRESENT;
8727 
8728 			up += TCPOPT_MAXSEG_LEN;
8729 			continue;
8730 
8731 		case TCPOPT_WSCALE:
8732 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8733 				break;
8734 
8735 			if (up[2] > TCP_MAX_WINSHIFT)
8736 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8737 			else
8738 				tcpopt->tcp_opt_wscale = up[2];
8739 			found |= TCP_OPT_WSCALE_PRESENT;
8740 
8741 			up += TCPOPT_WS_LEN;
8742 			continue;
8743 
8744 		case TCPOPT_SACK_PERMITTED:
8745 			if (len < TCPOPT_SACK_OK_LEN ||
8746 			    up[1] != TCPOPT_SACK_OK_LEN)
8747 				break;
8748 			found |= TCP_OPT_SACK_OK_PRESENT;
8749 			up += TCPOPT_SACK_OK_LEN;
8750 			continue;
8751 
8752 		case TCPOPT_SACK:
8753 			if (len <= 2 || up[1] <= 2 || len < up[1])
8754 				break;
8755 
8756 			/* If TCP is not interested in SACK blks... */
8757 			if ((tcp = tcpopt->tcp) == NULL) {
8758 				up += up[1];
8759 				continue;
8760 			}
8761 			sack_len = up[1] - TCPOPT_HEADER_LEN;
8762 			up += TCPOPT_HEADER_LEN;
8763 
8764 			/*
8765 			 * If the list is empty, allocate one and assume
8766 			 * nothing is sack'ed.
8767 			 */
8768 			ASSERT(tcp->tcp_sack_info != NULL);
8769 			if (tcp->tcp_notsack_list == NULL) {
8770 				tcp_notsack_update(&(tcp->tcp_notsack_list),
8771 				    tcp->tcp_suna, tcp->tcp_snxt,
8772 				    &(tcp->tcp_num_notsack_blk),
8773 				    &(tcp->tcp_cnt_notsack_list));
8774 
8775 				/*
8776 				 * Make sure tcp_notsack_list is not NULL.
8777 				 * This happens when kmem_alloc(KM_NOSLEEP)
8778 				 * returns NULL.
8779 				 */
8780 				if (tcp->tcp_notsack_list == NULL) {
8781 					up += sack_len;
8782 					continue;
8783 				}
8784 				tcp->tcp_fack = tcp->tcp_suna;
8785 			}
8786 
8787 			while (sack_len > 0) {
8788 				if (up + 8 > endp) {
8789 					up = endp;
8790 					break;
8791 				}
8792 				sack_begin = BE32_TO_U32(up);
8793 				up += 4;
8794 				sack_end = BE32_TO_U32(up);
8795 				up += 4;
8796 				sack_len -= 8;
8797 				/*
8798 				 * Bounds checking.  Make sure the SACK
8799 				 * info is within tcp_suna and tcp_snxt.
8800 				 * If this SACK blk is out of bound, ignore
8801 				 * it but continue to parse the following
8802 				 * blks.
8803 				 */
8804 				if (SEQ_LEQ(sack_end, sack_begin) ||
8805 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
8806 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
8807 					continue;
8808 				}
8809 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
8810 				    sack_begin, sack_end,
8811 				    &(tcp->tcp_num_notsack_blk),
8812 				    &(tcp->tcp_cnt_notsack_list));
8813 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
8814 					tcp->tcp_fack = sack_end;
8815 				}
8816 			}
8817 			found |= TCP_OPT_SACK_PRESENT;
8818 			continue;
8819 
8820 		case TCPOPT_TSTAMP:
8821 			if (len < TCPOPT_TSTAMP_LEN ||
8822 			    up[1] != TCPOPT_TSTAMP_LEN)
8823 				break;
8824 
8825 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
8826 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
8827 
8828 			found |= TCP_OPT_TSTAMP_PRESENT;
8829 
8830 			up += TCPOPT_TSTAMP_LEN;
8831 			continue;
8832 
8833 		default:
8834 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
8835 				break;
8836 			up += up[1];
8837 			continue;
8838 		}
8839 		break;
8840 	}
8841 	return (found);
8842 }
8843 
8844 /*
8845  * Set the mss associated with a particular tcp based on its current value,
8846  * and a new one passed in. Observe minimums and maximums, and reset
8847  * other state variables that we want to view as multiples of mss.
8848  *
8849  * This function is called in various places mainly because
8850  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
8851  *    other side's SYN/SYN-ACK packet arrives.
8852  * 2) PMTUd may get us a new MSS.
8853  * 3) If the other side stops sending us timestamp option, we need to
8854  *    increase the MSS size to use the extra bytes available.
8855  */
8856 static void
8857 tcp_mss_set(tcp_t *tcp, uint32_t mss)
8858 {
8859 	uint32_t	mss_max;
8860 
8861 	if (tcp->tcp_ipversion == IPV4_VERSION)
8862 		mss_max = tcp_mss_max_ipv4;
8863 	else
8864 		mss_max = tcp_mss_max_ipv6;
8865 
8866 	if (mss < tcp_mss_min)
8867 		mss = tcp_mss_min;
8868 	if (mss > mss_max)
8869 		mss = mss_max;
8870 	/*
8871 	 * Unless naglim has been set by our client to
8872 	 * a non-mss value, force naglim to track mss.
8873 	 * This can help to aggregate small writes.
8874 	 */
8875 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
8876 		tcp->tcp_naglim = mss;
8877 	/*
8878 	 * TCP should be able to buffer at least 4 MSS data for obvious
8879 	 * performance reason.
8880 	 */
8881 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
8882 		tcp->tcp_xmit_hiwater = mss << 2;
8883 
8884 	/*
8885 	 * Check if we need to apply the tcp_init_cwnd here.  If
8886 	 * it is set and the MSS gets bigger (should not happen
8887 	 * normally), we need to adjust the resulting tcp_cwnd properly.
8888 	 * The new tcp_cwnd should not get bigger.
8889 	 */
8890 	if (tcp->tcp_init_cwnd == 0) {
8891 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
8892 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
8893 	} else {
8894 		if (tcp->tcp_mss < mss) {
8895 			tcp->tcp_cwnd = MAX(1,
8896 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
8897 		} else {
8898 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
8899 		}
8900 	}
8901 	tcp->tcp_mss = mss;
8902 	tcp->tcp_cwnd_cnt = 0;
8903 	(void) tcp_maxpsz_set(tcp, B_TRUE);
8904 }
8905 
8906 static int
8907 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8908 {
8909 	tcp_t		*tcp = NULL;
8910 	conn_t		*connp;
8911 	int		err;
8912 	dev_t		conn_dev;
8913 	zoneid_t	zoneid = getzoneid();
8914 
8915 	if (q->q_ptr != NULL)
8916 		return (0);
8917 
8918 	if (sflag == MODOPEN) {
8919 		/*
8920 		 * This is a special case. The purpose of a modopen
8921 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
8922 		 * through for MIB browsers. Everything else is failed.
8923 		 */
8924 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
8925 
8926 		if (connp == NULL)
8927 			return (ENOMEM);
8928 
8929 		connp->conn_flags |= IPCL_TCPMOD;
8930 		connp->conn_cred = credp;
8931 		connp->conn_zoneid = zoneid;
8932 		q->q_ptr = WR(q)->q_ptr = connp;
8933 		crhold(credp);
8934 		q->q_qinfo = &tcp_mod_rinit;
8935 		WR(q)->q_qinfo = &tcp_mod_winit;
8936 		qprocson(q);
8937 		return (0);
8938 	}
8939 
8940 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
8941 		return (EBUSY);
8942 
8943 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
8944 
8945 	if (flag & SO_ACCEPTOR) {
8946 		q->q_qinfo = &tcp_acceptor_rinit;
8947 		q->q_ptr = (void *)conn_dev;
8948 		WR(q)->q_qinfo = &tcp_acceptor_winit;
8949 		WR(q)->q_ptr = (void *)conn_dev;
8950 		qprocson(q);
8951 		return (0);
8952 	}
8953 
8954 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
8955 	if (connp == NULL) {
8956 		inet_minor_free(ip_minor_arena, conn_dev);
8957 		q->q_ptr = NULL;
8958 		return (ENOSR);
8959 	}
8960 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
8961 	tcp = connp->conn_tcp;
8962 
8963 	q->q_ptr = WR(q)->q_ptr = connp;
8964 	if (getmajor(*devp) == TCP6_MAJ) {
8965 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
8966 		connp->conn_send = ip_output_v6;
8967 		connp->conn_af_isv6 = B_TRUE;
8968 		connp->conn_pkt_isv6 = B_TRUE;
8969 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
8970 		tcp->tcp_ipversion = IPV6_VERSION;
8971 		tcp->tcp_family = AF_INET6;
8972 		tcp->tcp_mss = tcp_mss_def_ipv6;
8973 	} else {
8974 		connp->conn_flags |= IPCL_TCP4;
8975 		connp->conn_send = ip_output;
8976 		connp->conn_af_isv6 = B_FALSE;
8977 		connp->conn_pkt_isv6 = B_FALSE;
8978 		tcp->tcp_ipversion = IPV4_VERSION;
8979 		tcp->tcp_family = AF_INET;
8980 		tcp->tcp_mss = tcp_mss_def_ipv4;
8981 	}
8982 
8983 	/*
8984 	 * TCP keeps a copy of cred for cache locality reasons but
8985 	 * we put a reference only once. If connp->conn_cred
8986 	 * becomes invalid, tcp_cred should also be set to NULL.
8987 	 */
8988 	tcp->tcp_cred = connp->conn_cred = credp;
8989 	crhold(connp->conn_cred);
8990 	tcp->tcp_cpid = curproc->p_pid;
8991 	connp->conn_zoneid = zoneid;
8992 
8993 	connp->conn_dev = conn_dev;
8994 
8995 	ASSERT(q->q_qinfo == &tcp_rinit);
8996 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
8997 
8998 	if (flag & SO_SOCKSTR) {
8999 		/*
9000 		 * No need to insert a socket in tcp acceptor hash.
9001 		 * If it was a socket acceptor stream, we dealt with
9002 		 * it above. A socket listener can never accept a
9003 		 * connection and doesn't need acceptor_id.
9004 		 */
9005 		connp->conn_flags |= IPCL_SOCKET;
9006 		tcp->tcp_issocket = 1;
9007 		WR(q)->q_qinfo = &tcp_sock_winit;
9008 	} else {
9009 #ifdef	_ILP32
9010 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9011 #else
9012 		tcp->tcp_acceptor_id = conn_dev;
9013 #endif	/* _ILP32 */
9014 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9015 	}
9016 
9017 	if (tcp_trace)
9018 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9019 
9020 	err = tcp_init(tcp, q);
9021 	if (err != 0) {
9022 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9023 		tcp_acceptor_hash_remove(tcp);
9024 		CONN_DEC_REF(connp);
9025 		q->q_ptr = WR(q)->q_ptr = NULL;
9026 		return (err);
9027 	}
9028 
9029 	RD(q)->q_hiwat = tcp_recv_hiwat;
9030 	tcp->tcp_rwnd = tcp_recv_hiwat;
9031 
9032 	/* Non-zero default values */
9033 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9034 	/*
9035 	 * Put the ref for TCP. Ref for IP was already put
9036 	 * by ipcl_conn_create. Also Make the conn_t globally
9037 	 * visible to walkers
9038 	 */
9039 	mutex_enter(&connp->conn_lock);
9040 	CONN_INC_REF_LOCKED(connp);
9041 	ASSERT(connp->conn_ref == 2);
9042 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9043 	mutex_exit(&connp->conn_lock);
9044 
9045 	qprocson(q);
9046 	return (0);
9047 }
9048 
9049 /*
9050  * Some TCP options can be "set" by requesting them in the option
9051  * buffer. This is needed for XTI feature test though we do not
9052  * allow it in general. We interpret that this mechanism is more
9053  * applicable to OSI protocols and need not be allowed in general.
9054  * This routine filters out options for which it is not allowed (most)
9055  * and lets through those (few) for which it is. [ The XTI interface
9056  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9057  * ever implemented will have to be allowed here ].
9058  */
9059 static boolean_t
9060 tcp_allow_connopt_set(int level, int name)
9061 {
9062 
9063 	switch (level) {
9064 	case IPPROTO_TCP:
9065 		switch (name) {
9066 		case TCP_NODELAY:
9067 			return (B_TRUE);
9068 		default:
9069 			return (B_FALSE);
9070 		}
9071 		/*NOTREACHED*/
9072 	default:
9073 		return (B_FALSE);
9074 	}
9075 	/*NOTREACHED*/
9076 }
9077 
9078 /*
9079  * This routine gets default values of certain options whose default
9080  * values are maintained by protocol specific code
9081  */
9082 /* ARGSUSED */
9083 int
9084 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9085 {
9086 	int32_t	*i1 = (int32_t *)ptr;
9087 
9088 	switch (level) {
9089 	case IPPROTO_TCP:
9090 		switch (name) {
9091 		case TCP_NOTIFY_THRESHOLD:
9092 			*i1 = tcp_ip_notify_interval;
9093 			break;
9094 		case TCP_ABORT_THRESHOLD:
9095 			*i1 = tcp_ip_abort_interval;
9096 			break;
9097 		case TCP_CONN_NOTIFY_THRESHOLD:
9098 			*i1 = tcp_ip_notify_cinterval;
9099 			break;
9100 		case TCP_CONN_ABORT_THRESHOLD:
9101 			*i1 = tcp_ip_abort_cinterval;
9102 			break;
9103 		default:
9104 			return (-1);
9105 		}
9106 		break;
9107 	case IPPROTO_IP:
9108 		switch (name) {
9109 		case IP_TTL:
9110 			*i1 = tcp_ipv4_ttl;
9111 			break;
9112 		default:
9113 			return (-1);
9114 		}
9115 		break;
9116 	case IPPROTO_IPV6:
9117 		switch (name) {
9118 		case IPV6_UNICAST_HOPS:
9119 			*i1 = tcp_ipv6_hoplimit;
9120 			break;
9121 		default:
9122 			return (-1);
9123 		}
9124 		break;
9125 	default:
9126 		return (-1);
9127 	}
9128 	return (sizeof (int));
9129 }
9130 
9131 
9132 /*
9133  * TCP routine to get the values of options.
9134  */
9135 int
9136 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9137 {
9138 	int		*i1 = (int *)ptr;
9139 	conn_t		*connp = Q_TO_CONN(q);
9140 	tcp_t		*tcp = connp->conn_tcp;
9141 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9142 
9143 	switch (level) {
9144 	case SOL_SOCKET:
9145 		switch (name) {
9146 		case SO_LINGER:	{
9147 			struct linger *lgr = (struct linger *)ptr;
9148 
9149 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9150 			lgr->l_linger = tcp->tcp_lingertime;
9151 			}
9152 			return (sizeof (struct linger));
9153 		case SO_DEBUG:
9154 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9155 			break;
9156 		case SO_KEEPALIVE:
9157 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9158 			break;
9159 		case SO_DONTROUTE:
9160 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9161 			break;
9162 		case SO_USELOOPBACK:
9163 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9164 			break;
9165 		case SO_BROADCAST:
9166 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9167 			break;
9168 		case SO_REUSEADDR:
9169 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9170 			break;
9171 		case SO_OOBINLINE:
9172 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9173 			break;
9174 		case SO_DGRAM_ERRIND:
9175 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9176 			break;
9177 		case SO_TYPE:
9178 			*i1 = SOCK_STREAM;
9179 			break;
9180 		case SO_SNDBUF:
9181 			*i1 = tcp->tcp_xmit_hiwater;
9182 			break;
9183 		case SO_RCVBUF:
9184 			*i1 = RD(q)->q_hiwat;
9185 			break;
9186 		case SO_SND_COPYAVOID:
9187 			*i1 = tcp->tcp_snd_zcopy_on ?
9188 			    SO_SND_COPYAVOID : 0;
9189 			break;
9190 		default:
9191 			return (-1);
9192 		}
9193 		break;
9194 	case IPPROTO_TCP:
9195 		switch (name) {
9196 		case TCP_NODELAY:
9197 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9198 			break;
9199 		case TCP_MAXSEG:
9200 			*i1 = tcp->tcp_mss;
9201 			break;
9202 		case TCP_NOTIFY_THRESHOLD:
9203 			*i1 = (int)tcp->tcp_first_timer_threshold;
9204 			break;
9205 		case TCP_ABORT_THRESHOLD:
9206 			*i1 = tcp->tcp_second_timer_threshold;
9207 			break;
9208 		case TCP_CONN_NOTIFY_THRESHOLD:
9209 			*i1 = tcp->tcp_first_ctimer_threshold;
9210 			break;
9211 		case TCP_CONN_ABORT_THRESHOLD:
9212 			*i1 = tcp->tcp_second_ctimer_threshold;
9213 			break;
9214 		case TCP_RECVDSTADDR:
9215 			*i1 = tcp->tcp_recvdstaddr;
9216 			break;
9217 		case TCP_ANONPRIVBIND:
9218 			*i1 = tcp->tcp_anon_priv_bind;
9219 			break;
9220 		case TCP_EXCLBIND:
9221 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9222 			break;
9223 		case TCP_INIT_CWND:
9224 			*i1 = tcp->tcp_init_cwnd;
9225 			break;
9226 		case TCP_KEEPALIVE_THRESHOLD:
9227 			*i1 = tcp->tcp_ka_interval;
9228 			break;
9229 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9230 			*i1 = tcp->tcp_ka_abort_thres;
9231 			break;
9232 		case TCP_CORK:
9233 			*i1 = tcp->tcp_cork;
9234 			break;
9235 		default:
9236 			return (-1);
9237 		}
9238 		break;
9239 	case IPPROTO_IP:
9240 		if (tcp->tcp_family != AF_INET)
9241 			return (-1);
9242 		switch (name) {
9243 		case IP_OPTIONS:
9244 		case T_IP_OPTIONS: {
9245 			/*
9246 			 * This is compatible with BSD in that in only return
9247 			 * the reverse source route with the final destination
9248 			 * as the last entry. The first 4 bytes of the option
9249 			 * will contain the final destination.
9250 			 */
9251 			char	*opt_ptr;
9252 			int	opt_len;
9253 			opt_ptr = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
9254 			opt_len = (char *)tcp->tcp_tcph - opt_ptr;
9255 			/* Caller ensures enough space */
9256 			if (opt_len > 0) {
9257 				/*
9258 				 * TODO: Do we have to handle getsockopt on an
9259 				 * initiator as well?
9260 				 */
9261 				return (tcp_opt_get_user(tcp->tcp_ipha, ptr));
9262 			}
9263 			return (0);
9264 			}
9265 		case IP_TOS:
9266 		case T_IP_TOS:
9267 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9268 			break;
9269 		case IP_TTL:
9270 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9271 			break;
9272 		default:
9273 			return (-1);
9274 		}
9275 		break;
9276 	case IPPROTO_IPV6:
9277 		/*
9278 		 * IPPROTO_IPV6 options are only supported for sockets
9279 		 * that are using IPv6 on the wire.
9280 		 */
9281 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9282 			return (-1);
9283 		}
9284 		switch (name) {
9285 		case IPV6_UNICAST_HOPS:
9286 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9287 			break;	/* goto sizeof (int) option return */
9288 		case IPV6_BOUND_IF:
9289 			/* Zero if not set */
9290 			*i1 = tcp->tcp_bound_if;
9291 			break;	/* goto sizeof (int) option return */
9292 		case IPV6_RECVPKTINFO:
9293 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9294 				*i1 = 1;
9295 			else
9296 				*i1 = 0;
9297 			break;	/* goto sizeof (int) option return */
9298 		case IPV6_RECVTCLASS:
9299 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9300 				*i1 = 1;
9301 			else
9302 				*i1 = 0;
9303 			break;	/* goto sizeof (int) option return */
9304 		case IPV6_RECVHOPLIMIT:
9305 			if (tcp->tcp_ipv6_recvancillary &
9306 			    TCP_IPV6_RECVHOPLIMIT)
9307 				*i1 = 1;
9308 			else
9309 				*i1 = 0;
9310 			break;	/* goto sizeof (int) option return */
9311 		case IPV6_RECVHOPOPTS:
9312 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9313 				*i1 = 1;
9314 			else
9315 				*i1 = 0;
9316 			break;	/* goto sizeof (int) option return */
9317 		case IPV6_RECVDSTOPTS:
9318 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9319 				*i1 = 1;
9320 			else
9321 				*i1 = 0;
9322 			break;	/* goto sizeof (int) option return */
9323 		case _OLD_IPV6_RECVDSTOPTS:
9324 			if (tcp->tcp_ipv6_recvancillary &
9325 			    TCP_OLD_IPV6_RECVDSTOPTS)
9326 				*i1 = 1;
9327 			else
9328 				*i1 = 0;
9329 			break;	/* goto sizeof (int) option return */
9330 		case IPV6_RECVRTHDR:
9331 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9332 				*i1 = 1;
9333 			else
9334 				*i1 = 0;
9335 			break;	/* goto sizeof (int) option return */
9336 		case IPV6_RECVRTHDRDSTOPTS:
9337 			if (tcp->tcp_ipv6_recvancillary &
9338 			    TCP_IPV6_RECVRTDSTOPTS)
9339 				*i1 = 1;
9340 			else
9341 				*i1 = 0;
9342 			break;	/* goto sizeof (int) option return */
9343 		case IPV6_PKTINFO: {
9344 			/* XXX assumes that caller has room for max size! */
9345 			struct in6_pktinfo *pkti;
9346 
9347 			pkti = (struct in6_pktinfo *)ptr;
9348 			if (ipp->ipp_fields & IPPF_IFINDEX)
9349 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9350 			else
9351 				pkti->ipi6_ifindex = 0;
9352 			if (ipp->ipp_fields & IPPF_ADDR)
9353 				pkti->ipi6_addr = ipp->ipp_addr;
9354 			else
9355 				pkti->ipi6_addr = ipv6_all_zeros;
9356 			return (sizeof (struct in6_pktinfo));
9357 		}
9358 		case IPV6_TCLASS:
9359 			if (ipp->ipp_fields & IPPF_TCLASS)
9360 				*i1 = ipp->ipp_tclass;
9361 			else
9362 				*i1 = IPV6_FLOW_TCLASS(
9363 				    IPV6_DEFAULT_VERS_AND_FLOW);
9364 			break;	/* goto sizeof (int) option return */
9365 		case IPV6_NEXTHOP: {
9366 			sin6_t *sin6 = (sin6_t *)ptr;
9367 
9368 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9369 				return (0);
9370 			*sin6 = sin6_null;
9371 			sin6->sin6_family = AF_INET6;
9372 			sin6->sin6_addr = ipp->ipp_nexthop;
9373 			return (sizeof (sin6_t));
9374 		}
9375 		case IPV6_HOPOPTS:
9376 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9377 				return (0);
9378 			bcopy(ipp->ipp_hopopts, ptr, ipp->ipp_hopoptslen);
9379 			return (ipp->ipp_hopoptslen);
9380 		case IPV6_RTHDRDSTOPTS:
9381 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9382 				return (0);
9383 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9384 			return (ipp->ipp_rtdstoptslen);
9385 		case IPV6_RTHDR:
9386 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9387 				return (0);
9388 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9389 			return (ipp->ipp_rthdrlen);
9390 		case IPV6_DSTOPTS:
9391 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9392 				return (0);
9393 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9394 			return (ipp->ipp_dstoptslen);
9395 		case IPV6_SRC_PREFERENCES:
9396 			return (ip6_get_src_preferences(connp,
9397 			    (uint32_t *)ptr));
9398 		case IPV6_PATHMTU: {
9399 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9400 
9401 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9402 				return (-1);
9403 
9404 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9405 				connp->conn_fport, mtuinfo));
9406 		}
9407 		default:
9408 			return (-1);
9409 		}
9410 		break;
9411 	default:
9412 		return (-1);
9413 	}
9414 	return (sizeof (int));
9415 }
9416 
9417 /*
9418  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9419  * Parameters are assumed to be verified by the caller.
9420  */
9421 /* ARGSUSED */
9422 int
9423 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9424     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9425     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9426 {
9427 	tcp_t	*tcp = Q_TO_TCP(q);
9428 	int	*i1 = (int *)invalp;
9429 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9430 	boolean_t checkonly;
9431 	int	reterr;
9432 
9433 	switch (optset_context) {
9434 	case SETFN_OPTCOM_CHECKONLY:
9435 		checkonly = B_TRUE;
9436 		/*
9437 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9438 		 * inlen != 0 implies value supplied and
9439 		 * 	we have to "pretend" to set it.
9440 		 * inlen == 0 implies that there is no
9441 		 * 	value part in T_CHECK request and just validation
9442 		 * done elsewhere should be enough, we just return here.
9443 		 */
9444 		if (inlen == 0) {
9445 			*outlenp = 0;
9446 			return (0);
9447 		}
9448 		break;
9449 	case SETFN_OPTCOM_NEGOTIATE:
9450 		checkonly = B_FALSE;
9451 		break;
9452 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9453 	case SETFN_CONN_NEGOTIATE:
9454 		checkonly = B_FALSE;
9455 		/*
9456 		 * Negotiating local and "association-related" options
9457 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9458 		 * primitives is allowed by XTI, but we choose
9459 		 * to not implement this style negotiation for Internet
9460 		 * protocols (We interpret it is a must for OSI world but
9461 		 * optional for Internet protocols) for all options.
9462 		 * [ Will do only for the few options that enable test
9463 		 * suites that our XTI implementation of this feature
9464 		 * works for transports that do allow it ]
9465 		 */
9466 		if (!tcp_allow_connopt_set(level, name)) {
9467 			*outlenp = 0;
9468 			return (EINVAL);
9469 		}
9470 		break;
9471 	default:
9472 		/*
9473 		 * We should never get here
9474 		 */
9475 		*outlenp = 0;
9476 		return (EINVAL);
9477 	}
9478 
9479 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9480 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9481 
9482 	/*
9483 	 * For TCP, we should have no ancillary data sent down
9484 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9485 	 * has to be zero.
9486 	 */
9487 	ASSERT(thisdg_attrs == NULL);
9488 
9489 	/*
9490 	 * For fixed length options, no sanity check
9491 	 * of passed in length is done. It is assumed *_optcom_req()
9492 	 * routines do the right thing.
9493 	 */
9494 
9495 	switch (level) {
9496 	case SOL_SOCKET:
9497 		switch (name) {
9498 		case SO_LINGER: {
9499 			struct linger *lgr = (struct linger *)invalp;
9500 
9501 			if (!checkonly) {
9502 				if (lgr->l_onoff) {
9503 					tcp->tcp_linger = 1;
9504 					tcp->tcp_lingertime = lgr->l_linger;
9505 				} else {
9506 					tcp->tcp_linger = 0;
9507 					tcp->tcp_lingertime = 0;
9508 				}
9509 				/* struct copy */
9510 				*(struct linger *)outvalp = *lgr;
9511 			} else {
9512 				if (!lgr->l_onoff) {
9513 				    ((struct linger *)outvalp)->l_onoff = 0;
9514 				    ((struct linger *)outvalp)->l_linger = 0;
9515 				} else {
9516 				    /* struct copy */
9517 				    *(struct linger *)outvalp = *lgr;
9518 				}
9519 			}
9520 			*outlenp = sizeof (struct linger);
9521 			return (0);
9522 		}
9523 		case SO_DEBUG:
9524 			if (!checkonly)
9525 				tcp->tcp_debug = onoff;
9526 			break;
9527 		case SO_KEEPALIVE:
9528 			if (checkonly) {
9529 				/* T_CHECK case */
9530 				break;
9531 			}
9532 
9533 			if (!onoff) {
9534 				if (tcp->tcp_ka_enabled) {
9535 					if (tcp->tcp_ka_tid != 0) {
9536 						(void) TCP_TIMER_CANCEL(tcp,
9537 						    tcp->tcp_ka_tid);
9538 						tcp->tcp_ka_tid = 0;
9539 					}
9540 					tcp->tcp_ka_enabled = 0;
9541 				}
9542 				break;
9543 			}
9544 			if (!tcp->tcp_ka_enabled) {
9545 				/* Crank up the keepalive timer */
9546 				tcp->tcp_ka_last_intrvl = 0;
9547 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9548 				    tcp_keepalive_killer,
9549 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
9550 				tcp->tcp_ka_enabled = 1;
9551 			}
9552 			break;
9553 		case SO_DONTROUTE:
9554 			/*
9555 			 * SO_DONTROUTE, SO_USELOOPBACK and SO_BROADCAST are
9556 			 * only of interest to IP.  We track them here only so
9557 			 * that we can report their current value.
9558 			 */
9559 			if (!checkonly) {
9560 				tcp->tcp_dontroute = onoff;
9561 				tcp->tcp_connp->conn_dontroute = onoff;
9562 			}
9563 			break;
9564 		case SO_USELOOPBACK:
9565 			if (!checkonly) {
9566 				tcp->tcp_useloopback = onoff;
9567 				tcp->tcp_connp->conn_loopback = onoff;
9568 			}
9569 			break;
9570 		case SO_BROADCAST:
9571 			if (!checkonly) {
9572 				tcp->tcp_broadcast = onoff;
9573 				tcp->tcp_connp->conn_broadcast = onoff;
9574 			}
9575 			break;
9576 		case SO_REUSEADDR:
9577 			if (!checkonly) {
9578 				tcp->tcp_reuseaddr = onoff;
9579 				tcp->tcp_connp->conn_reuseaddr = onoff;
9580 			}
9581 			break;
9582 		case SO_OOBINLINE:
9583 			if (!checkonly)
9584 				tcp->tcp_oobinline = onoff;
9585 			break;
9586 		case SO_DGRAM_ERRIND:
9587 			if (!checkonly)
9588 				tcp->tcp_dgram_errind = onoff;
9589 			break;
9590 		case SO_SNDBUF: {
9591 			tcp_t *peer_tcp;
9592 
9593 			if (*i1 > tcp_max_buf) {
9594 				*outlenp = 0;
9595 				return (ENOBUFS);
9596 			}
9597 			if (checkonly)
9598 				break;
9599 
9600 			tcp->tcp_xmit_hiwater = *i1;
9601 			if (tcp_snd_lowat_fraction != 0)
9602 				tcp->tcp_xmit_lowater =
9603 				    tcp->tcp_xmit_hiwater /
9604 				    tcp_snd_lowat_fraction;
9605 			(void) tcp_maxpsz_set(tcp, B_TRUE);
9606 			/*
9607 			 * If we are flow-controlled, recheck the condition.
9608 			 * There are apps that increase SO_SNDBUF size when
9609 			 * flow-controlled (EWOULDBLOCK), and expect the flow
9610 			 * control condition to be lifted right away.
9611 			 *
9612 			 * For the fused tcp loopback case, in order to avoid
9613 			 * a race with the peer's tcp_fuse_rrw() we need to
9614 			 * hold its fuse_lock while accessing tcp_flow_stopped.
9615 			 */
9616 			peer_tcp = tcp->tcp_loopback_peer;
9617 			ASSERT(!tcp->tcp_fused || peer_tcp != NULL);
9618 			if (tcp->tcp_fused)
9619 				mutex_enter(&peer_tcp->tcp_fuse_lock);
9620 
9621 			if (tcp->tcp_flow_stopped &&
9622 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
9623 				tcp_clrqfull(tcp);
9624 			}
9625 			if (tcp->tcp_fused)
9626 				mutex_exit(&peer_tcp->tcp_fuse_lock);
9627 			break;
9628 		}
9629 		case SO_RCVBUF:
9630 			if (*i1 > tcp_max_buf) {
9631 				*outlenp = 0;
9632 				return (ENOBUFS);
9633 			}
9634 			/* Silently ignore zero */
9635 			if (!checkonly && *i1 != 0) {
9636 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
9637 				(void) tcp_rwnd_set(tcp, *i1);
9638 			}
9639 			/*
9640 			 * XXX should we return the rwnd here
9641 			 * and tcp_opt_get ?
9642 			 */
9643 			break;
9644 		case SO_SND_COPYAVOID:
9645 			if (!checkonly) {
9646 				/* we only allow enable at most once for now */
9647 				if (tcp->tcp_loopback ||
9648 				    (!tcp->tcp_snd_zcopy_aware &&
9649 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
9650 					*outlenp = 0;
9651 					return (EOPNOTSUPP);
9652 				}
9653 				tcp->tcp_snd_zcopy_aware = 1;
9654 			}
9655 			break;
9656 		default:
9657 			*outlenp = 0;
9658 			return (EINVAL);
9659 		}
9660 		break;
9661 	case IPPROTO_TCP:
9662 		switch (name) {
9663 		case TCP_NODELAY:
9664 			if (!checkonly)
9665 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
9666 			break;
9667 		case TCP_NOTIFY_THRESHOLD:
9668 			if (!checkonly)
9669 				tcp->tcp_first_timer_threshold = *i1;
9670 			break;
9671 		case TCP_ABORT_THRESHOLD:
9672 			if (!checkonly)
9673 				tcp->tcp_second_timer_threshold = *i1;
9674 			break;
9675 		case TCP_CONN_NOTIFY_THRESHOLD:
9676 			if (!checkonly)
9677 				tcp->tcp_first_ctimer_threshold = *i1;
9678 			break;
9679 		case TCP_CONN_ABORT_THRESHOLD:
9680 			if (!checkonly)
9681 				tcp->tcp_second_ctimer_threshold = *i1;
9682 			break;
9683 		case TCP_RECVDSTADDR:
9684 			if (tcp->tcp_state > TCPS_LISTEN)
9685 				return (EOPNOTSUPP);
9686 			if (!checkonly)
9687 				tcp->tcp_recvdstaddr = onoff;
9688 			break;
9689 		case TCP_ANONPRIVBIND:
9690 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
9691 				*outlenp = 0;
9692 				return (reterr);
9693 			}
9694 			if (!checkonly) {
9695 				tcp->tcp_anon_priv_bind = onoff;
9696 			}
9697 			break;
9698 		case TCP_EXCLBIND:
9699 			if (!checkonly)
9700 				tcp->tcp_exclbind = onoff;
9701 			break;	/* goto sizeof (int) option return */
9702 		case TCP_INIT_CWND: {
9703 			uint32_t init_cwnd = *((uint32_t *)invalp);
9704 
9705 			if (checkonly)
9706 				break;
9707 
9708 			/*
9709 			 * Only allow socket with network configuration
9710 			 * privilege to set the initial cwnd to be larger
9711 			 * than allowed by RFC 3390.
9712 			 */
9713 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
9714 				tcp->tcp_init_cwnd = init_cwnd;
9715 				break;
9716 			}
9717 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
9718 				*outlenp = 0;
9719 				return (reterr);
9720 			}
9721 			if (init_cwnd > TCP_MAX_INIT_CWND) {
9722 				*outlenp = 0;
9723 				return (EINVAL);
9724 			}
9725 			tcp->tcp_init_cwnd = init_cwnd;
9726 			break;
9727 		}
9728 		case TCP_KEEPALIVE_THRESHOLD:
9729 			if (checkonly)
9730 				break;
9731 
9732 			if (*i1 < tcp_keepalive_interval_low ||
9733 			    *i1 > tcp_keepalive_interval_high) {
9734 				*outlenp = 0;
9735 				return (EINVAL);
9736 			}
9737 			if (*i1 != tcp->tcp_ka_interval) {
9738 				tcp->tcp_ka_interval = *i1;
9739 				/*
9740 				 * Check if we need to restart the
9741 				 * keepalive timer.
9742 				 */
9743 				if (tcp->tcp_ka_tid != 0) {
9744 					ASSERT(tcp->tcp_ka_enabled);
9745 					(void) TCP_TIMER_CANCEL(tcp,
9746 					    tcp->tcp_ka_tid);
9747 					tcp->tcp_ka_last_intrvl = 0;
9748 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
9749 					    tcp_keepalive_killer,
9750 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
9751 				}
9752 			}
9753 			break;
9754 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9755 			if (!checkonly) {
9756 				if (*i1 < tcp_keepalive_abort_interval_low ||
9757 				    *i1 > tcp_keepalive_abort_interval_high) {
9758 					*outlenp = 0;
9759 					return (EINVAL);
9760 				}
9761 				tcp->tcp_ka_abort_thres = *i1;
9762 			}
9763 			break;
9764 		case TCP_CORK:
9765 			if (!checkonly) {
9766 				/*
9767 				 * if tcp->tcp_cork was set and is now
9768 				 * being unset, we have to make sure that
9769 				 * the remaining data gets sent out. Also
9770 				 * unset tcp->tcp_cork so that tcp_wput_data()
9771 				 * can send data even if it is less than mss
9772 				 */
9773 				if (tcp->tcp_cork && onoff == 0 &&
9774 				    tcp->tcp_unsent > 0) {
9775 					tcp->tcp_cork = B_FALSE;
9776 					tcp_wput_data(tcp, NULL, B_FALSE);
9777 				}
9778 				tcp->tcp_cork = onoff;
9779 			}
9780 			break;
9781 		default:
9782 			*outlenp = 0;
9783 			return (EINVAL);
9784 		}
9785 		break;
9786 	case IPPROTO_IP:
9787 		if (tcp->tcp_family != AF_INET) {
9788 			*outlenp = 0;
9789 			return (ENOPROTOOPT);
9790 		}
9791 		switch (name) {
9792 		case IP_OPTIONS:
9793 		case T_IP_OPTIONS:
9794 			reterr = tcp_opt_set_header(tcp, checkonly,
9795 			    invalp, inlen);
9796 			if (reterr) {
9797 				*outlenp = 0;
9798 				return (reterr);
9799 			}
9800 			/* OK return - copy input buffer into output buffer */
9801 			if (invalp != outvalp) {
9802 				/* don't trust bcopy for identical src/dst */
9803 				bcopy(invalp, outvalp, inlen);
9804 			}
9805 			*outlenp = inlen;
9806 			return (0);
9807 		case IP_TOS:
9808 		case T_IP_TOS:
9809 			if (!checkonly) {
9810 				tcp->tcp_ipha->ipha_type_of_service =
9811 				    (uchar_t)*i1;
9812 				tcp->tcp_tos = (uchar_t)*i1;
9813 			}
9814 			break;
9815 		case IP_TTL:
9816 			if (!checkonly) {
9817 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
9818 				tcp->tcp_ttl = (uchar_t)*i1;
9819 			}
9820 			break;
9821 		case IP_BOUND_IF:
9822 			/* Handled at the IP level */
9823 			return (-EINVAL);
9824 		case IP_SEC_OPT:
9825 			/*
9826 			 * We should not allow policy setting after
9827 			 * we start listening for connections.
9828 			 */
9829 			if (tcp->tcp_state == TCPS_LISTEN) {
9830 				return (EINVAL);
9831 			} else {
9832 				/* Handled at the IP level */
9833 				return (-EINVAL);
9834 			}
9835 		default:
9836 			*outlenp = 0;
9837 			return (EINVAL);
9838 		}
9839 		break;
9840 	case IPPROTO_IPV6: {
9841 		ip6_pkt_t		*ipp;
9842 
9843 		/*
9844 		 * IPPROTO_IPV6 options are only supported for sockets
9845 		 * that are using IPv6 on the wire.
9846 		 */
9847 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9848 			*outlenp = 0;
9849 			return (ENOPROTOOPT);
9850 		}
9851 		/*
9852 		 * Only sticky options; no ancillary data
9853 		 */
9854 		ASSERT(thisdg_attrs == NULL);
9855 		ipp = &tcp->tcp_sticky_ipp;
9856 
9857 		switch (name) {
9858 		case IPV6_UNICAST_HOPS:
9859 			/* -1 means use default */
9860 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
9861 				*outlenp = 0;
9862 				return (EINVAL);
9863 			}
9864 			if (!checkonly) {
9865 				if (*i1 == -1) {
9866 					tcp->tcp_ip6h->ip6_hops =
9867 					    ipp->ipp_unicast_hops =
9868 					    (uint8_t)tcp_ipv6_hoplimit;
9869 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
9870 					/* Pass modified value to IP. */
9871 					*i1 = tcp->tcp_ip6h->ip6_hops;
9872 				} else {
9873 					tcp->tcp_ip6h->ip6_hops =
9874 					    ipp->ipp_unicast_hops =
9875 					    (uint8_t)*i1;
9876 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
9877 				}
9878 				reterr = tcp_build_hdrs(q, tcp);
9879 				if (reterr != 0)
9880 					return (reterr);
9881 			}
9882 			break;
9883 		case IPV6_BOUND_IF:
9884 			if (!checkonly) {
9885 				int error = 0;
9886 
9887 				tcp->tcp_bound_if = *i1;
9888 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
9889 				    B_TRUE, checkonly, level, name, mblk);
9890 				if (error != 0) {
9891 					*outlenp = 0;
9892 					return (error);
9893 				}
9894 			}
9895 			break;
9896 		/*
9897 		 * Set boolean switches for ancillary data delivery
9898 		 */
9899 		case IPV6_RECVPKTINFO:
9900 			if (!checkonly) {
9901 				if (onoff)
9902 					tcp->tcp_ipv6_recvancillary |=
9903 					    TCP_IPV6_RECVPKTINFO;
9904 				else
9905 					tcp->tcp_ipv6_recvancillary &=
9906 					    ~TCP_IPV6_RECVPKTINFO;
9907 				/* Force it to be sent up with the next msg */
9908 				tcp->tcp_recvifindex = 0;
9909 			}
9910 			break;
9911 		case IPV6_RECVTCLASS:
9912 			if (!checkonly) {
9913 				if (onoff)
9914 					tcp->tcp_ipv6_recvancillary |=
9915 					    TCP_IPV6_RECVTCLASS;
9916 				else
9917 					tcp->tcp_ipv6_recvancillary &=
9918 					    ~TCP_IPV6_RECVTCLASS;
9919 			}
9920 			break;
9921 		case IPV6_RECVHOPLIMIT:
9922 			if (!checkonly) {
9923 				if (onoff)
9924 					tcp->tcp_ipv6_recvancillary |=
9925 					    TCP_IPV6_RECVHOPLIMIT;
9926 				else
9927 					tcp->tcp_ipv6_recvancillary &=
9928 					    ~TCP_IPV6_RECVHOPLIMIT;
9929 				/* Force it to be sent up with the next msg */
9930 				tcp->tcp_recvhops = 0xffffffffU;
9931 			}
9932 			break;
9933 		case IPV6_RECVHOPOPTS:
9934 			if (!checkonly) {
9935 				if (onoff)
9936 					tcp->tcp_ipv6_recvancillary |=
9937 					    TCP_IPV6_RECVHOPOPTS;
9938 				else
9939 					tcp->tcp_ipv6_recvancillary &=
9940 					    ~TCP_IPV6_RECVHOPOPTS;
9941 			}
9942 			break;
9943 		case IPV6_RECVDSTOPTS:
9944 			if (!checkonly) {
9945 				if (onoff)
9946 					tcp->tcp_ipv6_recvancillary |=
9947 					    TCP_IPV6_RECVDSTOPTS;
9948 				else
9949 					tcp->tcp_ipv6_recvancillary &=
9950 					    ~TCP_IPV6_RECVDSTOPTS;
9951 			}
9952 			break;
9953 		case _OLD_IPV6_RECVDSTOPTS:
9954 			if (!checkonly) {
9955 				if (onoff)
9956 					tcp->tcp_ipv6_recvancillary |=
9957 					    TCP_OLD_IPV6_RECVDSTOPTS;
9958 				else
9959 					tcp->tcp_ipv6_recvancillary &=
9960 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
9961 			}
9962 			break;
9963 		case IPV6_RECVRTHDR:
9964 			if (!checkonly) {
9965 				if (onoff)
9966 					tcp->tcp_ipv6_recvancillary |=
9967 					    TCP_IPV6_RECVRTHDR;
9968 				else
9969 					tcp->tcp_ipv6_recvancillary &=
9970 					    ~TCP_IPV6_RECVRTHDR;
9971 			}
9972 			break;
9973 		case IPV6_RECVRTHDRDSTOPTS:
9974 			if (!checkonly) {
9975 				if (onoff)
9976 					tcp->tcp_ipv6_recvancillary |=
9977 					    TCP_IPV6_RECVRTDSTOPTS;
9978 				else
9979 					tcp->tcp_ipv6_recvancillary &=
9980 					    ~TCP_IPV6_RECVRTDSTOPTS;
9981 			}
9982 			break;
9983 		case IPV6_PKTINFO:
9984 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
9985 				return (EINVAL);
9986 			if (checkonly)
9987 				break;
9988 
9989 			if (inlen == 0) {
9990 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
9991 			} else {
9992 				struct in6_pktinfo *pkti;
9993 
9994 				pkti = (struct in6_pktinfo *)invalp;
9995 				/*
9996 				 * RFC 3542 states that ipi6_addr must be
9997 				 * the unspecified address when setting the
9998 				 * IPV6_PKTINFO sticky socket option on a
9999 				 * TCP socket.
10000 				 */
10001 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10002 					return (EINVAL);
10003 				/*
10004 				 * ip6_set_pktinfo() validates the source
10005 				 * address and interface index.
10006 				 */
10007 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10008 				    pkti, mblk);
10009 				if (reterr != 0)
10010 					return (reterr);
10011 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10012 				ipp->ipp_addr = pkti->ipi6_addr;
10013 				if (ipp->ipp_ifindex != 0)
10014 					ipp->ipp_fields |= IPPF_IFINDEX;
10015 				else
10016 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10017 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10018 					ipp->ipp_fields |= IPPF_ADDR;
10019 				else
10020 					ipp->ipp_fields &= ~IPPF_ADDR;
10021 			}
10022 			reterr = tcp_build_hdrs(q, tcp);
10023 			if (reterr != 0)
10024 				return (reterr);
10025 			break;
10026 		case IPV6_TCLASS:
10027 			if (inlen != 0 && inlen != sizeof (int))
10028 				return (EINVAL);
10029 			if (checkonly)
10030 				break;
10031 
10032 			if (inlen == 0) {
10033 				ipp->ipp_fields &= ~IPPF_TCLASS;
10034 			} else {
10035 				if (*i1 > 255 || *i1 < -1)
10036 					return (EINVAL);
10037 				if (*i1 == -1) {
10038 					ipp->ipp_tclass = 0;
10039 					*i1 = 0;
10040 				} else {
10041 					ipp->ipp_tclass = *i1;
10042 				}
10043 				ipp->ipp_fields |= IPPF_TCLASS;
10044 			}
10045 			reterr = tcp_build_hdrs(q, tcp);
10046 			if (reterr != 0)
10047 				return (reterr);
10048 			break;
10049 		case IPV6_NEXTHOP:
10050 			/*
10051 			 * IP will verify that the nexthop is reachable
10052 			 * and fail for sticky options.
10053 			 */
10054 			if (inlen != 0 && inlen != sizeof (sin6_t))
10055 				return (EINVAL);
10056 			if (checkonly)
10057 				break;
10058 
10059 			if (inlen == 0) {
10060 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10061 			} else {
10062 				sin6_t *sin6 = (sin6_t *)invalp;
10063 
10064 				if (sin6->sin6_family != AF_INET6)
10065 					return (EAFNOSUPPORT);
10066 				if (IN6_IS_ADDR_V4MAPPED(
10067 				    &sin6->sin6_addr))
10068 					return (EADDRNOTAVAIL);
10069 				ipp->ipp_nexthop = sin6->sin6_addr;
10070 				if (!IN6_IS_ADDR_UNSPECIFIED(
10071 				    &ipp->ipp_nexthop))
10072 					ipp->ipp_fields |= IPPF_NEXTHOP;
10073 				else
10074 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10075 			}
10076 			reterr = tcp_build_hdrs(q, tcp);
10077 			if (reterr != 0)
10078 				return (reterr);
10079 			break;
10080 		case IPV6_HOPOPTS: {
10081 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10082 			/*
10083 			 * Sanity checks - minimum size, size a multiple of
10084 			 * eight bytes, and matching size passed in.
10085 			 */
10086 			if (inlen != 0 &&
10087 			    inlen != (8 * (hopts->ip6h_len + 1)))
10088 				return (EINVAL);
10089 
10090 			if (checkonly)
10091 				break;
10092 
10093 			if (inlen == 0) {
10094 				if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
10095 					kmem_free(ipp->ipp_hopopts,
10096 					    ipp->ipp_hopoptslen);
10097 					ipp->ipp_hopopts = NULL;
10098 					ipp->ipp_hopoptslen = 0;
10099 				}
10100 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10101 			} else {
10102 				reterr = tcp_pkt_set(invalp, inlen,
10103 				    (uchar_t **)&ipp->ipp_hopopts,
10104 				    &ipp->ipp_hopoptslen);
10105 				if (reterr != 0)
10106 					return (reterr);
10107 				ipp->ipp_fields |= IPPF_HOPOPTS;
10108 			}
10109 			reterr = tcp_build_hdrs(q, tcp);
10110 			if (reterr != 0)
10111 				return (reterr);
10112 			break;
10113 		}
10114 		case IPV6_RTHDRDSTOPTS: {
10115 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10116 
10117 			/*
10118 			 * Sanity checks - minimum size, size a multiple of
10119 			 * eight bytes, and matching size passed in.
10120 			 */
10121 			if (inlen != 0 &&
10122 			    inlen != (8 * (dopts->ip6d_len + 1)))
10123 				return (EINVAL);
10124 
10125 			if (checkonly)
10126 				break;
10127 
10128 			if (inlen == 0) {
10129 				if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
10130 					kmem_free(ipp->ipp_rtdstopts,
10131 					    ipp->ipp_rtdstoptslen);
10132 					ipp->ipp_rtdstopts = NULL;
10133 					ipp->ipp_rtdstoptslen = 0;
10134 				}
10135 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10136 			} else {
10137 				reterr = tcp_pkt_set(invalp, inlen,
10138 				    (uchar_t **)&ipp->ipp_rtdstopts,
10139 				    &ipp->ipp_rtdstoptslen);
10140 				if (reterr != 0)
10141 					return (reterr);
10142 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10143 			}
10144 			reterr = tcp_build_hdrs(q, tcp);
10145 			if (reterr != 0)
10146 				return (reterr);
10147 			break;
10148 		}
10149 		case IPV6_DSTOPTS: {
10150 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10151 
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 * (dopts->ip6d_len + 1)))
10158 				return (EINVAL);
10159 
10160 			if (checkonly)
10161 				break;
10162 
10163 			if (inlen == 0) {
10164 				if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
10165 					kmem_free(ipp->ipp_dstopts,
10166 					    ipp->ipp_dstoptslen);
10167 					ipp->ipp_dstopts = NULL;
10168 					ipp->ipp_dstoptslen = 0;
10169 				}
10170 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10171 			} else {
10172 				reterr = tcp_pkt_set(invalp, inlen,
10173 				    (uchar_t **)&ipp->ipp_dstopts,
10174 				    &ipp->ipp_dstoptslen);
10175 				if (reterr != 0)
10176 					return (reterr);
10177 				ipp->ipp_fields |= IPPF_DSTOPTS;
10178 			}
10179 			reterr = tcp_build_hdrs(q, tcp);
10180 			if (reterr != 0)
10181 				return (reterr);
10182 			break;
10183 		}
10184 		case IPV6_RTHDR: {
10185 			ip6_rthdr_t *rt = (ip6_rthdr_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 * (rt->ip6r_len + 1)))
10193 				return (EINVAL);
10194 
10195 			if (checkonly)
10196 				break;
10197 
10198 			if (inlen == 0) {
10199 				if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
10200 					kmem_free(ipp->ipp_rthdr,
10201 					    ipp->ipp_rthdrlen);
10202 					ipp->ipp_rthdr = NULL;
10203 					ipp->ipp_rthdrlen = 0;
10204 				}
10205 				ipp->ipp_fields &= ~IPPF_RTHDR;
10206 			} else {
10207 				reterr = tcp_pkt_set(invalp, inlen,
10208 				    (uchar_t **)&ipp->ipp_rthdr,
10209 				    &ipp->ipp_rthdrlen);
10210 				if (reterr != 0)
10211 					return (reterr);
10212 				ipp->ipp_fields |= IPPF_RTHDR;
10213 			}
10214 			reterr = tcp_build_hdrs(q, tcp);
10215 			if (reterr != 0)
10216 				return (reterr);
10217 			break;
10218 		}
10219 		case IPV6_V6ONLY:
10220 			if (!checkonly)
10221 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10222 			break;
10223 		case IPV6_USE_MIN_MTU:
10224 			if (inlen != sizeof (int))
10225 				return (EINVAL);
10226 
10227 			if (*i1 < -1 || *i1 > 1)
10228 				return (EINVAL);
10229 
10230 			if (checkonly)
10231 				break;
10232 
10233 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10234 			ipp->ipp_use_min_mtu = *i1;
10235 			break;
10236 		case IPV6_BOUND_PIF:
10237 			/* Handled at the IP level */
10238 			return (-EINVAL);
10239 		case IPV6_SEC_OPT:
10240 			/*
10241 			 * We should not allow policy setting after
10242 			 * we start listening for connections.
10243 			 */
10244 			if (tcp->tcp_state == TCPS_LISTEN) {
10245 				return (EINVAL);
10246 			} else {
10247 				/* Handled at the IP level */
10248 				return (-EINVAL);
10249 			}
10250 		case IPV6_SRC_PREFERENCES:
10251 			if (inlen != sizeof (uint32_t))
10252 				return (EINVAL);
10253 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10254 			    *(uint32_t *)invalp);
10255 			if (reterr != 0) {
10256 				*outlenp = 0;
10257 				return (reterr);
10258 			}
10259 			break;
10260 		default:
10261 			*outlenp = 0;
10262 			return (EINVAL);
10263 		}
10264 		break;
10265 	}		/* end IPPROTO_IPV6 */
10266 	default:
10267 		*outlenp = 0;
10268 		return (EINVAL);
10269 	}
10270 	/*
10271 	 * Common case of OK return with outval same as inval
10272 	 */
10273 	if (invalp != outvalp) {
10274 		/* don't trust bcopy for identical src/dst */
10275 		(void) bcopy(invalp, outvalp, inlen);
10276 	}
10277 	*outlenp = inlen;
10278 	return (0);
10279 }
10280 
10281 /*
10282  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10283  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10284  * headers, and the maximum size tcp header (to avoid reallocation
10285  * on the fly for additional tcp options).
10286  * Returns failure if can't allocate memory.
10287  */
10288 static int
10289 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
10290 {
10291 	char	*hdrs;
10292 	uint_t	hdrs_len;
10293 	ip6i_t	*ip6i;
10294 	char	buf[TCP_MAX_HDR_LENGTH];
10295 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10296 	in6_addr_t src, dst;
10297 
10298 	/*
10299 	 * save the existing tcp header and source/dest IP addresses
10300 	 */
10301 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10302 	src = tcp->tcp_ip6h->ip6_src;
10303 	dst = tcp->tcp_ip6h->ip6_dst;
10304 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10305 	ASSERT(hdrs_len != 0);
10306 	if (hdrs_len > tcp->tcp_iphc_len) {
10307 		/* Need to reallocate */
10308 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10309 		if (hdrs == NULL)
10310 			return (ENOMEM);
10311 		if (tcp->tcp_iphc != NULL) {
10312 			if (tcp->tcp_hdr_grown) {
10313 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10314 			} else {
10315 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10316 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10317 			}
10318 			tcp->tcp_iphc_len = 0;
10319 		}
10320 		ASSERT(tcp->tcp_iphc_len == 0);
10321 		tcp->tcp_iphc = hdrs;
10322 		tcp->tcp_iphc_len = hdrs_len;
10323 		tcp->tcp_hdr_grown = B_TRUE;
10324 	}
10325 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10326 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10327 
10328 	/* Set header fields not in ipp */
10329 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10330 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10331 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10332 	} else {
10333 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10334 	}
10335 	/*
10336 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10337 	 *
10338 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10339 	 */
10340 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10341 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10342 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10343 
10344 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10345 
10346 	tcp->tcp_ip6h->ip6_src = src;
10347 	tcp->tcp_ip6h->ip6_dst = dst;
10348 
10349 	/*
10350 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10351 	 * the default value for TCP.
10352 	 */
10353 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10354 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
10355 
10356 	/*
10357 	 * If we're setting extension headers after a connection
10358 	 * has been established, and if we have a routing header
10359 	 * among the extension headers, call ip_massage_options_v6 to
10360 	 * manipulate the routing header/ip6_dst set the checksum
10361 	 * difference in the tcp header template.
10362 	 * (This happens in tcp_connect_ipv6 if the routing header
10363 	 * is set prior to the connect.)
10364 	 * Set the tcp_sum to zero first in case we've cleared a
10365 	 * routing header or don't have one at all.
10366 	 */
10367 	tcp->tcp_sum = 0;
10368 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10369 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10370 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10371 		    (uint8_t *)tcp->tcp_tcph);
10372 		if (rth != NULL) {
10373 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10374 			    rth);
10375 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10376 			    (tcp->tcp_sum >> 16));
10377 		}
10378 	}
10379 
10380 	/* Try to get everything in a single mblk */
10381 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
10382 	return (0);
10383 }
10384 
10385 /*
10386  * Set optbuf and optlen for the option.
10387  * Allocate memory (if not already present).
10388  * Otherwise just point optbuf and optlen at invalp and inlen.
10389  * Returns failure if memory can not be allocated.
10390  */
10391 static int
10392 tcp_pkt_set(uchar_t *invalp, uint_t inlen, uchar_t **optbufp, uint_t *optlenp)
10393 {
10394 	uchar_t *optbuf;
10395 
10396 	if (inlen == *optlenp) {
10397 		/* Unchanged length - no need to realocate */
10398 		bcopy(invalp, *optbufp, inlen);
10399 		return (0);
10400 	}
10401 	if (inlen != 0) {
10402 		/* Allocate new buffer before free */
10403 		optbuf = kmem_alloc(inlen, KM_NOSLEEP);
10404 		if (optbuf == NULL)
10405 			return (ENOMEM);
10406 	} else {
10407 		optbuf = NULL;
10408 	}
10409 	/* Free old buffer */
10410 	if (*optlenp != 0)
10411 		kmem_free(*optbufp, *optlenp);
10412 
10413 	bcopy(invalp, optbuf, inlen);
10414 	*optbufp = optbuf;
10415 	*optlenp = inlen;
10416 	return (0);
10417 }
10418 
10419 
10420 /*
10421  * Use the outgoing IP header to create an IP_OPTIONS option the way
10422  * it was passed down from the application.
10423  */
10424 static int
10425 tcp_opt_get_user(ipha_t *ipha, uchar_t *buf)
10426 {
10427 	ipoptp_t	opts;
10428 	uchar_t		*opt;
10429 	uint8_t		optval;
10430 	uint8_t		optlen;
10431 	uint32_t	len = 0;
10432 	uchar_t	*buf1 = buf;
10433 
10434 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
10435 	len += IP_ADDR_LEN;
10436 	bzero(buf1, IP_ADDR_LEN);
10437 
10438 	for (optval = ipoptp_first(&opts, ipha);
10439 	    optval != IPOPT_EOL;
10440 	    optval = ipoptp_next(&opts)) {
10441 		opt = opts.ipoptp_cur;
10442 		optlen = opts.ipoptp_len;
10443 		switch (optval) {
10444 			int	off;
10445 		case IPOPT_SSRR:
10446 		case IPOPT_LSRR:
10447 
10448 			/*
10449 			 * Insert ipha_dst as the first entry in the source
10450 			 * route and move down the entries on step.
10451 			 * The last entry gets placed at buf1.
10452 			 */
10453 			buf[IPOPT_OPTVAL] = optval;
10454 			buf[IPOPT_OLEN] = optlen;
10455 			buf[IPOPT_OFFSET] = optlen;
10456 
10457 			off = optlen - IP_ADDR_LEN;
10458 			if (off < 0) {
10459 				/* No entries in source route */
10460 				break;
10461 			}
10462 			/* Last entry in source route */
10463 			bcopy(opt + off, buf1, IP_ADDR_LEN);
10464 			off -= IP_ADDR_LEN;
10465 
10466 			while (off > 0) {
10467 				bcopy(opt + off,
10468 				    buf + off + IP_ADDR_LEN,
10469 				    IP_ADDR_LEN);
10470 				off -= IP_ADDR_LEN;
10471 			}
10472 			/* ipha_dst into first slot */
10473 			bcopy(&ipha->ipha_dst,
10474 			    buf + off + IP_ADDR_LEN,
10475 			    IP_ADDR_LEN);
10476 			buf += optlen;
10477 			len += optlen;
10478 			break;
10479 		default:
10480 			bcopy(opt, buf, optlen);
10481 			buf += optlen;
10482 			len += optlen;
10483 			break;
10484 		}
10485 	}
10486 done:
10487 	/* Pad the resulting options */
10488 	while (len & 0x3) {
10489 		*buf++ = IPOPT_EOL;
10490 		len++;
10491 	}
10492 	return (len);
10493 }
10494 
10495 /*
10496  * Transfer any source route option from ipha to buf/dst in reversed form.
10497  */
10498 static int
10499 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10500 {
10501 	ipoptp_t	opts;
10502 	uchar_t		*opt;
10503 	uint8_t		optval;
10504 	uint8_t		optlen;
10505 	uint32_t	len = 0;
10506 
10507 	for (optval = ipoptp_first(&opts, ipha);
10508 	    optval != IPOPT_EOL;
10509 	    optval = ipoptp_next(&opts)) {
10510 		opt = opts.ipoptp_cur;
10511 		optlen = opts.ipoptp_len;
10512 		switch (optval) {
10513 			int	off1, off2;
10514 		case IPOPT_SSRR:
10515 		case IPOPT_LSRR:
10516 
10517 			/* Reverse source route */
10518 			/*
10519 			 * First entry should be the next to last one in the
10520 			 * current source route (the last entry is our
10521 			 * address.)
10522 			 * The last entry should be the final destination.
10523 			 */
10524 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10525 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10526 			off1 = IPOPT_MINOFF_SR - 1;
10527 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10528 			if (off2 < 0) {
10529 				/* No entries in source route */
10530 				break;
10531 			}
10532 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10533 			/*
10534 			 * Note: use src since ipha has not had its src
10535 			 * and dst reversed (it is in the state it was
10536 			 * received.
10537 			 */
10538 			bcopy(&ipha->ipha_src, buf + off2,
10539 			    IP_ADDR_LEN);
10540 			off2 -= IP_ADDR_LEN;
10541 
10542 			while (off2 > 0) {
10543 				bcopy(opt + off2, buf + off1,
10544 				    IP_ADDR_LEN);
10545 				off1 += IP_ADDR_LEN;
10546 				off2 -= IP_ADDR_LEN;
10547 			}
10548 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10549 			buf += optlen;
10550 			len += optlen;
10551 			break;
10552 		}
10553 	}
10554 done:
10555 	/* Pad the resulting options */
10556 	while (len & 0x3) {
10557 		*buf++ = IPOPT_EOL;
10558 		len++;
10559 	}
10560 	return (len);
10561 }
10562 
10563 
10564 /*
10565  * Extract and revert a source route from ipha (if any)
10566  * and then update the relevant fields in both tcp_t and the standard header.
10567  */
10568 static void
10569 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
10570 {
10571 	char	buf[TCP_MAX_HDR_LENGTH];
10572 	uint_t	tcph_len;
10573 	int	len;
10574 
10575 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
10576 	len = IPH_HDR_LENGTH(ipha);
10577 	if (len == IP_SIMPLE_HDR_LENGTH)
10578 		/* Nothing to do */
10579 		return;
10580 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
10581 	    (len & 0x3))
10582 		return;
10583 
10584 	tcph_len = tcp->tcp_tcp_hdr_len;
10585 	bcopy(tcp->tcp_tcph, buf, tcph_len);
10586 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
10587 		(tcp->tcp_ipha->ipha_dst & 0xffff);
10588 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
10589 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
10590 	len += IP_SIMPLE_HDR_LENGTH;
10591 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
10592 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
10593 	if ((int)tcp->tcp_sum < 0)
10594 		tcp->tcp_sum--;
10595 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
10596 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
10597 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
10598 	bcopy(buf, tcp->tcp_tcph, tcph_len);
10599 	tcp->tcp_ip_hdr_len = len;
10600 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10601 	    (IP_VERSION << 4) | (len >> 2);
10602 	len += tcph_len;
10603 	tcp->tcp_hdr_len = len;
10604 }
10605 
10606 /*
10607  * Copy the standard header into its new location,
10608  * lay in the new options and then update the relevant
10609  * fields in both tcp_t and the standard header.
10610  */
10611 static int
10612 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
10613 {
10614 	uint_t	tcph_len;
10615 	char	*ip_optp;
10616 	tcph_t	*new_tcph;
10617 
10618 	if (checkonly) {
10619 		/*
10620 		 * do not really set, just pretend to - T_CHECK
10621 		 */
10622 		if (len != 0) {
10623 			/*
10624 			 * there is value supplied, validate it as if
10625 			 * for a real set operation.
10626 			 */
10627 			if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10628 				return (EINVAL);
10629 		}
10630 		return (0);
10631 	}
10632 
10633 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10634 		return (EINVAL);
10635 
10636 	ip_optp = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
10637 	tcph_len = tcp->tcp_tcp_hdr_len;
10638 	new_tcph = (tcph_t *)(ip_optp + len);
10639 	ovbcopy((char *)tcp->tcp_tcph, (char *)new_tcph, tcph_len);
10640 	tcp->tcp_tcph = new_tcph;
10641 	bcopy(ptr, ip_optp, len);
10642 
10643 	len += IP_SIMPLE_HDR_LENGTH;
10644 
10645 	tcp->tcp_ip_hdr_len = len;
10646 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10647 		(IP_VERSION << 4) | (len >> 2);
10648 	len += tcph_len;
10649 	tcp->tcp_hdr_len = len;
10650 	if (!TCP_IS_DETACHED(tcp)) {
10651 		/* Always allocate room for all options. */
10652 		(void) mi_set_sth_wroff(tcp->tcp_rq,
10653 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
10654 	}
10655 	return (0);
10656 }
10657 
10658 /* Get callback routine passed to nd_load by tcp_param_register */
10659 /* ARGSUSED */
10660 static int
10661 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
10662 {
10663 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10664 
10665 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
10666 	return (0);
10667 }
10668 
10669 /*
10670  * Walk through the param array specified registering each element with the
10671  * named dispatch handler.
10672  */
10673 static boolean_t
10674 tcp_param_register(tcpparam_t *tcppa, int cnt)
10675 {
10676 	for (; cnt-- > 0; tcppa++) {
10677 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
10678 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
10679 			    tcp_param_get, tcp_param_set,
10680 			    (caddr_t)tcppa)) {
10681 				nd_free(&tcp_g_nd);
10682 				return (B_FALSE);
10683 			}
10684 		}
10685 	}
10686 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
10687 	    tcp_param_get, tcp_param_set_aligned,
10688 	    (caddr_t)&tcp_wroff_xtra_param)) {
10689 		nd_free(&tcp_g_nd);
10690 		return (B_FALSE);
10691 	}
10692 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
10693 	    tcp_param_get, tcp_param_set_aligned,
10694 	    (caddr_t)&tcp_mdt_head_param)) {
10695 		nd_free(&tcp_g_nd);
10696 		return (B_FALSE);
10697 	}
10698 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
10699 	    tcp_param_get, tcp_param_set_aligned,
10700 	    (caddr_t)&tcp_mdt_tail_param)) {
10701 		nd_free(&tcp_g_nd);
10702 		return (B_FALSE);
10703 	}
10704 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
10705 	    tcp_param_get, tcp_param_set,
10706 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
10707 		nd_free(&tcp_g_nd);
10708 		return (B_FALSE);
10709 	}
10710 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
10711 	    tcp_extra_priv_ports_get, NULL, NULL)) {
10712 		nd_free(&tcp_g_nd);
10713 		return (B_FALSE);
10714 	}
10715 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
10716 	    NULL, tcp_extra_priv_ports_add, NULL)) {
10717 		nd_free(&tcp_g_nd);
10718 		return (B_FALSE);
10719 	}
10720 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
10721 	    NULL, tcp_extra_priv_ports_del, NULL)) {
10722 		nd_free(&tcp_g_nd);
10723 		return (B_FALSE);
10724 	}
10725 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
10726 	    NULL)) {
10727 		nd_free(&tcp_g_nd);
10728 		return (B_FALSE);
10729 	}
10730 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
10731 	    NULL, NULL)) {
10732 		nd_free(&tcp_g_nd);
10733 		return (B_FALSE);
10734 	}
10735 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
10736 	    NULL, NULL)) {
10737 		nd_free(&tcp_g_nd);
10738 		return (B_FALSE);
10739 	}
10740 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
10741 	    NULL, NULL)) {
10742 		nd_free(&tcp_g_nd);
10743 		return (B_FALSE);
10744 	}
10745 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
10746 	    NULL, NULL)) {
10747 		nd_free(&tcp_g_nd);
10748 		return (B_FALSE);
10749 	}
10750 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
10751 	    tcp_host_param_set, NULL)) {
10752 		nd_free(&tcp_g_nd);
10753 		return (B_FALSE);
10754 	}
10755 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
10756 	    tcp_host_param_set_ipv6, NULL)) {
10757 		nd_free(&tcp_g_nd);
10758 		return (B_FALSE);
10759 	}
10760 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
10761 	    NULL)) {
10762 		nd_free(&tcp_g_nd);
10763 		return (B_FALSE);
10764 	}
10765 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
10766 	    tcp_reserved_port_list, NULL, NULL)) {
10767 		nd_free(&tcp_g_nd);
10768 		return (B_FALSE);
10769 	}
10770 	/*
10771 	 * Dummy ndd variables - only to convey obsolescence information
10772 	 * through printing of their name (no get or set routines)
10773 	 * XXX Remove in future releases ?
10774 	 */
10775 	if (!nd_load(&tcp_g_nd,
10776 	    "tcp_close_wait_interval(obsoleted - "
10777 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
10778 		nd_free(&tcp_g_nd);
10779 		return (B_FALSE);
10780 	}
10781 	return (B_TRUE);
10782 }
10783 
10784 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
10785 /* ARGSUSED */
10786 static int
10787 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
10788     cred_t *cr)
10789 {
10790 	long new_value;
10791 	tcpparam_t *tcppa = (tcpparam_t *)cp;
10792 
10793 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10794 	    new_value < tcppa->tcp_param_min ||
10795 	    new_value > tcppa->tcp_param_max) {
10796 		return (EINVAL);
10797 	}
10798 	/*
10799 	 * Need to make sure new_value is a multiple of 4.  If it is not,
10800 	 * round it up.  For future 64 bit requirement, we actually make it
10801 	 * a multiple of 8.
10802 	 */
10803 	if (new_value & 0x7) {
10804 		new_value = (new_value & ~0x7) + 0x8;
10805 	}
10806 	tcppa->tcp_param_val = new_value;
10807 	return (0);
10808 }
10809 
10810 /* Set callback routine passed to nd_load by tcp_param_register */
10811 /* ARGSUSED */
10812 static int
10813 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
10814 {
10815 	long	new_value;
10816 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10817 
10818 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10819 	    new_value < tcppa->tcp_param_min ||
10820 	    new_value > tcppa->tcp_param_max) {
10821 		return (EINVAL);
10822 	}
10823 	tcppa->tcp_param_val = new_value;
10824 	return (0);
10825 }
10826 
10827 /*
10828  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
10829  * is filled, return as much as we can.  The message passed in may be
10830  * multi-part, chained using b_cont.  "start" is the starting sequence
10831  * number for this piece.
10832  */
10833 static mblk_t *
10834 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
10835 {
10836 	uint32_t	end;
10837 	mblk_t		*mp1;
10838 	mblk_t		*mp2;
10839 	mblk_t		*next_mp;
10840 	uint32_t	u1;
10841 
10842 	/* Walk through all the new pieces. */
10843 	do {
10844 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10845 		    (uintptr_t)INT_MAX);
10846 		end = start + (int)(mp->b_wptr - mp->b_rptr);
10847 		next_mp = mp->b_cont;
10848 		if (start == end) {
10849 			/* Empty.  Blast it. */
10850 			freeb(mp);
10851 			continue;
10852 		}
10853 		mp->b_cont = NULL;
10854 		TCP_REASS_SET_SEQ(mp, start);
10855 		TCP_REASS_SET_END(mp, end);
10856 		mp1 = tcp->tcp_reass_tail;
10857 		if (!mp1) {
10858 			tcp->tcp_reass_tail = mp;
10859 			tcp->tcp_reass_head = mp;
10860 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
10861 			UPDATE_MIB(&tcp_mib,
10862 			    tcpInDataUnorderBytes, end - start);
10863 			continue;
10864 		}
10865 		/* New stuff completely beyond tail? */
10866 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
10867 			/* Link it on end. */
10868 			mp1->b_cont = mp;
10869 			tcp->tcp_reass_tail = mp;
10870 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
10871 			UPDATE_MIB(&tcp_mib,
10872 			    tcpInDataUnorderBytes, end - start);
10873 			continue;
10874 		}
10875 		mp1 = tcp->tcp_reass_head;
10876 		u1 = TCP_REASS_SEQ(mp1);
10877 		/* New stuff at the front? */
10878 		if (SEQ_LT(start, u1)) {
10879 			/* Yes... Check for overlap. */
10880 			mp->b_cont = mp1;
10881 			tcp->tcp_reass_head = mp;
10882 			tcp_reass_elim_overlap(tcp, mp);
10883 			continue;
10884 		}
10885 		/*
10886 		 * The new piece fits somewhere between the head and tail.
10887 		 * We find our slot, where mp1 precedes us and mp2 trails.
10888 		 */
10889 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
10890 			u1 = TCP_REASS_SEQ(mp2);
10891 			if (SEQ_LEQ(start, u1))
10892 				break;
10893 		}
10894 		/* Link ourselves in */
10895 		mp->b_cont = mp2;
10896 		mp1->b_cont = mp;
10897 
10898 		/* Trim overlap with following mblk(s) first */
10899 		tcp_reass_elim_overlap(tcp, mp);
10900 
10901 		/* Trim overlap with preceding mblk */
10902 		tcp_reass_elim_overlap(tcp, mp1);
10903 
10904 	} while (start = end, mp = next_mp);
10905 	mp1 = tcp->tcp_reass_head;
10906 	/* Anything ready to go? */
10907 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
10908 		return (NULL);
10909 	/* Eat what we can off the queue */
10910 	for (;;) {
10911 		mp = mp1->b_cont;
10912 		end = TCP_REASS_END(mp1);
10913 		TCP_REASS_SET_SEQ(mp1, 0);
10914 		TCP_REASS_SET_END(mp1, 0);
10915 		if (!mp) {
10916 			tcp->tcp_reass_tail = NULL;
10917 			break;
10918 		}
10919 		if (end != TCP_REASS_SEQ(mp)) {
10920 			mp1->b_cont = NULL;
10921 			break;
10922 		}
10923 		mp1 = mp;
10924 	}
10925 	mp1 = tcp->tcp_reass_head;
10926 	tcp->tcp_reass_head = mp;
10927 	return (mp1);
10928 }
10929 
10930 /* Eliminate any overlap that mp may have over later mblks */
10931 static void
10932 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
10933 {
10934 	uint32_t	end;
10935 	mblk_t		*mp1;
10936 	uint32_t	u1;
10937 
10938 	end = TCP_REASS_END(mp);
10939 	while ((mp1 = mp->b_cont) != NULL) {
10940 		u1 = TCP_REASS_SEQ(mp1);
10941 		if (!SEQ_GT(end, u1))
10942 			break;
10943 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
10944 			mp->b_wptr -= end - u1;
10945 			TCP_REASS_SET_END(mp, u1);
10946 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
10947 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
10948 			break;
10949 		}
10950 		mp->b_cont = mp1->b_cont;
10951 		TCP_REASS_SET_SEQ(mp1, 0);
10952 		TCP_REASS_SET_END(mp1, 0);
10953 		freeb(mp1);
10954 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
10955 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
10956 	}
10957 	if (!mp1)
10958 		tcp->tcp_reass_tail = mp;
10959 }
10960 
10961 /*
10962  * Send up all messages queued on tcp_rcv_list.
10963  */
10964 static uint_t
10965 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
10966 {
10967 	mblk_t *mp;
10968 	uint_t ret = 0;
10969 	uint_t thwin;
10970 #ifdef DEBUG
10971 	uint_t cnt = 0;
10972 #endif
10973 	/* Can't drain on an eager connection */
10974 	if (tcp->tcp_listener != NULL)
10975 		return (ret);
10976 
10977 	/*
10978 	 * Handle two cases here: we are currently fused or we were
10979 	 * previously fused and have some urgent data to be delivered
10980 	 * upstream.  The latter happens because we either ran out of
10981 	 * memory or were detached and therefore sending the SIGURG was
10982 	 * deferred until this point.  In either case we pass control
10983 	 * over to tcp_fuse_rcv_drain() since it may need to complete
10984 	 * some work.
10985 	 */
10986 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
10987 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
10988 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
10989 		    &tcp->tcp_fused_sigurg_mp))
10990 			return (ret);
10991 	}
10992 
10993 	while ((mp = tcp->tcp_rcv_list) != NULL) {
10994 		tcp->tcp_rcv_list = mp->b_next;
10995 		mp->b_next = NULL;
10996 #ifdef DEBUG
10997 		cnt += msgdsize(mp);
10998 #endif
10999 		putnext(q, mp);
11000 	}
11001 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11002 	tcp->tcp_rcv_last_head = NULL;
11003 	tcp->tcp_rcv_last_tail = NULL;
11004 	tcp->tcp_rcv_cnt = 0;
11005 
11006 	/* Learn the latest rwnd information that we sent to the other side. */
11007 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11008 	    << tcp->tcp_rcv_ws;
11009 	/* This is peer's calculated send window (our receive window). */
11010 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11011 	/*
11012 	 * Increase the receive window to max.  But we need to do receiver
11013 	 * SWS avoidance.  This means that we need to check the increase of
11014 	 * of receive window is at least 1 MSS.
11015 	 */
11016 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11017 		/*
11018 		 * If the window that the other side knows is less than max
11019 		 * deferred acks segments, send an update immediately.
11020 		 */
11021 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11022 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11023 			ret = TH_ACK_NEEDED;
11024 		}
11025 		tcp->tcp_rwnd = q->q_hiwat;
11026 	}
11027 	/* No need for the push timer now. */
11028 	if (tcp->tcp_push_tid != 0) {
11029 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11030 		tcp->tcp_push_tid = 0;
11031 	}
11032 	return (ret);
11033 }
11034 
11035 /*
11036  * Queue data on tcp_rcv_list which is a b_next chain.
11037  * tcp_rcv_last_head/tail is the last element of this chain.
11038  * Each element of the chain is a b_cont chain.
11039  *
11040  * M_DATA messages are added to the current element.
11041  * Other messages are added as new (b_next) elements.
11042  */
11043 void
11044 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11045 {
11046 	ASSERT(seg_len == msgdsize(mp));
11047 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11048 
11049 	if (tcp->tcp_rcv_list == NULL) {
11050 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11051 		tcp->tcp_rcv_list = mp;
11052 		tcp->tcp_rcv_last_head = mp;
11053 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11054 		tcp->tcp_rcv_last_tail->b_cont = mp;
11055 	} else {
11056 		tcp->tcp_rcv_last_head->b_next = mp;
11057 		tcp->tcp_rcv_last_head = mp;
11058 	}
11059 
11060 	while (mp->b_cont)
11061 		mp = mp->b_cont;
11062 
11063 	tcp->tcp_rcv_last_tail = mp;
11064 	tcp->tcp_rcv_cnt += seg_len;
11065 	tcp->tcp_rwnd -= seg_len;
11066 }
11067 
11068 /*
11069  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11070  *
11071  * This is the default entry function into TCP on the read side. TCP is
11072  * always entered via squeue i.e. using squeue's for mutual exclusion.
11073  * When classifier does a lookup to find the tcp, it also puts a reference
11074  * on the conn structure associated so the tcp is guaranteed to exist
11075  * when we come here. We still need to check the state because it might
11076  * as well has been closed. The squeue processing function i.e. squeue_enter,
11077  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11078  * CONN_DEC_REF.
11079  *
11080  * Apart from the default entry point, IP also sends packets directly to
11081  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11082  * connections.
11083  */
11084 void
11085 tcp_input(void *arg, mblk_t *mp, void *arg2)
11086 {
11087 	conn_t	*connp = (conn_t *)arg;
11088 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11089 
11090 	/* arg2 is the sqp */
11091 	ASSERT(arg2 != NULL);
11092 	ASSERT(mp != NULL);
11093 
11094 	/*
11095 	 * Don't accept any input on a closed tcp as this TCP logically does
11096 	 * not exist on the system. Don't proceed further with this TCP.
11097 	 * For eg. this packet could trigger another close of this tcp
11098 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11099 	 * tcp_clean_death / tcp_closei_local must be called at most once
11100 	 * on a TCP. In this case we need to refeed the packet into the
11101 	 * classifier and figure out where the packet should go. Need to
11102 	 * preserve the recv_ill somehow. Until we figure that out, for
11103 	 * now just drop the packet if we can't classify the packet.
11104 	 */
11105 	if (tcp->tcp_state == TCPS_CLOSED ||
11106 	    tcp->tcp_state == TCPS_BOUND) {
11107 		conn_t	*new_connp;
11108 
11109 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11110 		if (new_connp != NULL) {
11111 			tcp_reinput(new_connp, mp, arg2);
11112 			return;
11113 		}
11114 		/* We failed to classify. For now just drop the packet */
11115 		freemsg(mp);
11116 		return;
11117 	}
11118 
11119 	if (DB_TYPE(mp) == M_DATA)
11120 		tcp_rput_data(connp, mp, arg2);
11121 	else
11122 		tcp_rput_common(tcp, mp);
11123 }
11124 
11125 /*
11126  * The read side put procedure.
11127  * The packets passed up by ip are assume to be aligned according to
11128  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11129  */
11130 static void
11131 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11132 {
11133 	/*
11134 	 * tcp_rput_data() does not expect M_CTL except for the case
11135 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11136 	 * type. Need to make sure that any other M_CTLs don't make
11137 	 * it to tcp_rput_data since it is not expecting any and doesn't
11138 	 * check for it.
11139 	 */
11140 	if (DB_TYPE(mp) == M_CTL) {
11141 		switch (*(uint32_t *)(mp->b_rptr)) {
11142 		case TCP_IOC_ABORT_CONN:
11143 			/*
11144 			 * Handle connection abort request.
11145 			 */
11146 			tcp_ioctl_abort_handler(tcp, mp);
11147 			return;
11148 		case IPSEC_IN:
11149 			/*
11150 			 * Only secure icmp arrive in TCP and they
11151 			 * don't go through data path.
11152 			 */
11153 			tcp_icmp_error(tcp, mp);
11154 			return;
11155 		case IN_PKTINFO:
11156 			/*
11157 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11158 			 * sockets that are receiving IPv4 traffic. tcp
11159 			 */
11160 			ASSERT(tcp->tcp_family == AF_INET6);
11161 			ASSERT(tcp->tcp_ipv6_recvancillary &
11162 			    TCP_IPV6_RECVPKTINFO);
11163 			tcp_rput_data(tcp->tcp_connp, mp,
11164 			    tcp->tcp_connp->conn_sqp);
11165 			return;
11166 		case MDT_IOC_INFO_UPDATE:
11167 			/*
11168 			 * Handle Multidata information update; the
11169 			 * following routine will free the message.
11170 			 */
11171 			if (tcp->tcp_connp->conn_mdt_ok) {
11172 				tcp_mdt_update(tcp,
11173 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11174 				    B_FALSE);
11175 			}
11176 			freemsg(mp);
11177 			return;
11178 		default:
11179 			break;
11180 		}
11181 	}
11182 
11183 	/* No point processing the message if tcp is already closed */
11184 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11185 		freemsg(mp);
11186 		return;
11187 	}
11188 
11189 	tcp_rput_other(tcp, mp);
11190 }
11191 
11192 
11193 /* The minimum of smoothed mean deviation in RTO calculation. */
11194 #define	TCP_SD_MIN	400
11195 
11196 /*
11197  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11198  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11199  * are the same as those in Appendix A.2 of that paper.
11200  *
11201  * m = new measurement
11202  * sa = smoothed RTT average (8 * average estimates).
11203  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11204  */
11205 static void
11206 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11207 {
11208 	long m = TICK_TO_MSEC(rtt);
11209 	clock_t sa = tcp->tcp_rtt_sa;
11210 	clock_t sv = tcp->tcp_rtt_sd;
11211 	clock_t rto;
11212 
11213 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
11214 	tcp->tcp_rtt_update++;
11215 
11216 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11217 	if (sa != 0) {
11218 		/*
11219 		 * Update average estimator:
11220 		 *	new rtt = 7/8 old rtt + 1/8 Error
11221 		 */
11222 
11223 		/* m is now Error in estimate. */
11224 		m -= sa >> 3;
11225 		if ((sa += m) <= 0) {
11226 			/*
11227 			 * Don't allow the smoothed average to be negative.
11228 			 * We use 0 to denote reinitialization of the
11229 			 * variables.
11230 			 */
11231 			sa = 1;
11232 		}
11233 
11234 		/*
11235 		 * Update deviation estimator:
11236 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11237 		 */
11238 		if (m < 0)
11239 			m = -m;
11240 		m -= sv >> 2;
11241 		sv += m;
11242 	} else {
11243 		/*
11244 		 * This follows BSD's implementation.  So the reinitialized
11245 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11246 		 * link is bandwidth dominated, doubling the window size
11247 		 * during slow start means doubling the RTT.  We want to be
11248 		 * more conservative when we reinitialize our estimates.  3
11249 		 * is just a convenient number.
11250 		 */
11251 		sa = m << 3;
11252 		sv = m << 1;
11253 	}
11254 	if (sv < TCP_SD_MIN) {
11255 		/*
11256 		 * We do not know that if sa captures the delay ACK
11257 		 * effect as in a long train of segments, a receiver
11258 		 * does not delay its ACKs.  So set the minimum of sv
11259 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11260 		 * of BSD DATO.  That means the minimum of mean
11261 		 * deviation is 100 ms.
11262 		 *
11263 		 */
11264 		sv = TCP_SD_MIN;
11265 	}
11266 	tcp->tcp_rtt_sa = sa;
11267 	tcp->tcp_rtt_sd = sv;
11268 	/*
11269 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11270 	 *
11271 	 * Add tcp_rexmit_interval extra in case of extreme environment
11272 	 * where the algorithm fails to work.  The default value of
11273 	 * tcp_rexmit_interval_extra should be 0.
11274 	 *
11275 	 * As we use a finer grained clock than BSD and update
11276 	 * RTO for every ACKs, add in another .25 of RTT to the
11277 	 * deviation of RTO to accomodate burstiness of 1/4 of
11278 	 * window size.
11279 	 */
11280 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
11281 
11282 	if (rto > tcp_rexmit_interval_max) {
11283 		tcp->tcp_rto = tcp_rexmit_interval_max;
11284 	} else if (rto < tcp_rexmit_interval_min) {
11285 		tcp->tcp_rto = tcp_rexmit_interval_min;
11286 	} else {
11287 		tcp->tcp_rto = rto;
11288 	}
11289 
11290 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11291 	tcp->tcp_timer_backoff = 0;
11292 }
11293 
11294 /*
11295  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11296  * send queue which starts at the given seq. no.
11297  *
11298  * Parameters:
11299  *	tcp_t *tcp: the tcp instance pointer.
11300  *	uint32_t seq: the starting seq. no of the requested segment.
11301  *	int32_t *off: after the execution, *off will be the offset to
11302  *		the returned mblk which points to the requested seq no.
11303  *		It is the caller's responsibility to send in a non-null off.
11304  *
11305  * Return:
11306  *	A mblk_t pointer pointing to the requested segment in send queue.
11307  */
11308 static mblk_t *
11309 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11310 {
11311 	int32_t	cnt;
11312 	mblk_t	*mp;
11313 
11314 	/* Defensive coding.  Make sure we don't send incorrect data. */
11315 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
11316 		return (NULL);
11317 
11318 	cnt = seq - tcp->tcp_suna;
11319 	mp = tcp->tcp_xmit_head;
11320 	while (cnt > 0 && mp != NULL) {
11321 		cnt -= mp->b_wptr - mp->b_rptr;
11322 		if (cnt < 0) {
11323 			cnt += mp->b_wptr - mp->b_rptr;
11324 			break;
11325 		}
11326 		mp = mp->b_cont;
11327 	}
11328 	ASSERT(mp != NULL);
11329 	*off = cnt;
11330 	return (mp);
11331 }
11332 
11333 /*
11334  * This function handles all retransmissions if SACK is enabled for this
11335  * connection.  First it calculates how many segments can be retransmitted
11336  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11337  * segments.  A segment is eligible if sack_cnt for that segment is greater
11338  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11339  * all eligible segments, it checks to see if TCP can send some new segments
11340  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11341  *
11342  * Parameters:
11343  *	tcp_t *tcp: the tcp structure of the connection.
11344  *	uint_t *flags: in return, appropriate value will be set for
11345  *	tcp_rput_data().
11346  */
11347 static void
11348 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11349 {
11350 	notsack_blk_t	*notsack_blk;
11351 	int32_t		usable_swnd;
11352 	int32_t		mss;
11353 	uint32_t	seg_len;
11354 	mblk_t		*xmit_mp;
11355 
11356 	ASSERT(tcp->tcp_sack_info != NULL);
11357 	ASSERT(tcp->tcp_notsack_list != NULL);
11358 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11359 
11360 	/* Defensive coding in case there is a bug... */
11361 	if (tcp->tcp_notsack_list == NULL) {
11362 		return;
11363 	}
11364 	notsack_blk = tcp->tcp_notsack_list;
11365 	mss = tcp->tcp_mss;
11366 
11367 	/*
11368 	 * Limit the num of outstanding data in the network to be
11369 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11370 	 */
11371 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11372 
11373 	/* At least retransmit 1 MSS of data. */
11374 	if (usable_swnd <= 0) {
11375 		usable_swnd = mss;
11376 	}
11377 
11378 	/* Make sure no new RTT samples will be taken. */
11379 	tcp->tcp_csuna = tcp->tcp_snxt;
11380 
11381 	notsack_blk = tcp->tcp_notsack_list;
11382 	while (usable_swnd > 0) {
11383 		mblk_t		*snxt_mp, *tmp_mp;
11384 		tcp_seq		begin = tcp->tcp_sack_snxt;
11385 		tcp_seq		end;
11386 		int32_t		off;
11387 
11388 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11389 			if (SEQ_GT(notsack_blk->end, begin) &&
11390 			    (notsack_blk->sack_cnt >=
11391 			    tcp_dupack_fast_retransmit)) {
11392 				end = notsack_blk->end;
11393 				if (SEQ_LT(begin, notsack_blk->begin)) {
11394 					begin = notsack_blk->begin;
11395 				}
11396 				break;
11397 			}
11398 		}
11399 		/*
11400 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11401 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11402 		 * set to tcp_cwnd_ssthresh.
11403 		 */
11404 		if (notsack_blk == NULL) {
11405 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11406 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11407 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11408 				ASSERT(tcp->tcp_cwnd > 0);
11409 				return;
11410 			} else {
11411 				usable_swnd = usable_swnd / mss;
11412 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11413 				    MAX(usable_swnd * mss, mss);
11414 				*flags |= TH_XMIT_NEEDED;
11415 				return;
11416 			}
11417 		}
11418 
11419 		/*
11420 		 * Note that we may send more than usable_swnd allows here
11421 		 * because of round off, but no more than 1 MSS of data.
11422 		 */
11423 		seg_len = end - begin;
11424 		if (seg_len > mss)
11425 			seg_len = mss;
11426 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11427 		ASSERT(snxt_mp != NULL);
11428 		/* This should not happen.  Defensive coding again... */
11429 		if (snxt_mp == NULL) {
11430 			return;
11431 		}
11432 
11433 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11434 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11435 		if (xmit_mp == NULL)
11436 			return;
11437 
11438 		usable_swnd -= seg_len;
11439 		tcp->tcp_pipe += seg_len;
11440 		tcp->tcp_sack_snxt = begin + seg_len;
11441 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
11442 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11443 
11444 		/*
11445 		 * Update the send timestamp to avoid false retransmission.
11446 		 */
11447 		snxt_mp->b_prev = (mblk_t *)lbolt;
11448 
11449 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
11450 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
11451 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
11452 		/*
11453 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11454 		 * This happens when new data sent during fast recovery is
11455 		 * also lost.  If TCP retransmits those new data, it needs
11456 		 * to extend SACK recover phase to avoid starting another
11457 		 * fast retransmit/recovery unnecessarily.
11458 		 */
11459 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11460 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11461 		}
11462 	}
11463 }
11464 
11465 /*
11466  * This function handles policy checking at TCP level for non-hard_bound/
11467  * detached connections.
11468  */
11469 static boolean_t
11470 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
11471     boolean_t secure, boolean_t mctl_present)
11472 {
11473 	ipsec_latch_t *ipl = NULL;
11474 	ipsec_action_t *act = NULL;
11475 	mblk_t *data_mp;
11476 	ipsec_in_t *ii;
11477 	const char *reason;
11478 	kstat_named_t *counter;
11479 
11480 	ASSERT(mctl_present || !secure);
11481 
11482 	ASSERT((ipha == NULL && ip6h != NULL) ||
11483 	    (ip6h == NULL && ipha != NULL));
11484 
11485 	/*
11486 	 * We don't necessarily have an ipsec_in_act action to verify
11487 	 * policy because of assymetrical policy where we have only
11488 	 * outbound policy and no inbound policy (possible with global
11489 	 * policy).
11490 	 */
11491 	if (!secure) {
11492 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
11493 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
11494 			return (B_TRUE);
11495 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
11496 		    "tcp_check_policy", ipha, ip6h, secure);
11497 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11498 		    &ipdrops_tcp_clear, &tcp_dropper);
11499 		return (B_FALSE);
11500 	}
11501 
11502 	/*
11503 	 * We have a secure packet.
11504 	 */
11505 	if (act == NULL) {
11506 		ipsec_log_policy_failure(tcp->tcp_wq,
11507 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
11508 		    secure);
11509 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11510 		    &ipdrops_tcp_secure, &tcp_dropper);
11511 		return (B_FALSE);
11512 	}
11513 
11514 	/*
11515 	 * XXX This whole routine is currently incorrect.  ipl should
11516 	 * be set to the latch pointer, but is currently not set, so
11517 	 * we initialize it to NULL to avoid picking up random garbage.
11518 	 */
11519 	if (ipl == NULL)
11520 		return (B_TRUE);
11521 
11522 	data_mp = first_mp->b_cont;
11523 
11524 	ii = (ipsec_in_t *)first_mp->b_rptr;
11525 
11526 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
11527 	    &counter)) {
11528 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
11529 		return (B_TRUE);
11530 	}
11531 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
11532 	    "tcp inbound policy mismatch: %s, packet dropped\n",
11533 	    reason);
11534 	BUMP_MIB(&ip_mib, ipsecInFailed);
11535 
11536 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
11537 	return (B_FALSE);
11538 }
11539 
11540 /*
11541  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
11542  * retransmission after a timeout.
11543  *
11544  * To limit the number of duplicate segments, we limit the number of segment
11545  * to be sent in one time to tcp_snd_burst, the burst variable.
11546  */
11547 static void
11548 tcp_ss_rexmit(tcp_t *tcp)
11549 {
11550 	uint32_t	snxt;
11551 	uint32_t	smax;
11552 	int32_t		win;
11553 	int32_t		mss;
11554 	int32_t		off;
11555 	int32_t		burst = tcp->tcp_snd_burst;
11556 	mblk_t		*snxt_mp;
11557 
11558 	/*
11559 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
11560 	 * all unack'ed segments.
11561 	 */
11562 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
11563 		smax = tcp->tcp_rexmit_max;
11564 		snxt = tcp->tcp_rexmit_nxt;
11565 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
11566 			snxt = tcp->tcp_suna;
11567 		}
11568 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
11569 		win -= snxt - tcp->tcp_suna;
11570 		mss = tcp->tcp_mss;
11571 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
11572 
11573 		while (SEQ_LT(snxt, smax) && (win > 0) &&
11574 		    (burst > 0) && (snxt_mp != NULL)) {
11575 			mblk_t	*xmit_mp;
11576 			mblk_t	*old_snxt_mp = snxt_mp;
11577 			uint32_t cnt = mss;
11578 
11579 			if (win < cnt) {
11580 				cnt = win;
11581 			}
11582 			if (SEQ_GT(snxt + cnt, smax)) {
11583 				cnt = smax - snxt;
11584 			}
11585 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
11586 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
11587 			if (xmit_mp == NULL)
11588 				return;
11589 
11590 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11591 
11592 			snxt += cnt;
11593 			win -= cnt;
11594 			/*
11595 			 * Update the send timestamp to avoid false
11596 			 * retransmission.
11597 			 */
11598 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
11599 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
11600 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
11601 
11602 			tcp->tcp_rexmit_nxt = snxt;
11603 			burst--;
11604 		}
11605 		/*
11606 		 * If we have transmitted all we have at the time
11607 		 * we started the retranmission, we can leave
11608 		 * the rest of the job to tcp_wput_data().  But we
11609 		 * need to check the send window first.  If the
11610 		 * win is not 0, go on with tcp_wput_data().
11611 		 */
11612 		if (SEQ_LT(snxt, smax) || win == 0) {
11613 			return;
11614 		}
11615 	}
11616 	/* Only call tcp_wput_data() if there is data to be sent. */
11617 	if (tcp->tcp_unsent) {
11618 		tcp_wput_data(tcp, NULL, B_FALSE);
11619 	}
11620 }
11621 
11622 /*
11623  * Process all TCP option in SYN segment.  Note that this function should
11624  * be called after tcp_adapt_ire() is called so that the necessary info
11625  * from IRE is already set in the tcp structure.
11626  *
11627  * This function sets up the correct tcp_mss value according to the
11628  * MSS option value and our header size.  It also sets up the window scale
11629  * and timestamp values, and initialize SACK info blocks.  But it does not
11630  * change receive window size after setting the tcp_mss value.  The caller
11631  * should do the appropriate change.
11632  */
11633 void
11634 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
11635 {
11636 	int options;
11637 	tcp_opt_t tcpopt;
11638 	uint32_t mss_max;
11639 	char *tmp_tcph;
11640 
11641 	tcpopt.tcp = NULL;
11642 	options = tcp_parse_options(tcph, &tcpopt);
11643 
11644 	/*
11645 	 * Process MSS option.  Note that MSS option value does not account
11646 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
11647 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
11648 	 * IPv6.
11649 	 */
11650 	if (!(options & TCP_OPT_MSS_PRESENT)) {
11651 		if (tcp->tcp_ipversion == IPV4_VERSION)
11652 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
11653 		else
11654 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
11655 	} else {
11656 		if (tcp->tcp_ipversion == IPV4_VERSION)
11657 			mss_max = tcp_mss_max_ipv4;
11658 		else
11659 			mss_max = tcp_mss_max_ipv6;
11660 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
11661 			tcpopt.tcp_opt_mss = tcp_mss_min;
11662 		else if (tcpopt.tcp_opt_mss > mss_max)
11663 			tcpopt.tcp_opt_mss = mss_max;
11664 	}
11665 
11666 	/* Process Window Scale option. */
11667 	if (options & TCP_OPT_WSCALE_PRESENT) {
11668 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
11669 		tcp->tcp_snd_ws_ok = B_TRUE;
11670 	} else {
11671 		tcp->tcp_snd_ws = B_FALSE;
11672 		tcp->tcp_snd_ws_ok = B_FALSE;
11673 		tcp->tcp_rcv_ws = B_FALSE;
11674 	}
11675 
11676 	/* Process Timestamp option. */
11677 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
11678 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
11679 		tmp_tcph = (char *)tcp->tcp_tcph;
11680 
11681 		tcp->tcp_snd_ts_ok = B_TRUE;
11682 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
11683 		tcp->tcp_last_rcv_lbolt = lbolt64;
11684 		ASSERT(OK_32PTR(tmp_tcph));
11685 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
11686 
11687 		/* Fill in our template header with basic timestamp option. */
11688 		tmp_tcph += tcp->tcp_tcp_hdr_len;
11689 		tmp_tcph[0] = TCPOPT_NOP;
11690 		tmp_tcph[1] = TCPOPT_NOP;
11691 		tmp_tcph[2] = TCPOPT_TSTAMP;
11692 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
11693 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
11694 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
11695 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
11696 	} else {
11697 		tcp->tcp_snd_ts_ok = B_FALSE;
11698 	}
11699 
11700 	/*
11701 	 * Process SACK options.  If SACK is enabled for this connection,
11702 	 * then allocate the SACK info structure.  Note the following ways
11703 	 * when tcp_snd_sack_ok is set to true.
11704 	 *
11705 	 * For active connection: in tcp_adapt_ire() called in
11706 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
11707 	 * is checked.
11708 	 *
11709 	 * For passive connection: in tcp_adapt_ire() called in
11710 	 * tcp_accept_comm().
11711 	 *
11712 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
11713 	 * That check makes sure that if we did not send a SACK OK option,
11714 	 * we will not enable SACK for this connection even though the other
11715 	 * side sends us SACK OK option.  For active connection, the SACK
11716 	 * info structure has already been allocated.  So we need to free
11717 	 * it if SACK is disabled.
11718 	 */
11719 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
11720 	    (tcp->tcp_snd_sack_ok ||
11721 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
11722 		/* This should be true only in the passive case. */
11723 		if (tcp->tcp_sack_info == NULL) {
11724 			ASSERT(TCP_IS_DETACHED(tcp));
11725 			tcp->tcp_sack_info =
11726 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
11727 		}
11728 		if (tcp->tcp_sack_info == NULL) {
11729 			tcp->tcp_snd_sack_ok = B_FALSE;
11730 		} else {
11731 			tcp->tcp_snd_sack_ok = B_TRUE;
11732 			if (tcp->tcp_snd_ts_ok) {
11733 				tcp->tcp_max_sack_blk = 3;
11734 			} else {
11735 				tcp->tcp_max_sack_blk = 4;
11736 			}
11737 		}
11738 	} else {
11739 		/*
11740 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
11741 		 * no SACK info will be used for this
11742 		 * connection.  This assumes that SACK usage
11743 		 * permission is negotiated.  This may need
11744 		 * to be changed once this is clarified.
11745 		 */
11746 		if (tcp->tcp_sack_info != NULL) {
11747 			ASSERT(tcp->tcp_notsack_list == NULL);
11748 			kmem_cache_free(tcp_sack_info_cache,
11749 			    tcp->tcp_sack_info);
11750 			tcp->tcp_sack_info = NULL;
11751 		}
11752 		tcp->tcp_snd_sack_ok = B_FALSE;
11753 	}
11754 
11755 	/*
11756 	 * Now we know the exact TCP/IP header length, subtract
11757 	 * that from tcp_mss to get our side's MSS.
11758 	 */
11759 	tcp->tcp_mss -= tcp->tcp_hdr_len;
11760 	/*
11761 	 * Here we assume that the other side's header size will be equal to
11762 	 * our header size.  We calculate the real MSS accordingly.  Need to
11763 	 * take into additional stuffs IPsec puts in.
11764 	 *
11765 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
11766 	 */
11767 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
11768 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
11769 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
11770 
11771 	/*
11772 	 * Set MSS to the smaller one of both ends of the connection.
11773 	 * We should not have called tcp_mss_set() before, but our
11774 	 * side of the MSS should have been set to a proper value
11775 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
11776 	 * STREAM head parameters properly.
11777 	 *
11778 	 * If we have a larger-than-16-bit window but the other side
11779 	 * didn't want to do window scale, tcp_rwnd_set() will take
11780 	 * care of that.
11781 	 */
11782 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
11783 }
11784 
11785 /*
11786  * Sends the T_CONN_IND to the listener. The caller calls this
11787  * functions via squeue to get inside the listener's perimeter
11788  * once the 3 way hand shake is done a T_CONN_IND needs to be
11789  * sent. As an optimization, the caller can call this directly
11790  * if listener's perimeter is same as eager's.
11791  */
11792 /* ARGSUSED */
11793 void
11794 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
11795 {
11796 	conn_t			*lconnp = (conn_t *)arg;
11797 	tcp_t			*listener = lconnp->conn_tcp;
11798 	tcp_t			*tcp;
11799 	struct T_conn_ind	*conn_ind;
11800 	ipaddr_t 		*addr_cache;
11801 	boolean_t		need_send_conn_ind = B_FALSE;
11802 
11803 	/* retrieve the eager */
11804 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
11805 	ASSERT(conn_ind->OPT_offset != 0 &&
11806 	    conn_ind->OPT_length == sizeof (intptr_t));
11807 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
11808 		conn_ind->OPT_length);
11809 
11810 	/*
11811 	 * TLI/XTI applications will get confused by
11812 	 * sending eager as an option since it violates
11813 	 * the option semantics. So remove the eager as
11814 	 * option since TLI/XTI app doesn't need it anyway.
11815 	 */
11816 	if (!TCP_IS_SOCKET(listener)) {
11817 		conn_ind->OPT_length = 0;
11818 		conn_ind->OPT_offset = 0;
11819 	}
11820 	if (listener->tcp_state == TCPS_CLOSED ||
11821 	    TCP_IS_DETACHED(listener)) {
11822 		/*
11823 		 * If listener has closed, it would have caused a
11824 		 * a cleanup/blowoff to happen for the eager. We
11825 		 * just need to return.
11826 		 */
11827 		freemsg(mp);
11828 		return;
11829 	}
11830 
11831 
11832 	/*
11833 	 * if the conn_req_q is full defer passing up the
11834 	 * T_CONN_IND until space is availabe after t_accept()
11835 	 * processing
11836 	 */
11837 	mutex_enter(&listener->tcp_eager_lock);
11838 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
11839 		tcp_t *tail;
11840 
11841 		/*
11842 		 * The eager already has an extra ref put in tcp_rput_data
11843 		 * so that it stays till accept comes back even though it
11844 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
11845 		 */
11846 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
11847 		listener->tcp_conn_req_cnt_q0--;
11848 		listener->tcp_conn_req_cnt_q++;
11849 
11850 		/* Move from SYN_RCVD to ESTABLISHED list  */
11851 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
11852 		    tcp->tcp_eager_prev_q0;
11853 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
11854 		    tcp->tcp_eager_next_q0;
11855 		tcp->tcp_eager_prev_q0 = NULL;
11856 		tcp->tcp_eager_next_q0 = NULL;
11857 
11858 		/*
11859 		 * Insert at end of the queue because sockfs
11860 		 * sends down T_CONN_RES in chronological
11861 		 * order. Leaving the older conn indications
11862 		 * at front of the queue helps reducing search
11863 		 * time.
11864 		 */
11865 		tail = listener->tcp_eager_last_q;
11866 		if (tail != NULL)
11867 			tail->tcp_eager_next_q = tcp;
11868 		else
11869 			listener->tcp_eager_next_q = tcp;
11870 		listener->tcp_eager_last_q = tcp;
11871 		tcp->tcp_eager_next_q = NULL;
11872 		/*
11873 		 * Delay sending up the T_conn_ind until we are
11874 		 * done with the eager. Once we have have sent up
11875 		 * the T_conn_ind, the accept can potentially complete
11876 		 * any time and release the refhold we have on the eager.
11877 		 */
11878 		need_send_conn_ind = B_TRUE;
11879 	} else {
11880 		/*
11881 		 * Defer connection on q0 and set deferred
11882 		 * connection bit true
11883 		 */
11884 		tcp->tcp_conn_def_q0 = B_TRUE;
11885 
11886 		/* take tcp out of q0 ... */
11887 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
11888 		    tcp->tcp_eager_next_q0;
11889 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
11890 		    tcp->tcp_eager_prev_q0;
11891 
11892 		/* ... and place it at the end of q0 */
11893 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
11894 		tcp->tcp_eager_next_q0 = listener;
11895 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
11896 		listener->tcp_eager_prev_q0 = tcp;
11897 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
11898 	}
11899 
11900 	/* we have timed out before */
11901 	if (tcp->tcp_syn_rcvd_timeout != 0) {
11902 		tcp->tcp_syn_rcvd_timeout = 0;
11903 		listener->tcp_syn_rcvd_timeout--;
11904 		if (listener->tcp_syn_defense &&
11905 		    listener->tcp_syn_rcvd_timeout <=
11906 		    (tcp_conn_req_max_q0 >> 5) &&
11907 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
11908 			listener->tcp_last_rcv_lbolt)) {
11909 			/*
11910 			 * Turn off the defense mode if we
11911 			 * believe the SYN attack is over.
11912 			 */
11913 			listener->tcp_syn_defense = B_FALSE;
11914 			if (listener->tcp_ip_addr_cache) {
11915 				kmem_free((void *)listener->tcp_ip_addr_cache,
11916 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
11917 				listener->tcp_ip_addr_cache = NULL;
11918 			}
11919 		}
11920 	}
11921 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
11922 	if (addr_cache != NULL) {
11923 		/*
11924 		 * We have finished a 3-way handshake with this
11925 		 * remote host. This proves the IP addr is good.
11926 		 * Cache it!
11927 		 */
11928 		addr_cache[IP_ADDR_CACHE_HASH(
11929 			tcp->tcp_remote)] = tcp->tcp_remote;
11930 	}
11931 	mutex_exit(&listener->tcp_eager_lock);
11932 	if (need_send_conn_ind)
11933 		putnext(listener->tcp_rq, mp);
11934 }
11935 
11936 mblk_t *
11937 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
11938     uint_t *ifindexp, ip6_pkt_t *ippp)
11939 {
11940 	in_pktinfo_t	*pinfo;
11941 	ip6_t		*ip6h;
11942 	uchar_t		*rptr;
11943 	mblk_t		*first_mp = mp;
11944 	boolean_t	mctl_present = B_FALSE;
11945 	uint_t 		ifindex = 0;
11946 	ip6_pkt_t	ipp;
11947 	uint_t		ipvers;
11948 	uint_t		ip_hdr_len;
11949 
11950 	rptr = mp->b_rptr;
11951 	ASSERT(OK_32PTR(rptr));
11952 	ASSERT(tcp != NULL);
11953 	ipp.ipp_fields = 0;
11954 
11955 	switch DB_TYPE(mp) {
11956 	case M_CTL:
11957 		mp = mp->b_cont;
11958 		if (mp == NULL) {
11959 			freemsg(first_mp);
11960 			return (NULL);
11961 		}
11962 		if (DB_TYPE(mp) != M_DATA) {
11963 			freemsg(first_mp);
11964 			return (NULL);
11965 		}
11966 		mctl_present = B_TRUE;
11967 		break;
11968 	case M_DATA:
11969 		break;
11970 	default:
11971 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
11972 		freemsg(mp);
11973 		return (NULL);
11974 	}
11975 	ipvers = IPH_HDR_VERSION(rptr);
11976 	if (ipvers == IPV4_VERSION) {
11977 		if (tcp == NULL) {
11978 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
11979 			goto done;
11980 		}
11981 
11982 		ipp.ipp_fields |= IPPF_HOPLIMIT;
11983 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
11984 
11985 		/*
11986 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
11987 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
11988 		 */
11989 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
11990 		    mctl_present) {
11991 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
11992 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
11993 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
11994 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
11995 				ipp.ipp_fields |= IPPF_IFINDEX;
11996 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
11997 				ifindex = pinfo->in_pkt_ifindex;
11998 			}
11999 			freeb(first_mp);
12000 			mctl_present = B_FALSE;
12001 		}
12002 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12003 	} else {
12004 		ip6h = (ip6_t *)rptr;
12005 
12006 		ASSERT(ipvers == IPV6_VERSION);
12007 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12008 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12009 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12010 
12011 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12012 			uint8_t	nexthdrp;
12013 
12014 			/* Look for ifindex information */
12015 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12016 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12017 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12018 					BUMP_MIB(&ip_mib, tcpInErrs);
12019 					freemsg(first_mp);
12020 					return (NULL);
12021 				}
12022 
12023 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12024 					ASSERT(ip6i->ip6i_ifindex != 0);
12025 					ipp.ipp_fields |= IPPF_IFINDEX;
12026 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12027 					ifindex = ip6i->ip6i_ifindex;
12028 				}
12029 				rptr = (uchar_t *)&ip6i[1];
12030 				mp->b_rptr = rptr;
12031 				if (rptr == mp->b_wptr) {
12032 					mblk_t *mp1;
12033 					mp1 = mp->b_cont;
12034 					freeb(mp);
12035 					mp = mp1;
12036 					rptr = mp->b_rptr;
12037 				}
12038 				if (MBLKL(mp) < IPV6_HDR_LEN +
12039 				    sizeof (tcph_t)) {
12040 					BUMP_MIB(&ip_mib, tcpInErrs);
12041 					freemsg(first_mp);
12042 					return (NULL);
12043 				}
12044 				ip6h = (ip6_t *)rptr;
12045 			}
12046 
12047 			/*
12048 			 * Find any potentially interesting extension headers
12049 			 * as well as the length of the IPv6 + extension
12050 			 * headers.
12051 			 */
12052 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12053 			/* Verify if this is a TCP packet */
12054 			if (nexthdrp != IPPROTO_TCP) {
12055 				BUMP_MIB(&ip_mib, tcpInErrs);
12056 				freemsg(first_mp);
12057 				return (NULL);
12058 			}
12059 		} else {
12060 			ip_hdr_len = IPV6_HDR_LEN;
12061 		}
12062 	}
12063 
12064 done:
12065 	if (ipversp != NULL)
12066 		*ipversp = ipvers;
12067 	if (ip_hdr_lenp != NULL)
12068 		*ip_hdr_lenp = ip_hdr_len;
12069 	if (ippp != NULL)
12070 		*ippp = ipp;
12071 	if (ifindexp != NULL)
12072 		*ifindexp = ifindex;
12073 	if (mctl_present) {
12074 		freeb(first_mp);
12075 	}
12076 	return (mp);
12077 }
12078 
12079 /*
12080  * Handle M_DATA messages from IP. Its called directly from IP via
12081  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12082  * in this path.
12083  *
12084  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12085  * v4 and v6), we are called through tcp_input() and a M_CTL can
12086  * be present for options but tcp_find_pktinfo() deals with it. We
12087  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12088  *
12089  * The first argument is always the connp/tcp to which the mp belongs.
12090  * There are no exceptions to this rule. The caller has already put
12091  * a reference on this connp/tcp and once tcp_rput_data() returns,
12092  * the squeue will do the refrele.
12093  *
12094  * The TH_SYN for the listener directly go to tcp_conn_request via
12095  * squeue.
12096  *
12097  * sqp: NULL = recursive, sqp != NULL means called from squeue
12098  */
12099 void
12100 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12101 {
12102 	int32_t		bytes_acked;
12103 	int32_t		gap;
12104 	mblk_t		*mp1;
12105 	uint_t		flags;
12106 	uint32_t	new_swnd = 0;
12107 	uchar_t		*iphdr;
12108 	uchar_t		*rptr;
12109 	int32_t		rgap;
12110 	uint32_t	seg_ack;
12111 	int		seg_len;
12112 	uint_t		ip_hdr_len;
12113 	uint32_t	seg_seq;
12114 	tcph_t		*tcph;
12115 	int		urp;
12116 	tcp_opt_t	tcpopt;
12117 	uint_t		ipvers;
12118 	ip6_pkt_t	ipp;
12119 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12120 	uint32_t	cwnd;
12121 	uint32_t	add;
12122 	int		npkt;
12123 	int		mss;
12124 	conn_t		*connp = (conn_t *)arg;
12125 	squeue_t	*sqp = (squeue_t *)arg2;
12126 	tcp_t		*tcp = connp->conn_tcp;
12127 
12128 	/*
12129 	 * RST from fused tcp loopback peer should trigger an unfuse.
12130 	 */
12131 	if (tcp->tcp_fused) {
12132 		TCP_STAT(tcp_fusion_aborted);
12133 		tcp_unfuse(tcp);
12134 	}
12135 
12136 	iphdr = mp->b_rptr;
12137 	rptr = mp->b_rptr;
12138 	ASSERT(OK_32PTR(rptr));
12139 
12140 	/*
12141 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12142 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12143 	 * necessary information.
12144 	 */
12145 	if (IPCL_IS_TCP4(connp)) {
12146 		ipvers = IPV4_VERSION;
12147 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12148 	} else {
12149 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12150 		    NULL, &ipp);
12151 		if (mp == NULL) {
12152 			TCP_STAT(tcp_rput_v6_error);
12153 			return;
12154 		}
12155 		iphdr = mp->b_rptr;
12156 		rptr = mp->b_rptr;
12157 	}
12158 	ASSERT(DB_TYPE(mp) == M_DATA);
12159 
12160 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12161 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12162 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12163 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12164 	seg_len = (int)(mp->b_wptr - rptr) -
12165 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12166 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12167 		do {
12168 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12169 			    (uintptr_t)INT_MAX);
12170 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12171 		} while ((mp1 = mp1->b_cont) != NULL &&
12172 		    mp1->b_datap->db_type == M_DATA);
12173 	}
12174 
12175 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12176 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12177 		    seg_len, tcph);
12178 		return;
12179 	}
12180 
12181 	if (sqp != NULL) {
12182 		/*
12183 		 * This is the correct place to update tcp_last_recv_time. Note
12184 		 * that it is also updated for tcp structure that belongs to
12185 		 * global and listener queues which do not really need updating.
12186 		 * But that should not cause any harm.  And it is updated for
12187 		 * all kinds of incoming segments, not only for data segments.
12188 		 */
12189 		tcp->tcp_last_recv_time = lbolt;
12190 	}
12191 
12192 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12193 
12194 	BUMP_LOCAL(tcp->tcp_ibsegs);
12195 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12196 
12197 	if ((flags & TH_URG) && sqp != NULL) {
12198 		/*
12199 		 * TCP can't handle urgent pointers that arrive before
12200 		 * the connection has been accept()ed since it can't
12201 		 * buffer OOB data.  Discard segment if this happens.
12202 		 *
12203 		 * Nor can it reassemble urgent pointers, so discard
12204 		 * if it's not the next segment expected.
12205 		 *
12206 		 * Otherwise, collapse chain into one mblk (discard if
12207 		 * that fails).  This makes sure the headers, retransmitted
12208 		 * data, and new data all are in the same mblk.
12209 		 */
12210 		ASSERT(mp != NULL);
12211 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
12212 			freemsg(mp);
12213 			return;
12214 		}
12215 		/* Update pointers into message */
12216 		iphdr = rptr = mp->b_rptr;
12217 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12218 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12219 			/*
12220 			 * Since we can't handle any data with this urgent
12221 			 * pointer that is out of sequence, we expunge
12222 			 * the data.  This allows us to still register
12223 			 * the urgent mark and generate the M_PCSIG,
12224 			 * which we can do.
12225 			 */
12226 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12227 			seg_len = 0;
12228 		}
12229 	}
12230 
12231 	switch (tcp->tcp_state) {
12232 	case TCPS_SYN_SENT:
12233 		if (flags & TH_ACK) {
12234 			/*
12235 			 * Note that our stack cannot send data before a
12236 			 * connection is established, therefore the
12237 			 * following check is valid.  Otherwise, it has
12238 			 * to be changed.
12239 			 */
12240 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12241 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12242 				freemsg(mp);
12243 				if (flags & TH_RST)
12244 					return;
12245 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12246 				    tcp, seg_ack, 0, TH_RST);
12247 				return;
12248 			}
12249 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12250 		}
12251 		if (flags & TH_RST) {
12252 			freemsg(mp);
12253 			if (flags & TH_ACK)
12254 				(void) tcp_clean_death(tcp,
12255 				    ECONNREFUSED, 13);
12256 			return;
12257 		}
12258 		if (!(flags & TH_SYN)) {
12259 			freemsg(mp);
12260 			return;
12261 		}
12262 
12263 		/* Process all TCP options. */
12264 		tcp_process_options(tcp, tcph);
12265 		/*
12266 		 * The following changes our rwnd to be a multiple of the
12267 		 * MIN(peer MSS, our MSS) for performance reason.
12268 		 */
12269 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12270 		    tcp->tcp_mss));
12271 
12272 		/* Is the other end ECN capable? */
12273 		if (tcp->tcp_ecn_ok) {
12274 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12275 				tcp->tcp_ecn_ok = B_FALSE;
12276 			}
12277 		}
12278 		/*
12279 		 * Clear ECN flags because it may interfere with later
12280 		 * processing.
12281 		 */
12282 		flags &= ~(TH_ECE|TH_CWR);
12283 
12284 		tcp->tcp_irs = seg_seq;
12285 		tcp->tcp_rack = seg_seq;
12286 		tcp->tcp_rnxt = seg_seq + 1;
12287 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12288 		if (!TCP_IS_DETACHED(tcp)) {
12289 			/* Allocate room for SACK options if needed. */
12290 			if (tcp->tcp_snd_sack_ok) {
12291 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12292 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
12293 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12294 			} else {
12295 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12296 				    tcp->tcp_hdr_len +
12297 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12298 			}
12299 		}
12300 		if (flags & TH_ACK) {
12301 			/*
12302 			 * If we can't get the confirmation upstream, pretend
12303 			 * we didn't even see this one.
12304 			 *
12305 			 * XXX: how can we pretend we didn't see it if we
12306 			 * have updated rnxt et. al.
12307 			 *
12308 			 * For loopback we defer sending up the T_CONN_CON
12309 			 * until after some checks below.
12310 			 */
12311 			mp1 = NULL;
12312 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12313 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12314 				freemsg(mp);
12315 				return;
12316 			}
12317 			/* SYN was acked - making progress */
12318 			if (tcp->tcp_ipversion == IPV6_VERSION)
12319 				tcp->tcp_ip_forward_progress = B_TRUE;
12320 
12321 			/* One for the SYN */
12322 			tcp->tcp_suna = tcp->tcp_iss + 1;
12323 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12324 			tcp->tcp_state = TCPS_ESTABLISHED;
12325 
12326 			/*
12327 			 * If SYN was retransmitted, need to reset all
12328 			 * retransmission info.  This is because this
12329 			 * segment will be treated as a dup ACK.
12330 			 */
12331 			if (tcp->tcp_rexmit) {
12332 				tcp->tcp_rexmit = B_FALSE;
12333 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12334 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12335 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12336 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12337 				tcp->tcp_ms_we_have_waited = 0;
12338 
12339 				/*
12340 				 * Set tcp_cwnd back to 1 MSS, per
12341 				 * recommendation from
12342 				 * draft-floyd-incr-init-win-01.txt,
12343 				 * Increasing TCP's Initial Window.
12344 				 */
12345 				tcp->tcp_cwnd = tcp->tcp_mss;
12346 			}
12347 
12348 			tcp->tcp_swl1 = seg_seq;
12349 			tcp->tcp_swl2 = seg_ack;
12350 
12351 			new_swnd = BE16_TO_U16(tcph->th_win);
12352 			tcp->tcp_swnd = new_swnd;
12353 			if (new_swnd > tcp->tcp_max_swnd)
12354 				tcp->tcp_max_swnd = new_swnd;
12355 
12356 			/*
12357 			 * Always send the three-way handshake ack immediately
12358 			 * in order to make the connection complete as soon as
12359 			 * possible on the accepting host.
12360 			 */
12361 			flags |= TH_ACK_NEEDED;
12362 
12363 			/*
12364 			 * Special case for loopback.  At this point we have
12365 			 * received SYN-ACK from the remote endpoint.  In
12366 			 * order to ensure that both endpoints reach the
12367 			 * fused state prior to any data exchange, the final
12368 			 * ACK needs to be sent before we indicate T_CONN_CON
12369 			 * to the module upstream.
12370 			 */
12371 			if (tcp->tcp_loopback) {
12372 				mblk_t *ack_mp;
12373 
12374 				ASSERT(!tcp->tcp_unfusable);
12375 				ASSERT(mp1 != NULL);
12376 				/*
12377 				 * For loopback, we always get a pure SYN-ACK
12378 				 * and only need to send back the final ACK
12379 				 * with no data (this is because the other
12380 				 * tcp is ours and we don't do T/TCP).  This
12381 				 * final ACK triggers the passive side to
12382 				 * perform fusion in ESTABLISHED state.
12383 				 */
12384 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12385 					if (tcp->tcp_ack_tid != 0) {
12386 						(void) TCP_TIMER_CANCEL(tcp,
12387 						    tcp->tcp_ack_tid);
12388 						tcp->tcp_ack_tid = 0;
12389 					}
12390 					TCP_RECORD_TRACE(tcp, ack_mp,
12391 					    TCP_TRACE_SEND_PKT);
12392 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
12393 					BUMP_LOCAL(tcp->tcp_obsegs);
12394 					BUMP_MIB(&tcp_mib, tcpOutAck);
12395 
12396 					/* Send up T_CONN_CON */
12397 					putnext(tcp->tcp_rq, mp1);
12398 
12399 					freemsg(mp);
12400 					return;
12401 				}
12402 				/*
12403 				 * Forget fusion; we need to handle more
12404 				 * complex cases below.  Send the deferred
12405 				 * T_CONN_CON message upstream and proceed
12406 				 * as usual.  Mark this tcp as not capable
12407 				 * of fusion.
12408 				 */
12409 				TCP_STAT(tcp_fusion_unfusable);
12410 				tcp->tcp_unfusable = B_TRUE;
12411 				putnext(tcp->tcp_rq, mp1);
12412 			}
12413 
12414 			/*
12415 			 * Check to see if there is data to be sent.  If
12416 			 * yes, set the transmit flag.  Then check to see
12417 			 * if received data processing needs to be done.
12418 			 * If not, go straight to xmit_check.  This short
12419 			 * cut is OK as we don't support T/TCP.
12420 			 */
12421 			if (tcp->tcp_unsent)
12422 				flags |= TH_XMIT_NEEDED;
12423 
12424 			if (seg_len == 0 && !(flags & TH_URG)) {
12425 				freemsg(mp);
12426 				goto xmit_check;
12427 			}
12428 
12429 			flags &= ~TH_SYN;
12430 			seg_seq++;
12431 			break;
12432 		}
12433 		tcp->tcp_state = TCPS_SYN_RCVD;
12434 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
12435 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
12436 		if (mp1) {
12437 			mblk_setcred(mp1, tcp->tcp_cred);
12438 			DB_CPID(mp1) = tcp->tcp_cpid;
12439 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
12440 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
12441 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12442 		}
12443 		freemsg(mp);
12444 		return;
12445 	case TCPS_SYN_RCVD:
12446 		if (flags & TH_ACK) {
12447 			/*
12448 			 * In this state, a SYN|ACK packet is either bogus
12449 			 * because the other side must be ACKing our SYN which
12450 			 * indicates it has seen the ACK for their SYN and
12451 			 * shouldn't retransmit it or we're crossing SYNs
12452 			 * on active open.
12453 			 */
12454 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
12455 				freemsg(mp);
12456 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
12457 				    tcp, seg_ack, 0, TH_RST);
12458 				return;
12459 			}
12460 			/*
12461 			 * NOTE: RFC 793 pg. 72 says this should be
12462 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
12463 			 * but that would mean we have an ack that ignored
12464 			 * our SYN.
12465 			 */
12466 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
12467 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12468 				freemsg(mp);
12469 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
12470 				    tcp, seg_ack, 0, TH_RST);
12471 				return;
12472 			}
12473 		}
12474 		break;
12475 	case TCPS_LISTEN:
12476 		/*
12477 		 * Only a TLI listener can come through this path when a
12478 		 * acceptor is going back to be a listener and a packet
12479 		 * for the acceptor hits the classifier. For a socket
12480 		 * listener, this can never happen because a listener
12481 		 * can never accept connection on itself and hence a
12482 		 * socket acceptor can not go back to being a listener.
12483 		 */
12484 		ASSERT(!TCP_IS_SOCKET(tcp));
12485 		/*FALLTHRU*/
12486 	case TCPS_CLOSED:
12487 	case TCPS_BOUND: {
12488 		conn_t	*new_connp;
12489 
12490 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
12491 		if (new_connp != NULL) {
12492 			tcp_reinput(new_connp, mp, connp->conn_sqp);
12493 			return;
12494 		}
12495 		/* We failed to classify. For now just drop the packet */
12496 		freemsg(mp);
12497 		return;
12498 	}
12499 	case TCPS_IDLE:
12500 		/*
12501 		 * Handle the case where the tcp_clean_death() has happened
12502 		 * on a connection (application hasn't closed yet) but a packet
12503 		 * was already queued on squeue before tcp_clean_death()
12504 		 * was processed. Calling tcp_clean_death() twice on same
12505 		 * connection can result in weird behaviour.
12506 		 */
12507 		freemsg(mp);
12508 		return;
12509 	default:
12510 		break;
12511 	}
12512 
12513 	/*
12514 	 * Already on the correct queue/perimeter.
12515 	 * If this is a detached connection and not an eager
12516 	 * connection hanging off a listener then new data
12517 	 * (past the FIN) will cause a reset.
12518 	 * We do a special check here where it
12519 	 * is out of the main line, rather than check
12520 	 * if we are detached every time we see new
12521 	 * data down below.
12522 	 */
12523 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
12524 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
12525 		BUMP_MIB(&tcp_mib, tcpInClosed);
12526 		TCP_RECORD_TRACE(tcp,
12527 		    mp, TCP_TRACE_RECV_PKT);
12528 		freemsg(mp);
12529 		tcp_xmit_ctl("new data when detached", tcp,
12530 		    tcp->tcp_snxt, 0, TH_RST);
12531 		(void) tcp_clean_death(tcp, EPROTO, 12);
12532 		return;
12533 	}
12534 
12535 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12536 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
12537 	new_swnd = BE16_TO_U16(tcph->th_win) <<
12538 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
12539 	mss = tcp->tcp_mss;
12540 
12541 	if (tcp->tcp_snd_ts_ok) {
12542 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
12543 			/*
12544 			 * This segment is not acceptable.
12545 			 * Drop it and send back an ACK.
12546 			 */
12547 			freemsg(mp);
12548 			flags |= TH_ACK_NEEDED;
12549 			goto ack_check;
12550 		}
12551 	} else if (tcp->tcp_snd_sack_ok) {
12552 		ASSERT(tcp->tcp_sack_info != NULL);
12553 		tcpopt.tcp = tcp;
12554 		/*
12555 		 * SACK info in already updated in tcp_parse_options.  Ignore
12556 		 * all other TCP options...
12557 		 */
12558 		(void) tcp_parse_options(tcph, &tcpopt);
12559 	}
12560 try_again:;
12561 	gap = seg_seq - tcp->tcp_rnxt;
12562 	rgap = tcp->tcp_rwnd - (gap + seg_len);
12563 	/*
12564 	 * gap is the amount of sequence space between what we expect to see
12565 	 * and what we got for seg_seq.  A positive value for gap means
12566 	 * something got lost.  A negative value means we got some old stuff.
12567 	 */
12568 	if (gap < 0) {
12569 		/* Old stuff present.  Is the SYN in there? */
12570 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
12571 		    (seg_len != 0)) {
12572 			flags &= ~TH_SYN;
12573 			seg_seq++;
12574 			urp--;
12575 			/* Recompute the gaps after noting the SYN. */
12576 			goto try_again;
12577 		}
12578 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
12579 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
12580 		    (seg_len > -gap ? -gap : seg_len));
12581 		/* Remove the old stuff from seg_len. */
12582 		seg_len += gap;
12583 		/*
12584 		 * Anything left?
12585 		 * Make sure to check for unack'd FIN when rest of data
12586 		 * has been previously ack'd.
12587 		 */
12588 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
12589 			/*
12590 			 * Resets are only valid if they lie within our offered
12591 			 * window.  If the RST bit is set, we just ignore this
12592 			 * segment.
12593 			 */
12594 			if (flags & TH_RST) {
12595 				freemsg(mp);
12596 				return;
12597 			}
12598 
12599 			/*
12600 			 * The arriving of dup data packets indicate that we
12601 			 * may have postponed an ack for too long, or the other
12602 			 * side's RTT estimate is out of shape. Start acking
12603 			 * more often.
12604 			 */
12605 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
12606 			    tcp->tcp_rack_cnt >= 1 &&
12607 			    tcp->tcp_rack_abs_max > 2) {
12608 				tcp->tcp_rack_abs_max--;
12609 			}
12610 			tcp->tcp_rack_cur_max = 1;
12611 
12612 			/*
12613 			 * This segment is "unacceptable".  None of its
12614 			 * sequence space lies within our advertized window.
12615 			 *
12616 			 * Adjust seg_len to the original value for tracing.
12617 			 */
12618 			seg_len -= gap;
12619 			if (tcp->tcp_debug) {
12620 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12621 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
12622 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
12623 				    "seg_len %d, rnxt %u, snxt %u, %s",
12624 				    gap, rgap, flags, seg_seq, seg_ack,
12625 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
12626 				    tcp_display(tcp, NULL,
12627 				    DISP_ADDR_AND_PORT));
12628 			}
12629 
12630 			/*
12631 			 * Arrange to send an ACK in response to the
12632 			 * unacceptable segment per RFC 793 page 69. There
12633 			 * is only one small difference between ours and the
12634 			 * acceptability test in the RFC - we accept ACK-only
12635 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
12636 			 * will be generated.
12637 			 *
12638 			 * Note that we have to ACK an ACK-only packet at least
12639 			 * for stacks that send 0-length keep-alives with
12640 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
12641 			 * section 4.2.3.6. As long as we don't ever generate
12642 			 * an unacceptable packet in response to an incoming
12643 			 * packet that is unacceptable, it should not cause
12644 			 * "ACK wars".
12645 			 */
12646 			flags |=  TH_ACK_NEEDED;
12647 
12648 			/*
12649 			 * Continue processing this segment in order to use the
12650 			 * ACK information it contains, but skip all other
12651 			 * sequence-number processing.	Processing the ACK
12652 			 * information is necessary in order to
12653 			 * re-synchronize connections that may have lost
12654 			 * synchronization.
12655 			 *
12656 			 * We clear seg_len and flag fields related to
12657 			 * sequence number processing as they are not
12658 			 * to be trusted for an unacceptable segment.
12659 			 */
12660 			seg_len = 0;
12661 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
12662 			goto process_ack;
12663 		}
12664 
12665 		/* Fix seg_seq, and chew the gap off the front. */
12666 		seg_seq = tcp->tcp_rnxt;
12667 		urp += gap;
12668 		do {
12669 			mblk_t	*mp2;
12670 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
12671 			    (uintptr_t)UINT_MAX);
12672 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
12673 			if (gap > 0) {
12674 				mp->b_rptr = mp->b_wptr - gap;
12675 				break;
12676 			}
12677 			mp2 = mp;
12678 			mp = mp->b_cont;
12679 			freeb(mp2);
12680 		} while (gap < 0);
12681 		/*
12682 		 * If the urgent data has already been acknowledged, we
12683 		 * should ignore TH_URG below
12684 		 */
12685 		if (urp < 0)
12686 			flags &= ~TH_URG;
12687 	}
12688 	/*
12689 	 * rgap is the amount of stuff received out of window.  A negative
12690 	 * value is the amount out of window.
12691 	 */
12692 	if (rgap < 0) {
12693 		mblk_t	*mp2;
12694 
12695 		if (tcp->tcp_rwnd == 0) {
12696 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
12697 		} else {
12698 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
12699 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
12700 		}
12701 
12702 		/*
12703 		 * seg_len does not include the FIN, so if more than
12704 		 * just the FIN is out of window, we act like we don't
12705 		 * see it.  (If just the FIN is out of window, rgap
12706 		 * will be zero and we will go ahead and acknowledge
12707 		 * the FIN.)
12708 		 */
12709 		flags &= ~TH_FIN;
12710 
12711 		/* Fix seg_len and make sure there is something left. */
12712 		seg_len += rgap;
12713 		if (seg_len <= 0) {
12714 			/*
12715 			 * Resets are only valid if they lie within our offered
12716 			 * window.  If the RST bit is set, we just ignore this
12717 			 * segment.
12718 			 */
12719 			if (flags & TH_RST) {
12720 				freemsg(mp);
12721 				return;
12722 			}
12723 
12724 			/* Per RFC 793, we need to send back an ACK. */
12725 			flags |= TH_ACK_NEEDED;
12726 
12727 			/*
12728 			 * Send SIGURG as soon as possible i.e. even
12729 			 * if the TH_URG was delivered in a window probe
12730 			 * packet (which will be unacceptable).
12731 			 *
12732 			 * We generate a signal if none has been generated
12733 			 * for this connection or if this is a new urgent
12734 			 * byte. Also send a zero-length "unmarked" message
12735 			 * to inform SIOCATMARK that this is not the mark.
12736 			 *
12737 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
12738 			 * is sent up. This plus the check for old data
12739 			 * (gap >= 0) handles the wraparound of the sequence
12740 			 * number space without having to always track the
12741 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
12742 			 * this max in its rcv_up variable).
12743 			 *
12744 			 * This prevents duplicate SIGURGS due to a "late"
12745 			 * zero-window probe when the T_EXDATA_IND has already
12746 			 * been sent up.
12747 			 */
12748 			if ((flags & TH_URG) &&
12749 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
12750 			    tcp->tcp_urp_last))) {
12751 				mp1 = allocb(0, BPRI_MED);
12752 				if (mp1 == NULL) {
12753 					freemsg(mp);
12754 					return;
12755 				}
12756 				if (!TCP_IS_DETACHED(tcp) &&
12757 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
12758 				    SIGURG)) {
12759 					/* Try again on the rexmit. */
12760 					freemsg(mp1);
12761 					freemsg(mp);
12762 					return;
12763 				}
12764 				/*
12765 				 * If the next byte would be the mark
12766 				 * then mark with MARKNEXT else mark
12767 				 * with NOTMARKNEXT.
12768 				 */
12769 				if (gap == 0 && urp == 0)
12770 					mp1->b_flag |= MSGMARKNEXT;
12771 				else
12772 					mp1->b_flag |= MSGNOTMARKNEXT;
12773 				freemsg(tcp->tcp_urp_mark_mp);
12774 				tcp->tcp_urp_mark_mp = mp1;
12775 				flags |= TH_SEND_URP_MARK;
12776 				tcp->tcp_urp_last_valid = B_TRUE;
12777 				tcp->tcp_urp_last = urp + seg_seq;
12778 			}
12779 			/*
12780 			 * If this is a zero window probe, continue to
12781 			 * process the ACK part.  But we need to set seg_len
12782 			 * to 0 to avoid data processing.  Otherwise just
12783 			 * drop the segment and send back an ACK.
12784 			 */
12785 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
12786 				flags &= ~(TH_SYN | TH_URG);
12787 				seg_len = 0;
12788 				goto process_ack;
12789 			} else {
12790 				freemsg(mp);
12791 				goto ack_check;
12792 			}
12793 		}
12794 		/* Pitch out of window stuff off the end. */
12795 		rgap = seg_len;
12796 		mp2 = mp;
12797 		do {
12798 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
12799 			    (uintptr_t)INT_MAX);
12800 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
12801 			if (rgap < 0) {
12802 				mp2->b_wptr += rgap;
12803 				if ((mp1 = mp2->b_cont) != NULL) {
12804 					mp2->b_cont = NULL;
12805 					freemsg(mp1);
12806 				}
12807 				break;
12808 			}
12809 		} while ((mp2 = mp2->b_cont) != NULL);
12810 	}
12811 ok:;
12812 	/*
12813 	 * TCP should check ECN info for segments inside the window only.
12814 	 * Therefore the check should be done here.
12815 	 */
12816 	if (tcp->tcp_ecn_ok) {
12817 		if (flags & TH_CWR) {
12818 			tcp->tcp_ecn_echo_on = B_FALSE;
12819 		}
12820 		/*
12821 		 * Note that both ECN_CE and CWR can be set in the
12822 		 * same segment.  In this case, we once again turn
12823 		 * on ECN_ECHO.
12824 		 */
12825 		if (tcp->tcp_ipversion == IPV4_VERSION) {
12826 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
12827 
12828 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
12829 				tcp->tcp_ecn_echo_on = B_TRUE;
12830 			}
12831 		} else {
12832 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
12833 
12834 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
12835 			    htonl(IPH_ECN_CE << 20)) {
12836 				tcp->tcp_ecn_echo_on = B_TRUE;
12837 			}
12838 		}
12839 	}
12840 
12841 	/*
12842 	 * Check whether we can update tcp_ts_recent.  This test is
12843 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
12844 	 * Extensions for High Performance: An Update", Internet Draft.
12845 	 */
12846 	if (tcp->tcp_snd_ts_ok &&
12847 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
12848 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
12849 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12850 		tcp->tcp_last_rcv_lbolt = lbolt64;
12851 	}
12852 
12853 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
12854 		/*
12855 		 * FIN in an out of order segment.  We record this in
12856 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
12857 		 * Clear the FIN so that any check on FIN flag will fail.
12858 		 * Remember that FIN also counts in the sequence number
12859 		 * space.  So we need to ack out of order FIN only segments.
12860 		 */
12861 		if (flags & TH_FIN) {
12862 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
12863 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
12864 			flags &= ~TH_FIN;
12865 			flags |= TH_ACK_NEEDED;
12866 		}
12867 		if (seg_len > 0) {
12868 			/* Fill in the SACK blk list. */
12869 			if (tcp->tcp_snd_sack_ok) {
12870 				ASSERT(tcp->tcp_sack_info != NULL);
12871 				tcp_sack_insert(tcp->tcp_sack_list,
12872 				    seg_seq, seg_seq + seg_len,
12873 				    &(tcp->tcp_num_sack_blk));
12874 			}
12875 
12876 			/*
12877 			 * Attempt reassembly and see if we have something
12878 			 * ready to go.
12879 			 */
12880 			mp = tcp_reass(tcp, mp, seg_seq);
12881 			/* Always ack out of order packets */
12882 			flags |= TH_ACK_NEEDED | TH_PUSH;
12883 			if (mp) {
12884 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
12885 				    (uintptr_t)INT_MAX);
12886 				seg_len = mp->b_cont ? msgdsize(mp) :
12887 					(int)(mp->b_wptr - mp->b_rptr);
12888 				seg_seq = tcp->tcp_rnxt;
12889 				/*
12890 				 * A gap is filled and the seq num and len
12891 				 * of the gap match that of a previously
12892 				 * received FIN, put the FIN flag back in.
12893 				 */
12894 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
12895 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
12896 					flags |= TH_FIN;
12897 					tcp->tcp_valid_bits &=
12898 					    ~TCP_OFO_FIN_VALID;
12899 				}
12900 			} else {
12901 				/*
12902 				 * Keep going even with NULL mp.
12903 				 * There may be a useful ACK or something else
12904 				 * we don't want to miss.
12905 				 *
12906 				 * But TCP should not perform fast retransmit
12907 				 * because of the ack number.  TCP uses
12908 				 * seg_len == 0 to determine if it is a pure
12909 				 * ACK.  And this is not a pure ACK.
12910 				 */
12911 				seg_len = 0;
12912 				ofo_seg = B_TRUE;
12913 			}
12914 		}
12915 	} else if (seg_len > 0) {
12916 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
12917 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
12918 		/*
12919 		 * If an out of order FIN was received before, and the seq
12920 		 * num and len of the new segment match that of the FIN,
12921 		 * put the FIN flag back in.
12922 		 */
12923 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
12924 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
12925 			flags |= TH_FIN;
12926 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
12927 		}
12928 	}
12929 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
12930 	if (flags & TH_RST) {
12931 		freemsg(mp);
12932 		switch (tcp->tcp_state) {
12933 		case TCPS_SYN_RCVD:
12934 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
12935 			break;
12936 		case TCPS_ESTABLISHED:
12937 		case TCPS_FIN_WAIT_1:
12938 		case TCPS_FIN_WAIT_2:
12939 		case TCPS_CLOSE_WAIT:
12940 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
12941 			break;
12942 		case TCPS_CLOSING:
12943 		case TCPS_LAST_ACK:
12944 			(void) tcp_clean_death(tcp, 0, 16);
12945 			break;
12946 		default:
12947 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
12948 			(void) tcp_clean_death(tcp, ENXIO, 17);
12949 			break;
12950 		}
12951 		return;
12952 	}
12953 	if (flags & TH_SYN) {
12954 		/*
12955 		 * See RFC 793, Page 71
12956 		 *
12957 		 * The seq number must be in the window as it should
12958 		 * be "fixed" above.  If it is outside window, it should
12959 		 * be already rejected.  Note that we allow seg_seq to be
12960 		 * rnxt + rwnd because we want to accept 0 window probe.
12961 		 */
12962 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
12963 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
12964 		freemsg(mp);
12965 		/*
12966 		 * If the ACK flag is not set, just use our snxt as the
12967 		 * seq number of the RST segment.
12968 		 */
12969 		if (!(flags & TH_ACK)) {
12970 			seg_ack = tcp->tcp_snxt;
12971 		}
12972 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
12973 		    TH_RST|TH_ACK);
12974 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
12975 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
12976 		return;
12977 	}
12978 	/*
12979 	 * urp could be -1 when the urp field in the packet is 0
12980 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
12981 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
12982 	 */
12983 	if (flags & TH_URG && urp >= 0) {
12984 		if (!tcp->tcp_urp_last_valid ||
12985 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
12986 			/*
12987 			 * If we haven't generated the signal yet for this
12988 			 * urgent pointer value, do it now.  Also, send up a
12989 			 * zero-length M_DATA indicating whether or not this is
12990 			 * the mark. The latter is not needed when a
12991 			 * T_EXDATA_IND is sent up. However, if there are
12992 			 * allocation failures this code relies on the sender
12993 			 * retransmitting and the socket code for determining
12994 			 * the mark should not block waiting for the peer to
12995 			 * transmit. Thus, for simplicity we always send up the
12996 			 * mark indication.
12997 			 */
12998 			mp1 = allocb(0, BPRI_MED);
12999 			if (mp1 == NULL) {
13000 				freemsg(mp);
13001 				return;
13002 			}
13003 			if (!TCP_IS_DETACHED(tcp) &&
13004 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13005 				/* Try again on the rexmit. */
13006 				freemsg(mp1);
13007 				freemsg(mp);
13008 				return;
13009 			}
13010 			/*
13011 			 * Mark with NOTMARKNEXT for now.
13012 			 * The code below will change this to MARKNEXT
13013 			 * if we are at the mark.
13014 			 *
13015 			 * If there are allocation failures (e.g. in dupmsg
13016 			 * below) the next time tcp_rput_data sees the urgent
13017 			 * segment it will send up the MSG*MARKNEXT message.
13018 			 */
13019 			mp1->b_flag |= MSGNOTMARKNEXT;
13020 			freemsg(tcp->tcp_urp_mark_mp);
13021 			tcp->tcp_urp_mark_mp = mp1;
13022 			flags |= TH_SEND_URP_MARK;
13023 #ifdef DEBUG
13024 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13025 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13026 			    "last %x, %s",
13027 			    seg_seq, urp, tcp->tcp_urp_last,
13028 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13029 #endif /* DEBUG */
13030 			tcp->tcp_urp_last_valid = B_TRUE;
13031 			tcp->tcp_urp_last = urp + seg_seq;
13032 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13033 			/*
13034 			 * An allocation failure prevented the previous
13035 			 * tcp_rput_data from sending up the allocated
13036 			 * MSG*MARKNEXT message - send it up this time
13037 			 * around.
13038 			 */
13039 			flags |= TH_SEND_URP_MARK;
13040 		}
13041 
13042 		/*
13043 		 * If the urgent byte is in this segment, make sure that it is
13044 		 * all by itself.  This makes it much easier to deal with the
13045 		 * possibility of an allocation failure on the T_exdata_ind.
13046 		 * Note that seg_len is the number of bytes in the segment, and
13047 		 * urp is the offset into the segment of the urgent byte.
13048 		 * urp < seg_len means that the urgent byte is in this segment.
13049 		 */
13050 		if (urp < seg_len) {
13051 			if (seg_len != 1) {
13052 				uint32_t  tmp_rnxt;
13053 				/*
13054 				 * Break it up and feed it back in.
13055 				 * Re-attach the IP header.
13056 				 */
13057 				mp->b_rptr = iphdr;
13058 				if (urp > 0) {
13059 					/*
13060 					 * There is stuff before the urgent
13061 					 * byte.
13062 					 */
13063 					mp1 = dupmsg(mp);
13064 					if (!mp1) {
13065 						/*
13066 						 * Trim from urgent byte on.
13067 						 * The rest will come back.
13068 						 */
13069 						(void) adjmsg(mp,
13070 						    urp - seg_len);
13071 						tcp_rput_data(connp,
13072 						    mp, NULL);
13073 						return;
13074 					}
13075 					(void) adjmsg(mp1, urp - seg_len);
13076 					/* Feed this piece back in. */
13077 					tmp_rnxt = tcp->tcp_rnxt;
13078 					tcp_rput_data(connp, mp1, NULL);
13079 					/*
13080 					 * If the data passed back in was not
13081 					 * processed (ie: bad ACK) sending
13082 					 * the remainder back in will cause a
13083 					 * loop. In this case, drop the
13084 					 * packet and let the sender try
13085 					 * sending a good packet.
13086 					 */
13087 					if (tmp_rnxt == tcp->tcp_rnxt) {
13088 						freemsg(mp);
13089 						return;
13090 					}
13091 				}
13092 				if (urp != seg_len - 1) {
13093 					uint32_t  tmp_rnxt;
13094 					/*
13095 					 * There is stuff after the urgent
13096 					 * byte.
13097 					 */
13098 					mp1 = dupmsg(mp);
13099 					if (!mp1) {
13100 						/*
13101 						 * Trim everything beyond the
13102 						 * urgent byte.  The rest will
13103 						 * come back.
13104 						 */
13105 						(void) adjmsg(mp,
13106 						    urp + 1 - seg_len);
13107 						tcp_rput_data(connp,
13108 						    mp, NULL);
13109 						return;
13110 					}
13111 					(void) adjmsg(mp1, urp + 1 - seg_len);
13112 					tmp_rnxt = tcp->tcp_rnxt;
13113 					tcp_rput_data(connp, mp1, NULL);
13114 					/*
13115 					 * If the data passed back in was not
13116 					 * processed (ie: bad ACK) sending
13117 					 * the remainder back in will cause a
13118 					 * loop. In this case, drop the
13119 					 * packet and let the sender try
13120 					 * sending a good packet.
13121 					 */
13122 					if (tmp_rnxt == tcp->tcp_rnxt) {
13123 						freemsg(mp);
13124 						return;
13125 					}
13126 				}
13127 				tcp_rput_data(connp, mp, NULL);
13128 				return;
13129 			}
13130 			/*
13131 			 * This segment contains only the urgent byte.  We
13132 			 * have to allocate the T_exdata_ind, if we can.
13133 			 */
13134 			if (!tcp->tcp_urp_mp) {
13135 				struct T_exdata_ind *tei;
13136 				mp1 = allocb(sizeof (struct T_exdata_ind),
13137 				    BPRI_MED);
13138 				if (!mp1) {
13139 					/*
13140 					 * Sigh... It'll be back.
13141 					 * Generate any MSG*MARK message now.
13142 					 */
13143 					freemsg(mp);
13144 					seg_len = 0;
13145 					if (flags & TH_SEND_URP_MARK) {
13146 
13147 
13148 						ASSERT(tcp->tcp_urp_mark_mp);
13149 						tcp->tcp_urp_mark_mp->b_flag &=
13150 							~MSGNOTMARKNEXT;
13151 						tcp->tcp_urp_mark_mp->b_flag |=
13152 							MSGMARKNEXT;
13153 					}
13154 					goto ack_check;
13155 				}
13156 				mp1->b_datap->db_type = M_PROTO;
13157 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13158 				tei->PRIM_type = T_EXDATA_IND;
13159 				tei->MORE_flag = 0;
13160 				mp1->b_wptr = (uchar_t *)&tei[1];
13161 				tcp->tcp_urp_mp = mp1;
13162 #ifdef DEBUG
13163 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13164 				    "tcp_rput: allocated exdata_ind %s",
13165 				    tcp_display(tcp, NULL,
13166 				    DISP_PORT_ONLY));
13167 #endif /* DEBUG */
13168 				/*
13169 				 * There is no need to send a separate MSG*MARK
13170 				 * message since the T_EXDATA_IND will be sent
13171 				 * now.
13172 				 */
13173 				flags &= ~TH_SEND_URP_MARK;
13174 				freemsg(tcp->tcp_urp_mark_mp);
13175 				tcp->tcp_urp_mark_mp = NULL;
13176 			}
13177 			/*
13178 			 * Now we are all set.  On the next putnext upstream,
13179 			 * tcp_urp_mp will be non-NULL and will get prepended
13180 			 * to what has to be this piece containing the urgent
13181 			 * byte.  If for any reason we abort this segment below,
13182 			 * if it comes back, we will have this ready, or it
13183 			 * will get blown off in close.
13184 			 */
13185 		} else if (urp == seg_len) {
13186 			/*
13187 			 * The urgent byte is the next byte after this sequence
13188 			 * number. If there is data it is marked with
13189 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13190 			 * since it is not needed. Otherwise, if the code
13191 			 * above just allocated a zero-length tcp_urp_mark_mp
13192 			 * message, that message is tagged with MSGMARKNEXT.
13193 			 * Sending up these MSGMARKNEXT messages makes
13194 			 * SIOCATMARK work correctly even though
13195 			 * the T_EXDATA_IND will not be sent up until the
13196 			 * urgent byte arrives.
13197 			 */
13198 			if (seg_len != 0) {
13199 				flags |= TH_MARKNEXT_NEEDED;
13200 				freemsg(tcp->tcp_urp_mark_mp);
13201 				tcp->tcp_urp_mark_mp = NULL;
13202 				flags &= ~TH_SEND_URP_MARK;
13203 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13204 				flags |= TH_SEND_URP_MARK;
13205 				tcp->tcp_urp_mark_mp->b_flag &=
13206 					~MSGNOTMARKNEXT;
13207 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13208 			}
13209 #ifdef DEBUG
13210 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13211 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13212 			    seg_len, flags,
13213 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13214 #endif /* DEBUG */
13215 		} else {
13216 			/* Data left until we hit mark */
13217 #ifdef DEBUG
13218 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13219 			    "tcp_rput: URP %d bytes left, %s",
13220 			    urp - seg_len, tcp_display(tcp, NULL,
13221 			    DISP_PORT_ONLY));
13222 #endif /* DEBUG */
13223 		}
13224 	}
13225 
13226 process_ack:
13227 	if (!(flags & TH_ACK)) {
13228 		freemsg(mp);
13229 		goto xmit_check;
13230 	}
13231 	}
13232 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13233 
13234 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13235 		tcp->tcp_ip_forward_progress = B_TRUE;
13236 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13237 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
13238 			/* 3-way handshake complete - pass up the T_CONN_IND */
13239 			tcp_t	*listener = tcp->tcp_listener;
13240 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13241 
13242 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13243 			/*
13244 			 * We are here means eager is fine but it can
13245 			 * get a TH_RST at any point between now and till
13246 			 * accept completes and disappear. We need to
13247 			 * ensure that reference to eager is valid after
13248 			 * we get out of eager's perimeter. So we do
13249 			 * an extra refhold.
13250 			 */
13251 			CONN_INC_REF(connp);
13252 
13253 			/*
13254 			 * The listener also exists because of the refhold
13255 			 * done in tcp_conn_request. Its possible that it
13256 			 * might have closed. We will check that once we
13257 			 * get inside listeners context.
13258 			 */
13259 			CONN_INC_REF(listener->tcp_connp);
13260 			if (listener->tcp_connp->conn_sqp ==
13261 			    connp->conn_sqp) {
13262 				tcp_send_conn_ind(listener->tcp_connp, mp,
13263 				    listener->tcp_connp->conn_sqp);
13264 				CONN_DEC_REF(listener->tcp_connp);
13265 			} else if (!tcp->tcp_loopback) {
13266 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
13267 				    tcp_send_conn_ind,
13268 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
13269 			} else {
13270 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
13271 				    tcp_send_conn_ind, listener->tcp_connp,
13272 				    SQTAG_TCP_CONN_IND);
13273 			}
13274 		}
13275 
13276 		if (tcp->tcp_active_open) {
13277 			/*
13278 			 * We are seeing the final ack in the three way
13279 			 * hand shake of a active open'ed connection
13280 			 * so we must send up a T_CONN_CON
13281 			 */
13282 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13283 				freemsg(mp);
13284 				return;
13285 			}
13286 			/*
13287 			 * Don't fuse the loopback endpoints for
13288 			 * simultaneous active opens.
13289 			 */
13290 			if (tcp->tcp_loopback) {
13291 				TCP_STAT(tcp_fusion_unfusable);
13292 				tcp->tcp_unfusable = B_TRUE;
13293 			}
13294 		}
13295 
13296 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
13297 		bytes_acked--;
13298 		/* SYN was acked - making progress */
13299 		if (tcp->tcp_ipversion == IPV6_VERSION)
13300 			tcp->tcp_ip_forward_progress = B_TRUE;
13301 
13302 		/*
13303 		 * If SYN was retransmitted, need to reset all
13304 		 * retransmission info as this segment will be
13305 		 * treated as a dup ACK.
13306 		 */
13307 		if (tcp->tcp_rexmit) {
13308 			tcp->tcp_rexmit = B_FALSE;
13309 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13310 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
13311 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13312 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13313 			tcp->tcp_ms_we_have_waited = 0;
13314 			tcp->tcp_cwnd = mss;
13315 		}
13316 
13317 		/*
13318 		 * We set the send window to zero here.
13319 		 * This is needed if there is data to be
13320 		 * processed already on the queue.
13321 		 * Later (at swnd_update label), the
13322 		 * "new_swnd > tcp_swnd" condition is satisfied
13323 		 * the XMIT_NEEDED flag is set in the current
13324 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
13325 		 * called if there is already data on queue in
13326 		 * this state.
13327 		 */
13328 		tcp->tcp_swnd = 0;
13329 
13330 		if (new_swnd > tcp->tcp_max_swnd)
13331 			tcp->tcp_max_swnd = new_swnd;
13332 		tcp->tcp_swl1 = seg_seq;
13333 		tcp->tcp_swl2 = seg_ack;
13334 		tcp->tcp_state = TCPS_ESTABLISHED;
13335 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13336 
13337 		/* Fuse when both sides are in ESTABLISHED state */
13338 		if (tcp->tcp_loopback && do_tcp_fusion)
13339 			tcp_fuse(tcp, iphdr, tcph);
13340 
13341 	}
13342 	/* This code follows 4.4BSD-Lite2 mostly. */
13343 	if (bytes_acked < 0)
13344 		goto est;
13345 
13346 	/*
13347 	 * If TCP is ECN capable and the congestion experience bit is
13348 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
13349 	 * done once per window (or more loosely, per RTT).
13350 	 */
13351 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
13352 		tcp->tcp_cwr = B_FALSE;
13353 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
13354 		if (!tcp->tcp_cwr) {
13355 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
13356 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
13357 			tcp->tcp_cwnd = npkt * mss;
13358 			/*
13359 			 * If the cwnd is 0, use the timer to clock out
13360 			 * new segments.  This is required by the ECN spec.
13361 			 */
13362 			if (npkt == 0) {
13363 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13364 				/*
13365 				 * This makes sure that when the ACK comes
13366 				 * back, we will increase tcp_cwnd by 1 MSS.
13367 				 */
13368 				tcp->tcp_cwnd_cnt = 0;
13369 			}
13370 			tcp->tcp_cwr = B_TRUE;
13371 			/*
13372 			 * This marks the end of the current window of in
13373 			 * flight data.  That is why we don't use
13374 			 * tcp_suna + tcp_swnd.  Only data in flight can
13375 			 * provide ECN info.
13376 			 */
13377 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13378 			tcp->tcp_ecn_cwr_sent = B_FALSE;
13379 		}
13380 	}
13381 
13382 	mp1 = tcp->tcp_xmit_head;
13383 	if (bytes_acked == 0) {
13384 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
13385 			int dupack_cnt;
13386 
13387 			BUMP_MIB(&tcp_mib, tcpInDupAck);
13388 			/*
13389 			 * Fast retransmit.  When we have seen exactly three
13390 			 * identical ACKs while we have unacked data
13391 			 * outstanding we take it as a hint that our peer
13392 			 * dropped something.
13393 			 *
13394 			 * If TCP is retransmitting, don't do fast retransmit.
13395 			 */
13396 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
13397 			    ! tcp->tcp_rexmit) {
13398 				/* Do Limited Transmit */
13399 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
13400 				    tcp_dupack_fast_retransmit) {
13401 					/*
13402 					 * RFC 3042
13403 					 *
13404 					 * What we need to do is temporarily
13405 					 * increase tcp_cwnd so that new
13406 					 * data can be sent if it is allowed
13407 					 * by the receive window (tcp_rwnd).
13408 					 * tcp_wput_data() will take care of
13409 					 * the rest.
13410 					 *
13411 					 * If the connection is SACK capable,
13412 					 * only do limited xmit when there
13413 					 * is SACK info.
13414 					 *
13415 					 * Note how tcp_cwnd is incremented.
13416 					 * The first dup ACK will increase
13417 					 * it by 1 MSS.  The second dup ACK
13418 					 * will increase it by 2 MSS.  This
13419 					 * means that only 1 new segment will
13420 					 * be sent for each dup ACK.
13421 					 */
13422 					if (tcp->tcp_unsent > 0 &&
13423 					    (!tcp->tcp_snd_sack_ok ||
13424 					    (tcp->tcp_snd_sack_ok &&
13425 					    tcp->tcp_notsack_list != NULL))) {
13426 						tcp->tcp_cwnd += mss <<
13427 						    (tcp->tcp_dupack_cnt - 1);
13428 						flags |= TH_LIMIT_XMIT;
13429 					}
13430 				} else if (dupack_cnt ==
13431 				    tcp_dupack_fast_retransmit) {
13432 
13433 				/*
13434 				 * If we have reduced tcp_ssthresh
13435 				 * because of ECN, do not reduce it again
13436 				 * unless it is already one window of data
13437 				 * away.  After one window of data, tcp_cwr
13438 				 * should then be cleared.  Note that
13439 				 * for non ECN capable connection, tcp_cwr
13440 				 * should always be false.
13441 				 *
13442 				 * Adjust cwnd since the duplicate
13443 				 * ack indicates that a packet was
13444 				 * dropped (due to congestion.)
13445 				 */
13446 				if (!tcp->tcp_cwr) {
13447 					npkt = ((tcp->tcp_snxt -
13448 					    tcp->tcp_suna) >> 1) / mss;
13449 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13450 					    mss;
13451 					tcp->tcp_cwnd = (npkt +
13452 					    tcp->tcp_dupack_cnt) * mss;
13453 				}
13454 				if (tcp->tcp_ecn_ok) {
13455 					tcp->tcp_cwr = B_TRUE;
13456 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13457 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13458 				}
13459 
13460 				/*
13461 				 * We do Hoe's algorithm.  Refer to her
13462 				 * paper "Improving the Start-up Behavior
13463 				 * of a Congestion Control Scheme for TCP,"
13464 				 * appeared in SIGCOMM'96.
13465 				 *
13466 				 * Save highest seq no we have sent so far.
13467 				 * Be careful about the invisible FIN byte.
13468 				 */
13469 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13470 				    (tcp->tcp_unsent == 0)) {
13471 					tcp->tcp_rexmit_max = tcp->tcp_fss;
13472 				} else {
13473 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
13474 				}
13475 
13476 				/*
13477 				 * Do not allow bursty traffic during.
13478 				 * fast recovery.  Refer to Fall and Floyd's
13479 				 * paper "Simulation-based Comparisons of
13480 				 * Tahoe, Reno and SACK TCP" (in CCR?)
13481 				 * This is a best current practise.
13482 				 */
13483 				tcp->tcp_snd_burst = TCP_CWND_SS;
13484 
13485 				/*
13486 				 * For SACK:
13487 				 * Calculate tcp_pipe, which is the
13488 				 * estimated number of bytes in
13489 				 * network.
13490 				 *
13491 				 * tcp_fack is the highest sack'ed seq num
13492 				 * TCP has received.
13493 				 *
13494 				 * tcp_pipe is explained in the above quoted
13495 				 * Fall and Floyd's paper.  tcp_fack is
13496 				 * explained in Mathis and Mahdavi's
13497 				 * "Forward Acknowledgment: Refining TCP
13498 				 * Congestion Control" in SIGCOMM '96.
13499 				 */
13500 				if (tcp->tcp_snd_sack_ok) {
13501 					ASSERT(tcp->tcp_sack_info != NULL);
13502 					if (tcp->tcp_notsack_list != NULL) {
13503 						tcp->tcp_pipe = tcp->tcp_snxt -
13504 						    tcp->tcp_fack;
13505 						tcp->tcp_sack_snxt = seg_ack;
13506 						flags |= TH_NEED_SACK_REXMIT;
13507 					} else {
13508 						/*
13509 						 * Always initialize tcp_pipe
13510 						 * even though we don't have
13511 						 * any SACK info.  If later
13512 						 * we get SACK info and
13513 						 * tcp_pipe is not initialized,
13514 						 * funny things will happen.
13515 						 */
13516 						tcp->tcp_pipe =
13517 						    tcp->tcp_cwnd_ssthresh;
13518 					}
13519 				} else {
13520 					flags |= TH_REXMIT_NEEDED;
13521 				} /* tcp_snd_sack_ok */
13522 
13523 				} else {
13524 					/*
13525 					 * Here we perform congestion
13526 					 * avoidance, but NOT slow start.
13527 					 * This is known as the Fast
13528 					 * Recovery Algorithm.
13529 					 */
13530 					if (tcp->tcp_snd_sack_ok &&
13531 					    tcp->tcp_notsack_list != NULL) {
13532 						flags |= TH_NEED_SACK_REXMIT;
13533 						tcp->tcp_pipe -= mss;
13534 						if (tcp->tcp_pipe < 0)
13535 							tcp->tcp_pipe = 0;
13536 					} else {
13537 					/*
13538 					 * We know that one more packet has
13539 					 * left the pipe thus we can update
13540 					 * cwnd.
13541 					 */
13542 					cwnd = tcp->tcp_cwnd + mss;
13543 					if (cwnd > tcp->tcp_cwnd_max)
13544 						cwnd = tcp->tcp_cwnd_max;
13545 					tcp->tcp_cwnd = cwnd;
13546 					if (tcp->tcp_unsent > 0)
13547 						flags |= TH_XMIT_NEEDED;
13548 					}
13549 				}
13550 			}
13551 		} else if (tcp->tcp_zero_win_probe) {
13552 			/*
13553 			 * If the window has opened, need to arrange
13554 			 * to send additional data.
13555 			 */
13556 			if (new_swnd != 0) {
13557 				/* tcp_suna != tcp_snxt */
13558 				/* Packet contains a window update */
13559 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
13560 				tcp->tcp_zero_win_probe = 0;
13561 				tcp->tcp_timer_backoff = 0;
13562 				tcp->tcp_ms_we_have_waited = 0;
13563 
13564 				/*
13565 				 * Transmit starting with tcp_suna since
13566 				 * the one byte probe is not ack'ed.
13567 				 * If TCP has sent more than one identical
13568 				 * probe, tcp_rexmit will be set.  That means
13569 				 * tcp_ss_rexmit() will send out the one
13570 				 * byte along with new data.  Otherwise,
13571 				 * fake the retransmission.
13572 				 */
13573 				flags |= TH_XMIT_NEEDED;
13574 				if (!tcp->tcp_rexmit) {
13575 					tcp->tcp_rexmit = B_TRUE;
13576 					tcp->tcp_dupack_cnt = 0;
13577 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13578 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
13579 				}
13580 			}
13581 		}
13582 		goto swnd_update;
13583 	}
13584 
13585 	/*
13586 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
13587 	 * If the ACK value acks something that we have not yet sent, it might
13588 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
13589 	 * other side.
13590 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
13591 	 * state is handled above, so we can always just drop the segment and
13592 	 * send an ACK here.
13593 	 *
13594 	 * Should we send ACKs in response to ACK only segments?
13595 	 */
13596 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13597 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
13598 		/* drop the received segment */
13599 		freemsg(mp);
13600 
13601 		/*
13602 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
13603 		 * greater than 0, check if the number of such
13604 		 * bogus ACks is greater than that count.  If yes,
13605 		 * don't send back any ACK.  This prevents TCP from
13606 		 * getting into an ACK storm if somehow an attacker
13607 		 * successfully spoofs an acceptable segment to our
13608 		 * peer.
13609 		 */
13610 		if (tcp_drop_ack_unsent_cnt > 0 &&
13611 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
13612 			TCP_STAT(tcp_in_ack_unsent_drop);
13613 			return;
13614 		}
13615 		mp = tcp_ack_mp(tcp);
13616 		if (mp != NULL) {
13617 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
13618 			BUMP_LOCAL(tcp->tcp_obsegs);
13619 			BUMP_MIB(&tcp_mib, tcpOutAck);
13620 			tcp_send_data(tcp, tcp->tcp_wq, mp);
13621 		}
13622 		return;
13623 	}
13624 
13625 	/*
13626 	 * TCP gets a new ACK, update the notsack'ed list to delete those
13627 	 * blocks that are covered by this ACK.
13628 	 */
13629 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
13630 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
13631 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
13632 	}
13633 
13634 	/*
13635 	 * If we got an ACK after fast retransmit, check to see
13636 	 * if it is a partial ACK.  If it is not and the congestion
13637 	 * window was inflated to account for the other side's
13638 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
13639 	 */
13640 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
13641 		ASSERT(tcp->tcp_rexmit == B_FALSE);
13642 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
13643 			tcp->tcp_dupack_cnt = 0;
13644 			/*
13645 			 * Restore the orig tcp_cwnd_ssthresh after
13646 			 * fast retransmit phase.
13647 			 */
13648 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
13649 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
13650 			}
13651 			tcp->tcp_rexmit_max = seg_ack;
13652 			tcp->tcp_cwnd_cnt = 0;
13653 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13654 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13655 
13656 			/*
13657 			 * Remove all notsack info to avoid confusion with
13658 			 * the next fast retrasnmit/recovery phase.
13659 			 */
13660 			if (tcp->tcp_snd_sack_ok &&
13661 			    tcp->tcp_notsack_list != NULL) {
13662 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
13663 			}
13664 		} else {
13665 			if (tcp->tcp_snd_sack_ok &&
13666 			    tcp->tcp_notsack_list != NULL) {
13667 				flags |= TH_NEED_SACK_REXMIT;
13668 				tcp->tcp_pipe -= mss;
13669 				if (tcp->tcp_pipe < 0)
13670 					tcp->tcp_pipe = 0;
13671 			} else {
13672 				/*
13673 				 * Hoe's algorithm:
13674 				 *
13675 				 * Retransmit the unack'ed segment and
13676 				 * restart fast recovery.  Note that we
13677 				 * need to scale back tcp_cwnd to the
13678 				 * original value when we started fast
13679 				 * recovery.  This is to prevent overly
13680 				 * aggressive behaviour in sending new
13681 				 * segments.
13682 				 */
13683 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
13684 					tcp_dupack_fast_retransmit * mss;
13685 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
13686 				flags |= TH_REXMIT_NEEDED;
13687 			}
13688 		}
13689 	} else {
13690 		tcp->tcp_dupack_cnt = 0;
13691 		if (tcp->tcp_rexmit) {
13692 			/*
13693 			 * TCP is retranmitting.  If the ACK ack's all
13694 			 * outstanding data, update tcp_rexmit_max and
13695 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
13696 			 * to the correct value.
13697 			 *
13698 			 * Note that SEQ_LEQ() is used.  This is to avoid
13699 			 * unnecessary fast retransmit caused by dup ACKs
13700 			 * received when TCP does slow start retransmission
13701 			 * after a time out.  During this phase, TCP may
13702 			 * send out segments which are already received.
13703 			 * This causes dup ACKs to be sent back.
13704 			 */
13705 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
13706 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
13707 					tcp->tcp_rexmit_nxt = seg_ack;
13708 				}
13709 				if (seg_ack != tcp->tcp_rexmit_max) {
13710 					flags |= TH_XMIT_NEEDED;
13711 				}
13712 			} else {
13713 				tcp->tcp_rexmit = B_FALSE;
13714 				tcp->tcp_xmit_zc_clean = B_FALSE;
13715 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13716 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13717 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13718 			}
13719 			tcp->tcp_ms_we_have_waited = 0;
13720 		}
13721 	}
13722 
13723 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
13724 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
13725 	tcp->tcp_suna = seg_ack;
13726 	if (tcp->tcp_zero_win_probe != 0) {
13727 		tcp->tcp_zero_win_probe = 0;
13728 		tcp->tcp_timer_backoff = 0;
13729 	}
13730 
13731 	/*
13732 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
13733 	 * Note that it cannot be the SYN being ack'ed.  The code flow
13734 	 * will not reach here.
13735 	 */
13736 	if (mp1 == NULL) {
13737 		goto fin_acked;
13738 	}
13739 
13740 	/*
13741 	 * Update the congestion window.
13742 	 *
13743 	 * If TCP is not ECN capable or TCP is ECN capable but the
13744 	 * congestion experience bit is not set, increase the tcp_cwnd as
13745 	 * usual.
13746 	 */
13747 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
13748 		cwnd = tcp->tcp_cwnd;
13749 		add = mss;
13750 
13751 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
13752 			/*
13753 			 * This is to prevent an increase of less than 1 MSS of
13754 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
13755 			 * may send out tinygrams in order to preserve mblk
13756 			 * boundaries.
13757 			 *
13758 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
13759 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
13760 			 * increased by 1 MSS for every RTTs.
13761 			 */
13762 			if (tcp->tcp_cwnd_cnt <= 0) {
13763 				tcp->tcp_cwnd_cnt = cwnd + add;
13764 			} else {
13765 				tcp->tcp_cwnd_cnt -= add;
13766 				add = 0;
13767 			}
13768 		}
13769 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
13770 	}
13771 
13772 	/* See if the latest urgent data has been acknowledged */
13773 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
13774 	    SEQ_GT(seg_ack, tcp->tcp_urg))
13775 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
13776 
13777 	/* Can we update the RTT estimates? */
13778 	if (tcp->tcp_snd_ts_ok) {
13779 		/* Ignore zero timestamp echo-reply. */
13780 		if (tcpopt.tcp_opt_ts_ecr != 0) {
13781 			tcp_set_rto(tcp, (int32_t)lbolt -
13782 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
13783 		}
13784 
13785 		/* If needed, restart the timer. */
13786 		if (tcp->tcp_set_timer == 1) {
13787 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13788 			tcp->tcp_set_timer = 0;
13789 		}
13790 		/*
13791 		 * Update tcp_csuna in case the other side stops sending
13792 		 * us timestamps.
13793 		 */
13794 		tcp->tcp_csuna = tcp->tcp_snxt;
13795 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
13796 		/*
13797 		 * An ACK sequence we haven't seen before, so get the RTT
13798 		 * and update the RTO. But first check if the timestamp is
13799 		 * valid to use.
13800 		 */
13801 		if ((mp1->b_next != NULL) &&
13802 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
13803 			tcp_set_rto(tcp, (int32_t)lbolt -
13804 			    (int32_t)(intptr_t)mp1->b_prev);
13805 		else
13806 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
13807 
13808 		/* Remeber the last sequence to be ACKed */
13809 		tcp->tcp_csuna = seg_ack;
13810 		if (tcp->tcp_set_timer == 1) {
13811 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13812 			tcp->tcp_set_timer = 0;
13813 		}
13814 	} else {
13815 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
13816 	}
13817 
13818 	/* Eat acknowledged bytes off the xmit queue. */
13819 	for (;;) {
13820 		mblk_t	*mp2;
13821 		uchar_t	*wptr;
13822 
13823 		wptr = mp1->b_wptr;
13824 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
13825 		bytes_acked -= (int)(wptr - mp1->b_rptr);
13826 		if (bytes_acked < 0) {
13827 			mp1->b_rptr = wptr + bytes_acked;
13828 			/*
13829 			 * Set a new timestamp if all the bytes timed by the
13830 			 * old timestamp have been ack'ed.
13831 			 */
13832 			if (SEQ_GT(seg_ack,
13833 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
13834 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
13835 				mp1->b_next = NULL;
13836 			}
13837 			break;
13838 		}
13839 		mp1->b_next = NULL;
13840 		mp1->b_prev = NULL;
13841 		mp2 = mp1;
13842 		mp1 = mp1->b_cont;
13843 
13844 		/*
13845 		 * This notification is required for some zero-copy
13846 		 * clients to maintain a copy semantic. After the data
13847 		 * is ack'ed, client is safe to modify or reuse the buffer.
13848 		 */
13849 		if (tcp->tcp_snd_zcopy_aware &&
13850 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
13851 			tcp_zcopy_notify(tcp);
13852 		freeb(mp2);
13853 		if (bytes_acked == 0) {
13854 			if (mp1 == NULL) {
13855 				/* Everything is ack'ed, clear the tail. */
13856 				tcp->tcp_xmit_tail = NULL;
13857 				/*
13858 				 * Cancel the timer unless we are still
13859 				 * waiting for an ACK for the FIN packet.
13860 				 */
13861 				if (tcp->tcp_timer_tid != 0 &&
13862 				    tcp->tcp_snxt == tcp->tcp_suna) {
13863 					(void) TCP_TIMER_CANCEL(tcp,
13864 					    tcp->tcp_timer_tid);
13865 					tcp->tcp_timer_tid = 0;
13866 				}
13867 				goto pre_swnd_update;
13868 			}
13869 			if (mp2 != tcp->tcp_xmit_tail)
13870 				break;
13871 			tcp->tcp_xmit_tail = mp1;
13872 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13873 			    (uintptr_t)INT_MAX);
13874 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
13875 			    mp1->b_rptr);
13876 			break;
13877 		}
13878 		if (mp1 == NULL) {
13879 			/*
13880 			 * More was acked but there is nothing more
13881 			 * outstanding.  This means that the FIN was
13882 			 * just acked or that we're talking to a clown.
13883 			 */
13884 fin_acked:
13885 			ASSERT(tcp->tcp_fin_sent);
13886 			tcp->tcp_xmit_tail = NULL;
13887 			if (tcp->tcp_fin_sent) {
13888 				/* FIN was acked - making progress */
13889 				if (tcp->tcp_ipversion == IPV6_VERSION &&
13890 				    !tcp->tcp_fin_acked)
13891 					tcp->tcp_ip_forward_progress = B_TRUE;
13892 				tcp->tcp_fin_acked = B_TRUE;
13893 				if (tcp->tcp_linger_tid != 0 &&
13894 				    TCP_TIMER_CANCEL(tcp,
13895 					tcp->tcp_linger_tid) >= 0) {
13896 					tcp_stop_lingering(tcp);
13897 				}
13898 			} else {
13899 				/*
13900 				 * We should never get here because
13901 				 * we have already checked that the
13902 				 * number of bytes ack'ed should be
13903 				 * smaller than or equal to what we
13904 				 * have sent so far (it is the
13905 				 * acceptability check of the ACK).
13906 				 * We can only get here if the send
13907 				 * queue is corrupted.
13908 				 *
13909 				 * Terminate the connection and
13910 				 * panic the system.  It is better
13911 				 * for us to panic instead of
13912 				 * continuing to avoid other disaster.
13913 				 */
13914 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
13915 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
13916 				panic("Memory corruption "
13917 				    "detected for connection %s.",
13918 				    tcp_display(tcp, NULL,
13919 					DISP_ADDR_AND_PORT));
13920 				/*NOTREACHED*/
13921 			}
13922 			goto pre_swnd_update;
13923 		}
13924 		ASSERT(mp2 != tcp->tcp_xmit_tail);
13925 	}
13926 	if (tcp->tcp_unsent) {
13927 		flags |= TH_XMIT_NEEDED;
13928 	}
13929 pre_swnd_update:
13930 	tcp->tcp_xmit_head = mp1;
13931 swnd_update:
13932 	/*
13933 	 * The following check is different from most other implementations.
13934 	 * For bi-directional transfer, when segments are dropped, the
13935 	 * "normal" check will not accept a window update in those
13936 	 * retransmitted segemnts.  Failing to do that, TCP may send out
13937 	 * segments which are outside receiver's window.  As TCP accepts
13938 	 * the ack in those retransmitted segments, if the window update in
13939 	 * the same segment is not accepted, TCP will incorrectly calculates
13940 	 * that it can send more segments.  This can create a deadlock
13941 	 * with the receiver if its window becomes zero.
13942 	 */
13943 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
13944 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
13945 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
13946 		/*
13947 		 * The criteria for update is:
13948 		 *
13949 		 * 1. the segment acknowledges some data.  Or
13950 		 * 2. the segment is new, i.e. it has a higher seq num. Or
13951 		 * 3. the segment is not old and the advertised window is
13952 		 * larger than the previous advertised window.
13953 		 */
13954 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
13955 			flags |= TH_XMIT_NEEDED;
13956 		tcp->tcp_swnd = new_swnd;
13957 		if (new_swnd > tcp->tcp_max_swnd)
13958 			tcp->tcp_max_swnd = new_swnd;
13959 		tcp->tcp_swl1 = seg_seq;
13960 		tcp->tcp_swl2 = seg_ack;
13961 	}
13962 est:
13963 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
13964 		switch (tcp->tcp_state) {
13965 		case TCPS_FIN_WAIT_1:
13966 			if (tcp->tcp_fin_acked) {
13967 				tcp->tcp_state = TCPS_FIN_WAIT_2;
13968 				/*
13969 				 * We implement the non-standard BSD/SunOS
13970 				 * FIN_WAIT_2 flushing algorithm.
13971 				 * If there is no user attached to this
13972 				 * TCP endpoint, then this TCP struct
13973 				 * could hang around forever in FIN_WAIT_2
13974 				 * state if the peer forgets to send us
13975 				 * a FIN.  To prevent this, we wait only
13976 				 * 2*MSL (a convenient time value) for
13977 				 * the FIN to arrive.  If it doesn't show up,
13978 				 * we flush the TCP endpoint.  This algorithm,
13979 				 * though a violation of RFC-793, has worked
13980 				 * for over 10 years in BSD systems.
13981 				 * Note: SunOS 4.x waits 675 seconds before
13982 				 * flushing the FIN_WAIT_2 connection.
13983 				 */
13984 				TCP_TIMER_RESTART(tcp,
13985 				    tcp_fin_wait_2_flush_interval);
13986 			}
13987 			break;
13988 		case TCPS_FIN_WAIT_2:
13989 			break;	/* Shutdown hook? */
13990 		case TCPS_LAST_ACK:
13991 			freemsg(mp);
13992 			if (tcp->tcp_fin_acked) {
13993 				(void) tcp_clean_death(tcp, 0, 19);
13994 				return;
13995 			}
13996 			goto xmit_check;
13997 		case TCPS_CLOSING:
13998 			if (tcp->tcp_fin_acked) {
13999 				tcp->tcp_state = TCPS_TIME_WAIT;
14000 				if (!TCP_IS_DETACHED(tcp)) {
14001 					TCP_TIMER_RESTART(tcp,
14002 					    tcp_time_wait_interval);
14003 				} else {
14004 					tcp_time_wait_append(tcp);
14005 					TCP_DBGSTAT(tcp_rput_time_wait);
14006 				}
14007 			}
14008 			/*FALLTHRU*/
14009 		case TCPS_CLOSE_WAIT:
14010 			freemsg(mp);
14011 			goto xmit_check;
14012 		default:
14013 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14014 			break;
14015 		}
14016 	}
14017 	if (flags & TH_FIN) {
14018 		/* Make sure we ack the fin */
14019 		flags |= TH_ACK_NEEDED;
14020 		if (!tcp->tcp_fin_rcvd) {
14021 			tcp->tcp_fin_rcvd = B_TRUE;
14022 			tcp->tcp_rnxt++;
14023 			tcph = tcp->tcp_tcph;
14024 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14025 
14026 			/*
14027 			 * Generate the ordrel_ind at the end unless we
14028 			 * are an eager guy.
14029 			 * In the eager case tcp_rsrv will do this when run
14030 			 * after tcp_accept is done.
14031 			 */
14032 			if (tcp->tcp_listener == NULL &&
14033 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14034 				flags |= TH_ORDREL_NEEDED;
14035 			switch (tcp->tcp_state) {
14036 			case TCPS_SYN_RCVD:
14037 			case TCPS_ESTABLISHED:
14038 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14039 				/* Keepalive? */
14040 				break;
14041 			case TCPS_FIN_WAIT_1:
14042 				if (!tcp->tcp_fin_acked) {
14043 					tcp->tcp_state = TCPS_CLOSING;
14044 					break;
14045 				}
14046 				/* FALLTHRU */
14047 			case TCPS_FIN_WAIT_2:
14048 				tcp->tcp_state = TCPS_TIME_WAIT;
14049 				if (!TCP_IS_DETACHED(tcp)) {
14050 					TCP_TIMER_RESTART(tcp,
14051 					    tcp_time_wait_interval);
14052 				} else {
14053 					tcp_time_wait_append(tcp);
14054 					TCP_DBGSTAT(tcp_rput_time_wait);
14055 				}
14056 				if (seg_len) {
14057 					/*
14058 					 * implies data piggybacked on FIN.
14059 					 * break to handle data.
14060 					 */
14061 					break;
14062 				}
14063 				freemsg(mp);
14064 				goto ack_check;
14065 			}
14066 		}
14067 	}
14068 	if (mp == NULL)
14069 		goto xmit_check;
14070 	if (seg_len == 0) {
14071 		freemsg(mp);
14072 		goto xmit_check;
14073 	}
14074 	if (mp->b_rptr == mp->b_wptr) {
14075 		/*
14076 		 * The header has been consumed, so we remove the
14077 		 * zero-length mblk here.
14078 		 */
14079 		mp1 = mp;
14080 		mp = mp->b_cont;
14081 		freeb(mp1);
14082 	}
14083 	tcph = tcp->tcp_tcph;
14084 	tcp->tcp_rack_cnt++;
14085 	{
14086 		uint32_t cur_max;
14087 
14088 		cur_max = tcp->tcp_rack_cur_max;
14089 		if (tcp->tcp_rack_cnt >= cur_max) {
14090 			/*
14091 			 * We have more unacked data than we should - send
14092 			 * an ACK now.
14093 			 */
14094 			flags |= TH_ACK_NEEDED;
14095 			cur_max++;
14096 			if (cur_max > tcp->tcp_rack_abs_max)
14097 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14098 			else
14099 				tcp->tcp_rack_cur_max = cur_max;
14100 		} else if (TCP_IS_DETACHED(tcp)) {
14101 			/* We don't have an ACK timer for detached TCP. */
14102 			flags |= TH_ACK_NEEDED;
14103 		} else if (seg_len < mss) {
14104 			/*
14105 			 * If we get a segment that is less than an mss, and we
14106 			 * already have unacknowledged data, and the amount
14107 			 * unacknowledged is not a multiple of mss, then we
14108 			 * better generate an ACK now.  Otherwise, this may be
14109 			 * the tail piece of a transaction, and we would rather
14110 			 * wait for the response.
14111 			 */
14112 			uint32_t udif;
14113 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14114 			    (uintptr_t)INT_MAX);
14115 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14116 			if (udif && (udif % mss))
14117 				flags |= TH_ACK_NEEDED;
14118 			else
14119 				flags |= TH_ACK_TIMER_NEEDED;
14120 		} else {
14121 			/* Start delayed ack timer */
14122 			flags |= TH_ACK_TIMER_NEEDED;
14123 		}
14124 	}
14125 	tcp->tcp_rnxt += seg_len;
14126 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14127 
14128 	/* Update SACK list */
14129 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14130 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14131 		    &(tcp->tcp_num_sack_blk));
14132 	}
14133 
14134 	if (tcp->tcp_urp_mp) {
14135 		tcp->tcp_urp_mp->b_cont = mp;
14136 		mp = tcp->tcp_urp_mp;
14137 		tcp->tcp_urp_mp = NULL;
14138 		/* Ready for a new signal. */
14139 		tcp->tcp_urp_last_valid = B_FALSE;
14140 #ifdef DEBUG
14141 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14142 		    "tcp_rput: sending exdata_ind %s",
14143 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14144 #endif /* DEBUG */
14145 	}
14146 
14147 	/*
14148 	 * Check for ancillary data changes compared to last segment.
14149 	 */
14150 	if (tcp->tcp_ipv6_recvancillary != 0) {
14151 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14152 		if (mp == NULL)
14153 			return;
14154 	}
14155 
14156 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14157 		/*
14158 		 * Side queue inbound data until the accept happens.
14159 		 * tcp_accept/tcp_rput drains this when the accept happens.
14160 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14161 		 * T_EXDATA_IND) it is queued on b_next.
14162 		 * XXX Make urgent data use this. Requires:
14163 		 *	Removing tcp_listener check for TH_URG
14164 		 *	Making M_PCPROTO and MARK messages skip the eager case
14165 		 */
14166 		tcp_rcv_enqueue(tcp, mp, seg_len);
14167 	} else {
14168 		if (mp->b_datap->db_type != M_DATA ||
14169 		    (flags & TH_MARKNEXT_NEEDED)) {
14170 			if (tcp->tcp_rcv_list != NULL) {
14171 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14172 			}
14173 			ASSERT(tcp->tcp_rcv_list == NULL ||
14174 			    tcp->tcp_fused_sigurg);
14175 			if (flags & TH_MARKNEXT_NEEDED) {
14176 #ifdef DEBUG
14177 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14178 				    "tcp_rput: sending MSGMARKNEXT %s",
14179 				    tcp_display(tcp, NULL,
14180 				    DISP_PORT_ONLY));
14181 #endif /* DEBUG */
14182 				mp->b_flag |= MSGMARKNEXT;
14183 				flags &= ~TH_MARKNEXT_NEEDED;
14184 			}
14185 			putnext(tcp->tcp_rq, mp);
14186 			if (!canputnext(tcp->tcp_rq))
14187 				tcp->tcp_rwnd -= seg_len;
14188 		} else if (((flags & (TH_PUSH|TH_FIN)) ||
14189 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) &&
14190 		    (sqp != NULL)) {
14191 			if (tcp->tcp_rcv_list != NULL) {
14192 				/*
14193 				 * Enqueue the new segment first and then
14194 				 * call tcp_rcv_drain() to send all data
14195 				 * up.  The other way to do this is to
14196 				 * send all queued data up and then call
14197 				 * putnext() to send the new segment up.
14198 				 * This way can remove the else part later
14199 				 * on.
14200 				 *
14201 				 * We don't this to avoid one more call to
14202 				 * canputnext() as tcp_rcv_drain() needs to
14203 				 * call canputnext().
14204 				 */
14205 				tcp_rcv_enqueue(tcp, mp, seg_len);
14206 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14207 			} else {
14208 				putnext(tcp->tcp_rq, mp);
14209 				if (!canputnext(tcp->tcp_rq))
14210 					tcp->tcp_rwnd -= seg_len;
14211 			}
14212 		} else {
14213 			/*
14214 			 * Enqueue all packets when processing an mblk
14215 			 * from the co queue and also enqueue normal packets.
14216 			 */
14217 			tcp_rcv_enqueue(tcp, mp, seg_len);
14218 		}
14219 		/*
14220 		 * Make sure the timer is running if we have data waiting
14221 		 * for a push bit. This provides resiliency against
14222 		 * implementations that do not correctly generate push bits.
14223 		 */
14224 		if ((sqp != NULL) && tcp->tcp_rcv_list != NULL &&
14225 		    tcp->tcp_push_tid == 0) {
14226 			/*
14227 			 * The connection may be closed at this point, so don't
14228 			 * do anything for a detached tcp.
14229 			 */
14230 			if (!TCP_IS_DETACHED(tcp))
14231 				tcp->tcp_push_tid = TCP_TIMER(tcp,
14232 				    tcp_push_timer,
14233 				    MSEC_TO_TICK(tcp_push_timer_interval));
14234 		}
14235 	}
14236 xmit_check:
14237 	/* Is there anything left to do? */
14238 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14239 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
14240 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
14241 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14242 		goto done;
14243 
14244 	/* Any transmit work to do and a non-zero window? */
14245 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
14246 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
14247 		if (flags & TH_REXMIT_NEEDED) {
14248 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
14249 
14250 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
14251 			if (snd_size > mss)
14252 				snd_size = mss;
14253 			if (snd_size > tcp->tcp_swnd)
14254 				snd_size = tcp->tcp_swnd;
14255 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
14256 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
14257 			    B_TRUE);
14258 
14259 			if (mp1 != NULL) {
14260 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14261 				tcp->tcp_csuna = tcp->tcp_snxt;
14262 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
14263 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
14264 				TCP_RECORD_TRACE(tcp, mp1,
14265 				    TCP_TRACE_SEND_PKT);
14266 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
14267 			}
14268 		}
14269 		if (flags & TH_NEED_SACK_REXMIT) {
14270 			tcp_sack_rxmit(tcp, &flags);
14271 		}
14272 		/*
14273 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
14274 		 * out new segment.  Note that tcp_rexmit should not be
14275 		 * set, otherwise TH_LIMIT_XMIT should not be set.
14276 		 */
14277 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
14278 			if (!tcp->tcp_rexmit) {
14279 				tcp_wput_data(tcp, NULL, B_FALSE);
14280 			} else {
14281 				tcp_ss_rexmit(tcp);
14282 			}
14283 		}
14284 		/*
14285 		 * Adjust tcp_cwnd back to normal value after sending
14286 		 * new data segments.
14287 		 */
14288 		if (flags & TH_LIMIT_XMIT) {
14289 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
14290 			/*
14291 			 * This will restart the timer.  Restarting the
14292 			 * timer is used to avoid a timeout before the
14293 			 * limited transmitted segment's ACK gets back.
14294 			 */
14295 			if (tcp->tcp_xmit_head != NULL)
14296 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14297 		}
14298 
14299 		/* Anything more to do? */
14300 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
14301 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14302 			goto done;
14303 	}
14304 ack_check:
14305 	if (flags & TH_SEND_URP_MARK) {
14306 		ASSERT(tcp->tcp_urp_mark_mp);
14307 		/*
14308 		 * Send up any queued data and then send the mark message
14309 		 */
14310 		if (tcp->tcp_rcv_list != NULL) {
14311 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14312 		}
14313 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14314 
14315 		mp1 = tcp->tcp_urp_mark_mp;
14316 		tcp->tcp_urp_mark_mp = NULL;
14317 #ifdef DEBUG
14318 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14319 		    "tcp_rput: sending zero-length %s %s",
14320 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
14321 		    "MSGNOTMARKNEXT"),
14322 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14323 #endif /* DEBUG */
14324 		putnext(tcp->tcp_rq, mp1);
14325 		flags &= ~TH_SEND_URP_MARK;
14326 	}
14327 	if (flags & TH_ACK_NEEDED) {
14328 		/*
14329 		 * Time to send an ack for some reason.
14330 		 */
14331 		mp1 = tcp_ack_mp(tcp);
14332 
14333 		if (mp1 != NULL) {
14334 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
14335 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
14336 			BUMP_LOCAL(tcp->tcp_obsegs);
14337 			BUMP_MIB(&tcp_mib, tcpOutAck);
14338 		}
14339 		if (tcp->tcp_ack_tid != 0) {
14340 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
14341 			tcp->tcp_ack_tid = 0;
14342 		}
14343 	}
14344 	if (flags & TH_ACK_TIMER_NEEDED) {
14345 		/*
14346 		 * Arrange for deferred ACK or push wait timeout.
14347 		 * Start timer if it is not already running.
14348 		 */
14349 		if (tcp->tcp_ack_tid == 0) {
14350 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
14351 			    MSEC_TO_TICK(tcp->tcp_localnet ?
14352 			    (clock_t)tcp_local_dack_interval :
14353 			    (clock_t)tcp_deferred_ack_interval));
14354 		}
14355 	}
14356 	if (flags & TH_ORDREL_NEEDED) {
14357 		/*
14358 		 * Send up the ordrel_ind unless we are an eager guy.
14359 		 * In the eager case tcp_rsrv will do this when run
14360 		 * after tcp_accept is done.
14361 		 */
14362 		ASSERT(tcp->tcp_listener == NULL);
14363 		if (tcp->tcp_rcv_list != NULL) {
14364 			/*
14365 			 * Push any mblk(s) enqueued from co processing.
14366 			 */
14367 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14368 		}
14369 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14370 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
14371 			tcp->tcp_ordrel_done = B_TRUE;
14372 			putnext(tcp->tcp_rq, mp1);
14373 			if (tcp->tcp_deferred_clean_death) {
14374 				/*
14375 				 * tcp_clean_death was deferred
14376 				 * for T_ORDREL_IND - do it now
14377 				 */
14378 				(void) tcp_clean_death(tcp,
14379 				    tcp->tcp_client_errno, 20);
14380 				tcp->tcp_deferred_clean_death =	B_FALSE;
14381 			}
14382 		} else {
14383 			/*
14384 			 * Run the orderly release in the
14385 			 * service routine.
14386 			 */
14387 			qenable(tcp->tcp_rq);
14388 			/*
14389 			 * Caveat(XXX): The machine may be so
14390 			 * overloaded that tcp_rsrv() is not scheduled
14391 			 * until after the endpoint has transitioned
14392 			 * to TCPS_TIME_WAIT
14393 			 * and tcp_time_wait_interval expires. Then
14394 			 * tcp_timer() will blow away state in tcp_t
14395 			 * and T_ORDREL_IND will never be delivered
14396 			 * upstream. Unlikely but potentially
14397 			 * a problem.
14398 			 */
14399 		}
14400 	}
14401 done:
14402 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14403 }
14404 
14405 /*
14406  * This function does PAWS protection check. Returns B_TRUE if the
14407  * segment passes the PAWS test, else returns B_FALSE.
14408  */
14409 boolean_t
14410 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
14411 {
14412 	uint8_t	flags;
14413 	int	options;
14414 	uint8_t *up;
14415 
14416 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
14417 	/*
14418 	 * If timestamp option is aligned nicely, get values inline,
14419 	 * otherwise call general routine to parse.  Only do that
14420 	 * if timestamp is the only option.
14421 	 */
14422 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
14423 	    TCPOPT_REAL_TS_LEN &&
14424 	    OK_32PTR((up = ((uint8_t *)tcph) +
14425 	    TCP_MIN_HEADER_LENGTH)) &&
14426 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
14427 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
14428 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
14429 
14430 		options = TCP_OPT_TSTAMP_PRESENT;
14431 	} else {
14432 		if (tcp->tcp_snd_sack_ok) {
14433 			tcpoptp->tcp = tcp;
14434 		} else {
14435 			tcpoptp->tcp = NULL;
14436 		}
14437 		options = tcp_parse_options(tcph, tcpoptp);
14438 	}
14439 
14440 	if (options & TCP_OPT_TSTAMP_PRESENT) {
14441 		/*
14442 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
14443 		 * regardless of the timestamp, page 18 RFC 1323.bis.
14444 		 */
14445 		if ((flags & TH_RST) == 0 &&
14446 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
14447 		    tcp->tcp_ts_recent)) {
14448 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
14449 			    PAWS_TIMEOUT)) {
14450 				/* This segment is not acceptable. */
14451 				return (B_FALSE);
14452 			} else {
14453 				/*
14454 				 * Connection has been idle for
14455 				 * too long.  Reset the timestamp
14456 				 * and assume the segment is valid.
14457 				 */
14458 				tcp->tcp_ts_recent =
14459 				    tcpoptp->tcp_opt_ts_val;
14460 			}
14461 		}
14462 	} else {
14463 		/*
14464 		 * If we don't get a timestamp on every packet, we
14465 		 * figure we can't really trust 'em, so we stop sending
14466 		 * and parsing them.
14467 		 */
14468 		tcp->tcp_snd_ts_ok = B_FALSE;
14469 
14470 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14471 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14472 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
14473 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
14474 		if (tcp->tcp_snd_sack_ok) {
14475 			ASSERT(tcp->tcp_sack_info != NULL);
14476 			tcp->tcp_max_sack_blk = 4;
14477 		}
14478 	}
14479 	return (B_TRUE);
14480 }
14481 
14482 /*
14483  * Attach ancillary data to a received TCP segments for the
14484  * ancillary pieces requested by the application that are
14485  * different than they were in the previous data segment.
14486  *
14487  * Save the "current" values once memory allocation is ok so that
14488  * when memory allocation fails we can just wait for the next data segment.
14489  */
14490 static mblk_t *
14491 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
14492 {
14493 	struct T_optdata_ind *todi;
14494 	int optlen;
14495 	uchar_t *optptr;
14496 	struct T_opthdr *toh;
14497 	uint_t addflag;	/* Which pieces to add */
14498 	mblk_t *mp1;
14499 
14500 	optlen = 0;
14501 	addflag = 0;
14502 	/* If app asked for pktinfo and the index has changed ... */
14503 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
14504 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
14505 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
14506 		optlen += sizeof (struct T_opthdr) +
14507 		    sizeof (struct in6_pktinfo);
14508 		addflag |= TCP_IPV6_RECVPKTINFO;
14509 	}
14510 	/* If app asked for hoplimit and it has changed ... */
14511 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
14512 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
14513 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
14514 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14515 		addflag |= TCP_IPV6_RECVHOPLIMIT;
14516 	}
14517 	/* If app asked for tclass and it has changed ... */
14518 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
14519 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
14520 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
14521 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14522 		addflag |= TCP_IPV6_RECVTCLASS;
14523 	}
14524 	/* If app asked for hopbyhop headers and it has changed ... */
14525 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
14526 	    tcp_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
14527 		(ipp->ipp_fields & IPPF_HOPOPTS),
14528 		ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
14529 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
14530 		addflag |= TCP_IPV6_RECVHOPOPTS;
14531 		if (!tcp_allocbuf((void **)&tcp->tcp_hopopts,
14532 		    &tcp->tcp_hopoptslen,
14533 		    (ipp->ipp_fields & IPPF_HOPOPTS),
14534 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
14535 			return (mp);
14536 	}
14537 	/* If app asked for dst headers before routing headers ... */
14538 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
14539 	    tcp_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
14540 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
14541 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
14542 		optlen += sizeof (struct T_opthdr) +
14543 		    ipp->ipp_rtdstoptslen;
14544 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
14545 		if (!tcp_allocbuf((void **)&tcp->tcp_rtdstopts,
14546 		    &tcp->tcp_rtdstoptslen,
14547 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
14548 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
14549 			return (mp);
14550 	}
14551 	/* If app asked for routing headers and it has changed ... */
14552 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
14553 	    tcp_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
14554 		(ipp->ipp_fields & IPPF_RTHDR),
14555 		ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
14556 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
14557 		addflag |= TCP_IPV6_RECVRTHDR;
14558 		if (!tcp_allocbuf((void **)&tcp->tcp_rthdr,
14559 		    &tcp->tcp_rthdrlen,
14560 		    (ipp->ipp_fields & IPPF_RTHDR),
14561 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
14562 			return (mp);
14563 	}
14564 	/* If app asked for dest headers and it has changed ... */
14565 	if ((tcp->tcp_ipv6_recvancillary &
14566 		(TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
14567 	    tcp_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
14568 		(ipp->ipp_fields & IPPF_DSTOPTS),
14569 		ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
14570 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
14571 		addflag |= TCP_IPV6_RECVDSTOPTS;
14572 		if (!tcp_allocbuf((void **)&tcp->tcp_dstopts,
14573 		    &tcp->tcp_dstoptslen,
14574 		    (ipp->ipp_fields & IPPF_DSTOPTS),
14575 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
14576 			return (mp);
14577 	}
14578 
14579 	if (optlen == 0) {
14580 		/* Nothing to add */
14581 		return (mp);
14582 	}
14583 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
14584 	if (mp1 == NULL) {
14585 		/*
14586 		 * Defer sending ancillary data until the next TCP segment
14587 		 * arrives.
14588 		 */
14589 		return (mp);
14590 	}
14591 	mp1->b_cont = mp;
14592 	mp = mp1;
14593 	mp->b_wptr += sizeof (*todi) + optlen;
14594 	mp->b_datap->db_type = M_PROTO;
14595 	todi = (struct T_optdata_ind *)mp->b_rptr;
14596 	todi->PRIM_type = T_OPTDATA_IND;
14597 	todi->DATA_flag = 1;	/* MORE data */
14598 	todi->OPT_length = optlen;
14599 	todi->OPT_offset = sizeof (*todi);
14600 	optptr = (uchar_t *)&todi[1];
14601 	/*
14602 	 * If app asked for pktinfo and the index has changed ...
14603 	 * Note that the local address never changes for the connection.
14604 	 */
14605 	if (addflag & TCP_IPV6_RECVPKTINFO) {
14606 		struct in6_pktinfo *pkti;
14607 
14608 		toh = (struct T_opthdr *)optptr;
14609 		toh->level = IPPROTO_IPV6;
14610 		toh->name = IPV6_PKTINFO;
14611 		toh->len = sizeof (*toh) + sizeof (*pkti);
14612 		toh->status = 0;
14613 		optptr += sizeof (*toh);
14614 		pkti = (struct in6_pktinfo *)optptr;
14615 		if (tcp->tcp_ipversion == IPV6_VERSION)
14616 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
14617 		else
14618 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
14619 			    &pkti->ipi6_addr);
14620 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
14621 		optptr += sizeof (*pkti);
14622 		ASSERT(OK_32PTR(optptr));
14623 		/* Save as "last" value */
14624 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
14625 	}
14626 	/* If app asked for hoplimit and it has changed ... */
14627 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
14628 		toh = (struct T_opthdr *)optptr;
14629 		toh->level = IPPROTO_IPV6;
14630 		toh->name = IPV6_HOPLIMIT;
14631 		toh->len = sizeof (*toh) + sizeof (uint_t);
14632 		toh->status = 0;
14633 		optptr += sizeof (*toh);
14634 		*(uint_t *)optptr = ipp->ipp_hoplimit;
14635 		optptr += sizeof (uint_t);
14636 		ASSERT(OK_32PTR(optptr));
14637 		/* Save as "last" value */
14638 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
14639 	}
14640 	/* If app asked for tclass and it has changed ... */
14641 	if (addflag & TCP_IPV6_RECVTCLASS) {
14642 		toh = (struct T_opthdr *)optptr;
14643 		toh->level = IPPROTO_IPV6;
14644 		toh->name = IPV6_TCLASS;
14645 		toh->len = sizeof (*toh) + sizeof (uint_t);
14646 		toh->status = 0;
14647 		optptr += sizeof (*toh);
14648 		*(uint_t *)optptr = ipp->ipp_tclass;
14649 		optptr += sizeof (uint_t);
14650 		ASSERT(OK_32PTR(optptr));
14651 		/* Save as "last" value */
14652 		tcp->tcp_recvtclass = ipp->ipp_tclass;
14653 	}
14654 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
14655 		toh = (struct T_opthdr *)optptr;
14656 		toh->level = IPPROTO_IPV6;
14657 		toh->name = IPV6_HOPOPTS;
14658 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
14659 		toh->status = 0;
14660 		optptr += sizeof (*toh);
14661 		bcopy(ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
14662 		optptr += ipp->ipp_hopoptslen;
14663 		ASSERT(OK_32PTR(optptr));
14664 		/* Save as last value */
14665 		tcp_savebuf((void **)&tcp->tcp_hopopts,
14666 		    &tcp->tcp_hopoptslen,
14667 		    (ipp->ipp_fields & IPPF_HOPOPTS),
14668 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14669 	}
14670 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
14671 		toh = (struct T_opthdr *)optptr;
14672 		toh->level = IPPROTO_IPV6;
14673 		toh->name = IPV6_RTHDRDSTOPTS;
14674 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
14675 		toh->status = 0;
14676 		optptr += sizeof (*toh);
14677 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
14678 		optptr += ipp->ipp_rtdstoptslen;
14679 		ASSERT(OK_32PTR(optptr));
14680 		/* Save as last value */
14681 		tcp_savebuf((void **)&tcp->tcp_rtdstopts,
14682 		    &tcp->tcp_rtdstoptslen,
14683 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
14684 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
14685 	}
14686 	if (addflag & TCP_IPV6_RECVRTHDR) {
14687 		toh = (struct T_opthdr *)optptr;
14688 		toh->level = IPPROTO_IPV6;
14689 		toh->name = IPV6_RTHDR;
14690 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
14691 		toh->status = 0;
14692 		optptr += sizeof (*toh);
14693 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
14694 		optptr += ipp->ipp_rthdrlen;
14695 		ASSERT(OK_32PTR(optptr));
14696 		/* Save as last value */
14697 		tcp_savebuf((void **)&tcp->tcp_rthdr,
14698 		    &tcp->tcp_rthdrlen,
14699 		    (ipp->ipp_fields & IPPF_RTHDR),
14700 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14701 	}
14702 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
14703 		toh = (struct T_opthdr *)optptr;
14704 		toh->level = IPPROTO_IPV6;
14705 		toh->name = IPV6_DSTOPTS;
14706 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
14707 		toh->status = 0;
14708 		optptr += sizeof (*toh);
14709 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
14710 		optptr += ipp->ipp_dstoptslen;
14711 		ASSERT(OK_32PTR(optptr));
14712 		/* Save as last value */
14713 		tcp_savebuf((void **)&tcp->tcp_dstopts,
14714 		    &tcp->tcp_dstoptslen,
14715 		    (ipp->ipp_fields & IPPF_DSTOPTS),
14716 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14717 	}
14718 	ASSERT(optptr == mp->b_wptr);
14719 	return (mp);
14720 }
14721 
14722 
14723 /*
14724  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
14725  * or a "bad" IRE detected by tcp_adapt_ire.
14726  * We can't tell if the failure was due to the laddr or the faddr
14727  * thus we clear out all addresses and ports.
14728  */
14729 static void
14730 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
14731 {
14732 	queue_t	*q = tcp->tcp_rq;
14733 	tcph_t	*tcph;
14734 	struct T_error_ack *tea;
14735 	conn_t	*connp = tcp->tcp_connp;
14736 
14737 
14738 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
14739 
14740 	if (mp->b_cont) {
14741 		freemsg(mp->b_cont);
14742 		mp->b_cont = NULL;
14743 	}
14744 	tea = (struct T_error_ack *)mp->b_rptr;
14745 	switch (tea->PRIM_type) {
14746 	case T_BIND_ACK:
14747 		/*
14748 		 * Need to unbind with classifier since we were just told that
14749 		 * our bind succeeded.
14750 		 */
14751 		tcp->tcp_hard_bound = B_FALSE;
14752 		tcp->tcp_hard_binding = B_FALSE;
14753 
14754 		ipcl_hash_remove(connp);
14755 		/* Reuse the mblk if possible */
14756 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
14757 			sizeof (*tea));
14758 		mp->b_rptr = mp->b_datap->db_base;
14759 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
14760 		tea = (struct T_error_ack *)mp->b_rptr;
14761 		tea->PRIM_type = T_ERROR_ACK;
14762 		tea->TLI_error = TSYSERR;
14763 		tea->UNIX_error = error;
14764 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
14765 			tea->ERROR_prim = T_CONN_REQ;
14766 		} else {
14767 			tea->ERROR_prim = O_T_BIND_REQ;
14768 		}
14769 		break;
14770 
14771 	case T_ERROR_ACK:
14772 		if (tcp->tcp_state >= TCPS_SYN_SENT)
14773 			tea->ERROR_prim = T_CONN_REQ;
14774 		break;
14775 	default:
14776 		panic("tcp_bind_failed: unexpected TPI type");
14777 		/*NOTREACHED*/
14778 	}
14779 
14780 	tcp->tcp_state = TCPS_IDLE;
14781 	if (tcp->tcp_ipversion == IPV4_VERSION)
14782 		tcp->tcp_ipha->ipha_src = 0;
14783 	else
14784 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
14785 	/*
14786 	 * Copy of the src addr. in tcp_t is needed since
14787 	 * the lookup funcs. can only look at tcp_t
14788 	 */
14789 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
14790 
14791 	tcph = tcp->tcp_tcph;
14792 	tcph->th_lport[0] = 0;
14793 	tcph->th_lport[1] = 0;
14794 	tcp_bind_hash_remove(tcp);
14795 	bzero(&connp->u_port, sizeof (connp->u_port));
14796 	/* blow away saved option results if any */
14797 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
14798 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
14799 
14800 	conn_delete_ire(tcp->tcp_connp, NULL);
14801 	putnext(q, mp);
14802 }
14803 
14804 /*
14805  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
14806  * messages.
14807  */
14808 void
14809 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
14810 {
14811 	mblk_t	*mp1;
14812 	uchar_t	*rptr = mp->b_rptr;
14813 	queue_t	*q = tcp->tcp_rq;
14814 	struct T_error_ack *tea;
14815 	uint32_t mss;
14816 	mblk_t *syn_mp;
14817 	mblk_t *mdti;
14818 	int	retval;
14819 	mblk_t *ire_mp;
14820 
14821 	switch (mp->b_datap->db_type) {
14822 	case M_PROTO:
14823 	case M_PCPROTO:
14824 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
14825 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
14826 			break;
14827 		tea = (struct T_error_ack *)rptr;
14828 		switch (tea->PRIM_type) {
14829 		case T_BIND_ACK:
14830 			/*
14831 			 * Adapt Multidata information, if any.  The
14832 			 * following tcp_mdt_update routine will free
14833 			 * the message.
14834 			 */
14835 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
14836 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
14837 				    b_rptr)->mdt_capab, B_TRUE);
14838 				freemsg(mdti);
14839 			}
14840 
14841 			/* Get the IRE, if we had requested for it */
14842 			ire_mp = tcp_ire_mp(mp);
14843 
14844 			if (tcp->tcp_hard_binding) {
14845 				tcp->tcp_hard_binding = B_FALSE;
14846 				tcp->tcp_hard_bound = B_TRUE;
14847 				CL_INET_CONNECT(tcp);
14848 			} else {
14849 				if (ire_mp != NULL)
14850 					freeb(ire_mp);
14851 				goto after_syn_sent;
14852 			}
14853 
14854 			retval = tcp_adapt_ire(tcp, ire_mp);
14855 			if (ire_mp != NULL)
14856 				freeb(ire_mp);
14857 			if (retval == 0) {
14858 				tcp_bind_failed(tcp, mp,
14859 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
14860 				    ENETUNREACH : EADDRNOTAVAIL));
14861 				return;
14862 			}
14863 			/*
14864 			 * Don't let an endpoint connect to itself.
14865 			 * Also checked in tcp_connect() but that
14866 			 * check can't handle the case when the
14867 			 * local IP address is INADDR_ANY.
14868 			 */
14869 			if (tcp->tcp_ipversion == IPV4_VERSION) {
14870 				if ((tcp->tcp_ipha->ipha_dst ==
14871 				    tcp->tcp_ipha->ipha_src) &&
14872 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
14873 				    tcp->tcp_tcph->th_fport))) {
14874 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
14875 					return;
14876 				}
14877 			} else {
14878 				if (IN6_ARE_ADDR_EQUAL(
14879 				    &tcp->tcp_ip6h->ip6_dst,
14880 				    &tcp->tcp_ip6h->ip6_src) &&
14881 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
14882 				    tcp->tcp_tcph->th_fport))) {
14883 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
14884 					return;
14885 				}
14886 			}
14887 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
14888 			/*
14889 			 * This should not be possible!  Just for
14890 			 * defensive coding...
14891 			 */
14892 			if (tcp->tcp_state != TCPS_SYN_SENT)
14893 				goto after_syn_sent;
14894 
14895 			ASSERT(q == tcp->tcp_rq);
14896 			/*
14897 			 * tcp_adapt_ire() does not adjust
14898 			 * for TCP/IP header length.
14899 			 */
14900 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
14901 
14902 			/*
14903 			 * Just make sure our rwnd is at
14904 			 * least tcp_recv_hiwat_mss * MSS
14905 			 * large, and round up to the nearest
14906 			 * MSS.
14907 			 *
14908 			 * We do the round up here because
14909 			 * we need to get the interface
14910 			 * MTU first before we can do the
14911 			 * round up.
14912 			 */
14913 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
14914 			    tcp_recv_hiwat_minmss * mss);
14915 			q->q_hiwat = tcp->tcp_rwnd;
14916 			tcp_set_ws_value(tcp);
14917 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
14918 			    tcp->tcp_tcph->th_win);
14919 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
14920 				tcp->tcp_snd_ws_ok = B_TRUE;
14921 
14922 			/*
14923 			 * Set tcp_snd_ts_ok to true
14924 			 * so that tcp_xmit_mp will
14925 			 * include the timestamp
14926 			 * option in the SYN segment.
14927 			 */
14928 			if (tcp_tstamp_always ||
14929 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
14930 				tcp->tcp_snd_ts_ok = B_TRUE;
14931 			}
14932 
14933 			/*
14934 			 * tcp_snd_sack_ok can be set in
14935 			 * tcp_adapt_ire() if the sack metric
14936 			 * is set.  So check it here also.
14937 			 */
14938 			if (tcp_sack_permitted == 2 ||
14939 			    tcp->tcp_snd_sack_ok) {
14940 				if (tcp->tcp_sack_info == NULL) {
14941 					tcp->tcp_sack_info =
14942 					kmem_cache_alloc(tcp_sack_info_cache,
14943 					    KM_SLEEP);
14944 				}
14945 				tcp->tcp_snd_sack_ok = B_TRUE;
14946 			}
14947 
14948 			/*
14949 			 * Should we use ECN?  Note that the current
14950 			 * default value (SunOS 5.9) of tcp_ecn_permitted
14951 			 * is 1.  The reason for doing this is that there
14952 			 * are equipments out there that will drop ECN
14953 			 * enabled IP packets.  Setting it to 1 avoids
14954 			 * compatibility problems.
14955 			 */
14956 			if (tcp_ecn_permitted == 2)
14957 				tcp->tcp_ecn_ok = B_TRUE;
14958 
14959 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14960 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
14961 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
14962 			if (syn_mp) {
14963 				cred_t *cr;
14964 				pid_t pid;
14965 
14966 				/*
14967 				 * Obtain the credential from the
14968 				 * thread calling connect(); the credential
14969 				 * lives on in the second mblk which
14970 				 * originated from T_CONN_REQ and is echoed
14971 				 * with the T_BIND_ACK from ip.  If none
14972 				 * can be found, default to the creator
14973 				 * of the socket.
14974 				 */
14975 				if (mp->b_cont == NULL ||
14976 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
14977 					cr = tcp->tcp_cred;
14978 					pid = tcp->tcp_cpid;
14979 				} else {
14980 					pid = DB_CPID(mp->b_cont);
14981 				}
14982 
14983 				TCP_RECORD_TRACE(tcp, syn_mp,
14984 				    TCP_TRACE_SEND_PKT);
14985 				mblk_setcred(syn_mp, cr);
14986 				DB_CPID(syn_mp) = pid;
14987 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
14988 			}
14989 		after_syn_sent:
14990 			/*
14991 			 * A trailer mblk indicates a waiting client upstream.
14992 			 * We complete here the processing begun in
14993 			 * either tcp_bind() or tcp_connect() by passing
14994 			 * upstream the reply message they supplied.
14995 			 */
14996 			mp1 = mp;
14997 			mp = mp->b_cont;
14998 			freeb(mp1);
14999 			if (mp)
15000 				break;
15001 			return;
15002 		case T_ERROR_ACK:
15003 			if (tcp->tcp_debug) {
15004 				(void) strlog(TCP_MOD_ID, 0, 1,
15005 				    SL_TRACE|SL_ERROR,
15006 				    "tcp_rput_other: case T_ERROR_ACK, "
15007 				    "ERROR_prim == %d",
15008 				    tea->ERROR_prim);
15009 			}
15010 			switch (tea->ERROR_prim) {
15011 			case O_T_BIND_REQ:
15012 			case T_BIND_REQ:
15013 				tcp_bind_failed(tcp, mp,
15014 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15015 				    ENETUNREACH : EADDRNOTAVAIL));
15016 				return;
15017 			case T_UNBIND_REQ:
15018 				tcp->tcp_hard_binding = B_FALSE;
15019 				tcp->tcp_hard_bound = B_FALSE;
15020 				if (mp->b_cont) {
15021 					freemsg(mp->b_cont);
15022 					mp->b_cont = NULL;
15023 				}
15024 				if (tcp->tcp_unbind_pending)
15025 					tcp->tcp_unbind_pending = 0;
15026 				else {
15027 					/* From tcp_ip_unbind() - free */
15028 					freemsg(mp);
15029 					return;
15030 				}
15031 				break;
15032 			case T_SVR4_OPTMGMT_REQ:
15033 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15034 					/* T_OPTMGMT_REQ generated by TCP */
15035 					printf("T_SVR4_OPTMGMT_REQ failed "
15036 					    "%d/%d - dropped (cnt %d)\n",
15037 					    tea->TLI_error, tea->UNIX_error,
15038 					    tcp->tcp_drop_opt_ack_cnt);
15039 					freemsg(mp);
15040 					tcp->tcp_drop_opt_ack_cnt--;
15041 					return;
15042 				}
15043 				break;
15044 			}
15045 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15046 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15047 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15048 				    "- dropped (cnt %d)\n",
15049 				    tea->TLI_error, tea->UNIX_error,
15050 				    tcp->tcp_drop_opt_ack_cnt);
15051 				freemsg(mp);
15052 				tcp->tcp_drop_opt_ack_cnt--;
15053 				return;
15054 			}
15055 			break;
15056 		case T_OPTMGMT_ACK:
15057 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15058 				/* T_OPTMGMT_REQ generated by TCP */
15059 				freemsg(mp);
15060 				tcp->tcp_drop_opt_ack_cnt--;
15061 				return;
15062 			}
15063 			break;
15064 		default:
15065 			break;
15066 		}
15067 		break;
15068 	case M_CTL:
15069 		/*
15070 		 * ICMP messages.
15071 		 */
15072 		tcp_icmp_error(tcp, mp);
15073 		return;
15074 	case M_FLUSH:
15075 		if (*rptr & FLUSHR)
15076 			flushq(q, FLUSHDATA);
15077 		break;
15078 	default:
15079 		break;
15080 	}
15081 	/*
15082 	 * Make sure we set this bit before sending the ACK for
15083 	 * bind. Otherwise accept could possibly run and free
15084 	 * this tcp struct.
15085 	 */
15086 	putnext(q, mp);
15087 }
15088 
15089 /*
15090  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15091  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15092  * tcp_rsrv() try again.
15093  */
15094 static void
15095 tcp_ordrel_kick(void *arg)
15096 {
15097 	conn_t 	*connp = (conn_t *)arg;
15098 	tcp_t	*tcp = connp->conn_tcp;
15099 
15100 	tcp->tcp_ordrelid = 0;
15101 	tcp->tcp_timeout = B_FALSE;
15102 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15103 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15104 		qenable(tcp->tcp_rq);
15105 	}
15106 }
15107 
15108 /* ARGSUSED */
15109 static void
15110 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15111 {
15112 	conn_t	*connp = (conn_t *)arg;
15113 	tcp_t	*tcp = connp->conn_tcp;
15114 	queue_t	*q = tcp->tcp_rq;
15115 	uint_t	thwin;
15116 
15117 	freeb(mp);
15118 
15119 	TCP_STAT(tcp_rsrv_calls);
15120 
15121 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15122 		return;
15123 	}
15124 
15125 	if (tcp->tcp_fused) {
15126 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15127 
15128 		ASSERT(tcp->tcp_fused);
15129 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15130 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15131 		ASSERT(!TCP_IS_DETACHED(tcp));
15132 		ASSERT(tcp->tcp_connp->conn_sqp ==
15133 		    peer_tcp->tcp_connp->conn_sqp);
15134 
15135 		/*
15136 		 * Normally we would not get backenabled in synchronous
15137 		 * streams mode, but in case this happens, we need to stop
15138 		 * synchronous streams temporarily to prevent a race with
15139 		 * tcp_fuse_rrw() or tcp_fuse_rinfop().  It is safe to access
15140 		 * tcp_rcv_list here because those entry points will return
15141 		 * right away when synchronous streams is stopped.
15142 		 */
15143 		TCP_FUSE_SYNCSTR_STOP(tcp);
15144 		if (tcp->tcp_rcv_list != NULL)
15145 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15146 
15147 		tcp_clrqfull(peer_tcp);
15148 		TCP_FUSE_SYNCSTR_RESUME(tcp);
15149 		TCP_STAT(tcp_fusion_backenabled);
15150 		return;
15151 	}
15152 
15153 	if (canputnext(q)) {
15154 		tcp->tcp_rwnd = q->q_hiwat;
15155 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15156 		    << tcp->tcp_rcv_ws;
15157 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15158 		/*
15159 		 * Send back a window update immediately if TCP is above
15160 		 * ESTABLISHED state and the increase of the rcv window
15161 		 * that the other side knows is at least 1 MSS after flow
15162 		 * control is lifted.
15163 		 */
15164 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15165 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15166 			tcp_xmit_ctl(NULL, tcp,
15167 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15168 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15169 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
15170 		}
15171 	}
15172 	/* Handle a failure to allocate a T_ORDREL_IND here */
15173 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15174 		ASSERT(tcp->tcp_listener == NULL);
15175 		if (tcp->tcp_rcv_list != NULL) {
15176 			(void) tcp_rcv_drain(q, tcp);
15177 		}
15178 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15179 		mp = mi_tpi_ordrel_ind();
15180 		if (mp) {
15181 			tcp->tcp_ordrel_done = B_TRUE;
15182 			putnext(q, mp);
15183 			if (tcp->tcp_deferred_clean_death) {
15184 				/*
15185 				 * tcp_clean_death was deferred for
15186 				 * T_ORDREL_IND - do it now
15187 				 */
15188 				tcp->tcp_deferred_clean_death = B_FALSE;
15189 				(void) tcp_clean_death(tcp,
15190 				    tcp->tcp_client_errno, 22);
15191 			}
15192 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15193 			/*
15194 			 * If there isn't already a timer running
15195 			 * start one.  Use a 4 second
15196 			 * timer as a fallback since it can't fail.
15197 			 */
15198 			tcp->tcp_timeout = B_TRUE;
15199 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15200 			    MSEC_TO_TICK(4000));
15201 		}
15202 	}
15203 }
15204 
15205 /*
15206  * The read side service routine is called mostly when we get back-enabled as a
15207  * result of flow control relief.  Since we don't actually queue anything in
15208  * TCP, we have no data to send out of here.  What we do is clear the receive
15209  * window, and send out a window update.
15210  * This routine is also called to drive an orderly release message upstream
15211  * if the attempt in tcp_rput failed.
15212  */
15213 static void
15214 tcp_rsrv(queue_t *q)
15215 {
15216 	conn_t *connp = Q_TO_CONN(q);
15217 	tcp_t	*tcp = connp->conn_tcp;
15218 	mblk_t	*mp;
15219 
15220 	/* No code does a putq on the read side */
15221 	ASSERT(q->q_first == NULL);
15222 
15223 	/* Nothing to do for the default queue */
15224 	if (q == tcp_g_q) {
15225 		return;
15226 	}
15227 
15228 	mp = allocb(0, BPRI_HI);
15229 	if (mp == NULL) {
15230 		/*
15231 		 * We are under memory pressure. Return for now and we
15232 		 * we will be called again later.
15233 		 */
15234 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15235 			/*
15236 			 * If there isn't already a timer running
15237 			 * start one.  Use a 4 second
15238 			 * timer as a fallback since it can't fail.
15239 			 */
15240 			tcp->tcp_timeout = B_TRUE;
15241 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15242 			    MSEC_TO_TICK(4000));
15243 		}
15244 		return;
15245 	}
15246 	CONN_INC_REF(connp);
15247 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15248 	    SQTAG_TCP_RSRV);
15249 }
15250 
15251 /*
15252  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15253  * We do not allow the receive window to shrink.  After setting rwnd,
15254  * set the flow control hiwat of the stream.
15255  *
15256  * This function is called in 2 cases:
15257  *
15258  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15259  *    connection (passive open) and in tcp_rput_data() for active connect.
15260  *    This is called after tcp_mss_set() when the desired MSS value is known.
15261  *    This makes sure that our window size is a mutiple of the other side's
15262  *    MSS.
15263  * 2) Handling SO_RCVBUF option.
15264  *
15265  * It is ASSUMED that the requested size is a multiple of the current MSS.
15266  *
15267  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15268  * user requests so.
15269  */
15270 static int
15271 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15272 {
15273 	uint32_t	mss = tcp->tcp_mss;
15274 	uint32_t	old_max_rwnd;
15275 	uint32_t	max_transmittable_rwnd;
15276 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15277 
15278 	if (tcp->tcp_fused) {
15279 		size_t sth_hiwat;
15280 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15281 
15282 		ASSERT(peer_tcp != NULL);
15283 		/*
15284 		 * Record the stream head's high water mark for
15285 		 * this endpoint; this is used for flow-control
15286 		 * purposes in tcp_fuse_output().
15287 		 */
15288 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15289 		if (!tcp_detached)
15290 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
15291 
15292 		/*
15293 		 * In the fusion case, the maxpsz stream head value of
15294 		 * our peer is set according to its send buffer size
15295 		 * and our receive buffer size; since the latter may
15296 		 * have changed we need to update the peer's maxpsz.
15297 		 */
15298 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15299 		return (rwnd);
15300 	}
15301 
15302 	if (tcp_detached)
15303 		old_max_rwnd = tcp->tcp_rwnd;
15304 	else
15305 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
15306 
15307 	/*
15308 	 * Insist on a receive window that is at least
15309 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15310 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15311 	 * and delayed acknowledgement.
15312 	 */
15313 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
15314 
15315 	/*
15316 	 * If window size info has already been exchanged, TCP should not
15317 	 * shrink the window.  Shrinking window is doable if done carefully.
15318 	 * We may add that support later.  But so far there is not a real
15319 	 * need to do that.
15320 	 */
15321 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15322 		/* MSS may have changed, do a round up again. */
15323 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15324 	}
15325 
15326 	/*
15327 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15328 	 * can be applied even before the window scale option is decided.
15329 	 */
15330 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15331 	if (rwnd > max_transmittable_rwnd) {
15332 		rwnd = max_transmittable_rwnd -
15333 		    (max_transmittable_rwnd % mss);
15334 		if (rwnd < mss)
15335 			rwnd = max_transmittable_rwnd;
15336 		/*
15337 		 * If we're over the limit we may have to back down tcp_rwnd.
15338 		 * The increment below won't work for us. So we set all three
15339 		 * here and the increment below will have no effect.
15340 		 */
15341 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15342 	}
15343 	if (tcp->tcp_localnet) {
15344 		tcp->tcp_rack_abs_max =
15345 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
15346 	} else {
15347 		/*
15348 		 * For a remote host on a different subnet (through a router),
15349 		 * we ack every other packet to be conforming to RFC1122.
15350 		 * tcp_deferred_acks_max is default to 2.
15351 		 */
15352 		tcp->tcp_rack_abs_max =
15353 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
15354 	}
15355 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15356 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15357 	else
15358 		tcp->tcp_rack_cur_max = 0;
15359 	/*
15360 	 * Increment the current rwnd by the amount the maximum grew (we
15361 	 * can not overwrite it since we might be in the middle of a
15362 	 * connection.)
15363 	 */
15364 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15365 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15366 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15367 		tcp->tcp_cwnd_max = rwnd;
15368 
15369 	if (tcp_detached)
15370 		return (rwnd);
15371 	/*
15372 	 * We set the maximum receive window into rq->q_hiwat.
15373 	 * This is not actually used for flow control.
15374 	 */
15375 	tcp->tcp_rq->q_hiwat = rwnd;
15376 	/*
15377 	 * Set the Stream head high water mark. This doesn't have to be
15378 	 * here, since we are simply using default values, but we would
15379 	 * prefer to choose these values algorithmically, with a likely
15380 	 * relationship to rwnd.
15381 	 */
15382 	(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd, tcp_sth_rcv_hiwat));
15383 	return (rwnd);
15384 }
15385 
15386 /*
15387  * Return SNMP stuff in buffer in mpdata.
15388  */
15389 int
15390 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15391 {
15392 	mblk_t			*mpdata;
15393 	mblk_t			*mp_conn_ctl = NULL;
15394 	mblk_t			*mp_conn_data;
15395 	mblk_t			*mp6_conn_ctl = NULL;
15396 	mblk_t			*mp6_conn_data;
15397 	mblk_t			*mp_conn_tail = NULL;
15398 	mblk_t			*mp6_conn_tail = NULL;
15399 	struct opthdr		*optp;
15400 	mib2_tcpConnEntry_t	tce;
15401 	mib2_tcp6ConnEntry_t	tce6;
15402 	connf_t			*connfp;
15403 	conn_t			*connp;
15404 	int			i;
15405 	boolean_t 		ispriv;
15406 	zoneid_t 		zoneid;
15407 
15408 	if (mpctl == NULL ||
15409 	    (mpdata = mpctl->b_cont) == NULL ||
15410 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15411 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL) {
15412 		if (mp_conn_ctl != NULL)
15413 			freemsg(mp_conn_ctl);
15414 		if (mp6_conn_ctl != NULL)
15415 			freemsg(mp6_conn_ctl);
15416 		return (0);
15417 	}
15418 
15419 	/* build table of connections -- need count in fixed part */
15420 	mp_conn_data = mp_conn_ctl->b_cont;
15421 	mp6_conn_data = mp6_conn_ctl->b_cont;
15422 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
15423 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
15424 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
15425 	SET_MIB(tcp_mib.tcpMaxConn, -1);
15426 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
15427 
15428 	ispriv =
15429 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15430 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15431 
15432 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15433 
15434 		connfp = &ipcl_globalhash_fanout[i];
15435 
15436 		connp = NULL;
15437 
15438 		while ((connp =
15439 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15440 			tcp_t *tcp;
15441 
15442 			if (connp->conn_zoneid != zoneid)
15443 				continue;	/* not in this zone */
15444 
15445 			tcp = connp->conn_tcp;
15446 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
15447 			tcp->tcp_ibsegs = 0;
15448 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
15449 			tcp->tcp_obsegs = 0;
15450 
15451 			tce6.tcp6ConnState = tce.tcpConnState =
15452 			    tcp_snmp_state(tcp);
15453 			if (tce.tcpConnState == MIB2_TCP_established ||
15454 			    tce.tcpConnState == MIB2_TCP_closeWait)
15455 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
15456 
15457 			/* Create a message to report on IPv6 entries */
15458 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15459 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15460 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15461 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15462 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15463 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15464 			/* Don't want just anybody seeing these... */
15465 			if (ispriv) {
15466 				tce6.tcp6ConnEntryInfo.ce_snxt =
15467 				    tcp->tcp_snxt;
15468 				tce6.tcp6ConnEntryInfo.ce_suna =
15469 				    tcp->tcp_suna;
15470 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15471 				    tcp->tcp_rnxt;
15472 				tce6.tcp6ConnEntryInfo.ce_rack =
15473 				    tcp->tcp_rack;
15474 			} else {
15475 				/*
15476 				 * Netstat, unfortunately, uses this to
15477 				 * get send/receive queue sizes.  How to fix?
15478 				 * Why not compute the difference only?
15479 				 */
15480 				tce6.tcp6ConnEntryInfo.ce_snxt =
15481 				    tcp->tcp_snxt - tcp->tcp_suna;
15482 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
15483 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15484 				    tcp->tcp_rnxt - tcp->tcp_rack;
15485 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
15486 			}
15487 
15488 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15489 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15490 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
15491 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
15492 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
15493 			(void) snmp_append_data2(mp6_conn_data, &mp6_conn_tail,
15494 			    (char *)&tce6, sizeof (tce6));
15495 			}
15496 			/*
15497 			 * Create an IPv4 table entry for IPv4 entries and also
15498 			 * for IPv6 entries which are bound to in6addr_any
15499 			 * but don't have IPV6_V6ONLY set.
15500 			 * (i.e. anything an IPv4 peer could connect to)
15501 			 */
15502 			if (tcp->tcp_ipversion == IPV4_VERSION ||
15503 			    (tcp->tcp_state <= TCPS_LISTEN &&
15504 			    !tcp->tcp_connp->conn_ipv6_v6only &&
15505 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
15506 				if (tcp->tcp_ipversion == IPV6_VERSION) {
15507 					tce.tcpConnRemAddress = INADDR_ANY;
15508 					tce.tcpConnLocalAddress = INADDR_ANY;
15509 				} else {
15510 					tce.tcpConnRemAddress =
15511 					    tcp->tcp_remote;
15512 					tce.tcpConnLocalAddress =
15513 					    tcp->tcp_ip_src;
15514 				}
15515 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
15516 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
15517 				/* Don't want just anybody seeing these... */
15518 				if (ispriv) {
15519 					tce.tcpConnEntryInfo.ce_snxt =
15520 					    tcp->tcp_snxt;
15521 					tce.tcpConnEntryInfo.ce_suna =
15522 					    tcp->tcp_suna;
15523 					tce.tcpConnEntryInfo.ce_rnxt =
15524 					    tcp->tcp_rnxt;
15525 					tce.tcpConnEntryInfo.ce_rack =
15526 					    tcp->tcp_rack;
15527 				} else {
15528 					/*
15529 					 * Netstat, unfortunately, uses this to
15530 					 * get send/receive queue sizes.  How
15531 					 * to fix?
15532 					 * Why not compute the difference only?
15533 					 */
15534 					tce.tcpConnEntryInfo.ce_snxt =
15535 					    tcp->tcp_snxt - tcp->tcp_suna;
15536 					tce.tcpConnEntryInfo.ce_suna = 0;
15537 					tce.tcpConnEntryInfo.ce_rnxt =
15538 					    tcp->tcp_rnxt - tcp->tcp_rack;
15539 					tce.tcpConnEntryInfo.ce_rack = 0;
15540 				}
15541 
15542 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15543 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15544 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
15545 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
15546 				tce.tcpConnEntryInfo.ce_state =
15547 				    tcp->tcp_state;
15548 				(void) snmp_append_data2(mp_conn_data,
15549 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
15550 			}
15551 		}
15552 	}
15553 
15554 	/* fixed length structure for IPv4 and IPv6 counters */
15555 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
15556 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
15557 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
15558 	optp->level = MIB2_TCP;
15559 	optp->name = 0;
15560 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
15561 	optp->len = msgdsize(mpdata);
15562 	qreply(q, mpctl);
15563 
15564 	/* table of connections... */
15565 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
15566 	    sizeof (struct T_optmgmt_ack)];
15567 	optp->level = MIB2_TCP;
15568 	optp->name = MIB2_TCP_CONN;
15569 	optp->len = msgdsize(mp_conn_data);
15570 	qreply(q, mp_conn_ctl);
15571 
15572 	/* table of IPv6 connections... */
15573 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
15574 	    sizeof (struct T_optmgmt_ack)];
15575 	optp->level = MIB2_TCP6;
15576 	optp->name = MIB2_TCP6_CONN;
15577 	optp->len = msgdsize(mp6_conn_data);
15578 	qreply(q, mp6_conn_ctl);
15579 	return (1);
15580 }
15581 
15582 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
15583 /* ARGSUSED */
15584 int
15585 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
15586 {
15587 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
15588 
15589 	switch (level) {
15590 	case MIB2_TCP:
15591 		switch (name) {
15592 		case 13:
15593 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
15594 				return (0);
15595 			/* TODO: delete entry defined by tce */
15596 			return (1);
15597 		default:
15598 			return (0);
15599 		}
15600 	default:
15601 		return (1);
15602 	}
15603 }
15604 
15605 /* Translate TCP state to MIB2 TCP state. */
15606 static int
15607 tcp_snmp_state(tcp_t *tcp)
15608 {
15609 	if (tcp == NULL)
15610 		return (0);
15611 
15612 	switch (tcp->tcp_state) {
15613 	case TCPS_CLOSED:
15614 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
15615 	case TCPS_BOUND:
15616 		return (MIB2_TCP_closed);
15617 	case TCPS_LISTEN:
15618 		return (MIB2_TCP_listen);
15619 	case TCPS_SYN_SENT:
15620 		return (MIB2_TCP_synSent);
15621 	case TCPS_SYN_RCVD:
15622 		return (MIB2_TCP_synReceived);
15623 	case TCPS_ESTABLISHED:
15624 		return (MIB2_TCP_established);
15625 	case TCPS_CLOSE_WAIT:
15626 		return (MIB2_TCP_closeWait);
15627 	case TCPS_FIN_WAIT_1:
15628 		return (MIB2_TCP_finWait1);
15629 	case TCPS_CLOSING:
15630 		return (MIB2_TCP_closing);
15631 	case TCPS_LAST_ACK:
15632 		return (MIB2_TCP_lastAck);
15633 	case TCPS_FIN_WAIT_2:
15634 		return (MIB2_TCP_finWait2);
15635 	case TCPS_TIME_WAIT:
15636 		return (MIB2_TCP_timeWait);
15637 	default:
15638 		return (0);
15639 	}
15640 }
15641 
15642 static char tcp_report_header[] =
15643 	"TCP     " MI_COL_HDRPAD_STR
15644 	"zone dest            snxt     suna     "
15645 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
15646 	"recent   [lport,fport] state";
15647 
15648 /*
15649  * TCP status report triggered via the Named Dispatch mechanism.
15650  */
15651 /* ARGSUSED */
15652 static void
15653 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
15654     cred_t *cr)
15655 {
15656 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
15657 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
15658 	char cflag;
15659 	in6_addr_t	v6dst;
15660 	char buf[80];
15661 	uint_t print_len, buf_len;
15662 
15663 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
15664 	if (buf_len <= 0)
15665 		return;
15666 
15667 	if (hashval >= 0)
15668 		(void) sprintf(hash, "%03d ", hashval);
15669 	else
15670 		hash[0] = '\0';
15671 
15672 	/*
15673 	 * Note that we use the remote address in the tcp_b  structure.
15674 	 * This means that it will print out the real destination address,
15675 	 * not the next hop's address if source routing is used.  This
15676 	 * avoid the confusion on the output because user may not
15677 	 * know that source routing is used for a connection.
15678 	 */
15679 	if (tcp->tcp_ipversion == IPV4_VERSION) {
15680 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
15681 	} else {
15682 		v6dst = tcp->tcp_remote_v6;
15683 	}
15684 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
15685 	/*
15686 	 * the ispriv checks are so that normal users cannot determine
15687 	 * sequence number information using NDD.
15688 	 */
15689 
15690 	if (TCP_IS_DETACHED(tcp))
15691 		cflag = '*';
15692 	else
15693 		cflag = ' ';
15694 	print_len = snprintf((char *)mp->b_wptr, buf_len,
15695 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
15696 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
15697 	    hash,
15698 	    (void *)tcp,
15699 	    tcp->tcp_connp->conn_zoneid,
15700 	    addrbuf,
15701 	    (ispriv) ? tcp->tcp_snxt : 0,
15702 	    (ispriv) ? tcp->tcp_suna : 0,
15703 	    tcp->tcp_swnd,
15704 	    (ispriv) ? tcp->tcp_rnxt : 0,
15705 	    (ispriv) ? tcp->tcp_rack : 0,
15706 	    tcp->tcp_rwnd,
15707 	    tcp->tcp_rto,
15708 	    tcp->tcp_mss,
15709 	    tcp->tcp_snd_ws_ok,
15710 	    tcp->tcp_snd_ws,
15711 	    tcp->tcp_rcv_ws,
15712 	    tcp->tcp_snd_ts_ok,
15713 	    tcp->tcp_ts_recent,
15714 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
15715 	if (print_len < buf_len) {
15716 		((mblk_t *)mp)->b_wptr += print_len;
15717 	} else {
15718 		((mblk_t *)mp)->b_wptr += buf_len;
15719 	}
15720 }
15721 
15722 /*
15723  * TCP status report (for listeners only) triggered via the Named Dispatch
15724  * mechanism.
15725  */
15726 /* ARGSUSED */
15727 static void
15728 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
15729 {
15730 	char addrbuf[INET6_ADDRSTRLEN];
15731 	in6_addr_t	v6dst;
15732 	uint_t print_len, buf_len;
15733 
15734 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
15735 	if (buf_len <= 0)
15736 		return;
15737 
15738 	if (tcp->tcp_ipversion == IPV4_VERSION) {
15739 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
15740 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
15741 	} else {
15742 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
15743 		    addrbuf, sizeof (addrbuf));
15744 	}
15745 	print_len = snprintf((char *)mp->b_wptr, buf_len,
15746 	    "%03d "
15747 	    MI_COL_PTRFMT_STR
15748 	    "%d %s %05u %08u %d/%d/%d%c\n",
15749 	    hashval, (void *)tcp,
15750 	    tcp->tcp_connp->conn_zoneid,
15751 	    addrbuf,
15752 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
15753 	    tcp->tcp_conn_req_seqnum,
15754 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
15755 	    tcp->tcp_conn_req_max,
15756 	    tcp->tcp_syn_defense ? '*' : ' ');
15757 	if (print_len < buf_len) {
15758 		((mblk_t *)mp)->b_wptr += print_len;
15759 	} else {
15760 		((mblk_t *)mp)->b_wptr += buf_len;
15761 	}
15762 }
15763 
15764 /* TCP status report triggered via the Named Dispatch mechanism. */
15765 /* ARGSUSED */
15766 static int
15767 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15768 {
15769 	tcp_t	*tcp;
15770 	int	i;
15771 	conn_t	*connp;
15772 	connf_t	*connfp;
15773 	zoneid_t zoneid;
15774 
15775 	/*
15776 	 * Because of the ndd constraint, at most we can have 64K buffer
15777 	 * to put in all TCP info.  So to be more efficient, just
15778 	 * allocate a 64K buffer here, assuming we need that large buffer.
15779 	 * This may be a problem as any user can read tcp_status.  Therefore
15780 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
15781 	 * This should be OK as normal users should not do this too often.
15782 	 */
15783 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15784 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15785 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15786 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15787 			return (0);
15788 		}
15789 	}
15790 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15791 		/* The following may work even if we cannot get a large buf. */
15792 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15793 		return (0);
15794 	}
15795 
15796 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
15797 
15798 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15799 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15800 
15801 		connfp = &ipcl_globalhash_fanout[i];
15802 
15803 		connp = NULL;
15804 
15805 		while ((connp =
15806 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15807 			tcp = connp->conn_tcp;
15808 			if (zoneid != GLOBAL_ZONEID &&
15809 			    zoneid != connp->conn_zoneid)
15810 				continue;
15811 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
15812 			    cr);
15813 		}
15814 
15815 	}
15816 
15817 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15818 	return (0);
15819 }
15820 
15821 /* TCP status report triggered via the Named Dispatch mechanism. */
15822 /* ARGSUSED */
15823 static int
15824 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15825 {
15826 	tf_t	*tbf;
15827 	tcp_t	*tcp;
15828 	int	i;
15829 	zoneid_t zoneid;
15830 
15831 	/* Refer to comments in tcp_status_report(). */
15832 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15833 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15834 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15835 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15836 			return (0);
15837 		}
15838 	}
15839 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15840 		/* The following may work even if we cannot get a large buf. */
15841 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15842 		return (0);
15843 	}
15844 
15845 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
15846 
15847 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15848 
15849 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
15850 		tbf = &tcp_bind_fanout[i];
15851 		mutex_enter(&tbf->tf_lock);
15852 		for (tcp = tbf->tf_tcp; tcp != NULL;
15853 		    tcp = tcp->tcp_bind_hash) {
15854 			if (zoneid != GLOBAL_ZONEID &&
15855 			    zoneid != tcp->tcp_connp->conn_zoneid)
15856 				continue;
15857 			CONN_INC_REF(tcp->tcp_connp);
15858 			tcp_report_item(mp->b_cont, tcp, i,
15859 			    Q_TO_TCP(q), cr);
15860 			CONN_DEC_REF(tcp->tcp_connp);
15861 		}
15862 		mutex_exit(&tbf->tf_lock);
15863 	}
15864 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15865 	return (0);
15866 }
15867 
15868 /* TCP status report triggered via the Named Dispatch mechanism. */
15869 /* ARGSUSED */
15870 static int
15871 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15872 {
15873 	connf_t	*connfp;
15874 	conn_t	*connp;
15875 	tcp_t	*tcp;
15876 	int	i;
15877 	zoneid_t zoneid;
15878 
15879 	/* Refer to comments in tcp_status_report(). */
15880 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15881 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15882 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15883 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15884 			return (0);
15885 		}
15886 	}
15887 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15888 		/* The following may work even if we cannot get a large buf. */
15889 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15890 		return (0);
15891 	}
15892 
15893 	(void) mi_mpprintf(mp,
15894 	    "    TCP    " MI_COL_HDRPAD_STR
15895 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
15896 
15897 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15898 
15899 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
15900 		connfp =  &ipcl_bind_fanout[i];
15901 		connp = NULL;
15902 		while ((connp =
15903 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15904 			tcp = connp->conn_tcp;
15905 			if (zoneid != GLOBAL_ZONEID &&
15906 			    zoneid != connp->conn_zoneid)
15907 				continue;
15908 			tcp_report_listener(mp->b_cont, tcp, i);
15909 		}
15910 	}
15911 
15912 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15913 	return (0);
15914 }
15915 
15916 /* TCP status report triggered via the Named Dispatch mechanism. */
15917 /* ARGSUSED */
15918 static int
15919 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15920 {
15921 	connf_t	*connfp;
15922 	conn_t	*connp;
15923 	tcp_t	*tcp;
15924 	int	i;
15925 	zoneid_t zoneid;
15926 
15927 	/* Refer to comments in tcp_status_report(). */
15928 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15929 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15930 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15931 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15932 			return (0);
15933 		}
15934 	}
15935 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15936 		/* The following may work even if we cannot get a large buf. */
15937 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15938 		return (0);
15939 	}
15940 
15941 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
15942 	    ipcl_conn_fanout_size);
15943 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
15944 
15945 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15946 
15947 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
15948 		connfp =  &ipcl_conn_fanout[i];
15949 		connp = NULL;
15950 		while ((connp =
15951 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15952 			tcp = connp->conn_tcp;
15953 			if (zoneid != GLOBAL_ZONEID &&
15954 			    zoneid != connp->conn_zoneid)
15955 				continue;
15956 			tcp_report_item(mp->b_cont, tcp, i,
15957 			    Q_TO_TCP(q), cr);
15958 		}
15959 	}
15960 
15961 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15962 	return (0);
15963 }
15964 
15965 /* TCP status report triggered via the Named Dispatch mechanism. */
15966 /* ARGSUSED */
15967 static int
15968 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15969 {
15970 	tf_t	*tf;
15971 	tcp_t	*tcp;
15972 	int	i;
15973 	zoneid_t zoneid;
15974 
15975 	/* Refer to comments in tcp_status_report(). */
15976 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15977 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15978 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15979 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15980 			return (0);
15981 		}
15982 	}
15983 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15984 		/* The following may work even if we cannot get a large buf. */
15985 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15986 		return (0);
15987 	}
15988 
15989 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
15990 
15991 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15992 
15993 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
15994 		tf = &tcp_acceptor_fanout[i];
15995 		mutex_enter(&tf->tf_lock);
15996 		for (tcp = tf->tf_tcp; tcp != NULL;
15997 		    tcp = tcp->tcp_acceptor_hash) {
15998 			if (zoneid != GLOBAL_ZONEID &&
15999 			    zoneid != tcp->tcp_connp->conn_zoneid)
16000 				continue;
16001 			tcp_report_item(mp->b_cont, tcp, i,
16002 			    Q_TO_TCP(q), cr);
16003 		}
16004 		mutex_exit(&tf->tf_lock);
16005 	}
16006 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16007 	return (0);
16008 }
16009 
16010 /*
16011  * tcp_timer is the timer service routine.  It handles the retransmission,
16012  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16013  * from the state of the tcp instance what kind of action needs to be done
16014  * at the time it is called.
16015  */
16016 static void
16017 tcp_timer(void *arg)
16018 {
16019 	mblk_t		*mp;
16020 	clock_t		first_threshold;
16021 	clock_t		second_threshold;
16022 	clock_t		ms;
16023 	uint32_t	mss;
16024 	conn_t		*connp = (conn_t *)arg;
16025 	tcp_t		*tcp = connp->conn_tcp;
16026 
16027 	tcp->tcp_timer_tid = 0;
16028 
16029 	if (tcp->tcp_fused)
16030 		return;
16031 
16032 	first_threshold =  tcp->tcp_first_timer_threshold;
16033 	second_threshold = tcp->tcp_second_timer_threshold;
16034 	switch (tcp->tcp_state) {
16035 	case TCPS_IDLE:
16036 	case TCPS_BOUND:
16037 	case TCPS_LISTEN:
16038 		return;
16039 	case TCPS_SYN_RCVD: {
16040 		tcp_t	*listener = tcp->tcp_listener;
16041 
16042 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16043 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16044 			/* it's our first timeout */
16045 			tcp->tcp_syn_rcvd_timeout = 1;
16046 			mutex_enter(&listener->tcp_eager_lock);
16047 			listener->tcp_syn_rcvd_timeout++;
16048 			if (!listener->tcp_syn_defense &&
16049 			    (listener->tcp_syn_rcvd_timeout >
16050 			    (tcp_conn_req_max_q0 >> 2)) &&
16051 			    (tcp_conn_req_max_q0 > 200)) {
16052 				/* We may be under attack. Put on a defense. */
16053 				listener->tcp_syn_defense = B_TRUE;
16054 				cmn_err(CE_WARN, "High TCP connect timeout "
16055 				    "rate! System (port %d) may be under a "
16056 				    "SYN flood attack!",
16057 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16058 
16059 				listener->tcp_ip_addr_cache = kmem_zalloc(
16060 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16061 				    KM_NOSLEEP);
16062 			}
16063 			mutex_exit(&listener->tcp_eager_lock);
16064 		}
16065 	}
16066 		/* FALLTHRU */
16067 	case TCPS_SYN_SENT:
16068 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16069 		second_threshold = tcp->tcp_second_ctimer_threshold;
16070 		break;
16071 	case TCPS_ESTABLISHED:
16072 	case TCPS_FIN_WAIT_1:
16073 	case TCPS_CLOSING:
16074 	case TCPS_CLOSE_WAIT:
16075 	case TCPS_LAST_ACK:
16076 		/* If we have data to rexmit */
16077 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16078 			clock_t	time_to_wait;
16079 
16080 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16081 			if (!tcp->tcp_xmit_head)
16082 				break;
16083 			time_to_wait = lbolt -
16084 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16085 			time_to_wait = tcp->tcp_rto -
16086 			    TICK_TO_MSEC(time_to_wait);
16087 			/*
16088 			 * If the timer fires too early, 1 clock tick earlier,
16089 			 * restart the timer.
16090 			 */
16091 			if (time_to_wait > msec_per_tick) {
16092 				TCP_STAT(tcp_timer_fire_early);
16093 				TCP_TIMER_RESTART(tcp, time_to_wait);
16094 				return;
16095 			}
16096 			/*
16097 			 * When we probe zero windows, we force the swnd open.
16098 			 * If our peer acks with a closed window swnd will be
16099 			 * set to zero by tcp_rput(). As long as we are
16100 			 * receiving acks tcp_rput will
16101 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16102 			 * first and second interval actions.  NOTE: the timer
16103 			 * interval is allowed to continue its exponential
16104 			 * backoff.
16105 			 */
16106 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16107 				if (tcp->tcp_debug) {
16108 					(void) strlog(TCP_MOD_ID, 0, 1,
16109 					    SL_TRACE, "tcp_timer: zero win");
16110 				}
16111 			} else {
16112 				/*
16113 				 * After retransmission, we need to do
16114 				 * slow start.  Set the ssthresh to one
16115 				 * half of current effective window and
16116 				 * cwnd to one MSS.  Also reset
16117 				 * tcp_cwnd_cnt.
16118 				 *
16119 				 * Note that if tcp_ssthresh is reduced because
16120 				 * of ECN, do not reduce it again unless it is
16121 				 * already one window of data away (tcp_cwr
16122 				 * should then be cleared) or this is a
16123 				 * timeout for a retransmitted segment.
16124 				 */
16125 				uint32_t npkt;
16126 
16127 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16128 					npkt = ((tcp->tcp_timer_backoff ?
16129 					    tcp->tcp_cwnd_ssthresh :
16130 					    tcp->tcp_snxt -
16131 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16132 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16133 					    tcp->tcp_mss;
16134 				}
16135 				tcp->tcp_cwnd = tcp->tcp_mss;
16136 				tcp->tcp_cwnd_cnt = 0;
16137 				if (tcp->tcp_ecn_ok) {
16138 					tcp->tcp_cwr = B_TRUE;
16139 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16140 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16141 				}
16142 			}
16143 			break;
16144 		}
16145 		/*
16146 		 * We have something to send yet we cannot send.  The
16147 		 * reason can be:
16148 		 *
16149 		 * 1. Zero send window: we need to do zero window probe.
16150 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16151 		 * segments.
16152 		 * 3. SWS avoidance: receiver may have shrunk window,
16153 		 * reset our knowledge.
16154 		 *
16155 		 * Note that condition 2 can happen with either 1 or
16156 		 * 3.  But 1 and 3 are exclusive.
16157 		 */
16158 		if (tcp->tcp_unsent != 0) {
16159 			if (tcp->tcp_cwnd == 0) {
16160 				/*
16161 				 * Set tcp_cwnd to 1 MSS so that a
16162 				 * new segment can be sent out.  We
16163 				 * are "clocking out" new data when
16164 				 * the network is really congested.
16165 				 */
16166 				ASSERT(tcp->tcp_ecn_ok);
16167 				tcp->tcp_cwnd = tcp->tcp_mss;
16168 			}
16169 			if (tcp->tcp_swnd == 0) {
16170 				/* Extend window for zero window probe */
16171 				tcp->tcp_swnd++;
16172 				tcp->tcp_zero_win_probe = B_TRUE;
16173 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
16174 			} else {
16175 				/*
16176 				 * Handle timeout from sender SWS avoidance.
16177 				 * Reset our knowledge of the max send window
16178 				 * since the receiver might have reduced its
16179 				 * receive buffer.  Avoid setting tcp_max_swnd
16180 				 * to one since that will essentially disable
16181 				 * the SWS checks.
16182 				 *
16183 				 * Note that since we don't have a SWS
16184 				 * state variable, if the timeout is set
16185 				 * for ECN but not for SWS, this
16186 				 * code will also be executed.  This is
16187 				 * fine as tcp_max_swnd is updated
16188 				 * constantly and it will not affect
16189 				 * anything.
16190 				 */
16191 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16192 			}
16193 			tcp_wput_data(tcp, NULL, B_FALSE);
16194 			return;
16195 		}
16196 		/* Is there a FIN that needs to be to re retransmitted? */
16197 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16198 		    !tcp->tcp_fin_acked)
16199 			break;
16200 		/* Nothing to do, return without restarting timer. */
16201 		TCP_STAT(tcp_timer_fire_miss);
16202 		return;
16203 	case TCPS_FIN_WAIT_2:
16204 		/*
16205 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16206 		 * We waited some time for for peer's FIN, but it hasn't
16207 		 * arrived.  We flush the connection now to avoid
16208 		 * case where the peer has rebooted.
16209 		 */
16210 		if (TCP_IS_DETACHED(tcp)) {
16211 			(void) tcp_clean_death(tcp, 0, 23);
16212 		} else {
16213 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
16214 		}
16215 		return;
16216 	case TCPS_TIME_WAIT:
16217 		(void) tcp_clean_death(tcp, 0, 24);
16218 		return;
16219 	default:
16220 		if (tcp->tcp_debug) {
16221 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16222 			    "tcp_timer: strange state (%d) %s",
16223 			    tcp->tcp_state, tcp_display(tcp, NULL,
16224 			    DISP_PORT_ONLY));
16225 		}
16226 		return;
16227 	}
16228 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16229 		/*
16230 		 * For zero window probe, we need to send indefinitely,
16231 		 * unless we have not heard from the other side for some
16232 		 * time...
16233 		 */
16234 		if ((tcp->tcp_zero_win_probe == 0) ||
16235 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16236 		    second_threshold)) {
16237 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
16238 			/*
16239 			 * If TCP is in SYN_RCVD state, send back a
16240 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16241 			 * should be zero in TCPS_SYN_RCVD state.
16242 			 */
16243 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16244 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16245 				    "in SYN_RCVD",
16246 				    tcp, tcp->tcp_snxt,
16247 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16248 			}
16249 			(void) tcp_clean_death(tcp,
16250 			    tcp->tcp_client_errno ?
16251 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16252 			return;
16253 		} else {
16254 			/*
16255 			 * Set tcp_ms_we_have_waited to second_threshold
16256 			 * so that in next timeout, we will do the above
16257 			 * check (lbolt - tcp_last_recv_time).  This is
16258 			 * also to avoid overflow.
16259 			 *
16260 			 * We don't need to decrement tcp_timer_backoff
16261 			 * to avoid overflow because it will be decremented
16262 			 * later if new timeout value is greater than
16263 			 * tcp_rexmit_interval_max.  In the case when
16264 			 * tcp_rexmit_interval_max is greater than
16265 			 * second_threshold, it means that we will wait
16266 			 * longer than second_threshold to send the next
16267 			 * window probe.
16268 			 */
16269 			tcp->tcp_ms_we_have_waited = second_threshold;
16270 		}
16271 	} else if (ms > first_threshold) {
16272 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16273 		    tcp->tcp_xmit_head != NULL) {
16274 			tcp->tcp_xmit_head =
16275 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16276 		}
16277 		/*
16278 		 * We have been retransmitting for too long...  The RTT
16279 		 * we calculated is probably incorrect.  Reinitialize it.
16280 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16281 		 * tcp_rtt_update so that we won't accidentally cache a
16282 		 * bad value.  But only do this if this is not a zero
16283 		 * window probe.
16284 		 */
16285 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16286 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16287 			    (tcp->tcp_rtt_sa >> 5);
16288 			tcp->tcp_rtt_sa = 0;
16289 			tcp_ip_notify(tcp);
16290 			tcp->tcp_rtt_update = 0;
16291 		}
16292 	}
16293 	tcp->tcp_timer_backoff++;
16294 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16295 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16296 	    tcp_rexmit_interval_min) {
16297 		/*
16298 		 * This means the original RTO is tcp_rexmit_interval_min.
16299 		 * So we will use tcp_rexmit_interval_min as the RTO value
16300 		 * and do the backoff.
16301 		 */
16302 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
16303 	} else {
16304 		ms <<= tcp->tcp_timer_backoff;
16305 	}
16306 	if (ms > tcp_rexmit_interval_max) {
16307 		ms = tcp_rexmit_interval_max;
16308 		/*
16309 		 * ms is at max, decrement tcp_timer_backoff to avoid
16310 		 * overflow.
16311 		 */
16312 		tcp->tcp_timer_backoff--;
16313 	}
16314 	tcp->tcp_ms_we_have_waited += ms;
16315 	if (tcp->tcp_zero_win_probe == 0) {
16316 		tcp->tcp_rto = ms;
16317 	}
16318 	TCP_TIMER_RESTART(tcp, ms);
16319 	/*
16320 	 * This is after a timeout and tcp_rto is backed off.  Set
16321 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16322 	 * restart the timer with a correct value.
16323 	 */
16324 	tcp->tcp_set_timer = 1;
16325 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16326 	if (mss > tcp->tcp_mss)
16327 		mss = tcp->tcp_mss;
16328 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16329 		mss = tcp->tcp_swnd;
16330 
16331 	if ((mp = tcp->tcp_xmit_head) != NULL)
16332 		mp->b_prev = (mblk_t *)lbolt;
16333 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16334 	    B_TRUE);
16335 
16336 	/*
16337 	 * When slow start after retransmission begins, start with
16338 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16339 	 * start phase.  tcp_snd_burst controls how many segments
16340 	 * can be sent because of an ack.
16341 	 */
16342 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16343 	tcp->tcp_snd_burst = TCP_CWND_SS;
16344 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16345 	    (tcp->tcp_unsent == 0)) {
16346 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16347 	} else {
16348 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16349 	}
16350 	tcp->tcp_rexmit = B_TRUE;
16351 	tcp->tcp_dupack_cnt = 0;
16352 
16353 	/*
16354 	 * Remove all rexmit SACK blk to start from fresh.
16355 	 */
16356 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16357 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16358 		tcp->tcp_num_notsack_blk = 0;
16359 		tcp->tcp_cnt_notsack_list = 0;
16360 	}
16361 	if (mp == NULL) {
16362 		return;
16363 	}
16364 	/* Attach credentials to retransmitted initial SYNs. */
16365 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16366 		mblk_setcred(mp, tcp->tcp_cred);
16367 		DB_CPID(mp) = tcp->tcp_cpid;
16368 	}
16369 
16370 	tcp->tcp_csuna = tcp->tcp_snxt;
16371 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
16372 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
16373 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
16374 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16375 
16376 }
16377 
16378 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16379 static void
16380 tcp_unbind(tcp_t *tcp, mblk_t *mp)
16381 {
16382 	conn_t	*connp;
16383 
16384 	switch (tcp->tcp_state) {
16385 	case TCPS_BOUND:
16386 	case TCPS_LISTEN:
16387 		break;
16388 	default:
16389 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
16390 		return;
16391 	}
16392 
16393 	/*
16394 	 * Need to clean up all the eagers since after the unbind, segments
16395 	 * will no longer be delivered to this listener stream.
16396 	 */
16397 	mutex_enter(&tcp->tcp_eager_lock);
16398 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16399 		tcp_eager_cleanup(tcp, 0);
16400 	}
16401 	mutex_exit(&tcp->tcp_eager_lock);
16402 
16403 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16404 		tcp->tcp_ipha->ipha_src = 0;
16405 	} else {
16406 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16407 	}
16408 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16409 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16410 	tcp_bind_hash_remove(tcp);
16411 	tcp->tcp_state = TCPS_IDLE;
16412 	tcp->tcp_mdt = B_FALSE;
16413 	/* Send M_FLUSH according to TPI */
16414 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16415 	connp = tcp->tcp_connp;
16416 	connp->conn_mdt_ok = B_FALSE;
16417 	ipcl_hash_remove(connp);
16418 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16419 	mp = mi_tpi_ok_ack_alloc(mp);
16420 	putnext(tcp->tcp_rq, mp);
16421 }
16422 
16423 /*
16424  * Don't let port fall into the privileged range.
16425  * Since the extra privileged ports can be arbitrary we also
16426  * ensure that we exclude those from consideration.
16427  * tcp_g_epriv_ports is not sorted thus we loop over it until
16428  * there are no changes.
16429  *
16430  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16431  * but instead the code relies on:
16432  * - the fact that the address of the array and its size never changes
16433  * - the atomic assignment of the elements of the array
16434  */
16435 static in_port_t
16436 tcp_update_next_port(in_port_t port, boolean_t random)
16437 {
16438 	int i;
16439 
16440 	if (random && tcp_random_anon_port != 0) {
16441 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16442 		    sizeof (in_port_t));
16443 		/*
16444 		 * Unless changed by a sys admin, the smallest anon port
16445 		 * is 32768 and the largest anon port is 65535.  It is
16446 		 * very likely (50%) for the random port to be smaller
16447 		 * than the smallest anon port.  When that happens,
16448 		 * add port % (anon port range) to the smallest anon
16449 		 * port to get the random port.  It should fall into the
16450 		 * valid anon port range.
16451 		 */
16452 		if (port < tcp_smallest_anon_port) {
16453 			port = tcp_smallest_anon_port +
16454 			    port % (tcp_largest_anon_port -
16455 				tcp_smallest_anon_port);
16456 		}
16457 	}
16458 
16459 retry:
16460 	if (port < tcp_smallest_anon_port || port > tcp_largest_anon_port)
16461 		port = (in_port_t)tcp_smallest_anon_port;
16462 
16463 	if (port < tcp_smallest_nonpriv_port)
16464 		port = (in_port_t)tcp_smallest_nonpriv_port;
16465 
16466 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
16467 		if (port == tcp_g_epriv_ports[i]) {
16468 			port++;
16469 			/*
16470 			 * Make sure whether the port is in the
16471 			 * valid range.
16472 			 *
16473 			 * XXX Note that if tcp_g_epriv_ports contains
16474 			 * all the anonymous ports this will be an
16475 			 * infinite loop.
16476 			 */
16477 			goto retry;
16478 		}
16479 	}
16480 	return (port);
16481 }
16482 
16483 /*
16484  * Return the next anonymous port in the priviledged port range for
16485  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16486  * downwards.  This is the same behavior as documented in the userland
16487  * library call rresvport(3N).
16488  */
16489 static in_port_t
16490 tcp_get_next_priv_port(void)
16491 {
16492 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16493 
16494 	if (next_priv_port < tcp_min_anonpriv_port) {
16495 		next_priv_port = IPPORT_RESERVED - 1;
16496 	}
16497 	return (next_priv_port--);
16498 }
16499 
16500 /* The write side r/w procedure. */
16501 
16502 #if CCS_STATS
16503 struct {
16504 	struct {
16505 		int64_t count, bytes;
16506 	} tot, hit;
16507 } wrw_stats;
16508 #endif
16509 
16510 /*
16511  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16512  * messages.
16513  */
16514 /* ARGSUSED */
16515 static void
16516 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16517 {
16518 	conn_t	*connp = (conn_t *)arg;
16519 	tcp_t	*tcp = connp->conn_tcp;
16520 	queue_t	*q = tcp->tcp_wq;
16521 
16522 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16523 	/*
16524 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16525 	 * Once the close starts, streamhead and sockfs will not let any data
16526 	 * packets come down (close ensures that there are no threads using the
16527 	 * queue and no new threads will come down) but since qprocsoff()
16528 	 * hasn't happened yet, a M_FLUSH or some non data message might
16529 	 * get reflected back (in response to our own FLUSHRW) and get
16530 	 * processed after tcp_close() is done. The conn would still be valid
16531 	 * because a ref would have added but we need to check the state
16532 	 * before actually processing the packet.
16533 	 */
16534 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16535 		freemsg(mp);
16536 		return;
16537 	}
16538 
16539 	switch (DB_TYPE(mp)) {
16540 	case M_IOCDATA:
16541 		tcp_wput_iocdata(tcp, mp);
16542 		break;
16543 	case M_FLUSH:
16544 		tcp_wput_flush(tcp, mp);
16545 		break;
16546 	default:
16547 		CALL_IP_WPUT(connp, q, mp);
16548 		break;
16549 	}
16550 }
16551 
16552 /*
16553  * The TCP fast path write put procedure.
16554  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16555  */
16556 /* ARGSUSED */
16557 static void
16558 tcp_output(void *arg, mblk_t *mp, void *arg2)
16559 {
16560 	int		len;
16561 	int		hdrlen;
16562 	int		plen;
16563 	mblk_t		*mp1;
16564 	uchar_t		*rptr;
16565 	uint32_t	snxt;
16566 	tcph_t		*tcph;
16567 	struct datab	*db;
16568 	uint32_t	suna;
16569 	uint32_t	mss;
16570 	ipaddr_t	*dst;
16571 	ipaddr_t	*src;
16572 	uint32_t	sum;
16573 	int		usable;
16574 	conn_t		*connp = (conn_t *)arg;
16575 	tcp_t		*tcp = connp->conn_tcp;
16576 	uint32_t	msize;
16577 
16578 	/*
16579 	 * Try and ASSERT the minimum possible references on the
16580 	 * conn early enough. Since we are executing on write side,
16581 	 * the connection is obviously not detached and that means
16582 	 * there is a ref each for TCP and IP. Since we are behind
16583 	 * the squeue, the minimum references needed are 3. If the
16584 	 * conn is in classifier hash list, there should be an
16585 	 * extra ref for that (we check both the possibilities).
16586 	 */
16587 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16588 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16589 
16590 	/* Bypass tcp protocol for fused tcp loopback */
16591 	if (tcp->tcp_fused) {
16592 		msize = msgdsize(mp);
16593 		mutex_enter(&connp->conn_lock);
16594 		tcp->tcp_squeue_bytes -= msize;
16595 		mutex_exit(&connp->conn_lock);
16596 
16597 		if (tcp_fuse_output(tcp, mp, msize))
16598 			return;
16599 	}
16600 
16601 	mss = tcp->tcp_mss;
16602 	if (tcp->tcp_xmit_zc_clean)
16603 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16604 
16605 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16606 	len = (int)(mp->b_wptr - mp->b_rptr);
16607 
16608 	/*
16609 	 * Criteria for fast path:
16610 	 *
16611 	 *   1. no unsent data
16612 	 *   2. single mblk in request
16613 	 *   3. connection established
16614 	 *   4. data in mblk
16615 	 *   5. len <= mss
16616 	 *   6. no tcp_valid bits
16617 	 */
16618 	if ((tcp->tcp_unsent != 0) ||
16619 	    (tcp->tcp_cork) ||
16620 	    (mp->b_cont != NULL) ||
16621 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16622 	    (len == 0) ||
16623 	    (len > mss) ||
16624 	    (tcp->tcp_valid_bits != 0)) {
16625 		msize = msgdsize(mp);
16626 		mutex_enter(&connp->conn_lock);
16627 		tcp->tcp_squeue_bytes -= msize;
16628 		mutex_exit(&connp->conn_lock);
16629 
16630 		tcp_wput_data(tcp, mp, B_FALSE);
16631 		return;
16632 	}
16633 
16634 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16635 	ASSERT(tcp->tcp_fin_sent == 0);
16636 
16637 	mutex_enter(&connp->conn_lock);
16638 	tcp->tcp_squeue_bytes -= len;
16639 	mutex_exit(&connp->conn_lock);
16640 
16641 	/* queue new packet onto retransmission queue */
16642 	if (tcp->tcp_xmit_head == NULL) {
16643 		tcp->tcp_xmit_head = mp;
16644 	} else {
16645 		tcp->tcp_xmit_last->b_cont = mp;
16646 	}
16647 	tcp->tcp_xmit_last = mp;
16648 	tcp->tcp_xmit_tail = mp;
16649 
16650 	/* find out how much we can send */
16651 	/* BEGIN CSTYLED */
16652 	/*
16653 	 *    un-acked           usable
16654 	 *  |--------------|-----------------|
16655 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
16656 	 */
16657 	/* END CSTYLED */
16658 
16659 	/* start sending from tcp_snxt */
16660 	snxt = tcp->tcp_snxt;
16661 
16662 	/*
16663 	 * Check to see if this connection has been idled for some
16664 	 * time and no ACK is expected.  If it is, we need to slow
16665 	 * start again to get back the connection's "self-clock" as
16666 	 * described in VJ's paper.
16667 	 *
16668 	 * Refer to the comment in tcp_mss_set() for the calculation
16669 	 * of tcp_cwnd after idle.
16670 	 */
16671 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16672 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16673 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
16674 	}
16675 
16676 	usable = tcp->tcp_swnd;		/* tcp window size */
16677 	if (usable > tcp->tcp_cwnd)
16678 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16679 	usable -= snxt;		/* subtract stuff already sent */
16680 	suna = tcp->tcp_suna;
16681 	usable += suna;
16682 	/* usable can be < 0 if the congestion window is smaller */
16683 	if (len > usable) {
16684 		/* Can't send complete M_DATA in one shot */
16685 		goto slow;
16686 	}
16687 
16688 	if (tcp->tcp_flow_stopped &&
16689 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16690 		tcp_clrqfull(tcp);
16691 	}
16692 
16693 	/*
16694 	 * determine if anything to send (Nagle).
16695 	 *
16696 	 *   1. len < tcp_mss (i.e. small)
16697 	 *   2. unacknowledged data present
16698 	 *   3. len < nagle limit
16699 	 *   4. last packet sent < nagle limit (previous packet sent)
16700 	 */
16701 	if ((len < mss) && (snxt != suna) &&
16702 	    (len < (int)tcp->tcp_naglim) &&
16703 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
16704 		/*
16705 		 * This was the first unsent packet and normally
16706 		 * mss < xmit_hiwater so there is no need to worry
16707 		 * about flow control. The next packet will go
16708 		 * through the flow control check in tcp_wput_data().
16709 		 */
16710 		/* leftover work from above */
16711 		tcp->tcp_unsent = len;
16712 		tcp->tcp_xmit_tail_unsent = len;
16713 
16714 		return;
16715 	}
16716 
16717 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
16718 
16719 	if (snxt == suna) {
16720 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16721 	}
16722 
16723 	/* we have always sent something */
16724 	tcp->tcp_rack_cnt = 0;
16725 
16726 	tcp->tcp_snxt = snxt + len;
16727 	tcp->tcp_rack = tcp->tcp_rnxt;
16728 
16729 	if ((mp1 = dupb(mp)) == 0)
16730 		goto no_memory;
16731 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
16732 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
16733 
16734 	/* adjust tcp header information */
16735 	tcph = tcp->tcp_tcph;
16736 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
16737 
16738 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
16739 	sum = (sum >> 16) + (sum & 0xFFFF);
16740 	U16_TO_ABE16(sum, tcph->th_sum);
16741 
16742 	U32_TO_ABE32(snxt, tcph->th_seq);
16743 
16744 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
16745 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
16746 	BUMP_LOCAL(tcp->tcp_obsegs);
16747 
16748 	/* Update the latest receive window size in TCP header. */
16749 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
16750 	    tcph->th_win);
16751 
16752 	tcp->tcp_last_sent_len = (ushort_t)len;
16753 
16754 	plen = len + tcp->tcp_hdr_len;
16755 
16756 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16757 		tcp->tcp_ipha->ipha_length = htons(plen);
16758 	} else {
16759 		tcp->tcp_ip6h->ip6_plen = htons(plen -
16760 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
16761 	}
16762 
16763 	/* see if we need to allocate a mblk for the headers */
16764 	hdrlen = tcp->tcp_hdr_len;
16765 	rptr = mp1->b_rptr - hdrlen;
16766 	db = mp1->b_datap;
16767 	if ((db->db_ref != 2) || rptr < db->db_base ||
16768 	    (!OK_32PTR(rptr))) {
16769 		/* NOTE: we assume allocb returns an OK_32PTR */
16770 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
16771 		    tcp_wroff_xtra, BPRI_MED);
16772 		if (!mp) {
16773 			freemsg(mp1);
16774 			goto no_memory;
16775 		}
16776 		mp->b_cont = mp1;
16777 		mp1 = mp;
16778 		/* Leave room for Link Level header */
16779 		/* hdrlen = tcp->tcp_hdr_len; */
16780 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
16781 		mp1->b_wptr = &rptr[hdrlen];
16782 	}
16783 	mp1->b_rptr = rptr;
16784 
16785 	/* Fill in the timestamp option. */
16786 	if (tcp->tcp_snd_ts_ok) {
16787 		U32_TO_BE32((uint32_t)lbolt,
16788 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
16789 		U32_TO_BE32(tcp->tcp_ts_recent,
16790 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
16791 	} else {
16792 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
16793 	}
16794 
16795 	/* copy header into outgoing packet */
16796 	dst = (ipaddr_t *)rptr;
16797 	src = (ipaddr_t *)tcp->tcp_iphc;
16798 	dst[0] = src[0];
16799 	dst[1] = src[1];
16800 	dst[2] = src[2];
16801 	dst[3] = src[3];
16802 	dst[4] = src[4];
16803 	dst[5] = src[5];
16804 	dst[6] = src[6];
16805 	dst[7] = src[7];
16806 	dst[8] = src[8];
16807 	dst[9] = src[9];
16808 	if (hdrlen -= 40) {
16809 		hdrlen >>= 2;
16810 		dst += 10;
16811 		src += 10;
16812 		do {
16813 			*dst++ = *src++;
16814 		} while (--hdrlen);
16815 	}
16816 
16817 	/*
16818 	 * Set the ECN info in the TCP header.  Note that this
16819 	 * is not the template header.
16820 	 */
16821 	if (tcp->tcp_ecn_ok) {
16822 		SET_ECT(tcp, rptr);
16823 
16824 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
16825 		if (tcp->tcp_ecn_echo_on)
16826 			tcph->th_flags[0] |= TH_ECE;
16827 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
16828 			tcph->th_flags[0] |= TH_CWR;
16829 			tcp->tcp_ecn_cwr_sent = B_TRUE;
16830 		}
16831 	}
16832 
16833 	if (tcp->tcp_ip_forward_progress) {
16834 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
16835 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
16836 		tcp->tcp_ip_forward_progress = B_FALSE;
16837 	}
16838 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
16839 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
16840 	return;
16841 
16842 	/*
16843 	 * If we ran out of memory, we pretend to have sent the packet
16844 	 * and that it was lost on the wire.
16845 	 */
16846 no_memory:
16847 	return;
16848 
16849 slow:
16850 	/* leftover work from above */
16851 	tcp->tcp_unsent = len;
16852 	tcp->tcp_xmit_tail_unsent = len;
16853 	tcp_wput_data(tcp, NULL, B_FALSE);
16854 }
16855 
16856 /*
16857  * The function called through squeue to get behind eager's perimeter to
16858  * finish the accept processing.
16859  */
16860 /* ARGSUSED */
16861 void
16862 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
16863 {
16864 	conn_t			*connp = (conn_t *)arg;
16865 	tcp_t			*tcp = connp->conn_tcp;
16866 	queue_t			*q = tcp->tcp_rq;
16867 	mblk_t			*mp1;
16868 	mblk_t			*stropt_mp = mp;
16869 	struct  stroptions	*stropt;
16870 	uint_t			thwin;
16871 
16872 	/*
16873 	 * Drop the eager's ref on the listener, that was placed when
16874 	 * this eager began life in tcp_conn_request.
16875 	 */
16876 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
16877 
16878 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
16879 		/*
16880 		 * Someone blewoff the eager before we could finish
16881 		 * the accept.
16882 		 *
16883 		 * The only reason eager exists it because we put in
16884 		 * a ref on it when conn ind went up. We need to send
16885 		 * a disconnect indication up while the last reference
16886 		 * on the eager will be dropped by the squeue when we
16887 		 * return.
16888 		 */
16889 		ASSERT(tcp->tcp_listener == NULL);
16890 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
16891 			struct	T_discon_ind	*tdi;
16892 
16893 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
16894 			/*
16895 			 * Let us reuse the incoming mblk to avoid memory
16896 			 * allocation failure problems. We know that the
16897 			 * size of the incoming mblk i.e. stroptions is greater
16898 			 * than sizeof T_discon_ind. So the reallocb below
16899 			 * can't fail.
16900 			 */
16901 			freemsg(mp->b_cont);
16902 			mp->b_cont = NULL;
16903 			ASSERT(DB_REF(mp) == 1);
16904 			mp = reallocb(mp, sizeof (struct T_discon_ind),
16905 			    B_FALSE);
16906 			ASSERT(mp != NULL);
16907 			DB_TYPE(mp) = M_PROTO;
16908 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
16909 			tdi = (struct T_discon_ind *)mp->b_rptr;
16910 			if (tcp->tcp_issocket) {
16911 				tdi->DISCON_reason = ECONNREFUSED;
16912 				tdi->SEQ_number = 0;
16913 			} else {
16914 				tdi->DISCON_reason = ENOPROTOOPT;
16915 				tdi->SEQ_number =
16916 				    tcp->tcp_conn_req_seqnum;
16917 			}
16918 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
16919 			putnext(q, mp);
16920 		} else {
16921 			freemsg(mp);
16922 		}
16923 		if (tcp->tcp_hard_binding) {
16924 			tcp->tcp_hard_binding = B_FALSE;
16925 			tcp->tcp_hard_bound = B_TRUE;
16926 		}
16927 		tcp->tcp_detached = B_FALSE;
16928 		return;
16929 	}
16930 
16931 	mp1 = stropt_mp->b_cont;
16932 	stropt_mp->b_cont = NULL;
16933 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
16934 	stropt = (struct stroptions *)stropt_mp->b_rptr;
16935 
16936 	while (mp1 != NULL) {
16937 		mp = mp1;
16938 		mp1 = mp1->b_cont;
16939 		mp->b_cont = NULL;
16940 		tcp->tcp_drop_opt_ack_cnt++;
16941 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
16942 	}
16943 	mp = NULL;
16944 
16945 	/*
16946 	 * For a loopback connection with tcp_direct_sockfs on, note that
16947 	 * we don't have to protect tcp_rcv_list yet because synchronous
16948 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
16949 	 * possibly race with us.
16950 	 */
16951 
16952 	/*
16953 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
16954 	 * properly.  This is the first time we know of the acceptor'
16955 	 * queue.  So we do it here.
16956 	 */
16957 	if (tcp->tcp_rcv_list == NULL) {
16958 		/*
16959 		 * Recv queue is empty, tcp_rwnd should not have changed.
16960 		 * That means it should be equal to the listener's tcp_rwnd.
16961 		 */
16962 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
16963 	} else {
16964 #ifdef DEBUG
16965 		uint_t cnt = 0;
16966 
16967 		mp1 = tcp->tcp_rcv_list;
16968 		while ((mp = mp1) != NULL) {
16969 			mp1 = mp->b_next;
16970 			cnt += msgdsize(mp);
16971 		}
16972 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
16973 #endif
16974 		/* There is some data, add them back to get the max. */
16975 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
16976 	}
16977 
16978 	stropt->so_flags = SO_HIWAT;
16979 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
16980 
16981 	stropt->so_flags |= SO_MAXBLK;
16982 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
16983 
16984 	/*
16985 	 * This is the first time we run on the correct
16986 	 * queue after tcp_accept. So fix all the q parameters
16987 	 * here.
16988 	 */
16989 	/* Allocate room for SACK options if needed. */
16990 	stropt->so_flags |= SO_WROFF;
16991 	if (tcp->tcp_fused) {
16992 		ASSERT(tcp->tcp_loopback);
16993 		ASSERT(tcp->tcp_loopback_peer != NULL);
16994 		/*
16995 		 * For fused tcp loopback, set the stream head's write
16996 		 * offset value to zero since we won't be needing any room
16997 		 * for TCP/IP headers.  This would also improve performance
16998 		 * since it would reduce the amount of work done by kmem.
16999 		 * Non-fused tcp loopback case is handled separately below.
17000 		 */
17001 		stropt->so_wroff = 0;
17002 		/*
17003 		 * Record the stream head's high water mark for this endpoint;
17004 		 * this is used for flow-control purposes in tcp_fuse_output().
17005 		 */
17006 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17007 		/*
17008 		 * Update the peer's transmit parameters according to
17009 		 * our recently calculated high water mark value.
17010 		 */
17011 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17012 	} else if (tcp->tcp_snd_sack_ok) {
17013 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17014 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17015 	} else {
17016 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17017 		    tcp_wroff_xtra);
17018 	}
17019 
17020 	/* Send the options up */
17021 	putnext(q, stropt_mp);
17022 
17023 	/*
17024 	 * Pass up any data and/or a fin that has been received.
17025 	 *
17026 	 * Adjust receive window in case it had decreased
17027 	 * (because there is data <=> tcp_rcv_list != NULL)
17028 	 * while the connection was detached. Note that
17029 	 * in case the eager was flow-controlled, w/o this
17030 	 * code, the rwnd may never open up again!
17031 	 */
17032 	if (tcp->tcp_rcv_list != NULL) {
17033 		/* We drain directly in case of fused tcp loopback */
17034 		if (!tcp->tcp_fused && canputnext(q)) {
17035 			tcp->tcp_rwnd = q->q_hiwat;
17036 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17037 			    << tcp->tcp_rcv_ws;
17038 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17039 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17040 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17041 				tcp_xmit_ctl(NULL,
17042 				    tcp, (tcp->tcp_swnd == 0) ?
17043 				    tcp->tcp_suna : tcp->tcp_snxt,
17044 				    tcp->tcp_rnxt, TH_ACK);
17045 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17046 			}
17047 
17048 		}
17049 		(void) tcp_rcv_drain(q, tcp);
17050 
17051 		/*
17052 		 * For fused tcp loopback, back-enable peer endpoint
17053 		 * if it's currently flow-controlled.
17054 		 */
17055 		if (tcp->tcp_fused &&
17056 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17057 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17058 
17059 			ASSERT(peer_tcp != NULL);
17060 			ASSERT(peer_tcp->tcp_fused);
17061 
17062 			tcp_clrqfull(peer_tcp);
17063 			TCP_STAT(tcp_fusion_backenabled);
17064 		}
17065 	}
17066 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17067 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17068 		mp = mi_tpi_ordrel_ind();
17069 		if (mp) {
17070 			tcp->tcp_ordrel_done = B_TRUE;
17071 			putnext(q, mp);
17072 			if (tcp->tcp_deferred_clean_death) {
17073 				/*
17074 				 * tcp_clean_death was deferred
17075 				 * for T_ORDREL_IND - do it now
17076 				 */
17077 				(void) tcp_clean_death(tcp,
17078 				    tcp->tcp_client_errno, 21);
17079 				tcp->tcp_deferred_clean_death = B_FALSE;
17080 			}
17081 		} else {
17082 			/*
17083 			 * Run the orderly release in the
17084 			 * service routine.
17085 			 */
17086 			qenable(q);
17087 		}
17088 	}
17089 	if (tcp->tcp_hard_binding) {
17090 		tcp->tcp_hard_binding = B_FALSE;
17091 		tcp->tcp_hard_bound = B_TRUE;
17092 	}
17093 
17094 	tcp->tcp_detached = B_FALSE;
17095 
17096 	/* We can enable synchronous streams now */
17097 	if (tcp->tcp_fused) {
17098 		tcp_fuse_syncstr_enable_pair(tcp);
17099 	}
17100 
17101 	if (tcp->tcp_ka_enabled) {
17102 		tcp->tcp_ka_last_intrvl = 0;
17103 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17104 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17105 	}
17106 
17107 	/*
17108 	 * At this point, eager is fully established and will
17109 	 * have the following references -
17110 	 *
17111 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17112 	 * 1 reference for the squeue which will be dropped by the squeue as
17113 	 *	soon as this function returns.
17114 	 * There will be 1 additonal reference for being in classifier
17115 	 *	hash list provided something bad hasn't happened.
17116 	 */
17117 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17118 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17119 }
17120 
17121 /*
17122  * The function called through squeue to get behind listener's perimeter to
17123  * send a deffered conn_ind.
17124  */
17125 /* ARGSUSED */
17126 void
17127 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17128 {
17129 	conn_t	*connp = (conn_t *)arg;
17130 	tcp_t *listener = connp->conn_tcp;
17131 
17132 	if (listener->tcp_state == TCPS_CLOSED ||
17133 	    TCP_IS_DETACHED(listener)) {
17134 		/*
17135 		 * If listener has closed, it would have caused a
17136 		 * a cleanup/blowoff to happen for the eager.
17137 		 */
17138 		tcp_t *tcp;
17139 		struct T_conn_ind	*conn_ind;
17140 
17141 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
17142 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17143 		    conn_ind->OPT_length);
17144 		/*
17145 		 * We need to drop the ref on eager that was put
17146 		 * tcp_rput_data() before trying to send the conn_ind
17147 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17148 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17149 		 * listener is closed so we drop the ref.
17150 		 */
17151 		CONN_DEC_REF(tcp->tcp_connp);
17152 		freemsg(mp);
17153 		return;
17154 	}
17155 	putnext(listener->tcp_rq, mp);
17156 }
17157 
17158 
17159 /*
17160  * This is the STREAMS entry point for T_CONN_RES coming down on
17161  * Acceptor STREAM when  sockfs listener does accept processing.
17162  * Read the block comment on top pf tcp_conn_request().
17163  */
17164 void
17165 tcp_wput_accept(queue_t *q, mblk_t *mp)
17166 {
17167 	queue_t *rq = RD(q);
17168 	struct T_conn_res *conn_res;
17169 	tcp_t *eager;
17170 	tcp_t *listener;
17171 	struct T_ok_ack *ok;
17172 	t_scalar_t PRIM_type;
17173 	mblk_t *opt_mp;
17174 	conn_t *econnp;
17175 
17176 	ASSERT(DB_TYPE(mp) == M_PROTO);
17177 
17178 	conn_res = (struct T_conn_res *)mp->b_rptr;
17179 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17180 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17181 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17182 		if (mp != NULL)
17183 			putnext(rq, mp);
17184 		return;
17185 	}
17186 	switch (conn_res->PRIM_type) {
17187 	case O_T_CONN_RES:
17188 	case T_CONN_RES:
17189 		/*
17190 		 * We pass up an err ack if allocb fails. This will
17191 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17192 		 * tcp_eager_blowoff to be called. sockfs will then call
17193 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17194 		 * we need to do the allocb up here because we have to
17195 		 * make sure rq->q_qinfo->qi_qclose still points to the
17196 		 * correct function (tcpclose_accept) in case allocb
17197 		 * fails.
17198 		 */
17199 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17200 		if (opt_mp == NULL) {
17201 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17202 			if (mp != NULL)
17203 				putnext(rq, mp);
17204 			return;
17205 		}
17206 
17207 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17208 		    &eager, conn_res->OPT_length);
17209 		PRIM_type = conn_res->PRIM_type;
17210 		mp->b_datap->db_type = M_PCPROTO;
17211 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17212 		ok = (struct T_ok_ack *)mp->b_rptr;
17213 		ok->PRIM_type = T_OK_ACK;
17214 		ok->CORRECT_prim = PRIM_type;
17215 		econnp = eager->tcp_connp;
17216 		econnp->conn_dev = (dev_t)q->q_ptr;
17217 		eager->tcp_rq = rq;
17218 		eager->tcp_wq = q;
17219 		rq->q_ptr = econnp;
17220 		rq->q_qinfo = &tcp_rinit;
17221 		q->q_ptr = econnp;
17222 		q->q_qinfo = &tcp_winit;
17223 		listener = eager->tcp_listener;
17224 		eager->tcp_issocket = B_TRUE;
17225 		eager->tcp_cred = econnp->conn_cred =
17226 		    listener->tcp_connp->conn_cred;
17227 		crhold(econnp->conn_cred);
17228 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17229 
17230 		/* Put the ref for IP */
17231 		CONN_INC_REF(econnp);
17232 
17233 		/*
17234 		 * We should have minimum of 3 references on the conn
17235 		 * at this point. One each for TCP and IP and one for
17236 		 * the T_conn_ind that was sent up when the 3-way handshake
17237 		 * completed. In the normal case we would also have another
17238 		 * reference (making a total of 4) for the conn being in the
17239 		 * classifier hash list. However the eager could have received
17240 		 * an RST subsequently and tcp_closei_local could have removed
17241 		 * the eager from the classifier hash list, hence we can't
17242 		 * assert that reference.
17243 		 */
17244 		ASSERT(econnp->conn_ref >= 3);
17245 
17246 		/*
17247 		 * Send the new local address also up to sockfs. There
17248 		 * should already be enough space in the mp that came
17249 		 * down from soaccept().
17250 		 */
17251 		if (eager->tcp_family == AF_INET) {
17252 			sin_t *sin;
17253 
17254 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17255 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17256 			sin = (sin_t *)mp->b_wptr;
17257 			mp->b_wptr += sizeof (sin_t);
17258 			sin->sin_family = AF_INET;
17259 			sin->sin_port = eager->tcp_lport;
17260 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17261 		} else {
17262 			sin6_t *sin6;
17263 
17264 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17265 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17266 			sin6 = (sin6_t *)mp->b_wptr;
17267 			mp->b_wptr += sizeof (sin6_t);
17268 			sin6->sin6_family = AF_INET6;
17269 			sin6->sin6_port = eager->tcp_lport;
17270 			if (eager->tcp_ipversion == IPV4_VERSION) {
17271 				sin6->sin6_flowinfo = 0;
17272 				IN6_IPADDR_TO_V4MAPPED(
17273 					eager->tcp_ipha->ipha_src,
17274 					    &sin6->sin6_addr);
17275 			} else {
17276 				ASSERT(eager->tcp_ip6h != NULL);
17277 				sin6->sin6_flowinfo =
17278 				    eager->tcp_ip6h->ip6_vcf &
17279 				    ~IPV6_VERS_AND_FLOW_MASK;
17280 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17281 			}
17282 			sin6->sin6_scope_id = 0;
17283 			sin6->__sin6_src_id = 0;
17284 		}
17285 
17286 		putnext(rq, mp);
17287 
17288 		opt_mp->b_datap->db_type = M_SETOPTS;
17289 		opt_mp->b_wptr += sizeof (struct stroptions);
17290 
17291 		/*
17292 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17293 		 * from listener to acceptor. The message is chained on the
17294 		 * bind_mp which tcp_rput_other will send down to IP.
17295 		 */
17296 		if (listener->tcp_bound_if != 0) {
17297 			/* allocate optmgmt req */
17298 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17299 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
17300 			    sizeof (int));
17301 			if (mp != NULL)
17302 				linkb(opt_mp, mp);
17303 		}
17304 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17305 			uint_t on = 1;
17306 
17307 			/* allocate optmgmt req */
17308 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17309 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
17310 			if (mp != NULL)
17311 				linkb(opt_mp, mp);
17312 		}
17313 
17314 
17315 		mutex_enter(&listener->tcp_eager_lock);
17316 
17317 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17318 
17319 			tcp_t *tail;
17320 			tcp_t *tcp;
17321 			mblk_t *mp1;
17322 
17323 			tcp = listener->tcp_eager_prev_q0;
17324 			/*
17325 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
17326 			 * deferred T_conn_ind queue. We need to get to the head
17327 			 * of the queue in order to send up T_conn_ind the same
17328 			 * order as how the 3WHS is completed.
17329 			 */
17330 			while (tcp != listener) {
17331 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
17332 					break;
17333 				else
17334 					tcp = tcp->tcp_eager_prev_q0;
17335 			}
17336 			ASSERT(tcp != listener);
17337 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17338 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17339 			/* Move from q0 to q */
17340 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17341 			listener->tcp_conn_req_cnt_q0--;
17342 			listener->tcp_conn_req_cnt_q++;
17343 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17344 			    tcp->tcp_eager_prev_q0;
17345 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17346 			    tcp->tcp_eager_next_q0;
17347 			tcp->tcp_eager_prev_q0 = NULL;
17348 			tcp->tcp_eager_next_q0 = NULL;
17349 			tcp->tcp_conn_def_q0 = B_FALSE;
17350 
17351 			/*
17352 			 * Insert at end of the queue because sockfs sends
17353 			 * down T_CONN_RES in chronological order. Leaving
17354 			 * the older conn indications at front of the queue
17355 			 * helps reducing search time.
17356 			 */
17357 			tail = listener->tcp_eager_last_q;
17358 			if (tail != NULL) {
17359 				tail->tcp_eager_next_q = tcp;
17360 			} else {
17361 				listener->tcp_eager_next_q = tcp;
17362 			}
17363 			listener->tcp_eager_last_q = tcp;
17364 			tcp->tcp_eager_next_q = NULL;
17365 
17366 			/* Need to get inside the listener perimeter */
17367 			CONN_INC_REF(listener->tcp_connp);
17368 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
17369 			    tcp_send_pending, listener->tcp_connp,
17370 			    SQTAG_TCP_SEND_PENDING);
17371 		}
17372 		tcp_eager_unlink(eager);
17373 		mutex_exit(&listener->tcp_eager_lock);
17374 
17375 		/*
17376 		 * At this point, the eager is detached from the listener
17377 		 * but we still have an extra refs on eager (apart from the
17378 		 * usual tcp references). The ref was placed in tcp_rput_data
17379 		 * before sending the conn_ind in tcp_send_conn_ind.
17380 		 * The ref will be dropped in tcp_accept_finish().
17381 		 */
17382 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
17383 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
17384 		return;
17385 	default:
17386 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17387 		if (mp != NULL)
17388 			putnext(rq, mp);
17389 		return;
17390 	}
17391 }
17392 
17393 void
17394 tcp_wput(queue_t *q, mblk_t *mp)
17395 {
17396 	conn_t	*connp = Q_TO_CONN(q);
17397 	tcp_t	*tcp;
17398 	void (*output_proc)();
17399 	t_scalar_t type;
17400 	uchar_t *rptr;
17401 	struct iocblk	*iocp;
17402 	uint32_t	msize;
17403 
17404 	ASSERT(connp->conn_ref >= 2);
17405 
17406 	switch (DB_TYPE(mp)) {
17407 	case M_DATA:
17408 		tcp = connp->conn_tcp;
17409 		ASSERT(tcp != NULL);
17410 
17411 		msize = msgdsize(mp);
17412 
17413 		mutex_enter(&connp->conn_lock);
17414 		CONN_INC_REF_LOCKED(connp);
17415 
17416 		tcp->tcp_squeue_bytes += msize;
17417 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
17418 			mutex_exit(&connp->conn_lock);
17419 			tcp_setqfull(tcp);
17420 		} else
17421 			mutex_exit(&connp->conn_lock);
17422 
17423 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17424 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
17425 		return;
17426 	case M_PROTO:
17427 	case M_PCPROTO:
17428 		/*
17429 		 * if it is a snmp message, don't get behind the squeue
17430 		 */
17431 		tcp = connp->conn_tcp;
17432 		rptr = mp->b_rptr;
17433 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
17434 			type = ((union T_primitives *)rptr)->type;
17435 		} else {
17436 			if (tcp->tcp_debug) {
17437 				(void) strlog(TCP_MOD_ID, 0, 1,
17438 				    SL_ERROR|SL_TRACE,
17439 				    "tcp_wput_proto, dropping one...");
17440 			}
17441 			freemsg(mp);
17442 			return;
17443 		}
17444 		if (type == T_SVR4_OPTMGMT_REQ) {
17445 			cred_t	*cr = DB_CREDDEF(mp,
17446 			    tcp->tcp_cred);
17447 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
17448 			    cr)) {
17449 				/*
17450 				 * This was a SNMP request
17451 				 */
17452 				return;
17453 			} else {
17454 				output_proc = tcp_wput_proto;
17455 			}
17456 		} else {
17457 			output_proc = tcp_wput_proto;
17458 		}
17459 		break;
17460 	case M_IOCTL:
17461 		/*
17462 		 * Most ioctls can be processed right away without going via
17463 		 * squeues - process them right here. Those that do require
17464 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
17465 		 * are processed by tcp_wput_ioctl().
17466 		 */
17467 		iocp = (struct iocblk *)mp->b_rptr;
17468 		tcp = connp->conn_tcp;
17469 
17470 		switch (iocp->ioc_cmd) {
17471 		case TCP_IOC_ABORT_CONN:
17472 			tcp_ioctl_abort_conn(q, mp);
17473 			return;
17474 		case TI_GETPEERNAME:
17475 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
17476 				iocp->ioc_error = ENOTCONN;
17477 				iocp->ioc_count = 0;
17478 				mp->b_datap->db_type = M_IOCACK;
17479 				qreply(q, mp);
17480 				return;
17481 			}
17482 			/* FALLTHRU */
17483 		case TI_GETMYNAME:
17484 			mi_copyin(q, mp, NULL,
17485 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
17486 			return;
17487 		case ND_SET:
17488 			/* nd_getset does the necessary checks */
17489 		case ND_GET:
17490 			if (!nd_getset(q, tcp_g_nd, mp)) {
17491 				CALL_IP_WPUT(connp, q, mp);
17492 				return;
17493 			}
17494 			qreply(q, mp);
17495 			return;
17496 		case TCP_IOC_DEFAULT_Q:
17497 			/*
17498 			 * Wants to be the default wq. Check the credentials
17499 			 * first, the rest is executed via squeue.
17500 			 */
17501 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
17502 				iocp->ioc_error = EPERM;
17503 				iocp->ioc_count = 0;
17504 				mp->b_datap->db_type = M_IOCACK;
17505 				qreply(q, mp);
17506 				return;
17507 			}
17508 			output_proc = tcp_wput_ioctl;
17509 			break;
17510 		default:
17511 			output_proc = tcp_wput_ioctl;
17512 			break;
17513 		}
17514 		break;
17515 	default:
17516 		output_proc = tcp_wput_nondata;
17517 		break;
17518 	}
17519 
17520 	CONN_INC_REF(connp);
17521 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17522 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
17523 }
17524 
17525 /*
17526  * Initial STREAMS write side put() procedure for sockets. It tries to
17527  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
17528  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
17529  * are handled by tcp_wput() as usual.
17530  *
17531  * All further messages will also be handled by tcp_wput() because we cannot
17532  * be sure that the above short cut is safe later.
17533  */
17534 static void
17535 tcp_wput_sock(queue_t *wq, mblk_t *mp)
17536 {
17537 	conn_t			*connp = Q_TO_CONN(wq);
17538 	tcp_t			*tcp = connp->conn_tcp;
17539 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
17540 
17541 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
17542 	wq->q_qinfo = &tcp_winit;
17543 
17544 	ASSERT(IPCL_IS_TCP(connp));
17545 	ASSERT(TCP_IS_SOCKET(tcp));
17546 
17547 	if (DB_TYPE(mp) == M_PCPROTO &&
17548 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
17549 	    car->PRIM_type == T_CAPABILITY_REQ) {
17550 		tcp_capability_req(tcp, mp);
17551 		return;
17552 	}
17553 
17554 	tcp_wput(wq, mp);
17555 }
17556 
17557 static boolean_t
17558 tcp_zcopy_check(tcp_t *tcp)
17559 {
17560 	conn_t	*connp = tcp->tcp_connp;
17561 	ire_t	*ire;
17562 	boolean_t	zc_enabled = B_FALSE;
17563 
17564 	if (do_tcpzcopy == 2)
17565 		zc_enabled = B_TRUE;
17566 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
17567 	    IPCL_IS_CONNECTED(connp) &&
17568 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
17569 	    connp->conn_dontroute == 0 &&
17570 	    connp->conn_xmit_if_ill == NULL &&
17571 	    connp->conn_nofailover_ill == NULL &&
17572 	    do_tcpzcopy == 1) {
17573 		/*
17574 		 * the checks above  closely resemble the fast path checks
17575 		 * in tcp_send_data().
17576 		 */
17577 		mutex_enter(&connp->conn_lock);
17578 		ire = connp->conn_ire_cache;
17579 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
17580 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17581 			IRE_REFHOLD(ire);
17582 			if (ire->ire_stq != NULL) {
17583 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
17584 
17585 				zc_enabled = ill && (ill->ill_capabilities &
17586 				    ILL_CAPAB_ZEROCOPY) &&
17587 				    (ill->ill_zerocopy_capab->
17588 				    ill_zerocopy_flags != 0);
17589 			}
17590 			IRE_REFRELE(ire);
17591 		}
17592 		mutex_exit(&connp->conn_lock);
17593 	}
17594 	tcp->tcp_snd_zcopy_on = zc_enabled;
17595 	if (!TCP_IS_DETACHED(tcp)) {
17596 		if (zc_enabled) {
17597 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
17598 			TCP_STAT(tcp_zcopy_on);
17599 		} else {
17600 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
17601 			TCP_STAT(tcp_zcopy_off);
17602 		}
17603 	}
17604 	return (zc_enabled);
17605 }
17606 
17607 static mblk_t *
17608 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
17609 {
17610 	if (do_tcpzcopy == 2)
17611 		return (bp);
17612 	else if (tcp->tcp_snd_zcopy_on) {
17613 		tcp->tcp_snd_zcopy_on = B_FALSE;
17614 		if (!TCP_IS_DETACHED(tcp)) {
17615 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
17616 			TCP_STAT(tcp_zcopy_disable);
17617 		}
17618 	}
17619 	return (tcp_zcopy_backoff(tcp, bp, 0));
17620 }
17621 
17622 /*
17623  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
17624  * the original desballoca'ed segmapped mblk.
17625  */
17626 static mblk_t *
17627 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
17628 {
17629 	mblk_t *head, *tail, *nbp;
17630 	if (IS_VMLOANED_MBLK(bp)) {
17631 		TCP_STAT(tcp_zcopy_backoff);
17632 		if ((head = copyb(bp)) == NULL) {
17633 			/* fail to backoff; leave it for the next backoff */
17634 			tcp->tcp_xmit_zc_clean = B_FALSE;
17635 			return (bp);
17636 		}
17637 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
17638 			if (fix_xmitlist)
17639 				tcp_zcopy_notify(tcp);
17640 			else
17641 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
17642 		}
17643 		nbp = bp->b_cont;
17644 		if (fix_xmitlist) {
17645 			head->b_prev = bp->b_prev;
17646 			head->b_next = bp->b_next;
17647 			if (tcp->tcp_xmit_tail == bp)
17648 				tcp->tcp_xmit_tail = head;
17649 		}
17650 		bp->b_next = NULL;
17651 		bp->b_prev = NULL;
17652 		freeb(bp);
17653 	} else {
17654 		head = bp;
17655 		nbp = bp->b_cont;
17656 	}
17657 	tail = head;
17658 	while (nbp) {
17659 		if (IS_VMLOANED_MBLK(nbp)) {
17660 			TCP_STAT(tcp_zcopy_backoff);
17661 			if ((tail->b_cont = copyb(nbp)) == NULL) {
17662 				tcp->tcp_xmit_zc_clean = B_FALSE;
17663 				tail->b_cont = nbp;
17664 				return (head);
17665 			}
17666 			tail = tail->b_cont;
17667 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
17668 				if (fix_xmitlist)
17669 					tcp_zcopy_notify(tcp);
17670 				else
17671 					tail->b_datap->db_struioflag |=
17672 					    STRUIO_ZCNOTIFY;
17673 			}
17674 			bp = nbp;
17675 			nbp = nbp->b_cont;
17676 			if (fix_xmitlist) {
17677 				tail->b_prev = bp->b_prev;
17678 				tail->b_next = bp->b_next;
17679 				if (tcp->tcp_xmit_tail == bp)
17680 					tcp->tcp_xmit_tail = tail;
17681 			}
17682 			bp->b_next = NULL;
17683 			bp->b_prev = NULL;
17684 			freeb(bp);
17685 		} else {
17686 			tail->b_cont = nbp;
17687 			tail = nbp;
17688 			nbp = nbp->b_cont;
17689 		}
17690 	}
17691 	if (fix_xmitlist) {
17692 		tcp->tcp_xmit_last = tail;
17693 		tcp->tcp_xmit_zc_clean = B_TRUE;
17694 	}
17695 	return (head);
17696 }
17697 
17698 static void
17699 tcp_zcopy_notify(tcp_t *tcp)
17700 {
17701 	struct stdata	*stp;
17702 
17703 	if (tcp->tcp_detached)
17704 		return;
17705 	stp = STREAM(tcp->tcp_rq);
17706 	mutex_enter(&stp->sd_lock);
17707 	stp->sd_flag |= STZCNOTIFY;
17708 	cv_broadcast(&stp->sd_zcopy_wait);
17709 	mutex_exit(&stp->sd_lock);
17710 }
17711 
17712 static void
17713 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
17714 {
17715 	ipha_t		*ipha;
17716 	ipaddr_t	src;
17717 	ipaddr_t	dst;
17718 	uint32_t	cksum;
17719 	ire_t		*ire;
17720 	uint16_t	*up;
17721 	ill_t		*ill;
17722 	conn_t		*connp = tcp->tcp_connp;
17723 	uint32_t	hcksum_txflags = 0;
17724 	mblk_t		*ire_fp_mp;
17725 	uint_t		ire_fp_mp_len;
17726 
17727 	ASSERT(DB_TYPE(mp) == M_DATA);
17728 
17729 	ipha = (ipha_t *)mp->b_rptr;
17730 	src = ipha->ipha_src;
17731 	dst = ipha->ipha_dst;
17732 
17733 	/*
17734 	 * Drop off slow path for IPv6 and also if options are present.
17735 	 */
17736 	if (tcp->tcp_ipversion != IPV4_VERSION ||
17737 	    !IPCL_IS_CONNECTED(connp) ||
17738 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
17739 	    connp->conn_dontroute ||
17740 	    connp->conn_xmit_if_ill != NULL ||
17741 	    connp->conn_nofailover_ill != NULL ||
17742 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
17743 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
17744 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
17745 		if (tcp->tcp_snd_zcopy_aware)
17746 			mp = tcp_zcopy_disable(tcp, mp);
17747 		TCP_STAT(tcp_ip_send);
17748 		CALL_IP_WPUT(connp, q, mp);
17749 		return;
17750 	}
17751 
17752 	mutex_enter(&connp->conn_lock);
17753 	ire = connp->conn_ire_cache;
17754 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
17755 	if (ire != NULL && ire->ire_addr == dst &&
17756 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17757 		IRE_REFHOLD(ire);
17758 		mutex_exit(&connp->conn_lock);
17759 	} else {
17760 		boolean_t cached = B_FALSE;
17761 
17762 		/* force a recheck later on */
17763 		tcp->tcp_ire_ill_check_done = B_FALSE;
17764 
17765 		TCP_DBGSTAT(tcp_ire_null1);
17766 		connp->conn_ire_cache = NULL;
17767 		mutex_exit(&connp->conn_lock);
17768 		if (ire != NULL)
17769 			IRE_REFRELE_NOTR(ire);
17770 		ire = ire_cache_lookup(dst, connp->conn_zoneid);
17771 		if (ire == NULL) {
17772 			if (tcp->tcp_snd_zcopy_aware)
17773 				mp = tcp_zcopy_backoff(tcp, mp, 0);
17774 			TCP_STAT(tcp_ire_null);
17775 			CALL_IP_WPUT(connp, q, mp);
17776 			return;
17777 		}
17778 		IRE_REFHOLD_NOTR(ire);
17779 		/*
17780 		 * Since we are inside the squeue, there cannot be another
17781 		 * thread in TCP trying to set the conn_ire_cache now.  The
17782 		 * check for IRE_MARK_CONDEMNED ensures that an interface
17783 		 * unplumb thread has not yet started cleaning up the conns.
17784 		 * Hence we don't need to grab the conn lock.
17785 		 */
17786 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
17787 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
17788 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17789 				connp->conn_ire_cache = ire;
17790 				cached = B_TRUE;
17791 			}
17792 			rw_exit(&ire->ire_bucket->irb_lock);
17793 		}
17794 
17795 		/*
17796 		 * We can continue to use the ire but since it was
17797 		 * not cached, we should drop the extra reference.
17798 		 */
17799 		if (!cached)
17800 			IRE_REFRELE_NOTR(ire);
17801 	}
17802 
17803 	if (ire->ire_flags & RTF_MULTIRT ||
17804 	    ire->ire_stq == NULL ||
17805 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
17806 	    (ire_fp_mp = ire->ire_fp_mp) == NULL ||
17807 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
17808 		if (tcp->tcp_snd_zcopy_aware)
17809 			mp = tcp_zcopy_disable(tcp, mp);
17810 		TCP_STAT(tcp_ip_ire_send);
17811 		IRE_REFRELE(ire);
17812 		CALL_IP_WPUT(connp, q, mp);
17813 		return;
17814 	}
17815 
17816 	ill = ire_to_ill(ire);
17817 	if (connp->conn_outgoing_ill != NULL) {
17818 		ill_t *conn_outgoing_ill = NULL;
17819 		/*
17820 		 * Choose a good ill in the group to send the packets on.
17821 		 */
17822 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
17823 		ill = ire_to_ill(ire);
17824 	}
17825 	ASSERT(ill != NULL);
17826 
17827 	if (!tcp->tcp_ire_ill_check_done) {
17828 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
17829 		tcp->tcp_ire_ill_check_done = B_TRUE;
17830 	}
17831 
17832 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
17833 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
17834 #ifndef _BIG_ENDIAN
17835 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
17836 #endif
17837 
17838 	/*
17839 	 * Check to see if we need to re-enable MDT for this connection
17840 	 * because it was previously disabled due to changes in the ill;
17841 	 * note that by doing it here, this re-enabling only applies when
17842 	 * the packet is not dispatched through CALL_IP_WPUT().
17843 	 *
17844 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
17845 	 * case, since that's how we ended up here.  For IPv6, we do the
17846 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
17847 	 */
17848 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
17849 		/*
17850 		 * Restore MDT for this connection, so that next time around
17851 		 * it is eligible to go through tcp_multisend() path again.
17852 		 */
17853 		TCP_STAT(tcp_mdt_conn_resumed1);
17854 		tcp->tcp_mdt = B_TRUE;
17855 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
17856 		    "interface %s\n", (void *)connp, ill->ill_name));
17857 	}
17858 
17859 	if (tcp->tcp_snd_zcopy_aware) {
17860 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
17861 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
17862 			mp = tcp_zcopy_disable(tcp, mp);
17863 		/*
17864 		 * we shouldn't need to reset ipha as the mp containing
17865 		 * ipha should never be a zero-copy mp.
17866 		 */
17867 	}
17868 
17869 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
17870 		ASSERT(ill->ill_hcksum_capab != NULL);
17871 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
17872 	}
17873 
17874 	/* pseudo-header checksum (do it in parts for IP header checksum) */
17875 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
17876 
17877 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
17878 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
17879 
17880 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
17881 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
17882 
17883 	/* Software checksum? */
17884 	if (DB_CKSUMFLAGS(mp) == 0) {
17885 		TCP_STAT(tcp_out_sw_cksum);
17886 		TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
17887 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
17888 	}
17889 
17890 	ipha->ipha_fragment_offset_and_flags |=
17891 	    (uint32_t)htons(ire->ire_frag_flag);
17892 
17893 	/* Calculate IP header checksum if hardware isn't capable */
17894 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
17895 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
17896 		    ((uint16_t *)ipha)[4]);
17897 	}
17898 
17899 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
17900 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
17901 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
17902 
17903 	UPDATE_OB_PKT_COUNT(ire);
17904 	ire->ire_last_used_time = lbolt;
17905 	BUMP_MIB(&ip_mib, ipOutRequests);
17906 
17907 	if (ILL_POLL_CAPABLE(ill)) {
17908 		/*
17909 		 * Send the packet directly to DLD, where it may be queued
17910 		 * depending on the availability of transmit resources at
17911 		 * the media layer.
17912 		 */
17913 		IP_POLL_ILL_TX(ill, mp);
17914 	} else {
17915 		putnext(ire->ire_stq, mp);
17916 	}
17917 	IRE_REFRELE(ire);
17918 }
17919 
17920 /*
17921  * This handles the case when the receiver has shrunk its win. Per RFC 1122
17922  * if the receiver shrinks the window, i.e. moves the right window to the
17923  * left, the we should not send new data, but should retransmit normally the
17924  * old unacked data between suna and suna + swnd. We might has sent data
17925  * that is now outside the new window, pretend that we didn't send  it.
17926  */
17927 static void
17928 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
17929 {
17930 	uint32_t	snxt = tcp->tcp_snxt;
17931 	mblk_t		*xmit_tail;
17932 	int32_t		offset;
17933 
17934 	ASSERT(shrunk_count > 0);
17935 
17936 	/* Pretend we didn't send the data outside the window */
17937 	snxt -= shrunk_count;
17938 
17939 	/* Get the mblk and the offset in it per the shrunk window */
17940 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
17941 
17942 	ASSERT(xmit_tail != NULL);
17943 
17944 	/* Reset all the values per the now shrunk window */
17945 	tcp->tcp_snxt = snxt;
17946 	tcp->tcp_xmit_tail = xmit_tail;
17947 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
17948 	    offset;
17949 	tcp->tcp_unsent += shrunk_count;
17950 
17951 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
17952 		/*
17953 		 * Make sure the timer is running so that we will probe a zero
17954 		 * window.
17955 		 */
17956 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17957 }
17958 
17959 
17960 /*
17961  * The TCP normal data output path.
17962  * NOTE: the logic of the fast path is duplicated from this function.
17963  */
17964 static void
17965 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
17966 {
17967 	int		len;
17968 	mblk_t		*local_time;
17969 	mblk_t		*mp1;
17970 	uint32_t	snxt;
17971 	int		tail_unsent;
17972 	int		tcpstate;
17973 	int		usable = 0;
17974 	mblk_t		*xmit_tail;
17975 	queue_t		*q = tcp->tcp_wq;
17976 	int32_t		mss;
17977 	int32_t		num_sack_blk = 0;
17978 	int32_t		tcp_hdr_len;
17979 	int32_t		tcp_tcp_hdr_len;
17980 	int		mdt_thres;
17981 	int		rc;
17982 
17983 	tcpstate = tcp->tcp_state;
17984 	if (mp == NULL) {
17985 		/*
17986 		 * tcp_wput_data() with NULL mp should only be called when
17987 		 * there is unsent data.
17988 		 */
17989 		ASSERT(tcp->tcp_unsent > 0);
17990 		/* Really tacky... but we need this for detached closes. */
17991 		len = tcp->tcp_unsent;
17992 		goto data_null;
17993 	}
17994 
17995 #if CCS_STATS
17996 	wrw_stats.tot.count++;
17997 	wrw_stats.tot.bytes += msgdsize(mp);
17998 #endif
17999 	ASSERT(mp->b_datap->db_type == M_DATA);
18000 	/*
18001 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18002 	 * or before a connection attempt has begun.
18003 	 */
18004 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18005 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18006 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18007 #ifdef DEBUG
18008 			cmn_err(CE_WARN,
18009 			    "tcp_wput_data: data after ordrel, %s",
18010 			    tcp_display(tcp, NULL,
18011 			    DISP_ADDR_AND_PORT));
18012 #else
18013 			if (tcp->tcp_debug) {
18014 				(void) strlog(TCP_MOD_ID, 0, 1,
18015 				    SL_TRACE|SL_ERROR,
18016 				    "tcp_wput_data: data after ordrel, %s\n",
18017 				    tcp_display(tcp, NULL,
18018 				    DISP_ADDR_AND_PORT));
18019 			}
18020 #endif /* DEBUG */
18021 		}
18022 		if (tcp->tcp_snd_zcopy_aware &&
18023 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18024 			tcp_zcopy_notify(tcp);
18025 		freemsg(mp);
18026 		if (tcp->tcp_flow_stopped &&
18027 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18028 			tcp_clrqfull(tcp);
18029 		}
18030 		return;
18031 	}
18032 
18033 	/* Strip empties */
18034 	for (;;) {
18035 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18036 		    (uintptr_t)INT_MAX);
18037 		len = (int)(mp->b_wptr - mp->b_rptr);
18038 		if (len > 0)
18039 			break;
18040 		mp1 = mp;
18041 		mp = mp->b_cont;
18042 		freeb(mp1);
18043 		if (!mp) {
18044 			return;
18045 		}
18046 	}
18047 
18048 	/* If we are the first on the list ... */
18049 	if (tcp->tcp_xmit_head == NULL) {
18050 		tcp->tcp_xmit_head = mp;
18051 		tcp->tcp_xmit_tail = mp;
18052 		tcp->tcp_xmit_tail_unsent = len;
18053 	} else {
18054 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18055 		struct datab *dp;
18056 
18057 		mp1 = tcp->tcp_xmit_last;
18058 		if (len < tcp_tx_pull_len &&
18059 		    (dp = mp1->b_datap)->db_ref == 1 &&
18060 		    dp->db_lim - mp1->b_wptr >= len) {
18061 			ASSERT(len > 0);
18062 			ASSERT(!mp1->b_cont);
18063 			if (len == 1) {
18064 				*mp1->b_wptr++ = *mp->b_rptr;
18065 			} else {
18066 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18067 				mp1->b_wptr += len;
18068 			}
18069 			if (mp1 == tcp->tcp_xmit_tail)
18070 				tcp->tcp_xmit_tail_unsent += len;
18071 			mp1->b_cont = mp->b_cont;
18072 			if (tcp->tcp_snd_zcopy_aware &&
18073 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18074 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18075 			freeb(mp);
18076 			mp = mp1;
18077 		} else {
18078 			tcp->tcp_xmit_last->b_cont = mp;
18079 		}
18080 		len += tcp->tcp_unsent;
18081 	}
18082 
18083 	/* Tack on however many more positive length mblks we have */
18084 	if ((mp1 = mp->b_cont) != NULL) {
18085 		do {
18086 			int tlen;
18087 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18088 			    (uintptr_t)INT_MAX);
18089 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18090 			if (tlen <= 0) {
18091 				mp->b_cont = mp1->b_cont;
18092 				freeb(mp1);
18093 			} else {
18094 				len += tlen;
18095 				mp = mp1;
18096 			}
18097 		} while ((mp1 = mp->b_cont) != NULL);
18098 	}
18099 	tcp->tcp_xmit_last = mp;
18100 	tcp->tcp_unsent = len;
18101 
18102 	if (urgent)
18103 		usable = 1;
18104 
18105 data_null:
18106 	snxt = tcp->tcp_snxt;
18107 	xmit_tail = tcp->tcp_xmit_tail;
18108 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18109 
18110 	/*
18111 	 * Note that tcp_mss has been adjusted to take into account the
18112 	 * timestamp option if applicable.  Because SACK options do not
18113 	 * appear in every TCP segments and they are of variable lengths,
18114 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18115 	 * the actual segment length when we need to send a segment which
18116 	 * includes SACK options.
18117 	 */
18118 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18119 		int32_t	opt_len;
18120 
18121 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18122 		    tcp->tcp_num_sack_blk);
18123 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18124 		    2 + TCPOPT_HEADER_LEN;
18125 		mss = tcp->tcp_mss - opt_len;
18126 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18127 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18128 	} else {
18129 		mss = tcp->tcp_mss;
18130 		tcp_hdr_len = tcp->tcp_hdr_len;
18131 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18132 	}
18133 
18134 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18135 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18136 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
18137 	}
18138 	if (tcpstate == TCPS_SYN_RCVD) {
18139 		/*
18140 		 * The three-way connection establishment handshake is not
18141 		 * complete yet. We want to queue the data for transmission
18142 		 * after entering ESTABLISHED state (RFC793). A jump to
18143 		 * "done" label effectively leaves data on the queue.
18144 		 */
18145 		goto done;
18146 	} else {
18147 		int usable_r = tcp->tcp_swnd;
18148 
18149 		/*
18150 		 * In the special case when cwnd is zero, which can only
18151 		 * happen if the connection is ECN capable, return now.
18152 		 * New segments is sent using tcp_timer().  The timer
18153 		 * is set in tcp_rput_data().
18154 		 */
18155 		if (tcp->tcp_cwnd == 0) {
18156 			/*
18157 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18158 			 * finished.
18159 			 */
18160 			ASSERT(tcp->tcp_ecn_ok ||
18161 			    tcp->tcp_state < TCPS_ESTABLISHED);
18162 			return;
18163 		}
18164 
18165 		/* NOTE: trouble if xmitting while SYN not acked? */
18166 		usable_r -= snxt;
18167 		usable_r += tcp->tcp_suna;
18168 
18169 		/*
18170 		 * Check if the receiver has shrunk the window.  If
18171 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18172 		 * cannot be set as there is unsent data, so FIN cannot
18173 		 * be sent out.  Otherwise, we need to take into account
18174 		 * of FIN as it consumes an "invisible" sequence number.
18175 		 */
18176 		ASSERT(tcp->tcp_fin_sent == 0);
18177 		if (usable_r < 0) {
18178 			/*
18179 			 * The receiver has shrunk the window and we have sent
18180 			 * -usable_r date beyond the window, re-adjust.
18181 			 *
18182 			 * If TCP window scaling is enabled, there can be
18183 			 * round down error as the advertised receive window
18184 			 * is actually right shifted n bits.  This means that
18185 			 * the lower n bits info is wiped out.  It will look
18186 			 * like the window is shrunk.  Do a check here to
18187 			 * see if the shrunk amount is actually within the
18188 			 * error in window calculation.  If it is, just
18189 			 * return.  Note that this check is inside the
18190 			 * shrunk window check.  This makes sure that even
18191 			 * though tcp_process_shrunk_swnd() is not called,
18192 			 * we will stop further processing.
18193 			 */
18194 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18195 				tcp_process_shrunk_swnd(tcp, -usable_r);
18196 			}
18197 			return;
18198 		}
18199 
18200 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18201 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18202 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18203 
18204 		/* usable = MIN(usable, unsent) */
18205 		if (usable_r > len)
18206 			usable_r = len;
18207 
18208 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18209 		if (usable_r > 0) {
18210 			usable = usable_r;
18211 		} else {
18212 			/* Bypass all other unnecessary processing. */
18213 			goto done;
18214 		}
18215 	}
18216 
18217 	local_time = (mblk_t *)lbolt;
18218 
18219 	/*
18220 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18221 	 * BSD.  This is more in line with the true intent of Nagle.
18222 	 *
18223 	 * The conditions are:
18224 	 * 1. The amount of unsent data (or amount of data which can be
18225 	 *    sent, whichever is smaller) is less than Nagle limit.
18226 	 * 2. The last sent size is also less than Nagle limit.
18227 	 * 3. There is unack'ed data.
18228 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18229 	 *    Nagle algorithm.  This reduces the probability that urgent
18230 	 *    bytes get "merged" together.
18231 	 * 5. The app has not closed the connection.  This eliminates the
18232 	 *    wait time of the receiving side waiting for the last piece of
18233 	 *    (small) data.
18234 	 *
18235 	 * If all are satisified, exit without sending anything.  Note
18236 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18237 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18238 	 * 4095).
18239 	 */
18240 	if (usable < (int)tcp->tcp_naglim &&
18241 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18242 	    snxt != tcp->tcp_suna &&
18243 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18244 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18245 		goto done;
18246 	}
18247 
18248 	if (tcp->tcp_cork) {
18249 		/*
18250 		 * if the tcp->tcp_cork option is set, then we have to force
18251 		 * TCP not to send partial segment (smaller than MSS bytes).
18252 		 * We are calculating the usable now based on full mss and
18253 		 * will save the rest of remaining data for later.
18254 		 */
18255 		if (usable < mss)
18256 			goto done;
18257 		usable = (usable / mss) * mss;
18258 	}
18259 
18260 	/* Update the latest receive window size in TCP header. */
18261 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18262 	    tcp->tcp_tcph->th_win);
18263 
18264 	/*
18265 	 * Determine if it's worthwhile to attempt MDT, based on:
18266 	 *
18267 	 * 1. Simple TCP/IP{v4,v6} (no options).
18268 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18269 	 * 3. If the TCP connection is in ESTABLISHED state.
18270 	 * 4. The TCP is not detached.
18271 	 *
18272 	 * If any of the above conditions have changed during the
18273 	 * connection, stop using MDT and restore the stream head
18274 	 * parameters accordingly.
18275 	 */
18276 	if (tcp->tcp_mdt &&
18277 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
18278 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
18279 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18280 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
18281 	    tcp->tcp_state != TCPS_ESTABLISHED ||
18282 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
18283 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
18284 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
18285 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
18286 		tcp->tcp_mdt = B_FALSE;
18287 
18288 		/* Anything other than detached is considered pathological */
18289 		if (!TCP_IS_DETACHED(tcp)) {
18290 			TCP_STAT(tcp_mdt_conn_halted1);
18291 			(void) tcp_maxpsz_set(tcp, B_TRUE);
18292 		}
18293 	}
18294 
18295 	/* Use MDT if sendable amount is greater than the threshold */
18296 	if (tcp->tcp_mdt &&
18297 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
18298 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
18299 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
18300 	    (tcp->tcp_valid_bits == 0 ||
18301 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
18302 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
18303 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18304 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18305 		    local_time, mdt_thres);
18306 	} else {
18307 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18308 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18309 		    local_time, INT_MAX);
18310 	}
18311 
18312 	/* Pretend that all we were trying to send really got sent */
18313 	if (rc < 0 && tail_unsent < 0) {
18314 		do {
18315 			xmit_tail = xmit_tail->b_cont;
18316 			xmit_tail->b_prev = local_time;
18317 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
18318 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
18319 			tail_unsent += (int)(xmit_tail->b_wptr -
18320 			    xmit_tail->b_rptr);
18321 		} while (tail_unsent < 0);
18322 	}
18323 done:;
18324 	tcp->tcp_xmit_tail = xmit_tail;
18325 	tcp->tcp_xmit_tail_unsent = tail_unsent;
18326 	len = tcp->tcp_snxt - snxt;
18327 	if (len) {
18328 		/*
18329 		 * If new data was sent, need to update the notsack
18330 		 * list, which is, afterall, data blocks that have
18331 		 * not been sack'ed by the receiver.  New data is
18332 		 * not sack'ed.
18333 		 */
18334 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
18335 			/* len is a negative value. */
18336 			tcp->tcp_pipe -= len;
18337 			tcp_notsack_update(&(tcp->tcp_notsack_list),
18338 			    tcp->tcp_snxt, snxt,
18339 			    &(tcp->tcp_num_notsack_blk),
18340 			    &(tcp->tcp_cnt_notsack_list));
18341 		}
18342 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
18343 		tcp->tcp_rack = tcp->tcp_rnxt;
18344 		tcp->tcp_rack_cnt = 0;
18345 		if ((snxt + len) == tcp->tcp_suna) {
18346 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18347 		}
18348 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
18349 		/*
18350 		 * Didn't send anything. Make sure the timer is running
18351 		 * so that we will probe a zero window.
18352 		 */
18353 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18354 	}
18355 	/* Note that len is the amount we just sent but with a negative sign */
18356 	tcp->tcp_unsent += len;
18357 	if (tcp->tcp_flow_stopped) {
18358 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18359 			tcp_clrqfull(tcp);
18360 		}
18361 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
18362 		tcp_setqfull(tcp);
18363 	}
18364 }
18365 
18366 /*
18367  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
18368  * outgoing TCP header with the template header, as well as other
18369  * options such as time-stamp, ECN and/or SACK.
18370  */
18371 static void
18372 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
18373 {
18374 	tcph_t *tcp_tmpl, *tcp_h;
18375 	uint32_t *dst, *src;
18376 	int hdrlen;
18377 
18378 	ASSERT(OK_32PTR(rptr));
18379 
18380 	/* Template header */
18381 	tcp_tmpl = tcp->tcp_tcph;
18382 
18383 	/* Header of outgoing packet */
18384 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18385 
18386 	/* dst and src are opaque 32-bit fields, used for copying */
18387 	dst = (uint32_t *)rptr;
18388 	src = (uint32_t *)tcp->tcp_iphc;
18389 	hdrlen = tcp->tcp_hdr_len;
18390 
18391 	/* Fill time-stamp option if needed */
18392 	if (tcp->tcp_snd_ts_ok) {
18393 		U32_TO_BE32((uint32_t)now,
18394 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
18395 		U32_TO_BE32(tcp->tcp_ts_recent,
18396 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
18397 	} else {
18398 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18399 	}
18400 
18401 	/*
18402 	 * Copy the template header; is this really more efficient than
18403 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
18404 	 * but perhaps not for other scenarios.
18405 	 */
18406 	dst[0] = src[0];
18407 	dst[1] = src[1];
18408 	dst[2] = src[2];
18409 	dst[3] = src[3];
18410 	dst[4] = src[4];
18411 	dst[5] = src[5];
18412 	dst[6] = src[6];
18413 	dst[7] = src[7];
18414 	dst[8] = src[8];
18415 	dst[9] = src[9];
18416 	if (hdrlen -= 40) {
18417 		hdrlen >>= 2;
18418 		dst += 10;
18419 		src += 10;
18420 		do {
18421 			*dst++ = *src++;
18422 		} while (--hdrlen);
18423 	}
18424 
18425 	/*
18426 	 * Set the ECN info in the TCP header if it is not a zero
18427 	 * window probe.  Zero window probe is only sent in
18428 	 * tcp_wput_data() and tcp_timer().
18429 	 */
18430 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
18431 		SET_ECT(tcp, rptr);
18432 
18433 		if (tcp->tcp_ecn_echo_on)
18434 			tcp_h->th_flags[0] |= TH_ECE;
18435 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18436 			tcp_h->th_flags[0] |= TH_CWR;
18437 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18438 		}
18439 	}
18440 
18441 	/* Fill in SACK options */
18442 	if (num_sack_blk > 0) {
18443 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
18444 		sack_blk_t *tmp;
18445 		int32_t	i;
18446 
18447 		wptr[0] = TCPOPT_NOP;
18448 		wptr[1] = TCPOPT_NOP;
18449 		wptr[2] = TCPOPT_SACK;
18450 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18451 		    sizeof (sack_blk_t);
18452 		wptr += TCPOPT_REAL_SACK_LEN;
18453 
18454 		tmp = tcp->tcp_sack_list;
18455 		for (i = 0; i < num_sack_blk; i++) {
18456 			U32_TO_BE32(tmp[i].begin, wptr);
18457 			wptr += sizeof (tcp_seq);
18458 			U32_TO_BE32(tmp[i].end, wptr);
18459 			wptr += sizeof (tcp_seq);
18460 		}
18461 		tcp_h->th_offset_and_rsrvd[0] +=
18462 		    ((num_sack_blk * 2 + 1) << 4);
18463 	}
18464 }
18465 
18466 /*
18467  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
18468  * the destination address and SAP attribute, and if necessary, the
18469  * hardware checksum offload attribute to a Multidata message.
18470  */
18471 static int
18472 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
18473     const uint32_t start, const uint32_t stuff, const uint32_t end,
18474     const uint32_t flags)
18475 {
18476 	/* Add global destination address & SAP attribute */
18477 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
18478 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
18479 		    "destination address+SAP\n"));
18480 
18481 		if (dlmp != NULL)
18482 			TCP_STAT(tcp_mdt_allocfail);
18483 		return (-1);
18484 	}
18485 
18486 	/* Add global hwcksum attribute */
18487 	if (hwcksum &&
18488 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
18489 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
18490 		    "checksum attribute\n"));
18491 
18492 		TCP_STAT(tcp_mdt_allocfail);
18493 		return (-1);
18494 	}
18495 
18496 	return (0);
18497 }
18498 
18499 /*
18500  * Smaller and private version of pdescinfo_t used specifically for TCP,
18501  * which allows for only two payload spans per packet.
18502  */
18503 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
18504 
18505 /*
18506  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
18507  * scheme, and returns one the following:
18508  *
18509  * -1 = failed allocation.
18510  *  0 = success; burst count reached, or usable send window is too small,
18511  *      and that we'd rather wait until later before sending again.
18512  */
18513 static int
18514 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
18515     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
18516     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
18517     const int mdt_thres)
18518 {
18519 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
18520 	multidata_t	*mmd;
18521 	uint_t		obsegs, obbytes, hdr_frag_sz;
18522 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
18523 	int		num_burst_seg, max_pld;
18524 	pdesc_t		*pkt;
18525 	tcp_pdescinfo_t	tcp_pkt_info;
18526 	pdescinfo_t	*pkt_info;
18527 	int		pbuf_idx, pbuf_idx_nxt;
18528 	int		seg_len, len, spill, af;
18529 	boolean_t	add_buffer, zcopy, clusterwide;
18530 	boolean_t	rconfirm = B_FALSE;
18531 	boolean_t	done = B_FALSE;
18532 	uint32_t	cksum;
18533 	uint32_t	hwcksum_flags;
18534 	ire_t		*ire;
18535 	ill_t		*ill;
18536 	ipha_t		*ipha;
18537 	ip6_t		*ip6h;
18538 	ipaddr_t	src, dst;
18539 	ill_zerocopy_capab_t *zc_cap = NULL;
18540 	uint16_t	*up;
18541 	int		err;
18542 
18543 #ifdef	_BIG_ENDIAN
18544 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
18545 #else
18546 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
18547 #endif
18548 
18549 #define	PREP_NEW_MULTIDATA() {			\
18550 	mmd = NULL;				\
18551 	md_mp = md_hbuf = NULL;			\
18552 	cur_hdr_off = 0;			\
18553 	max_pld = tcp->tcp_mdt_max_pld;		\
18554 	pbuf_idx = pbuf_idx_nxt = -1;		\
18555 	add_buffer = B_TRUE;			\
18556 	zcopy = B_FALSE;			\
18557 }
18558 
18559 #define	PREP_NEW_PBUF() {			\
18560 	md_pbuf = md_pbuf_nxt = NULL;		\
18561 	pbuf_idx = pbuf_idx_nxt = -1;		\
18562 	cur_pld_off = 0;			\
18563 	first_snxt = *snxt;			\
18564 	ASSERT(*tail_unsent > 0);		\
18565 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
18566 }
18567 
18568 	ASSERT(mdt_thres >= mss);
18569 	ASSERT(*usable > 0 && *usable > mdt_thres);
18570 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
18571 	ASSERT(!TCP_IS_DETACHED(tcp));
18572 	ASSERT(tcp->tcp_valid_bits == 0 ||
18573 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
18574 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
18575 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
18576 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18577 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
18578 	ASSERT(tcp->tcp_connp != NULL);
18579 	ASSERT(CONN_IS_MD_FASTPATH(tcp->tcp_connp));
18580 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp));
18581 
18582 	/*
18583 	 * Note that tcp will only declare at most 2 payload spans per
18584 	 * packet, which is much lower than the maximum allowable number
18585 	 * of packet spans per Multidata.  For this reason, we use the
18586 	 * privately declared and smaller descriptor info structure, in
18587 	 * order to save some stack space.
18588 	 */
18589 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
18590 
18591 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
18592 	if (af == AF_INET) {
18593 		dst = tcp->tcp_ipha->ipha_dst;
18594 		src = tcp->tcp_ipha->ipha_src;
18595 		ASSERT(!CLASSD(dst));
18596 	}
18597 	ASSERT(af == AF_INET ||
18598 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
18599 
18600 	obsegs = obbytes = 0;
18601 	num_burst_seg = tcp->tcp_snd_burst;
18602 	md_mp_head = NULL;
18603 	PREP_NEW_MULTIDATA();
18604 
18605 	/*
18606 	 * Before we go on further, make sure there is an IRE that we can
18607 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
18608 	 * in proceeding any further, and we should just hand everything
18609 	 * off to the legacy path.
18610 	 */
18611 	mutex_enter(&tcp->tcp_connp->conn_lock);
18612 	ire = tcp->tcp_connp->conn_ire_cache;
18613 	ASSERT(!(tcp->tcp_connp->conn_state_flags & CONN_INCIPIENT));
18614 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
18615 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
18616 	    &tcp->tcp_ip6h->ip6_dst))) &&
18617 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18618 		IRE_REFHOLD(ire);
18619 		mutex_exit(&tcp->tcp_connp->conn_lock);
18620 	} else {
18621 		boolean_t cached = B_FALSE;
18622 
18623 		/* force a recheck later on */
18624 		tcp->tcp_ire_ill_check_done = B_FALSE;
18625 
18626 		TCP_DBGSTAT(tcp_ire_null1);
18627 		tcp->tcp_connp->conn_ire_cache = NULL;
18628 		mutex_exit(&tcp->tcp_connp->conn_lock);
18629 
18630 		/* Release the old ire */
18631 		if (ire != NULL)
18632 			IRE_REFRELE_NOTR(ire);
18633 
18634 		ire = (af == AF_INET) ?
18635 		    ire_cache_lookup(dst, tcp->tcp_connp->conn_zoneid) :
18636 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18637 		    tcp->tcp_connp->conn_zoneid);
18638 
18639 		if (ire == NULL) {
18640 			TCP_STAT(tcp_ire_null);
18641 			goto legacy_send_no_md;
18642 		}
18643 
18644 		IRE_REFHOLD_NOTR(ire);
18645 		/*
18646 		 * Since we are inside the squeue, there cannot be another
18647 		 * thread in TCP trying to set the conn_ire_cache now. The
18648 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18649 		 * unplumb thread has not yet started cleaning up the conns.
18650 		 * Hence we don't need to grab the conn lock.
18651 		 */
18652 		if (!(tcp->tcp_connp->conn_state_flags & CONN_CLOSING)) {
18653 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18654 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18655 				tcp->tcp_connp->conn_ire_cache = ire;
18656 				cached = B_TRUE;
18657 			}
18658 			rw_exit(&ire->ire_bucket->irb_lock);
18659 		}
18660 
18661 		/*
18662 		 * We can continue to use the ire but since it was not
18663 		 * cached, we should drop the extra reference.
18664 		 */
18665 		if (!cached)
18666 			IRE_REFRELE_NOTR(ire);
18667 	}
18668 
18669 	ASSERT(ire != NULL);
18670 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
18671 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
18672 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
18673 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18674 	/*
18675 	 * If we do support loopback for MDT (which requires modifications
18676 	 * to the receiving paths), the following assertions should go away,
18677 	 * and we would be sending the Multidata to loopback conn later on.
18678 	 */
18679 	ASSERT(!IRE_IS_LOCAL(ire));
18680 	ASSERT(ire->ire_stq != NULL);
18681 
18682 	ill = ire_to_ill(ire);
18683 	ASSERT(ill != NULL);
18684 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
18685 
18686 	if (!tcp->tcp_ire_ill_check_done) {
18687 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18688 		tcp->tcp_ire_ill_check_done = B_TRUE;
18689 	}
18690 
18691 	/*
18692 	 * If the underlying interface conditions have changed, or if the
18693 	 * new interface does not support MDT, go back to legacy path.
18694 	 */
18695 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
18696 		/* don't go through this path anymore for this connection */
18697 		TCP_STAT(tcp_mdt_conn_halted2);
18698 		tcp->tcp_mdt = B_FALSE;
18699 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
18700 		    "interface %s\n", (void *)tcp->tcp_connp, ill->ill_name));
18701 		/* IRE will be released prior to returning */
18702 		goto legacy_send_no_md;
18703 	}
18704 
18705 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
18706 		zc_cap = ill->ill_zerocopy_capab;
18707 
18708 	/* go to legacy path if interface doesn't support zerocopy */
18709 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
18710 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
18711 		/* IRE will be released prior to returning */
18712 		goto legacy_send_no_md;
18713 	}
18714 
18715 	/* does the interface support hardware checksum offload? */
18716 	hwcksum_flags = 0;
18717 	if (ILL_HCKSUM_CAPABLE(ill) &&
18718 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
18719 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
18720 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
18721 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18722 		    HCKSUM_IPHDRCKSUM)
18723 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
18724 
18725 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18726 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
18727 			hwcksum_flags |= HCK_FULLCKSUM;
18728 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18729 		    HCKSUM_INET_PARTIAL)
18730 			hwcksum_flags |= HCK_PARTIALCKSUM;
18731 	}
18732 
18733 	/*
18734 	 * Each header fragment consists of the leading extra space,
18735 	 * followed by the TCP/IP header, and the trailing extra space.
18736 	 * We make sure that each header fragment begins on a 32-bit
18737 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
18738 	 * aligned in tcp_mdt_update).
18739 	 */
18740 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
18741 	    tcp->tcp_mdt_hdr_tail), 4);
18742 
18743 	/* are we starting from the beginning of data block? */
18744 	if (*tail_unsent == 0) {
18745 		*xmit_tail = (*xmit_tail)->b_cont;
18746 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
18747 		*tail_unsent = (int)MBLKL(*xmit_tail);
18748 	}
18749 
18750 	/*
18751 	 * Here we create one or more Multidata messages, each made up of
18752 	 * one header buffer and up to N payload buffers.  This entire
18753 	 * operation is done within two loops:
18754 	 *
18755 	 * The outer loop mostly deals with creating the Multidata message,
18756 	 * as well as the header buffer that gets added to it.  It also
18757 	 * links the Multidata messages together such that all of them can
18758 	 * be sent down to the lower layer in a single putnext call; this
18759 	 * linking behavior depends on the tcp_mdt_chain tunable.
18760 	 *
18761 	 * The inner loop takes an existing Multidata message, and adds
18762 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
18763 	 * packetizes those buffers by filling up the corresponding header
18764 	 * buffer fragments with the proper IP and TCP headers, and by
18765 	 * describing the layout of each packet in the packet descriptors
18766 	 * that get added to the Multidata.
18767 	 */
18768 	do {
18769 		/*
18770 		 * If usable send window is too small, or data blocks in
18771 		 * transmit list are smaller than our threshold (i.e. app
18772 		 * performs large writes followed by small ones), we hand
18773 		 * off the control over to the legacy path.  Note that we'll
18774 		 * get back the control once it encounters a large block.
18775 		 */
18776 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
18777 		    (*xmit_tail)->b_cont != NULL &&
18778 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
18779 			/* send down what we've got so far */
18780 			if (md_mp_head != NULL) {
18781 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
18782 				    obsegs, obbytes, &rconfirm);
18783 			}
18784 			/*
18785 			 * Pass control over to tcp_send(), but tell it to
18786 			 * return to us once a large-size transmission is
18787 			 * possible.
18788 			 */
18789 			TCP_STAT(tcp_mdt_legacy_small);
18790 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
18791 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
18792 			    tail_unsent, xmit_tail, local_time,
18793 			    mdt_thres)) <= 0) {
18794 				/* burst count reached, or alloc failed */
18795 				IRE_REFRELE(ire);
18796 				return (err);
18797 			}
18798 
18799 			/* tcp_send() may have sent everything, so check */
18800 			if (*usable <= 0) {
18801 				IRE_REFRELE(ire);
18802 				return (0);
18803 			}
18804 
18805 			TCP_STAT(tcp_mdt_legacy_ret);
18806 			/*
18807 			 * We may have delivered the Multidata, so make sure
18808 			 * to re-initialize before the next round.
18809 			 */
18810 			md_mp_head = NULL;
18811 			obsegs = obbytes = 0;
18812 			num_burst_seg = tcp->tcp_snd_burst;
18813 			PREP_NEW_MULTIDATA();
18814 
18815 			/* are we starting from the beginning of data block? */
18816 			if (*tail_unsent == 0) {
18817 				*xmit_tail = (*xmit_tail)->b_cont;
18818 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
18819 				    (uintptr_t)INT_MAX);
18820 				*tail_unsent = (int)MBLKL(*xmit_tail);
18821 			}
18822 		}
18823 
18824 		/*
18825 		 * max_pld limits the number of mblks in tcp's transmit
18826 		 * queue that can be added to a Multidata message.  Once
18827 		 * this counter reaches zero, no more additional mblks
18828 		 * can be added to it.  What happens afterwards depends
18829 		 * on whether or not we are set to chain the Multidata
18830 		 * messages.  If we are to link them together, reset
18831 		 * max_pld to its original value (tcp_mdt_max_pld) and
18832 		 * prepare to create a new Multidata message which will
18833 		 * get linked to md_mp_head.  Else, leave it alone and
18834 		 * let the inner loop break on its own.
18835 		 */
18836 		if (tcp_mdt_chain && max_pld == 0)
18837 			PREP_NEW_MULTIDATA();
18838 
18839 		/* adding a payload buffer; re-initialize values */
18840 		if (add_buffer)
18841 			PREP_NEW_PBUF();
18842 
18843 		/*
18844 		 * If we don't have a Multidata, either because we just
18845 		 * (re)entered this outer loop, or after we branched off
18846 		 * to tcp_send above, setup the Multidata and header
18847 		 * buffer to be used.
18848 		 */
18849 		if (md_mp == NULL) {
18850 			int md_hbuflen;
18851 			uint32_t start, stuff;
18852 
18853 			/*
18854 			 * Calculate Multidata header buffer size large enough
18855 			 * to hold all of the headers that can possibly be
18856 			 * sent at this moment.  We'd rather over-estimate
18857 			 * the size than running out of space; this is okay
18858 			 * since this buffer is small anyway.
18859 			 */
18860 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
18861 
18862 			/*
18863 			 * Start and stuff offset for partial hardware
18864 			 * checksum offload; these are currently for IPv4.
18865 			 * For full checksum offload, they are set to zero.
18866 			 */
18867 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
18868 				if (af == AF_INET) {
18869 					start = IP_SIMPLE_HDR_LENGTH;
18870 					stuff = IP_SIMPLE_HDR_LENGTH +
18871 					    TCP_CHECKSUM_OFFSET;
18872 				} else {
18873 					start = IPV6_HDR_LEN;
18874 					stuff = IPV6_HDR_LEN +
18875 					    TCP_CHECKSUM_OFFSET;
18876 				}
18877 			} else {
18878 				start = stuff = 0;
18879 			}
18880 
18881 			/*
18882 			 * Create the header buffer, Multidata, as well as
18883 			 * any necessary attributes (destination address,
18884 			 * SAP and hardware checksum offload) that should
18885 			 * be associated with the Multidata message.
18886 			 */
18887 			ASSERT(cur_hdr_off == 0);
18888 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
18889 			    ((md_hbuf->b_wptr += md_hbuflen),
18890 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
18891 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
18892 			    /* fastpath mblk */
18893 			    (af == AF_INET) ? ire->ire_dlureq_mp :
18894 			    ire->ire_nce->nce_res_mp,
18895 			    /* hardware checksum enabled */
18896 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
18897 			    /* hardware checksum offsets */
18898 			    start, stuff, 0,
18899 			    /* hardware checksum flag */
18900 			    hwcksum_flags) != 0)) {
18901 legacy_send:
18902 				if (md_mp != NULL) {
18903 					/* Unlink message from the chain */
18904 					if (md_mp_head != NULL) {
18905 						err = (intptr_t)rmvb(md_mp_head,
18906 						    md_mp);
18907 						/*
18908 						 * We can't assert that rmvb
18909 						 * did not return -1, since we
18910 						 * may get here before linkb
18911 						 * happens.  We do, however,
18912 						 * check if we just removed the
18913 						 * only element in the list.
18914 						 */
18915 						if (err == 0)
18916 							md_mp_head = NULL;
18917 					}
18918 					/* md_hbuf gets freed automatically */
18919 					TCP_STAT(tcp_mdt_discarded);
18920 					freeb(md_mp);
18921 				} else {
18922 					/* Either allocb or mmd_alloc failed */
18923 					TCP_STAT(tcp_mdt_allocfail);
18924 					if (md_hbuf != NULL)
18925 						freeb(md_hbuf);
18926 				}
18927 
18928 				/* send down what we've got so far */
18929 				if (md_mp_head != NULL) {
18930 					tcp_multisend_data(tcp, ire, ill,
18931 					    md_mp_head, obsegs, obbytes,
18932 					    &rconfirm);
18933 				}
18934 legacy_send_no_md:
18935 				if (ire != NULL)
18936 					IRE_REFRELE(ire);
18937 				/*
18938 				 * Too bad; let the legacy path handle this.
18939 				 * We specify INT_MAX for the threshold, since
18940 				 * we gave up with the Multidata processings
18941 				 * and let the old path have it all.
18942 				 */
18943 				TCP_STAT(tcp_mdt_legacy_all);
18944 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
18945 				    tcp_tcp_hdr_len, num_sack_blk, usable,
18946 				    snxt, tail_unsent, xmit_tail, local_time,
18947 				    INT_MAX));
18948 			}
18949 
18950 			/* link to any existing ones, if applicable */
18951 			TCP_STAT(tcp_mdt_allocd);
18952 			if (md_mp_head == NULL) {
18953 				md_mp_head = md_mp;
18954 			} else if (tcp_mdt_chain) {
18955 				TCP_STAT(tcp_mdt_linked);
18956 				linkb(md_mp_head, md_mp);
18957 			}
18958 		}
18959 
18960 		ASSERT(md_mp_head != NULL);
18961 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
18962 		ASSERT(md_mp != NULL && mmd != NULL);
18963 		ASSERT(md_hbuf != NULL);
18964 
18965 		/*
18966 		 * Packetize the transmittable portion of the data block;
18967 		 * each data block is essentially added to the Multidata
18968 		 * as a payload buffer.  We also deal with adding more
18969 		 * than one payload buffers, which happens when the remaining
18970 		 * packetized portion of the current payload buffer is less
18971 		 * than MSS, while the next data block in transmit queue
18972 		 * has enough data to make up for one.  This "spillover"
18973 		 * case essentially creates a split-packet, where portions
18974 		 * of the packet's payload fragments may span across two
18975 		 * virtually discontiguous address blocks.
18976 		 */
18977 		seg_len = mss;
18978 		do {
18979 			len = seg_len;
18980 
18981 			ASSERT(len > 0);
18982 			ASSERT(max_pld >= 0);
18983 			ASSERT(!add_buffer || cur_pld_off == 0);
18984 
18985 			/*
18986 			 * First time around for this payload buffer; note
18987 			 * in the case of a spillover, the following has
18988 			 * been done prior to adding the split-packet
18989 			 * descriptor to Multidata, and we don't want to
18990 			 * repeat the process.
18991 			 */
18992 			if (add_buffer) {
18993 				ASSERT(mmd != NULL);
18994 				ASSERT(md_pbuf == NULL);
18995 				ASSERT(md_pbuf_nxt == NULL);
18996 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
18997 
18998 				/*
18999 				 * Have we reached the limit?  We'd get to
19000 				 * this case when we're not chaining the
19001 				 * Multidata messages together, and since
19002 				 * we're done, terminate this loop.
19003 				 */
19004 				if (max_pld == 0)
19005 					break; /* done */
19006 
19007 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19008 					TCP_STAT(tcp_mdt_allocfail);
19009 					goto legacy_send; /* out_of_mem */
19010 				}
19011 
19012 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19013 				    zc_cap != NULL) {
19014 					if (!ip_md_zcopy_attr(mmd, NULL,
19015 					    zc_cap->ill_zerocopy_flags)) {
19016 						freeb(md_pbuf);
19017 						TCP_STAT(tcp_mdt_allocfail);
19018 						/* out_of_mem */
19019 						goto legacy_send;
19020 					}
19021 					zcopy = B_TRUE;
19022 				}
19023 
19024 				md_pbuf->b_rptr += base_pld_off;
19025 
19026 				/*
19027 				 * Add a payload buffer to the Multidata; this
19028 				 * operation must not fail, or otherwise our
19029 				 * logic in this routine is broken.  There
19030 				 * is no memory allocation done by the
19031 				 * routine, so any returned failure simply
19032 				 * tells us that we've done something wrong.
19033 				 *
19034 				 * A failure tells us that either we're adding
19035 				 * the same payload buffer more than once, or
19036 				 * we're trying to add more buffers than
19037 				 * allowed (max_pld calculation is wrong).
19038 				 * None of the above cases should happen, and
19039 				 * we panic because either there's horrible
19040 				 * heap corruption, and/or programming mistake.
19041 				 */
19042 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19043 				if (pbuf_idx < 0) {
19044 					cmn_err(CE_PANIC, "tcp_multisend: "
19045 					    "payload buffer logic error "
19046 					    "detected for tcp %p mmd %p "
19047 					    "pbuf %p (%d)\n",
19048 					    (void *)tcp, (void *)mmd,
19049 					    (void *)md_pbuf, pbuf_idx);
19050 				}
19051 
19052 				ASSERT(max_pld > 0);
19053 				--max_pld;
19054 				add_buffer = B_FALSE;
19055 			}
19056 
19057 			ASSERT(md_mp_head != NULL);
19058 			ASSERT(md_pbuf != NULL);
19059 			ASSERT(md_pbuf_nxt == NULL);
19060 			ASSERT(pbuf_idx != -1);
19061 			ASSERT(pbuf_idx_nxt == -1);
19062 			ASSERT(*usable > 0);
19063 
19064 			/*
19065 			 * We spillover to the next payload buffer only
19066 			 * if all of the following is true:
19067 			 *
19068 			 *   1. There is not enough data on the current
19069 			 *	payload buffer to make up `len',
19070 			 *   2. We are allowed to send `len',
19071 			 *   3. The next payload buffer length is large
19072 			 *	enough to accomodate `spill'.
19073 			 */
19074 			if ((spill = len - *tail_unsent) > 0 &&
19075 			    *usable >= len &&
19076 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19077 			    max_pld > 0) {
19078 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19079 				if (md_pbuf_nxt == NULL) {
19080 					TCP_STAT(tcp_mdt_allocfail);
19081 					goto legacy_send; /* out_of_mem */
19082 				}
19083 
19084 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19085 				    zc_cap != NULL) {
19086 					if (!ip_md_zcopy_attr(mmd, NULL,
19087 					    zc_cap->ill_zerocopy_flags)) {
19088 						freeb(md_pbuf_nxt);
19089 						TCP_STAT(tcp_mdt_allocfail);
19090 						/* out_of_mem */
19091 						goto legacy_send;
19092 					}
19093 					zcopy = B_TRUE;
19094 				}
19095 
19096 				/*
19097 				 * See comments above on the first call to
19098 				 * mmd_addpldbuf for explanation on the panic.
19099 				 */
19100 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19101 				if (pbuf_idx_nxt < 0) {
19102 					panic("tcp_multisend: "
19103 					    "next payload buffer logic error "
19104 					    "detected for tcp %p mmd %p "
19105 					    "pbuf %p (%d)\n",
19106 					    (void *)tcp, (void *)mmd,
19107 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19108 				}
19109 
19110 				ASSERT(max_pld > 0);
19111 				--max_pld;
19112 			} else if (spill > 0) {
19113 				/*
19114 				 * If there's a spillover, but the following
19115 				 * xmit_tail couldn't give us enough octets
19116 				 * to reach "len", then stop the current
19117 				 * Multidata creation and let the legacy
19118 				 * tcp_send() path take over.  We don't want
19119 				 * to send the tiny segment as part of this
19120 				 * Multidata for performance reasons; instead,
19121 				 * we let the legacy path deal with grouping
19122 				 * it with the subsequent small mblks.
19123 				 */
19124 				if (*usable >= len &&
19125 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19126 					max_pld = 0;
19127 					break;	/* done */
19128 				}
19129 
19130 				/*
19131 				 * We can't spillover, and we are near
19132 				 * the end of the current payload buffer,
19133 				 * so send what's left.
19134 				 */
19135 				ASSERT(*tail_unsent > 0);
19136 				len = *tail_unsent;
19137 			}
19138 
19139 			/* tail_unsent is negated if there is a spillover */
19140 			*tail_unsent -= len;
19141 			*usable -= len;
19142 			ASSERT(*usable >= 0);
19143 
19144 			if (*usable < mss)
19145 				seg_len = *usable;
19146 			/*
19147 			 * Sender SWS avoidance; see comments in tcp_send();
19148 			 * everything else is the same, except that we only
19149 			 * do this here if there is no more data to be sent
19150 			 * following the current xmit_tail.  We don't check
19151 			 * for 1-byte urgent data because we shouldn't get
19152 			 * here if TCP_URG_VALID is set.
19153 			 */
19154 			if (*usable > 0 && *usable < mss &&
19155 			    ((md_pbuf_nxt == NULL &&
19156 			    (*xmit_tail)->b_cont == NULL) ||
19157 			    (md_pbuf_nxt != NULL &&
19158 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19159 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19160 			    (tcp->tcp_unsent -
19161 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19162 			    !tcp->tcp_zero_win_probe) {
19163 				if ((*snxt + len) == tcp->tcp_snxt &&
19164 				    (*snxt + len) == tcp->tcp_suna) {
19165 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19166 				}
19167 				done = B_TRUE;
19168 			}
19169 
19170 			/*
19171 			 * Prime pump for IP's checksumming on our behalf;
19172 			 * include the adjustment for a source route if any.
19173 			 * Do this only for software/partial hardware checksum
19174 			 * offload, as this field gets zeroed out later for
19175 			 * the full hardware checksum offload case.
19176 			 */
19177 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19178 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19179 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19180 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19181 			}
19182 
19183 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19184 			*snxt += len;
19185 
19186 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19187 			/*
19188 			 * We set the PUSH bit only if TCP has no more buffered
19189 			 * data to be transmitted (or if sender SWS avoidance
19190 			 * takes place), as opposed to setting it for every
19191 			 * last packet in the burst.
19192 			 */
19193 			if (done ||
19194 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19195 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19196 
19197 			/*
19198 			 * Set FIN bit if this is our last segment; snxt
19199 			 * already includes its length, and it will not
19200 			 * be adjusted after this point.
19201 			 */
19202 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19203 			    *snxt == tcp->tcp_fss) {
19204 				if (!tcp->tcp_fin_acked) {
19205 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19206 					BUMP_MIB(&tcp_mib, tcpOutControl);
19207 				}
19208 				if (!tcp->tcp_fin_sent) {
19209 					tcp->tcp_fin_sent = B_TRUE;
19210 					/*
19211 					 * tcp state must be ESTABLISHED
19212 					 * in order for us to get here in
19213 					 * the first place.
19214 					 */
19215 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19216 
19217 					/*
19218 					 * Upon returning from this routine,
19219 					 * tcp_wput_data() will set tcp_snxt
19220 					 * to be equal to snxt + tcp_fin_sent.
19221 					 * This is essentially the same as
19222 					 * setting it to tcp_fss + 1.
19223 					 */
19224 				}
19225 			}
19226 
19227 			tcp->tcp_last_sent_len = (ushort_t)len;
19228 
19229 			len += tcp_hdr_len;
19230 			if (tcp->tcp_ipversion == IPV4_VERSION)
19231 				tcp->tcp_ipha->ipha_length = htons(len);
19232 			else
19233 				tcp->tcp_ip6h->ip6_plen = htons(len -
19234 				    ((char *)&tcp->tcp_ip6h[1] -
19235 				    tcp->tcp_iphc));
19236 
19237 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19238 
19239 			/* setup header fragment */
19240 			PDESC_HDR_ADD(pkt_info,
19241 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19242 			    tcp->tcp_mdt_hdr_head,		/* head room */
19243 			    tcp_hdr_len,			/* len */
19244 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19245 
19246 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
19247 			    hdr_frag_sz);
19248 			ASSERT(MBLKIN(md_hbuf,
19249 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
19250 			    PDESC_HDRSIZE(pkt_info)));
19251 
19252 			/* setup first payload fragment */
19253 			PDESC_PLD_INIT(pkt_info);
19254 			PDESC_PLD_SPAN_ADD(pkt_info,
19255 			    pbuf_idx,				/* index */
19256 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
19257 			    tcp->tcp_last_sent_len);		/* len */
19258 
19259 			/* create a split-packet in case of a spillover */
19260 			if (md_pbuf_nxt != NULL) {
19261 				ASSERT(spill > 0);
19262 				ASSERT(pbuf_idx_nxt > pbuf_idx);
19263 				ASSERT(!add_buffer);
19264 
19265 				md_pbuf = md_pbuf_nxt;
19266 				md_pbuf_nxt = NULL;
19267 				pbuf_idx = pbuf_idx_nxt;
19268 				pbuf_idx_nxt = -1;
19269 				cur_pld_off = spill;
19270 
19271 				/* trim out first payload fragment */
19272 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
19273 
19274 				/* setup second payload fragment */
19275 				PDESC_PLD_SPAN_ADD(pkt_info,
19276 				    pbuf_idx,			/* index */
19277 				    md_pbuf->b_rptr,		/* start */
19278 				    spill);			/* len */
19279 
19280 				if ((*xmit_tail)->b_next == NULL) {
19281 					/*
19282 					 * Store the lbolt used for RTT
19283 					 * estimation. We can only record one
19284 					 * timestamp per mblk so we do it when
19285 					 * we reach the end of the payload
19286 					 * buffer.  Also we only take a new
19287 					 * timestamp sample when the previous
19288 					 * timed data from the same mblk has
19289 					 * been ack'ed.
19290 					 */
19291 					(*xmit_tail)->b_prev = local_time;
19292 					(*xmit_tail)->b_next =
19293 					    (mblk_t *)(uintptr_t)first_snxt;
19294 				}
19295 
19296 				first_snxt = *snxt - spill;
19297 
19298 				/*
19299 				 * Advance xmit_tail; usable could be 0 by
19300 				 * the time we got here, but we made sure
19301 				 * above that we would only spillover to
19302 				 * the next data block if usable includes
19303 				 * the spilled-over amount prior to the
19304 				 * subtraction.  Therefore, we are sure
19305 				 * that xmit_tail->b_cont can't be NULL.
19306 				 */
19307 				ASSERT((*xmit_tail)->b_cont != NULL);
19308 				*xmit_tail = (*xmit_tail)->b_cont;
19309 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19310 				    (uintptr_t)INT_MAX);
19311 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
19312 			} else {
19313 				cur_pld_off += tcp->tcp_last_sent_len;
19314 			}
19315 
19316 			/*
19317 			 * Fill in the header using the template header, and
19318 			 * add options such as time-stamp, ECN and/or SACK,
19319 			 * as needed.
19320 			 */
19321 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
19322 			    (clock_t)local_time, num_sack_blk);
19323 
19324 			/* take care of some IP header businesses */
19325 			if (af == AF_INET) {
19326 				ipha = (ipha_t *)pkt_info->hdr_rptr;
19327 
19328 				ASSERT(OK_32PTR((uchar_t *)ipha));
19329 				ASSERT(PDESC_HDRL(pkt_info) >=
19330 				    IP_SIMPLE_HDR_LENGTH);
19331 				ASSERT(ipha->ipha_version_and_hdr_length ==
19332 				    IP_SIMPLE_HDR_VERSION);
19333 
19334 				/*
19335 				 * Assign ident value for current packet; see
19336 				 * related comments in ip_wput_ire() about the
19337 				 * contract private interface with clustering
19338 				 * group.
19339 				 */
19340 				clusterwide = B_FALSE;
19341 				if (cl_inet_ipident != NULL) {
19342 					ASSERT(cl_inet_isclusterwide != NULL);
19343 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19344 					    AF_INET,
19345 					    (uint8_t *)(uintptr_t)src)) {
19346 						ipha->ipha_ident =
19347 						    (*cl_inet_ipident)
19348 						    (IPPROTO_IP, AF_INET,
19349 						    (uint8_t *)(uintptr_t)src,
19350 						    (uint8_t *)(uintptr_t)dst);
19351 						clusterwide = B_TRUE;
19352 					}
19353 				}
19354 
19355 				if (!clusterwide) {
19356 					ipha->ipha_ident = (uint16_t)
19357 					    atomic_add_32_nv(
19358 						&ire->ire_ident, 1);
19359 				}
19360 #ifndef _BIG_ENDIAN
19361 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
19362 				    (ipha->ipha_ident >> 8);
19363 #endif
19364 			} else {
19365 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
19366 
19367 				ASSERT(OK_32PTR((uchar_t *)ip6h));
19368 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
19369 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
19370 				ASSERT(PDESC_HDRL(pkt_info) >=
19371 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
19372 				    TCP_CHECKSUM_SIZE));
19373 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
19374 
19375 				if (tcp->tcp_ip_forward_progress) {
19376 					rconfirm = B_TRUE;
19377 					tcp->tcp_ip_forward_progress = B_FALSE;
19378 				}
19379 			}
19380 
19381 			/* at least one payload span, and at most two */
19382 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
19383 
19384 			/* add the packet descriptor to Multidata */
19385 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
19386 			    KM_NOSLEEP)) == NULL) {
19387 				/*
19388 				 * Any failure other than ENOMEM indicates
19389 				 * that we have passed in invalid pkt_info
19390 				 * or parameters to mmd_addpdesc, which must
19391 				 * not happen.
19392 				 *
19393 				 * EINVAL is a result of failure on boundary
19394 				 * checks against the pkt_info contents.  It
19395 				 * should not happen, and we panic because
19396 				 * either there's horrible heap corruption,
19397 				 * and/or programming mistake.
19398 				 */
19399 				if (err != ENOMEM) {
19400 					cmn_err(CE_PANIC, "tcp_multisend: "
19401 					    "pdesc logic error detected for "
19402 					    "tcp %p mmd %p pinfo %p (%d)\n",
19403 					    (void *)tcp, (void *)mmd,
19404 					    (void *)pkt_info, err);
19405 				}
19406 				TCP_STAT(tcp_mdt_addpdescfail);
19407 				goto legacy_send; /* out_of_mem */
19408 			}
19409 			ASSERT(pkt != NULL);
19410 
19411 			/* calculate IP header and TCP checksums */
19412 			if (af == AF_INET) {
19413 				/* calculate pseudo-header checksum */
19414 				cksum = (dst >> 16) + (dst & 0xFFFF) +
19415 				    (src >> 16) + (src & 0xFFFF);
19416 
19417 				/* offset for TCP header checksum */
19418 				up = IPH_TCPH_CHECKSUMP(ipha,
19419 				    IP_SIMPLE_HDR_LENGTH);
19420 			} else {
19421 				up = (uint16_t *)&ip6h->ip6_src;
19422 
19423 				/* calculate pseudo-header checksum */
19424 				cksum = up[0] + up[1] + up[2] + up[3] +
19425 				    up[4] + up[5] + up[6] + up[7] +
19426 				    up[8] + up[9] + up[10] + up[11] +
19427 				    up[12] + up[13] + up[14] + up[15];
19428 
19429 				/* Fold the initial sum */
19430 				cksum = (cksum & 0xffff) + (cksum >> 16);
19431 
19432 				up = (uint16_t *)(((uchar_t *)ip6h) +
19433 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
19434 			}
19435 
19436 			if (hwcksum_flags & HCK_FULLCKSUM) {
19437 				/* clear checksum field for hardware */
19438 				*up = 0;
19439 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
19440 				uint32_t sum;
19441 
19442 				/* pseudo-header checksumming */
19443 				sum = *up + cksum + IP_TCP_CSUM_COMP;
19444 				sum = (sum & 0xFFFF) + (sum >> 16);
19445 				*up = (sum & 0xFFFF) + (sum >> 16);
19446 			} else {
19447 				/* software checksumming */
19448 				TCP_STAT(tcp_out_sw_cksum);
19449 				TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
19450 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
19451 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
19452 				    cksum + IP_TCP_CSUM_COMP);
19453 				if (*up == 0)
19454 					*up = 0xFFFF;
19455 			}
19456 
19457 			/* IPv4 header checksum */
19458 			if (af == AF_INET) {
19459 				ipha->ipha_fragment_offset_and_flags |=
19460 				    (uint32_t)htons(ire->ire_frag_flag);
19461 
19462 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
19463 					ipha->ipha_hdr_checksum = 0;
19464 				} else {
19465 					IP_HDR_CKSUM(ipha, cksum,
19466 					    ((uint32_t *)ipha)[0],
19467 					    ((uint16_t *)ipha)[4]);
19468 				}
19469 			}
19470 
19471 			/* advance header offset */
19472 			cur_hdr_off += hdr_frag_sz;
19473 
19474 			obbytes += tcp->tcp_last_sent_len;
19475 			++obsegs;
19476 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
19477 		    *tail_unsent > 0);
19478 
19479 		if ((*xmit_tail)->b_next == NULL) {
19480 			/*
19481 			 * Store the lbolt used for RTT estimation. We can only
19482 			 * record one timestamp per mblk so we do it when we
19483 			 * reach the end of the payload buffer. Also we only
19484 			 * take a new timestamp sample when the previous timed
19485 			 * data from the same mblk has been ack'ed.
19486 			 */
19487 			(*xmit_tail)->b_prev = local_time;
19488 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
19489 		}
19490 
19491 		ASSERT(*tail_unsent >= 0);
19492 		if (*tail_unsent > 0) {
19493 			/*
19494 			 * We got here because we broke out of the above
19495 			 * loop due to of one of the following cases:
19496 			 *
19497 			 *   1. len < adjusted MSS (i.e. small),
19498 			 *   2. Sender SWS avoidance,
19499 			 *   3. max_pld is zero.
19500 			 *
19501 			 * We are done for this Multidata, so trim our
19502 			 * last payload buffer (if any) accordingly.
19503 			 */
19504 			if (md_pbuf != NULL)
19505 				md_pbuf->b_wptr -= *tail_unsent;
19506 		} else if (*usable > 0) {
19507 			*xmit_tail = (*xmit_tail)->b_cont;
19508 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19509 			    (uintptr_t)INT_MAX);
19510 			*tail_unsent = (int)MBLKL(*xmit_tail);
19511 			add_buffer = B_TRUE;
19512 		}
19513 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
19514 	    (tcp_mdt_chain || max_pld > 0));
19515 
19516 	/* send everything down */
19517 	tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
19518 	    &rconfirm);
19519 
19520 #undef PREP_NEW_MULTIDATA
19521 #undef PREP_NEW_PBUF
19522 #undef IPVER
19523 
19524 	IRE_REFRELE(ire);
19525 	return (0);
19526 }
19527 
19528 /*
19529  * A wrapper function for sending one or more Multidata messages down to
19530  * the module below ip; this routine does not release the reference of the
19531  * IRE (caller does that).  This routine is analogous to tcp_send_data().
19532  */
19533 static void
19534 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
19535     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
19536 {
19537 	uint64_t delta;
19538 	nce_t *nce;
19539 
19540 	ASSERT(ire != NULL && ill != NULL);
19541 	ASSERT(ire->ire_stq != NULL);
19542 	ASSERT(md_mp_head != NULL);
19543 	ASSERT(rconfirm != NULL);
19544 
19545 	/* adjust MIBs and IRE timestamp */
19546 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
19547 	tcp->tcp_obsegs += obsegs;
19548 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
19549 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
19550 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
19551 
19552 	if (tcp->tcp_ipversion == IPV4_VERSION) {
19553 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
19554 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
19555 	} else {
19556 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
19557 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
19558 	}
19559 
19560 	ire->ire_ob_pkt_count += obsegs;
19561 	if (ire->ire_ipif != NULL)
19562 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
19563 	ire->ire_last_used_time = lbolt;
19564 
19565 	/* send it down */
19566 	putnext(ire->ire_stq, md_mp_head);
19567 
19568 	/* we're done for TCP/IPv4 */
19569 	if (tcp->tcp_ipversion == IPV4_VERSION)
19570 		return;
19571 
19572 	nce = ire->ire_nce;
19573 
19574 	ASSERT(nce != NULL);
19575 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
19576 	ASSERT(nce->nce_state != ND_INCOMPLETE);
19577 
19578 	/* reachability confirmation? */
19579 	if (*rconfirm) {
19580 		nce->nce_last = TICK_TO_MSEC(lbolt64);
19581 		if (nce->nce_state != ND_REACHABLE) {
19582 			mutex_enter(&nce->nce_lock);
19583 			nce->nce_state = ND_REACHABLE;
19584 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
19585 			mutex_exit(&nce->nce_lock);
19586 			(void) untimeout(nce->nce_timeout_id);
19587 			if (ip_debug > 2) {
19588 				/* ip1dbg */
19589 				pr_addr_dbg("tcp_multisend_data: state "
19590 				    "for %s changed to REACHABLE\n",
19591 				    AF_INET6, &ire->ire_addr_v6);
19592 			}
19593 		}
19594 		/* reset transport reachability confirmation */
19595 		*rconfirm = B_FALSE;
19596 	}
19597 
19598 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
19599 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
19600 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
19601 
19602 	if (delta > (uint64_t)ill->ill_reachable_time) {
19603 		mutex_enter(&nce->nce_lock);
19604 		switch (nce->nce_state) {
19605 		case ND_REACHABLE:
19606 		case ND_STALE:
19607 			/*
19608 			 * ND_REACHABLE is identical to ND_STALE in this
19609 			 * specific case. If reachable time has expired for
19610 			 * this neighbor (delta is greater than reachable
19611 			 * time), conceptually, the neighbor cache is no
19612 			 * longer in REACHABLE state, but already in STALE
19613 			 * state.  So the correct transition here is to
19614 			 * ND_DELAY.
19615 			 */
19616 			nce->nce_state = ND_DELAY;
19617 			mutex_exit(&nce->nce_lock);
19618 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
19619 			if (ip_debug > 3) {
19620 				/* ip2dbg */
19621 				pr_addr_dbg("tcp_multisend_data: state "
19622 				    "for %s changed to DELAY\n",
19623 				    AF_INET6, &ire->ire_addr_v6);
19624 			}
19625 			break;
19626 		case ND_DELAY:
19627 		case ND_PROBE:
19628 			mutex_exit(&nce->nce_lock);
19629 			/* Timers have already started */
19630 			break;
19631 		case ND_UNREACHABLE:
19632 			/*
19633 			 * ndp timer has detected that this nce is
19634 			 * unreachable and initiated deleting this nce
19635 			 * and all its associated IREs. This is a race
19636 			 * where we found the ire before it was deleted
19637 			 * and have just sent out a packet using this
19638 			 * unreachable nce.
19639 			 */
19640 			mutex_exit(&nce->nce_lock);
19641 			break;
19642 		default:
19643 			ASSERT(0);
19644 		}
19645 	}
19646 }
19647 
19648 /*
19649  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
19650  * scheme, and returns one of the following:
19651  *
19652  * -1 = failed allocation.
19653  *  0 = success; burst count reached, or usable send window is too small,
19654  *      and that we'd rather wait until later before sending again.
19655  *  1 = success; we are called from tcp_multisend(), and both usable send
19656  *      window and tail_unsent are greater than the MDT threshold, and thus
19657  *      Multidata Transmit should be used instead.
19658  */
19659 static int
19660 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19661     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19662     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19663     const int mdt_thres)
19664 {
19665 	int num_burst_seg = tcp->tcp_snd_burst;
19666 
19667 	for (;;) {
19668 		struct datab	*db;
19669 		tcph_t		*tcph;
19670 		uint32_t	sum;
19671 		mblk_t		*mp, *mp1;
19672 		uchar_t		*rptr;
19673 		int		len;
19674 
19675 		/*
19676 		 * If we're called by tcp_multisend(), and the amount of
19677 		 * sendable data as well as the size of current xmit_tail
19678 		 * is beyond the MDT threshold, return to the caller and
19679 		 * let the large data transmit be done using MDT.
19680 		 */
19681 		if (*usable > 0 && *usable > mdt_thres &&
19682 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
19683 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
19684 			ASSERT(tcp->tcp_mdt);
19685 			return (1);	/* success; do large send */
19686 		}
19687 
19688 		if (num_burst_seg-- == 0)
19689 			break;		/* success; burst count reached */
19690 
19691 		len = mss;
19692 		if (len > *usable) {
19693 			len = *usable;
19694 			if (len <= 0) {
19695 				/* Terminate the loop */
19696 				break;	/* success; too small */
19697 			}
19698 			/*
19699 			 * Sender silly-window avoidance.
19700 			 * Ignore this if we are going to send a
19701 			 * zero window probe out.
19702 			 *
19703 			 * TODO: force data into microscopic window?
19704 			 *	==> (!pushed || (unsent > usable))
19705 			 */
19706 			if (len < (tcp->tcp_max_swnd >> 1) &&
19707 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
19708 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
19709 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
19710 				/*
19711 				 * If the retransmit timer is not running
19712 				 * we start it so that we will retransmit
19713 				 * in the case when the the receiver has
19714 				 * decremented the window.
19715 				 */
19716 				if (*snxt == tcp->tcp_snxt &&
19717 				    *snxt == tcp->tcp_suna) {
19718 					/*
19719 					 * We are not supposed to send
19720 					 * anything.  So let's wait a little
19721 					 * bit longer before breaking SWS
19722 					 * avoidance.
19723 					 *
19724 					 * What should the value be?
19725 					 * Suggestion: MAX(init rexmit time,
19726 					 * tcp->tcp_rto)
19727 					 */
19728 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19729 				}
19730 				break;	/* success; too small */
19731 			}
19732 		}
19733 
19734 		tcph = tcp->tcp_tcph;
19735 
19736 		*usable -= len; /* Approximate - can be adjusted later */
19737 		if (*usable > 0)
19738 			tcph->th_flags[0] = TH_ACK;
19739 		else
19740 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
19741 
19742 		/*
19743 		 * Prime pump for IP's checksumming on our behalf
19744 		 * Include the adjustment for a source route if any.
19745 		 */
19746 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19747 		sum = (sum >> 16) + (sum & 0xFFFF);
19748 		U16_TO_ABE16(sum, tcph->th_sum);
19749 
19750 		U32_TO_ABE32(*snxt, tcph->th_seq);
19751 
19752 		/*
19753 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
19754 		 * set.  For the case when TCP_FSS_VALID is the only valid
19755 		 * bit (normal active close), branch off only when we think
19756 		 * that the FIN flag needs to be set.  Note for this case,
19757 		 * that (snxt + len) may not reflect the actual seg_len,
19758 		 * as len may be further reduced in tcp_xmit_mp().  If len
19759 		 * gets modified, we will end up here again.
19760 		 */
19761 		if (tcp->tcp_valid_bits != 0 &&
19762 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
19763 		    ((*snxt + len) == tcp->tcp_fss))) {
19764 			uchar_t		*prev_rptr;
19765 			uint32_t	prev_snxt = tcp->tcp_snxt;
19766 
19767 			if (*tail_unsent == 0) {
19768 				ASSERT((*xmit_tail)->b_cont != NULL);
19769 				*xmit_tail = (*xmit_tail)->b_cont;
19770 				prev_rptr = (*xmit_tail)->b_rptr;
19771 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
19772 				    (*xmit_tail)->b_rptr);
19773 			} else {
19774 				prev_rptr = (*xmit_tail)->b_rptr;
19775 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
19776 				    *tail_unsent;
19777 			}
19778 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
19779 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
19780 			/* Restore tcp_snxt so we get amount sent right. */
19781 			tcp->tcp_snxt = prev_snxt;
19782 			if (prev_rptr == (*xmit_tail)->b_rptr) {
19783 				/*
19784 				 * If the previous timestamp is still in use,
19785 				 * don't stomp on it.
19786 				 */
19787 				if ((*xmit_tail)->b_next == NULL) {
19788 					(*xmit_tail)->b_prev = local_time;
19789 					(*xmit_tail)->b_next =
19790 					    (mblk_t *)(uintptr_t)(*snxt);
19791 				}
19792 			} else
19793 				(*xmit_tail)->b_rptr = prev_rptr;
19794 
19795 			if (mp == NULL)
19796 				return (-1);
19797 			mp1 = mp->b_cont;
19798 
19799 			tcp->tcp_last_sent_len = (ushort_t)len;
19800 			while (mp1->b_cont) {
19801 				*xmit_tail = (*xmit_tail)->b_cont;
19802 				(*xmit_tail)->b_prev = local_time;
19803 				(*xmit_tail)->b_next =
19804 				    (mblk_t *)(uintptr_t)(*snxt);
19805 				mp1 = mp1->b_cont;
19806 			}
19807 			*snxt += len;
19808 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
19809 			BUMP_LOCAL(tcp->tcp_obsegs);
19810 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
19811 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
19812 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
19813 			tcp_send_data(tcp, q, mp);
19814 			continue;
19815 		}
19816 
19817 		*snxt += len;	/* Adjust later if we don't send all of len */
19818 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
19819 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
19820 
19821 		if (*tail_unsent) {
19822 			/* Are the bytes above us in flight? */
19823 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
19824 			if (rptr != (*xmit_tail)->b_rptr) {
19825 				*tail_unsent -= len;
19826 				tcp->tcp_last_sent_len = (ushort_t)len;
19827 				len += tcp_hdr_len;
19828 				if (tcp->tcp_ipversion == IPV4_VERSION)
19829 					tcp->tcp_ipha->ipha_length = htons(len);
19830 				else
19831 					tcp->tcp_ip6h->ip6_plen =
19832 					    htons(len -
19833 					    ((char *)&tcp->tcp_ip6h[1] -
19834 					    tcp->tcp_iphc));
19835 				mp = dupb(*xmit_tail);
19836 				if (!mp)
19837 					return (-1);	/* out_of_mem */
19838 				mp->b_rptr = rptr;
19839 				/*
19840 				 * If the old timestamp is no longer in use,
19841 				 * sample a new timestamp now.
19842 				 */
19843 				if ((*xmit_tail)->b_next == NULL) {
19844 					(*xmit_tail)->b_prev = local_time;
19845 					(*xmit_tail)->b_next =
19846 					    (mblk_t *)(uintptr_t)(*snxt-len);
19847 				}
19848 				goto must_alloc;
19849 			}
19850 		} else {
19851 			*xmit_tail = (*xmit_tail)->b_cont;
19852 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
19853 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
19854 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
19855 			    (*xmit_tail)->b_rptr);
19856 		}
19857 
19858 		(*xmit_tail)->b_prev = local_time;
19859 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
19860 
19861 		*tail_unsent -= len;
19862 		tcp->tcp_last_sent_len = (ushort_t)len;
19863 
19864 		len += tcp_hdr_len;
19865 		if (tcp->tcp_ipversion == IPV4_VERSION)
19866 			tcp->tcp_ipha->ipha_length = htons(len);
19867 		else
19868 			tcp->tcp_ip6h->ip6_plen = htons(len -
19869 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
19870 
19871 		mp = dupb(*xmit_tail);
19872 		if (!mp)
19873 			return (-1);	/* out_of_mem */
19874 
19875 		len = tcp_hdr_len;
19876 		/*
19877 		 * There are four reasons to allocate a new hdr mblk:
19878 		 *  1) The bytes above us are in use by another packet
19879 		 *  2) We don't have good alignment
19880 		 *  3) The mblk is being shared
19881 		 *  4) We don't have enough room for a header
19882 		 */
19883 		rptr = mp->b_rptr - len;
19884 		if (!OK_32PTR(rptr) ||
19885 		    ((db = mp->b_datap), db->db_ref != 2) ||
19886 		    rptr < db->db_base) {
19887 			/* NOTE: we assume allocb returns an OK_32PTR */
19888 
19889 		must_alloc:;
19890 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
19891 			    tcp_wroff_xtra, BPRI_MED);
19892 			if (!mp1) {
19893 				freemsg(mp);
19894 				return (-1);	/* out_of_mem */
19895 			}
19896 			mp1->b_cont = mp;
19897 			mp = mp1;
19898 			/* Leave room for Link Level header */
19899 			len = tcp_hdr_len;
19900 			rptr = &mp->b_rptr[tcp_wroff_xtra];
19901 			mp->b_wptr = &rptr[len];
19902 		}
19903 
19904 		/*
19905 		 * Fill in the header using the template header, and add
19906 		 * options such as time-stamp, ECN and/or SACK, as needed.
19907 		 */
19908 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
19909 
19910 		mp->b_rptr = rptr;
19911 
19912 		if (*tail_unsent) {
19913 			int spill = *tail_unsent;
19914 
19915 			mp1 = mp->b_cont;
19916 			if (!mp1)
19917 				mp1 = mp;
19918 
19919 			/*
19920 			 * If we're a little short, tack on more mblks until
19921 			 * there is no more spillover.
19922 			 */
19923 			while (spill < 0) {
19924 				mblk_t *nmp;
19925 				int nmpsz;
19926 
19927 				nmp = (*xmit_tail)->b_cont;
19928 				nmpsz = MBLKL(nmp);
19929 
19930 				/*
19931 				 * Excess data in mblk; can we split it?
19932 				 * If MDT is enabled for the connection,
19933 				 * keep on splitting as this is a transient
19934 				 * send path.
19935 				 */
19936 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
19937 					/*
19938 					 * Don't split if stream head was
19939 					 * told to break up larger writes
19940 					 * into smaller ones.
19941 					 */
19942 					if (tcp->tcp_maxpsz > 0)
19943 						break;
19944 
19945 					/*
19946 					 * Next mblk is less than SMSS/2
19947 					 * rounded up to nearest 64-byte;
19948 					 * let it get sent as part of the
19949 					 * next segment.
19950 					 */
19951 					if (tcp->tcp_localnet &&
19952 					    !tcp->tcp_cork &&
19953 					    (nmpsz < roundup((mss >> 1), 64)))
19954 						break;
19955 				}
19956 
19957 				*xmit_tail = nmp;
19958 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
19959 				/* Stash for rtt use later */
19960 				(*xmit_tail)->b_prev = local_time;
19961 				(*xmit_tail)->b_next =
19962 				    (mblk_t *)(uintptr_t)(*snxt - len);
19963 				mp1->b_cont = dupb(*xmit_tail);
19964 				mp1 = mp1->b_cont;
19965 
19966 				spill += nmpsz;
19967 				if (mp1 == NULL) {
19968 					*tail_unsent = spill;
19969 					freemsg(mp);
19970 					return (-1);	/* out_of_mem */
19971 				}
19972 			}
19973 
19974 			/* Trim back any surplus on the last mblk */
19975 			if (spill >= 0) {
19976 				mp1->b_wptr -= spill;
19977 				*tail_unsent = spill;
19978 			} else {
19979 				/*
19980 				 * We did not send everything we could in
19981 				 * order to remain within the b_cont limit.
19982 				 */
19983 				*usable -= spill;
19984 				*snxt += spill;
19985 				tcp->tcp_last_sent_len += spill;
19986 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
19987 				/*
19988 				 * Adjust the checksum
19989 				 */
19990 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19991 				sum += spill;
19992 				sum = (sum >> 16) + (sum & 0xFFFF);
19993 				U16_TO_ABE16(sum, tcph->th_sum);
19994 				if (tcp->tcp_ipversion == IPV4_VERSION) {
19995 					sum = ntohs(
19996 					    ((ipha_t *)rptr)->ipha_length) +
19997 					    spill;
19998 					((ipha_t *)rptr)->ipha_length =
19999 					    htons(sum);
20000 				} else {
20001 					sum = ntohs(
20002 					    ((ip6_t *)rptr)->ip6_plen) +
20003 					    spill;
20004 					((ip6_t *)rptr)->ip6_plen =
20005 					    htons(sum);
20006 				}
20007 				*tail_unsent = 0;
20008 			}
20009 		}
20010 		if (tcp->tcp_ip_forward_progress) {
20011 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20012 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20013 			tcp->tcp_ip_forward_progress = B_FALSE;
20014 		}
20015 
20016 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20017 		tcp_send_data(tcp, q, mp);
20018 		BUMP_LOCAL(tcp->tcp_obsegs);
20019 	}
20020 
20021 	return (0);
20022 }
20023 
20024 /* Unlink and return any mblk that looks like it contains a MDT info */
20025 static mblk_t *
20026 tcp_mdt_info_mp(mblk_t *mp)
20027 {
20028 	mblk_t	*prev_mp;
20029 
20030 	for (;;) {
20031 		prev_mp = mp;
20032 		/* no more to process? */
20033 		if ((mp = mp->b_cont) == NULL)
20034 			break;
20035 
20036 		switch (DB_TYPE(mp)) {
20037 		case M_CTL:
20038 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20039 				continue;
20040 			ASSERT(prev_mp != NULL);
20041 			prev_mp->b_cont = mp->b_cont;
20042 			mp->b_cont = NULL;
20043 			return (mp);
20044 		default:
20045 			break;
20046 		}
20047 	}
20048 	return (mp);
20049 }
20050 
20051 /* MDT info update routine, called when IP notifies us about MDT */
20052 static void
20053 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20054 {
20055 	boolean_t prev_state;
20056 
20057 	/*
20058 	 * IP is telling us to abort MDT on this connection?  We know
20059 	 * this because the capability is only turned off when IP
20060 	 * encounters some pathological cases, e.g. link-layer change
20061 	 * where the new driver doesn't support MDT, or in situation
20062 	 * where MDT usage on the link-layer has been switched off.
20063 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20064 	 * if the link-layer doesn't support MDT, and if it does, it
20065 	 * will indicate that the feature is to be turned on.
20066 	 */
20067 	prev_state = tcp->tcp_mdt;
20068 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20069 	if (!tcp->tcp_mdt && !first) {
20070 		TCP_STAT(tcp_mdt_conn_halted3);
20071 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20072 		    (void *)tcp->tcp_connp));
20073 	}
20074 
20075 	/*
20076 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20077 	 * so disable MDT otherwise.  The checks are done here
20078 	 * and in tcp_wput_data().
20079 	 */
20080 	if (tcp->tcp_mdt &&
20081 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20082 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20083 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20084 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20085 		tcp->tcp_mdt = B_FALSE;
20086 
20087 	if (tcp->tcp_mdt) {
20088 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
20089 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
20090 			    "version (%d), expected version is %d",
20091 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
20092 			tcp->tcp_mdt = B_FALSE;
20093 			return;
20094 		}
20095 
20096 		/*
20097 		 * We need the driver to be able to handle at least three
20098 		 * spans per packet in order for tcp MDT to be utilized.
20099 		 * The first is for the header portion, while the rest are
20100 		 * needed to handle a packet that straddles across two
20101 		 * virtually non-contiguous buffers; a typical tcp packet
20102 		 * therefore consists of only two spans.  Note that we take
20103 		 * a zero as "don't care".
20104 		 */
20105 		if (mdt_capab->ill_mdt_span_limit > 0 &&
20106 		    mdt_capab->ill_mdt_span_limit < 3) {
20107 			tcp->tcp_mdt = B_FALSE;
20108 			return;
20109 		}
20110 
20111 		/* a zero means driver wants default value */
20112 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
20113 		    tcp_mdt_max_pbufs);
20114 		if (tcp->tcp_mdt_max_pld == 0)
20115 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
20116 
20117 		/* ensure 32-bit alignment */
20118 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
20119 		    mdt_capab->ill_mdt_hdr_head), 4);
20120 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
20121 		    mdt_capab->ill_mdt_hdr_tail), 4);
20122 
20123 		if (!first && !prev_state) {
20124 			TCP_STAT(tcp_mdt_conn_resumed2);
20125 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
20126 			    (void *)tcp->tcp_connp));
20127 		}
20128 	}
20129 }
20130 
20131 static void
20132 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
20133 {
20134 	conn_t *connp = tcp->tcp_connp;
20135 
20136 	ASSERT(ire != NULL);
20137 
20138 	/*
20139 	 * We may be in the fastpath here, and although we essentially do
20140 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
20141 	 * we try to keep things as brief as possible.  After all, these
20142 	 * are only best-effort checks, and we do more thorough ones prior
20143 	 * to calling tcp_multisend().
20144 	 */
20145 	if (ip_multidata_outbound && check_mdt &&
20146 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
20147 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
20148 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
20149 	    !(ire->ire_flags & RTF_MULTIRT) &&
20150 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
20151 	    CONN_IS_MD_FASTPATH(connp)) {
20152 		/* Remember the result */
20153 		connp->conn_mdt_ok = B_TRUE;
20154 
20155 		ASSERT(ill->ill_mdt_capab != NULL);
20156 		if (!ill->ill_mdt_capab->ill_mdt_on) {
20157 			/*
20158 			 * If MDT has been previously turned off in the past,
20159 			 * and we currently can do MDT (due to IPQoS policy
20160 			 * removal, etc.) then enable it for this interface.
20161 			 */
20162 			ill->ill_mdt_capab->ill_mdt_on = 1;
20163 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
20164 			    "interface %s\n", (void *)connp, ill->ill_name));
20165 		}
20166 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
20167 	}
20168 
20169 	/*
20170 	 * The goal is to reduce the number of generated tcp segments by
20171 	 * setting the maxpsz multiplier to 0; this will have an affect on
20172 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
20173 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
20174 	 * of outbound segments and incoming ACKs, thus allowing for better
20175 	 * network and system performance.  In contrast the legacy behavior
20176 	 * may result in sending less than SMSS size, because the last mblk
20177 	 * for some packets may have more data than needed to make up SMSS,
20178 	 * and the legacy code refused to "split" it.
20179 	 *
20180 	 * We apply the new behavior on following situations:
20181 	 *
20182 	 *   1) Loopback connections,
20183 	 *   2) Connections in which the remote peer is not on local subnet,
20184 	 *   3) Local subnet connections over the bge interface (see below).
20185 	 *
20186 	 * Ideally, we would like this behavior to apply for interfaces other
20187 	 * than bge.  However, doing so would negatively impact drivers which
20188 	 * perform dynamic mapping and unmapping of DMA resources, which are
20189 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
20190 	 * packet will be generated by tcp).  The bge driver does not suffer
20191 	 * from this, as it copies the mblks into pre-mapped buffers, and
20192 	 * therefore does not require more I/O resources than before.
20193 	 *
20194 	 * Otherwise, this behavior is present on all network interfaces when
20195 	 * the destination endpoint is non-local, since reducing the number
20196 	 * of packets in general is good for the network.
20197 	 *
20198 	 * TODO We need to remove this hard-coded conditional for bge once
20199 	 *	a better "self-tuning" mechanism, or a way to comprehend
20200 	 *	the driver transmit strategy is devised.  Until the solution
20201 	 *	is found and well understood, we live with this hack.
20202 	 */
20203 	if (!tcp_static_maxpsz &&
20204 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
20205 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
20206 		/* override the default value */
20207 		tcp->tcp_maxpsz = 0;
20208 
20209 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
20210 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
20211 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
20212 	}
20213 
20214 	/* set the stream head parameters accordingly */
20215 	(void) tcp_maxpsz_set(tcp, B_TRUE);
20216 }
20217 
20218 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
20219 static void
20220 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
20221 {
20222 	uchar_t	fval = *mp->b_rptr;
20223 	mblk_t	*tail;
20224 	queue_t	*q = tcp->tcp_wq;
20225 
20226 	/* TODO: How should flush interact with urgent data? */
20227 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
20228 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
20229 		/*
20230 		 * Flush only data that has not yet been put on the wire.  If
20231 		 * we flush data that we have already transmitted, life, as we
20232 		 * know it, may come to an end.
20233 		 */
20234 		tail = tcp->tcp_xmit_tail;
20235 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
20236 		tcp->tcp_xmit_tail_unsent = 0;
20237 		tcp->tcp_unsent = 0;
20238 		if (tail->b_wptr != tail->b_rptr)
20239 			tail = tail->b_cont;
20240 		if (tail) {
20241 			mblk_t **excess = &tcp->tcp_xmit_head;
20242 			for (;;) {
20243 				mblk_t *mp1 = *excess;
20244 				if (mp1 == tail)
20245 					break;
20246 				tcp->tcp_xmit_tail = mp1;
20247 				tcp->tcp_xmit_last = mp1;
20248 				excess = &mp1->b_cont;
20249 			}
20250 			*excess = NULL;
20251 			tcp_close_mpp(&tail);
20252 			if (tcp->tcp_snd_zcopy_aware)
20253 				tcp_zcopy_notify(tcp);
20254 		}
20255 		/*
20256 		 * We have no unsent data, so unsent must be less than
20257 		 * tcp_xmit_lowater, so re-enable flow.
20258 		 */
20259 		if (tcp->tcp_flow_stopped) {
20260 			tcp_clrqfull(tcp);
20261 		}
20262 	}
20263 	/*
20264 	 * TODO: you can't just flush these, you have to increase rwnd for one
20265 	 * thing.  For another, how should urgent data interact?
20266 	 */
20267 	if (fval & FLUSHR) {
20268 		*mp->b_rptr = fval & ~FLUSHW;
20269 		/* XXX */
20270 		qreply(q, mp);
20271 		return;
20272 	}
20273 	freemsg(mp);
20274 }
20275 
20276 /*
20277  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
20278  * messages.
20279  */
20280 static void
20281 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
20282 {
20283 	mblk_t	*mp1;
20284 	STRUCT_HANDLE(strbuf, sb);
20285 	uint16_t port;
20286 	queue_t 	*q = tcp->tcp_wq;
20287 	in6_addr_t	v6addr;
20288 	ipaddr_t	v4addr;
20289 	uint32_t	flowinfo = 0;
20290 	int		addrlen;
20291 
20292 	/* Make sure it is one of ours. */
20293 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20294 	case TI_GETMYNAME:
20295 	case TI_GETPEERNAME:
20296 		break;
20297 	default:
20298 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20299 		return;
20300 	}
20301 	switch (mi_copy_state(q, mp, &mp1)) {
20302 	case -1:
20303 		return;
20304 	case MI_COPY_CASE(MI_COPY_IN, 1):
20305 		break;
20306 	case MI_COPY_CASE(MI_COPY_OUT, 1):
20307 		/* Copy out the strbuf. */
20308 		mi_copyout(q, mp);
20309 		return;
20310 	case MI_COPY_CASE(MI_COPY_OUT, 2):
20311 		/* All done. */
20312 		mi_copy_done(q, mp, 0);
20313 		return;
20314 	default:
20315 		mi_copy_done(q, mp, EPROTO);
20316 		return;
20317 	}
20318 	/* Check alignment of the strbuf */
20319 	if (!OK_32PTR(mp1->b_rptr)) {
20320 		mi_copy_done(q, mp, EINVAL);
20321 		return;
20322 	}
20323 
20324 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
20325 	    (void *)mp1->b_rptr);
20326 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
20327 
20328 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
20329 		mi_copy_done(q, mp, EINVAL);
20330 		return;
20331 	}
20332 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20333 	case TI_GETMYNAME:
20334 		if (tcp->tcp_family == AF_INET) {
20335 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20336 				v4addr = tcp->tcp_ipha->ipha_src;
20337 			} else {
20338 				/* can't return an address in this case */
20339 				v4addr = 0;
20340 			}
20341 		} else {
20342 			/* tcp->tcp_family == AF_INET6 */
20343 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20344 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
20345 				    &v6addr);
20346 			} else {
20347 				v6addr = tcp->tcp_ip6h->ip6_src;
20348 			}
20349 		}
20350 		port = tcp->tcp_lport;
20351 		break;
20352 	case TI_GETPEERNAME:
20353 		if (tcp->tcp_family == AF_INET) {
20354 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20355 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
20356 				    v4addr);
20357 			} else {
20358 				/* can't return an address in this case */
20359 				v4addr = 0;
20360 			}
20361 		} else {
20362 			/* tcp->tcp_family == AF_INET6) */
20363 			v6addr = tcp->tcp_remote_v6;
20364 			if (tcp->tcp_ipversion == IPV6_VERSION) {
20365 				/*
20366 				 * No flowinfo if tcp->tcp_ipversion is v4.
20367 				 *
20368 				 * flowinfo was already initialized to zero
20369 				 * where it was declared above, so only
20370 				 * set it if ipversion is v6.
20371 				 */
20372 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
20373 				    ~IPV6_VERS_AND_FLOW_MASK;
20374 			}
20375 		}
20376 		port = tcp->tcp_fport;
20377 		break;
20378 	default:
20379 		mi_copy_done(q, mp, EPROTO);
20380 		return;
20381 	}
20382 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
20383 	if (!mp1)
20384 		return;
20385 
20386 	if (tcp->tcp_family == AF_INET) {
20387 		sin_t *sin;
20388 
20389 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
20390 		sin = (sin_t *)mp1->b_rptr;
20391 		mp1->b_wptr = (uchar_t *)&sin[1];
20392 		*sin = sin_null;
20393 		sin->sin_family = AF_INET;
20394 		sin->sin_addr.s_addr = v4addr;
20395 		sin->sin_port = port;
20396 	} else {
20397 		/* tcp->tcp_family == AF_INET6 */
20398 		sin6_t *sin6;
20399 
20400 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
20401 		sin6 = (sin6_t *)mp1->b_rptr;
20402 		mp1->b_wptr = (uchar_t *)&sin6[1];
20403 		*sin6 = sin6_null;
20404 		sin6->sin6_family = AF_INET6;
20405 		sin6->sin6_flowinfo = flowinfo;
20406 		sin6->sin6_addr = v6addr;
20407 		sin6->sin6_port = port;
20408 	}
20409 	/* Copy out the address */
20410 	mi_copyout(q, mp);
20411 }
20412 
20413 /*
20414  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
20415  * messages.
20416  */
20417 /* ARGSUSED */
20418 static void
20419 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
20420 {
20421 	conn_t 	*connp = (conn_t *)arg;
20422 	tcp_t	*tcp = connp->conn_tcp;
20423 	queue_t	*q = tcp->tcp_wq;
20424 	struct iocblk	*iocp;
20425 
20426 	ASSERT(DB_TYPE(mp) == M_IOCTL);
20427 	/*
20428 	 * Try and ASSERT the minimum possible references on the
20429 	 * conn early enough. Since we are executing on write side,
20430 	 * the connection is obviously not detached and that means
20431 	 * there is a ref each for TCP and IP. Since we are behind
20432 	 * the squeue, the minimum references needed are 3. If the
20433 	 * conn is in classifier hash list, there should be an
20434 	 * extra ref for that (we check both the possibilities).
20435 	 */
20436 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20437 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20438 
20439 	iocp = (struct iocblk *)mp->b_rptr;
20440 	switch (iocp->ioc_cmd) {
20441 	case TCP_IOC_DEFAULT_Q:
20442 		/* Wants to be the default wq. */
20443 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
20444 			iocp->ioc_error = EPERM;
20445 			iocp->ioc_count = 0;
20446 			mp->b_datap->db_type = M_IOCACK;
20447 			qreply(q, mp);
20448 			return;
20449 		}
20450 		tcp_def_q_set(tcp, mp);
20451 		return;
20452 	case _SIOCSOCKFALLBACK:
20453 		/*
20454 		 * Either sockmod is about to be popped and the socket
20455 		 * would now be treated as a plain stream, or a module
20456 		 * is about to be pushed so we could no longer use read-
20457 		 * side synchronous streams for fused loopback tcp.
20458 		 * Drain any queued data and disable direct sockfs
20459 		 * interface from now on.
20460 		 */
20461 		if (!tcp->tcp_issocket) {
20462 			DB_TYPE(mp) = M_IOCNAK;
20463 			iocp->ioc_error = EINVAL;
20464 		} else {
20465 #ifdef	_ILP32
20466 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
20467 #else
20468 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
20469 #endif
20470 			/*
20471 			 * Insert this socket into the acceptor hash.
20472 			 * We might need it for T_CONN_RES message
20473 			 */
20474 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
20475 
20476 			if (tcp->tcp_fused) {
20477 				/*
20478 				 * This is a fused loopback tcp; disable
20479 				 * read-side synchronous streams interface
20480 				 * and drain any queued data.  It is okay
20481 				 * to do this for non-synchronous streams
20482 				 * fused tcp as well.
20483 				 */
20484 				tcp_fuse_disable_pair(tcp, B_FALSE);
20485 			}
20486 			tcp->tcp_issocket = B_FALSE;
20487 			TCP_STAT(tcp_sock_fallback);
20488 
20489 			DB_TYPE(mp) = M_IOCACK;
20490 			iocp->ioc_error = 0;
20491 		}
20492 		iocp->ioc_count = 0;
20493 		iocp->ioc_rval = 0;
20494 		qreply(q, mp);
20495 		return;
20496 	}
20497 	CALL_IP_WPUT(connp, q, mp);
20498 }
20499 
20500 /*
20501  * This routine is called by tcp_wput() to handle all TPI requests.
20502  */
20503 /* ARGSUSED */
20504 static void
20505 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
20506 {
20507 	conn_t 	*connp = (conn_t *)arg;
20508 	tcp_t	*tcp = connp->conn_tcp;
20509 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
20510 	uchar_t *rptr;
20511 	t_scalar_t type;
20512 	int len;
20513 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
20514 
20515 	/*
20516 	 * Try and ASSERT the minimum possible references on the
20517 	 * conn early enough. Since we are executing on write side,
20518 	 * the connection is obviously not detached and that means
20519 	 * there is a ref each for TCP and IP. Since we are behind
20520 	 * the squeue, the minimum references needed are 3. If the
20521 	 * conn is in classifier hash list, there should be an
20522 	 * extra ref for that (we check both the possibilities).
20523 	 */
20524 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20525 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20526 
20527 	rptr = mp->b_rptr;
20528 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
20529 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
20530 		type = ((union T_primitives *)rptr)->type;
20531 		if (type == T_EXDATA_REQ) {
20532 			uint32_t msize = msgdsize(mp->b_cont);
20533 
20534 			len = msize - 1;
20535 			if (len < 0) {
20536 				freemsg(mp);
20537 				return;
20538 			}
20539 			/*
20540 			 * Try to force urgent data out on the wire.
20541 			 * Even if we have unsent data this will
20542 			 * at least send the urgent flag.
20543 			 * XXX does not handle more flag correctly.
20544 			 */
20545 			len += tcp->tcp_unsent;
20546 			len += tcp->tcp_snxt;
20547 			tcp->tcp_urg = len;
20548 			tcp->tcp_valid_bits |= TCP_URG_VALID;
20549 
20550 			/* Bypass tcp protocol for fused tcp loopback */
20551 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
20552 				return;
20553 		} else if (type != T_DATA_REQ) {
20554 			goto non_urgent_data;
20555 		}
20556 		/* TODO: options, flags, ... from user */
20557 		/* Set length to zero for reclamation below */
20558 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
20559 		freeb(mp);
20560 		return;
20561 	} else {
20562 		if (tcp->tcp_debug) {
20563 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20564 			    "tcp_wput_proto, dropping one...");
20565 		}
20566 		freemsg(mp);
20567 		return;
20568 	}
20569 
20570 non_urgent_data:
20571 
20572 	switch ((int)tprim->type) {
20573 	case O_T_BIND_REQ:	/* bind request */
20574 	case T_BIND_REQ:	/* new semantics bind request */
20575 		tcp_bind(tcp, mp);
20576 		break;
20577 	case T_UNBIND_REQ:	/* unbind request */
20578 		tcp_unbind(tcp, mp);
20579 		break;
20580 	case O_T_CONN_RES:	/* old connection response XXX */
20581 	case T_CONN_RES:	/* connection response */
20582 		tcp_accept(tcp, mp);
20583 		break;
20584 	case T_CONN_REQ:	/* connection request */
20585 		tcp_connect(tcp, mp);
20586 		break;
20587 	case T_DISCON_REQ:	/* disconnect request */
20588 		tcp_disconnect(tcp, mp);
20589 		break;
20590 	case T_CAPABILITY_REQ:
20591 		tcp_capability_req(tcp, mp);	/* capability request */
20592 		break;
20593 	case T_INFO_REQ:	/* information request */
20594 		tcp_info_req(tcp, mp);
20595 		break;
20596 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
20597 		/* Only IP is allowed to return meaningful value */
20598 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
20599 		break;
20600 	case T_OPTMGMT_REQ:
20601 		/*
20602 		 * Note:  no support for snmpcom_req() through new
20603 		 * T_OPTMGMT_REQ. See comments in ip.c
20604 		 */
20605 		/* Only IP is allowed to return meaningful value */
20606 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
20607 		break;
20608 
20609 	case T_UNITDATA_REQ:	/* unitdata request */
20610 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
20611 		break;
20612 	case T_ORDREL_REQ:	/* orderly release req */
20613 		freemsg(mp);
20614 
20615 		if (tcp->tcp_fused)
20616 			tcp_unfuse(tcp);
20617 
20618 		if (tcp_xmit_end(tcp) != 0) {
20619 			/*
20620 			 * We were crossing FINs and got a reset from
20621 			 * the other side. Just ignore it.
20622 			 */
20623 			if (tcp->tcp_debug) {
20624 				(void) strlog(TCP_MOD_ID, 0, 1,
20625 				    SL_ERROR|SL_TRACE,
20626 				    "tcp_wput_proto, T_ORDREL_REQ out of "
20627 				    "state %s",
20628 				    tcp_display(tcp, NULL,
20629 				    DISP_ADDR_AND_PORT));
20630 			}
20631 		}
20632 		break;
20633 	case T_ADDR_REQ:
20634 		tcp_addr_req(tcp, mp);
20635 		break;
20636 	default:
20637 		if (tcp->tcp_debug) {
20638 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20639 			    "tcp_wput_proto, bogus TPI msg, type %d",
20640 			    tprim->type);
20641 		}
20642 		/*
20643 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
20644 		 * to recover.
20645 		 */
20646 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
20647 		break;
20648 	}
20649 }
20650 
20651 /*
20652  * The TCP write service routine should never be called...
20653  */
20654 /* ARGSUSED */
20655 static void
20656 tcp_wsrv(queue_t *q)
20657 {
20658 	TCP_STAT(tcp_wsrv_called);
20659 }
20660 
20661 /* Non overlapping byte exchanger */
20662 static void
20663 tcp_xchg(uchar_t *a, uchar_t *b, int len)
20664 {
20665 	uchar_t	uch;
20666 
20667 	while (len-- > 0) {
20668 		uch = a[len];
20669 		a[len] = b[len];
20670 		b[len] = uch;
20671 	}
20672 }
20673 
20674 /*
20675  * Send out a control packet on the tcp connection specified.  This routine
20676  * is typically called where we need a simple ACK or RST generated.
20677  */
20678 static void
20679 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
20680 {
20681 	uchar_t		*rptr;
20682 	tcph_t		*tcph;
20683 	ipha_t		*ipha = NULL;
20684 	ip6_t		*ip6h = NULL;
20685 	uint32_t	sum;
20686 	int		tcp_hdr_len;
20687 	int		tcp_ip_hdr_len;
20688 	mblk_t		*mp;
20689 
20690 	/*
20691 	 * Save sum for use in source route later.
20692 	 */
20693 	ASSERT(tcp != NULL);
20694 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
20695 	tcp_hdr_len = tcp->tcp_hdr_len;
20696 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
20697 
20698 	/* If a text string is passed in with the request, pass it to strlog. */
20699 	if (str != NULL && tcp->tcp_debug) {
20700 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
20701 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
20702 		    str, seq, ack, ctl);
20703 	}
20704 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
20705 	    BPRI_MED);
20706 	if (mp == NULL) {
20707 		return;
20708 	}
20709 	rptr = &mp->b_rptr[tcp_wroff_xtra];
20710 	mp->b_rptr = rptr;
20711 	mp->b_wptr = &rptr[tcp_hdr_len];
20712 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
20713 
20714 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20715 		ipha = (ipha_t *)rptr;
20716 		ipha->ipha_length = htons(tcp_hdr_len);
20717 	} else {
20718 		ip6h = (ip6_t *)rptr;
20719 		ASSERT(tcp != NULL);
20720 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
20721 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20722 	}
20723 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
20724 	tcph->th_flags[0] = (uint8_t)ctl;
20725 	if (ctl & TH_RST) {
20726 		BUMP_MIB(&tcp_mib, tcpOutRsts);
20727 		BUMP_MIB(&tcp_mib, tcpOutControl);
20728 		/*
20729 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
20730 		 */
20731 		if (tcp->tcp_snd_ts_ok &&
20732 		    tcp->tcp_state > TCPS_SYN_SENT) {
20733 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
20734 			*(mp->b_wptr) = TCPOPT_EOL;
20735 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20736 				ipha->ipha_length = htons(tcp_hdr_len -
20737 				    TCPOPT_REAL_TS_LEN);
20738 			} else {
20739 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
20740 				    TCPOPT_REAL_TS_LEN);
20741 			}
20742 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
20743 			sum -= TCPOPT_REAL_TS_LEN;
20744 		}
20745 	}
20746 	if (ctl & TH_ACK) {
20747 		if (tcp->tcp_snd_ts_ok) {
20748 			U32_TO_BE32(lbolt,
20749 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
20750 			U32_TO_BE32(tcp->tcp_ts_recent,
20751 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
20752 		}
20753 
20754 		/* Update the latest receive window size in TCP header. */
20755 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
20756 		    tcph->th_win);
20757 		tcp->tcp_rack = ack;
20758 		tcp->tcp_rack_cnt = 0;
20759 		BUMP_MIB(&tcp_mib, tcpOutAck);
20760 	}
20761 	BUMP_LOCAL(tcp->tcp_obsegs);
20762 	U32_TO_BE32(seq, tcph->th_seq);
20763 	U32_TO_BE32(ack, tcph->th_ack);
20764 	/*
20765 	 * Include the adjustment for a source route if any.
20766 	 */
20767 	sum = (sum >> 16) + (sum & 0xFFFF);
20768 	U16_TO_BE16(sum, tcph->th_sum);
20769 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20770 	tcp_send_data(tcp, tcp->tcp_wq, mp);
20771 }
20772 
20773 /*
20774  * If this routine returns B_TRUE, TCP can generate a RST in response
20775  * to a segment.  If it returns B_FALSE, TCP should not respond.
20776  */
20777 static boolean_t
20778 tcp_send_rst_chk(void)
20779 {
20780 	clock_t	now;
20781 
20782 	/*
20783 	 * TCP needs to protect itself from generating too many RSTs.
20784 	 * This can be a DoS attack by sending us random segments
20785 	 * soliciting RSTs.
20786 	 *
20787 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
20788 	 * in each 1 second interval.  In this way, TCP still generate
20789 	 * RSTs in normal cases but when under attack, the impact is
20790 	 * limited.
20791 	 */
20792 	if (tcp_rst_sent_rate_enabled != 0) {
20793 		now = lbolt;
20794 		/* lbolt can wrap around. */
20795 		if ((tcp_last_rst_intrvl > now) ||
20796 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
20797 			tcp_last_rst_intrvl = now;
20798 			tcp_rst_cnt = 1;
20799 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
20800 			return (B_FALSE);
20801 		}
20802 	}
20803 	return (B_TRUE);
20804 }
20805 
20806 /*
20807  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
20808  */
20809 static void
20810 tcp_ip_ire_mark_advice(tcp_t *tcp)
20811 {
20812 	mblk_t *mp;
20813 	ipic_t *ipic;
20814 
20815 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20816 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
20817 		    &ipic);
20818 	} else {
20819 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
20820 		    &ipic);
20821 	}
20822 	if (mp == NULL)
20823 		return;
20824 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
20825 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
20826 }
20827 
20828 /*
20829  * Return an IP advice ioctl mblk and set ipic to be the pointer
20830  * to the advice structure.
20831  */
20832 static mblk_t *
20833 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
20834 {
20835 	struct iocblk *ioc;
20836 	mblk_t *mp, *mp1;
20837 
20838 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
20839 	if (mp == NULL)
20840 		return (NULL);
20841 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
20842 	*ipic = (ipic_t *)mp->b_rptr;
20843 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
20844 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
20845 
20846 	bcopy(addr, *ipic + 1, addr_len);
20847 
20848 	(*ipic)->ipic_addr_length = addr_len;
20849 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
20850 
20851 	mp1 = mkiocb(IP_IOCTL);
20852 	if (mp1 == NULL) {
20853 		freemsg(mp);
20854 		return (NULL);
20855 	}
20856 	mp1->b_cont = mp;
20857 	ioc = (struct iocblk *)mp1->b_rptr;
20858 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
20859 
20860 	return (mp1);
20861 }
20862 
20863 /*
20864  * Generate a reset based on an inbound packet for which there is no active
20865  * tcp state that we can find.
20866  *
20867  * IPSEC NOTE : Try to send the reply with the same protection as it came
20868  * in.  We still have the ipsec_mp that the packet was attached to. Thus
20869  * the packet will go out at the same level of protection as it came in by
20870  * converting the IPSEC_IN to IPSEC_OUT.
20871  */
20872 static void
20873 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
20874     uint32_t ack, int ctl, uint_t ip_hdr_len)
20875 {
20876 	ipha_t		*ipha = NULL;
20877 	ip6_t		*ip6h = NULL;
20878 	ushort_t	len;
20879 	tcph_t		*tcph;
20880 	int		i;
20881 	mblk_t		*ipsec_mp;
20882 	boolean_t	mctl_present;
20883 	ipic_t		*ipic;
20884 	ipaddr_t	v4addr;
20885 	in6_addr_t	v6addr;
20886 	int		addr_len;
20887 	void		*addr;
20888 	queue_t		*q = tcp_g_q;
20889 	tcp_t		*tcp = Q_TO_TCP(q);
20890 
20891 	if (!tcp_send_rst_chk()) {
20892 		tcp_rst_unsent++;
20893 		freemsg(mp);
20894 		return;
20895 	}
20896 
20897 	if (mp->b_datap->db_type == M_CTL) {
20898 		ipsec_mp = mp;
20899 		mp = mp->b_cont;
20900 		mctl_present = B_TRUE;
20901 	} else {
20902 		ipsec_mp = mp;
20903 		mctl_present = B_FALSE;
20904 	}
20905 
20906 	if (str && q && tcp_dbg) {
20907 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
20908 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
20909 		    "flags 0x%x",
20910 		    str, seq, ack, ctl);
20911 	}
20912 	if (mp->b_datap->db_ref != 1) {
20913 		mblk_t *mp1 = copyb(mp);
20914 		freemsg(mp);
20915 		mp = mp1;
20916 		if (!mp) {
20917 			if (mctl_present)
20918 				freeb(ipsec_mp);
20919 			return;
20920 		} else {
20921 			if (mctl_present) {
20922 				ipsec_mp->b_cont = mp;
20923 			} else {
20924 				ipsec_mp = mp;
20925 			}
20926 		}
20927 	} else if (mp->b_cont) {
20928 		freemsg(mp->b_cont);
20929 		mp->b_cont = NULL;
20930 	}
20931 	/*
20932 	 * We skip reversing source route here.
20933 	 * (for now we replace all IP options with EOL)
20934 	 */
20935 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
20936 		ipha = (ipha_t *)mp->b_rptr;
20937 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
20938 			mp->b_rptr[i] = IPOPT_EOL;
20939 		/*
20940 		 * Make sure that src address isn't flagrantly invalid.
20941 		 * Not all broadcast address checking for the src address
20942 		 * is possible, since we don't know the netmask of the src
20943 		 * addr.  No check for destination address is done, since
20944 		 * IP will not pass up a packet with a broadcast dest
20945 		 * address to TCP.  Similar checks are done below for IPv6.
20946 		 */
20947 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
20948 		    CLASSD(ipha->ipha_src)) {
20949 			freemsg(ipsec_mp);
20950 			BUMP_MIB(&ip_mib, ipInDiscards);
20951 			return;
20952 		}
20953 	} else {
20954 		ip6h = (ip6_t *)mp->b_rptr;
20955 
20956 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
20957 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
20958 			freemsg(ipsec_mp);
20959 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
20960 			return;
20961 		}
20962 
20963 		/* Remove any extension headers assuming partial overlay */
20964 		if (ip_hdr_len > IPV6_HDR_LEN) {
20965 			uint8_t *to;
20966 
20967 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
20968 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
20969 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
20970 			ip_hdr_len = IPV6_HDR_LEN;
20971 			ip6h = (ip6_t *)mp->b_rptr;
20972 			ip6h->ip6_nxt = IPPROTO_TCP;
20973 		}
20974 	}
20975 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
20976 	if (tcph->th_flags[0] & TH_RST) {
20977 		freemsg(ipsec_mp);
20978 		return;
20979 	}
20980 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
20981 	len = ip_hdr_len + sizeof (tcph_t);
20982 	mp->b_wptr = &mp->b_rptr[len];
20983 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
20984 		ipha->ipha_length = htons(len);
20985 		/* Swap addresses */
20986 		v4addr = ipha->ipha_src;
20987 		ipha->ipha_src = ipha->ipha_dst;
20988 		ipha->ipha_dst = v4addr;
20989 		ipha->ipha_ident = 0;
20990 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
20991 		addr_len = IP_ADDR_LEN;
20992 		addr = &v4addr;
20993 	} else {
20994 		/* No ip6i_t in this case */
20995 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
20996 		/* Swap addresses */
20997 		v6addr = ip6h->ip6_src;
20998 		ip6h->ip6_src = ip6h->ip6_dst;
20999 		ip6h->ip6_dst = v6addr;
21000 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21001 		addr_len = IPV6_ADDR_LEN;
21002 		addr = &v6addr;
21003 	}
21004 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21005 	U32_TO_BE32(ack, tcph->th_ack);
21006 	U32_TO_BE32(seq, tcph->th_seq);
21007 	U16_TO_BE16(0, tcph->th_win);
21008 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21009 	tcph->th_flags[0] = (uint8_t)ctl;
21010 	if (ctl & TH_RST) {
21011 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21012 		BUMP_MIB(&tcp_mib, tcpOutControl);
21013 	}
21014 	if (mctl_present) {
21015 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21016 
21017 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21018 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21019 			return;
21020 		}
21021 	}
21022 	/*
21023 	 * NOTE:  one might consider tracing a TCP packet here, but
21024 	 * this function has no active TCP state nd no tcp structure
21025 	 * which has trace buffer.  If we traced here, we would have
21026 	 * to keep a local trace buffer in tcp_record_trace().
21027 	 */
21028 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21029 
21030 	/*
21031 	 * Tell IP to mark the IRE used for this destination temporary.
21032 	 * This way, we can limit our exposure to DoS attack because IP
21033 	 * creates an IRE for each destination.  If there are too many,
21034 	 * the time to do any routing lookup will be extremely long.  And
21035 	 * the lookup can be in interrupt context.
21036 	 *
21037 	 * Note that in normal circumstances, this marking should not
21038 	 * affect anything.  It would be nice if only 1 message is
21039 	 * needed to inform IP that the IRE created for this RST should
21040 	 * not be added to the cache table.  But there is currently
21041 	 * not such communication mechanism between TCP and IP.  So
21042 	 * the best we can do now is to send the advice ioctl to IP
21043 	 * to mark the IRE temporary.
21044 	 */
21045 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21046 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21047 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21048 	}
21049 }
21050 
21051 /*
21052  * Initiate closedown sequence on an active connection.  (May be called as
21053  * writer.)  Return value zero for OK return, non-zero for error return.
21054  */
21055 static int
21056 tcp_xmit_end(tcp_t *tcp)
21057 {
21058 	ipic_t	*ipic;
21059 	mblk_t	*mp;
21060 
21061 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21062 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21063 		/*
21064 		 * Invalid state, only states TCPS_SYN_RCVD,
21065 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21066 		 */
21067 		return (-1);
21068 	}
21069 
21070 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21071 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21072 	/*
21073 	 * If there is nothing more unsent, send the FIN now.
21074 	 * Otherwise, it will go out with the last segment.
21075 	 */
21076 	if (tcp->tcp_unsent == 0) {
21077 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21078 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21079 
21080 		if (mp) {
21081 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21082 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21083 		} else {
21084 			/*
21085 			 * Couldn't allocate msg.  Pretend we got it out.
21086 			 * Wait for rexmit timeout.
21087 			 */
21088 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21089 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21090 		}
21091 
21092 		/*
21093 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21094 		 * changed.
21095 		 */
21096 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21097 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21098 		}
21099 	} else {
21100 		/*
21101 		 * If tcp->tcp_cork is set, then the data will not get sent,
21102 		 * so we have to check that and unset it first.
21103 		 */
21104 		if (tcp->tcp_cork)
21105 			tcp->tcp_cork = B_FALSE;
21106 		tcp_wput_data(tcp, NULL, B_FALSE);
21107 	}
21108 
21109 	/*
21110 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
21111 	 * is 0, don't update the cache.
21112 	 */
21113 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
21114 		return (0);
21115 
21116 	/*
21117 	 * NOTE: should not update if source routes i.e. if tcp_remote if
21118 	 * different from the destination.
21119 	 */
21120 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21121 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
21122 			return (0);
21123 		}
21124 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21125 		    &ipic);
21126 	} else {
21127 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
21128 		    &tcp->tcp_ip6h->ip6_dst))) {
21129 			return (0);
21130 		}
21131 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21132 		    &ipic);
21133 	}
21134 
21135 	/* Record route attributes in the IRE for use by future connections. */
21136 	if (mp == NULL)
21137 		return (0);
21138 
21139 	/*
21140 	 * We do not have a good algorithm to update ssthresh at this time.
21141 	 * So don't do any update.
21142 	 */
21143 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
21144 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
21145 
21146 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21147 	return (0);
21148 }
21149 
21150 /*
21151  * Generate a "no listener here" RST in response to an "unknown" segment.
21152  * Note that we are reusing the incoming mp to construct the outgoing
21153  * RST.
21154  */
21155 void
21156 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len)
21157 {
21158 	uchar_t		*rptr;
21159 	uint32_t	seg_len;
21160 	tcph_t		*tcph;
21161 	uint32_t	seg_seq;
21162 	uint32_t	seg_ack;
21163 	uint_t		flags;
21164 	mblk_t		*ipsec_mp;
21165 	ipha_t 		*ipha;
21166 	ip6_t 		*ip6h;
21167 	boolean_t	mctl_present = B_FALSE;
21168 	boolean_t	check = B_TRUE;
21169 	boolean_t	policy_present;
21170 
21171 	TCP_STAT(tcp_no_listener);
21172 
21173 	ipsec_mp = mp;
21174 
21175 	if (mp->b_datap->db_type == M_CTL) {
21176 		ipsec_in_t *ii;
21177 
21178 		mctl_present = B_TRUE;
21179 		mp = mp->b_cont;
21180 
21181 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21182 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21183 		if (ii->ipsec_in_dont_check) {
21184 			check = B_FALSE;
21185 			if (!ii->ipsec_in_secure) {
21186 				freeb(ipsec_mp);
21187 				mctl_present = B_FALSE;
21188 				ipsec_mp = mp;
21189 			}
21190 		}
21191 	}
21192 
21193 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21194 		policy_present = ipsec_inbound_v4_policy_present;
21195 		ipha = (ipha_t *)mp->b_rptr;
21196 		ip6h = NULL;
21197 	} else {
21198 		policy_present = ipsec_inbound_v6_policy_present;
21199 		ipha = NULL;
21200 		ip6h = (ip6_t *)mp->b_rptr;
21201 	}
21202 
21203 	if (check && policy_present) {
21204 		/*
21205 		 * The conn_t parameter is NULL because we already know
21206 		 * nobody's home.
21207 		 */
21208 		ipsec_mp = ipsec_check_global_policy(
21209 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
21210 		if (ipsec_mp == NULL)
21211 			return;
21212 	}
21213 
21214 
21215 	rptr = mp->b_rptr;
21216 
21217 	tcph = (tcph_t *)&rptr[ip_hdr_len];
21218 	seg_seq = BE32_TO_U32(tcph->th_seq);
21219 	seg_ack = BE32_TO_U32(tcph->th_ack);
21220 	flags = tcph->th_flags[0];
21221 
21222 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
21223 	if (flags & TH_RST) {
21224 		freemsg(ipsec_mp);
21225 	} else if (flags & TH_ACK) {
21226 		tcp_xmit_early_reset("no tcp, reset",
21227 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len);
21228 	} else {
21229 		if (flags & TH_SYN) {
21230 			seg_len++;
21231 		} else {
21232 			/*
21233 			 * Here we violate the RFC.  Note that a normal
21234 			 * TCP will never send a segment without the ACK
21235 			 * flag, except for RST or SYN segment.  This
21236 			 * segment is neither.  Just drop it on the
21237 			 * floor.
21238 			 */
21239 			freemsg(ipsec_mp);
21240 			tcp_rst_unsent++;
21241 			return;
21242 		}
21243 
21244 		tcp_xmit_early_reset("no tcp, reset/ack",
21245 		    ipsec_mp, 0, seg_seq + seg_len,
21246 		    TH_RST | TH_ACK, ip_hdr_len);
21247 	}
21248 }
21249 
21250 /*
21251  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
21252  * ip and tcp header ready to pass down to IP.  If the mp passed in is
21253  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
21254  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
21255  * otherwise it will dup partial mblks.)
21256  * Otherwise, an appropriate ACK packet will be generated.  This
21257  * routine is not usually called to send new data for the first time.  It
21258  * is mostly called out of the timer for retransmits, and to generate ACKs.
21259  *
21260  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
21261  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
21262  * of the original mblk chain will be returned in *offset and *end_mp.
21263  */
21264 static mblk_t *
21265 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
21266     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
21267     boolean_t rexmit)
21268 {
21269 	int	data_length;
21270 	int32_t	off = 0;
21271 	uint_t	flags;
21272 	mblk_t	*mp1;
21273 	mblk_t	*mp2;
21274 	uchar_t	*rptr;
21275 	tcph_t	*tcph;
21276 	int32_t	num_sack_blk = 0;
21277 	int32_t	sack_opt_len = 0;
21278 
21279 	/* Allocate for our maximum TCP header + link-level */
21280 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21281 	    BPRI_MED);
21282 	if (!mp1)
21283 		return (NULL);
21284 	data_length = 0;
21285 
21286 	/*
21287 	 * Note that tcp_mss has been adjusted to take into account the
21288 	 * timestamp option if applicable.  Because SACK options do not
21289 	 * appear in every TCP segments and they are of variable lengths,
21290 	 * they cannot be included in tcp_mss.  Thus we need to calculate
21291 	 * the actual segment length when we need to send a segment which
21292 	 * includes SACK options.
21293 	 */
21294 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21295 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21296 		    tcp->tcp_num_sack_blk);
21297 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21298 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21299 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
21300 			max_to_send -= sack_opt_len;
21301 	}
21302 
21303 	if (offset != NULL) {
21304 		off = *offset;
21305 		/* We use offset as an indicator that end_mp is not NULL. */
21306 		*end_mp = NULL;
21307 	}
21308 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
21309 		/* This could be faster with cooperation from downstream */
21310 		if (mp2 != mp1 && !sendall &&
21311 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
21312 		    max_to_send)
21313 			/*
21314 			 * Don't send the next mblk since the whole mblk
21315 			 * does not fit.
21316 			 */
21317 			break;
21318 		mp2->b_cont = dupb(mp);
21319 		mp2 = mp2->b_cont;
21320 		if (!mp2) {
21321 			freemsg(mp1);
21322 			return (NULL);
21323 		}
21324 		mp2->b_rptr += off;
21325 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
21326 		    (uintptr_t)INT_MAX);
21327 
21328 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
21329 		if (data_length > max_to_send) {
21330 			mp2->b_wptr -= data_length - max_to_send;
21331 			data_length = max_to_send;
21332 			off = mp2->b_wptr - mp->b_rptr;
21333 			break;
21334 		} else {
21335 			off = 0;
21336 		}
21337 	}
21338 	if (offset != NULL) {
21339 		*offset = off;
21340 		*end_mp = mp;
21341 	}
21342 	if (seg_len != NULL) {
21343 		*seg_len = data_length;
21344 	}
21345 
21346 	/* Update the latest receive window size in TCP header. */
21347 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21348 	    tcp->tcp_tcph->th_win);
21349 
21350 	rptr = mp1->b_rptr + tcp_wroff_xtra;
21351 	mp1->b_rptr = rptr;
21352 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
21353 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21354 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21355 	U32_TO_ABE32(seq, tcph->th_seq);
21356 
21357 	/*
21358 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
21359 	 * that this function was called from tcp_wput_data. Thus, when called
21360 	 * to retransmit data the setting of the PUSH bit may appear some
21361 	 * what random in that it might get set when it should not. This
21362 	 * should not pose any performance issues.
21363 	 */
21364 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
21365 	    tcp->tcp_unsent == data_length)) {
21366 		flags = TH_ACK | TH_PUSH;
21367 	} else {
21368 		flags = TH_ACK;
21369 	}
21370 
21371 	if (tcp->tcp_ecn_ok) {
21372 		if (tcp->tcp_ecn_echo_on)
21373 			flags |= TH_ECE;
21374 
21375 		/*
21376 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
21377 		 * There is no TCP flow control for non-data segments, and
21378 		 * only data segment is transmitted reliably.
21379 		 */
21380 		if (data_length > 0 && !rexmit) {
21381 			SET_ECT(tcp, rptr);
21382 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
21383 				flags |= TH_CWR;
21384 				tcp->tcp_ecn_cwr_sent = B_TRUE;
21385 			}
21386 		}
21387 	}
21388 
21389 	if (tcp->tcp_valid_bits) {
21390 		uint32_t u1;
21391 
21392 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
21393 		    seq == tcp->tcp_iss) {
21394 			uchar_t	*wptr;
21395 
21396 			/*
21397 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
21398 			 * TCP can only be in SYN-SENT, SYN-RCVD or
21399 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
21400 			 * our SYN is not ack'ed but the app closes this
21401 			 * TCP connection.
21402 			 */
21403 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
21404 			    tcp->tcp_state == TCPS_SYN_RCVD ||
21405 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
21406 
21407 			/*
21408 			 * Tack on the MSS option.  It is always needed
21409 			 * for both active and passive open.
21410 			 *
21411 			 * MSS option value should be interface MTU - MIN
21412 			 * TCP/IP header according to RFC 793 as it means
21413 			 * the maximum segment size TCP can receive.  But
21414 			 * to get around some broken middle boxes/end hosts
21415 			 * out there, we allow the option value to be the
21416 			 * same as the MSS option size on the peer side.
21417 			 * In this way, the other side will not send
21418 			 * anything larger than they can receive.
21419 			 *
21420 			 * Note that for SYN_SENT state, the ndd param
21421 			 * tcp_use_smss_as_mss_opt has no effect as we
21422 			 * don't know the peer's MSS option value. So
21423 			 * the only case we need to take care of is in
21424 			 * SYN_RCVD state, which is done later.
21425 			 */
21426 			wptr = mp1->b_wptr;
21427 			wptr[0] = TCPOPT_MAXSEG;
21428 			wptr[1] = TCPOPT_MAXSEG_LEN;
21429 			wptr += 2;
21430 			u1 = tcp->tcp_if_mtu -
21431 			    (tcp->tcp_ipversion == IPV4_VERSION ?
21432 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
21433 			    TCP_MIN_HEADER_LENGTH;
21434 			U16_TO_BE16(u1, wptr);
21435 			mp1->b_wptr = wptr + 2;
21436 			/* Update the offset to cover the additional word */
21437 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
21438 
21439 			/*
21440 			 * Note that the following way of filling in
21441 			 * TCP options are not optimal.  Some NOPs can
21442 			 * be saved.  But there is no need at this time
21443 			 * to optimize it.  When it is needed, we will
21444 			 * do it.
21445 			 */
21446 			switch (tcp->tcp_state) {
21447 			case TCPS_SYN_SENT:
21448 				flags = TH_SYN;
21449 
21450 				if (tcp->tcp_snd_ts_ok) {
21451 					uint32_t llbolt = (uint32_t)lbolt;
21452 
21453 					wptr = mp1->b_wptr;
21454 					wptr[0] = TCPOPT_NOP;
21455 					wptr[1] = TCPOPT_NOP;
21456 					wptr[2] = TCPOPT_TSTAMP;
21457 					wptr[3] = TCPOPT_TSTAMP_LEN;
21458 					wptr += 4;
21459 					U32_TO_BE32(llbolt, wptr);
21460 					wptr += 4;
21461 					ASSERT(tcp->tcp_ts_recent == 0);
21462 					U32_TO_BE32(0L, wptr);
21463 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
21464 					tcph->th_offset_and_rsrvd[0] +=
21465 					    (3 << 4);
21466 				}
21467 
21468 				/*
21469 				 * Set up all the bits to tell other side
21470 				 * we are ECN capable.
21471 				 */
21472 				if (tcp->tcp_ecn_ok) {
21473 					flags |= (TH_ECE | TH_CWR);
21474 				}
21475 				break;
21476 			case TCPS_SYN_RCVD:
21477 				flags |= TH_SYN;
21478 
21479 				/*
21480 				 * Reset the MSS option value to be SMSS
21481 				 * We should probably add back the bytes
21482 				 * for timestamp option and IPsec.  We
21483 				 * don't do that as this is a workaround
21484 				 * for broken middle boxes/end hosts, it
21485 				 * is better for us to be more cautious.
21486 				 * They may not take these things into
21487 				 * account in their SMSS calculation.  Thus
21488 				 * the peer's calculated SMSS may be smaller
21489 				 * than what it can be.  This should be OK.
21490 				 */
21491 				if (tcp_use_smss_as_mss_opt) {
21492 					u1 = tcp->tcp_mss;
21493 					U16_TO_BE16(u1, wptr);
21494 				}
21495 
21496 				/*
21497 				 * If the other side is ECN capable, reply
21498 				 * that we are also ECN capable.
21499 				 */
21500 				if (tcp->tcp_ecn_ok)
21501 					flags |= TH_ECE;
21502 				break;
21503 			default:
21504 				/*
21505 				 * The above ASSERT() makes sure that this
21506 				 * must be FIN-WAIT-1 state.  Our SYN has
21507 				 * not been ack'ed so retransmit it.
21508 				 */
21509 				flags |= TH_SYN;
21510 				break;
21511 			}
21512 
21513 			if (tcp->tcp_snd_ws_ok) {
21514 				wptr = mp1->b_wptr;
21515 				wptr[0] =  TCPOPT_NOP;
21516 				wptr[1] =  TCPOPT_WSCALE;
21517 				wptr[2] =  TCPOPT_WS_LEN;
21518 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
21519 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
21520 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
21521 			}
21522 
21523 			if (tcp->tcp_snd_sack_ok) {
21524 				wptr = mp1->b_wptr;
21525 				wptr[0] = TCPOPT_NOP;
21526 				wptr[1] = TCPOPT_NOP;
21527 				wptr[2] = TCPOPT_SACK_PERMITTED;
21528 				wptr[3] = TCPOPT_SACK_OK_LEN;
21529 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
21530 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
21531 			}
21532 
21533 			/* allocb() of adequate mblk assures space */
21534 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
21535 			    (uintptr_t)INT_MAX);
21536 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
21537 			/*
21538 			 * Get IP set to checksum on our behalf
21539 			 * Include the adjustment for a source route if any.
21540 			 */
21541 			u1 += tcp->tcp_sum;
21542 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
21543 			U16_TO_BE16(u1, tcph->th_sum);
21544 			BUMP_MIB(&tcp_mib, tcpOutControl);
21545 		}
21546 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
21547 		    (seq + data_length) == tcp->tcp_fss) {
21548 			if (!tcp->tcp_fin_acked) {
21549 				flags |= TH_FIN;
21550 				BUMP_MIB(&tcp_mib, tcpOutControl);
21551 			}
21552 			if (!tcp->tcp_fin_sent) {
21553 				tcp->tcp_fin_sent = B_TRUE;
21554 				switch (tcp->tcp_state) {
21555 				case TCPS_SYN_RCVD:
21556 				case TCPS_ESTABLISHED:
21557 					tcp->tcp_state = TCPS_FIN_WAIT_1;
21558 					break;
21559 				case TCPS_CLOSE_WAIT:
21560 					tcp->tcp_state = TCPS_LAST_ACK;
21561 					break;
21562 				}
21563 				if (tcp->tcp_suna == tcp->tcp_snxt)
21564 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21565 				tcp->tcp_snxt = tcp->tcp_fss + 1;
21566 			}
21567 		}
21568 		/*
21569 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
21570 		 * is smaller than seq, u1 will become a very huge value.
21571 		 * So the comparison will fail.  Also note that tcp_urp
21572 		 * should be positive, see RFC 793 page 17.
21573 		 */
21574 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
21575 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
21576 		    u1 < (uint32_t)(64 * 1024)) {
21577 			flags |= TH_URG;
21578 			BUMP_MIB(&tcp_mib, tcpOutUrg);
21579 			U32_TO_ABE16(u1, tcph->th_urp);
21580 		}
21581 	}
21582 	tcph->th_flags[0] = (uchar_t)flags;
21583 	tcp->tcp_rack = tcp->tcp_rnxt;
21584 	tcp->tcp_rack_cnt = 0;
21585 
21586 	if (tcp->tcp_snd_ts_ok) {
21587 		if (tcp->tcp_state != TCPS_SYN_SENT) {
21588 			uint32_t llbolt = (uint32_t)lbolt;
21589 
21590 			U32_TO_BE32(llbolt,
21591 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21592 			U32_TO_BE32(tcp->tcp_ts_recent,
21593 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21594 		}
21595 	}
21596 
21597 	if (num_sack_blk > 0) {
21598 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
21599 		sack_blk_t *tmp;
21600 		int32_t	i;
21601 
21602 		wptr[0] = TCPOPT_NOP;
21603 		wptr[1] = TCPOPT_NOP;
21604 		wptr[2] = TCPOPT_SACK;
21605 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
21606 		    sizeof (sack_blk_t);
21607 		wptr += TCPOPT_REAL_SACK_LEN;
21608 
21609 		tmp = tcp->tcp_sack_list;
21610 		for (i = 0; i < num_sack_blk; i++) {
21611 			U32_TO_BE32(tmp[i].begin, wptr);
21612 			wptr += sizeof (tcp_seq);
21613 			U32_TO_BE32(tmp[i].end, wptr);
21614 			wptr += sizeof (tcp_seq);
21615 		}
21616 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
21617 	}
21618 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21619 	data_length += (int)(mp1->b_wptr - rptr);
21620 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21621 		((ipha_t *)rptr)->ipha_length = htons(data_length);
21622 	} else {
21623 		ip6_t *ip6 = (ip6_t *)(rptr +
21624 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
21625 		    sizeof (ip6i_t) : 0));
21626 
21627 		ip6->ip6_plen = htons(data_length -
21628 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21629 	}
21630 
21631 	/*
21632 	 * Prime pump for IP
21633 	 * Include the adjustment for a source route if any.
21634 	 */
21635 	data_length -= tcp->tcp_ip_hdr_len;
21636 	data_length += tcp->tcp_sum;
21637 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
21638 	U16_TO_ABE16(data_length, tcph->th_sum);
21639 	if (tcp->tcp_ip_forward_progress) {
21640 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21641 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
21642 		tcp->tcp_ip_forward_progress = B_FALSE;
21643 	}
21644 	return (mp1);
21645 }
21646 
21647 /* This function handles the push timeout. */
21648 void
21649 tcp_push_timer(void *arg)
21650 {
21651 	conn_t	*connp = (conn_t *)arg;
21652 	tcp_t *tcp = connp->conn_tcp;
21653 
21654 	TCP_DBGSTAT(tcp_push_timer_cnt);
21655 
21656 	ASSERT(tcp->tcp_listener == NULL);
21657 
21658 	/*
21659 	 * We need to stop synchronous streams temporarily to prevent a race
21660 	 * with tcp_fuse_rrw() or tcp_fusion rinfop().  It is safe to access
21661 	 * tcp_rcv_list here because those entry points will return right
21662 	 * away when synchronous streams is stopped.
21663 	 */
21664 	TCP_FUSE_SYNCSTR_STOP(tcp);
21665 	tcp->tcp_push_tid = 0;
21666 	if ((tcp->tcp_rcv_list != NULL) &&
21667 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
21668 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21669 	TCP_FUSE_SYNCSTR_RESUME(tcp);
21670 }
21671 
21672 /*
21673  * This function handles delayed ACK timeout.
21674  */
21675 static void
21676 tcp_ack_timer(void *arg)
21677 {
21678 	conn_t	*connp = (conn_t *)arg;
21679 	tcp_t *tcp = connp->conn_tcp;
21680 	mblk_t *mp;
21681 
21682 	TCP_DBGSTAT(tcp_ack_timer_cnt);
21683 
21684 	tcp->tcp_ack_tid = 0;
21685 
21686 	if (tcp->tcp_fused)
21687 		return;
21688 
21689 	/*
21690 	 * Do not send ACK if there is no outstanding unack'ed data.
21691 	 */
21692 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
21693 		return;
21694 	}
21695 
21696 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
21697 		/*
21698 		 * Make sure we don't allow deferred ACKs to result in
21699 		 * timer-based ACKing.  If we have held off an ACK
21700 		 * when there was more than an mss here, and the timer
21701 		 * goes off, we have to worry about the possibility
21702 		 * that the sender isn't doing slow-start, or is out
21703 		 * of step with us for some other reason.  We fall
21704 		 * permanently back in the direction of
21705 		 * ACK-every-other-packet as suggested in RFC 1122.
21706 		 */
21707 		if (tcp->tcp_rack_abs_max > 2)
21708 			tcp->tcp_rack_abs_max--;
21709 		tcp->tcp_rack_cur_max = 2;
21710 	}
21711 	mp = tcp_ack_mp(tcp);
21712 
21713 	if (mp != NULL) {
21714 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21715 		BUMP_LOCAL(tcp->tcp_obsegs);
21716 		BUMP_MIB(&tcp_mib, tcpOutAck);
21717 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
21718 		tcp_send_data(tcp, tcp->tcp_wq, mp);
21719 	}
21720 }
21721 
21722 
21723 /* Generate an ACK-only (no data) segment for a TCP endpoint */
21724 static mblk_t *
21725 tcp_ack_mp(tcp_t *tcp)
21726 {
21727 	uint32_t	seq_no;
21728 
21729 	/*
21730 	 * There are a few cases to be considered while setting the sequence no.
21731 	 * Essentially, we can come here while processing an unacceptable pkt
21732 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
21733 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
21734 	 * If we are here for a zero window probe, stick with suna. In all
21735 	 * other cases, we check if suna + swnd encompasses snxt and set
21736 	 * the sequence number to snxt, if so. If snxt falls outside the
21737 	 * window (the receiver probably shrunk its window), we will go with
21738 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
21739 	 * receiver.
21740 	 */
21741 	if (tcp->tcp_zero_win_probe) {
21742 		seq_no = tcp->tcp_suna;
21743 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
21744 		ASSERT(tcp->tcp_swnd == 0);
21745 		seq_no = tcp->tcp_snxt;
21746 	} else {
21747 		seq_no = SEQ_GT(tcp->tcp_snxt,
21748 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
21749 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
21750 	}
21751 
21752 	if (tcp->tcp_valid_bits) {
21753 		/*
21754 		 * For the complex case where we have to send some
21755 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
21756 		 */
21757 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
21758 		    NULL, B_FALSE));
21759 	} else {
21760 		/* Generate a simple ACK */
21761 		int	data_length;
21762 		uchar_t	*rptr;
21763 		tcph_t	*tcph;
21764 		mblk_t	*mp1;
21765 		int32_t	tcp_hdr_len;
21766 		int32_t	tcp_tcp_hdr_len;
21767 		int32_t	num_sack_blk = 0;
21768 		int32_t sack_opt_len;
21769 
21770 		/*
21771 		 * Allocate space for TCP + IP headers
21772 		 * and link-level header
21773 		 */
21774 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21775 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21776 			    tcp->tcp_num_sack_blk);
21777 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21778 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21779 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
21780 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
21781 		} else {
21782 			tcp_hdr_len = tcp->tcp_hdr_len;
21783 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
21784 		}
21785 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
21786 		if (!mp1)
21787 			return (NULL);
21788 
21789 		/* Update the latest receive window size in TCP header. */
21790 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21791 		    tcp->tcp_tcph->th_win);
21792 		/* copy in prototype TCP + IP header */
21793 		rptr = mp1->b_rptr + tcp_wroff_xtra;
21794 		mp1->b_rptr = rptr;
21795 		mp1->b_wptr = rptr + tcp_hdr_len;
21796 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21797 
21798 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21799 
21800 		/* Set the TCP sequence number. */
21801 		U32_TO_ABE32(seq_no, tcph->th_seq);
21802 
21803 		/* Set up the TCP flag field. */
21804 		tcph->th_flags[0] = (uchar_t)TH_ACK;
21805 		if (tcp->tcp_ecn_echo_on)
21806 			tcph->th_flags[0] |= TH_ECE;
21807 
21808 		tcp->tcp_rack = tcp->tcp_rnxt;
21809 		tcp->tcp_rack_cnt = 0;
21810 
21811 		/* fill in timestamp option if in use */
21812 		if (tcp->tcp_snd_ts_ok) {
21813 			uint32_t llbolt = (uint32_t)lbolt;
21814 
21815 			U32_TO_BE32(llbolt,
21816 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21817 			U32_TO_BE32(tcp->tcp_ts_recent,
21818 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21819 		}
21820 
21821 		/* Fill in SACK options */
21822 		if (num_sack_blk > 0) {
21823 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
21824 			sack_blk_t *tmp;
21825 			int32_t	i;
21826 
21827 			wptr[0] = TCPOPT_NOP;
21828 			wptr[1] = TCPOPT_NOP;
21829 			wptr[2] = TCPOPT_SACK;
21830 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
21831 			    sizeof (sack_blk_t);
21832 			wptr += TCPOPT_REAL_SACK_LEN;
21833 
21834 			tmp = tcp->tcp_sack_list;
21835 			for (i = 0; i < num_sack_blk; i++) {
21836 				U32_TO_BE32(tmp[i].begin, wptr);
21837 				wptr += sizeof (tcp_seq);
21838 				U32_TO_BE32(tmp[i].end, wptr);
21839 				wptr += sizeof (tcp_seq);
21840 			}
21841 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
21842 			    << 4);
21843 		}
21844 
21845 		if (tcp->tcp_ipversion == IPV4_VERSION) {
21846 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
21847 		} else {
21848 			/* Check for ip6i_t header in sticky hdrs */
21849 			ip6_t *ip6 = (ip6_t *)(rptr +
21850 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
21851 			    sizeof (ip6i_t) : 0));
21852 
21853 			ip6->ip6_plen = htons(tcp_hdr_len -
21854 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21855 		}
21856 
21857 		/*
21858 		 * Prime pump for checksum calculation in IP.  Include the
21859 		 * adjustment for a source route if any.
21860 		 */
21861 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
21862 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
21863 		U16_TO_ABE16(data_length, tcph->th_sum);
21864 
21865 		if (tcp->tcp_ip_forward_progress) {
21866 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21867 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
21868 			tcp->tcp_ip_forward_progress = B_FALSE;
21869 		}
21870 		return (mp1);
21871 	}
21872 }
21873 
21874 /*
21875  * To create a temporary tcp structure for inserting into bind hash list.
21876  * The parameter is assumed to be in network byte order, ready for use.
21877  */
21878 /* ARGSUSED */
21879 static tcp_t *
21880 tcp_alloc_temp_tcp(in_port_t port)
21881 {
21882 	conn_t	*connp;
21883 	tcp_t	*tcp;
21884 
21885 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
21886 	if (connp == NULL)
21887 		return (NULL);
21888 
21889 	tcp = connp->conn_tcp;
21890 
21891 	/*
21892 	 * Only initialize the necessary info in those structures.  Note
21893 	 * that since INADDR_ANY is all 0, we do not need to set
21894 	 * tcp_bound_source to INADDR_ANY here.
21895 	 */
21896 	tcp->tcp_state = TCPS_BOUND;
21897 	tcp->tcp_lport = port;
21898 	tcp->tcp_exclbind = 1;
21899 	tcp->tcp_reserved_port = 1;
21900 
21901 	/* Just for place holding... */
21902 	tcp->tcp_ipversion = IPV4_VERSION;
21903 
21904 	return (tcp);
21905 }
21906 
21907 /*
21908  * To remove a port range specified by lo_port and hi_port from the
21909  * reserved port ranges.  This is one of the three public functions of
21910  * the reserved port interface.  Note that a port range has to be removed
21911  * as a whole.  Ports in a range cannot be removed individually.
21912  *
21913  * Params:
21914  *	in_port_t lo_port: the beginning port of the reserved port range to
21915  *		be deleted.
21916  *	in_port_t hi_port: the ending port of the reserved port range to
21917  *		be deleted.
21918  *
21919  * Return:
21920  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
21921  */
21922 boolean_t
21923 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
21924 {
21925 	int	i, j;
21926 	int	size;
21927 	tcp_t	**temp_tcp_array;
21928 	tcp_t	*tcp;
21929 
21930 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
21931 
21932 	/* First make sure that the port ranage is indeed reserved. */
21933 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
21934 		if (tcp_reserved_port[i].lo_port == lo_port) {
21935 			hi_port = tcp_reserved_port[i].hi_port;
21936 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
21937 			break;
21938 		}
21939 	}
21940 	if (i == tcp_reserved_port_array_size) {
21941 		rw_exit(&tcp_reserved_port_lock);
21942 		return (B_FALSE);
21943 	}
21944 
21945 	/*
21946 	 * Remove the range from the array.  This simple loop is possible
21947 	 * because port ranges are inserted in ascending order.
21948 	 */
21949 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
21950 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
21951 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
21952 		tcp_reserved_port[j].temp_tcp_array =
21953 		    tcp_reserved_port[j+1].temp_tcp_array;
21954 	}
21955 
21956 	/* Remove all the temporary tcp structures. */
21957 	size = hi_port - lo_port + 1;
21958 	while (size > 0) {
21959 		tcp = temp_tcp_array[size - 1];
21960 		ASSERT(tcp != NULL);
21961 		tcp_bind_hash_remove(tcp);
21962 		CONN_DEC_REF(tcp->tcp_connp);
21963 		size--;
21964 	}
21965 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
21966 	tcp_reserved_port_array_size--;
21967 	rw_exit(&tcp_reserved_port_lock);
21968 	return (B_TRUE);
21969 }
21970 
21971 /*
21972  * Macro to remove temporary tcp structure from the bind hash list.  The
21973  * first parameter is the list of tcp to be removed.  The second parameter
21974  * is the number of tcps in the array.
21975  */
21976 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
21977 { \
21978 	while ((num) > 0) { \
21979 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
21980 		tf_t *tbf; \
21981 		tcp_t *tcpnext; \
21982 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
21983 		mutex_enter(&tbf->tf_lock); \
21984 		tcpnext = tcp->tcp_bind_hash; \
21985 		if (tcpnext) { \
21986 			tcpnext->tcp_ptpbhn = \
21987 				tcp->tcp_ptpbhn; \
21988 		} \
21989 		*tcp->tcp_ptpbhn = tcpnext; \
21990 		mutex_exit(&tbf->tf_lock); \
21991 		kmem_free(tcp, sizeof (tcp_t)); \
21992 		(tcp_array)[(num) - 1] = NULL; \
21993 		(num)--; \
21994 	} \
21995 }
21996 
21997 /*
21998  * The public interface for other modules to call to reserve a port range
21999  * in TCP.  The caller passes in how large a port range it wants.  TCP
22000  * will try to find a range and return it via lo_port and hi_port.  This is
22001  * used by NCA's nca_conn_init.
22002  * NCA can only be used in the global zone so this only affects the global
22003  * zone's ports.
22004  *
22005  * Params:
22006  *	int size: the size of the port range to be reserved.
22007  *	in_port_t *lo_port (referenced): returns the beginning port of the
22008  *		reserved port range added.
22009  *	in_port_t *hi_port (referenced): returns the ending port of the
22010  *		reserved port range added.
22011  *
22012  * Return:
22013  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22014  */
22015 boolean_t
22016 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22017 {
22018 	tcp_t		*tcp;
22019 	tcp_t		*tmp_tcp;
22020 	tcp_t		**temp_tcp_array;
22021 	tf_t		*tbf;
22022 	in_port_t	net_port;
22023 	in_port_t	port;
22024 	int32_t		cur_size;
22025 	int		i, j;
22026 	boolean_t	used;
22027 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22028 	zoneid_t	zoneid = GLOBAL_ZONEID;
22029 
22030 	/* Sanity check. */
22031 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22032 		return (B_FALSE);
22033 	}
22034 
22035 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22036 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22037 		rw_exit(&tcp_reserved_port_lock);
22038 		return (B_FALSE);
22039 	}
22040 
22041 	/*
22042 	 * Find the starting port to try.  Since the port ranges are ordered
22043 	 * in the reserved port array, we can do a simple search here.
22044 	 */
22045 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22046 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22047 	for (i = 0; i < tcp_reserved_port_array_size;
22048 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22049 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22050 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22051 			break;
22052 		}
22053 	}
22054 	/* No available port range. */
22055 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22056 		rw_exit(&tcp_reserved_port_lock);
22057 		return (B_FALSE);
22058 	}
22059 
22060 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22061 	if (temp_tcp_array == NULL) {
22062 		rw_exit(&tcp_reserved_port_lock);
22063 		return (B_FALSE);
22064 	}
22065 
22066 	/* Go thru the port range to see if some ports are already bound. */
22067 	for (port = *lo_port, cur_size = 0;
22068 	    cur_size < size && port <= *hi_port;
22069 	    cur_size++, port++) {
22070 		used = B_FALSE;
22071 		net_port = htons(port);
22072 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22073 		mutex_enter(&tbf->tf_lock);
22074 		for (tcp = tbf->tf_tcp; tcp != NULL;
22075 		    tcp = tcp->tcp_bind_hash) {
22076 			if (zoneid == tcp->tcp_connp->conn_zoneid &&
22077 			    net_port == tcp->tcp_lport) {
22078 				/*
22079 				 * A port is already bound.  Search again
22080 				 * starting from port + 1.  Release all
22081 				 * temporary tcps.
22082 				 */
22083 				mutex_exit(&tbf->tf_lock);
22084 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22085 				*lo_port = port + 1;
22086 				cur_size = -1;
22087 				used = B_TRUE;
22088 				break;
22089 			}
22090 		}
22091 		if (!used) {
22092 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22093 				/*
22094 				 * Allocation failure.  Just fail the request.
22095 				 * Need to remove all those temporary tcp
22096 				 * structures.
22097 				 */
22098 				mutex_exit(&tbf->tf_lock);
22099 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22100 				rw_exit(&tcp_reserved_port_lock);
22101 				kmem_free(temp_tcp_array,
22102 				    (hi_port - lo_port + 1) *
22103 				    sizeof (tcp_t *));
22104 				return (B_FALSE);
22105 			}
22106 			temp_tcp_array[cur_size] = tmp_tcp;
22107 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22108 			mutex_exit(&tbf->tf_lock);
22109 		}
22110 	}
22111 
22112 	/*
22113 	 * The current range is not large enough.  We can actually do another
22114 	 * search if this search is done between 2 reserved port ranges.  But
22115 	 * for first release, we just stop here and return saying that no port
22116 	 * range is available.
22117 	 */
22118 	if (cur_size < size) {
22119 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22120 		rw_exit(&tcp_reserved_port_lock);
22121 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
22122 		return (B_FALSE);
22123 	}
22124 	*hi_port = port - 1;
22125 
22126 	/*
22127 	 * Insert range into array in ascending order.  Since this function
22128 	 * must not be called often, we choose to use the simplest method.
22129 	 * The above array should not consume excessive stack space as
22130 	 * the size must be very small.  If in future releases, we find
22131 	 * that we should provide more reserved port ranges, this function
22132 	 * has to be modified to be more efficient.
22133 	 */
22134 	if (tcp_reserved_port_array_size == 0) {
22135 		tcp_reserved_port[0].lo_port = *lo_port;
22136 		tcp_reserved_port[0].hi_port = *hi_port;
22137 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
22138 	} else {
22139 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
22140 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
22141 				tmp_ports[j].lo_port = *lo_port;
22142 				tmp_ports[j].hi_port = *hi_port;
22143 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
22144 				j++;
22145 			}
22146 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
22147 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
22148 			tmp_ports[j].temp_tcp_array =
22149 			    tcp_reserved_port[i].temp_tcp_array;
22150 		}
22151 		if (j == i) {
22152 			tmp_ports[j].lo_port = *lo_port;
22153 			tmp_ports[j].hi_port = *hi_port;
22154 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
22155 		}
22156 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
22157 	}
22158 	tcp_reserved_port_array_size++;
22159 	rw_exit(&tcp_reserved_port_lock);
22160 	return (B_TRUE);
22161 }
22162 
22163 /*
22164  * Check to see if a port is in any reserved port range.
22165  *
22166  * Params:
22167  *	in_port_t port: the port to be verified.
22168  *
22169  * Return:
22170  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
22171  */
22172 boolean_t
22173 tcp_reserved_port_check(in_port_t port)
22174 {
22175 	int i;
22176 
22177 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22178 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22179 		if (port >= tcp_reserved_port[i].lo_port ||
22180 		    port <= tcp_reserved_port[i].hi_port) {
22181 			rw_exit(&tcp_reserved_port_lock);
22182 			return (B_TRUE);
22183 		}
22184 	}
22185 	rw_exit(&tcp_reserved_port_lock);
22186 	return (B_FALSE);
22187 }
22188 
22189 /*
22190  * To list all reserved port ranges.  This is the function to handle
22191  * ndd tcp_reserved_port_list.
22192  */
22193 /* ARGSUSED */
22194 static int
22195 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22196 {
22197 	int i;
22198 
22199 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22200 	if (tcp_reserved_port_array_size > 0)
22201 		(void) mi_mpprintf(mp, "The following ports are reserved:");
22202 	else
22203 		(void) mi_mpprintf(mp, "No port is reserved.");
22204 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22205 		(void) mi_mpprintf(mp, "%d-%d",
22206 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
22207 	}
22208 	rw_exit(&tcp_reserved_port_lock);
22209 	return (0);
22210 }
22211 
22212 /*
22213  * Hash list insertion routine for tcp_t structures.
22214  * Inserts entries with the ones bound to a specific IP address first
22215  * followed by those bound to INADDR_ANY.
22216  */
22217 static void
22218 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
22219 {
22220 	tcp_t	**tcpp;
22221 	tcp_t	*tcpnext;
22222 
22223 	if (tcp->tcp_ptpbhn != NULL) {
22224 		ASSERT(!caller_holds_lock);
22225 		tcp_bind_hash_remove(tcp);
22226 	}
22227 	tcpp = &tbf->tf_tcp;
22228 	if (!caller_holds_lock) {
22229 		mutex_enter(&tbf->tf_lock);
22230 	} else {
22231 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
22232 	}
22233 	tcpnext = tcpp[0];
22234 	if (tcpnext) {
22235 		/*
22236 		 * If the new tcp bound to the INADDR_ANY address
22237 		 * and the first one in the list is not bound to
22238 		 * INADDR_ANY we skip all entries until we find the
22239 		 * first one bound to INADDR_ANY.
22240 		 * This makes sure that applications binding to a
22241 		 * specific address get preference over those binding to
22242 		 * INADDR_ANY.
22243 		 */
22244 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
22245 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
22246 			while ((tcpnext = tcpp[0]) != NULL &&
22247 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
22248 				tcpp = &(tcpnext->tcp_bind_hash);
22249 			if (tcpnext)
22250 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22251 		} else
22252 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22253 	}
22254 	tcp->tcp_bind_hash = tcpnext;
22255 	tcp->tcp_ptpbhn = tcpp;
22256 	tcpp[0] = tcp;
22257 	if (!caller_holds_lock)
22258 		mutex_exit(&tbf->tf_lock);
22259 }
22260 
22261 /*
22262  * Hash list removal routine for tcp_t structures.
22263  */
22264 static void
22265 tcp_bind_hash_remove(tcp_t *tcp)
22266 {
22267 	tcp_t	*tcpnext;
22268 	kmutex_t *lockp;
22269 
22270 	if (tcp->tcp_ptpbhn == NULL)
22271 		return;
22272 
22273 	/*
22274 	 * Extract the lock pointer in case there are concurrent
22275 	 * hash_remove's for this instance.
22276 	 */
22277 	ASSERT(tcp->tcp_lport != 0);
22278 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
22279 
22280 	ASSERT(lockp != NULL);
22281 	mutex_enter(lockp);
22282 	if (tcp->tcp_ptpbhn) {
22283 		tcpnext = tcp->tcp_bind_hash;
22284 		if (tcpnext) {
22285 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
22286 			tcp->tcp_bind_hash = NULL;
22287 		}
22288 		*tcp->tcp_ptpbhn = tcpnext;
22289 		tcp->tcp_ptpbhn = NULL;
22290 	}
22291 	mutex_exit(lockp);
22292 }
22293 
22294 
22295 /*
22296  * Hash list lookup routine for tcp_t structures.
22297  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
22298  */
22299 static tcp_t *
22300 tcp_acceptor_hash_lookup(t_uscalar_t id)
22301 {
22302 	tf_t	*tf;
22303 	tcp_t	*tcp;
22304 
22305 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22306 	mutex_enter(&tf->tf_lock);
22307 	for (tcp = tf->tf_tcp; tcp != NULL;
22308 	    tcp = tcp->tcp_acceptor_hash) {
22309 		if (tcp->tcp_acceptor_id == id) {
22310 			CONN_INC_REF(tcp->tcp_connp);
22311 			mutex_exit(&tf->tf_lock);
22312 			return (tcp);
22313 		}
22314 	}
22315 	mutex_exit(&tf->tf_lock);
22316 	return (NULL);
22317 }
22318 
22319 
22320 /*
22321  * Hash list insertion routine for tcp_t structures.
22322  */
22323 void
22324 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
22325 {
22326 	tf_t	*tf;
22327 	tcp_t	**tcpp;
22328 	tcp_t	*tcpnext;
22329 
22330 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22331 
22332 	if (tcp->tcp_ptpahn != NULL)
22333 		tcp_acceptor_hash_remove(tcp);
22334 	tcpp = &tf->tf_tcp;
22335 	mutex_enter(&tf->tf_lock);
22336 	tcpnext = tcpp[0];
22337 	if (tcpnext)
22338 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
22339 	tcp->tcp_acceptor_hash = tcpnext;
22340 	tcp->tcp_ptpahn = tcpp;
22341 	tcpp[0] = tcp;
22342 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
22343 	mutex_exit(&tf->tf_lock);
22344 }
22345 
22346 /*
22347  * Hash list removal routine for tcp_t structures.
22348  */
22349 static void
22350 tcp_acceptor_hash_remove(tcp_t *tcp)
22351 {
22352 	tcp_t	*tcpnext;
22353 	kmutex_t *lockp;
22354 
22355 	/*
22356 	 * Extract the lock pointer in case there are concurrent
22357 	 * hash_remove's for this instance.
22358 	 */
22359 	lockp = tcp->tcp_acceptor_lockp;
22360 
22361 	if (tcp->tcp_ptpahn == NULL)
22362 		return;
22363 
22364 	ASSERT(lockp != NULL);
22365 	mutex_enter(lockp);
22366 	if (tcp->tcp_ptpahn) {
22367 		tcpnext = tcp->tcp_acceptor_hash;
22368 		if (tcpnext) {
22369 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
22370 			tcp->tcp_acceptor_hash = NULL;
22371 		}
22372 		*tcp->tcp_ptpahn = tcpnext;
22373 		tcp->tcp_ptpahn = NULL;
22374 	}
22375 	mutex_exit(lockp);
22376 	tcp->tcp_acceptor_lockp = NULL;
22377 }
22378 
22379 /* ARGSUSED */
22380 static int
22381 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
22382 {
22383 	int error = 0;
22384 	int retval;
22385 	char *end;
22386 
22387 	tcp_hsp_t *hsp;
22388 	tcp_hsp_t *hspprev;
22389 
22390 	ipaddr_t addr = 0;		/* Address we're looking for */
22391 	in6_addr_t v6addr;		/* Address we're looking for */
22392 	uint32_t hash;			/* Hash of that address */
22393 
22394 	/*
22395 	 * If the following variables are still zero after parsing the input
22396 	 * string, the user didn't specify them and we don't change them in
22397 	 * the HSP.
22398 	 */
22399 
22400 	ipaddr_t mask = 0;		/* Subnet mask */
22401 	in6_addr_t v6mask;
22402 	long sendspace = 0;		/* Send buffer size */
22403 	long recvspace = 0;		/* Receive buffer size */
22404 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
22405 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
22406 
22407 	rw_enter(&tcp_hsp_lock, RW_WRITER);
22408 
22409 	/* Parse and validate address */
22410 	if (af == AF_INET) {
22411 		retval = inet_pton(af, value, &addr);
22412 		if (retval == 1)
22413 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
22414 	} else if (af == AF_INET6) {
22415 		retval = inet_pton(af, value, &v6addr);
22416 	} else {
22417 		error = EINVAL;
22418 		goto done;
22419 	}
22420 	if (retval == 0) {
22421 		error = EINVAL;
22422 		goto done;
22423 	}
22424 
22425 	while ((*value) && *value != ' ')
22426 		value++;
22427 
22428 	/* Parse individual keywords, set variables if found */
22429 	while (*value) {
22430 		/* Skip leading blanks */
22431 
22432 		while (*value == ' ' || *value == '\t')
22433 			value++;
22434 
22435 		/* If at end of string, we're done */
22436 
22437 		if (!*value)
22438 			break;
22439 
22440 		/* We have a word, figure out what it is */
22441 
22442 		if (strncmp("mask", value, 4) == 0) {
22443 			value += 4;
22444 			while (*value == ' ' || *value == '\t')
22445 				value++;
22446 			/* Parse subnet mask */
22447 			if (af == AF_INET) {
22448 				retval = inet_pton(af, value, &mask);
22449 				if (retval == 1) {
22450 					V4MASK_TO_V6(mask, v6mask);
22451 				}
22452 			} else if (af == AF_INET6) {
22453 				retval = inet_pton(af, value, &v6mask);
22454 			}
22455 			if (retval != 1) {
22456 				error = EINVAL;
22457 				goto done;
22458 			}
22459 			while ((*value) && *value != ' ')
22460 				value++;
22461 		} else if (strncmp("sendspace", value, 9) == 0) {
22462 			value += 9;
22463 
22464 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
22465 			    sendspace < TCP_XMIT_HIWATER ||
22466 			    sendspace >= (1L<<30)) {
22467 				error = EINVAL;
22468 				goto done;
22469 			}
22470 			value = end;
22471 		} else if (strncmp("recvspace", value, 9) == 0) {
22472 			value += 9;
22473 
22474 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
22475 			    recvspace < TCP_RECV_HIWATER ||
22476 			    recvspace >= (1L<<30)) {
22477 				error = EINVAL;
22478 				goto done;
22479 			}
22480 			value = end;
22481 		} else if (strncmp("timestamp", value, 9) == 0) {
22482 			value += 9;
22483 
22484 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
22485 			    timestamp < 0 || timestamp > 1) {
22486 				error = EINVAL;
22487 				goto done;
22488 			}
22489 
22490 			/*
22491 			 * We increment timestamp so we know it's been set;
22492 			 * this is undone when we put it in the HSP
22493 			 */
22494 			timestamp++;
22495 			value = end;
22496 		} else if (strncmp("delete", value, 6) == 0) {
22497 			value += 6;
22498 			delete = B_TRUE;
22499 		} else {
22500 			error = EINVAL;
22501 			goto done;
22502 		}
22503 	}
22504 
22505 	/* Hash address for lookup */
22506 
22507 	hash = TCP_HSP_HASH(addr);
22508 
22509 	if (delete) {
22510 		/*
22511 		 * Note that deletes don't return an error if the thing
22512 		 * we're trying to delete isn't there.
22513 		 */
22514 		if (tcp_hsp_hash == NULL)
22515 			goto done;
22516 		hsp = tcp_hsp_hash[hash];
22517 
22518 		if (hsp) {
22519 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
22520 			    &v6addr)) {
22521 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
22522 				mi_free((char *)hsp);
22523 			} else {
22524 				hspprev = hsp;
22525 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
22526 					if (IN6_ARE_ADDR_EQUAL(
22527 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
22528 						hspprev->tcp_hsp_next =
22529 						    hsp->tcp_hsp_next;
22530 						mi_free((char *)hsp);
22531 						break;
22532 					}
22533 					hspprev = hsp;
22534 				}
22535 			}
22536 		}
22537 	} else {
22538 		/*
22539 		 * We're adding/modifying an HSP.  If we haven't already done
22540 		 * so, allocate the hash table.
22541 		 */
22542 
22543 		if (!tcp_hsp_hash) {
22544 			tcp_hsp_hash = (tcp_hsp_t **)
22545 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
22546 			if (!tcp_hsp_hash) {
22547 				error = EINVAL;
22548 				goto done;
22549 			}
22550 		}
22551 
22552 		/* Get head of hash chain */
22553 
22554 		hsp = tcp_hsp_hash[hash];
22555 
22556 		/* Try to find pre-existing hsp on hash chain */
22557 		/* Doesn't handle CIDR prefixes. */
22558 		while (hsp) {
22559 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
22560 				break;
22561 			hsp = hsp->tcp_hsp_next;
22562 		}
22563 
22564 		/*
22565 		 * If we didn't, create one with default values and put it
22566 		 * at head of hash chain
22567 		 */
22568 
22569 		if (!hsp) {
22570 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
22571 			if (!hsp) {
22572 				error = EINVAL;
22573 				goto done;
22574 			}
22575 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
22576 			tcp_hsp_hash[hash] = hsp;
22577 		}
22578 
22579 		/* Set values that the user asked us to change */
22580 
22581 		hsp->tcp_hsp_addr_v6 = v6addr;
22582 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
22583 			hsp->tcp_hsp_vers = IPV4_VERSION;
22584 		else
22585 			hsp->tcp_hsp_vers = IPV6_VERSION;
22586 		hsp->tcp_hsp_subnet_v6 = v6mask;
22587 		if (sendspace > 0)
22588 			hsp->tcp_hsp_sendspace = sendspace;
22589 		if (recvspace > 0)
22590 			hsp->tcp_hsp_recvspace = recvspace;
22591 		if (timestamp > 0)
22592 			hsp->tcp_hsp_tstamp = timestamp - 1;
22593 	}
22594 
22595 done:
22596 	rw_exit(&tcp_hsp_lock);
22597 	return (error);
22598 }
22599 
22600 /* Set callback routine passed to nd_load by tcp_param_register. */
22601 /* ARGSUSED */
22602 static int
22603 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
22604 {
22605 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
22606 }
22607 /* ARGSUSED */
22608 static int
22609 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22610     cred_t *cr)
22611 {
22612 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
22613 }
22614 
22615 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
22616 /* ARGSUSED */
22617 static int
22618 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22619 {
22620 	tcp_hsp_t *hsp;
22621 	int i;
22622 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
22623 
22624 	rw_enter(&tcp_hsp_lock, RW_READER);
22625 	(void) mi_mpprintf(mp,
22626 	    "Hash HSP     " MI_COL_HDRPAD_STR
22627 	    "Address         Subnet Mask     Send       Receive    TStamp");
22628 	if (tcp_hsp_hash) {
22629 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
22630 			hsp = tcp_hsp_hash[i];
22631 			while (hsp) {
22632 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
22633 					(void) inet_ntop(AF_INET,
22634 					    &hsp->tcp_hsp_addr,
22635 					    addrbuf, sizeof (addrbuf));
22636 					(void) inet_ntop(AF_INET,
22637 					    &hsp->tcp_hsp_subnet,
22638 					    subnetbuf, sizeof (subnetbuf));
22639 				} else {
22640 					(void) inet_ntop(AF_INET6,
22641 					    &hsp->tcp_hsp_addr_v6,
22642 					    addrbuf, sizeof (addrbuf));
22643 					(void) inet_ntop(AF_INET6,
22644 					    &hsp->tcp_hsp_subnet_v6,
22645 					    subnetbuf, sizeof (subnetbuf));
22646 				}
22647 				(void) mi_mpprintf(mp,
22648 				    " %03d " MI_COL_PTRFMT_STR
22649 				    "%s %s %010d %010d      %d",
22650 				    i,
22651 				    (void *)hsp,
22652 				    addrbuf,
22653 				    subnetbuf,
22654 				    hsp->tcp_hsp_sendspace,
22655 				    hsp->tcp_hsp_recvspace,
22656 				    hsp->tcp_hsp_tstamp);
22657 
22658 				hsp = hsp->tcp_hsp_next;
22659 			}
22660 		}
22661 	}
22662 	rw_exit(&tcp_hsp_lock);
22663 	return (0);
22664 }
22665 
22666 
22667 /* Data for fast netmask macro used by tcp_hsp_lookup */
22668 
22669 static ipaddr_t netmasks[] = {
22670 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
22671 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
22672 };
22673 
22674 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
22675 
22676 /*
22677  * XXX This routine should go away and instead we should use the metrics
22678  * associated with the routes to determine the default sndspace and rcvspace.
22679  */
22680 static tcp_hsp_t *
22681 tcp_hsp_lookup(ipaddr_t addr)
22682 {
22683 	tcp_hsp_t *hsp = NULL;
22684 
22685 	/* Quick check without acquiring the lock. */
22686 	if (tcp_hsp_hash == NULL)
22687 		return (NULL);
22688 
22689 	rw_enter(&tcp_hsp_lock, RW_READER);
22690 
22691 	/* This routine finds the best-matching HSP for address addr. */
22692 
22693 	if (tcp_hsp_hash) {
22694 		int i;
22695 		ipaddr_t srchaddr;
22696 		tcp_hsp_t *hsp_net;
22697 
22698 		/* We do three passes: host, network, and subnet. */
22699 
22700 		srchaddr = addr;
22701 
22702 		for (i = 1; i <= 3; i++) {
22703 			/* Look for exact match on srchaddr */
22704 
22705 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
22706 			while (hsp) {
22707 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
22708 				    hsp->tcp_hsp_addr == srchaddr)
22709 					break;
22710 				hsp = hsp->tcp_hsp_next;
22711 			}
22712 			ASSERT(hsp == NULL ||
22713 			    hsp->tcp_hsp_vers == IPV4_VERSION);
22714 
22715 			/*
22716 			 * If this is the first pass:
22717 			 *   If we found a match, great, return it.
22718 			 *   If not, search for the network on the second pass.
22719 			 */
22720 
22721 			if (i == 1)
22722 				if (hsp)
22723 					break;
22724 				else
22725 				{
22726 					srchaddr = addr & netmask(addr);
22727 					continue;
22728 				}
22729 
22730 			/*
22731 			 * If this is the second pass:
22732 			 *   If we found a match, but there's a subnet mask,
22733 			 *    save the match but try again using the subnet
22734 			 *    mask on the third pass.
22735 			 *   Otherwise, return whatever we found.
22736 			 */
22737 
22738 			if (i == 2) {
22739 				if (hsp && hsp->tcp_hsp_subnet) {
22740 					hsp_net = hsp;
22741 					srchaddr = addr & hsp->tcp_hsp_subnet;
22742 					continue;
22743 				} else {
22744 					break;
22745 				}
22746 			}
22747 
22748 			/*
22749 			 * This must be the third pass.  If we didn't find
22750 			 * anything, return the saved network HSP instead.
22751 			 */
22752 
22753 			if (!hsp)
22754 				hsp = hsp_net;
22755 		}
22756 	}
22757 
22758 	rw_exit(&tcp_hsp_lock);
22759 	return (hsp);
22760 }
22761 
22762 /*
22763  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
22764  * match lookup.
22765  */
22766 static tcp_hsp_t *
22767 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
22768 {
22769 	tcp_hsp_t *hsp = NULL;
22770 
22771 	/* Quick check without acquiring the lock. */
22772 	if (tcp_hsp_hash == NULL)
22773 		return (NULL);
22774 
22775 	rw_enter(&tcp_hsp_lock, RW_READER);
22776 
22777 	/* This routine finds the best-matching HSP for address addr. */
22778 
22779 	if (tcp_hsp_hash) {
22780 		int i;
22781 		in6_addr_t v6srchaddr;
22782 		tcp_hsp_t *hsp_net;
22783 
22784 		/* We do three passes: host, network, and subnet. */
22785 
22786 		v6srchaddr = *v6addr;
22787 
22788 		for (i = 1; i <= 3; i++) {
22789 			/* Look for exact match on srchaddr */
22790 
22791 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
22792 			    V4_PART_OF_V6(v6srchaddr))];
22793 			while (hsp) {
22794 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
22795 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
22796 				    &v6srchaddr))
22797 					break;
22798 				hsp = hsp->tcp_hsp_next;
22799 			}
22800 
22801 			/*
22802 			 * If this is the first pass:
22803 			 *   If we found a match, great, return it.
22804 			 *   If not, search for the network on the second pass.
22805 			 */
22806 
22807 			if (i == 1)
22808 				if (hsp)
22809 					break;
22810 				else {
22811 					/* Assume a 64 bit mask */
22812 					v6srchaddr.s6_addr32[0] =
22813 					    v6addr->s6_addr32[0];
22814 					v6srchaddr.s6_addr32[1] =
22815 					    v6addr->s6_addr32[1];
22816 					v6srchaddr.s6_addr32[2] = 0;
22817 					v6srchaddr.s6_addr32[3] = 0;
22818 					continue;
22819 				}
22820 
22821 			/*
22822 			 * If this is the second pass:
22823 			 *   If we found a match, but there's a subnet mask,
22824 			 *    save the match but try again using the subnet
22825 			 *    mask on the third pass.
22826 			 *   Otherwise, return whatever we found.
22827 			 */
22828 
22829 			if (i == 2) {
22830 				ASSERT(hsp == NULL ||
22831 				    hsp->tcp_hsp_vers == IPV6_VERSION);
22832 				if (hsp &&
22833 				    !IN6_IS_ADDR_UNSPECIFIED(
22834 				    &hsp->tcp_hsp_subnet_v6)) {
22835 					hsp_net = hsp;
22836 					V6_MASK_COPY(*v6addr,
22837 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
22838 					continue;
22839 				} else {
22840 					break;
22841 				}
22842 			}
22843 
22844 			/*
22845 			 * This must be the third pass.  If we didn't find
22846 			 * anything, return the saved network HSP instead.
22847 			 */
22848 
22849 			if (!hsp)
22850 				hsp = hsp_net;
22851 		}
22852 	}
22853 
22854 	rw_exit(&tcp_hsp_lock);
22855 	return (hsp);
22856 }
22857 
22858 /*
22859  * Type three generator adapted from the random() function in 4.4 BSD:
22860  */
22861 
22862 /*
22863  * Copyright (c) 1983, 1993
22864  *	The Regents of the University of California.  All rights reserved.
22865  *
22866  * Redistribution and use in source and binary forms, with or without
22867  * modification, are permitted provided that the following conditions
22868  * are met:
22869  * 1. Redistributions of source code must retain the above copyright
22870  *    notice, this list of conditions and the following disclaimer.
22871  * 2. Redistributions in binary form must reproduce the above copyright
22872  *    notice, this list of conditions and the following disclaimer in the
22873  *    documentation and/or other materials provided with the distribution.
22874  * 3. All advertising materials mentioning features or use of this software
22875  *    must display the following acknowledgement:
22876  *	This product includes software developed by the University of
22877  *	California, Berkeley and its contributors.
22878  * 4. Neither the name of the University nor the names of its contributors
22879  *    may be used to endorse or promote products derived from this software
22880  *    without specific prior written permission.
22881  *
22882  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22883  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22884  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22885  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22886  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22887  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22888  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22889  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22890  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22891  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
22892  * SUCH DAMAGE.
22893  */
22894 
22895 /* Type 3 -- x**31 + x**3 + 1 */
22896 #define	DEG_3		31
22897 #define	SEP_3		3
22898 
22899 
22900 /* Protected by tcp_random_lock */
22901 static int tcp_randtbl[DEG_3 + 1];
22902 
22903 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
22904 static int *tcp_random_rptr = &tcp_randtbl[1];
22905 
22906 static int *tcp_random_state = &tcp_randtbl[1];
22907 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
22908 
22909 kmutex_t tcp_random_lock;
22910 
22911 void
22912 tcp_random_init(void)
22913 {
22914 	int i;
22915 	hrtime_t hrt;
22916 	time_t wallclock;
22917 	uint64_t result;
22918 
22919 	/*
22920 	 * Use high-res timer and current time for seed.  Gethrtime() returns
22921 	 * a longlong, which may contain resolution down to nanoseconds.
22922 	 * The current time will either be a 32-bit or a 64-bit quantity.
22923 	 * XOR the two together in a 64-bit result variable.
22924 	 * Convert the result to a 32-bit value by multiplying the high-order
22925 	 * 32-bits by the low-order 32-bits.
22926 	 */
22927 
22928 	hrt = gethrtime();
22929 	(void) drv_getparm(TIME, &wallclock);
22930 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
22931 	mutex_enter(&tcp_random_lock);
22932 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
22933 	    (result & 0xffffffff);
22934 
22935 	for (i = 1; i < DEG_3; i++)
22936 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
22937 			+ 12345;
22938 	tcp_random_fptr = &tcp_random_state[SEP_3];
22939 	tcp_random_rptr = &tcp_random_state[0];
22940 	mutex_exit(&tcp_random_lock);
22941 	for (i = 0; i < 10 * DEG_3; i++)
22942 		(void) tcp_random();
22943 }
22944 
22945 /*
22946  * tcp_random: Return a random number in the range [1 - (128K + 1)].
22947  * This range is selected to be approximately centered on TCP_ISS / 2,
22948  * and easy to compute. We get this value by generating a 32-bit random
22949  * number, selecting out the high-order 17 bits, and then adding one so
22950  * that we never return zero.
22951  */
22952 int
22953 tcp_random(void)
22954 {
22955 	int i;
22956 
22957 	mutex_enter(&tcp_random_lock);
22958 	*tcp_random_fptr += *tcp_random_rptr;
22959 
22960 	/*
22961 	 * The high-order bits are more random than the low-order bits,
22962 	 * so we select out the high-order 17 bits and add one so that
22963 	 * we never return zero.
22964 	 */
22965 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
22966 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
22967 		tcp_random_fptr = tcp_random_state;
22968 		++tcp_random_rptr;
22969 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
22970 		tcp_random_rptr = tcp_random_state;
22971 
22972 	mutex_exit(&tcp_random_lock);
22973 	return (i);
22974 }
22975 
22976 /*
22977  * XXX This will go away when TPI is extended to send
22978  * info reqs to sockfs/timod .....
22979  * Given a queue, set the max packet size for the write
22980  * side of the queue below stream head.  This value is
22981  * cached on the stream head.
22982  * Returns 1 on success, 0 otherwise.
22983  */
22984 static int
22985 setmaxps(queue_t *q, int maxpsz)
22986 {
22987 	struct stdata	*stp;
22988 	queue_t		*wq;
22989 	stp = STREAM(q);
22990 
22991 	/*
22992 	 * At this point change of a queue parameter is not allowed
22993 	 * when a multiplexor is sitting on top.
22994 	 */
22995 	if (stp->sd_flag & STPLEX)
22996 		return (0);
22997 
22998 	claimstr(stp->sd_wrq);
22999 	wq = stp->sd_wrq->q_next;
23000 	ASSERT(wq != NULL);
23001 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23002 	releasestr(stp->sd_wrq);
23003 	return (1);
23004 }
23005 
23006 static int
23007 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23008     int *t_errorp, int *sys_errorp)
23009 {
23010 	int error;
23011 	int is_absreq_failure;
23012 	t_scalar_t *opt_lenp;
23013 	t_scalar_t opt_offset;
23014 	int prim_type;
23015 	struct T_conn_req *tcreqp;
23016 	struct T_conn_res *tcresp;
23017 	cred_t *cr;
23018 
23019 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23020 
23021 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23022 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23023 	    prim_type == T_CONN_RES);
23024 
23025 	switch (prim_type) {
23026 	case T_CONN_REQ:
23027 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23028 		opt_offset = tcreqp->OPT_offset;
23029 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23030 		break;
23031 	case O_T_CONN_RES:
23032 	case T_CONN_RES:
23033 		tcresp = (struct T_conn_res *)mp->b_rptr;
23034 		opt_offset = tcresp->OPT_offset;
23035 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23036 		break;
23037 	}
23038 
23039 	*t_errorp = 0;
23040 	*sys_errorp = 0;
23041 	*do_disconnectp = 0;
23042 
23043 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23044 	    opt_offset, cr, &tcp_opt_obj,
23045 	    NULL, &is_absreq_failure);
23046 
23047 	switch (error) {
23048 	case  0:		/* no error */
23049 		ASSERT(is_absreq_failure == 0);
23050 		return (0);
23051 	case ENOPROTOOPT:
23052 		*t_errorp = TBADOPT;
23053 		break;
23054 	case EACCES:
23055 		*t_errorp = TACCES;
23056 		break;
23057 	default:
23058 		*t_errorp = TSYSERR; *sys_errorp = error;
23059 		break;
23060 	}
23061 	if (is_absreq_failure != 0) {
23062 		/*
23063 		 * The connection request should get the local ack
23064 		 * T_OK_ACK and then a T_DISCON_IND.
23065 		 */
23066 		*do_disconnectp = 1;
23067 	}
23068 	return (-1);
23069 }
23070 
23071 /*
23072  * Split this function out so that if the secret changes, I'm okay.
23073  *
23074  * Initialize the tcp_iss_cookie and tcp_iss_key.
23075  */
23076 
23077 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23078 
23079 static void
23080 tcp_iss_key_init(uint8_t *phrase, int len)
23081 {
23082 	struct {
23083 		int32_t current_time;
23084 		uint32_t randnum;
23085 		uint16_t pad;
23086 		uint8_t ether[6];
23087 		uint8_t passwd[PASSWD_SIZE];
23088 	} tcp_iss_cookie;
23089 	time_t t;
23090 
23091 	/*
23092 	 * Start with the current absolute time.
23093 	 */
23094 	(void) drv_getparm(TIME, &t);
23095 	tcp_iss_cookie.current_time = t;
23096 
23097 	/*
23098 	 * XXX - Need a more random number per RFC 1750, not this crap.
23099 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23100 	 */
23101 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23102 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23103 
23104 	/*
23105 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23106 	 * as a good template.
23107 	 */
23108 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23109 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23110 
23111 	/*
23112 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23113 	 */
23114 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23115 
23116 	/*
23117 	 * See 4010593 if this section becomes a problem again,
23118 	 * but the local ethernet address is useful here.
23119 	 */
23120 	(void) localetheraddr(NULL,
23121 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23122 
23123 	/*
23124 	 * Hash 'em all together.  The MD5Final is called per-connection.
23125 	 */
23126 	mutex_enter(&tcp_iss_key_lock);
23127 	MD5Init(&tcp_iss_key);
23128 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
23129 	    sizeof (tcp_iss_cookie));
23130 	mutex_exit(&tcp_iss_key_lock);
23131 }
23132 
23133 /*
23134  * Set the RFC 1948 pass phrase
23135  */
23136 /* ARGSUSED */
23137 static int
23138 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23139     cred_t *cr)
23140 {
23141 	/*
23142 	 * Basically, value contains a new pass phrase.  Pass it along!
23143 	 */
23144 	tcp_iss_key_init((uint8_t *)value, strlen(value));
23145 	return (0);
23146 }
23147 
23148 /* ARGSUSED */
23149 static int
23150 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23151 {
23152 	bzero(buf, sizeof (tcp_sack_info_t));
23153 	return (0);
23154 }
23155 
23156 /* ARGSUSED */
23157 static int
23158 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23159 {
23160 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23161 	return (0);
23162 }
23163 
23164 void
23165 tcp_ddi_init(void)
23166 {
23167 	int i;
23168 
23169 	/* Initialize locks */
23170 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
23171 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23172 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23173 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23174 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23175 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
23176 
23177 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23178 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
23179 		    MUTEX_DEFAULT, NULL);
23180 	}
23181 
23182 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23183 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
23184 		    MUTEX_DEFAULT, NULL);
23185 	}
23186 
23187 	/* TCP's IPsec code calls the packet dropper. */
23188 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
23189 
23190 	if (!tcp_g_nd) {
23191 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
23192 			nd_free(&tcp_g_nd);
23193 		}
23194 	}
23195 
23196 	/*
23197 	 * Note: To really walk the device tree you need the devinfo
23198 	 * pointer to your device which is only available after probe/attach.
23199 	 * The following is safe only because it uses ddi_root_node()
23200 	 */
23201 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23202 	    tcp_opt_obj.odb_opt_arr_cnt);
23203 
23204 	tcp_timercache = kmem_cache_create("tcp_timercache",
23205 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23206 	    NULL, NULL, NULL, NULL, NULL, 0);
23207 
23208 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23209 	    sizeof (tcp_sack_info_t), 0,
23210 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23211 
23212 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23213 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23214 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23215 
23216 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
23217 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
23218 
23219 	ip_squeue_init(tcp_squeue_add);
23220 
23221 	/* Initialize the random number generator */
23222 	tcp_random_init();
23223 
23224 	/*
23225 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23226 	 * by the boot scripts.
23227 	 *
23228 	 * Use NULL name, as the name is caught by the new lockstats.
23229 	 *
23230 	 * Initialize with some random, non-guessable string, like the global
23231 	 * T_INFO_ACK.
23232 	 */
23233 
23234 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23235 	    sizeof (tcp_g_t_info_ack));
23236 
23237 	if ((tcp_kstat = kstat_create(TCP_MOD_NAME, 0, "tcpstat",
23238 		"net", KSTAT_TYPE_NAMED,
23239 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
23240 		KSTAT_FLAG_VIRTUAL)) != NULL) {
23241 		tcp_kstat->ks_data = &tcp_statistics;
23242 		kstat_install(tcp_kstat);
23243 	}
23244 
23245 	tcp_kstat_init();
23246 }
23247 
23248 void
23249 tcp_ddi_destroy(void)
23250 {
23251 	int i;
23252 
23253 	nd_free(&tcp_g_nd);
23254 
23255 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23256 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
23257 	}
23258 
23259 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23260 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
23261 	}
23262 
23263 	mutex_destroy(&tcp_iss_key_lock);
23264 	rw_destroy(&tcp_hsp_lock);
23265 	mutex_destroy(&tcp_g_q_lock);
23266 	mutex_destroy(&tcp_random_lock);
23267 	mutex_destroy(&tcp_epriv_port_lock);
23268 	rw_destroy(&tcp_reserved_port_lock);
23269 
23270 	ip_drop_unregister(&tcp_dropper);
23271 
23272 	kmem_cache_destroy(tcp_timercache);
23273 	kmem_cache_destroy(tcp_sack_info_cache);
23274 	kmem_cache_destroy(tcp_iphc_cache);
23275 
23276 	tcp_kstat_fini();
23277 }
23278 
23279 /*
23280  * Generate ISS, taking into account NDD changes may happen halfway through.
23281  * (If the iss is not zero, set it.)
23282  */
23283 
23284 static void
23285 tcp_iss_init(tcp_t *tcp)
23286 {
23287 	MD5_CTX context;
23288 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
23289 	uint32_t answer[4];
23290 
23291 	tcp_iss_incr_extra += (ISS_INCR >> 1);
23292 	tcp->tcp_iss = tcp_iss_incr_extra;
23293 	switch (tcp_strong_iss) {
23294 	case 2:
23295 		mutex_enter(&tcp_iss_key_lock);
23296 		context = tcp_iss_key;
23297 		mutex_exit(&tcp_iss_key_lock);
23298 		arg.ports = tcp->tcp_ports;
23299 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23300 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
23301 			    &arg.src);
23302 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
23303 			    &arg.dst);
23304 		} else {
23305 			arg.src = tcp->tcp_ip6h->ip6_src;
23306 			arg.dst = tcp->tcp_ip6h->ip6_dst;
23307 		}
23308 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
23309 		MD5Final((uchar_t *)answer, &context);
23310 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
23311 		/*
23312 		 * Now that we've hashed into a unique per-connection sequence
23313 		 * space, add a random increment per strong_iss == 1.  So I
23314 		 * guess we'll have to...
23315 		 */
23316 		/* FALLTHRU */
23317 	case 1:
23318 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
23319 		break;
23320 	default:
23321 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
23322 		break;
23323 	}
23324 	tcp->tcp_valid_bits = TCP_ISS_VALID;
23325 	tcp->tcp_fss = tcp->tcp_iss - 1;
23326 	tcp->tcp_suna = tcp->tcp_iss;
23327 	tcp->tcp_snxt = tcp->tcp_iss + 1;
23328 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23329 	tcp->tcp_csuna = tcp->tcp_snxt;
23330 }
23331 
23332 /*
23333  * Exported routine for extracting active tcp connection status.
23334  *
23335  * This is used by the Solaris Cluster Networking software to
23336  * gather a list of connections that need to be forwarded to
23337  * specific nodes in the cluster when configuration changes occur.
23338  *
23339  * The callback is invoked for each tcp_t structure. Returning
23340  * non-zero from the callback routine terminates the search.
23341  */
23342 int
23343 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
23344 {
23345 	tcp_t *tcp;
23346 	cl_tcp_info_t	cl_tcpi;
23347 	connf_t	*connfp;
23348 	conn_t	*connp;
23349 	int	i;
23350 
23351 	ASSERT(callback != NULL);
23352 
23353 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
23354 
23355 		connfp = &ipcl_globalhash_fanout[i];
23356 		connp = NULL;
23357 
23358 		while ((connp =
23359 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
23360 
23361 			tcp = connp->conn_tcp;
23362 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
23363 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
23364 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
23365 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
23366 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
23367 			/*
23368 			 * The macros tcp_laddr and tcp_faddr give the IPv4
23369 			 * addresses. They are copied implicitly below as
23370 			 * mapped addresses.
23371 			 */
23372 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
23373 			if (tcp->tcp_ipversion == IPV4_VERSION) {
23374 				cl_tcpi.cl_tcpi_faddr =
23375 				    tcp->tcp_ipha->ipha_dst;
23376 			} else {
23377 				cl_tcpi.cl_tcpi_faddr_v6 =
23378 				    tcp->tcp_ip6h->ip6_dst;
23379 			}
23380 
23381 			/*
23382 			 * If the callback returns non-zero
23383 			 * we terminate the traversal.
23384 			 */
23385 			if ((*callback)(&cl_tcpi, arg) != 0) {
23386 				CONN_DEC_REF(tcp->tcp_connp);
23387 				return (1);
23388 			}
23389 		}
23390 	}
23391 
23392 	return (0);
23393 }
23394 
23395 /*
23396  * Macros used for accessing the different types of sockaddr
23397  * structures inside a tcp_ioc_abort_conn_t.
23398  */
23399 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
23400 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
23401 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
23402 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
23403 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
23404 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
23405 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
23406 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
23407 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
23408 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
23409 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
23410 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
23411 
23412 /*
23413  * Return the correct error code to mimic the behavior
23414  * of a connection reset.
23415  */
23416 #define	TCP_AC_GET_ERRCODE(state, err) {	\
23417 		switch ((state)) {		\
23418 		case TCPS_SYN_SENT:		\
23419 		case TCPS_SYN_RCVD:		\
23420 			(err) = ECONNREFUSED;	\
23421 			break;			\
23422 		case TCPS_ESTABLISHED:		\
23423 		case TCPS_FIN_WAIT_1:		\
23424 		case TCPS_FIN_WAIT_2:		\
23425 		case TCPS_CLOSE_WAIT:		\
23426 			(err) = ECONNRESET;	\
23427 			break;			\
23428 		case TCPS_CLOSING:		\
23429 		case TCPS_LAST_ACK:		\
23430 		case TCPS_TIME_WAIT:		\
23431 			(err) = 0;		\
23432 			break;			\
23433 		default:			\
23434 			(err) = ENXIO;		\
23435 		}				\
23436 	}
23437 
23438 /*
23439  * Check if a tcp structure matches the info in acp.
23440  */
23441 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
23442 	(((acp)->ac_local.ss_family == AF_INET) ?		\
23443 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
23444 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
23445 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
23446 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
23447 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
23448 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
23449 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
23450 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
23451 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23452 	(acp)->ac_end >= (tcp)->tcp_state) :		\
23453 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
23454 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
23455 	&(tcp)->tcp_ip_src_v6)) &&				\
23456 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
23457 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
23458 	&(tcp)->tcp_remote_v6)) &&				\
23459 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
23460 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
23461 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
23462 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
23463 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23464 	(acp)->ac_end >= (tcp)->tcp_state))
23465 
23466 #define	TCP_AC_MATCH(acp, tcp)					\
23467 	(((acp)->ac_zoneid == ALL_ZONES ||			\
23468 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
23469 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
23470 
23471 /*
23472  * Build a message containing a tcp_ioc_abort_conn_t structure
23473  * which is filled in with information from acp and tp.
23474  */
23475 static mblk_t *
23476 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
23477 {
23478 	mblk_t *mp;
23479 	tcp_ioc_abort_conn_t *tacp;
23480 
23481 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
23482 	if (mp == NULL)
23483 		return (NULL);
23484 
23485 	mp->b_datap->db_type = M_CTL;
23486 
23487 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
23488 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
23489 		sizeof (uint32_t));
23490 
23491 	tacp->ac_start = acp->ac_start;
23492 	tacp->ac_end = acp->ac_end;
23493 	tacp->ac_zoneid = acp->ac_zoneid;
23494 
23495 	if (acp->ac_local.ss_family == AF_INET) {
23496 		tacp->ac_local.ss_family = AF_INET;
23497 		tacp->ac_remote.ss_family = AF_INET;
23498 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
23499 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
23500 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
23501 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
23502 	} else {
23503 		tacp->ac_local.ss_family = AF_INET6;
23504 		tacp->ac_remote.ss_family = AF_INET6;
23505 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
23506 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
23507 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
23508 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
23509 	}
23510 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
23511 	return (mp);
23512 }
23513 
23514 /*
23515  * Print a tcp_ioc_abort_conn_t structure.
23516  */
23517 static void
23518 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
23519 {
23520 	char lbuf[128];
23521 	char rbuf[128];
23522 	sa_family_t af;
23523 	in_port_t lport, rport;
23524 	ushort_t logflags;
23525 
23526 	af = acp->ac_local.ss_family;
23527 
23528 	if (af == AF_INET) {
23529 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
23530 				lbuf, 128);
23531 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
23532 				rbuf, 128);
23533 		lport = ntohs(TCP_AC_V4LPORT(acp));
23534 		rport = ntohs(TCP_AC_V4RPORT(acp));
23535 	} else {
23536 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
23537 				lbuf, 128);
23538 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
23539 				rbuf, 128);
23540 		lport = ntohs(TCP_AC_V6LPORT(acp));
23541 		rport = ntohs(TCP_AC_V6RPORT(acp));
23542 	}
23543 
23544 	logflags = SL_TRACE | SL_NOTE;
23545 	/*
23546 	 * Don't print this message to the console if the operation was done
23547 	 * to a non-global zone.
23548 	 */
23549 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
23550 		logflags |= SL_CONSOLE;
23551 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
23552 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
23553 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
23554 		acp->ac_start, acp->ac_end);
23555 }
23556 
23557 /*
23558  * Called inside tcp_rput when a message built using
23559  * tcp_ioctl_abort_build_msg is put into a queue.
23560  * Note that when we get here there is no wildcard in acp any more.
23561  */
23562 static void
23563 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
23564 {
23565 	tcp_ioc_abort_conn_t *acp;
23566 
23567 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
23568 	if (tcp->tcp_state <= acp->ac_end) {
23569 		/*
23570 		 * If we get here, we are already on the correct
23571 		 * squeue. This ioctl follows the following path
23572 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
23573 		 * ->tcp_ioctl_abort->squeue_fill (if on a
23574 		 * different squeue)
23575 		 */
23576 		int errcode;
23577 
23578 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
23579 		(void) tcp_clean_death(tcp, errcode, 26);
23580 	}
23581 	freemsg(mp);
23582 }
23583 
23584 /*
23585  * Abort all matching connections on a hash chain.
23586  */
23587 static int
23588 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
23589     boolean_t exact)
23590 {
23591 	int nmatch, err = 0;
23592 	tcp_t *tcp;
23593 	MBLKP mp, last, listhead = NULL;
23594 	conn_t	*tconnp;
23595 	connf_t	*connfp = &ipcl_conn_fanout[index];
23596 
23597 startover:
23598 	nmatch = 0;
23599 
23600 	mutex_enter(&connfp->connf_lock);
23601 	for (tconnp = connfp->connf_head; tconnp != NULL;
23602 	    tconnp = tconnp->conn_next) {
23603 		tcp = tconnp->conn_tcp;
23604 		if (TCP_AC_MATCH(acp, tcp)) {
23605 			CONN_INC_REF(tcp->tcp_connp);
23606 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
23607 			if (mp == NULL) {
23608 				err = ENOMEM;
23609 				CONN_DEC_REF(tcp->tcp_connp);
23610 				break;
23611 			}
23612 			mp->b_prev = (mblk_t *)tcp;
23613 
23614 			if (listhead == NULL) {
23615 				listhead = mp;
23616 				last = mp;
23617 			} else {
23618 				last->b_next = mp;
23619 				last = mp;
23620 			}
23621 			nmatch++;
23622 			if (exact)
23623 				break;
23624 		}
23625 
23626 		/* Avoid holding lock for too long. */
23627 		if (nmatch >= 500)
23628 			break;
23629 	}
23630 	mutex_exit(&connfp->connf_lock);
23631 
23632 	/* Pass mp into the correct tcp */
23633 	while ((mp = listhead) != NULL) {
23634 		listhead = listhead->b_next;
23635 		tcp = (tcp_t *)mp->b_prev;
23636 		mp->b_next = mp->b_prev = NULL;
23637 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
23638 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
23639 	}
23640 
23641 	*count += nmatch;
23642 	if (nmatch >= 500 && err == 0)
23643 		goto startover;
23644 	return (err);
23645 }
23646 
23647 /*
23648  * Abort all connections that matches the attributes specified in acp.
23649  */
23650 static int
23651 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
23652 {
23653 	sa_family_t af;
23654 	uint32_t  ports;
23655 	uint16_t *pports;
23656 	int err = 0, count = 0;
23657 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
23658 	int index = -1;
23659 	ushort_t logflags;
23660 
23661 	af = acp->ac_local.ss_family;
23662 
23663 	if (af == AF_INET) {
23664 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
23665 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
23666 			pports = (uint16_t *)&ports;
23667 			pports[1] = TCP_AC_V4LPORT(acp);
23668 			pports[0] = TCP_AC_V4RPORT(acp);
23669 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
23670 		}
23671 	} else {
23672 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
23673 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
23674 			pports = (uint16_t *)&ports;
23675 			pports[1] = TCP_AC_V6LPORT(acp);
23676 			pports[0] = TCP_AC_V6RPORT(acp);
23677 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
23678 		}
23679 	}
23680 
23681 	/*
23682 	 * For cases where remote addr, local port, and remote port are non-
23683 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
23684 	 */
23685 	if (index != -1) {
23686 		err = tcp_ioctl_abort_bucket(acp, index,
23687 			    &count, exact);
23688 	} else {
23689 		/*
23690 		 * loop through all entries for wildcard case
23691 		 */
23692 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
23693 			err = tcp_ioctl_abort_bucket(acp, index,
23694 			    &count, exact);
23695 			if (err != 0)
23696 				break;
23697 		}
23698 	}
23699 
23700 	logflags = SL_TRACE | SL_NOTE;
23701 	/*
23702 	 * Don't print this message to the console if the operation was done
23703 	 * to a non-global zone.
23704 	 */
23705 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
23706 		logflags |= SL_CONSOLE;
23707 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
23708 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
23709 	if (err == 0 && count == 0)
23710 		err = ENOENT;
23711 	return (err);
23712 }
23713 
23714 /*
23715  * Process the TCP_IOC_ABORT_CONN ioctl request.
23716  */
23717 static void
23718 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
23719 {
23720 	int	err;
23721 	IOCP    iocp;
23722 	MBLKP   mp1;
23723 	sa_family_t laf, raf;
23724 	tcp_ioc_abort_conn_t *acp;
23725 	zone_t *zptr;
23726 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
23727 
23728 	iocp = (IOCP)mp->b_rptr;
23729 
23730 	if ((mp1 = mp->b_cont) == NULL ||
23731 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
23732 		err = EINVAL;
23733 		goto out;
23734 	}
23735 
23736 	/* check permissions */
23737 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
23738 		err = EPERM;
23739 		goto out;
23740 	}
23741 
23742 	if (mp1->b_cont != NULL) {
23743 		freemsg(mp1->b_cont);
23744 		mp1->b_cont = NULL;
23745 	}
23746 
23747 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
23748 	laf = acp->ac_local.ss_family;
23749 	raf = acp->ac_remote.ss_family;
23750 
23751 	/* check that a zone with the supplied zoneid exists */
23752 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
23753 		zptr = zone_find_by_id(zoneid);
23754 		if (zptr != NULL) {
23755 			zone_rele(zptr);
23756 		} else {
23757 			err = EINVAL;
23758 			goto out;
23759 		}
23760 	}
23761 
23762 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
23763 	    acp->ac_start > acp->ac_end || laf != raf ||
23764 	    (laf != AF_INET && laf != AF_INET6)) {
23765 		err = EINVAL;
23766 		goto out;
23767 	}
23768 
23769 	tcp_ioctl_abort_dump(acp);
23770 	err = tcp_ioctl_abort(acp);
23771 
23772 out:
23773 	if (mp1 != NULL) {
23774 		freemsg(mp1);
23775 		mp->b_cont = NULL;
23776 	}
23777 
23778 	if (err != 0)
23779 		miocnak(q, mp, 0, err);
23780 	else
23781 		miocack(q, mp, 0, 0);
23782 }
23783 
23784 /*
23785  * tcp_time_wait_processing() handles processing of incoming packets when
23786  * the tcp is in the TIME_WAIT state.
23787  * A TIME_WAIT tcp that has an associated open TCP stream is never put
23788  * on the time wait list.
23789  */
23790 void
23791 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
23792     uint32_t seg_ack, int seg_len, tcph_t *tcph)
23793 {
23794 	int32_t		bytes_acked;
23795 	int32_t		gap;
23796 	int32_t		rgap;
23797 	tcp_opt_t	tcpopt;
23798 	uint_t		flags;
23799 	uint32_t	new_swnd = 0;
23800 	conn_t		*connp;
23801 
23802 	BUMP_LOCAL(tcp->tcp_ibsegs);
23803 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
23804 
23805 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
23806 	new_swnd = BE16_TO_U16(tcph->th_win) <<
23807 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
23808 	if (tcp->tcp_snd_ts_ok) {
23809 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
23810 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
23811 			    tcp->tcp_rnxt, TH_ACK);
23812 			goto done;
23813 		}
23814 	}
23815 	gap = seg_seq - tcp->tcp_rnxt;
23816 	rgap = tcp->tcp_rwnd - (gap + seg_len);
23817 	if (gap < 0) {
23818 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
23819 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
23820 		    (seg_len > -gap ? -gap : seg_len));
23821 		seg_len += gap;
23822 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
23823 			if (flags & TH_RST) {
23824 				goto done;
23825 			}
23826 			if ((flags & TH_FIN) && seg_len == -1) {
23827 				/*
23828 				 * When TCP receives a duplicate FIN in
23829 				 * TIME_WAIT state, restart the 2 MSL timer.
23830 				 * See page 73 in RFC 793. Make sure this TCP
23831 				 * is already on the TIME_WAIT list. If not,
23832 				 * just restart the timer.
23833 				 */
23834 				if (TCP_IS_DETACHED(tcp)) {
23835 					tcp_time_wait_remove(tcp, NULL);
23836 					tcp_time_wait_append(tcp);
23837 					TCP_DBGSTAT(tcp_rput_time_wait);
23838 				} else {
23839 					ASSERT(tcp != NULL);
23840 					TCP_TIMER_RESTART(tcp,
23841 					    tcp_time_wait_interval);
23842 				}
23843 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
23844 				    tcp->tcp_rnxt, TH_ACK);
23845 				goto done;
23846 			}
23847 			flags |=  TH_ACK_NEEDED;
23848 			seg_len = 0;
23849 			goto process_ack;
23850 		}
23851 
23852 		/* Fix seg_seq, and chew the gap off the front. */
23853 		seg_seq = tcp->tcp_rnxt;
23854 	}
23855 
23856 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
23857 		/*
23858 		 * Make sure that when we accept the connection, pick
23859 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
23860 		 * old connection.
23861 		 *
23862 		 * The next ISS generated is equal to tcp_iss_incr_extra
23863 		 * + ISS_INCR/2 + other components depending on the
23864 		 * value of tcp_strong_iss.  We pre-calculate the new
23865 		 * ISS here and compare with tcp_snxt to determine if
23866 		 * we need to make adjustment to tcp_iss_incr_extra.
23867 		 *
23868 		 * The above calculation is ugly and is a
23869 		 * waste of CPU cycles...
23870 		 */
23871 		uint32_t new_iss = tcp_iss_incr_extra;
23872 		int32_t adj;
23873 
23874 		switch (tcp_strong_iss) {
23875 		case 2: {
23876 			/* Add time and MD5 components. */
23877 			uint32_t answer[4];
23878 			struct {
23879 				uint32_t ports;
23880 				in6_addr_t src;
23881 				in6_addr_t dst;
23882 			} arg;
23883 			MD5_CTX context;
23884 
23885 			mutex_enter(&tcp_iss_key_lock);
23886 			context = tcp_iss_key;
23887 			mutex_exit(&tcp_iss_key_lock);
23888 			arg.ports = tcp->tcp_ports;
23889 			/* We use MAPPED addresses in tcp_iss_init */
23890 			arg.src = tcp->tcp_ip_src_v6;
23891 			if (tcp->tcp_ipversion == IPV4_VERSION) {
23892 				IN6_IPADDR_TO_V4MAPPED(
23893 					tcp->tcp_ipha->ipha_dst,
23894 					    &arg.dst);
23895 			} else {
23896 				arg.dst =
23897 				    tcp->tcp_ip6h->ip6_dst;
23898 			}
23899 			MD5Update(&context, (uchar_t *)&arg,
23900 			    sizeof (arg));
23901 			MD5Final((uchar_t *)answer, &context);
23902 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
23903 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
23904 			break;
23905 		}
23906 		case 1:
23907 			/* Add time component and min random (i.e. 1). */
23908 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
23909 			break;
23910 		default:
23911 			/* Add only time component. */
23912 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
23913 			break;
23914 		}
23915 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
23916 			/*
23917 			 * New ISS not guaranteed to be ISS_INCR/2
23918 			 * ahead of the current tcp_snxt, so add the
23919 			 * difference to tcp_iss_incr_extra.
23920 			 */
23921 			tcp_iss_incr_extra += adj;
23922 		}
23923 		/*
23924 		 * If tcp_clean_death() can not perform the task now,
23925 		 * drop the SYN packet and let the other side re-xmit.
23926 		 * Otherwise pass the SYN packet back in, since the
23927 		 * old tcp state has been cleaned up or freed.
23928 		 */
23929 		if (tcp_clean_death(tcp, 0, 27) == -1)
23930 			goto done;
23931 		/*
23932 		 * We will come back to tcp_rput_data
23933 		 * on the global queue. Packets destined
23934 		 * for the global queue will be checked
23935 		 * with global policy. But the policy for
23936 		 * this packet has already been checked as
23937 		 * this was destined for the detached
23938 		 * connection. We need to bypass policy
23939 		 * check this time by attaching a dummy
23940 		 * ipsec_in with ipsec_in_dont_check set.
23941 		 */
23942 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
23943 		    NULL) {
23944 			TCP_STAT(tcp_time_wait_syn_success);
23945 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
23946 			return;
23947 		}
23948 		goto done;
23949 	}
23950 
23951 	/*
23952 	 * rgap is the amount of stuff received out of window.  A negative
23953 	 * value is the amount out of window.
23954 	 */
23955 	if (rgap < 0) {
23956 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
23957 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
23958 		/* Fix seg_len and make sure there is something left. */
23959 		seg_len += rgap;
23960 		if (seg_len <= 0) {
23961 			if (flags & TH_RST) {
23962 				goto done;
23963 			}
23964 			flags |=  TH_ACK_NEEDED;
23965 			seg_len = 0;
23966 			goto process_ack;
23967 		}
23968 	}
23969 	/*
23970 	 * Check whether we can update tcp_ts_recent.  This test is
23971 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
23972 	 * Extensions for High Performance: An Update", Internet Draft.
23973 	 */
23974 	if (tcp->tcp_snd_ts_ok &&
23975 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
23976 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
23977 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
23978 		tcp->tcp_last_rcv_lbolt = lbolt64;
23979 	}
23980 
23981 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
23982 		/* Always ack out of order packets */
23983 		flags |= TH_ACK_NEEDED;
23984 		seg_len = 0;
23985 	} else if (seg_len > 0) {
23986 		BUMP_MIB(&tcp_mib, tcpInClosed);
23987 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
23988 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
23989 	}
23990 	if (flags & TH_RST) {
23991 		(void) tcp_clean_death(tcp, 0, 28);
23992 		goto done;
23993 	}
23994 	if (flags & TH_SYN) {
23995 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
23996 		    TH_RST|TH_ACK);
23997 		/*
23998 		 * Do not delete the TCP structure if it is in
23999 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24000 		 */
24001 		goto done;
24002 	}
24003 process_ack:
24004 	if (flags & TH_ACK) {
24005 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24006 		if (bytes_acked <= 0) {
24007 			if (bytes_acked == 0 && seg_len == 0 &&
24008 			    new_swnd == tcp->tcp_swnd)
24009 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24010 		} else {
24011 			/* Acks something not sent */
24012 			flags |= TH_ACK_NEEDED;
24013 		}
24014 	}
24015 	if (flags & TH_ACK_NEEDED) {
24016 		/*
24017 		 * Time to send an ack for some reason.
24018 		 */
24019 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24020 		    tcp->tcp_rnxt, TH_ACK);
24021 	}
24022 done:
24023 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24024 		DB_CKSUMSTART(mp) = 0;
24025 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24026 		TCP_STAT(tcp_time_wait_syn_fail);
24027 	}
24028 	freemsg(mp);
24029 }
24030 
24031 /*
24032  * Return zero if the buffers are identical in length and content.
24033  * This is used for comparing extension header buffers.
24034  * Note that an extension header would be declared different
24035  * even if all that changed was the next header value in that header i.e.
24036  * what really changed is the next extension header.
24037  */
24038 static boolean_t
24039 tcp_cmpbuf(void *a, uint_t alen, boolean_t b_valid, void *b, uint_t blen)
24040 {
24041 	if (!b_valid)
24042 		blen = 0;
24043 
24044 	if (alen != blen)
24045 		return (B_TRUE);
24046 	if (alen == 0)
24047 		return (B_FALSE);	/* Both zero length */
24048 	return (bcmp(a, b, alen));
24049 }
24050 
24051 /*
24052  * Preallocate memory for tcp_savebuf(). Returns B_TRUE if ok.
24053  * Return B_FALSE if memory allocation fails - don't change any state!
24054  */
24055 static boolean_t
24056 tcp_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24057     void *src, uint_t srclen)
24058 {
24059 	void *dst;
24060 
24061 	if (!src_valid)
24062 		srclen = 0;
24063 
24064 	ASSERT(*dstlenp == 0);
24065 	if (src != NULL && srclen != 0) {
24066 		dst = mi_alloc(srclen, BPRI_MED);
24067 		if (dst == NULL)
24068 			return (B_FALSE);
24069 	} else {
24070 		dst = NULL;
24071 	}
24072 	if (*dstp != NULL) {
24073 		mi_free(*dstp);
24074 		*dstp = NULL;
24075 		*dstlenp = 0;
24076 	}
24077 	*dstp = dst;
24078 	if (dst != NULL)
24079 		*dstlenp = srclen;
24080 	else
24081 		*dstlenp = 0;
24082 	return (B_TRUE);
24083 }
24084 
24085 /*
24086  * Replace what is in *dst, *dstlen with the source.
24087  * Assumes tcp_allocbuf has already been called.
24088  */
24089 static void
24090 tcp_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24091     void *src, uint_t srclen)
24092 {
24093 	if (!src_valid)
24094 		srclen = 0;
24095 
24096 	ASSERT(*dstlenp == srclen);
24097 	if (src != NULL && srclen != 0) {
24098 		bcopy(src, *dstp, srclen);
24099 	}
24100 }
24101 
24102 /*
24103  * Allocate a T_SVR4_OPTMGMT_REQ.
24104  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24105  * that tcp_rput_other can drop the acks.
24106  */
24107 static mblk_t *
24108 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24109 {
24110 	mblk_t *mp;
24111 	struct T_optmgmt_req *tor;
24112 	struct opthdr *oh;
24113 	uint_t size;
24114 	char *optptr;
24115 
24116 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24117 	mp = allocb(size, BPRI_MED);
24118 	if (mp == NULL)
24119 		return (NULL);
24120 
24121 	mp->b_wptr += size;
24122 	mp->b_datap->db_type = M_PROTO;
24123 	tor = (struct T_optmgmt_req *)mp->b_rptr;
24124 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
24125 	tor->MGMT_flags = T_NEGOTIATE;
24126 	tor->OPT_length = sizeof (*oh) + optlen;
24127 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
24128 
24129 	oh = (struct opthdr *)&tor[1];
24130 	oh->level = level;
24131 	oh->name = cmd;
24132 	oh->len = optlen;
24133 	if (optlen != 0) {
24134 		optptr = (char *)&oh[1];
24135 		bcopy(opt, optptr, optlen);
24136 	}
24137 	return (mp);
24138 }
24139 
24140 /*
24141  * TCP Timers Implementation.
24142  */
24143 timeout_id_t
24144 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24145 {
24146 	mblk_t *mp;
24147 	tcp_timer_t *tcpt;
24148 	tcp_t *tcp = connp->conn_tcp;
24149 
24150 	ASSERT(connp->conn_sqp != NULL);
24151 
24152 	TCP_DBGSTAT(tcp_timeout_calls);
24153 
24154 	if (tcp->tcp_timercache == NULL) {
24155 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24156 	} else {
24157 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
24158 		mp = tcp->tcp_timercache;
24159 		tcp->tcp_timercache = mp->b_next;
24160 		mp->b_next = NULL;
24161 		ASSERT(mp->b_wptr == NULL);
24162 	}
24163 
24164 	CONN_INC_REF(connp);
24165 	tcpt = (tcp_timer_t *)mp->b_rptr;
24166 	tcpt->connp = connp;
24167 	tcpt->tcpt_proc = f;
24168 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
24169 	return ((timeout_id_t)mp);
24170 }
24171 
24172 static void
24173 tcp_timer_callback(void *arg)
24174 {
24175 	mblk_t *mp = (mblk_t *)arg;
24176 	tcp_timer_t *tcpt;
24177 	conn_t	*connp;
24178 
24179 	tcpt = (tcp_timer_t *)mp->b_rptr;
24180 	connp = tcpt->connp;
24181 	squeue_fill(connp->conn_sqp, mp,
24182 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
24183 }
24184 
24185 static void
24186 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24187 {
24188 	tcp_timer_t *tcpt;
24189 	conn_t *connp = (conn_t *)arg;
24190 	tcp_t *tcp = connp->conn_tcp;
24191 
24192 	tcpt = (tcp_timer_t *)mp->b_rptr;
24193 	ASSERT(connp == tcpt->connp);
24194 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24195 
24196 	/*
24197 	 * If the TCP has reached the closed state, don't proceed any
24198 	 * further. This TCP logically does not exist on the system.
24199 	 * tcpt_proc could for example access queues, that have already
24200 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24201 	 */
24202 	if (tcp->tcp_state != TCPS_CLOSED) {
24203 		(*tcpt->tcpt_proc)(connp);
24204 	} else {
24205 		tcp->tcp_timer_tid = 0;
24206 	}
24207 	tcp_timer_free(connp->conn_tcp, mp);
24208 }
24209 
24210 /*
24211  * There is potential race with untimeout and the handler firing at the same
24212  * time. The mblock may be freed by the handler while we are trying to use
24213  * it. But since both should execute on the same squeue, this race should not
24214  * occur.
24215  */
24216 clock_t
24217 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24218 {
24219 	mblk_t	*mp = (mblk_t *)id;
24220 	tcp_timer_t *tcpt;
24221 	clock_t delta;
24222 
24223 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
24224 
24225 	if (mp == NULL)
24226 		return (-1);
24227 
24228 	tcpt = (tcp_timer_t *)mp->b_rptr;
24229 	ASSERT(tcpt->connp == connp);
24230 
24231 	delta = untimeout(tcpt->tcpt_tid);
24232 
24233 	if (delta >= 0) {
24234 		TCP_DBGSTAT(tcp_timeout_canceled);
24235 		tcp_timer_free(connp->conn_tcp, mp);
24236 		CONN_DEC_REF(connp);
24237 	}
24238 
24239 	return (delta);
24240 }
24241 
24242 /*
24243  * Allocate space for the timer event. The allocation looks like mblk, but it is
24244  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24245  *
24246  * Dealing with failures: If we can't allocate from the timer cache we try
24247  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24248  * points to b_rptr.
24249  * If we can't allocate anything using allocb_tryhard(), we perform a last
24250  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24251  * save the actual allocation size in b_datap.
24252  */
24253 mblk_t *
24254 tcp_timermp_alloc(int kmflags)
24255 {
24256 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
24257 	    kmflags & ~KM_PANIC);
24258 
24259 	if (mp != NULL) {
24260 		mp->b_next = mp->b_prev = NULL;
24261 		mp->b_rptr = (uchar_t *)(&mp[1]);
24262 		mp->b_wptr = NULL;
24263 		mp->b_datap = NULL;
24264 		mp->b_queue = NULL;
24265 	} else if (kmflags & KM_PANIC) {
24266 		/*
24267 		 * Failed to allocate memory for the timer. Try allocating from
24268 		 * dblock caches.
24269 		 */
24270 		TCP_STAT(tcp_timermp_allocfail);
24271 		mp = allocb_tryhard(sizeof (tcp_timer_t));
24272 		if (mp == NULL) {
24273 			size_t size = 0;
24274 			/*
24275 			 * Memory is really low. Try tryhard allocation.
24276 			 */
24277 			TCP_STAT(tcp_timermp_allocdblfail);
24278 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
24279 			    sizeof (tcp_timer_t), &size, kmflags);
24280 			mp->b_rptr = (uchar_t *)(&mp[1]);
24281 			mp->b_next = mp->b_prev = NULL;
24282 			mp->b_wptr = (uchar_t *)-1;
24283 			mp->b_datap = (dblk_t *)size;
24284 			mp->b_queue = NULL;
24285 		}
24286 		ASSERT(mp->b_wptr != NULL);
24287 	}
24288 	TCP_DBGSTAT(tcp_timermp_alloced);
24289 
24290 	return (mp);
24291 }
24292 
24293 /*
24294  * Free per-tcp timer cache.
24295  * It can only contain entries from tcp_timercache.
24296  */
24297 void
24298 tcp_timermp_free(tcp_t *tcp)
24299 {
24300 	mblk_t *mp;
24301 
24302 	while ((mp = tcp->tcp_timercache) != NULL) {
24303 		ASSERT(mp->b_wptr == NULL);
24304 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
24305 		kmem_cache_free(tcp_timercache, mp);
24306 	}
24307 }
24308 
24309 /*
24310  * Free timer event. Put it on the per-tcp timer cache if there is not too many
24311  * events there already (currently at most two events are cached).
24312  * If the event is not allocated from the timer cache, free it right away.
24313  */
24314 static void
24315 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
24316 {
24317 	mblk_t *mp1 = tcp->tcp_timercache;
24318 
24319 	if (mp->b_wptr != NULL) {
24320 		/*
24321 		 * This allocation is not from a timer cache, free it right
24322 		 * away.
24323 		 */
24324 		if (mp->b_wptr != (uchar_t *)-1)
24325 			freeb(mp);
24326 		else
24327 			kmem_free(mp, (size_t)mp->b_datap);
24328 	} else if (mp1 == NULL || mp1->b_next == NULL) {
24329 		/* Cache this timer block for future allocations */
24330 		mp->b_rptr = (uchar_t *)(&mp[1]);
24331 		mp->b_next = mp1;
24332 		tcp->tcp_timercache = mp;
24333 	} else {
24334 		kmem_cache_free(tcp_timercache, mp);
24335 		TCP_DBGSTAT(tcp_timermp_freed);
24336 	}
24337 }
24338 
24339 /*
24340  * End of TCP Timers implementation.
24341  */
24342 
24343 /*
24344  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
24345  * on the specified backing STREAMS q. Note, the caller may make the
24346  * decision to call based on the tcp_t.tcp_flow_stopped value which
24347  * when check outside the q's lock is only an advisory check ...
24348  */
24349 
24350 void
24351 tcp_setqfull(tcp_t *tcp)
24352 {
24353 	queue_t *q = tcp->tcp_wq;
24354 
24355 	if (!(q->q_flag & QFULL)) {
24356 		mutex_enter(QLOCK(q));
24357 		if (!(q->q_flag & QFULL)) {
24358 			/* still need to set QFULL */
24359 			q->q_flag |= QFULL;
24360 			tcp->tcp_flow_stopped = B_TRUE;
24361 			mutex_exit(QLOCK(q));
24362 			TCP_STAT(tcp_flwctl_on);
24363 		} else {
24364 			mutex_exit(QLOCK(q));
24365 		}
24366 	}
24367 }
24368 
24369 void
24370 tcp_clrqfull(tcp_t *tcp)
24371 {
24372 	queue_t *q = tcp->tcp_wq;
24373 
24374 	if (q->q_flag & QFULL) {
24375 		mutex_enter(QLOCK(q));
24376 		if (q->q_flag & QFULL) {
24377 			q->q_flag &= ~QFULL;
24378 			tcp->tcp_flow_stopped = B_FALSE;
24379 			mutex_exit(QLOCK(q));
24380 			if (q->q_flag & QWANTW)
24381 				qbackenable(q, 0);
24382 		} else {
24383 			mutex_exit(QLOCK(q));
24384 		}
24385 	}
24386 }
24387 
24388 /*
24389  * TCP Kstats implementation
24390  */
24391 static void
24392 tcp_kstat_init(void)
24393 {
24394 	tcp_named_kstat_t template = {
24395 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
24396 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
24397 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
24398 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
24399 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
24400 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
24401 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
24402 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
24403 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
24404 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
24405 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
24406 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
24407 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
24408 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
24409 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
24410 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
24411 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
24412 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
24413 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
24414 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
24415 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
24416 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
24417 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
24418 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
24419 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
24420 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
24421 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
24422 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
24423 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
24424 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
24425 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
24426 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
24427 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
24428 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
24429 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
24430 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
24431 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
24432 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
24433 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
24434 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
24435 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
24436 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
24437 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
24438 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
24439 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
24440 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
24441 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
24442 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
24443 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
24444 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
24445 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
24446 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
24447 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
24448 	};
24449 
24450 	tcp_mibkp = kstat_create(TCP_MOD_NAME, 0, TCP_MOD_NAME,
24451 	    "mib2", KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0);
24452 
24453 	if (tcp_mibkp == NULL)
24454 		return;
24455 
24456 	template.rtoAlgorithm.value.ui32 = 4;
24457 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
24458 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
24459 	template.maxConn.value.i32 = -1;
24460 
24461 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
24462 
24463 	tcp_mibkp->ks_update = tcp_kstat_update;
24464 
24465 	kstat_install(tcp_mibkp);
24466 }
24467 
24468 static void
24469 tcp_kstat_fini(void)
24470 {
24471 
24472 	if (tcp_mibkp != NULL) {
24473 		kstat_delete(tcp_mibkp);
24474 		tcp_mibkp = NULL;
24475 	}
24476 }
24477 
24478 static int
24479 tcp_kstat_update(kstat_t *kp, int rw)
24480 {
24481 	tcp_named_kstat_t	*tcpkp;
24482 	tcp_t			*tcp;
24483 	connf_t			*connfp;
24484 	conn_t			*connp;
24485 	int 			i;
24486 
24487 	if (!kp || !kp->ks_data)
24488 		return (EIO);
24489 
24490 	if (rw == KSTAT_WRITE)
24491 		return (EACCES);
24492 
24493 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
24494 
24495 	tcpkp->currEstab.value.ui32 = 0;
24496 
24497 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24498 		connfp = &ipcl_globalhash_fanout[i];
24499 		connp = NULL;
24500 		while ((connp =
24501 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24502 			tcp = connp->conn_tcp;
24503 			switch (tcp_snmp_state(tcp)) {
24504 			case MIB2_TCP_established:
24505 			case MIB2_TCP_closeWait:
24506 				tcpkp->currEstab.value.ui32++;
24507 				break;
24508 			}
24509 		}
24510 	}
24511 
24512 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
24513 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
24514 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
24515 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
24516 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
24517 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
24518 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
24519 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
24520 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
24521 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
24522 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
24523 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
24524 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
24525 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
24526 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
24527 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
24528 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
24529 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
24530 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
24531 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
24532 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
24533 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
24534 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
24535 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
24536 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
24537 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
24538 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
24539 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
24540 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
24541 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
24542 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
24543 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
24544 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
24545 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
24546 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
24547 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
24548 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
24549 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
24550 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
24551 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
24552 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
24553 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
24554 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
24555 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
24556 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
24557 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
24558 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
24559 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
24560 
24561 	return (0);
24562 }
24563 
24564 void
24565 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
24566 {
24567 	uint16_t	hdr_len;
24568 	ipha_t		*ipha;
24569 	uint8_t		*nexthdrp;
24570 	tcph_t		*tcph;
24571 
24572 	/* Already has an eager */
24573 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24574 		TCP_STAT(tcp_reinput_syn);
24575 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
24576 		    connp, SQTAG_TCP_REINPUT_EAGER);
24577 		return;
24578 	}
24579 
24580 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
24581 	case IPV4_VERSION:
24582 		ipha = (ipha_t *)mp->b_rptr;
24583 		hdr_len = IPH_HDR_LENGTH(ipha);
24584 		break;
24585 	case IPV6_VERSION:
24586 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
24587 		    &hdr_len, &nexthdrp)) {
24588 			CONN_DEC_REF(connp);
24589 			freemsg(mp);
24590 			return;
24591 		}
24592 		break;
24593 	}
24594 
24595 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
24596 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
24597 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
24598 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
24599 	}
24600 
24601 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
24602 	    SQTAG_TCP_REINPUT);
24603 }
24604 
24605 static squeue_func_t
24606 tcp_squeue_switch(int val)
24607 {
24608 	squeue_func_t rval = squeue_fill;
24609 
24610 	switch (val) {
24611 	case 1:
24612 		rval = squeue_enter_nodrain;
24613 		break;
24614 	case 2:
24615 		rval = squeue_enter;
24616 		break;
24617 	default:
24618 		break;
24619 	}
24620 	return (rval);
24621 }
24622 
24623 static void
24624 tcp_squeue_add(squeue_t *sqp)
24625 {
24626 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
24627 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
24628 
24629 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
24630 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
24631 	    sqp, TCP_TIME_WAIT_DELAY);
24632 }
24633