xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision e23347b1b88ce2c0847fad6e9467a1f953597aa7)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #define	_SUN_TPI_VERSION 2
35 #include <sys/tihdr.h>
36 #include <sys/timod.h>
37 #include <sys/ddi.h>
38 #include <sys/sunddi.h>
39 #include <sys/suntpi.h>
40 #include <sys/xti_inet.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/sdt.h>
44 #include <sys/vtrace.h>
45 #include <sys/kmem.h>
46 #include <sys/ethernet.h>
47 #include <sys/cpuvar.h>
48 #include <sys/dlpi.h>
49 #include <sys/multidata.h>
50 #include <sys/multidata_impl.h>
51 #include <sys/pattr.h>
52 #include <sys/policy.h>
53 #include <sys/priv.h>
54 #include <sys/zone.h>
55 #include <sys/sunldi.h>
56 
57 #include <sys/errno.h>
58 #include <sys/signal.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/sockio.h>
62 #include <sys/isa_defs.h>
63 #include <sys/md5.h>
64 #include <sys/random.h>
65 #include <sys/uio.h>
66 #include <sys/systm.h>
67 #include <netinet/in.h>
68 #include <netinet/tcp.h>
69 #include <netinet/ip6.h>
70 #include <netinet/icmp6.h>
71 #include <net/if.h>
72 #include <net/route.h>
73 #include <inet/ipsec_impl.h>
74 
75 #include <inet/common.h>
76 #include <inet/ip.h>
77 #include <inet/ip_impl.h>
78 #include <inet/ip6.h>
79 #include <inet/ip_ndp.h>
80 #include <inet/proto_set.h>
81 #include <inet/mib2.h>
82 #include <inet/nd.h>
83 #include <inet/optcom.h>
84 #include <inet/snmpcom.h>
85 #include <inet/kstatcom.h>
86 #include <inet/tcp.h>
87 #include <inet/tcp_impl.h>
88 #include <inet/udp_impl.h>
89 #include <net/pfkeyv2.h>
90 #include <inet/ipsec_info.h>
91 #include <inet/ipdrop.h>
92 
93 #include <inet/ipclassifier.h>
94 #include <inet/ip_ire.h>
95 #include <inet/ip_ftable.h>
96 #include <inet/ip_if.h>
97 #include <inet/ipp_common.h>
98 #include <inet/ip_netinfo.h>
99 #include <sys/squeue_impl.h>
100 #include <sys/squeue.h>
101 #include <inet/kssl/ksslapi.h>
102 #include <sys/tsol/label.h>
103 #include <sys/tsol/tnet.h>
104 #include <rpc/pmap_prot.h>
105 #include <sys/callo.h>
106 
107 /*
108  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
109  *
110  * (Read the detailed design doc in PSARC case directory)
111  *
112  * The entire tcp state is contained in tcp_t and conn_t structure
113  * which are allocated in tandem using ipcl_conn_create() and passing
114  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
115  * the references on the tcp_t. The tcp_t structure is never compressed
116  * and packets always land on the correct TCP perimeter from the time
117  * eager is created till the time tcp_t dies (as such the old mentat
118  * TCP global queue is not used for detached state and no IPSEC checking
119  * is required). The global queue is still allocated to send out resets
120  * for connection which have no listeners and IP directly calls
121  * tcp_xmit_listeners_reset() which does any policy check.
122  *
123  * Protection and Synchronisation mechanism:
124  *
125  * The tcp data structure does not use any kind of lock for protecting
126  * its state but instead uses 'squeues' for mutual exclusion from various
127  * read and write side threads. To access a tcp member, the thread should
128  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
129  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
130  * can pass any tcp function having prototype of edesc_t as argument
131  * (different from traditional STREAMs model where packets come in only
132  * designated entry points). The list of functions that can be directly
133  * called via squeue are listed before the usual function prototype.
134  *
135  * Referencing:
136  *
137  * TCP is MT-Hot and we use a reference based scheme to make sure that the
138  * tcp structure doesn't disappear when its needed. When the application
139  * creates an outgoing connection or accepts an incoming connection, we
140  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
141  * The IP reference is just a symbolic reference since ip_tcpclose()
142  * looks at tcp structure after tcp_close_output() returns which could
143  * have dropped the last TCP reference. So as long as the connection is
144  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
145  * conn_t. The classifier puts its own reference when the connection is
146  * inserted in listen or connected hash. Anytime a thread needs to enter
147  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
148  * on write side or by doing a classify on read side and then puts a
149  * reference on the conn before doing squeue_enter/tryenter/fill. For
150  * read side, the classifier itself puts the reference under fanout lock
151  * to make sure that tcp can't disappear before it gets processed. The
152  * squeue will drop this reference automatically so the called function
153  * doesn't have to do a DEC_REF.
154  *
155  * Opening a new connection:
156  *
157  * The outgoing connection open is pretty simple. tcp_open() does the
158  * work in creating the conn/tcp structure and initializing it. The
159  * squeue assignment is done based on the CPU the application
160  * is running on. So for outbound connections, processing is always done
161  * on application CPU which might be different from the incoming CPU
162  * being interrupted by the NIC. An optimal way would be to figure out
163  * the NIC <-> CPU binding at listen time, and assign the outgoing
164  * connection to the squeue attached to the CPU that will be interrupted
165  * for incoming packets (we know the NIC based on the bind IP address).
166  * This might seem like a problem if more data is going out but the
167  * fact is that in most cases the transmit is ACK driven transmit where
168  * the outgoing data normally sits on TCP's xmit queue waiting to be
169  * transmitted.
170  *
171  * Accepting a connection:
172  *
173  * This is a more interesting case because of various races involved in
174  * establishing a eager in its own perimeter. Read the meta comment on
175  * top of tcp_conn_request(). But briefly, the squeue is picked by
176  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
177  *
178  * Closing a connection:
179  *
180  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
181  * via squeue to do the close and mark the tcp as detached if the connection
182  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
183  * reference but tcp_close() drop IP's reference always. So if tcp was
184  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
185  * and 1 because it is in classifier's connected hash. This is the condition
186  * we use to determine that its OK to clean up the tcp outside of squeue
187  * when time wait expires (check the ref under fanout and conn_lock and
188  * if it is 2, remove it from fanout hash and kill it).
189  *
190  * Although close just drops the necessary references and marks the
191  * tcp_detached state, tcp_close needs to know the tcp_detached has been
192  * set (under squeue) before letting the STREAM go away (because a
193  * inbound packet might attempt to go up the STREAM while the close
194  * has happened and tcp_detached is not set). So a special lock and
195  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
196  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
197  * tcp_detached.
198  *
199  * Special provisions and fast paths:
200  *
201  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
202  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
203  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
204  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
205  * check to send packets directly to tcp_rput_data via squeue. Everyone
206  * else comes through tcp_input() on the read side.
207  *
208  * We also make special provisions for sockfs by marking tcp_issocket
209  * whenever we have only sockfs on top of TCP. This allows us to skip
210  * putting the tcp in acceptor hash since a sockfs listener can never
211  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
212  * since eager has already been allocated and the accept now happens
213  * on acceptor STREAM. There is a big blob of comment on top of
214  * tcp_conn_request explaining the new accept. When socket is POP'd,
215  * sockfs sends us an ioctl to mark the fact and we go back to old
216  * behaviour. Once tcp_issocket is unset, its never set for the
217  * life of that connection.
218  *
219  * IPsec notes :
220  *
221  * Since a packet is always executed on the correct TCP perimeter
222  * all IPsec processing is defered to IP including checking new
223  * connections and setting IPSEC policies for new connection. The
224  * only exception is tcp_xmit_listeners_reset() which is called
225  * directly from IP and needs to policy check to see if TH_RST
226  * can be sent out.
227  *
228  * PFHooks notes :
229  *
230  * For mdt case, one meta buffer contains multiple packets. Mblks for every
231  * packet are assembled and passed to the hooks. When packets are blocked,
232  * or boundary of any packet is changed, the mdt processing is stopped, and
233  * packets of the meta buffer are send to the IP path one by one.
234  */
235 
236 /*
237  * Values for squeue switch:
238  * 1: SQ_NODRAIN
239  * 2: SQ_PROCESS
240  * 3: SQ_FILL
241  */
242 int tcp_squeue_wput = 2;	/* /etc/systems */
243 int tcp_squeue_flag;
244 
245 /*
246  * This controls how tiny a write must be before we try to copy it
247  * into the the mblk on the tail of the transmit queue.  Not much
248  * speedup is observed for values larger than sixteen.  Zero will
249  * disable the optimisation.
250  */
251 int tcp_tx_pull_len = 16;
252 
253 /*
254  * TCP Statistics.
255  *
256  * How TCP statistics work.
257  *
258  * There are two types of statistics invoked by two macros.
259  *
260  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
261  * supposed to be used in non MT-hot paths of the code.
262  *
263  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
264  * supposed to be used for DEBUG purposes and may be used on a hot path.
265  *
266  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
267  * (use "kstat tcp" to get them).
268  *
269  * There is also additional debugging facility that marks tcp_clean_death()
270  * instances and saves them in tcp_t structure. It is triggered by
271  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
272  * tcp_clean_death() calls that counts the number of times each tag was hit. It
273  * is triggered by TCP_CLD_COUNTERS define.
274  *
275  * How to add new counters.
276  *
277  * 1) Add a field in the tcp_stat structure describing your counter.
278  * 2) Add a line in the template in tcp_kstat2_init() with the name
279  *    of the counter.
280  *
281  *    IMPORTANT!! - make sure that both are in sync !!
282  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
283  *
284  * Please avoid using private counters which are not kstat-exported.
285  *
286  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
287  * in tcp_t structure.
288  *
289  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
290  */
291 
292 #ifndef TCP_DEBUG_COUNTER
293 #ifdef DEBUG
294 #define	TCP_DEBUG_COUNTER 1
295 #else
296 #define	TCP_DEBUG_COUNTER 0
297 #endif
298 #endif
299 
300 #define	TCP_CLD_COUNTERS 0
301 
302 #define	TCP_TAG_CLEAN_DEATH 1
303 #define	TCP_MAX_CLEAN_DEATH_TAG 32
304 
305 #ifdef lint
306 static int _lint_dummy_;
307 #endif
308 
309 #if TCP_CLD_COUNTERS
310 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
311 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
312 #elif defined(lint)
313 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
314 #else
315 #define	TCP_CLD_STAT(x)
316 #endif
317 
318 #if TCP_DEBUG_COUNTER
319 #define	TCP_DBGSTAT(tcps, x)	\
320 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
321 #define	TCP_G_DBGSTAT(x)	\
322 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
323 #elif defined(lint)
324 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
325 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
326 #else
327 #define	TCP_DBGSTAT(tcps, x)
328 #define	TCP_G_DBGSTAT(x)
329 #endif
330 
331 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
332 
333 tcp_g_stat_t	tcp_g_statistics;
334 kstat_t		*tcp_g_kstat;
335 
336 /*
337  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
338  * tcp write side.
339  */
340 #define	CALL_IP_WPUT(connp, q, mp) {					\
341 	ASSERT(((q)->q_flag & QREADR) == 0);				\
342 	TCP_DBGSTAT(connp->conn_netstack->netstack_tcp, tcp_ip_output);	\
343 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
344 }
345 
346 /* Macros for timestamp comparisons */
347 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
348 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
349 
350 /*
351  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
352  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
353  * by adding three components: a time component which grows by 1 every 4096
354  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
355  * a per-connection component which grows by 125000 for every new connection;
356  * and an "extra" component that grows by a random amount centered
357  * approximately on 64000.  This causes the the ISS generator to cycle every
358  * 4.89 hours if no TCP connections are made, and faster if connections are
359  * made.
360  *
361  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
362  * components: a time component which grows by 250000 every second; and
363  * a per-connection component which grows by 125000 for every new connections.
364  *
365  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
366  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
367  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
368  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
369  * password.
370  */
371 #define	ISS_INCR	250000
372 #define	ISS_NSEC_SHT	12
373 
374 static sin_t	sin_null;	/* Zero address for quick clears */
375 static sin6_t	sin6_null;	/* Zero address for quick clears */
376 
377 /*
378  * This implementation follows the 4.3BSD interpretation of the urgent
379  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
380  * incompatible changes in protocols like telnet and rlogin.
381  */
382 #define	TCP_OLD_URP_INTERPRETATION	1
383 
384 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
385 	(TCP_IS_DETACHED(tcp) && \
386 	    (!(tcp)->tcp_hard_binding))
387 
388 /*
389  * TCP reassembly macros.  We hide starting and ending sequence numbers in
390  * b_next and b_prev of messages on the reassembly queue.  The messages are
391  * chained using b_cont.  These macros are used in tcp_reass() so we don't
392  * have to see the ugly casts and assignments.
393  */
394 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
395 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
396 					(mblk_t *)(uintptr_t)(u))
397 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
398 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
399 					(mblk_t *)(uintptr_t)(u))
400 
401 /*
402  * Implementation of TCP Timers.
403  * =============================
404  *
405  * INTERFACE:
406  *
407  * There are two basic functions dealing with tcp timers:
408  *
409  *	timeout_id_t	tcp_timeout(connp, func, time)
410  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
411  *	TCP_TIMER_RESTART(tcp, intvl)
412  *
413  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
414  * after 'time' ticks passed. The function called by timeout() must adhere to
415  * the same restrictions as a driver soft interrupt handler - it must not sleep
416  * or call other functions that might sleep. The value returned is the opaque
417  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
418  * cancel the request. The call to tcp_timeout() may fail in which case it
419  * returns zero. This is different from the timeout(9F) function which never
420  * fails.
421  *
422  * The call-back function 'func' always receives 'connp' as its single
423  * argument. It is always executed in the squeue corresponding to the tcp
424  * structure. The tcp structure is guaranteed to be present at the time the
425  * call-back is called.
426  *
427  * NOTE: The call-back function 'func' is never called if tcp is in
428  * 	the TCPS_CLOSED state.
429  *
430  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
431  * request. locks acquired by the call-back routine should not be held across
432  * the call to tcp_timeout_cancel() or a deadlock may result.
433  *
434  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
435  * Otherwise, it returns an integer value greater than or equal to 0. In
436  * particular, if the call-back function is already placed on the squeue, it can
437  * not be canceled.
438  *
439  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
440  * 	within squeue context corresponding to the tcp instance. Since the
441  *	call-back is also called via the same squeue, there are no race
442  *	conditions described in untimeout(9F) manual page since all calls are
443  *	strictly serialized.
444  *
445  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
446  *	stored in tcp_timer_tid and starts a new one using
447  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
448  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
449  *	field.
450  *
451  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
452  *	call-back may still be called, so it is possible tcp_timer() will be
453  *	called several times. This should not be a problem since tcp_timer()
454  *	should always check the tcp instance state.
455  *
456  *
457  * IMPLEMENTATION:
458  *
459  * TCP timers are implemented using three-stage process. The call to
460  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
461  * when the timer expires. The tcp_timer_callback() arranges the call of the
462  * tcp_timer_handler() function via squeue corresponding to the tcp
463  * instance. The tcp_timer_handler() calls actual requested timeout call-back
464  * and passes tcp instance as an argument to it. Information is passed between
465  * stages using the tcp_timer_t structure which contains the connp pointer, the
466  * tcp call-back to call and the timeout id returned by the timeout(9F).
467  *
468  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
469  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
470  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
471  * returns the pointer to this mblk.
472  *
473  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
474  * looks like a normal mblk without actual dblk attached to it.
475  *
476  * To optimize performance each tcp instance holds a small cache of timer
477  * mblocks. In the current implementation it caches up to two timer mblocks per
478  * tcp instance. The cache is preserved over tcp frees and is only freed when
479  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
480  * timer processing happens on a corresponding squeue, the cache manipulation
481  * does not require any locks. Experiments show that majority of timer mblocks
482  * allocations are satisfied from the tcp cache and do not involve kmem calls.
483  *
484  * The tcp_timeout() places a refhold on the connp instance which guarantees
485  * that it will be present at the time the call-back function fires. The
486  * tcp_timer_handler() drops the reference after calling the call-back, so the
487  * call-back function does not need to manipulate the references explicitly.
488  */
489 
490 typedef struct tcp_timer_s {
491 	conn_t	*connp;
492 	void 	(*tcpt_proc)(void *);
493 	callout_id_t   tcpt_tid;
494 } tcp_timer_t;
495 
496 static kmem_cache_t *tcp_timercache;
497 kmem_cache_t	*tcp_sack_info_cache;
498 kmem_cache_t	*tcp_iphc_cache;
499 
500 /*
501  * For scalability, we must not run a timer for every TCP connection
502  * in TIME_WAIT state.  To see why, consider (for time wait interval of
503  * 4 minutes):
504  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
505  *
506  * This list is ordered by time, so you need only delete from the head
507  * until you get to entries which aren't old enough to delete yet.
508  * The list consists of only the detached TIME_WAIT connections.
509  *
510  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
511  * becomes detached TIME_WAIT (either by changing the state and already
512  * being detached or the other way around). This means that the TIME_WAIT
513  * state can be extended (up to doubled) if the connection doesn't become
514  * detached for a long time.
515  *
516  * The list manipulations (including tcp_time_wait_next/prev)
517  * are protected by the tcp_time_wait_lock. The content of the
518  * detached TIME_WAIT connections is protected by the normal perimeters.
519  *
520  * This list is per squeue and squeues are shared across the tcp_stack_t's.
521  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
522  * and conn_netstack.
523  * The tcp_t's that are added to tcp_free_list are disassociated and
524  * have NULL tcp_tcps and conn_netstack pointers.
525  */
526 typedef struct tcp_squeue_priv_s {
527 	kmutex_t	tcp_time_wait_lock;
528 	callout_id_t	tcp_time_wait_tid;
529 	tcp_t		*tcp_time_wait_head;
530 	tcp_t		*tcp_time_wait_tail;
531 	tcp_t		*tcp_free_list;
532 	uint_t		tcp_free_list_cnt;
533 } tcp_squeue_priv_t;
534 
535 /*
536  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
537  * Running it every 5 seconds seems to give the best results.
538  */
539 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
540 
541 /*
542  * To prevent memory hog, limit the number of entries in tcp_free_list
543  * to 1% of available memory / number of cpus
544  */
545 uint_t tcp_free_list_max_cnt = 0;
546 
547 #define	TCP_XMIT_LOWATER	4096
548 #define	TCP_XMIT_HIWATER	49152
549 #define	TCP_RECV_LOWATER	2048
550 #define	TCP_RECV_HIWATER	49152
551 
552 /*
553  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
554  */
555 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
556 
557 #define	TIDUSZ	4096	/* transport interface data unit size */
558 
559 /*
560  * Bind hash list size and has function.  It has to be a power of 2 for
561  * hashing.
562  */
563 #define	TCP_BIND_FANOUT_SIZE	512
564 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
565 /*
566  * Size of listen and acceptor hash list.  It has to be a power of 2 for
567  * hashing.
568  */
569 #define	TCP_FANOUT_SIZE		256
570 
571 #ifdef	_ILP32
572 #define	TCP_ACCEPTOR_HASH(accid)					\
573 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
574 #else
575 #define	TCP_ACCEPTOR_HASH(accid)					\
576 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
577 #endif	/* _ILP32 */
578 
579 #define	IP_ADDR_CACHE_SIZE	2048
580 #define	IP_ADDR_CACHE_HASH(faddr)					\
581 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
582 
583 /*
584  * TCP options struct returned from tcp_parse_options.
585  */
586 typedef struct tcp_opt_s {
587 	uint32_t	tcp_opt_mss;
588 	uint32_t	tcp_opt_wscale;
589 	uint32_t	tcp_opt_ts_val;
590 	uint32_t	tcp_opt_ts_ecr;
591 	tcp_t		*tcp;
592 } tcp_opt_t;
593 
594 /*
595  * TCP option struct passing information b/w lisenter and eager.
596  */
597 struct tcp_options {
598 	uint_t			to_flags;
599 	ssize_t			to_boundif;	/* IPV6_BOUND_IF */
600 };
601 
602 #define	TCPOPT_BOUNDIF		0x00000001	/* set IPV6_BOUND_IF */
603 #define	TCPOPT_RECVPKTINFO	0x00000002	/* set IPV6_RECVPKTINFO */
604 
605 /*
606  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
607  */
608 
609 #ifdef _BIG_ENDIAN
610 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
611 	(TCPOPT_TSTAMP << 8) | 10)
612 #else
613 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
614 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
615 #endif
616 
617 /*
618  * Flags returned from tcp_parse_options.
619  */
620 #define	TCP_OPT_MSS_PRESENT	1
621 #define	TCP_OPT_WSCALE_PRESENT	2
622 #define	TCP_OPT_TSTAMP_PRESENT	4
623 #define	TCP_OPT_SACK_OK_PRESENT	8
624 #define	TCP_OPT_SACK_PRESENT	16
625 
626 /* TCP option length */
627 #define	TCPOPT_NOP_LEN		1
628 #define	TCPOPT_MAXSEG_LEN	4
629 #define	TCPOPT_WS_LEN		3
630 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
631 #define	TCPOPT_TSTAMP_LEN	10
632 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
633 #define	TCPOPT_SACK_OK_LEN	2
634 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
635 #define	TCPOPT_REAL_SACK_LEN	4
636 #define	TCPOPT_MAX_SACK_LEN	36
637 #define	TCPOPT_HEADER_LEN	2
638 
639 /* TCP cwnd burst factor. */
640 #define	TCP_CWND_INFINITE	65535
641 #define	TCP_CWND_SS		3
642 #define	TCP_CWND_NORMAL		5
643 
644 /* Maximum TCP initial cwin (start/restart). */
645 #define	TCP_MAX_INIT_CWND	8
646 
647 /*
648  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
649  * either tcp_slow_start_initial or tcp_slow_start_after idle
650  * depending on the caller.  If the upper layer has not used the
651  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
652  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
653  * If the upper layer has changed set the tcp_init_cwnd, just use
654  * it to calculate the tcp_cwnd.
655  */
656 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
657 {									\
658 	if ((tcp)->tcp_init_cwnd == 0) {				\
659 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
660 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
661 	} else {							\
662 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
663 	}								\
664 	tcp->tcp_cwnd_cnt = 0;						\
665 }
666 
667 /* TCP Timer control structure */
668 typedef struct tcpt_s {
669 	pfv_t	tcpt_pfv;	/* The routine we are to call */
670 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
671 } tcpt_t;
672 
673 /*
674  * Functions called directly via squeue having a prototype of edesc_t.
675  */
676 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
677 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
678 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
679 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
680 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
681 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
682 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
683 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
684 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
685 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2);
686 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
687 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
688 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
689 
690 
691 /* Prototype for TCP functions */
692 static void	tcp_random_init(void);
693 int		tcp_random(void);
694 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
695 static int	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
696 		    tcp_t *eager);
697 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
698 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
699     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
700     boolean_t user_specified);
701 static void	tcp_closei_local(tcp_t *tcp);
702 static void	tcp_close_detached(tcp_t *tcp);
703 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
704 			mblk_t *idmp, mblk_t **defermp);
705 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
706 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
707 		    in_port_t dstport, uint_t srcid, cred_t *cr, pid_t pid);
708 static int 	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
709 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
710 		    uint32_t scope_id, cred_t *cr, pid_t pid);
711 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
712 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
713 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
714 static char	*tcp_display(tcp_t *tcp, char *, char);
715 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
716 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
717 static void	tcp_eager_unlink(tcp_t *tcp);
718 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
719 		    int unixerr);
720 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
721 		    int tlierr, int unixerr);
722 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
723 		    cred_t *cr);
724 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
725 		    char *value, caddr_t cp, cred_t *cr);
726 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
727 		    char *value, caddr_t cp, cred_t *cr);
728 static int	tcp_tpistate(tcp_t *tcp);
729 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
730     int caller_holds_lock);
731 static void	tcp_bind_hash_remove(tcp_t *tcp);
732 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
733 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
734 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
735 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
736 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
737 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
738 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
739 void		tcp_g_q_setup(tcp_stack_t *);
740 void		tcp_g_q_create(tcp_stack_t *);
741 void		tcp_g_q_destroy(tcp_stack_t *);
742 static int	tcp_header_init_ipv4(tcp_t *tcp);
743 static int	tcp_header_init_ipv6(tcp_t *tcp);
744 int		tcp_init(tcp_t *tcp, queue_t *q);
745 static int	tcp_init_values(tcp_t *tcp);
746 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
747 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
748 static void	tcp_ip_notify(tcp_t *tcp);
749 static mblk_t	*tcp_ire_mp(mblk_t **mpp);
750 static void	tcp_iss_init(tcp_t *tcp);
751 static void	tcp_keepalive_killer(void *arg);
752 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
753 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
754 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
755 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
756 static boolean_t tcp_allow_connopt_set(int level, int name);
757 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
758 int		tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
759 int		tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level,
760 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
761 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
762 		    mblk_t *mblk);
763 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
764 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
765 		    uchar_t *ptr, uint_t len);
766 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
767 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
768     tcp_stack_t *);
769 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
770 		    caddr_t cp, cred_t *cr);
771 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
772 		    caddr_t cp, cred_t *cr);
773 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
774 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
775 		    caddr_t cp, cred_t *cr);
776 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
777 static void	tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt);
778 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
779 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
780 static void	tcp_reinit(tcp_t *tcp);
781 static void	tcp_reinit_values(tcp_t *tcp);
782 
783 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
784 static uint_t	tcp_rcv_drain(tcp_t *tcp);
785 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
786 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
787 static void	tcp_ss_rexmit(tcp_t *tcp);
788 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
789 static void	tcp_process_options(tcp_t *, tcph_t *);
790 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
791 static void	tcp_rsrv(queue_t *q);
792 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
793 static int	tcp_snmp_state(tcp_t *tcp);
794 static void	tcp_timer(void *arg);
795 static void	tcp_timer_callback(void *);
796 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
797     boolean_t random);
798 static in_port_t tcp_get_next_priv_port(const tcp_t *);
799 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
800 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
801 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
802 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
803 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
804 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
805 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
806 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
807 		    const int num_sack_blk, int *usable, uint_t *snxt,
808 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
809 		    const int mdt_thres);
810 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
811 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
812 		    const int num_sack_blk, int *usable, uint_t *snxt,
813 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
814 		    const int mdt_thres);
815 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
816 		    int num_sack_blk);
817 static void	tcp_wsrv(queue_t *q);
818 static int	tcp_xmit_end(tcp_t *tcp);
819 static void	tcp_ack_timer(void *arg);
820 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
821 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
822 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
823 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
824 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
825 		    uint32_t ack, int ctl);
826 static int	setmaxps(queue_t *q, int maxpsz);
827 static void	tcp_set_rto(tcp_t *, time_t);
828 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
829 		    boolean_t, boolean_t);
830 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
831 		    boolean_t ipsec_mctl);
832 static int	tcp_build_hdrs(tcp_t *);
833 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
834 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
835 		    tcph_t *tcph);
836 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
837 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
838 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
839 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
840 		    const boolean_t, const uint32_t, const uint32_t,
841 		    const uint32_t, const uint32_t, tcp_stack_t *);
842 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
843 		    const uint_t, const uint_t, boolean_t *);
844 static mblk_t	*tcp_lso_info_mp(mblk_t *);
845 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
846 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
847 extern mblk_t	*tcp_timermp_alloc(int);
848 extern void	tcp_timermp_free(tcp_t *);
849 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
850 static void	tcp_stop_lingering(tcp_t *tcp);
851 static void	tcp_close_linger_timeout(void *arg);
852 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
853 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
854 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
855 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
856 static void	tcp_g_kstat_fini(kstat_t *);
857 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
858 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
859 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
860 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
861 static int	tcp_kstat_update(kstat_t *kp, int rw);
862 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
863 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
864 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
865 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
866 			tcph_t *tcph, mblk_t *idmp);
867 static int	tcp_squeue_switch(int);
868 
869 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
870 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
871 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
872 static int	tcp_tpi_close(queue_t *, int);
873 static int	tcp_tpi_close_accept(queue_t *);
874 
875 static void	tcp_squeue_add(squeue_t *);
876 static boolean_t tcp_zcopy_check(tcp_t *);
877 static void	tcp_zcopy_notify(tcp_t *);
878 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
879 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
880 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
881 
882 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
883 
884 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
885 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
886 
887 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
888 	    sock_upper_handle_t, cred_t *);
889 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
890 static int tcp_post_ip_bind(tcp_t *, mblk_t *, int, cred_t *, pid_t);
891 static int tcp_do_listen(conn_t *, struct sockaddr *, socklen_t, int, cred_t *,
892     boolean_t);
893 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
894     cred_t *, pid_t);
895 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
896     boolean_t);
897 static int tcp_do_unbind(conn_t *);
898 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
899     boolean_t);
900 
901 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_t *);
902 
903 /*
904  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
905  *
906  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
907  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
908  * (defined in tcp.h) needs to be filled in and passed into the kernel
909  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
910  * structure contains the four-tuple of a TCP connection and a range of TCP
911  * states (specified by ac_start and ac_end). The use of wildcard addresses
912  * and ports is allowed. Connections with a matching four tuple and a state
913  * within the specified range will be aborted. The valid states for the
914  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
915  * inclusive.
916  *
917  * An application which has its connection aborted by this ioctl will receive
918  * an error that is dependent on the connection state at the time of the abort.
919  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
920  * though a RST packet has been received.  If the connection state is equal to
921  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
922  * and all resources associated with the connection will be freed.
923  */
924 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
925 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
926 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
927 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
928 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
929 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
930     boolean_t, tcp_stack_t *);
931 
932 static struct module_info tcp_rinfo =  {
933 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
934 };
935 
936 static struct module_info tcp_winfo =  {
937 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
938 };
939 
940 /*
941  * Entry points for TCP as a device. The normal case which supports
942  * the TCP functionality.
943  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
944  */
945 struct qinit tcp_rinitv4 = {
946 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
947 };
948 
949 struct qinit tcp_rinitv6 = {
950 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
951 };
952 
953 struct qinit tcp_winit = {
954 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
955 };
956 
957 /* Initial entry point for TCP in socket mode. */
958 struct qinit tcp_sock_winit = {
959 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
960 };
961 
962 /* TCP entry point during fallback */
963 struct qinit tcp_fallback_sock_winit = {
964 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
965 };
966 
967 /*
968  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
969  * an accept. Avoid allocating data structures since eager has already
970  * been created.
971  */
972 struct qinit tcp_acceptor_rinit = {
973 	NULL, (pfi_t)tcp_rsrv, NULL, tcp_tpi_close_accept, NULL, &tcp_winfo
974 };
975 
976 struct qinit tcp_acceptor_winit = {
977 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
978 };
979 
980 /* For AF_INET aka /dev/tcp */
981 struct streamtab tcpinfov4 = {
982 	&tcp_rinitv4, &tcp_winit
983 };
984 
985 /* For AF_INET6 aka /dev/tcp6 */
986 struct streamtab tcpinfov6 = {
987 	&tcp_rinitv6, &tcp_winit
988 };
989 
990 sock_downcalls_t sock_tcp_downcalls;
991 
992 /*
993  * Have to ensure that tcp_g_q_close is not done by an
994  * interrupt thread.
995  */
996 static taskq_t *tcp_taskq;
997 
998 /* Setable only in /etc/system. Move to ndd? */
999 boolean_t tcp_icmp_source_quench = B_FALSE;
1000 
1001 /*
1002  * Following assumes TPI alignment requirements stay along 32 bit
1003  * boundaries
1004  */
1005 #define	ROUNDUP32(x) \
1006 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1007 
1008 /* Template for response to info request. */
1009 static struct T_info_ack tcp_g_t_info_ack = {
1010 	T_INFO_ACK,		/* PRIM_type */
1011 	0,			/* TSDU_size */
1012 	T_INFINITE,		/* ETSDU_size */
1013 	T_INVALID,		/* CDATA_size */
1014 	T_INVALID,		/* DDATA_size */
1015 	sizeof (sin_t),		/* ADDR_size */
1016 	0,			/* OPT_size - not initialized here */
1017 	TIDUSZ,			/* TIDU_size */
1018 	T_COTS_ORD,		/* SERV_type */
1019 	TCPS_IDLE,		/* CURRENT_state */
1020 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1021 };
1022 
1023 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1024 	T_INFO_ACK,		/* PRIM_type */
1025 	0,			/* TSDU_size */
1026 	T_INFINITE,		/* ETSDU_size */
1027 	T_INVALID,		/* CDATA_size */
1028 	T_INVALID,		/* DDATA_size */
1029 	sizeof (sin6_t),	/* ADDR_size */
1030 	0,			/* OPT_size - not initialized here */
1031 	TIDUSZ,		/* TIDU_size */
1032 	T_COTS_ORD,		/* SERV_type */
1033 	TCPS_IDLE,		/* CURRENT_state */
1034 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1035 };
1036 
1037 #define	MS	1L
1038 #define	SECONDS	(1000 * MS)
1039 #define	MINUTES	(60 * SECONDS)
1040 #define	HOURS	(60 * MINUTES)
1041 #define	DAYS	(24 * HOURS)
1042 
1043 #define	PARAM_MAX (~(uint32_t)0)
1044 
1045 /* Max size IP datagram is 64k - 1 */
1046 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1047 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1048 /* Max of the above */
1049 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1050 
1051 /* Largest TCP port number */
1052 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1053 
1054 /*
1055  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1056  * layer header.  It has to be a multiple of 4.
1057  */
1058 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1059 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1060 
1061 /*
1062  * All of these are alterable, within the min/max values given, at run time.
1063  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1064  * per the TCP spec.
1065  */
1066 /* BEGIN CSTYLED */
1067 static tcpparam_t	lcl_tcp_param_arr[] = {
1068  /*min		max		value		name */
1069  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1070  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1071  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1072  { 1,		1024,		1,		"tcp_conn_req_min" },
1073  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1074  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1075  { 0,		10,		0,		"tcp_debug" },
1076  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1077  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1078  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1079  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1080  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1081  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1082  { 1,		255,		64,		"tcp_ipv4_ttl"},
1083  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1084  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1085  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1086  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1087  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1088  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1089  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1090  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1091  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1092  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1093  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1094  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1095  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1096  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1097  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1098  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1099  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1100  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1101  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1102  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1103  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1104  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1105  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1106 /*
1107  * Question:  What default value should I set for tcp_strong_iss?
1108  */
1109  { 0,		2,		1,		"tcp_strong_iss"},
1110  { 0,		65536,		20,		"tcp_rtt_updates"},
1111  { 0,		1,		1,		"tcp_wscale_always"},
1112  { 0,		1,		0,		"tcp_tstamp_always"},
1113  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1114  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1115  { 0,		16,		2,		"tcp_deferred_acks_max"},
1116  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1117  { 1,		4,		4,		"tcp_slow_start_initial"},
1118  { 0,		2,		2,		"tcp_sack_permitted"},
1119  { 0,		1,		1,		"tcp_compression_enabled"},
1120  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1121  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1122  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1123  { 0,		1,		0,		"tcp_rev_src_routes"},
1124  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1125  { 0,		16,		8,		"tcp_local_dacks_max"},
1126  { 0,		2,		1,		"tcp_ecn_permitted"},
1127  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1128  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1129  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1130  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1131  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1132 };
1133 /* END CSTYLED */
1134 
1135 /*
1136  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1137  * each header fragment in the header buffer.  Each parameter value has
1138  * to be a multiple of 4 (32-bit aligned).
1139  */
1140 static tcpparam_t lcl_tcp_mdt_head_param =
1141 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1142 static tcpparam_t lcl_tcp_mdt_tail_param =
1143 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1144 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1145 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1146 
1147 /*
1148  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1149  * the maximum number of payload buffers associated per Multidata.
1150  */
1151 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1152 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1153 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1154 
1155 /* Round up the value to the nearest mss. */
1156 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1157 
1158 /*
1159  * Set ECN capable transport (ECT) code point in IP header.
1160  *
1161  * Note that there are 2 ECT code points '01' and '10', which are called
1162  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1163  * point ECT(0) for TCP as described in RFC 2481.
1164  */
1165 #define	SET_ECT(tcp, iph) \
1166 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1167 		/* We need to clear the code point first. */ \
1168 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1169 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1170 	} else { \
1171 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1172 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1173 	}
1174 
1175 /*
1176  * The format argument to pass to tcp_display().
1177  * DISP_PORT_ONLY means that the returned string has only port info.
1178  * DISP_ADDR_AND_PORT means that the returned string also contains the
1179  * remote and local IP address.
1180  */
1181 #define	DISP_PORT_ONLY		1
1182 #define	DISP_ADDR_AND_PORT	2
1183 
1184 #define	IS_VMLOANED_MBLK(mp) \
1185 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1186 
1187 
1188 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1189 boolean_t tcp_mdt_chain = B_TRUE;
1190 
1191 /*
1192  * MDT threshold in the form of effective send MSS multiplier; we take
1193  * the MDT path if the amount of unsent data exceeds the threshold value
1194  * (default threshold is 1*SMSS).
1195  */
1196 uint_t tcp_mdt_smss_threshold = 1;
1197 
1198 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1199 
1200 /*
1201  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1202  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1203  * determined dynamically during tcp_adapt_ire(), which is the default.
1204  */
1205 boolean_t tcp_static_maxpsz = B_FALSE;
1206 
1207 /* Setable in /etc/system */
1208 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1209 uint32_t tcp_random_anon_port = 1;
1210 
1211 /*
1212  * To reach to an eager in Q0 which can be dropped due to an incoming
1213  * new SYN request when Q0 is full, a new doubly linked list is
1214  * introduced. This list allows to select an eager from Q0 in O(1) time.
1215  * This is needed to avoid spending too much time walking through the
1216  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1217  * this new list has to be a member of Q0.
1218  * This list is headed by listener's tcp_t. When the list is empty,
1219  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1220  * of listener's tcp_t point to listener's tcp_t itself.
1221  *
1222  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1223  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1224  * These macros do not affect the eager's membership to Q0.
1225  */
1226 
1227 
1228 #define	MAKE_DROPPABLE(listener, eager)					\
1229 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1230 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1231 		    = (eager);						\
1232 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1233 		(eager)->tcp_eager_next_drop_q0 =			\
1234 		    (listener)->tcp_eager_next_drop_q0;			\
1235 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1236 	}
1237 
1238 #define	MAKE_UNDROPPABLE(eager)						\
1239 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1240 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1241 		    = (eager)->tcp_eager_prev_drop_q0;			\
1242 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1243 		    = (eager)->tcp_eager_next_drop_q0;			\
1244 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1245 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1246 	}
1247 
1248 /*
1249  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1250  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1251  * data, TCP will not respond with an ACK.  RFC 793 requires that
1252  * TCP responds with an ACK for such a bogus ACK.  By not following
1253  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1254  * an attacker successfully spoofs an acceptable segment to our
1255  * peer; or when our peer is "confused."
1256  */
1257 uint32_t tcp_drop_ack_unsent_cnt = 10;
1258 
1259 /*
1260  * Hook functions to enable cluster networking
1261  * On non-clustered systems these vectors must always be NULL.
1262  */
1263 
1264 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1265 			    sa_family_t addr_family, uint8_t *laddrp,
1266 			    in_port_t lport, void *args) = NULL;
1267 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1268 			    sa_family_t addr_family, uint8_t *laddrp,
1269 			    in_port_t lport, void *args) = NULL;
1270 
1271 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1272 			    boolean_t is_outgoing,
1273 			    sa_family_t addr_family,
1274 			    uint8_t *laddrp, in_port_t lport,
1275 			    uint8_t *faddrp, in_port_t fport,
1276 			    void *args) = NULL;
1277 
1278 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1279 			    sa_family_t addr_family, uint8_t *laddrp,
1280 			    in_port_t lport, uint8_t *faddrp,
1281 			    in_port_t fport, void *args) = NULL;
1282 
1283 /*
1284  * The following are defined in ip.c
1285  */
1286 extern int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
1287 			    sa_family_t addr_family, uint8_t *laddrp,
1288 			    void *args);
1289 extern uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
1290 			    sa_family_t addr_family, uint8_t *laddrp,
1291 			    uint8_t *faddrp, void *args);
1292 
1293 
1294 /*
1295  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1296  */
1297 #define	CL_INET_CONNECT(connp, tcp, is_outgoing, err) {		\
1298 	(err) = 0;						\
1299 	if (cl_inet_connect2 != NULL) {				\
1300 		/*						\
1301 		 * Running in cluster mode - register active connection	\
1302 		 * information						\
1303 		 */							\
1304 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1305 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1306 				(err) = (*cl_inet_connect2)(		\
1307 				    (connp)->conn_netstack->netstack_stackid,\
1308 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1309 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1310 				    (in_port_t)(tcp)->tcp_lport,	\
1311 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1312 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1313 			}						\
1314 		} else {						\
1315 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1316 			    &(tcp)->tcp_ip6h->ip6_src)) {		\
1317 				(err) = (*cl_inet_connect2)(		\
1318 				    (connp)->conn_netstack->netstack_stackid,\
1319 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1320 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1321 				    (in_port_t)(tcp)->tcp_lport,	\
1322 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1323 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1324 			}						\
1325 		}							\
1326 	}								\
1327 }
1328 
1329 #define	CL_INET_DISCONNECT(connp, tcp)	{				\
1330 	if (cl_inet_disconnect != NULL) {				\
1331 		/*							\
1332 		 * Running in cluster mode - deregister active		\
1333 		 * connection information				\
1334 		 */							\
1335 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1336 			if ((tcp)->tcp_ip_src != 0) {			\
1337 				(*cl_inet_disconnect)(			\
1338 				    (connp)->conn_netstack->netstack_stackid,\
1339 				    IPPROTO_TCP, AF_INET,		\
1340 				    (uint8_t *)(&((tcp)->tcp_ip_src)),	\
1341 				    (in_port_t)(tcp)->tcp_lport,	\
1342 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1343 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1344 			}						\
1345 		} else {						\
1346 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1347 			    &(tcp)->tcp_ip_src_v6)) {			\
1348 				(*cl_inet_disconnect)(			\
1349 				    (connp)->conn_netstack->netstack_stackid,\
1350 				    IPPROTO_TCP, AF_INET6,		\
1351 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1352 				    (in_port_t)(tcp)->tcp_lport,	\
1353 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1354 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1355 			}						\
1356 		}							\
1357 	}								\
1358 }
1359 
1360 /*
1361  * Cluster networking hook for traversing current connection list.
1362  * This routine is used to extract the current list of live connections
1363  * which must continue to to be dispatched to this node.
1364  */
1365 int cl_tcp_walk_list(netstackid_t stack_id,
1366     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1367 
1368 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1369     void *arg, tcp_stack_t *tcps);
1370 
1371 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1372 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1373 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1374 	    ip6_t *, ip6h, int, 0);
1375 
1376 /*
1377  * Figure out the value of window scale opton.  Note that the rwnd is
1378  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1379  * We cannot find the scale value and then do a round up of tcp_rwnd
1380  * because the scale value may not be correct after that.
1381  *
1382  * Set the compiler flag to make this function inline.
1383  */
1384 static void
1385 tcp_set_ws_value(tcp_t *tcp)
1386 {
1387 	int i;
1388 	uint32_t rwnd = tcp->tcp_rwnd;
1389 
1390 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1391 	    i++, rwnd >>= 1)
1392 		;
1393 	tcp->tcp_rcv_ws = i;
1394 }
1395 
1396 /*
1397  * Remove a connection from the list of detached TIME_WAIT connections.
1398  * It returns B_FALSE if it can't remove the connection from the list
1399  * as the connection has already been removed from the list due to an
1400  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1401  */
1402 static boolean_t
1403 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1404 {
1405 	boolean_t	locked = B_FALSE;
1406 
1407 	if (tcp_time_wait == NULL) {
1408 		tcp_time_wait = *((tcp_squeue_priv_t **)
1409 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1410 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1411 		locked = B_TRUE;
1412 	} else {
1413 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1414 	}
1415 
1416 	if (tcp->tcp_time_wait_expire == 0) {
1417 		ASSERT(tcp->tcp_time_wait_next == NULL);
1418 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1419 		if (locked)
1420 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1421 		return (B_FALSE);
1422 	}
1423 	ASSERT(TCP_IS_DETACHED(tcp));
1424 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1425 
1426 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1427 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1428 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1429 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1430 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1431 			    NULL;
1432 		} else {
1433 			tcp_time_wait->tcp_time_wait_tail = NULL;
1434 		}
1435 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1436 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1437 		ASSERT(tcp->tcp_time_wait_next == NULL);
1438 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1439 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1440 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1441 	} else {
1442 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1443 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1444 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1445 		    tcp->tcp_time_wait_next;
1446 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1447 		    tcp->tcp_time_wait_prev;
1448 	}
1449 	tcp->tcp_time_wait_next = NULL;
1450 	tcp->tcp_time_wait_prev = NULL;
1451 	tcp->tcp_time_wait_expire = 0;
1452 
1453 	if (locked)
1454 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1455 	return (B_TRUE);
1456 }
1457 
1458 /*
1459  * Add a connection to the list of detached TIME_WAIT connections
1460  * and set its time to expire.
1461  */
1462 static void
1463 tcp_time_wait_append(tcp_t *tcp)
1464 {
1465 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1466 	tcp_squeue_priv_t *tcp_time_wait =
1467 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1468 	    SQPRIVATE_TCP));
1469 
1470 	tcp_timers_stop(tcp);
1471 
1472 	/* Freed above */
1473 	ASSERT(tcp->tcp_timer_tid == 0);
1474 	ASSERT(tcp->tcp_ack_tid == 0);
1475 
1476 	/* must have happened at the time of detaching the tcp */
1477 	ASSERT(tcp->tcp_ptpahn == NULL);
1478 	ASSERT(tcp->tcp_flow_stopped == 0);
1479 	ASSERT(tcp->tcp_time_wait_next == NULL);
1480 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1481 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1482 	ASSERT(tcp->tcp_listener == NULL);
1483 
1484 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1485 	/*
1486 	 * The value computed below in tcp->tcp_time_wait_expire may
1487 	 * appear negative or wrap around. That is ok since our
1488 	 * interest is only in the difference between the current lbolt
1489 	 * value and tcp->tcp_time_wait_expire. But the value should not
1490 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1491 	 * The corresponding comparison in tcp_time_wait_collector() uses
1492 	 * modular arithmetic.
1493 	 */
1494 	tcp->tcp_time_wait_expire +=
1495 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1496 	if (tcp->tcp_time_wait_expire == 0)
1497 		tcp->tcp_time_wait_expire = 1;
1498 
1499 	ASSERT(TCP_IS_DETACHED(tcp));
1500 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1501 	ASSERT(tcp->tcp_time_wait_next == NULL);
1502 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1503 	TCP_DBGSTAT(tcps, tcp_time_wait);
1504 
1505 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1506 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1507 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1508 		tcp_time_wait->tcp_time_wait_head = tcp;
1509 	} else {
1510 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1511 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1512 		    TCPS_TIME_WAIT);
1513 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1514 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1515 	}
1516 	tcp_time_wait->tcp_time_wait_tail = tcp;
1517 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1518 }
1519 
1520 /* ARGSUSED */
1521 void
1522 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1523 {
1524 	conn_t	*connp = (conn_t *)arg;
1525 	tcp_t	*tcp = connp->conn_tcp;
1526 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1527 
1528 	ASSERT(tcp != NULL);
1529 	if (tcp->tcp_state == TCPS_CLOSED) {
1530 		return;
1531 	}
1532 
1533 	ASSERT((tcp->tcp_family == AF_INET &&
1534 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1535 	    (tcp->tcp_family == AF_INET6 &&
1536 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1537 	    tcp->tcp_ipversion == IPV6_VERSION)));
1538 	ASSERT(!tcp->tcp_listener);
1539 
1540 	TCP_STAT(tcps, tcp_time_wait_reap);
1541 	ASSERT(TCP_IS_DETACHED(tcp));
1542 
1543 	/*
1544 	 * Because they have no upstream client to rebind or tcp_close()
1545 	 * them later, we axe the connection here and now.
1546 	 */
1547 	tcp_close_detached(tcp);
1548 }
1549 
1550 /*
1551  * Remove cached/latched IPsec references.
1552  */
1553 void
1554 tcp_ipsec_cleanup(tcp_t *tcp)
1555 {
1556 	conn_t		*connp = tcp->tcp_connp;
1557 
1558 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1559 
1560 	if (connp->conn_latch != NULL) {
1561 		IPLATCH_REFRELE(connp->conn_latch,
1562 		    connp->conn_netstack);
1563 		connp->conn_latch = NULL;
1564 	}
1565 	if (connp->conn_policy != NULL) {
1566 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1567 		connp->conn_policy = NULL;
1568 	}
1569 }
1570 
1571 /*
1572  * Cleaup before placing on free list.
1573  * Disassociate from the netstack/tcp_stack_t since the freelist
1574  * is per squeue and not per netstack.
1575  */
1576 void
1577 tcp_cleanup(tcp_t *tcp)
1578 {
1579 	mblk_t		*mp;
1580 	char		*tcp_iphc;
1581 	int		tcp_iphc_len;
1582 	int		tcp_hdr_grown;
1583 	tcp_sack_info_t	*tcp_sack_info;
1584 	conn_t		*connp = tcp->tcp_connp;
1585 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1586 	netstack_t	*ns = tcps->tcps_netstack;
1587 	mblk_t		*tcp_rsrv_mp;
1588 
1589 	tcp_bind_hash_remove(tcp);
1590 
1591 	/* Cleanup that which needs the netstack first */
1592 	tcp_ipsec_cleanup(tcp);
1593 
1594 	tcp_free(tcp);
1595 
1596 	/* Release any SSL context */
1597 	if (tcp->tcp_kssl_ent != NULL) {
1598 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1599 		tcp->tcp_kssl_ent = NULL;
1600 	}
1601 
1602 	if (tcp->tcp_kssl_ctx != NULL) {
1603 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1604 		tcp->tcp_kssl_ctx = NULL;
1605 	}
1606 	tcp->tcp_kssl_pending = B_FALSE;
1607 
1608 	conn_delete_ire(connp, NULL);
1609 
1610 	/*
1611 	 * Since we will bzero the entire structure, we need to
1612 	 * remove it and reinsert it in global hash list. We
1613 	 * know the walkers can't get to this conn because we
1614 	 * had set CONDEMNED flag earlier and checked reference
1615 	 * under conn_lock so walker won't pick it and when we
1616 	 * go the ipcl_globalhash_remove() below, no walker
1617 	 * can get to it.
1618 	 */
1619 	ipcl_globalhash_remove(connp);
1620 
1621 	/*
1622 	 * Now it is safe to decrement the reference counts.
1623 	 * This might be the last reference on the netstack and TCPS
1624 	 * in which case it will cause the tcp_g_q_close and
1625 	 * the freeing of the IP Instance.
1626 	 */
1627 	connp->conn_netstack = NULL;
1628 	netstack_rele(ns);
1629 	ASSERT(tcps != NULL);
1630 	tcp->tcp_tcps = NULL;
1631 	TCPS_REFRELE(tcps);
1632 
1633 	/* Save some state */
1634 	mp = tcp->tcp_timercache;
1635 
1636 	tcp_sack_info = tcp->tcp_sack_info;
1637 	tcp_iphc = tcp->tcp_iphc;
1638 	tcp_iphc_len = tcp->tcp_iphc_len;
1639 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1640 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1641 
1642 	if (connp->conn_cred != NULL) {
1643 		crfree(connp->conn_cred);
1644 		connp->conn_cred = NULL;
1645 	}
1646 	if (connp->conn_effective_cred != NULL) {
1647 		crfree(connp->conn_effective_cred);
1648 		connp->conn_effective_cred = NULL;
1649 	}
1650 	ipcl_conn_cleanup(connp);
1651 	connp->conn_flags = IPCL_TCPCONN;
1652 	bzero(tcp, sizeof (tcp_t));
1653 
1654 	/* restore the state */
1655 	tcp->tcp_timercache = mp;
1656 
1657 	tcp->tcp_sack_info = tcp_sack_info;
1658 	tcp->tcp_iphc = tcp_iphc;
1659 	tcp->tcp_iphc_len = tcp_iphc_len;
1660 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1661 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1662 
1663 	tcp->tcp_connp = connp;
1664 
1665 	ASSERT(connp->conn_tcp == tcp);
1666 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1667 	connp->conn_state_flags = CONN_INCIPIENT;
1668 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1669 	ASSERT(connp->conn_ref == 1);
1670 }
1671 
1672 /*
1673  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1674  * is done forwards from the head.
1675  * This walks all stack instances since
1676  * tcp_time_wait remains global across all stacks.
1677  */
1678 /* ARGSUSED */
1679 void
1680 tcp_time_wait_collector(void *arg)
1681 {
1682 	tcp_t *tcp;
1683 	clock_t now;
1684 	mblk_t *mp;
1685 	conn_t *connp;
1686 	kmutex_t *lock;
1687 	boolean_t removed;
1688 
1689 	squeue_t *sqp = (squeue_t *)arg;
1690 	tcp_squeue_priv_t *tcp_time_wait =
1691 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1692 
1693 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1694 	tcp_time_wait->tcp_time_wait_tid = 0;
1695 
1696 	if (tcp_time_wait->tcp_free_list != NULL &&
1697 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1698 		TCP_G_STAT(tcp_freelist_cleanup);
1699 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1700 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1701 			tcp->tcp_time_wait_next = NULL;
1702 			tcp_time_wait->tcp_free_list_cnt--;
1703 			ASSERT(tcp->tcp_tcps == NULL);
1704 			CONN_DEC_REF(tcp->tcp_connp);
1705 		}
1706 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1707 	}
1708 
1709 	/*
1710 	 * In order to reap time waits reliably, we should use a
1711 	 * source of time that is not adjustable by the user -- hence
1712 	 * the call to ddi_get_lbolt().
1713 	 */
1714 	now = ddi_get_lbolt();
1715 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1716 		/*
1717 		 * Compare times using modular arithmetic, since
1718 		 * lbolt can wrapover.
1719 		 */
1720 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1721 			break;
1722 		}
1723 
1724 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1725 		ASSERT(removed);
1726 
1727 		connp = tcp->tcp_connp;
1728 		ASSERT(connp->conn_fanout != NULL);
1729 		lock = &connp->conn_fanout->connf_lock;
1730 		/*
1731 		 * This is essentially a TW reclaim fast path optimization for
1732 		 * performance where the timewait collector checks under the
1733 		 * fanout lock (so that no one else can get access to the
1734 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1735 		 * the classifier hash list. If ref count is indeed 2, we can
1736 		 * just remove the conn under the fanout lock and avoid
1737 		 * cleaning up the conn under the squeue, provided that
1738 		 * clustering callbacks are not enabled. If clustering is
1739 		 * enabled, we need to make the clustering callback before
1740 		 * setting the CONDEMNED flag and after dropping all locks and
1741 		 * so we forego this optimization and fall back to the slow
1742 		 * path. Also please see the comments in tcp_closei_local
1743 		 * regarding the refcnt logic.
1744 		 *
1745 		 * Since we are holding the tcp_time_wait_lock, its better
1746 		 * not to block on the fanout_lock because other connections
1747 		 * can't add themselves to time_wait list. So we do a
1748 		 * tryenter instead of mutex_enter.
1749 		 */
1750 		if (mutex_tryenter(lock)) {
1751 			mutex_enter(&connp->conn_lock);
1752 			if ((connp->conn_ref == 2) &&
1753 			    (cl_inet_disconnect == NULL)) {
1754 				ipcl_hash_remove_locked(connp,
1755 				    connp->conn_fanout);
1756 				/*
1757 				 * Set the CONDEMNED flag now itself so that
1758 				 * the refcnt cannot increase due to any
1759 				 * walker. But we have still not cleaned up
1760 				 * conn_ire_cache. This is still ok since
1761 				 * we are going to clean it up in tcp_cleanup
1762 				 * immediately and any interface unplumb
1763 				 * thread will wait till the ire is blown away
1764 				 */
1765 				connp->conn_state_flags |= CONN_CONDEMNED;
1766 				mutex_exit(lock);
1767 				mutex_exit(&connp->conn_lock);
1768 				if (tcp_time_wait->tcp_free_list_cnt <
1769 				    tcp_free_list_max_cnt) {
1770 					/* Add to head of tcp_free_list */
1771 					mutex_exit(
1772 					    &tcp_time_wait->tcp_time_wait_lock);
1773 					tcp_cleanup(tcp);
1774 					ASSERT(connp->conn_latch == NULL);
1775 					ASSERT(connp->conn_policy == NULL);
1776 					ASSERT(tcp->tcp_tcps == NULL);
1777 					ASSERT(connp->conn_netstack == NULL);
1778 
1779 					mutex_enter(
1780 					    &tcp_time_wait->tcp_time_wait_lock);
1781 					tcp->tcp_time_wait_next =
1782 					    tcp_time_wait->tcp_free_list;
1783 					tcp_time_wait->tcp_free_list = tcp;
1784 					tcp_time_wait->tcp_free_list_cnt++;
1785 					continue;
1786 				} else {
1787 					/* Do not add to tcp_free_list */
1788 					mutex_exit(
1789 					    &tcp_time_wait->tcp_time_wait_lock);
1790 					tcp_bind_hash_remove(tcp);
1791 					conn_delete_ire(tcp->tcp_connp, NULL);
1792 					tcp_ipsec_cleanup(tcp);
1793 					CONN_DEC_REF(tcp->tcp_connp);
1794 				}
1795 			} else {
1796 				CONN_INC_REF_LOCKED(connp);
1797 				mutex_exit(lock);
1798 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1799 				mutex_exit(&connp->conn_lock);
1800 				/*
1801 				 * We can reuse the closemp here since conn has
1802 				 * detached (otherwise we wouldn't even be in
1803 				 * time_wait list). tcp_closemp_used can safely
1804 				 * be changed without taking a lock as no other
1805 				 * thread can concurrently access it at this
1806 				 * point in the connection lifecycle.
1807 				 */
1808 
1809 				if (tcp->tcp_closemp.b_prev == NULL)
1810 					tcp->tcp_closemp_used = B_TRUE;
1811 				else
1812 					cmn_err(CE_PANIC,
1813 					    "tcp_timewait_collector: "
1814 					    "concurrent use of tcp_closemp: "
1815 					    "connp %p tcp %p\n", (void *)connp,
1816 					    (void *)tcp);
1817 
1818 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1819 				mp = &tcp->tcp_closemp;
1820 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1821 				    tcp_timewait_output, connp,
1822 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1823 			}
1824 		} else {
1825 			mutex_enter(&connp->conn_lock);
1826 			CONN_INC_REF_LOCKED(connp);
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). tcp_closemp_used can safely
1833 			 * be changed without taking a lock as no other
1834 			 * thread can concurrently access it at this
1835 			 * point in the connection lifecycle.
1836 			 */
1837 
1838 			if (tcp->tcp_closemp.b_prev == NULL)
1839 				tcp->tcp_closemp_used = B_TRUE;
1840 			else
1841 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1842 				    "concurrent use of tcp_closemp: "
1843 				    "connp %p tcp %p\n", (void *)connp,
1844 				    (void *)tcp);
1845 
1846 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1847 			mp = &tcp->tcp_closemp;
1848 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1849 			    tcp_timewait_output, connp,
1850 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1851 		}
1852 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1853 	}
1854 
1855 	if (tcp_time_wait->tcp_free_list != NULL)
1856 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1857 
1858 	tcp_time_wait->tcp_time_wait_tid =
1859 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1860 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1861 	    CALLOUT_FLAG_ROUNDUP);
1862 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1863 }
1864 
1865 /*
1866  * Reply to a clients T_CONN_RES TPI message. This function
1867  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1868  * on the acceptor STREAM and processed in tcp_wput_accept().
1869  * Read the block comment on top of tcp_conn_request().
1870  */
1871 static void
1872 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1873 {
1874 	tcp_t	*acceptor;
1875 	tcp_t	*eager;
1876 	tcp_t   *tcp;
1877 	struct T_conn_res	*tcr;
1878 	t_uscalar_t	acceptor_id;
1879 	t_scalar_t	seqnum;
1880 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1881 	struct tcp_options *tcpopt;
1882 	mblk_t	*ok_mp;
1883 	mblk_t	*mp1;
1884 	tcp_stack_t	*tcps = listener->tcp_tcps;
1885 	int	error;
1886 
1887 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1888 		tcp_err_ack(listener, mp, TPROTO, 0);
1889 		return;
1890 	}
1891 	tcr = (struct T_conn_res *)mp->b_rptr;
1892 
1893 	/*
1894 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1895 	 * read side queue of the streams device underneath us i.e. the
1896 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1897 	 * look it up in the queue_hash.  Under LP64 it sends down the
1898 	 * minor_t of the accepting endpoint.
1899 	 *
1900 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1901 	 * fanout hash lock is held.
1902 	 * This prevents any thread from entering the acceptor queue from
1903 	 * below (since it has not been hard bound yet i.e. any inbound
1904 	 * packets will arrive on the listener or default tcp queue and
1905 	 * go through tcp_lookup).
1906 	 * The CONN_INC_REF will prevent the acceptor from closing.
1907 	 *
1908 	 * XXX It is still possible for a tli application to send down data
1909 	 * on the accepting stream while another thread calls t_accept.
1910 	 * This should not be a problem for well-behaved applications since
1911 	 * the T_OK_ACK is sent after the queue swapping is completed.
1912 	 *
1913 	 * If the accepting fd is the same as the listening fd, avoid
1914 	 * queue hash lookup since that will return an eager listener in a
1915 	 * already established state.
1916 	 */
1917 	acceptor_id = tcr->ACCEPTOR_id;
1918 	mutex_enter(&listener->tcp_eager_lock);
1919 	if (listener->tcp_acceptor_id == acceptor_id) {
1920 		eager = listener->tcp_eager_next_q;
1921 		/* only count how many T_CONN_INDs so don't count q0 */
1922 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1923 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1924 			mutex_exit(&listener->tcp_eager_lock);
1925 			tcp_err_ack(listener, mp, TBADF, 0);
1926 			return;
1927 		}
1928 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1929 			/* Throw away all the eagers on q0. */
1930 			tcp_eager_cleanup(listener, 1);
1931 		}
1932 		if (listener->tcp_syn_defense) {
1933 			listener->tcp_syn_defense = B_FALSE;
1934 			if (listener->tcp_ip_addr_cache != NULL) {
1935 				kmem_free(listener->tcp_ip_addr_cache,
1936 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1937 				listener->tcp_ip_addr_cache = NULL;
1938 			}
1939 		}
1940 		/*
1941 		 * Transfer tcp_conn_req_max to the eager so that when
1942 		 * a disconnect occurs we can revert the endpoint to the
1943 		 * listen state.
1944 		 */
1945 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1946 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1947 		/*
1948 		 * Get a reference on the acceptor just like the
1949 		 * tcp_acceptor_hash_lookup below.
1950 		 */
1951 		acceptor = listener;
1952 		CONN_INC_REF(acceptor->tcp_connp);
1953 	} else {
1954 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1955 		if (acceptor == NULL) {
1956 			if (listener->tcp_debug) {
1957 				(void) strlog(TCP_MOD_ID, 0, 1,
1958 				    SL_ERROR|SL_TRACE,
1959 				    "tcp_accept: did not find acceptor 0x%x\n",
1960 				    acceptor_id);
1961 			}
1962 			mutex_exit(&listener->tcp_eager_lock);
1963 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1964 			return;
1965 		}
1966 		/*
1967 		 * Verify acceptor state. The acceptable states for an acceptor
1968 		 * include TCPS_IDLE and TCPS_BOUND.
1969 		 */
1970 		switch (acceptor->tcp_state) {
1971 		case TCPS_IDLE:
1972 			/* FALLTHRU */
1973 		case TCPS_BOUND:
1974 			break;
1975 		default:
1976 			CONN_DEC_REF(acceptor->tcp_connp);
1977 			mutex_exit(&listener->tcp_eager_lock);
1978 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
1979 			return;
1980 		}
1981 	}
1982 
1983 	/* The listener must be in TCPS_LISTEN */
1984 	if (listener->tcp_state != TCPS_LISTEN) {
1985 		CONN_DEC_REF(acceptor->tcp_connp);
1986 		mutex_exit(&listener->tcp_eager_lock);
1987 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
1988 		return;
1989 	}
1990 
1991 	/*
1992 	 * Rendezvous with an eager connection request packet hanging off
1993 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
1994 	 * tcp structure when the connection packet arrived in
1995 	 * tcp_conn_request().
1996 	 */
1997 	seqnum = tcr->SEQ_number;
1998 	eager = listener;
1999 	do {
2000 		eager = eager->tcp_eager_next_q;
2001 		if (eager == NULL) {
2002 			CONN_DEC_REF(acceptor->tcp_connp);
2003 			mutex_exit(&listener->tcp_eager_lock);
2004 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2005 			return;
2006 		}
2007 	} while (eager->tcp_conn_req_seqnum != seqnum);
2008 	mutex_exit(&listener->tcp_eager_lock);
2009 
2010 	/*
2011 	 * At this point, both acceptor and listener have 2 ref
2012 	 * that they begin with. Acceptor has one additional ref
2013 	 * we placed in lookup while listener has 3 additional
2014 	 * ref for being behind the squeue (tcp_accept() is
2015 	 * done on listener's squeue); being in classifier hash;
2016 	 * and eager's ref on listener.
2017 	 */
2018 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2019 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2020 
2021 	/*
2022 	 * The eager at this point is set in its own squeue and
2023 	 * could easily have been killed (tcp_accept_finish will
2024 	 * deal with that) because of a TH_RST so we can only
2025 	 * ASSERT for a single ref.
2026 	 */
2027 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2028 
2029 	/* Pre allocate the stroptions mblk also */
2030 	opt_mp = allocb(MAX(sizeof (struct tcp_options),
2031 	    sizeof (struct T_conn_res)), BPRI_HI);
2032 	if (opt_mp == NULL) {
2033 		CONN_DEC_REF(acceptor->tcp_connp);
2034 		CONN_DEC_REF(eager->tcp_connp);
2035 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2036 		return;
2037 	}
2038 	DB_TYPE(opt_mp) = M_SETOPTS;
2039 	opt_mp->b_wptr += sizeof (struct tcp_options);
2040 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
2041 	tcpopt->to_flags = 0;
2042 
2043 	/*
2044 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2045 	 * from listener to acceptor.
2046 	 */
2047 	if (listener->tcp_bound_if != 0) {
2048 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
2049 		tcpopt->to_boundif = listener->tcp_bound_if;
2050 	}
2051 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2052 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
2053 	}
2054 
2055 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2056 	if ((mp1 = copymsg(mp)) == NULL) {
2057 		CONN_DEC_REF(acceptor->tcp_connp);
2058 		CONN_DEC_REF(eager->tcp_connp);
2059 		freemsg(opt_mp);
2060 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2061 		return;
2062 	}
2063 
2064 	tcr = (struct T_conn_res *)mp1->b_rptr;
2065 
2066 	/*
2067 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2068 	 * which allocates a larger mblk and appends the new
2069 	 * local address to the ok_ack.  The address is copied by
2070 	 * soaccept() for getsockname().
2071 	 */
2072 	{
2073 		int extra;
2074 
2075 		extra = (eager->tcp_family == AF_INET) ?
2076 		    sizeof (sin_t) : sizeof (sin6_t);
2077 
2078 		/*
2079 		 * Try to re-use mp, if possible.  Otherwise, allocate
2080 		 * an mblk and return it as ok_mp.  In any case, mp
2081 		 * is no longer usable upon return.
2082 		 */
2083 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2084 			CONN_DEC_REF(acceptor->tcp_connp);
2085 			CONN_DEC_REF(eager->tcp_connp);
2086 			freemsg(opt_mp);
2087 			/* Original mp has been freed by now, so use mp1 */
2088 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2089 			return;
2090 		}
2091 
2092 		mp = NULL;	/* We should never use mp after this point */
2093 
2094 		switch (extra) {
2095 		case sizeof (sin_t): {
2096 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2097 
2098 				ok_mp->b_wptr += extra;
2099 				sin->sin_family = AF_INET;
2100 				sin->sin_port = eager->tcp_lport;
2101 				sin->sin_addr.s_addr =
2102 				    eager->tcp_ipha->ipha_src;
2103 				break;
2104 			}
2105 		case sizeof (sin6_t): {
2106 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2107 
2108 				ok_mp->b_wptr += extra;
2109 				sin6->sin6_family = AF_INET6;
2110 				sin6->sin6_port = eager->tcp_lport;
2111 				if (eager->tcp_ipversion == IPV4_VERSION) {
2112 					sin6->sin6_flowinfo = 0;
2113 					IN6_IPADDR_TO_V4MAPPED(
2114 					    eager->tcp_ipha->ipha_src,
2115 					    &sin6->sin6_addr);
2116 				} else {
2117 					ASSERT(eager->tcp_ip6h != NULL);
2118 					sin6->sin6_flowinfo =
2119 					    eager->tcp_ip6h->ip6_vcf &
2120 					    ~IPV6_VERS_AND_FLOW_MASK;
2121 					sin6->sin6_addr =
2122 					    eager->tcp_ip6h->ip6_src;
2123 				}
2124 				sin6->sin6_scope_id = 0;
2125 				sin6->__sin6_src_id = 0;
2126 				break;
2127 			}
2128 		default:
2129 			break;
2130 		}
2131 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2132 	}
2133 
2134 	/*
2135 	 * If there are no options we know that the T_CONN_RES will
2136 	 * succeed. However, we can't send the T_OK_ACK upstream until
2137 	 * the tcp_accept_swap is done since it would be dangerous to
2138 	 * let the application start using the new fd prior to the swap.
2139 	 */
2140 	error = tcp_accept_swap(listener, acceptor, eager);
2141 	if (error != 0) {
2142 		CONN_DEC_REF(acceptor->tcp_connp);
2143 		CONN_DEC_REF(eager->tcp_connp);
2144 		freemsg(ok_mp);
2145 		/* Original mp has been freed by now, so use mp1 */
2146 		tcp_err_ack(listener, mp1, TSYSERR, error);
2147 		return;
2148 	}
2149 
2150 	/*
2151 	 * tcp_accept_swap unlinks eager from listener but does not drop
2152 	 * the eager's reference on the listener.
2153 	 */
2154 	ASSERT(eager->tcp_listener == NULL);
2155 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2156 
2157 	/*
2158 	 * The eager is now associated with its own queue. Insert in
2159 	 * the hash so that the connection can be reused for a future
2160 	 * T_CONN_RES.
2161 	 */
2162 	tcp_acceptor_hash_insert(acceptor_id, eager);
2163 
2164 	/*
2165 	 * We now do the processing of options with T_CONN_RES.
2166 	 * We delay till now since we wanted to have queue to pass to
2167 	 * option processing routines that points back to the right
2168 	 * instance structure which does not happen until after
2169 	 * tcp_accept_swap().
2170 	 *
2171 	 * Note:
2172 	 * The sanity of the logic here assumes that whatever options
2173 	 * are appropriate to inherit from listner=>eager are done
2174 	 * before this point, and whatever were to be overridden (or not)
2175 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2176 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2177 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2178 	 * This may not be true at this point in time but can be fixed
2179 	 * independently. This option processing code starts with
2180 	 * the instantiated acceptor instance and the final queue at
2181 	 * this point.
2182 	 */
2183 
2184 	if (tcr->OPT_length != 0) {
2185 		/* Options to process */
2186 		int t_error = 0;
2187 		int sys_error = 0;
2188 		int do_disconnect = 0;
2189 
2190 		if (tcp_conprim_opt_process(eager, mp1,
2191 		    &do_disconnect, &t_error, &sys_error) < 0) {
2192 			eager->tcp_accept_error = 1;
2193 			if (do_disconnect) {
2194 				/*
2195 				 * An option failed which does not allow
2196 				 * connection to be accepted.
2197 				 *
2198 				 * We allow T_CONN_RES to succeed and
2199 				 * put a T_DISCON_IND on the eager queue.
2200 				 */
2201 				ASSERT(t_error == 0 && sys_error == 0);
2202 				eager->tcp_send_discon_ind = 1;
2203 			} else {
2204 				ASSERT(t_error != 0);
2205 				freemsg(ok_mp);
2206 				/*
2207 				 * Original mp was either freed or set
2208 				 * to ok_mp above, so use mp1 instead.
2209 				 */
2210 				tcp_err_ack(listener, mp1, t_error, sys_error);
2211 				goto finish;
2212 			}
2213 		}
2214 		/*
2215 		 * Most likely success in setting options (except if
2216 		 * eager->tcp_send_discon_ind set).
2217 		 * mp1 option buffer represented by OPT_length/offset
2218 		 * potentially modified and contains results of setting
2219 		 * options at this point
2220 		 */
2221 	}
2222 
2223 	/* We no longer need mp1, since all options processing has passed */
2224 	freemsg(mp1);
2225 
2226 	putnext(listener->tcp_rq, ok_mp);
2227 
2228 	mutex_enter(&listener->tcp_eager_lock);
2229 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2230 		tcp_t	*tail;
2231 		mblk_t	*conn_ind;
2232 
2233 		/*
2234 		 * This path should not be executed if listener and
2235 		 * acceptor streams are the same.
2236 		 */
2237 		ASSERT(listener != acceptor);
2238 
2239 		tcp = listener->tcp_eager_prev_q0;
2240 		/*
2241 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2242 		 * deferred T_conn_ind queue. We need to get to the head of
2243 		 * the queue in order to send up T_conn_ind the same order as
2244 		 * how the 3WHS is completed.
2245 		 */
2246 		while (tcp != listener) {
2247 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2248 				break;
2249 			else
2250 				tcp = tcp->tcp_eager_prev_q0;
2251 		}
2252 		ASSERT(tcp != listener);
2253 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2254 		ASSERT(conn_ind != NULL);
2255 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2256 
2257 		/* Move from q0 to q */
2258 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2259 		listener->tcp_conn_req_cnt_q0--;
2260 		listener->tcp_conn_req_cnt_q++;
2261 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2262 		    tcp->tcp_eager_prev_q0;
2263 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2264 		    tcp->tcp_eager_next_q0;
2265 		tcp->tcp_eager_prev_q0 = NULL;
2266 		tcp->tcp_eager_next_q0 = NULL;
2267 		tcp->tcp_conn_def_q0 = B_FALSE;
2268 
2269 		/* Make sure the tcp isn't in the list of droppables */
2270 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2271 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2272 
2273 		/*
2274 		 * Insert at end of the queue because sockfs sends
2275 		 * down T_CONN_RES in chronological order. Leaving
2276 		 * the older conn indications at front of the queue
2277 		 * helps reducing search time.
2278 		 */
2279 		tail = listener->tcp_eager_last_q;
2280 		if (tail != NULL)
2281 			tail->tcp_eager_next_q = tcp;
2282 		else
2283 			listener->tcp_eager_next_q = tcp;
2284 		listener->tcp_eager_last_q = tcp;
2285 		tcp->tcp_eager_next_q = NULL;
2286 		mutex_exit(&listener->tcp_eager_lock);
2287 		putnext(tcp->tcp_rq, conn_ind);
2288 	} else {
2289 		mutex_exit(&listener->tcp_eager_lock);
2290 	}
2291 
2292 	/*
2293 	 * Done with the acceptor - free it
2294 	 *
2295 	 * Note: from this point on, no access to listener should be made
2296 	 * as listener can be equal to acceptor.
2297 	 */
2298 finish:
2299 	ASSERT(acceptor->tcp_detached);
2300 	ASSERT(tcps->tcps_g_q != NULL);
2301 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2302 	acceptor->tcp_rq = tcps->tcps_g_q;
2303 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2304 	(void) tcp_clean_death(acceptor, 0, 2);
2305 	CONN_DEC_REF(acceptor->tcp_connp);
2306 
2307 	/*
2308 	 * In case we already received a FIN we have to make tcp_rput send
2309 	 * the ordrel_ind. This will also send up a window update if the window
2310 	 * has opened up.
2311 	 *
2312 	 * In the normal case of a successful connection acceptance
2313 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2314 	 * indication that this was just accepted. This tells tcp_rput to
2315 	 * pass up any data queued in tcp_rcv_list.
2316 	 *
2317 	 * In the fringe case where options sent with T_CONN_RES failed and
2318 	 * we required, we would be indicating a T_DISCON_IND to blow
2319 	 * away this connection.
2320 	 */
2321 
2322 	/*
2323 	 * XXX: we currently have a problem if XTI application closes the
2324 	 * acceptor stream in between. This problem exists in on10-gate also
2325 	 * and is well know but nothing can be done short of major rewrite
2326 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2327 	 * eager same squeue as listener (we can distinguish non socket
2328 	 * listeners at the time of handling a SYN in tcp_conn_request)
2329 	 * and do most of the work that tcp_accept_finish does here itself
2330 	 * and then get behind the acceptor squeue to access the acceptor
2331 	 * queue.
2332 	 */
2333 	/*
2334 	 * We already have a ref on tcp so no need to do one before squeue_enter
2335 	 */
2336 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2337 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2338 }
2339 
2340 /*
2341  * Swap information between the eager and acceptor for a TLI/XTI client.
2342  * The sockfs accept is done on the acceptor stream and control goes
2343  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2344  * called. In either case, both the eager and listener are in their own
2345  * perimeter (squeue) and the code has to deal with potential race.
2346  *
2347  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2348  */
2349 static int
2350 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2351 {
2352 	conn_t	*econnp, *aconnp;
2353 	cred_t	*effective_cred = NULL;
2354 
2355 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2356 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2357 	ASSERT(!eager->tcp_hard_bound);
2358 	ASSERT(!TCP_IS_SOCKET(acceptor));
2359 	ASSERT(!TCP_IS_SOCKET(eager));
2360 	ASSERT(!TCP_IS_SOCKET(listener));
2361 
2362 	econnp = eager->tcp_connp;
2363 	aconnp = acceptor->tcp_connp;
2364 
2365 	/*
2366 	 * Trusted Extensions may need to use a security label that is
2367 	 * different from the acceptor's label on MLP and MAC-Exempt
2368 	 * sockets. If this is the case, the required security label
2369 	 * already exists in econnp->conn_effective_cred. Use this label
2370 	 * to generate a new effective cred for the acceptor.
2371 	 *
2372 	 * We allow for potential application level retry attempts by
2373 	 * checking for transient errors before modifying eager.
2374 	 */
2375 	if (is_system_labeled() &&
2376 	    aconnp->conn_cred != NULL && econnp->conn_effective_cred != NULL) {
2377 		effective_cred = copycred_from_tslabel(aconnp->conn_cred,
2378 		    crgetlabel(econnp->conn_effective_cred), KM_NOSLEEP);
2379 		if (effective_cred == NULL)
2380 			return (ENOMEM);
2381 	}
2382 
2383 	acceptor->tcp_detached = B_TRUE;
2384 	/*
2385 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2386 	 * the acceptor id.
2387 	 */
2388 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2389 
2390 	/* remove eager from listen list... */
2391 	mutex_enter(&listener->tcp_eager_lock);
2392 	tcp_eager_unlink(eager);
2393 	ASSERT(eager->tcp_eager_next_q == NULL &&
2394 	    eager->tcp_eager_last_q == NULL);
2395 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2396 	    eager->tcp_eager_prev_q0 == NULL);
2397 	mutex_exit(&listener->tcp_eager_lock);
2398 	eager->tcp_rq = acceptor->tcp_rq;
2399 	eager->tcp_wq = acceptor->tcp_wq;
2400 
2401 	eager->tcp_rq->q_ptr = econnp;
2402 	eager->tcp_wq->q_ptr = econnp;
2403 
2404 	/*
2405 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2406 	 * which might be a different squeue from our peer TCP instance.
2407 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2408 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2409 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2410 	 * above reach global visibility prior to the clearing of tcp_detached.
2411 	 */
2412 	membar_producer();
2413 	eager->tcp_detached = B_FALSE;
2414 
2415 	ASSERT(eager->tcp_ack_tid == 0);
2416 
2417 	econnp->conn_dev = aconnp->conn_dev;
2418 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2419 
2420 	ASSERT(econnp->conn_minor_arena != NULL);
2421 	if (eager->tcp_cred != NULL)
2422 		crfree(eager->tcp_cred);
2423 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2424 	if (econnp->conn_effective_cred != NULL)
2425 		crfree(econnp->conn_effective_cred);
2426 	econnp->conn_effective_cred = effective_cred;
2427 	aconnp->conn_cred = NULL;
2428 	ASSERT(aconnp->conn_effective_cred == NULL);
2429 
2430 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2431 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2432 
2433 	econnp->conn_zoneid = aconnp->conn_zoneid;
2434 	econnp->conn_allzones = aconnp->conn_allzones;
2435 
2436 	aconnp->conn_mac_exempt = B_FALSE;
2437 
2438 	/* Do the IPC initialization */
2439 	CONN_INC_REF(econnp);
2440 
2441 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2442 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2443 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2444 
2445 	/* Done with old IPC. Drop its ref on its connp */
2446 	CONN_DEC_REF(aconnp);
2447 	return (0);
2448 }
2449 
2450 
2451 /*
2452  * Adapt to the information, such as rtt and rtt_sd, provided from the
2453  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2454  *
2455  * Checks for multicast and broadcast destination address.
2456  * Returns zero on failure; non-zero if ok.
2457  *
2458  * Note that the MSS calculation here is based on the info given in
2459  * the IRE.  We do not do any calculation based on TCP options.  They
2460  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2461  * knows which options to use.
2462  *
2463  * Note on how TCP gets its parameters for a connection.
2464  *
2465  * When a tcp_t structure is allocated, it gets all the default parameters.
2466  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2467  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2468  * default.
2469  *
2470  * An incoming SYN with a multicast or broadcast destination address, is dropped
2471  * in 1 of 2 places.
2472  *
2473  * 1. If the packet was received over the wire it is dropped in
2474  * ip_rput_process_broadcast()
2475  *
2476  * 2. If the packet was received through internal IP loopback, i.e. the packet
2477  * was generated and received on the same machine, it is dropped in
2478  * ip_wput_local()
2479  *
2480  * An incoming SYN with a multicast or broadcast source address is always
2481  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2482  * reject an attempt to connect to a broadcast or multicast (destination)
2483  * address.
2484  */
2485 static int
2486 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2487 {
2488 	ire_t		*ire;
2489 	ire_t		*sire = NULL;
2490 	iulp_t		*ire_uinfo = NULL;
2491 	uint32_t	mss_max;
2492 	uint32_t	mss;
2493 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2494 	conn_t		*connp = tcp->tcp_connp;
2495 	boolean_t	ire_cacheable = B_FALSE;
2496 	zoneid_t	zoneid = connp->conn_zoneid;
2497 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2498 	    MATCH_IRE_SECATTR;
2499 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2500 	ill_t		*ill = NULL;
2501 	boolean_t	incoming = (ire_mp == NULL);
2502 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2503 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2504 
2505 	ASSERT(connp->conn_ire_cache == NULL);
2506 
2507 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2508 
2509 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2510 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2511 			return (0);
2512 		}
2513 		/*
2514 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2515 		 * for the destination with the nexthop as gateway.
2516 		 * ire_ctable_lookup() is used because this particular
2517 		 * ire, if it exists, will be marked private.
2518 		 * If that is not available, use the interface ire
2519 		 * for the nexthop.
2520 		 *
2521 		 * TSol: tcp_update_label will detect label mismatches based
2522 		 * only on the destination's label, but that would not
2523 		 * detect label mismatches based on the security attributes
2524 		 * of routes or next hop gateway. Hence we need to pass the
2525 		 * label to ire_ftable_lookup below in order to locate the
2526 		 * right prefix (and/or) ire cache. Similarly we also need
2527 		 * pass the label to the ire_cache_lookup below to locate
2528 		 * the right ire that also matches on the label.
2529 		 */
2530 		if (tcp->tcp_connp->conn_nexthop_set) {
2531 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2532 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2533 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2534 			    ipst);
2535 			if (ire == NULL) {
2536 				ire = ire_ftable_lookup(
2537 				    tcp->tcp_connp->conn_nexthop_v4,
2538 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2539 				    tsl, match_flags, ipst);
2540 				if (ire == NULL)
2541 					return (0);
2542 			} else {
2543 				ire_uinfo = &ire->ire_uinfo;
2544 			}
2545 		} else {
2546 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2547 			    zoneid, tsl, ipst);
2548 			if (ire != NULL) {
2549 				ire_cacheable = B_TRUE;
2550 				ire_uinfo = (ire_mp != NULL) ?
2551 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2552 				    &ire->ire_uinfo;
2553 
2554 			} else {
2555 				if (ire_mp == NULL) {
2556 					ire = ire_ftable_lookup(
2557 					    tcp->tcp_connp->conn_rem,
2558 					    0, 0, 0, NULL, &sire, zoneid, 0,
2559 					    tsl, (MATCH_IRE_RECURSIVE |
2560 					    MATCH_IRE_DEFAULT), ipst);
2561 					if (ire == NULL)
2562 						return (0);
2563 					ire_uinfo = (sire != NULL) ?
2564 					    &sire->ire_uinfo :
2565 					    &ire->ire_uinfo;
2566 				} else {
2567 					ire = (ire_t *)ire_mp->b_rptr;
2568 					ire_uinfo =
2569 					    &((ire_t *)
2570 					    ire_mp->b_rptr)->ire_uinfo;
2571 				}
2572 			}
2573 		}
2574 		ASSERT(ire != NULL);
2575 
2576 		if ((ire->ire_src_addr == INADDR_ANY) ||
2577 		    (ire->ire_type & IRE_BROADCAST)) {
2578 			/*
2579 			 * ire->ire_mp is non null when ire_mp passed in is used
2580 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2581 			 */
2582 			if (ire->ire_mp == NULL)
2583 				ire_refrele(ire);
2584 			if (sire != NULL)
2585 				ire_refrele(sire);
2586 			return (0);
2587 		}
2588 
2589 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2590 			ipaddr_t src_addr;
2591 
2592 			/*
2593 			 * ip_bind_connected() has stored the correct source
2594 			 * address in conn_src.
2595 			 */
2596 			src_addr = tcp->tcp_connp->conn_src;
2597 			tcp->tcp_ipha->ipha_src = src_addr;
2598 			/*
2599 			 * Copy of the src addr. in tcp_t is needed
2600 			 * for the lookup funcs.
2601 			 */
2602 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2603 		}
2604 		/*
2605 		 * Set the fragment bit so that IP will tell us if the MTU
2606 		 * should change. IP tells us the latest setting of
2607 		 * ip_path_mtu_discovery through ire_frag_flag.
2608 		 */
2609 		if (ipst->ips_ip_path_mtu_discovery) {
2610 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2611 			    htons(IPH_DF);
2612 		}
2613 		/*
2614 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2615 		 * for IP_NEXTHOP. No cache ire has been found for the
2616 		 * destination and we are working with the nexthop's
2617 		 * interface ire. Since we need to forward all packets
2618 		 * to the nexthop first, we "blindly" set tcp_localnet
2619 		 * to false, eventhough the destination may also be
2620 		 * onlink.
2621 		 */
2622 		if (ire_uinfo == NULL)
2623 			tcp->tcp_localnet = 0;
2624 		else
2625 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2626 	} else {
2627 		/*
2628 		 * For incoming connection ire_mp = NULL
2629 		 * For outgoing connection ire_mp != NULL
2630 		 * Technically we should check conn_incoming_ill
2631 		 * when ire_mp is NULL and conn_outgoing_ill when
2632 		 * ire_mp is non-NULL. But this is performance
2633 		 * critical path and for IPV*_BOUND_IF, outgoing
2634 		 * and incoming ill are always set to the same value.
2635 		 */
2636 		ill_t	*dst_ill = NULL;
2637 		ipif_t  *dst_ipif = NULL;
2638 
2639 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2640 
2641 		if (connp->conn_outgoing_ill != NULL) {
2642 			/* Outgoing or incoming path */
2643 			int   err;
2644 
2645 			dst_ill = conn_get_held_ill(connp,
2646 			    &connp->conn_outgoing_ill, &err);
2647 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2648 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2649 				return (0);
2650 			}
2651 			match_flags |= MATCH_IRE_ILL;
2652 			dst_ipif = dst_ill->ill_ipif;
2653 		}
2654 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2655 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2656 
2657 		if (ire != NULL) {
2658 			ire_cacheable = B_TRUE;
2659 			ire_uinfo = (ire_mp != NULL) ?
2660 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2661 			    &ire->ire_uinfo;
2662 		} else {
2663 			if (ire_mp == NULL) {
2664 				ire = ire_ftable_lookup_v6(
2665 				    &tcp->tcp_connp->conn_remv6,
2666 				    0, 0, 0, dst_ipif, &sire, zoneid,
2667 				    0, tsl, match_flags, ipst);
2668 				if (ire == NULL) {
2669 					if (dst_ill != NULL)
2670 						ill_refrele(dst_ill);
2671 					return (0);
2672 				}
2673 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2674 				    &ire->ire_uinfo;
2675 			} else {
2676 				ire = (ire_t *)ire_mp->b_rptr;
2677 				ire_uinfo =
2678 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2679 			}
2680 		}
2681 		if (dst_ill != NULL)
2682 			ill_refrele(dst_ill);
2683 
2684 		ASSERT(ire != NULL);
2685 		ASSERT(ire_uinfo != NULL);
2686 
2687 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2688 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2689 			/*
2690 			 * ire->ire_mp is non null when ire_mp passed in is used
2691 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2692 			 */
2693 			if (ire->ire_mp == NULL)
2694 				ire_refrele(ire);
2695 			if (sire != NULL)
2696 				ire_refrele(sire);
2697 			return (0);
2698 		}
2699 
2700 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2701 			in6_addr_t	src_addr;
2702 
2703 			/*
2704 			 * ip_bind_connected_v6() has stored the correct source
2705 			 * address per IPv6 addr. selection policy in
2706 			 * conn_src_v6.
2707 			 */
2708 			src_addr = tcp->tcp_connp->conn_srcv6;
2709 
2710 			tcp->tcp_ip6h->ip6_src = src_addr;
2711 			/*
2712 			 * Copy of the src addr. in tcp_t is needed
2713 			 * for the lookup funcs.
2714 			 */
2715 			tcp->tcp_ip_src_v6 = src_addr;
2716 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2717 			    &connp->conn_srcv6));
2718 		}
2719 		tcp->tcp_localnet =
2720 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2721 	}
2722 
2723 	/*
2724 	 * This allows applications to fail quickly when connections are made
2725 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2726 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2727 	 */
2728 	if ((ire->ire_flags & RTF_REJECT) &&
2729 	    (ire->ire_flags & RTF_PRIVATE))
2730 		goto error;
2731 
2732 	/*
2733 	 * Make use of the cached rtt and rtt_sd values to calculate the
2734 	 * initial RTO.  Note that they are already initialized in
2735 	 * tcp_init_values().
2736 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2737 	 * IP_NEXTHOP, but instead are using the interface ire for the
2738 	 * nexthop, then we do not use the ire_uinfo from that ire to
2739 	 * do any initializations.
2740 	 */
2741 	if (ire_uinfo != NULL) {
2742 		if (ire_uinfo->iulp_rtt != 0) {
2743 			clock_t	rto;
2744 
2745 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2746 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2747 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2748 			    tcps->tcps_rexmit_interval_extra +
2749 			    (tcp->tcp_rtt_sa >> 5);
2750 
2751 			if (rto > tcps->tcps_rexmit_interval_max) {
2752 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2753 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2754 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2755 			} else {
2756 				tcp->tcp_rto = rto;
2757 			}
2758 		}
2759 		if (ire_uinfo->iulp_ssthresh != 0)
2760 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2761 		else
2762 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2763 		if (ire_uinfo->iulp_spipe > 0) {
2764 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2765 			    tcps->tcps_max_buf);
2766 			if (tcps->tcps_snd_lowat_fraction != 0)
2767 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2768 				    tcps->tcps_snd_lowat_fraction;
2769 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2770 		}
2771 		/*
2772 		 * Note that up till now, acceptor always inherits receive
2773 		 * window from the listener.  But if there is a metrics
2774 		 * associated with a host, we should use that instead of
2775 		 * inheriting it from listener. Thus we need to pass this
2776 		 * info back to the caller.
2777 		 */
2778 		if (ire_uinfo->iulp_rpipe > 0) {
2779 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2780 			    tcps->tcps_max_buf);
2781 		}
2782 
2783 		if (ire_uinfo->iulp_rtomax > 0) {
2784 			tcp->tcp_second_timer_threshold =
2785 			    ire_uinfo->iulp_rtomax;
2786 		}
2787 
2788 		/*
2789 		 * Use the metric option settings, iulp_tstamp_ok and
2790 		 * iulp_wscale_ok, only for active open. What this means
2791 		 * is that if the other side uses timestamp or window
2792 		 * scale option, TCP will also use those options. That
2793 		 * is for passive open.  If the application sets a
2794 		 * large window, window scale is enabled regardless of
2795 		 * the value in iulp_wscale_ok.  This is the behavior
2796 		 * since 2.6.  So we keep it.
2797 		 * The only case left in passive open processing is the
2798 		 * check for SACK.
2799 		 * For ECN, it should probably be like SACK.  But the
2800 		 * current value is binary, so we treat it like the other
2801 		 * cases.  The metric only controls active open.For passive
2802 		 * open, the ndd param, tcp_ecn_permitted, controls the
2803 		 * behavior.
2804 		 */
2805 		if (!tcp_detached) {
2806 			/*
2807 			 * The if check means that the following can only
2808 			 * be turned on by the metrics only IRE, but not off.
2809 			 */
2810 			if (ire_uinfo->iulp_tstamp_ok)
2811 				tcp->tcp_snd_ts_ok = B_TRUE;
2812 			if (ire_uinfo->iulp_wscale_ok)
2813 				tcp->tcp_snd_ws_ok = B_TRUE;
2814 			if (ire_uinfo->iulp_sack == 2)
2815 				tcp->tcp_snd_sack_ok = B_TRUE;
2816 			if (ire_uinfo->iulp_ecn_ok)
2817 				tcp->tcp_ecn_ok = B_TRUE;
2818 		} else {
2819 			/*
2820 			 * Passive open.
2821 			 *
2822 			 * As above, the if check means that SACK can only be
2823 			 * turned on by the metric only IRE.
2824 			 */
2825 			if (ire_uinfo->iulp_sack > 0) {
2826 				tcp->tcp_snd_sack_ok = B_TRUE;
2827 			}
2828 		}
2829 	}
2830 
2831 
2832 	/*
2833 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2834 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2835 	 * length of all those options exceeds 28 bytes.  But because
2836 	 * of the tcp_mss_min check below, we may not have a problem if
2837 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2838 	 * the negative problem still exists.  And the check defeats PMTUd.
2839 	 * In fact, if PMTUd finds that the MSS should be smaller than
2840 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2841 	 * value.
2842 	 *
2843 	 * We do not deal with that now.  All those problems related to
2844 	 * PMTUd will be fixed later.
2845 	 */
2846 	ASSERT(ire->ire_max_frag != 0);
2847 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2848 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2849 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2850 			mss = MIN(mss, IPV6_MIN_MTU);
2851 		}
2852 	}
2853 
2854 	/* Sanity check for MSS value. */
2855 	if (tcp->tcp_ipversion == IPV4_VERSION)
2856 		mss_max = tcps->tcps_mss_max_ipv4;
2857 	else
2858 		mss_max = tcps->tcps_mss_max_ipv6;
2859 
2860 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2861 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2862 		/*
2863 		 * After receiving an ICMPv6 "packet too big" message with a
2864 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2865 		 * will insert a 8-byte fragment header in every packet; we
2866 		 * reduce the MSS by that amount here.
2867 		 */
2868 		mss -= sizeof (ip6_frag_t);
2869 	}
2870 
2871 	if (tcp->tcp_ipsec_overhead == 0)
2872 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2873 
2874 	mss -= tcp->tcp_ipsec_overhead;
2875 
2876 	if (mss < tcps->tcps_mss_min)
2877 		mss = tcps->tcps_mss_min;
2878 	if (mss > mss_max)
2879 		mss = mss_max;
2880 
2881 	/* Note that this is the maximum MSS, excluding all options. */
2882 	tcp->tcp_mss = mss;
2883 
2884 	/*
2885 	 * Initialize the ISS here now that we have the full connection ID.
2886 	 * The RFC 1948 method of initial sequence number generation requires
2887 	 * knowledge of the full connection ID before setting the ISS.
2888 	 */
2889 
2890 	tcp_iss_init(tcp);
2891 
2892 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2893 		tcp->tcp_loopback = B_TRUE;
2894 
2895 	if (sire != NULL)
2896 		IRE_REFRELE(sire);
2897 
2898 	/*
2899 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2900 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2901 	 */
2902 	if (tcp->tcp_loopback ||
2903 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2904 		/*
2905 		 * For incoming, see if this tcp may be MDT-capable.  For
2906 		 * outgoing, this process has been taken care of through
2907 		 * tcp_rput_other.
2908 		 */
2909 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2910 		tcp->tcp_ire_ill_check_done = B_TRUE;
2911 	}
2912 
2913 	mutex_enter(&connp->conn_lock);
2914 	/*
2915 	 * Make sure that conn is not marked incipient
2916 	 * for incoming connections. A blind
2917 	 * removal of incipient flag is cheaper than
2918 	 * check and removal.
2919 	 */
2920 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2921 
2922 	/*
2923 	 * Must not cache forwarding table routes
2924 	 * or recache an IRE after the conn_t has
2925 	 * had conn_ire_cache cleared and is flagged
2926 	 * unusable, (see the CONN_CACHE_IRE() macro).
2927 	 */
2928 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2929 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2930 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2931 			connp->conn_ire_cache = ire;
2932 			IRE_UNTRACE_REF(ire);
2933 			rw_exit(&ire->ire_bucket->irb_lock);
2934 			mutex_exit(&connp->conn_lock);
2935 			return (1);
2936 		}
2937 		rw_exit(&ire->ire_bucket->irb_lock);
2938 	}
2939 	mutex_exit(&connp->conn_lock);
2940 
2941 	if (ire->ire_mp == NULL)
2942 		ire_refrele(ire);
2943 	return (1);
2944 
2945 error:
2946 	if (ire->ire_mp == NULL)
2947 		ire_refrele(ire);
2948 	if (sire != NULL)
2949 		ire_refrele(sire);
2950 	return (0);
2951 }
2952 
2953 static void
2954 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2955 {
2956 	int	error;
2957 	conn_t	*connp = tcp->tcp_connp;
2958 	struct sockaddr	*sa;
2959 	mblk_t  *mp1;
2960 	struct T_bind_req *tbr;
2961 	int	backlog;
2962 	socklen_t	len;
2963 	sin_t	*sin;
2964 	sin6_t	*sin6;
2965 	cred_t		*cr;
2966 
2967 	/*
2968 	 * All Solaris components should pass a db_credp
2969 	 * for this TPI message, hence we ASSERT.
2970 	 * But in case there is some other M_PROTO that looks
2971 	 * like a TPI message sent by some other kernel
2972 	 * component, we check and return an error.
2973 	 */
2974 	cr = msg_getcred(mp, NULL);
2975 	ASSERT(cr != NULL);
2976 	if (cr == NULL) {
2977 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2978 		return;
2979 	}
2980 
2981 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2982 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2983 		if (tcp->tcp_debug) {
2984 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2985 			    "tcp_tpi_bind: bad req, len %u",
2986 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2987 		}
2988 		tcp_err_ack(tcp, mp, TPROTO, 0);
2989 		return;
2990 	}
2991 	/* Make sure the largest address fits */
2992 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
2993 	if (mp1 == NULL) {
2994 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2995 		return;
2996 	}
2997 	mp = mp1;
2998 	tbr = (struct T_bind_req *)mp->b_rptr;
2999 
3000 	backlog = tbr->CONIND_number;
3001 	len = tbr->ADDR_length;
3002 
3003 	switch (len) {
3004 	case 0:		/* request for a generic port */
3005 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3006 		if (tcp->tcp_family == AF_INET) {
3007 			tbr->ADDR_length = sizeof (sin_t);
3008 			sin = (sin_t *)&tbr[1];
3009 			*sin = sin_null;
3010 			sin->sin_family = AF_INET;
3011 			sa = (struct sockaddr *)sin;
3012 			len = sizeof (sin_t);
3013 			mp->b_wptr = (uchar_t *)&sin[1];
3014 		} else {
3015 			ASSERT(tcp->tcp_family == AF_INET6);
3016 			tbr->ADDR_length = sizeof (sin6_t);
3017 			sin6 = (sin6_t *)&tbr[1];
3018 			*sin6 = sin6_null;
3019 			sin6->sin6_family = AF_INET6;
3020 			sa = (struct sockaddr *)sin6;
3021 			len = sizeof (sin6_t);
3022 			mp->b_wptr = (uchar_t *)&sin6[1];
3023 		}
3024 		break;
3025 
3026 	case sizeof (sin_t):    /* Complete IPv4 address */
3027 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
3028 		    sizeof (sin_t));
3029 		break;
3030 
3031 	case sizeof (sin6_t): /* Complete IPv6 address */
3032 		sa = (struct sockaddr *)mi_offset_param(mp,
3033 		    tbr->ADDR_offset, sizeof (sin6_t));
3034 		break;
3035 
3036 	default:
3037 		if (tcp->tcp_debug) {
3038 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3039 			    "tcp_tpi_bind: bad address length, %d",
3040 			    tbr->ADDR_length);
3041 		}
3042 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3043 		return;
3044 	}
3045 
3046 	if (backlog > 0) {
3047 		error = tcp_do_listen(connp, sa, len, backlog, DB_CRED(mp),
3048 		    tbr->PRIM_type != O_T_BIND_REQ);
3049 	} else {
3050 		error = tcp_do_bind(connp, sa, len, DB_CRED(mp),
3051 		    tbr->PRIM_type != O_T_BIND_REQ);
3052 	}
3053 done:
3054 	if (error > 0) {
3055 		tcp_err_ack(tcp, mp, TSYSERR, error);
3056 	} else if (error < 0) {
3057 		tcp_err_ack(tcp, mp, -error, 0);
3058 	} else {
3059 		/*
3060 		 * Update port information as sockfs/tpi needs it for checking
3061 		 */
3062 		if (tcp->tcp_family == AF_INET) {
3063 			sin = (sin_t *)sa;
3064 			sin->sin_port = tcp->tcp_lport;
3065 		} else {
3066 			sin6 = (sin6_t *)sa;
3067 			sin6->sin6_port = tcp->tcp_lport;
3068 		}
3069 		mp->b_datap->db_type = M_PCPROTO;
3070 		tbr->PRIM_type = T_BIND_ACK;
3071 		putnext(tcp->tcp_rq, mp);
3072 	}
3073 }
3074 
3075 /*
3076  * If the "bind_to_req_port_only" parameter is set, if the requested port
3077  * number is available, return it, If not return 0
3078  *
3079  * If "bind_to_req_port_only" parameter is not set and
3080  * If the requested port number is available, return it.  If not, return
3081  * the first anonymous port we happen across.  If no anonymous ports are
3082  * available, return 0. addr is the requested local address, if any.
3083  *
3084  * In either case, when succeeding update the tcp_t to record the port number
3085  * and insert it in the bind hash table.
3086  *
3087  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3088  * without setting SO_REUSEADDR. This is needed so that they
3089  * can be viewed as two independent transport protocols.
3090  */
3091 static in_port_t
3092 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3093     int reuseaddr, boolean_t quick_connect,
3094     boolean_t bind_to_req_port_only, boolean_t user_specified)
3095 {
3096 	/* number of times we have run around the loop */
3097 	int count = 0;
3098 	/* maximum number of times to run around the loop */
3099 	int loopmax;
3100 	conn_t *connp = tcp->tcp_connp;
3101 	zoneid_t zoneid = connp->conn_zoneid;
3102 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3103 
3104 	/*
3105 	 * Lookup for free addresses is done in a loop and "loopmax"
3106 	 * influences how long we spin in the loop
3107 	 */
3108 	if (bind_to_req_port_only) {
3109 		/*
3110 		 * If the requested port is busy, don't bother to look
3111 		 * for a new one. Setting loop maximum count to 1 has
3112 		 * that effect.
3113 		 */
3114 		loopmax = 1;
3115 	} else {
3116 		/*
3117 		 * If the requested port is busy, look for a free one
3118 		 * in the anonymous port range.
3119 		 * Set loopmax appropriately so that one does not look
3120 		 * forever in the case all of the anonymous ports are in use.
3121 		 */
3122 		if (tcp->tcp_anon_priv_bind) {
3123 			/*
3124 			 * loopmax =
3125 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3126 			 */
3127 			loopmax = IPPORT_RESERVED -
3128 			    tcps->tcps_min_anonpriv_port;
3129 		} else {
3130 			loopmax = (tcps->tcps_largest_anon_port -
3131 			    tcps->tcps_smallest_anon_port + 1);
3132 		}
3133 	}
3134 	do {
3135 		uint16_t	lport;
3136 		tf_t		*tbf;
3137 		tcp_t		*ltcp;
3138 		conn_t		*lconnp;
3139 
3140 		lport = htons(port);
3141 
3142 		/*
3143 		 * Ensure that the tcp_t is not currently in the bind hash.
3144 		 * Hold the lock on the hash bucket to ensure that
3145 		 * the duplicate check plus the insertion is an atomic
3146 		 * operation.
3147 		 *
3148 		 * This function does an inline lookup on the bind hash list
3149 		 * Make sure that we access only members of tcp_t
3150 		 * and that we don't look at tcp_tcp, since we are not
3151 		 * doing a CONN_INC_REF.
3152 		 */
3153 		tcp_bind_hash_remove(tcp);
3154 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3155 		mutex_enter(&tbf->tf_lock);
3156 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3157 		    ltcp = ltcp->tcp_bind_hash) {
3158 			if (lport == ltcp->tcp_lport)
3159 				break;
3160 		}
3161 
3162 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3163 			boolean_t not_socket;
3164 			boolean_t exclbind;
3165 
3166 			lconnp = ltcp->tcp_connp;
3167 
3168 			/*
3169 			 * On a labeled system, we must treat bindings to ports
3170 			 * on shared IP addresses by sockets with MAC exemption
3171 			 * privilege as being in all zones, as there's
3172 			 * otherwise no way to identify the right receiver.
3173 			 */
3174 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3175 			    IPCL_ZONE_MATCH(connp,
3176 			    ltcp->tcp_connp->conn_zoneid)) &&
3177 			    !lconnp->conn_mac_exempt &&
3178 			    !connp->conn_mac_exempt)
3179 				continue;
3180 
3181 			/*
3182 			 * If TCP_EXCLBIND is set for either the bound or
3183 			 * binding endpoint, the semantics of bind
3184 			 * is changed according to the following.
3185 			 *
3186 			 * spec = specified address (v4 or v6)
3187 			 * unspec = unspecified address (v4 or v6)
3188 			 * A = specified addresses are different for endpoints
3189 			 *
3190 			 * bound	bind to		allowed
3191 			 * -------------------------------------
3192 			 * unspec	unspec		no
3193 			 * unspec	spec		no
3194 			 * spec		unspec		no
3195 			 * spec		spec		yes if A
3196 			 *
3197 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3198 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3199 			 *
3200 			 * Note:
3201 			 *
3202 			 * 1. Because of TLI semantics, an endpoint can go
3203 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3204 			 * TCPS_BOUND, depending on whether it is originally
3205 			 * a listener or not.  That is why we need to check
3206 			 * for states greater than or equal to TCPS_BOUND
3207 			 * here.
3208 			 *
3209 			 * 2. Ideally, we should only check for state equals
3210 			 * to TCPS_LISTEN. And the following check should be
3211 			 * added.
3212 			 *
3213 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3214 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3215 			 *		...
3216 			 * }
3217 			 *
3218 			 * The semantics will be changed to this.  If the
3219 			 * endpoint on the list is in state not equal to
3220 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3221 			 * set, let the bind succeed.
3222 			 *
3223 			 * Because of (1), we cannot do that for TLI
3224 			 * endpoints.  But we can do that for socket endpoints.
3225 			 * If in future, we can change this going back
3226 			 * semantics, we can use the above check for TLI also.
3227 			 */
3228 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3229 			    TCP_IS_SOCKET(tcp));
3230 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3231 
3232 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3233 			    (exclbind && (not_socket ||
3234 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3235 				if (V6_OR_V4_INADDR_ANY(
3236 				    ltcp->tcp_bound_source_v6) ||
3237 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3238 				    IN6_ARE_ADDR_EQUAL(laddr,
3239 				    &ltcp->tcp_bound_source_v6)) {
3240 					break;
3241 				}
3242 				continue;
3243 			}
3244 
3245 			/*
3246 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3247 			 * have disjoint port number spaces, if *_EXCLBIND
3248 			 * is not set and only if the application binds to a
3249 			 * specific port. We use the same autoassigned port
3250 			 * number space for IPv4 and IPv6 sockets.
3251 			 */
3252 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3253 			    bind_to_req_port_only)
3254 				continue;
3255 
3256 			/*
3257 			 * Ideally, we should make sure that the source
3258 			 * address, remote address, and remote port in the
3259 			 * four tuple for this tcp-connection is unique.
3260 			 * However, trying to find out the local source
3261 			 * address would require too much code duplication
3262 			 * with IP, since IP needs needs to have that code
3263 			 * to support userland TCP implementations.
3264 			 */
3265 			if (quick_connect &&
3266 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3267 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3268 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3269 			    &ltcp->tcp_remote_v6)))
3270 				continue;
3271 
3272 			if (!reuseaddr) {
3273 				/*
3274 				 * No socket option SO_REUSEADDR.
3275 				 * If existing port is bound to
3276 				 * a non-wildcard IP address
3277 				 * and the requesting stream is
3278 				 * bound to a distinct
3279 				 * different IP addresses
3280 				 * (non-wildcard, also), keep
3281 				 * going.
3282 				 */
3283 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3284 				    !V6_OR_V4_INADDR_ANY(
3285 				    ltcp->tcp_bound_source_v6) &&
3286 				    !IN6_ARE_ADDR_EQUAL(laddr,
3287 				    &ltcp->tcp_bound_source_v6))
3288 					continue;
3289 				if (ltcp->tcp_state >= TCPS_BOUND) {
3290 					/*
3291 					 * This port is being used and
3292 					 * its state is >= TCPS_BOUND,
3293 					 * so we can't bind to it.
3294 					 */
3295 					break;
3296 				}
3297 			} else {
3298 				/*
3299 				 * socket option SO_REUSEADDR is set on the
3300 				 * binding tcp_t.
3301 				 *
3302 				 * If two streams are bound to
3303 				 * same IP address or both addr
3304 				 * and bound source are wildcards
3305 				 * (INADDR_ANY), we want to stop
3306 				 * searching.
3307 				 * We have found a match of IP source
3308 				 * address and source port, which is
3309 				 * refused regardless of the
3310 				 * SO_REUSEADDR setting, so we break.
3311 				 */
3312 				if (IN6_ARE_ADDR_EQUAL(laddr,
3313 				    &ltcp->tcp_bound_source_v6) &&
3314 				    (ltcp->tcp_state == TCPS_LISTEN ||
3315 				    ltcp->tcp_state == TCPS_BOUND))
3316 					break;
3317 			}
3318 		}
3319 		if (ltcp != NULL) {
3320 			/* The port number is busy */
3321 			mutex_exit(&tbf->tf_lock);
3322 		} else {
3323 			/*
3324 			 * This port is ours. Insert in fanout and mark as
3325 			 * bound to prevent others from getting the port
3326 			 * number.
3327 			 */
3328 			tcp->tcp_state = TCPS_BOUND;
3329 			tcp->tcp_lport = htons(port);
3330 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3331 
3332 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3333 			    tcp->tcp_lport)] == tbf);
3334 			tcp_bind_hash_insert(tbf, tcp, 1);
3335 
3336 			mutex_exit(&tbf->tf_lock);
3337 
3338 			/*
3339 			 * We don't want tcp_next_port_to_try to "inherit"
3340 			 * a port number supplied by the user in a bind.
3341 			 */
3342 			if (user_specified)
3343 				return (port);
3344 
3345 			/*
3346 			 * This is the only place where tcp_next_port_to_try
3347 			 * is updated. After the update, it may or may not
3348 			 * be in the valid range.
3349 			 */
3350 			if (!tcp->tcp_anon_priv_bind)
3351 				tcps->tcps_next_port_to_try = port + 1;
3352 			return (port);
3353 		}
3354 
3355 		if (tcp->tcp_anon_priv_bind) {
3356 			port = tcp_get_next_priv_port(tcp);
3357 		} else {
3358 			if (count == 0 && user_specified) {
3359 				/*
3360 				 * We may have to return an anonymous port. So
3361 				 * get one to start with.
3362 				 */
3363 				port =
3364 				    tcp_update_next_port(
3365 				    tcps->tcps_next_port_to_try,
3366 				    tcp, B_TRUE);
3367 				user_specified = B_FALSE;
3368 			} else {
3369 				port = tcp_update_next_port(port + 1, tcp,
3370 				    B_FALSE);
3371 			}
3372 		}
3373 		if (port == 0)
3374 			break;
3375 
3376 		/*
3377 		 * Don't let this loop run forever in the case where
3378 		 * all of the anonymous ports are in use.
3379 		 */
3380 	} while (++count < loopmax);
3381 	return (0);
3382 }
3383 
3384 /*
3385  * tcp_clean_death / tcp_close_detached must not be called more than once
3386  * on a tcp. Thus every function that potentially calls tcp_clean_death
3387  * must check for the tcp state before calling tcp_clean_death.
3388  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3389  * tcp_timer_handler, all check for the tcp state.
3390  */
3391 /* ARGSUSED */
3392 void
3393 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3394 {
3395 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3396 
3397 	freemsg(mp);
3398 	if (tcp->tcp_state > TCPS_BOUND)
3399 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3400 		    ETIMEDOUT, 5);
3401 }
3402 
3403 /*
3404  * We are dying for some reason.  Try to do it gracefully.  (May be called
3405  * as writer.)
3406  *
3407  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3408  * done by a service procedure).
3409  * TBD - Should the return value distinguish between the tcp_t being
3410  * freed and it being reinitialized?
3411  */
3412 static int
3413 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3414 {
3415 	mblk_t	*mp;
3416 	queue_t	*q;
3417 	conn_t	*connp = tcp->tcp_connp;
3418 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3419 
3420 	TCP_CLD_STAT(tag);
3421 
3422 #if TCP_TAG_CLEAN_DEATH
3423 	tcp->tcp_cleandeathtag = tag;
3424 #endif
3425 
3426 	if (tcp->tcp_fused)
3427 		tcp_unfuse(tcp);
3428 
3429 	if (tcp->tcp_linger_tid != 0 &&
3430 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3431 		tcp_stop_lingering(tcp);
3432 	}
3433 
3434 	ASSERT(tcp != NULL);
3435 	ASSERT((tcp->tcp_family == AF_INET &&
3436 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3437 	    (tcp->tcp_family == AF_INET6 &&
3438 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3439 	    tcp->tcp_ipversion == IPV6_VERSION)));
3440 
3441 	if (TCP_IS_DETACHED(tcp)) {
3442 		if (tcp->tcp_hard_binding) {
3443 			/*
3444 			 * Its an eager that we are dealing with. We close the
3445 			 * eager but in case a conn_ind has already gone to the
3446 			 * listener, let tcp_accept_finish() send a discon_ind
3447 			 * to the listener and drop the last reference. If the
3448 			 * listener doesn't even know about the eager i.e. the
3449 			 * conn_ind hasn't gone up, blow away the eager and drop
3450 			 * the last reference as well. If the conn_ind has gone
3451 			 * up, state should be BOUND. tcp_accept_finish
3452 			 * will figure out that the connection has received a
3453 			 * RST and will send a DISCON_IND to the application.
3454 			 */
3455 			tcp_closei_local(tcp);
3456 			if (!tcp->tcp_tconnind_started) {
3457 				CONN_DEC_REF(connp);
3458 			} else {
3459 				tcp->tcp_state = TCPS_BOUND;
3460 			}
3461 		} else {
3462 			tcp_close_detached(tcp);
3463 		}
3464 		return (0);
3465 	}
3466 
3467 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3468 
3469 	q = tcp->tcp_rq;
3470 
3471 	/* Trash all inbound data */
3472 	if (!IPCL_IS_NONSTR(connp)) {
3473 		ASSERT(q != NULL);
3474 		flushq(q, FLUSHALL);
3475 	}
3476 
3477 	/*
3478 	 * If we are at least part way open and there is error
3479 	 * (err==0 implies no error)
3480 	 * notify our client by a T_DISCON_IND.
3481 	 */
3482 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3483 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3484 		    !TCP_IS_SOCKET(tcp)) {
3485 			/*
3486 			 * Send M_FLUSH according to TPI. Because sockets will
3487 			 * (and must) ignore FLUSHR we do that only for TPI
3488 			 * endpoints and sockets in STREAMS mode.
3489 			 */
3490 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3491 		}
3492 		if (tcp->tcp_debug) {
3493 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3494 			    "tcp_clean_death: discon err %d", err);
3495 		}
3496 		if (IPCL_IS_NONSTR(connp)) {
3497 			/* Direct socket, use upcall */
3498 			(*connp->conn_upcalls->su_disconnected)(
3499 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3500 		} else {
3501 			mp = mi_tpi_discon_ind(NULL, err, 0);
3502 			if (mp != NULL) {
3503 				putnext(q, mp);
3504 			} else {
3505 				if (tcp->tcp_debug) {
3506 					(void) strlog(TCP_MOD_ID, 0, 1,
3507 					    SL_ERROR|SL_TRACE,
3508 					    "tcp_clean_death, sending M_ERROR");
3509 				}
3510 				(void) putnextctl1(q, M_ERROR, EPROTO);
3511 			}
3512 		}
3513 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3514 			/* SYN_SENT or SYN_RCVD */
3515 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3516 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3517 			/* ESTABLISHED or CLOSE_WAIT */
3518 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3519 		}
3520 	}
3521 
3522 	tcp_reinit(tcp);
3523 	if (IPCL_IS_NONSTR(connp))
3524 		(void) tcp_do_unbind(connp);
3525 
3526 	return (-1);
3527 }
3528 
3529 /*
3530  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3531  * to expire, stop the wait and finish the close.
3532  */
3533 static void
3534 tcp_stop_lingering(tcp_t *tcp)
3535 {
3536 	clock_t	delta = 0;
3537 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3538 
3539 	tcp->tcp_linger_tid = 0;
3540 	if (tcp->tcp_state > TCPS_LISTEN) {
3541 		tcp_acceptor_hash_remove(tcp);
3542 		mutex_enter(&tcp->tcp_non_sq_lock);
3543 		if (tcp->tcp_flow_stopped) {
3544 			tcp_clrqfull(tcp);
3545 		}
3546 		mutex_exit(&tcp->tcp_non_sq_lock);
3547 
3548 		if (tcp->tcp_timer_tid != 0) {
3549 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3550 			tcp->tcp_timer_tid = 0;
3551 		}
3552 		/*
3553 		 * Need to cancel those timers which will not be used when
3554 		 * TCP is detached.  This has to be done before the tcp_wq
3555 		 * is set to the global queue.
3556 		 */
3557 		tcp_timers_stop(tcp);
3558 
3559 		tcp->tcp_detached = B_TRUE;
3560 		ASSERT(tcps->tcps_g_q != NULL);
3561 		tcp->tcp_rq = tcps->tcps_g_q;
3562 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3563 
3564 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3565 			tcp_time_wait_append(tcp);
3566 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3567 			goto finish;
3568 		}
3569 
3570 		/*
3571 		 * If delta is zero the timer event wasn't executed and was
3572 		 * successfully canceled. In this case we need to restart it
3573 		 * with the minimal delta possible.
3574 		 */
3575 		if (delta >= 0) {
3576 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3577 			    delta ? delta : 1);
3578 		}
3579 	} else {
3580 		tcp_closei_local(tcp);
3581 		CONN_DEC_REF(tcp->tcp_connp);
3582 	}
3583 finish:
3584 	/* Signal closing thread that it can complete close */
3585 	mutex_enter(&tcp->tcp_closelock);
3586 	tcp->tcp_detached = B_TRUE;
3587 	ASSERT(tcps->tcps_g_q != NULL);
3588 
3589 	tcp->tcp_rq = tcps->tcps_g_q;
3590 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3591 
3592 	tcp->tcp_closed = 1;
3593 	cv_signal(&tcp->tcp_closecv);
3594 	mutex_exit(&tcp->tcp_closelock);
3595 }
3596 
3597 /*
3598  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3599  * expires.
3600  */
3601 static void
3602 tcp_close_linger_timeout(void *arg)
3603 {
3604 	conn_t	*connp = (conn_t *)arg;
3605 	tcp_t 	*tcp = connp->conn_tcp;
3606 
3607 	tcp->tcp_client_errno = ETIMEDOUT;
3608 	tcp_stop_lingering(tcp);
3609 }
3610 
3611 static void
3612 tcp_close_common(conn_t *connp, int flags)
3613 {
3614 	tcp_t		*tcp = connp->conn_tcp;
3615 	mblk_t 		*mp = &tcp->tcp_closemp;
3616 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3617 	mblk_t		*bp;
3618 
3619 	ASSERT(connp->conn_ref >= 2);
3620 
3621 	/*
3622 	 * Mark the conn as closing. ill_pending_mp_add will not
3623 	 * add any mp to the pending mp list, after this conn has
3624 	 * started closing. Same for sq_pending_mp_add
3625 	 */
3626 	mutex_enter(&connp->conn_lock);
3627 	connp->conn_state_flags |= CONN_CLOSING;
3628 	if (connp->conn_oper_pending_ill != NULL)
3629 		conn_ioctl_cleanup_reqd = B_TRUE;
3630 	CONN_INC_REF_LOCKED(connp);
3631 	mutex_exit(&connp->conn_lock);
3632 	tcp->tcp_closeflags = (uint8_t)flags;
3633 	ASSERT(connp->conn_ref >= 3);
3634 
3635 	/*
3636 	 * tcp_closemp_used is used below without any protection of a lock
3637 	 * as we don't expect any one else to use it concurrently at this
3638 	 * point otherwise it would be a major defect.
3639 	 */
3640 
3641 	if (mp->b_prev == NULL)
3642 		tcp->tcp_closemp_used = B_TRUE;
3643 	else
3644 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3645 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3646 
3647 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3648 
3649 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3650 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3651 
3652 	mutex_enter(&tcp->tcp_closelock);
3653 	while (!tcp->tcp_closed) {
3654 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3655 			/*
3656 			 * The cv_wait_sig() was interrupted. We now do the
3657 			 * following:
3658 			 *
3659 			 * 1) If the endpoint was lingering, we allow this
3660 			 * to be interrupted by cancelling the linger timeout
3661 			 * and closing normally.
3662 			 *
3663 			 * 2) Revert to calling cv_wait()
3664 			 *
3665 			 * We revert to using cv_wait() to avoid an
3666 			 * infinite loop which can occur if the calling
3667 			 * thread is higher priority than the squeue worker
3668 			 * thread and is bound to the same cpu.
3669 			 */
3670 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3671 				mutex_exit(&tcp->tcp_closelock);
3672 				/* Entering squeue, bump ref count. */
3673 				CONN_INC_REF(connp);
3674 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3675 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3676 				    tcp_linger_interrupted, connp,
3677 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3678 				mutex_enter(&tcp->tcp_closelock);
3679 			}
3680 			break;
3681 		}
3682 	}
3683 	while (!tcp->tcp_closed)
3684 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3685 	mutex_exit(&tcp->tcp_closelock);
3686 
3687 	/*
3688 	 * In the case of listener streams that have eagers in the q or q0
3689 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3690 	 * tcp_wq of the eagers point to our queues. By waiting for the
3691 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3692 	 * up their queue pointers and also dropped their references to us.
3693 	 */
3694 	if (tcp->tcp_wait_for_eagers) {
3695 		mutex_enter(&connp->conn_lock);
3696 		while (connp->conn_ref != 1) {
3697 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3698 		}
3699 		mutex_exit(&connp->conn_lock);
3700 	}
3701 	/*
3702 	 * ioctl cleanup. The mp is queued in the
3703 	 * ill_pending_mp or in the sq_pending_mp.
3704 	 */
3705 	if (conn_ioctl_cleanup_reqd)
3706 		conn_ioctl_cleanup(connp);
3707 
3708 	tcp->tcp_cpid = -1;
3709 }
3710 
3711 static int
3712 tcp_tpi_close(queue_t *q, int flags)
3713 {
3714 	conn_t		*connp;
3715 
3716 	ASSERT(WR(q)->q_next == NULL);
3717 
3718 	if (flags & SO_FALLBACK) {
3719 		/*
3720 		 * stream is being closed while in fallback
3721 		 * simply free the resources that were allocated
3722 		 */
3723 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3724 		qprocsoff(q);
3725 		goto done;
3726 	}
3727 
3728 	connp = Q_TO_CONN(q);
3729 	/*
3730 	 * We are being closed as /dev/tcp or /dev/tcp6.
3731 	 */
3732 	tcp_close_common(connp, flags);
3733 
3734 	qprocsoff(q);
3735 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3736 
3737 	/*
3738 	 * Drop IP's reference on the conn. This is the last reference
3739 	 * on the connp if the state was less than established. If the
3740 	 * connection has gone into timewait state, then we will have
3741 	 * one ref for the TCP and one more ref (total of two) for the
3742 	 * classifier connected hash list (a timewait connections stays
3743 	 * in connected hash till closed).
3744 	 *
3745 	 * We can't assert the references because there might be other
3746 	 * transient reference places because of some walkers or queued
3747 	 * packets in squeue for the timewait state.
3748 	 */
3749 	CONN_DEC_REF(connp);
3750 done:
3751 	q->q_ptr = WR(q)->q_ptr = NULL;
3752 	return (0);
3753 }
3754 
3755 static int
3756 tcp_tpi_close_accept(queue_t *q)
3757 {
3758 	vmem_t	*minor_arena;
3759 	dev_t	conn_dev;
3760 
3761 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3762 
3763 	/*
3764 	 * We had opened an acceptor STREAM for sockfs which is
3765 	 * now being closed due to some error.
3766 	 */
3767 	qprocsoff(q);
3768 
3769 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3770 	conn_dev = (dev_t)RD(q)->q_ptr;
3771 	ASSERT(minor_arena != NULL);
3772 	ASSERT(conn_dev != 0);
3773 	inet_minor_free(minor_arena, conn_dev);
3774 	q->q_ptr = WR(q)->q_ptr = NULL;
3775 	return (0);
3776 }
3777 
3778 /*
3779  * Called by tcp_close() routine via squeue when lingering is
3780  * interrupted by a signal.
3781  */
3782 
3783 /* ARGSUSED */
3784 static void
3785 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3786 {
3787 	conn_t	*connp = (conn_t *)arg;
3788 	tcp_t	*tcp = connp->conn_tcp;
3789 
3790 	freeb(mp);
3791 	if (tcp->tcp_linger_tid != 0 &&
3792 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3793 		tcp_stop_lingering(tcp);
3794 		tcp->tcp_client_errno = EINTR;
3795 	}
3796 }
3797 
3798 /*
3799  * Called by streams close routine via squeues when our client blows off her
3800  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3801  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3802  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3803  * acked.
3804  *
3805  * NOTE: tcp_close potentially returns error when lingering.
3806  * However, the stream head currently does not pass these errors
3807  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3808  * errors to the application (from tsleep()) and not errors
3809  * like ECONNRESET caused by receiving a reset packet.
3810  */
3811 
3812 /* ARGSUSED */
3813 static void
3814 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3815 {
3816 	char	*msg;
3817 	conn_t	*connp = (conn_t *)arg;
3818 	tcp_t	*tcp = connp->conn_tcp;
3819 	clock_t	delta = 0;
3820 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3821 
3822 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3823 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3824 
3825 	mutex_enter(&tcp->tcp_eager_lock);
3826 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3827 		/* Cleanup for listener */
3828 		tcp_eager_cleanup(tcp, 0);
3829 		tcp->tcp_wait_for_eagers = 1;
3830 	}
3831 	mutex_exit(&tcp->tcp_eager_lock);
3832 
3833 	connp->conn_mdt_ok = B_FALSE;
3834 	tcp->tcp_mdt = B_FALSE;
3835 
3836 	connp->conn_lso_ok = B_FALSE;
3837 	tcp->tcp_lso = B_FALSE;
3838 
3839 	msg = NULL;
3840 	switch (tcp->tcp_state) {
3841 	case TCPS_CLOSED:
3842 	case TCPS_IDLE:
3843 	case TCPS_BOUND:
3844 	case TCPS_LISTEN:
3845 		break;
3846 	case TCPS_SYN_SENT:
3847 		msg = "tcp_close, during connect";
3848 		break;
3849 	case TCPS_SYN_RCVD:
3850 		/*
3851 		 * Close during the connect 3-way handshake
3852 		 * but here there may or may not be pending data
3853 		 * already on queue. Process almost same as in
3854 		 * the ESTABLISHED state.
3855 		 */
3856 		/* FALLTHRU */
3857 	default:
3858 		if (tcp->tcp_fused)
3859 			tcp_unfuse(tcp);
3860 
3861 		/*
3862 		 * If SO_LINGER has set a zero linger time, abort the
3863 		 * connection with a reset.
3864 		 */
3865 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3866 			msg = "tcp_close, zero lingertime";
3867 			break;
3868 		}
3869 
3870 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3871 		/*
3872 		 * Abort connection if there is unread data queued.
3873 		 */
3874 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3875 			msg = "tcp_close, unread data";
3876 			break;
3877 		}
3878 		/*
3879 		 * tcp_hard_bound is now cleared thus all packets go through
3880 		 * tcp_lookup. This fact is used by tcp_detach below.
3881 		 *
3882 		 * We have done a qwait() above which could have possibly
3883 		 * drained more messages in turn causing transition to a
3884 		 * different state. Check whether we have to do the rest
3885 		 * of the processing or not.
3886 		 */
3887 		if (tcp->tcp_state <= TCPS_LISTEN)
3888 			break;
3889 
3890 		/*
3891 		 * Transmit the FIN before detaching the tcp_t.
3892 		 * After tcp_detach returns this queue/perimeter
3893 		 * no longer owns the tcp_t thus others can modify it.
3894 		 */
3895 		(void) tcp_xmit_end(tcp);
3896 
3897 		/*
3898 		 * If lingering on close then wait until the fin is acked,
3899 		 * the SO_LINGER time passes, or a reset is sent/received.
3900 		 */
3901 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3902 		    !(tcp->tcp_fin_acked) &&
3903 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3904 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3905 				tcp->tcp_client_errno = EWOULDBLOCK;
3906 			} else if (tcp->tcp_client_errno == 0) {
3907 
3908 				ASSERT(tcp->tcp_linger_tid == 0);
3909 
3910 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3911 				    tcp_close_linger_timeout,
3912 				    tcp->tcp_lingertime * hz);
3913 
3914 				/* tcp_close_linger_timeout will finish close */
3915 				if (tcp->tcp_linger_tid == 0)
3916 					tcp->tcp_client_errno = ENOSR;
3917 				else
3918 					return;
3919 			}
3920 
3921 			/*
3922 			 * Check if we need to detach or just close
3923 			 * the instance.
3924 			 */
3925 			if (tcp->tcp_state <= TCPS_LISTEN)
3926 				break;
3927 		}
3928 
3929 		/*
3930 		 * Make sure that no other thread will access the tcp_rq of
3931 		 * this instance (through lookups etc.) as tcp_rq will go
3932 		 * away shortly.
3933 		 */
3934 		tcp_acceptor_hash_remove(tcp);
3935 
3936 		mutex_enter(&tcp->tcp_non_sq_lock);
3937 		if (tcp->tcp_flow_stopped) {
3938 			tcp_clrqfull(tcp);
3939 		}
3940 		mutex_exit(&tcp->tcp_non_sq_lock);
3941 
3942 		if (tcp->tcp_timer_tid != 0) {
3943 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3944 			tcp->tcp_timer_tid = 0;
3945 		}
3946 		/*
3947 		 * Need to cancel those timers which will not be used when
3948 		 * TCP is detached.  This has to be done before the tcp_wq
3949 		 * is set to the global queue.
3950 		 */
3951 		tcp_timers_stop(tcp);
3952 
3953 		tcp->tcp_detached = B_TRUE;
3954 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3955 			tcp_time_wait_append(tcp);
3956 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3957 			ASSERT(connp->conn_ref >= 3);
3958 			goto finish;
3959 		}
3960 
3961 		/*
3962 		 * If delta is zero the timer event wasn't executed and was
3963 		 * successfully canceled. In this case we need to restart it
3964 		 * with the minimal delta possible.
3965 		 */
3966 		if (delta >= 0)
3967 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3968 			    delta ? delta : 1);
3969 
3970 		ASSERT(connp->conn_ref >= 3);
3971 		goto finish;
3972 	}
3973 
3974 	/* Detach did not complete. Still need to remove q from stream. */
3975 	if (msg) {
3976 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3977 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3978 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3979 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3980 		    tcp->tcp_state == TCPS_SYN_RCVD)
3981 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3982 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3983 	}
3984 
3985 	tcp_closei_local(tcp);
3986 	CONN_DEC_REF(connp);
3987 	ASSERT(connp->conn_ref >= 2);
3988 
3989 finish:
3990 	/*
3991 	 * Although packets are always processed on the correct
3992 	 * tcp's perimeter and access is serialized via squeue's,
3993 	 * IP still needs a queue when sending packets in time_wait
3994 	 * state so use WR(tcps_g_q) till ip_output() can be
3995 	 * changed to deal with just connp. For read side, we
3996 	 * could have set tcp_rq to NULL but there are some cases
3997 	 * in tcp_rput_data() from early days of this code which
3998 	 * do a putnext without checking if tcp is closed. Those
3999 	 * need to be identified before both tcp_rq and tcp_wq
4000 	 * can be set to NULL and tcps_g_q can disappear forever.
4001 	 */
4002 	mutex_enter(&tcp->tcp_closelock);
4003 	/*
4004 	 * Don't change the queues in the case of a listener that has
4005 	 * eagers in its q or q0. It could surprise the eagers.
4006 	 * Instead wait for the eagers outside the squeue.
4007 	 */
4008 	if (!tcp->tcp_wait_for_eagers) {
4009 		tcp->tcp_detached = B_TRUE;
4010 		/*
4011 		 * When default queue is closing we set tcps_g_q to NULL
4012 		 * after the close is done.
4013 		 */
4014 		ASSERT(tcps->tcps_g_q != NULL);
4015 		tcp->tcp_rq = tcps->tcps_g_q;
4016 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4017 	}
4018 
4019 	/* Signal tcp_close() to finish closing. */
4020 	tcp->tcp_closed = 1;
4021 	cv_signal(&tcp->tcp_closecv);
4022 	mutex_exit(&tcp->tcp_closelock);
4023 }
4024 
4025 /*
4026  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4027  * Some stream heads get upset if they see these later on as anything but NULL.
4028  */
4029 static void
4030 tcp_close_mpp(mblk_t **mpp)
4031 {
4032 	mblk_t	*mp;
4033 
4034 	if ((mp = *mpp) != NULL) {
4035 		do {
4036 			mp->b_next = NULL;
4037 			mp->b_prev = NULL;
4038 		} while ((mp = mp->b_cont) != NULL);
4039 
4040 		mp = *mpp;
4041 		*mpp = NULL;
4042 		freemsg(mp);
4043 	}
4044 }
4045 
4046 /* Do detached close. */
4047 static void
4048 tcp_close_detached(tcp_t *tcp)
4049 {
4050 	if (tcp->tcp_fused)
4051 		tcp_unfuse(tcp);
4052 
4053 	/*
4054 	 * Clustering code serializes TCP disconnect callbacks and
4055 	 * cluster tcp list walks by blocking a TCP disconnect callback
4056 	 * if a cluster tcp list walk is in progress. This ensures
4057 	 * accurate accounting of TCPs in the cluster code even though
4058 	 * the TCP list walk itself is not atomic.
4059 	 */
4060 	tcp_closei_local(tcp);
4061 	CONN_DEC_REF(tcp->tcp_connp);
4062 }
4063 
4064 /*
4065  * Stop all TCP timers, and free the timer mblks if requested.
4066  */
4067 void
4068 tcp_timers_stop(tcp_t *tcp)
4069 {
4070 	if (tcp->tcp_timer_tid != 0) {
4071 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4072 		tcp->tcp_timer_tid = 0;
4073 	}
4074 	if (tcp->tcp_ka_tid != 0) {
4075 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4076 		tcp->tcp_ka_tid = 0;
4077 	}
4078 	if (tcp->tcp_ack_tid != 0) {
4079 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4080 		tcp->tcp_ack_tid = 0;
4081 	}
4082 	if (tcp->tcp_push_tid != 0) {
4083 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4084 		tcp->tcp_push_tid = 0;
4085 	}
4086 }
4087 
4088 /*
4089  * The tcp_t is going away. Remove it from all lists and set it
4090  * to TCPS_CLOSED. The freeing up of memory is deferred until
4091  * tcp_inactive. This is needed since a thread in tcp_rput might have
4092  * done a CONN_INC_REF on this structure before it was removed from the
4093  * hashes.
4094  */
4095 static void
4096 tcp_closei_local(tcp_t *tcp)
4097 {
4098 	ire_t 	*ire;
4099 	conn_t	*connp = tcp->tcp_connp;
4100 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4101 
4102 	if (!TCP_IS_SOCKET(tcp))
4103 		tcp_acceptor_hash_remove(tcp);
4104 
4105 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4106 	tcp->tcp_ibsegs = 0;
4107 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4108 	tcp->tcp_obsegs = 0;
4109 
4110 	/*
4111 	 * If we are an eager connection hanging off a listener that
4112 	 * hasn't formally accepted the connection yet, get off his
4113 	 * list and blow off any data that we have accumulated.
4114 	 */
4115 	if (tcp->tcp_listener != NULL) {
4116 		tcp_t	*listener = tcp->tcp_listener;
4117 		mutex_enter(&listener->tcp_eager_lock);
4118 		/*
4119 		 * tcp_tconnind_started == B_TRUE means that the
4120 		 * conn_ind has already gone to listener. At
4121 		 * this point, eager will be closed but we
4122 		 * leave it in listeners eager list so that
4123 		 * if listener decides to close without doing
4124 		 * accept, we can clean this up. In tcp_wput_accept
4125 		 * we take care of the case of accept on closed
4126 		 * eager.
4127 		 */
4128 		if (!tcp->tcp_tconnind_started) {
4129 			tcp_eager_unlink(tcp);
4130 			mutex_exit(&listener->tcp_eager_lock);
4131 			/*
4132 			 * We don't want to have any pointers to the
4133 			 * listener queue, after we have released our
4134 			 * reference on the listener
4135 			 */
4136 			ASSERT(tcps->tcps_g_q != NULL);
4137 			tcp->tcp_rq = tcps->tcps_g_q;
4138 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4139 			CONN_DEC_REF(listener->tcp_connp);
4140 		} else {
4141 			mutex_exit(&listener->tcp_eager_lock);
4142 		}
4143 	}
4144 
4145 	/* Stop all the timers */
4146 	tcp_timers_stop(tcp);
4147 
4148 	if (tcp->tcp_state == TCPS_LISTEN) {
4149 		if (tcp->tcp_ip_addr_cache) {
4150 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4151 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4152 			tcp->tcp_ip_addr_cache = NULL;
4153 		}
4154 	}
4155 	mutex_enter(&tcp->tcp_non_sq_lock);
4156 	if (tcp->tcp_flow_stopped)
4157 		tcp_clrqfull(tcp);
4158 	mutex_exit(&tcp->tcp_non_sq_lock);
4159 
4160 	tcp_bind_hash_remove(tcp);
4161 	/*
4162 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4163 	 * is trying to remove this tcp from the time wait list, we will
4164 	 * block in tcp_time_wait_remove while trying to acquire the
4165 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4166 	 * requires the ipcl_hash_remove to be ordered after the
4167 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4168 	 */
4169 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4170 		(void) tcp_time_wait_remove(tcp, NULL);
4171 	CL_INET_DISCONNECT(connp, tcp);
4172 	ipcl_hash_remove(connp);
4173 
4174 	/*
4175 	 * Delete the cached ire in conn_ire_cache and also mark
4176 	 * the conn as CONDEMNED
4177 	 */
4178 	mutex_enter(&connp->conn_lock);
4179 	connp->conn_state_flags |= CONN_CONDEMNED;
4180 	ire = connp->conn_ire_cache;
4181 	connp->conn_ire_cache = NULL;
4182 	mutex_exit(&connp->conn_lock);
4183 	if (ire != NULL)
4184 		IRE_REFRELE_NOTR(ire);
4185 
4186 	/* Need to cleanup any pending ioctls */
4187 	ASSERT(tcp->tcp_time_wait_next == NULL);
4188 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4189 	ASSERT(tcp->tcp_time_wait_expire == 0);
4190 	tcp->tcp_state = TCPS_CLOSED;
4191 
4192 	/* Release any SSL context */
4193 	if (tcp->tcp_kssl_ent != NULL) {
4194 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4195 		tcp->tcp_kssl_ent = NULL;
4196 	}
4197 	if (tcp->tcp_kssl_ctx != NULL) {
4198 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4199 		tcp->tcp_kssl_ctx = NULL;
4200 	}
4201 	tcp->tcp_kssl_pending = B_FALSE;
4202 
4203 	tcp_ipsec_cleanup(tcp);
4204 }
4205 
4206 /*
4207  * tcp is dying (called from ipcl_conn_destroy and error cases).
4208  * Free the tcp_t in either case.
4209  */
4210 void
4211 tcp_free(tcp_t *tcp)
4212 {
4213 	mblk_t	*mp;
4214 	ip6_pkt_t	*ipp;
4215 
4216 	ASSERT(tcp != NULL);
4217 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4218 
4219 	tcp->tcp_rq = NULL;
4220 	tcp->tcp_wq = NULL;
4221 
4222 	tcp_close_mpp(&tcp->tcp_xmit_head);
4223 	tcp_close_mpp(&tcp->tcp_reass_head);
4224 	if (tcp->tcp_rcv_list != NULL) {
4225 		/* Free b_next chain */
4226 		tcp_close_mpp(&tcp->tcp_rcv_list);
4227 	}
4228 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4229 		freemsg(mp);
4230 	}
4231 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4232 		freemsg(mp);
4233 	}
4234 
4235 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4236 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4237 		freeb(tcp->tcp_fused_sigurg_mp);
4238 		tcp->tcp_fused_sigurg_mp = NULL;
4239 	}
4240 
4241 	if (tcp->tcp_ordrel_mp != NULL) {
4242 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4243 		freeb(tcp->tcp_ordrel_mp);
4244 		tcp->tcp_ordrel_mp = NULL;
4245 	}
4246 
4247 	if (tcp->tcp_sack_info != NULL) {
4248 		if (tcp->tcp_notsack_list != NULL) {
4249 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
4250 			    tcp);
4251 		}
4252 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4253 	}
4254 
4255 	if (tcp->tcp_hopopts != NULL) {
4256 		mi_free(tcp->tcp_hopopts);
4257 		tcp->tcp_hopopts = NULL;
4258 		tcp->tcp_hopoptslen = 0;
4259 	}
4260 	ASSERT(tcp->tcp_hopoptslen == 0);
4261 	if (tcp->tcp_dstopts != NULL) {
4262 		mi_free(tcp->tcp_dstopts);
4263 		tcp->tcp_dstopts = NULL;
4264 		tcp->tcp_dstoptslen = 0;
4265 	}
4266 	ASSERT(tcp->tcp_dstoptslen == 0);
4267 	if (tcp->tcp_rtdstopts != NULL) {
4268 		mi_free(tcp->tcp_rtdstopts);
4269 		tcp->tcp_rtdstopts = NULL;
4270 		tcp->tcp_rtdstoptslen = 0;
4271 	}
4272 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4273 	if (tcp->tcp_rthdr != NULL) {
4274 		mi_free(tcp->tcp_rthdr);
4275 		tcp->tcp_rthdr = NULL;
4276 		tcp->tcp_rthdrlen = 0;
4277 	}
4278 	ASSERT(tcp->tcp_rthdrlen == 0);
4279 
4280 	ipp = &tcp->tcp_sticky_ipp;
4281 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4282 	    IPPF_RTHDR))
4283 		ip6_pkt_free(ipp);
4284 
4285 	/*
4286 	 * Free memory associated with the tcp/ip header template.
4287 	 */
4288 
4289 	if (tcp->tcp_iphc != NULL)
4290 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4291 
4292 	/*
4293 	 * Following is really a blowing away a union.
4294 	 * It happens to have exactly two members of identical size
4295 	 * the following code is enough.
4296 	 */
4297 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4298 }
4299 
4300 
4301 /*
4302  * Put a connection confirmation message upstream built from the
4303  * address information within 'iph' and 'tcph'.  Report our success or failure.
4304  */
4305 static boolean_t
4306 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4307     mblk_t **defermp)
4308 {
4309 	sin_t	sin;
4310 	sin6_t	sin6;
4311 	mblk_t	*mp;
4312 	char	*optp = NULL;
4313 	int	optlen = 0;
4314 
4315 	if (defermp != NULL)
4316 		*defermp = NULL;
4317 
4318 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4319 		/*
4320 		 * Return in T_CONN_CON results of option negotiation through
4321 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4322 		 * negotiation, then what is received from remote end needs
4323 		 * to be taken into account but there is no such thing (yet?)
4324 		 * in our TCP/IP.
4325 		 * Note: We do not use mi_offset_param() here as
4326 		 * tcp_opts_conn_req contents do not directly come from
4327 		 * an application and are either generated in kernel or
4328 		 * from user input that was already verified.
4329 		 */
4330 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4331 		optp = (char *)(mp->b_rptr +
4332 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4333 		optlen = (int)
4334 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4335 	}
4336 
4337 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4338 		ipha_t *ipha = (ipha_t *)iphdr;
4339 
4340 		/* packet is IPv4 */
4341 		if (tcp->tcp_family == AF_INET) {
4342 			sin = sin_null;
4343 			sin.sin_addr.s_addr = ipha->ipha_src;
4344 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4345 			sin.sin_family = AF_INET;
4346 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4347 			    (int)sizeof (sin_t), optp, optlen);
4348 		} else {
4349 			sin6 = sin6_null;
4350 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4351 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4352 			sin6.sin6_family = AF_INET6;
4353 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4354 			    (int)sizeof (sin6_t), optp, optlen);
4355 
4356 		}
4357 	} else {
4358 		ip6_t	*ip6h = (ip6_t *)iphdr;
4359 
4360 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4361 		ASSERT(tcp->tcp_family == AF_INET6);
4362 		sin6 = sin6_null;
4363 		sin6.sin6_addr = ip6h->ip6_src;
4364 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4365 		sin6.sin6_family = AF_INET6;
4366 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4367 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4368 		    (int)sizeof (sin6_t), optp, optlen);
4369 	}
4370 
4371 	if (!mp)
4372 		return (B_FALSE);
4373 
4374 	mblk_copycred(mp, idmp);
4375 
4376 	if (defermp == NULL) {
4377 		conn_t *connp = tcp->tcp_connp;
4378 		if (IPCL_IS_NONSTR(connp)) {
4379 			cred_t *cr;
4380 			pid_t cpid;
4381 
4382 			cr = msg_getcred(mp, &cpid);
4383 			(*connp->conn_upcalls->su_connected)
4384 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4385 			    cpid);
4386 			freemsg(mp);
4387 		} else {
4388 			putnext(tcp->tcp_rq, mp);
4389 		}
4390 	} else {
4391 		*defermp = mp;
4392 	}
4393 
4394 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4395 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4396 	return (B_TRUE);
4397 }
4398 
4399 /*
4400  * Defense for the SYN attack -
4401  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4402  *    one from the list of droppable eagers. This list is a subset of q0.
4403  *    see comments before the definition of MAKE_DROPPABLE().
4404  * 2. Don't drop a SYN request before its first timeout. This gives every
4405  *    request at least til the first timeout to complete its 3-way handshake.
4406  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4407  *    requests currently on the queue that has timed out. This will be used
4408  *    as an indicator of whether an attack is under way, so that appropriate
4409  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4410  *    either when eager goes into ESTABLISHED, or gets freed up.)
4411  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4412  *    # of timeout drops back to <= q0len/32 => SYN alert off
4413  */
4414 static boolean_t
4415 tcp_drop_q0(tcp_t *tcp)
4416 {
4417 	tcp_t	*eager;
4418 	mblk_t	*mp;
4419 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4420 
4421 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4422 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4423 
4424 	/* Pick oldest eager from the list of droppable eagers */
4425 	eager = tcp->tcp_eager_prev_drop_q0;
4426 
4427 	/* If list is empty. return B_FALSE */
4428 	if (eager == tcp) {
4429 		return (B_FALSE);
4430 	}
4431 
4432 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4433 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4434 		return (B_FALSE);
4435 
4436 	/*
4437 	 * Take this eager out from the list of droppable eagers since we are
4438 	 * going to drop it.
4439 	 */
4440 	MAKE_UNDROPPABLE(eager);
4441 
4442 	if (tcp->tcp_debug) {
4443 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4444 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4445 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4446 		    tcp->tcp_conn_req_cnt_q0,
4447 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4448 	}
4449 
4450 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4451 
4452 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4453 	CONN_INC_REF(eager->tcp_connp);
4454 
4455 	/* Mark the IRE created for this SYN request temporary */
4456 	tcp_ip_ire_mark_advice(eager);
4457 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4458 	    tcp_clean_death_wrapper, eager->tcp_connp,
4459 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4460 
4461 	return (B_TRUE);
4462 }
4463 
4464 int
4465 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4466     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4467 {
4468 	tcp_t 		*ltcp = lconnp->conn_tcp;
4469 	tcp_t		*tcp = connp->conn_tcp;
4470 	mblk_t		*tpi_mp;
4471 	ipha_t		*ipha;
4472 	ip6_t		*ip6h;
4473 	sin6_t 		sin6;
4474 	in6_addr_t 	v6dst;
4475 	int		err;
4476 	int		ifindex = 0;
4477 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4478 
4479 	if (ipvers == IPV4_VERSION) {
4480 		ipha = (ipha_t *)mp->b_rptr;
4481 
4482 		connp->conn_send = ip_output;
4483 		connp->conn_recv = tcp_input;
4484 
4485 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4486 		    &connp->conn_bound_source_v6);
4487 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4488 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4489 
4490 		sin6 = sin6_null;
4491 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4492 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4493 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4494 		sin6.sin6_family = AF_INET6;
4495 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4496 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4497 		if (tcp->tcp_recvdstaddr) {
4498 			sin6_t	sin6d;
4499 
4500 			sin6d = sin6_null;
4501 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4502 			    &sin6d.sin6_addr);
4503 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4504 			sin6d.sin6_family = AF_INET;
4505 			tpi_mp = mi_tpi_extconn_ind(NULL,
4506 			    (char *)&sin6d, sizeof (sin6_t),
4507 			    (char *)&tcp,
4508 			    (t_scalar_t)sizeof (intptr_t),
4509 			    (char *)&sin6d, sizeof (sin6_t),
4510 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4511 		} else {
4512 			tpi_mp = mi_tpi_conn_ind(NULL,
4513 			    (char *)&sin6, sizeof (sin6_t),
4514 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4515 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4516 		}
4517 	} else {
4518 		ip6h = (ip6_t *)mp->b_rptr;
4519 
4520 		connp->conn_send = ip_output_v6;
4521 		connp->conn_recv = tcp_input;
4522 
4523 		connp->conn_bound_source_v6 = ip6h->ip6_dst;
4524 		connp->conn_srcv6 = ip6h->ip6_dst;
4525 		connp->conn_remv6 = ip6h->ip6_src;
4526 
4527 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4528 		ifindex = (int)DB_CKSUMSTUFF(mp);
4529 		DB_CKSUMSTUFF(mp) = 0;
4530 
4531 		sin6 = sin6_null;
4532 		sin6.sin6_addr = ip6h->ip6_src;
4533 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4534 		sin6.sin6_family = AF_INET6;
4535 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4536 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4537 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4538 
4539 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4540 			/* Pass up the scope_id of remote addr */
4541 			sin6.sin6_scope_id = ifindex;
4542 		} else {
4543 			sin6.sin6_scope_id = 0;
4544 		}
4545 		if (tcp->tcp_recvdstaddr) {
4546 			sin6_t	sin6d;
4547 
4548 			sin6d = sin6_null;
4549 			sin6.sin6_addr = ip6h->ip6_dst;
4550 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4551 			sin6d.sin6_family = AF_INET;
4552 			tpi_mp = mi_tpi_extconn_ind(NULL,
4553 			    (char *)&sin6d, sizeof (sin6_t),
4554 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4555 			    (char *)&sin6d, sizeof (sin6_t),
4556 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4557 		} else {
4558 			tpi_mp = mi_tpi_conn_ind(NULL,
4559 			    (char *)&sin6, sizeof (sin6_t),
4560 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4561 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4562 		}
4563 	}
4564 
4565 	if (tpi_mp == NULL)
4566 		return (ENOMEM);
4567 
4568 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4569 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4570 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4571 	connp->conn_fully_bound = B_FALSE;
4572 
4573 	/* Inherit information from the "parent" */
4574 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4575 	tcp->tcp_family = ltcp->tcp_family;
4576 
4577 	tcp->tcp_wq = ltcp->tcp_wq;
4578 	tcp->tcp_rq = ltcp->tcp_rq;
4579 
4580 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4581 	tcp->tcp_detached = B_TRUE;
4582 	SOCK_CONNID_INIT(tcp->tcp_connid);
4583 	if ((err = tcp_init_values(tcp)) != 0) {
4584 		freemsg(tpi_mp);
4585 		return (err);
4586 	}
4587 
4588 	if (ipvers == IPV4_VERSION) {
4589 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4590 			freemsg(tpi_mp);
4591 			return (err);
4592 		}
4593 		ASSERT(tcp->tcp_ipha != NULL);
4594 	} else {
4595 		/* ifindex must be already set */
4596 		ASSERT(ifindex != 0);
4597 
4598 		if (ltcp->tcp_bound_if != 0)
4599 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4600 		else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src))
4601 			tcp->tcp_bound_if = ifindex;
4602 
4603 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4604 		tcp->tcp_recvifindex = 0;
4605 		tcp->tcp_recvhops = 0xffffffffU;
4606 		ASSERT(tcp->tcp_ip6h != NULL);
4607 	}
4608 
4609 	tcp->tcp_lport = ltcp->tcp_lport;
4610 
4611 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4612 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4613 			/*
4614 			 * Listener had options of some sort; eager inherits.
4615 			 * Free up the eager template and allocate one
4616 			 * of the right size.
4617 			 */
4618 			if (tcp->tcp_hdr_grown) {
4619 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4620 			} else {
4621 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4622 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4623 			}
4624 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4625 			    KM_NOSLEEP);
4626 			if (tcp->tcp_iphc == NULL) {
4627 				tcp->tcp_iphc_len = 0;
4628 				freemsg(tpi_mp);
4629 				return (ENOMEM);
4630 			}
4631 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4632 			tcp->tcp_hdr_grown = B_TRUE;
4633 		}
4634 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4635 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4636 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4637 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4638 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4639 
4640 		/*
4641 		 * Copy the IP+TCP header template from listener to eager
4642 		 */
4643 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4644 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4645 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4646 			    IPPROTO_RAW) {
4647 				tcp->tcp_ip6h =
4648 				    (ip6_t *)(tcp->tcp_iphc +
4649 				    sizeof (ip6i_t));
4650 			} else {
4651 				tcp->tcp_ip6h =
4652 				    (ip6_t *)(tcp->tcp_iphc);
4653 			}
4654 			tcp->tcp_ipha = NULL;
4655 		} else {
4656 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4657 			tcp->tcp_ip6h = NULL;
4658 		}
4659 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4660 		    tcp->tcp_ip_hdr_len);
4661 	} else {
4662 		/*
4663 		 * only valid case when ipversion of listener and
4664 		 * eager differ is when listener is IPv6 and
4665 		 * eager is IPv4.
4666 		 * Eager header template has been initialized to the
4667 		 * maximum v4 header sizes, which includes space for
4668 		 * TCP and IP options.
4669 		 */
4670 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4671 		    (tcp->tcp_ipversion == IPV4_VERSION));
4672 		ASSERT(tcp->tcp_iphc_len >=
4673 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4674 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4675 		/* copy IP header fields individually */
4676 		tcp->tcp_ipha->ipha_ttl =
4677 		    ltcp->tcp_ip6h->ip6_hops;
4678 		bcopy(ltcp->tcp_tcph->th_lport,
4679 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4680 	}
4681 
4682 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4683 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4684 	    sizeof (in_port_t));
4685 
4686 	if (ltcp->tcp_lport == 0) {
4687 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4688 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4689 		    sizeof (in_port_t));
4690 	}
4691 
4692 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4693 		ASSERT(ipha != NULL);
4694 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4695 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4696 
4697 		/* Source routing option copyover (reverse it) */
4698 		if (tcps->tcps_rev_src_routes)
4699 			tcp_opt_reverse(tcp, ipha);
4700 	} else {
4701 		ASSERT(ip6h != NULL);
4702 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4703 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4704 	}
4705 
4706 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4707 	ASSERT(!tcp->tcp_tconnind_started);
4708 	/*
4709 	 * If the SYN contains a credential, it's a loopback packet; attach
4710 	 * the credential to the TPI message.
4711 	 */
4712 	mblk_copycred(tpi_mp, idmp);
4713 
4714 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4715 
4716 	/* Inherit the listener's SSL protection state */
4717 
4718 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4719 		kssl_hold_ent(tcp->tcp_kssl_ent);
4720 		tcp->tcp_kssl_pending = B_TRUE;
4721 	}
4722 
4723 	/* Inherit the listener's non-STREAMS flag */
4724 	if (IPCL_IS_NONSTR(lconnp)) {
4725 		connp->conn_flags |= IPCL_NONSTR;
4726 	}
4727 
4728 	return (0);
4729 }
4730 
4731 
4732 int
4733 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4734     tcph_t *tcph, mblk_t *idmp)
4735 {
4736 	tcp_t 		*ltcp = lconnp->conn_tcp;
4737 	tcp_t		*tcp = connp->conn_tcp;
4738 	sin_t		sin;
4739 	mblk_t		*tpi_mp = NULL;
4740 	int		err;
4741 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4742 
4743 	sin = sin_null;
4744 	sin.sin_addr.s_addr = ipha->ipha_src;
4745 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4746 	sin.sin_family = AF_INET;
4747 	if (ltcp->tcp_recvdstaddr) {
4748 		sin_t	sind;
4749 
4750 		sind = sin_null;
4751 		sind.sin_addr.s_addr = ipha->ipha_dst;
4752 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4753 		sind.sin_family = AF_INET;
4754 		tpi_mp = mi_tpi_extconn_ind(NULL,
4755 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4756 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4757 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4758 	} else {
4759 		tpi_mp = mi_tpi_conn_ind(NULL,
4760 		    (char *)&sin, sizeof (sin_t),
4761 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4762 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4763 	}
4764 
4765 	if (tpi_mp == NULL) {
4766 		return (ENOMEM);
4767 	}
4768 
4769 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4770 	connp->conn_send = ip_output;
4771 	connp->conn_recv = tcp_input;
4772 	connp->conn_fully_bound = B_FALSE;
4773 
4774 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4775 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4776 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4777 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4778 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4779 
4780 	/* Inherit information from the "parent" */
4781 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4782 	tcp->tcp_family = ltcp->tcp_family;
4783 	tcp->tcp_wq = ltcp->tcp_wq;
4784 	tcp->tcp_rq = ltcp->tcp_rq;
4785 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4786 	tcp->tcp_detached = B_TRUE;
4787 	SOCK_CONNID_INIT(tcp->tcp_connid);
4788 	if ((err = tcp_init_values(tcp)) != 0) {
4789 		freemsg(tpi_mp);
4790 		return (err);
4791 	}
4792 
4793 	/*
4794 	 * Let's make sure that eager tcp template has enough space to
4795 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4796 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4797 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4798 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4799 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4800 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4801 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4802 	 */
4803 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4804 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4805 
4806 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4807 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4808 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4809 	tcp->tcp_ttl = ltcp->tcp_ttl;
4810 	tcp->tcp_tos = ltcp->tcp_tos;
4811 
4812 	/* Copy the IP+TCP header template from listener to eager */
4813 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4814 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4815 	tcp->tcp_ip6h = NULL;
4816 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4817 	    tcp->tcp_ip_hdr_len);
4818 
4819 	/* Initialize the IP addresses and Ports */
4820 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4821 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4822 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4823 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4824 
4825 	/* Source routing option copyover (reverse it) */
4826 	if (tcps->tcps_rev_src_routes)
4827 		tcp_opt_reverse(tcp, ipha);
4828 
4829 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4830 	ASSERT(!tcp->tcp_tconnind_started);
4831 
4832 	/*
4833 	 * If the SYN contains a credential, it's a loopback packet; attach
4834 	 * the credential to the TPI message.
4835 	 */
4836 	mblk_copycred(tpi_mp, idmp);
4837 
4838 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4839 
4840 	/* Inherit the listener's SSL protection state */
4841 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4842 		kssl_hold_ent(tcp->tcp_kssl_ent);
4843 		tcp->tcp_kssl_pending = B_TRUE;
4844 	}
4845 
4846 	/* Inherit the listener's non-STREAMS flag */
4847 	if (IPCL_IS_NONSTR(lconnp)) {
4848 		connp->conn_flags |= IPCL_NONSTR;
4849 	}
4850 
4851 	return (0);
4852 }
4853 
4854 /*
4855  * sets up conn for ipsec.
4856  * if the first mblk is M_CTL it is consumed and mpp is updated.
4857  * in case of error mpp is freed.
4858  */
4859 conn_t *
4860 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4861 {
4862 	conn_t 		*connp = tcp->tcp_connp;
4863 	conn_t 		*econnp;
4864 	squeue_t 	*new_sqp;
4865 	mblk_t 		*first_mp = *mpp;
4866 	mblk_t		*mp = *mpp;
4867 	boolean_t	mctl_present = B_FALSE;
4868 	uint_t		ipvers;
4869 
4870 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4871 	if (econnp == NULL) {
4872 		freemsg(first_mp);
4873 		return (NULL);
4874 	}
4875 	if (DB_TYPE(mp) == M_CTL) {
4876 		if (mp->b_cont == NULL ||
4877 		    mp->b_cont->b_datap->db_type != M_DATA) {
4878 			freemsg(first_mp);
4879 			return (NULL);
4880 		}
4881 		mp = mp->b_cont;
4882 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4883 			freemsg(first_mp);
4884 			return (NULL);
4885 		}
4886 
4887 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4888 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4889 		mctl_present = B_TRUE;
4890 	} else {
4891 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4892 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4893 	}
4894 
4895 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4896 	DB_CKSUMSTART(mp) = 0;
4897 
4898 	ASSERT(OK_32PTR(mp->b_rptr));
4899 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4900 	if (ipvers == IPV4_VERSION) {
4901 		uint16_t  	*up;
4902 		uint32_t	ports;
4903 		ipha_t		*ipha;
4904 
4905 		ipha = (ipha_t *)mp->b_rptr;
4906 		up = (uint16_t *)((uchar_t *)ipha +
4907 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4908 		ports = *(uint32_t *)up;
4909 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4910 		    ipha->ipha_dst, ipha->ipha_src, ports);
4911 	} else {
4912 		uint16_t  	*up;
4913 		uint32_t	ports;
4914 		uint16_t	ip_hdr_len;
4915 		uint8_t		*nexthdrp;
4916 		ip6_t 		*ip6h;
4917 		tcph_t		*tcph;
4918 
4919 		ip6h = (ip6_t *)mp->b_rptr;
4920 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4921 			ip_hdr_len = IPV6_HDR_LEN;
4922 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4923 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4924 			CONN_DEC_REF(econnp);
4925 			freemsg(first_mp);
4926 			return (NULL);
4927 		}
4928 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4929 		up = (uint16_t *)tcph->th_lport;
4930 		ports = *(uint32_t *)up;
4931 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4932 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4933 	}
4934 
4935 	/*
4936 	 * The caller already ensured that there is a sqp present.
4937 	 */
4938 	econnp->conn_sqp = new_sqp;
4939 	econnp->conn_initial_sqp = new_sqp;
4940 
4941 	if (connp->conn_policy != NULL) {
4942 		ipsec_in_t *ii;
4943 		ii = (ipsec_in_t *)(first_mp->b_rptr);
4944 		ASSERT(ii->ipsec_in_policy == NULL);
4945 		IPPH_REFHOLD(connp->conn_policy);
4946 		ii->ipsec_in_policy = connp->conn_policy;
4947 
4948 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
4949 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
4950 			CONN_DEC_REF(econnp);
4951 			freemsg(first_mp);
4952 			return (NULL);
4953 		}
4954 	}
4955 
4956 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
4957 		CONN_DEC_REF(econnp);
4958 		freemsg(first_mp);
4959 		return (NULL);
4960 	}
4961 
4962 	/*
4963 	 * If we know we have some policy, pass the "IPSEC"
4964 	 * options size TCP uses this adjust the MSS.
4965 	 */
4966 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
4967 	if (mctl_present) {
4968 		freeb(first_mp);
4969 		*mpp = mp;
4970 	}
4971 
4972 	return (econnp);
4973 }
4974 
4975 /*
4976  * tcp_get_conn/tcp_free_conn
4977  *
4978  * tcp_get_conn is used to get a clean tcp connection structure.
4979  * It tries to reuse the connections put on the freelist by the
4980  * time_wait_collector failing which it goes to kmem_cache. This
4981  * way has two benefits compared to just allocating from and
4982  * freeing to kmem_cache.
4983  * 1) The time_wait_collector can free (which includes the cleanup)
4984  * outside the squeue. So when the interrupt comes, we have a clean
4985  * connection sitting in the freelist. Obviously, this buys us
4986  * performance.
4987  *
4988  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
4989  * has multiple disadvantages - tying up the squeue during alloc, and the
4990  * fact that IPSec policy initialization has to happen here which
4991  * requires us sending a M_CTL and checking for it i.e. real ugliness.
4992  * But allocating the conn/tcp in IP land is also not the best since
4993  * we can't check the 'q' and 'q0' which are protected by squeue and
4994  * blindly allocate memory which might have to be freed here if we are
4995  * not allowed to accept the connection. By using the freelist and
4996  * putting the conn/tcp back in freelist, we don't pay a penalty for
4997  * allocating memory without checking 'q/q0' and freeing it if we can't
4998  * accept the connection.
4999  *
5000  * Care should be taken to put the conn back in the same squeue's freelist
5001  * from which it was allocated. Best results are obtained if conn is
5002  * allocated from listener's squeue and freed to the same. Time wait
5003  * collector will free up the freelist is the connection ends up sitting
5004  * there for too long.
5005  */
5006 void *
5007 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5008 {
5009 	tcp_t			*tcp = NULL;
5010 	conn_t			*connp = NULL;
5011 	squeue_t		*sqp = (squeue_t *)arg;
5012 	tcp_squeue_priv_t 	*tcp_time_wait;
5013 	netstack_t		*ns;
5014 	mblk_t			*tcp_rsrv_mp = NULL;
5015 
5016 	tcp_time_wait =
5017 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5018 
5019 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5020 	tcp = tcp_time_wait->tcp_free_list;
5021 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5022 	if (tcp != NULL) {
5023 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5024 		tcp_time_wait->tcp_free_list_cnt--;
5025 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5026 		tcp->tcp_time_wait_next = NULL;
5027 		connp = tcp->tcp_connp;
5028 		connp->conn_flags |= IPCL_REUSED;
5029 
5030 		ASSERT(tcp->tcp_tcps == NULL);
5031 		ASSERT(connp->conn_netstack == NULL);
5032 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5033 		ns = tcps->tcps_netstack;
5034 		netstack_hold(ns);
5035 		connp->conn_netstack = ns;
5036 		tcp->tcp_tcps = tcps;
5037 		TCPS_REFHOLD(tcps);
5038 		ipcl_globalhash_insert(connp);
5039 		return ((void *)connp);
5040 	}
5041 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5042 	/*
5043 	 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
5044 	 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
5045 	 */
5046 	tcp_rsrv_mp = allocb(0, BPRI_HI);
5047 	if (tcp_rsrv_mp == NULL)
5048 		return (NULL);
5049 
5050 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5051 	    tcps->tcps_netstack)) == NULL) {
5052 		freeb(tcp_rsrv_mp);
5053 		return (NULL);
5054 	}
5055 
5056 	tcp = connp->conn_tcp;
5057 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
5058 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5059 
5060 	tcp->tcp_tcps = tcps;
5061 	TCPS_REFHOLD(tcps);
5062 
5063 	return ((void *)connp);
5064 }
5065 
5066 /*
5067  * Update the cached label for the given tcp_t.  This should be called once per
5068  * connection, and before any packets are sent or tcp_process_options is
5069  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5070  */
5071 static boolean_t
5072 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5073 {
5074 	conn_t *connp = tcp->tcp_connp;
5075 
5076 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5077 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5078 		int added;
5079 
5080 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5081 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5082 			return (B_FALSE);
5083 
5084 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5085 		if (added == -1)
5086 			return (B_FALSE);
5087 		tcp->tcp_hdr_len += added;
5088 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5089 		tcp->tcp_ip_hdr_len += added;
5090 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5091 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5092 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5093 			    tcp->tcp_hdr_len);
5094 			if (added == -1)
5095 				return (B_FALSE);
5096 			tcp->tcp_hdr_len += added;
5097 			tcp->tcp_tcph = (tcph_t *)
5098 			    ((uchar_t *)tcp->tcp_tcph + added);
5099 			tcp->tcp_ip_hdr_len += added;
5100 		}
5101 	} else {
5102 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5103 
5104 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5105 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5106 			return (B_FALSE);
5107 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5108 		    &tcp->tcp_label_len, optbuf) != 0)
5109 			return (B_FALSE);
5110 		if (tcp_build_hdrs(tcp) != 0)
5111 			return (B_FALSE);
5112 	}
5113 
5114 	connp->conn_ulp_labeled = 1;
5115 
5116 	return (B_TRUE);
5117 }
5118 
5119 /* BEGIN CSTYLED */
5120 /*
5121  *
5122  * The sockfs ACCEPT path:
5123  * =======================
5124  *
5125  * The eager is now established in its own perimeter as soon as SYN is
5126  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5127  * completes the accept processing on the acceptor STREAM. The sending
5128  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5129  * listener but a TLI/XTI listener completes the accept processing
5130  * on the listener perimeter.
5131  *
5132  * Common control flow for 3 way handshake:
5133  * ----------------------------------------
5134  *
5135  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5136  *					-> tcp_conn_request()
5137  *
5138  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5139  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5140  *
5141  * Sockfs ACCEPT Path:
5142  * -------------------
5143  *
5144  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5145  * as STREAM entry point)
5146  *
5147  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5148  *
5149  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5150  * association (we are not behind eager's squeue but sockfs is protecting us
5151  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5152  * is changed to point at tcp_wput().
5153  *
5154  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5155  * listener (done on listener's perimeter).
5156  *
5157  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5158  * accept.
5159  *
5160  * TLI/XTI client ACCEPT path:
5161  * ---------------------------
5162  *
5163  * soaccept() sends T_CONN_RES on the listener STREAM.
5164  *
5165  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5166  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5167  *
5168  * Locks:
5169  * ======
5170  *
5171  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5172  * and listeners->tcp_eager_next_q.
5173  *
5174  * Referencing:
5175  * ============
5176  *
5177  * 1) We start out in tcp_conn_request by eager placing a ref on
5178  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5179  *
5180  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5181  * doing so we place a ref on the eager. This ref is finally dropped at the
5182  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5183  * reference is dropped by the squeue framework.
5184  *
5185  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5186  *
5187  * The reference must be released by the same entity that added the reference
5188  * In the above scheme, the eager is the entity that adds and releases the
5189  * references. Note that tcp_accept_finish executes in the squeue of the eager
5190  * (albeit after it is attached to the acceptor stream). Though 1. executes
5191  * in the listener's squeue, the eager is nascent at this point and the
5192  * reference can be considered to have been added on behalf of the eager.
5193  *
5194  * Eager getting a Reset or listener closing:
5195  * ==========================================
5196  *
5197  * Once the listener and eager are linked, the listener never does the unlink.
5198  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5199  * a message on all eager perimeter. The eager then does the unlink, clears
5200  * any pointers to the listener's queue and drops the reference to the
5201  * listener. The listener waits in tcp_close outside the squeue until its
5202  * refcount has dropped to 1. This ensures that the listener has waited for
5203  * all eagers to clear their association with the listener.
5204  *
5205  * Similarly, if eager decides to go away, it can unlink itself and close.
5206  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5207  * the reference to eager is still valid because of the extra ref we put
5208  * in tcp_send_conn_ind.
5209  *
5210  * Listener can always locate the eager under the protection
5211  * of the listener->tcp_eager_lock, and then do a refhold
5212  * on the eager during the accept processing.
5213  *
5214  * The acceptor stream accesses the eager in the accept processing
5215  * based on the ref placed on eager before sending T_conn_ind.
5216  * The only entity that can negate this refhold is a listener close
5217  * which is mutually exclusive with an active acceptor stream.
5218  *
5219  * Eager's reference on the listener
5220  * ===================================
5221  *
5222  * If the accept happens (even on a closed eager) the eager drops its
5223  * reference on the listener at the start of tcp_accept_finish. If the
5224  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5225  * the reference is dropped in tcp_closei_local. If the listener closes,
5226  * the reference is dropped in tcp_eager_kill. In all cases the reference
5227  * is dropped while executing in the eager's context (squeue).
5228  */
5229 /* END CSTYLED */
5230 
5231 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5232 
5233 /*
5234  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5235  * tcp_rput_data will not see any SYN packets.
5236  */
5237 /* ARGSUSED */
5238 void
5239 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5240 {
5241 	tcph_t		*tcph;
5242 	uint32_t	seg_seq;
5243 	tcp_t		*eager;
5244 	uint_t		ipvers;
5245 	ipha_t		*ipha;
5246 	ip6_t		*ip6h;
5247 	int		err;
5248 	conn_t		*econnp = NULL;
5249 	squeue_t	*new_sqp;
5250 	mblk_t		*mp1;
5251 	uint_t 		ip_hdr_len;
5252 	conn_t		*connp = (conn_t *)arg;
5253 	tcp_t		*tcp = connp->conn_tcp;
5254 	cred_t		*credp;
5255 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5256 	ip_stack_t	*ipst;
5257 
5258 	if (tcp->tcp_state != TCPS_LISTEN)
5259 		goto error2;
5260 
5261 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5262 
5263 	mutex_enter(&tcp->tcp_eager_lock);
5264 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5265 		mutex_exit(&tcp->tcp_eager_lock);
5266 		TCP_STAT(tcps, tcp_listendrop);
5267 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5268 		if (tcp->tcp_debug) {
5269 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5270 			    "tcp_conn_request: listen backlog (max=%d) "
5271 			    "overflow (%d pending) on %s",
5272 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5273 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5274 		}
5275 		goto error2;
5276 	}
5277 
5278 	if (tcp->tcp_conn_req_cnt_q0 >=
5279 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5280 		/*
5281 		 * Q0 is full. Drop a pending half-open req from the queue
5282 		 * to make room for the new SYN req. Also mark the time we
5283 		 * drop a SYN.
5284 		 *
5285 		 * A more aggressive defense against SYN attack will
5286 		 * be to set the "tcp_syn_defense" flag now.
5287 		 */
5288 		TCP_STAT(tcps, tcp_listendropq0);
5289 		tcp->tcp_last_rcv_lbolt = lbolt64;
5290 		if (!tcp_drop_q0(tcp)) {
5291 			mutex_exit(&tcp->tcp_eager_lock);
5292 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5293 			if (tcp->tcp_debug) {
5294 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5295 				    "tcp_conn_request: listen half-open queue "
5296 				    "(max=%d) full (%d pending) on %s",
5297 				    tcps->tcps_conn_req_max_q0,
5298 				    tcp->tcp_conn_req_cnt_q0,
5299 				    tcp_display(tcp, NULL,
5300 				    DISP_PORT_ONLY));
5301 			}
5302 			goto error2;
5303 		}
5304 	}
5305 	mutex_exit(&tcp->tcp_eager_lock);
5306 
5307 	/*
5308 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5309 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5310 	 * link local address.  If IPSec is enabled, db_struioflag has
5311 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5312 	 * otherwise an error case if neither of them is set.
5313 	 */
5314 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5315 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5316 		DB_CKSUMSTART(mp) = 0;
5317 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5318 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5319 		if (econnp == NULL)
5320 			goto error2;
5321 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5322 		econnp->conn_sqp = new_sqp;
5323 		econnp->conn_initial_sqp = new_sqp;
5324 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5325 		/*
5326 		 * mp is updated in tcp_get_ipsec_conn().
5327 		 */
5328 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5329 		if (econnp == NULL) {
5330 			/*
5331 			 * mp freed by tcp_get_ipsec_conn.
5332 			 */
5333 			return;
5334 		}
5335 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5336 	} else {
5337 		goto error2;
5338 	}
5339 
5340 	ASSERT(DB_TYPE(mp) == M_DATA);
5341 
5342 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5343 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5344 	ASSERT(OK_32PTR(mp->b_rptr));
5345 	if (ipvers == IPV4_VERSION) {
5346 		ipha = (ipha_t *)mp->b_rptr;
5347 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5348 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5349 	} else {
5350 		ip6h = (ip6_t *)mp->b_rptr;
5351 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5352 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5353 	}
5354 
5355 	if (tcp->tcp_family == AF_INET) {
5356 		ASSERT(ipvers == IPV4_VERSION);
5357 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5358 	} else {
5359 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5360 	}
5361 
5362 	if (err)
5363 		goto error3;
5364 
5365 	eager = econnp->conn_tcp;
5366 	ASSERT(eager->tcp_ordrel_mp == NULL);
5367 
5368 	if (!IPCL_IS_NONSTR(econnp)) {
5369 		/*
5370 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
5371 		 * at close time, we will always have that to send up.
5372 		 * Otherwise, we need to do special handling in case the
5373 		 * allocation fails at that time.
5374 		 */
5375 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5376 			goto error3;
5377 	}
5378 	/* Inherit various TCP parameters from the listener */
5379 	eager->tcp_naglim = tcp->tcp_naglim;
5380 	eager->tcp_first_timer_threshold = tcp->tcp_first_timer_threshold;
5381 	eager->tcp_second_timer_threshold = tcp->tcp_second_timer_threshold;
5382 
5383 	eager->tcp_first_ctimer_threshold = tcp->tcp_first_ctimer_threshold;
5384 	eager->tcp_second_ctimer_threshold = tcp->tcp_second_ctimer_threshold;
5385 
5386 	/*
5387 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5388 	 * If it does not, the eager's receive window will be set to the
5389 	 * listener's receive window later in this function.
5390 	 */
5391 	eager->tcp_rwnd = 0;
5392 
5393 	/*
5394 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5395 	 * calling tcp_process_options() where tcp_mss_set() is called
5396 	 * to set the initial cwnd.
5397 	 */
5398 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5399 
5400 	/*
5401 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5402 	 * zone id before the accept is completed in tcp_wput_accept().
5403 	 */
5404 	econnp->conn_zoneid = connp->conn_zoneid;
5405 	econnp->conn_allzones = connp->conn_allzones;
5406 
5407 	/* Copy nexthop information from listener to eager */
5408 	if (connp->conn_nexthop_set) {
5409 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5410 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5411 	}
5412 
5413 	/*
5414 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5415 	 * eager is accepted
5416 	 */
5417 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5418 	crhold(credp);
5419 
5420 	ASSERT(econnp->conn_effective_cred == NULL);
5421 	if (is_system_labeled()) {
5422 		cred_t *cr;
5423 		ts_label_t *tsl;
5424 
5425 		/*
5426 		 * If this is an MLP connection or a MAC-Exempt connection
5427 		 * with an unlabeled node, packets are to be
5428 		 * exchanged using the security label of the received
5429 		 * SYN packet instead of the server application's label.
5430 		 */
5431 		if ((cr = msg_getcred(mp, NULL)) != NULL &&
5432 		    (tsl = crgetlabel(cr)) != NULL &&
5433 		    (connp->conn_mlp_type != mlptSingle ||
5434 		    (connp->conn_mac_exempt == B_TRUE &&
5435 		    (tsl->tsl_flags & TSLF_UNLABELED)))) {
5436 			if ((econnp->conn_effective_cred =
5437 			    copycred_from_tslabel(econnp->conn_cred,
5438 			    tsl, KM_NOSLEEP)) != NULL) {
5439 				DTRACE_PROBE2(
5440 				    syn_accept_peerlabel,
5441 				    conn_t *, econnp, cred_t *,
5442 				    econnp->conn_effective_cred);
5443 			} else {
5444 				DTRACE_PROBE3(
5445 				    tx__ip__log__error__set__eagercred__tcp,
5446 				    char *,
5447 				    "SYN mp(1) label on eager connp(2) failed",
5448 				    mblk_t *, mp, conn_t *, econnp);
5449 				goto error3;
5450 			}
5451 		} else {
5452 			DTRACE_PROBE2(syn_accept, conn_t *,
5453 			    econnp, cred_t *, econnp->conn_cred)
5454 		}
5455 
5456 		/*
5457 		 * Verify the destination is allowed to receive packets
5458 		 * at the security label of the SYN-ACK we are generating.
5459 		 * tsol_check_dest() may create a new effective cred for
5460 		 * this connection with a modified label or label flags.
5461 		 */
5462 		if (IN6_IS_ADDR_V4MAPPED(&econnp->conn_remv6)) {
5463 			uint32_t dst;
5464 			IN6_V4MAPPED_TO_IPADDR(&econnp->conn_remv6, dst);
5465 			err = tsol_check_dest(CONN_CRED(econnp), &dst,
5466 			    IPV4_VERSION, B_FALSE, &cr);
5467 		} else {
5468 			err = tsol_check_dest(CONN_CRED(econnp),
5469 			    &econnp->conn_remv6, IPV6_VERSION,
5470 			    B_FALSE, &cr);
5471 		}
5472 		if (err != 0)
5473 			goto error3;
5474 		if (cr != NULL) {
5475 			if (econnp->conn_effective_cred != NULL)
5476 				crfree(econnp->conn_effective_cred);
5477 			econnp->conn_effective_cred = cr;
5478 		}
5479 
5480 		/*
5481 		 * Generate the security label to be used in the text of
5482 		 * this connection's outgoing packets.
5483 		 */
5484 		if (!tcp_update_label(eager, CONN_CRED(econnp))) {
5485 			DTRACE_PROBE3(
5486 			    tx__ip__log__error__connrequest__tcp,
5487 			    char *, "eager connp(1) label on SYN mp(2) failed",
5488 			    conn_t *, econnp, mblk_t *, mp);
5489 			goto error3;
5490 		}
5491 	}
5492 
5493 	eager->tcp_hard_binding = B_TRUE;
5494 
5495 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5496 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5497 
5498 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5499 	if (err != 0) {
5500 		tcp_bind_hash_remove(eager);
5501 		goto error3;
5502 	}
5503 
5504 	/*
5505 	 * No need to check for multicast destination since ip will only pass
5506 	 * up multicasts to those that have expressed interest
5507 	 * TODO: what about rejecting broadcasts?
5508 	 * Also check that source is not a multicast or broadcast address.
5509 	 */
5510 	eager->tcp_state = TCPS_SYN_RCVD;
5511 
5512 
5513 	/*
5514 	 * There should be no ire in the mp as we are being called after
5515 	 * receiving the SYN.
5516 	 */
5517 	ASSERT(tcp_ire_mp(&mp) == NULL);
5518 
5519 	/*
5520 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5521 	 */
5522 
5523 	if (tcp_adapt_ire(eager, NULL) == 0) {
5524 		/* Undo the bind_hash_insert */
5525 		tcp_bind_hash_remove(eager);
5526 		goto error3;
5527 	}
5528 
5529 	/* Process all TCP options. */
5530 	tcp_process_options(eager, tcph);
5531 
5532 	/* Is the other end ECN capable? */
5533 	if (tcps->tcps_ecn_permitted >= 1 &&
5534 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5535 		eager->tcp_ecn_ok = B_TRUE;
5536 	}
5537 
5538 	/*
5539 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5540 	 * window size changed via SO_RCVBUF option.  First round up the
5541 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5542 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5543 	 * setting.
5544 	 *
5545 	 * Note if there is a rpipe metric associated with the remote host,
5546 	 * we should not inherit receive window size from listener.
5547 	 */
5548 	eager->tcp_rwnd = MSS_ROUNDUP(
5549 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5550 	    eager->tcp_rwnd), eager->tcp_mss);
5551 	if (eager->tcp_snd_ws_ok)
5552 		tcp_set_ws_value(eager);
5553 	/*
5554 	 * Note that this is the only place tcp_rwnd_set() is called for
5555 	 * accepting a connection.  We need to call it here instead of
5556 	 * after the 3-way handshake because we need to tell the other
5557 	 * side our rwnd in the SYN-ACK segment.
5558 	 */
5559 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5560 
5561 	/*
5562 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5563 	 * via soaccept()->soinheritoptions() which essentially applies
5564 	 * all the listener options to the new STREAM. The options that we
5565 	 * need to take care of are:
5566 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5567 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5568 	 * SO_SNDBUF, SO_RCVBUF.
5569 	 *
5570 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5571 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5572 	 *		tcp_maxpsz_set() gets called later from
5573 	 *		tcp_accept_finish(), the option takes effect.
5574 	 *
5575 	 */
5576 	/* Set the TCP options */
5577 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5578 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5579 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5580 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5581 	eager->tcp_oobinline = tcp->tcp_oobinline;
5582 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5583 	eager->tcp_broadcast = tcp->tcp_broadcast;
5584 	eager->tcp_useloopback = tcp->tcp_useloopback;
5585 	eager->tcp_dontroute = tcp->tcp_dontroute;
5586 	eager->tcp_debug = tcp->tcp_debug;
5587 	eager->tcp_linger = tcp->tcp_linger;
5588 	eager->tcp_lingertime = tcp->tcp_lingertime;
5589 	if (tcp->tcp_ka_enabled)
5590 		eager->tcp_ka_enabled = 1;
5591 
5592 	/* Set the IP options */
5593 	econnp->conn_broadcast = connp->conn_broadcast;
5594 	econnp->conn_loopback = connp->conn_loopback;
5595 	econnp->conn_dontroute = connp->conn_dontroute;
5596 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5597 
5598 	/* Put a ref on the listener for the eager. */
5599 	CONN_INC_REF(connp);
5600 	mutex_enter(&tcp->tcp_eager_lock);
5601 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5602 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5603 	tcp->tcp_eager_next_q0 = eager;
5604 	eager->tcp_eager_prev_q0 = tcp;
5605 
5606 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5607 	eager->tcp_listener = tcp;
5608 	eager->tcp_saved_listener = tcp;
5609 
5610 	/*
5611 	 * Tag this detached tcp vector for later retrieval
5612 	 * by our listener client in tcp_accept().
5613 	 */
5614 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5615 	tcp->tcp_conn_req_cnt_q0++;
5616 	if (++tcp->tcp_conn_req_seqnum == -1) {
5617 		/*
5618 		 * -1 is "special" and defined in TPI as something
5619 		 * that should never be used in T_CONN_IND
5620 		 */
5621 		++tcp->tcp_conn_req_seqnum;
5622 	}
5623 	mutex_exit(&tcp->tcp_eager_lock);
5624 
5625 	if (tcp->tcp_syn_defense) {
5626 		/* Don't drop the SYN that comes from a good IP source */
5627 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5628 		if (addr_cache != NULL && eager->tcp_remote ==
5629 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5630 			eager->tcp_dontdrop = B_TRUE;
5631 		}
5632 	}
5633 
5634 	/*
5635 	 * We need to insert the eager in its own perimeter but as soon
5636 	 * as we do that, we expose the eager to the classifier and
5637 	 * should not touch any field outside the eager's perimeter.
5638 	 * So do all the work necessary before inserting the eager
5639 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5640 	 * will succeed but undo everything if it fails.
5641 	 */
5642 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5643 	eager->tcp_irs = seg_seq;
5644 	eager->tcp_rack = seg_seq;
5645 	eager->tcp_rnxt = seg_seq + 1;
5646 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5647 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5648 	eager->tcp_state = TCPS_SYN_RCVD;
5649 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5650 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5651 	if (mp1 == NULL) {
5652 		/*
5653 		 * Increment the ref count as we are going to
5654 		 * enqueueing an mp in squeue
5655 		 */
5656 		CONN_INC_REF(econnp);
5657 		goto error;
5658 	}
5659 
5660 	/*
5661 	 * Note that in theory this should use the current pid
5662 	 * so that getpeerucred on the client returns the actual listener
5663 	 * that does accept. But accept() hasn't been called yet. We could use
5664 	 * the pid of the process that did bind/listen on the server.
5665 	 * However, with common usage like inetd() the bind/listen can be done
5666 	 * by a different process than the accept().
5667 	 * Hence we do the simple thing of using the open pid here.
5668 	 * Note that db_credp is set later in tcp_send_data().
5669 	 */
5670 	mblk_setcred(mp1, credp, tcp->tcp_cpid);
5671 	eager->tcp_cpid = tcp->tcp_cpid;
5672 	eager->tcp_open_time = lbolt64;
5673 
5674 	/*
5675 	 * We need to start the rto timer. In normal case, we start
5676 	 * the timer after sending the packet on the wire (or at
5677 	 * least believing that packet was sent by waiting for
5678 	 * CALL_IP_WPUT() to return). Since this is the first packet
5679 	 * being sent on the wire for the eager, our initial tcp_rto
5680 	 * is at least tcp_rexmit_interval_min which is a fairly
5681 	 * large value to allow the algorithm to adjust slowly to large
5682 	 * fluctuations of RTT during first few transmissions.
5683 	 *
5684 	 * Starting the timer first and then sending the packet in this
5685 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5686 	 * is of the order of several 100ms and starting the timer
5687 	 * first and then sending the packet will result in difference
5688 	 * of few micro seconds.
5689 	 *
5690 	 * Without this optimization, we are forced to hold the fanout
5691 	 * lock across the ipcl_bind_insert() and sending the packet
5692 	 * so that we don't race against an incoming packet (maybe RST)
5693 	 * for this eager.
5694 	 *
5695 	 * It is necessary to acquire an extra reference on the eager
5696 	 * at this point and hold it until after tcp_send_data() to
5697 	 * ensure against an eager close race.
5698 	 */
5699 
5700 	CONN_INC_REF(eager->tcp_connp);
5701 
5702 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5703 
5704 	/*
5705 	 * Insert the eager in its own perimeter now. We are ready to deal
5706 	 * with any packets on eager.
5707 	 */
5708 	if (eager->tcp_ipversion == IPV4_VERSION) {
5709 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5710 			goto error;
5711 		}
5712 	} else {
5713 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5714 			goto error;
5715 		}
5716 	}
5717 
5718 	/* mark conn as fully-bound */
5719 	econnp->conn_fully_bound = B_TRUE;
5720 
5721 	/* Send the SYN-ACK */
5722 	tcp_send_data(eager, eager->tcp_wq, mp1);
5723 	CONN_DEC_REF(eager->tcp_connp);
5724 	freemsg(mp);
5725 
5726 	return;
5727 error:
5728 	freemsg(mp1);
5729 	eager->tcp_closemp_used = B_TRUE;
5730 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5731 	mp1 = &eager->tcp_closemp;
5732 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5733 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5734 
5735 	/*
5736 	 * If a connection already exists, send the mp to that connections so
5737 	 * that it can be appropriately dealt with.
5738 	 */
5739 	ipst = tcps->tcps_netstack->netstack_ip;
5740 
5741 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5742 		if (!IPCL_IS_CONNECTED(econnp)) {
5743 			/*
5744 			 * Something bad happened. ipcl_conn_insert()
5745 			 * failed because a connection already existed
5746 			 * in connected hash but we can't find it
5747 			 * anymore (someone blew it away). Just
5748 			 * free this message and hopefully remote
5749 			 * will retransmit at which time the SYN can be
5750 			 * treated as a new connection or dealth with
5751 			 * a TH_RST if a connection already exists.
5752 			 */
5753 			CONN_DEC_REF(econnp);
5754 			freemsg(mp);
5755 		} else {
5756 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5757 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5758 		}
5759 	} else {
5760 		/* Nobody wants this packet */
5761 		freemsg(mp);
5762 	}
5763 	return;
5764 error3:
5765 	CONN_DEC_REF(econnp);
5766 error2:
5767 	freemsg(mp);
5768 }
5769 
5770 /*
5771  * In an ideal case of vertical partition in NUMA architecture, its
5772  * beneficial to have the listener and all the incoming connections
5773  * tied to the same squeue. The other constraint is that incoming
5774  * connections should be tied to the squeue attached to interrupted
5775  * CPU for obvious locality reason so this leaves the listener to
5776  * be tied to the same squeue. Our only problem is that when listener
5777  * is binding, the CPU that will get interrupted by the NIC whose
5778  * IP address the listener is binding to is not even known. So
5779  * the code below allows us to change that binding at the time the
5780  * CPU is interrupted by virtue of incoming connection's squeue.
5781  *
5782  * This is usefull only in case of a listener bound to a specific IP
5783  * address. For other kind of listeners, they get bound the
5784  * very first time and there is no attempt to rebind them.
5785  */
5786 void
5787 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5788 {
5789 	conn_t		*connp = (conn_t *)arg;
5790 	squeue_t	*sqp = (squeue_t *)arg2;
5791 	squeue_t	*new_sqp;
5792 	uint32_t	conn_flags;
5793 
5794 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5795 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5796 	} else {
5797 		goto done;
5798 	}
5799 
5800 	if (connp->conn_fanout == NULL)
5801 		goto done;
5802 
5803 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5804 		mutex_enter(&connp->conn_fanout->connf_lock);
5805 		mutex_enter(&connp->conn_lock);
5806 		/*
5807 		 * No one from read or write side can access us now
5808 		 * except for already queued packets on this squeue.
5809 		 * But since we haven't changed the squeue yet, they
5810 		 * can't execute. If they are processed after we have
5811 		 * changed the squeue, they are sent back to the
5812 		 * correct squeue down below.
5813 		 * But a listner close can race with processing of
5814 		 * incoming SYN. If incoming SYN processing changes
5815 		 * the squeue then the listener close which is waiting
5816 		 * to enter the squeue would operate on the wrong
5817 		 * squeue. Hence we don't change the squeue here unless
5818 		 * the refcount is exactly the minimum refcount. The
5819 		 * minimum refcount of 4 is counted as - 1 each for
5820 		 * TCP and IP, 1 for being in the classifier hash, and
5821 		 * 1 for the mblk being processed.
5822 		 */
5823 
5824 		if (connp->conn_ref != 4 ||
5825 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5826 			mutex_exit(&connp->conn_lock);
5827 			mutex_exit(&connp->conn_fanout->connf_lock);
5828 			goto done;
5829 		}
5830 		if (connp->conn_sqp != new_sqp) {
5831 			while (connp->conn_sqp != new_sqp)
5832 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5833 		}
5834 
5835 		do {
5836 			conn_flags = connp->conn_flags;
5837 			conn_flags |= IPCL_FULLY_BOUND;
5838 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5839 			    conn_flags);
5840 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5841 
5842 		mutex_exit(&connp->conn_fanout->connf_lock);
5843 		mutex_exit(&connp->conn_lock);
5844 	}
5845 
5846 done:
5847 	if (connp->conn_sqp != sqp) {
5848 		CONN_INC_REF(connp);
5849 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5850 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5851 	} else {
5852 		tcp_conn_request(connp, mp, sqp);
5853 	}
5854 }
5855 
5856 /*
5857  * Successful connect request processing begins when our client passes
5858  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5859  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5860  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5861  *   upstream <- tcp_rput()		<- IP
5862  * After various error checks are completed, tcp_tpi_connect() lays
5863  * the target address and port into the composite header template,
5864  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5865  * request followed by an IRE request, and passes the three mblk message
5866  * down to IP looking like this:
5867  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5868  * Processing continues in tcp_rput() when we receive the following message:
5869  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5870  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5871  * to fire off the connection request, and then passes the T_OK_ACK mblk
5872  * upstream that we filled in below.  There are, of course, numerous
5873  * error conditions along the way which truncate the processing described
5874  * above.
5875  */
5876 static void
5877 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5878 {
5879 	sin_t		*sin;
5880 	queue_t		*q = tcp->tcp_wq;
5881 	struct T_conn_req	*tcr;
5882 	struct sockaddr	*sa;
5883 	socklen_t	len;
5884 	int		error;
5885 	cred_t		*cr;
5886 	pid_t		cpid;
5887 
5888 	/*
5889 	 * All Solaris components should pass a db_credp
5890 	 * for this TPI message, hence we ASSERT.
5891 	 * But in case there is some other M_PROTO that looks
5892 	 * like a TPI message sent by some other kernel
5893 	 * component, we check and return an error.
5894 	 */
5895 	cr = msg_getcred(mp, &cpid);
5896 	ASSERT(cr != NULL);
5897 	if (cr == NULL) {
5898 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5899 		return;
5900 	}
5901 
5902 	tcr = (struct T_conn_req *)mp->b_rptr;
5903 
5904 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5905 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5906 		tcp_err_ack(tcp, mp, TPROTO, 0);
5907 		return;
5908 	}
5909 
5910 	/*
5911 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5912 	 * will always have that to send up.  Otherwise, we need to do
5913 	 * special handling in case the allocation fails at that time.
5914 	 * If the end point is TPI, the tcp_t can be reused and the
5915 	 * tcp_ordrel_mp may be allocated already.
5916 	 */
5917 	if (tcp->tcp_ordrel_mp == NULL) {
5918 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5919 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5920 			return;
5921 		}
5922 	}
5923 
5924 	/*
5925 	 * Determine packet type based on type of address passed in
5926 	 * the request should contain an IPv4 or IPv6 address.
5927 	 * Make sure that address family matches the type of
5928 	 * family of the the address passed down
5929 	 */
5930 	switch (tcr->DEST_length) {
5931 	default:
5932 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5933 		return;
5934 
5935 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5936 		/*
5937 		 * XXX: The check for valid DEST_length was not there
5938 		 * in earlier releases and some buggy
5939 		 * TLI apps (e.g Sybase) got away with not feeding
5940 		 * in sin_zero part of address.
5941 		 * We allow that bug to keep those buggy apps humming.
5942 		 * Test suites require the check on DEST_length.
5943 		 * We construct a new mblk with valid DEST_length
5944 		 * free the original so the rest of the code does
5945 		 * not have to keep track of this special shorter
5946 		 * length address case.
5947 		 */
5948 		mblk_t *nmp;
5949 		struct T_conn_req *ntcr;
5950 		sin_t *nsin;
5951 
5952 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5953 		    tcr->OPT_length, BPRI_HI);
5954 		if (nmp == NULL) {
5955 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5956 			return;
5957 		}
5958 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5959 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5960 		ntcr->PRIM_type = T_CONN_REQ;
5961 		ntcr->DEST_length = sizeof (sin_t);
5962 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5963 
5964 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5965 		*nsin = sin_null;
5966 		/* Get pointer to shorter address to copy from original mp */
5967 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5968 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5969 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5970 			freemsg(nmp);
5971 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5972 			return;
5973 		}
5974 		nsin->sin_family = sin->sin_family;
5975 		nsin->sin_port = sin->sin_port;
5976 		nsin->sin_addr = sin->sin_addr;
5977 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5978 		nmp->b_wptr = (uchar_t *)&nsin[1];
5979 		if (tcr->OPT_length != 0) {
5980 			ntcr->OPT_length = tcr->OPT_length;
5981 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5982 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5983 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5984 			    tcr->OPT_length);
5985 			nmp->b_wptr += tcr->OPT_length;
5986 		}
5987 		freemsg(mp);	/* original mp freed */
5988 		mp = nmp;	/* re-initialize original variables */
5989 		tcr = ntcr;
5990 	}
5991 	/* FALLTHRU */
5992 
5993 	case sizeof (sin_t):
5994 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5995 		    sizeof (sin_t));
5996 		len = sizeof (sin_t);
5997 		break;
5998 
5999 	case sizeof (sin6_t):
6000 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6001 		    sizeof (sin6_t));
6002 		len = sizeof (sin6_t);
6003 		break;
6004 	}
6005 
6006 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6007 	if (error != 0) {
6008 		tcp_err_ack(tcp, mp, TSYSERR, error);
6009 		return;
6010 	}
6011 
6012 	/*
6013 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6014 	 * should key on their sequence number and cut them loose.
6015 	 */
6016 
6017 	/*
6018 	 * If options passed in, feed it for verification and handling
6019 	 */
6020 	if (tcr->OPT_length != 0) {
6021 		mblk_t	*ok_mp;
6022 		mblk_t	*discon_mp;
6023 		mblk_t  *conn_opts_mp;
6024 		int t_error, sys_error, do_disconnect;
6025 
6026 		conn_opts_mp = NULL;
6027 
6028 		if (tcp_conprim_opt_process(tcp, mp,
6029 		    &do_disconnect, &t_error, &sys_error) < 0) {
6030 			if (do_disconnect) {
6031 				ASSERT(t_error == 0 && sys_error == 0);
6032 				discon_mp = mi_tpi_discon_ind(NULL,
6033 				    ECONNREFUSED, 0);
6034 				if (!discon_mp) {
6035 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6036 					    TSYSERR, ENOMEM);
6037 					return;
6038 				}
6039 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6040 				if (!ok_mp) {
6041 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6042 					    TSYSERR, ENOMEM);
6043 					return;
6044 				}
6045 				qreply(q, ok_mp);
6046 				qreply(q, discon_mp); /* no flush! */
6047 			} else {
6048 				ASSERT(t_error != 0);
6049 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6050 				    sys_error);
6051 			}
6052 			return;
6053 		}
6054 		/*
6055 		 * Success in setting options, the mp option buffer represented
6056 		 * by OPT_length/offset has been potentially modified and
6057 		 * contains results of option processing. We copy it in
6058 		 * another mp to save it for potentially influencing returning
6059 		 * it in T_CONN_CONN.
6060 		 */
6061 		if (tcr->OPT_length != 0) { /* there are resulting options */
6062 			conn_opts_mp = copyb(mp);
6063 			if (!conn_opts_mp) {
6064 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6065 				    TSYSERR, ENOMEM);
6066 				return;
6067 			}
6068 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6069 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6070 			/*
6071 			 * Note:
6072 			 * These resulting option negotiation can include any
6073 			 * end-to-end negotiation options but there no such
6074 			 * thing (yet?) in our TCP/IP.
6075 			 */
6076 		}
6077 	}
6078 
6079 	/* call the non-TPI version */
6080 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
6081 	if (error < 0) {
6082 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6083 	} else if (error > 0) {
6084 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6085 	} else {
6086 		mp = mi_tpi_ok_ack_alloc(mp);
6087 	}
6088 
6089 	/*
6090 	 * Note: Code below is the "failure" case
6091 	 */
6092 	/* return error ack and blow away saved option results if any */
6093 connect_failed:
6094 	if (mp != NULL)
6095 		putnext(tcp->tcp_rq, mp);
6096 	else {
6097 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6098 		    TSYSERR, ENOMEM);
6099 	}
6100 }
6101 
6102 /*
6103  * Handle connect to IPv4 destinations, including connections for AF_INET6
6104  * sockets connecting to IPv4 mapped IPv6 destinations.
6105  */
6106 static int
6107 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6108     uint_t srcid, cred_t *cr, pid_t pid)
6109 {
6110 	tcph_t	*tcph;
6111 	mblk_t	*mp;
6112 	ipaddr_t dstaddr = *dstaddrp;
6113 	int32_t	oldstate;
6114 	uint16_t lport;
6115 	int	error = 0;
6116 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6117 
6118 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6119 
6120 	/* Check for attempt to connect to INADDR_ANY */
6121 	if (dstaddr == INADDR_ANY)  {
6122 		/*
6123 		 * SunOS 4.x and 4.3 BSD allow an application
6124 		 * to connect a TCP socket to INADDR_ANY.
6125 		 * When they do this, the kernel picks the
6126 		 * address of one interface and uses it
6127 		 * instead.  The kernel usually ends up
6128 		 * picking the address of the loopback
6129 		 * interface.  This is an undocumented feature.
6130 		 * However, we provide the same thing here
6131 		 * in order to have source and binary
6132 		 * compatibility with SunOS 4.x.
6133 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6134 		 * generate the T_CONN_CON.
6135 		 */
6136 		dstaddr = htonl(INADDR_LOOPBACK);
6137 		*dstaddrp = dstaddr;
6138 	}
6139 
6140 	/* Handle __sin6_src_id if socket not bound to an IP address */
6141 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6142 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6143 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6144 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6145 		    tcp->tcp_ipha->ipha_src);
6146 	}
6147 
6148 	/*
6149 	 * Don't let an endpoint connect to itself.  Note that
6150 	 * the test here does not catch the case where the
6151 	 * source IP addr was left unspecified by the user. In
6152 	 * this case, the source addr is set in tcp_adapt_ire()
6153 	 * using the reply to the T_BIND message that we send
6154 	 * down to IP here and the check is repeated in tcp_rput_other.
6155 	 */
6156 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6157 	    dstport == tcp->tcp_lport) {
6158 		error = -TBADADDR;
6159 		goto failed;
6160 	}
6161 
6162 	/*
6163 	 * Verify the destination is allowed to receive packets
6164 	 * at the security label of the connection we are initiating.
6165 	 * tsol_check_dest() may create a new effective cred for this
6166 	 * connection with a modified label or label flags.
6167 	 */
6168 	if (is_system_labeled()) {
6169 		ASSERT(tcp->tcp_connp->conn_effective_cred == NULL);
6170 		if ((error = tsol_check_dest(CONN_CRED(tcp->tcp_connp),
6171 		    &dstaddr, IPV4_VERSION, tcp->tcp_connp->conn_mac_exempt,
6172 		    &tcp->tcp_connp->conn_effective_cred)) != 0) {
6173 			if (error != EHOSTUNREACH)
6174 				error = -TSYSERR;
6175 			goto failed;
6176 		}
6177 	}
6178 
6179 	tcp->tcp_ipha->ipha_dst = dstaddr;
6180 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6181 
6182 	/*
6183 	 * Massage a source route if any putting the first hop
6184 	 * in iph_dst. Compute a starting value for the checksum which
6185 	 * takes into account that the original iph_dst should be
6186 	 * included in the checksum but that ip will include the
6187 	 * first hop in the source route in the tcp checksum.
6188 	 */
6189 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6190 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6191 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6192 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6193 	if ((int)tcp->tcp_sum < 0)
6194 		tcp->tcp_sum--;
6195 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6196 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6197 	    (tcp->tcp_sum >> 16));
6198 	tcph = tcp->tcp_tcph;
6199 	*(uint16_t *)tcph->th_fport = dstport;
6200 	tcp->tcp_fport = dstport;
6201 
6202 	oldstate = tcp->tcp_state;
6203 	/*
6204 	 * At this point the remote destination address and remote port fields
6205 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6206 	 * have to see which state tcp was in so we can take apropriate action.
6207 	 */
6208 	if (oldstate == TCPS_IDLE) {
6209 		/*
6210 		 * We support a quick connect capability here, allowing
6211 		 * clients to transition directly from IDLE to SYN_SENT
6212 		 * tcp_bindi will pick an unused port, insert the connection
6213 		 * in the bind hash and transition to BOUND state.
6214 		 */
6215 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6216 		    tcp, B_TRUE);
6217 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6218 		    B_FALSE, B_FALSE);
6219 		if (lport == 0) {
6220 			error = -TNOADDR;
6221 			goto failed;
6222 		}
6223 	}
6224 	tcp->tcp_state = TCPS_SYN_SENT;
6225 
6226 	mp = allocb(sizeof (ire_t), BPRI_HI);
6227 	if (mp == NULL) {
6228 		tcp->tcp_state = oldstate;
6229 		error = ENOMEM;
6230 		goto failed;
6231 	}
6232 
6233 	mp->b_wptr += sizeof (ire_t);
6234 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6235 	tcp->tcp_hard_binding = 1;
6236 
6237 	/*
6238 	 * We need to make sure that the conn_recv is set to a non-null
6239 	 * value before we insert the conn_t into the classifier table.
6240 	 * This is to avoid a race with an incoming packet which does
6241 	 * an ipcl_classify().
6242 	 */
6243 	tcp->tcp_connp->conn_recv = tcp_input;
6244 
6245 	if (tcp->tcp_family == AF_INET) {
6246 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6247 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6248 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6249 	} else {
6250 		in6_addr_t v6src;
6251 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6252 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6253 		} else {
6254 			v6src = tcp->tcp_ip6h->ip6_src;
6255 		}
6256 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6257 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6258 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6259 	}
6260 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6261 	tcp->tcp_active_open = 1;
6262 
6263 
6264 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6265 failed:
6266 	/* return error ack and blow away saved option results if any */
6267 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6268 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6269 	return (error);
6270 }
6271 
6272 /*
6273  * Handle connect to IPv6 destinations.
6274  */
6275 static int
6276 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6277     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6278 {
6279 	tcph_t	*tcph;
6280 	mblk_t	*mp;
6281 	ip6_rthdr_t *rth;
6282 	int32_t  oldstate;
6283 	uint16_t lport;
6284 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6285 	int	error = 0;
6286 	conn_t	*connp = tcp->tcp_connp;
6287 
6288 	ASSERT(tcp->tcp_family == AF_INET6);
6289 
6290 	/*
6291 	 * If we're here, it means that the destination address is a native
6292 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6293 	 * reason why it might not be IPv6 is if the socket was bound to an
6294 	 * IPv4-mapped IPv6 address.
6295 	 */
6296 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6297 		return (-TBADADDR);
6298 	}
6299 
6300 	/*
6301 	 * Interpret a zero destination to mean loopback.
6302 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6303 	 * generate the T_CONN_CON.
6304 	 */
6305 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6306 		*dstaddrp = ipv6_loopback;
6307 	}
6308 
6309 	/* Handle __sin6_src_id if socket not bound to an IP address */
6310 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6311 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6312 		    connp->conn_zoneid, tcps->tcps_netstack);
6313 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6314 	}
6315 
6316 	/*
6317 	 * Take care of the scope_id now and add ip6i_t
6318 	 * if ip6i_t is not already allocated through TCP
6319 	 * sticky options. At this point tcp_ip6h does not
6320 	 * have dst info, thus use dstaddrp.
6321 	 */
6322 	if (scope_id != 0 &&
6323 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6324 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6325 		ip6i_t  *ip6i;
6326 
6327 		ipp->ipp_ifindex = scope_id;
6328 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6329 
6330 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6331 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6332 			/* Already allocated */
6333 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6334 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6335 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6336 		} else {
6337 			int reterr;
6338 
6339 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6340 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6341 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6342 			reterr = tcp_build_hdrs(tcp);
6343 			if (reterr != 0)
6344 				goto failed;
6345 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6346 		}
6347 	}
6348 
6349 	/*
6350 	 * Don't let an endpoint connect to itself.  Note that
6351 	 * the test here does not catch the case where the
6352 	 * source IP addr was left unspecified by the user. In
6353 	 * this case, the source addr is set in tcp_adapt_ire()
6354 	 * using the reply to the T_BIND message that we send
6355 	 * down to IP here and the check is repeated in tcp_rput_other.
6356 	 */
6357 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6358 	    (dstport == tcp->tcp_lport)) {
6359 		error = -TBADADDR;
6360 		goto failed;
6361 	}
6362 
6363 	/*
6364 	 * Verify the destination is allowed to receive packets
6365 	 * at the security label of the connection we are initiating.
6366 	 * check_dest may create a new effective cred for this
6367 	 * connection with a modified label or label flags.
6368 	 */
6369 	if (is_system_labeled()) {
6370 		ASSERT(tcp->tcp_connp->conn_effective_cred == NULL);
6371 		if ((error = tsol_check_dest(CONN_CRED(tcp->tcp_connp),
6372 		    dstaddrp, IPV6_VERSION, tcp->tcp_connp->conn_mac_exempt,
6373 		    &tcp->tcp_connp->conn_effective_cred)) != 0) {
6374 			if (error != EHOSTUNREACH)
6375 				error = -TSYSERR;
6376 			goto failed;
6377 		}
6378 	}
6379 
6380 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6381 	tcp->tcp_remote_v6 = *dstaddrp;
6382 	tcp->tcp_ip6h->ip6_vcf =
6383 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6384 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6385 
6386 	/*
6387 	 * Massage a routing header (if present) putting the first hop
6388 	 * in ip6_dst. Compute a starting value for the checksum which
6389 	 * takes into account that the original ip6_dst should be
6390 	 * included in the checksum but that ip will include the
6391 	 * first hop in the source route in the tcp checksum.
6392 	 */
6393 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6394 	if (rth != NULL) {
6395 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6396 		    tcps->tcps_netstack);
6397 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6398 		    (tcp->tcp_sum >> 16));
6399 	} else {
6400 		tcp->tcp_sum = 0;
6401 	}
6402 
6403 	tcph = tcp->tcp_tcph;
6404 	*(uint16_t *)tcph->th_fport = dstport;
6405 	tcp->tcp_fport = dstport;
6406 
6407 	oldstate = tcp->tcp_state;
6408 	/*
6409 	 * At this point the remote destination address and remote port fields
6410 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6411 	 * have to see which state tcp was in so we can take apropriate action.
6412 	 */
6413 	if (oldstate == TCPS_IDLE) {
6414 		/*
6415 		 * We support a quick connect capability here, allowing
6416 		 * clients to transition directly from IDLE to SYN_SENT
6417 		 * tcp_bindi will pick an unused port, insert the connection
6418 		 * in the bind hash and transition to BOUND state.
6419 		 */
6420 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6421 		    tcp, B_TRUE);
6422 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6423 		    B_FALSE, B_FALSE);
6424 		if (lport == 0) {
6425 			error = -TNOADDR;
6426 			goto failed;
6427 		}
6428 	}
6429 	tcp->tcp_state = TCPS_SYN_SENT;
6430 
6431 	mp = allocb(sizeof (ire_t), BPRI_HI);
6432 	if (mp != NULL) {
6433 		in6_addr_t v6src;
6434 
6435 		mp->b_wptr += sizeof (ire_t);
6436 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6437 
6438 		tcp->tcp_hard_binding = 1;
6439 
6440 		/*
6441 		 * We need to make sure that the conn_recv is set to a non-null
6442 		 * value before we insert the conn_t into the classifier table.
6443 		 * This is to avoid a race with an incoming packet which does
6444 		 * an ipcl_classify().
6445 		 */
6446 		tcp->tcp_connp->conn_recv = tcp_input;
6447 
6448 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6449 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6450 		} else {
6451 			v6src = tcp->tcp_ip6h->ip6_src;
6452 		}
6453 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6454 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6455 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6456 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6457 		tcp->tcp_active_open = 1;
6458 
6459 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6460 	}
6461 	/* Error case */
6462 	tcp->tcp_state = oldstate;
6463 	error = ENOMEM;
6464 
6465 failed:
6466 	/* return error ack and blow away saved option results if any */
6467 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6468 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6469 	return (error);
6470 }
6471 
6472 /*
6473  * We need a stream q for detached closing tcp connections
6474  * to use.  Our client hereby indicates that this q is the
6475  * one to use.
6476  */
6477 static void
6478 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6479 {
6480 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6481 	queue_t	*q = tcp->tcp_wq;
6482 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6483 
6484 #ifdef NS_DEBUG
6485 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6486 	    tcps->tcps_netstack->netstack_stackid);
6487 #endif
6488 	mp->b_datap->db_type = M_IOCACK;
6489 	iocp->ioc_count = 0;
6490 	mutex_enter(&tcps->tcps_g_q_lock);
6491 	if (tcps->tcps_g_q != NULL) {
6492 		mutex_exit(&tcps->tcps_g_q_lock);
6493 		iocp->ioc_error = EALREADY;
6494 	} else {
6495 		int error = 0;
6496 		conn_t *connp = tcp->tcp_connp;
6497 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6498 
6499 		tcps->tcps_g_q = tcp->tcp_rq;
6500 		mutex_exit(&tcps->tcps_g_q_lock);
6501 		iocp->ioc_error = 0;
6502 		iocp->ioc_rval = 0;
6503 		/*
6504 		 * We are passing tcp_sticky_ipp as NULL
6505 		 * as it is not useful for tcp_default queue
6506 		 *
6507 		 * Set conn_recv just in case.
6508 		 */
6509 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6510 
6511 		ASSERT(connp->conn_af_isv6);
6512 		connp->conn_ulp = IPPROTO_TCP;
6513 
6514 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6515 		    NULL || connp->conn_mac_exempt) {
6516 			error = -TBADADDR;
6517 		} else {
6518 			connp->conn_srcv6 = ipv6_all_zeros;
6519 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6520 		}
6521 
6522 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6523 	}
6524 	qreply(q, mp);
6525 }
6526 
6527 static int
6528 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6529 {
6530 	tcp_t	*ltcp = NULL;
6531 	conn_t	*connp;
6532 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6533 
6534 	/*
6535 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6536 	 * when the stream is in BOUND state. Do not send a reset,
6537 	 * since the destination IP address is not valid, and it can
6538 	 * be the initialized value of all zeros (broadcast address).
6539 	 *
6540 	 * XXX There won't be any pending bind request to IP.
6541 	 */
6542 	if (tcp->tcp_state <= TCPS_BOUND) {
6543 		if (tcp->tcp_debug) {
6544 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6545 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6546 		}
6547 		return (TOUTSTATE);
6548 	}
6549 
6550 
6551 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6552 
6553 		/*
6554 		 * According to TPI, for non-listeners, ignore seqnum
6555 		 * and disconnect.
6556 		 * Following interpretation of -1 seqnum is historical
6557 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6558 		 * a valid seqnum should not be -1).
6559 		 *
6560 		 *	-1 means disconnect everything
6561 		 *	regardless even on a listener.
6562 		 */
6563 
6564 		int old_state = tcp->tcp_state;
6565 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6566 
6567 		/*
6568 		 * The connection can't be on the tcp_time_wait_head list
6569 		 * since it is not detached.
6570 		 */
6571 		ASSERT(tcp->tcp_time_wait_next == NULL);
6572 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6573 		ASSERT(tcp->tcp_time_wait_expire == 0);
6574 		ltcp = NULL;
6575 		/*
6576 		 * If it used to be a listener, check to make sure no one else
6577 		 * has taken the port before switching back to LISTEN state.
6578 		 */
6579 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6580 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6581 			    tcp->tcp_ipha->ipha_src,
6582 			    tcp->tcp_connp->conn_zoneid, ipst);
6583 			if (connp != NULL)
6584 				ltcp = connp->conn_tcp;
6585 		} else {
6586 			/* Allow tcp_bound_if listeners? */
6587 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6588 			    &tcp->tcp_ip6h->ip6_src, 0,
6589 			    tcp->tcp_connp->conn_zoneid, ipst);
6590 			if (connp != NULL)
6591 				ltcp = connp->conn_tcp;
6592 		}
6593 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6594 			tcp->tcp_state = TCPS_LISTEN;
6595 		} else if (old_state > TCPS_BOUND) {
6596 			tcp->tcp_conn_req_max = 0;
6597 			tcp->tcp_state = TCPS_BOUND;
6598 		}
6599 		if (ltcp != NULL)
6600 			CONN_DEC_REF(ltcp->tcp_connp);
6601 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6602 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6603 		} else if (old_state == TCPS_ESTABLISHED ||
6604 		    old_state == TCPS_CLOSE_WAIT) {
6605 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6606 		}
6607 
6608 		if (tcp->tcp_fused)
6609 			tcp_unfuse(tcp);
6610 
6611 		mutex_enter(&tcp->tcp_eager_lock);
6612 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6613 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6614 			tcp_eager_cleanup(tcp, 0);
6615 		}
6616 		mutex_exit(&tcp->tcp_eager_lock);
6617 
6618 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6619 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6620 
6621 		tcp_reinit(tcp);
6622 
6623 		return (0);
6624 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6625 		return (TBADSEQ);
6626 	}
6627 	return (0);
6628 }
6629 
6630 /*
6631  * Our client hereby directs us to reject the connection request
6632  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6633  * of sending the appropriate RST, not an ICMP error.
6634  */
6635 static void
6636 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6637 {
6638 	t_scalar_t seqnum;
6639 	int	error;
6640 
6641 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6642 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6643 		tcp_err_ack(tcp, mp, TPROTO, 0);
6644 		return;
6645 	}
6646 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6647 	error = tcp_disconnect_common(tcp, seqnum);
6648 	if (error != 0)
6649 		tcp_err_ack(tcp, mp, error, 0);
6650 	else {
6651 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6652 			/* Send M_FLUSH according to TPI */
6653 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6654 		}
6655 		mp = mi_tpi_ok_ack_alloc(mp);
6656 		if (mp)
6657 			putnext(tcp->tcp_rq, mp);
6658 	}
6659 }
6660 
6661 /*
6662  * Diagnostic routine used to return a string associated with the tcp state.
6663  * Note that if the caller does not supply a buffer, it will use an internal
6664  * static string.  This means that if multiple threads call this function at
6665  * the same time, output can be corrupted...  Note also that this function
6666  * does not check the size of the supplied buffer.  The caller has to make
6667  * sure that it is big enough.
6668  */
6669 static char *
6670 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6671 {
6672 	char		buf1[30];
6673 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6674 	char		*buf;
6675 	char		*cp;
6676 	in6_addr_t	local, remote;
6677 	char		local_addrbuf[INET6_ADDRSTRLEN];
6678 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6679 
6680 	if (sup_buf != NULL)
6681 		buf = sup_buf;
6682 	else
6683 		buf = priv_buf;
6684 
6685 	if (tcp == NULL)
6686 		return ("NULL_TCP");
6687 	switch (tcp->tcp_state) {
6688 	case TCPS_CLOSED:
6689 		cp = "TCP_CLOSED";
6690 		break;
6691 	case TCPS_IDLE:
6692 		cp = "TCP_IDLE";
6693 		break;
6694 	case TCPS_BOUND:
6695 		cp = "TCP_BOUND";
6696 		break;
6697 	case TCPS_LISTEN:
6698 		cp = "TCP_LISTEN";
6699 		break;
6700 	case TCPS_SYN_SENT:
6701 		cp = "TCP_SYN_SENT";
6702 		break;
6703 	case TCPS_SYN_RCVD:
6704 		cp = "TCP_SYN_RCVD";
6705 		break;
6706 	case TCPS_ESTABLISHED:
6707 		cp = "TCP_ESTABLISHED";
6708 		break;
6709 	case TCPS_CLOSE_WAIT:
6710 		cp = "TCP_CLOSE_WAIT";
6711 		break;
6712 	case TCPS_FIN_WAIT_1:
6713 		cp = "TCP_FIN_WAIT_1";
6714 		break;
6715 	case TCPS_CLOSING:
6716 		cp = "TCP_CLOSING";
6717 		break;
6718 	case TCPS_LAST_ACK:
6719 		cp = "TCP_LAST_ACK";
6720 		break;
6721 	case TCPS_FIN_WAIT_2:
6722 		cp = "TCP_FIN_WAIT_2";
6723 		break;
6724 	case TCPS_TIME_WAIT:
6725 		cp = "TCP_TIME_WAIT";
6726 		break;
6727 	default:
6728 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6729 		cp = buf1;
6730 		break;
6731 	}
6732 	switch (format) {
6733 	case DISP_ADDR_AND_PORT:
6734 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6735 			/*
6736 			 * Note that we use the remote address in the tcp_b
6737 			 * structure.  This means that it will print out
6738 			 * the real destination address, not the next hop's
6739 			 * address if source routing is used.
6740 			 */
6741 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6742 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6743 
6744 		} else {
6745 			local = tcp->tcp_ip_src_v6;
6746 			remote = tcp->tcp_remote_v6;
6747 		}
6748 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6749 		    sizeof (local_addrbuf));
6750 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6751 		    sizeof (remote_addrbuf));
6752 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6753 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6754 		    ntohs(tcp->tcp_fport), cp);
6755 		break;
6756 	case DISP_PORT_ONLY:
6757 	default:
6758 		(void) mi_sprintf(buf, "[%u, %u] %s",
6759 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6760 		break;
6761 	}
6762 
6763 	return (buf);
6764 }
6765 
6766 /*
6767  * Called via squeue to get on to eager's perimeter. It sends a
6768  * TH_RST if eager is in the fanout table. The listener wants the
6769  * eager to disappear either by means of tcp_eager_blowoff() or
6770  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6771  * called (via squeue) if the eager cannot be inserted in the
6772  * fanout table in tcp_conn_request().
6773  */
6774 /* ARGSUSED */
6775 void
6776 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6777 {
6778 	conn_t	*econnp = (conn_t *)arg;
6779 	tcp_t	*eager = econnp->conn_tcp;
6780 	tcp_t	*listener = eager->tcp_listener;
6781 	tcp_stack_t	*tcps = eager->tcp_tcps;
6782 
6783 	/*
6784 	 * We could be called because listener is closing. Since
6785 	 * the eager is using listener's queue's, its not safe.
6786 	 * Better use the default queue just to send the TH_RST
6787 	 * out.
6788 	 */
6789 	ASSERT(tcps->tcps_g_q != NULL);
6790 	eager->tcp_rq = tcps->tcps_g_q;
6791 	eager->tcp_wq = WR(tcps->tcps_g_q);
6792 
6793 	/*
6794 	 * An eager's conn_fanout will be NULL if it's a duplicate
6795 	 * for an existing 4-tuples in the conn fanout table.
6796 	 * We don't want to send an RST out in such case.
6797 	 */
6798 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6799 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6800 		    eager, eager->tcp_snxt, 0, TH_RST);
6801 	}
6802 
6803 	/* We are here because listener wants this eager gone */
6804 	if (listener != NULL) {
6805 		mutex_enter(&listener->tcp_eager_lock);
6806 		tcp_eager_unlink(eager);
6807 		if (eager->tcp_tconnind_started) {
6808 			/*
6809 			 * The eager has sent a conn_ind up to the
6810 			 * listener but listener decides to close
6811 			 * instead. We need to drop the extra ref
6812 			 * placed on eager in tcp_rput_data() before
6813 			 * sending the conn_ind to listener.
6814 			 */
6815 			CONN_DEC_REF(econnp);
6816 		}
6817 		mutex_exit(&listener->tcp_eager_lock);
6818 		CONN_DEC_REF(listener->tcp_connp);
6819 	}
6820 
6821 	if (eager->tcp_state != TCPS_CLOSED)
6822 		tcp_close_detached(eager);
6823 }
6824 
6825 /*
6826  * Reset any eager connection hanging off this listener marked
6827  * with 'seqnum' and then reclaim it's resources.
6828  */
6829 static boolean_t
6830 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6831 {
6832 	tcp_t	*eager;
6833 	mblk_t 	*mp;
6834 	tcp_stack_t	*tcps = listener->tcp_tcps;
6835 
6836 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6837 	eager = listener;
6838 	mutex_enter(&listener->tcp_eager_lock);
6839 	do {
6840 		eager = eager->tcp_eager_next_q;
6841 		if (eager == NULL) {
6842 			mutex_exit(&listener->tcp_eager_lock);
6843 			return (B_FALSE);
6844 		}
6845 	} while (eager->tcp_conn_req_seqnum != seqnum);
6846 
6847 	if (eager->tcp_closemp_used) {
6848 		mutex_exit(&listener->tcp_eager_lock);
6849 		return (B_TRUE);
6850 	}
6851 	eager->tcp_closemp_used = B_TRUE;
6852 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6853 	CONN_INC_REF(eager->tcp_connp);
6854 	mutex_exit(&listener->tcp_eager_lock);
6855 	mp = &eager->tcp_closemp;
6856 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6857 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6858 	return (B_TRUE);
6859 }
6860 
6861 /*
6862  * Reset any eager connection hanging off this listener
6863  * and then reclaim it's resources.
6864  */
6865 static void
6866 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6867 {
6868 	tcp_t	*eager;
6869 	mblk_t	*mp;
6870 	tcp_stack_t	*tcps = listener->tcp_tcps;
6871 
6872 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6873 
6874 	if (!q0_only) {
6875 		/* First cleanup q */
6876 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6877 		eager = listener->tcp_eager_next_q;
6878 		while (eager != NULL) {
6879 			if (!eager->tcp_closemp_used) {
6880 				eager->tcp_closemp_used = B_TRUE;
6881 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6882 				CONN_INC_REF(eager->tcp_connp);
6883 				mp = &eager->tcp_closemp;
6884 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6885 				    tcp_eager_kill, eager->tcp_connp,
6886 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6887 			}
6888 			eager = eager->tcp_eager_next_q;
6889 		}
6890 	}
6891 	/* Then cleanup q0 */
6892 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6893 	eager = listener->tcp_eager_next_q0;
6894 	while (eager != listener) {
6895 		if (!eager->tcp_closemp_used) {
6896 			eager->tcp_closemp_used = B_TRUE;
6897 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6898 			CONN_INC_REF(eager->tcp_connp);
6899 			mp = &eager->tcp_closemp;
6900 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6901 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6902 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6903 		}
6904 		eager = eager->tcp_eager_next_q0;
6905 	}
6906 }
6907 
6908 /*
6909  * If we are an eager connection hanging off a listener that hasn't
6910  * formally accepted the connection yet, get off his list and blow off
6911  * any data that we have accumulated.
6912  */
6913 static void
6914 tcp_eager_unlink(tcp_t *tcp)
6915 {
6916 	tcp_t	*listener = tcp->tcp_listener;
6917 
6918 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6919 	ASSERT(listener != NULL);
6920 	if (tcp->tcp_eager_next_q0 != NULL) {
6921 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6922 
6923 		/* Remove the eager tcp from q0 */
6924 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6925 		    tcp->tcp_eager_prev_q0;
6926 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6927 		    tcp->tcp_eager_next_q0;
6928 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6929 		listener->tcp_conn_req_cnt_q0--;
6930 
6931 		tcp->tcp_eager_next_q0 = NULL;
6932 		tcp->tcp_eager_prev_q0 = NULL;
6933 
6934 		/*
6935 		 * Take the eager out, if it is in the list of droppable
6936 		 * eagers.
6937 		 */
6938 		MAKE_UNDROPPABLE(tcp);
6939 
6940 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6941 			/* we have timed out before */
6942 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6943 			listener->tcp_syn_rcvd_timeout--;
6944 		}
6945 	} else {
6946 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6947 		tcp_t	*prev = NULL;
6948 
6949 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6950 			if (tcpp[0] == tcp) {
6951 				if (listener->tcp_eager_last_q == tcp) {
6952 					/*
6953 					 * If we are unlinking the last
6954 					 * element on the list, adjust
6955 					 * tail pointer. Set tail pointer
6956 					 * to nil when list is empty.
6957 					 */
6958 					ASSERT(tcp->tcp_eager_next_q == NULL);
6959 					if (listener->tcp_eager_last_q ==
6960 					    listener->tcp_eager_next_q) {
6961 						listener->tcp_eager_last_q =
6962 						    NULL;
6963 					} else {
6964 						/*
6965 						 * We won't get here if there
6966 						 * is only one eager in the
6967 						 * list.
6968 						 */
6969 						ASSERT(prev != NULL);
6970 						listener->tcp_eager_last_q =
6971 						    prev;
6972 					}
6973 				}
6974 				tcpp[0] = tcp->tcp_eager_next_q;
6975 				tcp->tcp_eager_next_q = NULL;
6976 				tcp->tcp_eager_last_q = NULL;
6977 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6978 				listener->tcp_conn_req_cnt_q--;
6979 				break;
6980 			}
6981 			prev = tcpp[0];
6982 		}
6983 	}
6984 	tcp->tcp_listener = NULL;
6985 }
6986 
6987 /* Shorthand to generate and send TPI error acks to our client */
6988 static void
6989 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6990 {
6991 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6992 		putnext(tcp->tcp_rq, mp);
6993 }
6994 
6995 /* Shorthand to generate and send TPI error acks to our client */
6996 static void
6997 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6998     int t_error, int sys_error)
6999 {
7000 	struct T_error_ack	*teackp;
7001 
7002 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7003 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7004 		teackp = (struct T_error_ack *)mp->b_rptr;
7005 		teackp->ERROR_prim = primitive;
7006 		teackp->TLI_error = t_error;
7007 		teackp->UNIX_error = sys_error;
7008 		putnext(tcp->tcp_rq, mp);
7009 	}
7010 }
7011 
7012 /*
7013  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7014  * but instead the code relies on:
7015  * - the fact that the address of the array and its size never changes
7016  * - the atomic assignment of the elements of the array
7017  */
7018 /* ARGSUSED */
7019 static int
7020 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7021 {
7022 	int i;
7023 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7024 
7025 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7026 		if (tcps->tcps_g_epriv_ports[i] != 0)
7027 			(void) mi_mpprintf(mp, "%d ",
7028 			    tcps->tcps_g_epriv_ports[i]);
7029 	}
7030 	return (0);
7031 }
7032 
7033 /*
7034  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7035  * threads from changing it at the same time.
7036  */
7037 /* ARGSUSED */
7038 static int
7039 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7040     cred_t *cr)
7041 {
7042 	long	new_value;
7043 	int	i;
7044 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7045 
7046 	/*
7047 	 * Fail the request if the new value does not lie within the
7048 	 * port number limits.
7049 	 */
7050 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7051 	    new_value <= 0 || new_value >= 65536) {
7052 		return (EINVAL);
7053 	}
7054 
7055 	mutex_enter(&tcps->tcps_epriv_port_lock);
7056 	/* Check if the value is already in the list */
7057 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7058 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7059 			mutex_exit(&tcps->tcps_epriv_port_lock);
7060 			return (EEXIST);
7061 		}
7062 	}
7063 	/* Find an empty slot */
7064 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7065 		if (tcps->tcps_g_epriv_ports[i] == 0)
7066 			break;
7067 	}
7068 	if (i == tcps->tcps_g_num_epriv_ports) {
7069 		mutex_exit(&tcps->tcps_epriv_port_lock);
7070 		return (EOVERFLOW);
7071 	}
7072 	/* Set the new value */
7073 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7074 	mutex_exit(&tcps->tcps_epriv_port_lock);
7075 	return (0);
7076 }
7077 
7078 /*
7079  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7080  * threads from changing it at the same time.
7081  */
7082 /* ARGSUSED */
7083 static int
7084 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7085     cred_t *cr)
7086 {
7087 	long	new_value;
7088 	int	i;
7089 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7090 
7091 	/*
7092 	 * Fail the request if the new value does not lie within the
7093 	 * port number limits.
7094 	 */
7095 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7096 	    new_value >= 65536) {
7097 		return (EINVAL);
7098 	}
7099 
7100 	mutex_enter(&tcps->tcps_epriv_port_lock);
7101 	/* Check that the value is already in the list */
7102 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7103 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7104 			break;
7105 	}
7106 	if (i == tcps->tcps_g_num_epriv_ports) {
7107 		mutex_exit(&tcps->tcps_epriv_port_lock);
7108 		return (ESRCH);
7109 	}
7110 	/* Clear the value */
7111 	tcps->tcps_g_epriv_ports[i] = 0;
7112 	mutex_exit(&tcps->tcps_epriv_port_lock);
7113 	return (0);
7114 }
7115 
7116 /* Return the TPI/TLI equivalent of our current tcp_state */
7117 static int
7118 tcp_tpistate(tcp_t *tcp)
7119 {
7120 	switch (tcp->tcp_state) {
7121 	case TCPS_IDLE:
7122 		return (TS_UNBND);
7123 	case TCPS_LISTEN:
7124 		/*
7125 		 * Return whether there are outstanding T_CONN_IND waiting
7126 		 * for the matching T_CONN_RES. Therefore don't count q0.
7127 		 */
7128 		if (tcp->tcp_conn_req_cnt_q > 0)
7129 			return (TS_WRES_CIND);
7130 		else
7131 			return (TS_IDLE);
7132 	case TCPS_BOUND:
7133 		return (TS_IDLE);
7134 	case TCPS_SYN_SENT:
7135 		return (TS_WCON_CREQ);
7136 	case TCPS_SYN_RCVD:
7137 		/*
7138 		 * Note: assumption: this has to the active open SYN_RCVD.
7139 		 * The passive instance is detached in SYN_RCVD stage of
7140 		 * incoming connection processing so we cannot get request
7141 		 * for T_info_ack on it.
7142 		 */
7143 		return (TS_WACK_CRES);
7144 	case TCPS_ESTABLISHED:
7145 		return (TS_DATA_XFER);
7146 	case TCPS_CLOSE_WAIT:
7147 		return (TS_WREQ_ORDREL);
7148 	case TCPS_FIN_WAIT_1:
7149 		return (TS_WIND_ORDREL);
7150 	case TCPS_FIN_WAIT_2:
7151 		return (TS_WIND_ORDREL);
7152 
7153 	case TCPS_CLOSING:
7154 	case TCPS_LAST_ACK:
7155 	case TCPS_TIME_WAIT:
7156 	case TCPS_CLOSED:
7157 		/*
7158 		 * Following TS_WACK_DREQ7 is a rendition of "not
7159 		 * yet TS_IDLE" TPI state. There is no best match to any
7160 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7161 		 * choose a value chosen that will map to TLI/XTI level
7162 		 * state of TSTATECHNG (state is process of changing) which
7163 		 * captures what this dummy state represents.
7164 		 */
7165 		return (TS_WACK_DREQ7);
7166 	default:
7167 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7168 		    tcp->tcp_state, tcp_display(tcp, NULL,
7169 		    DISP_PORT_ONLY));
7170 		return (TS_UNBND);
7171 	}
7172 }
7173 
7174 static void
7175 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7176 {
7177 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7178 
7179 	if (tcp->tcp_family == AF_INET6)
7180 		*tia = tcp_g_t_info_ack_v6;
7181 	else
7182 		*tia = tcp_g_t_info_ack;
7183 	tia->CURRENT_state = tcp_tpistate(tcp);
7184 	tia->OPT_size = tcp_max_optsize;
7185 	if (tcp->tcp_mss == 0) {
7186 		/* Not yet set - tcp_open does not set mss */
7187 		if (tcp->tcp_ipversion == IPV4_VERSION)
7188 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7189 		else
7190 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7191 	} else {
7192 		tia->TIDU_size = tcp->tcp_mss;
7193 	}
7194 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7195 }
7196 
7197 static void
7198 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7199     t_uscalar_t cap_bits1)
7200 {
7201 	tcap->CAP_bits1 = 0;
7202 
7203 	if (cap_bits1 & TC1_INFO) {
7204 		tcp_copy_info(&tcap->INFO_ack, tcp);
7205 		tcap->CAP_bits1 |= TC1_INFO;
7206 	}
7207 
7208 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7209 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7210 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7211 	}
7212 
7213 }
7214 
7215 /*
7216  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7217  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7218  * tcp_g_t_info_ack.  The current state of the stream is copied from
7219  * tcp_state.
7220  */
7221 static void
7222 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7223 {
7224 	t_uscalar_t		cap_bits1;
7225 	struct T_capability_ack	*tcap;
7226 
7227 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7228 		freemsg(mp);
7229 		return;
7230 	}
7231 
7232 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7233 
7234 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7235 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7236 	if (mp == NULL)
7237 		return;
7238 
7239 	tcap = (struct T_capability_ack *)mp->b_rptr;
7240 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7241 
7242 	putnext(tcp->tcp_rq, mp);
7243 }
7244 
7245 /*
7246  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7247  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7248  * The current state of the stream is copied from tcp_state.
7249  */
7250 static void
7251 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7252 {
7253 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7254 	    T_INFO_ACK);
7255 	if (!mp) {
7256 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7257 		return;
7258 	}
7259 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7260 	putnext(tcp->tcp_rq, mp);
7261 }
7262 
7263 /* Respond to the TPI addr request */
7264 static void
7265 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7266 {
7267 	sin_t	*sin;
7268 	mblk_t	*ackmp;
7269 	struct T_addr_ack *taa;
7270 
7271 	/* Make it large enough for worst case */
7272 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7273 	    2 * sizeof (sin6_t), 1);
7274 	if (ackmp == NULL) {
7275 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7276 		return;
7277 	}
7278 
7279 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7280 		tcp_addr_req_ipv6(tcp, ackmp);
7281 		return;
7282 	}
7283 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7284 
7285 	bzero(taa, sizeof (struct T_addr_ack));
7286 	ackmp->b_wptr = (uchar_t *)&taa[1];
7287 
7288 	taa->PRIM_type = T_ADDR_ACK;
7289 	ackmp->b_datap->db_type = M_PCPROTO;
7290 
7291 	/*
7292 	 * Note: Following code assumes 32 bit alignment of basic
7293 	 * data structures like sin_t and struct T_addr_ack.
7294 	 */
7295 	if (tcp->tcp_state >= TCPS_BOUND) {
7296 		/*
7297 		 * Fill in local address
7298 		 */
7299 		taa->LOCADDR_length = sizeof (sin_t);
7300 		taa->LOCADDR_offset = sizeof (*taa);
7301 
7302 		sin = (sin_t *)&taa[1];
7303 
7304 		/* Fill zeroes and then intialize non-zero fields */
7305 		*sin = sin_null;
7306 
7307 		sin->sin_family = AF_INET;
7308 
7309 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7310 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7311 
7312 		ackmp->b_wptr = (uchar_t *)&sin[1];
7313 
7314 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7315 			/*
7316 			 * Fill in Remote address
7317 			 */
7318 			taa->REMADDR_length = sizeof (sin_t);
7319 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7320 			    taa->LOCADDR_length);
7321 
7322 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7323 			*sin = sin_null;
7324 			sin->sin_family = AF_INET;
7325 			sin->sin_addr.s_addr = tcp->tcp_remote;
7326 			sin->sin_port = tcp->tcp_fport;
7327 
7328 			ackmp->b_wptr = (uchar_t *)&sin[1];
7329 		}
7330 	}
7331 	putnext(tcp->tcp_rq, ackmp);
7332 }
7333 
7334 /* Assumes that tcp_addr_req gets enough space and alignment */
7335 static void
7336 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7337 {
7338 	sin6_t	*sin6;
7339 	struct T_addr_ack *taa;
7340 
7341 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7342 	ASSERT(OK_32PTR(ackmp->b_rptr));
7343 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7344 	    2 * sizeof (sin6_t));
7345 
7346 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7347 
7348 	bzero(taa, sizeof (struct T_addr_ack));
7349 	ackmp->b_wptr = (uchar_t *)&taa[1];
7350 
7351 	taa->PRIM_type = T_ADDR_ACK;
7352 	ackmp->b_datap->db_type = M_PCPROTO;
7353 
7354 	/*
7355 	 * Note: Following code assumes 32 bit alignment of basic
7356 	 * data structures like sin6_t and struct T_addr_ack.
7357 	 */
7358 	if (tcp->tcp_state >= TCPS_BOUND) {
7359 		/*
7360 		 * Fill in local address
7361 		 */
7362 		taa->LOCADDR_length = sizeof (sin6_t);
7363 		taa->LOCADDR_offset = sizeof (*taa);
7364 
7365 		sin6 = (sin6_t *)&taa[1];
7366 		*sin6 = sin6_null;
7367 
7368 		sin6->sin6_family = AF_INET6;
7369 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7370 		sin6->sin6_port = tcp->tcp_lport;
7371 
7372 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7373 
7374 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7375 			/*
7376 			 * Fill in Remote address
7377 			 */
7378 			taa->REMADDR_length = sizeof (sin6_t);
7379 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7380 			    taa->LOCADDR_length);
7381 
7382 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7383 			*sin6 = sin6_null;
7384 			sin6->sin6_family = AF_INET6;
7385 			sin6->sin6_flowinfo =
7386 			    tcp->tcp_ip6h->ip6_vcf &
7387 			    ~IPV6_VERS_AND_FLOW_MASK;
7388 			sin6->sin6_addr = tcp->tcp_remote_v6;
7389 			sin6->sin6_port = tcp->tcp_fport;
7390 
7391 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7392 		}
7393 	}
7394 	putnext(tcp->tcp_rq, ackmp);
7395 }
7396 
7397 /*
7398  * Handle reinitialization of a tcp structure.
7399  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7400  */
7401 static void
7402 tcp_reinit(tcp_t *tcp)
7403 {
7404 	mblk_t	*mp;
7405 	int 	err;
7406 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7407 
7408 	TCP_STAT(tcps, tcp_reinit_calls);
7409 
7410 	/* tcp_reinit should never be called for detached tcp_t's */
7411 	ASSERT(tcp->tcp_listener == NULL);
7412 	ASSERT((tcp->tcp_family == AF_INET &&
7413 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7414 	    (tcp->tcp_family == AF_INET6 &&
7415 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7416 	    tcp->tcp_ipversion == IPV6_VERSION)));
7417 
7418 	/* Cancel outstanding timers */
7419 	tcp_timers_stop(tcp);
7420 
7421 	/*
7422 	 * Reset everything in the state vector, after updating global
7423 	 * MIB data from instance counters.
7424 	 */
7425 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7426 	tcp->tcp_ibsegs = 0;
7427 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7428 	tcp->tcp_obsegs = 0;
7429 
7430 	tcp_close_mpp(&tcp->tcp_xmit_head);
7431 	if (tcp->tcp_snd_zcopy_aware)
7432 		tcp_zcopy_notify(tcp);
7433 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7434 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7435 	mutex_enter(&tcp->tcp_non_sq_lock);
7436 	if (tcp->tcp_flow_stopped &&
7437 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7438 		tcp_clrqfull(tcp);
7439 	}
7440 	mutex_exit(&tcp->tcp_non_sq_lock);
7441 	tcp_close_mpp(&tcp->tcp_reass_head);
7442 	tcp->tcp_reass_tail = NULL;
7443 	if (tcp->tcp_rcv_list != NULL) {
7444 		/* Free b_next chain */
7445 		tcp_close_mpp(&tcp->tcp_rcv_list);
7446 		tcp->tcp_rcv_last_head = NULL;
7447 		tcp->tcp_rcv_last_tail = NULL;
7448 		tcp->tcp_rcv_cnt = 0;
7449 	}
7450 	tcp->tcp_rcv_last_tail = NULL;
7451 
7452 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7453 		freemsg(mp);
7454 		tcp->tcp_urp_mp = NULL;
7455 	}
7456 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7457 		freemsg(mp);
7458 		tcp->tcp_urp_mark_mp = NULL;
7459 	}
7460 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7461 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7462 		freeb(tcp->tcp_fused_sigurg_mp);
7463 		tcp->tcp_fused_sigurg_mp = NULL;
7464 	}
7465 	if (tcp->tcp_ordrel_mp != NULL) {
7466 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7467 		freeb(tcp->tcp_ordrel_mp);
7468 		tcp->tcp_ordrel_mp = NULL;
7469 	}
7470 
7471 	/*
7472 	 * Following is a union with two members which are
7473 	 * identical types and size so the following cleanup
7474 	 * is enough.
7475 	 */
7476 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7477 
7478 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7479 
7480 	/*
7481 	 * The connection can't be on the tcp_time_wait_head list
7482 	 * since it is not detached.
7483 	 */
7484 	ASSERT(tcp->tcp_time_wait_next == NULL);
7485 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7486 	ASSERT(tcp->tcp_time_wait_expire == 0);
7487 
7488 	if (tcp->tcp_kssl_pending) {
7489 		tcp->tcp_kssl_pending = B_FALSE;
7490 
7491 		/* Don't reset if the initialized by bind. */
7492 		if (tcp->tcp_kssl_ent != NULL) {
7493 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7494 			    KSSL_NO_PROXY);
7495 		}
7496 	}
7497 	if (tcp->tcp_kssl_ctx != NULL) {
7498 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7499 		tcp->tcp_kssl_ctx = NULL;
7500 	}
7501 
7502 	/*
7503 	 * Reset/preserve other values
7504 	 */
7505 	tcp_reinit_values(tcp);
7506 	ipcl_hash_remove(tcp->tcp_connp);
7507 	conn_delete_ire(tcp->tcp_connp, NULL);
7508 	tcp_ipsec_cleanup(tcp);
7509 
7510 	if (tcp->tcp_connp->conn_effective_cred != NULL) {
7511 		crfree(tcp->tcp_connp->conn_effective_cred);
7512 		tcp->tcp_connp->conn_effective_cred = NULL;
7513 	}
7514 
7515 	if (tcp->tcp_conn_req_max != 0) {
7516 		/*
7517 		 * This is the case when a TLI program uses the same
7518 		 * transport end point to accept a connection.  This
7519 		 * makes the TCP both a listener and acceptor.  When
7520 		 * this connection is closed, we need to set the state
7521 		 * back to TCPS_LISTEN.  Make sure that the eager list
7522 		 * is reinitialized.
7523 		 *
7524 		 * Note that this stream is still bound to the four
7525 		 * tuples of the previous connection in IP.  If a new
7526 		 * SYN with different foreign address comes in, IP will
7527 		 * not find it and will send it to the global queue.  In
7528 		 * the global queue, TCP will do a tcp_lookup_listener()
7529 		 * to find this stream.  This works because this stream
7530 		 * is only removed from connected hash.
7531 		 *
7532 		 */
7533 		tcp->tcp_state = TCPS_LISTEN;
7534 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7535 		tcp->tcp_eager_next_drop_q0 = tcp;
7536 		tcp->tcp_eager_prev_drop_q0 = tcp;
7537 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7538 		if (tcp->tcp_family == AF_INET6) {
7539 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7540 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7541 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7542 		} else {
7543 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7544 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7545 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7546 		}
7547 	} else {
7548 		tcp->tcp_state = TCPS_BOUND;
7549 	}
7550 
7551 	/*
7552 	 * Initialize to default values
7553 	 * Can't fail since enough header template space already allocated
7554 	 * at open().
7555 	 */
7556 	err = tcp_init_values(tcp);
7557 	ASSERT(err == 0);
7558 	/* Restore state in tcp_tcph */
7559 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7560 	if (tcp->tcp_ipversion == IPV4_VERSION)
7561 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7562 	else
7563 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7564 	/*
7565 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7566 	 * since the lookup funcs can only lookup on tcp_t
7567 	 */
7568 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7569 
7570 	ASSERT(tcp->tcp_ptpbhn != NULL);
7571 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7572 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7573 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7574 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7575 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7576 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7577 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7578 }
7579 
7580 /*
7581  * Force values to zero that need be zero.
7582  * Do not touch values asociated with the BOUND or LISTEN state
7583  * since the connection will end up in that state after the reinit.
7584  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7585  * structure!
7586  */
7587 static void
7588 tcp_reinit_values(tcp)
7589 	tcp_t *tcp;
7590 {
7591 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7592 
7593 #ifndef	lint
7594 #define	DONTCARE(x)
7595 #define	PRESERVE(x)
7596 #else
7597 #define	DONTCARE(x)	((x) = (x))
7598 #define	PRESERVE(x)	((x) = (x))
7599 #endif	/* lint */
7600 
7601 	PRESERVE(tcp->tcp_bind_hash_port);
7602 	PRESERVE(tcp->tcp_bind_hash);
7603 	PRESERVE(tcp->tcp_ptpbhn);
7604 	PRESERVE(tcp->tcp_acceptor_hash);
7605 	PRESERVE(tcp->tcp_ptpahn);
7606 
7607 	/* Should be ASSERT NULL on these with new code! */
7608 	ASSERT(tcp->tcp_time_wait_next == NULL);
7609 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7610 	ASSERT(tcp->tcp_time_wait_expire == 0);
7611 	PRESERVE(tcp->tcp_state);
7612 	PRESERVE(tcp->tcp_rq);
7613 	PRESERVE(tcp->tcp_wq);
7614 
7615 	ASSERT(tcp->tcp_xmit_head == NULL);
7616 	ASSERT(tcp->tcp_xmit_last == NULL);
7617 	ASSERT(tcp->tcp_unsent == 0);
7618 	ASSERT(tcp->tcp_xmit_tail == NULL);
7619 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7620 
7621 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7622 	tcp->tcp_suna = 0;			/* Displayed in mib */
7623 	tcp->tcp_swnd = 0;
7624 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7625 
7626 	ASSERT(tcp->tcp_ibsegs == 0);
7627 	ASSERT(tcp->tcp_obsegs == 0);
7628 
7629 	if (tcp->tcp_iphc != NULL) {
7630 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7631 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7632 	}
7633 
7634 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7635 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7636 	DONTCARE(tcp->tcp_ipha);
7637 	DONTCARE(tcp->tcp_ip6h);
7638 	DONTCARE(tcp->tcp_ip_hdr_len);
7639 	DONTCARE(tcp->tcp_tcph);
7640 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7641 	tcp->tcp_valid_bits = 0;
7642 
7643 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7644 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7645 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7646 	tcp->tcp_last_rcv_lbolt = 0;
7647 
7648 	tcp->tcp_init_cwnd = 0;
7649 
7650 	tcp->tcp_urp_last_valid = 0;
7651 	tcp->tcp_hard_binding = 0;
7652 	tcp->tcp_hard_bound = 0;
7653 	PRESERVE(tcp->tcp_cred);
7654 	PRESERVE(tcp->tcp_cpid);
7655 	PRESERVE(tcp->tcp_open_time);
7656 	PRESERVE(tcp->tcp_exclbind);
7657 
7658 	tcp->tcp_fin_acked = 0;
7659 	tcp->tcp_fin_rcvd = 0;
7660 	tcp->tcp_fin_sent = 0;
7661 	tcp->tcp_ordrel_done = 0;
7662 
7663 	tcp->tcp_debug = 0;
7664 	tcp->tcp_dontroute = 0;
7665 	tcp->tcp_broadcast = 0;
7666 
7667 	tcp->tcp_useloopback = 0;
7668 	tcp->tcp_reuseaddr = 0;
7669 	tcp->tcp_oobinline = 0;
7670 	tcp->tcp_dgram_errind = 0;
7671 
7672 	tcp->tcp_detached = 0;
7673 	tcp->tcp_bind_pending = 0;
7674 	tcp->tcp_unbind_pending = 0;
7675 
7676 	tcp->tcp_snd_ws_ok = B_FALSE;
7677 	tcp->tcp_snd_ts_ok = B_FALSE;
7678 	tcp->tcp_linger = 0;
7679 	tcp->tcp_ka_enabled = 0;
7680 	tcp->tcp_zero_win_probe = 0;
7681 
7682 	tcp->tcp_loopback = 0;
7683 	tcp->tcp_refuse = 0;
7684 	tcp->tcp_localnet = 0;
7685 	tcp->tcp_syn_defense = 0;
7686 	tcp->tcp_set_timer = 0;
7687 
7688 	tcp->tcp_active_open = 0;
7689 	tcp->tcp_rexmit = B_FALSE;
7690 	tcp->tcp_xmit_zc_clean = B_FALSE;
7691 
7692 	tcp->tcp_snd_sack_ok = B_FALSE;
7693 	PRESERVE(tcp->tcp_recvdstaddr);
7694 	tcp->tcp_hwcksum = B_FALSE;
7695 
7696 	tcp->tcp_ire_ill_check_done = B_FALSE;
7697 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7698 
7699 	tcp->tcp_mdt = B_FALSE;
7700 	tcp->tcp_mdt_hdr_head = 0;
7701 	tcp->tcp_mdt_hdr_tail = 0;
7702 
7703 	tcp->tcp_conn_def_q0 = 0;
7704 	tcp->tcp_ip_forward_progress = B_FALSE;
7705 	tcp->tcp_anon_priv_bind = 0;
7706 	tcp->tcp_ecn_ok = B_FALSE;
7707 
7708 	tcp->tcp_cwr = B_FALSE;
7709 	tcp->tcp_ecn_echo_on = B_FALSE;
7710 	tcp->tcp_is_wnd_shrnk = B_FALSE;
7711 
7712 	if (tcp->tcp_sack_info != NULL) {
7713 		if (tcp->tcp_notsack_list != NULL) {
7714 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
7715 			    tcp);
7716 		}
7717 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7718 		tcp->tcp_sack_info = NULL;
7719 	}
7720 
7721 	tcp->tcp_rcv_ws = 0;
7722 	tcp->tcp_snd_ws = 0;
7723 	tcp->tcp_ts_recent = 0;
7724 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7725 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7726 	tcp->tcp_if_mtu = 0;
7727 
7728 	ASSERT(tcp->tcp_reass_head == NULL);
7729 	ASSERT(tcp->tcp_reass_tail == NULL);
7730 
7731 	tcp->tcp_cwnd_cnt = 0;
7732 
7733 	ASSERT(tcp->tcp_rcv_list == NULL);
7734 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7735 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7736 	ASSERT(tcp->tcp_rcv_cnt == 0);
7737 
7738 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7739 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7740 	tcp->tcp_csuna = 0;
7741 
7742 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7743 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7744 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7745 	tcp->tcp_rtt_update = 0;
7746 
7747 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7748 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7749 
7750 	tcp->tcp_rack = 0;			/* Displayed in mib */
7751 	tcp->tcp_rack_cnt = 0;
7752 	tcp->tcp_rack_cur_max = 0;
7753 	tcp->tcp_rack_abs_max = 0;
7754 
7755 	tcp->tcp_max_swnd = 0;
7756 
7757 	ASSERT(tcp->tcp_listener == NULL);
7758 
7759 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7760 
7761 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7762 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7763 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7764 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7765 
7766 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7767 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7768 	PRESERVE(tcp->tcp_conn_req_max);
7769 	PRESERVE(tcp->tcp_conn_req_seqnum);
7770 
7771 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7772 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7773 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7774 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7775 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7776 
7777 	tcp->tcp_lingertime = 0;
7778 
7779 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7780 	ASSERT(tcp->tcp_urp_mp == NULL);
7781 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7782 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7783 
7784 	ASSERT(tcp->tcp_eager_next_q == NULL);
7785 	ASSERT(tcp->tcp_eager_last_q == NULL);
7786 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7787 	    tcp->tcp_eager_prev_q0 == NULL) ||
7788 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7789 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7790 
7791 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7792 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7793 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7794 
7795 	tcp->tcp_client_errno = 0;
7796 
7797 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7798 
7799 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7800 
7801 	PRESERVE(tcp->tcp_bound_source_v6);
7802 	tcp->tcp_last_sent_len = 0;
7803 	tcp->tcp_dupack_cnt = 0;
7804 
7805 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7806 	PRESERVE(tcp->tcp_lport);
7807 
7808 	PRESERVE(tcp->tcp_acceptor_lockp);
7809 
7810 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7811 	PRESERVE(tcp->tcp_acceptor_id);
7812 	DONTCARE(tcp->tcp_ipsec_overhead);
7813 
7814 	PRESERVE(tcp->tcp_family);
7815 	if (tcp->tcp_family == AF_INET6) {
7816 		tcp->tcp_ipversion = IPV6_VERSION;
7817 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7818 	} else {
7819 		tcp->tcp_ipversion = IPV4_VERSION;
7820 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7821 	}
7822 
7823 	tcp->tcp_bound_if = 0;
7824 	tcp->tcp_ipv6_recvancillary = 0;
7825 	tcp->tcp_recvifindex = 0;
7826 	tcp->tcp_recvhops = 0;
7827 	tcp->tcp_closed = 0;
7828 	tcp->tcp_cleandeathtag = 0;
7829 	if (tcp->tcp_hopopts != NULL) {
7830 		mi_free(tcp->tcp_hopopts);
7831 		tcp->tcp_hopopts = NULL;
7832 		tcp->tcp_hopoptslen = 0;
7833 	}
7834 	ASSERT(tcp->tcp_hopoptslen == 0);
7835 	if (tcp->tcp_dstopts != NULL) {
7836 		mi_free(tcp->tcp_dstopts);
7837 		tcp->tcp_dstopts = NULL;
7838 		tcp->tcp_dstoptslen = 0;
7839 	}
7840 	ASSERT(tcp->tcp_dstoptslen == 0);
7841 	if (tcp->tcp_rtdstopts != NULL) {
7842 		mi_free(tcp->tcp_rtdstopts);
7843 		tcp->tcp_rtdstopts = NULL;
7844 		tcp->tcp_rtdstoptslen = 0;
7845 	}
7846 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7847 	if (tcp->tcp_rthdr != NULL) {
7848 		mi_free(tcp->tcp_rthdr);
7849 		tcp->tcp_rthdr = NULL;
7850 		tcp->tcp_rthdrlen = 0;
7851 	}
7852 	ASSERT(tcp->tcp_rthdrlen == 0);
7853 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7854 
7855 	/* Reset fusion-related fields */
7856 	tcp->tcp_fused = B_FALSE;
7857 	tcp->tcp_unfusable = B_FALSE;
7858 	tcp->tcp_fused_sigurg = B_FALSE;
7859 	tcp->tcp_loopback_peer = NULL;
7860 	tcp->tcp_fuse_rcv_hiwater = 0;
7861 
7862 	tcp->tcp_lso = B_FALSE;
7863 
7864 	tcp->tcp_in_ack_unsent = 0;
7865 	tcp->tcp_cork = B_FALSE;
7866 	tcp->tcp_tconnind_started = B_FALSE;
7867 
7868 	PRESERVE(tcp->tcp_squeue_bytes);
7869 
7870 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7871 	ASSERT(!tcp->tcp_kssl_pending);
7872 	PRESERVE(tcp->tcp_kssl_ent);
7873 
7874 	tcp->tcp_closemp_used = B_FALSE;
7875 
7876 	PRESERVE(tcp->tcp_rsrv_mp);
7877 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7878 
7879 #ifdef DEBUG
7880 	DONTCARE(tcp->tcmp_stk[0]);
7881 #endif
7882 
7883 	PRESERVE(tcp->tcp_connid);
7884 
7885 
7886 #undef	DONTCARE
7887 #undef	PRESERVE
7888 }
7889 
7890 /*
7891  * Allocate necessary resources and initialize state vector.
7892  * Guaranteed not to fail so that when an error is returned,
7893  * the caller doesn't need to do any additional cleanup.
7894  */
7895 int
7896 tcp_init(tcp_t *tcp, queue_t *q)
7897 {
7898 	int	err;
7899 
7900 	tcp->tcp_rq = q;
7901 	tcp->tcp_wq = WR(q);
7902 	tcp->tcp_state = TCPS_IDLE;
7903 	if ((err = tcp_init_values(tcp)) != 0)
7904 		tcp_timers_stop(tcp);
7905 	return (err);
7906 }
7907 
7908 static int
7909 tcp_init_values(tcp_t *tcp)
7910 {
7911 	int	err;
7912 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7913 
7914 	ASSERT((tcp->tcp_family == AF_INET &&
7915 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7916 	    (tcp->tcp_family == AF_INET6 &&
7917 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7918 	    tcp->tcp_ipversion == IPV6_VERSION)));
7919 
7920 	/*
7921 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7922 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7923 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7924 	 * during first few transmissions of a connection as seen in slow
7925 	 * links.
7926 	 */
7927 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7928 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7929 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7930 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7931 	    tcps->tcps_conn_grace_period;
7932 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7933 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7934 	tcp->tcp_timer_backoff = 0;
7935 	tcp->tcp_ms_we_have_waited = 0;
7936 	tcp->tcp_last_recv_time = lbolt;
7937 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7938 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7939 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7940 
7941 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7942 
7943 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7944 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7945 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7946 	/*
7947 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7948 	 * passive open.
7949 	 */
7950 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7951 
7952 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7953 
7954 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7955 
7956 	tcp->tcp_mdt_hdr_head = 0;
7957 	tcp->tcp_mdt_hdr_tail = 0;
7958 
7959 	/* Reset fusion-related fields */
7960 	tcp->tcp_fused = B_FALSE;
7961 	tcp->tcp_unfusable = B_FALSE;
7962 	tcp->tcp_fused_sigurg = B_FALSE;
7963 	tcp->tcp_loopback_peer = NULL;
7964 	tcp->tcp_fuse_rcv_hiwater = 0;
7965 
7966 	/* Initialize the header template */
7967 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7968 		err = tcp_header_init_ipv4(tcp);
7969 	} else {
7970 		err = tcp_header_init_ipv6(tcp);
7971 	}
7972 	if (err)
7973 		return (err);
7974 
7975 	/*
7976 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7977 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7978 	 */
7979 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7980 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7981 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
7982 
7983 	tcp->tcp_cork = B_FALSE;
7984 	/*
7985 	 * Init the tcp_debug option.  This value determines whether TCP
7986 	 * calls strlog() to print out debug messages.  Doing this
7987 	 * initialization here means that this value is not inherited thru
7988 	 * tcp_reinit().
7989 	 */
7990 	tcp->tcp_debug = tcps->tcps_dbg;
7991 
7992 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
7993 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
7994 
7995 	return (0);
7996 }
7997 
7998 /*
7999  * Initialize the IPv4 header. Loses any record of any IP options.
8000  */
8001 static int
8002 tcp_header_init_ipv4(tcp_t *tcp)
8003 {
8004 	tcph_t		*tcph;
8005 	uint32_t	sum;
8006 	conn_t		*connp;
8007 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8008 
8009 	/*
8010 	 * This is a simple initialization. If there's
8011 	 * already a template, it should never be too small,
8012 	 * so reuse it.  Otherwise, allocate space for the new one.
8013 	 */
8014 	if (tcp->tcp_iphc == NULL) {
8015 		ASSERT(tcp->tcp_iphc_len == 0);
8016 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8017 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8018 		if (tcp->tcp_iphc == NULL) {
8019 			tcp->tcp_iphc_len = 0;
8020 			return (ENOMEM);
8021 		}
8022 	}
8023 
8024 	/* options are gone; may need a new label */
8025 	connp = tcp->tcp_connp;
8026 	connp->conn_mlp_type = mlptSingle;
8027 	connp->conn_ulp_labeled = !is_system_labeled();
8028 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8029 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8030 	tcp->tcp_ip6h = NULL;
8031 	tcp->tcp_ipversion = IPV4_VERSION;
8032 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8033 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8034 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8035 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8036 	tcp->tcp_ipha->ipha_version_and_hdr_length
8037 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8038 	tcp->tcp_ipha->ipha_ident = 0;
8039 
8040 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8041 	tcp->tcp_tos = 0;
8042 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8043 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8044 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8045 
8046 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8047 	tcp->tcp_tcph = tcph;
8048 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8049 	/*
8050 	 * IP wants our header length in the checksum field to
8051 	 * allow it to perform a single pseudo-header+checksum
8052 	 * calculation on behalf of TCP.
8053 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8054 	 */
8055 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8056 	sum = (sum >> 16) + (sum & 0xFFFF);
8057 	U16_TO_ABE16(sum, tcph->th_sum);
8058 	return (0);
8059 }
8060 
8061 /*
8062  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8063  */
8064 static int
8065 tcp_header_init_ipv6(tcp_t *tcp)
8066 {
8067 	tcph_t	*tcph;
8068 	uint32_t	sum;
8069 	conn_t	*connp;
8070 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8071 
8072 	/*
8073 	 * This is a simple initialization. If there's
8074 	 * already a template, it should never be too small,
8075 	 * so reuse it. Otherwise, allocate space for the new one.
8076 	 * Ensure that there is enough space to "downgrade" the tcp_t
8077 	 * to an IPv4 tcp_t. This requires having space for a full load
8078 	 * of IPv4 options, as well as a full load of TCP options
8079 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8080 	 * than a v6 header and a TCP header with a full load of TCP options
8081 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8082 	 * We want to avoid reallocation in the "downgraded" case when
8083 	 * processing outbound IPv4 options.
8084 	 */
8085 	if (tcp->tcp_iphc == NULL) {
8086 		ASSERT(tcp->tcp_iphc_len == 0);
8087 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8088 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8089 		if (tcp->tcp_iphc == NULL) {
8090 			tcp->tcp_iphc_len = 0;
8091 			return (ENOMEM);
8092 		}
8093 	}
8094 
8095 	/* options are gone; may need a new label */
8096 	connp = tcp->tcp_connp;
8097 	connp->conn_mlp_type = mlptSingle;
8098 	connp->conn_ulp_labeled = !is_system_labeled();
8099 
8100 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8101 	tcp->tcp_ipversion = IPV6_VERSION;
8102 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8103 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8104 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8105 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8106 	tcp->tcp_ipha = NULL;
8107 
8108 	/* Initialize the header template */
8109 
8110 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8111 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8112 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8113 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8114 
8115 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8116 	tcp->tcp_tcph = tcph;
8117 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8118 	/*
8119 	 * IP wants our header length in the checksum field to
8120 	 * allow it to perform a single psuedo-header+checksum
8121 	 * calculation on behalf of TCP.
8122 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8123 	 */
8124 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8125 	sum = (sum >> 16) + (sum & 0xFFFF);
8126 	U16_TO_ABE16(sum, tcph->th_sum);
8127 	return (0);
8128 }
8129 
8130 /* At minimum we need 8 bytes in the TCP header for the lookup */
8131 #define	ICMP_MIN_TCP_HDR	8
8132 
8133 /*
8134  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8135  * passed up by IP. The message is always received on the correct tcp_t.
8136  * Assumes that IP has pulled up everything up to and including the ICMP header.
8137  */
8138 void
8139 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8140 {
8141 	icmph_t *icmph;
8142 	ipha_t	*ipha;
8143 	int	iph_hdr_length;
8144 	tcph_t	*tcph;
8145 	boolean_t ipsec_mctl = B_FALSE;
8146 	boolean_t secure;
8147 	mblk_t *first_mp = mp;
8148 	int32_t new_mss;
8149 	uint32_t ratio;
8150 	size_t mp_size = MBLKL(mp);
8151 	uint32_t seg_seq;
8152 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8153 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8154 
8155 	/* Assume IP provides aligned packets - otherwise toss */
8156 	if (!OK_32PTR(mp->b_rptr)) {
8157 		freemsg(mp);
8158 		return;
8159 	}
8160 
8161 	/*
8162 	 * Since ICMP errors are normal data marked with M_CTL when sent
8163 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8164 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8165 	 */
8166 	if ((mp_size == sizeof (ipsec_info_t)) &&
8167 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8168 		ASSERT(mp->b_cont != NULL);
8169 		mp = mp->b_cont;
8170 		/* IP should have done this */
8171 		ASSERT(OK_32PTR(mp->b_rptr));
8172 		mp_size = MBLKL(mp);
8173 		ipsec_mctl = B_TRUE;
8174 	}
8175 
8176 	/*
8177 	 * Verify that we have a complete outer IP header. If not, drop it.
8178 	 */
8179 	if (mp_size < sizeof (ipha_t)) {
8180 noticmpv4:
8181 		freemsg(first_mp);
8182 		return;
8183 	}
8184 
8185 	ipha = (ipha_t *)mp->b_rptr;
8186 	/*
8187 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8188 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8189 	 */
8190 	switch (IPH_HDR_VERSION(ipha)) {
8191 	case IPV6_VERSION:
8192 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8193 		return;
8194 	case IPV4_VERSION:
8195 		break;
8196 	default:
8197 		goto noticmpv4;
8198 	}
8199 
8200 	/* Skip past the outer IP and ICMP headers */
8201 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8202 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8203 	/*
8204 	 * If we don't have the correct outer IP header length or if the ULP
8205 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8206 	 * send it upstream.
8207 	 */
8208 	if (iph_hdr_length < sizeof (ipha_t) ||
8209 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8210 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8211 		goto noticmpv4;
8212 	}
8213 	ipha = (ipha_t *)&icmph[1];
8214 
8215 	/* Skip past the inner IP and find the ULP header */
8216 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8217 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8218 	/*
8219 	 * If we don't have the correct inner IP header length or if the ULP
8220 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8221 	 * bytes of TCP header, drop it.
8222 	 */
8223 	if (iph_hdr_length < sizeof (ipha_t) ||
8224 	    ipha->ipha_protocol != IPPROTO_TCP ||
8225 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8226 		goto noticmpv4;
8227 	}
8228 
8229 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8230 		if (ipsec_mctl) {
8231 			secure = ipsec_in_is_secure(first_mp);
8232 		} else {
8233 			secure = B_FALSE;
8234 		}
8235 		if (secure) {
8236 			/*
8237 			 * If we are willing to accept this in clear
8238 			 * we don't have to verify policy.
8239 			 */
8240 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8241 				if (!tcp_check_policy(tcp, first_mp,
8242 				    ipha, NULL, secure, ipsec_mctl)) {
8243 					/*
8244 					 * tcp_check_policy called
8245 					 * ip_drop_packet() on failure.
8246 					 */
8247 					return;
8248 				}
8249 			}
8250 		}
8251 	} else if (ipsec_mctl) {
8252 		/*
8253 		 * This is a hard_bound connection. IP has already
8254 		 * verified policy. We don't have to do it again.
8255 		 */
8256 		freeb(first_mp);
8257 		first_mp = mp;
8258 		ipsec_mctl = B_FALSE;
8259 	}
8260 
8261 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8262 	/*
8263 	 * TCP SHOULD check that the TCP sequence number contained in
8264 	 * payload of the ICMP error message is within the range
8265 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8266 	 */
8267 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8268 		/*
8269 		 * The ICMP message is bogus, just drop it.  But if this is
8270 		 * an ICMP too big message, IP has already changed
8271 		 * the ire_max_frag to the bogus value.  We need to change
8272 		 * it back.
8273 		 */
8274 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8275 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8276 			conn_t *connp = tcp->tcp_connp;
8277 			ire_t *ire;
8278 			int flag;
8279 
8280 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8281 				flag = tcp->tcp_ipha->
8282 				    ipha_fragment_offset_and_flags;
8283 			} else {
8284 				flag = 0;
8285 			}
8286 			mutex_enter(&connp->conn_lock);
8287 			if ((ire = connp->conn_ire_cache) != NULL) {
8288 				mutex_enter(&ire->ire_lock);
8289 				mutex_exit(&connp->conn_lock);
8290 				ire->ire_max_frag = tcp->tcp_if_mtu;
8291 				ire->ire_frag_flag |= flag;
8292 				mutex_exit(&ire->ire_lock);
8293 			} else {
8294 				mutex_exit(&connp->conn_lock);
8295 			}
8296 		}
8297 		goto noticmpv4;
8298 	}
8299 
8300 	switch (icmph->icmph_type) {
8301 	case ICMP_DEST_UNREACHABLE:
8302 		switch (icmph->icmph_code) {
8303 		case ICMP_FRAGMENTATION_NEEDED:
8304 			/*
8305 			 * Reduce the MSS based on the new MTU.  This will
8306 			 * eliminate any fragmentation locally.
8307 			 * N.B.  There may well be some funny side-effects on
8308 			 * the local send policy and the remote receive policy.
8309 			 * Pending further research, we provide
8310 			 * tcp_ignore_path_mtu just in case this proves
8311 			 * disastrous somewhere.
8312 			 *
8313 			 * After updating the MSS, retransmit part of the
8314 			 * dropped segment using the new mss by calling
8315 			 * tcp_wput_data().  Need to adjust all those
8316 			 * params to make sure tcp_wput_data() work properly.
8317 			 */
8318 			if (tcps->tcps_ignore_path_mtu ||
8319 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8320 				break;
8321 
8322 			/*
8323 			 * Decrease the MSS by time stamp options
8324 			 * IP options and IPSEC options. tcp_hdr_len
8325 			 * includes time stamp option and IP option
8326 			 * length.  Note that new_mss may be negative
8327 			 * if tcp_ipsec_overhead is large and the
8328 			 * icmph_du_mtu is the minimum value, which is 68.
8329 			 */
8330 			new_mss = ntohs(icmph->icmph_du_mtu) -
8331 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8332 
8333 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8334 			    new_mss);
8335 
8336 			/*
8337 			 * Only update the MSS if the new one is
8338 			 * smaller than the previous one.  This is
8339 			 * to avoid problems when getting multiple
8340 			 * ICMP errors for the same MTU.
8341 			 */
8342 			if (new_mss >= tcp->tcp_mss)
8343 				break;
8344 
8345 			/*
8346 			 * Note that we are using the template header's DF
8347 			 * bit in the fast path sending.  So we need to compare
8348 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8349 			 * And stop doing IPv4 PMTUd if new_mss is less than
8350 			 * MAX(tcps_mss_min, ip_pmtu_min).
8351 			 */
8352 			if (new_mss < tcps->tcps_mss_min ||
8353 			    new_mss < ipst->ips_ip_pmtu_min) {
8354 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8355 				    0;
8356 			}
8357 
8358 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8359 			ASSERT(ratio >= 1);
8360 			tcp_mss_set(tcp, new_mss, B_TRUE);
8361 
8362 			/*
8363 			 * Make sure we have something to
8364 			 * send.
8365 			 */
8366 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8367 			    (tcp->tcp_xmit_head != NULL)) {
8368 				/*
8369 				 * Shrink tcp_cwnd in
8370 				 * proportion to the old MSS/new MSS.
8371 				 */
8372 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8373 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8374 				    (tcp->tcp_unsent == 0)) {
8375 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8376 				} else {
8377 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8378 				}
8379 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8380 				tcp->tcp_rexmit = B_TRUE;
8381 				tcp->tcp_dupack_cnt = 0;
8382 				tcp->tcp_snd_burst = TCP_CWND_SS;
8383 				tcp_ss_rexmit(tcp);
8384 			}
8385 			break;
8386 		case ICMP_PORT_UNREACHABLE:
8387 		case ICMP_PROTOCOL_UNREACHABLE:
8388 			switch (tcp->tcp_state) {
8389 			case TCPS_SYN_SENT:
8390 			case TCPS_SYN_RCVD:
8391 				/*
8392 				 * ICMP can snipe away incipient
8393 				 * TCP connections as long as
8394 				 * seq number is same as initial
8395 				 * send seq number.
8396 				 */
8397 				if (seg_seq == tcp->tcp_iss) {
8398 					(void) tcp_clean_death(tcp,
8399 					    ECONNREFUSED, 6);
8400 				}
8401 				break;
8402 			}
8403 			break;
8404 		case ICMP_HOST_UNREACHABLE:
8405 		case ICMP_NET_UNREACHABLE:
8406 			/* Record the error in case we finally time out. */
8407 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8408 				tcp->tcp_client_errno = EHOSTUNREACH;
8409 			else
8410 				tcp->tcp_client_errno = ENETUNREACH;
8411 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8412 				if (tcp->tcp_listener != NULL &&
8413 				    tcp->tcp_listener->tcp_syn_defense) {
8414 					/*
8415 					 * Ditch the half-open connection if we
8416 					 * suspect a SYN attack is under way.
8417 					 */
8418 					tcp_ip_ire_mark_advice(tcp);
8419 					(void) tcp_clean_death(tcp,
8420 					    tcp->tcp_client_errno, 7);
8421 				}
8422 			}
8423 			break;
8424 		default:
8425 			break;
8426 		}
8427 		break;
8428 	case ICMP_SOURCE_QUENCH: {
8429 		/*
8430 		 * use a global boolean to control
8431 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8432 		 * The default is false.
8433 		 */
8434 		if (tcp_icmp_source_quench) {
8435 			/*
8436 			 * Reduce the sending rate as if we got a
8437 			 * retransmit timeout
8438 			 */
8439 			uint32_t npkt;
8440 
8441 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8442 			    tcp->tcp_mss;
8443 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8444 			tcp->tcp_cwnd = tcp->tcp_mss;
8445 			tcp->tcp_cwnd_cnt = 0;
8446 		}
8447 		break;
8448 	}
8449 	}
8450 	freemsg(first_mp);
8451 }
8452 
8453 /*
8454  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8455  * error messages passed up by IP.
8456  * Assumes that IP has pulled up all the extension headers as well
8457  * as the ICMPv6 header.
8458  */
8459 static void
8460 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8461 {
8462 	icmp6_t *icmp6;
8463 	ip6_t	*ip6h;
8464 	uint16_t	iph_hdr_length;
8465 	tcpha_t	*tcpha;
8466 	uint8_t	*nexthdrp;
8467 	uint32_t new_mss;
8468 	uint32_t ratio;
8469 	boolean_t secure;
8470 	mblk_t *first_mp = mp;
8471 	size_t mp_size;
8472 	uint32_t seg_seq;
8473 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8474 
8475 	/*
8476 	 * The caller has determined if this is an IPSEC_IN packet and
8477 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8478 	 */
8479 	if (ipsec_mctl)
8480 		mp = mp->b_cont;
8481 
8482 	mp_size = MBLKL(mp);
8483 
8484 	/*
8485 	 * Verify that we have a complete IP header. If not, send it upstream.
8486 	 */
8487 	if (mp_size < sizeof (ip6_t)) {
8488 noticmpv6:
8489 		freemsg(first_mp);
8490 		return;
8491 	}
8492 
8493 	/*
8494 	 * Verify this is an ICMPV6 packet, else send it upstream.
8495 	 */
8496 	ip6h = (ip6_t *)mp->b_rptr;
8497 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8498 		iph_hdr_length = IPV6_HDR_LEN;
8499 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8500 	    &nexthdrp) ||
8501 	    *nexthdrp != IPPROTO_ICMPV6) {
8502 		goto noticmpv6;
8503 	}
8504 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8505 	ip6h = (ip6_t *)&icmp6[1];
8506 	/*
8507 	 * Verify if we have a complete ICMP and inner IP header.
8508 	 */
8509 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8510 		goto noticmpv6;
8511 
8512 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8513 		goto noticmpv6;
8514 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8515 	/*
8516 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8517 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8518 	 * packet.
8519 	 */
8520 	if ((*nexthdrp != IPPROTO_TCP) ||
8521 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8522 		goto noticmpv6;
8523 	}
8524 
8525 	/*
8526 	 * ICMP errors come on the right queue or come on
8527 	 * listener/global queue for detached connections and
8528 	 * get switched to the right queue. If it comes on the
8529 	 * right queue, policy check has already been done by IP
8530 	 * and thus free the first_mp without verifying the policy.
8531 	 * If it has come for a non-hard bound connection, we need
8532 	 * to verify policy as IP may not have done it.
8533 	 */
8534 	if (!tcp->tcp_hard_bound) {
8535 		if (ipsec_mctl) {
8536 			secure = ipsec_in_is_secure(first_mp);
8537 		} else {
8538 			secure = B_FALSE;
8539 		}
8540 		if (secure) {
8541 			/*
8542 			 * If we are willing to accept this in clear
8543 			 * we don't have to verify policy.
8544 			 */
8545 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8546 				if (!tcp_check_policy(tcp, first_mp,
8547 				    NULL, ip6h, secure, ipsec_mctl)) {
8548 					/*
8549 					 * tcp_check_policy called
8550 					 * ip_drop_packet() on failure.
8551 					 */
8552 					return;
8553 				}
8554 			}
8555 		}
8556 	} else if (ipsec_mctl) {
8557 		/*
8558 		 * This is a hard_bound connection. IP has already
8559 		 * verified policy. We don't have to do it again.
8560 		 */
8561 		freeb(first_mp);
8562 		first_mp = mp;
8563 		ipsec_mctl = B_FALSE;
8564 	}
8565 
8566 	seg_seq = ntohl(tcpha->tha_seq);
8567 	/*
8568 	 * TCP SHOULD check that the TCP sequence number contained in
8569 	 * payload of the ICMP error message is within the range
8570 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8571 	 */
8572 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8573 		/*
8574 		 * If the ICMP message is bogus, should we kill the
8575 		 * connection, or should we just drop the bogus ICMP
8576 		 * message? It would probably make more sense to just
8577 		 * drop the message so that if this one managed to get
8578 		 * in, the real connection should not suffer.
8579 		 */
8580 		goto noticmpv6;
8581 	}
8582 
8583 	switch (icmp6->icmp6_type) {
8584 	case ICMP6_PACKET_TOO_BIG:
8585 		/*
8586 		 * Reduce the MSS based on the new MTU.  This will
8587 		 * eliminate any fragmentation locally.
8588 		 * N.B.  There may well be some funny side-effects on
8589 		 * the local send policy and the remote receive policy.
8590 		 * Pending further research, we provide
8591 		 * tcp_ignore_path_mtu just in case this proves
8592 		 * disastrous somewhere.
8593 		 *
8594 		 * After updating the MSS, retransmit part of the
8595 		 * dropped segment using the new mss by calling
8596 		 * tcp_wput_data().  Need to adjust all those
8597 		 * params to make sure tcp_wput_data() work properly.
8598 		 */
8599 		if (tcps->tcps_ignore_path_mtu)
8600 			break;
8601 
8602 		/*
8603 		 * Decrease the MSS by time stamp options
8604 		 * IP options and IPSEC options. tcp_hdr_len
8605 		 * includes time stamp option and IP option
8606 		 * length.
8607 		 */
8608 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8609 		    tcp->tcp_ipsec_overhead;
8610 
8611 		/*
8612 		 * Only update the MSS if the new one is
8613 		 * smaller than the previous one.  This is
8614 		 * to avoid problems when getting multiple
8615 		 * ICMP errors for the same MTU.
8616 		 */
8617 		if (new_mss >= tcp->tcp_mss)
8618 			break;
8619 
8620 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8621 		ASSERT(ratio >= 1);
8622 		tcp_mss_set(tcp, new_mss, B_TRUE);
8623 
8624 		/*
8625 		 * Make sure we have something to
8626 		 * send.
8627 		 */
8628 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8629 		    (tcp->tcp_xmit_head != NULL)) {
8630 			/*
8631 			 * Shrink tcp_cwnd in
8632 			 * proportion to the old MSS/new MSS.
8633 			 */
8634 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8635 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8636 			    (tcp->tcp_unsent == 0)) {
8637 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8638 			} else {
8639 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8640 			}
8641 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8642 			tcp->tcp_rexmit = B_TRUE;
8643 			tcp->tcp_dupack_cnt = 0;
8644 			tcp->tcp_snd_burst = TCP_CWND_SS;
8645 			tcp_ss_rexmit(tcp);
8646 		}
8647 		break;
8648 
8649 	case ICMP6_DST_UNREACH:
8650 		switch (icmp6->icmp6_code) {
8651 		case ICMP6_DST_UNREACH_NOPORT:
8652 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8653 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8654 			    (seg_seq == tcp->tcp_iss)) {
8655 				(void) tcp_clean_death(tcp,
8656 				    ECONNREFUSED, 8);
8657 			}
8658 			break;
8659 
8660 		case ICMP6_DST_UNREACH_ADMIN:
8661 		case ICMP6_DST_UNREACH_NOROUTE:
8662 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8663 		case ICMP6_DST_UNREACH_ADDR:
8664 			/* Record the error in case we finally time out. */
8665 			tcp->tcp_client_errno = EHOSTUNREACH;
8666 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8667 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8668 			    (seg_seq == tcp->tcp_iss)) {
8669 				if (tcp->tcp_listener != NULL &&
8670 				    tcp->tcp_listener->tcp_syn_defense) {
8671 					/*
8672 					 * Ditch the half-open connection if we
8673 					 * suspect a SYN attack is under way.
8674 					 */
8675 					tcp_ip_ire_mark_advice(tcp);
8676 					(void) tcp_clean_death(tcp,
8677 					    tcp->tcp_client_errno, 9);
8678 				}
8679 			}
8680 
8681 
8682 			break;
8683 		default:
8684 			break;
8685 		}
8686 		break;
8687 
8688 	case ICMP6_PARAM_PROB:
8689 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8690 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8691 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8692 		    (uchar_t *)nexthdrp) {
8693 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8694 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8695 				(void) tcp_clean_death(tcp,
8696 				    ECONNREFUSED, 10);
8697 			}
8698 			break;
8699 		}
8700 		break;
8701 
8702 	case ICMP6_TIME_EXCEEDED:
8703 	default:
8704 		break;
8705 	}
8706 	freemsg(first_mp);
8707 }
8708 
8709 /*
8710  * Notify IP that we are having trouble with this connection.  IP should
8711  * blow the IRE away and start over.
8712  */
8713 static void
8714 tcp_ip_notify(tcp_t *tcp)
8715 {
8716 	struct iocblk	*iocp;
8717 	ipid_t	*ipid;
8718 	mblk_t	*mp;
8719 
8720 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8721 	if (tcp->tcp_ipversion == IPV6_VERSION)
8722 		return;
8723 
8724 	mp = mkiocb(IP_IOCTL);
8725 	if (mp == NULL)
8726 		return;
8727 
8728 	iocp = (struct iocblk *)mp->b_rptr;
8729 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8730 
8731 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8732 	if (!mp->b_cont) {
8733 		freeb(mp);
8734 		return;
8735 	}
8736 
8737 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8738 	mp->b_cont->b_wptr += iocp->ioc_count;
8739 	bzero(ipid, sizeof (*ipid));
8740 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8741 	ipid->ipid_ire_type = IRE_CACHE;
8742 	ipid->ipid_addr_offset = sizeof (ipid_t);
8743 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8744 	/*
8745 	 * Note: in the case of source routing we want to blow away the
8746 	 * route to the first source route hop.
8747 	 */
8748 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8749 	    sizeof (tcp->tcp_ipha->ipha_dst));
8750 
8751 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8752 }
8753 
8754 /* Unlink and return any mblk that looks like it contains an ire */
8755 static mblk_t *
8756 tcp_ire_mp(mblk_t **mpp)
8757 {
8758 	mblk_t 	*mp = *mpp;
8759 	mblk_t	*prev_mp = NULL;
8760 
8761 	for (;;) {
8762 		switch (DB_TYPE(mp)) {
8763 		case IRE_DB_TYPE:
8764 		case IRE_DB_REQ_TYPE:
8765 			if (mp == *mpp) {
8766 				*mpp = mp->b_cont;
8767 			} else {
8768 				prev_mp->b_cont = mp->b_cont;
8769 			}
8770 			mp->b_cont = NULL;
8771 			return (mp);
8772 		default:
8773 			break;
8774 		}
8775 		prev_mp = mp;
8776 		mp = mp->b_cont;
8777 		if (mp == NULL)
8778 			break;
8779 	}
8780 	return (mp);
8781 }
8782 
8783 /*
8784  * Timer callback routine for keepalive probe.  We do a fake resend of
8785  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8786  * check to see if we have heard anything from the other end for the last
8787  * RTO period.  If we have, set the timer to expire for another
8788  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8789  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8790  * the timeout if we have not heard from the other side.  If for more than
8791  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8792  * kill the connection unless the keepalive abort threshold is 0.  In
8793  * that case, we will probe "forever."
8794  */
8795 static void
8796 tcp_keepalive_killer(void *arg)
8797 {
8798 	mblk_t	*mp;
8799 	conn_t	*connp = (conn_t *)arg;
8800 	tcp_t  	*tcp = connp->conn_tcp;
8801 	int32_t	firetime;
8802 	int32_t	idletime;
8803 	int32_t	ka_intrvl;
8804 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8805 
8806 	tcp->tcp_ka_tid = 0;
8807 
8808 	if (tcp->tcp_fused)
8809 		return;
8810 
8811 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8812 	ka_intrvl = tcp->tcp_ka_interval;
8813 
8814 	/*
8815 	 * Keepalive probe should only be sent if the application has not
8816 	 * done a close on the connection.
8817 	 */
8818 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8819 		return;
8820 	}
8821 	/* Timer fired too early, restart it. */
8822 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8823 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8824 		    MSEC_TO_TICK(ka_intrvl));
8825 		return;
8826 	}
8827 
8828 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8829 	/*
8830 	 * If we have not heard from the other side for a long
8831 	 * time, kill the connection unless the keepalive abort
8832 	 * threshold is 0.  In that case, we will probe "forever."
8833 	 */
8834 	if (tcp->tcp_ka_abort_thres != 0 &&
8835 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8836 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8837 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8838 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8839 		return;
8840 	}
8841 
8842 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8843 	    idletime >= ka_intrvl) {
8844 		/* Fake resend of last ACKed byte. */
8845 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8846 
8847 		if (mp1 != NULL) {
8848 			*mp1->b_wptr++ = '\0';
8849 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8850 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8851 			freeb(mp1);
8852 			/*
8853 			 * if allocation failed, fall through to start the
8854 			 * timer back.
8855 			 */
8856 			if (mp != NULL) {
8857 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8858 				BUMP_MIB(&tcps->tcps_mib,
8859 				    tcpTimKeepaliveProbe);
8860 				if (tcp->tcp_ka_last_intrvl != 0) {
8861 					int max;
8862 					/*
8863 					 * We should probe again at least
8864 					 * in ka_intrvl, but not more than
8865 					 * tcp_rexmit_interval_max.
8866 					 */
8867 					max = tcps->tcps_rexmit_interval_max;
8868 					firetime = MIN(ka_intrvl - 1,
8869 					    tcp->tcp_ka_last_intrvl << 1);
8870 					if (firetime > max)
8871 						firetime = max;
8872 				} else {
8873 					firetime = tcp->tcp_rto;
8874 				}
8875 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8876 				    tcp_keepalive_killer,
8877 				    MSEC_TO_TICK(firetime));
8878 				tcp->tcp_ka_last_intrvl = firetime;
8879 				return;
8880 			}
8881 		}
8882 	} else {
8883 		tcp->tcp_ka_last_intrvl = 0;
8884 	}
8885 
8886 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8887 	if ((firetime = ka_intrvl - idletime) < 0) {
8888 		firetime = ka_intrvl;
8889 	}
8890 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8891 	    MSEC_TO_TICK(firetime));
8892 }
8893 
8894 int
8895 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8896 {
8897 	queue_t	*q = tcp->tcp_rq;
8898 	int32_t	mss = tcp->tcp_mss;
8899 	int	maxpsz;
8900 	conn_t	*connp = tcp->tcp_connp;
8901 
8902 	if (TCP_IS_DETACHED(tcp))
8903 		return (mss);
8904 	if (tcp->tcp_fused) {
8905 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8906 		mss = INFPSZ;
8907 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8908 		/*
8909 		 * Set the sd_qn_maxpsz according to the socket send buffer
8910 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8911 		 * instruct the stream head to copyin user data into contiguous
8912 		 * kernel-allocated buffers without breaking it up into smaller
8913 		 * chunks.  We round up the buffer size to the nearest SMSS.
8914 		 */
8915 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8916 		if (tcp->tcp_kssl_ctx == NULL)
8917 			mss = INFPSZ;
8918 		else
8919 			mss = SSL3_MAX_RECORD_LEN;
8920 	} else {
8921 		/*
8922 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8923 		 * (and a multiple of the mss).  This instructs the stream
8924 		 * head to break down larger than SMSS writes into SMSS-
8925 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8926 		 */
8927 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8928 		maxpsz = tcp->tcp_maxpsz * mss;
8929 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8930 			maxpsz = tcp->tcp_xmit_hiwater/2;
8931 			/* Round up to nearest mss */
8932 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8933 		}
8934 	}
8935 
8936 	(void) proto_set_maxpsz(q, connp, maxpsz);
8937 	if (!(IPCL_IS_NONSTR(connp))) {
8938 		/* XXX do it in set_maxpsz()? */
8939 		tcp->tcp_wq->q_maxpsz = maxpsz;
8940 	}
8941 
8942 	if (set_maxblk)
8943 		(void) proto_set_tx_maxblk(q, connp, mss);
8944 	return (mss);
8945 }
8946 
8947 /*
8948  * Extract option values from a tcp header.  We put any found values into the
8949  * tcpopt struct and return a bitmask saying which options were found.
8950  */
8951 static int
8952 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8953 {
8954 	uchar_t		*endp;
8955 	int		len;
8956 	uint32_t	mss;
8957 	uchar_t		*up = (uchar_t *)tcph;
8958 	int		found = 0;
8959 	int32_t		sack_len;
8960 	tcp_seq		sack_begin, sack_end;
8961 	tcp_t		*tcp;
8962 
8963 	endp = up + TCP_HDR_LENGTH(tcph);
8964 	up += TCP_MIN_HEADER_LENGTH;
8965 	while (up < endp) {
8966 		len = endp - up;
8967 		switch (*up) {
8968 		case TCPOPT_EOL:
8969 			break;
8970 
8971 		case TCPOPT_NOP:
8972 			up++;
8973 			continue;
8974 
8975 		case TCPOPT_MAXSEG:
8976 			if (len < TCPOPT_MAXSEG_LEN ||
8977 			    up[1] != TCPOPT_MAXSEG_LEN)
8978 				break;
8979 
8980 			mss = BE16_TO_U16(up+2);
8981 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8982 			tcpopt->tcp_opt_mss = mss;
8983 			found |= TCP_OPT_MSS_PRESENT;
8984 
8985 			up += TCPOPT_MAXSEG_LEN;
8986 			continue;
8987 
8988 		case TCPOPT_WSCALE:
8989 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8990 				break;
8991 
8992 			if (up[2] > TCP_MAX_WINSHIFT)
8993 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8994 			else
8995 				tcpopt->tcp_opt_wscale = up[2];
8996 			found |= TCP_OPT_WSCALE_PRESENT;
8997 
8998 			up += TCPOPT_WS_LEN;
8999 			continue;
9000 
9001 		case TCPOPT_SACK_PERMITTED:
9002 			if (len < TCPOPT_SACK_OK_LEN ||
9003 			    up[1] != TCPOPT_SACK_OK_LEN)
9004 				break;
9005 			found |= TCP_OPT_SACK_OK_PRESENT;
9006 			up += TCPOPT_SACK_OK_LEN;
9007 			continue;
9008 
9009 		case TCPOPT_SACK:
9010 			if (len <= 2 || up[1] <= 2 || len < up[1])
9011 				break;
9012 
9013 			/* If TCP is not interested in SACK blks... */
9014 			if ((tcp = tcpopt->tcp) == NULL) {
9015 				up += up[1];
9016 				continue;
9017 			}
9018 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9019 			up += TCPOPT_HEADER_LEN;
9020 
9021 			/*
9022 			 * If the list is empty, allocate one and assume
9023 			 * nothing is sack'ed.
9024 			 */
9025 			ASSERT(tcp->tcp_sack_info != NULL);
9026 			if (tcp->tcp_notsack_list == NULL) {
9027 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9028 				    tcp->tcp_suna, tcp->tcp_snxt,
9029 				    &(tcp->tcp_num_notsack_blk),
9030 				    &(tcp->tcp_cnt_notsack_list));
9031 
9032 				/*
9033 				 * Make sure tcp_notsack_list is not NULL.
9034 				 * This happens when kmem_alloc(KM_NOSLEEP)
9035 				 * returns NULL.
9036 				 */
9037 				if (tcp->tcp_notsack_list == NULL) {
9038 					up += sack_len;
9039 					continue;
9040 				}
9041 				tcp->tcp_fack = tcp->tcp_suna;
9042 			}
9043 
9044 			while (sack_len > 0) {
9045 				if (up + 8 > endp) {
9046 					up = endp;
9047 					break;
9048 				}
9049 				sack_begin = BE32_TO_U32(up);
9050 				up += 4;
9051 				sack_end = BE32_TO_U32(up);
9052 				up += 4;
9053 				sack_len -= 8;
9054 				/*
9055 				 * Bounds checking.  Make sure the SACK
9056 				 * info is within tcp_suna and tcp_snxt.
9057 				 * If this SACK blk is out of bound, ignore
9058 				 * it but continue to parse the following
9059 				 * blks.
9060 				 */
9061 				if (SEQ_LEQ(sack_end, sack_begin) ||
9062 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9063 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9064 					continue;
9065 				}
9066 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9067 				    sack_begin, sack_end,
9068 				    &(tcp->tcp_num_notsack_blk),
9069 				    &(tcp->tcp_cnt_notsack_list));
9070 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9071 					tcp->tcp_fack = sack_end;
9072 				}
9073 			}
9074 			found |= TCP_OPT_SACK_PRESENT;
9075 			continue;
9076 
9077 		case TCPOPT_TSTAMP:
9078 			if (len < TCPOPT_TSTAMP_LEN ||
9079 			    up[1] != TCPOPT_TSTAMP_LEN)
9080 				break;
9081 
9082 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9083 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9084 
9085 			found |= TCP_OPT_TSTAMP_PRESENT;
9086 
9087 			up += TCPOPT_TSTAMP_LEN;
9088 			continue;
9089 
9090 		default:
9091 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9092 				break;
9093 			up += up[1];
9094 			continue;
9095 		}
9096 		break;
9097 	}
9098 	return (found);
9099 }
9100 
9101 /*
9102  * Set the mss associated with a particular tcp based on its current value,
9103  * and a new one passed in. Observe minimums and maximums, and reset
9104  * other state variables that we want to view as multiples of mss.
9105  *
9106  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9107  * highwater marks etc. need to be initialized or adjusted.
9108  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9109  *    packet arrives.
9110  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9111  *    ICMP6_PACKET_TOO_BIG arrives.
9112  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9113  *    to increase the MSS to use the extra bytes available.
9114  *
9115  * Callers except tcp_paws_check() ensure that they only reduce mss.
9116  */
9117 static void
9118 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9119 {
9120 	uint32_t	mss_max;
9121 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9122 
9123 	if (tcp->tcp_ipversion == IPV4_VERSION)
9124 		mss_max = tcps->tcps_mss_max_ipv4;
9125 	else
9126 		mss_max = tcps->tcps_mss_max_ipv6;
9127 
9128 	if (mss < tcps->tcps_mss_min)
9129 		mss = tcps->tcps_mss_min;
9130 	if (mss > mss_max)
9131 		mss = mss_max;
9132 	/*
9133 	 * Unless naglim has been set by our client to
9134 	 * a non-mss value, force naglim to track mss.
9135 	 * This can help to aggregate small writes.
9136 	 */
9137 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9138 		tcp->tcp_naglim = mss;
9139 	/*
9140 	 * TCP should be able to buffer at least 4 MSS data for obvious
9141 	 * performance reason.
9142 	 */
9143 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9144 		tcp->tcp_xmit_hiwater = mss << 2;
9145 
9146 	/*
9147 	 * Set the xmit_lowater to at least twice of MSS.
9148 	 */
9149 	if ((mss << 1) > tcp->tcp_xmit_lowater)
9150 		tcp->tcp_xmit_lowater = mss << 1;
9151 
9152 	if (do_ss) {
9153 		/*
9154 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9155 		 * changing due to a reduction in MTU, presumably as a
9156 		 * result of a new path component, reset cwnd to its
9157 		 * "initial" value, as a multiple of the new mss.
9158 		 */
9159 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9160 	} else {
9161 		/*
9162 		 * Called by tcp_paws_check(), the mss increased
9163 		 * marginally to allow use of space previously taken
9164 		 * by the timestamp option. It would be inappropriate
9165 		 * to apply slow start or tcp_init_cwnd values to
9166 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9167 		 */
9168 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9169 		tcp->tcp_cwnd_cnt = 0;
9170 	}
9171 	tcp->tcp_mss = mss;
9172 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9173 }
9174 
9175 /* For /dev/tcp aka AF_INET open */
9176 static int
9177 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9178 {
9179 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9180 }
9181 
9182 /* For /dev/tcp6 aka AF_INET6 open */
9183 static int
9184 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9185 {
9186 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9187 }
9188 
9189 static conn_t *
9190 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9191     boolean_t issocket, int *errorp)
9192 {
9193 	tcp_t		*tcp = NULL;
9194 	conn_t		*connp;
9195 	int		err;
9196 	zoneid_t	zoneid;
9197 	tcp_stack_t	*tcps;
9198 	squeue_t	*sqp;
9199 
9200 	ASSERT(errorp != NULL);
9201 	/*
9202 	 * Find the proper zoneid and netstack.
9203 	 */
9204 	/*
9205 	 * Special case for install: miniroot needs to be able to
9206 	 * access files via NFS as though it were always in the
9207 	 * global zone.
9208 	 */
9209 	if (credp == kcred && nfs_global_client_only != 0) {
9210 		zoneid = GLOBAL_ZONEID;
9211 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9212 		    netstack_tcp;
9213 		ASSERT(tcps != NULL);
9214 	} else {
9215 		netstack_t *ns;
9216 
9217 		ns = netstack_find_by_cred(credp);
9218 		ASSERT(ns != NULL);
9219 		tcps = ns->netstack_tcp;
9220 		ASSERT(tcps != NULL);
9221 
9222 		/*
9223 		 * For exclusive stacks we set the zoneid to zero
9224 		 * to make TCP operate as if in the global zone.
9225 		 */
9226 		if (tcps->tcps_netstack->netstack_stackid !=
9227 		    GLOBAL_NETSTACKID)
9228 			zoneid = GLOBAL_ZONEID;
9229 		else
9230 			zoneid = crgetzoneid(credp);
9231 	}
9232 	/*
9233 	 * For stackid zero this is done from strplumb.c, but
9234 	 * non-zero stackids are handled here.
9235 	 */
9236 	if (tcps->tcps_g_q == NULL &&
9237 	    tcps->tcps_netstack->netstack_stackid !=
9238 	    GLOBAL_NETSTACKID) {
9239 		tcp_g_q_setup(tcps);
9240 	}
9241 
9242 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9243 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9244 	/*
9245 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9246 	 * so we drop it by one.
9247 	 */
9248 	netstack_rele(tcps->tcps_netstack);
9249 	if (connp == NULL) {
9250 		*errorp = ENOSR;
9251 		return (NULL);
9252 	}
9253 	connp->conn_sqp = sqp;
9254 	connp->conn_initial_sqp = connp->conn_sqp;
9255 	tcp = connp->conn_tcp;
9256 
9257 	if (isv6) {
9258 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9259 		connp->conn_send = ip_output_v6;
9260 		connp->conn_af_isv6 = B_TRUE;
9261 		connp->conn_pkt_isv6 = B_TRUE;
9262 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9263 		tcp->tcp_ipversion = IPV6_VERSION;
9264 		tcp->tcp_family = AF_INET6;
9265 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9266 	} else {
9267 		connp->conn_flags |= IPCL_TCP4;
9268 		connp->conn_send = ip_output;
9269 		connp->conn_af_isv6 = B_FALSE;
9270 		connp->conn_pkt_isv6 = B_FALSE;
9271 		tcp->tcp_ipversion = IPV4_VERSION;
9272 		tcp->tcp_family = AF_INET;
9273 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9274 	}
9275 
9276 	/*
9277 	 * TCP keeps a copy of cred for cache locality reasons but
9278 	 * we put a reference only once. If connp->conn_cred
9279 	 * becomes invalid, tcp_cred should also be set to NULL.
9280 	 */
9281 	tcp->tcp_cred = connp->conn_cred = credp;
9282 	crhold(connp->conn_cred);
9283 	tcp->tcp_cpid = curproc->p_pid;
9284 	tcp->tcp_open_time = lbolt64;
9285 	connp->conn_zoneid = zoneid;
9286 	connp->conn_mlp_type = mlptSingle;
9287 	connp->conn_ulp_labeled = !is_system_labeled();
9288 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9289 	ASSERT(tcp->tcp_tcps == tcps);
9290 
9291 	/*
9292 	 * If the caller has the process-wide flag set, then default to MAC
9293 	 * exempt mode.  This allows read-down to unlabeled hosts.
9294 	 */
9295 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9296 		connp->conn_mac_exempt = B_TRUE;
9297 
9298 	connp->conn_dev = NULL;
9299 	if (issocket) {
9300 		connp->conn_flags |= IPCL_SOCKET;
9301 		tcp->tcp_issocket = 1;
9302 	}
9303 
9304 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9305 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9306 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9307 
9308 	/* Non-zero default values */
9309 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9310 
9311 	if (q == NULL) {
9312 		/*
9313 		 * Create a helper stream for non-STREAMS socket.
9314 		 */
9315 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9316 		if (err != 0) {
9317 			ip1dbg(("tcp_create_common: create of IP helper stream "
9318 			    "failed\n"));
9319 			CONN_DEC_REF(connp);
9320 			*errorp = err;
9321 			return (NULL);
9322 		}
9323 		q = connp->conn_rq;
9324 	} else {
9325 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9326 	}
9327 
9328 	SOCK_CONNID_INIT(tcp->tcp_connid);
9329 	err = tcp_init(tcp, q);
9330 	if (err != 0) {
9331 		CONN_DEC_REF(connp);
9332 		*errorp = err;
9333 		return (NULL);
9334 	}
9335 
9336 	return (connp);
9337 }
9338 
9339 static int
9340 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9341     boolean_t isv6)
9342 {
9343 	tcp_t		*tcp = NULL;
9344 	conn_t		*connp = NULL;
9345 	int		err;
9346 	vmem_t		*minor_arena = NULL;
9347 	dev_t		conn_dev;
9348 	boolean_t	issocket;
9349 
9350 	if (q->q_ptr != NULL)
9351 		return (0);
9352 
9353 	if (sflag == MODOPEN)
9354 		return (EINVAL);
9355 
9356 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9357 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9358 		minor_arena = ip_minor_arena_la;
9359 	} else {
9360 		/*
9361 		 * Either minor numbers in the large arena were exhausted
9362 		 * or a non socket application is doing the open.
9363 		 * Try to allocate from the small arena.
9364 		 */
9365 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9366 			return (EBUSY);
9367 		}
9368 		minor_arena = ip_minor_arena_sa;
9369 	}
9370 
9371 	ASSERT(minor_arena != NULL);
9372 
9373 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9374 
9375 	if (flag & SO_FALLBACK) {
9376 		/*
9377 		 * Non streams socket needs a stream to fallback to
9378 		 */
9379 		RD(q)->q_ptr = (void *)conn_dev;
9380 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9381 		WR(q)->q_ptr = (void *)minor_arena;
9382 		qprocson(q);
9383 		return (0);
9384 	} else if (flag & SO_ACCEPTOR) {
9385 		q->q_qinfo = &tcp_acceptor_rinit;
9386 		/*
9387 		 * the conn_dev and minor_arena will be subsequently used by
9388 		 * tcp_wput_accept() and tcp_tpi_close_accept() to figure out
9389 		 * the minor device number for this connection from the q_ptr.
9390 		 */
9391 		RD(q)->q_ptr = (void *)conn_dev;
9392 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9393 		WR(q)->q_ptr = (void *)minor_arena;
9394 		qprocson(q);
9395 		return (0);
9396 	}
9397 
9398 	issocket = flag & SO_SOCKSTR;
9399 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9400 
9401 	if (connp == NULL) {
9402 		inet_minor_free(minor_arena, conn_dev);
9403 		q->q_ptr = WR(q)->q_ptr = NULL;
9404 		return (err);
9405 	}
9406 
9407 	q->q_ptr = WR(q)->q_ptr = connp;
9408 
9409 	connp->conn_dev = conn_dev;
9410 	connp->conn_minor_arena = minor_arena;
9411 
9412 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9413 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9414 
9415 	tcp = connp->conn_tcp;
9416 
9417 	if (issocket) {
9418 		WR(q)->q_qinfo = &tcp_sock_winit;
9419 	} else {
9420 #ifdef  _ILP32
9421 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9422 #else
9423 		tcp->tcp_acceptor_id = conn_dev;
9424 #endif  /* _ILP32 */
9425 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9426 	}
9427 
9428 	/*
9429 	 * Put the ref for TCP. Ref for IP was already put
9430 	 * by ipcl_conn_create. Also Make the conn_t globally
9431 	 * visible to walkers
9432 	 */
9433 	mutex_enter(&connp->conn_lock);
9434 	CONN_INC_REF_LOCKED(connp);
9435 	ASSERT(connp->conn_ref == 2);
9436 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9437 	mutex_exit(&connp->conn_lock);
9438 
9439 	qprocson(q);
9440 	return (0);
9441 }
9442 
9443 /*
9444  * Some TCP options can be "set" by requesting them in the option
9445  * buffer. This is needed for XTI feature test though we do not
9446  * allow it in general. We interpret that this mechanism is more
9447  * applicable to OSI protocols and need not be allowed in general.
9448  * This routine filters out options for which it is not allowed (most)
9449  * and lets through those (few) for which it is. [ The XTI interface
9450  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9451  * ever implemented will have to be allowed here ].
9452  */
9453 static boolean_t
9454 tcp_allow_connopt_set(int level, int name)
9455 {
9456 
9457 	switch (level) {
9458 	case IPPROTO_TCP:
9459 		switch (name) {
9460 		case TCP_NODELAY:
9461 			return (B_TRUE);
9462 		default:
9463 			return (B_FALSE);
9464 		}
9465 		/*NOTREACHED*/
9466 	default:
9467 		return (B_FALSE);
9468 	}
9469 	/*NOTREACHED*/
9470 }
9471 
9472 /*
9473  * this routine gets default values of certain options whose default
9474  * values are maintained by protocol specific code
9475  */
9476 /* ARGSUSED */
9477 int
9478 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9479 {
9480 	int32_t	*i1 = (int32_t *)ptr;
9481 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9482 
9483 	switch (level) {
9484 	case IPPROTO_TCP:
9485 		switch (name) {
9486 		case TCP_NOTIFY_THRESHOLD:
9487 			*i1 = tcps->tcps_ip_notify_interval;
9488 			break;
9489 		case TCP_ABORT_THRESHOLD:
9490 			*i1 = tcps->tcps_ip_abort_interval;
9491 			break;
9492 		case TCP_CONN_NOTIFY_THRESHOLD:
9493 			*i1 = tcps->tcps_ip_notify_cinterval;
9494 			break;
9495 		case TCP_CONN_ABORT_THRESHOLD:
9496 			*i1 = tcps->tcps_ip_abort_cinterval;
9497 			break;
9498 		default:
9499 			return (-1);
9500 		}
9501 		break;
9502 	case IPPROTO_IP:
9503 		switch (name) {
9504 		case IP_TTL:
9505 			*i1 = tcps->tcps_ipv4_ttl;
9506 			break;
9507 		default:
9508 			return (-1);
9509 		}
9510 		break;
9511 	case IPPROTO_IPV6:
9512 		switch (name) {
9513 		case IPV6_UNICAST_HOPS:
9514 			*i1 = tcps->tcps_ipv6_hoplimit;
9515 			break;
9516 		default:
9517 			return (-1);
9518 		}
9519 		break;
9520 	default:
9521 		return (-1);
9522 	}
9523 	return (sizeof (int));
9524 }
9525 
9526 static int
9527 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9528 {
9529 	int		*i1 = (int *)ptr;
9530 	tcp_t		*tcp = connp->conn_tcp;
9531 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9532 
9533 	switch (level) {
9534 	case SOL_SOCKET:
9535 		switch (name) {
9536 		case SO_LINGER:	{
9537 			struct linger *lgr = (struct linger *)ptr;
9538 
9539 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9540 			lgr->l_linger = tcp->tcp_lingertime;
9541 			}
9542 			return (sizeof (struct linger));
9543 		case SO_DEBUG:
9544 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9545 			break;
9546 		case SO_KEEPALIVE:
9547 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9548 			break;
9549 		case SO_DONTROUTE:
9550 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9551 			break;
9552 		case SO_USELOOPBACK:
9553 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9554 			break;
9555 		case SO_BROADCAST:
9556 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9557 			break;
9558 		case SO_REUSEADDR:
9559 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9560 			break;
9561 		case SO_OOBINLINE:
9562 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9563 			break;
9564 		case SO_DGRAM_ERRIND:
9565 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9566 			break;
9567 		case SO_TYPE:
9568 			*i1 = SOCK_STREAM;
9569 			break;
9570 		case SO_SNDBUF:
9571 			*i1 = tcp->tcp_xmit_hiwater;
9572 			break;
9573 		case SO_RCVBUF:
9574 			*i1 = tcp->tcp_recv_hiwater;
9575 			break;
9576 		case SO_SND_COPYAVOID:
9577 			*i1 = tcp->tcp_snd_zcopy_on ?
9578 			    SO_SND_COPYAVOID : 0;
9579 			break;
9580 		case SO_ALLZONES:
9581 			*i1 = connp->conn_allzones ? 1 : 0;
9582 			break;
9583 		case SO_ANON_MLP:
9584 			*i1 = connp->conn_anon_mlp;
9585 			break;
9586 		case SO_MAC_EXEMPT:
9587 			*i1 = connp->conn_mac_exempt;
9588 			break;
9589 		case SO_EXCLBIND:
9590 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9591 			break;
9592 		case SO_PROTOTYPE:
9593 			*i1 = IPPROTO_TCP;
9594 			break;
9595 		case SO_DOMAIN:
9596 			*i1 = tcp->tcp_family;
9597 			break;
9598 		case SO_ACCEPTCONN:
9599 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9600 		default:
9601 			return (-1);
9602 		}
9603 		break;
9604 	case IPPROTO_TCP:
9605 		switch (name) {
9606 		case TCP_NODELAY:
9607 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9608 			break;
9609 		case TCP_MAXSEG:
9610 			*i1 = tcp->tcp_mss;
9611 			break;
9612 		case TCP_NOTIFY_THRESHOLD:
9613 			*i1 = (int)tcp->tcp_first_timer_threshold;
9614 			break;
9615 		case TCP_ABORT_THRESHOLD:
9616 			*i1 = tcp->tcp_second_timer_threshold;
9617 			break;
9618 		case TCP_CONN_NOTIFY_THRESHOLD:
9619 			*i1 = tcp->tcp_first_ctimer_threshold;
9620 			break;
9621 		case TCP_CONN_ABORT_THRESHOLD:
9622 			*i1 = tcp->tcp_second_ctimer_threshold;
9623 			break;
9624 		case TCP_RECVDSTADDR:
9625 			*i1 = tcp->tcp_recvdstaddr;
9626 			break;
9627 		case TCP_ANONPRIVBIND:
9628 			*i1 = tcp->tcp_anon_priv_bind;
9629 			break;
9630 		case TCP_EXCLBIND:
9631 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9632 			break;
9633 		case TCP_INIT_CWND:
9634 			*i1 = tcp->tcp_init_cwnd;
9635 			break;
9636 		case TCP_KEEPALIVE_THRESHOLD:
9637 			*i1 = tcp->tcp_ka_interval;
9638 			break;
9639 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9640 			*i1 = tcp->tcp_ka_abort_thres;
9641 			break;
9642 		case TCP_CORK:
9643 			*i1 = tcp->tcp_cork;
9644 			break;
9645 		default:
9646 			return (-1);
9647 		}
9648 		break;
9649 	case IPPROTO_IP:
9650 		if (tcp->tcp_family != AF_INET)
9651 			return (-1);
9652 		switch (name) {
9653 		case IP_OPTIONS:
9654 		case T_IP_OPTIONS: {
9655 			/*
9656 			 * This is compatible with BSD in that in only return
9657 			 * the reverse source route with the final destination
9658 			 * as the last entry. The first 4 bytes of the option
9659 			 * will contain the final destination.
9660 			 */
9661 			int	opt_len;
9662 
9663 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9664 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9665 			ASSERT(opt_len >= 0);
9666 			/* Caller ensures enough space */
9667 			if (opt_len > 0) {
9668 				/*
9669 				 * TODO: Do we have to handle getsockopt on an
9670 				 * initiator as well?
9671 				 */
9672 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9673 			}
9674 			return (0);
9675 			}
9676 		case IP_TOS:
9677 		case T_IP_TOS:
9678 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9679 			break;
9680 		case IP_TTL:
9681 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9682 			break;
9683 		case IP_NEXTHOP:
9684 			/* Handled at IP level */
9685 			return (-EINVAL);
9686 		default:
9687 			return (-1);
9688 		}
9689 		break;
9690 	case IPPROTO_IPV6:
9691 		/*
9692 		 * IPPROTO_IPV6 options are only supported for sockets
9693 		 * that are using IPv6 on the wire.
9694 		 */
9695 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9696 			return (-1);
9697 		}
9698 		switch (name) {
9699 		case IPV6_UNICAST_HOPS:
9700 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9701 			break;	/* goto sizeof (int) option return */
9702 		case IPV6_BOUND_IF:
9703 			/* Zero if not set */
9704 			*i1 = tcp->tcp_bound_if;
9705 			break;	/* goto sizeof (int) option return */
9706 		case IPV6_RECVPKTINFO:
9707 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9708 				*i1 = 1;
9709 			else
9710 				*i1 = 0;
9711 			break;	/* goto sizeof (int) option return */
9712 		case IPV6_RECVTCLASS:
9713 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9714 				*i1 = 1;
9715 			else
9716 				*i1 = 0;
9717 			break;	/* goto sizeof (int) option return */
9718 		case IPV6_RECVHOPLIMIT:
9719 			if (tcp->tcp_ipv6_recvancillary &
9720 			    TCP_IPV6_RECVHOPLIMIT)
9721 				*i1 = 1;
9722 			else
9723 				*i1 = 0;
9724 			break;	/* goto sizeof (int) option return */
9725 		case IPV6_RECVHOPOPTS:
9726 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9727 				*i1 = 1;
9728 			else
9729 				*i1 = 0;
9730 			break;	/* goto sizeof (int) option return */
9731 		case IPV6_RECVDSTOPTS:
9732 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9733 				*i1 = 1;
9734 			else
9735 				*i1 = 0;
9736 			break;	/* goto sizeof (int) option return */
9737 		case _OLD_IPV6_RECVDSTOPTS:
9738 			if (tcp->tcp_ipv6_recvancillary &
9739 			    TCP_OLD_IPV6_RECVDSTOPTS)
9740 				*i1 = 1;
9741 			else
9742 				*i1 = 0;
9743 			break;	/* goto sizeof (int) option return */
9744 		case IPV6_RECVRTHDR:
9745 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9746 				*i1 = 1;
9747 			else
9748 				*i1 = 0;
9749 			break;	/* goto sizeof (int) option return */
9750 		case IPV6_RECVRTHDRDSTOPTS:
9751 			if (tcp->tcp_ipv6_recvancillary &
9752 			    TCP_IPV6_RECVRTDSTOPTS)
9753 				*i1 = 1;
9754 			else
9755 				*i1 = 0;
9756 			break;	/* goto sizeof (int) option return */
9757 		case IPV6_PKTINFO: {
9758 			/* XXX assumes that caller has room for max size! */
9759 			struct in6_pktinfo *pkti;
9760 
9761 			pkti = (struct in6_pktinfo *)ptr;
9762 			if (ipp->ipp_fields & IPPF_IFINDEX)
9763 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9764 			else
9765 				pkti->ipi6_ifindex = 0;
9766 			if (ipp->ipp_fields & IPPF_ADDR)
9767 				pkti->ipi6_addr = ipp->ipp_addr;
9768 			else
9769 				pkti->ipi6_addr = ipv6_all_zeros;
9770 			return (sizeof (struct in6_pktinfo));
9771 		}
9772 		case IPV6_TCLASS:
9773 			if (ipp->ipp_fields & IPPF_TCLASS)
9774 				*i1 = ipp->ipp_tclass;
9775 			else
9776 				*i1 = IPV6_FLOW_TCLASS(
9777 				    IPV6_DEFAULT_VERS_AND_FLOW);
9778 			break;	/* goto sizeof (int) option return */
9779 		case IPV6_NEXTHOP: {
9780 			sin6_t *sin6 = (sin6_t *)ptr;
9781 
9782 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9783 				return (0);
9784 			*sin6 = sin6_null;
9785 			sin6->sin6_family = AF_INET6;
9786 			sin6->sin6_addr = ipp->ipp_nexthop;
9787 			return (sizeof (sin6_t));
9788 		}
9789 		case IPV6_HOPOPTS:
9790 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9791 				return (0);
9792 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9793 				return (0);
9794 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9795 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9796 			if (tcp->tcp_label_len > 0) {
9797 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9798 				ptr[1] = (ipp->ipp_hopoptslen -
9799 				    tcp->tcp_label_len + 7) / 8 - 1;
9800 			}
9801 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9802 		case IPV6_RTHDRDSTOPTS:
9803 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9804 				return (0);
9805 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9806 			return (ipp->ipp_rtdstoptslen);
9807 		case IPV6_RTHDR:
9808 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9809 				return (0);
9810 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9811 			return (ipp->ipp_rthdrlen);
9812 		case IPV6_DSTOPTS:
9813 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9814 				return (0);
9815 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9816 			return (ipp->ipp_dstoptslen);
9817 		case IPV6_SRC_PREFERENCES:
9818 			return (ip6_get_src_preferences(connp,
9819 			    (uint32_t *)ptr));
9820 		case IPV6_PATHMTU: {
9821 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9822 
9823 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9824 				return (-1);
9825 
9826 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9827 			    connp->conn_fport, mtuinfo,
9828 			    connp->conn_netstack));
9829 		}
9830 		default:
9831 			return (-1);
9832 		}
9833 		break;
9834 	default:
9835 		return (-1);
9836 	}
9837 	return (sizeof (int));
9838 }
9839 
9840 /*
9841  * TCP routine to get the values of options.
9842  */
9843 int
9844 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9845 {
9846 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9847 }
9848 
9849 /* returns UNIX error, the optlen is a value-result arg */
9850 int
9851 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9852     void *optvalp, socklen_t *optlen, cred_t *cr)
9853 {
9854 	conn_t		*connp = (conn_t *)proto_handle;
9855 	squeue_t	*sqp = connp->conn_sqp;
9856 	int		error;
9857 	t_uscalar_t	max_optbuf_len;
9858 	void		*optvalp_buf;
9859 	int		len;
9860 
9861 	ASSERT(connp->conn_upper_handle != NULL);
9862 
9863 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9864 	    tcp_opt_obj.odb_opt_des_arr,
9865 	    tcp_opt_obj.odb_opt_arr_cnt,
9866 	    tcp_opt_obj.odb_topmost_tpiprovider,
9867 	    B_FALSE, B_TRUE, cr);
9868 	if (error != 0) {
9869 		if (error < 0) {
9870 			error = proto_tlitosyserr(-error);
9871 		}
9872 		return (error);
9873 	}
9874 
9875 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9876 
9877 	error = squeue_synch_enter(sqp, connp, NULL);
9878 	if (error == ENOMEM) {
9879 		return (ENOMEM);
9880 	}
9881 
9882 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9883 	squeue_synch_exit(sqp, connp);
9884 
9885 	if (len < 0) {
9886 		/*
9887 		 * Pass on to IP
9888 		 */
9889 		kmem_free(optvalp_buf, max_optbuf_len);
9890 		return (ip_get_options(connp, level, option_name,
9891 		    optvalp, optlen, cr));
9892 	} else {
9893 		/*
9894 		 * update optlen and copy option value
9895 		 */
9896 		t_uscalar_t size = MIN(len, *optlen);
9897 		bcopy(optvalp_buf, optvalp, size);
9898 		bcopy(&size, optlen, sizeof (size));
9899 
9900 		kmem_free(optvalp_buf, max_optbuf_len);
9901 		return (0);
9902 	}
9903 }
9904 
9905 /*
9906  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9907  * Parameters are assumed to be verified by the caller.
9908  */
9909 /* ARGSUSED */
9910 int
9911 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9912     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9913     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9914 {
9915 	tcp_t	*tcp = connp->conn_tcp;
9916 	int	*i1 = (int *)invalp;
9917 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9918 	boolean_t checkonly;
9919 	int	reterr;
9920 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9921 
9922 	switch (optset_context) {
9923 	case SETFN_OPTCOM_CHECKONLY:
9924 		checkonly = B_TRUE;
9925 		/*
9926 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9927 		 * inlen != 0 implies value supplied and
9928 		 * 	we have to "pretend" to set it.
9929 		 * inlen == 0 implies that there is no
9930 		 * 	value part in T_CHECK request and just validation
9931 		 * done elsewhere should be enough, we just return here.
9932 		 */
9933 		if (inlen == 0) {
9934 			*outlenp = 0;
9935 			return (0);
9936 		}
9937 		break;
9938 	case SETFN_OPTCOM_NEGOTIATE:
9939 		checkonly = B_FALSE;
9940 		break;
9941 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9942 	case SETFN_CONN_NEGOTIATE:
9943 		checkonly = B_FALSE;
9944 		/*
9945 		 * Negotiating local and "association-related" options
9946 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9947 		 * primitives is allowed by XTI, but we choose
9948 		 * to not implement this style negotiation for Internet
9949 		 * protocols (We interpret it is a must for OSI world but
9950 		 * optional for Internet protocols) for all options.
9951 		 * [ Will do only for the few options that enable test
9952 		 * suites that our XTI implementation of this feature
9953 		 * works for transports that do allow it ]
9954 		 */
9955 		if (!tcp_allow_connopt_set(level, name)) {
9956 			*outlenp = 0;
9957 			return (EINVAL);
9958 		}
9959 		break;
9960 	default:
9961 		/*
9962 		 * We should never get here
9963 		 */
9964 		*outlenp = 0;
9965 		return (EINVAL);
9966 	}
9967 
9968 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9969 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9970 
9971 	/*
9972 	 * For TCP, we should have no ancillary data sent down
9973 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9974 	 * has to be zero.
9975 	 */
9976 	ASSERT(thisdg_attrs == NULL);
9977 
9978 	/*
9979 	 * For fixed length options, no sanity check
9980 	 * of passed in length is done. It is assumed *_optcom_req()
9981 	 * routines do the right thing.
9982 	 */
9983 	switch (level) {
9984 	case SOL_SOCKET:
9985 		switch (name) {
9986 		case SO_LINGER: {
9987 			struct linger *lgr = (struct linger *)invalp;
9988 
9989 			if (!checkonly) {
9990 				if (lgr->l_onoff) {
9991 					tcp->tcp_linger = 1;
9992 					tcp->tcp_lingertime = lgr->l_linger;
9993 				} else {
9994 					tcp->tcp_linger = 0;
9995 					tcp->tcp_lingertime = 0;
9996 				}
9997 				/* struct copy */
9998 				*(struct linger *)outvalp = *lgr;
9999 			} else {
10000 				if (!lgr->l_onoff) {
10001 					((struct linger *)
10002 					    outvalp)->l_onoff = 0;
10003 					((struct linger *)
10004 					    outvalp)->l_linger = 0;
10005 				} else {
10006 					/* struct copy */
10007 					*(struct linger *)outvalp = *lgr;
10008 				}
10009 			}
10010 			*outlenp = sizeof (struct linger);
10011 			return (0);
10012 		}
10013 		case SO_DEBUG:
10014 			if (!checkonly)
10015 				tcp->tcp_debug = onoff;
10016 			break;
10017 		case SO_KEEPALIVE:
10018 			if (checkonly) {
10019 				/* check only case */
10020 				break;
10021 			}
10022 
10023 			if (!onoff) {
10024 				if (tcp->tcp_ka_enabled) {
10025 					if (tcp->tcp_ka_tid != 0) {
10026 						(void) TCP_TIMER_CANCEL(tcp,
10027 						    tcp->tcp_ka_tid);
10028 						tcp->tcp_ka_tid = 0;
10029 					}
10030 					tcp->tcp_ka_enabled = 0;
10031 				}
10032 				break;
10033 			}
10034 			if (!tcp->tcp_ka_enabled) {
10035 				/* Crank up the keepalive timer */
10036 				tcp->tcp_ka_last_intrvl = 0;
10037 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10038 				    tcp_keepalive_killer,
10039 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10040 				tcp->tcp_ka_enabled = 1;
10041 			}
10042 			break;
10043 		case SO_DONTROUTE:
10044 			/*
10045 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10046 			 * only of interest to IP.  We track them here only so
10047 			 * that we can report their current value.
10048 			 */
10049 			if (!checkonly) {
10050 				tcp->tcp_dontroute = onoff;
10051 				tcp->tcp_connp->conn_dontroute = onoff;
10052 			}
10053 			break;
10054 		case SO_USELOOPBACK:
10055 			if (!checkonly) {
10056 				tcp->tcp_useloopback = onoff;
10057 				tcp->tcp_connp->conn_loopback = onoff;
10058 			}
10059 			break;
10060 		case SO_BROADCAST:
10061 			if (!checkonly) {
10062 				tcp->tcp_broadcast = onoff;
10063 				tcp->tcp_connp->conn_broadcast = onoff;
10064 			}
10065 			break;
10066 		case SO_REUSEADDR:
10067 			if (!checkonly) {
10068 				tcp->tcp_reuseaddr = onoff;
10069 				tcp->tcp_connp->conn_reuseaddr = onoff;
10070 			}
10071 			break;
10072 		case SO_OOBINLINE:
10073 			if (!checkonly) {
10074 				tcp->tcp_oobinline = onoff;
10075 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10076 					proto_set_rx_oob_opt(connp, onoff);
10077 			}
10078 			break;
10079 		case SO_DGRAM_ERRIND:
10080 			if (!checkonly)
10081 				tcp->tcp_dgram_errind = onoff;
10082 			break;
10083 		case SO_SNDBUF: {
10084 			if (*i1 > tcps->tcps_max_buf) {
10085 				*outlenp = 0;
10086 				return (ENOBUFS);
10087 			}
10088 			if (checkonly)
10089 				break;
10090 
10091 			tcp->tcp_xmit_hiwater = *i1;
10092 			if (tcps->tcps_snd_lowat_fraction != 0)
10093 				tcp->tcp_xmit_lowater =
10094 				    tcp->tcp_xmit_hiwater /
10095 				    tcps->tcps_snd_lowat_fraction;
10096 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10097 			/*
10098 			 * If we are flow-controlled, recheck the condition.
10099 			 * There are apps that increase SO_SNDBUF size when
10100 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10101 			 * control condition to be lifted right away.
10102 			 */
10103 			mutex_enter(&tcp->tcp_non_sq_lock);
10104 			if (tcp->tcp_flow_stopped &&
10105 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10106 				tcp_clrqfull(tcp);
10107 			}
10108 			mutex_exit(&tcp->tcp_non_sq_lock);
10109 			break;
10110 		}
10111 		case SO_RCVBUF:
10112 			if (*i1 > tcps->tcps_max_buf) {
10113 				*outlenp = 0;
10114 				return (ENOBUFS);
10115 			}
10116 			/* Silently ignore zero */
10117 			if (!checkonly && *i1 != 0) {
10118 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10119 				(void) tcp_rwnd_set(tcp, *i1);
10120 			}
10121 			/*
10122 			 * XXX should we return the rwnd here
10123 			 * and tcp_opt_get ?
10124 			 */
10125 			break;
10126 		case SO_SND_COPYAVOID:
10127 			if (!checkonly) {
10128 				/* we only allow enable at most once for now */
10129 				if (tcp->tcp_loopback ||
10130 				    (tcp->tcp_kssl_ctx != NULL) ||
10131 				    (!tcp->tcp_snd_zcopy_aware &&
10132 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10133 					*outlenp = 0;
10134 					return (EOPNOTSUPP);
10135 				}
10136 				tcp->tcp_snd_zcopy_aware = 1;
10137 			}
10138 			break;
10139 		case SO_RCVTIMEO:
10140 		case SO_SNDTIMEO:
10141 			/*
10142 			 * Pass these two options in order for third part
10143 			 * protocol usage. Here just return directly.
10144 			 */
10145 			return (0);
10146 		case SO_ALLZONES:
10147 			/* Pass option along to IP level for handling */
10148 			return (-EINVAL);
10149 		case SO_ANON_MLP:
10150 			/* Pass option along to IP level for handling */
10151 			return (-EINVAL);
10152 		case SO_MAC_EXEMPT:
10153 			/* Pass option along to IP level for handling */
10154 			return (-EINVAL);
10155 		case SO_EXCLBIND:
10156 			if (!checkonly)
10157 				tcp->tcp_exclbind = onoff;
10158 			break;
10159 		default:
10160 			*outlenp = 0;
10161 			return (EINVAL);
10162 		}
10163 		break;
10164 	case IPPROTO_TCP:
10165 		switch (name) {
10166 		case TCP_NODELAY:
10167 			if (!checkonly)
10168 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10169 			break;
10170 		case TCP_NOTIFY_THRESHOLD:
10171 			if (!checkonly)
10172 				tcp->tcp_first_timer_threshold = *i1;
10173 			break;
10174 		case TCP_ABORT_THRESHOLD:
10175 			if (!checkonly)
10176 				tcp->tcp_second_timer_threshold = *i1;
10177 			break;
10178 		case TCP_CONN_NOTIFY_THRESHOLD:
10179 			if (!checkonly)
10180 				tcp->tcp_first_ctimer_threshold = *i1;
10181 			break;
10182 		case TCP_CONN_ABORT_THRESHOLD:
10183 			if (!checkonly)
10184 				tcp->tcp_second_ctimer_threshold = *i1;
10185 			break;
10186 		case TCP_RECVDSTADDR:
10187 			if (tcp->tcp_state > TCPS_LISTEN)
10188 				return (EOPNOTSUPP);
10189 			if (!checkonly)
10190 				tcp->tcp_recvdstaddr = onoff;
10191 			break;
10192 		case TCP_ANONPRIVBIND:
10193 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10194 			    IPPROTO_TCP)) != 0) {
10195 				*outlenp = 0;
10196 				return (reterr);
10197 			}
10198 			if (!checkonly) {
10199 				tcp->tcp_anon_priv_bind = onoff;
10200 			}
10201 			break;
10202 		case TCP_EXCLBIND:
10203 			if (!checkonly)
10204 				tcp->tcp_exclbind = onoff;
10205 			break;	/* goto sizeof (int) option return */
10206 		case TCP_INIT_CWND: {
10207 			uint32_t init_cwnd = *((uint32_t *)invalp);
10208 
10209 			if (checkonly)
10210 				break;
10211 
10212 			/*
10213 			 * Only allow socket with network configuration
10214 			 * privilege to set the initial cwnd to be larger
10215 			 * than allowed by RFC 3390.
10216 			 */
10217 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10218 				tcp->tcp_init_cwnd = init_cwnd;
10219 				break;
10220 			}
10221 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10222 				*outlenp = 0;
10223 				return (reterr);
10224 			}
10225 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10226 				*outlenp = 0;
10227 				return (EINVAL);
10228 			}
10229 			tcp->tcp_init_cwnd = init_cwnd;
10230 			break;
10231 		}
10232 		case TCP_KEEPALIVE_THRESHOLD:
10233 			if (checkonly)
10234 				break;
10235 
10236 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10237 			    *i1 > tcps->tcps_keepalive_interval_high) {
10238 				*outlenp = 0;
10239 				return (EINVAL);
10240 			}
10241 			if (*i1 != tcp->tcp_ka_interval) {
10242 				tcp->tcp_ka_interval = *i1;
10243 				/*
10244 				 * Check if we need to restart the
10245 				 * keepalive timer.
10246 				 */
10247 				if (tcp->tcp_ka_tid != 0) {
10248 					ASSERT(tcp->tcp_ka_enabled);
10249 					(void) TCP_TIMER_CANCEL(tcp,
10250 					    tcp->tcp_ka_tid);
10251 					tcp->tcp_ka_last_intrvl = 0;
10252 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10253 					    tcp_keepalive_killer,
10254 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10255 				}
10256 			}
10257 			break;
10258 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10259 			if (!checkonly) {
10260 				if (*i1 <
10261 				    tcps->tcps_keepalive_abort_interval_low ||
10262 				    *i1 >
10263 				    tcps->tcps_keepalive_abort_interval_high) {
10264 					*outlenp = 0;
10265 					return (EINVAL);
10266 				}
10267 				tcp->tcp_ka_abort_thres = *i1;
10268 			}
10269 			break;
10270 		case TCP_CORK:
10271 			if (!checkonly) {
10272 				/*
10273 				 * if tcp->tcp_cork was set and is now
10274 				 * being unset, we have to make sure that
10275 				 * the remaining data gets sent out. Also
10276 				 * unset tcp->tcp_cork so that tcp_wput_data()
10277 				 * can send data even if it is less than mss
10278 				 */
10279 				if (tcp->tcp_cork && onoff == 0 &&
10280 				    tcp->tcp_unsent > 0) {
10281 					tcp->tcp_cork = B_FALSE;
10282 					tcp_wput_data(tcp, NULL, B_FALSE);
10283 				}
10284 				tcp->tcp_cork = onoff;
10285 			}
10286 			break;
10287 		default:
10288 			*outlenp = 0;
10289 			return (EINVAL);
10290 		}
10291 		break;
10292 	case IPPROTO_IP:
10293 		if (tcp->tcp_family != AF_INET) {
10294 			*outlenp = 0;
10295 			return (ENOPROTOOPT);
10296 		}
10297 		switch (name) {
10298 		case IP_OPTIONS:
10299 		case T_IP_OPTIONS:
10300 			reterr = tcp_opt_set_header(tcp, checkonly,
10301 			    invalp, inlen);
10302 			if (reterr) {
10303 				*outlenp = 0;
10304 				return (reterr);
10305 			}
10306 			/* OK return - copy input buffer into output buffer */
10307 			if (invalp != outvalp) {
10308 				/* don't trust bcopy for identical src/dst */
10309 				bcopy(invalp, outvalp, inlen);
10310 			}
10311 			*outlenp = inlen;
10312 			return (0);
10313 		case IP_TOS:
10314 		case T_IP_TOS:
10315 			if (!checkonly) {
10316 				tcp->tcp_ipha->ipha_type_of_service =
10317 				    (uchar_t)*i1;
10318 				tcp->tcp_tos = (uchar_t)*i1;
10319 			}
10320 			break;
10321 		case IP_TTL:
10322 			if (!checkonly) {
10323 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10324 				tcp->tcp_ttl = (uchar_t)*i1;
10325 			}
10326 			break;
10327 		case IP_BOUND_IF:
10328 		case IP_NEXTHOP:
10329 			/* Handled at the IP level */
10330 			return (-EINVAL);
10331 		case IP_SEC_OPT:
10332 			/*
10333 			 * We should not allow policy setting after
10334 			 * we start listening for connections.
10335 			 */
10336 			if (tcp->tcp_state == TCPS_LISTEN) {
10337 				return (EINVAL);
10338 			} else {
10339 				/* Handled at the IP level */
10340 				return (-EINVAL);
10341 			}
10342 		default:
10343 			*outlenp = 0;
10344 			return (EINVAL);
10345 		}
10346 		break;
10347 	case IPPROTO_IPV6: {
10348 		ip6_pkt_t		*ipp;
10349 
10350 		/*
10351 		 * IPPROTO_IPV6 options are only supported for sockets
10352 		 * that are using IPv6 on the wire.
10353 		 */
10354 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10355 			*outlenp = 0;
10356 			return (ENOPROTOOPT);
10357 		}
10358 		/*
10359 		 * Only sticky options; no ancillary data
10360 		 */
10361 		ipp = &tcp->tcp_sticky_ipp;
10362 
10363 		switch (name) {
10364 		case IPV6_UNICAST_HOPS:
10365 			/* -1 means use default */
10366 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10367 				*outlenp = 0;
10368 				return (EINVAL);
10369 			}
10370 			if (!checkonly) {
10371 				if (*i1 == -1) {
10372 					tcp->tcp_ip6h->ip6_hops =
10373 					    ipp->ipp_unicast_hops =
10374 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10375 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10376 					/* Pass modified value to IP. */
10377 					*i1 = tcp->tcp_ip6h->ip6_hops;
10378 				} else {
10379 					tcp->tcp_ip6h->ip6_hops =
10380 					    ipp->ipp_unicast_hops =
10381 					    (uint8_t)*i1;
10382 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10383 				}
10384 				reterr = tcp_build_hdrs(tcp);
10385 				if (reterr != 0)
10386 					return (reterr);
10387 			}
10388 			break;
10389 		case IPV6_BOUND_IF:
10390 			if (!checkonly) {
10391 				tcp->tcp_bound_if = *i1;
10392 				PASS_OPT_TO_IP(connp);
10393 			}
10394 			break;
10395 		/*
10396 		 * Set boolean switches for ancillary data delivery
10397 		 */
10398 		case IPV6_RECVPKTINFO:
10399 			if (!checkonly) {
10400 				if (onoff)
10401 					tcp->tcp_ipv6_recvancillary |=
10402 					    TCP_IPV6_RECVPKTINFO;
10403 				else
10404 					tcp->tcp_ipv6_recvancillary &=
10405 					    ~TCP_IPV6_RECVPKTINFO;
10406 				/* Force it to be sent up with the next msg */
10407 				tcp->tcp_recvifindex = 0;
10408 				PASS_OPT_TO_IP(connp);
10409 			}
10410 			break;
10411 		case IPV6_RECVTCLASS:
10412 			if (!checkonly) {
10413 				if (onoff)
10414 					tcp->tcp_ipv6_recvancillary |=
10415 					    TCP_IPV6_RECVTCLASS;
10416 				else
10417 					tcp->tcp_ipv6_recvancillary &=
10418 					    ~TCP_IPV6_RECVTCLASS;
10419 				PASS_OPT_TO_IP(connp);
10420 			}
10421 			break;
10422 		case IPV6_RECVHOPLIMIT:
10423 			if (!checkonly) {
10424 				if (onoff)
10425 					tcp->tcp_ipv6_recvancillary |=
10426 					    TCP_IPV6_RECVHOPLIMIT;
10427 				else
10428 					tcp->tcp_ipv6_recvancillary &=
10429 					    ~TCP_IPV6_RECVHOPLIMIT;
10430 				/* Force it to be sent up with the next msg */
10431 				tcp->tcp_recvhops = 0xffffffffU;
10432 				PASS_OPT_TO_IP(connp);
10433 			}
10434 			break;
10435 		case IPV6_RECVHOPOPTS:
10436 			if (!checkonly) {
10437 				if (onoff)
10438 					tcp->tcp_ipv6_recvancillary |=
10439 					    TCP_IPV6_RECVHOPOPTS;
10440 				else
10441 					tcp->tcp_ipv6_recvancillary &=
10442 					    ~TCP_IPV6_RECVHOPOPTS;
10443 				PASS_OPT_TO_IP(connp);
10444 			}
10445 			break;
10446 		case IPV6_RECVDSTOPTS:
10447 			if (!checkonly) {
10448 				if (onoff)
10449 					tcp->tcp_ipv6_recvancillary |=
10450 					    TCP_IPV6_RECVDSTOPTS;
10451 				else
10452 					tcp->tcp_ipv6_recvancillary &=
10453 					    ~TCP_IPV6_RECVDSTOPTS;
10454 				PASS_OPT_TO_IP(connp);
10455 			}
10456 			break;
10457 		case _OLD_IPV6_RECVDSTOPTS:
10458 			if (!checkonly) {
10459 				if (onoff)
10460 					tcp->tcp_ipv6_recvancillary |=
10461 					    TCP_OLD_IPV6_RECVDSTOPTS;
10462 				else
10463 					tcp->tcp_ipv6_recvancillary &=
10464 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10465 			}
10466 			break;
10467 		case IPV6_RECVRTHDR:
10468 			if (!checkonly) {
10469 				if (onoff)
10470 					tcp->tcp_ipv6_recvancillary |=
10471 					    TCP_IPV6_RECVRTHDR;
10472 				else
10473 					tcp->tcp_ipv6_recvancillary &=
10474 					    ~TCP_IPV6_RECVRTHDR;
10475 				PASS_OPT_TO_IP(connp);
10476 			}
10477 			break;
10478 		case IPV6_RECVRTHDRDSTOPTS:
10479 			if (!checkonly) {
10480 				if (onoff)
10481 					tcp->tcp_ipv6_recvancillary |=
10482 					    TCP_IPV6_RECVRTDSTOPTS;
10483 				else
10484 					tcp->tcp_ipv6_recvancillary &=
10485 					    ~TCP_IPV6_RECVRTDSTOPTS;
10486 				PASS_OPT_TO_IP(connp);
10487 			}
10488 			break;
10489 		case IPV6_PKTINFO:
10490 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10491 				return (EINVAL);
10492 			if (checkonly)
10493 				break;
10494 
10495 			if (inlen == 0) {
10496 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10497 			} else {
10498 				struct in6_pktinfo *pkti;
10499 
10500 				pkti = (struct in6_pktinfo *)invalp;
10501 				/*
10502 				 * RFC 3542 states that ipi6_addr must be
10503 				 * the unspecified address when setting the
10504 				 * IPV6_PKTINFO sticky socket option on a
10505 				 * TCP socket.
10506 				 */
10507 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10508 					return (EINVAL);
10509 				/*
10510 				 * IP will validate the source address and
10511 				 * interface index.
10512 				 */
10513 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10514 					reterr = ip_set_options(tcp->tcp_connp,
10515 					    level, name, invalp, inlen, cr);
10516 				} else {
10517 					reterr = ip6_set_pktinfo(cr,
10518 					    tcp->tcp_connp, pkti);
10519 				}
10520 				if (reterr != 0)
10521 					return (reterr);
10522 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10523 				ipp->ipp_addr = pkti->ipi6_addr;
10524 				if (ipp->ipp_ifindex != 0)
10525 					ipp->ipp_fields |= IPPF_IFINDEX;
10526 				else
10527 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10528 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10529 					ipp->ipp_fields |= IPPF_ADDR;
10530 				else
10531 					ipp->ipp_fields &= ~IPPF_ADDR;
10532 			}
10533 			reterr = tcp_build_hdrs(tcp);
10534 			if (reterr != 0)
10535 				return (reterr);
10536 			break;
10537 		case IPV6_TCLASS:
10538 			if (inlen != 0 && inlen != sizeof (int))
10539 				return (EINVAL);
10540 			if (checkonly)
10541 				break;
10542 
10543 			if (inlen == 0) {
10544 				ipp->ipp_fields &= ~IPPF_TCLASS;
10545 			} else {
10546 				if (*i1 > 255 || *i1 < -1)
10547 					return (EINVAL);
10548 				if (*i1 == -1) {
10549 					ipp->ipp_tclass = 0;
10550 					*i1 = 0;
10551 				} else {
10552 					ipp->ipp_tclass = *i1;
10553 				}
10554 				ipp->ipp_fields |= IPPF_TCLASS;
10555 			}
10556 			reterr = tcp_build_hdrs(tcp);
10557 			if (reterr != 0)
10558 				return (reterr);
10559 			break;
10560 		case IPV6_NEXTHOP:
10561 			/*
10562 			 * IP will verify that the nexthop is reachable
10563 			 * and fail for sticky options.
10564 			 */
10565 			if (inlen != 0 && inlen != sizeof (sin6_t))
10566 				return (EINVAL);
10567 			if (checkonly)
10568 				break;
10569 
10570 			if (inlen == 0) {
10571 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10572 			} else {
10573 				sin6_t *sin6 = (sin6_t *)invalp;
10574 
10575 				if (sin6->sin6_family != AF_INET6)
10576 					return (EAFNOSUPPORT);
10577 				if (IN6_IS_ADDR_V4MAPPED(
10578 				    &sin6->sin6_addr))
10579 					return (EADDRNOTAVAIL);
10580 				ipp->ipp_nexthop = sin6->sin6_addr;
10581 				if (!IN6_IS_ADDR_UNSPECIFIED(
10582 				    &ipp->ipp_nexthop))
10583 					ipp->ipp_fields |= IPPF_NEXTHOP;
10584 				else
10585 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10586 			}
10587 			reterr = tcp_build_hdrs(tcp);
10588 			if (reterr != 0)
10589 				return (reterr);
10590 			PASS_OPT_TO_IP(connp);
10591 			break;
10592 		case IPV6_HOPOPTS: {
10593 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10594 
10595 			/*
10596 			 * Sanity checks - minimum size, size a multiple of
10597 			 * eight bytes, and matching size passed in.
10598 			 */
10599 			if (inlen != 0 &&
10600 			    inlen != (8 * (hopts->ip6h_len + 1)))
10601 				return (EINVAL);
10602 
10603 			if (checkonly)
10604 				break;
10605 
10606 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10607 			    (uchar_t **)&ipp->ipp_hopopts,
10608 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10609 			if (reterr != 0)
10610 				return (reterr);
10611 			if (ipp->ipp_hopoptslen == 0)
10612 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10613 			else
10614 				ipp->ipp_fields |= IPPF_HOPOPTS;
10615 			reterr = tcp_build_hdrs(tcp);
10616 			if (reterr != 0)
10617 				return (reterr);
10618 			break;
10619 		}
10620 		case IPV6_RTHDRDSTOPTS: {
10621 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10622 
10623 			/*
10624 			 * Sanity checks - minimum size, size a multiple of
10625 			 * eight bytes, and matching size passed in.
10626 			 */
10627 			if (inlen != 0 &&
10628 			    inlen != (8 * (dopts->ip6d_len + 1)))
10629 				return (EINVAL);
10630 
10631 			if (checkonly)
10632 				break;
10633 
10634 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10635 			    (uchar_t **)&ipp->ipp_rtdstopts,
10636 			    &ipp->ipp_rtdstoptslen, 0);
10637 			if (reterr != 0)
10638 				return (reterr);
10639 			if (ipp->ipp_rtdstoptslen == 0)
10640 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10641 			else
10642 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10643 			reterr = tcp_build_hdrs(tcp);
10644 			if (reterr != 0)
10645 				return (reterr);
10646 			break;
10647 		}
10648 		case IPV6_DSTOPTS: {
10649 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10650 
10651 			/*
10652 			 * Sanity checks - minimum size, size a multiple of
10653 			 * eight bytes, and matching size passed in.
10654 			 */
10655 			if (inlen != 0 &&
10656 			    inlen != (8 * (dopts->ip6d_len + 1)))
10657 				return (EINVAL);
10658 
10659 			if (checkonly)
10660 				break;
10661 
10662 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10663 			    (uchar_t **)&ipp->ipp_dstopts,
10664 			    &ipp->ipp_dstoptslen, 0);
10665 			if (reterr != 0)
10666 				return (reterr);
10667 			if (ipp->ipp_dstoptslen == 0)
10668 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10669 			else
10670 				ipp->ipp_fields |= IPPF_DSTOPTS;
10671 			reterr = tcp_build_hdrs(tcp);
10672 			if (reterr != 0)
10673 				return (reterr);
10674 			break;
10675 		}
10676 		case IPV6_RTHDR: {
10677 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10678 
10679 			/*
10680 			 * Sanity checks - minimum size, size a multiple of
10681 			 * eight bytes, and matching size passed in.
10682 			 */
10683 			if (inlen != 0 &&
10684 			    inlen != (8 * (rt->ip6r_len + 1)))
10685 				return (EINVAL);
10686 
10687 			if (checkonly)
10688 				break;
10689 
10690 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10691 			    (uchar_t **)&ipp->ipp_rthdr,
10692 			    &ipp->ipp_rthdrlen, 0);
10693 			if (reterr != 0)
10694 				return (reterr);
10695 			if (ipp->ipp_rthdrlen == 0)
10696 				ipp->ipp_fields &= ~IPPF_RTHDR;
10697 			else
10698 				ipp->ipp_fields |= IPPF_RTHDR;
10699 			reterr = tcp_build_hdrs(tcp);
10700 			if (reterr != 0)
10701 				return (reterr);
10702 			break;
10703 		}
10704 		case IPV6_V6ONLY:
10705 			if (!checkonly) {
10706 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10707 			}
10708 			break;
10709 		case IPV6_USE_MIN_MTU:
10710 			if (inlen != sizeof (int))
10711 				return (EINVAL);
10712 
10713 			if (*i1 < -1 || *i1 > 1)
10714 				return (EINVAL);
10715 
10716 			if (checkonly)
10717 				break;
10718 
10719 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10720 			ipp->ipp_use_min_mtu = *i1;
10721 			break;
10722 		case IPV6_SEC_OPT:
10723 			/*
10724 			 * We should not allow policy setting after
10725 			 * we start listening for connections.
10726 			 */
10727 			if (tcp->tcp_state == TCPS_LISTEN) {
10728 				return (EINVAL);
10729 			} else {
10730 				/* Handled at the IP level */
10731 				return (-EINVAL);
10732 			}
10733 		case IPV6_SRC_PREFERENCES:
10734 			if (inlen != sizeof (uint32_t))
10735 				return (EINVAL);
10736 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10737 			    *(uint32_t *)invalp);
10738 			if (reterr != 0) {
10739 				*outlenp = 0;
10740 				return (reterr);
10741 			}
10742 			break;
10743 		default:
10744 			*outlenp = 0;
10745 			return (EINVAL);
10746 		}
10747 		break;
10748 	}		/* end IPPROTO_IPV6 */
10749 	default:
10750 		*outlenp = 0;
10751 		return (EINVAL);
10752 	}
10753 	/*
10754 	 * Common case of OK return with outval same as inval
10755 	 */
10756 	if (invalp != outvalp) {
10757 		/* don't trust bcopy for identical src/dst */
10758 		(void) bcopy(invalp, outvalp, inlen);
10759 	}
10760 	*outlenp = inlen;
10761 	return (0);
10762 }
10763 
10764 /* ARGSUSED */
10765 int
10766 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10767     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10768     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10769 {
10770 	conn_t	*connp =  Q_TO_CONN(q);
10771 
10772 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10773 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10774 }
10775 
10776 int
10777 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10778     const void *optvalp, socklen_t optlen, cred_t *cr)
10779 {
10780 	conn_t		*connp = (conn_t *)proto_handle;
10781 	squeue_t	*sqp = connp->conn_sqp;
10782 	int		error;
10783 
10784 	ASSERT(connp->conn_upper_handle != NULL);
10785 	/*
10786 	 * Entering the squeue synchronously can result in a context switch,
10787 	 * which can cause a rather sever performance degradation. So we try to
10788 	 * handle whatever options we can without entering the squeue.
10789 	 */
10790 	if (level == IPPROTO_TCP) {
10791 		switch (option_name) {
10792 		case TCP_NODELAY:
10793 			if (optlen != sizeof (int32_t))
10794 				return (EINVAL);
10795 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10796 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10797 			    connp->conn_tcp->tcp_mss;
10798 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10799 			return (0);
10800 		default:
10801 			break;
10802 		}
10803 	}
10804 
10805 	error = squeue_synch_enter(sqp, connp, NULL);
10806 	if (error == ENOMEM) {
10807 		return (ENOMEM);
10808 	}
10809 
10810 	error = proto_opt_check(level, option_name, optlen, NULL,
10811 	    tcp_opt_obj.odb_opt_des_arr,
10812 	    tcp_opt_obj.odb_opt_arr_cnt,
10813 	    tcp_opt_obj.odb_topmost_tpiprovider,
10814 	    B_TRUE, B_FALSE, cr);
10815 
10816 	if (error != 0) {
10817 		if (error < 0) {
10818 			error = proto_tlitosyserr(-error);
10819 		}
10820 		squeue_synch_exit(sqp, connp);
10821 		return (error);
10822 	}
10823 
10824 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10825 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10826 	    NULL, cr, NULL);
10827 	squeue_synch_exit(sqp, connp);
10828 
10829 	if (error < 0) {
10830 		/*
10831 		 * Pass on to ip
10832 		 */
10833 		error = ip_set_options(connp, level, option_name, optvalp,
10834 		    optlen, cr);
10835 	}
10836 	return (error);
10837 }
10838 
10839 /*
10840  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10841  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10842  * headers, and the maximum size tcp header (to avoid reallocation
10843  * on the fly for additional tcp options).
10844  * Returns failure if can't allocate memory.
10845  */
10846 static int
10847 tcp_build_hdrs(tcp_t *tcp)
10848 {
10849 	char	*hdrs;
10850 	uint_t	hdrs_len;
10851 	ip6i_t	*ip6i;
10852 	char	buf[TCP_MAX_HDR_LENGTH];
10853 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10854 	in6_addr_t src, dst;
10855 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10856 	conn_t *connp = tcp->tcp_connp;
10857 
10858 	/*
10859 	 * save the existing tcp header and source/dest IP addresses
10860 	 */
10861 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10862 	src = tcp->tcp_ip6h->ip6_src;
10863 	dst = tcp->tcp_ip6h->ip6_dst;
10864 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10865 	ASSERT(hdrs_len != 0);
10866 	if (hdrs_len > tcp->tcp_iphc_len) {
10867 		/* Need to reallocate */
10868 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10869 		if (hdrs == NULL)
10870 			return (ENOMEM);
10871 		if (tcp->tcp_iphc != NULL) {
10872 			if (tcp->tcp_hdr_grown) {
10873 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10874 			} else {
10875 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10876 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10877 			}
10878 			tcp->tcp_iphc_len = 0;
10879 		}
10880 		ASSERT(tcp->tcp_iphc_len == 0);
10881 		tcp->tcp_iphc = hdrs;
10882 		tcp->tcp_iphc_len = hdrs_len;
10883 		tcp->tcp_hdr_grown = B_TRUE;
10884 	}
10885 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10886 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10887 
10888 	/* Set header fields not in ipp */
10889 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10890 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10891 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10892 	} else {
10893 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10894 	}
10895 	/*
10896 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10897 	 *
10898 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10899 	 */
10900 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10901 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10902 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10903 
10904 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10905 
10906 	tcp->tcp_ip6h->ip6_src = src;
10907 	tcp->tcp_ip6h->ip6_dst = dst;
10908 
10909 	/*
10910 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10911 	 * the default value for TCP.
10912 	 */
10913 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10914 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10915 
10916 	/*
10917 	 * If we're setting extension headers after a connection
10918 	 * has been established, and if we have a routing header
10919 	 * among the extension headers, call ip_massage_options_v6 to
10920 	 * manipulate the routing header/ip6_dst set the checksum
10921 	 * difference in the tcp header template.
10922 	 * (This happens in tcp_connect_ipv6 if the routing header
10923 	 * is set prior to the connect.)
10924 	 * Set the tcp_sum to zero first in case we've cleared a
10925 	 * routing header or don't have one at all.
10926 	 */
10927 	tcp->tcp_sum = 0;
10928 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10929 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10930 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10931 		    (uint8_t *)tcp->tcp_tcph);
10932 		if (rth != NULL) {
10933 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10934 			    rth, tcps->tcps_netstack);
10935 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10936 			    (tcp->tcp_sum >> 16));
10937 		}
10938 	}
10939 
10940 	/* Try to get everything in a single mblk */
10941 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10942 	    hdrs_len + tcps->tcps_wroff_xtra);
10943 	return (0);
10944 }
10945 
10946 /*
10947  * Transfer any source route option from ipha to buf/dst in reversed form.
10948  */
10949 static int
10950 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10951 {
10952 	ipoptp_t	opts;
10953 	uchar_t		*opt;
10954 	uint8_t		optval;
10955 	uint8_t		optlen;
10956 	uint32_t	len = 0;
10957 
10958 	for (optval = ipoptp_first(&opts, ipha);
10959 	    optval != IPOPT_EOL;
10960 	    optval = ipoptp_next(&opts)) {
10961 		opt = opts.ipoptp_cur;
10962 		optlen = opts.ipoptp_len;
10963 		switch (optval) {
10964 			int	off1, off2;
10965 		case IPOPT_SSRR:
10966 		case IPOPT_LSRR:
10967 
10968 			/* Reverse source route */
10969 			/*
10970 			 * First entry should be the next to last one in the
10971 			 * current source route (the last entry is our
10972 			 * address.)
10973 			 * The last entry should be the final destination.
10974 			 */
10975 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10976 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10977 			off1 = IPOPT_MINOFF_SR - 1;
10978 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10979 			if (off2 < 0) {
10980 				/* No entries in source route */
10981 				break;
10982 			}
10983 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10984 			/*
10985 			 * Note: use src since ipha has not had its src
10986 			 * and dst reversed (it is in the state it was
10987 			 * received.
10988 			 */
10989 			bcopy(&ipha->ipha_src, buf + off2,
10990 			    IP_ADDR_LEN);
10991 			off2 -= IP_ADDR_LEN;
10992 
10993 			while (off2 > 0) {
10994 				bcopy(opt + off2, buf + off1,
10995 				    IP_ADDR_LEN);
10996 				off1 += IP_ADDR_LEN;
10997 				off2 -= IP_ADDR_LEN;
10998 			}
10999 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11000 			buf += optlen;
11001 			len += optlen;
11002 			break;
11003 		}
11004 	}
11005 done:
11006 	/* Pad the resulting options */
11007 	while (len & 0x3) {
11008 		*buf++ = IPOPT_EOL;
11009 		len++;
11010 	}
11011 	return (len);
11012 }
11013 
11014 
11015 /*
11016  * Extract and revert a source route from ipha (if any)
11017  * and then update the relevant fields in both tcp_t and the standard header.
11018  */
11019 static void
11020 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11021 {
11022 	char	buf[TCP_MAX_HDR_LENGTH];
11023 	uint_t	tcph_len;
11024 	int	len;
11025 
11026 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11027 	len = IPH_HDR_LENGTH(ipha);
11028 	if (len == IP_SIMPLE_HDR_LENGTH)
11029 		/* Nothing to do */
11030 		return;
11031 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11032 	    (len & 0x3))
11033 		return;
11034 
11035 	tcph_len = tcp->tcp_tcp_hdr_len;
11036 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11037 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11038 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11039 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11040 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11041 	len += IP_SIMPLE_HDR_LENGTH;
11042 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11043 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11044 	if ((int)tcp->tcp_sum < 0)
11045 		tcp->tcp_sum--;
11046 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11047 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11048 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11049 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11050 	tcp->tcp_ip_hdr_len = len;
11051 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11052 	    (IP_VERSION << 4) | (len >> 2);
11053 	len += tcph_len;
11054 	tcp->tcp_hdr_len = len;
11055 }
11056 
11057 /*
11058  * Copy the standard header into its new location,
11059  * lay in the new options and then update the relevant
11060  * fields in both tcp_t and the standard header.
11061  */
11062 static int
11063 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11064 {
11065 	uint_t	tcph_len;
11066 	uint8_t	*ip_optp;
11067 	tcph_t	*new_tcph;
11068 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11069 	conn_t	*connp = tcp->tcp_connp;
11070 
11071 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11072 		return (EINVAL);
11073 
11074 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11075 		return (EINVAL);
11076 
11077 	if (checkonly) {
11078 		/*
11079 		 * do not really set, just pretend to - T_CHECK
11080 		 */
11081 		return (0);
11082 	}
11083 
11084 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11085 	if (tcp->tcp_label_len > 0) {
11086 		int padlen;
11087 		uint8_t opt;
11088 
11089 		/* convert list termination to no-ops */
11090 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11091 		ip_optp += ip_optp[IPOPT_OLEN];
11092 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11093 		while (--padlen >= 0)
11094 			*ip_optp++ = opt;
11095 	}
11096 	tcph_len = tcp->tcp_tcp_hdr_len;
11097 	new_tcph = (tcph_t *)(ip_optp + len);
11098 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11099 	tcp->tcp_tcph = new_tcph;
11100 	bcopy(ptr, ip_optp, len);
11101 
11102 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11103 
11104 	tcp->tcp_ip_hdr_len = len;
11105 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11106 	    (IP_VERSION << 4) | (len >> 2);
11107 	tcp->tcp_hdr_len = len + tcph_len;
11108 	if (!TCP_IS_DETACHED(tcp)) {
11109 		/* Always allocate room for all options. */
11110 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11111 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11112 	}
11113 	return (0);
11114 }
11115 
11116 /* Get callback routine passed to nd_load by tcp_param_register */
11117 /* ARGSUSED */
11118 static int
11119 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11120 {
11121 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11122 
11123 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11124 	return (0);
11125 }
11126 
11127 /*
11128  * Walk through the param array specified registering each element with the
11129  * named dispatch handler.
11130  */
11131 static boolean_t
11132 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11133 {
11134 	for (; cnt-- > 0; tcppa++) {
11135 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11136 			if (!nd_load(ndp, tcppa->tcp_param_name,
11137 			    tcp_param_get, tcp_param_set,
11138 			    (caddr_t)tcppa)) {
11139 				nd_free(ndp);
11140 				return (B_FALSE);
11141 			}
11142 		}
11143 	}
11144 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11145 	    KM_SLEEP);
11146 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11147 	    sizeof (tcpparam_t));
11148 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11149 	    tcp_param_get, tcp_param_set_aligned,
11150 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11151 		nd_free(ndp);
11152 		return (B_FALSE);
11153 	}
11154 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11155 	    KM_SLEEP);
11156 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11157 	    sizeof (tcpparam_t));
11158 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11159 	    tcp_param_get, tcp_param_set_aligned,
11160 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11161 		nd_free(ndp);
11162 		return (B_FALSE);
11163 	}
11164 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11165 	    KM_SLEEP);
11166 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11167 	    sizeof (tcpparam_t));
11168 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11169 	    tcp_param_get, tcp_param_set_aligned,
11170 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11171 		nd_free(ndp);
11172 		return (B_FALSE);
11173 	}
11174 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11175 	    KM_SLEEP);
11176 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11177 	    sizeof (tcpparam_t));
11178 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11179 	    tcp_param_get, tcp_param_set_aligned,
11180 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11181 		nd_free(ndp);
11182 		return (B_FALSE);
11183 	}
11184 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11185 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11186 		nd_free(ndp);
11187 		return (B_FALSE);
11188 	}
11189 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11190 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11191 		nd_free(ndp);
11192 		return (B_FALSE);
11193 	}
11194 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11195 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11196 		nd_free(ndp);
11197 		return (B_FALSE);
11198 	}
11199 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11200 	    tcp_1948_phrase_set, NULL)) {
11201 		nd_free(ndp);
11202 		return (B_FALSE);
11203 	}
11204 	/*
11205 	 * Dummy ndd variables - only to convey obsolescence information
11206 	 * through printing of their name (no get or set routines)
11207 	 * XXX Remove in future releases ?
11208 	 */
11209 	if (!nd_load(ndp,
11210 	    "tcp_close_wait_interval(obsoleted - "
11211 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11212 		nd_free(ndp);
11213 		return (B_FALSE);
11214 	}
11215 	return (B_TRUE);
11216 }
11217 
11218 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11219 /* ARGSUSED */
11220 static int
11221 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11222     cred_t *cr)
11223 {
11224 	long new_value;
11225 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11226 
11227 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11228 	    new_value < tcppa->tcp_param_min ||
11229 	    new_value > tcppa->tcp_param_max) {
11230 		return (EINVAL);
11231 	}
11232 	/*
11233 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11234 	 * round it up.  For future 64 bit requirement, we actually make it
11235 	 * a multiple of 8.
11236 	 */
11237 	if (new_value & 0x7) {
11238 		new_value = (new_value & ~0x7) + 0x8;
11239 	}
11240 	tcppa->tcp_param_val = new_value;
11241 	return (0);
11242 }
11243 
11244 /* Set callback routine passed to nd_load by tcp_param_register */
11245 /* ARGSUSED */
11246 static int
11247 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11248 {
11249 	long	new_value;
11250 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11251 
11252 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11253 	    new_value < tcppa->tcp_param_min ||
11254 	    new_value > tcppa->tcp_param_max) {
11255 		return (EINVAL);
11256 	}
11257 	tcppa->tcp_param_val = new_value;
11258 	return (0);
11259 }
11260 
11261 /*
11262  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11263  * is filled, return as much as we can.  The message passed in may be
11264  * multi-part, chained using b_cont.  "start" is the starting sequence
11265  * number for this piece.
11266  */
11267 static mblk_t *
11268 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11269 {
11270 	uint32_t	end;
11271 	mblk_t		*mp1;
11272 	mblk_t		*mp2;
11273 	mblk_t		*next_mp;
11274 	uint32_t	u1;
11275 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11276 
11277 	/* Walk through all the new pieces. */
11278 	do {
11279 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11280 		    (uintptr_t)INT_MAX);
11281 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11282 		next_mp = mp->b_cont;
11283 		if (start == end) {
11284 			/* Empty.  Blast it. */
11285 			freeb(mp);
11286 			continue;
11287 		}
11288 		mp->b_cont = NULL;
11289 		TCP_REASS_SET_SEQ(mp, start);
11290 		TCP_REASS_SET_END(mp, end);
11291 		mp1 = tcp->tcp_reass_tail;
11292 		if (!mp1) {
11293 			tcp->tcp_reass_tail = mp;
11294 			tcp->tcp_reass_head = mp;
11295 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11296 			UPDATE_MIB(&tcps->tcps_mib,
11297 			    tcpInDataUnorderBytes, end - start);
11298 			continue;
11299 		}
11300 		/* New stuff completely beyond tail? */
11301 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11302 			/* Link it on end. */
11303 			mp1->b_cont = mp;
11304 			tcp->tcp_reass_tail = mp;
11305 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11306 			UPDATE_MIB(&tcps->tcps_mib,
11307 			    tcpInDataUnorderBytes, end - start);
11308 			continue;
11309 		}
11310 		mp1 = tcp->tcp_reass_head;
11311 		u1 = TCP_REASS_SEQ(mp1);
11312 		/* New stuff at the front? */
11313 		if (SEQ_LT(start, u1)) {
11314 			/* Yes... Check for overlap. */
11315 			mp->b_cont = mp1;
11316 			tcp->tcp_reass_head = mp;
11317 			tcp_reass_elim_overlap(tcp, mp);
11318 			continue;
11319 		}
11320 		/*
11321 		 * The new piece fits somewhere between the head and tail.
11322 		 * We find our slot, where mp1 precedes us and mp2 trails.
11323 		 */
11324 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11325 			u1 = TCP_REASS_SEQ(mp2);
11326 			if (SEQ_LEQ(start, u1))
11327 				break;
11328 		}
11329 		/* Link ourselves in */
11330 		mp->b_cont = mp2;
11331 		mp1->b_cont = mp;
11332 
11333 		/* Trim overlap with following mblk(s) first */
11334 		tcp_reass_elim_overlap(tcp, mp);
11335 
11336 		/* Trim overlap with preceding mblk */
11337 		tcp_reass_elim_overlap(tcp, mp1);
11338 
11339 	} while (start = end, mp = next_mp);
11340 	mp1 = tcp->tcp_reass_head;
11341 	/* Anything ready to go? */
11342 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11343 		return (NULL);
11344 	/* Eat what we can off the queue */
11345 	for (;;) {
11346 		mp = mp1->b_cont;
11347 		end = TCP_REASS_END(mp1);
11348 		TCP_REASS_SET_SEQ(mp1, 0);
11349 		TCP_REASS_SET_END(mp1, 0);
11350 		if (!mp) {
11351 			tcp->tcp_reass_tail = NULL;
11352 			break;
11353 		}
11354 		if (end != TCP_REASS_SEQ(mp)) {
11355 			mp1->b_cont = NULL;
11356 			break;
11357 		}
11358 		mp1 = mp;
11359 	}
11360 	mp1 = tcp->tcp_reass_head;
11361 	tcp->tcp_reass_head = mp;
11362 	return (mp1);
11363 }
11364 
11365 /* Eliminate any overlap that mp may have over later mblks */
11366 static void
11367 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11368 {
11369 	uint32_t	end;
11370 	mblk_t		*mp1;
11371 	uint32_t	u1;
11372 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11373 
11374 	end = TCP_REASS_END(mp);
11375 	while ((mp1 = mp->b_cont) != NULL) {
11376 		u1 = TCP_REASS_SEQ(mp1);
11377 		if (!SEQ_GT(end, u1))
11378 			break;
11379 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11380 			mp->b_wptr -= end - u1;
11381 			TCP_REASS_SET_END(mp, u1);
11382 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11383 			UPDATE_MIB(&tcps->tcps_mib,
11384 			    tcpInDataPartDupBytes, end - u1);
11385 			break;
11386 		}
11387 		mp->b_cont = mp1->b_cont;
11388 		TCP_REASS_SET_SEQ(mp1, 0);
11389 		TCP_REASS_SET_END(mp1, 0);
11390 		freeb(mp1);
11391 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11392 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11393 	}
11394 	if (!mp1)
11395 		tcp->tcp_reass_tail = mp;
11396 }
11397 
11398 static uint_t
11399 tcp_rwnd_reopen(tcp_t *tcp)
11400 {
11401 	uint_t ret = 0;
11402 	uint_t thwin;
11403 
11404 	/* Learn the latest rwnd information that we sent to the other side. */
11405 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11406 	    << tcp->tcp_rcv_ws;
11407 	/* This is peer's calculated send window (our receive window). */
11408 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11409 	/*
11410 	 * Increase the receive window to max.  But we need to do receiver
11411 	 * SWS avoidance.  This means that we need to check the increase of
11412 	 * of receive window is at least 1 MSS.
11413 	 */
11414 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11415 		/*
11416 		 * If the window that the other side knows is less than max
11417 		 * deferred acks segments, send an update immediately.
11418 		 */
11419 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11420 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11421 			ret = TH_ACK_NEEDED;
11422 		}
11423 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11424 	}
11425 	return (ret);
11426 }
11427 
11428 /*
11429  * Send up all messages queued on tcp_rcv_list.
11430  */
11431 static uint_t
11432 tcp_rcv_drain(tcp_t *tcp)
11433 {
11434 	mblk_t *mp;
11435 	uint_t ret = 0;
11436 #ifdef DEBUG
11437 	uint_t cnt = 0;
11438 #endif
11439 	queue_t	*q = tcp->tcp_rq;
11440 
11441 	/* Can't drain on an eager connection */
11442 	if (tcp->tcp_listener != NULL)
11443 		return (ret);
11444 
11445 	/* Can't be a non-STREAMS connection */
11446 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
11447 
11448 	/* No need for the push timer now. */
11449 	if (tcp->tcp_push_tid != 0) {
11450 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11451 		tcp->tcp_push_tid = 0;
11452 	}
11453 
11454 	/*
11455 	 * Handle two cases here: we are currently fused or we were
11456 	 * previously fused and have some urgent data to be delivered
11457 	 * upstream.  The latter happens because we either ran out of
11458 	 * memory or were detached and therefore sending the SIGURG was
11459 	 * deferred until this point.  In either case we pass control
11460 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11461 	 * some work.
11462 	 */
11463 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11464 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11465 		    tcp->tcp_fused_sigurg_mp != NULL);
11466 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11467 		    &tcp->tcp_fused_sigurg_mp))
11468 			return (ret);
11469 	}
11470 
11471 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11472 		tcp->tcp_rcv_list = mp->b_next;
11473 		mp->b_next = NULL;
11474 #ifdef DEBUG
11475 		cnt += msgdsize(mp);
11476 #endif
11477 		/* Does this need SSL processing first? */
11478 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11479 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11480 			    mblk_t *, mp);
11481 			tcp_kssl_input(tcp, mp);
11482 			continue;
11483 		}
11484 		putnext(q, mp);
11485 	}
11486 #ifdef DEBUG
11487 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11488 #endif
11489 	tcp->tcp_rcv_last_head = NULL;
11490 	tcp->tcp_rcv_last_tail = NULL;
11491 	tcp->tcp_rcv_cnt = 0;
11492 
11493 	if (canputnext(q))
11494 		return (tcp_rwnd_reopen(tcp));
11495 
11496 	return (ret);
11497 }
11498 
11499 /*
11500  * Queue data on tcp_rcv_list which is a b_next chain.
11501  * tcp_rcv_last_head/tail is the last element of this chain.
11502  * Each element of the chain is a b_cont chain.
11503  *
11504  * M_DATA messages are added to the current element.
11505  * Other messages are added as new (b_next) elements.
11506  */
11507 void
11508 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11509 {
11510 	ASSERT(seg_len == msgdsize(mp));
11511 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11512 
11513 	if (tcp->tcp_rcv_list == NULL) {
11514 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11515 		tcp->tcp_rcv_list = mp;
11516 		tcp->tcp_rcv_last_head = mp;
11517 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11518 		tcp->tcp_rcv_last_tail->b_cont = mp;
11519 	} else {
11520 		tcp->tcp_rcv_last_head->b_next = mp;
11521 		tcp->tcp_rcv_last_head = mp;
11522 	}
11523 
11524 	while (mp->b_cont)
11525 		mp = mp->b_cont;
11526 
11527 	tcp->tcp_rcv_last_tail = mp;
11528 	tcp->tcp_rcv_cnt += seg_len;
11529 	tcp->tcp_rwnd -= seg_len;
11530 }
11531 
11532 /*
11533  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11534  *
11535  * This is the default entry function into TCP on the read side. TCP is
11536  * always entered via squeue i.e. using squeue's for mutual exclusion.
11537  * When classifier does a lookup to find the tcp, it also puts a reference
11538  * on the conn structure associated so the tcp is guaranteed to exist
11539  * when we come here. We still need to check the state because it might
11540  * as well has been closed. The squeue processing function i.e. squeue_enter,
11541  * is responsible for doing the CONN_DEC_REF.
11542  *
11543  * Apart from the default entry point, IP also sends packets directly to
11544  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11545  * connections.
11546  */
11547 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11548 void
11549 tcp_input(void *arg, mblk_t *mp, void *arg2)
11550 {
11551 	conn_t	*connp = (conn_t *)arg;
11552 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11553 
11554 	/* arg2 is the sqp */
11555 	ASSERT(arg2 != NULL);
11556 	ASSERT(mp != NULL);
11557 
11558 	/*
11559 	 * Don't accept any input on a closed tcp as this TCP logically does
11560 	 * not exist on the system. Don't proceed further with this TCP.
11561 	 * For eg. this packet could trigger another close of this tcp
11562 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11563 	 * tcp_clean_death / tcp_closei_local must be called at most once
11564 	 * on a TCP. In this case we need to refeed the packet into the
11565 	 * classifier and figure out where the packet should go. Need to
11566 	 * preserve the recv_ill somehow. Until we figure that out, for
11567 	 * now just drop the packet if we can't classify the packet.
11568 	 */
11569 	if (tcp->tcp_state == TCPS_CLOSED ||
11570 	    tcp->tcp_state == TCPS_BOUND) {
11571 		conn_t	*new_connp;
11572 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11573 
11574 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11575 		if (new_connp != NULL) {
11576 			tcp_reinput(new_connp, mp, arg2);
11577 			return;
11578 		}
11579 		/* We failed to classify. For now just drop the packet */
11580 		freemsg(mp);
11581 		return;
11582 	}
11583 
11584 	if (DB_TYPE(mp) != M_DATA) {
11585 		tcp_rput_common(tcp, mp);
11586 		return;
11587 	}
11588 
11589 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11590 		squeue_t	*final_sqp;
11591 
11592 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11593 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11594 		DB_CKSUMSTART(mp) = 0;
11595 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11596 		    connp->conn_final_sqp == NULL &&
11597 		    tcp_outbound_squeue_switch) {
11598 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11599 			connp->conn_final_sqp = final_sqp;
11600 			if (connp->conn_final_sqp != connp->conn_sqp) {
11601 				CONN_INC_REF(connp);
11602 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11603 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11604 				    tcp_rput_data, connp, ip_squeue_flag,
11605 				    SQTAG_CONNECT_FINISH);
11606 				return;
11607 			}
11608 		}
11609 	}
11610 	tcp_rput_data(connp, mp, arg2);
11611 }
11612 
11613 /*
11614  * The read side put procedure.
11615  * The packets passed up by ip are assume to be aligned according to
11616  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11617  */
11618 static void
11619 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11620 {
11621 	/*
11622 	 * tcp_rput_data() does not expect M_CTL except for the case
11623 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11624 	 * type. Need to make sure that any other M_CTLs don't make
11625 	 * it to tcp_rput_data since it is not expecting any and doesn't
11626 	 * check for it.
11627 	 */
11628 	if (DB_TYPE(mp) == M_CTL) {
11629 		switch (*(uint32_t *)(mp->b_rptr)) {
11630 		case TCP_IOC_ABORT_CONN:
11631 			/*
11632 			 * Handle connection abort request.
11633 			 */
11634 			tcp_ioctl_abort_handler(tcp, mp);
11635 			return;
11636 		case IPSEC_IN:
11637 			/*
11638 			 * Only secure icmp arrive in TCP and they
11639 			 * don't go through data path.
11640 			 */
11641 			tcp_icmp_error(tcp, mp);
11642 			return;
11643 		case IN_PKTINFO:
11644 			/*
11645 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11646 			 * sockets that are receiving IPv4 traffic. tcp
11647 			 */
11648 			ASSERT(tcp->tcp_family == AF_INET6);
11649 			ASSERT(tcp->tcp_ipv6_recvancillary &
11650 			    TCP_IPV6_RECVPKTINFO);
11651 			tcp_rput_data(tcp->tcp_connp, mp,
11652 			    tcp->tcp_connp->conn_sqp);
11653 			return;
11654 		case MDT_IOC_INFO_UPDATE:
11655 			/*
11656 			 * Handle Multidata information update; the
11657 			 * following routine will free the message.
11658 			 */
11659 			if (tcp->tcp_connp->conn_mdt_ok) {
11660 				tcp_mdt_update(tcp,
11661 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11662 				    B_FALSE);
11663 			}
11664 			freemsg(mp);
11665 			return;
11666 		case LSO_IOC_INFO_UPDATE:
11667 			/*
11668 			 * Handle LSO information update; the following
11669 			 * routine will free the message.
11670 			 */
11671 			if (tcp->tcp_connp->conn_lso_ok) {
11672 				tcp_lso_update(tcp,
11673 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11674 			}
11675 			freemsg(mp);
11676 			return;
11677 		default:
11678 			/*
11679 			 * tcp_icmp_err() will process the M_CTL packets.
11680 			 * Non-ICMP packets, if any, will be discarded in
11681 			 * tcp_icmp_err(). We will process the ICMP packet
11682 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11683 			 * incoming ICMP packet may result in changing
11684 			 * the tcp_mss, which we would need if we have
11685 			 * packets to retransmit.
11686 			 */
11687 			tcp_icmp_error(tcp, mp);
11688 			return;
11689 		}
11690 	}
11691 
11692 	/* No point processing the message if tcp is already closed */
11693 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11694 		freemsg(mp);
11695 		return;
11696 	}
11697 
11698 	tcp_rput_other(tcp, mp);
11699 }
11700 
11701 
11702 /* The minimum of smoothed mean deviation in RTO calculation. */
11703 #define	TCP_SD_MIN	400
11704 
11705 /*
11706  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11707  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11708  * are the same as those in Appendix A.2 of that paper.
11709  *
11710  * m = new measurement
11711  * sa = smoothed RTT average (8 * average estimates).
11712  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11713  */
11714 static void
11715 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11716 {
11717 	long m = TICK_TO_MSEC(rtt);
11718 	clock_t sa = tcp->tcp_rtt_sa;
11719 	clock_t sv = tcp->tcp_rtt_sd;
11720 	clock_t rto;
11721 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11722 
11723 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11724 	tcp->tcp_rtt_update++;
11725 
11726 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11727 	if (sa != 0) {
11728 		/*
11729 		 * Update average estimator:
11730 		 *	new rtt = 7/8 old rtt + 1/8 Error
11731 		 */
11732 
11733 		/* m is now Error in estimate. */
11734 		m -= sa >> 3;
11735 		if ((sa += m) <= 0) {
11736 			/*
11737 			 * Don't allow the smoothed average to be negative.
11738 			 * We use 0 to denote reinitialization of the
11739 			 * variables.
11740 			 */
11741 			sa = 1;
11742 		}
11743 
11744 		/*
11745 		 * Update deviation estimator:
11746 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11747 		 */
11748 		if (m < 0)
11749 			m = -m;
11750 		m -= sv >> 2;
11751 		sv += m;
11752 	} else {
11753 		/*
11754 		 * This follows BSD's implementation.  So the reinitialized
11755 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11756 		 * link is bandwidth dominated, doubling the window size
11757 		 * during slow start means doubling the RTT.  We want to be
11758 		 * more conservative when we reinitialize our estimates.  3
11759 		 * is just a convenient number.
11760 		 */
11761 		sa = m << 3;
11762 		sv = m << 1;
11763 	}
11764 	if (sv < TCP_SD_MIN) {
11765 		/*
11766 		 * We do not know that if sa captures the delay ACK
11767 		 * effect as in a long train of segments, a receiver
11768 		 * does not delay its ACKs.  So set the minimum of sv
11769 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11770 		 * of BSD DATO.  That means the minimum of mean
11771 		 * deviation is 100 ms.
11772 		 *
11773 		 */
11774 		sv = TCP_SD_MIN;
11775 	}
11776 	tcp->tcp_rtt_sa = sa;
11777 	tcp->tcp_rtt_sd = sv;
11778 	/*
11779 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11780 	 *
11781 	 * Add tcp_rexmit_interval extra in case of extreme environment
11782 	 * where the algorithm fails to work.  The default value of
11783 	 * tcp_rexmit_interval_extra should be 0.
11784 	 *
11785 	 * As we use a finer grained clock than BSD and update
11786 	 * RTO for every ACKs, add in another .25 of RTT to the
11787 	 * deviation of RTO to accomodate burstiness of 1/4 of
11788 	 * window size.
11789 	 */
11790 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11791 
11792 	if (rto > tcps->tcps_rexmit_interval_max) {
11793 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11794 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11795 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11796 	} else {
11797 		tcp->tcp_rto = rto;
11798 	}
11799 
11800 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11801 	tcp->tcp_timer_backoff = 0;
11802 }
11803 
11804 /*
11805  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11806  * send queue which starts at the given sequence number. If the given
11807  * sequence number is equal to last valid sequence number (tcp_snxt), the
11808  * returned mblk is the last valid mblk, and off is set to the length of
11809  * that mblk.
11810  *
11811  * send queue which starts at the given seq. no.
11812  *
11813  * Parameters:
11814  *	tcp_t *tcp: the tcp instance pointer.
11815  *	uint32_t seq: the starting seq. no of the requested segment.
11816  *	int32_t *off: after the execution, *off will be the offset to
11817  *		the returned mblk which points to the requested seq no.
11818  *		It is the caller's responsibility to send in a non-null off.
11819  *
11820  * Return:
11821  *	A mblk_t pointer pointing to the requested segment in send queue.
11822  */
11823 static mblk_t *
11824 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11825 {
11826 	int32_t	cnt;
11827 	mblk_t	*mp;
11828 
11829 	/* Defensive coding.  Make sure we don't send incorrect data. */
11830 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
11831 		return (NULL);
11832 
11833 	cnt = seq - tcp->tcp_suna;
11834 	mp = tcp->tcp_xmit_head;
11835 	while (cnt > 0 && mp != NULL) {
11836 		cnt -= mp->b_wptr - mp->b_rptr;
11837 		if (cnt <= 0) {
11838 			cnt += mp->b_wptr - mp->b_rptr;
11839 			break;
11840 		}
11841 		mp = mp->b_cont;
11842 	}
11843 	ASSERT(mp != NULL);
11844 	*off = cnt;
11845 	return (mp);
11846 }
11847 
11848 /*
11849  * This function handles all retransmissions if SACK is enabled for this
11850  * connection.  First it calculates how many segments can be retransmitted
11851  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11852  * segments.  A segment is eligible if sack_cnt for that segment is greater
11853  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11854  * all eligible segments, it checks to see if TCP can send some new segments
11855  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11856  *
11857  * Parameters:
11858  *	tcp_t *tcp: the tcp structure of the connection.
11859  *	uint_t *flags: in return, appropriate value will be set for
11860  *	tcp_rput_data().
11861  */
11862 static void
11863 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11864 {
11865 	notsack_blk_t	*notsack_blk;
11866 	int32_t		usable_swnd;
11867 	int32_t		mss;
11868 	uint32_t	seg_len;
11869 	mblk_t		*xmit_mp;
11870 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11871 
11872 	ASSERT(tcp->tcp_sack_info != NULL);
11873 	ASSERT(tcp->tcp_notsack_list != NULL);
11874 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11875 
11876 	/* Defensive coding in case there is a bug... */
11877 	if (tcp->tcp_notsack_list == NULL) {
11878 		return;
11879 	}
11880 	notsack_blk = tcp->tcp_notsack_list;
11881 	mss = tcp->tcp_mss;
11882 
11883 	/*
11884 	 * Limit the num of outstanding data in the network to be
11885 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11886 	 */
11887 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11888 
11889 	/* At least retransmit 1 MSS of data. */
11890 	if (usable_swnd <= 0) {
11891 		usable_swnd = mss;
11892 	}
11893 
11894 	/* Make sure no new RTT samples will be taken. */
11895 	tcp->tcp_csuna = tcp->tcp_snxt;
11896 
11897 	notsack_blk = tcp->tcp_notsack_list;
11898 	while (usable_swnd > 0) {
11899 		mblk_t		*snxt_mp, *tmp_mp;
11900 		tcp_seq		begin = tcp->tcp_sack_snxt;
11901 		tcp_seq		end;
11902 		int32_t		off;
11903 
11904 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11905 			if (SEQ_GT(notsack_blk->end, begin) &&
11906 			    (notsack_blk->sack_cnt >=
11907 			    tcps->tcps_dupack_fast_retransmit)) {
11908 				end = notsack_blk->end;
11909 				if (SEQ_LT(begin, notsack_blk->begin)) {
11910 					begin = notsack_blk->begin;
11911 				}
11912 				break;
11913 			}
11914 		}
11915 		/*
11916 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11917 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11918 		 * set to tcp_cwnd_ssthresh.
11919 		 */
11920 		if (notsack_blk == NULL) {
11921 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11922 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11923 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11924 				ASSERT(tcp->tcp_cwnd > 0);
11925 				return;
11926 			} else {
11927 				usable_swnd = usable_swnd / mss;
11928 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11929 				    MAX(usable_swnd * mss, mss);
11930 				*flags |= TH_XMIT_NEEDED;
11931 				return;
11932 			}
11933 		}
11934 
11935 		/*
11936 		 * Note that we may send more than usable_swnd allows here
11937 		 * because of round off, but no more than 1 MSS of data.
11938 		 */
11939 		seg_len = end - begin;
11940 		if (seg_len > mss)
11941 			seg_len = mss;
11942 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11943 		ASSERT(snxt_mp != NULL);
11944 		/* This should not happen.  Defensive coding again... */
11945 		if (snxt_mp == NULL) {
11946 			return;
11947 		}
11948 
11949 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11950 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11951 		if (xmit_mp == NULL)
11952 			return;
11953 
11954 		usable_swnd -= seg_len;
11955 		tcp->tcp_pipe += seg_len;
11956 		tcp->tcp_sack_snxt = begin + seg_len;
11957 
11958 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11959 
11960 		/*
11961 		 * Update the send timestamp to avoid false retransmission.
11962 		 */
11963 		snxt_mp->b_prev = (mblk_t *)lbolt;
11964 
11965 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
11966 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
11967 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
11968 		/*
11969 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11970 		 * This happens when new data sent during fast recovery is
11971 		 * also lost.  If TCP retransmits those new data, it needs
11972 		 * to extend SACK recover phase to avoid starting another
11973 		 * fast retransmit/recovery unnecessarily.
11974 		 */
11975 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11976 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11977 		}
11978 	}
11979 }
11980 
11981 /*
11982  * This function handles policy checking at TCP level for non-hard_bound/
11983  * detached connections.
11984  */
11985 static boolean_t
11986 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
11987     boolean_t secure, boolean_t mctl_present)
11988 {
11989 	ipsec_latch_t *ipl = NULL;
11990 	ipsec_action_t *act = NULL;
11991 	mblk_t *data_mp;
11992 	ipsec_in_t *ii;
11993 	const char *reason;
11994 	kstat_named_t *counter;
11995 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11996 	ipsec_stack_t	*ipss;
11997 	ip_stack_t	*ipst;
11998 
11999 	ASSERT(mctl_present || !secure);
12000 
12001 	ASSERT((ipha == NULL && ip6h != NULL) ||
12002 	    (ip6h == NULL && ipha != NULL));
12003 
12004 	/*
12005 	 * We don't necessarily have an ipsec_in_act action to verify
12006 	 * policy because of assymetrical policy where we have only
12007 	 * outbound policy and no inbound policy (possible with global
12008 	 * policy).
12009 	 */
12010 	if (!secure) {
12011 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12012 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12013 			return (B_TRUE);
12014 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12015 		    "tcp_check_policy", ipha, ip6h, secure,
12016 		    tcps->tcps_netstack);
12017 		ipss = tcps->tcps_netstack->netstack_ipsec;
12018 
12019 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12020 		    DROPPER(ipss, ipds_tcp_clear),
12021 		    &tcps->tcps_dropper);
12022 		return (B_FALSE);
12023 	}
12024 
12025 	/*
12026 	 * We have a secure packet.
12027 	 */
12028 	if (act == NULL) {
12029 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12030 		    "tcp_check_policy", ipha, ip6h, secure,
12031 		    tcps->tcps_netstack);
12032 		ipss = tcps->tcps_netstack->netstack_ipsec;
12033 
12034 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12035 		    DROPPER(ipss, ipds_tcp_secure),
12036 		    &tcps->tcps_dropper);
12037 		return (B_FALSE);
12038 	}
12039 
12040 	/*
12041 	 * XXX This whole routine is currently incorrect.  ipl should
12042 	 * be set to the latch pointer, but is currently not set, so
12043 	 * we initialize it to NULL to avoid picking up random garbage.
12044 	 */
12045 	if (ipl == NULL)
12046 		return (B_TRUE);
12047 
12048 	data_mp = first_mp->b_cont;
12049 
12050 	ii = (ipsec_in_t *)first_mp->b_rptr;
12051 
12052 	ipst = tcps->tcps_netstack->netstack_ip;
12053 
12054 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12055 	    &counter, tcp->tcp_connp)) {
12056 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12057 		return (B_TRUE);
12058 	}
12059 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12060 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12061 	    reason);
12062 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12063 
12064 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12065 	    &tcps->tcps_dropper);
12066 	return (B_FALSE);
12067 }
12068 
12069 /*
12070  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12071  * retransmission after a timeout.
12072  *
12073  * To limit the number of duplicate segments, we limit the number of segment
12074  * to be sent in one time to tcp_snd_burst, the burst variable.
12075  */
12076 static void
12077 tcp_ss_rexmit(tcp_t *tcp)
12078 {
12079 	uint32_t	snxt;
12080 	uint32_t	smax;
12081 	int32_t		win;
12082 	int32_t		mss;
12083 	int32_t		off;
12084 	int32_t		burst = tcp->tcp_snd_burst;
12085 	mblk_t		*snxt_mp;
12086 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12087 
12088 	/*
12089 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12090 	 * all unack'ed segments.
12091 	 */
12092 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12093 		smax = tcp->tcp_rexmit_max;
12094 		snxt = tcp->tcp_rexmit_nxt;
12095 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12096 			snxt = tcp->tcp_suna;
12097 		}
12098 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12099 		win -= snxt - tcp->tcp_suna;
12100 		mss = tcp->tcp_mss;
12101 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12102 
12103 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12104 		    (burst > 0) && (snxt_mp != NULL)) {
12105 			mblk_t	*xmit_mp;
12106 			mblk_t	*old_snxt_mp = snxt_mp;
12107 			uint32_t cnt = mss;
12108 
12109 			if (win < cnt) {
12110 				cnt = win;
12111 			}
12112 			if (SEQ_GT(snxt + cnt, smax)) {
12113 				cnt = smax - snxt;
12114 			}
12115 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12116 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12117 			if (xmit_mp == NULL)
12118 				return;
12119 
12120 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12121 
12122 			snxt += cnt;
12123 			win -= cnt;
12124 			/*
12125 			 * Update the send timestamp to avoid false
12126 			 * retransmission.
12127 			 */
12128 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12129 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12130 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12131 
12132 			tcp->tcp_rexmit_nxt = snxt;
12133 			burst--;
12134 		}
12135 		/*
12136 		 * If we have transmitted all we have at the time
12137 		 * we started the retranmission, we can leave
12138 		 * the rest of the job to tcp_wput_data().  But we
12139 		 * need to check the send window first.  If the
12140 		 * win is not 0, go on with tcp_wput_data().
12141 		 */
12142 		if (SEQ_LT(snxt, smax) || win == 0) {
12143 			return;
12144 		}
12145 	}
12146 	/* Only call tcp_wput_data() if there is data to be sent. */
12147 	if (tcp->tcp_unsent) {
12148 		tcp_wput_data(tcp, NULL, B_FALSE);
12149 	}
12150 }
12151 
12152 /*
12153  * Process all TCP option in SYN segment.  Note that this function should
12154  * be called after tcp_adapt_ire() is called so that the necessary info
12155  * from IRE is already set in the tcp structure.
12156  *
12157  * This function sets up the correct tcp_mss value according to the
12158  * MSS option value and our header size.  It also sets up the window scale
12159  * and timestamp values, and initialize SACK info blocks.  But it does not
12160  * change receive window size after setting the tcp_mss value.  The caller
12161  * should do the appropriate change.
12162  */
12163 void
12164 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12165 {
12166 	int options;
12167 	tcp_opt_t tcpopt;
12168 	uint32_t mss_max;
12169 	char *tmp_tcph;
12170 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12171 
12172 	tcpopt.tcp = NULL;
12173 	options = tcp_parse_options(tcph, &tcpopt);
12174 
12175 	/*
12176 	 * Process MSS option.  Note that MSS option value does not account
12177 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12178 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12179 	 * IPv6.
12180 	 */
12181 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12182 		if (tcp->tcp_ipversion == IPV4_VERSION)
12183 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12184 		else
12185 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12186 	} else {
12187 		if (tcp->tcp_ipversion == IPV4_VERSION)
12188 			mss_max = tcps->tcps_mss_max_ipv4;
12189 		else
12190 			mss_max = tcps->tcps_mss_max_ipv6;
12191 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12192 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12193 		else if (tcpopt.tcp_opt_mss > mss_max)
12194 			tcpopt.tcp_opt_mss = mss_max;
12195 	}
12196 
12197 	/* Process Window Scale option. */
12198 	if (options & TCP_OPT_WSCALE_PRESENT) {
12199 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12200 		tcp->tcp_snd_ws_ok = B_TRUE;
12201 	} else {
12202 		tcp->tcp_snd_ws = B_FALSE;
12203 		tcp->tcp_snd_ws_ok = B_FALSE;
12204 		tcp->tcp_rcv_ws = B_FALSE;
12205 	}
12206 
12207 	/* Process Timestamp option. */
12208 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12209 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12210 		tmp_tcph = (char *)tcp->tcp_tcph;
12211 
12212 		tcp->tcp_snd_ts_ok = B_TRUE;
12213 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12214 		tcp->tcp_last_rcv_lbolt = lbolt64;
12215 		ASSERT(OK_32PTR(tmp_tcph));
12216 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12217 
12218 		/* Fill in our template header with basic timestamp option. */
12219 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12220 		tmp_tcph[0] = TCPOPT_NOP;
12221 		tmp_tcph[1] = TCPOPT_NOP;
12222 		tmp_tcph[2] = TCPOPT_TSTAMP;
12223 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12224 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12225 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12226 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12227 	} else {
12228 		tcp->tcp_snd_ts_ok = B_FALSE;
12229 	}
12230 
12231 	/*
12232 	 * Process SACK options.  If SACK is enabled for this connection,
12233 	 * then allocate the SACK info structure.  Note the following ways
12234 	 * when tcp_snd_sack_ok is set to true.
12235 	 *
12236 	 * For active connection: in tcp_adapt_ire() called in
12237 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12238 	 * is checked.
12239 	 *
12240 	 * For passive connection: in tcp_adapt_ire() called in
12241 	 * tcp_accept_comm().
12242 	 *
12243 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12244 	 * That check makes sure that if we did not send a SACK OK option,
12245 	 * we will not enable SACK for this connection even though the other
12246 	 * side sends us SACK OK option.  For active connection, the SACK
12247 	 * info structure has already been allocated.  So we need to free
12248 	 * it if SACK is disabled.
12249 	 */
12250 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12251 	    (tcp->tcp_snd_sack_ok ||
12252 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12253 		/* This should be true only in the passive case. */
12254 		if (tcp->tcp_sack_info == NULL) {
12255 			ASSERT(TCP_IS_DETACHED(tcp));
12256 			tcp->tcp_sack_info =
12257 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12258 		}
12259 		if (tcp->tcp_sack_info == NULL) {
12260 			tcp->tcp_snd_sack_ok = B_FALSE;
12261 		} else {
12262 			tcp->tcp_snd_sack_ok = B_TRUE;
12263 			if (tcp->tcp_snd_ts_ok) {
12264 				tcp->tcp_max_sack_blk = 3;
12265 			} else {
12266 				tcp->tcp_max_sack_blk = 4;
12267 			}
12268 		}
12269 	} else {
12270 		/*
12271 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12272 		 * no SACK info will be used for this
12273 		 * connection.  This assumes that SACK usage
12274 		 * permission is negotiated.  This may need
12275 		 * to be changed once this is clarified.
12276 		 */
12277 		if (tcp->tcp_sack_info != NULL) {
12278 			ASSERT(tcp->tcp_notsack_list == NULL);
12279 			kmem_cache_free(tcp_sack_info_cache,
12280 			    tcp->tcp_sack_info);
12281 			tcp->tcp_sack_info = NULL;
12282 		}
12283 		tcp->tcp_snd_sack_ok = B_FALSE;
12284 	}
12285 
12286 	/*
12287 	 * Now we know the exact TCP/IP header length, subtract
12288 	 * that from tcp_mss to get our side's MSS.
12289 	 */
12290 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12291 	/*
12292 	 * Here we assume that the other side's header size will be equal to
12293 	 * our header size.  We calculate the real MSS accordingly.  Need to
12294 	 * take into additional stuffs IPsec puts in.
12295 	 *
12296 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12297 	 */
12298 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12299 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12300 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12301 
12302 	/*
12303 	 * Set MSS to the smaller one of both ends of the connection.
12304 	 * We should not have called tcp_mss_set() before, but our
12305 	 * side of the MSS should have been set to a proper value
12306 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12307 	 * STREAM head parameters properly.
12308 	 *
12309 	 * If we have a larger-than-16-bit window but the other side
12310 	 * didn't want to do window scale, tcp_rwnd_set() will take
12311 	 * care of that.
12312 	 */
12313 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12314 }
12315 
12316 /*
12317  * Sends the T_CONN_IND to the listener. The caller calls this
12318  * functions via squeue to get inside the listener's perimeter
12319  * once the 3 way hand shake is done a T_CONN_IND needs to be
12320  * sent. As an optimization, the caller can call this directly
12321  * if listener's perimeter is same as eager's.
12322  */
12323 /* ARGSUSED */
12324 void
12325 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12326 {
12327 	conn_t			*lconnp = (conn_t *)arg;
12328 	tcp_t			*listener = lconnp->conn_tcp;
12329 	tcp_t			*tcp;
12330 	struct T_conn_ind	*conn_ind;
12331 	ipaddr_t 		*addr_cache;
12332 	boolean_t		need_send_conn_ind = B_FALSE;
12333 	tcp_stack_t		*tcps = listener->tcp_tcps;
12334 
12335 	/* retrieve the eager */
12336 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12337 	ASSERT(conn_ind->OPT_offset != 0 &&
12338 	    conn_ind->OPT_length == sizeof (intptr_t));
12339 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12340 	    conn_ind->OPT_length);
12341 
12342 	/*
12343 	 * TLI/XTI applications will get confused by
12344 	 * sending eager as an option since it violates
12345 	 * the option semantics. So remove the eager as
12346 	 * option since TLI/XTI app doesn't need it anyway.
12347 	 */
12348 	if (!TCP_IS_SOCKET(listener)) {
12349 		conn_ind->OPT_length = 0;
12350 		conn_ind->OPT_offset = 0;
12351 	}
12352 	if (listener->tcp_state != TCPS_LISTEN) {
12353 		/*
12354 		 * If listener has closed, it would have caused a
12355 		 * a cleanup/blowoff to happen for the eager. We
12356 		 * just need to return.
12357 		 */
12358 		freemsg(mp);
12359 		return;
12360 	}
12361 
12362 
12363 	/*
12364 	 * if the conn_req_q is full defer passing up the
12365 	 * T_CONN_IND until space is availabe after t_accept()
12366 	 * processing
12367 	 */
12368 	mutex_enter(&listener->tcp_eager_lock);
12369 
12370 	/*
12371 	 * Take the eager out, if it is in the list of droppable eagers
12372 	 * as we are here because the 3W handshake is over.
12373 	 */
12374 	MAKE_UNDROPPABLE(tcp);
12375 
12376 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12377 		tcp_t *tail;
12378 
12379 		/*
12380 		 * The eager already has an extra ref put in tcp_rput_data
12381 		 * so that it stays till accept comes back even though it
12382 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12383 		 */
12384 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12385 		listener->tcp_conn_req_cnt_q0--;
12386 		listener->tcp_conn_req_cnt_q++;
12387 
12388 		/* Move from SYN_RCVD to ESTABLISHED list  */
12389 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12390 		    tcp->tcp_eager_prev_q0;
12391 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12392 		    tcp->tcp_eager_next_q0;
12393 		tcp->tcp_eager_prev_q0 = NULL;
12394 		tcp->tcp_eager_next_q0 = NULL;
12395 
12396 		/*
12397 		 * Insert at end of the queue because sockfs
12398 		 * sends down T_CONN_RES in chronological
12399 		 * order. Leaving the older conn indications
12400 		 * at front of the queue helps reducing search
12401 		 * time.
12402 		 */
12403 		tail = listener->tcp_eager_last_q;
12404 		if (tail != NULL)
12405 			tail->tcp_eager_next_q = tcp;
12406 		else
12407 			listener->tcp_eager_next_q = tcp;
12408 		listener->tcp_eager_last_q = tcp;
12409 		tcp->tcp_eager_next_q = NULL;
12410 		/*
12411 		 * Delay sending up the T_conn_ind until we are
12412 		 * done with the eager. Once we have have sent up
12413 		 * the T_conn_ind, the accept can potentially complete
12414 		 * any time and release the refhold we have on the eager.
12415 		 */
12416 		need_send_conn_ind = B_TRUE;
12417 	} else {
12418 		/*
12419 		 * Defer connection on q0 and set deferred
12420 		 * connection bit true
12421 		 */
12422 		tcp->tcp_conn_def_q0 = B_TRUE;
12423 
12424 		/* take tcp out of q0 ... */
12425 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12426 		    tcp->tcp_eager_next_q0;
12427 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12428 		    tcp->tcp_eager_prev_q0;
12429 
12430 		/* ... and place it at the end of q0 */
12431 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12432 		tcp->tcp_eager_next_q0 = listener;
12433 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12434 		listener->tcp_eager_prev_q0 = tcp;
12435 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12436 	}
12437 
12438 	/* we have timed out before */
12439 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12440 		tcp->tcp_syn_rcvd_timeout = 0;
12441 		listener->tcp_syn_rcvd_timeout--;
12442 		if (listener->tcp_syn_defense &&
12443 		    listener->tcp_syn_rcvd_timeout <=
12444 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12445 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12446 		    listener->tcp_last_rcv_lbolt)) {
12447 			/*
12448 			 * Turn off the defense mode if we
12449 			 * believe the SYN attack is over.
12450 			 */
12451 			listener->tcp_syn_defense = B_FALSE;
12452 			if (listener->tcp_ip_addr_cache) {
12453 				kmem_free((void *)listener->tcp_ip_addr_cache,
12454 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12455 				listener->tcp_ip_addr_cache = NULL;
12456 			}
12457 		}
12458 	}
12459 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12460 	if (addr_cache != NULL) {
12461 		/*
12462 		 * We have finished a 3-way handshake with this
12463 		 * remote host. This proves the IP addr is good.
12464 		 * Cache it!
12465 		 */
12466 		addr_cache[IP_ADDR_CACHE_HASH(
12467 		    tcp->tcp_remote)] = tcp->tcp_remote;
12468 	}
12469 	mutex_exit(&listener->tcp_eager_lock);
12470 	if (need_send_conn_ind)
12471 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12472 }
12473 
12474 /*
12475  * Send the newconn notification to ulp. The eager is blown off if the
12476  * notification fails.
12477  */
12478 static void
12479 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12480 {
12481 	if (IPCL_IS_NONSTR(lconnp)) {
12482 		cred_t	*cr;
12483 		pid_t	cpid;
12484 
12485 		cr = msg_getcred(mp, &cpid);
12486 
12487 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12488 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12489 		    lconnp->conn_tcp);
12490 
12491 		/* Keep the message around in case of a fallback to TPI */
12492 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12493 
12494 		/*
12495 		 * Notify the ULP about the newconn. It is guaranteed that no
12496 		 * tcp_accept() call will be made for the eager if the
12497 		 * notification fails, so it's safe to blow it off in that
12498 		 * case.
12499 		 *
12500 		 * The upper handle will be assigned when tcp_accept() is
12501 		 * called.
12502 		 */
12503 		if ((*lconnp->conn_upcalls->su_newconn)
12504 		    (lconnp->conn_upper_handle,
12505 		    (sock_lower_handle_t)econnp,
12506 		    &sock_tcp_downcalls, cr, cpid,
12507 		    &econnp->conn_upcalls) == NULL) {
12508 			/* Failed to allocate a socket */
12509 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12510 			    tcpEstabResets);
12511 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12512 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12513 		}
12514 	} else {
12515 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12516 	}
12517 }
12518 
12519 mblk_t *
12520 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12521     uint_t *ifindexp, ip6_pkt_t *ippp)
12522 {
12523 	ip_pktinfo_t	*pinfo;
12524 	ip6_t		*ip6h;
12525 	uchar_t		*rptr;
12526 	mblk_t		*first_mp = mp;
12527 	boolean_t	mctl_present = B_FALSE;
12528 	uint_t 		ifindex = 0;
12529 	ip6_pkt_t	ipp;
12530 	uint_t		ipvers;
12531 	uint_t		ip_hdr_len;
12532 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12533 
12534 	rptr = mp->b_rptr;
12535 	ASSERT(OK_32PTR(rptr));
12536 	ASSERT(tcp != NULL);
12537 	ipp.ipp_fields = 0;
12538 
12539 	switch DB_TYPE(mp) {
12540 	case M_CTL:
12541 		mp = mp->b_cont;
12542 		if (mp == NULL) {
12543 			freemsg(first_mp);
12544 			return (NULL);
12545 		}
12546 		if (DB_TYPE(mp) != M_DATA) {
12547 			freemsg(first_mp);
12548 			return (NULL);
12549 		}
12550 		mctl_present = B_TRUE;
12551 		break;
12552 	case M_DATA:
12553 		break;
12554 	default:
12555 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12556 		freemsg(mp);
12557 		return (NULL);
12558 	}
12559 	ipvers = IPH_HDR_VERSION(rptr);
12560 	if (ipvers == IPV4_VERSION) {
12561 		if (tcp == NULL) {
12562 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12563 			goto done;
12564 		}
12565 
12566 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12567 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12568 
12569 		/*
12570 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12571 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12572 		 */
12573 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12574 		    mctl_present) {
12575 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12576 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12577 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12578 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12579 				ipp.ipp_fields |= IPPF_IFINDEX;
12580 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12581 				ifindex = pinfo->ip_pkt_ifindex;
12582 			}
12583 			freeb(first_mp);
12584 			mctl_present = B_FALSE;
12585 		}
12586 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12587 	} else {
12588 		ip6h = (ip6_t *)rptr;
12589 
12590 		ASSERT(ipvers == IPV6_VERSION);
12591 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12592 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12593 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12594 
12595 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12596 			uint8_t	nexthdrp;
12597 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12598 
12599 			/* Look for ifindex information */
12600 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12601 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12602 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12603 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12604 					freemsg(first_mp);
12605 					return (NULL);
12606 				}
12607 
12608 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12609 					ASSERT(ip6i->ip6i_ifindex != 0);
12610 					ipp.ipp_fields |= IPPF_IFINDEX;
12611 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12612 					ifindex = ip6i->ip6i_ifindex;
12613 				}
12614 				rptr = (uchar_t *)&ip6i[1];
12615 				mp->b_rptr = rptr;
12616 				if (rptr == mp->b_wptr) {
12617 					mblk_t *mp1;
12618 					mp1 = mp->b_cont;
12619 					freeb(mp);
12620 					mp = mp1;
12621 					rptr = mp->b_rptr;
12622 				}
12623 				if (MBLKL(mp) < IPV6_HDR_LEN +
12624 				    sizeof (tcph_t)) {
12625 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12626 					freemsg(first_mp);
12627 					return (NULL);
12628 				}
12629 				ip6h = (ip6_t *)rptr;
12630 			}
12631 
12632 			/*
12633 			 * Find any potentially interesting extension headers
12634 			 * as well as the length of the IPv6 + extension
12635 			 * headers.
12636 			 */
12637 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12638 			/* Verify if this is a TCP packet */
12639 			if (nexthdrp != IPPROTO_TCP) {
12640 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12641 				freemsg(first_mp);
12642 				return (NULL);
12643 			}
12644 		} else {
12645 			ip_hdr_len = IPV6_HDR_LEN;
12646 		}
12647 	}
12648 
12649 done:
12650 	if (ipversp != NULL)
12651 		*ipversp = ipvers;
12652 	if (ip_hdr_lenp != NULL)
12653 		*ip_hdr_lenp = ip_hdr_len;
12654 	if (ippp != NULL)
12655 		*ippp = ipp;
12656 	if (ifindexp != NULL)
12657 		*ifindexp = ifindex;
12658 	if (mctl_present) {
12659 		freeb(first_mp);
12660 	}
12661 	return (mp);
12662 }
12663 
12664 /*
12665  * Handle M_DATA messages from IP. Its called directly from IP via
12666  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12667  * in this path.
12668  *
12669  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12670  * v4 and v6), we are called through tcp_input() and a M_CTL can
12671  * be present for options but tcp_find_pktinfo() deals with it. We
12672  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12673  *
12674  * The first argument is always the connp/tcp to which the mp belongs.
12675  * There are no exceptions to this rule. The caller has already put
12676  * a reference on this connp/tcp and once tcp_rput_data() returns,
12677  * the squeue will do the refrele.
12678  *
12679  * The TH_SYN for the listener directly go to tcp_conn_request via
12680  * squeue.
12681  *
12682  * sqp: NULL = recursive, sqp != NULL means called from squeue
12683  */
12684 void
12685 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12686 {
12687 	int32_t		bytes_acked;
12688 	int32_t		gap;
12689 	mblk_t		*mp1;
12690 	uint_t		flags;
12691 	uint32_t	new_swnd = 0;
12692 	uchar_t		*iphdr;
12693 	uchar_t		*rptr;
12694 	int32_t		rgap;
12695 	uint32_t	seg_ack;
12696 	int		seg_len;
12697 	uint_t		ip_hdr_len;
12698 	uint32_t	seg_seq;
12699 	tcph_t		*tcph;
12700 	int		urp;
12701 	tcp_opt_t	tcpopt;
12702 	uint_t		ipvers;
12703 	ip6_pkt_t	ipp;
12704 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12705 	uint32_t	cwnd;
12706 	uint32_t	add;
12707 	int		npkt;
12708 	int		mss;
12709 	conn_t		*connp = (conn_t *)arg;
12710 	squeue_t	*sqp = (squeue_t *)arg2;
12711 	tcp_t		*tcp = connp->conn_tcp;
12712 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12713 
12714 	/*
12715 	 * RST from fused tcp loopback peer should trigger an unfuse.
12716 	 */
12717 	if (tcp->tcp_fused) {
12718 		TCP_STAT(tcps, tcp_fusion_aborted);
12719 		tcp_unfuse(tcp);
12720 	}
12721 
12722 	iphdr = mp->b_rptr;
12723 	rptr = mp->b_rptr;
12724 	ASSERT(OK_32PTR(rptr));
12725 
12726 	/*
12727 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12728 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12729 	 * necessary information.
12730 	 */
12731 	if (IPCL_IS_TCP4(connp)) {
12732 		ipvers = IPV4_VERSION;
12733 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12734 	} else {
12735 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12736 		    NULL, &ipp);
12737 		if (mp == NULL) {
12738 			TCP_STAT(tcps, tcp_rput_v6_error);
12739 			return;
12740 		}
12741 		iphdr = mp->b_rptr;
12742 		rptr = mp->b_rptr;
12743 	}
12744 	ASSERT(DB_TYPE(mp) == M_DATA);
12745 	ASSERT(mp->b_next == NULL);
12746 
12747 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12748 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12749 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12750 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12751 	seg_len = (int)(mp->b_wptr - rptr) -
12752 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12753 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12754 		do {
12755 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12756 			    (uintptr_t)INT_MAX);
12757 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12758 		} while ((mp1 = mp1->b_cont) != NULL &&
12759 		    mp1->b_datap->db_type == M_DATA);
12760 	}
12761 
12762 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12763 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12764 		    seg_len, tcph);
12765 		return;
12766 	}
12767 
12768 	if (sqp != NULL) {
12769 		/*
12770 		 * This is the correct place to update tcp_last_recv_time. Note
12771 		 * that it is also updated for tcp structure that belongs to
12772 		 * global and listener queues which do not really need updating.
12773 		 * But that should not cause any harm.  And it is updated for
12774 		 * all kinds of incoming segments, not only for data segments.
12775 		 */
12776 		tcp->tcp_last_recv_time = lbolt;
12777 	}
12778 
12779 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12780 
12781 	BUMP_LOCAL(tcp->tcp_ibsegs);
12782 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12783 
12784 	if ((flags & TH_URG) && sqp != NULL) {
12785 		/*
12786 		 * TCP can't handle urgent pointers that arrive before
12787 		 * the connection has been accept()ed since it can't
12788 		 * buffer OOB data.  Discard segment if this happens.
12789 		 *
12790 		 * We can't just rely on a non-null tcp_listener to indicate
12791 		 * that the accept() has completed since unlinking of the
12792 		 * eager and completion of the accept are not atomic.
12793 		 * tcp_detached, when it is not set (B_FALSE) indicates
12794 		 * that the accept() has completed.
12795 		 *
12796 		 * Nor can it reassemble urgent pointers, so discard
12797 		 * if it's not the next segment expected.
12798 		 *
12799 		 * Otherwise, collapse chain into one mblk (discard if
12800 		 * that fails).  This makes sure the headers, retransmitted
12801 		 * data, and new data all are in the same mblk.
12802 		 */
12803 		ASSERT(mp != NULL);
12804 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12805 			freemsg(mp);
12806 			return;
12807 		}
12808 		/* Update pointers into message */
12809 		iphdr = rptr = mp->b_rptr;
12810 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12811 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12812 			/*
12813 			 * Since we can't handle any data with this urgent
12814 			 * pointer that is out of sequence, we expunge
12815 			 * the data.  This allows us to still register
12816 			 * the urgent mark and generate the M_PCSIG,
12817 			 * which we can do.
12818 			 */
12819 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12820 			seg_len = 0;
12821 		}
12822 	}
12823 
12824 	switch (tcp->tcp_state) {
12825 	case TCPS_SYN_SENT:
12826 		if (flags & TH_ACK) {
12827 			/*
12828 			 * Note that our stack cannot send data before a
12829 			 * connection is established, therefore the
12830 			 * following check is valid.  Otherwise, it has
12831 			 * to be changed.
12832 			 */
12833 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12834 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12835 				freemsg(mp);
12836 				if (flags & TH_RST)
12837 					return;
12838 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12839 				    tcp, seg_ack, 0, TH_RST);
12840 				return;
12841 			}
12842 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12843 		}
12844 		if (flags & TH_RST) {
12845 			freemsg(mp);
12846 			if (flags & TH_ACK)
12847 				(void) tcp_clean_death(tcp,
12848 				    ECONNREFUSED, 13);
12849 			return;
12850 		}
12851 		if (!(flags & TH_SYN)) {
12852 			freemsg(mp);
12853 			return;
12854 		}
12855 
12856 		/* Process all TCP options. */
12857 		tcp_process_options(tcp, tcph);
12858 		/*
12859 		 * The following changes our rwnd to be a multiple of the
12860 		 * MIN(peer MSS, our MSS) for performance reason.
12861 		 */
12862 		(void) tcp_rwnd_set(tcp,
12863 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
12864 
12865 		/* Is the other end ECN capable? */
12866 		if (tcp->tcp_ecn_ok) {
12867 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12868 				tcp->tcp_ecn_ok = B_FALSE;
12869 			}
12870 		}
12871 		/*
12872 		 * Clear ECN flags because it may interfere with later
12873 		 * processing.
12874 		 */
12875 		flags &= ~(TH_ECE|TH_CWR);
12876 
12877 		tcp->tcp_irs = seg_seq;
12878 		tcp->tcp_rack = seg_seq;
12879 		tcp->tcp_rnxt = seg_seq + 1;
12880 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12881 		if (!TCP_IS_DETACHED(tcp)) {
12882 			/* Allocate room for SACK options if needed. */
12883 			if (tcp->tcp_snd_sack_ok) {
12884 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12885 				    tcp->tcp_hdr_len +
12886 				    TCPOPT_MAX_SACK_LEN +
12887 				    (tcp->tcp_loopback ? 0 :
12888 				    tcps->tcps_wroff_xtra));
12889 			} else {
12890 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12891 				    tcp->tcp_hdr_len +
12892 				    (tcp->tcp_loopback ? 0 :
12893 				    tcps->tcps_wroff_xtra));
12894 			}
12895 		}
12896 		if (flags & TH_ACK) {
12897 			/*
12898 			 * If we can't get the confirmation upstream, pretend
12899 			 * we didn't even see this one.
12900 			 *
12901 			 * XXX: how can we pretend we didn't see it if we
12902 			 * have updated rnxt et. al.
12903 			 *
12904 			 * For loopback we defer sending up the T_CONN_CON
12905 			 * until after some checks below.
12906 			 */
12907 			mp1 = NULL;
12908 			/*
12909 			 * tcp_sendmsg() checks tcp_state without entering
12910 			 * the squeue so tcp_state should be updated before
12911 			 * sending up connection confirmation
12912 			 */
12913 			tcp->tcp_state = TCPS_ESTABLISHED;
12914 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12915 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12916 				tcp->tcp_state = TCPS_SYN_SENT;
12917 				freemsg(mp);
12918 				return;
12919 			}
12920 			/* SYN was acked - making progress */
12921 			if (tcp->tcp_ipversion == IPV6_VERSION)
12922 				tcp->tcp_ip_forward_progress = B_TRUE;
12923 
12924 			/* One for the SYN */
12925 			tcp->tcp_suna = tcp->tcp_iss + 1;
12926 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12927 
12928 			/*
12929 			 * If SYN was retransmitted, need to reset all
12930 			 * retransmission info.  This is because this
12931 			 * segment will be treated as a dup ACK.
12932 			 */
12933 			if (tcp->tcp_rexmit) {
12934 				tcp->tcp_rexmit = B_FALSE;
12935 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12936 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12937 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12938 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12939 				tcp->tcp_ms_we_have_waited = 0;
12940 
12941 				/*
12942 				 * Set tcp_cwnd back to 1 MSS, per
12943 				 * recommendation from
12944 				 * draft-floyd-incr-init-win-01.txt,
12945 				 * Increasing TCP's Initial Window.
12946 				 */
12947 				tcp->tcp_cwnd = tcp->tcp_mss;
12948 			}
12949 
12950 			tcp->tcp_swl1 = seg_seq;
12951 			tcp->tcp_swl2 = seg_ack;
12952 
12953 			new_swnd = BE16_TO_U16(tcph->th_win);
12954 			tcp->tcp_swnd = new_swnd;
12955 			if (new_swnd > tcp->tcp_max_swnd)
12956 				tcp->tcp_max_swnd = new_swnd;
12957 
12958 			/*
12959 			 * Always send the three-way handshake ack immediately
12960 			 * in order to make the connection complete as soon as
12961 			 * possible on the accepting host.
12962 			 */
12963 			flags |= TH_ACK_NEEDED;
12964 
12965 			/*
12966 			 * Special case for loopback.  At this point we have
12967 			 * received SYN-ACK from the remote endpoint.  In
12968 			 * order to ensure that both endpoints reach the
12969 			 * fused state prior to any data exchange, the final
12970 			 * ACK needs to be sent before we indicate T_CONN_CON
12971 			 * to the module upstream.
12972 			 */
12973 			if (tcp->tcp_loopback) {
12974 				mblk_t *ack_mp;
12975 
12976 				ASSERT(!tcp->tcp_unfusable);
12977 				ASSERT(mp1 != NULL);
12978 				/*
12979 				 * For loopback, we always get a pure SYN-ACK
12980 				 * and only need to send back the final ACK
12981 				 * with no data (this is because the other
12982 				 * tcp is ours and we don't do T/TCP).  This
12983 				 * final ACK triggers the passive side to
12984 				 * perform fusion in ESTABLISHED state.
12985 				 */
12986 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12987 					if (tcp->tcp_ack_tid != 0) {
12988 						(void) TCP_TIMER_CANCEL(tcp,
12989 						    tcp->tcp_ack_tid);
12990 						tcp->tcp_ack_tid = 0;
12991 					}
12992 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
12993 					BUMP_LOCAL(tcp->tcp_obsegs);
12994 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
12995 
12996 					if (!IPCL_IS_NONSTR(connp)) {
12997 						/* Send up T_CONN_CON */
12998 						putnext(tcp->tcp_rq, mp1);
12999 					} else {
13000 						cred_t	*cr;
13001 						pid_t	cpid;
13002 
13003 						cr = msg_getcred(mp1, &cpid);
13004 						(*connp->conn_upcalls->
13005 						    su_connected)
13006 						    (connp->conn_upper_handle,
13007 						    tcp->tcp_connid, cr, cpid);
13008 						freemsg(mp1);
13009 					}
13010 
13011 					freemsg(mp);
13012 					return;
13013 				}
13014 				/*
13015 				 * Forget fusion; we need to handle more
13016 				 * complex cases below.  Send the deferred
13017 				 * T_CONN_CON message upstream and proceed
13018 				 * as usual.  Mark this tcp as not capable
13019 				 * of fusion.
13020 				 */
13021 				TCP_STAT(tcps, tcp_fusion_unfusable);
13022 				tcp->tcp_unfusable = B_TRUE;
13023 				if (!IPCL_IS_NONSTR(connp)) {
13024 					putnext(tcp->tcp_rq, mp1);
13025 				} else {
13026 					cred_t	*cr;
13027 					pid_t	cpid;
13028 
13029 					cr = msg_getcred(mp1, &cpid);
13030 					(*connp->conn_upcalls->su_connected)
13031 					    (connp->conn_upper_handle,
13032 					    tcp->tcp_connid, cr, cpid);
13033 					freemsg(mp1);
13034 				}
13035 			}
13036 
13037 			/*
13038 			 * Check to see if there is data to be sent.  If
13039 			 * yes, set the transmit flag.  Then check to see
13040 			 * if received data processing needs to be done.
13041 			 * If not, go straight to xmit_check.  This short
13042 			 * cut is OK as we don't support T/TCP.
13043 			 */
13044 			if (tcp->tcp_unsent)
13045 				flags |= TH_XMIT_NEEDED;
13046 
13047 			if (seg_len == 0 && !(flags & TH_URG)) {
13048 				freemsg(mp);
13049 				goto xmit_check;
13050 			}
13051 
13052 			flags &= ~TH_SYN;
13053 			seg_seq++;
13054 			break;
13055 		}
13056 		tcp->tcp_state = TCPS_SYN_RCVD;
13057 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13058 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13059 		if (mp1) {
13060 			/*
13061 			 * See comment in tcp_conn_request() for why we use
13062 			 * the open() time pid here.
13063 			 */
13064 			DB_CPID(mp1) = tcp->tcp_cpid;
13065 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13066 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13067 		}
13068 		freemsg(mp);
13069 		return;
13070 	case TCPS_SYN_RCVD:
13071 		if (flags & TH_ACK) {
13072 			/*
13073 			 * In this state, a SYN|ACK packet is either bogus
13074 			 * because the other side must be ACKing our SYN which
13075 			 * indicates it has seen the ACK for their SYN and
13076 			 * shouldn't retransmit it or we're crossing SYNs
13077 			 * on active open.
13078 			 */
13079 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13080 				freemsg(mp);
13081 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13082 				    tcp, seg_ack, 0, TH_RST);
13083 				return;
13084 			}
13085 			/*
13086 			 * NOTE: RFC 793 pg. 72 says this should be
13087 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13088 			 * but that would mean we have an ack that ignored
13089 			 * our SYN.
13090 			 */
13091 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13092 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13093 				freemsg(mp);
13094 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13095 				    tcp, seg_ack, 0, TH_RST);
13096 				return;
13097 			}
13098 		}
13099 		break;
13100 	case TCPS_LISTEN:
13101 		/*
13102 		 * Only a TLI listener can come through this path when a
13103 		 * acceptor is going back to be a listener and a packet
13104 		 * for the acceptor hits the classifier. For a socket
13105 		 * listener, this can never happen because a listener
13106 		 * can never accept connection on itself and hence a
13107 		 * socket acceptor can not go back to being a listener.
13108 		 */
13109 		ASSERT(!TCP_IS_SOCKET(tcp));
13110 		/*FALLTHRU*/
13111 	case TCPS_CLOSED:
13112 	case TCPS_BOUND: {
13113 		conn_t	*new_connp;
13114 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13115 
13116 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13117 		if (new_connp != NULL) {
13118 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13119 			return;
13120 		}
13121 		/* We failed to classify. For now just drop the packet */
13122 		freemsg(mp);
13123 		return;
13124 	}
13125 	case TCPS_IDLE:
13126 		/*
13127 		 * Handle the case where the tcp_clean_death() has happened
13128 		 * on a connection (application hasn't closed yet) but a packet
13129 		 * was already queued on squeue before tcp_clean_death()
13130 		 * was processed. Calling tcp_clean_death() twice on same
13131 		 * connection can result in weird behaviour.
13132 		 */
13133 		freemsg(mp);
13134 		return;
13135 	default:
13136 		break;
13137 	}
13138 
13139 	/*
13140 	 * Already on the correct queue/perimeter.
13141 	 * If this is a detached connection and not an eager
13142 	 * connection hanging off a listener then new data
13143 	 * (past the FIN) will cause a reset.
13144 	 * We do a special check here where it
13145 	 * is out of the main line, rather than check
13146 	 * if we are detached every time we see new
13147 	 * data down below.
13148 	 */
13149 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13150 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13151 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13152 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13153 
13154 		freemsg(mp);
13155 		/*
13156 		 * This could be an SSL closure alert. We're detached so just
13157 		 * acknowledge it this last time.
13158 		 */
13159 		if (tcp->tcp_kssl_ctx != NULL) {
13160 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13161 			tcp->tcp_kssl_ctx = NULL;
13162 
13163 			tcp->tcp_rnxt += seg_len;
13164 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13165 			flags |= TH_ACK_NEEDED;
13166 			goto ack_check;
13167 		}
13168 
13169 		tcp_xmit_ctl("new data when detached", tcp,
13170 		    tcp->tcp_snxt, 0, TH_RST);
13171 		(void) tcp_clean_death(tcp, EPROTO, 12);
13172 		return;
13173 	}
13174 
13175 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13176 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13177 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13178 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13179 
13180 	if (tcp->tcp_snd_ts_ok) {
13181 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13182 			/*
13183 			 * This segment is not acceptable.
13184 			 * Drop it and send back an ACK.
13185 			 */
13186 			freemsg(mp);
13187 			flags |= TH_ACK_NEEDED;
13188 			goto ack_check;
13189 		}
13190 	} else if (tcp->tcp_snd_sack_ok) {
13191 		ASSERT(tcp->tcp_sack_info != NULL);
13192 		tcpopt.tcp = tcp;
13193 		/*
13194 		 * SACK info in already updated in tcp_parse_options.  Ignore
13195 		 * all other TCP options...
13196 		 */
13197 		(void) tcp_parse_options(tcph, &tcpopt);
13198 	}
13199 try_again:;
13200 	mss = tcp->tcp_mss;
13201 	gap = seg_seq - tcp->tcp_rnxt;
13202 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13203 	/*
13204 	 * gap is the amount of sequence space between what we expect to see
13205 	 * and what we got for seg_seq.  A positive value for gap means
13206 	 * something got lost.  A negative value means we got some old stuff.
13207 	 */
13208 	if (gap < 0) {
13209 		/* Old stuff present.  Is the SYN in there? */
13210 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13211 		    (seg_len != 0)) {
13212 			flags &= ~TH_SYN;
13213 			seg_seq++;
13214 			urp--;
13215 			/* Recompute the gaps after noting the SYN. */
13216 			goto try_again;
13217 		}
13218 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13219 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13220 		    (seg_len > -gap ? -gap : seg_len));
13221 		/* Remove the old stuff from seg_len. */
13222 		seg_len += gap;
13223 		/*
13224 		 * Anything left?
13225 		 * Make sure to check for unack'd FIN when rest of data
13226 		 * has been previously ack'd.
13227 		 */
13228 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13229 			/*
13230 			 * Resets are only valid if they lie within our offered
13231 			 * window.  If the RST bit is set, we just ignore this
13232 			 * segment.
13233 			 */
13234 			if (flags & TH_RST) {
13235 				freemsg(mp);
13236 				return;
13237 			}
13238 
13239 			/*
13240 			 * The arriving of dup data packets indicate that we
13241 			 * may have postponed an ack for too long, or the other
13242 			 * side's RTT estimate is out of shape. Start acking
13243 			 * more often.
13244 			 */
13245 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13246 			    tcp->tcp_rack_cnt >= 1 &&
13247 			    tcp->tcp_rack_abs_max > 2) {
13248 				tcp->tcp_rack_abs_max--;
13249 			}
13250 			tcp->tcp_rack_cur_max = 1;
13251 
13252 			/*
13253 			 * This segment is "unacceptable".  None of its
13254 			 * sequence space lies within our advertized window.
13255 			 *
13256 			 * Adjust seg_len to the original value for tracing.
13257 			 */
13258 			seg_len -= gap;
13259 			if (tcp->tcp_debug) {
13260 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13261 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13262 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13263 				    "seg_len %d, rnxt %u, snxt %u, %s",
13264 				    gap, rgap, flags, seg_seq, seg_ack,
13265 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13266 				    tcp_display(tcp, NULL,
13267 				    DISP_ADDR_AND_PORT));
13268 			}
13269 
13270 			/*
13271 			 * Arrange to send an ACK in response to the
13272 			 * unacceptable segment per RFC 793 page 69. There
13273 			 * is only one small difference between ours and the
13274 			 * acceptability test in the RFC - we accept ACK-only
13275 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13276 			 * will be generated.
13277 			 *
13278 			 * Note that we have to ACK an ACK-only packet at least
13279 			 * for stacks that send 0-length keep-alives with
13280 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13281 			 * section 4.2.3.6. As long as we don't ever generate
13282 			 * an unacceptable packet in response to an incoming
13283 			 * packet that is unacceptable, it should not cause
13284 			 * "ACK wars".
13285 			 */
13286 			flags |=  TH_ACK_NEEDED;
13287 
13288 			/*
13289 			 * Continue processing this segment in order to use the
13290 			 * ACK information it contains, but skip all other
13291 			 * sequence-number processing.	Processing the ACK
13292 			 * information is necessary in order to
13293 			 * re-synchronize connections that may have lost
13294 			 * synchronization.
13295 			 *
13296 			 * We clear seg_len and flag fields related to
13297 			 * sequence number processing as they are not
13298 			 * to be trusted for an unacceptable segment.
13299 			 */
13300 			seg_len = 0;
13301 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13302 			goto process_ack;
13303 		}
13304 
13305 		/* Fix seg_seq, and chew the gap off the front. */
13306 		seg_seq = tcp->tcp_rnxt;
13307 		urp += gap;
13308 		do {
13309 			mblk_t	*mp2;
13310 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13311 			    (uintptr_t)UINT_MAX);
13312 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13313 			if (gap > 0) {
13314 				mp->b_rptr = mp->b_wptr - gap;
13315 				break;
13316 			}
13317 			mp2 = mp;
13318 			mp = mp->b_cont;
13319 			freeb(mp2);
13320 		} while (gap < 0);
13321 		/*
13322 		 * If the urgent data has already been acknowledged, we
13323 		 * should ignore TH_URG below
13324 		 */
13325 		if (urp < 0)
13326 			flags &= ~TH_URG;
13327 	}
13328 	/*
13329 	 * rgap is the amount of stuff received out of window.  A negative
13330 	 * value is the amount out of window.
13331 	 */
13332 	if (rgap < 0) {
13333 		mblk_t	*mp2;
13334 
13335 		if (tcp->tcp_rwnd == 0) {
13336 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13337 		} else {
13338 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13339 			UPDATE_MIB(&tcps->tcps_mib,
13340 			    tcpInDataPastWinBytes, -rgap);
13341 		}
13342 
13343 		/*
13344 		 * seg_len does not include the FIN, so if more than
13345 		 * just the FIN is out of window, we act like we don't
13346 		 * see it.  (If just the FIN is out of window, rgap
13347 		 * will be zero and we will go ahead and acknowledge
13348 		 * the FIN.)
13349 		 */
13350 		flags &= ~TH_FIN;
13351 
13352 		/* Fix seg_len and make sure there is something left. */
13353 		seg_len += rgap;
13354 		if (seg_len <= 0) {
13355 			/*
13356 			 * Resets are only valid if they lie within our offered
13357 			 * window.  If the RST bit is set, we just ignore this
13358 			 * segment.
13359 			 */
13360 			if (flags & TH_RST) {
13361 				freemsg(mp);
13362 				return;
13363 			}
13364 
13365 			/* Per RFC 793, we need to send back an ACK. */
13366 			flags |= TH_ACK_NEEDED;
13367 
13368 			/*
13369 			 * Send SIGURG as soon as possible i.e. even
13370 			 * if the TH_URG was delivered in a window probe
13371 			 * packet (which will be unacceptable).
13372 			 *
13373 			 * We generate a signal if none has been generated
13374 			 * for this connection or if this is a new urgent
13375 			 * byte. Also send a zero-length "unmarked" message
13376 			 * to inform SIOCATMARK that this is not the mark.
13377 			 *
13378 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13379 			 * is sent up. This plus the check for old data
13380 			 * (gap >= 0) handles the wraparound of the sequence
13381 			 * number space without having to always track the
13382 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13383 			 * this max in its rcv_up variable).
13384 			 *
13385 			 * This prevents duplicate SIGURGS due to a "late"
13386 			 * zero-window probe when the T_EXDATA_IND has already
13387 			 * been sent up.
13388 			 */
13389 			if ((flags & TH_URG) &&
13390 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13391 			    tcp->tcp_urp_last))) {
13392 				if (IPCL_IS_NONSTR(connp)) {
13393 					if (!TCP_IS_DETACHED(tcp)) {
13394 						(*connp->conn_upcalls->
13395 						    su_signal_oob)
13396 						    (connp->conn_upper_handle,
13397 						    urp);
13398 					}
13399 				} else {
13400 					mp1 = allocb(0, BPRI_MED);
13401 					if (mp1 == NULL) {
13402 						freemsg(mp);
13403 						return;
13404 					}
13405 					if (!TCP_IS_DETACHED(tcp) &&
13406 					    !putnextctl1(tcp->tcp_rq,
13407 					    M_PCSIG, SIGURG)) {
13408 						/* Try again on the rexmit. */
13409 						freemsg(mp1);
13410 						freemsg(mp);
13411 						return;
13412 					}
13413 					/*
13414 					 * If the next byte would be the mark
13415 					 * then mark with MARKNEXT else mark
13416 					 * with NOTMARKNEXT.
13417 					 */
13418 					if (gap == 0 && urp == 0)
13419 						mp1->b_flag |= MSGMARKNEXT;
13420 					else
13421 						mp1->b_flag |= MSGNOTMARKNEXT;
13422 					freemsg(tcp->tcp_urp_mark_mp);
13423 					tcp->tcp_urp_mark_mp = mp1;
13424 					flags |= TH_SEND_URP_MARK;
13425 				}
13426 				tcp->tcp_urp_last_valid = B_TRUE;
13427 				tcp->tcp_urp_last = urp + seg_seq;
13428 			}
13429 			/*
13430 			 * If this is a zero window probe, continue to
13431 			 * process the ACK part.  But we need to set seg_len
13432 			 * to 0 to avoid data processing.  Otherwise just
13433 			 * drop the segment and send back an ACK.
13434 			 */
13435 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13436 				flags &= ~(TH_SYN | TH_URG);
13437 				seg_len = 0;
13438 				goto process_ack;
13439 			} else {
13440 				freemsg(mp);
13441 				goto ack_check;
13442 			}
13443 		}
13444 		/* Pitch out of window stuff off the end. */
13445 		rgap = seg_len;
13446 		mp2 = mp;
13447 		do {
13448 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13449 			    (uintptr_t)INT_MAX);
13450 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13451 			if (rgap < 0) {
13452 				mp2->b_wptr += rgap;
13453 				if ((mp1 = mp2->b_cont) != NULL) {
13454 					mp2->b_cont = NULL;
13455 					freemsg(mp1);
13456 				}
13457 				break;
13458 			}
13459 		} while ((mp2 = mp2->b_cont) != NULL);
13460 	}
13461 ok:;
13462 	/*
13463 	 * TCP should check ECN info for segments inside the window only.
13464 	 * Therefore the check should be done here.
13465 	 */
13466 	if (tcp->tcp_ecn_ok) {
13467 		if (flags & TH_CWR) {
13468 			tcp->tcp_ecn_echo_on = B_FALSE;
13469 		}
13470 		/*
13471 		 * Note that both ECN_CE and CWR can be set in the
13472 		 * same segment.  In this case, we once again turn
13473 		 * on ECN_ECHO.
13474 		 */
13475 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13476 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13477 
13478 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13479 				tcp->tcp_ecn_echo_on = B_TRUE;
13480 			}
13481 		} else {
13482 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13483 
13484 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13485 			    htonl(IPH_ECN_CE << 20)) {
13486 				tcp->tcp_ecn_echo_on = B_TRUE;
13487 			}
13488 		}
13489 	}
13490 
13491 	/*
13492 	 * Check whether we can update tcp_ts_recent.  This test is
13493 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13494 	 * Extensions for High Performance: An Update", Internet Draft.
13495 	 */
13496 	if (tcp->tcp_snd_ts_ok &&
13497 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13498 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13499 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13500 		tcp->tcp_last_rcv_lbolt = lbolt64;
13501 	}
13502 
13503 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13504 		/*
13505 		 * FIN in an out of order segment.  We record this in
13506 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13507 		 * Clear the FIN so that any check on FIN flag will fail.
13508 		 * Remember that FIN also counts in the sequence number
13509 		 * space.  So we need to ack out of order FIN only segments.
13510 		 */
13511 		if (flags & TH_FIN) {
13512 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13513 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13514 			flags &= ~TH_FIN;
13515 			flags |= TH_ACK_NEEDED;
13516 		}
13517 		if (seg_len > 0) {
13518 			/* Fill in the SACK blk list. */
13519 			if (tcp->tcp_snd_sack_ok) {
13520 				ASSERT(tcp->tcp_sack_info != NULL);
13521 				tcp_sack_insert(tcp->tcp_sack_list,
13522 				    seg_seq, seg_seq + seg_len,
13523 				    &(tcp->tcp_num_sack_blk));
13524 			}
13525 
13526 			/*
13527 			 * Attempt reassembly and see if we have something
13528 			 * ready to go.
13529 			 */
13530 			mp = tcp_reass(tcp, mp, seg_seq);
13531 			/* Always ack out of order packets */
13532 			flags |= TH_ACK_NEEDED | TH_PUSH;
13533 			if (mp) {
13534 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13535 				    (uintptr_t)INT_MAX);
13536 				seg_len = mp->b_cont ? msgdsize(mp) :
13537 				    (int)(mp->b_wptr - mp->b_rptr);
13538 				seg_seq = tcp->tcp_rnxt;
13539 				/*
13540 				 * A gap is filled and the seq num and len
13541 				 * of the gap match that of a previously
13542 				 * received FIN, put the FIN flag back in.
13543 				 */
13544 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13545 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13546 					flags |= TH_FIN;
13547 					tcp->tcp_valid_bits &=
13548 					    ~TCP_OFO_FIN_VALID;
13549 				}
13550 			} else {
13551 				/*
13552 				 * Keep going even with NULL mp.
13553 				 * There may be a useful ACK or something else
13554 				 * we don't want to miss.
13555 				 *
13556 				 * But TCP should not perform fast retransmit
13557 				 * because of the ack number.  TCP uses
13558 				 * seg_len == 0 to determine if it is a pure
13559 				 * ACK.  And this is not a pure ACK.
13560 				 */
13561 				seg_len = 0;
13562 				ofo_seg = B_TRUE;
13563 			}
13564 		}
13565 	} else if (seg_len > 0) {
13566 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13567 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13568 		/*
13569 		 * If an out of order FIN was received before, and the seq
13570 		 * num and len of the new segment match that of the FIN,
13571 		 * put the FIN flag back in.
13572 		 */
13573 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13574 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13575 			flags |= TH_FIN;
13576 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13577 		}
13578 	}
13579 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13580 	if (flags & TH_RST) {
13581 		freemsg(mp);
13582 		switch (tcp->tcp_state) {
13583 		case TCPS_SYN_RCVD:
13584 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13585 			break;
13586 		case TCPS_ESTABLISHED:
13587 		case TCPS_FIN_WAIT_1:
13588 		case TCPS_FIN_WAIT_2:
13589 		case TCPS_CLOSE_WAIT:
13590 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13591 			break;
13592 		case TCPS_CLOSING:
13593 		case TCPS_LAST_ACK:
13594 			(void) tcp_clean_death(tcp, 0, 16);
13595 			break;
13596 		default:
13597 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13598 			(void) tcp_clean_death(tcp, ENXIO, 17);
13599 			break;
13600 		}
13601 		return;
13602 	}
13603 	if (flags & TH_SYN) {
13604 		/*
13605 		 * See RFC 793, Page 71
13606 		 *
13607 		 * The seq number must be in the window as it should
13608 		 * be "fixed" above.  If it is outside window, it should
13609 		 * be already rejected.  Note that we allow seg_seq to be
13610 		 * rnxt + rwnd because we want to accept 0 window probe.
13611 		 */
13612 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13613 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13614 		freemsg(mp);
13615 		/*
13616 		 * If the ACK flag is not set, just use our snxt as the
13617 		 * seq number of the RST segment.
13618 		 */
13619 		if (!(flags & TH_ACK)) {
13620 			seg_ack = tcp->tcp_snxt;
13621 		}
13622 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13623 		    TH_RST|TH_ACK);
13624 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13625 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13626 		return;
13627 	}
13628 	/*
13629 	 * urp could be -1 when the urp field in the packet is 0
13630 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13631 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13632 	 */
13633 	if (flags & TH_URG && urp >= 0) {
13634 		if (!tcp->tcp_urp_last_valid ||
13635 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13636 			if (IPCL_IS_NONSTR(connp)) {
13637 				if (!TCP_IS_DETACHED(tcp)) {
13638 					(*connp->conn_upcalls->su_signal_oob)
13639 					    (connp->conn_upper_handle, urp);
13640 				}
13641 			} else {
13642 				/*
13643 				 * If we haven't generated the signal yet for
13644 				 * this urgent pointer value, do it now.  Also,
13645 				 * send up a zero-length M_DATA indicating
13646 				 * whether or not this is the mark. The latter
13647 				 * is not needed when a T_EXDATA_IND is sent up.
13648 				 * However, if there are allocation failures
13649 				 * this code relies on the sender retransmitting
13650 				 * and the socket code for determining the mark
13651 				 * should not block waiting for the peer to
13652 				 * transmit. Thus, for simplicity we always
13653 				 * send up the mark indication.
13654 				 */
13655 				mp1 = allocb(0, BPRI_MED);
13656 				if (mp1 == NULL) {
13657 					freemsg(mp);
13658 					return;
13659 				}
13660 				if (!TCP_IS_DETACHED(tcp) &&
13661 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13662 				    SIGURG)) {
13663 					/* Try again on the rexmit. */
13664 					freemsg(mp1);
13665 					freemsg(mp);
13666 					return;
13667 				}
13668 				/*
13669 				 * Mark with NOTMARKNEXT for now.
13670 				 * The code below will change this to MARKNEXT
13671 				 * if we are at the mark.
13672 				 *
13673 				 * If there are allocation failures (e.g. in
13674 				 * dupmsg below) the next time tcp_rput_data
13675 				 * sees the urgent segment it will send up the
13676 				 * MSGMARKNEXT message.
13677 				 */
13678 				mp1->b_flag |= MSGNOTMARKNEXT;
13679 				freemsg(tcp->tcp_urp_mark_mp);
13680 				tcp->tcp_urp_mark_mp = mp1;
13681 				flags |= TH_SEND_URP_MARK;
13682 #ifdef DEBUG
13683 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13684 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13685 				    "last %x, %s",
13686 				    seg_seq, urp, tcp->tcp_urp_last,
13687 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13688 #endif /* DEBUG */
13689 			}
13690 			tcp->tcp_urp_last_valid = B_TRUE;
13691 			tcp->tcp_urp_last = urp + seg_seq;
13692 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13693 			/*
13694 			 * An allocation failure prevented the previous
13695 			 * tcp_rput_data from sending up the allocated
13696 			 * MSG*MARKNEXT message - send it up this time
13697 			 * around.
13698 			 */
13699 			flags |= TH_SEND_URP_MARK;
13700 		}
13701 
13702 		/*
13703 		 * If the urgent byte is in this segment, make sure that it is
13704 		 * all by itself.  This makes it much easier to deal with the
13705 		 * possibility of an allocation failure on the T_exdata_ind.
13706 		 * Note that seg_len is the number of bytes in the segment, and
13707 		 * urp is the offset into the segment of the urgent byte.
13708 		 * urp < seg_len means that the urgent byte is in this segment.
13709 		 */
13710 		if (urp < seg_len) {
13711 			if (seg_len != 1) {
13712 				uint32_t  tmp_rnxt;
13713 				/*
13714 				 * Break it up and feed it back in.
13715 				 * Re-attach the IP header.
13716 				 */
13717 				mp->b_rptr = iphdr;
13718 				if (urp > 0) {
13719 					/*
13720 					 * There is stuff before the urgent
13721 					 * byte.
13722 					 */
13723 					mp1 = dupmsg(mp);
13724 					if (!mp1) {
13725 						/*
13726 						 * Trim from urgent byte on.
13727 						 * The rest will come back.
13728 						 */
13729 						(void) adjmsg(mp,
13730 						    urp - seg_len);
13731 						tcp_rput_data(connp,
13732 						    mp, NULL);
13733 						return;
13734 					}
13735 					(void) adjmsg(mp1, urp - seg_len);
13736 					/* Feed this piece back in. */
13737 					tmp_rnxt = tcp->tcp_rnxt;
13738 					tcp_rput_data(connp, mp1, NULL);
13739 					/*
13740 					 * If the data passed back in was not
13741 					 * processed (ie: bad ACK) sending
13742 					 * the remainder back in will cause a
13743 					 * loop. In this case, drop the
13744 					 * packet and let the sender try
13745 					 * sending a good packet.
13746 					 */
13747 					if (tmp_rnxt == tcp->tcp_rnxt) {
13748 						freemsg(mp);
13749 						return;
13750 					}
13751 				}
13752 				if (urp != seg_len - 1) {
13753 					uint32_t  tmp_rnxt;
13754 					/*
13755 					 * There is stuff after the urgent
13756 					 * byte.
13757 					 */
13758 					mp1 = dupmsg(mp);
13759 					if (!mp1) {
13760 						/*
13761 						 * Trim everything beyond the
13762 						 * urgent byte.  The rest will
13763 						 * come back.
13764 						 */
13765 						(void) adjmsg(mp,
13766 						    urp + 1 - seg_len);
13767 						tcp_rput_data(connp,
13768 						    mp, NULL);
13769 						return;
13770 					}
13771 					(void) adjmsg(mp1, urp + 1 - seg_len);
13772 					tmp_rnxt = tcp->tcp_rnxt;
13773 					tcp_rput_data(connp, mp1, NULL);
13774 					/*
13775 					 * If the data passed back in was not
13776 					 * processed (ie: bad ACK) sending
13777 					 * the remainder back in will cause a
13778 					 * loop. In this case, drop the
13779 					 * packet and let the sender try
13780 					 * sending a good packet.
13781 					 */
13782 					if (tmp_rnxt == tcp->tcp_rnxt) {
13783 						freemsg(mp);
13784 						return;
13785 					}
13786 				}
13787 				tcp_rput_data(connp, mp, NULL);
13788 				return;
13789 			}
13790 			/*
13791 			 * This segment contains only the urgent byte.  We
13792 			 * have to allocate the T_exdata_ind, if we can.
13793 			 */
13794 			if (IPCL_IS_NONSTR(connp)) {
13795 				int error;
13796 
13797 				(*connp->conn_upcalls->su_recv)
13798 				    (connp->conn_upper_handle, mp, seg_len,
13799 				    MSG_OOB, &error, NULL);
13800 				/*
13801 				 * We should never be in middle of a
13802 				 * fallback, the squeue guarantees that.
13803 				 */
13804 				ASSERT(error != EOPNOTSUPP);
13805 				mp = NULL;
13806 				goto update_ack;
13807 			} else if (!tcp->tcp_urp_mp) {
13808 				struct T_exdata_ind *tei;
13809 				mp1 = allocb(sizeof (struct T_exdata_ind),
13810 				    BPRI_MED);
13811 				if (!mp1) {
13812 					/*
13813 					 * Sigh... It'll be back.
13814 					 * Generate any MSG*MARK message now.
13815 					 */
13816 					freemsg(mp);
13817 					seg_len = 0;
13818 					if (flags & TH_SEND_URP_MARK) {
13819 
13820 
13821 						ASSERT(tcp->tcp_urp_mark_mp);
13822 						tcp->tcp_urp_mark_mp->b_flag &=
13823 						    ~MSGNOTMARKNEXT;
13824 						tcp->tcp_urp_mark_mp->b_flag |=
13825 						    MSGMARKNEXT;
13826 					}
13827 					goto ack_check;
13828 				}
13829 				mp1->b_datap->db_type = M_PROTO;
13830 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13831 				tei->PRIM_type = T_EXDATA_IND;
13832 				tei->MORE_flag = 0;
13833 				mp1->b_wptr = (uchar_t *)&tei[1];
13834 				tcp->tcp_urp_mp = mp1;
13835 #ifdef DEBUG
13836 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13837 				    "tcp_rput: allocated exdata_ind %s",
13838 				    tcp_display(tcp, NULL,
13839 				    DISP_PORT_ONLY));
13840 #endif /* DEBUG */
13841 				/*
13842 				 * There is no need to send a separate MSG*MARK
13843 				 * message since the T_EXDATA_IND will be sent
13844 				 * now.
13845 				 */
13846 				flags &= ~TH_SEND_URP_MARK;
13847 				freemsg(tcp->tcp_urp_mark_mp);
13848 				tcp->tcp_urp_mark_mp = NULL;
13849 			}
13850 			/*
13851 			 * Now we are all set.  On the next putnext upstream,
13852 			 * tcp_urp_mp will be non-NULL and will get prepended
13853 			 * to what has to be this piece containing the urgent
13854 			 * byte.  If for any reason we abort this segment below,
13855 			 * if it comes back, we will have this ready, or it
13856 			 * will get blown off in close.
13857 			 */
13858 		} else if (urp == seg_len) {
13859 			/*
13860 			 * The urgent byte is the next byte after this sequence
13861 			 * number. If there is data it is marked with
13862 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13863 			 * since it is not needed. Otherwise, if the code
13864 			 * above just allocated a zero-length tcp_urp_mark_mp
13865 			 * message, that message is tagged with MSGMARKNEXT.
13866 			 * Sending up these MSGMARKNEXT messages makes
13867 			 * SIOCATMARK work correctly even though
13868 			 * the T_EXDATA_IND will not be sent up until the
13869 			 * urgent byte arrives.
13870 			 */
13871 			if (seg_len != 0) {
13872 				flags |= TH_MARKNEXT_NEEDED;
13873 				freemsg(tcp->tcp_urp_mark_mp);
13874 				tcp->tcp_urp_mark_mp = NULL;
13875 				flags &= ~TH_SEND_URP_MARK;
13876 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13877 				flags |= TH_SEND_URP_MARK;
13878 				tcp->tcp_urp_mark_mp->b_flag &=
13879 				    ~MSGNOTMARKNEXT;
13880 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13881 			}
13882 #ifdef DEBUG
13883 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13884 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13885 			    seg_len, flags,
13886 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13887 #endif /* DEBUG */
13888 		}
13889 #ifdef DEBUG
13890 		else {
13891 			/* Data left until we hit mark */
13892 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13893 			    "tcp_rput: URP %d bytes left, %s",
13894 			    urp - seg_len, tcp_display(tcp, NULL,
13895 			    DISP_PORT_ONLY));
13896 		}
13897 #endif /* DEBUG */
13898 	}
13899 
13900 process_ack:
13901 	if (!(flags & TH_ACK)) {
13902 		freemsg(mp);
13903 		goto xmit_check;
13904 	}
13905 	}
13906 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13907 
13908 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13909 		tcp->tcp_ip_forward_progress = B_TRUE;
13910 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13911 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13912 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13913 			/* 3-way handshake complete - pass up the T_CONN_IND */
13914 			tcp_t	*listener = tcp->tcp_listener;
13915 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13916 
13917 			tcp->tcp_tconnind_started = B_TRUE;
13918 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13919 			/*
13920 			 * We are here means eager is fine but it can
13921 			 * get a TH_RST at any point between now and till
13922 			 * accept completes and disappear. We need to
13923 			 * ensure that reference to eager is valid after
13924 			 * we get out of eager's perimeter. So we do
13925 			 * an extra refhold.
13926 			 */
13927 			CONN_INC_REF(connp);
13928 
13929 			/*
13930 			 * The listener also exists because of the refhold
13931 			 * done in tcp_conn_request. Its possible that it
13932 			 * might have closed. We will check that once we
13933 			 * get inside listeners context.
13934 			 */
13935 			CONN_INC_REF(listener->tcp_connp);
13936 			if (listener->tcp_connp->conn_sqp ==
13937 			    connp->conn_sqp) {
13938 				/*
13939 				 * We optimize by not calling an SQUEUE_ENTER
13940 				 * on the listener since we know that the
13941 				 * listener and eager squeues are the same.
13942 				 * We are able to make this check safely only
13943 				 * because neither the eager nor the listener
13944 				 * can change its squeue. Only an active connect
13945 				 * can change its squeue
13946 				 */
13947 				tcp_send_conn_ind(listener->tcp_connp, mp,
13948 				    listener->tcp_connp->conn_sqp);
13949 				CONN_DEC_REF(listener->tcp_connp);
13950 			} else if (!tcp->tcp_loopback) {
13951 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
13952 				    mp, tcp_send_conn_ind,
13953 				    listener->tcp_connp, SQ_FILL,
13954 				    SQTAG_TCP_CONN_IND);
13955 			} else {
13956 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
13957 				    mp, tcp_send_conn_ind,
13958 				    listener->tcp_connp, SQ_PROCESS,
13959 				    SQTAG_TCP_CONN_IND);
13960 			}
13961 		}
13962 
13963 		/*
13964 		 * We are seeing the final ack in the three way
13965 		 * hand shake of a active open'ed connection
13966 		 * so we must send up a T_CONN_CON
13967 		 *
13968 		 * tcp_sendmsg() checks tcp_state without entering
13969 		 * the squeue so tcp_state should be updated before
13970 		 * sending up connection confirmation.
13971 		 */
13972 		tcp->tcp_state = TCPS_ESTABLISHED;
13973 		if (tcp->tcp_active_open) {
13974 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13975 				freemsg(mp);
13976 				tcp->tcp_state = TCPS_SYN_RCVD;
13977 				return;
13978 			}
13979 			/*
13980 			 * Don't fuse the loopback endpoints for
13981 			 * simultaneous active opens.
13982 			 */
13983 			if (tcp->tcp_loopback) {
13984 				TCP_STAT(tcps, tcp_fusion_unfusable);
13985 				tcp->tcp_unfusable = B_TRUE;
13986 			}
13987 		}
13988 
13989 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
13990 		bytes_acked--;
13991 		/* SYN was acked - making progress */
13992 		if (tcp->tcp_ipversion == IPV6_VERSION)
13993 			tcp->tcp_ip_forward_progress = B_TRUE;
13994 
13995 		/*
13996 		 * If SYN was retransmitted, need to reset all
13997 		 * retransmission info as this segment will be
13998 		 * treated as a dup ACK.
13999 		 */
14000 		if (tcp->tcp_rexmit) {
14001 			tcp->tcp_rexmit = B_FALSE;
14002 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14003 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14004 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14005 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14006 			tcp->tcp_ms_we_have_waited = 0;
14007 			tcp->tcp_cwnd = mss;
14008 		}
14009 
14010 		/*
14011 		 * We set the send window to zero here.
14012 		 * This is needed if there is data to be
14013 		 * processed already on the queue.
14014 		 * Later (at swnd_update label), the
14015 		 * "new_swnd > tcp_swnd" condition is satisfied
14016 		 * the XMIT_NEEDED flag is set in the current
14017 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14018 		 * called if there is already data on queue in
14019 		 * this state.
14020 		 */
14021 		tcp->tcp_swnd = 0;
14022 
14023 		if (new_swnd > tcp->tcp_max_swnd)
14024 			tcp->tcp_max_swnd = new_swnd;
14025 		tcp->tcp_swl1 = seg_seq;
14026 		tcp->tcp_swl2 = seg_ack;
14027 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14028 
14029 		/* Fuse when both sides are in ESTABLISHED state */
14030 		if (tcp->tcp_loopback && do_tcp_fusion)
14031 			tcp_fuse(tcp, iphdr, tcph);
14032 
14033 	}
14034 	/* This code follows 4.4BSD-Lite2 mostly. */
14035 	if (bytes_acked < 0)
14036 		goto est;
14037 
14038 	/*
14039 	 * If TCP is ECN capable and the congestion experience bit is
14040 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14041 	 * done once per window (or more loosely, per RTT).
14042 	 */
14043 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14044 		tcp->tcp_cwr = B_FALSE;
14045 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14046 		if (!tcp->tcp_cwr) {
14047 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14048 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14049 			tcp->tcp_cwnd = npkt * mss;
14050 			/*
14051 			 * If the cwnd is 0, use the timer to clock out
14052 			 * new segments.  This is required by the ECN spec.
14053 			 */
14054 			if (npkt == 0) {
14055 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14056 				/*
14057 				 * This makes sure that when the ACK comes
14058 				 * back, we will increase tcp_cwnd by 1 MSS.
14059 				 */
14060 				tcp->tcp_cwnd_cnt = 0;
14061 			}
14062 			tcp->tcp_cwr = B_TRUE;
14063 			/*
14064 			 * This marks the end of the current window of in
14065 			 * flight data.  That is why we don't use
14066 			 * tcp_suna + tcp_swnd.  Only data in flight can
14067 			 * provide ECN info.
14068 			 */
14069 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14070 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14071 		}
14072 	}
14073 
14074 	mp1 = tcp->tcp_xmit_head;
14075 	if (bytes_acked == 0) {
14076 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14077 			int dupack_cnt;
14078 
14079 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14080 			/*
14081 			 * Fast retransmit.  When we have seen exactly three
14082 			 * identical ACKs while we have unacked data
14083 			 * outstanding we take it as a hint that our peer
14084 			 * dropped something.
14085 			 *
14086 			 * If TCP is retransmitting, don't do fast retransmit.
14087 			 */
14088 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14089 			    ! tcp->tcp_rexmit) {
14090 				/* Do Limited Transmit */
14091 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14092 				    tcps->tcps_dupack_fast_retransmit) {
14093 					/*
14094 					 * RFC 3042
14095 					 *
14096 					 * What we need to do is temporarily
14097 					 * increase tcp_cwnd so that new
14098 					 * data can be sent if it is allowed
14099 					 * by the receive window (tcp_rwnd).
14100 					 * tcp_wput_data() will take care of
14101 					 * the rest.
14102 					 *
14103 					 * If the connection is SACK capable,
14104 					 * only do limited xmit when there
14105 					 * is SACK info.
14106 					 *
14107 					 * Note how tcp_cwnd is incremented.
14108 					 * The first dup ACK will increase
14109 					 * it by 1 MSS.  The second dup ACK
14110 					 * will increase it by 2 MSS.  This
14111 					 * means that only 1 new segment will
14112 					 * be sent for each dup ACK.
14113 					 */
14114 					if (tcp->tcp_unsent > 0 &&
14115 					    (!tcp->tcp_snd_sack_ok ||
14116 					    (tcp->tcp_snd_sack_ok &&
14117 					    tcp->tcp_notsack_list != NULL))) {
14118 						tcp->tcp_cwnd += mss <<
14119 						    (tcp->tcp_dupack_cnt - 1);
14120 						flags |= TH_LIMIT_XMIT;
14121 					}
14122 				} else if (dupack_cnt ==
14123 				    tcps->tcps_dupack_fast_retransmit) {
14124 
14125 				/*
14126 				 * If we have reduced tcp_ssthresh
14127 				 * because of ECN, do not reduce it again
14128 				 * unless it is already one window of data
14129 				 * away.  After one window of data, tcp_cwr
14130 				 * should then be cleared.  Note that
14131 				 * for non ECN capable connection, tcp_cwr
14132 				 * should always be false.
14133 				 *
14134 				 * Adjust cwnd since the duplicate
14135 				 * ack indicates that a packet was
14136 				 * dropped (due to congestion.)
14137 				 */
14138 				if (!tcp->tcp_cwr) {
14139 					npkt = ((tcp->tcp_snxt -
14140 					    tcp->tcp_suna) >> 1) / mss;
14141 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14142 					    mss;
14143 					tcp->tcp_cwnd = (npkt +
14144 					    tcp->tcp_dupack_cnt) * mss;
14145 				}
14146 				if (tcp->tcp_ecn_ok) {
14147 					tcp->tcp_cwr = B_TRUE;
14148 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14149 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14150 				}
14151 
14152 				/*
14153 				 * We do Hoe's algorithm.  Refer to her
14154 				 * paper "Improving the Start-up Behavior
14155 				 * of a Congestion Control Scheme for TCP,"
14156 				 * appeared in SIGCOMM'96.
14157 				 *
14158 				 * Save highest seq no we have sent so far.
14159 				 * Be careful about the invisible FIN byte.
14160 				 */
14161 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14162 				    (tcp->tcp_unsent == 0)) {
14163 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14164 				} else {
14165 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14166 				}
14167 
14168 				/*
14169 				 * Do not allow bursty traffic during.
14170 				 * fast recovery.  Refer to Fall and Floyd's
14171 				 * paper "Simulation-based Comparisons of
14172 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14173 				 * This is a best current practise.
14174 				 */
14175 				tcp->tcp_snd_burst = TCP_CWND_SS;
14176 
14177 				/*
14178 				 * For SACK:
14179 				 * Calculate tcp_pipe, which is the
14180 				 * estimated number of bytes in
14181 				 * network.
14182 				 *
14183 				 * tcp_fack is the highest sack'ed seq num
14184 				 * TCP has received.
14185 				 *
14186 				 * tcp_pipe is explained in the above quoted
14187 				 * Fall and Floyd's paper.  tcp_fack is
14188 				 * explained in Mathis and Mahdavi's
14189 				 * "Forward Acknowledgment: Refining TCP
14190 				 * Congestion Control" in SIGCOMM '96.
14191 				 */
14192 				if (tcp->tcp_snd_sack_ok) {
14193 					ASSERT(tcp->tcp_sack_info != NULL);
14194 					if (tcp->tcp_notsack_list != NULL) {
14195 						tcp->tcp_pipe = tcp->tcp_snxt -
14196 						    tcp->tcp_fack;
14197 						tcp->tcp_sack_snxt = seg_ack;
14198 						flags |= TH_NEED_SACK_REXMIT;
14199 					} else {
14200 						/*
14201 						 * Always initialize tcp_pipe
14202 						 * even though we don't have
14203 						 * any SACK info.  If later
14204 						 * we get SACK info and
14205 						 * tcp_pipe is not initialized,
14206 						 * funny things will happen.
14207 						 */
14208 						tcp->tcp_pipe =
14209 						    tcp->tcp_cwnd_ssthresh;
14210 					}
14211 				} else {
14212 					flags |= TH_REXMIT_NEEDED;
14213 				} /* tcp_snd_sack_ok */
14214 
14215 				} else {
14216 					/*
14217 					 * Here we perform congestion
14218 					 * avoidance, but NOT slow start.
14219 					 * This is known as the Fast
14220 					 * Recovery Algorithm.
14221 					 */
14222 					if (tcp->tcp_snd_sack_ok &&
14223 					    tcp->tcp_notsack_list != NULL) {
14224 						flags |= TH_NEED_SACK_REXMIT;
14225 						tcp->tcp_pipe -= mss;
14226 						if (tcp->tcp_pipe < 0)
14227 							tcp->tcp_pipe = 0;
14228 					} else {
14229 					/*
14230 					 * We know that one more packet has
14231 					 * left the pipe thus we can update
14232 					 * cwnd.
14233 					 */
14234 					cwnd = tcp->tcp_cwnd + mss;
14235 					if (cwnd > tcp->tcp_cwnd_max)
14236 						cwnd = tcp->tcp_cwnd_max;
14237 					tcp->tcp_cwnd = cwnd;
14238 					if (tcp->tcp_unsent > 0)
14239 						flags |= TH_XMIT_NEEDED;
14240 					}
14241 				}
14242 			}
14243 		} else if (tcp->tcp_zero_win_probe) {
14244 			/*
14245 			 * If the window has opened, need to arrange
14246 			 * to send additional data.
14247 			 */
14248 			if (new_swnd != 0) {
14249 				/* tcp_suna != tcp_snxt */
14250 				/* Packet contains a window update */
14251 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14252 				tcp->tcp_zero_win_probe = 0;
14253 				tcp->tcp_timer_backoff = 0;
14254 				tcp->tcp_ms_we_have_waited = 0;
14255 
14256 				/*
14257 				 * Transmit starting with tcp_suna since
14258 				 * the one byte probe is not ack'ed.
14259 				 * If TCP has sent more than one identical
14260 				 * probe, tcp_rexmit will be set.  That means
14261 				 * tcp_ss_rexmit() will send out the one
14262 				 * byte along with new data.  Otherwise,
14263 				 * fake the retransmission.
14264 				 */
14265 				flags |= TH_XMIT_NEEDED;
14266 				if (!tcp->tcp_rexmit) {
14267 					tcp->tcp_rexmit = B_TRUE;
14268 					tcp->tcp_dupack_cnt = 0;
14269 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14270 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14271 				}
14272 			}
14273 		}
14274 		goto swnd_update;
14275 	}
14276 
14277 	/*
14278 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14279 	 * If the ACK value acks something that we have not yet sent, it might
14280 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14281 	 * other side.
14282 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14283 	 * state is handled above, so we can always just drop the segment and
14284 	 * send an ACK here.
14285 	 *
14286 	 * In the case where the peer shrinks the window, we see the new window
14287 	 * update, but all the data sent previously is queued up by the peer.
14288 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
14289 	 * number, which was already sent, and within window, is recorded.
14290 	 * tcp_snxt is then updated.
14291 	 *
14292 	 * If the window has previously shrunk, and an ACK for data not yet
14293 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
14294 	 * the ACK is for data within the window at the time the window was
14295 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
14296 	 * the sequence number ACK'ed.
14297 	 *
14298 	 * If the ACK covers all the data sent at the time the window was
14299 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
14300 	 *
14301 	 * Should we send ACKs in response to ACK only segments?
14302 	 */
14303 
14304 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14305 		if ((tcp->tcp_is_wnd_shrnk) &&
14306 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
14307 			uint32_t data_acked_ahead_snxt;
14308 
14309 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
14310 			tcp_update_xmit_tail(tcp, seg_ack);
14311 			tcp->tcp_unsent -= data_acked_ahead_snxt;
14312 		} else {
14313 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14314 			/* drop the received segment */
14315 			freemsg(mp);
14316 
14317 			/*
14318 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14319 			 * greater than 0, check if the number of such
14320 			 * bogus ACks is greater than that count.  If yes,
14321 			 * don't send back any ACK.  This prevents TCP from
14322 			 * getting into an ACK storm if somehow an attacker
14323 			 * successfully spoofs an acceptable segment to our
14324 			 * peer.
14325 			 */
14326 			if (tcp_drop_ack_unsent_cnt > 0 &&
14327 			    ++tcp->tcp_in_ack_unsent >
14328 			    tcp_drop_ack_unsent_cnt) {
14329 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14330 				return;
14331 			}
14332 			mp = tcp_ack_mp(tcp);
14333 			if (mp != NULL) {
14334 				BUMP_LOCAL(tcp->tcp_obsegs);
14335 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14336 				tcp_send_data(tcp, tcp->tcp_wq, mp);
14337 			}
14338 			return;
14339 		}
14340 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
14341 	    tcp->tcp_snxt_shrunk)) {
14342 			tcp->tcp_is_wnd_shrnk = B_FALSE;
14343 	}
14344 
14345 	/*
14346 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14347 	 * blocks that are covered by this ACK.
14348 	 */
14349 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14350 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14351 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14352 	}
14353 
14354 	/*
14355 	 * If we got an ACK after fast retransmit, check to see
14356 	 * if it is a partial ACK.  If it is not and the congestion
14357 	 * window was inflated to account for the other side's
14358 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14359 	 */
14360 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14361 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14362 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14363 			tcp->tcp_dupack_cnt = 0;
14364 			/*
14365 			 * Restore the orig tcp_cwnd_ssthresh after
14366 			 * fast retransmit phase.
14367 			 */
14368 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14369 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14370 			}
14371 			tcp->tcp_rexmit_max = seg_ack;
14372 			tcp->tcp_cwnd_cnt = 0;
14373 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14374 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14375 
14376 			/*
14377 			 * Remove all notsack info to avoid confusion with
14378 			 * the next fast retrasnmit/recovery phase.
14379 			 */
14380 			if (tcp->tcp_snd_sack_ok &&
14381 			    tcp->tcp_notsack_list != NULL) {
14382 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
14383 				    tcp);
14384 			}
14385 		} else {
14386 			if (tcp->tcp_snd_sack_ok &&
14387 			    tcp->tcp_notsack_list != NULL) {
14388 				flags |= TH_NEED_SACK_REXMIT;
14389 				tcp->tcp_pipe -= mss;
14390 				if (tcp->tcp_pipe < 0)
14391 					tcp->tcp_pipe = 0;
14392 			} else {
14393 				/*
14394 				 * Hoe's algorithm:
14395 				 *
14396 				 * Retransmit the unack'ed segment and
14397 				 * restart fast recovery.  Note that we
14398 				 * need to scale back tcp_cwnd to the
14399 				 * original value when we started fast
14400 				 * recovery.  This is to prevent overly
14401 				 * aggressive behaviour in sending new
14402 				 * segments.
14403 				 */
14404 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14405 				    tcps->tcps_dupack_fast_retransmit * mss;
14406 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14407 				flags |= TH_REXMIT_NEEDED;
14408 			}
14409 		}
14410 	} else {
14411 		tcp->tcp_dupack_cnt = 0;
14412 		if (tcp->tcp_rexmit) {
14413 			/*
14414 			 * TCP is retranmitting.  If the ACK ack's all
14415 			 * outstanding data, update tcp_rexmit_max and
14416 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14417 			 * to the correct value.
14418 			 *
14419 			 * Note that SEQ_LEQ() is used.  This is to avoid
14420 			 * unnecessary fast retransmit caused by dup ACKs
14421 			 * received when TCP does slow start retransmission
14422 			 * after a time out.  During this phase, TCP may
14423 			 * send out segments which are already received.
14424 			 * This causes dup ACKs to be sent back.
14425 			 */
14426 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14427 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14428 					tcp->tcp_rexmit_nxt = seg_ack;
14429 				}
14430 				if (seg_ack != tcp->tcp_rexmit_max) {
14431 					flags |= TH_XMIT_NEEDED;
14432 				}
14433 			} else {
14434 				tcp->tcp_rexmit = B_FALSE;
14435 				tcp->tcp_xmit_zc_clean = B_FALSE;
14436 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14437 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14438 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14439 			}
14440 			tcp->tcp_ms_we_have_waited = 0;
14441 		}
14442 	}
14443 
14444 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14445 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14446 	tcp->tcp_suna = seg_ack;
14447 	if (tcp->tcp_zero_win_probe != 0) {
14448 		tcp->tcp_zero_win_probe = 0;
14449 		tcp->tcp_timer_backoff = 0;
14450 	}
14451 
14452 	/*
14453 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14454 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14455 	 * will not reach here.
14456 	 */
14457 	if (mp1 == NULL) {
14458 		goto fin_acked;
14459 	}
14460 
14461 	/*
14462 	 * Update the congestion window.
14463 	 *
14464 	 * If TCP is not ECN capable or TCP is ECN capable but the
14465 	 * congestion experience bit is not set, increase the tcp_cwnd as
14466 	 * usual.
14467 	 */
14468 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14469 		cwnd = tcp->tcp_cwnd;
14470 		add = mss;
14471 
14472 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14473 			/*
14474 			 * This is to prevent an increase of less than 1 MSS of
14475 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14476 			 * may send out tinygrams in order to preserve mblk
14477 			 * boundaries.
14478 			 *
14479 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14480 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14481 			 * increased by 1 MSS for every RTTs.
14482 			 */
14483 			if (tcp->tcp_cwnd_cnt <= 0) {
14484 				tcp->tcp_cwnd_cnt = cwnd + add;
14485 			} else {
14486 				tcp->tcp_cwnd_cnt -= add;
14487 				add = 0;
14488 			}
14489 		}
14490 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14491 	}
14492 
14493 	/* See if the latest urgent data has been acknowledged */
14494 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14495 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14496 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14497 
14498 	/* Can we update the RTT estimates? */
14499 	if (tcp->tcp_snd_ts_ok) {
14500 		/* Ignore zero timestamp echo-reply. */
14501 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14502 			tcp_set_rto(tcp, (int32_t)lbolt -
14503 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14504 		}
14505 
14506 		/* If needed, restart the timer. */
14507 		if (tcp->tcp_set_timer == 1) {
14508 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14509 			tcp->tcp_set_timer = 0;
14510 		}
14511 		/*
14512 		 * Update tcp_csuna in case the other side stops sending
14513 		 * us timestamps.
14514 		 */
14515 		tcp->tcp_csuna = tcp->tcp_snxt;
14516 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14517 		/*
14518 		 * An ACK sequence we haven't seen before, so get the RTT
14519 		 * and update the RTO. But first check if the timestamp is
14520 		 * valid to use.
14521 		 */
14522 		if ((mp1->b_next != NULL) &&
14523 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14524 			tcp_set_rto(tcp, (int32_t)lbolt -
14525 			    (int32_t)(intptr_t)mp1->b_prev);
14526 		else
14527 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14528 
14529 		/* Remeber the last sequence to be ACKed */
14530 		tcp->tcp_csuna = seg_ack;
14531 		if (tcp->tcp_set_timer == 1) {
14532 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14533 			tcp->tcp_set_timer = 0;
14534 		}
14535 	} else {
14536 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14537 	}
14538 
14539 	/* Eat acknowledged bytes off the xmit queue. */
14540 	for (;;) {
14541 		mblk_t	*mp2;
14542 		uchar_t	*wptr;
14543 
14544 		wptr = mp1->b_wptr;
14545 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14546 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14547 		if (bytes_acked < 0) {
14548 			mp1->b_rptr = wptr + bytes_acked;
14549 			/*
14550 			 * Set a new timestamp if all the bytes timed by the
14551 			 * old timestamp have been ack'ed.
14552 			 */
14553 			if (SEQ_GT(seg_ack,
14554 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14555 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14556 				mp1->b_next = NULL;
14557 			}
14558 			break;
14559 		}
14560 		mp1->b_next = NULL;
14561 		mp1->b_prev = NULL;
14562 		mp2 = mp1;
14563 		mp1 = mp1->b_cont;
14564 
14565 		/*
14566 		 * This notification is required for some zero-copy
14567 		 * clients to maintain a copy semantic. After the data
14568 		 * is ack'ed, client is safe to modify or reuse the buffer.
14569 		 */
14570 		if (tcp->tcp_snd_zcopy_aware &&
14571 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14572 			tcp_zcopy_notify(tcp);
14573 		freeb(mp2);
14574 		if (bytes_acked == 0) {
14575 			if (mp1 == NULL) {
14576 				/* Everything is ack'ed, clear the tail. */
14577 				tcp->tcp_xmit_tail = NULL;
14578 				/*
14579 				 * Cancel the timer unless we are still
14580 				 * waiting for an ACK for the FIN packet.
14581 				 */
14582 				if (tcp->tcp_timer_tid != 0 &&
14583 				    tcp->tcp_snxt == tcp->tcp_suna) {
14584 					(void) TCP_TIMER_CANCEL(tcp,
14585 					    tcp->tcp_timer_tid);
14586 					tcp->tcp_timer_tid = 0;
14587 				}
14588 				goto pre_swnd_update;
14589 			}
14590 			if (mp2 != tcp->tcp_xmit_tail)
14591 				break;
14592 			tcp->tcp_xmit_tail = mp1;
14593 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14594 			    (uintptr_t)INT_MAX);
14595 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14596 			    mp1->b_rptr);
14597 			break;
14598 		}
14599 		if (mp1 == NULL) {
14600 			/*
14601 			 * More was acked but there is nothing more
14602 			 * outstanding.  This means that the FIN was
14603 			 * just acked or that we're talking to a clown.
14604 			 */
14605 fin_acked:
14606 			ASSERT(tcp->tcp_fin_sent);
14607 			tcp->tcp_xmit_tail = NULL;
14608 			if (tcp->tcp_fin_sent) {
14609 				/* FIN was acked - making progress */
14610 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14611 				    !tcp->tcp_fin_acked)
14612 					tcp->tcp_ip_forward_progress = B_TRUE;
14613 				tcp->tcp_fin_acked = B_TRUE;
14614 				if (tcp->tcp_linger_tid != 0 &&
14615 				    TCP_TIMER_CANCEL(tcp,
14616 				    tcp->tcp_linger_tid) >= 0) {
14617 					tcp_stop_lingering(tcp);
14618 					freemsg(mp);
14619 					mp = NULL;
14620 				}
14621 			} else {
14622 				/*
14623 				 * We should never get here because
14624 				 * we have already checked that the
14625 				 * number of bytes ack'ed should be
14626 				 * smaller than or equal to what we
14627 				 * have sent so far (it is the
14628 				 * acceptability check of the ACK).
14629 				 * We can only get here if the send
14630 				 * queue is corrupted.
14631 				 *
14632 				 * Terminate the connection and
14633 				 * panic the system.  It is better
14634 				 * for us to panic instead of
14635 				 * continuing to avoid other disaster.
14636 				 */
14637 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14638 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14639 				panic("Memory corruption "
14640 				    "detected for connection %s.",
14641 				    tcp_display(tcp, NULL,
14642 				    DISP_ADDR_AND_PORT));
14643 				/*NOTREACHED*/
14644 			}
14645 			goto pre_swnd_update;
14646 		}
14647 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14648 	}
14649 	if (tcp->tcp_unsent) {
14650 		flags |= TH_XMIT_NEEDED;
14651 	}
14652 pre_swnd_update:
14653 	tcp->tcp_xmit_head = mp1;
14654 swnd_update:
14655 	/*
14656 	 * The following check is different from most other implementations.
14657 	 * For bi-directional transfer, when segments are dropped, the
14658 	 * "normal" check will not accept a window update in those
14659 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14660 	 * segments which are outside receiver's window.  As TCP accepts
14661 	 * the ack in those retransmitted segments, if the window update in
14662 	 * the same segment is not accepted, TCP will incorrectly calculates
14663 	 * that it can send more segments.  This can create a deadlock
14664 	 * with the receiver if its window becomes zero.
14665 	 */
14666 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14667 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14668 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14669 		/*
14670 		 * The criteria for update is:
14671 		 *
14672 		 * 1. the segment acknowledges some data.  Or
14673 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14674 		 * 3. the segment is not old and the advertised window is
14675 		 * larger than the previous advertised window.
14676 		 */
14677 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14678 			flags |= TH_XMIT_NEEDED;
14679 		tcp->tcp_swnd = new_swnd;
14680 		if (new_swnd > tcp->tcp_max_swnd)
14681 			tcp->tcp_max_swnd = new_swnd;
14682 		tcp->tcp_swl1 = seg_seq;
14683 		tcp->tcp_swl2 = seg_ack;
14684 	}
14685 est:
14686 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14687 
14688 		switch (tcp->tcp_state) {
14689 		case TCPS_FIN_WAIT_1:
14690 			if (tcp->tcp_fin_acked) {
14691 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14692 				/*
14693 				 * We implement the non-standard BSD/SunOS
14694 				 * FIN_WAIT_2 flushing algorithm.
14695 				 * If there is no user attached to this
14696 				 * TCP endpoint, then this TCP struct
14697 				 * could hang around forever in FIN_WAIT_2
14698 				 * state if the peer forgets to send us
14699 				 * a FIN.  To prevent this, we wait only
14700 				 * 2*MSL (a convenient time value) for
14701 				 * the FIN to arrive.  If it doesn't show up,
14702 				 * we flush the TCP endpoint.  This algorithm,
14703 				 * though a violation of RFC-793, has worked
14704 				 * for over 10 years in BSD systems.
14705 				 * Note: SunOS 4.x waits 675 seconds before
14706 				 * flushing the FIN_WAIT_2 connection.
14707 				 */
14708 				TCP_TIMER_RESTART(tcp,
14709 				    tcps->tcps_fin_wait_2_flush_interval);
14710 			}
14711 			break;
14712 		case TCPS_FIN_WAIT_2:
14713 			break;	/* Shutdown hook? */
14714 		case TCPS_LAST_ACK:
14715 			freemsg(mp);
14716 			if (tcp->tcp_fin_acked) {
14717 				(void) tcp_clean_death(tcp, 0, 19);
14718 				return;
14719 			}
14720 			goto xmit_check;
14721 		case TCPS_CLOSING:
14722 			if (tcp->tcp_fin_acked) {
14723 				tcp->tcp_state = TCPS_TIME_WAIT;
14724 				/*
14725 				 * Unconditionally clear the exclusive binding
14726 				 * bit so this TIME-WAIT connection won't
14727 				 * interfere with new ones.
14728 				 */
14729 				tcp->tcp_exclbind = 0;
14730 				if (!TCP_IS_DETACHED(tcp)) {
14731 					TCP_TIMER_RESTART(tcp,
14732 					    tcps->tcps_time_wait_interval);
14733 				} else {
14734 					tcp_time_wait_append(tcp);
14735 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14736 				}
14737 			}
14738 			/*FALLTHRU*/
14739 		case TCPS_CLOSE_WAIT:
14740 			freemsg(mp);
14741 			goto xmit_check;
14742 		default:
14743 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14744 			break;
14745 		}
14746 	}
14747 	if (flags & TH_FIN) {
14748 		/* Make sure we ack the fin */
14749 		flags |= TH_ACK_NEEDED;
14750 		if (!tcp->tcp_fin_rcvd) {
14751 			tcp->tcp_fin_rcvd = B_TRUE;
14752 			tcp->tcp_rnxt++;
14753 			tcph = tcp->tcp_tcph;
14754 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14755 
14756 			/*
14757 			 * Generate the ordrel_ind at the end unless we
14758 			 * are an eager guy.
14759 			 * In the eager case tcp_rsrv will do this when run
14760 			 * after tcp_accept is done.
14761 			 */
14762 			if (tcp->tcp_listener == NULL &&
14763 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14764 				flags |= TH_ORDREL_NEEDED;
14765 			switch (tcp->tcp_state) {
14766 			case TCPS_SYN_RCVD:
14767 			case TCPS_ESTABLISHED:
14768 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14769 				/* Keepalive? */
14770 				break;
14771 			case TCPS_FIN_WAIT_1:
14772 				if (!tcp->tcp_fin_acked) {
14773 					tcp->tcp_state = TCPS_CLOSING;
14774 					break;
14775 				}
14776 				/* FALLTHRU */
14777 			case TCPS_FIN_WAIT_2:
14778 				tcp->tcp_state = TCPS_TIME_WAIT;
14779 				/*
14780 				 * Unconditionally clear the exclusive binding
14781 				 * bit so this TIME-WAIT connection won't
14782 				 * interfere with new ones.
14783 				 */
14784 				tcp->tcp_exclbind = 0;
14785 				if (!TCP_IS_DETACHED(tcp)) {
14786 					TCP_TIMER_RESTART(tcp,
14787 					    tcps->tcps_time_wait_interval);
14788 				} else {
14789 					tcp_time_wait_append(tcp);
14790 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14791 				}
14792 				if (seg_len) {
14793 					/*
14794 					 * implies data piggybacked on FIN.
14795 					 * break to handle data.
14796 					 */
14797 					break;
14798 				}
14799 				freemsg(mp);
14800 				goto ack_check;
14801 			}
14802 		}
14803 	}
14804 	if (mp == NULL)
14805 		goto xmit_check;
14806 	if (seg_len == 0) {
14807 		freemsg(mp);
14808 		goto xmit_check;
14809 	}
14810 	if (mp->b_rptr == mp->b_wptr) {
14811 		/*
14812 		 * The header has been consumed, so we remove the
14813 		 * zero-length mblk here.
14814 		 */
14815 		mp1 = mp;
14816 		mp = mp->b_cont;
14817 		freeb(mp1);
14818 	}
14819 update_ack:
14820 	tcph = tcp->tcp_tcph;
14821 	tcp->tcp_rack_cnt++;
14822 	{
14823 		uint32_t cur_max;
14824 
14825 		cur_max = tcp->tcp_rack_cur_max;
14826 		if (tcp->tcp_rack_cnt >= cur_max) {
14827 			/*
14828 			 * We have more unacked data than we should - send
14829 			 * an ACK now.
14830 			 */
14831 			flags |= TH_ACK_NEEDED;
14832 			cur_max++;
14833 			if (cur_max > tcp->tcp_rack_abs_max)
14834 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14835 			else
14836 				tcp->tcp_rack_cur_max = cur_max;
14837 		} else if (TCP_IS_DETACHED(tcp)) {
14838 			/* We don't have an ACK timer for detached TCP. */
14839 			flags |= TH_ACK_NEEDED;
14840 		} else if (seg_len < mss) {
14841 			/*
14842 			 * If we get a segment that is less than an mss, and we
14843 			 * already have unacknowledged data, and the amount
14844 			 * unacknowledged is not a multiple of mss, then we
14845 			 * better generate an ACK now.  Otherwise, this may be
14846 			 * the tail piece of a transaction, and we would rather
14847 			 * wait for the response.
14848 			 */
14849 			uint32_t udif;
14850 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14851 			    (uintptr_t)INT_MAX);
14852 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14853 			if (udif && (udif % mss))
14854 				flags |= TH_ACK_NEEDED;
14855 			else
14856 				flags |= TH_ACK_TIMER_NEEDED;
14857 		} else {
14858 			/* Start delayed ack timer */
14859 			flags |= TH_ACK_TIMER_NEEDED;
14860 		}
14861 	}
14862 	tcp->tcp_rnxt += seg_len;
14863 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14864 
14865 	if (mp == NULL)
14866 		goto xmit_check;
14867 
14868 	/* Update SACK list */
14869 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14870 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14871 		    &(tcp->tcp_num_sack_blk));
14872 	}
14873 
14874 	if (tcp->tcp_urp_mp) {
14875 		tcp->tcp_urp_mp->b_cont = mp;
14876 		mp = tcp->tcp_urp_mp;
14877 		tcp->tcp_urp_mp = NULL;
14878 		/* Ready for a new signal. */
14879 		tcp->tcp_urp_last_valid = B_FALSE;
14880 #ifdef DEBUG
14881 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14882 		    "tcp_rput: sending exdata_ind %s",
14883 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14884 #endif /* DEBUG */
14885 	}
14886 
14887 	/*
14888 	 * Check for ancillary data changes compared to last segment.
14889 	 */
14890 	if (tcp->tcp_ipv6_recvancillary != 0) {
14891 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14892 		ASSERT(mp != NULL);
14893 	}
14894 
14895 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14896 		/*
14897 		 * Side queue inbound data until the accept happens.
14898 		 * tcp_accept/tcp_rput drains this when the accept happens.
14899 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14900 		 * T_EXDATA_IND) it is queued on b_next.
14901 		 * XXX Make urgent data use this. Requires:
14902 		 *	Removing tcp_listener check for TH_URG
14903 		 *	Making M_PCPROTO and MARK messages skip the eager case
14904 		 */
14905 
14906 		if (tcp->tcp_kssl_pending) {
14907 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
14908 			    mblk_t *, mp);
14909 			tcp_kssl_input(tcp, mp);
14910 		} else {
14911 			tcp_rcv_enqueue(tcp, mp, seg_len);
14912 		}
14913 	} else {
14914 		if (mp->b_datap->db_type != M_DATA ||
14915 		    (flags & TH_MARKNEXT_NEEDED)) {
14916 			if (IPCL_IS_NONSTR(connp)) {
14917 				int error;
14918 
14919 				if ((*connp->conn_upcalls->su_recv)
14920 				    (connp->conn_upper_handle, mp,
14921 				    seg_len, 0, &error, NULL) <= 0) {
14922 					/*
14923 					 * We should never be in middle of a
14924 					 * fallback, the squeue guarantees that.
14925 					 */
14926 					ASSERT(error != EOPNOTSUPP);
14927 					if (error == ENOSPC)
14928 						tcp->tcp_rwnd -= seg_len;
14929 				}
14930 			} else if (tcp->tcp_rcv_list != NULL) {
14931 				flags |= tcp_rcv_drain(tcp);
14932 			}
14933 			ASSERT(tcp->tcp_rcv_list == NULL ||
14934 			    tcp->tcp_fused_sigurg);
14935 
14936 			if (flags & TH_MARKNEXT_NEEDED) {
14937 #ifdef DEBUG
14938 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14939 				    "tcp_rput: sending MSGMARKNEXT %s",
14940 				    tcp_display(tcp, NULL,
14941 				    DISP_PORT_ONLY));
14942 #endif /* DEBUG */
14943 				mp->b_flag |= MSGMARKNEXT;
14944 				flags &= ~TH_MARKNEXT_NEEDED;
14945 			}
14946 
14947 			/* Does this need SSL processing first? */
14948 			if ((tcp->tcp_kssl_ctx != NULL) &&
14949 			    (DB_TYPE(mp) == M_DATA)) {
14950 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
14951 				    mblk_t *, mp);
14952 				tcp_kssl_input(tcp, mp);
14953 			} else if (!IPCL_IS_NONSTR(connp)) {
14954 				/* Already handled non-STREAMS case. */
14955 				putnext(tcp->tcp_rq, mp);
14956 				if (!canputnext(tcp->tcp_rq))
14957 					tcp->tcp_rwnd -= seg_len;
14958 			}
14959 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
14960 		    (DB_TYPE(mp) == M_DATA)) {
14961 			/* Does this need SSL processing first? */
14962 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
14963 			tcp_kssl_input(tcp, mp);
14964 		} else if (IPCL_IS_NONSTR(connp)) {
14965 			/* Non-STREAMS socket */
14966 			boolean_t push = flags & (TH_PUSH|TH_FIN);
14967 			int	error;
14968 
14969 			if ((*connp->conn_upcalls->su_recv)(
14970 			    connp->conn_upper_handle,
14971 			    mp, seg_len, 0, &error, &push) <= 0) {
14972 				/*
14973 				 * We should never be in middle of a
14974 				 * fallback, the squeue guarantees that.
14975 				 */
14976 				ASSERT(error != EOPNOTSUPP);
14977 				if (error == ENOSPC)
14978 					tcp->tcp_rwnd -= seg_len;
14979 			} else if (push) {
14980 				/*
14981 				 * PUSH bit set and sockfs is not
14982 				 * flow controlled
14983 				 */
14984 				flags |= tcp_rwnd_reopen(tcp);
14985 			}
14986 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14987 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
14988 			if (tcp->tcp_rcv_list != NULL) {
14989 				/*
14990 				 * Enqueue the new segment first and then
14991 				 * call tcp_rcv_drain() to send all data
14992 				 * up.  The other way to do this is to
14993 				 * send all queued data up and then call
14994 				 * putnext() to send the new segment up.
14995 				 * This way can remove the else part later
14996 				 * on.
14997 				 *
14998 				 * We don't do this to avoid one more call to
14999 				 * canputnext() as tcp_rcv_drain() needs to
15000 				 * call canputnext().
15001 				 */
15002 				tcp_rcv_enqueue(tcp, mp, seg_len);
15003 				flags |= tcp_rcv_drain(tcp);
15004 			} else {
15005 				putnext(tcp->tcp_rq, mp);
15006 				if (!canputnext(tcp->tcp_rq))
15007 					tcp->tcp_rwnd -= seg_len;
15008 			}
15009 		} else {
15010 			/*
15011 			 * Enqueue all packets when processing an mblk
15012 			 * from the co queue and also enqueue normal packets.
15013 			 */
15014 			tcp_rcv_enqueue(tcp, mp, seg_len);
15015 		}
15016 		/*
15017 		 * Make sure the timer is running if we have data waiting
15018 		 * for a push bit. This provides resiliency against
15019 		 * implementations that do not correctly generate push bits.
15020 		 */
15021 		if (!IPCL_IS_NONSTR(connp) && tcp->tcp_rcv_list != NULL &&
15022 		    tcp->tcp_push_tid == 0) {
15023 			/*
15024 			 * The connection may be closed at this point, so don't
15025 			 * do anything for a detached tcp.
15026 			 */
15027 			if (!TCP_IS_DETACHED(tcp))
15028 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15029 				    tcp_push_timer,
15030 				    MSEC_TO_TICK(
15031 				    tcps->tcps_push_timer_interval));
15032 		}
15033 	}
15034 
15035 xmit_check:
15036 	/* Is there anything left to do? */
15037 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15038 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15039 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15040 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15041 		goto done;
15042 
15043 	/* Any transmit work to do and a non-zero window? */
15044 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15045 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15046 		if (flags & TH_REXMIT_NEEDED) {
15047 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15048 
15049 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15050 			if (snd_size > mss)
15051 				snd_size = mss;
15052 			if (snd_size > tcp->tcp_swnd)
15053 				snd_size = tcp->tcp_swnd;
15054 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15055 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15056 			    B_TRUE);
15057 
15058 			if (mp1 != NULL) {
15059 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15060 				tcp->tcp_csuna = tcp->tcp_snxt;
15061 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15062 				UPDATE_MIB(&tcps->tcps_mib,
15063 				    tcpRetransBytes, snd_size);
15064 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15065 			}
15066 		}
15067 		if (flags & TH_NEED_SACK_REXMIT) {
15068 			tcp_sack_rxmit(tcp, &flags);
15069 		}
15070 		/*
15071 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15072 		 * out new segment.  Note that tcp_rexmit should not be
15073 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15074 		 */
15075 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15076 			if (!tcp->tcp_rexmit) {
15077 				tcp_wput_data(tcp, NULL, B_FALSE);
15078 			} else {
15079 				tcp_ss_rexmit(tcp);
15080 			}
15081 		}
15082 		/*
15083 		 * Adjust tcp_cwnd back to normal value after sending
15084 		 * new data segments.
15085 		 */
15086 		if (flags & TH_LIMIT_XMIT) {
15087 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15088 			/*
15089 			 * This will restart the timer.  Restarting the
15090 			 * timer is used to avoid a timeout before the
15091 			 * limited transmitted segment's ACK gets back.
15092 			 */
15093 			if (tcp->tcp_xmit_head != NULL)
15094 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15095 		}
15096 
15097 		/* Anything more to do? */
15098 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15099 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15100 			goto done;
15101 	}
15102 ack_check:
15103 	if (flags & TH_SEND_URP_MARK) {
15104 		ASSERT(tcp->tcp_urp_mark_mp);
15105 		ASSERT(!IPCL_IS_NONSTR(connp));
15106 		/*
15107 		 * Send up any queued data and then send the mark message
15108 		 */
15109 		if (tcp->tcp_rcv_list != NULL) {
15110 			flags |= tcp_rcv_drain(tcp);
15111 
15112 		}
15113 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15114 		mp1 = tcp->tcp_urp_mark_mp;
15115 		tcp->tcp_urp_mark_mp = NULL;
15116 		putnext(tcp->tcp_rq, mp1);
15117 #ifdef DEBUG
15118 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15119 		    "tcp_rput: sending zero-length %s %s",
15120 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15121 		    "MSGNOTMARKNEXT"),
15122 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15123 #endif /* DEBUG */
15124 		flags &= ~TH_SEND_URP_MARK;
15125 	}
15126 	if (flags & TH_ACK_NEEDED) {
15127 		/*
15128 		 * Time to send an ack for some reason.
15129 		 */
15130 		mp1 = tcp_ack_mp(tcp);
15131 
15132 		if (mp1 != NULL) {
15133 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15134 			BUMP_LOCAL(tcp->tcp_obsegs);
15135 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15136 		}
15137 		if (tcp->tcp_ack_tid != 0) {
15138 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15139 			tcp->tcp_ack_tid = 0;
15140 		}
15141 	}
15142 	if (flags & TH_ACK_TIMER_NEEDED) {
15143 		/*
15144 		 * Arrange for deferred ACK or push wait timeout.
15145 		 * Start timer if it is not already running.
15146 		 */
15147 		if (tcp->tcp_ack_tid == 0) {
15148 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15149 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15150 			    (clock_t)tcps->tcps_local_dack_interval :
15151 			    (clock_t)tcps->tcps_deferred_ack_interval));
15152 		}
15153 	}
15154 	if (flags & TH_ORDREL_NEEDED) {
15155 		/*
15156 		 * Send up the ordrel_ind unless we are an eager guy.
15157 		 * In the eager case tcp_rsrv will do this when run
15158 		 * after tcp_accept is done.
15159 		 */
15160 		ASSERT(tcp->tcp_listener == NULL);
15161 
15162 		if (IPCL_IS_NONSTR(connp)) {
15163 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15164 			tcp->tcp_ordrel_done = B_TRUE;
15165 			(*connp->conn_upcalls->su_opctl)
15166 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15167 			goto done;
15168 		}
15169 
15170 		if (tcp->tcp_rcv_list != NULL) {
15171 			/*
15172 			 * Push any mblk(s) enqueued from co processing.
15173 			 */
15174 			flags |= tcp_rcv_drain(tcp);
15175 		}
15176 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15177 
15178 		mp1 = tcp->tcp_ordrel_mp;
15179 		tcp->tcp_ordrel_mp = NULL;
15180 		tcp->tcp_ordrel_done = B_TRUE;
15181 		putnext(tcp->tcp_rq, mp1);
15182 	}
15183 done:
15184 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15185 }
15186 
15187 /*
15188  * This routine adjusts next-to-send sequence number variables, in the
15189  * case where the reciever has shrunk it's window.
15190  */
15191 static void
15192 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
15193 {
15194 	mblk_t *xmit_tail;
15195 	int32_t offset;
15196 
15197 	tcp->tcp_snxt = snxt;
15198 
15199 	/* Get the mblk, and the offset in it, as per the shrunk window */
15200 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
15201 	ASSERT(xmit_tail != NULL);
15202 	tcp->tcp_xmit_tail = xmit_tail;
15203 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
15204 	    xmit_tail->b_rptr - offset;
15205 }
15206 
15207 /*
15208  * This function does PAWS protection check. Returns B_TRUE if the
15209  * segment passes the PAWS test, else returns B_FALSE.
15210  */
15211 boolean_t
15212 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15213 {
15214 	uint8_t	flags;
15215 	int	options;
15216 	uint8_t *up;
15217 
15218 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15219 	/*
15220 	 * If timestamp option is aligned nicely, get values inline,
15221 	 * otherwise call general routine to parse.  Only do that
15222 	 * if timestamp is the only option.
15223 	 */
15224 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15225 	    TCPOPT_REAL_TS_LEN &&
15226 	    OK_32PTR((up = ((uint8_t *)tcph) +
15227 	    TCP_MIN_HEADER_LENGTH)) &&
15228 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15229 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15230 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15231 
15232 		options = TCP_OPT_TSTAMP_PRESENT;
15233 	} else {
15234 		if (tcp->tcp_snd_sack_ok) {
15235 			tcpoptp->tcp = tcp;
15236 		} else {
15237 			tcpoptp->tcp = NULL;
15238 		}
15239 		options = tcp_parse_options(tcph, tcpoptp);
15240 	}
15241 
15242 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15243 		/*
15244 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15245 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15246 		 */
15247 		if ((flags & TH_RST) == 0 &&
15248 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15249 		    tcp->tcp_ts_recent)) {
15250 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15251 			    PAWS_TIMEOUT)) {
15252 				/* This segment is not acceptable. */
15253 				return (B_FALSE);
15254 			} else {
15255 				/*
15256 				 * Connection has been idle for
15257 				 * too long.  Reset the timestamp
15258 				 * and assume the segment is valid.
15259 				 */
15260 				tcp->tcp_ts_recent =
15261 				    tcpoptp->tcp_opt_ts_val;
15262 			}
15263 		}
15264 	} else {
15265 		/*
15266 		 * If we don't get a timestamp on every packet, we
15267 		 * figure we can't really trust 'em, so we stop sending
15268 		 * and parsing them.
15269 		 */
15270 		tcp->tcp_snd_ts_ok = B_FALSE;
15271 
15272 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15273 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15274 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15275 		/*
15276 		 * Adjust the tcp_mss accordingly. We also need to
15277 		 * adjust tcp_cwnd here in accordance with the new mss.
15278 		 * But we avoid doing a slow start here so as to not
15279 		 * to lose on the transfer rate built up so far.
15280 		 */
15281 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15282 		if (tcp->tcp_snd_sack_ok) {
15283 			ASSERT(tcp->tcp_sack_info != NULL);
15284 			tcp->tcp_max_sack_blk = 4;
15285 		}
15286 	}
15287 	return (B_TRUE);
15288 }
15289 
15290 /*
15291  * Attach ancillary data to a received TCP segments for the
15292  * ancillary pieces requested by the application that are
15293  * different than they were in the previous data segment.
15294  *
15295  * Save the "current" values once memory allocation is ok so that
15296  * when memory allocation fails we can just wait for the next data segment.
15297  */
15298 static mblk_t *
15299 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15300 {
15301 	struct T_optdata_ind *todi;
15302 	int optlen;
15303 	uchar_t *optptr;
15304 	struct T_opthdr *toh;
15305 	uint_t addflag;	/* Which pieces to add */
15306 	mblk_t *mp1;
15307 
15308 	optlen = 0;
15309 	addflag = 0;
15310 	/* If app asked for pktinfo and the index has changed ... */
15311 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15312 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15313 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15314 		optlen += sizeof (struct T_opthdr) +
15315 		    sizeof (struct in6_pktinfo);
15316 		addflag |= TCP_IPV6_RECVPKTINFO;
15317 	}
15318 	/* If app asked for hoplimit and it has changed ... */
15319 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15320 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15321 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15322 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15323 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15324 	}
15325 	/* If app asked for tclass and it has changed ... */
15326 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15327 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15328 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15329 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15330 		addflag |= TCP_IPV6_RECVTCLASS;
15331 	}
15332 	/*
15333 	 * If app asked for hopbyhop headers and it has changed ...
15334 	 * For security labels, note that (1) security labels can't change on
15335 	 * a connected socket at all, (2) we're connected to at most one peer,
15336 	 * (3) if anything changes, then it must be some other extra option.
15337 	 */
15338 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15339 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15340 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15341 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15342 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15343 		    tcp->tcp_label_len;
15344 		addflag |= TCP_IPV6_RECVHOPOPTS;
15345 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15346 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15347 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15348 			return (mp);
15349 	}
15350 	/* If app asked for dst headers before routing headers ... */
15351 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15352 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15353 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15354 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15355 		optlen += sizeof (struct T_opthdr) +
15356 		    ipp->ipp_rtdstoptslen;
15357 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15358 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15359 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15360 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15361 			return (mp);
15362 	}
15363 	/* If app asked for routing headers and it has changed ... */
15364 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15365 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15366 	    (ipp->ipp_fields & IPPF_RTHDR),
15367 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15368 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15369 		addflag |= TCP_IPV6_RECVRTHDR;
15370 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15371 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15372 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15373 			return (mp);
15374 	}
15375 	/* If app asked for dest headers and it has changed ... */
15376 	if ((tcp->tcp_ipv6_recvancillary &
15377 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15378 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15379 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15380 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15381 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15382 		addflag |= TCP_IPV6_RECVDSTOPTS;
15383 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15384 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15385 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15386 			return (mp);
15387 	}
15388 
15389 	if (optlen == 0) {
15390 		/* Nothing to add */
15391 		return (mp);
15392 	}
15393 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15394 	if (mp1 == NULL) {
15395 		/*
15396 		 * Defer sending ancillary data until the next TCP segment
15397 		 * arrives.
15398 		 */
15399 		return (mp);
15400 	}
15401 	mp1->b_cont = mp;
15402 	mp = mp1;
15403 	mp->b_wptr += sizeof (*todi) + optlen;
15404 	mp->b_datap->db_type = M_PROTO;
15405 	todi = (struct T_optdata_ind *)mp->b_rptr;
15406 	todi->PRIM_type = T_OPTDATA_IND;
15407 	todi->DATA_flag = 1;	/* MORE data */
15408 	todi->OPT_length = optlen;
15409 	todi->OPT_offset = sizeof (*todi);
15410 	optptr = (uchar_t *)&todi[1];
15411 	/*
15412 	 * If app asked for pktinfo and the index has changed ...
15413 	 * Note that the local address never changes for the connection.
15414 	 */
15415 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15416 		struct in6_pktinfo *pkti;
15417 
15418 		toh = (struct T_opthdr *)optptr;
15419 		toh->level = IPPROTO_IPV6;
15420 		toh->name = IPV6_PKTINFO;
15421 		toh->len = sizeof (*toh) + sizeof (*pkti);
15422 		toh->status = 0;
15423 		optptr += sizeof (*toh);
15424 		pkti = (struct in6_pktinfo *)optptr;
15425 		if (tcp->tcp_ipversion == IPV6_VERSION)
15426 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15427 		else
15428 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15429 			    &pkti->ipi6_addr);
15430 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15431 		optptr += sizeof (*pkti);
15432 		ASSERT(OK_32PTR(optptr));
15433 		/* Save as "last" value */
15434 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15435 	}
15436 	/* If app asked for hoplimit and it has changed ... */
15437 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15438 		toh = (struct T_opthdr *)optptr;
15439 		toh->level = IPPROTO_IPV6;
15440 		toh->name = IPV6_HOPLIMIT;
15441 		toh->len = sizeof (*toh) + sizeof (uint_t);
15442 		toh->status = 0;
15443 		optptr += sizeof (*toh);
15444 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15445 		optptr += sizeof (uint_t);
15446 		ASSERT(OK_32PTR(optptr));
15447 		/* Save as "last" value */
15448 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15449 	}
15450 	/* If app asked for tclass and it has changed ... */
15451 	if (addflag & TCP_IPV6_RECVTCLASS) {
15452 		toh = (struct T_opthdr *)optptr;
15453 		toh->level = IPPROTO_IPV6;
15454 		toh->name = IPV6_TCLASS;
15455 		toh->len = sizeof (*toh) + sizeof (uint_t);
15456 		toh->status = 0;
15457 		optptr += sizeof (*toh);
15458 		*(uint_t *)optptr = ipp->ipp_tclass;
15459 		optptr += sizeof (uint_t);
15460 		ASSERT(OK_32PTR(optptr));
15461 		/* Save as "last" value */
15462 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15463 	}
15464 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15465 		toh = (struct T_opthdr *)optptr;
15466 		toh->level = IPPROTO_IPV6;
15467 		toh->name = IPV6_HOPOPTS;
15468 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15469 		    tcp->tcp_label_len;
15470 		toh->status = 0;
15471 		optptr += sizeof (*toh);
15472 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15473 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15474 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15475 		ASSERT(OK_32PTR(optptr));
15476 		/* Save as last value */
15477 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15478 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15479 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15480 	}
15481 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15482 		toh = (struct T_opthdr *)optptr;
15483 		toh->level = IPPROTO_IPV6;
15484 		toh->name = IPV6_RTHDRDSTOPTS;
15485 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15486 		toh->status = 0;
15487 		optptr += sizeof (*toh);
15488 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15489 		optptr += ipp->ipp_rtdstoptslen;
15490 		ASSERT(OK_32PTR(optptr));
15491 		/* Save as last value */
15492 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15493 		    &tcp->tcp_rtdstoptslen,
15494 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15495 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15496 	}
15497 	if (addflag & TCP_IPV6_RECVRTHDR) {
15498 		toh = (struct T_opthdr *)optptr;
15499 		toh->level = IPPROTO_IPV6;
15500 		toh->name = IPV6_RTHDR;
15501 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15502 		toh->status = 0;
15503 		optptr += sizeof (*toh);
15504 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15505 		optptr += ipp->ipp_rthdrlen;
15506 		ASSERT(OK_32PTR(optptr));
15507 		/* Save as last value */
15508 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15509 		    (ipp->ipp_fields & IPPF_RTHDR),
15510 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15511 	}
15512 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15513 		toh = (struct T_opthdr *)optptr;
15514 		toh->level = IPPROTO_IPV6;
15515 		toh->name = IPV6_DSTOPTS;
15516 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15517 		toh->status = 0;
15518 		optptr += sizeof (*toh);
15519 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15520 		optptr += ipp->ipp_dstoptslen;
15521 		ASSERT(OK_32PTR(optptr));
15522 		/* Save as last value */
15523 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15524 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15525 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15526 	}
15527 	ASSERT(optptr == mp->b_wptr);
15528 	return (mp);
15529 }
15530 
15531 /*
15532  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15533  * messages.
15534  */
15535 void
15536 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15537 {
15538 	uchar_t	*rptr = mp->b_rptr;
15539 	queue_t	*q = tcp->tcp_rq;
15540 	struct T_error_ack *tea;
15541 
15542 	switch (mp->b_datap->db_type) {
15543 	case M_PROTO:
15544 	case M_PCPROTO:
15545 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15546 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15547 			break;
15548 		tea = (struct T_error_ack *)rptr;
15549 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15550 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15551 		    tea->ERROR_prim != T_BIND_REQ);
15552 		switch (tea->PRIM_type) {
15553 		case T_ERROR_ACK:
15554 			if (tcp->tcp_debug) {
15555 				(void) strlog(TCP_MOD_ID, 0, 1,
15556 				    SL_TRACE|SL_ERROR,
15557 				    "tcp_rput_other: case T_ERROR_ACK, "
15558 				    "ERROR_prim == %d",
15559 				    tea->ERROR_prim);
15560 			}
15561 			switch (tea->ERROR_prim) {
15562 			case T_SVR4_OPTMGMT_REQ:
15563 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15564 					/* T_OPTMGMT_REQ generated by TCP */
15565 					printf("T_SVR4_OPTMGMT_REQ failed "
15566 					    "%d/%d - dropped (cnt %d)\n",
15567 					    tea->TLI_error, tea->UNIX_error,
15568 					    tcp->tcp_drop_opt_ack_cnt);
15569 					freemsg(mp);
15570 					tcp->tcp_drop_opt_ack_cnt--;
15571 					return;
15572 				}
15573 				break;
15574 			}
15575 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15576 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15577 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15578 				    "- dropped (cnt %d)\n",
15579 				    tea->TLI_error, tea->UNIX_error,
15580 				    tcp->tcp_drop_opt_ack_cnt);
15581 				freemsg(mp);
15582 				tcp->tcp_drop_opt_ack_cnt--;
15583 				return;
15584 			}
15585 			break;
15586 		case T_OPTMGMT_ACK:
15587 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15588 				/* T_OPTMGMT_REQ generated by TCP */
15589 				freemsg(mp);
15590 				tcp->tcp_drop_opt_ack_cnt--;
15591 				return;
15592 			}
15593 			break;
15594 		default:
15595 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15596 			break;
15597 		}
15598 		break;
15599 	case M_FLUSH:
15600 		if (*rptr & FLUSHR)
15601 			flushq(q, FLUSHDATA);
15602 		break;
15603 	default:
15604 		/* M_CTL will be directly sent to tcp_icmp_error() */
15605 		ASSERT(DB_TYPE(mp) != M_CTL);
15606 		break;
15607 	}
15608 	/*
15609 	 * Make sure we set this bit before sending the ACK for
15610 	 * bind. Otherwise accept could possibly run and free
15611 	 * this tcp struct.
15612 	 */
15613 	ASSERT(q != NULL);
15614 	putnext(q, mp);
15615 }
15616 
15617 /* ARGSUSED */
15618 static void
15619 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15620 {
15621 	conn_t	*connp = (conn_t *)arg;
15622 	tcp_t	*tcp = connp->conn_tcp;
15623 	queue_t	*q = tcp->tcp_rq;
15624 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15625 
15626 	ASSERT(!IPCL_IS_NONSTR(connp));
15627 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15628 	tcp->tcp_rsrv_mp = mp;
15629 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15630 
15631 	TCP_STAT(tcps, tcp_rsrv_calls);
15632 
15633 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15634 		return;
15635 	}
15636 
15637 	if (tcp->tcp_fused) {
15638 		tcp_fuse_backenable(tcp);
15639 		return;
15640 	}
15641 
15642 	if (canputnext(q)) {
15643 		/* Not flow-controlled, open rwnd */
15644 		tcp->tcp_rwnd = q->q_hiwat;
15645 
15646 		/*
15647 		 * Send back a window update immediately if TCP is above
15648 		 * ESTABLISHED state and the increase of the rcv window
15649 		 * that the other side knows is at least 1 MSS after flow
15650 		 * control is lifted.
15651 		 */
15652 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15653 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
15654 			tcp_xmit_ctl(NULL, tcp,
15655 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15656 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15657 		}
15658 	}
15659 }
15660 
15661 /*
15662  * The read side service routine is called mostly when we get back-enabled as a
15663  * result of flow control relief.  Since we don't actually queue anything in
15664  * TCP, we have no data to send out of here.  What we do is clear the receive
15665  * window, and send out a window update.
15666  */
15667 static void
15668 tcp_rsrv(queue_t *q)
15669 {
15670 	conn_t		*connp = Q_TO_CONN(q);
15671 	tcp_t		*tcp = connp->conn_tcp;
15672 	mblk_t		*mp;
15673 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15674 
15675 	/* No code does a putq on the read side */
15676 	ASSERT(q->q_first == NULL);
15677 
15678 	/* Nothing to do for the default queue */
15679 	if (q == tcps->tcps_g_q) {
15680 		return;
15681 	}
15682 
15683 	/*
15684 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15685 	 * been run.  So just return.
15686 	 */
15687 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15688 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15689 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15690 		return;
15691 	}
15692 	tcp->tcp_rsrv_mp = NULL;
15693 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15694 
15695 	CONN_INC_REF(connp);
15696 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15697 	    SQ_PROCESS, SQTAG_TCP_RSRV);
15698 }
15699 
15700 /*
15701  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15702  * We do not allow the receive window to shrink.  After setting rwnd,
15703  * set the flow control hiwat of the stream.
15704  *
15705  * This function is called in 2 cases:
15706  *
15707  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15708  *    connection (passive open) and in tcp_rput_data() for active connect.
15709  *    This is called after tcp_mss_set() when the desired MSS value is known.
15710  *    This makes sure that our window size is a mutiple of the other side's
15711  *    MSS.
15712  * 2) Handling SO_RCVBUF option.
15713  *
15714  * It is ASSUMED that the requested size is a multiple of the current MSS.
15715  *
15716  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15717  * user requests so.
15718  */
15719 static int
15720 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15721 {
15722 	uint32_t	mss = tcp->tcp_mss;
15723 	uint32_t	old_max_rwnd;
15724 	uint32_t	max_transmittable_rwnd;
15725 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15726 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15727 
15728 	if (tcp->tcp_fused) {
15729 		size_t sth_hiwat;
15730 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15731 
15732 		ASSERT(peer_tcp != NULL);
15733 		/*
15734 		 * Record the stream head's high water mark for
15735 		 * this endpoint; this is used for flow-control
15736 		 * purposes in tcp_fuse_output().
15737 		 */
15738 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15739 		if (!tcp_detached) {
15740 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15741 			    sth_hiwat);
15742 			if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
15743 				conn_t *connp = tcp->tcp_connp;
15744 				struct sock_proto_props sopp;
15745 
15746 				sopp.sopp_flags = SOCKOPT_RCVTHRESH;
15747 				sopp.sopp_rcvthresh = sth_hiwat >> 3;
15748 
15749 				(*connp->conn_upcalls->su_set_proto_props)
15750 				    (connp->conn_upper_handle, &sopp);
15751 			}
15752 		}
15753 
15754 		/*
15755 		 * In the fusion case, the maxpsz stream head value of
15756 		 * our peer is set according to its send buffer size
15757 		 * and our receive buffer size; since the latter may
15758 		 * have changed we need to update the peer's maxpsz.
15759 		 */
15760 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15761 		return (rwnd);
15762 	}
15763 
15764 	if (tcp_detached) {
15765 		old_max_rwnd = tcp->tcp_rwnd;
15766 	} else {
15767 		old_max_rwnd = tcp->tcp_recv_hiwater;
15768 	}
15769 
15770 	/*
15771 	 * Insist on a receive window that is at least
15772 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15773 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15774 	 * and delayed acknowledgement.
15775 	 */
15776 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
15777 
15778 	/*
15779 	 * If window size info has already been exchanged, TCP should not
15780 	 * shrink the window.  Shrinking window is doable if done carefully.
15781 	 * We may add that support later.  But so far there is not a real
15782 	 * need to do that.
15783 	 */
15784 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15785 		/* MSS may have changed, do a round up again. */
15786 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15787 	}
15788 
15789 	/*
15790 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15791 	 * can be applied even before the window scale option is decided.
15792 	 */
15793 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15794 	if (rwnd > max_transmittable_rwnd) {
15795 		rwnd = max_transmittable_rwnd -
15796 		    (max_transmittable_rwnd % mss);
15797 		if (rwnd < mss)
15798 			rwnd = max_transmittable_rwnd;
15799 		/*
15800 		 * If we're over the limit we may have to back down tcp_rwnd.
15801 		 * The increment below won't work for us. So we set all three
15802 		 * here and the increment below will have no effect.
15803 		 */
15804 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15805 	}
15806 	if (tcp->tcp_localnet) {
15807 		tcp->tcp_rack_abs_max =
15808 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
15809 	} else {
15810 		/*
15811 		 * For a remote host on a different subnet (through a router),
15812 		 * we ack every other packet to be conforming to RFC1122.
15813 		 * tcp_deferred_acks_max is default to 2.
15814 		 */
15815 		tcp->tcp_rack_abs_max =
15816 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
15817 	}
15818 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15819 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15820 	else
15821 		tcp->tcp_rack_cur_max = 0;
15822 	/*
15823 	 * Increment the current rwnd by the amount the maximum grew (we
15824 	 * can not overwrite it since we might be in the middle of a
15825 	 * connection.)
15826 	 */
15827 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15828 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15829 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15830 		tcp->tcp_cwnd_max = rwnd;
15831 
15832 	if (tcp_detached)
15833 		return (rwnd);
15834 	/*
15835 	 * We set the maximum receive window into rq->q_hiwat if it is
15836 	 * a STREAMS socket.
15837 	 * This is not actually used for flow control.
15838 	 */
15839 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
15840 		tcp->tcp_rq->q_hiwat = rwnd;
15841 	tcp->tcp_recv_hiwater = rwnd;
15842 	/*
15843 	 * Set the STREAM head high water mark. This doesn't have to be
15844 	 * here, since we are simply using default values, but we would
15845 	 * prefer to choose these values algorithmically, with a likely
15846 	 * relationship to rwnd.
15847 	 */
15848 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15849 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
15850 	return (rwnd);
15851 }
15852 
15853 /*
15854  * Return SNMP stuff in buffer in mpdata.
15855  */
15856 mblk_t *
15857 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15858 {
15859 	mblk_t			*mpdata;
15860 	mblk_t			*mp_conn_ctl = NULL;
15861 	mblk_t			*mp_conn_tail;
15862 	mblk_t			*mp_attr_ctl = NULL;
15863 	mblk_t			*mp_attr_tail;
15864 	mblk_t			*mp6_conn_ctl = NULL;
15865 	mblk_t			*mp6_conn_tail;
15866 	mblk_t			*mp6_attr_ctl = NULL;
15867 	mblk_t			*mp6_attr_tail;
15868 	struct opthdr		*optp;
15869 	mib2_tcpConnEntry_t	tce;
15870 	mib2_tcp6ConnEntry_t	tce6;
15871 	mib2_transportMLPEntry_t mlp;
15872 	connf_t			*connfp;
15873 	int			i;
15874 	boolean_t 		ispriv;
15875 	zoneid_t 		zoneid;
15876 	int			v4_conn_idx;
15877 	int			v6_conn_idx;
15878 	conn_t			*connp = Q_TO_CONN(q);
15879 	tcp_stack_t		*tcps;
15880 	ip_stack_t		*ipst;
15881 	mblk_t			*mp2ctl;
15882 
15883 	/*
15884 	 * make a copy of the original message
15885 	 */
15886 	mp2ctl = copymsg(mpctl);
15887 
15888 	if (mpctl == NULL ||
15889 	    (mpdata = mpctl->b_cont) == NULL ||
15890 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15891 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
15892 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
15893 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
15894 		freemsg(mp_conn_ctl);
15895 		freemsg(mp_attr_ctl);
15896 		freemsg(mp6_conn_ctl);
15897 		freemsg(mp6_attr_ctl);
15898 		freemsg(mpctl);
15899 		freemsg(mp2ctl);
15900 		return (NULL);
15901 	}
15902 
15903 	ipst = connp->conn_netstack->netstack_ip;
15904 	tcps = connp->conn_netstack->netstack_tcp;
15905 
15906 	/* build table of connections -- need count in fixed part */
15907 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
15908 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
15909 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
15910 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
15911 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
15912 
15913 	ispriv =
15914 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15915 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15916 
15917 	v4_conn_idx = v6_conn_idx = 0;
15918 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
15919 
15920 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15921 		ipst = tcps->tcps_netstack->netstack_ip;
15922 
15923 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
15924 
15925 		connp = NULL;
15926 
15927 		while ((connp =
15928 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15929 			tcp_t *tcp;
15930 			boolean_t needattr;
15931 
15932 			if (connp->conn_zoneid != zoneid)
15933 				continue;	/* not in this zone */
15934 
15935 			tcp = connp->conn_tcp;
15936 			UPDATE_MIB(&tcps->tcps_mib,
15937 			    tcpHCInSegs, tcp->tcp_ibsegs);
15938 			tcp->tcp_ibsegs = 0;
15939 			UPDATE_MIB(&tcps->tcps_mib,
15940 			    tcpHCOutSegs, tcp->tcp_obsegs);
15941 			tcp->tcp_obsegs = 0;
15942 
15943 			tce6.tcp6ConnState = tce.tcpConnState =
15944 			    tcp_snmp_state(tcp);
15945 			if (tce.tcpConnState == MIB2_TCP_established ||
15946 			    tce.tcpConnState == MIB2_TCP_closeWait)
15947 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
15948 
15949 			needattr = B_FALSE;
15950 			bzero(&mlp, sizeof (mlp));
15951 			if (connp->conn_mlp_type != mlptSingle) {
15952 				if (connp->conn_mlp_type == mlptShared ||
15953 				    connp->conn_mlp_type == mlptBoth)
15954 					mlp.tme_flags |= MIB2_TMEF_SHARED;
15955 				if (connp->conn_mlp_type == mlptPrivate ||
15956 				    connp->conn_mlp_type == mlptBoth)
15957 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
15958 				needattr = B_TRUE;
15959 			}
15960 			if (connp->conn_anon_mlp) {
15961 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
15962 				needattr = B_TRUE;
15963 			}
15964 			if (connp->conn_mac_exempt) {
15965 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
15966 				needattr = B_TRUE;
15967 			}
15968 			if (connp->conn_fully_bound &&
15969 			    connp->conn_effective_cred != NULL) {
15970 				ts_label_t *tsl;
15971 
15972 				tsl = crgetlabel(connp->conn_effective_cred);
15973 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
15974 				mlp.tme_doi = label2doi(tsl);
15975 				mlp.tme_label = *label2bslabel(tsl);
15976 				needattr = B_TRUE;
15977 			}
15978 
15979 			/* Create a message to report on IPv6 entries */
15980 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15981 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15982 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15983 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15984 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15985 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15986 			/* Don't want just anybody seeing these... */
15987 			if (ispriv) {
15988 				tce6.tcp6ConnEntryInfo.ce_snxt =
15989 				    tcp->tcp_snxt;
15990 				tce6.tcp6ConnEntryInfo.ce_suna =
15991 				    tcp->tcp_suna;
15992 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15993 				    tcp->tcp_rnxt;
15994 				tce6.tcp6ConnEntryInfo.ce_rack =
15995 				    tcp->tcp_rack;
15996 			} else {
15997 				/*
15998 				 * Netstat, unfortunately, uses this to
15999 				 * get send/receive queue sizes.  How to fix?
16000 				 * Why not compute the difference only?
16001 				 */
16002 				tce6.tcp6ConnEntryInfo.ce_snxt =
16003 				    tcp->tcp_snxt - tcp->tcp_suna;
16004 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16005 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16006 				    tcp->tcp_rnxt - tcp->tcp_rack;
16007 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16008 			}
16009 
16010 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16011 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16012 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16013 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16014 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16015 
16016 			tce6.tcp6ConnCreationProcess =
16017 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16018 			    tcp->tcp_cpid;
16019 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16020 
16021 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16022 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16023 
16024 			mlp.tme_connidx = v6_conn_idx++;
16025 			if (needattr)
16026 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16027 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16028 			}
16029 			/*
16030 			 * Create an IPv4 table entry for IPv4 entries and also
16031 			 * for IPv6 entries which are bound to in6addr_any
16032 			 * but don't have IPV6_V6ONLY set.
16033 			 * (i.e. anything an IPv4 peer could connect to)
16034 			 */
16035 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16036 			    (tcp->tcp_state <= TCPS_LISTEN &&
16037 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16038 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16039 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16040 					tce.tcpConnRemAddress = INADDR_ANY;
16041 					tce.tcpConnLocalAddress = INADDR_ANY;
16042 				} else {
16043 					tce.tcpConnRemAddress =
16044 					    tcp->tcp_remote;
16045 					tce.tcpConnLocalAddress =
16046 					    tcp->tcp_ip_src;
16047 				}
16048 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16049 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16050 				/* Don't want just anybody seeing these... */
16051 				if (ispriv) {
16052 					tce.tcpConnEntryInfo.ce_snxt =
16053 					    tcp->tcp_snxt;
16054 					tce.tcpConnEntryInfo.ce_suna =
16055 					    tcp->tcp_suna;
16056 					tce.tcpConnEntryInfo.ce_rnxt =
16057 					    tcp->tcp_rnxt;
16058 					tce.tcpConnEntryInfo.ce_rack =
16059 					    tcp->tcp_rack;
16060 				} else {
16061 					/*
16062 					 * Netstat, unfortunately, uses this to
16063 					 * get send/receive queue sizes.  How
16064 					 * to fix?
16065 					 * Why not compute the difference only?
16066 					 */
16067 					tce.tcpConnEntryInfo.ce_snxt =
16068 					    tcp->tcp_snxt - tcp->tcp_suna;
16069 					tce.tcpConnEntryInfo.ce_suna = 0;
16070 					tce.tcpConnEntryInfo.ce_rnxt =
16071 					    tcp->tcp_rnxt - tcp->tcp_rack;
16072 					tce.tcpConnEntryInfo.ce_rack = 0;
16073 				}
16074 
16075 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16076 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16077 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16078 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16079 				tce.tcpConnEntryInfo.ce_state =
16080 				    tcp->tcp_state;
16081 
16082 				tce.tcpConnCreationProcess =
16083 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16084 				    tcp->tcp_cpid;
16085 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16086 
16087 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16088 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16089 
16090 				mlp.tme_connidx = v4_conn_idx++;
16091 				if (needattr)
16092 					(void) snmp_append_data2(
16093 					    mp_attr_ctl->b_cont,
16094 					    &mp_attr_tail, (char *)&mlp,
16095 					    sizeof (mlp));
16096 			}
16097 		}
16098 	}
16099 
16100 	/* fixed length structure for IPv4 and IPv6 counters */
16101 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16102 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16103 	    sizeof (mib2_tcp6ConnEntry_t));
16104 	/* synchronize 32- and 64-bit counters */
16105 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16106 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16107 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16108 	optp->level = MIB2_TCP;
16109 	optp->name = 0;
16110 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16111 	    sizeof (tcps->tcps_mib));
16112 	optp->len = msgdsize(mpdata);
16113 	qreply(q, mpctl);
16114 
16115 	/* table of connections... */
16116 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16117 	    sizeof (struct T_optmgmt_ack)];
16118 	optp->level = MIB2_TCP;
16119 	optp->name = MIB2_TCP_CONN;
16120 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16121 	qreply(q, mp_conn_ctl);
16122 
16123 	/* table of MLP attributes... */
16124 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16125 	    sizeof (struct T_optmgmt_ack)];
16126 	optp->level = MIB2_TCP;
16127 	optp->name = EXPER_XPORT_MLP;
16128 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16129 	if (optp->len == 0)
16130 		freemsg(mp_attr_ctl);
16131 	else
16132 		qreply(q, mp_attr_ctl);
16133 
16134 	/* table of IPv6 connections... */
16135 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16136 	    sizeof (struct T_optmgmt_ack)];
16137 	optp->level = MIB2_TCP6;
16138 	optp->name = MIB2_TCP6_CONN;
16139 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16140 	qreply(q, mp6_conn_ctl);
16141 
16142 	/* table of IPv6 MLP attributes... */
16143 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16144 	    sizeof (struct T_optmgmt_ack)];
16145 	optp->level = MIB2_TCP6;
16146 	optp->name = EXPER_XPORT_MLP;
16147 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16148 	if (optp->len == 0)
16149 		freemsg(mp6_attr_ctl);
16150 	else
16151 		qreply(q, mp6_attr_ctl);
16152 	return (mp2ctl);
16153 }
16154 
16155 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16156 /* ARGSUSED */
16157 int
16158 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16159 {
16160 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16161 
16162 	switch (level) {
16163 	case MIB2_TCP:
16164 		switch (name) {
16165 		case 13:
16166 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16167 				return (0);
16168 			/* TODO: delete entry defined by tce */
16169 			return (1);
16170 		default:
16171 			return (0);
16172 		}
16173 	default:
16174 		return (1);
16175 	}
16176 }
16177 
16178 /* Translate TCP state to MIB2 TCP state. */
16179 static int
16180 tcp_snmp_state(tcp_t *tcp)
16181 {
16182 	if (tcp == NULL)
16183 		return (0);
16184 
16185 	switch (tcp->tcp_state) {
16186 	case TCPS_CLOSED:
16187 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16188 	case TCPS_BOUND:
16189 		return (MIB2_TCP_closed);
16190 	case TCPS_LISTEN:
16191 		return (MIB2_TCP_listen);
16192 	case TCPS_SYN_SENT:
16193 		return (MIB2_TCP_synSent);
16194 	case TCPS_SYN_RCVD:
16195 		return (MIB2_TCP_synReceived);
16196 	case TCPS_ESTABLISHED:
16197 		return (MIB2_TCP_established);
16198 	case TCPS_CLOSE_WAIT:
16199 		return (MIB2_TCP_closeWait);
16200 	case TCPS_FIN_WAIT_1:
16201 		return (MIB2_TCP_finWait1);
16202 	case TCPS_CLOSING:
16203 		return (MIB2_TCP_closing);
16204 	case TCPS_LAST_ACK:
16205 		return (MIB2_TCP_lastAck);
16206 	case TCPS_FIN_WAIT_2:
16207 		return (MIB2_TCP_finWait2);
16208 	case TCPS_TIME_WAIT:
16209 		return (MIB2_TCP_timeWait);
16210 	default:
16211 		return (0);
16212 	}
16213 }
16214 
16215 /*
16216  * tcp_timer is the timer service routine.  It handles the retransmission,
16217  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16218  * from the state of the tcp instance what kind of action needs to be done
16219  * at the time it is called.
16220  */
16221 static void
16222 tcp_timer(void *arg)
16223 {
16224 	mblk_t		*mp;
16225 	clock_t		first_threshold;
16226 	clock_t		second_threshold;
16227 	clock_t		ms;
16228 	uint32_t	mss;
16229 	conn_t		*connp = (conn_t *)arg;
16230 	tcp_t		*tcp = connp->conn_tcp;
16231 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16232 
16233 	tcp->tcp_timer_tid = 0;
16234 
16235 	if (tcp->tcp_fused)
16236 		return;
16237 
16238 	first_threshold =  tcp->tcp_first_timer_threshold;
16239 	second_threshold = tcp->tcp_second_timer_threshold;
16240 	switch (tcp->tcp_state) {
16241 	case TCPS_IDLE:
16242 	case TCPS_BOUND:
16243 	case TCPS_LISTEN:
16244 		return;
16245 	case TCPS_SYN_RCVD: {
16246 		tcp_t	*listener = tcp->tcp_listener;
16247 
16248 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16249 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16250 			/* it's our first timeout */
16251 			tcp->tcp_syn_rcvd_timeout = 1;
16252 			mutex_enter(&listener->tcp_eager_lock);
16253 			listener->tcp_syn_rcvd_timeout++;
16254 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16255 				/*
16256 				 * Make this eager available for drop if we
16257 				 * need to drop one to accomodate a new
16258 				 * incoming SYN request.
16259 				 */
16260 				MAKE_DROPPABLE(listener, tcp);
16261 			}
16262 			if (!listener->tcp_syn_defense &&
16263 			    (listener->tcp_syn_rcvd_timeout >
16264 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16265 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16266 				/* We may be under attack. Put on a defense. */
16267 				listener->tcp_syn_defense = B_TRUE;
16268 				cmn_err(CE_WARN, "High TCP connect timeout "
16269 				    "rate! System (port %d) may be under a "
16270 				    "SYN flood attack!",
16271 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16272 
16273 				listener->tcp_ip_addr_cache = kmem_zalloc(
16274 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16275 				    KM_NOSLEEP);
16276 			}
16277 			mutex_exit(&listener->tcp_eager_lock);
16278 		} else if (listener != NULL) {
16279 			mutex_enter(&listener->tcp_eager_lock);
16280 			tcp->tcp_syn_rcvd_timeout++;
16281 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16282 			    !tcp->tcp_closemp_used) {
16283 				/*
16284 				 * This is our second timeout. Put the tcp in
16285 				 * the list of droppable eagers to allow it to
16286 				 * be dropped, if needed. We don't check
16287 				 * whether tcp_dontdrop is set or not to
16288 				 * protect ourselve from a SYN attack where a
16289 				 * remote host can spoof itself as one of the
16290 				 * good IP source and continue to hold
16291 				 * resources too long.
16292 				 */
16293 				MAKE_DROPPABLE(listener, tcp);
16294 			}
16295 			mutex_exit(&listener->tcp_eager_lock);
16296 		}
16297 	}
16298 		/* FALLTHRU */
16299 	case TCPS_SYN_SENT:
16300 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16301 		second_threshold = tcp->tcp_second_ctimer_threshold;
16302 		break;
16303 	case TCPS_ESTABLISHED:
16304 	case TCPS_FIN_WAIT_1:
16305 	case TCPS_CLOSING:
16306 	case TCPS_CLOSE_WAIT:
16307 	case TCPS_LAST_ACK:
16308 		/* If we have data to rexmit */
16309 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16310 			clock_t	time_to_wait;
16311 
16312 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16313 			if (!tcp->tcp_xmit_head)
16314 				break;
16315 			time_to_wait = lbolt -
16316 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16317 			time_to_wait = tcp->tcp_rto -
16318 			    TICK_TO_MSEC(time_to_wait);
16319 			/*
16320 			 * If the timer fires too early, 1 clock tick earlier,
16321 			 * restart the timer.
16322 			 */
16323 			if (time_to_wait > msec_per_tick) {
16324 				TCP_STAT(tcps, tcp_timer_fire_early);
16325 				TCP_TIMER_RESTART(tcp, time_to_wait);
16326 				return;
16327 			}
16328 			/*
16329 			 * When we probe zero windows, we force the swnd open.
16330 			 * If our peer acks with a closed window swnd will be
16331 			 * set to zero by tcp_rput(). As long as we are
16332 			 * receiving acks tcp_rput will
16333 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16334 			 * first and second interval actions.  NOTE: the timer
16335 			 * interval is allowed to continue its exponential
16336 			 * backoff.
16337 			 */
16338 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16339 				if (tcp->tcp_debug) {
16340 					(void) strlog(TCP_MOD_ID, 0, 1,
16341 					    SL_TRACE, "tcp_timer: zero win");
16342 				}
16343 			} else {
16344 				/*
16345 				 * After retransmission, we need to do
16346 				 * slow start.  Set the ssthresh to one
16347 				 * half of current effective window and
16348 				 * cwnd to one MSS.  Also reset
16349 				 * tcp_cwnd_cnt.
16350 				 *
16351 				 * Note that if tcp_ssthresh is reduced because
16352 				 * of ECN, do not reduce it again unless it is
16353 				 * already one window of data away (tcp_cwr
16354 				 * should then be cleared) or this is a
16355 				 * timeout for a retransmitted segment.
16356 				 */
16357 				uint32_t npkt;
16358 
16359 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16360 					npkt = ((tcp->tcp_timer_backoff ?
16361 					    tcp->tcp_cwnd_ssthresh :
16362 					    tcp->tcp_snxt -
16363 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16364 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16365 					    tcp->tcp_mss;
16366 				}
16367 				tcp->tcp_cwnd = tcp->tcp_mss;
16368 				tcp->tcp_cwnd_cnt = 0;
16369 				if (tcp->tcp_ecn_ok) {
16370 					tcp->tcp_cwr = B_TRUE;
16371 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16372 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16373 				}
16374 			}
16375 			break;
16376 		}
16377 		/*
16378 		 * We have something to send yet we cannot send.  The
16379 		 * reason can be:
16380 		 *
16381 		 * 1. Zero send window: we need to do zero window probe.
16382 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16383 		 * segments.
16384 		 * 3. SWS avoidance: receiver may have shrunk window,
16385 		 * reset our knowledge.
16386 		 *
16387 		 * Note that condition 2 can happen with either 1 or
16388 		 * 3.  But 1 and 3 are exclusive.
16389 		 */
16390 		if (tcp->tcp_unsent != 0) {
16391 			if (tcp->tcp_cwnd == 0) {
16392 				/*
16393 				 * Set tcp_cwnd to 1 MSS so that a
16394 				 * new segment can be sent out.  We
16395 				 * are "clocking out" new data when
16396 				 * the network is really congested.
16397 				 */
16398 				ASSERT(tcp->tcp_ecn_ok);
16399 				tcp->tcp_cwnd = tcp->tcp_mss;
16400 			}
16401 			if (tcp->tcp_swnd == 0) {
16402 				/* Extend window for zero window probe */
16403 				tcp->tcp_swnd++;
16404 				tcp->tcp_zero_win_probe = B_TRUE;
16405 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
16406 			} else {
16407 				/*
16408 				 * Handle timeout from sender SWS avoidance.
16409 				 * Reset our knowledge of the max send window
16410 				 * since the receiver might have reduced its
16411 				 * receive buffer.  Avoid setting tcp_max_swnd
16412 				 * to one since that will essentially disable
16413 				 * the SWS checks.
16414 				 *
16415 				 * Note that since we don't have a SWS
16416 				 * state variable, if the timeout is set
16417 				 * for ECN but not for SWS, this
16418 				 * code will also be executed.  This is
16419 				 * fine as tcp_max_swnd is updated
16420 				 * constantly and it will not affect
16421 				 * anything.
16422 				 */
16423 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16424 			}
16425 			tcp_wput_data(tcp, NULL, B_FALSE);
16426 			return;
16427 		}
16428 		/* Is there a FIN that needs to be to re retransmitted? */
16429 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16430 		    !tcp->tcp_fin_acked)
16431 			break;
16432 		/* Nothing to do, return without restarting timer. */
16433 		TCP_STAT(tcps, tcp_timer_fire_miss);
16434 		return;
16435 	case TCPS_FIN_WAIT_2:
16436 		/*
16437 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16438 		 * We waited some time for for peer's FIN, but it hasn't
16439 		 * arrived.  We flush the connection now to avoid
16440 		 * case where the peer has rebooted.
16441 		 */
16442 		if (TCP_IS_DETACHED(tcp)) {
16443 			(void) tcp_clean_death(tcp, 0, 23);
16444 		} else {
16445 			TCP_TIMER_RESTART(tcp,
16446 			    tcps->tcps_fin_wait_2_flush_interval);
16447 		}
16448 		return;
16449 	case TCPS_TIME_WAIT:
16450 		(void) tcp_clean_death(tcp, 0, 24);
16451 		return;
16452 	default:
16453 		if (tcp->tcp_debug) {
16454 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16455 			    "tcp_timer: strange state (%d) %s",
16456 			    tcp->tcp_state, tcp_display(tcp, NULL,
16457 			    DISP_PORT_ONLY));
16458 		}
16459 		return;
16460 	}
16461 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16462 		/*
16463 		 * For zero window probe, we need to send indefinitely,
16464 		 * unless we have not heard from the other side for some
16465 		 * time...
16466 		 */
16467 		if ((tcp->tcp_zero_win_probe == 0) ||
16468 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16469 		    second_threshold)) {
16470 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
16471 			/*
16472 			 * If TCP is in SYN_RCVD state, send back a
16473 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16474 			 * should be zero in TCPS_SYN_RCVD state.
16475 			 */
16476 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16477 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16478 				    "in SYN_RCVD",
16479 				    tcp, tcp->tcp_snxt,
16480 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16481 			}
16482 			(void) tcp_clean_death(tcp,
16483 			    tcp->tcp_client_errno ?
16484 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16485 			return;
16486 		} else {
16487 			/*
16488 			 * Set tcp_ms_we_have_waited to second_threshold
16489 			 * so that in next timeout, we will do the above
16490 			 * check (lbolt - tcp_last_recv_time).  This is
16491 			 * also to avoid overflow.
16492 			 *
16493 			 * We don't need to decrement tcp_timer_backoff
16494 			 * to avoid overflow because it will be decremented
16495 			 * later if new timeout value is greater than
16496 			 * tcp_rexmit_interval_max.  In the case when
16497 			 * tcp_rexmit_interval_max is greater than
16498 			 * second_threshold, it means that we will wait
16499 			 * longer than second_threshold to send the next
16500 			 * window probe.
16501 			 */
16502 			tcp->tcp_ms_we_have_waited = second_threshold;
16503 		}
16504 	} else if (ms > first_threshold) {
16505 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16506 		    tcp->tcp_xmit_head != NULL) {
16507 			tcp->tcp_xmit_head =
16508 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16509 		}
16510 		/*
16511 		 * We have been retransmitting for too long...  The RTT
16512 		 * we calculated is probably incorrect.  Reinitialize it.
16513 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16514 		 * tcp_rtt_update so that we won't accidentally cache a
16515 		 * bad value.  But only do this if this is not a zero
16516 		 * window probe.
16517 		 */
16518 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16519 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16520 			    (tcp->tcp_rtt_sa >> 5);
16521 			tcp->tcp_rtt_sa = 0;
16522 			tcp_ip_notify(tcp);
16523 			tcp->tcp_rtt_update = 0;
16524 		}
16525 	}
16526 	tcp->tcp_timer_backoff++;
16527 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16528 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16529 	    tcps->tcps_rexmit_interval_min) {
16530 		/*
16531 		 * This means the original RTO is tcp_rexmit_interval_min.
16532 		 * So we will use tcp_rexmit_interval_min as the RTO value
16533 		 * and do the backoff.
16534 		 */
16535 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
16536 	} else {
16537 		ms <<= tcp->tcp_timer_backoff;
16538 	}
16539 	if (ms > tcps->tcps_rexmit_interval_max) {
16540 		ms = tcps->tcps_rexmit_interval_max;
16541 		/*
16542 		 * ms is at max, decrement tcp_timer_backoff to avoid
16543 		 * overflow.
16544 		 */
16545 		tcp->tcp_timer_backoff--;
16546 	}
16547 	tcp->tcp_ms_we_have_waited += ms;
16548 	if (tcp->tcp_zero_win_probe == 0) {
16549 		tcp->tcp_rto = ms;
16550 	}
16551 	TCP_TIMER_RESTART(tcp, ms);
16552 	/*
16553 	 * This is after a timeout and tcp_rto is backed off.  Set
16554 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16555 	 * restart the timer with a correct value.
16556 	 */
16557 	tcp->tcp_set_timer = 1;
16558 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16559 	if (mss > tcp->tcp_mss)
16560 		mss = tcp->tcp_mss;
16561 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16562 		mss = tcp->tcp_swnd;
16563 
16564 	if ((mp = tcp->tcp_xmit_head) != NULL)
16565 		mp->b_prev = (mblk_t *)lbolt;
16566 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16567 	    B_TRUE);
16568 
16569 	/*
16570 	 * When slow start after retransmission begins, start with
16571 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16572 	 * start phase.  tcp_snd_burst controls how many segments
16573 	 * can be sent because of an ack.
16574 	 */
16575 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16576 	tcp->tcp_snd_burst = TCP_CWND_SS;
16577 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16578 	    (tcp->tcp_unsent == 0)) {
16579 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16580 	} else {
16581 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16582 	}
16583 	tcp->tcp_rexmit = B_TRUE;
16584 	tcp->tcp_dupack_cnt = 0;
16585 
16586 	/*
16587 	 * Remove all rexmit SACK blk to start from fresh.
16588 	 */
16589 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
16590 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
16591 	if (mp == NULL) {
16592 		return;
16593 	}
16594 	/*
16595 	 * Attach credentials to retransmitted initial SYNs.
16596 	 * In theory we should use the credentials from the connect()
16597 	 * call to ensure that getpeerucred() on the peer will be correct.
16598 	 * But we assume that SYN's are not dropped for loopback connections.
16599 	 */
16600 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16601 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp), tcp->tcp_cpid);
16602 	}
16603 
16604 	tcp->tcp_csuna = tcp->tcp_snxt;
16605 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
16606 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
16607 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16608 
16609 }
16610 
16611 static int
16612 tcp_do_unbind(conn_t *connp)
16613 {
16614 	tcp_t *tcp = connp->conn_tcp;
16615 	int error = 0;
16616 
16617 	switch (tcp->tcp_state) {
16618 	case TCPS_BOUND:
16619 	case TCPS_LISTEN:
16620 		break;
16621 	default:
16622 		return (-TOUTSTATE);
16623 	}
16624 
16625 	/*
16626 	 * Need to clean up all the eagers since after the unbind, segments
16627 	 * will no longer be delivered to this listener stream.
16628 	 */
16629 	mutex_enter(&tcp->tcp_eager_lock);
16630 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16631 		tcp_eager_cleanup(tcp, 0);
16632 	}
16633 	mutex_exit(&tcp->tcp_eager_lock);
16634 
16635 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16636 		tcp->tcp_ipha->ipha_src = 0;
16637 	} else {
16638 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16639 	}
16640 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16641 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16642 	tcp_bind_hash_remove(tcp);
16643 	tcp->tcp_state = TCPS_IDLE;
16644 	tcp->tcp_mdt = B_FALSE;
16645 
16646 	connp = tcp->tcp_connp;
16647 	connp->conn_mdt_ok = B_FALSE;
16648 	ipcl_hash_remove(connp);
16649 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16650 
16651 	return (error);
16652 }
16653 
16654 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16655 static void
16656 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
16657 {
16658 	int error = tcp_do_unbind(tcp->tcp_connp);
16659 
16660 	if (error > 0) {
16661 		tcp_err_ack(tcp, mp, TSYSERR, error);
16662 	} else if (error < 0) {
16663 		tcp_err_ack(tcp, mp, -error, 0);
16664 	} else {
16665 		/* Send M_FLUSH according to TPI */
16666 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16667 
16668 		mp = mi_tpi_ok_ack_alloc(mp);
16669 		putnext(tcp->tcp_rq, mp);
16670 	}
16671 }
16672 
16673 /*
16674  * Don't let port fall into the privileged range.
16675  * Since the extra privileged ports can be arbitrary we also
16676  * ensure that we exclude those from consideration.
16677  * tcp_g_epriv_ports is not sorted thus we loop over it until
16678  * there are no changes.
16679  *
16680  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16681  * but instead the code relies on:
16682  * - the fact that the address of the array and its size never changes
16683  * - the atomic assignment of the elements of the array
16684  *
16685  * Returns 0 if there are no more ports available.
16686  *
16687  * TS note: skip multilevel ports.
16688  */
16689 static in_port_t
16690 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16691 {
16692 	int i;
16693 	boolean_t restart = B_FALSE;
16694 	tcp_stack_t *tcps = tcp->tcp_tcps;
16695 
16696 	if (random && tcp_random_anon_port != 0) {
16697 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16698 		    sizeof (in_port_t));
16699 		/*
16700 		 * Unless changed by a sys admin, the smallest anon port
16701 		 * is 32768 and the largest anon port is 65535.  It is
16702 		 * very likely (50%) for the random port to be smaller
16703 		 * than the smallest anon port.  When that happens,
16704 		 * add port % (anon port range) to the smallest anon
16705 		 * port to get the random port.  It should fall into the
16706 		 * valid anon port range.
16707 		 */
16708 		if (port < tcps->tcps_smallest_anon_port) {
16709 			port = tcps->tcps_smallest_anon_port +
16710 			    port % (tcps->tcps_largest_anon_port -
16711 			    tcps->tcps_smallest_anon_port);
16712 		}
16713 	}
16714 
16715 retry:
16716 	if (port < tcps->tcps_smallest_anon_port)
16717 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16718 
16719 	if (port > tcps->tcps_largest_anon_port) {
16720 		if (restart)
16721 			return (0);
16722 		restart = B_TRUE;
16723 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16724 	}
16725 
16726 	if (port < tcps->tcps_smallest_nonpriv_port)
16727 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
16728 
16729 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
16730 		if (port == tcps->tcps_g_epriv_ports[i]) {
16731 			port++;
16732 			/*
16733 			 * Make sure whether the port is in the
16734 			 * valid range.
16735 			 */
16736 			goto retry;
16737 		}
16738 	}
16739 	if (is_system_labeled() &&
16740 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
16741 	    IPPROTO_TCP, B_TRUE)) != 0) {
16742 		port = i;
16743 		goto retry;
16744 	}
16745 	return (port);
16746 }
16747 
16748 /*
16749  * Return the next anonymous port in the privileged port range for
16750  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16751  * downwards.  This is the same behavior as documented in the userland
16752  * library call rresvport(3N).
16753  *
16754  * TS note: skip multilevel ports.
16755  */
16756 static in_port_t
16757 tcp_get_next_priv_port(const tcp_t *tcp)
16758 {
16759 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16760 	in_port_t nextport;
16761 	boolean_t restart = B_FALSE;
16762 	tcp_stack_t *tcps = tcp->tcp_tcps;
16763 retry:
16764 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
16765 	    next_priv_port >= IPPORT_RESERVED) {
16766 		next_priv_port = IPPORT_RESERVED - 1;
16767 		if (restart)
16768 			return (0);
16769 		restart = B_TRUE;
16770 	}
16771 	if (is_system_labeled() &&
16772 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
16773 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
16774 		next_priv_port = nextport;
16775 		goto retry;
16776 	}
16777 	return (next_priv_port--);
16778 }
16779 
16780 /* The write side r/w procedure. */
16781 
16782 #if CCS_STATS
16783 struct {
16784 	struct {
16785 		int64_t count, bytes;
16786 	} tot, hit;
16787 } wrw_stats;
16788 #endif
16789 
16790 /*
16791  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16792  * messages.
16793  */
16794 /* ARGSUSED */
16795 static void
16796 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16797 {
16798 	conn_t	*connp = (conn_t *)arg;
16799 	tcp_t	*tcp = connp->conn_tcp;
16800 	queue_t	*q = tcp->tcp_wq;
16801 
16802 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16803 	/*
16804 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16805 	 * Once the close starts, streamhead and sockfs will not let any data
16806 	 * packets come down (close ensures that there are no threads using the
16807 	 * queue and no new threads will come down) but since qprocsoff()
16808 	 * hasn't happened yet, a M_FLUSH or some non data message might
16809 	 * get reflected back (in response to our own FLUSHRW) and get
16810 	 * processed after tcp_close() is done. The conn would still be valid
16811 	 * because a ref would have added but we need to check the state
16812 	 * before actually processing the packet.
16813 	 */
16814 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16815 		freemsg(mp);
16816 		return;
16817 	}
16818 
16819 	switch (DB_TYPE(mp)) {
16820 	case M_IOCDATA:
16821 		tcp_wput_iocdata(tcp, mp);
16822 		break;
16823 	case M_FLUSH:
16824 		tcp_wput_flush(tcp, mp);
16825 		break;
16826 	default:
16827 		CALL_IP_WPUT(connp, q, mp);
16828 		break;
16829 	}
16830 }
16831 
16832 /*
16833  * The TCP fast path write put procedure.
16834  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16835  */
16836 /* ARGSUSED */
16837 void
16838 tcp_output(void *arg, mblk_t *mp, void *arg2)
16839 {
16840 	int		len;
16841 	int		hdrlen;
16842 	int		plen;
16843 	mblk_t		*mp1;
16844 	uchar_t		*rptr;
16845 	uint32_t	snxt;
16846 	tcph_t		*tcph;
16847 	struct datab	*db;
16848 	uint32_t	suna;
16849 	uint32_t	mss;
16850 	ipaddr_t	*dst;
16851 	ipaddr_t	*src;
16852 	uint32_t	sum;
16853 	int		usable;
16854 	conn_t		*connp = (conn_t *)arg;
16855 	tcp_t		*tcp = connp->conn_tcp;
16856 	uint32_t	msize;
16857 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16858 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
16859 
16860 	/*
16861 	 * Try and ASSERT the minimum possible references on the
16862 	 * conn early enough. Since we are executing on write side,
16863 	 * the connection is obviously not detached and that means
16864 	 * there is a ref each for TCP and IP. Since we are behind
16865 	 * the squeue, the minimum references needed are 3. If the
16866 	 * conn is in classifier hash list, there should be an
16867 	 * extra ref for that (we check both the possibilities).
16868 	 */
16869 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16870 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16871 
16872 	ASSERT(DB_TYPE(mp) == M_DATA);
16873 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
16874 
16875 	mutex_enter(&tcp->tcp_non_sq_lock);
16876 	tcp->tcp_squeue_bytes -= msize;
16877 	mutex_exit(&tcp->tcp_non_sq_lock);
16878 
16879 	/* Check to see if this connection wants to be re-fused. */
16880 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
16881 		if (tcp->tcp_ipversion == IPV4_VERSION) {
16882 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
16883 			    &tcp->tcp_saved_tcph);
16884 		} else {
16885 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
16886 			    &tcp->tcp_saved_tcph);
16887 		}
16888 	}
16889 	/* Bypass tcp protocol for fused tcp loopback */
16890 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
16891 		return;
16892 
16893 	mss = tcp->tcp_mss;
16894 	if (tcp->tcp_xmit_zc_clean)
16895 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16896 
16897 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16898 	len = (int)(mp->b_wptr - mp->b_rptr);
16899 
16900 	/*
16901 	 * Criteria for fast path:
16902 	 *
16903 	 *   1. no unsent data
16904 	 *   2. single mblk in request
16905 	 *   3. connection established
16906 	 *   4. data in mblk
16907 	 *   5. len <= mss
16908 	 *   6. no tcp_valid bits
16909 	 */
16910 	if ((tcp->tcp_unsent != 0) ||
16911 	    (tcp->tcp_cork) ||
16912 	    (mp->b_cont != NULL) ||
16913 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16914 	    (len == 0) ||
16915 	    (len > mss) ||
16916 	    (tcp->tcp_valid_bits != 0)) {
16917 		tcp_wput_data(tcp, mp, B_FALSE);
16918 		return;
16919 	}
16920 
16921 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16922 	ASSERT(tcp->tcp_fin_sent == 0);
16923 
16924 	/* queue new packet onto retransmission queue */
16925 	if (tcp->tcp_xmit_head == NULL) {
16926 		tcp->tcp_xmit_head = mp;
16927 	} else {
16928 		tcp->tcp_xmit_last->b_cont = mp;
16929 	}
16930 	tcp->tcp_xmit_last = mp;
16931 	tcp->tcp_xmit_tail = mp;
16932 
16933 	/* find out how much we can send */
16934 	/* BEGIN CSTYLED */
16935 	/*
16936 	 *    un-acked	   usable
16937 	 *  |--------------|-----------------|
16938 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
16939 	 */
16940 	/* END CSTYLED */
16941 
16942 	/* start sending from tcp_snxt */
16943 	snxt = tcp->tcp_snxt;
16944 
16945 	/*
16946 	 * Check to see if this connection has been idled for some
16947 	 * time and no ACK is expected.  If it is, we need to slow
16948 	 * start again to get back the connection's "self-clock" as
16949 	 * described in VJ's paper.
16950 	 *
16951 	 * Refer to the comment in tcp_mss_set() for the calculation
16952 	 * of tcp_cwnd after idle.
16953 	 */
16954 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16955 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16956 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
16957 	}
16958 
16959 	usable = tcp->tcp_swnd;		/* tcp window size */
16960 	if (usable > tcp->tcp_cwnd)
16961 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16962 	usable -= snxt;		/* subtract stuff already sent */
16963 	suna = tcp->tcp_suna;
16964 	usable += suna;
16965 	/* usable can be < 0 if the congestion window is smaller */
16966 	if (len > usable) {
16967 		/* Can't send complete M_DATA in one shot */
16968 		goto slow;
16969 	}
16970 
16971 	mutex_enter(&tcp->tcp_non_sq_lock);
16972 	if (tcp->tcp_flow_stopped &&
16973 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16974 		tcp_clrqfull(tcp);
16975 	}
16976 	mutex_exit(&tcp->tcp_non_sq_lock);
16977 
16978 	/*
16979 	 * determine if anything to send (Nagle).
16980 	 *
16981 	 *   1. len < tcp_mss (i.e. small)
16982 	 *   2. unacknowledged data present
16983 	 *   3. len < nagle limit
16984 	 *   4. last packet sent < nagle limit (previous packet sent)
16985 	 */
16986 	if ((len < mss) && (snxt != suna) &&
16987 	    (len < (int)tcp->tcp_naglim) &&
16988 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
16989 		/*
16990 		 * This was the first unsent packet and normally
16991 		 * mss < xmit_hiwater so there is no need to worry
16992 		 * about flow control. The next packet will go
16993 		 * through the flow control check in tcp_wput_data().
16994 		 */
16995 		/* leftover work from above */
16996 		tcp->tcp_unsent = len;
16997 		tcp->tcp_xmit_tail_unsent = len;
16998 
16999 		return;
17000 	}
17001 
17002 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17003 
17004 	if (snxt == suna) {
17005 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17006 	}
17007 
17008 	/* we have always sent something */
17009 	tcp->tcp_rack_cnt = 0;
17010 
17011 	tcp->tcp_snxt = snxt + len;
17012 	tcp->tcp_rack = tcp->tcp_rnxt;
17013 
17014 	if ((mp1 = dupb(mp)) == 0)
17015 		goto no_memory;
17016 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17017 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17018 
17019 	/* adjust tcp header information */
17020 	tcph = tcp->tcp_tcph;
17021 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17022 
17023 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17024 	sum = (sum >> 16) + (sum & 0xFFFF);
17025 	U16_TO_ABE16(sum, tcph->th_sum);
17026 
17027 	U32_TO_ABE32(snxt, tcph->th_seq);
17028 
17029 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17030 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17031 	BUMP_LOCAL(tcp->tcp_obsegs);
17032 
17033 	/* Update the latest receive window size in TCP header. */
17034 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17035 	    tcph->th_win);
17036 
17037 	tcp->tcp_last_sent_len = (ushort_t)len;
17038 
17039 	plen = len + tcp->tcp_hdr_len;
17040 
17041 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17042 		tcp->tcp_ipha->ipha_length = htons(plen);
17043 	} else {
17044 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17045 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17046 	}
17047 
17048 	/* see if we need to allocate a mblk for the headers */
17049 	hdrlen = tcp->tcp_hdr_len;
17050 	rptr = mp1->b_rptr - hdrlen;
17051 	db = mp1->b_datap;
17052 	if ((db->db_ref != 2) || rptr < db->db_base ||
17053 	    (!OK_32PTR(rptr))) {
17054 		/* NOTE: we assume allocb returns an OK_32PTR */
17055 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17056 		    tcps->tcps_wroff_xtra, BPRI_MED);
17057 		if (!mp) {
17058 			freemsg(mp1);
17059 			goto no_memory;
17060 		}
17061 		mp->b_cont = mp1;
17062 		mp1 = mp;
17063 		/* Leave room for Link Level header */
17064 		/* hdrlen = tcp->tcp_hdr_len; */
17065 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17066 		mp1->b_wptr = &rptr[hdrlen];
17067 	}
17068 	mp1->b_rptr = rptr;
17069 
17070 	/* Fill in the timestamp option. */
17071 	if (tcp->tcp_snd_ts_ok) {
17072 		U32_TO_BE32((uint32_t)lbolt,
17073 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17074 		U32_TO_BE32(tcp->tcp_ts_recent,
17075 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17076 	} else {
17077 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17078 	}
17079 
17080 	/* copy header into outgoing packet */
17081 	dst = (ipaddr_t *)rptr;
17082 	src = (ipaddr_t *)tcp->tcp_iphc;
17083 	dst[0] = src[0];
17084 	dst[1] = src[1];
17085 	dst[2] = src[2];
17086 	dst[3] = src[3];
17087 	dst[4] = src[4];
17088 	dst[5] = src[5];
17089 	dst[6] = src[6];
17090 	dst[7] = src[7];
17091 	dst[8] = src[8];
17092 	dst[9] = src[9];
17093 	if (hdrlen -= 40) {
17094 		hdrlen >>= 2;
17095 		dst += 10;
17096 		src += 10;
17097 		do {
17098 			*dst++ = *src++;
17099 		} while (--hdrlen);
17100 	}
17101 
17102 	/*
17103 	 * Set the ECN info in the TCP header.  Note that this
17104 	 * is not the template header.
17105 	 */
17106 	if (tcp->tcp_ecn_ok) {
17107 		SET_ECT(tcp, rptr);
17108 
17109 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17110 		if (tcp->tcp_ecn_echo_on)
17111 			tcph->th_flags[0] |= TH_ECE;
17112 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17113 			tcph->th_flags[0] |= TH_CWR;
17114 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17115 		}
17116 	}
17117 
17118 	if (tcp->tcp_ip_forward_progress) {
17119 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17120 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17121 		tcp->tcp_ip_forward_progress = B_FALSE;
17122 	}
17123 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17124 	return;
17125 
17126 	/*
17127 	 * If we ran out of memory, we pretend to have sent the packet
17128 	 * and that it was lost on the wire.
17129 	 */
17130 no_memory:
17131 	return;
17132 
17133 slow:
17134 	/* leftover work from above */
17135 	tcp->tcp_unsent = len;
17136 	tcp->tcp_xmit_tail_unsent = len;
17137 	tcp_wput_data(tcp, NULL, B_FALSE);
17138 }
17139 
17140 /* ARGSUSED */
17141 void
17142 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17143 {
17144 	conn_t			*connp = (conn_t *)arg;
17145 	tcp_t			*tcp = connp->conn_tcp;
17146 	queue_t			*q = tcp->tcp_rq;
17147 	struct tcp_options	*tcpopt;
17148 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17149 
17150 	/* socket options */
17151 	uint_t 			sopp_flags;
17152 	ssize_t			sopp_rxhiwat;
17153 	ssize_t			sopp_maxblk;
17154 	ushort_t		sopp_wroff;
17155 	ushort_t		sopp_tail;
17156 	ushort_t		sopp_copyopt;
17157 
17158 	tcpopt = (struct tcp_options *)mp->b_rptr;
17159 
17160 	/*
17161 	 * Drop the eager's ref on the listener, that was placed when
17162 	 * this eager began life in tcp_conn_request.
17163 	 */
17164 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17165 	if (IPCL_IS_NONSTR(connp)) {
17166 		/* Safe to free conn_ind message */
17167 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17168 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17169 	}
17170 
17171 	tcp->tcp_detached = B_FALSE;
17172 
17173 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17174 		/*
17175 		 * Someone blewoff the eager before we could finish
17176 		 * the accept.
17177 		 *
17178 		 * The only reason eager exists it because we put in
17179 		 * a ref on it when conn ind went up. We need to send
17180 		 * a disconnect indication up while the last reference
17181 		 * on the eager will be dropped by the squeue when we
17182 		 * return.
17183 		 */
17184 		ASSERT(tcp->tcp_listener == NULL);
17185 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17186 			if (IPCL_IS_NONSTR(connp)) {
17187 				ASSERT(tcp->tcp_issocket);
17188 				(*connp->conn_upcalls->su_disconnected)(
17189 				    connp->conn_upper_handle, tcp->tcp_connid,
17190 				    ECONNREFUSED);
17191 				freemsg(mp);
17192 			} else {
17193 				struct	T_discon_ind	*tdi;
17194 
17195 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17196 				/*
17197 				 * Let us reuse the incoming mblk to avoid
17198 				 * memory allocation failure problems. We know
17199 				 * that the size of the incoming mblk i.e.
17200 				 * stroptions is greater than sizeof
17201 				 * T_discon_ind. So the reallocb below can't
17202 				 * fail.
17203 				 */
17204 				freemsg(mp->b_cont);
17205 				mp->b_cont = NULL;
17206 				ASSERT(DB_REF(mp) == 1);
17207 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17208 				    B_FALSE);
17209 				ASSERT(mp != NULL);
17210 				DB_TYPE(mp) = M_PROTO;
17211 				((union T_primitives *)mp->b_rptr)->type =
17212 				    T_DISCON_IND;
17213 				tdi = (struct T_discon_ind *)mp->b_rptr;
17214 				if (tcp->tcp_issocket) {
17215 					tdi->DISCON_reason = ECONNREFUSED;
17216 					tdi->SEQ_number = 0;
17217 				} else {
17218 					tdi->DISCON_reason = ENOPROTOOPT;
17219 					tdi->SEQ_number =
17220 					    tcp->tcp_conn_req_seqnum;
17221 				}
17222 				mp->b_wptr = mp->b_rptr +
17223 				    sizeof (struct T_discon_ind);
17224 				putnext(q, mp);
17225 				return;
17226 			}
17227 		}
17228 		if (tcp->tcp_hard_binding) {
17229 			tcp->tcp_hard_binding = B_FALSE;
17230 			tcp->tcp_hard_bound = B_TRUE;
17231 		}
17232 		return;
17233 	}
17234 
17235 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17236 		int boundif = tcpopt->to_boundif;
17237 		uint_t len = sizeof (int);
17238 
17239 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17240 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17241 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17242 	}
17243 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17244 		uint_t on = 1;
17245 		uint_t len = sizeof (uint_t);
17246 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17247 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17248 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17249 	}
17250 
17251 	/*
17252 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17253 	 * properly.  This is the first time we know of the acceptor'
17254 	 * queue.  So we do it here.
17255 	 *
17256 	 * XXX
17257 	 */
17258 	if (tcp->tcp_rcv_list == NULL) {
17259 		/*
17260 		 * Recv queue is empty, tcp_rwnd should not have changed.
17261 		 * That means it should be equal to the listener's tcp_rwnd.
17262 		 */
17263 		if (!IPCL_IS_NONSTR(connp))
17264 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17265 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17266 	} else {
17267 #ifdef DEBUG
17268 		mblk_t *tmp;
17269 		mblk_t	*mp1;
17270 		uint_t	cnt = 0;
17271 
17272 		mp1 = tcp->tcp_rcv_list;
17273 		while ((tmp = mp1) != NULL) {
17274 			mp1 = tmp->b_next;
17275 			cnt += msgdsize(tmp);
17276 		}
17277 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17278 #endif
17279 		/* There is some data, add them back to get the max. */
17280 		if (!IPCL_IS_NONSTR(connp))
17281 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17282 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17283 	}
17284 	/*
17285 	 * This is the first time we run on the correct
17286 	 * queue after tcp_accept. So fix all the q parameters
17287 	 * here.
17288 	 */
17289 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17290 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17291 
17292 	/*
17293 	 * Record the stream head's high water mark for this endpoint;
17294 	 * this is used for flow-control purposes.
17295 	 */
17296 	sopp_rxhiwat = tcp->tcp_fused ?
17297 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17298 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
17299 
17300 	/*
17301 	 * Determine what write offset value to use depending on SACK and
17302 	 * whether the endpoint is fused or not.
17303 	 */
17304 	if (tcp->tcp_fused) {
17305 		ASSERT(tcp->tcp_loopback);
17306 		ASSERT(tcp->tcp_loopback_peer != NULL);
17307 		/*
17308 		 * For fused tcp loopback, set the stream head's write
17309 		 * offset value to zero since we won't be needing any room
17310 		 * for TCP/IP headers.  This would also improve performance
17311 		 * since it would reduce the amount of work done by kmem.
17312 		 * Non-fused tcp loopback case is handled separately below.
17313 		 */
17314 		sopp_wroff = 0;
17315 		/*
17316 		 * Update the peer's transmit parameters according to
17317 		 * our recently calculated high water mark value.
17318 		 */
17319 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17320 	} else if (tcp->tcp_snd_sack_ok) {
17321 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17322 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17323 	} else {
17324 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17325 		    tcps->tcps_wroff_xtra);
17326 	}
17327 
17328 	/*
17329 	 * If this is endpoint is handling SSL, then reserve extra
17330 	 * offset and space at the end.
17331 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17332 	 * overriding the previous setting. The extra cost of signing and
17333 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17334 	 * instead of a single contiguous one by the stream head
17335 	 * largely outweighs the statistical reduction of ACKs, when
17336 	 * applicable. The peer will also save on decryption and verification
17337 	 * costs.
17338 	 */
17339 	if (tcp->tcp_kssl_ctx != NULL) {
17340 		sopp_wroff += SSL3_WROFFSET;
17341 
17342 		sopp_flags |= SOCKOPT_TAIL;
17343 		sopp_tail = SSL3_MAX_TAIL_LEN;
17344 
17345 		sopp_flags |= SOCKOPT_ZCOPY;
17346 		sopp_copyopt = ZCVMUNSAFE;
17347 
17348 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
17349 	}
17350 
17351 	/* Send the options up */
17352 	if (IPCL_IS_NONSTR(connp)) {
17353 		struct sock_proto_props sopp;
17354 
17355 		sopp.sopp_flags = sopp_flags;
17356 		sopp.sopp_wroff = sopp_wroff;
17357 		sopp.sopp_maxblk = sopp_maxblk;
17358 		sopp.sopp_rxhiwat = sopp_rxhiwat;
17359 		if (sopp_flags & SOCKOPT_TAIL) {
17360 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17361 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
17362 			sopp.sopp_tail = sopp_tail;
17363 			sopp.sopp_zcopyflag = sopp_copyopt;
17364 		}
17365 		(*connp->conn_upcalls->su_set_proto_props)
17366 		    (connp->conn_upper_handle, &sopp);
17367 	} else {
17368 		struct stroptions *stropt;
17369 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17370 		if (stropt_mp == NULL) {
17371 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
17372 			return;
17373 		}
17374 		DB_TYPE(stropt_mp) = M_SETOPTS;
17375 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17376 		stropt_mp->b_wptr += sizeof (struct stroptions);
17377 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
17378 		stropt->so_hiwat = sopp_rxhiwat;
17379 		stropt->so_wroff = sopp_wroff;
17380 		stropt->so_maxblk = sopp_maxblk;
17381 
17382 		if (sopp_flags & SOCKOPT_TAIL) {
17383 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17384 
17385 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
17386 			stropt->so_tail = sopp_tail;
17387 			stropt->so_copyopt = sopp_copyopt;
17388 		}
17389 
17390 		/* Send the options up */
17391 		putnext(q, stropt_mp);
17392 	}
17393 
17394 	freemsg(mp);
17395 	/*
17396 	 * Pass up any data and/or a fin that has been received.
17397 	 *
17398 	 * Adjust receive window in case it had decreased
17399 	 * (because there is data <=> tcp_rcv_list != NULL)
17400 	 * while the connection was detached. Note that
17401 	 * in case the eager was flow-controlled, w/o this
17402 	 * code, the rwnd may never open up again!
17403 	 */
17404 	if (tcp->tcp_rcv_list != NULL) {
17405 		if (IPCL_IS_NONSTR(connp)) {
17406 			mblk_t *mp;
17407 			int space_left;
17408 			int error;
17409 			boolean_t push = B_TRUE;
17410 
17411 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
17412 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
17413 			    &push) >= 0) {
17414 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17415 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17416 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17417 					tcp_xmit_ctl(NULL,
17418 					    tcp, (tcp->tcp_swnd == 0) ?
17419 					    tcp->tcp_suna : tcp->tcp_snxt,
17420 					    tcp->tcp_rnxt, TH_ACK);
17421 				}
17422 			}
17423 			while ((mp = tcp->tcp_rcv_list) != NULL) {
17424 				push = B_TRUE;
17425 				tcp->tcp_rcv_list = mp->b_next;
17426 				mp->b_next = NULL;
17427 				space_left = (*connp->conn_upcalls->su_recv)
17428 				    (connp->conn_upper_handle, mp, msgdsize(mp),
17429 				    0, &error, &push);
17430 				if (space_left < 0) {
17431 					/*
17432 					 * We should never be in middle of a
17433 					 * fallback, the squeue guarantees that.
17434 					 */
17435 					ASSERT(error != EOPNOTSUPP);
17436 				}
17437 			}
17438 			tcp->tcp_rcv_last_head = NULL;
17439 			tcp->tcp_rcv_last_tail = NULL;
17440 			tcp->tcp_rcv_cnt = 0;
17441 		} else {
17442 			/* We drain directly in case of fused tcp loopback */
17443 
17444 			if (!tcp->tcp_fused && canputnext(q)) {
17445 				tcp->tcp_rwnd = q->q_hiwat;
17446 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17447 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17448 					tcp_xmit_ctl(NULL,
17449 					    tcp, (tcp->tcp_swnd == 0) ?
17450 					    tcp->tcp_suna : tcp->tcp_snxt,
17451 					    tcp->tcp_rnxt, TH_ACK);
17452 				}
17453 			}
17454 
17455 			(void) tcp_rcv_drain(tcp);
17456 		}
17457 
17458 		/*
17459 		 * For fused tcp loopback, back-enable peer endpoint
17460 		 * if it's currently flow-controlled.
17461 		 */
17462 		if (tcp->tcp_fused) {
17463 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17464 
17465 			ASSERT(peer_tcp != NULL);
17466 			ASSERT(peer_tcp->tcp_fused);
17467 
17468 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
17469 			if (peer_tcp->tcp_flow_stopped) {
17470 				tcp_clrqfull(peer_tcp);
17471 				TCP_STAT(tcps, tcp_fusion_backenabled);
17472 			}
17473 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17474 		}
17475 	}
17476 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17477 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17478 		tcp->tcp_ordrel_done = B_TRUE;
17479 		if (IPCL_IS_NONSTR(connp)) {
17480 			ASSERT(tcp->tcp_ordrel_mp == NULL);
17481 			(*connp->conn_upcalls->su_opctl)(
17482 			    connp->conn_upper_handle,
17483 			    SOCK_OPCTL_SHUT_RECV, 0);
17484 		} else {
17485 			mp = tcp->tcp_ordrel_mp;
17486 			tcp->tcp_ordrel_mp = NULL;
17487 			putnext(q, mp);
17488 		}
17489 	}
17490 	if (tcp->tcp_hard_binding) {
17491 		tcp->tcp_hard_binding = B_FALSE;
17492 		tcp->tcp_hard_bound = B_TRUE;
17493 	}
17494 
17495 	if (tcp->tcp_ka_enabled) {
17496 		tcp->tcp_ka_last_intrvl = 0;
17497 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17498 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17499 	}
17500 
17501 	/*
17502 	 * At this point, eager is fully established and will
17503 	 * have the following references -
17504 	 *
17505 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17506 	 * 1 reference for the squeue which will be dropped by the squeue as
17507 	 *	soon as this function returns.
17508 	 * There will be 1 additonal reference for being in classifier
17509 	 *	hash list provided something bad hasn't happened.
17510 	 */
17511 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17512 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17513 }
17514 
17515 /*
17516  * The function called through squeue to get behind listener's perimeter to
17517  * send a deffered conn_ind.
17518  */
17519 /* ARGSUSED */
17520 void
17521 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17522 {
17523 	conn_t	*connp = (conn_t *)arg;
17524 	tcp_t *listener = connp->conn_tcp;
17525 	struct T_conn_ind *conn_ind;
17526 	tcp_t *tcp;
17527 
17528 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
17529 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17530 	    conn_ind->OPT_length);
17531 
17532 	if (listener->tcp_state != TCPS_LISTEN) {
17533 		/*
17534 		 * If listener has closed, it would have caused a
17535 		 * a cleanup/blowoff to happen for the eager, so
17536 		 * we don't need to do anything more.
17537 		 */
17538 		freemsg(mp);
17539 		return;
17540 	}
17541 
17542 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
17543 }
17544 
17545 /* ARGSUSED */
17546 static int
17547 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
17548 {
17549 	tcp_t *listener, *eager;
17550 	mblk_t *opt_mp;
17551 	struct tcp_options *tcpopt;
17552 
17553 	listener = lconnp->conn_tcp;
17554 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17555 	eager = econnp->conn_tcp;
17556 	ASSERT(eager->tcp_listener != NULL);
17557 
17558 	ASSERT(eager->tcp_rq != NULL);
17559 
17560 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
17561 	if (opt_mp == NULL) {
17562 		return (-TPROTO);
17563 	}
17564 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
17565 	eager->tcp_issocket = B_TRUE;
17566 
17567 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17568 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17569 	ASSERT(econnp->conn_netstack ==
17570 	    listener->tcp_connp->conn_netstack);
17571 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
17572 
17573 	/* Put the ref for IP */
17574 	CONN_INC_REF(econnp);
17575 
17576 	/*
17577 	 * We should have minimum of 3 references on the conn
17578 	 * at this point. One each for TCP and IP and one for
17579 	 * the T_conn_ind that was sent up when the 3-way handshake
17580 	 * completed. In the normal case we would also have another
17581 	 * reference (making a total of 4) for the conn being in the
17582 	 * classifier hash list. However the eager could have received
17583 	 * an RST subsequently and tcp_closei_local could have removed
17584 	 * the eager from the classifier hash list, hence we can't
17585 	 * assert that reference.
17586 	 */
17587 	ASSERT(econnp->conn_ref >= 3);
17588 
17589 	opt_mp->b_datap->db_type = M_SETOPTS;
17590 	opt_mp->b_wptr += sizeof (struct tcp_options);
17591 
17592 	/*
17593 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17594 	 * from listener to acceptor.
17595 	 */
17596 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
17597 	tcpopt->to_flags = 0;
17598 
17599 	if (listener->tcp_bound_if != 0) {
17600 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
17601 		tcpopt->to_boundif = listener->tcp_bound_if;
17602 	}
17603 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17604 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
17605 	}
17606 
17607 	mutex_enter(&listener->tcp_eager_lock);
17608 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17609 
17610 		tcp_t *tail;
17611 		tcp_t *tcp;
17612 		mblk_t *mp1;
17613 
17614 		tcp = listener->tcp_eager_prev_q0;
17615 		/*
17616 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
17617 		 * deferred T_conn_ind queue. We need to get to the head
17618 		 * of the queue in order to send up T_conn_ind the same
17619 		 * order as how the 3WHS is completed.
17620 		 */
17621 		while (tcp != listener) {
17622 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17623 			    !tcp->tcp_kssl_pending)
17624 				break;
17625 			else
17626 				tcp = tcp->tcp_eager_prev_q0;
17627 		}
17628 		/* None of the pending eagers can be sent up now */
17629 		if (tcp == listener)
17630 			goto no_more_eagers;
17631 
17632 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17633 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17634 		/* Move from q0 to q */
17635 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17636 		listener->tcp_conn_req_cnt_q0--;
17637 		listener->tcp_conn_req_cnt_q++;
17638 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17639 		    tcp->tcp_eager_prev_q0;
17640 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17641 		    tcp->tcp_eager_next_q0;
17642 		tcp->tcp_eager_prev_q0 = NULL;
17643 		tcp->tcp_eager_next_q0 = NULL;
17644 		tcp->tcp_conn_def_q0 = B_FALSE;
17645 
17646 		/* Make sure the tcp isn't in the list of droppables */
17647 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
17648 		    tcp->tcp_eager_prev_drop_q0 == NULL);
17649 
17650 		/*
17651 		 * Insert at end of the queue because sockfs sends
17652 		 * down T_CONN_RES in chronological order. Leaving
17653 		 * the older conn indications at front of the queue
17654 		 * helps reducing search time.
17655 		 */
17656 		tail = listener->tcp_eager_last_q;
17657 		if (tail != NULL) {
17658 			tail->tcp_eager_next_q = tcp;
17659 		} else {
17660 			listener->tcp_eager_next_q = tcp;
17661 		}
17662 		listener->tcp_eager_last_q = tcp;
17663 		tcp->tcp_eager_next_q = NULL;
17664 
17665 		/* Need to get inside the listener perimeter */
17666 		CONN_INC_REF(listener->tcp_connp);
17667 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
17668 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
17669 		    SQTAG_TCP_SEND_PENDING);
17670 	}
17671 no_more_eagers:
17672 	tcp_eager_unlink(eager);
17673 	mutex_exit(&listener->tcp_eager_lock);
17674 
17675 	/*
17676 	 * At this point, the eager is detached from the listener
17677 	 * but we still have an extra refs on eager (apart from the
17678 	 * usual tcp references). The ref was placed in tcp_rput_data
17679 	 * before sending the conn_ind in tcp_send_conn_ind.
17680 	 * The ref will be dropped in tcp_accept_finish().
17681 	 */
17682 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
17683 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
17684 	return (0);
17685 }
17686 
17687 int
17688 tcp_accept(sock_lower_handle_t lproto_handle,
17689     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
17690     cred_t *cr)
17691 {
17692 	conn_t *lconnp, *econnp;
17693 	tcp_t *listener, *eager;
17694 	tcp_stack_t	*tcps;
17695 
17696 	lconnp = (conn_t *)lproto_handle;
17697 	listener = lconnp->conn_tcp;
17698 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17699 	econnp = (conn_t *)eproto_handle;
17700 	eager = econnp->conn_tcp;
17701 	ASSERT(eager->tcp_listener != NULL);
17702 	tcps = eager->tcp_tcps;
17703 
17704 	/*
17705 	 * It is OK to manipulate these fields outside the eager's squeue
17706 	 * because they will not start being used until tcp_accept_finish
17707 	 * has been called.
17708 	 */
17709 	ASSERT(lconnp->conn_upper_handle != NULL);
17710 	ASSERT(econnp->conn_upper_handle == NULL);
17711 	econnp->conn_upper_handle = sock_handle;
17712 	econnp->conn_upcalls = lconnp->conn_upcalls;
17713 	ASSERT(IPCL_IS_NONSTR(econnp));
17714 	/*
17715 	 * Create helper stream if it is a non-TPI TCP connection.
17716 	 */
17717 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
17718 		ip1dbg(("tcp_accept: create of IP helper stream"
17719 		    " failed\n"));
17720 		return (EPROTO);
17721 	}
17722 	eager->tcp_rq = econnp->conn_rq;
17723 	eager->tcp_wq = econnp->conn_wq;
17724 
17725 	ASSERT(eager->tcp_rq != NULL);
17726 
17727 	return (tcp_accept_common(lconnp, econnp, cr));
17728 }
17729 
17730 
17731 /*
17732  * This is the STREAMS entry point for T_CONN_RES coming down on
17733  * Acceptor STREAM when  sockfs listener does accept processing.
17734  * Read the block comment on top of tcp_conn_request().
17735  */
17736 void
17737 tcp_tpi_accept(queue_t *q, mblk_t *mp)
17738 {
17739 	queue_t *rq = RD(q);
17740 	struct T_conn_res *conn_res;
17741 	tcp_t *eager;
17742 	tcp_t *listener;
17743 	struct T_ok_ack *ok;
17744 	t_scalar_t PRIM_type;
17745 	conn_t *econnp;
17746 	cred_t *cr;
17747 
17748 	ASSERT(DB_TYPE(mp) == M_PROTO);
17749 
17750 	/*
17751 	 * All Solaris components should pass a db_credp
17752 	 * for this TPI message, hence we ASSERT.
17753 	 * But in case there is some other M_PROTO that looks
17754 	 * like a TPI message sent by some other kernel
17755 	 * component, we check and return an error.
17756 	 */
17757 	cr = msg_getcred(mp, NULL);
17758 	ASSERT(cr != NULL);
17759 	if (cr == NULL) {
17760 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
17761 		if (mp != NULL)
17762 			putnext(rq, mp);
17763 		return;
17764 	}
17765 	conn_res = (struct T_conn_res *)mp->b_rptr;
17766 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17767 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17768 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17769 		if (mp != NULL)
17770 			putnext(rq, mp);
17771 		return;
17772 	}
17773 	switch (conn_res->PRIM_type) {
17774 	case O_T_CONN_RES:
17775 	case T_CONN_RES:
17776 		/*
17777 		 * We pass up an err ack if allocb fails. This will
17778 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17779 		 * tcp_eager_blowoff to be called. sockfs will then call
17780 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17781 		 * we need to do the allocb up here because we have to
17782 		 * make sure rq->q_qinfo->qi_qclose still points to the
17783 		 * correct function (tcp_tpi_close_accept) in case allocb
17784 		 * fails.
17785 		 */
17786 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17787 		    &eager, conn_res->OPT_length);
17788 		PRIM_type = conn_res->PRIM_type;
17789 		mp->b_datap->db_type = M_PCPROTO;
17790 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17791 		ok = (struct T_ok_ack *)mp->b_rptr;
17792 		ok->PRIM_type = T_OK_ACK;
17793 		ok->CORRECT_prim = PRIM_type;
17794 		econnp = eager->tcp_connp;
17795 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
17796 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
17797 		eager->tcp_rq = rq;
17798 		eager->tcp_wq = q;
17799 		rq->q_ptr = econnp;
17800 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
17801 		q->q_ptr = econnp;
17802 		q->q_qinfo = &tcp_winit;
17803 		listener = eager->tcp_listener;
17804 
17805 		if (tcp_accept_common(listener->tcp_connp,
17806 		    econnp, cr) < 0) {
17807 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17808 			if (mp != NULL)
17809 				putnext(rq, mp);
17810 			return;
17811 		}
17812 
17813 		/*
17814 		 * Send the new local address also up to sockfs. There
17815 		 * should already be enough space in the mp that came
17816 		 * down from soaccept().
17817 		 */
17818 		if (eager->tcp_family == AF_INET) {
17819 			sin_t *sin;
17820 
17821 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17822 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17823 			sin = (sin_t *)mp->b_wptr;
17824 			mp->b_wptr += sizeof (sin_t);
17825 			sin->sin_family = AF_INET;
17826 			sin->sin_port = eager->tcp_lport;
17827 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17828 		} else {
17829 			sin6_t *sin6;
17830 
17831 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17832 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17833 			sin6 = (sin6_t *)mp->b_wptr;
17834 			mp->b_wptr += sizeof (sin6_t);
17835 			sin6->sin6_family = AF_INET6;
17836 			sin6->sin6_port = eager->tcp_lport;
17837 			if (eager->tcp_ipversion == IPV4_VERSION) {
17838 				sin6->sin6_flowinfo = 0;
17839 				IN6_IPADDR_TO_V4MAPPED(
17840 				    eager->tcp_ipha->ipha_src,
17841 				    &sin6->sin6_addr);
17842 			} else {
17843 				ASSERT(eager->tcp_ip6h != NULL);
17844 				sin6->sin6_flowinfo =
17845 				    eager->tcp_ip6h->ip6_vcf &
17846 				    ~IPV6_VERS_AND_FLOW_MASK;
17847 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17848 			}
17849 			sin6->sin6_scope_id = 0;
17850 			sin6->__sin6_src_id = 0;
17851 		}
17852 
17853 		putnext(rq, mp);
17854 		return;
17855 	default:
17856 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17857 		if (mp != NULL)
17858 			putnext(rq, mp);
17859 		return;
17860 	}
17861 }
17862 
17863 static int
17864 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17865 {
17866 	sin_t *sin = (sin_t *)sa;
17867 	sin6_t *sin6 = (sin6_t *)sa;
17868 
17869 	switch (tcp->tcp_family) {
17870 	case AF_INET:
17871 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17872 
17873 		if (*salenp < sizeof (sin_t))
17874 			return (EINVAL);
17875 
17876 		*sin = sin_null;
17877 		sin->sin_family = AF_INET;
17878 		if (tcp->tcp_state >= TCPS_BOUND) {
17879 			sin->sin_port = tcp->tcp_lport;
17880 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
17881 		}
17882 		*salenp = sizeof (sin_t);
17883 		break;
17884 
17885 	case AF_INET6:
17886 		if (*salenp < sizeof (sin6_t))
17887 			return (EINVAL);
17888 
17889 		*sin6 = sin6_null;
17890 		sin6->sin6_family = AF_INET6;
17891 		if (tcp->tcp_state >= TCPS_BOUND) {
17892 			sin6->sin6_port = tcp->tcp_lport;
17893 			if (tcp->tcp_ipversion == IPV4_VERSION) {
17894 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
17895 				    &sin6->sin6_addr);
17896 			} else {
17897 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
17898 			}
17899 		}
17900 		*salenp = sizeof (sin6_t);
17901 		break;
17902 	}
17903 
17904 	return (0);
17905 }
17906 
17907 static int
17908 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17909 {
17910 	sin_t *sin = (sin_t *)sa;
17911 	sin6_t *sin6 = (sin6_t *)sa;
17912 
17913 	if (tcp->tcp_state < TCPS_SYN_RCVD)
17914 		return (ENOTCONN);
17915 
17916 	switch (tcp->tcp_family) {
17917 	case AF_INET:
17918 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17919 
17920 		if (*salenp < sizeof (sin_t))
17921 			return (EINVAL);
17922 
17923 		*sin = sin_null;
17924 		sin->sin_family = AF_INET;
17925 		sin->sin_port = tcp->tcp_fport;
17926 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
17927 		    sin->sin_addr.s_addr);
17928 		*salenp = sizeof (sin_t);
17929 		break;
17930 
17931 	case AF_INET6:
17932 		if (*salenp < sizeof (sin6_t))
17933 			return (EINVAL);
17934 
17935 		*sin6 = sin6_null;
17936 		sin6->sin6_family = AF_INET6;
17937 		sin6->sin6_port = tcp->tcp_fport;
17938 		sin6->sin6_addr = tcp->tcp_remote_v6;
17939 		if (tcp->tcp_ipversion == IPV6_VERSION) {
17940 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
17941 			    ~IPV6_VERS_AND_FLOW_MASK;
17942 		}
17943 		*salenp = sizeof (sin6_t);
17944 		break;
17945 	}
17946 
17947 	return (0);
17948 }
17949 
17950 /*
17951  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
17952  */
17953 static void
17954 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
17955 {
17956 	void	*data;
17957 	mblk_t	*datamp = mp->b_cont;
17958 	tcp_t	*tcp = Q_TO_TCP(q);
17959 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
17960 
17961 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
17962 		cmdp->cb_error = EPROTO;
17963 		qreply(q, mp);
17964 		return;
17965 	}
17966 
17967 	data = datamp->b_rptr;
17968 
17969 	switch (cmdp->cb_cmd) {
17970 	case TI_GETPEERNAME:
17971 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
17972 		break;
17973 	case TI_GETMYNAME:
17974 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
17975 		break;
17976 	default:
17977 		cmdp->cb_error = EINVAL;
17978 		break;
17979 	}
17980 
17981 	qreply(q, mp);
17982 }
17983 
17984 void
17985 tcp_wput(queue_t *q, mblk_t *mp)
17986 {
17987 	conn_t	*connp = Q_TO_CONN(q);
17988 	tcp_t	*tcp;
17989 	void (*output_proc)();
17990 	t_scalar_t type;
17991 	uchar_t *rptr;
17992 	struct iocblk	*iocp;
17993 	size_t size;
17994 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17995 
17996 	ASSERT(connp->conn_ref >= 2);
17997 
17998 	switch (DB_TYPE(mp)) {
17999 	case M_DATA:
18000 		tcp = connp->conn_tcp;
18001 		ASSERT(tcp != NULL);
18002 
18003 		size = msgdsize(mp);
18004 
18005 		mutex_enter(&tcp->tcp_non_sq_lock);
18006 		tcp->tcp_squeue_bytes += size;
18007 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18008 			tcp_setqfull(tcp);
18009 		}
18010 		mutex_exit(&tcp->tcp_non_sq_lock);
18011 
18012 		CONN_INC_REF(connp);
18013 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18014 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18015 		return;
18016 
18017 	case M_CMD:
18018 		tcp_wput_cmdblk(q, mp);
18019 		return;
18020 
18021 	case M_PROTO:
18022 	case M_PCPROTO:
18023 		/*
18024 		 * if it is a snmp message, don't get behind the squeue
18025 		 */
18026 		tcp = connp->conn_tcp;
18027 		rptr = mp->b_rptr;
18028 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18029 			type = ((union T_primitives *)rptr)->type;
18030 		} else {
18031 			if (tcp->tcp_debug) {
18032 				(void) strlog(TCP_MOD_ID, 0, 1,
18033 				    SL_ERROR|SL_TRACE,
18034 				    "tcp_wput_proto, dropping one...");
18035 			}
18036 			freemsg(mp);
18037 			return;
18038 		}
18039 		if (type == T_SVR4_OPTMGMT_REQ) {
18040 			/*
18041 			 * All Solaris components should pass a db_credp
18042 			 * for this TPI message, hence we ASSERT.
18043 			 * But in case there is some other M_PROTO that looks
18044 			 * like a TPI message sent by some other kernel
18045 			 * component, we check and return an error.
18046 			 */
18047 			cred_t	*cr = msg_getcred(mp, NULL);
18048 
18049 			ASSERT(cr != NULL);
18050 			if (cr == NULL) {
18051 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18052 				return;
18053 			}
18054 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18055 			    cr)) {
18056 				/*
18057 				 * This was a SNMP request
18058 				 */
18059 				return;
18060 			} else {
18061 				output_proc = tcp_wput_proto;
18062 			}
18063 		} else {
18064 			output_proc = tcp_wput_proto;
18065 		}
18066 		break;
18067 	case M_IOCTL:
18068 		/*
18069 		 * Most ioctls can be processed right away without going via
18070 		 * squeues - process them right here. Those that do require
18071 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18072 		 * are processed by tcp_wput_ioctl().
18073 		 */
18074 		iocp = (struct iocblk *)mp->b_rptr;
18075 		tcp = connp->conn_tcp;
18076 
18077 		switch (iocp->ioc_cmd) {
18078 		case TCP_IOC_ABORT_CONN:
18079 			tcp_ioctl_abort_conn(q, mp);
18080 			return;
18081 		case TI_GETPEERNAME:
18082 		case TI_GETMYNAME:
18083 			mi_copyin(q, mp, NULL,
18084 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18085 			return;
18086 		case ND_SET:
18087 			/* nd_getset does the necessary checks */
18088 		case ND_GET:
18089 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18090 				CALL_IP_WPUT(connp, q, mp);
18091 				return;
18092 			}
18093 			qreply(q, mp);
18094 			return;
18095 		case TCP_IOC_DEFAULT_Q:
18096 			/*
18097 			 * Wants to be the default wq. Check the credentials
18098 			 * first, the rest is executed via squeue.
18099 			 */
18100 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18101 				iocp->ioc_error = EPERM;
18102 				iocp->ioc_count = 0;
18103 				mp->b_datap->db_type = M_IOCACK;
18104 				qreply(q, mp);
18105 				return;
18106 			}
18107 			output_proc = tcp_wput_ioctl;
18108 			break;
18109 		default:
18110 			output_proc = tcp_wput_ioctl;
18111 			break;
18112 		}
18113 		break;
18114 	default:
18115 		output_proc = tcp_wput_nondata;
18116 		break;
18117 	}
18118 
18119 	CONN_INC_REF(connp);
18120 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18121 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18122 }
18123 
18124 /*
18125  * Initial STREAMS write side put() procedure for sockets. It tries to
18126  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18127  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18128  * are handled by tcp_wput() as usual.
18129  *
18130  * All further messages will also be handled by tcp_wput() because we cannot
18131  * be sure that the above short cut is safe later.
18132  */
18133 static void
18134 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18135 {
18136 	conn_t			*connp = Q_TO_CONN(wq);
18137 	tcp_t			*tcp = connp->conn_tcp;
18138 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18139 
18140 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18141 	wq->q_qinfo = &tcp_winit;
18142 
18143 	ASSERT(IPCL_IS_TCP(connp));
18144 	ASSERT(TCP_IS_SOCKET(tcp));
18145 
18146 	if (DB_TYPE(mp) == M_PCPROTO &&
18147 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18148 	    car->PRIM_type == T_CAPABILITY_REQ) {
18149 		tcp_capability_req(tcp, mp);
18150 		return;
18151 	}
18152 
18153 	tcp_wput(wq, mp);
18154 }
18155 
18156 /* ARGSUSED */
18157 static void
18158 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18159 {
18160 #ifdef DEBUG
18161 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18162 #endif
18163 	freemsg(mp);
18164 }
18165 
18166 static boolean_t
18167 tcp_zcopy_check(tcp_t *tcp)
18168 {
18169 	conn_t	*connp = tcp->tcp_connp;
18170 	ire_t	*ire;
18171 	boolean_t	zc_enabled = B_FALSE;
18172 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18173 
18174 	if (do_tcpzcopy == 2)
18175 		zc_enabled = B_TRUE;
18176 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18177 	    IPCL_IS_CONNECTED(connp) &&
18178 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18179 	    connp->conn_dontroute == 0 &&
18180 	    !connp->conn_nexthop_set &&
18181 	    connp->conn_outgoing_ill == NULL &&
18182 	    do_tcpzcopy == 1) {
18183 		/*
18184 		 * the checks above  closely resemble the fast path checks
18185 		 * in tcp_send_data().
18186 		 */
18187 		mutex_enter(&connp->conn_lock);
18188 		ire = connp->conn_ire_cache;
18189 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18190 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18191 			IRE_REFHOLD(ire);
18192 			if (ire->ire_stq != NULL) {
18193 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18194 
18195 				zc_enabled = ill && (ill->ill_capabilities &
18196 				    ILL_CAPAB_ZEROCOPY) &&
18197 				    (ill->ill_zerocopy_capab->
18198 				    ill_zerocopy_flags != 0);
18199 			}
18200 			IRE_REFRELE(ire);
18201 		}
18202 		mutex_exit(&connp->conn_lock);
18203 	}
18204 	tcp->tcp_snd_zcopy_on = zc_enabled;
18205 	if (!TCP_IS_DETACHED(tcp)) {
18206 		if (zc_enabled) {
18207 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18208 			    ZCVMSAFE);
18209 			TCP_STAT(tcps, tcp_zcopy_on);
18210 		} else {
18211 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18212 			    ZCVMUNSAFE);
18213 			TCP_STAT(tcps, tcp_zcopy_off);
18214 		}
18215 	}
18216 	return (zc_enabled);
18217 }
18218 
18219 static mblk_t *
18220 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18221 {
18222 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18223 
18224 	if (do_tcpzcopy == 2)
18225 		return (bp);
18226 	else if (tcp->tcp_snd_zcopy_on) {
18227 		tcp->tcp_snd_zcopy_on = B_FALSE;
18228 		if (!TCP_IS_DETACHED(tcp)) {
18229 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18230 			    ZCVMUNSAFE);
18231 			TCP_STAT(tcps, tcp_zcopy_disable);
18232 		}
18233 	}
18234 	return (tcp_zcopy_backoff(tcp, bp, 0));
18235 }
18236 
18237 /*
18238  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18239  * the original desballoca'ed segmapped mblk.
18240  */
18241 static mblk_t *
18242 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18243 {
18244 	mblk_t *head, *tail, *nbp;
18245 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18246 
18247 	if (IS_VMLOANED_MBLK(bp)) {
18248 		TCP_STAT(tcps, tcp_zcopy_backoff);
18249 		if ((head = copyb(bp)) == NULL) {
18250 			/* fail to backoff; leave it for the next backoff */
18251 			tcp->tcp_xmit_zc_clean = B_FALSE;
18252 			return (bp);
18253 		}
18254 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18255 			if (fix_xmitlist)
18256 				tcp_zcopy_notify(tcp);
18257 			else
18258 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18259 		}
18260 		nbp = bp->b_cont;
18261 		if (fix_xmitlist) {
18262 			head->b_prev = bp->b_prev;
18263 			head->b_next = bp->b_next;
18264 			if (tcp->tcp_xmit_tail == bp)
18265 				tcp->tcp_xmit_tail = head;
18266 		}
18267 		bp->b_next = NULL;
18268 		bp->b_prev = NULL;
18269 		freeb(bp);
18270 	} else {
18271 		head = bp;
18272 		nbp = bp->b_cont;
18273 	}
18274 	tail = head;
18275 	while (nbp) {
18276 		if (IS_VMLOANED_MBLK(nbp)) {
18277 			TCP_STAT(tcps, tcp_zcopy_backoff);
18278 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18279 				tcp->tcp_xmit_zc_clean = B_FALSE;
18280 				tail->b_cont = nbp;
18281 				return (head);
18282 			}
18283 			tail = tail->b_cont;
18284 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18285 				if (fix_xmitlist)
18286 					tcp_zcopy_notify(tcp);
18287 				else
18288 					tail->b_datap->db_struioflag |=
18289 					    STRUIO_ZCNOTIFY;
18290 			}
18291 			bp = nbp;
18292 			nbp = nbp->b_cont;
18293 			if (fix_xmitlist) {
18294 				tail->b_prev = bp->b_prev;
18295 				tail->b_next = bp->b_next;
18296 				if (tcp->tcp_xmit_tail == bp)
18297 					tcp->tcp_xmit_tail = tail;
18298 			}
18299 			bp->b_next = NULL;
18300 			bp->b_prev = NULL;
18301 			freeb(bp);
18302 		} else {
18303 			tail->b_cont = nbp;
18304 			tail = nbp;
18305 			nbp = nbp->b_cont;
18306 		}
18307 	}
18308 	if (fix_xmitlist) {
18309 		tcp->tcp_xmit_last = tail;
18310 		tcp->tcp_xmit_zc_clean = B_TRUE;
18311 	}
18312 	return (head);
18313 }
18314 
18315 static void
18316 tcp_zcopy_notify(tcp_t *tcp)
18317 {
18318 	struct stdata	*stp;
18319 	conn_t *connp;
18320 
18321 	if (tcp->tcp_detached)
18322 		return;
18323 	connp = tcp->tcp_connp;
18324 	if (IPCL_IS_NONSTR(connp)) {
18325 		(*connp->conn_upcalls->su_zcopy_notify)
18326 		    (connp->conn_upper_handle);
18327 		return;
18328 	}
18329 	stp = STREAM(tcp->tcp_rq);
18330 	mutex_enter(&stp->sd_lock);
18331 	stp->sd_flag |= STZCNOTIFY;
18332 	cv_broadcast(&stp->sd_zcopy_wait);
18333 	mutex_exit(&stp->sd_lock);
18334 }
18335 
18336 static boolean_t
18337 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18338 {
18339 	ire_t	*ire;
18340 	conn_t	*connp = tcp->tcp_connp;
18341 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18342 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18343 
18344 	mutex_enter(&connp->conn_lock);
18345 	ire = connp->conn_ire_cache;
18346 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18347 
18348 	if ((ire != NULL) &&
18349 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18350 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18351 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18352 		IRE_REFHOLD(ire);
18353 		mutex_exit(&connp->conn_lock);
18354 	} else {
18355 		boolean_t cached = B_FALSE;
18356 		ts_label_t *tsl;
18357 
18358 		/* force a recheck later on */
18359 		tcp->tcp_ire_ill_check_done = B_FALSE;
18360 
18361 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18362 		connp->conn_ire_cache = NULL;
18363 		mutex_exit(&connp->conn_lock);
18364 
18365 		if (ire != NULL)
18366 			IRE_REFRELE_NOTR(ire);
18367 
18368 		tsl = crgetlabel(CONN_CRED(connp));
18369 		ire = (dst ?
18370 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18371 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18372 		    connp->conn_zoneid, tsl, ipst));
18373 
18374 		if (ire == NULL) {
18375 			TCP_STAT(tcps, tcp_ire_null);
18376 			return (B_FALSE);
18377 		}
18378 
18379 		IRE_REFHOLD_NOTR(ire);
18380 
18381 		mutex_enter(&connp->conn_lock);
18382 		if (CONN_CACHE_IRE(connp)) {
18383 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18384 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18385 				TCP_CHECK_IREINFO(tcp, ire);
18386 				connp->conn_ire_cache = ire;
18387 				cached = B_TRUE;
18388 			}
18389 			rw_exit(&ire->ire_bucket->irb_lock);
18390 		}
18391 		mutex_exit(&connp->conn_lock);
18392 
18393 		/*
18394 		 * We can continue to use the ire but since it was
18395 		 * not cached, we should drop the extra reference.
18396 		 */
18397 		if (!cached)
18398 			IRE_REFRELE_NOTR(ire);
18399 
18400 		/*
18401 		 * Rampart note: no need to select a new label here, since
18402 		 * labels are not allowed to change during the life of a TCP
18403 		 * connection.
18404 		 */
18405 	}
18406 
18407 	*irep = ire;
18408 
18409 	return (B_TRUE);
18410 }
18411 
18412 /*
18413  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18414  *
18415  * 0 = success;
18416  * 1 = failed to find ire and ill.
18417  */
18418 static boolean_t
18419 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18420 {
18421 	ipha_t		*ipha;
18422 	ipaddr_t	dst;
18423 	ire_t		*ire;
18424 	ill_t		*ill;
18425 	mblk_t		*ire_fp_mp;
18426 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18427 
18428 	if (mp != NULL)
18429 		ipha = (ipha_t *)mp->b_rptr;
18430 	else
18431 		ipha = tcp->tcp_ipha;
18432 	dst = ipha->ipha_dst;
18433 
18434 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18435 		return (B_FALSE);
18436 
18437 	if ((ire->ire_flags & RTF_MULTIRT) ||
18438 	    (ire->ire_stq == NULL) ||
18439 	    (ire->ire_nce == NULL) ||
18440 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18441 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18442 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18443 		TCP_STAT(tcps, tcp_ip_ire_send);
18444 		IRE_REFRELE(ire);
18445 		return (B_FALSE);
18446 	}
18447 
18448 	ill = ire_to_ill(ire);
18449 	ASSERT(ill != NULL);
18450 
18451 	if (!tcp->tcp_ire_ill_check_done) {
18452 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18453 		tcp->tcp_ire_ill_check_done = B_TRUE;
18454 	}
18455 
18456 	*irep = ire;
18457 	*illp = ill;
18458 
18459 	return (B_TRUE);
18460 }
18461 
18462 static void
18463 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18464 {
18465 	ipha_t		*ipha;
18466 	ipaddr_t	src;
18467 	ipaddr_t	dst;
18468 	uint32_t	cksum;
18469 	ire_t		*ire;
18470 	uint16_t	*up;
18471 	ill_t		*ill;
18472 	conn_t		*connp = tcp->tcp_connp;
18473 	uint32_t	hcksum_txflags = 0;
18474 	mblk_t		*ire_fp_mp;
18475 	uint_t		ire_fp_mp_len;
18476 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18477 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18478 	cred_t		*cr;
18479 	pid_t		cpid;
18480 
18481 	ASSERT(DB_TYPE(mp) == M_DATA);
18482 
18483 	/*
18484 	 * Here we need to handle the overloading of the cred_t for
18485 	 * both getpeerucred and TX.
18486 	 * If this is a SYN then the caller already set db_credp so
18487 	 * that getpeerucred will work. But if TX is in use we might have
18488 	 * a conn_effective_cred which is different, and we need to use that
18489 	 * cred to make TX use the correct label and label dependent route.
18490 	 */
18491 	if (is_system_labeled()) {
18492 		cr = msg_getcred(mp, &cpid);
18493 		if (cr == NULL || connp->conn_effective_cred != NULL)
18494 			mblk_setcred(mp, CONN_CRED(connp), cpid);
18495 	}
18496 
18497 	ipha = (ipha_t *)mp->b_rptr;
18498 	src = ipha->ipha_src;
18499 	dst = ipha->ipha_dst;
18500 
18501 	ASSERT(q != NULL);
18502 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
18503 
18504 	/*
18505 	 * Drop off fast path for IPv6 and also if options are present or
18506 	 * we need to resolve a TS label.
18507 	 */
18508 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18509 	    !IPCL_IS_CONNECTED(connp) ||
18510 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18511 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18512 	    !connp->conn_ulp_labeled ||
18513 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18514 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18515 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18516 		if (tcp->tcp_snd_zcopy_aware)
18517 			mp = tcp_zcopy_disable(tcp, mp);
18518 		TCP_STAT(tcps, tcp_ip_send);
18519 		CALL_IP_WPUT(connp, q, mp);
18520 		return;
18521 	}
18522 
18523 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18524 		if (tcp->tcp_snd_zcopy_aware)
18525 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18526 		CALL_IP_WPUT(connp, q, mp);
18527 		return;
18528 	}
18529 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18530 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18531 
18532 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18533 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18534 #ifndef _BIG_ENDIAN
18535 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18536 #endif
18537 
18538 	/*
18539 	 * Check to see if we need to re-enable LSO/MDT for this connection
18540 	 * because it was previously disabled due to changes in the ill;
18541 	 * note that by doing it here, this re-enabling only applies when
18542 	 * the packet is not dispatched through CALL_IP_WPUT().
18543 	 *
18544 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18545 	 * case, since that's how we ended up here.  For IPv6, we do the
18546 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18547 	 */
18548 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18549 		/*
18550 		 * Restore LSO for this connection, so that next time around
18551 		 * it is eligible to go through tcp_lsosend() path again.
18552 		 */
18553 		TCP_STAT(tcps, tcp_lso_enabled);
18554 		tcp->tcp_lso = B_TRUE;
18555 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18556 		    "interface %s\n", (void *)connp, ill->ill_name));
18557 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18558 		/*
18559 		 * Restore MDT for this connection, so that next time around
18560 		 * it is eligible to go through tcp_multisend() path again.
18561 		 */
18562 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18563 		tcp->tcp_mdt = B_TRUE;
18564 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18565 		    "interface %s\n", (void *)connp, ill->ill_name));
18566 	}
18567 
18568 	if (tcp->tcp_snd_zcopy_aware) {
18569 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18570 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18571 			mp = tcp_zcopy_disable(tcp, mp);
18572 		/*
18573 		 * we shouldn't need to reset ipha as the mp containing
18574 		 * ipha should never be a zero-copy mp.
18575 		 */
18576 	}
18577 
18578 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18579 		ASSERT(ill->ill_hcksum_capab != NULL);
18580 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18581 	}
18582 
18583 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18584 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18585 
18586 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18587 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18588 
18589 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18590 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18591 
18592 	/* Software checksum? */
18593 	if (DB_CKSUMFLAGS(mp) == 0) {
18594 		TCP_STAT(tcps, tcp_out_sw_cksum);
18595 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18596 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18597 	}
18598 
18599 	/* Calculate IP header checksum if hardware isn't capable */
18600 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18601 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18602 		    ((uint16_t *)ipha)[4]);
18603 	}
18604 
18605 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18606 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18607 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18608 
18609 	UPDATE_OB_PKT_COUNT(ire);
18610 	ire->ire_last_used_time = lbolt;
18611 
18612 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18613 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18614 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18615 	    ntohs(ipha->ipha_length));
18616 
18617 	DTRACE_PROBE4(ip4__physical__out__start,
18618 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
18619 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
18620 	    ipst->ips_ipv4firewall_physical_out,
18621 	    NULL, ill, ipha, mp, mp, 0, ipst);
18622 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18623 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
18624 
18625 	if (mp != NULL) {
18626 		if (ipst->ips_ipobs_enabled) {
18627 			zoneid_t szone;
18628 
18629 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
18630 			    ipst, ALL_ZONES);
18631 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
18632 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
18633 		}
18634 
18635 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
18636 	}
18637 
18638 	IRE_REFRELE(ire);
18639 }
18640 
18641 /*
18642  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18643  * if the receiver shrinks the window, i.e. moves the right window to the
18644  * left, the we should not send new data, but should retransmit normally the
18645  * old unacked data between suna and suna + swnd. We might has sent data
18646  * that is now outside the new window, pretend that we didn't send  it.
18647  */
18648 static void
18649 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18650 {
18651 	uint32_t	snxt = tcp->tcp_snxt;
18652 
18653 	ASSERT(shrunk_count > 0);
18654 
18655 	if (!tcp->tcp_is_wnd_shrnk) {
18656 		tcp->tcp_snxt_shrunk = snxt;
18657 		tcp->tcp_is_wnd_shrnk = B_TRUE;
18658 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
18659 		tcp->tcp_snxt_shrunk = snxt;
18660 	}
18661 
18662 	/* Pretend we didn't send the data outside the window */
18663 	snxt -= shrunk_count;
18664 
18665 	/* Reset all the values per the now shrunk window */
18666 	tcp_update_xmit_tail(tcp, snxt);
18667 	tcp->tcp_unsent += shrunk_count;
18668 
18669 	/*
18670 	 * If the SACK option is set, delete the entire list of
18671 	 * notsack'ed blocks.
18672 	 */
18673 	if (tcp->tcp_sack_info != NULL) {
18674 		if (tcp->tcp_notsack_list != NULL)
18675 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
18676 	}
18677 
18678 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18679 		/*
18680 		 * Make sure the timer is running so that we will probe a zero
18681 		 * window.
18682 		 */
18683 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18684 }
18685 
18686 
18687 /*
18688  * The TCP normal data output path.
18689  * NOTE: the logic of the fast path is duplicated from this function.
18690  */
18691 static void
18692 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18693 {
18694 	int		len;
18695 	mblk_t		*local_time;
18696 	mblk_t		*mp1;
18697 	uint32_t	snxt;
18698 	int		tail_unsent;
18699 	int		tcpstate;
18700 	int		usable = 0;
18701 	mblk_t		*xmit_tail;
18702 	queue_t		*q = tcp->tcp_wq;
18703 	int32_t		mss;
18704 	int32_t		num_sack_blk = 0;
18705 	int32_t		tcp_hdr_len;
18706 	int32_t		tcp_tcp_hdr_len;
18707 	int		mdt_thres;
18708 	int		rc;
18709 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18710 	ip_stack_t	*ipst;
18711 
18712 	tcpstate = tcp->tcp_state;
18713 	if (mp == NULL) {
18714 		/*
18715 		 * tcp_wput_data() with NULL mp should only be called when
18716 		 * there is unsent data.
18717 		 */
18718 		ASSERT(tcp->tcp_unsent > 0);
18719 		/* Really tacky... but we need this for detached closes. */
18720 		len = tcp->tcp_unsent;
18721 		goto data_null;
18722 	}
18723 
18724 #if CCS_STATS
18725 	wrw_stats.tot.count++;
18726 	wrw_stats.tot.bytes += msgdsize(mp);
18727 #endif
18728 	ASSERT(mp->b_datap->db_type == M_DATA);
18729 	/*
18730 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18731 	 * or before a connection attempt has begun.
18732 	 */
18733 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18734 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18735 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18736 #ifdef DEBUG
18737 			cmn_err(CE_WARN,
18738 			    "tcp_wput_data: data after ordrel, %s",
18739 			    tcp_display(tcp, NULL,
18740 			    DISP_ADDR_AND_PORT));
18741 #else
18742 			if (tcp->tcp_debug) {
18743 				(void) strlog(TCP_MOD_ID, 0, 1,
18744 				    SL_TRACE|SL_ERROR,
18745 				    "tcp_wput_data: data after ordrel, %s\n",
18746 				    tcp_display(tcp, NULL,
18747 				    DISP_ADDR_AND_PORT));
18748 			}
18749 #endif /* DEBUG */
18750 		}
18751 		if (tcp->tcp_snd_zcopy_aware &&
18752 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18753 			tcp_zcopy_notify(tcp);
18754 		freemsg(mp);
18755 		mutex_enter(&tcp->tcp_non_sq_lock);
18756 		if (tcp->tcp_flow_stopped &&
18757 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18758 			tcp_clrqfull(tcp);
18759 		}
18760 		mutex_exit(&tcp->tcp_non_sq_lock);
18761 		return;
18762 	}
18763 
18764 	/* Strip empties */
18765 	for (;;) {
18766 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18767 		    (uintptr_t)INT_MAX);
18768 		len = (int)(mp->b_wptr - mp->b_rptr);
18769 		if (len > 0)
18770 			break;
18771 		mp1 = mp;
18772 		mp = mp->b_cont;
18773 		freeb(mp1);
18774 		if (!mp) {
18775 			return;
18776 		}
18777 	}
18778 
18779 	/* If we are the first on the list ... */
18780 	if (tcp->tcp_xmit_head == NULL) {
18781 		tcp->tcp_xmit_head = mp;
18782 		tcp->tcp_xmit_tail = mp;
18783 		tcp->tcp_xmit_tail_unsent = len;
18784 	} else {
18785 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18786 		struct datab *dp;
18787 
18788 		mp1 = tcp->tcp_xmit_last;
18789 		if (len < tcp_tx_pull_len &&
18790 		    (dp = mp1->b_datap)->db_ref == 1 &&
18791 		    dp->db_lim - mp1->b_wptr >= len) {
18792 			ASSERT(len > 0);
18793 			ASSERT(!mp1->b_cont);
18794 			if (len == 1) {
18795 				*mp1->b_wptr++ = *mp->b_rptr;
18796 			} else {
18797 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18798 				mp1->b_wptr += len;
18799 			}
18800 			if (mp1 == tcp->tcp_xmit_tail)
18801 				tcp->tcp_xmit_tail_unsent += len;
18802 			mp1->b_cont = mp->b_cont;
18803 			if (tcp->tcp_snd_zcopy_aware &&
18804 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18805 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18806 			freeb(mp);
18807 			mp = mp1;
18808 		} else {
18809 			tcp->tcp_xmit_last->b_cont = mp;
18810 		}
18811 		len += tcp->tcp_unsent;
18812 	}
18813 
18814 	/* Tack on however many more positive length mblks we have */
18815 	if ((mp1 = mp->b_cont) != NULL) {
18816 		do {
18817 			int tlen;
18818 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18819 			    (uintptr_t)INT_MAX);
18820 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18821 			if (tlen <= 0) {
18822 				mp->b_cont = mp1->b_cont;
18823 				freeb(mp1);
18824 			} else {
18825 				len += tlen;
18826 				mp = mp1;
18827 			}
18828 		} while ((mp1 = mp->b_cont) != NULL);
18829 	}
18830 	tcp->tcp_xmit_last = mp;
18831 	tcp->tcp_unsent = len;
18832 
18833 	if (urgent)
18834 		usable = 1;
18835 
18836 data_null:
18837 	snxt = tcp->tcp_snxt;
18838 	xmit_tail = tcp->tcp_xmit_tail;
18839 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18840 
18841 	/*
18842 	 * Note that tcp_mss has been adjusted to take into account the
18843 	 * timestamp option if applicable.  Because SACK options do not
18844 	 * appear in every TCP segments and they are of variable lengths,
18845 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18846 	 * the actual segment length when we need to send a segment which
18847 	 * includes SACK options.
18848 	 */
18849 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18850 		int32_t	opt_len;
18851 
18852 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18853 		    tcp->tcp_num_sack_blk);
18854 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18855 		    2 + TCPOPT_HEADER_LEN;
18856 		mss = tcp->tcp_mss - opt_len;
18857 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18858 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18859 	} else {
18860 		mss = tcp->tcp_mss;
18861 		tcp_hdr_len = tcp->tcp_hdr_len;
18862 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18863 	}
18864 
18865 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18866 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18867 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18868 	}
18869 	if (tcpstate == TCPS_SYN_RCVD) {
18870 		/*
18871 		 * The three-way connection establishment handshake is not
18872 		 * complete yet. We want to queue the data for transmission
18873 		 * after entering ESTABLISHED state (RFC793). A jump to
18874 		 * "done" label effectively leaves data on the queue.
18875 		 */
18876 		goto done;
18877 	} else {
18878 		int usable_r;
18879 
18880 		/*
18881 		 * In the special case when cwnd is zero, which can only
18882 		 * happen if the connection is ECN capable, return now.
18883 		 * New segments is sent using tcp_timer().  The timer
18884 		 * is set in tcp_rput_data().
18885 		 */
18886 		if (tcp->tcp_cwnd == 0) {
18887 			/*
18888 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18889 			 * finished.
18890 			 */
18891 			ASSERT(tcp->tcp_ecn_ok ||
18892 			    tcp->tcp_state < TCPS_ESTABLISHED);
18893 			return;
18894 		}
18895 
18896 		/* NOTE: trouble if xmitting while SYN not acked? */
18897 		usable_r = snxt - tcp->tcp_suna;
18898 		usable_r = tcp->tcp_swnd - usable_r;
18899 
18900 		/*
18901 		 * Check if the receiver has shrunk the window.  If
18902 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18903 		 * cannot be set as there is unsent data, so FIN cannot
18904 		 * be sent out.  Otherwise, we need to take into account
18905 		 * of FIN as it consumes an "invisible" sequence number.
18906 		 */
18907 		ASSERT(tcp->tcp_fin_sent == 0);
18908 		if (usable_r < 0) {
18909 			/*
18910 			 * The receiver has shrunk the window and we have sent
18911 			 * -usable_r date beyond the window, re-adjust.
18912 			 *
18913 			 * If TCP window scaling is enabled, there can be
18914 			 * round down error as the advertised receive window
18915 			 * is actually right shifted n bits.  This means that
18916 			 * the lower n bits info is wiped out.  It will look
18917 			 * like the window is shrunk.  Do a check here to
18918 			 * see if the shrunk amount is actually within the
18919 			 * error in window calculation.  If it is, just
18920 			 * return.  Note that this check is inside the
18921 			 * shrunk window check.  This makes sure that even
18922 			 * though tcp_process_shrunk_swnd() is not called,
18923 			 * we will stop further processing.
18924 			 */
18925 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18926 				tcp_process_shrunk_swnd(tcp, -usable_r);
18927 			}
18928 			return;
18929 		}
18930 
18931 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18932 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18933 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18934 
18935 		/* usable = MIN(usable, unsent) */
18936 		if (usable_r > len)
18937 			usable_r = len;
18938 
18939 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18940 		if (usable_r > 0) {
18941 			usable = usable_r;
18942 		} else {
18943 			/* Bypass all other unnecessary processing. */
18944 			goto done;
18945 		}
18946 	}
18947 
18948 	local_time = (mblk_t *)lbolt;
18949 
18950 	/*
18951 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18952 	 * BSD.  This is more in line with the true intent of Nagle.
18953 	 *
18954 	 * The conditions are:
18955 	 * 1. The amount of unsent data (or amount of data which can be
18956 	 *    sent, whichever is smaller) is less than Nagle limit.
18957 	 * 2. The last sent size is also less than Nagle limit.
18958 	 * 3. There is unack'ed data.
18959 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18960 	 *    Nagle algorithm.  This reduces the probability that urgent
18961 	 *    bytes get "merged" together.
18962 	 * 5. The app has not closed the connection.  This eliminates the
18963 	 *    wait time of the receiving side waiting for the last piece of
18964 	 *    (small) data.
18965 	 *
18966 	 * If all are satisified, exit without sending anything.  Note
18967 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18968 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18969 	 * 4095).
18970 	 */
18971 	if (usable < (int)tcp->tcp_naglim &&
18972 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18973 	    snxt != tcp->tcp_suna &&
18974 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18975 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18976 		goto done;
18977 	}
18978 
18979 	/*
18980 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
18981 	 * is set, then we have to force TCP not to send partial segment
18982 	 * (smaller than MSS bytes). We are calculating the usable now
18983 	 * based on full mss and will save the rest of remaining data for
18984 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
18985 	 * something to do zero window probe.
18986 	 */
18987 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
18988 		if (usable < mss)
18989 			goto done;
18990 		usable = (usable / mss) * mss;
18991 	}
18992 
18993 	/* Update the latest receive window size in TCP header. */
18994 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18995 	    tcp->tcp_tcph->th_win);
18996 
18997 	/*
18998 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
18999 	 *
19000 	 * 1. Simple TCP/IP{v4,v6} (no options).
19001 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19002 	 * 3. If the TCP connection is in ESTABLISHED state.
19003 	 * 4. The TCP is not detached.
19004 	 *
19005 	 * If any of the above conditions have changed during the
19006 	 * connection, stop using LSO/MDT and restore the stream head
19007 	 * parameters accordingly.
19008 	 */
19009 	ipst = tcps->tcps_netstack->netstack_ip;
19010 
19011 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19012 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19013 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19014 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19015 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19016 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19017 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19018 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19019 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19020 		if (tcp->tcp_lso) {
19021 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19022 			tcp->tcp_lso = B_FALSE;
19023 		} else {
19024 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19025 			tcp->tcp_mdt = B_FALSE;
19026 		}
19027 
19028 		/* Anything other than detached is considered pathological */
19029 		if (!TCP_IS_DETACHED(tcp)) {
19030 			if (tcp->tcp_lso)
19031 				TCP_STAT(tcps, tcp_lso_disabled);
19032 			else
19033 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19034 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19035 		}
19036 	}
19037 
19038 	/* Use MDT if sendable amount is greater than the threshold */
19039 	if (tcp->tcp_mdt &&
19040 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19041 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19042 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19043 	    (tcp->tcp_valid_bits == 0 ||
19044 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19045 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19046 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19047 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19048 		    local_time, mdt_thres);
19049 	} else {
19050 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19051 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19052 		    local_time, INT_MAX);
19053 	}
19054 
19055 	/* Pretend that all we were trying to send really got sent */
19056 	if (rc < 0 && tail_unsent < 0) {
19057 		do {
19058 			xmit_tail = xmit_tail->b_cont;
19059 			xmit_tail->b_prev = local_time;
19060 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19061 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19062 			tail_unsent += (int)(xmit_tail->b_wptr -
19063 			    xmit_tail->b_rptr);
19064 		} while (tail_unsent < 0);
19065 	}
19066 done:;
19067 	tcp->tcp_xmit_tail = xmit_tail;
19068 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19069 	len = tcp->tcp_snxt - snxt;
19070 	if (len) {
19071 		/*
19072 		 * If new data was sent, need to update the notsack
19073 		 * list, which is, afterall, data blocks that have
19074 		 * not been sack'ed by the receiver.  New data is
19075 		 * not sack'ed.
19076 		 */
19077 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19078 			/* len is a negative value. */
19079 			tcp->tcp_pipe -= len;
19080 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19081 			    tcp->tcp_snxt, snxt,
19082 			    &(tcp->tcp_num_notsack_blk),
19083 			    &(tcp->tcp_cnt_notsack_list));
19084 		}
19085 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19086 		tcp->tcp_rack = tcp->tcp_rnxt;
19087 		tcp->tcp_rack_cnt = 0;
19088 		if ((snxt + len) == tcp->tcp_suna) {
19089 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19090 		}
19091 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19092 		/*
19093 		 * Didn't send anything. Make sure the timer is running
19094 		 * so that we will probe a zero window.
19095 		 */
19096 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19097 	}
19098 	/* Note that len is the amount we just sent but with a negative sign */
19099 	tcp->tcp_unsent += len;
19100 	mutex_enter(&tcp->tcp_non_sq_lock);
19101 	if (tcp->tcp_flow_stopped) {
19102 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19103 			tcp_clrqfull(tcp);
19104 		}
19105 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19106 		tcp_setqfull(tcp);
19107 	}
19108 	mutex_exit(&tcp->tcp_non_sq_lock);
19109 }
19110 
19111 /*
19112  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19113  * outgoing TCP header with the template header, as well as other
19114  * options such as time-stamp, ECN and/or SACK.
19115  */
19116 static void
19117 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19118 {
19119 	tcph_t *tcp_tmpl, *tcp_h;
19120 	uint32_t *dst, *src;
19121 	int hdrlen;
19122 
19123 	ASSERT(OK_32PTR(rptr));
19124 
19125 	/* Template header */
19126 	tcp_tmpl = tcp->tcp_tcph;
19127 
19128 	/* Header of outgoing packet */
19129 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19130 
19131 	/* dst and src are opaque 32-bit fields, used for copying */
19132 	dst = (uint32_t *)rptr;
19133 	src = (uint32_t *)tcp->tcp_iphc;
19134 	hdrlen = tcp->tcp_hdr_len;
19135 
19136 	/* Fill time-stamp option if needed */
19137 	if (tcp->tcp_snd_ts_ok) {
19138 		U32_TO_BE32((uint32_t)now,
19139 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19140 		U32_TO_BE32(tcp->tcp_ts_recent,
19141 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19142 	} else {
19143 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19144 	}
19145 
19146 	/*
19147 	 * Copy the template header; is this really more efficient than
19148 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19149 	 * but perhaps not for other scenarios.
19150 	 */
19151 	dst[0] = src[0];
19152 	dst[1] = src[1];
19153 	dst[2] = src[2];
19154 	dst[3] = src[3];
19155 	dst[4] = src[4];
19156 	dst[5] = src[5];
19157 	dst[6] = src[6];
19158 	dst[7] = src[7];
19159 	dst[8] = src[8];
19160 	dst[9] = src[9];
19161 	if (hdrlen -= 40) {
19162 		hdrlen >>= 2;
19163 		dst += 10;
19164 		src += 10;
19165 		do {
19166 			*dst++ = *src++;
19167 		} while (--hdrlen);
19168 	}
19169 
19170 	/*
19171 	 * Set the ECN info in the TCP header if it is not a zero
19172 	 * window probe.  Zero window probe is only sent in
19173 	 * tcp_wput_data() and tcp_timer().
19174 	 */
19175 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19176 		SET_ECT(tcp, rptr);
19177 
19178 		if (tcp->tcp_ecn_echo_on)
19179 			tcp_h->th_flags[0] |= TH_ECE;
19180 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19181 			tcp_h->th_flags[0] |= TH_CWR;
19182 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19183 		}
19184 	}
19185 
19186 	/* Fill in SACK options */
19187 	if (num_sack_blk > 0) {
19188 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19189 		sack_blk_t *tmp;
19190 		int32_t	i;
19191 
19192 		wptr[0] = TCPOPT_NOP;
19193 		wptr[1] = TCPOPT_NOP;
19194 		wptr[2] = TCPOPT_SACK;
19195 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19196 		    sizeof (sack_blk_t);
19197 		wptr += TCPOPT_REAL_SACK_LEN;
19198 
19199 		tmp = tcp->tcp_sack_list;
19200 		for (i = 0; i < num_sack_blk; i++) {
19201 			U32_TO_BE32(tmp[i].begin, wptr);
19202 			wptr += sizeof (tcp_seq);
19203 			U32_TO_BE32(tmp[i].end, wptr);
19204 			wptr += sizeof (tcp_seq);
19205 		}
19206 		tcp_h->th_offset_and_rsrvd[0] +=
19207 		    ((num_sack_blk * 2 + 1) << 4);
19208 	}
19209 }
19210 
19211 /*
19212  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19213  * the destination address and SAP attribute, and if necessary, the
19214  * hardware checksum offload attribute to a Multidata message.
19215  */
19216 static int
19217 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19218     const uint32_t start, const uint32_t stuff, const uint32_t end,
19219     const uint32_t flags, tcp_stack_t *tcps)
19220 {
19221 	/* Add global destination address & SAP attribute */
19222 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19223 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19224 		    "destination address+SAP\n"));
19225 
19226 		if (dlmp != NULL)
19227 			TCP_STAT(tcps, tcp_mdt_allocfail);
19228 		return (-1);
19229 	}
19230 
19231 	/* Add global hwcksum attribute */
19232 	if (hwcksum &&
19233 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19234 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19235 		    "checksum attribute\n"));
19236 
19237 		TCP_STAT(tcps, tcp_mdt_allocfail);
19238 		return (-1);
19239 	}
19240 
19241 	return (0);
19242 }
19243 
19244 /*
19245  * Smaller and private version of pdescinfo_t used specifically for TCP,
19246  * which allows for only two payload spans per packet.
19247  */
19248 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19249 
19250 /*
19251  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19252  * scheme, and returns one the following:
19253  *
19254  * -1 = failed allocation.
19255  *  0 = success; burst count reached, or usable send window is too small,
19256  *      and that we'd rather wait until later before sending again.
19257  */
19258 static int
19259 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19260     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19261     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19262     const int mdt_thres)
19263 {
19264 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19265 	multidata_t	*mmd;
19266 	uint_t		obsegs, obbytes, hdr_frag_sz;
19267 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19268 	int		num_burst_seg, max_pld;
19269 	pdesc_t		*pkt;
19270 	tcp_pdescinfo_t	tcp_pkt_info;
19271 	pdescinfo_t	*pkt_info;
19272 	int		pbuf_idx, pbuf_idx_nxt;
19273 	int		seg_len, len, spill, af;
19274 	boolean_t	add_buffer, zcopy, clusterwide;
19275 	boolean_t	rconfirm = B_FALSE;
19276 	boolean_t	done = B_FALSE;
19277 	uint32_t	cksum;
19278 	uint32_t	hwcksum_flags;
19279 	ire_t		*ire = NULL;
19280 	ill_t		*ill;
19281 	ipha_t		*ipha;
19282 	ip6_t		*ip6h;
19283 	ipaddr_t	src, dst;
19284 	ill_zerocopy_capab_t *zc_cap = NULL;
19285 	uint16_t	*up;
19286 	int		err;
19287 	conn_t		*connp;
19288 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19289 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19290 	int		usable_mmd, tail_unsent_mmd;
19291 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19292 	mblk_t		*xmit_tail_mmd;
19293 	netstackid_t	stack_id;
19294 
19295 #ifdef	_BIG_ENDIAN
19296 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19297 #else
19298 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19299 #endif
19300 
19301 #define	PREP_NEW_MULTIDATA() {			\
19302 	mmd = NULL;				\
19303 	md_mp = md_hbuf = NULL;			\
19304 	cur_hdr_off = 0;			\
19305 	max_pld = tcp->tcp_mdt_max_pld;		\
19306 	pbuf_idx = pbuf_idx_nxt = -1;		\
19307 	add_buffer = B_TRUE;			\
19308 	zcopy = B_FALSE;			\
19309 }
19310 
19311 #define	PREP_NEW_PBUF() {			\
19312 	md_pbuf = md_pbuf_nxt = NULL;		\
19313 	pbuf_idx = pbuf_idx_nxt = -1;		\
19314 	cur_pld_off = 0;			\
19315 	first_snxt = *snxt;			\
19316 	ASSERT(*tail_unsent > 0);		\
19317 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19318 }
19319 
19320 	ASSERT(mdt_thres >= mss);
19321 	ASSERT(*usable > 0 && *usable > mdt_thres);
19322 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19323 	ASSERT(!TCP_IS_DETACHED(tcp));
19324 	ASSERT(tcp->tcp_valid_bits == 0 ||
19325 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19326 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19327 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19328 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19329 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19330 
19331 	connp = tcp->tcp_connp;
19332 	ASSERT(connp != NULL);
19333 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19334 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19335 
19336 	stack_id = connp->conn_netstack->netstack_stackid;
19337 
19338 	usable_mmd = tail_unsent_mmd = 0;
19339 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
19340 	xmit_tail_mmd = NULL;
19341 	/*
19342 	 * Note that tcp will only declare at most 2 payload spans per
19343 	 * packet, which is much lower than the maximum allowable number
19344 	 * of packet spans per Multidata.  For this reason, we use the
19345 	 * privately declared and smaller descriptor info structure, in
19346 	 * order to save some stack space.
19347 	 */
19348 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19349 
19350 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19351 	if (af == AF_INET) {
19352 		dst = tcp->tcp_ipha->ipha_dst;
19353 		src = tcp->tcp_ipha->ipha_src;
19354 		ASSERT(!CLASSD(dst));
19355 	}
19356 	ASSERT(af == AF_INET ||
19357 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19358 
19359 	obsegs = obbytes = 0;
19360 	num_burst_seg = tcp->tcp_snd_burst;
19361 	md_mp_head = NULL;
19362 	PREP_NEW_MULTIDATA();
19363 
19364 	/*
19365 	 * Before we go on further, make sure there is an IRE that we can
19366 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19367 	 * in proceeding any further, and we should just hand everything
19368 	 * off to the legacy path.
19369 	 */
19370 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19371 		goto legacy_send_no_md;
19372 
19373 	ASSERT(ire != NULL);
19374 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19375 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19376 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19377 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19378 	/*
19379 	 * If we do support loopback for MDT (which requires modifications
19380 	 * to the receiving paths), the following assertions should go away,
19381 	 * and we would be sending the Multidata to loopback conn later on.
19382 	 */
19383 	ASSERT(!IRE_IS_LOCAL(ire));
19384 	ASSERT(ire->ire_stq != NULL);
19385 
19386 	ill = ire_to_ill(ire);
19387 	ASSERT(ill != NULL);
19388 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19389 
19390 	if (!tcp->tcp_ire_ill_check_done) {
19391 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19392 		tcp->tcp_ire_ill_check_done = B_TRUE;
19393 	}
19394 
19395 	/*
19396 	 * If the underlying interface conditions have changed, or if the
19397 	 * new interface does not support MDT, go back to legacy path.
19398 	 */
19399 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19400 		/* don't go through this path anymore for this connection */
19401 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19402 		tcp->tcp_mdt = B_FALSE;
19403 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19404 		    "interface %s\n", (void *)connp, ill->ill_name));
19405 		/* IRE will be released prior to returning */
19406 		goto legacy_send_no_md;
19407 	}
19408 
19409 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19410 		zc_cap = ill->ill_zerocopy_capab;
19411 
19412 	/*
19413 	 * Check if we can take tcp fast-path. Note that "incomplete"
19414 	 * ire's (where the link-layer for next hop is not resolved
19415 	 * or where the fast-path header in nce_fp_mp is not available
19416 	 * yet) are sent down the legacy (slow) path.
19417 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19418 	 */
19419 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19420 		/* IRE will be released prior to returning */
19421 		goto legacy_send_no_md;
19422 	}
19423 
19424 	/* go to legacy path if interface doesn't support zerocopy */
19425 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19426 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19427 		/* IRE will be released prior to returning */
19428 		goto legacy_send_no_md;
19429 	}
19430 
19431 	/* does the interface support hardware checksum offload? */
19432 	hwcksum_flags = 0;
19433 	if (ILL_HCKSUM_CAPABLE(ill) &&
19434 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19435 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19436 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19437 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19438 		    HCKSUM_IPHDRCKSUM)
19439 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19440 
19441 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19442 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19443 			hwcksum_flags |= HCK_FULLCKSUM;
19444 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19445 		    HCKSUM_INET_PARTIAL)
19446 			hwcksum_flags |= HCK_PARTIALCKSUM;
19447 	}
19448 
19449 	/*
19450 	 * Each header fragment consists of the leading extra space,
19451 	 * followed by the TCP/IP header, and the trailing extra space.
19452 	 * We make sure that each header fragment begins on a 32-bit
19453 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19454 	 * aligned in tcp_mdt_update).
19455 	 */
19456 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19457 	    tcp->tcp_mdt_hdr_tail), 4);
19458 
19459 	/* are we starting from the beginning of data block? */
19460 	if (*tail_unsent == 0) {
19461 		*xmit_tail = (*xmit_tail)->b_cont;
19462 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19463 		*tail_unsent = (int)MBLKL(*xmit_tail);
19464 	}
19465 
19466 	/*
19467 	 * Here we create one or more Multidata messages, each made up of
19468 	 * one header buffer and up to N payload buffers.  This entire
19469 	 * operation is done within two loops:
19470 	 *
19471 	 * The outer loop mostly deals with creating the Multidata message,
19472 	 * as well as the header buffer that gets added to it.  It also
19473 	 * links the Multidata messages together such that all of them can
19474 	 * be sent down to the lower layer in a single putnext call; this
19475 	 * linking behavior depends on the tcp_mdt_chain tunable.
19476 	 *
19477 	 * The inner loop takes an existing Multidata message, and adds
19478 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19479 	 * packetizes those buffers by filling up the corresponding header
19480 	 * buffer fragments with the proper IP and TCP headers, and by
19481 	 * describing the layout of each packet in the packet descriptors
19482 	 * that get added to the Multidata.
19483 	 */
19484 	do {
19485 		/*
19486 		 * If usable send window is too small, or data blocks in
19487 		 * transmit list are smaller than our threshold (i.e. app
19488 		 * performs large writes followed by small ones), we hand
19489 		 * off the control over to the legacy path.  Note that we'll
19490 		 * get back the control once it encounters a large block.
19491 		 */
19492 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19493 		    (*xmit_tail)->b_cont != NULL &&
19494 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19495 			/* send down what we've got so far */
19496 			if (md_mp_head != NULL) {
19497 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19498 				    obsegs, obbytes, &rconfirm);
19499 			}
19500 			/*
19501 			 * Pass control over to tcp_send(), but tell it to
19502 			 * return to us once a large-size transmission is
19503 			 * possible.
19504 			 */
19505 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19506 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19507 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19508 			    tail_unsent, xmit_tail, local_time,
19509 			    mdt_thres)) <= 0) {
19510 				/* burst count reached, or alloc failed */
19511 				IRE_REFRELE(ire);
19512 				return (err);
19513 			}
19514 
19515 			/* tcp_send() may have sent everything, so check */
19516 			if (*usable <= 0) {
19517 				IRE_REFRELE(ire);
19518 				return (0);
19519 			}
19520 
19521 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19522 			/*
19523 			 * We may have delivered the Multidata, so make sure
19524 			 * to re-initialize before the next round.
19525 			 */
19526 			md_mp_head = NULL;
19527 			obsegs = obbytes = 0;
19528 			num_burst_seg = tcp->tcp_snd_burst;
19529 			PREP_NEW_MULTIDATA();
19530 
19531 			/* are we starting from the beginning of data block? */
19532 			if (*tail_unsent == 0) {
19533 				*xmit_tail = (*xmit_tail)->b_cont;
19534 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19535 				    (uintptr_t)INT_MAX);
19536 				*tail_unsent = (int)MBLKL(*xmit_tail);
19537 			}
19538 		}
19539 		/*
19540 		 * Record current values for parameters we may need to pass
19541 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
19542 		 * each iteration of the outer loop (each multidata message
19543 		 * creation). If we have a failure in the inner loop, we send
19544 		 * any complete multidata messages we have before reverting
19545 		 * to using the traditional non-md path.
19546 		 */
19547 		snxt_mmd = *snxt;
19548 		usable_mmd = *usable;
19549 		xmit_tail_mmd = *xmit_tail;
19550 		tail_unsent_mmd = *tail_unsent;
19551 		obsegs_mmd = obsegs;
19552 		obbytes_mmd = obbytes;
19553 
19554 		/*
19555 		 * max_pld limits the number of mblks in tcp's transmit
19556 		 * queue that can be added to a Multidata message.  Once
19557 		 * this counter reaches zero, no more additional mblks
19558 		 * can be added to it.  What happens afterwards depends
19559 		 * on whether or not we are set to chain the Multidata
19560 		 * messages.  If we are to link them together, reset
19561 		 * max_pld to its original value (tcp_mdt_max_pld) and
19562 		 * prepare to create a new Multidata message which will
19563 		 * get linked to md_mp_head.  Else, leave it alone and
19564 		 * let the inner loop break on its own.
19565 		 */
19566 		if (tcp_mdt_chain && max_pld == 0)
19567 			PREP_NEW_MULTIDATA();
19568 
19569 		/* adding a payload buffer; re-initialize values */
19570 		if (add_buffer)
19571 			PREP_NEW_PBUF();
19572 
19573 		/*
19574 		 * If we don't have a Multidata, either because we just
19575 		 * (re)entered this outer loop, or after we branched off
19576 		 * to tcp_send above, setup the Multidata and header
19577 		 * buffer to be used.
19578 		 */
19579 		if (md_mp == NULL) {
19580 			int md_hbuflen;
19581 			uint32_t start, stuff;
19582 
19583 			/*
19584 			 * Calculate Multidata header buffer size large enough
19585 			 * to hold all of the headers that can possibly be
19586 			 * sent at this moment.  We'd rather over-estimate
19587 			 * the size than running out of space; this is okay
19588 			 * since this buffer is small anyway.
19589 			 */
19590 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19591 
19592 			/*
19593 			 * Start and stuff offset for partial hardware
19594 			 * checksum offload; these are currently for IPv4.
19595 			 * For full checksum offload, they are set to zero.
19596 			 */
19597 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19598 				if (af == AF_INET) {
19599 					start = IP_SIMPLE_HDR_LENGTH;
19600 					stuff = IP_SIMPLE_HDR_LENGTH +
19601 					    TCP_CHECKSUM_OFFSET;
19602 				} else {
19603 					start = IPV6_HDR_LEN;
19604 					stuff = IPV6_HDR_LEN +
19605 					    TCP_CHECKSUM_OFFSET;
19606 				}
19607 			} else {
19608 				start = stuff = 0;
19609 			}
19610 
19611 			/*
19612 			 * Create the header buffer, Multidata, as well as
19613 			 * any necessary attributes (destination address,
19614 			 * SAP and hardware checksum offload) that should
19615 			 * be associated with the Multidata message.
19616 			 */
19617 			ASSERT(cur_hdr_off == 0);
19618 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19619 			    ((md_hbuf->b_wptr += md_hbuflen),
19620 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19621 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19622 			    /* fastpath mblk */
19623 			    ire->ire_nce->nce_res_mp,
19624 			    /* hardware checksum enabled */
19625 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19626 			    /* hardware checksum offsets */
19627 			    start, stuff, 0,
19628 			    /* hardware checksum flag */
19629 			    hwcksum_flags, tcps) != 0)) {
19630 legacy_send:
19631 				/*
19632 				 * We arrive here from a failure within the
19633 				 * inner (packetizer) loop or we fail one of
19634 				 * the conditionals above. We restore the
19635 				 * previously checkpointed values for:
19636 				 *    xmit_tail
19637 				 *    usable
19638 				 *    tail_unsent
19639 				 *    snxt
19640 				 *    obbytes
19641 				 *    obsegs
19642 				 * We should then be able to dispatch any
19643 				 * complete multidata before reverting to the
19644 				 * traditional path with consistent parameters
19645 				 * (the inner loop updates these as it
19646 				 * iterates).
19647 				 */
19648 				*xmit_tail = xmit_tail_mmd;
19649 				*usable = usable_mmd;
19650 				*tail_unsent = tail_unsent_mmd;
19651 				*snxt = snxt_mmd;
19652 				obbytes = obbytes_mmd;
19653 				obsegs = obsegs_mmd;
19654 				if (md_mp != NULL) {
19655 					/* Unlink message from the chain */
19656 					if (md_mp_head != NULL) {
19657 						err = (intptr_t)rmvb(md_mp_head,
19658 						    md_mp);
19659 						/*
19660 						 * We can't assert that rmvb
19661 						 * did not return -1, since we
19662 						 * may get here before linkb
19663 						 * happens.  We do, however,
19664 						 * check if we just removed the
19665 						 * only element in the list.
19666 						 */
19667 						if (err == 0)
19668 							md_mp_head = NULL;
19669 					}
19670 					/* md_hbuf gets freed automatically */
19671 					TCP_STAT(tcps, tcp_mdt_discarded);
19672 					freeb(md_mp);
19673 				} else {
19674 					/* Either allocb or mmd_alloc failed */
19675 					TCP_STAT(tcps, tcp_mdt_allocfail);
19676 					if (md_hbuf != NULL)
19677 						freeb(md_hbuf);
19678 				}
19679 
19680 				/* send down what we've got so far */
19681 				if (md_mp_head != NULL) {
19682 					tcp_multisend_data(tcp, ire, ill,
19683 					    md_mp_head, obsegs, obbytes,
19684 					    &rconfirm);
19685 				}
19686 legacy_send_no_md:
19687 				if (ire != NULL)
19688 					IRE_REFRELE(ire);
19689 				/*
19690 				 * Too bad; let the legacy path handle this.
19691 				 * We specify INT_MAX for the threshold, since
19692 				 * we gave up with the Multidata processings
19693 				 * and let the old path have it all.
19694 				 */
19695 				TCP_STAT(tcps, tcp_mdt_legacy_all);
19696 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19697 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19698 				    snxt, tail_unsent, xmit_tail, local_time,
19699 				    INT_MAX));
19700 			}
19701 
19702 			/* link to any existing ones, if applicable */
19703 			TCP_STAT(tcps, tcp_mdt_allocd);
19704 			if (md_mp_head == NULL) {
19705 				md_mp_head = md_mp;
19706 			} else if (tcp_mdt_chain) {
19707 				TCP_STAT(tcps, tcp_mdt_linked);
19708 				linkb(md_mp_head, md_mp);
19709 			}
19710 		}
19711 
19712 		ASSERT(md_mp_head != NULL);
19713 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19714 		ASSERT(md_mp != NULL && mmd != NULL);
19715 		ASSERT(md_hbuf != NULL);
19716 
19717 		/*
19718 		 * Packetize the transmittable portion of the data block;
19719 		 * each data block is essentially added to the Multidata
19720 		 * as a payload buffer.  We also deal with adding more
19721 		 * than one payload buffers, which happens when the remaining
19722 		 * packetized portion of the current payload buffer is less
19723 		 * than MSS, while the next data block in transmit queue
19724 		 * has enough data to make up for one.  This "spillover"
19725 		 * case essentially creates a split-packet, where portions
19726 		 * of the packet's payload fragments may span across two
19727 		 * virtually discontiguous address blocks.
19728 		 */
19729 		seg_len = mss;
19730 		do {
19731 			len = seg_len;
19732 
19733 			/* one must remain NULL for DTRACE_IP_FASTPATH */
19734 			ipha = NULL;
19735 			ip6h = NULL;
19736 
19737 			ASSERT(len > 0);
19738 			ASSERT(max_pld >= 0);
19739 			ASSERT(!add_buffer || cur_pld_off == 0);
19740 
19741 			/*
19742 			 * First time around for this payload buffer; note
19743 			 * in the case of a spillover, the following has
19744 			 * been done prior to adding the split-packet
19745 			 * descriptor to Multidata, and we don't want to
19746 			 * repeat the process.
19747 			 */
19748 			if (add_buffer) {
19749 				ASSERT(mmd != NULL);
19750 				ASSERT(md_pbuf == NULL);
19751 				ASSERT(md_pbuf_nxt == NULL);
19752 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19753 
19754 				/*
19755 				 * Have we reached the limit?  We'd get to
19756 				 * this case when we're not chaining the
19757 				 * Multidata messages together, and since
19758 				 * we're done, terminate this loop.
19759 				 */
19760 				if (max_pld == 0)
19761 					break; /* done */
19762 
19763 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19764 					TCP_STAT(tcps, tcp_mdt_allocfail);
19765 					goto legacy_send; /* out_of_mem */
19766 				}
19767 
19768 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19769 				    zc_cap != NULL) {
19770 					if (!ip_md_zcopy_attr(mmd, NULL,
19771 					    zc_cap->ill_zerocopy_flags)) {
19772 						freeb(md_pbuf);
19773 						TCP_STAT(tcps,
19774 						    tcp_mdt_allocfail);
19775 						/* out_of_mem */
19776 						goto legacy_send;
19777 					}
19778 					zcopy = B_TRUE;
19779 				}
19780 
19781 				md_pbuf->b_rptr += base_pld_off;
19782 
19783 				/*
19784 				 * Add a payload buffer to the Multidata; this
19785 				 * operation must not fail, or otherwise our
19786 				 * logic in this routine is broken.  There
19787 				 * is no memory allocation done by the
19788 				 * routine, so any returned failure simply
19789 				 * tells us that we've done something wrong.
19790 				 *
19791 				 * A failure tells us that either we're adding
19792 				 * the same payload buffer more than once, or
19793 				 * we're trying to add more buffers than
19794 				 * allowed (max_pld calculation is wrong).
19795 				 * None of the above cases should happen, and
19796 				 * we panic because either there's horrible
19797 				 * heap corruption, and/or programming mistake.
19798 				 */
19799 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19800 				if (pbuf_idx < 0) {
19801 					cmn_err(CE_PANIC, "tcp_multisend: "
19802 					    "payload buffer logic error "
19803 					    "detected for tcp %p mmd %p "
19804 					    "pbuf %p (%d)\n",
19805 					    (void *)tcp, (void *)mmd,
19806 					    (void *)md_pbuf, pbuf_idx);
19807 				}
19808 
19809 				ASSERT(max_pld > 0);
19810 				--max_pld;
19811 				add_buffer = B_FALSE;
19812 			}
19813 
19814 			ASSERT(md_mp_head != NULL);
19815 			ASSERT(md_pbuf != NULL);
19816 			ASSERT(md_pbuf_nxt == NULL);
19817 			ASSERT(pbuf_idx != -1);
19818 			ASSERT(pbuf_idx_nxt == -1);
19819 			ASSERT(*usable > 0);
19820 
19821 			/*
19822 			 * We spillover to the next payload buffer only
19823 			 * if all of the following is true:
19824 			 *
19825 			 *   1. There is not enough data on the current
19826 			 *	payload buffer to make up `len',
19827 			 *   2. We are allowed to send `len',
19828 			 *   3. The next payload buffer length is large
19829 			 *	enough to accomodate `spill'.
19830 			 */
19831 			if ((spill = len - *tail_unsent) > 0 &&
19832 			    *usable >= len &&
19833 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19834 			    max_pld > 0) {
19835 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19836 				if (md_pbuf_nxt == NULL) {
19837 					TCP_STAT(tcps, tcp_mdt_allocfail);
19838 					goto legacy_send; /* out_of_mem */
19839 				}
19840 
19841 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19842 				    zc_cap != NULL) {
19843 					if (!ip_md_zcopy_attr(mmd, NULL,
19844 					    zc_cap->ill_zerocopy_flags)) {
19845 						freeb(md_pbuf_nxt);
19846 						TCP_STAT(tcps,
19847 						    tcp_mdt_allocfail);
19848 						/* out_of_mem */
19849 						goto legacy_send;
19850 					}
19851 					zcopy = B_TRUE;
19852 				}
19853 
19854 				/*
19855 				 * See comments above on the first call to
19856 				 * mmd_addpldbuf for explanation on the panic.
19857 				 */
19858 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19859 				if (pbuf_idx_nxt < 0) {
19860 					panic("tcp_multisend: "
19861 					    "next payload buffer logic error "
19862 					    "detected for tcp %p mmd %p "
19863 					    "pbuf %p (%d)\n",
19864 					    (void *)tcp, (void *)mmd,
19865 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19866 				}
19867 
19868 				ASSERT(max_pld > 0);
19869 				--max_pld;
19870 			} else if (spill > 0) {
19871 				/*
19872 				 * If there's a spillover, but the following
19873 				 * xmit_tail couldn't give us enough octets
19874 				 * to reach "len", then stop the current
19875 				 * Multidata creation and let the legacy
19876 				 * tcp_send() path take over.  We don't want
19877 				 * to send the tiny segment as part of this
19878 				 * Multidata for performance reasons; instead,
19879 				 * we let the legacy path deal with grouping
19880 				 * it with the subsequent small mblks.
19881 				 */
19882 				if (*usable >= len &&
19883 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19884 					max_pld = 0;
19885 					break;	/* done */
19886 				}
19887 
19888 				/*
19889 				 * We can't spillover, and we are near
19890 				 * the end of the current payload buffer,
19891 				 * so send what's left.
19892 				 */
19893 				ASSERT(*tail_unsent > 0);
19894 				len = *tail_unsent;
19895 			}
19896 
19897 			/* tail_unsent is negated if there is a spillover */
19898 			*tail_unsent -= len;
19899 			*usable -= len;
19900 			ASSERT(*usable >= 0);
19901 
19902 			if (*usable < mss)
19903 				seg_len = *usable;
19904 			/*
19905 			 * Sender SWS avoidance; see comments in tcp_send();
19906 			 * everything else is the same, except that we only
19907 			 * do this here if there is no more data to be sent
19908 			 * following the current xmit_tail.  We don't check
19909 			 * for 1-byte urgent data because we shouldn't get
19910 			 * here if TCP_URG_VALID is set.
19911 			 */
19912 			if (*usable > 0 && *usable < mss &&
19913 			    ((md_pbuf_nxt == NULL &&
19914 			    (*xmit_tail)->b_cont == NULL) ||
19915 			    (md_pbuf_nxt != NULL &&
19916 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19917 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19918 			    (tcp->tcp_unsent -
19919 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19920 			    !tcp->tcp_zero_win_probe) {
19921 				if ((*snxt + len) == tcp->tcp_snxt &&
19922 				    (*snxt + len) == tcp->tcp_suna) {
19923 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19924 				}
19925 				done = B_TRUE;
19926 			}
19927 
19928 			/*
19929 			 * Prime pump for IP's checksumming on our behalf;
19930 			 * include the adjustment for a source route if any.
19931 			 * Do this only for software/partial hardware checksum
19932 			 * offload, as this field gets zeroed out later for
19933 			 * the full hardware checksum offload case.
19934 			 */
19935 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19936 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19937 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19938 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19939 			}
19940 
19941 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19942 			*snxt += len;
19943 
19944 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19945 			/*
19946 			 * We set the PUSH bit only if TCP has no more buffered
19947 			 * data to be transmitted (or if sender SWS avoidance
19948 			 * takes place), as opposed to setting it for every
19949 			 * last packet in the burst.
19950 			 */
19951 			if (done ||
19952 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19953 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19954 
19955 			/*
19956 			 * Set FIN bit if this is our last segment; snxt
19957 			 * already includes its length, and it will not
19958 			 * be adjusted after this point.
19959 			 */
19960 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19961 			    *snxt == tcp->tcp_fss) {
19962 				if (!tcp->tcp_fin_acked) {
19963 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19964 					BUMP_MIB(&tcps->tcps_mib,
19965 					    tcpOutControl);
19966 				}
19967 				if (!tcp->tcp_fin_sent) {
19968 					tcp->tcp_fin_sent = B_TRUE;
19969 					/*
19970 					 * tcp state must be ESTABLISHED
19971 					 * in order for us to get here in
19972 					 * the first place.
19973 					 */
19974 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19975 
19976 					/*
19977 					 * Upon returning from this routine,
19978 					 * tcp_wput_data() will set tcp_snxt
19979 					 * to be equal to snxt + tcp_fin_sent.
19980 					 * This is essentially the same as
19981 					 * setting it to tcp_fss + 1.
19982 					 */
19983 				}
19984 			}
19985 
19986 			tcp->tcp_last_sent_len = (ushort_t)len;
19987 
19988 			len += tcp_hdr_len;
19989 			if (tcp->tcp_ipversion == IPV4_VERSION)
19990 				tcp->tcp_ipha->ipha_length = htons(len);
19991 			else
19992 				tcp->tcp_ip6h->ip6_plen = htons(len -
19993 				    ((char *)&tcp->tcp_ip6h[1] -
19994 				    tcp->tcp_iphc));
19995 
19996 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19997 
19998 			/* setup header fragment */
19999 			PDESC_HDR_ADD(pkt_info,
20000 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20001 			    tcp->tcp_mdt_hdr_head,		/* head room */
20002 			    tcp_hdr_len,			/* len */
20003 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20004 
20005 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20006 			    hdr_frag_sz);
20007 			ASSERT(MBLKIN(md_hbuf,
20008 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20009 			    PDESC_HDRSIZE(pkt_info)));
20010 
20011 			/* setup first payload fragment */
20012 			PDESC_PLD_INIT(pkt_info);
20013 			PDESC_PLD_SPAN_ADD(pkt_info,
20014 			    pbuf_idx,				/* index */
20015 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20016 			    tcp->tcp_last_sent_len);		/* len */
20017 
20018 			/* create a split-packet in case of a spillover */
20019 			if (md_pbuf_nxt != NULL) {
20020 				ASSERT(spill > 0);
20021 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20022 				ASSERT(!add_buffer);
20023 
20024 				md_pbuf = md_pbuf_nxt;
20025 				md_pbuf_nxt = NULL;
20026 				pbuf_idx = pbuf_idx_nxt;
20027 				pbuf_idx_nxt = -1;
20028 				cur_pld_off = spill;
20029 
20030 				/* trim out first payload fragment */
20031 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20032 
20033 				/* setup second payload fragment */
20034 				PDESC_PLD_SPAN_ADD(pkt_info,
20035 				    pbuf_idx,			/* index */
20036 				    md_pbuf->b_rptr,		/* start */
20037 				    spill);			/* len */
20038 
20039 				if ((*xmit_tail)->b_next == NULL) {
20040 					/*
20041 					 * Store the lbolt used for RTT
20042 					 * estimation. We can only record one
20043 					 * timestamp per mblk so we do it when
20044 					 * we reach the end of the payload
20045 					 * buffer.  Also we only take a new
20046 					 * timestamp sample when the previous
20047 					 * timed data from the same mblk has
20048 					 * been ack'ed.
20049 					 */
20050 					(*xmit_tail)->b_prev = local_time;
20051 					(*xmit_tail)->b_next =
20052 					    (mblk_t *)(uintptr_t)first_snxt;
20053 				}
20054 
20055 				first_snxt = *snxt - spill;
20056 
20057 				/*
20058 				 * Advance xmit_tail; usable could be 0 by
20059 				 * the time we got here, but we made sure
20060 				 * above that we would only spillover to
20061 				 * the next data block if usable includes
20062 				 * the spilled-over amount prior to the
20063 				 * subtraction.  Therefore, we are sure
20064 				 * that xmit_tail->b_cont can't be NULL.
20065 				 */
20066 				ASSERT((*xmit_tail)->b_cont != NULL);
20067 				*xmit_tail = (*xmit_tail)->b_cont;
20068 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20069 				    (uintptr_t)INT_MAX);
20070 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20071 			} else {
20072 				cur_pld_off += tcp->tcp_last_sent_len;
20073 			}
20074 
20075 			/*
20076 			 * Fill in the header using the template header, and
20077 			 * add options such as time-stamp, ECN and/or SACK,
20078 			 * as needed.
20079 			 */
20080 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20081 			    (clock_t)local_time, num_sack_blk);
20082 
20083 			/* take care of some IP header businesses */
20084 			if (af == AF_INET) {
20085 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20086 
20087 				ASSERT(OK_32PTR((uchar_t *)ipha));
20088 				ASSERT(PDESC_HDRL(pkt_info) >=
20089 				    IP_SIMPLE_HDR_LENGTH);
20090 				ASSERT(ipha->ipha_version_and_hdr_length ==
20091 				    IP_SIMPLE_HDR_VERSION);
20092 
20093 				/*
20094 				 * Assign ident value for current packet; see
20095 				 * related comments in ip_wput_ire() about the
20096 				 * contract private interface with clustering
20097 				 * group.
20098 				 */
20099 				clusterwide = B_FALSE;
20100 				if (cl_inet_ipident != NULL) {
20101 					ASSERT(cl_inet_isclusterwide != NULL);
20102 					if ((*cl_inet_isclusterwide)(stack_id,
20103 					    IPPROTO_IP, AF_INET,
20104 					    (uint8_t *)(uintptr_t)src, NULL)) {
20105 						ipha->ipha_ident =
20106 						    (*cl_inet_ipident)(stack_id,
20107 						    IPPROTO_IP, AF_INET,
20108 						    (uint8_t *)(uintptr_t)src,
20109 						    (uint8_t *)(uintptr_t)dst,
20110 						    NULL);
20111 						clusterwide = B_TRUE;
20112 					}
20113 				}
20114 
20115 				if (!clusterwide) {
20116 					ipha->ipha_ident = (uint16_t)
20117 					    atomic_add_32_nv(
20118 						&ire->ire_ident, 1);
20119 				}
20120 #ifndef _BIG_ENDIAN
20121 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20122 				    (ipha->ipha_ident >> 8);
20123 #endif
20124 			} else {
20125 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20126 
20127 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20128 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20129 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20130 				ASSERT(PDESC_HDRL(pkt_info) >=
20131 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20132 				    TCP_CHECKSUM_SIZE));
20133 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20134 
20135 				if (tcp->tcp_ip_forward_progress) {
20136 					rconfirm = B_TRUE;
20137 					tcp->tcp_ip_forward_progress = B_FALSE;
20138 				}
20139 			}
20140 
20141 			/* at least one payload span, and at most two */
20142 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20143 
20144 			/* add the packet descriptor to Multidata */
20145 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20146 			    KM_NOSLEEP)) == NULL) {
20147 				/*
20148 				 * Any failure other than ENOMEM indicates
20149 				 * that we have passed in invalid pkt_info
20150 				 * or parameters to mmd_addpdesc, which must
20151 				 * not happen.
20152 				 *
20153 				 * EINVAL is a result of failure on boundary
20154 				 * checks against the pkt_info contents.  It
20155 				 * should not happen, and we panic because
20156 				 * either there's horrible heap corruption,
20157 				 * and/or programming mistake.
20158 				 */
20159 				if (err != ENOMEM) {
20160 					cmn_err(CE_PANIC, "tcp_multisend: "
20161 					    "pdesc logic error detected for "
20162 					    "tcp %p mmd %p pinfo %p (%d)\n",
20163 					    (void *)tcp, (void *)mmd,
20164 					    (void *)pkt_info, err);
20165 				}
20166 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20167 				goto legacy_send; /* out_of_mem */
20168 			}
20169 			ASSERT(pkt != NULL);
20170 
20171 			/* calculate IP header and TCP checksums */
20172 			if (af == AF_INET) {
20173 				/* calculate pseudo-header checksum */
20174 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20175 				    (src >> 16) + (src & 0xFFFF);
20176 
20177 				/* offset for TCP header checksum */
20178 				up = IPH_TCPH_CHECKSUMP(ipha,
20179 				    IP_SIMPLE_HDR_LENGTH);
20180 			} else {
20181 				up = (uint16_t *)&ip6h->ip6_src;
20182 
20183 				/* calculate pseudo-header checksum */
20184 				cksum = up[0] + up[1] + up[2] + up[3] +
20185 				    up[4] + up[5] + up[6] + up[7] +
20186 				    up[8] + up[9] + up[10] + up[11] +
20187 				    up[12] + up[13] + up[14] + up[15];
20188 
20189 				/* Fold the initial sum */
20190 				cksum = (cksum & 0xffff) + (cksum >> 16);
20191 
20192 				up = (uint16_t *)(((uchar_t *)ip6h) +
20193 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20194 			}
20195 
20196 			if (hwcksum_flags & HCK_FULLCKSUM) {
20197 				/* clear checksum field for hardware */
20198 				*up = 0;
20199 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20200 				uint32_t sum;
20201 
20202 				/* pseudo-header checksumming */
20203 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20204 				sum = (sum & 0xFFFF) + (sum >> 16);
20205 				*up = (sum & 0xFFFF) + (sum >> 16);
20206 			} else {
20207 				/* software checksumming */
20208 				TCP_STAT(tcps, tcp_out_sw_cksum);
20209 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20210 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20211 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20212 				    cksum + IP_TCP_CSUM_COMP);
20213 				if (*up == 0)
20214 					*up = 0xFFFF;
20215 			}
20216 
20217 			/* IPv4 header checksum */
20218 			if (af == AF_INET) {
20219 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20220 					ipha->ipha_hdr_checksum = 0;
20221 				} else {
20222 					IP_HDR_CKSUM(ipha, cksum,
20223 					    ((uint32_t *)ipha)[0],
20224 					    ((uint16_t *)ipha)[4]);
20225 				}
20226 			}
20227 
20228 			if (af == AF_INET &&
20229 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20230 			    af == AF_INET6 &&
20231 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20232 				mblk_t	*mp, *mp1;
20233 				uchar_t	*hdr_rptr, *hdr_wptr;
20234 				uchar_t	*pld_rptr, *pld_wptr;
20235 
20236 				/*
20237 				 * We reconstruct a pseudo packet for the hooks
20238 				 * framework using mmd_transform_link().
20239 				 * If it is a split packet we pullup the
20240 				 * payload. FW_HOOKS expects a pkt comprising
20241 				 * of two mblks: a header and the payload.
20242 				 */
20243 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20244 					TCP_STAT(tcps, tcp_mdt_allocfail);
20245 					goto legacy_send;
20246 				}
20247 
20248 				if (pkt_info->pld_cnt > 1) {
20249 					/* split payload, more than one pld */
20250 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20251 					    NULL) {
20252 						freemsg(mp);
20253 						TCP_STAT(tcps,
20254 						    tcp_mdt_allocfail);
20255 						goto legacy_send;
20256 					}
20257 					freemsg(mp->b_cont);
20258 					mp->b_cont = mp1;
20259 				} else {
20260 					mp1 = mp->b_cont;
20261 				}
20262 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20263 
20264 				/*
20265 				 * Remember the message offsets. This is so we
20266 				 * can detect changes when we return from the
20267 				 * FW_HOOKS callbacks.
20268 				 */
20269 				hdr_rptr = mp->b_rptr;
20270 				hdr_wptr = mp->b_wptr;
20271 				pld_rptr = mp->b_cont->b_rptr;
20272 				pld_wptr = mp->b_cont->b_wptr;
20273 
20274 				if (af == AF_INET) {
20275 					DTRACE_PROBE4(
20276 					    ip4__physical__out__start,
20277 					    ill_t *, NULL,
20278 					    ill_t *, ill,
20279 					    ipha_t *, ipha,
20280 					    mblk_t *, mp);
20281 					FW_HOOKS(
20282 					    ipst->ips_ip4_physical_out_event,
20283 					    ipst->ips_ipv4firewall_physical_out,
20284 					    NULL, ill, ipha, mp, mp, 0, ipst);
20285 					DTRACE_PROBE1(
20286 					    ip4__physical__out__end,
20287 					    mblk_t *, mp);
20288 				} else {
20289 					DTRACE_PROBE4(
20290 					    ip6__physical__out_start,
20291 					    ill_t *, NULL,
20292 					    ill_t *, ill,
20293 					    ip6_t *, ip6h,
20294 					    mblk_t *, mp);
20295 					FW_HOOKS6(
20296 					    ipst->ips_ip6_physical_out_event,
20297 					    ipst->ips_ipv6firewall_physical_out,
20298 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20299 					DTRACE_PROBE1(
20300 					    ip6__physical__out__end,
20301 					    mblk_t *, mp);
20302 				}
20303 
20304 				if (mp == NULL ||
20305 				    (mp1 = mp->b_cont) == NULL ||
20306 				    mp->b_rptr != hdr_rptr ||
20307 				    mp->b_wptr != hdr_wptr ||
20308 				    mp1->b_rptr != pld_rptr ||
20309 				    mp1->b_wptr != pld_wptr ||
20310 				    mp1->b_cont != NULL) {
20311 					/*
20312 					 * We abandon multidata processing and
20313 					 * return to the normal path, either
20314 					 * when a packet is blocked, or when
20315 					 * the boundaries of header buffer or
20316 					 * payload buffer have been changed by
20317 					 * FW_HOOKS[6].
20318 					 */
20319 					if (mp != NULL)
20320 						freemsg(mp);
20321 					goto legacy_send;
20322 				}
20323 				/* Finished with the pseudo packet */
20324 				freemsg(mp);
20325 			}
20326 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
20327 			    ill, ipha, ip6h);
20328 			/* advance header offset */
20329 			cur_hdr_off += hdr_frag_sz;
20330 
20331 			obbytes += tcp->tcp_last_sent_len;
20332 			++obsegs;
20333 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20334 		    *tail_unsent > 0);
20335 
20336 		if ((*xmit_tail)->b_next == NULL) {
20337 			/*
20338 			 * Store the lbolt used for RTT estimation. We can only
20339 			 * record one timestamp per mblk so we do it when we
20340 			 * reach the end of the payload buffer. Also we only
20341 			 * take a new timestamp sample when the previous timed
20342 			 * data from the same mblk has been ack'ed.
20343 			 */
20344 			(*xmit_tail)->b_prev = local_time;
20345 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20346 		}
20347 
20348 		ASSERT(*tail_unsent >= 0);
20349 		if (*tail_unsent > 0) {
20350 			/*
20351 			 * We got here because we broke out of the above
20352 			 * loop due to of one of the following cases:
20353 			 *
20354 			 *   1. len < adjusted MSS (i.e. small),
20355 			 *   2. Sender SWS avoidance,
20356 			 *   3. max_pld is zero.
20357 			 *
20358 			 * We are done for this Multidata, so trim our
20359 			 * last payload buffer (if any) accordingly.
20360 			 */
20361 			if (md_pbuf != NULL)
20362 				md_pbuf->b_wptr -= *tail_unsent;
20363 		} else if (*usable > 0) {
20364 			*xmit_tail = (*xmit_tail)->b_cont;
20365 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20366 			    (uintptr_t)INT_MAX);
20367 			*tail_unsent = (int)MBLKL(*xmit_tail);
20368 			add_buffer = B_TRUE;
20369 		}
20370 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20371 	    (tcp_mdt_chain || max_pld > 0));
20372 
20373 	if (md_mp_head != NULL) {
20374 		/* send everything down */
20375 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20376 		    &rconfirm);
20377 	}
20378 
20379 #undef PREP_NEW_MULTIDATA
20380 #undef PREP_NEW_PBUF
20381 #undef IPVER
20382 
20383 	IRE_REFRELE(ire);
20384 	return (0);
20385 }
20386 
20387 /*
20388  * A wrapper function for sending one or more Multidata messages down to
20389  * the module below ip; this routine does not release the reference of the
20390  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20391  */
20392 static void
20393 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20394     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20395 {
20396 	uint64_t delta;
20397 	nce_t *nce;
20398 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20399 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20400 
20401 	ASSERT(ire != NULL && ill != NULL);
20402 	ASSERT(ire->ire_stq != NULL);
20403 	ASSERT(md_mp_head != NULL);
20404 	ASSERT(rconfirm != NULL);
20405 
20406 	/* adjust MIBs and IRE timestamp */
20407 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
20408 	tcp->tcp_obsegs += obsegs;
20409 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20410 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20411 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20412 
20413 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20414 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20415 	} else {
20416 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20417 	}
20418 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20419 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20420 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20421 
20422 	ire->ire_ob_pkt_count += obsegs;
20423 	if (ire->ire_ipif != NULL)
20424 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20425 	ire->ire_last_used_time = lbolt;
20426 
20427 	if (ipst->ips_ipobs_enabled) {
20428 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
20429 		pdesc_t *dl_pkt;
20430 		pdescinfo_t pinfo;
20431 		mblk_t *nmp;
20432 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
20433 
20434 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
20435 		    (dl_pkt != NULL);
20436 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
20437 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
20438 				continue;
20439 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
20440 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
20441 			freemsg(nmp);
20442 		}
20443 	}
20444 
20445 	/* send it down */
20446 	putnext(ire->ire_stq, md_mp_head);
20447 
20448 	/* we're done for TCP/IPv4 */
20449 	if (tcp->tcp_ipversion == IPV4_VERSION)
20450 		return;
20451 
20452 	nce = ire->ire_nce;
20453 
20454 	ASSERT(nce != NULL);
20455 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20456 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20457 
20458 	/* reachability confirmation? */
20459 	if (*rconfirm) {
20460 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20461 		if (nce->nce_state != ND_REACHABLE) {
20462 			mutex_enter(&nce->nce_lock);
20463 			nce->nce_state = ND_REACHABLE;
20464 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20465 			mutex_exit(&nce->nce_lock);
20466 			(void) untimeout(nce->nce_timeout_id);
20467 			if (ip_debug > 2) {
20468 				/* ip1dbg */
20469 				pr_addr_dbg("tcp_multisend_data: state "
20470 				    "for %s changed to REACHABLE\n",
20471 				    AF_INET6, &ire->ire_addr_v6);
20472 			}
20473 		}
20474 		/* reset transport reachability confirmation */
20475 		*rconfirm = B_FALSE;
20476 	}
20477 
20478 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20479 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20480 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20481 
20482 	if (delta > (uint64_t)ill->ill_reachable_time) {
20483 		mutex_enter(&nce->nce_lock);
20484 		switch (nce->nce_state) {
20485 		case ND_REACHABLE:
20486 		case ND_STALE:
20487 			/*
20488 			 * ND_REACHABLE is identical to ND_STALE in this
20489 			 * specific case. If reachable time has expired for
20490 			 * this neighbor (delta is greater than reachable
20491 			 * time), conceptually, the neighbor cache is no
20492 			 * longer in REACHABLE state, but already in STALE
20493 			 * state.  So the correct transition here is to
20494 			 * ND_DELAY.
20495 			 */
20496 			nce->nce_state = ND_DELAY;
20497 			mutex_exit(&nce->nce_lock);
20498 			NDP_RESTART_TIMER(nce,
20499 			    ipst->ips_delay_first_probe_time);
20500 			if (ip_debug > 3) {
20501 				/* ip2dbg */
20502 				pr_addr_dbg("tcp_multisend_data: state "
20503 				    "for %s changed to DELAY\n",
20504 				    AF_INET6, &ire->ire_addr_v6);
20505 			}
20506 			break;
20507 		case ND_DELAY:
20508 		case ND_PROBE:
20509 			mutex_exit(&nce->nce_lock);
20510 			/* Timers have already started */
20511 			break;
20512 		case ND_UNREACHABLE:
20513 			/*
20514 			 * ndp timer has detected that this nce is
20515 			 * unreachable and initiated deleting this nce
20516 			 * and all its associated IREs. This is a race
20517 			 * where we found the ire before it was deleted
20518 			 * and have just sent out a packet using this
20519 			 * unreachable nce.
20520 			 */
20521 			mutex_exit(&nce->nce_lock);
20522 			break;
20523 		default:
20524 			ASSERT(0);
20525 		}
20526 	}
20527 }
20528 
20529 /*
20530  * Derived from tcp_send_data().
20531  */
20532 static void
20533 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20534     int num_lso_seg)
20535 {
20536 	ipha_t		*ipha;
20537 	mblk_t		*ire_fp_mp;
20538 	uint_t		ire_fp_mp_len;
20539 	uint32_t	hcksum_txflags = 0;
20540 	ipaddr_t	src;
20541 	ipaddr_t	dst;
20542 	uint32_t	cksum;
20543 	uint16_t	*up;
20544 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20545 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20546 
20547 	ASSERT(DB_TYPE(mp) == M_DATA);
20548 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20549 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20550 	ASSERT(tcp->tcp_connp != NULL);
20551 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20552 
20553 	ipha = (ipha_t *)mp->b_rptr;
20554 	src = ipha->ipha_src;
20555 	dst = ipha->ipha_dst;
20556 
20557 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
20558 
20559 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20560 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20561 	    num_lso_seg);
20562 #ifndef _BIG_ENDIAN
20563 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20564 #endif
20565 	if (tcp->tcp_snd_zcopy_aware) {
20566 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20567 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20568 			mp = tcp_zcopy_disable(tcp, mp);
20569 	}
20570 
20571 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20572 		ASSERT(ill->ill_hcksum_capab != NULL);
20573 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20574 	}
20575 
20576 	/*
20577 	 * Since the TCP checksum should be recalculated by h/w, we can just
20578 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20579 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20580 	 * The partial pseudo-header excludes TCP length, that was calculated
20581 	 * in tcp_send(), so to zero *up before further processing.
20582 	 */
20583 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20584 
20585 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20586 	*up = 0;
20587 
20588 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20589 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20590 
20591 	/*
20592 	 * Append LSO flags and mss to the mp.
20593 	 */
20594 	lso_info_set(mp, mss, HW_LSO);
20595 
20596 	ipha->ipha_fragment_offset_and_flags |=
20597 	    (uint32_t)htons(ire->ire_frag_flag);
20598 
20599 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20600 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20601 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20602 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20603 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20604 
20605 	UPDATE_OB_PKT_COUNT(ire);
20606 	ire->ire_last_used_time = lbolt;
20607 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20608 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20609 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20610 	    ntohs(ipha->ipha_length));
20611 
20612 	DTRACE_PROBE4(ip4__physical__out__start,
20613 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
20614 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
20615 	    ipst->ips_ipv4firewall_physical_out, NULL,
20616 	    ill, ipha, mp, mp, 0, ipst);
20617 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20618 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
20619 
20620 	if (mp != NULL) {
20621 		if (ipst->ips_ipobs_enabled) {
20622 			zoneid_t szone;
20623 
20624 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
20625 			    ipst, ALL_ZONES);
20626 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
20627 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
20628 		}
20629 
20630 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
20631 	}
20632 }
20633 
20634 /*
20635  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20636  * scheme, and returns one of the following:
20637  *
20638  * -1 = failed allocation.
20639  *  0 = success; burst count reached, or usable send window is too small,
20640  *      and that we'd rather wait until later before sending again.
20641  *  1 = success; we are called from tcp_multisend(), and both usable send
20642  *      window and tail_unsent are greater than the MDT threshold, and thus
20643  *      Multidata Transmit should be used instead.
20644  */
20645 static int
20646 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20647     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20648     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20649     const int mdt_thres)
20650 {
20651 	int num_burst_seg = tcp->tcp_snd_burst;
20652 	ire_t		*ire = NULL;
20653 	ill_t		*ill = NULL;
20654 	mblk_t		*ire_fp_mp = NULL;
20655 	uint_t		ire_fp_mp_len = 0;
20656 	int		num_lso_seg = 1;
20657 	uint_t		lso_usable;
20658 	boolean_t	do_lso_send = B_FALSE;
20659 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20660 
20661 	/*
20662 	 * Check LSO capability before any further work. And the similar check
20663 	 * need to be done in for(;;) loop.
20664 	 * LSO will be deployed when therer is more than one mss of available
20665 	 * data and a burst transmission is allowed.
20666 	 */
20667 	if (tcp->tcp_lso &&
20668 	    (tcp->tcp_valid_bits == 0 ||
20669 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20670 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20671 		/*
20672 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20673 		 * Double check LSO usability before going further, since the
20674 		 * underlying interface could have been changed. In case of any
20675 		 * change of LSO capability, set tcp_ire_ill_check_done to
20676 		 * B_FALSE to force to check the ILL with the next send.
20677 		 */
20678 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
20679 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
20680 			/*
20681 			 * Enable LSO with this transmission.
20682 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
20683 			 * IRE_REFRELE(ire) should be called before return.
20684 			 */
20685 			do_lso_send = B_TRUE;
20686 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
20687 			ire_fp_mp_len = MBLKL(ire_fp_mp);
20688 			/* Round up to multiple of 4 */
20689 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
20690 		} else {
20691 			tcp->tcp_lso = B_FALSE;
20692 			tcp->tcp_ire_ill_check_done = B_FALSE;
20693 			do_lso_send = B_FALSE;
20694 			ill = NULL;
20695 		}
20696 	}
20697 
20698 	for (;;) {
20699 		struct datab	*db;
20700 		tcph_t		*tcph;
20701 		uint32_t	sum;
20702 		mblk_t		*mp, *mp1;
20703 		uchar_t		*rptr;
20704 		int		len;
20705 
20706 		/*
20707 		 * If we're called by tcp_multisend(), and the amount of
20708 		 * sendable data as well as the size of current xmit_tail
20709 		 * is beyond the MDT threshold, return to the caller and
20710 		 * let the large data transmit be done using MDT.
20711 		 */
20712 		if (*usable > 0 && *usable > mdt_thres &&
20713 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20714 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20715 			ASSERT(tcp->tcp_mdt);
20716 			return (1);	/* success; do large send */
20717 		}
20718 
20719 		if (num_burst_seg == 0)
20720 			break;		/* success; burst count reached */
20721 
20722 		/*
20723 		 * Calculate the maximum payload length we can send in *one*
20724 		 * time.
20725 		 */
20726 		if (do_lso_send) {
20727 			/*
20728 			 * Check whether need to do LSO any more.
20729 			 */
20730 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20731 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
20732 				lso_usable = MIN(lso_usable,
20733 				    num_burst_seg * mss);
20734 
20735 				num_lso_seg = lso_usable / mss;
20736 				if (lso_usable % mss) {
20737 					num_lso_seg++;
20738 					tcp->tcp_last_sent_len = (ushort_t)
20739 					    (lso_usable % mss);
20740 				} else {
20741 					tcp->tcp_last_sent_len = (ushort_t)mss;
20742 				}
20743 			} else {
20744 				do_lso_send = B_FALSE;
20745 				num_lso_seg = 1;
20746 				lso_usable = mss;
20747 			}
20748 		}
20749 
20750 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
20751 
20752 		/*
20753 		 * Adjust num_burst_seg here.
20754 		 */
20755 		num_burst_seg -= num_lso_seg;
20756 
20757 		len = mss;
20758 		if (len > *usable) {
20759 			ASSERT(do_lso_send == B_FALSE);
20760 
20761 			len = *usable;
20762 			if (len <= 0) {
20763 				/* Terminate the loop */
20764 				break;	/* success; too small */
20765 			}
20766 			/*
20767 			 * Sender silly-window avoidance.
20768 			 * Ignore this if we are going to send a
20769 			 * zero window probe out.
20770 			 *
20771 			 * TODO: force data into microscopic window?
20772 			 *	==> (!pushed || (unsent > usable))
20773 			 */
20774 			if (len < (tcp->tcp_max_swnd >> 1) &&
20775 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20776 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20777 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20778 				/*
20779 				 * If the retransmit timer is not running
20780 				 * we start it so that we will retransmit
20781 				 * in the case when the the receiver has
20782 				 * decremented the window.
20783 				 */
20784 				if (*snxt == tcp->tcp_snxt &&
20785 				    *snxt == tcp->tcp_suna) {
20786 					/*
20787 					 * We are not supposed to send
20788 					 * anything.  So let's wait a little
20789 					 * bit longer before breaking SWS
20790 					 * avoidance.
20791 					 *
20792 					 * What should the value be?
20793 					 * Suggestion: MAX(init rexmit time,
20794 					 * tcp->tcp_rto)
20795 					 */
20796 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20797 				}
20798 				break;	/* success; too small */
20799 			}
20800 		}
20801 
20802 		tcph = tcp->tcp_tcph;
20803 
20804 		/*
20805 		 * The reason to adjust len here is that we need to set flags
20806 		 * and calculate checksum.
20807 		 */
20808 		if (do_lso_send)
20809 			len = lso_usable;
20810 
20811 		*usable -= len; /* Approximate - can be adjusted later */
20812 		if (*usable > 0)
20813 			tcph->th_flags[0] = TH_ACK;
20814 		else
20815 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20816 
20817 		/*
20818 		 * Prime pump for IP's checksumming on our behalf
20819 		 * Include the adjustment for a source route if any.
20820 		 */
20821 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20822 		sum = (sum >> 16) + (sum & 0xFFFF);
20823 		U16_TO_ABE16(sum, tcph->th_sum);
20824 
20825 		U32_TO_ABE32(*snxt, tcph->th_seq);
20826 
20827 		/*
20828 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20829 		 * set.  For the case when TCP_FSS_VALID is the only valid
20830 		 * bit (normal active close), branch off only when we think
20831 		 * that the FIN flag needs to be set.  Note for this case,
20832 		 * that (snxt + len) may not reflect the actual seg_len,
20833 		 * as len may be further reduced in tcp_xmit_mp().  If len
20834 		 * gets modified, we will end up here again.
20835 		 */
20836 		if (tcp->tcp_valid_bits != 0 &&
20837 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20838 		    ((*snxt + len) == tcp->tcp_fss))) {
20839 			uchar_t		*prev_rptr;
20840 			uint32_t	prev_snxt = tcp->tcp_snxt;
20841 
20842 			if (*tail_unsent == 0) {
20843 				ASSERT((*xmit_tail)->b_cont != NULL);
20844 				*xmit_tail = (*xmit_tail)->b_cont;
20845 				prev_rptr = (*xmit_tail)->b_rptr;
20846 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20847 				    (*xmit_tail)->b_rptr);
20848 			} else {
20849 				prev_rptr = (*xmit_tail)->b_rptr;
20850 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20851 				    *tail_unsent;
20852 			}
20853 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20854 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20855 			/* Restore tcp_snxt so we get amount sent right. */
20856 			tcp->tcp_snxt = prev_snxt;
20857 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20858 				/*
20859 				 * If the previous timestamp is still in use,
20860 				 * don't stomp on it.
20861 				 */
20862 				if ((*xmit_tail)->b_next == NULL) {
20863 					(*xmit_tail)->b_prev = local_time;
20864 					(*xmit_tail)->b_next =
20865 					    (mblk_t *)(uintptr_t)(*snxt);
20866 				}
20867 			} else
20868 				(*xmit_tail)->b_rptr = prev_rptr;
20869 
20870 			if (mp == NULL) {
20871 				if (ire != NULL)
20872 					IRE_REFRELE(ire);
20873 				return (-1);
20874 			}
20875 			mp1 = mp->b_cont;
20876 
20877 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
20878 				tcp->tcp_last_sent_len = (ushort_t)len;
20879 			while (mp1->b_cont) {
20880 				*xmit_tail = (*xmit_tail)->b_cont;
20881 				(*xmit_tail)->b_prev = local_time;
20882 				(*xmit_tail)->b_next =
20883 				    (mblk_t *)(uintptr_t)(*snxt);
20884 				mp1 = mp1->b_cont;
20885 			}
20886 			*snxt += len;
20887 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20888 			BUMP_LOCAL(tcp->tcp_obsegs);
20889 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20890 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20891 			tcp_send_data(tcp, q, mp);
20892 			continue;
20893 		}
20894 
20895 		*snxt += len;	/* Adjust later if we don't send all of len */
20896 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20897 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20898 
20899 		if (*tail_unsent) {
20900 			/* Are the bytes above us in flight? */
20901 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20902 			if (rptr != (*xmit_tail)->b_rptr) {
20903 				*tail_unsent -= len;
20904 				if (len <= mss) /* LSO is unusable */
20905 					tcp->tcp_last_sent_len = (ushort_t)len;
20906 				len += tcp_hdr_len;
20907 				if (tcp->tcp_ipversion == IPV4_VERSION)
20908 					tcp->tcp_ipha->ipha_length = htons(len);
20909 				else
20910 					tcp->tcp_ip6h->ip6_plen =
20911 					    htons(len -
20912 					    ((char *)&tcp->tcp_ip6h[1] -
20913 					    tcp->tcp_iphc));
20914 				mp = dupb(*xmit_tail);
20915 				if (mp == NULL) {
20916 					if (ire != NULL)
20917 						IRE_REFRELE(ire);
20918 					return (-1);	/* out_of_mem */
20919 				}
20920 				mp->b_rptr = rptr;
20921 				/*
20922 				 * If the old timestamp is no longer in use,
20923 				 * sample a new timestamp now.
20924 				 */
20925 				if ((*xmit_tail)->b_next == NULL) {
20926 					(*xmit_tail)->b_prev = local_time;
20927 					(*xmit_tail)->b_next =
20928 					    (mblk_t *)(uintptr_t)(*snxt-len);
20929 				}
20930 				goto must_alloc;
20931 			}
20932 		} else {
20933 			*xmit_tail = (*xmit_tail)->b_cont;
20934 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20935 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20936 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20937 			    (*xmit_tail)->b_rptr);
20938 		}
20939 
20940 		(*xmit_tail)->b_prev = local_time;
20941 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20942 
20943 		*tail_unsent -= len;
20944 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
20945 			tcp->tcp_last_sent_len = (ushort_t)len;
20946 
20947 		len += tcp_hdr_len;
20948 		if (tcp->tcp_ipversion == IPV4_VERSION)
20949 			tcp->tcp_ipha->ipha_length = htons(len);
20950 		else
20951 			tcp->tcp_ip6h->ip6_plen = htons(len -
20952 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20953 
20954 		mp = dupb(*xmit_tail);
20955 		if (mp == NULL) {
20956 			if (ire != NULL)
20957 				IRE_REFRELE(ire);
20958 			return (-1);	/* out_of_mem */
20959 		}
20960 
20961 		len = tcp_hdr_len;
20962 		/*
20963 		 * There are four reasons to allocate a new hdr mblk:
20964 		 *  1) The bytes above us are in use by another packet
20965 		 *  2) We don't have good alignment
20966 		 *  3) The mblk is being shared
20967 		 *  4) We don't have enough room for a header
20968 		 */
20969 		rptr = mp->b_rptr - len;
20970 		if (!OK_32PTR(rptr) ||
20971 		    ((db = mp->b_datap), db->db_ref != 2) ||
20972 		    rptr < db->db_base + ire_fp_mp_len) {
20973 			/* NOTE: we assume allocb returns an OK_32PTR */
20974 
20975 		must_alloc:;
20976 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20977 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
20978 			if (mp1 == NULL) {
20979 				freemsg(mp);
20980 				if (ire != NULL)
20981 					IRE_REFRELE(ire);
20982 				return (-1);	/* out_of_mem */
20983 			}
20984 			mp1->b_cont = mp;
20985 			mp = mp1;
20986 			/* Leave room for Link Level header */
20987 			len = tcp_hdr_len;
20988 			rptr =
20989 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
20990 			mp->b_wptr = &rptr[len];
20991 		}
20992 
20993 		/*
20994 		 * Fill in the header using the template header, and add
20995 		 * options such as time-stamp, ECN and/or SACK, as needed.
20996 		 */
20997 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20998 
20999 		mp->b_rptr = rptr;
21000 
21001 		if (*tail_unsent) {
21002 			int spill = *tail_unsent;
21003 
21004 			mp1 = mp->b_cont;
21005 			if (mp1 == NULL)
21006 				mp1 = mp;
21007 
21008 			/*
21009 			 * If we're a little short, tack on more mblks until
21010 			 * there is no more spillover.
21011 			 */
21012 			while (spill < 0) {
21013 				mblk_t *nmp;
21014 				int nmpsz;
21015 
21016 				nmp = (*xmit_tail)->b_cont;
21017 				nmpsz = MBLKL(nmp);
21018 
21019 				/*
21020 				 * Excess data in mblk; can we split it?
21021 				 * If MDT is enabled for the connection,
21022 				 * keep on splitting as this is a transient
21023 				 * send path.
21024 				 */
21025 				if (!do_lso_send && !tcp->tcp_mdt &&
21026 				    (spill + nmpsz > 0)) {
21027 					/*
21028 					 * Don't split if stream head was
21029 					 * told to break up larger writes
21030 					 * into smaller ones.
21031 					 */
21032 					if (tcp->tcp_maxpsz > 0)
21033 						break;
21034 
21035 					/*
21036 					 * Next mblk is less than SMSS/2
21037 					 * rounded up to nearest 64-byte;
21038 					 * let it get sent as part of the
21039 					 * next segment.
21040 					 */
21041 					if (tcp->tcp_localnet &&
21042 					    !tcp->tcp_cork &&
21043 					    (nmpsz < roundup((mss >> 1), 64)))
21044 						break;
21045 				}
21046 
21047 				*xmit_tail = nmp;
21048 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21049 				/* Stash for rtt use later */
21050 				(*xmit_tail)->b_prev = local_time;
21051 				(*xmit_tail)->b_next =
21052 				    (mblk_t *)(uintptr_t)(*snxt - len);
21053 				mp1->b_cont = dupb(*xmit_tail);
21054 				mp1 = mp1->b_cont;
21055 
21056 				spill += nmpsz;
21057 				if (mp1 == NULL) {
21058 					*tail_unsent = spill;
21059 					freemsg(mp);
21060 					if (ire != NULL)
21061 						IRE_REFRELE(ire);
21062 					return (-1);	/* out_of_mem */
21063 				}
21064 			}
21065 
21066 			/* Trim back any surplus on the last mblk */
21067 			if (spill >= 0) {
21068 				mp1->b_wptr -= spill;
21069 				*tail_unsent = spill;
21070 			} else {
21071 				/*
21072 				 * We did not send everything we could in
21073 				 * order to remain within the b_cont limit.
21074 				 */
21075 				*usable -= spill;
21076 				*snxt += spill;
21077 				tcp->tcp_last_sent_len += spill;
21078 				UPDATE_MIB(&tcps->tcps_mib,
21079 				    tcpOutDataBytes, spill);
21080 				/*
21081 				 * Adjust the checksum
21082 				 */
21083 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21084 				sum += spill;
21085 				sum = (sum >> 16) + (sum & 0xFFFF);
21086 				U16_TO_ABE16(sum, tcph->th_sum);
21087 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21088 					sum = ntohs(
21089 					    ((ipha_t *)rptr)->ipha_length) +
21090 					    spill;
21091 					((ipha_t *)rptr)->ipha_length =
21092 					    htons(sum);
21093 				} else {
21094 					sum = ntohs(
21095 					    ((ip6_t *)rptr)->ip6_plen) +
21096 					    spill;
21097 					((ip6_t *)rptr)->ip6_plen =
21098 					    htons(sum);
21099 				}
21100 				*tail_unsent = 0;
21101 			}
21102 		}
21103 		if (tcp->tcp_ip_forward_progress) {
21104 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21105 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21106 			tcp->tcp_ip_forward_progress = B_FALSE;
21107 		}
21108 
21109 		if (do_lso_send) {
21110 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21111 			    num_lso_seg);
21112 			tcp->tcp_obsegs += num_lso_seg;
21113 
21114 			TCP_STAT(tcps, tcp_lso_times);
21115 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21116 		} else {
21117 			tcp_send_data(tcp, q, mp);
21118 			BUMP_LOCAL(tcp->tcp_obsegs);
21119 		}
21120 	}
21121 
21122 	if (ire != NULL)
21123 		IRE_REFRELE(ire);
21124 	return (0);
21125 }
21126 
21127 /* Unlink and return any mblk that looks like it contains a MDT info */
21128 static mblk_t *
21129 tcp_mdt_info_mp(mblk_t *mp)
21130 {
21131 	mblk_t	*prev_mp;
21132 
21133 	for (;;) {
21134 		prev_mp = mp;
21135 		/* no more to process? */
21136 		if ((mp = mp->b_cont) == NULL)
21137 			break;
21138 
21139 		switch (DB_TYPE(mp)) {
21140 		case M_CTL:
21141 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21142 				continue;
21143 			ASSERT(prev_mp != NULL);
21144 			prev_mp->b_cont = mp->b_cont;
21145 			mp->b_cont = NULL;
21146 			return (mp);
21147 		default:
21148 			break;
21149 		}
21150 	}
21151 	return (mp);
21152 }
21153 
21154 /* MDT info update routine, called when IP notifies us about MDT */
21155 static void
21156 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21157 {
21158 	boolean_t prev_state;
21159 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21160 
21161 	/*
21162 	 * IP is telling us to abort MDT on this connection?  We know
21163 	 * this because the capability is only turned off when IP
21164 	 * encounters some pathological cases, e.g. link-layer change
21165 	 * where the new driver doesn't support MDT, or in situation
21166 	 * where MDT usage on the link-layer has been switched off.
21167 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21168 	 * if the link-layer doesn't support MDT, and if it does, it
21169 	 * will indicate that the feature is to be turned on.
21170 	 */
21171 	prev_state = tcp->tcp_mdt;
21172 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21173 	if (!tcp->tcp_mdt && !first) {
21174 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21175 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21176 		    (void *)tcp->tcp_connp));
21177 	}
21178 
21179 	/*
21180 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21181 	 * so disable MDT otherwise.  The checks are done here
21182 	 * and in tcp_wput_data().
21183 	 */
21184 	if (tcp->tcp_mdt &&
21185 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21186 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21187 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21188 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21189 		tcp->tcp_mdt = B_FALSE;
21190 
21191 	if (tcp->tcp_mdt) {
21192 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21193 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21194 			    "version (%d), expected version is %d",
21195 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21196 			tcp->tcp_mdt = B_FALSE;
21197 			return;
21198 		}
21199 
21200 		/*
21201 		 * We need the driver to be able to handle at least three
21202 		 * spans per packet in order for tcp MDT to be utilized.
21203 		 * The first is for the header portion, while the rest are
21204 		 * needed to handle a packet that straddles across two
21205 		 * virtually non-contiguous buffers; a typical tcp packet
21206 		 * therefore consists of only two spans.  Note that we take
21207 		 * a zero as "don't care".
21208 		 */
21209 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21210 		    mdt_capab->ill_mdt_span_limit < 3) {
21211 			tcp->tcp_mdt = B_FALSE;
21212 			return;
21213 		}
21214 
21215 		/* a zero means driver wants default value */
21216 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21217 		    tcps->tcps_mdt_max_pbufs);
21218 		if (tcp->tcp_mdt_max_pld == 0)
21219 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21220 
21221 		/* ensure 32-bit alignment */
21222 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21223 		    mdt_capab->ill_mdt_hdr_head), 4);
21224 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21225 		    mdt_capab->ill_mdt_hdr_tail), 4);
21226 
21227 		if (!first && !prev_state) {
21228 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21229 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21230 			    (void *)tcp->tcp_connp));
21231 		}
21232 	}
21233 }
21234 
21235 /* Unlink and return any mblk that looks like it contains a LSO info */
21236 static mblk_t *
21237 tcp_lso_info_mp(mblk_t *mp)
21238 {
21239 	mblk_t	*prev_mp;
21240 
21241 	for (;;) {
21242 		prev_mp = mp;
21243 		/* no more to process? */
21244 		if ((mp = mp->b_cont) == NULL)
21245 			break;
21246 
21247 		switch (DB_TYPE(mp)) {
21248 		case M_CTL:
21249 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21250 				continue;
21251 			ASSERT(prev_mp != NULL);
21252 			prev_mp->b_cont = mp->b_cont;
21253 			mp->b_cont = NULL;
21254 			return (mp);
21255 		default:
21256 			break;
21257 		}
21258 	}
21259 
21260 	return (mp);
21261 }
21262 
21263 /* LSO info update routine, called when IP notifies us about LSO */
21264 static void
21265 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21266 {
21267 	tcp_stack_t *tcps = tcp->tcp_tcps;
21268 
21269 	/*
21270 	 * IP is telling us to abort LSO on this connection?  We know
21271 	 * this because the capability is only turned off when IP
21272 	 * encounters some pathological cases, e.g. link-layer change
21273 	 * where the new NIC/driver doesn't support LSO, or in situation
21274 	 * where LSO usage on the link-layer has been switched off.
21275 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21276 	 * if the link-layer doesn't support LSO, and if it does, it
21277 	 * will indicate that the feature is to be turned on.
21278 	 */
21279 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21280 	TCP_STAT(tcps, tcp_lso_enabled);
21281 
21282 	/*
21283 	 * We currently only support LSO on simple TCP/IPv4,
21284 	 * so disable LSO otherwise.  The checks are done here
21285 	 * and in tcp_wput_data().
21286 	 */
21287 	if (tcp->tcp_lso &&
21288 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21289 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21290 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21291 		tcp->tcp_lso = B_FALSE;
21292 		TCP_STAT(tcps, tcp_lso_disabled);
21293 	} else {
21294 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21295 		    lso_capab->ill_lso_max);
21296 	}
21297 }
21298 
21299 static void
21300 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21301 {
21302 	conn_t *connp = tcp->tcp_connp;
21303 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21304 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21305 
21306 	ASSERT(ire != NULL);
21307 
21308 	/*
21309 	 * We may be in the fastpath here, and although we essentially do
21310 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21311 	 * we try to keep things as brief as possible.  After all, these
21312 	 * are only best-effort checks, and we do more thorough ones prior
21313 	 * to calling tcp_send()/tcp_multisend().
21314 	 */
21315 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21316 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21317 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21318 	    !(ire->ire_flags & RTF_MULTIRT) &&
21319 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21320 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21321 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21322 			/* Cache the result */
21323 			connp->conn_lso_ok = B_TRUE;
21324 
21325 			ASSERT(ill->ill_lso_capab != NULL);
21326 			if (!ill->ill_lso_capab->ill_lso_on) {
21327 				ill->ill_lso_capab->ill_lso_on = 1;
21328 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21329 				    "LSO for interface %s\n", (void *)connp,
21330 				    ill->ill_name));
21331 			}
21332 			tcp_lso_update(tcp, ill->ill_lso_capab);
21333 		} else if (ipst->ips_ip_multidata_outbound &&
21334 		    ILL_MDT_CAPABLE(ill)) {
21335 			/* Cache the result */
21336 			connp->conn_mdt_ok = B_TRUE;
21337 
21338 			ASSERT(ill->ill_mdt_capab != NULL);
21339 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21340 				ill->ill_mdt_capab->ill_mdt_on = 1;
21341 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21342 				    "MDT for interface %s\n", (void *)connp,
21343 				    ill->ill_name));
21344 			}
21345 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21346 		}
21347 	}
21348 
21349 	/*
21350 	 * The goal is to reduce the number of generated tcp segments by
21351 	 * setting the maxpsz multiplier to 0; this will have an affect on
21352 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21353 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21354 	 * of outbound segments and incoming ACKs, thus allowing for better
21355 	 * network and system performance.  In contrast the legacy behavior
21356 	 * may result in sending less than SMSS size, because the last mblk
21357 	 * for some packets may have more data than needed to make up SMSS,
21358 	 * and the legacy code refused to "split" it.
21359 	 *
21360 	 * We apply the new behavior on following situations:
21361 	 *
21362 	 *   1) Loopback connections,
21363 	 *   2) Connections in which the remote peer is not on local subnet,
21364 	 *   3) Local subnet connections over the bge interface (see below).
21365 	 *
21366 	 * Ideally, we would like this behavior to apply for interfaces other
21367 	 * than bge.  However, doing so would negatively impact drivers which
21368 	 * perform dynamic mapping and unmapping of DMA resources, which are
21369 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21370 	 * packet will be generated by tcp).  The bge driver does not suffer
21371 	 * from this, as it copies the mblks into pre-mapped buffers, and
21372 	 * therefore does not require more I/O resources than before.
21373 	 *
21374 	 * Otherwise, this behavior is present on all network interfaces when
21375 	 * the destination endpoint is non-local, since reducing the number
21376 	 * of packets in general is good for the network.
21377 	 *
21378 	 * TODO We need to remove this hard-coded conditional for bge once
21379 	 *	a better "self-tuning" mechanism, or a way to comprehend
21380 	 *	the driver transmit strategy is devised.  Until the solution
21381 	 *	is found and well understood, we live with this hack.
21382 	 */
21383 	if (!tcp_static_maxpsz &&
21384 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21385 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21386 		/* override the default value */
21387 		tcp->tcp_maxpsz = 0;
21388 
21389 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21390 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21391 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21392 	}
21393 
21394 	/* set the stream head parameters accordingly */
21395 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21396 }
21397 
21398 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21399 static void
21400 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21401 {
21402 	uchar_t	fval = *mp->b_rptr;
21403 	mblk_t	*tail;
21404 	queue_t	*q = tcp->tcp_wq;
21405 
21406 	/* TODO: How should flush interact with urgent data? */
21407 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21408 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21409 		/*
21410 		 * Flush only data that has not yet been put on the wire.  If
21411 		 * we flush data that we have already transmitted, life, as we
21412 		 * know it, may come to an end.
21413 		 */
21414 		tail = tcp->tcp_xmit_tail;
21415 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21416 		tcp->tcp_xmit_tail_unsent = 0;
21417 		tcp->tcp_unsent = 0;
21418 		if (tail->b_wptr != tail->b_rptr)
21419 			tail = tail->b_cont;
21420 		if (tail) {
21421 			mblk_t **excess = &tcp->tcp_xmit_head;
21422 			for (;;) {
21423 				mblk_t *mp1 = *excess;
21424 				if (mp1 == tail)
21425 					break;
21426 				tcp->tcp_xmit_tail = mp1;
21427 				tcp->tcp_xmit_last = mp1;
21428 				excess = &mp1->b_cont;
21429 			}
21430 			*excess = NULL;
21431 			tcp_close_mpp(&tail);
21432 			if (tcp->tcp_snd_zcopy_aware)
21433 				tcp_zcopy_notify(tcp);
21434 		}
21435 		/*
21436 		 * We have no unsent data, so unsent must be less than
21437 		 * tcp_xmit_lowater, so re-enable flow.
21438 		 */
21439 		mutex_enter(&tcp->tcp_non_sq_lock);
21440 		if (tcp->tcp_flow_stopped) {
21441 			tcp_clrqfull(tcp);
21442 		}
21443 		mutex_exit(&tcp->tcp_non_sq_lock);
21444 	}
21445 	/*
21446 	 * TODO: you can't just flush these, you have to increase rwnd for one
21447 	 * thing.  For another, how should urgent data interact?
21448 	 */
21449 	if (fval & FLUSHR) {
21450 		*mp->b_rptr = fval & ~FLUSHW;
21451 		/* XXX */
21452 		qreply(q, mp);
21453 		return;
21454 	}
21455 	freemsg(mp);
21456 }
21457 
21458 /*
21459  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21460  * messages.
21461  */
21462 static void
21463 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21464 {
21465 	mblk_t	*mp1;
21466 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
21467 	STRUCT_HANDLE(strbuf, sb);
21468 	queue_t *q = tcp->tcp_wq;
21469 	int	error;
21470 	uint_t	addrlen;
21471 
21472 	/* Make sure it is one of ours. */
21473 	switch (iocp->ioc_cmd) {
21474 	case TI_GETMYNAME:
21475 	case TI_GETPEERNAME:
21476 		break;
21477 	default:
21478 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21479 		return;
21480 	}
21481 	switch (mi_copy_state(q, mp, &mp1)) {
21482 	case -1:
21483 		return;
21484 	case MI_COPY_CASE(MI_COPY_IN, 1):
21485 		break;
21486 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21487 		/* Copy out the strbuf. */
21488 		mi_copyout(q, mp);
21489 		return;
21490 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21491 		/* All done. */
21492 		mi_copy_done(q, mp, 0);
21493 		return;
21494 	default:
21495 		mi_copy_done(q, mp, EPROTO);
21496 		return;
21497 	}
21498 	/* Check alignment of the strbuf */
21499 	if (!OK_32PTR(mp1->b_rptr)) {
21500 		mi_copy_done(q, mp, EINVAL);
21501 		return;
21502 	}
21503 
21504 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
21505 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21506 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21507 		mi_copy_done(q, mp, EINVAL);
21508 		return;
21509 	}
21510 
21511 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21512 	if (mp1 == NULL)
21513 		return;
21514 
21515 	switch (iocp->ioc_cmd) {
21516 	case TI_GETMYNAME:
21517 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
21518 		break;
21519 	case TI_GETPEERNAME:
21520 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
21521 		break;
21522 	}
21523 
21524 	if (error != 0) {
21525 		mi_copy_done(q, mp, error);
21526 	} else {
21527 		mp1->b_wptr += addrlen;
21528 		STRUCT_FSET(sb, len, addrlen);
21529 
21530 		/* Copy out the address */
21531 		mi_copyout(q, mp);
21532 	}
21533 }
21534 
21535 static void
21536 tcp_use_pure_tpi(tcp_t *tcp)
21537 {
21538 #ifdef	_ILP32
21539 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
21540 #else
21541 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21542 #endif
21543 	/*
21544 	 * Insert this socket into the acceptor hash.
21545 	 * We might need it for T_CONN_RES message
21546 	 */
21547 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21548 
21549 	tcp->tcp_issocket = B_FALSE;
21550 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
21551 }
21552 
21553 /*
21554  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21555  * messages.
21556  */
21557 /* ARGSUSED */
21558 static void
21559 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21560 {
21561 	conn_t 	*connp = (conn_t *)arg;
21562 	tcp_t	*tcp = connp->conn_tcp;
21563 	queue_t	*q = tcp->tcp_wq;
21564 	struct iocblk	*iocp;
21565 
21566 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21567 	/*
21568 	 * Try and ASSERT the minimum possible references on the
21569 	 * conn early enough. Since we are executing on write side,
21570 	 * the connection is obviously not detached and that means
21571 	 * there is a ref each for TCP and IP. Since we are behind
21572 	 * the squeue, the minimum references needed are 3. If the
21573 	 * conn is in classifier hash list, there should be an
21574 	 * extra ref for that (we check both the possibilities).
21575 	 */
21576 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21577 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21578 
21579 	iocp = (struct iocblk *)mp->b_rptr;
21580 	switch (iocp->ioc_cmd) {
21581 	case TCP_IOC_DEFAULT_Q:
21582 		/* Wants to be the default wq. */
21583 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21584 			iocp->ioc_error = EPERM;
21585 			iocp->ioc_count = 0;
21586 			mp->b_datap->db_type = M_IOCACK;
21587 			qreply(q, mp);
21588 			return;
21589 		}
21590 		tcp_def_q_set(tcp, mp);
21591 		return;
21592 	case _SIOCSOCKFALLBACK:
21593 		/*
21594 		 * Either sockmod is about to be popped and the socket
21595 		 * would now be treated as a plain stream, or a module
21596 		 * is about to be pushed so we could no longer use read-
21597 		 * side synchronous streams for fused loopback tcp.
21598 		 * Drain any queued data and disable direct sockfs
21599 		 * interface from now on.
21600 		 */
21601 		if (!tcp->tcp_issocket) {
21602 			DB_TYPE(mp) = M_IOCNAK;
21603 			iocp->ioc_error = EINVAL;
21604 		} else {
21605 			tcp_use_pure_tpi(tcp);
21606 			DB_TYPE(mp) = M_IOCACK;
21607 			iocp->ioc_error = 0;
21608 		}
21609 		iocp->ioc_count = 0;
21610 		iocp->ioc_rval = 0;
21611 		qreply(q, mp);
21612 		return;
21613 	}
21614 	CALL_IP_WPUT(connp, q, mp);
21615 }
21616 
21617 /*
21618  * This routine is called by tcp_wput() to handle all TPI requests.
21619  */
21620 /* ARGSUSED */
21621 static void
21622 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21623 {
21624 	conn_t 	*connp = (conn_t *)arg;
21625 	tcp_t	*tcp = connp->conn_tcp;
21626 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21627 	uchar_t *rptr;
21628 	t_scalar_t type;
21629 	cred_t *cr;
21630 
21631 	/*
21632 	 * Try and ASSERT the minimum possible references on the
21633 	 * conn early enough. Since we are executing on write side,
21634 	 * the connection is obviously not detached and that means
21635 	 * there is a ref each for TCP and IP. Since we are behind
21636 	 * the squeue, the minimum references needed are 3. If the
21637 	 * conn is in classifier hash list, there should be an
21638 	 * extra ref for that (we check both the possibilities).
21639 	 */
21640 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21641 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21642 
21643 	rptr = mp->b_rptr;
21644 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21645 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21646 		type = ((union T_primitives *)rptr)->type;
21647 		if (type == T_EXDATA_REQ) {
21648 			tcp_output_urgent(connp, mp, arg2);
21649 		} else if (type != T_DATA_REQ) {
21650 			goto non_urgent_data;
21651 		} else {
21652 			/* TODO: options, flags, ... from user */
21653 			/* Set length to zero for reclamation below */
21654 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21655 			freeb(mp);
21656 		}
21657 		return;
21658 	} else {
21659 		if (tcp->tcp_debug) {
21660 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21661 			    "tcp_wput_proto, dropping one...");
21662 		}
21663 		freemsg(mp);
21664 		return;
21665 	}
21666 
21667 non_urgent_data:
21668 
21669 	switch ((int)tprim->type) {
21670 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21671 		/*
21672 		 * save the kssl_ent_t from the next block, and convert this
21673 		 * back to a normal bind_req.
21674 		 */
21675 		if (mp->b_cont != NULL) {
21676 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21677 
21678 			if (tcp->tcp_kssl_ent != NULL) {
21679 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21680 				    KSSL_NO_PROXY);
21681 				tcp->tcp_kssl_ent = NULL;
21682 			}
21683 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21684 			    sizeof (kssl_ent_t));
21685 			kssl_hold_ent(tcp->tcp_kssl_ent);
21686 			freemsg(mp->b_cont);
21687 			mp->b_cont = NULL;
21688 		}
21689 		tprim->type = T_BIND_REQ;
21690 
21691 	/* FALLTHROUGH */
21692 	case O_T_BIND_REQ:	/* bind request */
21693 	case T_BIND_REQ:	/* new semantics bind request */
21694 		tcp_tpi_bind(tcp, mp);
21695 		break;
21696 	case T_UNBIND_REQ:	/* unbind request */
21697 		tcp_tpi_unbind(tcp, mp);
21698 		break;
21699 	case O_T_CONN_RES:	/* old connection response XXX */
21700 	case T_CONN_RES:	/* connection response */
21701 		tcp_tli_accept(tcp, mp);
21702 		break;
21703 	case T_CONN_REQ:	/* connection request */
21704 		tcp_tpi_connect(tcp, mp);
21705 		break;
21706 	case T_DISCON_REQ:	/* disconnect request */
21707 		tcp_disconnect(tcp, mp);
21708 		break;
21709 	case T_CAPABILITY_REQ:
21710 		tcp_capability_req(tcp, mp);	/* capability request */
21711 		break;
21712 	case T_INFO_REQ:	/* information request */
21713 		tcp_info_req(tcp, mp);
21714 		break;
21715 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21716 	case T_OPTMGMT_REQ:
21717 		/*
21718 		 * Note:  no support for snmpcom_req() through new
21719 		 * T_OPTMGMT_REQ. See comments in ip.c
21720 		 */
21721 
21722 		/*
21723 		 * All Solaris components should pass a db_credp
21724 		 * for this TPI message, hence we ASSERT.
21725 		 * But in case there is some other M_PROTO that looks
21726 		 * like a TPI message sent by some other kernel
21727 		 * component, we check and return an error.
21728 		 */
21729 		cr = msg_getcred(mp, NULL);
21730 		ASSERT(cr != NULL);
21731 		if (cr == NULL) {
21732 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
21733 			return;
21734 		}
21735 		/*
21736 		 * If EINPROGRESS is returned, the request has been queued
21737 		 * for subsequent processing by ip_restart_optmgmt(), which
21738 		 * will do the CONN_DEC_REF().
21739 		 */
21740 		CONN_INC_REF(connp);
21741 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
21742 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21743 			    B_TRUE) != EINPROGRESS) {
21744 				CONN_DEC_REF(connp);
21745 			}
21746 		} else {
21747 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21748 			    B_TRUE) != EINPROGRESS) {
21749 				CONN_DEC_REF(connp);
21750 			}
21751 		}
21752 		break;
21753 
21754 	case T_UNITDATA_REQ:	/* unitdata request */
21755 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21756 		break;
21757 	case T_ORDREL_REQ:	/* orderly release req */
21758 		freemsg(mp);
21759 
21760 		if (tcp->tcp_fused)
21761 			tcp_unfuse(tcp);
21762 
21763 		if (tcp_xmit_end(tcp) != 0) {
21764 			/*
21765 			 * We were crossing FINs and got a reset from
21766 			 * the other side. Just ignore it.
21767 			 */
21768 			if (tcp->tcp_debug) {
21769 				(void) strlog(TCP_MOD_ID, 0, 1,
21770 				    SL_ERROR|SL_TRACE,
21771 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21772 				    "state %s",
21773 				    tcp_display(tcp, NULL,
21774 				    DISP_ADDR_AND_PORT));
21775 			}
21776 		}
21777 		break;
21778 	case T_ADDR_REQ:
21779 		tcp_addr_req(tcp, mp);
21780 		break;
21781 	default:
21782 		if (tcp->tcp_debug) {
21783 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21784 			    "tcp_wput_proto, bogus TPI msg, type %d",
21785 			    tprim->type);
21786 		}
21787 		/*
21788 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21789 		 * to recover.
21790 		 */
21791 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21792 		break;
21793 	}
21794 }
21795 
21796 /*
21797  * The TCP write service routine should never be called...
21798  */
21799 /* ARGSUSED */
21800 static void
21801 tcp_wsrv(queue_t *q)
21802 {
21803 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
21804 
21805 	TCP_STAT(tcps, tcp_wsrv_called);
21806 }
21807 
21808 /* Non overlapping byte exchanger */
21809 static void
21810 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21811 {
21812 	uchar_t	uch;
21813 
21814 	while (len-- > 0) {
21815 		uch = a[len];
21816 		a[len] = b[len];
21817 		b[len] = uch;
21818 	}
21819 }
21820 
21821 /*
21822  * Send out a control packet on the tcp connection specified.  This routine
21823  * is typically called where we need a simple ACK or RST generated.
21824  */
21825 static void
21826 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21827 {
21828 	uchar_t		*rptr;
21829 	tcph_t		*tcph;
21830 	ipha_t		*ipha = NULL;
21831 	ip6_t		*ip6h = NULL;
21832 	uint32_t	sum;
21833 	int		tcp_hdr_len;
21834 	int		tcp_ip_hdr_len;
21835 	mblk_t		*mp;
21836 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21837 
21838 	/*
21839 	 * Save sum for use in source route later.
21840 	 */
21841 	ASSERT(tcp != NULL);
21842 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21843 	tcp_hdr_len = tcp->tcp_hdr_len;
21844 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21845 
21846 	/* If a text string is passed in with the request, pass it to strlog. */
21847 	if (str != NULL && tcp->tcp_debug) {
21848 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21849 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21850 		    str, seq, ack, ctl);
21851 	}
21852 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
21853 	    BPRI_MED);
21854 	if (mp == NULL) {
21855 		return;
21856 	}
21857 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
21858 	mp->b_rptr = rptr;
21859 	mp->b_wptr = &rptr[tcp_hdr_len];
21860 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21861 
21862 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21863 		ipha = (ipha_t *)rptr;
21864 		ipha->ipha_length = htons(tcp_hdr_len);
21865 	} else {
21866 		ip6h = (ip6_t *)rptr;
21867 		ASSERT(tcp != NULL);
21868 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21869 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21870 	}
21871 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21872 	tcph->th_flags[0] = (uint8_t)ctl;
21873 	if (ctl & TH_RST) {
21874 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
21875 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
21876 		/*
21877 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21878 		 */
21879 		if (tcp->tcp_snd_ts_ok &&
21880 		    tcp->tcp_state > TCPS_SYN_SENT) {
21881 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21882 			*(mp->b_wptr) = TCPOPT_EOL;
21883 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21884 				ipha->ipha_length = htons(tcp_hdr_len -
21885 				    TCPOPT_REAL_TS_LEN);
21886 			} else {
21887 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21888 				    TCPOPT_REAL_TS_LEN);
21889 			}
21890 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21891 			sum -= TCPOPT_REAL_TS_LEN;
21892 		}
21893 	}
21894 	if (ctl & TH_ACK) {
21895 		if (tcp->tcp_snd_ts_ok) {
21896 			U32_TO_BE32(lbolt,
21897 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21898 			U32_TO_BE32(tcp->tcp_ts_recent,
21899 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21900 		}
21901 
21902 		/* Update the latest receive window size in TCP header. */
21903 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21904 		    tcph->th_win);
21905 		tcp->tcp_rack = ack;
21906 		tcp->tcp_rack_cnt = 0;
21907 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
21908 	}
21909 	BUMP_LOCAL(tcp->tcp_obsegs);
21910 	U32_TO_BE32(seq, tcph->th_seq);
21911 	U32_TO_BE32(ack, tcph->th_ack);
21912 	/*
21913 	 * Include the adjustment for a source route if any.
21914 	 */
21915 	sum = (sum >> 16) + (sum & 0xFFFF);
21916 	U16_TO_BE16(sum, tcph->th_sum);
21917 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21918 }
21919 
21920 /*
21921  * If this routine returns B_TRUE, TCP can generate a RST in response
21922  * to a segment.  If it returns B_FALSE, TCP should not respond.
21923  */
21924 static boolean_t
21925 tcp_send_rst_chk(tcp_stack_t *tcps)
21926 {
21927 	clock_t	now;
21928 
21929 	/*
21930 	 * TCP needs to protect itself from generating too many RSTs.
21931 	 * This can be a DoS attack by sending us random segments
21932 	 * soliciting RSTs.
21933 	 *
21934 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21935 	 * in each 1 second interval.  In this way, TCP still generate
21936 	 * RSTs in normal cases but when under attack, the impact is
21937 	 * limited.
21938 	 */
21939 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
21940 		now = lbolt;
21941 		/* lbolt can wrap around. */
21942 		if ((tcps->tcps_last_rst_intrvl > now) ||
21943 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
21944 		    1*SECONDS)) {
21945 			tcps->tcps_last_rst_intrvl = now;
21946 			tcps->tcps_rst_cnt = 1;
21947 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
21948 			return (B_FALSE);
21949 		}
21950 	}
21951 	return (B_TRUE);
21952 }
21953 
21954 /*
21955  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21956  */
21957 static void
21958 tcp_ip_ire_mark_advice(tcp_t *tcp)
21959 {
21960 	mblk_t *mp;
21961 	ipic_t *ipic;
21962 
21963 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21964 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21965 		    &ipic);
21966 	} else {
21967 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21968 		    &ipic);
21969 	}
21970 	if (mp == NULL)
21971 		return;
21972 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21973 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21974 }
21975 
21976 /*
21977  * Return an IP advice ioctl mblk and set ipic to be the pointer
21978  * to the advice structure.
21979  */
21980 static mblk_t *
21981 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21982 {
21983 	struct iocblk *ioc;
21984 	mblk_t *mp, *mp1;
21985 
21986 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21987 	if (mp == NULL)
21988 		return (NULL);
21989 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21990 	*ipic = (ipic_t *)mp->b_rptr;
21991 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21992 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21993 
21994 	bcopy(addr, *ipic + 1, addr_len);
21995 
21996 	(*ipic)->ipic_addr_length = addr_len;
21997 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21998 
21999 	mp1 = mkiocb(IP_IOCTL);
22000 	if (mp1 == NULL) {
22001 		freemsg(mp);
22002 		return (NULL);
22003 	}
22004 	mp1->b_cont = mp;
22005 	ioc = (struct iocblk *)mp1->b_rptr;
22006 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22007 
22008 	return (mp1);
22009 }
22010 
22011 /*
22012  * Generate a reset based on an inbound packet, connp is set by caller
22013  * when RST is in response to an unexpected inbound packet for which
22014  * there is active tcp state in the system.
22015  *
22016  * IPSEC NOTE : Try to send the reply with the same protection as it came
22017  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22018  * the packet will go out at the same level of protection as it came in by
22019  * converting the IPSEC_IN to IPSEC_OUT.
22020  */
22021 static void
22022 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22023     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22024     tcp_stack_t *tcps, conn_t *connp)
22025 {
22026 	ipha_t		*ipha = NULL;
22027 	ip6_t		*ip6h = NULL;
22028 	ushort_t	len;
22029 	tcph_t		*tcph;
22030 	int		i;
22031 	mblk_t		*ipsec_mp;
22032 	boolean_t	mctl_present;
22033 	ipic_t		*ipic;
22034 	ipaddr_t	v4addr;
22035 	in6_addr_t	v6addr;
22036 	int		addr_len;
22037 	void		*addr;
22038 	queue_t		*q = tcps->tcps_g_q;
22039 	tcp_t		*tcp;
22040 	cred_t		*cr;
22041 	pid_t		pid;
22042 	mblk_t		*nmp;
22043 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22044 
22045 	if (tcps->tcps_g_q == NULL) {
22046 		/*
22047 		 * For non-zero stackids the default queue isn't created
22048 		 * until the first open, thus there can be a need to send
22049 		 * a reset before then. But we can't do that, hence we just
22050 		 * drop the packet. Later during boot, when the default queue
22051 		 * has been setup, a retransmitted packet from the peer
22052 		 * will result in a reset.
22053 		 */
22054 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22055 		    GLOBAL_NETSTACKID);
22056 		freemsg(mp);
22057 		return;
22058 	}
22059 
22060 	if (connp != NULL)
22061 		tcp = connp->conn_tcp;
22062 	else
22063 		tcp = Q_TO_TCP(q);
22064 
22065 	if (!tcp_send_rst_chk(tcps)) {
22066 		tcps->tcps_rst_unsent++;
22067 		freemsg(mp);
22068 		return;
22069 	}
22070 
22071 	if (mp->b_datap->db_type == M_CTL) {
22072 		ipsec_mp = mp;
22073 		mp = mp->b_cont;
22074 		mctl_present = B_TRUE;
22075 	} else {
22076 		ipsec_mp = mp;
22077 		mctl_present = B_FALSE;
22078 	}
22079 
22080 	if (str && q && tcps->tcps_dbg) {
22081 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22082 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22083 		    "flags 0x%x",
22084 		    str, seq, ack, ctl);
22085 	}
22086 	if (mp->b_datap->db_ref != 1) {
22087 		mblk_t *mp1 = copyb(mp);
22088 		freemsg(mp);
22089 		mp = mp1;
22090 		if (!mp) {
22091 			if (mctl_present)
22092 				freeb(ipsec_mp);
22093 			return;
22094 		} else {
22095 			if (mctl_present) {
22096 				ipsec_mp->b_cont = mp;
22097 			} else {
22098 				ipsec_mp = mp;
22099 			}
22100 		}
22101 	} else if (mp->b_cont) {
22102 		freemsg(mp->b_cont);
22103 		mp->b_cont = NULL;
22104 	}
22105 	/*
22106 	 * We skip reversing source route here.
22107 	 * (for now we replace all IP options with EOL)
22108 	 */
22109 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22110 		ipha = (ipha_t *)mp->b_rptr;
22111 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22112 			mp->b_rptr[i] = IPOPT_EOL;
22113 		/*
22114 		 * Make sure that src address isn't flagrantly invalid.
22115 		 * Not all broadcast address checking for the src address
22116 		 * is possible, since we don't know the netmask of the src
22117 		 * addr.  No check for destination address is done, since
22118 		 * IP will not pass up a packet with a broadcast dest
22119 		 * address to TCP.  Similar checks are done below for IPv6.
22120 		 */
22121 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22122 		    CLASSD(ipha->ipha_src)) {
22123 			freemsg(ipsec_mp);
22124 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22125 			return;
22126 		}
22127 	} else {
22128 		ip6h = (ip6_t *)mp->b_rptr;
22129 
22130 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22131 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22132 			freemsg(ipsec_mp);
22133 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22134 			return;
22135 		}
22136 
22137 		/* Remove any extension headers assuming partial overlay */
22138 		if (ip_hdr_len > IPV6_HDR_LEN) {
22139 			uint8_t *to;
22140 
22141 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22142 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22143 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22144 			ip_hdr_len = IPV6_HDR_LEN;
22145 			ip6h = (ip6_t *)mp->b_rptr;
22146 			ip6h->ip6_nxt = IPPROTO_TCP;
22147 		}
22148 	}
22149 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22150 	if (tcph->th_flags[0] & TH_RST) {
22151 		freemsg(ipsec_mp);
22152 		return;
22153 	}
22154 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22155 	len = ip_hdr_len + sizeof (tcph_t);
22156 	mp->b_wptr = &mp->b_rptr[len];
22157 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22158 		ipha->ipha_length = htons(len);
22159 		/* Swap addresses */
22160 		v4addr = ipha->ipha_src;
22161 		ipha->ipha_src = ipha->ipha_dst;
22162 		ipha->ipha_dst = v4addr;
22163 		ipha->ipha_ident = 0;
22164 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22165 		addr_len = IP_ADDR_LEN;
22166 		addr = &v4addr;
22167 	} else {
22168 		/* No ip6i_t in this case */
22169 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22170 		/* Swap addresses */
22171 		v6addr = ip6h->ip6_src;
22172 		ip6h->ip6_src = ip6h->ip6_dst;
22173 		ip6h->ip6_dst = v6addr;
22174 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22175 		addr_len = IPV6_ADDR_LEN;
22176 		addr = &v6addr;
22177 	}
22178 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22179 	U32_TO_BE32(ack, tcph->th_ack);
22180 	U32_TO_BE32(seq, tcph->th_seq);
22181 	U16_TO_BE16(0, tcph->th_win);
22182 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22183 	tcph->th_flags[0] = (uint8_t)ctl;
22184 	if (ctl & TH_RST) {
22185 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22186 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22187 	}
22188 
22189 	/* IP trusts us to set up labels when required. */
22190 	if (is_system_labeled() && (cr = msg_getcred(mp, &pid)) != NULL &&
22191 	    crgetlabel(cr) != NULL) {
22192 		int err;
22193 
22194 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22195 			err = tsol_check_label(cr, &mp,
22196 			    tcp->tcp_connp->conn_mac_exempt,
22197 			    tcps->tcps_netstack->netstack_ip, pid);
22198 		else
22199 			err = tsol_check_label_v6(cr, &mp,
22200 			    tcp->tcp_connp->conn_mac_exempt,
22201 			    tcps->tcps_netstack->netstack_ip, pid);
22202 		if (mctl_present)
22203 			ipsec_mp->b_cont = mp;
22204 		else
22205 			ipsec_mp = mp;
22206 		if (err != 0) {
22207 			freemsg(ipsec_mp);
22208 			return;
22209 		}
22210 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22211 			ipha = (ipha_t *)mp->b_rptr;
22212 		} else {
22213 			ip6h = (ip6_t *)mp->b_rptr;
22214 		}
22215 	}
22216 
22217 	if (mctl_present) {
22218 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22219 
22220 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22221 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22222 			return;
22223 		}
22224 	}
22225 	if (zoneid == ALL_ZONES)
22226 		zoneid = GLOBAL_ZONEID;
22227 
22228 	/* Add the zoneid so ip_output routes it properly */
22229 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22230 		freemsg(ipsec_mp);
22231 		return;
22232 	}
22233 	ipsec_mp = nmp;
22234 
22235 	/*
22236 	 * NOTE:  one might consider tracing a TCP packet here, but
22237 	 * this function has no active TCP state and no tcp structure
22238 	 * that has a trace buffer.  If we traced here, we would have
22239 	 * to keep a local trace buffer in tcp_record_trace().
22240 	 *
22241 	 * TSol note: The mblk that contains the incoming packet was
22242 	 * reused by tcp_xmit_listener_reset, so it already contains
22243 	 * the right credentials and we don't need to call mblk_setcred.
22244 	 * Also the conn's cred is not right since it is associated
22245 	 * with tcps_g_q.
22246 	 */
22247 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22248 
22249 	/*
22250 	 * Tell IP to mark the IRE used for this destination temporary.
22251 	 * This way, we can limit our exposure to DoS attack because IP
22252 	 * creates an IRE for each destination.  If there are too many,
22253 	 * the time to do any routing lookup will be extremely long.  And
22254 	 * the lookup can be in interrupt context.
22255 	 *
22256 	 * Note that in normal circumstances, this marking should not
22257 	 * affect anything.  It would be nice if only 1 message is
22258 	 * needed to inform IP that the IRE created for this RST should
22259 	 * not be added to the cache table.  But there is currently
22260 	 * not such communication mechanism between TCP and IP.  So
22261 	 * the best we can do now is to send the advice ioctl to IP
22262 	 * to mark the IRE temporary.
22263 	 */
22264 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22265 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22266 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22267 	}
22268 }
22269 
22270 /*
22271  * Initiate closedown sequence on an active connection.  (May be called as
22272  * writer.)  Return value zero for OK return, non-zero for error return.
22273  */
22274 static int
22275 tcp_xmit_end(tcp_t *tcp)
22276 {
22277 	ipic_t	*ipic;
22278 	mblk_t	*mp;
22279 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22280 
22281 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22282 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22283 		/*
22284 		 * Invalid state, only states TCPS_SYN_RCVD,
22285 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22286 		 */
22287 		return (-1);
22288 	}
22289 
22290 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22291 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22292 	/*
22293 	 * If there is nothing more unsent, send the FIN now.
22294 	 * Otherwise, it will go out with the last segment.
22295 	 */
22296 	if (tcp->tcp_unsent == 0) {
22297 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22298 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22299 
22300 		if (mp) {
22301 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22302 		} else {
22303 			/*
22304 			 * Couldn't allocate msg.  Pretend we got it out.
22305 			 * Wait for rexmit timeout.
22306 			 */
22307 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22308 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22309 		}
22310 
22311 		/*
22312 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22313 		 * changed.
22314 		 */
22315 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22316 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22317 		}
22318 	} else {
22319 		/*
22320 		 * If tcp->tcp_cork is set, then the data will not get sent,
22321 		 * so we have to check that and unset it first.
22322 		 */
22323 		if (tcp->tcp_cork)
22324 			tcp->tcp_cork = B_FALSE;
22325 		tcp_wput_data(tcp, NULL, B_FALSE);
22326 	}
22327 
22328 	/*
22329 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22330 	 * is 0, don't update the cache.
22331 	 */
22332 	if (tcps->tcps_rtt_updates == 0 ||
22333 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22334 		return (0);
22335 
22336 	/*
22337 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22338 	 * different from the destination.
22339 	 */
22340 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22341 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22342 			return (0);
22343 		}
22344 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22345 		    &ipic);
22346 	} else {
22347 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22348 		    &tcp->tcp_ip6h->ip6_dst))) {
22349 			return (0);
22350 		}
22351 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22352 		    &ipic);
22353 	}
22354 
22355 	/* Record route attributes in the IRE for use by future connections. */
22356 	if (mp == NULL)
22357 		return (0);
22358 
22359 	/*
22360 	 * We do not have a good algorithm to update ssthresh at this time.
22361 	 * So don't do any update.
22362 	 */
22363 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22364 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22365 
22366 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22367 
22368 	return (0);
22369 }
22370 
22371 /* ARGSUSED */
22372 void
22373 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
22374 {
22375 	conn_t *connp = (conn_t *)arg;
22376 	mblk_t *mp1;
22377 	tcp_t *tcp = connp->conn_tcp;
22378 	tcp_xmit_reset_event_t *eventp;
22379 
22380 	ASSERT(mp->b_datap->db_type == M_PROTO &&
22381 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
22382 
22383 	if (tcp->tcp_state != TCPS_LISTEN) {
22384 		freemsg(mp);
22385 		return;
22386 	}
22387 
22388 	mp1 = mp->b_cont;
22389 	mp->b_cont = NULL;
22390 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
22391 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
22392 	    connp->conn_netstack);
22393 
22394 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
22395 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
22396 	freemsg(mp);
22397 }
22398 
22399 /*
22400  * Generate a "no listener here" RST in response to an "unknown" segment.
22401  * connp is set by caller when RST is in response to an unexpected
22402  * inbound packet for which there is active tcp state in the system.
22403  * Note that we are reusing the incoming mp to construct the outgoing RST.
22404  */
22405 void
22406 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22407     tcp_stack_t *tcps, conn_t *connp)
22408 {
22409 	uchar_t		*rptr;
22410 	uint32_t	seg_len;
22411 	tcph_t		*tcph;
22412 	uint32_t	seg_seq;
22413 	uint32_t	seg_ack;
22414 	uint_t		flags;
22415 	mblk_t		*ipsec_mp;
22416 	ipha_t 		*ipha;
22417 	ip6_t 		*ip6h;
22418 	boolean_t	mctl_present = B_FALSE;
22419 	boolean_t	check = B_TRUE;
22420 	boolean_t	policy_present;
22421 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22422 
22423 	TCP_STAT(tcps, tcp_no_listener);
22424 
22425 	ipsec_mp = mp;
22426 
22427 	if (mp->b_datap->db_type == M_CTL) {
22428 		ipsec_in_t *ii;
22429 
22430 		mctl_present = B_TRUE;
22431 		mp = mp->b_cont;
22432 
22433 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22434 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22435 		if (ii->ipsec_in_dont_check) {
22436 			check = B_FALSE;
22437 			if (!ii->ipsec_in_secure) {
22438 				freeb(ipsec_mp);
22439 				mctl_present = B_FALSE;
22440 				ipsec_mp = mp;
22441 			}
22442 		}
22443 	}
22444 
22445 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22446 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22447 		ipha = (ipha_t *)mp->b_rptr;
22448 		ip6h = NULL;
22449 	} else {
22450 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22451 		ipha = NULL;
22452 		ip6h = (ip6_t *)mp->b_rptr;
22453 	}
22454 
22455 	if (check && policy_present) {
22456 		/*
22457 		 * The conn_t parameter is NULL because we already know
22458 		 * nobody's home.
22459 		 */
22460 		ipsec_mp = ipsec_check_global_policy(
22461 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22462 		    tcps->tcps_netstack);
22463 		if (ipsec_mp == NULL)
22464 			return;
22465 	}
22466 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22467 		DTRACE_PROBE2(
22468 		    tx__ip__log__error__nolistener__tcp,
22469 		    char *, "Could not reply with RST to mp(1)",
22470 		    mblk_t *, mp);
22471 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22472 		freemsg(ipsec_mp);
22473 		return;
22474 	}
22475 
22476 	rptr = mp->b_rptr;
22477 
22478 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22479 	seg_seq = BE32_TO_U32(tcph->th_seq);
22480 	seg_ack = BE32_TO_U32(tcph->th_ack);
22481 	flags = tcph->th_flags[0];
22482 
22483 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22484 	if (flags & TH_RST) {
22485 		freemsg(ipsec_mp);
22486 	} else if (flags & TH_ACK) {
22487 		tcp_xmit_early_reset("no tcp, reset",
22488 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22489 		    connp);
22490 	} else {
22491 		if (flags & TH_SYN) {
22492 			seg_len++;
22493 		} else {
22494 			/*
22495 			 * Here we violate the RFC.  Note that a normal
22496 			 * TCP will never send a segment without the ACK
22497 			 * flag, except for RST or SYN segment.  This
22498 			 * segment is neither.  Just drop it on the
22499 			 * floor.
22500 			 */
22501 			freemsg(ipsec_mp);
22502 			tcps->tcps_rst_unsent++;
22503 			return;
22504 		}
22505 
22506 		tcp_xmit_early_reset("no tcp, reset/ack",
22507 		    ipsec_mp, 0, seg_seq + seg_len,
22508 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22509 	}
22510 }
22511 
22512 /*
22513  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22514  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22515  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22516  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22517  * otherwise it will dup partial mblks.)
22518  * Otherwise, an appropriate ACK packet will be generated.  This
22519  * routine is not usually called to send new data for the first time.  It
22520  * is mostly called out of the timer for retransmits, and to generate ACKs.
22521  *
22522  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22523  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22524  * of the original mblk chain will be returned in *offset and *end_mp.
22525  */
22526 mblk_t *
22527 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22528     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22529     boolean_t rexmit)
22530 {
22531 	int	data_length;
22532 	int32_t	off = 0;
22533 	uint_t	flags;
22534 	mblk_t	*mp1;
22535 	mblk_t	*mp2;
22536 	uchar_t	*rptr;
22537 	tcph_t	*tcph;
22538 	int32_t	num_sack_blk = 0;
22539 	int32_t	sack_opt_len = 0;
22540 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22541 
22542 	/* Allocate for our maximum TCP header + link-level */
22543 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22544 	    tcps->tcps_wroff_xtra, BPRI_MED);
22545 	if (!mp1)
22546 		return (NULL);
22547 	data_length = 0;
22548 
22549 	/*
22550 	 * Note that tcp_mss has been adjusted to take into account the
22551 	 * timestamp option if applicable.  Because SACK options do not
22552 	 * appear in every TCP segments and they are of variable lengths,
22553 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22554 	 * the actual segment length when we need to send a segment which
22555 	 * includes SACK options.
22556 	 */
22557 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22558 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22559 		    tcp->tcp_num_sack_blk);
22560 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22561 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22562 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22563 			max_to_send -= sack_opt_len;
22564 	}
22565 
22566 	if (offset != NULL) {
22567 		off = *offset;
22568 		/* We use offset as an indicator that end_mp is not NULL. */
22569 		*end_mp = NULL;
22570 	}
22571 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22572 		/* This could be faster with cooperation from downstream */
22573 		if (mp2 != mp1 && !sendall &&
22574 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22575 		    max_to_send)
22576 			/*
22577 			 * Don't send the next mblk since the whole mblk
22578 			 * does not fit.
22579 			 */
22580 			break;
22581 		mp2->b_cont = dupb(mp);
22582 		mp2 = mp2->b_cont;
22583 		if (!mp2) {
22584 			freemsg(mp1);
22585 			return (NULL);
22586 		}
22587 		mp2->b_rptr += off;
22588 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22589 		    (uintptr_t)INT_MAX);
22590 
22591 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22592 		if (data_length > max_to_send) {
22593 			mp2->b_wptr -= data_length - max_to_send;
22594 			data_length = max_to_send;
22595 			off = mp2->b_wptr - mp->b_rptr;
22596 			break;
22597 		} else {
22598 			off = 0;
22599 		}
22600 	}
22601 	if (offset != NULL) {
22602 		*offset = off;
22603 		*end_mp = mp;
22604 	}
22605 	if (seg_len != NULL) {
22606 		*seg_len = data_length;
22607 	}
22608 
22609 	/* Update the latest receive window size in TCP header. */
22610 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22611 	    tcp->tcp_tcph->th_win);
22612 
22613 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22614 	mp1->b_rptr = rptr;
22615 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22616 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22617 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22618 	U32_TO_ABE32(seq, tcph->th_seq);
22619 
22620 	/*
22621 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22622 	 * that this function was called from tcp_wput_data. Thus, when called
22623 	 * to retransmit data the setting of the PUSH bit may appear some
22624 	 * what random in that it might get set when it should not. This
22625 	 * should not pose any performance issues.
22626 	 */
22627 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22628 	    tcp->tcp_unsent == data_length)) {
22629 		flags = TH_ACK | TH_PUSH;
22630 	} else {
22631 		flags = TH_ACK;
22632 	}
22633 
22634 	if (tcp->tcp_ecn_ok) {
22635 		if (tcp->tcp_ecn_echo_on)
22636 			flags |= TH_ECE;
22637 
22638 		/*
22639 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22640 		 * There is no TCP flow control for non-data segments, and
22641 		 * only data segment is transmitted reliably.
22642 		 */
22643 		if (data_length > 0 && !rexmit) {
22644 			SET_ECT(tcp, rptr);
22645 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22646 				flags |= TH_CWR;
22647 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22648 			}
22649 		}
22650 	}
22651 
22652 	if (tcp->tcp_valid_bits) {
22653 		uint32_t u1;
22654 
22655 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22656 		    seq == tcp->tcp_iss) {
22657 			uchar_t	*wptr;
22658 
22659 			/*
22660 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22661 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22662 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22663 			 * our SYN is not ack'ed but the app closes this
22664 			 * TCP connection.
22665 			 */
22666 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22667 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22668 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22669 
22670 			/*
22671 			 * Tack on the MSS option.  It is always needed
22672 			 * for both active and passive open.
22673 			 *
22674 			 * MSS option value should be interface MTU - MIN
22675 			 * TCP/IP header according to RFC 793 as it means
22676 			 * the maximum segment size TCP can receive.  But
22677 			 * to get around some broken middle boxes/end hosts
22678 			 * out there, we allow the option value to be the
22679 			 * same as the MSS option size on the peer side.
22680 			 * In this way, the other side will not send
22681 			 * anything larger than they can receive.
22682 			 *
22683 			 * Note that for SYN_SENT state, the ndd param
22684 			 * tcp_use_smss_as_mss_opt has no effect as we
22685 			 * don't know the peer's MSS option value. So
22686 			 * the only case we need to take care of is in
22687 			 * SYN_RCVD state, which is done later.
22688 			 */
22689 			wptr = mp1->b_wptr;
22690 			wptr[0] = TCPOPT_MAXSEG;
22691 			wptr[1] = TCPOPT_MAXSEG_LEN;
22692 			wptr += 2;
22693 			u1 = tcp->tcp_if_mtu -
22694 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22695 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22696 			    TCP_MIN_HEADER_LENGTH;
22697 			U16_TO_BE16(u1, wptr);
22698 			mp1->b_wptr = wptr + 2;
22699 			/* Update the offset to cover the additional word */
22700 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22701 
22702 			/*
22703 			 * Note that the following way of filling in
22704 			 * TCP options are not optimal.  Some NOPs can
22705 			 * be saved.  But there is no need at this time
22706 			 * to optimize it.  When it is needed, we will
22707 			 * do it.
22708 			 */
22709 			switch (tcp->tcp_state) {
22710 			case TCPS_SYN_SENT:
22711 				flags = TH_SYN;
22712 
22713 				if (tcp->tcp_snd_ts_ok) {
22714 					uint32_t llbolt = (uint32_t)lbolt;
22715 
22716 					wptr = mp1->b_wptr;
22717 					wptr[0] = TCPOPT_NOP;
22718 					wptr[1] = TCPOPT_NOP;
22719 					wptr[2] = TCPOPT_TSTAMP;
22720 					wptr[3] = TCPOPT_TSTAMP_LEN;
22721 					wptr += 4;
22722 					U32_TO_BE32(llbolt, wptr);
22723 					wptr += 4;
22724 					ASSERT(tcp->tcp_ts_recent == 0);
22725 					U32_TO_BE32(0L, wptr);
22726 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22727 					tcph->th_offset_and_rsrvd[0] +=
22728 					    (3 << 4);
22729 				}
22730 
22731 				/*
22732 				 * Set up all the bits to tell other side
22733 				 * we are ECN capable.
22734 				 */
22735 				if (tcp->tcp_ecn_ok) {
22736 					flags |= (TH_ECE | TH_CWR);
22737 				}
22738 				break;
22739 			case TCPS_SYN_RCVD:
22740 				flags |= TH_SYN;
22741 
22742 				/*
22743 				 * Reset the MSS option value to be SMSS
22744 				 * We should probably add back the bytes
22745 				 * for timestamp option and IPsec.  We
22746 				 * don't do that as this is a workaround
22747 				 * for broken middle boxes/end hosts, it
22748 				 * is better for us to be more cautious.
22749 				 * They may not take these things into
22750 				 * account in their SMSS calculation.  Thus
22751 				 * the peer's calculated SMSS may be smaller
22752 				 * than what it can be.  This should be OK.
22753 				 */
22754 				if (tcps->tcps_use_smss_as_mss_opt) {
22755 					u1 = tcp->tcp_mss;
22756 					U16_TO_BE16(u1, wptr);
22757 				}
22758 
22759 				/*
22760 				 * If the other side is ECN capable, reply
22761 				 * that we are also ECN capable.
22762 				 */
22763 				if (tcp->tcp_ecn_ok)
22764 					flags |= TH_ECE;
22765 				break;
22766 			default:
22767 				/*
22768 				 * The above ASSERT() makes sure that this
22769 				 * must be FIN-WAIT-1 state.  Our SYN has
22770 				 * not been ack'ed so retransmit it.
22771 				 */
22772 				flags |= TH_SYN;
22773 				break;
22774 			}
22775 
22776 			if (tcp->tcp_snd_ws_ok) {
22777 				wptr = mp1->b_wptr;
22778 				wptr[0] =  TCPOPT_NOP;
22779 				wptr[1] =  TCPOPT_WSCALE;
22780 				wptr[2] =  TCPOPT_WS_LEN;
22781 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22782 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22783 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22784 			}
22785 
22786 			if (tcp->tcp_snd_sack_ok) {
22787 				wptr = mp1->b_wptr;
22788 				wptr[0] = TCPOPT_NOP;
22789 				wptr[1] = TCPOPT_NOP;
22790 				wptr[2] = TCPOPT_SACK_PERMITTED;
22791 				wptr[3] = TCPOPT_SACK_OK_LEN;
22792 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22793 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22794 			}
22795 
22796 			/* allocb() of adequate mblk assures space */
22797 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22798 			    (uintptr_t)INT_MAX);
22799 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22800 			/*
22801 			 * Get IP set to checksum on our behalf
22802 			 * Include the adjustment for a source route if any.
22803 			 */
22804 			u1 += tcp->tcp_sum;
22805 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22806 			U16_TO_BE16(u1, tcph->th_sum);
22807 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22808 		}
22809 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22810 		    (seq + data_length) == tcp->tcp_fss) {
22811 			if (!tcp->tcp_fin_acked) {
22812 				flags |= TH_FIN;
22813 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22814 			}
22815 			if (!tcp->tcp_fin_sent) {
22816 				tcp->tcp_fin_sent = B_TRUE;
22817 				switch (tcp->tcp_state) {
22818 				case TCPS_SYN_RCVD:
22819 				case TCPS_ESTABLISHED:
22820 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22821 					break;
22822 				case TCPS_CLOSE_WAIT:
22823 					tcp->tcp_state = TCPS_LAST_ACK;
22824 					break;
22825 				}
22826 				if (tcp->tcp_suna == tcp->tcp_snxt)
22827 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22828 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22829 			}
22830 		}
22831 		/*
22832 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22833 		 * is smaller than seq, u1 will become a very huge value.
22834 		 * So the comparison will fail.  Also note that tcp_urp
22835 		 * should be positive, see RFC 793 page 17.
22836 		 */
22837 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22838 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22839 		    u1 < (uint32_t)(64 * 1024)) {
22840 			flags |= TH_URG;
22841 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
22842 			U32_TO_ABE16(u1, tcph->th_urp);
22843 		}
22844 	}
22845 	tcph->th_flags[0] = (uchar_t)flags;
22846 	tcp->tcp_rack = tcp->tcp_rnxt;
22847 	tcp->tcp_rack_cnt = 0;
22848 
22849 	if (tcp->tcp_snd_ts_ok) {
22850 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22851 			uint32_t llbolt = (uint32_t)lbolt;
22852 
22853 			U32_TO_BE32(llbolt,
22854 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22855 			U32_TO_BE32(tcp->tcp_ts_recent,
22856 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22857 		}
22858 	}
22859 
22860 	if (num_sack_blk > 0) {
22861 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22862 		sack_blk_t *tmp;
22863 		int32_t	i;
22864 
22865 		wptr[0] = TCPOPT_NOP;
22866 		wptr[1] = TCPOPT_NOP;
22867 		wptr[2] = TCPOPT_SACK;
22868 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22869 		    sizeof (sack_blk_t);
22870 		wptr += TCPOPT_REAL_SACK_LEN;
22871 
22872 		tmp = tcp->tcp_sack_list;
22873 		for (i = 0; i < num_sack_blk; i++) {
22874 			U32_TO_BE32(tmp[i].begin, wptr);
22875 			wptr += sizeof (tcp_seq);
22876 			U32_TO_BE32(tmp[i].end, wptr);
22877 			wptr += sizeof (tcp_seq);
22878 		}
22879 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22880 	}
22881 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22882 	data_length += (int)(mp1->b_wptr - rptr);
22883 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22884 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22885 	} else {
22886 		ip6_t *ip6 = (ip6_t *)(rptr +
22887 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22888 		    sizeof (ip6i_t) : 0));
22889 
22890 		ip6->ip6_plen = htons(data_length -
22891 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22892 	}
22893 
22894 	/*
22895 	 * Prime pump for IP
22896 	 * Include the adjustment for a source route if any.
22897 	 */
22898 	data_length -= tcp->tcp_ip_hdr_len;
22899 	data_length += tcp->tcp_sum;
22900 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22901 	U16_TO_ABE16(data_length, tcph->th_sum);
22902 	if (tcp->tcp_ip_forward_progress) {
22903 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22904 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22905 		tcp->tcp_ip_forward_progress = B_FALSE;
22906 	}
22907 	return (mp1);
22908 }
22909 
22910 /* This function handles the push timeout. */
22911 void
22912 tcp_push_timer(void *arg)
22913 {
22914 	conn_t	*connp = (conn_t *)arg;
22915 	tcp_t *tcp = connp->conn_tcp;
22916 
22917 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
22918 
22919 	ASSERT(tcp->tcp_listener == NULL);
22920 
22921 	ASSERT(!IPCL_IS_NONSTR(connp));
22922 
22923 	tcp->tcp_push_tid = 0;
22924 
22925 	if (tcp->tcp_rcv_list != NULL &&
22926 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
22927 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22928 }
22929 
22930 /*
22931  * This function handles delayed ACK timeout.
22932  */
22933 static void
22934 tcp_ack_timer(void *arg)
22935 {
22936 	conn_t	*connp = (conn_t *)arg;
22937 	tcp_t *tcp = connp->conn_tcp;
22938 	mblk_t *mp;
22939 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22940 
22941 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
22942 
22943 	tcp->tcp_ack_tid = 0;
22944 
22945 	if (tcp->tcp_fused)
22946 		return;
22947 
22948 	/*
22949 	 * Do not send ACK if there is no outstanding unack'ed data.
22950 	 */
22951 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22952 		return;
22953 	}
22954 
22955 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22956 		/*
22957 		 * Make sure we don't allow deferred ACKs to result in
22958 		 * timer-based ACKing.  If we have held off an ACK
22959 		 * when there was more than an mss here, and the timer
22960 		 * goes off, we have to worry about the possibility
22961 		 * that the sender isn't doing slow-start, or is out
22962 		 * of step with us for some other reason.  We fall
22963 		 * permanently back in the direction of
22964 		 * ACK-every-other-packet as suggested in RFC 1122.
22965 		 */
22966 		if (tcp->tcp_rack_abs_max > 2)
22967 			tcp->tcp_rack_abs_max--;
22968 		tcp->tcp_rack_cur_max = 2;
22969 	}
22970 	mp = tcp_ack_mp(tcp);
22971 
22972 	if (mp != NULL) {
22973 		BUMP_LOCAL(tcp->tcp_obsegs);
22974 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22975 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
22976 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22977 	}
22978 }
22979 
22980 
22981 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22982 static mblk_t *
22983 tcp_ack_mp(tcp_t *tcp)
22984 {
22985 	uint32_t	seq_no;
22986 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22987 
22988 	/*
22989 	 * There are a few cases to be considered while setting the sequence no.
22990 	 * Essentially, we can come here while processing an unacceptable pkt
22991 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
22992 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
22993 	 * If we are here for a zero window probe, stick with suna. In all
22994 	 * other cases, we check if suna + swnd encompasses snxt and set
22995 	 * the sequence number to snxt, if so. If snxt falls outside the
22996 	 * window (the receiver probably shrunk its window), we will go with
22997 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
22998 	 * receiver.
22999 	 */
23000 	if (tcp->tcp_zero_win_probe) {
23001 		seq_no = tcp->tcp_suna;
23002 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23003 		ASSERT(tcp->tcp_swnd == 0);
23004 		seq_no = tcp->tcp_snxt;
23005 	} else {
23006 		seq_no = SEQ_GT(tcp->tcp_snxt,
23007 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23008 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23009 	}
23010 
23011 	if (tcp->tcp_valid_bits) {
23012 		/*
23013 		 * For the complex case where we have to send some
23014 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23015 		 */
23016 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23017 		    NULL, B_FALSE));
23018 	} else {
23019 		/* Generate a simple ACK */
23020 		int	data_length;
23021 		uchar_t	*rptr;
23022 		tcph_t	*tcph;
23023 		mblk_t	*mp1;
23024 		int32_t	tcp_hdr_len;
23025 		int32_t	tcp_tcp_hdr_len;
23026 		int32_t	num_sack_blk = 0;
23027 		int32_t sack_opt_len;
23028 
23029 		/*
23030 		 * Allocate space for TCP + IP headers
23031 		 * and link-level header
23032 		 */
23033 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23034 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23035 			    tcp->tcp_num_sack_blk);
23036 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23037 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23038 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23039 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23040 		} else {
23041 			tcp_hdr_len = tcp->tcp_hdr_len;
23042 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23043 		}
23044 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23045 		if (!mp1)
23046 			return (NULL);
23047 
23048 		/* Update the latest receive window size in TCP header. */
23049 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23050 		    tcp->tcp_tcph->th_win);
23051 		/* copy in prototype TCP + IP header */
23052 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23053 		mp1->b_rptr = rptr;
23054 		mp1->b_wptr = rptr + tcp_hdr_len;
23055 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23056 
23057 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23058 
23059 		/* Set the TCP sequence number. */
23060 		U32_TO_ABE32(seq_no, tcph->th_seq);
23061 
23062 		/* Set up the TCP flag field. */
23063 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23064 		if (tcp->tcp_ecn_echo_on)
23065 			tcph->th_flags[0] |= TH_ECE;
23066 
23067 		tcp->tcp_rack = tcp->tcp_rnxt;
23068 		tcp->tcp_rack_cnt = 0;
23069 
23070 		/* fill in timestamp option if in use */
23071 		if (tcp->tcp_snd_ts_ok) {
23072 			uint32_t llbolt = (uint32_t)lbolt;
23073 
23074 			U32_TO_BE32(llbolt,
23075 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23076 			U32_TO_BE32(tcp->tcp_ts_recent,
23077 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23078 		}
23079 
23080 		/* Fill in SACK options */
23081 		if (num_sack_blk > 0) {
23082 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23083 			sack_blk_t *tmp;
23084 			int32_t	i;
23085 
23086 			wptr[0] = TCPOPT_NOP;
23087 			wptr[1] = TCPOPT_NOP;
23088 			wptr[2] = TCPOPT_SACK;
23089 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23090 			    sizeof (sack_blk_t);
23091 			wptr += TCPOPT_REAL_SACK_LEN;
23092 
23093 			tmp = tcp->tcp_sack_list;
23094 			for (i = 0; i < num_sack_blk; i++) {
23095 				U32_TO_BE32(tmp[i].begin, wptr);
23096 				wptr += sizeof (tcp_seq);
23097 				U32_TO_BE32(tmp[i].end, wptr);
23098 				wptr += sizeof (tcp_seq);
23099 			}
23100 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23101 			    << 4);
23102 		}
23103 
23104 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23105 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23106 		} else {
23107 			/* Check for ip6i_t header in sticky hdrs */
23108 			ip6_t *ip6 = (ip6_t *)(rptr +
23109 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23110 			    sizeof (ip6i_t) : 0));
23111 
23112 			ip6->ip6_plen = htons(tcp_hdr_len -
23113 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23114 		}
23115 
23116 		/*
23117 		 * Prime pump for checksum calculation in IP.  Include the
23118 		 * adjustment for a source route if any.
23119 		 */
23120 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23121 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23122 		U16_TO_ABE16(data_length, tcph->th_sum);
23123 
23124 		if (tcp->tcp_ip_forward_progress) {
23125 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23126 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23127 			tcp->tcp_ip_forward_progress = B_FALSE;
23128 		}
23129 		return (mp1);
23130 	}
23131 }
23132 
23133 /*
23134  * Hash list insertion routine for tcp_t structures. Each hash bucket
23135  * contains a list of tcp_t entries, and each entry is bound to a unique
23136  * port. If there are multiple tcp_t's that are bound to the same port, then
23137  * one of them will be linked into the hash bucket list, and the rest will
23138  * hang off of that one entry. For each port, entries bound to a specific IP
23139  * address will be inserted before those those bound to INADDR_ANY.
23140  */
23141 static void
23142 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23143 {
23144 	tcp_t	**tcpp;
23145 	tcp_t	*tcpnext;
23146 	tcp_t	*tcphash;
23147 
23148 	if (tcp->tcp_ptpbhn != NULL) {
23149 		ASSERT(!caller_holds_lock);
23150 		tcp_bind_hash_remove(tcp);
23151 	}
23152 	tcpp = &tbf->tf_tcp;
23153 	if (!caller_holds_lock) {
23154 		mutex_enter(&tbf->tf_lock);
23155 	} else {
23156 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23157 	}
23158 	tcphash = tcpp[0];
23159 	tcpnext = NULL;
23160 	if (tcphash != NULL) {
23161 		/* Look for an entry using the same port */
23162 		while ((tcphash = tcpp[0]) != NULL &&
23163 		    tcp->tcp_lport != tcphash->tcp_lport)
23164 			tcpp = &(tcphash->tcp_bind_hash);
23165 
23166 		/* The port was not found, just add to the end */
23167 		if (tcphash == NULL)
23168 			goto insert;
23169 
23170 		/*
23171 		 * OK, there already exists an entry bound to the
23172 		 * same port.
23173 		 *
23174 		 * If the new tcp bound to the INADDR_ANY address
23175 		 * and the first one in the list is not bound to
23176 		 * INADDR_ANY we skip all entries until we find the
23177 		 * first one bound to INADDR_ANY.
23178 		 * This makes sure that applications binding to a
23179 		 * specific address get preference over those binding to
23180 		 * INADDR_ANY.
23181 		 */
23182 		tcpnext = tcphash;
23183 		tcphash = NULL;
23184 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23185 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23186 			while ((tcpnext = tcpp[0]) != NULL &&
23187 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23188 				tcpp = &(tcpnext->tcp_bind_hash_port);
23189 
23190 			if (tcpnext) {
23191 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23192 				tcphash = tcpnext->tcp_bind_hash;
23193 				if (tcphash != NULL) {
23194 					tcphash->tcp_ptpbhn =
23195 					    &(tcp->tcp_bind_hash);
23196 					tcpnext->tcp_bind_hash = NULL;
23197 				}
23198 			}
23199 		} else {
23200 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23201 			tcphash = tcpnext->tcp_bind_hash;
23202 			if (tcphash != NULL) {
23203 				tcphash->tcp_ptpbhn =
23204 				    &(tcp->tcp_bind_hash);
23205 				tcpnext->tcp_bind_hash = NULL;
23206 			}
23207 		}
23208 	}
23209 insert:
23210 	tcp->tcp_bind_hash_port = tcpnext;
23211 	tcp->tcp_bind_hash = tcphash;
23212 	tcp->tcp_ptpbhn = tcpp;
23213 	tcpp[0] = tcp;
23214 	if (!caller_holds_lock)
23215 		mutex_exit(&tbf->tf_lock);
23216 }
23217 
23218 /*
23219  * Hash list removal routine for tcp_t structures.
23220  */
23221 static void
23222 tcp_bind_hash_remove(tcp_t *tcp)
23223 {
23224 	tcp_t	*tcpnext;
23225 	kmutex_t *lockp;
23226 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23227 
23228 	if (tcp->tcp_ptpbhn == NULL)
23229 		return;
23230 
23231 	/*
23232 	 * Extract the lock pointer in case there are concurrent
23233 	 * hash_remove's for this instance.
23234 	 */
23235 	ASSERT(tcp->tcp_lport != 0);
23236 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23237 
23238 	ASSERT(lockp != NULL);
23239 	mutex_enter(lockp);
23240 	if (tcp->tcp_ptpbhn) {
23241 		tcpnext = tcp->tcp_bind_hash_port;
23242 		if (tcpnext != NULL) {
23243 			tcp->tcp_bind_hash_port = NULL;
23244 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23245 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23246 			if (tcpnext->tcp_bind_hash != NULL) {
23247 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23248 				    &(tcpnext->tcp_bind_hash);
23249 				tcp->tcp_bind_hash = NULL;
23250 			}
23251 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23252 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23253 			tcp->tcp_bind_hash = NULL;
23254 		}
23255 		*tcp->tcp_ptpbhn = tcpnext;
23256 		tcp->tcp_ptpbhn = NULL;
23257 	}
23258 	mutex_exit(lockp);
23259 }
23260 
23261 
23262 /*
23263  * Hash list lookup routine for tcp_t structures.
23264  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23265  */
23266 static tcp_t *
23267 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23268 {
23269 	tf_t	*tf;
23270 	tcp_t	*tcp;
23271 
23272 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23273 	mutex_enter(&tf->tf_lock);
23274 	for (tcp = tf->tf_tcp; tcp != NULL;
23275 	    tcp = tcp->tcp_acceptor_hash) {
23276 		if (tcp->tcp_acceptor_id == id) {
23277 			CONN_INC_REF(tcp->tcp_connp);
23278 			mutex_exit(&tf->tf_lock);
23279 			return (tcp);
23280 		}
23281 	}
23282 	mutex_exit(&tf->tf_lock);
23283 	return (NULL);
23284 }
23285 
23286 
23287 /*
23288  * Hash list insertion routine for tcp_t structures.
23289  */
23290 void
23291 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23292 {
23293 	tf_t	*tf;
23294 	tcp_t	**tcpp;
23295 	tcp_t	*tcpnext;
23296 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23297 
23298 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23299 
23300 	if (tcp->tcp_ptpahn != NULL)
23301 		tcp_acceptor_hash_remove(tcp);
23302 	tcpp = &tf->tf_tcp;
23303 	mutex_enter(&tf->tf_lock);
23304 	tcpnext = tcpp[0];
23305 	if (tcpnext)
23306 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23307 	tcp->tcp_acceptor_hash = tcpnext;
23308 	tcp->tcp_ptpahn = tcpp;
23309 	tcpp[0] = tcp;
23310 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23311 	mutex_exit(&tf->tf_lock);
23312 }
23313 
23314 /*
23315  * Hash list removal routine for tcp_t structures.
23316  */
23317 static void
23318 tcp_acceptor_hash_remove(tcp_t *tcp)
23319 {
23320 	tcp_t	*tcpnext;
23321 	kmutex_t *lockp;
23322 
23323 	/*
23324 	 * Extract the lock pointer in case there are concurrent
23325 	 * hash_remove's for this instance.
23326 	 */
23327 	lockp = tcp->tcp_acceptor_lockp;
23328 
23329 	if (tcp->tcp_ptpahn == NULL)
23330 		return;
23331 
23332 	ASSERT(lockp != NULL);
23333 	mutex_enter(lockp);
23334 	if (tcp->tcp_ptpahn) {
23335 		tcpnext = tcp->tcp_acceptor_hash;
23336 		if (tcpnext) {
23337 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23338 			tcp->tcp_acceptor_hash = NULL;
23339 		}
23340 		*tcp->tcp_ptpahn = tcpnext;
23341 		tcp->tcp_ptpahn = NULL;
23342 	}
23343 	mutex_exit(lockp);
23344 	tcp->tcp_acceptor_lockp = NULL;
23345 }
23346 
23347 /*
23348  * Type three generator adapted from the random() function in 4.4 BSD:
23349  */
23350 
23351 /*
23352  * Copyright (c) 1983, 1993
23353  *	The Regents of the University of California.  All rights reserved.
23354  *
23355  * Redistribution and use in source and binary forms, with or without
23356  * modification, are permitted provided that the following conditions
23357  * are met:
23358  * 1. Redistributions of source code must retain the above copyright
23359  *    notice, this list of conditions and the following disclaimer.
23360  * 2. Redistributions in binary form must reproduce the above copyright
23361  *    notice, this list of conditions and the following disclaimer in the
23362  *    documentation and/or other materials provided with the distribution.
23363  * 3. All advertising materials mentioning features or use of this software
23364  *    must display the following acknowledgement:
23365  *	This product includes software developed by the University of
23366  *	California, Berkeley and its contributors.
23367  * 4. Neither the name of the University nor the names of its contributors
23368  *    may be used to endorse or promote products derived from this software
23369  *    without specific prior written permission.
23370  *
23371  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23372  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23373  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23374  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23375  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23376  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23377  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23378  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23379  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23380  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23381  * SUCH DAMAGE.
23382  */
23383 
23384 /* Type 3 -- x**31 + x**3 + 1 */
23385 #define	DEG_3		31
23386 #define	SEP_3		3
23387 
23388 
23389 /* Protected by tcp_random_lock */
23390 static int tcp_randtbl[DEG_3 + 1];
23391 
23392 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23393 static int *tcp_random_rptr = &tcp_randtbl[1];
23394 
23395 static int *tcp_random_state = &tcp_randtbl[1];
23396 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23397 
23398 kmutex_t tcp_random_lock;
23399 
23400 void
23401 tcp_random_init(void)
23402 {
23403 	int i;
23404 	hrtime_t hrt;
23405 	time_t wallclock;
23406 	uint64_t result;
23407 
23408 	/*
23409 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23410 	 * a longlong, which may contain resolution down to nanoseconds.
23411 	 * The current time will either be a 32-bit or a 64-bit quantity.
23412 	 * XOR the two together in a 64-bit result variable.
23413 	 * Convert the result to a 32-bit value by multiplying the high-order
23414 	 * 32-bits by the low-order 32-bits.
23415 	 */
23416 
23417 	hrt = gethrtime();
23418 	(void) drv_getparm(TIME, &wallclock);
23419 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23420 	mutex_enter(&tcp_random_lock);
23421 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23422 	    (result & 0xffffffff);
23423 
23424 	for (i = 1; i < DEG_3; i++)
23425 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23426 		    + 12345;
23427 	tcp_random_fptr = &tcp_random_state[SEP_3];
23428 	tcp_random_rptr = &tcp_random_state[0];
23429 	mutex_exit(&tcp_random_lock);
23430 	for (i = 0; i < 10 * DEG_3; i++)
23431 		(void) tcp_random();
23432 }
23433 
23434 /*
23435  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23436  * This range is selected to be approximately centered on TCP_ISS / 2,
23437  * and easy to compute. We get this value by generating a 32-bit random
23438  * number, selecting out the high-order 17 bits, and then adding one so
23439  * that we never return zero.
23440  */
23441 int
23442 tcp_random(void)
23443 {
23444 	int i;
23445 
23446 	mutex_enter(&tcp_random_lock);
23447 	*tcp_random_fptr += *tcp_random_rptr;
23448 
23449 	/*
23450 	 * The high-order bits are more random than the low-order bits,
23451 	 * so we select out the high-order 17 bits and add one so that
23452 	 * we never return zero.
23453 	 */
23454 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23455 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23456 		tcp_random_fptr = tcp_random_state;
23457 		++tcp_random_rptr;
23458 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23459 		tcp_random_rptr = tcp_random_state;
23460 
23461 	mutex_exit(&tcp_random_lock);
23462 	return (i);
23463 }
23464 
23465 static int
23466 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23467     int *t_errorp, int *sys_errorp)
23468 {
23469 	int error;
23470 	int is_absreq_failure;
23471 	t_scalar_t *opt_lenp;
23472 	t_scalar_t opt_offset;
23473 	int prim_type;
23474 	struct T_conn_req *tcreqp;
23475 	struct T_conn_res *tcresp;
23476 	cred_t *cr;
23477 
23478 	/*
23479 	 * All Solaris components should pass a db_credp
23480 	 * for this TPI message, hence we ASSERT.
23481 	 * But in case there is some other M_PROTO that looks
23482 	 * like a TPI message sent by some other kernel
23483 	 * component, we check and return an error.
23484 	 */
23485 	cr = msg_getcred(mp, NULL);
23486 	ASSERT(cr != NULL);
23487 	if (cr == NULL)
23488 		return (-1);
23489 
23490 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23491 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23492 	    prim_type == T_CONN_RES);
23493 
23494 	switch (prim_type) {
23495 	case T_CONN_REQ:
23496 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23497 		opt_offset = tcreqp->OPT_offset;
23498 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23499 		break;
23500 	case O_T_CONN_RES:
23501 	case T_CONN_RES:
23502 		tcresp = (struct T_conn_res *)mp->b_rptr;
23503 		opt_offset = tcresp->OPT_offset;
23504 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23505 		break;
23506 	}
23507 
23508 	*t_errorp = 0;
23509 	*sys_errorp = 0;
23510 	*do_disconnectp = 0;
23511 
23512 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23513 	    opt_offset, cr, &tcp_opt_obj,
23514 	    NULL, &is_absreq_failure);
23515 
23516 	switch (error) {
23517 	case  0:		/* no error */
23518 		ASSERT(is_absreq_failure == 0);
23519 		return (0);
23520 	case ENOPROTOOPT:
23521 		*t_errorp = TBADOPT;
23522 		break;
23523 	case EACCES:
23524 		*t_errorp = TACCES;
23525 		break;
23526 	default:
23527 		*t_errorp = TSYSERR; *sys_errorp = error;
23528 		break;
23529 	}
23530 	if (is_absreq_failure != 0) {
23531 		/*
23532 		 * The connection request should get the local ack
23533 		 * T_OK_ACK and then a T_DISCON_IND.
23534 		 */
23535 		*do_disconnectp = 1;
23536 	}
23537 	return (-1);
23538 }
23539 
23540 /*
23541  * Split this function out so that if the secret changes, I'm okay.
23542  *
23543  * Initialize the tcp_iss_cookie and tcp_iss_key.
23544  */
23545 
23546 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23547 
23548 static void
23549 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
23550 {
23551 	struct {
23552 		int32_t current_time;
23553 		uint32_t randnum;
23554 		uint16_t pad;
23555 		uint8_t ether[6];
23556 		uint8_t passwd[PASSWD_SIZE];
23557 	} tcp_iss_cookie;
23558 	time_t t;
23559 
23560 	/*
23561 	 * Start with the current absolute time.
23562 	 */
23563 	(void) drv_getparm(TIME, &t);
23564 	tcp_iss_cookie.current_time = t;
23565 
23566 	/*
23567 	 * XXX - Need a more random number per RFC 1750, not this crap.
23568 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23569 	 */
23570 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23571 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23572 
23573 	/*
23574 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23575 	 * as a good template.
23576 	 */
23577 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23578 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23579 
23580 	/*
23581 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23582 	 */
23583 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23584 
23585 	/*
23586 	 * See 4010593 if this section becomes a problem again,
23587 	 * but the local ethernet address is useful here.
23588 	 */
23589 	(void) localetheraddr(NULL,
23590 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23591 
23592 	/*
23593 	 * Hash 'em all together.  The MD5Final is called per-connection.
23594 	 */
23595 	mutex_enter(&tcps->tcps_iss_key_lock);
23596 	MD5Init(&tcps->tcps_iss_key);
23597 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
23598 	    sizeof (tcp_iss_cookie));
23599 	mutex_exit(&tcps->tcps_iss_key_lock);
23600 }
23601 
23602 /*
23603  * Set the RFC 1948 pass phrase
23604  */
23605 /* ARGSUSED */
23606 static int
23607 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23608     cred_t *cr)
23609 {
23610 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23611 
23612 	/*
23613 	 * Basically, value contains a new pass phrase.  Pass it along!
23614 	 */
23615 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
23616 	return (0);
23617 }
23618 
23619 /* ARGSUSED */
23620 static int
23621 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23622 {
23623 	bzero(buf, sizeof (tcp_sack_info_t));
23624 	return (0);
23625 }
23626 
23627 /* ARGSUSED */
23628 static int
23629 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23630 {
23631 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23632 	return (0);
23633 }
23634 
23635 /*
23636  * Make sure we wait until the default queue is setup, yet allow
23637  * tcp_g_q_create() to open a TCP stream.
23638  * We need to allow tcp_g_q_create() do do an open
23639  * of tcp, hence we compare curhread.
23640  * All others have to wait until the tcps_g_q has been
23641  * setup.
23642  */
23643 void
23644 tcp_g_q_setup(tcp_stack_t *tcps)
23645 {
23646 	mutex_enter(&tcps->tcps_g_q_lock);
23647 	if (tcps->tcps_g_q != NULL) {
23648 		mutex_exit(&tcps->tcps_g_q_lock);
23649 		return;
23650 	}
23651 	if (tcps->tcps_g_q_creator == NULL) {
23652 		/* This thread will set it up */
23653 		tcps->tcps_g_q_creator = curthread;
23654 		mutex_exit(&tcps->tcps_g_q_lock);
23655 		tcp_g_q_create(tcps);
23656 		mutex_enter(&tcps->tcps_g_q_lock);
23657 		ASSERT(tcps->tcps_g_q_creator == curthread);
23658 		tcps->tcps_g_q_creator = NULL;
23659 		cv_signal(&tcps->tcps_g_q_cv);
23660 		ASSERT(tcps->tcps_g_q != NULL);
23661 		mutex_exit(&tcps->tcps_g_q_lock);
23662 		return;
23663 	}
23664 	/* Everybody but the creator has to wait */
23665 	if (tcps->tcps_g_q_creator != curthread) {
23666 		while (tcps->tcps_g_q == NULL)
23667 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
23668 	}
23669 	mutex_exit(&tcps->tcps_g_q_lock);
23670 }
23671 
23672 #define	IP	"ip"
23673 
23674 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
23675 
23676 /*
23677  * Create a default tcp queue here instead of in strplumb
23678  */
23679 void
23680 tcp_g_q_create(tcp_stack_t *tcps)
23681 {
23682 	int error;
23683 	ldi_handle_t	lh = NULL;
23684 	ldi_ident_t	li = NULL;
23685 	int		rval;
23686 	cred_t		*cr;
23687 	major_t IP_MAJ;
23688 
23689 #ifdef NS_DEBUG
23690 	(void) printf("tcp_g_q_create()\n");
23691 #endif
23692 
23693 	IP_MAJ = ddi_name_to_major(IP);
23694 
23695 	ASSERT(tcps->tcps_g_q_creator == curthread);
23696 
23697 	error = ldi_ident_from_major(IP_MAJ, &li);
23698 	if (error) {
23699 #ifdef DEBUG
23700 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
23701 		    error);
23702 #endif
23703 		return;
23704 	}
23705 
23706 	cr = zone_get_kcred(netstackid_to_zoneid(
23707 	    tcps->tcps_netstack->netstack_stackid));
23708 	ASSERT(cr != NULL);
23709 	/*
23710 	 * We set the tcp default queue to IPv6 because IPv4 falls
23711 	 * back to IPv6 when it can't find a client, but
23712 	 * IPv6 does not fall back to IPv4.
23713 	 */
23714 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
23715 	if (error) {
23716 #ifdef DEBUG
23717 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
23718 		    error);
23719 #endif
23720 		goto out;
23721 	}
23722 
23723 	/*
23724 	 * This ioctl causes the tcp framework to cache a pointer to
23725 	 * this stream, so we don't want to close the stream after
23726 	 * this operation.
23727 	 * Use the kernel credentials that are for the zone we're in.
23728 	 */
23729 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
23730 	    (intptr_t)0, FKIOCTL, cr, &rval);
23731 	if (error) {
23732 #ifdef DEBUG
23733 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
23734 		    "error %d\n", error);
23735 #endif
23736 		goto out;
23737 	}
23738 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
23739 	lh = NULL;
23740 out:
23741 	/* Close layered handles */
23742 	if (li)
23743 		ldi_ident_release(li);
23744 	/* Keep cred around until _inactive needs it */
23745 	tcps->tcps_g_q_cr = cr;
23746 }
23747 
23748 /*
23749  * We keep tcp_g_q set until all other tcp_t's in the zone
23750  * has gone away, and then when tcp_g_q_inactive() is called
23751  * we clear it.
23752  */
23753 void
23754 tcp_g_q_destroy(tcp_stack_t *tcps)
23755 {
23756 #ifdef NS_DEBUG
23757 	(void) printf("tcp_g_q_destroy()for stack %d\n",
23758 	    tcps->tcps_netstack->netstack_stackid);
23759 #endif
23760 
23761 	if (tcps->tcps_g_q == NULL) {
23762 		return;	/* Nothing to cleanup */
23763 	}
23764 	/*
23765 	 * Drop reference corresponding to the default queue.
23766 	 * This reference was added from tcp_open when the default queue
23767 	 * was created, hence we compensate for this extra drop in
23768 	 * tcp_g_q_close. If the refcnt drops to zero here it means
23769 	 * the default queue was the last one to be open, in which
23770 	 * case, then tcp_g_q_inactive will be
23771 	 * called as a result of the refrele.
23772 	 */
23773 	TCPS_REFRELE(tcps);
23774 }
23775 
23776 /*
23777  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23778  * Run by tcp_q_q_inactive using a taskq.
23779  */
23780 static void
23781 tcp_g_q_close(void *arg)
23782 {
23783 	tcp_stack_t *tcps = arg;
23784 	int error;
23785 	ldi_handle_t	lh = NULL;
23786 	ldi_ident_t	li = NULL;
23787 	cred_t		*cr;
23788 	major_t IP_MAJ;
23789 
23790 	IP_MAJ = ddi_name_to_major(IP);
23791 
23792 #ifdef NS_DEBUG
23793 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
23794 	    tcps->tcps_netstack->netstack_stackid,
23795 	    tcps->tcps_netstack->netstack_refcnt);
23796 #endif
23797 	lh = tcps->tcps_g_q_lh;
23798 	if (lh == NULL)
23799 		return;	/* Nothing to cleanup */
23800 
23801 	ASSERT(tcps->tcps_refcnt == 1);
23802 	ASSERT(tcps->tcps_g_q != NULL);
23803 
23804 	error = ldi_ident_from_major(IP_MAJ, &li);
23805 	if (error) {
23806 #ifdef DEBUG
23807 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
23808 		    error);
23809 #endif
23810 		return;
23811 	}
23812 
23813 	cr = tcps->tcps_g_q_cr;
23814 	tcps->tcps_g_q_cr = NULL;
23815 	ASSERT(cr != NULL);
23816 
23817 	/*
23818 	 * Make sure we can break the recursion when tcp_close decrements
23819 	 * the reference count causing g_q_inactive to be called again.
23820 	 */
23821 	tcps->tcps_g_q_lh = NULL;
23822 
23823 	/* close the default queue */
23824 	(void) ldi_close(lh, FREAD|FWRITE, cr);
23825 	/*
23826 	 * At this point in time tcps and the rest of netstack_t might
23827 	 * have been deleted.
23828 	 */
23829 	tcps = NULL;
23830 
23831 	/* Close layered handles */
23832 	ldi_ident_release(li);
23833 	crfree(cr);
23834 }
23835 
23836 /*
23837  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23838  *
23839  * Have to ensure that the ldi routines are not used by an
23840  * interrupt thread by using a taskq.
23841  */
23842 void
23843 tcp_g_q_inactive(tcp_stack_t *tcps)
23844 {
23845 	if (tcps->tcps_g_q_lh == NULL)
23846 		return;	/* Nothing to cleanup */
23847 
23848 	ASSERT(tcps->tcps_refcnt == 0);
23849 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
23850 
23851 	if (servicing_interrupt()) {
23852 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
23853 		    (void *) tcps, TQ_SLEEP);
23854 	} else {
23855 		tcp_g_q_close(tcps);
23856 	}
23857 }
23858 
23859 /*
23860  * Called by IP when IP is loaded into the kernel
23861  */
23862 void
23863 tcp_ddi_g_init(void)
23864 {
23865 	tcp_timercache = kmem_cache_create("tcp_timercache",
23866 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23867 	    NULL, NULL, NULL, NULL, NULL, 0);
23868 
23869 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23870 	    sizeof (tcp_sack_info_t), 0,
23871 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23872 
23873 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23874 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23875 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23876 
23877 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23878 
23879 	/* Initialize the random number generator */
23880 	tcp_random_init();
23881 
23882 	/* A single callback independently of how many netstacks we have */
23883 	ip_squeue_init(tcp_squeue_add);
23884 
23885 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
23886 
23887 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
23888 	    TASKQ_PREPOPULATE);
23889 
23890 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
23891 
23892 	/*
23893 	 * We want to be informed each time a stack is created or
23894 	 * destroyed in the kernel, so we can maintain the
23895 	 * set of tcp_stack_t's.
23896 	 */
23897 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
23898 	    tcp_stack_fini);
23899 }
23900 
23901 
23902 #define	INET_NAME	"ip"
23903 
23904 /*
23905  * Initialize the TCP stack instance.
23906  */
23907 static void *
23908 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
23909 {
23910 	tcp_stack_t	*tcps;
23911 	tcpparam_t	*pa;
23912 	int		i;
23913 	int		error = 0;
23914 	major_t		major;
23915 
23916 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
23917 	tcps->tcps_netstack = ns;
23918 
23919 	/* Initialize locks */
23920 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23921 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
23922 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23923 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23924 
23925 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
23926 	tcps->tcps_g_epriv_ports[0] = 2049;
23927 	tcps->tcps_g_epriv_ports[1] = 4045;
23928 	tcps->tcps_min_anonpriv_port = 512;
23929 
23930 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
23931 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
23932 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
23933 	    TCP_FANOUT_SIZE, KM_SLEEP);
23934 
23935 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
23936 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
23937 		    MUTEX_DEFAULT, NULL);
23938 	}
23939 
23940 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
23941 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
23942 		    MUTEX_DEFAULT, NULL);
23943 	}
23944 
23945 	/* TCP's IPsec code calls the packet dropper. */
23946 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
23947 
23948 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
23949 	tcps->tcps_params = pa;
23950 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
23951 
23952 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
23953 	    A_CNT(lcl_tcp_param_arr), tcps);
23954 
23955 	/*
23956 	 * Note: To really walk the device tree you need the devinfo
23957 	 * pointer to your device which is only available after probe/attach.
23958 	 * The following is safe only because it uses ddi_root_node()
23959 	 */
23960 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23961 	    tcp_opt_obj.odb_opt_arr_cnt);
23962 
23963 	/*
23964 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23965 	 * by the boot scripts.
23966 	 *
23967 	 * Use NULL name, as the name is caught by the new lockstats.
23968 	 *
23969 	 * Initialize with some random, non-guessable string, like the global
23970 	 * T_INFO_ACK.
23971 	 */
23972 
23973 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23974 	    sizeof (tcp_g_t_info_ack), tcps);
23975 
23976 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
23977 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
23978 
23979 	major = mod_name_to_major(INET_NAME);
23980 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
23981 	ASSERT(error == 0);
23982 	return (tcps);
23983 }
23984 
23985 /*
23986  * Called when the IP module is about to be unloaded.
23987  */
23988 void
23989 tcp_ddi_g_destroy(void)
23990 {
23991 	tcp_g_kstat_fini(tcp_g_kstat);
23992 	tcp_g_kstat = NULL;
23993 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
23994 
23995 	mutex_destroy(&tcp_random_lock);
23996 
23997 	kmem_cache_destroy(tcp_timercache);
23998 	kmem_cache_destroy(tcp_sack_info_cache);
23999 	kmem_cache_destroy(tcp_iphc_cache);
24000 
24001 	netstack_unregister(NS_TCP);
24002 	taskq_destroy(tcp_taskq);
24003 }
24004 
24005 /*
24006  * Shut down the TCP stack instance.
24007  */
24008 /* ARGSUSED */
24009 static void
24010 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24011 {
24012 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24013 
24014 	tcp_g_q_destroy(tcps);
24015 }
24016 
24017 /*
24018  * Free the TCP stack instance.
24019  */
24020 static void
24021 tcp_stack_fini(netstackid_t stackid, void *arg)
24022 {
24023 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24024 	int i;
24025 
24026 	nd_free(&tcps->tcps_g_nd);
24027 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24028 	tcps->tcps_params = NULL;
24029 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24030 	tcps->tcps_wroff_xtra_param = NULL;
24031 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24032 	tcps->tcps_mdt_head_param = NULL;
24033 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24034 	tcps->tcps_mdt_tail_param = NULL;
24035 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24036 	tcps->tcps_mdt_max_pbufs_param = NULL;
24037 
24038 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24039 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24040 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24041 	}
24042 
24043 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24044 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24045 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24046 	}
24047 
24048 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24049 	tcps->tcps_bind_fanout = NULL;
24050 
24051 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24052 	tcps->tcps_acceptor_fanout = NULL;
24053 
24054 	mutex_destroy(&tcps->tcps_iss_key_lock);
24055 	mutex_destroy(&tcps->tcps_g_q_lock);
24056 	cv_destroy(&tcps->tcps_g_q_cv);
24057 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24058 
24059 	ip_drop_unregister(&tcps->tcps_dropper);
24060 
24061 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24062 	tcps->tcps_kstat = NULL;
24063 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24064 
24065 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24066 	tcps->tcps_mibkp = NULL;
24067 
24068 	ldi_ident_release(tcps->tcps_ldi_ident);
24069 	kmem_free(tcps, sizeof (*tcps));
24070 }
24071 
24072 /*
24073  * Generate ISS, taking into account NDD changes may happen halfway through.
24074  * (If the iss is not zero, set it.)
24075  */
24076 
24077 static void
24078 tcp_iss_init(tcp_t *tcp)
24079 {
24080 	MD5_CTX context;
24081 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24082 	uint32_t answer[4];
24083 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24084 
24085 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24086 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24087 	switch (tcps->tcps_strong_iss) {
24088 	case 2:
24089 		mutex_enter(&tcps->tcps_iss_key_lock);
24090 		context = tcps->tcps_iss_key;
24091 		mutex_exit(&tcps->tcps_iss_key_lock);
24092 		arg.ports = tcp->tcp_ports;
24093 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24094 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24095 			    &arg.src);
24096 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24097 			    &arg.dst);
24098 		} else {
24099 			arg.src = tcp->tcp_ip6h->ip6_src;
24100 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24101 		}
24102 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24103 		MD5Final((uchar_t *)answer, &context);
24104 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24105 		/*
24106 		 * Now that we've hashed into a unique per-connection sequence
24107 		 * space, add a random increment per strong_iss == 1.  So I
24108 		 * guess we'll have to...
24109 		 */
24110 		/* FALLTHRU */
24111 	case 1:
24112 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24113 		break;
24114 	default:
24115 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24116 		break;
24117 	}
24118 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24119 	tcp->tcp_fss = tcp->tcp_iss - 1;
24120 	tcp->tcp_suna = tcp->tcp_iss;
24121 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24122 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24123 	tcp->tcp_csuna = tcp->tcp_snxt;
24124 }
24125 
24126 /*
24127  * Exported routine for extracting active tcp connection status.
24128  *
24129  * This is used by the Solaris Cluster Networking software to
24130  * gather a list of connections that need to be forwarded to
24131  * specific nodes in the cluster when configuration changes occur.
24132  *
24133  * The callback is invoked for each tcp_t structure from all netstacks,
24134  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24135  * from the netstack with the specified stack_id. Returning
24136  * non-zero from the callback routine terminates the search.
24137  */
24138 int
24139 cl_tcp_walk_list(netstackid_t stack_id,
24140     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24141 {
24142 	netstack_handle_t nh;
24143 	netstack_t *ns;
24144 	int ret = 0;
24145 
24146 	if (stack_id >= 0) {
24147 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24148 			return (EINVAL);
24149 
24150 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24151 		    ns->netstack_tcp);
24152 		netstack_rele(ns);
24153 		return (ret);
24154 	}
24155 
24156 	netstack_next_init(&nh);
24157 	while ((ns = netstack_next(&nh)) != NULL) {
24158 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24159 		    ns->netstack_tcp);
24160 		netstack_rele(ns);
24161 	}
24162 	netstack_next_fini(&nh);
24163 	return (ret);
24164 }
24165 
24166 static int
24167 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
24168     tcp_stack_t *tcps)
24169 {
24170 	tcp_t *tcp;
24171 	cl_tcp_info_t	cl_tcpi;
24172 	connf_t	*connfp;
24173 	conn_t	*connp;
24174 	int	i;
24175 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24176 
24177 	ASSERT(callback != NULL);
24178 
24179 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24180 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
24181 		connp = NULL;
24182 
24183 		while ((connp =
24184 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24185 
24186 			tcp = connp->conn_tcp;
24187 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24188 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24189 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24190 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24191 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24192 			/*
24193 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24194 			 * addresses. They are copied implicitly below as
24195 			 * mapped addresses.
24196 			 */
24197 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24198 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24199 				cl_tcpi.cl_tcpi_faddr =
24200 				    tcp->tcp_ipha->ipha_dst;
24201 			} else {
24202 				cl_tcpi.cl_tcpi_faddr_v6 =
24203 				    tcp->tcp_ip6h->ip6_dst;
24204 			}
24205 
24206 			/*
24207 			 * If the callback returns non-zero
24208 			 * we terminate the traversal.
24209 			 */
24210 			if ((*callback)(&cl_tcpi, arg) != 0) {
24211 				CONN_DEC_REF(tcp->tcp_connp);
24212 				return (1);
24213 			}
24214 		}
24215 	}
24216 
24217 	return (0);
24218 }
24219 
24220 /*
24221  * Macros used for accessing the different types of sockaddr
24222  * structures inside a tcp_ioc_abort_conn_t.
24223  */
24224 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24225 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24226 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24227 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24228 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24229 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24230 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24231 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24232 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24233 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24234 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24235 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24236 
24237 /*
24238  * Return the correct error code to mimic the behavior
24239  * of a connection reset.
24240  */
24241 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24242 		switch ((state)) {		\
24243 		case TCPS_SYN_SENT:		\
24244 		case TCPS_SYN_RCVD:		\
24245 			(err) = ECONNREFUSED;	\
24246 			break;			\
24247 		case TCPS_ESTABLISHED:		\
24248 		case TCPS_FIN_WAIT_1:		\
24249 		case TCPS_FIN_WAIT_2:		\
24250 		case TCPS_CLOSE_WAIT:		\
24251 			(err) = ECONNRESET;	\
24252 			break;			\
24253 		case TCPS_CLOSING:		\
24254 		case TCPS_LAST_ACK:		\
24255 		case TCPS_TIME_WAIT:		\
24256 			(err) = 0;		\
24257 			break;			\
24258 		default:			\
24259 			(err) = ENXIO;		\
24260 		}				\
24261 	}
24262 
24263 /*
24264  * Check if a tcp structure matches the info in acp.
24265  */
24266 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24267 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24268 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24269 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24270 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24271 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24272 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24273 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24274 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24275 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24276 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24277 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24278 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24279 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24280 	&(tcp)->tcp_ip_src_v6)) &&				\
24281 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24282 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24283 	&(tcp)->tcp_remote_v6)) &&				\
24284 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24285 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24286 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24287 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24288 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24289 	(acp)->ac_end >= (tcp)->tcp_state))
24290 
24291 #define	TCP_AC_MATCH(acp, tcp)					\
24292 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24293 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24294 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24295 
24296 /*
24297  * Build a message containing a tcp_ioc_abort_conn_t structure
24298  * which is filled in with information from acp and tp.
24299  */
24300 static mblk_t *
24301 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24302 {
24303 	mblk_t *mp;
24304 	tcp_ioc_abort_conn_t *tacp;
24305 
24306 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24307 	if (mp == NULL)
24308 		return (NULL);
24309 
24310 	mp->b_datap->db_type = M_CTL;
24311 
24312 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24313 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24314 	    sizeof (uint32_t));
24315 
24316 	tacp->ac_start = acp->ac_start;
24317 	tacp->ac_end = acp->ac_end;
24318 	tacp->ac_zoneid = acp->ac_zoneid;
24319 
24320 	if (acp->ac_local.ss_family == AF_INET) {
24321 		tacp->ac_local.ss_family = AF_INET;
24322 		tacp->ac_remote.ss_family = AF_INET;
24323 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24324 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24325 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24326 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24327 	} else {
24328 		tacp->ac_local.ss_family = AF_INET6;
24329 		tacp->ac_remote.ss_family = AF_INET6;
24330 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24331 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24332 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24333 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24334 	}
24335 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24336 	return (mp);
24337 }
24338 
24339 /*
24340  * Print a tcp_ioc_abort_conn_t structure.
24341  */
24342 static void
24343 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24344 {
24345 	char lbuf[128];
24346 	char rbuf[128];
24347 	sa_family_t af;
24348 	in_port_t lport, rport;
24349 	ushort_t logflags;
24350 
24351 	af = acp->ac_local.ss_family;
24352 
24353 	if (af == AF_INET) {
24354 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24355 		    lbuf, 128);
24356 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24357 		    rbuf, 128);
24358 		lport = ntohs(TCP_AC_V4LPORT(acp));
24359 		rport = ntohs(TCP_AC_V4RPORT(acp));
24360 	} else {
24361 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24362 		    lbuf, 128);
24363 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24364 		    rbuf, 128);
24365 		lport = ntohs(TCP_AC_V6LPORT(acp));
24366 		rport = ntohs(TCP_AC_V6RPORT(acp));
24367 	}
24368 
24369 	logflags = SL_TRACE | SL_NOTE;
24370 	/*
24371 	 * Don't print this message to the console if the operation was done
24372 	 * to a non-global zone.
24373 	 */
24374 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24375 		logflags |= SL_CONSOLE;
24376 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24377 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24378 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24379 	    acp->ac_start, acp->ac_end);
24380 }
24381 
24382 /*
24383  * Called inside tcp_rput when a message built using
24384  * tcp_ioctl_abort_build_msg is put into a queue.
24385  * Note that when we get here there is no wildcard in acp any more.
24386  */
24387 static void
24388 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24389 {
24390 	tcp_ioc_abort_conn_t *acp;
24391 
24392 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24393 	if (tcp->tcp_state <= acp->ac_end) {
24394 		/*
24395 		 * If we get here, we are already on the correct
24396 		 * squeue. This ioctl follows the following path
24397 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24398 		 * ->tcp_ioctl_abort->squeue_enter (if on a
24399 		 * different squeue)
24400 		 */
24401 		int errcode;
24402 
24403 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24404 		(void) tcp_clean_death(tcp, errcode, 26);
24405 	}
24406 	freemsg(mp);
24407 }
24408 
24409 /*
24410  * Abort all matching connections on a hash chain.
24411  */
24412 static int
24413 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24414     boolean_t exact, tcp_stack_t *tcps)
24415 {
24416 	int nmatch, err = 0;
24417 	tcp_t *tcp;
24418 	MBLKP mp, last, listhead = NULL;
24419 	conn_t	*tconnp;
24420 	connf_t	*connfp;
24421 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24422 
24423 	connfp = &ipst->ips_ipcl_conn_fanout[index];
24424 
24425 startover:
24426 	nmatch = 0;
24427 
24428 	mutex_enter(&connfp->connf_lock);
24429 	for (tconnp = connfp->connf_head; tconnp != NULL;
24430 	    tconnp = tconnp->conn_next) {
24431 		tcp = tconnp->conn_tcp;
24432 		if (TCP_AC_MATCH(acp, tcp)) {
24433 			CONN_INC_REF(tcp->tcp_connp);
24434 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24435 			if (mp == NULL) {
24436 				err = ENOMEM;
24437 				CONN_DEC_REF(tcp->tcp_connp);
24438 				break;
24439 			}
24440 			mp->b_prev = (mblk_t *)tcp;
24441 
24442 			if (listhead == NULL) {
24443 				listhead = mp;
24444 				last = mp;
24445 			} else {
24446 				last->b_next = mp;
24447 				last = mp;
24448 			}
24449 			nmatch++;
24450 			if (exact)
24451 				break;
24452 		}
24453 
24454 		/* Avoid holding lock for too long. */
24455 		if (nmatch >= 500)
24456 			break;
24457 	}
24458 	mutex_exit(&connfp->connf_lock);
24459 
24460 	/* Pass mp into the correct tcp */
24461 	while ((mp = listhead) != NULL) {
24462 		listhead = listhead->b_next;
24463 		tcp = (tcp_t *)mp->b_prev;
24464 		mp->b_next = mp->b_prev = NULL;
24465 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
24466 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
24467 	}
24468 
24469 	*count += nmatch;
24470 	if (nmatch >= 500 && err == 0)
24471 		goto startover;
24472 	return (err);
24473 }
24474 
24475 /*
24476  * Abort all connections that matches the attributes specified in acp.
24477  */
24478 static int
24479 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
24480 {
24481 	sa_family_t af;
24482 	uint32_t  ports;
24483 	uint16_t *pports;
24484 	int err = 0, count = 0;
24485 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24486 	int index = -1;
24487 	ushort_t logflags;
24488 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24489 
24490 	af = acp->ac_local.ss_family;
24491 
24492 	if (af == AF_INET) {
24493 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24494 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24495 			pports = (uint16_t *)&ports;
24496 			pports[1] = TCP_AC_V4LPORT(acp);
24497 			pports[0] = TCP_AC_V4RPORT(acp);
24498 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24499 		}
24500 	} else {
24501 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24502 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24503 			pports = (uint16_t *)&ports;
24504 			pports[1] = TCP_AC_V6LPORT(acp);
24505 			pports[0] = TCP_AC_V6RPORT(acp);
24506 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24507 		}
24508 	}
24509 
24510 	/*
24511 	 * For cases where remote addr, local port, and remote port are non-
24512 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24513 	 */
24514 	if (index != -1) {
24515 		err = tcp_ioctl_abort_bucket(acp, index,
24516 		    &count, exact, tcps);
24517 	} else {
24518 		/*
24519 		 * loop through all entries for wildcard case
24520 		 */
24521 		for (index = 0;
24522 		    index < ipst->ips_ipcl_conn_fanout_size;
24523 		    index++) {
24524 			err = tcp_ioctl_abort_bucket(acp, index,
24525 			    &count, exact, tcps);
24526 			if (err != 0)
24527 				break;
24528 		}
24529 	}
24530 
24531 	logflags = SL_TRACE | SL_NOTE;
24532 	/*
24533 	 * Don't print this message to the console if the operation was done
24534 	 * to a non-global zone.
24535 	 */
24536 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24537 		logflags |= SL_CONSOLE;
24538 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24539 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24540 	if (err == 0 && count == 0)
24541 		err = ENOENT;
24542 	return (err);
24543 }
24544 
24545 /*
24546  * Process the TCP_IOC_ABORT_CONN ioctl request.
24547  */
24548 static void
24549 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24550 {
24551 	int	err;
24552 	IOCP    iocp;
24553 	MBLKP   mp1;
24554 	sa_family_t laf, raf;
24555 	tcp_ioc_abort_conn_t *acp;
24556 	zone_t		*zptr;
24557 	conn_t		*connp = Q_TO_CONN(q);
24558 	zoneid_t	zoneid = connp->conn_zoneid;
24559 	tcp_t		*tcp = connp->conn_tcp;
24560 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24561 
24562 	iocp = (IOCP)mp->b_rptr;
24563 
24564 	if ((mp1 = mp->b_cont) == NULL ||
24565 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24566 		err = EINVAL;
24567 		goto out;
24568 	}
24569 
24570 	/* check permissions */
24571 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
24572 		err = EPERM;
24573 		goto out;
24574 	}
24575 
24576 	if (mp1->b_cont != NULL) {
24577 		freemsg(mp1->b_cont);
24578 		mp1->b_cont = NULL;
24579 	}
24580 
24581 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24582 	laf = acp->ac_local.ss_family;
24583 	raf = acp->ac_remote.ss_family;
24584 
24585 	/* check that a zone with the supplied zoneid exists */
24586 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24587 		zptr = zone_find_by_id(zoneid);
24588 		if (zptr != NULL) {
24589 			zone_rele(zptr);
24590 		} else {
24591 			err = EINVAL;
24592 			goto out;
24593 		}
24594 	}
24595 
24596 	/*
24597 	 * For exclusive stacks we set the zoneid to zero
24598 	 * to make TCP operate as if in the global zone.
24599 	 */
24600 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
24601 		acp->ac_zoneid = GLOBAL_ZONEID;
24602 
24603 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24604 	    acp->ac_start > acp->ac_end || laf != raf ||
24605 	    (laf != AF_INET && laf != AF_INET6)) {
24606 		err = EINVAL;
24607 		goto out;
24608 	}
24609 
24610 	tcp_ioctl_abort_dump(acp);
24611 	err = tcp_ioctl_abort(acp, tcps);
24612 
24613 out:
24614 	if (mp1 != NULL) {
24615 		freemsg(mp1);
24616 		mp->b_cont = NULL;
24617 	}
24618 
24619 	if (err != 0)
24620 		miocnak(q, mp, 0, err);
24621 	else
24622 		miocack(q, mp, 0, 0);
24623 }
24624 
24625 /*
24626  * tcp_time_wait_processing() handles processing of incoming packets when
24627  * the tcp is in the TIME_WAIT state.
24628  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24629  * on the time wait list.
24630  */
24631 void
24632 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24633     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24634 {
24635 	int32_t		bytes_acked;
24636 	int32_t		gap;
24637 	int32_t		rgap;
24638 	tcp_opt_t	tcpopt;
24639 	uint_t		flags;
24640 	uint32_t	new_swnd = 0;
24641 	conn_t		*connp;
24642 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24643 
24644 	BUMP_LOCAL(tcp->tcp_ibsegs);
24645 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
24646 
24647 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24648 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24649 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24650 	if (tcp->tcp_snd_ts_ok) {
24651 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24652 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24653 			    tcp->tcp_rnxt, TH_ACK);
24654 			goto done;
24655 		}
24656 	}
24657 	gap = seg_seq - tcp->tcp_rnxt;
24658 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24659 	if (gap < 0) {
24660 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
24661 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
24662 		    (seg_len > -gap ? -gap : seg_len));
24663 		seg_len += gap;
24664 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24665 			if (flags & TH_RST) {
24666 				goto done;
24667 			}
24668 			if ((flags & TH_FIN) && seg_len == -1) {
24669 				/*
24670 				 * When TCP receives a duplicate FIN in
24671 				 * TIME_WAIT state, restart the 2 MSL timer.
24672 				 * See page 73 in RFC 793. Make sure this TCP
24673 				 * is already on the TIME_WAIT list. If not,
24674 				 * just restart the timer.
24675 				 */
24676 				if (TCP_IS_DETACHED(tcp)) {
24677 					if (tcp_time_wait_remove(tcp, NULL) ==
24678 					    B_TRUE) {
24679 						tcp_time_wait_append(tcp);
24680 						TCP_DBGSTAT(tcps,
24681 						    tcp_rput_time_wait);
24682 					}
24683 				} else {
24684 					ASSERT(tcp != NULL);
24685 					TCP_TIMER_RESTART(tcp,
24686 					    tcps->tcps_time_wait_interval);
24687 				}
24688 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24689 				    tcp->tcp_rnxt, TH_ACK);
24690 				goto done;
24691 			}
24692 			flags |=  TH_ACK_NEEDED;
24693 			seg_len = 0;
24694 			goto process_ack;
24695 		}
24696 
24697 		/* Fix seg_seq, and chew the gap off the front. */
24698 		seg_seq = tcp->tcp_rnxt;
24699 	}
24700 
24701 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24702 		/*
24703 		 * Make sure that when we accept the connection, pick
24704 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24705 		 * old connection.
24706 		 *
24707 		 * The next ISS generated is equal to tcp_iss_incr_extra
24708 		 * + ISS_INCR/2 + other components depending on the
24709 		 * value of tcp_strong_iss.  We pre-calculate the new
24710 		 * ISS here and compare with tcp_snxt to determine if
24711 		 * we need to make adjustment to tcp_iss_incr_extra.
24712 		 *
24713 		 * The above calculation is ugly and is a
24714 		 * waste of CPU cycles...
24715 		 */
24716 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
24717 		int32_t adj;
24718 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24719 
24720 		switch (tcps->tcps_strong_iss) {
24721 		case 2: {
24722 			/* Add time and MD5 components. */
24723 			uint32_t answer[4];
24724 			struct {
24725 				uint32_t ports;
24726 				in6_addr_t src;
24727 				in6_addr_t dst;
24728 			} arg;
24729 			MD5_CTX context;
24730 
24731 			mutex_enter(&tcps->tcps_iss_key_lock);
24732 			context = tcps->tcps_iss_key;
24733 			mutex_exit(&tcps->tcps_iss_key_lock);
24734 			arg.ports = tcp->tcp_ports;
24735 			/* We use MAPPED addresses in tcp_iss_init */
24736 			arg.src = tcp->tcp_ip_src_v6;
24737 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24738 				IN6_IPADDR_TO_V4MAPPED(
24739 				    tcp->tcp_ipha->ipha_dst,
24740 				    &arg.dst);
24741 			} else {
24742 				arg.dst =
24743 				    tcp->tcp_ip6h->ip6_dst;
24744 			}
24745 			MD5Update(&context, (uchar_t *)&arg,
24746 			    sizeof (arg));
24747 			MD5Final((uchar_t *)answer, &context);
24748 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24749 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24750 			break;
24751 		}
24752 		case 1:
24753 			/* Add time component and min random (i.e. 1). */
24754 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24755 			break;
24756 		default:
24757 			/* Add only time component. */
24758 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24759 			break;
24760 		}
24761 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24762 			/*
24763 			 * New ISS not guaranteed to be ISS_INCR/2
24764 			 * ahead of the current tcp_snxt, so add the
24765 			 * difference to tcp_iss_incr_extra.
24766 			 */
24767 			tcps->tcps_iss_incr_extra += adj;
24768 		}
24769 		/*
24770 		 * If tcp_clean_death() can not perform the task now,
24771 		 * drop the SYN packet and let the other side re-xmit.
24772 		 * Otherwise pass the SYN packet back in, since the
24773 		 * old tcp state has been cleaned up or freed.
24774 		 */
24775 		if (tcp_clean_death(tcp, 0, 27) == -1)
24776 			goto done;
24777 		/*
24778 		 * We will come back to tcp_rput_data
24779 		 * on the global queue. Packets destined
24780 		 * for the global queue will be checked
24781 		 * with global policy. But the policy for
24782 		 * this packet has already been checked as
24783 		 * this was destined for the detached
24784 		 * connection. We need to bypass policy
24785 		 * check this time by attaching a dummy
24786 		 * ipsec_in with ipsec_in_dont_check set.
24787 		 */
24788 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
24789 		if (connp != NULL) {
24790 			TCP_STAT(tcps, tcp_time_wait_syn_success);
24791 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24792 			return;
24793 		}
24794 		goto done;
24795 	}
24796 
24797 	/*
24798 	 * rgap is the amount of stuff received out of window.  A negative
24799 	 * value is the amount out of window.
24800 	 */
24801 	if (rgap < 0) {
24802 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
24803 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
24804 		/* Fix seg_len and make sure there is something left. */
24805 		seg_len += rgap;
24806 		if (seg_len <= 0) {
24807 			if (flags & TH_RST) {
24808 				goto done;
24809 			}
24810 			flags |=  TH_ACK_NEEDED;
24811 			seg_len = 0;
24812 			goto process_ack;
24813 		}
24814 	}
24815 	/*
24816 	 * Check whether we can update tcp_ts_recent.  This test is
24817 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24818 	 * Extensions for High Performance: An Update", Internet Draft.
24819 	 */
24820 	if (tcp->tcp_snd_ts_ok &&
24821 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24822 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24823 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24824 		tcp->tcp_last_rcv_lbolt = lbolt64;
24825 	}
24826 
24827 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24828 		/* Always ack out of order packets */
24829 		flags |= TH_ACK_NEEDED;
24830 		seg_len = 0;
24831 	} else if (seg_len > 0) {
24832 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
24833 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
24834 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
24835 	}
24836 	if (flags & TH_RST) {
24837 		(void) tcp_clean_death(tcp, 0, 28);
24838 		goto done;
24839 	}
24840 	if (flags & TH_SYN) {
24841 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24842 		    TH_RST|TH_ACK);
24843 		/*
24844 		 * Do not delete the TCP structure if it is in
24845 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24846 		 */
24847 		goto done;
24848 	}
24849 process_ack:
24850 	if (flags & TH_ACK) {
24851 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24852 		if (bytes_acked <= 0) {
24853 			if (bytes_acked == 0 && seg_len == 0 &&
24854 			    new_swnd == tcp->tcp_swnd)
24855 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
24856 		} else {
24857 			/* Acks something not sent */
24858 			flags |= TH_ACK_NEEDED;
24859 		}
24860 	}
24861 	if (flags & TH_ACK_NEEDED) {
24862 		/*
24863 		 * Time to send an ack for some reason.
24864 		 */
24865 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24866 		    tcp->tcp_rnxt, TH_ACK);
24867 	}
24868 done:
24869 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24870 		DB_CKSUMSTART(mp) = 0;
24871 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24872 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
24873 	}
24874 	freemsg(mp);
24875 }
24876 
24877 /*
24878  * TCP Timers Implementation.
24879  */
24880 timeout_id_t
24881 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24882 {
24883 	mblk_t *mp;
24884 	tcp_timer_t *tcpt;
24885 	tcp_t *tcp = connp->conn_tcp;
24886 
24887 	ASSERT(connp->conn_sqp != NULL);
24888 
24889 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
24890 
24891 	if (tcp->tcp_timercache == NULL) {
24892 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24893 	} else {
24894 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
24895 		mp = tcp->tcp_timercache;
24896 		tcp->tcp_timercache = mp->b_next;
24897 		mp->b_next = NULL;
24898 		ASSERT(mp->b_wptr == NULL);
24899 	}
24900 
24901 	CONN_INC_REF(connp);
24902 	tcpt = (tcp_timer_t *)mp->b_rptr;
24903 	tcpt->connp = connp;
24904 	tcpt->tcpt_proc = f;
24905 	/*
24906 	 * TCP timers are normal timeouts. Plus, they do not require more than
24907 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
24908 	 * rounding up the expiration to the next resolution boundary, we can
24909 	 * batch timers in the callout subsystem to make TCP timers more
24910 	 * efficient. The roundup also protects short timers from expiring too
24911 	 * early before they have a chance to be cancelled.
24912 	 */
24913 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
24914 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
24915 
24916 	return ((timeout_id_t)mp);
24917 }
24918 
24919 static void
24920 tcp_timer_callback(void *arg)
24921 {
24922 	mblk_t *mp = (mblk_t *)arg;
24923 	tcp_timer_t *tcpt;
24924 	conn_t	*connp;
24925 
24926 	tcpt = (tcp_timer_t *)mp->b_rptr;
24927 	connp = tcpt->connp;
24928 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
24929 	    SQ_FILL, SQTAG_TCP_TIMER);
24930 }
24931 
24932 static void
24933 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24934 {
24935 	tcp_timer_t *tcpt;
24936 	conn_t *connp = (conn_t *)arg;
24937 	tcp_t *tcp = connp->conn_tcp;
24938 
24939 	tcpt = (tcp_timer_t *)mp->b_rptr;
24940 	ASSERT(connp == tcpt->connp);
24941 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24942 
24943 	/*
24944 	 * If the TCP has reached the closed state, don't proceed any
24945 	 * further. This TCP logically does not exist on the system.
24946 	 * tcpt_proc could for example access queues, that have already
24947 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24948 	 */
24949 	if (tcp->tcp_state != TCPS_CLOSED) {
24950 		(*tcpt->tcpt_proc)(connp);
24951 	} else {
24952 		tcp->tcp_timer_tid = 0;
24953 	}
24954 	tcp_timer_free(connp->conn_tcp, mp);
24955 }
24956 
24957 /*
24958  * There is potential race with untimeout and the handler firing at the same
24959  * time. The mblock may be freed by the handler while we are trying to use
24960  * it. But since both should execute on the same squeue, this race should not
24961  * occur.
24962  */
24963 clock_t
24964 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24965 {
24966 	mblk_t	*mp = (mblk_t *)id;
24967 	tcp_timer_t *tcpt;
24968 	clock_t delta;
24969 
24970 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
24971 
24972 	if (mp == NULL)
24973 		return (-1);
24974 
24975 	tcpt = (tcp_timer_t *)mp->b_rptr;
24976 	ASSERT(tcpt->connp == connp);
24977 
24978 	delta = untimeout_default(tcpt->tcpt_tid, 0);
24979 
24980 	if (delta >= 0) {
24981 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
24982 		tcp_timer_free(connp->conn_tcp, mp);
24983 		CONN_DEC_REF(connp);
24984 	}
24985 
24986 	return (delta);
24987 }
24988 
24989 /*
24990  * Allocate space for the timer event. The allocation looks like mblk, but it is
24991  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24992  *
24993  * Dealing with failures: If we can't allocate from the timer cache we try
24994  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24995  * points to b_rptr.
24996  * If we can't allocate anything using allocb_tryhard(), we perform a last
24997  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24998  * save the actual allocation size in b_datap.
24999  */
25000 mblk_t *
25001 tcp_timermp_alloc(int kmflags)
25002 {
25003 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25004 	    kmflags & ~KM_PANIC);
25005 
25006 	if (mp != NULL) {
25007 		mp->b_next = mp->b_prev = NULL;
25008 		mp->b_rptr = (uchar_t *)(&mp[1]);
25009 		mp->b_wptr = NULL;
25010 		mp->b_datap = NULL;
25011 		mp->b_queue = NULL;
25012 		mp->b_cont = NULL;
25013 	} else if (kmflags & KM_PANIC) {
25014 		/*
25015 		 * Failed to allocate memory for the timer. Try allocating from
25016 		 * dblock caches.
25017 		 */
25018 		/* ipclassifier calls this from a constructor - hence no tcps */
25019 		TCP_G_STAT(tcp_timermp_allocfail);
25020 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25021 		if (mp == NULL) {
25022 			size_t size = 0;
25023 			/*
25024 			 * Memory is really low. Try tryhard allocation.
25025 			 *
25026 			 * ipclassifier calls this from a constructor -
25027 			 * hence no tcps
25028 			 */
25029 			TCP_G_STAT(tcp_timermp_allocdblfail);
25030 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25031 			    sizeof (tcp_timer_t), &size, kmflags);
25032 			mp->b_rptr = (uchar_t *)(&mp[1]);
25033 			mp->b_next = mp->b_prev = NULL;
25034 			mp->b_wptr = (uchar_t *)-1;
25035 			mp->b_datap = (dblk_t *)size;
25036 			mp->b_queue = NULL;
25037 			mp->b_cont = NULL;
25038 		}
25039 		ASSERT(mp->b_wptr != NULL);
25040 	}
25041 	/* ipclassifier calls this from a constructor - hence no tcps */
25042 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25043 
25044 	return (mp);
25045 }
25046 
25047 /*
25048  * Free per-tcp timer cache.
25049  * It can only contain entries from tcp_timercache.
25050  */
25051 void
25052 tcp_timermp_free(tcp_t *tcp)
25053 {
25054 	mblk_t *mp;
25055 
25056 	while ((mp = tcp->tcp_timercache) != NULL) {
25057 		ASSERT(mp->b_wptr == NULL);
25058 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25059 		kmem_cache_free(tcp_timercache, mp);
25060 	}
25061 }
25062 
25063 /*
25064  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25065  * events there already (currently at most two events are cached).
25066  * If the event is not allocated from the timer cache, free it right away.
25067  */
25068 static void
25069 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25070 {
25071 	mblk_t *mp1 = tcp->tcp_timercache;
25072 
25073 	if (mp->b_wptr != NULL) {
25074 		/*
25075 		 * This allocation is not from a timer cache, free it right
25076 		 * away.
25077 		 */
25078 		if (mp->b_wptr != (uchar_t *)-1)
25079 			freeb(mp);
25080 		else
25081 			kmem_free(mp, (size_t)mp->b_datap);
25082 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25083 		/* Cache this timer block for future allocations */
25084 		mp->b_rptr = (uchar_t *)(&mp[1]);
25085 		mp->b_next = mp1;
25086 		tcp->tcp_timercache = mp;
25087 	} else {
25088 		kmem_cache_free(tcp_timercache, mp);
25089 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25090 	}
25091 }
25092 
25093 /*
25094  * End of TCP Timers implementation.
25095  */
25096 
25097 /*
25098  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25099  * on the specified backing STREAMS q. Note, the caller may make the
25100  * decision to call based on the tcp_t.tcp_flow_stopped value which
25101  * when check outside the q's lock is only an advisory check ...
25102  */
25103 void
25104 tcp_setqfull(tcp_t *tcp)
25105 {
25106 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25107 	conn_t	*connp = tcp->tcp_connp;
25108 
25109 	if (tcp->tcp_closed)
25110 		return;
25111 
25112 	if (IPCL_IS_NONSTR(connp)) {
25113 		(*connp->conn_upcalls->su_txq_full)
25114 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25115 		tcp->tcp_flow_stopped = B_TRUE;
25116 	} else {
25117 		queue_t *q = tcp->tcp_wq;
25118 
25119 		if (!(q->q_flag & QFULL)) {
25120 			mutex_enter(QLOCK(q));
25121 			if (!(q->q_flag & QFULL)) {
25122 				/* still need to set QFULL */
25123 				q->q_flag |= QFULL;
25124 				tcp->tcp_flow_stopped = B_TRUE;
25125 				mutex_exit(QLOCK(q));
25126 				TCP_STAT(tcps, tcp_flwctl_on);
25127 			} else {
25128 				mutex_exit(QLOCK(q));
25129 			}
25130 		}
25131 	}
25132 }
25133 
25134 void
25135 tcp_clrqfull(tcp_t *tcp)
25136 {
25137 	conn_t  *connp = tcp->tcp_connp;
25138 
25139 	if (tcp->tcp_closed)
25140 		return;
25141 
25142 	if (IPCL_IS_NONSTR(connp)) {
25143 		(*connp->conn_upcalls->su_txq_full)
25144 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25145 		tcp->tcp_flow_stopped = B_FALSE;
25146 	} else {
25147 		queue_t *q = tcp->tcp_wq;
25148 
25149 		if (q->q_flag & QFULL) {
25150 			mutex_enter(QLOCK(q));
25151 			if (q->q_flag & QFULL) {
25152 				q->q_flag &= ~QFULL;
25153 				tcp->tcp_flow_stopped = B_FALSE;
25154 				mutex_exit(QLOCK(q));
25155 				if (q->q_flag & QWANTW)
25156 					qbackenable(q, 0);
25157 			} else {
25158 				mutex_exit(QLOCK(q));
25159 			}
25160 		}
25161 	}
25162 }
25163 
25164 /*
25165  * kstats related to squeues i.e. not per IP instance
25166  */
25167 static void *
25168 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
25169 {
25170 	kstat_t *ksp;
25171 
25172 	tcp_g_stat_t template = {
25173 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
25174 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
25175 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
25176 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
25177 	};
25178 
25179 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
25180 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25181 	    KSTAT_FLAG_VIRTUAL);
25182 
25183 	if (ksp == NULL)
25184 		return (NULL);
25185 
25186 	bcopy(&template, tcp_g_statp, sizeof (template));
25187 	ksp->ks_data = (void *)tcp_g_statp;
25188 
25189 	kstat_install(ksp);
25190 	return (ksp);
25191 }
25192 
25193 static void
25194 tcp_g_kstat_fini(kstat_t *ksp)
25195 {
25196 	if (ksp != NULL) {
25197 		kstat_delete(ksp);
25198 	}
25199 }
25200 
25201 
25202 static void *
25203 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
25204 {
25205 	kstat_t *ksp;
25206 
25207 	tcp_stat_t template = {
25208 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
25209 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
25210 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
25211 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
25212 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
25213 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
25214 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
25215 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
25216 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
25217 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
25218 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
25219 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
25220 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
25221 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
25222 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
25223 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
25224 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
25225 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
25226 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
25227 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
25228 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
25229 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
25230 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
25231 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
25232 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
25233 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
25234 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
25235 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
25236 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
25237 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
25238 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
25239 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
25240 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
25241 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
25242 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
25243 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
25244 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
25245 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
25246 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
25247 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
25248 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
25249 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
25250 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
25251 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
25252 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
25253 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
25254 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
25255 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
25256 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
25257 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
25258 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
25259 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
25260 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
25261 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
25262 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
25263 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
25264 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
25265 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
25266 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
25267 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
25268 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
25269 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
25270 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
25271 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
25272 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
25273 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
25274 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
25275 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
25276 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
25277 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
25278 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
25279 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
25280 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
25281 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
25282 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
25283 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
25284 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
25285 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
25286 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
25287 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
25288 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
25289 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
25290 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
25291 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
25292 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
25293 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
25294 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
25295 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
25296 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
25297 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
25298 	};
25299 
25300 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
25301 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25302 	    KSTAT_FLAG_VIRTUAL, stackid);
25303 
25304 	if (ksp == NULL)
25305 		return (NULL);
25306 
25307 	bcopy(&template, tcps_statisticsp, sizeof (template));
25308 	ksp->ks_data = (void *)tcps_statisticsp;
25309 	ksp->ks_private = (void *)(uintptr_t)stackid;
25310 
25311 	kstat_install(ksp);
25312 	return (ksp);
25313 }
25314 
25315 static void
25316 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
25317 {
25318 	if (ksp != NULL) {
25319 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25320 		kstat_delete_netstack(ksp, stackid);
25321 	}
25322 }
25323 
25324 /*
25325  * TCP Kstats implementation
25326  */
25327 static void *
25328 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
25329 {
25330 	kstat_t	*ksp;
25331 
25332 	tcp_named_kstat_t template = {
25333 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25334 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25335 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25336 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25337 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25338 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25339 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25340 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25341 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25342 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25343 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25344 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25345 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25346 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25347 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25348 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25349 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25350 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25351 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25352 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25353 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25354 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25355 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25356 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25357 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25358 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25359 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25360 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25361 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25362 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25363 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25364 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25365 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25366 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25367 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25368 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25369 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25370 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25371 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25372 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25373 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25374 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25375 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25376 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25377 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25378 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25379 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25380 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25381 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25382 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25383 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25384 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25385 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25386 	};
25387 
25388 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
25389 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
25390 
25391 	if (ksp == NULL)
25392 		return (NULL);
25393 
25394 	template.rtoAlgorithm.value.ui32 = 4;
25395 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
25396 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
25397 	template.maxConn.value.i32 = -1;
25398 
25399 	bcopy(&template, ksp->ks_data, sizeof (template));
25400 	ksp->ks_update = tcp_kstat_update;
25401 	ksp->ks_private = (void *)(uintptr_t)stackid;
25402 
25403 	kstat_install(ksp);
25404 	return (ksp);
25405 }
25406 
25407 static void
25408 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
25409 {
25410 	if (ksp != NULL) {
25411 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25412 		kstat_delete_netstack(ksp, stackid);
25413 	}
25414 }
25415 
25416 static int
25417 tcp_kstat_update(kstat_t *kp, int rw)
25418 {
25419 	tcp_named_kstat_t *tcpkp;
25420 	tcp_t		*tcp;
25421 	connf_t		*connfp;
25422 	conn_t		*connp;
25423 	int 		i;
25424 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
25425 	netstack_t	*ns;
25426 	tcp_stack_t	*tcps;
25427 	ip_stack_t	*ipst;
25428 
25429 	if ((kp == NULL) || (kp->ks_data == NULL))
25430 		return (EIO);
25431 
25432 	if (rw == KSTAT_WRITE)
25433 		return (EACCES);
25434 
25435 	ns = netstack_find_by_stackid(stackid);
25436 	if (ns == NULL)
25437 		return (-1);
25438 	tcps = ns->netstack_tcp;
25439 	if (tcps == NULL) {
25440 		netstack_rele(ns);
25441 		return (-1);
25442 	}
25443 
25444 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25445 
25446 	tcpkp->currEstab.value.ui32 = 0;
25447 
25448 	ipst = ns->netstack_ip;
25449 
25450 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25451 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25452 		connp = NULL;
25453 		while ((connp =
25454 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25455 			tcp = connp->conn_tcp;
25456 			switch (tcp_snmp_state(tcp)) {
25457 			case MIB2_TCP_established:
25458 			case MIB2_TCP_closeWait:
25459 				tcpkp->currEstab.value.ui32++;
25460 				break;
25461 			}
25462 		}
25463 	}
25464 
25465 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
25466 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
25467 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
25468 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
25469 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
25470 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
25471 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
25472 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
25473 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
25474 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
25475 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
25476 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
25477 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
25478 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
25479 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
25480 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
25481 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
25482 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
25483 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
25484 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
25485 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
25486 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
25487 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
25488 	tcpkp->inDataInorderSegs.value.ui32 =
25489 	    tcps->tcps_mib.tcpInDataInorderSegs;
25490 	tcpkp->inDataInorderBytes.value.ui32 =
25491 	    tcps->tcps_mib.tcpInDataInorderBytes;
25492 	tcpkp->inDataUnorderSegs.value.ui32 =
25493 	    tcps->tcps_mib.tcpInDataUnorderSegs;
25494 	tcpkp->inDataUnorderBytes.value.ui32 =
25495 	    tcps->tcps_mib.tcpInDataUnorderBytes;
25496 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
25497 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
25498 	tcpkp->inDataPartDupSegs.value.ui32 =
25499 	    tcps->tcps_mib.tcpInDataPartDupSegs;
25500 	tcpkp->inDataPartDupBytes.value.ui32 =
25501 	    tcps->tcps_mib.tcpInDataPartDupBytes;
25502 	tcpkp->inDataPastWinSegs.value.ui32 =
25503 	    tcps->tcps_mib.tcpInDataPastWinSegs;
25504 	tcpkp->inDataPastWinBytes.value.ui32 =
25505 	    tcps->tcps_mib.tcpInDataPastWinBytes;
25506 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
25507 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
25508 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
25509 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
25510 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
25511 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
25512 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
25513 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
25514 	tcpkp->timKeepaliveProbe.value.ui32 =
25515 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
25516 	tcpkp->timKeepaliveDrop.value.ui32 =
25517 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
25518 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
25519 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
25520 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
25521 	tcpkp->outSackRetransSegs.value.ui32 =
25522 	    tcps->tcps_mib.tcpOutSackRetransSegs;
25523 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
25524 
25525 	netstack_rele(ns);
25526 	return (0);
25527 }
25528 
25529 void
25530 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25531 {
25532 	uint16_t	hdr_len;
25533 	ipha_t		*ipha;
25534 	uint8_t		*nexthdrp;
25535 	tcph_t		*tcph;
25536 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
25537 
25538 	/* Already has an eager */
25539 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25540 		TCP_STAT(tcps, tcp_reinput_syn);
25541 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25542 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
25543 		return;
25544 	}
25545 
25546 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25547 	case IPV4_VERSION:
25548 		ipha = (ipha_t *)mp->b_rptr;
25549 		hdr_len = IPH_HDR_LENGTH(ipha);
25550 		break;
25551 	case IPV6_VERSION:
25552 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25553 		    &hdr_len, &nexthdrp)) {
25554 			CONN_DEC_REF(connp);
25555 			freemsg(mp);
25556 			return;
25557 		}
25558 		break;
25559 	}
25560 
25561 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25562 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25563 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25564 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25565 	}
25566 
25567 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25568 	    SQ_FILL, SQTAG_TCP_REINPUT);
25569 }
25570 
25571 static int
25572 tcp_squeue_switch(int val)
25573 {
25574 	int rval = SQ_FILL;
25575 
25576 	switch (val) {
25577 	case 1:
25578 		rval = SQ_NODRAIN;
25579 		break;
25580 	case 2:
25581 		rval = SQ_PROCESS;
25582 		break;
25583 	default:
25584 		break;
25585 	}
25586 	return (rval);
25587 }
25588 
25589 /*
25590  * This is called once for each squeue - globally for all stack
25591  * instances.
25592  */
25593 static void
25594 tcp_squeue_add(squeue_t *sqp)
25595 {
25596 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25597 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
25598 
25599 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25600 	tcp_time_wait->tcp_time_wait_tid =
25601 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
25602 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
25603 	    CALLOUT_FLAG_ROUNDUP);
25604 	if (tcp_free_list_max_cnt == 0) {
25605 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25606 		    max_ncpus : boot_max_ncpus);
25607 
25608 		/*
25609 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25610 		 */
25611 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25612 		    (tcp_ncpus * sizeof (tcp_t) * 100);
25613 	}
25614 	tcp_time_wait->tcp_free_list_cnt = 0;
25615 }
25616 
25617 static int
25618 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
25619 {
25620 	mblk_t	*ire_mp = NULL;
25621 	mblk_t	*syn_mp;
25622 	mblk_t	*mdti;
25623 	mblk_t	*lsoi;
25624 	int	retval;
25625 	tcph_t	*tcph;
25626 	cred_t	*ecr;
25627 	ts_label_t	*tsl;
25628 	uint32_t	mss;
25629 	queue_t	*q = tcp->tcp_rq;
25630 	conn_t	*connp = tcp->tcp_connp;
25631 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25632 
25633 	if (error == 0) {
25634 		/*
25635 		 * Adapt Multidata information, if any.  The
25636 		 * following tcp_mdt_update routine will free
25637 		 * the message.
25638 		 */
25639 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
25640 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
25641 			    b_rptr)->mdt_capab, B_TRUE);
25642 			freemsg(mdti);
25643 		}
25644 
25645 		/*
25646 		 * Check to update LSO information with tcp, and
25647 		 * tcp_lso_update routine will free the message.
25648 		 */
25649 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
25650 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
25651 			    b_rptr)->lso_capab);
25652 			freemsg(lsoi);
25653 		}
25654 
25655 		/* Get the IRE, if we had requested for it */
25656 		if (mp != NULL)
25657 			ire_mp = tcp_ire_mp(&mp);
25658 
25659 		if (tcp->tcp_hard_binding) {
25660 			tcp->tcp_hard_binding = B_FALSE;
25661 			tcp->tcp_hard_bound = B_TRUE;
25662 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
25663 			if (retval != 0) {
25664 				error = EADDRINUSE;
25665 				goto bind_failed;
25666 			}
25667 		} else {
25668 			if (ire_mp != NULL)
25669 				freeb(ire_mp);
25670 			goto after_syn_sent;
25671 		}
25672 
25673 		retval = tcp_adapt_ire(tcp, ire_mp);
25674 		if (ire_mp != NULL)
25675 			freeb(ire_mp);
25676 		if (retval == 0) {
25677 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
25678 			    ENETUNREACH : EADDRNOTAVAIL);
25679 			goto ipcl_rm;
25680 		}
25681 		/*
25682 		 * Don't let an endpoint connect to itself.
25683 		 * Also checked in tcp_connect() but that
25684 		 * check can't handle the case when the
25685 		 * local IP address is INADDR_ANY.
25686 		 */
25687 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25688 			if ((tcp->tcp_ipha->ipha_dst ==
25689 			    tcp->tcp_ipha->ipha_src) &&
25690 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25691 			    tcp->tcp_tcph->th_fport))) {
25692 				error = EADDRNOTAVAIL;
25693 				goto ipcl_rm;
25694 			}
25695 		} else {
25696 			if (IN6_ARE_ADDR_EQUAL(
25697 			    &tcp->tcp_ip6h->ip6_dst,
25698 			    &tcp->tcp_ip6h->ip6_src) &&
25699 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25700 			    tcp->tcp_tcph->th_fport))) {
25701 				error = EADDRNOTAVAIL;
25702 				goto ipcl_rm;
25703 			}
25704 		}
25705 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
25706 		/*
25707 		 * This should not be possible!  Just for
25708 		 * defensive coding...
25709 		 */
25710 		if (tcp->tcp_state != TCPS_SYN_SENT)
25711 			goto after_syn_sent;
25712 
25713 		if (is_system_labeled() &&
25714 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
25715 			error = EHOSTUNREACH;
25716 			goto ipcl_rm;
25717 		}
25718 
25719 		/*
25720 		 * tcp_adapt_ire() does not adjust
25721 		 * for TCP/IP header length.
25722 		 */
25723 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
25724 
25725 		/*
25726 		 * Just make sure our rwnd is at
25727 		 * least tcp_recv_hiwat_mss * MSS
25728 		 * large, and round up to the nearest
25729 		 * MSS.
25730 		 *
25731 		 * We do the round up here because
25732 		 * we need to get the interface
25733 		 * MTU first before we can do the
25734 		 * round up.
25735 		 */
25736 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
25737 		    tcps->tcps_recv_hiwat_minmss * mss);
25738 		if (!IPCL_IS_NONSTR(connp))
25739 			q->q_hiwat = tcp->tcp_rwnd;
25740 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
25741 		tcp_set_ws_value(tcp);
25742 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
25743 		    tcp->tcp_tcph->th_win);
25744 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
25745 			tcp->tcp_snd_ws_ok = B_TRUE;
25746 
25747 		/*
25748 		 * Set tcp_snd_ts_ok to true
25749 		 * so that tcp_xmit_mp will
25750 		 * include the timestamp
25751 		 * option in the SYN segment.
25752 		 */
25753 		if (tcps->tcps_tstamp_always ||
25754 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
25755 			tcp->tcp_snd_ts_ok = B_TRUE;
25756 		}
25757 
25758 		/*
25759 		 * tcp_snd_sack_ok can be set in
25760 		 * tcp_adapt_ire() if the sack metric
25761 		 * is set.  So check it here also.
25762 		 */
25763 		if (tcps->tcps_sack_permitted == 2 ||
25764 		    tcp->tcp_snd_sack_ok) {
25765 			if (tcp->tcp_sack_info == NULL) {
25766 				tcp->tcp_sack_info =
25767 				    kmem_cache_alloc(tcp_sack_info_cache,
25768 				    KM_SLEEP);
25769 			}
25770 			tcp->tcp_snd_sack_ok = B_TRUE;
25771 		}
25772 
25773 		/*
25774 		 * Should we use ECN?  Note that the current
25775 		 * default value (SunOS 5.9) of tcp_ecn_permitted
25776 		 * is 1.  The reason for doing this is that there
25777 		 * are equipments out there that will drop ECN
25778 		 * enabled IP packets.  Setting it to 1 avoids
25779 		 * compatibility problems.
25780 		 */
25781 		if (tcps->tcps_ecn_permitted == 2)
25782 			tcp->tcp_ecn_ok = B_TRUE;
25783 
25784 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
25785 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
25786 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
25787 		if (syn_mp) {
25788 			/*
25789 			 * cr contains the cred from the thread calling
25790 			 * connect().
25791 			 *
25792 			 * If no thread cred is available, use the
25793 			 * socket creator's cred instead. If still no
25794 			 * cred, drop the request rather than risk a
25795 			 * panic on production systems.
25796 			 */
25797 			if (cr == NULL) {
25798 				cr = CONN_CRED(connp);
25799 				pid = tcp->tcp_cpid;
25800 				ASSERT(cr != NULL);
25801 				if (cr != NULL) {
25802 					mblk_setcred(syn_mp, cr, pid);
25803 				} else {
25804 					error = ECONNABORTED;
25805 					goto ipcl_rm;
25806 				}
25807 
25808 			/*
25809 			 * If an effective security label exists for
25810 			 * the connection, create a copy of the thread's
25811 			 * cred but with the effective label attached.
25812 			 */
25813 			} else if (is_system_labeled() &&
25814 			    connp->conn_effective_cred != NULL &&
25815 			    (tsl = crgetlabel(connp->
25816 			    conn_effective_cred)) != NULL) {
25817 				if ((ecr = copycred_from_tslabel(cr,
25818 				    tsl, KM_NOSLEEP)) == NULL) {
25819 					error = ENOMEM;
25820 					goto ipcl_rm;
25821 				}
25822 				mblk_setcred(syn_mp, ecr, pid);
25823 				crfree(ecr);
25824 
25825 			/*
25826 			 * Default to using the thread's cred unchanged.
25827 			 */
25828 			} else {
25829 				mblk_setcred(syn_mp, cr, pid);
25830 			}
25831 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
25832 		}
25833 	after_syn_sent:
25834 		if (mp != NULL) {
25835 			ASSERT(mp->b_cont == NULL);
25836 			freeb(mp);
25837 		}
25838 		return (error);
25839 	} else {
25840 		/* error */
25841 		if (tcp->tcp_debug) {
25842 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
25843 			    "tcp_post_ip_bind: error == %d", error);
25844 		}
25845 		if (mp != NULL) {
25846 			freeb(mp);
25847 		}
25848 	}
25849 
25850 ipcl_rm:
25851 	/*
25852 	 * Need to unbind with classifier since we were just
25853 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
25854 	 */
25855 	tcp->tcp_hard_bound = B_FALSE;
25856 	tcp->tcp_hard_binding = B_FALSE;
25857 
25858 	ipcl_hash_remove(connp);
25859 
25860 bind_failed:
25861 	tcp->tcp_state = TCPS_IDLE;
25862 	if (tcp->tcp_ipversion == IPV4_VERSION)
25863 		tcp->tcp_ipha->ipha_src = 0;
25864 	else
25865 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
25866 	/*
25867 	 * Copy of the src addr. in tcp_t is needed since
25868 	 * the lookup funcs. can only look at tcp_t
25869 	 */
25870 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
25871 
25872 	tcph = tcp->tcp_tcph;
25873 	tcph->th_lport[0] = 0;
25874 	tcph->th_lport[1] = 0;
25875 	tcp_bind_hash_remove(tcp);
25876 	bzero(&connp->u_port, sizeof (connp->u_port));
25877 	/* blow away saved option results if any */
25878 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
25879 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
25880 
25881 	conn_delete_ire(tcp->tcp_connp, NULL);
25882 
25883 	return (error);
25884 }
25885 
25886 static int
25887 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
25888     boolean_t bind_to_req_port_only, cred_t *cr)
25889 {
25890 	in_port_t	mlp_port;
25891 	mlp_type_t 	addrtype, mlptype;
25892 	boolean_t	user_specified;
25893 	in_port_t	allocated_port;
25894 	in_port_t	requested_port = *requested_port_ptr;
25895 	conn_t		*connp;
25896 	zone_t		*zone;
25897 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25898 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
25899 
25900 	/*
25901 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
25902 	 */
25903 	if (cr == NULL)
25904 		cr = tcp->tcp_cred;
25905 	/*
25906 	 * Get a valid port (within the anonymous range and should not
25907 	 * be a privileged one) to use if the user has not given a port.
25908 	 * If multiple threads are here, they may all start with
25909 	 * with the same initial port. But, it should be fine as long as
25910 	 * tcp_bindi will ensure that no two threads will be assigned
25911 	 * the same port.
25912 	 *
25913 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
25914 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
25915 	 * unless TCP_ANONPRIVBIND option is set.
25916 	 */
25917 	mlptype = mlptSingle;
25918 	mlp_port = requested_port;
25919 	if (requested_port == 0) {
25920 		requested_port = tcp->tcp_anon_priv_bind ?
25921 		    tcp_get_next_priv_port(tcp) :
25922 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
25923 		    tcp, B_TRUE);
25924 		if (requested_port == 0) {
25925 			return (-TNOADDR);
25926 		}
25927 		user_specified = B_FALSE;
25928 
25929 		/*
25930 		 * If the user went through one of the RPC interfaces to create
25931 		 * this socket and RPC is MLP in this zone, then give him an
25932 		 * anonymous MLP.
25933 		 */
25934 		connp = tcp->tcp_connp;
25935 		if (connp->conn_anon_mlp && is_system_labeled()) {
25936 			zone = crgetzone(cr);
25937 			addrtype = tsol_mlp_addr_type(zone->zone_id,
25938 			    IPV6_VERSION, &v6addr,
25939 			    tcps->tcps_netstack->netstack_ip);
25940 			if (addrtype == mlptSingle) {
25941 				return (-TNOADDR);
25942 			}
25943 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25944 			    PMAPPORT, addrtype);
25945 			mlp_port = PMAPPORT;
25946 		}
25947 	} else {
25948 		int i;
25949 		boolean_t priv = B_FALSE;
25950 
25951 		/*
25952 		 * If the requested_port is in the well-known privileged range,
25953 		 * verify that the stream was opened by a privileged user.
25954 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
25955 		 * but instead the code relies on:
25956 		 * - the fact that the address of the array and its size never
25957 		 *   changes
25958 		 * - the atomic assignment of the elements of the array
25959 		 */
25960 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
25961 			priv = B_TRUE;
25962 		} else {
25963 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
25964 				if (requested_port ==
25965 				    tcps->tcps_g_epriv_ports[i]) {
25966 					priv = B_TRUE;
25967 					break;
25968 				}
25969 			}
25970 		}
25971 		if (priv) {
25972 			if (secpolicy_net_privaddr(cr, requested_port,
25973 			    IPPROTO_TCP) != 0) {
25974 				if (tcp->tcp_debug) {
25975 					(void) strlog(TCP_MOD_ID, 0, 1,
25976 					    SL_ERROR|SL_TRACE,
25977 					    "tcp_bind: no priv for port %d",
25978 					    requested_port);
25979 				}
25980 				return (-TACCES);
25981 			}
25982 		}
25983 		user_specified = B_TRUE;
25984 
25985 		connp = tcp->tcp_connp;
25986 		if (is_system_labeled()) {
25987 			zone = crgetzone(cr);
25988 			addrtype = tsol_mlp_addr_type(zone->zone_id,
25989 			    IPV6_VERSION, &v6addr,
25990 			    tcps->tcps_netstack->netstack_ip);
25991 			if (addrtype == mlptSingle) {
25992 				return (-TNOADDR);
25993 			}
25994 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25995 			    requested_port, addrtype);
25996 		}
25997 	}
25998 
25999 	if (mlptype != mlptSingle) {
26000 		if (secpolicy_net_bindmlp(cr) != 0) {
26001 			if (tcp->tcp_debug) {
26002 				(void) strlog(TCP_MOD_ID, 0, 1,
26003 				    SL_ERROR|SL_TRACE,
26004 				    "tcp_bind: no priv for multilevel port %d",
26005 				    requested_port);
26006 			}
26007 			return (-TACCES);
26008 		}
26009 
26010 		/*
26011 		 * If we're specifically binding a shared IP address and the
26012 		 * port is MLP on shared addresses, then check to see if this
26013 		 * zone actually owns the MLP.  Reject if not.
26014 		 */
26015 		if (mlptype == mlptShared && addrtype == mlptShared) {
26016 			/*
26017 			 * No need to handle exclusive-stack zones since
26018 			 * ALL_ZONES only applies to the shared stack.
26019 			 */
26020 			zoneid_t mlpzone;
26021 
26022 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26023 			    htons(mlp_port));
26024 			if (connp->conn_zoneid != mlpzone) {
26025 				if (tcp->tcp_debug) {
26026 					(void) strlog(TCP_MOD_ID, 0, 1,
26027 					    SL_ERROR|SL_TRACE,
26028 					    "tcp_bind: attempt to bind port "
26029 					    "%d on shared addr in zone %d "
26030 					    "(should be %d)",
26031 					    mlp_port, connp->conn_zoneid,
26032 					    mlpzone);
26033 				}
26034 				return (-TACCES);
26035 			}
26036 		}
26037 
26038 		if (!user_specified) {
26039 			int err;
26040 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26041 			    requested_port, B_TRUE);
26042 			if (err != 0) {
26043 				if (tcp->tcp_debug) {
26044 					(void) strlog(TCP_MOD_ID, 0, 1,
26045 					    SL_ERROR|SL_TRACE,
26046 					    "tcp_bind: cannot establish anon "
26047 					    "MLP for port %d",
26048 					    requested_port);
26049 				}
26050 				return (err);
26051 			}
26052 			connp->conn_anon_port = B_TRUE;
26053 		}
26054 		connp->conn_mlp_type = mlptype;
26055 	}
26056 
26057 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26058 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26059 
26060 	if (allocated_port == 0) {
26061 		connp->conn_mlp_type = mlptSingle;
26062 		if (connp->conn_anon_port) {
26063 			connp->conn_anon_port = B_FALSE;
26064 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26065 			    requested_port, B_FALSE);
26066 		}
26067 		if (bind_to_req_port_only) {
26068 			if (tcp->tcp_debug) {
26069 				(void) strlog(TCP_MOD_ID, 0, 1,
26070 				    SL_ERROR|SL_TRACE,
26071 				    "tcp_bind: requested addr busy");
26072 			}
26073 			return (-TADDRBUSY);
26074 		} else {
26075 			/* If we are out of ports, fail the bind. */
26076 			if (tcp->tcp_debug) {
26077 				(void) strlog(TCP_MOD_ID, 0, 1,
26078 				    SL_ERROR|SL_TRACE,
26079 				    "tcp_bind: out of ports?");
26080 			}
26081 			return (-TNOADDR);
26082 		}
26083 	}
26084 
26085 	/* Pass the allocated port back */
26086 	*requested_port_ptr = allocated_port;
26087 	return (0);
26088 }
26089 
26090 static int
26091 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26092     boolean_t bind_to_req_port_only)
26093 {
26094 	tcp_t	*tcp = connp->conn_tcp;
26095 	sin_t	*sin;
26096 	sin6_t  *sin6;
26097 	in_port_t requested_port;
26098 	ipaddr_t	v4addr;
26099 	in6_addr_t	v6addr;
26100 	uint_t	origipversion;
26101 	int	error = 0;
26102 
26103 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26104 
26105 	if (tcp->tcp_state == TCPS_BOUND) {
26106 		return (0);
26107 	} else if (tcp->tcp_state > TCPS_BOUND) {
26108 		if (tcp->tcp_debug) {
26109 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26110 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26111 		}
26112 		return (-TOUTSTATE);
26113 	}
26114 	origipversion = tcp->tcp_ipversion;
26115 
26116 	ASSERT(sa != NULL && len != 0);
26117 
26118 	if (!OK_32PTR((char *)sa)) {
26119 		if (tcp->tcp_debug) {
26120 			(void) strlog(TCP_MOD_ID, 0, 1,
26121 			    SL_ERROR|SL_TRACE,
26122 			    "tcp_bind: bad address parameter, "
26123 			    "address %p, len %d",
26124 			    (void *)sa, len);
26125 		}
26126 		return (-TPROTO);
26127 	}
26128 
26129 	switch (len) {
26130 	case sizeof (sin_t):	/* Complete IPv4 address */
26131 		sin = (sin_t *)sa;
26132 		/*
26133 		 * With sockets sockfs will accept bogus sin_family in
26134 		 * bind() and replace it with the family used in the socket
26135 		 * call.
26136 		 */
26137 		if (sin->sin_family != AF_INET ||
26138 		    tcp->tcp_family != AF_INET) {
26139 			return (EAFNOSUPPORT);
26140 		}
26141 		requested_port = ntohs(sin->sin_port);
26142 		tcp->tcp_ipversion = IPV4_VERSION;
26143 		v4addr = sin->sin_addr.s_addr;
26144 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26145 		break;
26146 
26147 	case sizeof (sin6_t): /* Complete IPv6 address */
26148 		sin6 = (sin6_t *)sa;
26149 		if (sin6->sin6_family != AF_INET6 ||
26150 		    tcp->tcp_family != AF_INET6) {
26151 			return (EAFNOSUPPORT);
26152 		}
26153 		requested_port = ntohs(sin6->sin6_port);
26154 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26155 		    IPV4_VERSION : IPV6_VERSION;
26156 		v6addr = sin6->sin6_addr;
26157 		break;
26158 
26159 	default:
26160 		if (tcp->tcp_debug) {
26161 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26162 			    "tcp_bind: bad address length, %d", len);
26163 		}
26164 		return (EAFNOSUPPORT);
26165 		/* return (-TBADADDR); */
26166 	}
26167 
26168 	tcp->tcp_bound_source_v6 = v6addr;
26169 
26170 	/* Check for change in ipversion */
26171 	if (origipversion != tcp->tcp_ipversion) {
26172 		ASSERT(tcp->tcp_family == AF_INET6);
26173 		error = tcp->tcp_ipversion == IPV6_VERSION ?
26174 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26175 		if (error) {
26176 			return (ENOMEM);
26177 		}
26178 	}
26179 
26180 	/*
26181 	 * Initialize family specific fields. Copy of the src addr.
26182 	 * in tcp_t is needed for the lookup funcs.
26183 	 */
26184 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26185 		tcp->tcp_ip6h->ip6_src = v6addr;
26186 	} else {
26187 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
26188 	}
26189 	tcp->tcp_ip_src_v6 = v6addr;
26190 
26191 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
26192 
26193 	error = tcp_bind_select_lport(tcp, &requested_port,
26194 	    bind_to_req_port_only, cr);
26195 
26196 	return (error);
26197 }
26198 
26199 /*
26200  * Return unix error is tli error is TSYSERR, otherwise return a negative
26201  * tli error.
26202  */
26203 int
26204 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26205     boolean_t bind_to_req_port_only)
26206 {
26207 	int error;
26208 	tcp_t *tcp = connp->conn_tcp;
26209 
26210 	if (tcp->tcp_state >= TCPS_BOUND) {
26211 		if (tcp->tcp_debug) {
26212 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26213 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26214 		}
26215 		return (-TOUTSTATE);
26216 	}
26217 
26218 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
26219 	if (error != 0)
26220 		return (error);
26221 
26222 	ASSERT(tcp->tcp_state == TCPS_BOUND);
26223 
26224 	tcp->tcp_conn_req_max = 0;
26225 
26226 	if (tcp->tcp_family == AF_INET6) {
26227 		ASSERT(tcp->tcp_connp->conn_af_isv6);
26228 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
26229 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
26230 	} else {
26231 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
26232 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
26233 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
26234 	}
26235 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
26236 }
26237 
26238 int
26239 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
26240     socklen_t len, cred_t *cr)
26241 {
26242 	int 		error;
26243 	conn_t		*connp = (conn_t *)proto_handle;
26244 	squeue_t	*sqp = connp->conn_sqp;
26245 
26246 	/* All Solaris components should pass a cred for this operation. */
26247 	ASSERT(cr != NULL);
26248 
26249 	ASSERT(sqp != NULL);
26250 	ASSERT(connp->conn_upper_handle != NULL);
26251 
26252 	error = squeue_synch_enter(sqp, connp, NULL);
26253 	if (error != 0) {
26254 		/* failed to enter */
26255 		return (ENOSR);
26256 	}
26257 
26258 	/* binding to a NULL address really means unbind */
26259 	if (sa == NULL) {
26260 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
26261 			error = tcp_do_unbind(connp);
26262 		else
26263 			error = EINVAL;
26264 	} else {
26265 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
26266 	}
26267 
26268 	squeue_synch_exit(sqp, connp);
26269 
26270 	if (error < 0) {
26271 		if (error == -TOUTSTATE)
26272 			error = EINVAL;
26273 		else
26274 			error = proto_tlitosyserr(-error);
26275 	}
26276 
26277 	return (error);
26278 }
26279 
26280 /*
26281  * If the return value from this function is positive, it's a UNIX error.
26282  * Otherwise, if it's negative, then the absolute value is a TLI error.
26283  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
26284  */
26285 int
26286 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
26287     cred_t *cr, pid_t pid)
26288 {
26289 	tcp_t		*tcp = connp->conn_tcp;
26290 	sin_t		*sin = (sin_t *)sa;
26291 	sin6_t		*sin6 = (sin6_t *)sa;
26292 	ipaddr_t	*dstaddrp;
26293 	in_port_t	dstport;
26294 	uint_t		srcid;
26295 	int		error = 0;
26296 
26297 	switch (len) {
26298 	default:
26299 		/*
26300 		 * Should never happen
26301 		 */
26302 		return (EINVAL);
26303 
26304 	case sizeof (sin_t):
26305 		sin = (sin_t *)sa;
26306 		if (sin->sin_port == 0) {
26307 			return (-TBADADDR);
26308 		}
26309 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
26310 			return (EAFNOSUPPORT);
26311 		}
26312 		break;
26313 
26314 	case sizeof (sin6_t):
26315 		sin6 = (sin6_t *)sa;
26316 		if (sin6->sin6_port == 0) {
26317 			return (-TBADADDR);
26318 		}
26319 		break;
26320 	}
26321 	/*
26322 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
26323 	 * make sure that the template IP header in the tcp structure is an
26324 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
26325 	 * need to this before we call tcp_bindi() so that the port lookup
26326 	 * code will look for ports in the correct port space (IPv4 and
26327 	 * IPv6 have separate port spaces).
26328 	 */
26329 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
26330 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26331 		int err = 0;
26332 
26333 		err = tcp_header_init_ipv4(tcp);
26334 			if (err != 0) {
26335 				error = ENOMEM;
26336 				goto connect_failed;
26337 			}
26338 		if (tcp->tcp_lport != 0)
26339 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
26340 	}
26341 
26342 	switch (tcp->tcp_state) {
26343 	case TCPS_LISTEN:
26344 		/*
26345 		 * Listening sockets are not allowed to issue connect().
26346 		 */
26347 		if (IPCL_IS_NONSTR(connp))
26348 			return (EOPNOTSUPP);
26349 		/* FALLTHRU */
26350 	case TCPS_IDLE:
26351 		/*
26352 		 * We support quick connect, refer to comments in
26353 		 * tcp_connect_*()
26354 		 */
26355 		/* FALLTHRU */
26356 	case TCPS_BOUND:
26357 		/*
26358 		 * We must bump the generation before the operation start.
26359 		 * This is done to ensure that any upcall made later on sends
26360 		 * up the right generation to the socket.
26361 		 */
26362 		SOCK_CONNID_BUMP(tcp->tcp_connid);
26363 
26364 		if (tcp->tcp_family == AF_INET6) {
26365 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26366 				return (tcp_connect_ipv6(tcp,
26367 				    &sin6->sin6_addr,
26368 				    sin6->sin6_port, sin6->sin6_flowinfo,
26369 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
26370 				    cr, pid));
26371 			}
26372 			/*
26373 			 * Destination adress is mapped IPv6 address.
26374 			 * Source bound address should be unspecified or
26375 			 * IPv6 mapped address as well.
26376 			 */
26377 			if (!IN6_IS_ADDR_UNSPECIFIED(
26378 			    &tcp->tcp_bound_source_v6) &&
26379 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
26380 				return (EADDRNOTAVAIL);
26381 			}
26382 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
26383 			dstport = sin6->sin6_port;
26384 			srcid = sin6->__sin6_src_id;
26385 		} else {
26386 			dstaddrp = &sin->sin_addr.s_addr;
26387 			dstport = sin->sin_port;
26388 			srcid = 0;
26389 		}
26390 
26391 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
26392 		    pid);
26393 		break;
26394 	default:
26395 		return (-TOUTSTATE);
26396 	}
26397 	/*
26398 	 * Note: Code below is the "failure" case
26399 	 */
26400 connect_failed:
26401 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26402 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26403 	return (error);
26404 }
26405 
26406 int
26407 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
26408     socklen_t len, sock_connid_t *id, cred_t *cr)
26409 {
26410 	conn_t		*connp = (conn_t *)proto_handle;
26411 	tcp_t		*tcp = connp->conn_tcp;
26412 	squeue_t	*sqp = connp->conn_sqp;
26413 	int		error;
26414 
26415 	ASSERT(connp->conn_upper_handle != NULL);
26416 
26417 	/* All Solaris components should pass a cred for this operation. */
26418 	ASSERT(cr != NULL);
26419 
26420 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
26421 	if (error != 0) {
26422 		return (error);
26423 	}
26424 
26425 	error = squeue_synch_enter(sqp, connp, NULL);
26426 	if (error != 0) {
26427 		/* failed to enter */
26428 		return (ENOSR);
26429 	}
26430 
26431 	/*
26432 	 * TCP supports quick connect, so no need to do an implicit bind
26433 	 */
26434 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
26435 	if (error == 0) {
26436 		*id = connp->conn_tcp->tcp_connid;
26437 	} else if (error < 0) {
26438 		if (error == -TOUTSTATE) {
26439 			switch (connp->conn_tcp->tcp_state) {
26440 			case TCPS_SYN_SENT:
26441 				error = EALREADY;
26442 				break;
26443 			case TCPS_ESTABLISHED:
26444 				error = EISCONN;
26445 				break;
26446 			case TCPS_LISTEN:
26447 				error = EOPNOTSUPP;
26448 				break;
26449 			default:
26450 				error = EINVAL;
26451 				break;
26452 			}
26453 		} else {
26454 			error = proto_tlitosyserr(-error);
26455 		}
26456 	}
26457 done:
26458 	squeue_synch_exit(sqp, connp);
26459 
26460 	return ((error == 0) ? EINPROGRESS : error);
26461 }
26462 
26463 /* ARGSUSED */
26464 sock_lower_handle_t
26465 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
26466     uint_t *smodep, int *errorp, int flags, cred_t *credp)
26467 {
26468 	conn_t		*connp;
26469 	boolean_t	isv6 = family == AF_INET6;
26470 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
26471 	    (proto != 0 && proto != IPPROTO_TCP)) {
26472 		*errorp = EPROTONOSUPPORT;
26473 		return (NULL);
26474 	}
26475 
26476 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
26477 	if (connp == NULL) {
26478 		return (NULL);
26479 	}
26480 
26481 	/*
26482 	 * Put the ref for TCP. Ref for IP was already put
26483 	 * by ipcl_conn_create. Also Make the conn_t globally
26484 	 * visible to walkers
26485 	 */
26486 	mutex_enter(&connp->conn_lock);
26487 	CONN_INC_REF_LOCKED(connp);
26488 	ASSERT(connp->conn_ref == 2);
26489 	connp->conn_state_flags &= ~CONN_INCIPIENT;
26490 
26491 	connp->conn_flags |= IPCL_NONSTR;
26492 	mutex_exit(&connp->conn_lock);
26493 
26494 	ASSERT(errorp != NULL);
26495 	*errorp = 0;
26496 	*sock_downcalls = &sock_tcp_downcalls;
26497 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
26498 	    SM_SENDFILESUPP;
26499 
26500 	return ((sock_lower_handle_t)connp);
26501 }
26502 
26503 /* ARGSUSED */
26504 void
26505 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
26506     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
26507 {
26508 	conn_t *connp = (conn_t *)proto_handle;
26509 	struct sock_proto_props sopp;
26510 
26511 	ASSERT(connp->conn_upper_handle == NULL);
26512 
26513 	/* All Solaris components should pass a cred for this operation. */
26514 	ASSERT(cr != NULL);
26515 
26516 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
26517 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
26518 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
26519 
26520 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
26521 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
26522 	sopp.sopp_maxpsz = INFPSZ;
26523 	sopp.sopp_maxblk = INFPSZ;
26524 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
26525 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
26526 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
26527 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
26528 	    tcp_rinfo.mi_minpsz;
26529 
26530 	connp->conn_upcalls = sock_upcalls;
26531 	connp->conn_upper_handle = sock_handle;
26532 
26533 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
26534 }
26535 
26536 /* ARGSUSED */
26537 int
26538 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
26539 {
26540 	conn_t *connp = (conn_t *)proto_handle;
26541 
26542 	ASSERT(connp->conn_upper_handle != NULL);
26543 
26544 	/* All Solaris components should pass a cred for this operation. */
26545 	ASSERT(cr != NULL);
26546 
26547 	tcp_close_common(connp, flags);
26548 
26549 	ip_free_helper_stream(connp);
26550 
26551 	/*
26552 	 * Drop IP's reference on the conn. This is the last reference
26553 	 * on the connp if the state was less than established. If the
26554 	 * connection has gone into timewait state, then we will have
26555 	 * one ref for the TCP and one more ref (total of two) for the
26556 	 * classifier connected hash list (a timewait connections stays
26557 	 * in connected hash till closed).
26558 	 *
26559 	 * We can't assert the references because there might be other
26560 	 * transient reference places because of some walkers or queued
26561 	 * packets in squeue for the timewait state.
26562 	 */
26563 	CONN_DEC_REF(connp);
26564 	return (0);
26565 }
26566 
26567 /* ARGSUSED */
26568 int
26569 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
26570     cred_t *cr)
26571 {
26572 	tcp_t		*tcp;
26573 	uint32_t	msize;
26574 	conn_t *connp = (conn_t *)proto_handle;
26575 	int32_t		tcpstate;
26576 
26577 	/* All Solaris components should pass a cred for this operation. */
26578 	ASSERT(cr != NULL);
26579 
26580 	ASSERT(connp->conn_ref >= 2);
26581 	ASSERT(connp->conn_upper_handle != NULL);
26582 
26583 	if (msg->msg_controllen != 0) {
26584 		return (EOPNOTSUPP);
26585 
26586 	}
26587 	switch (DB_TYPE(mp)) {
26588 	case M_DATA:
26589 		tcp = connp->conn_tcp;
26590 		ASSERT(tcp != NULL);
26591 
26592 		tcpstate = tcp->tcp_state;
26593 		if (tcpstate < TCPS_ESTABLISHED) {
26594 			freemsg(mp);
26595 			return (ENOTCONN);
26596 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
26597 			freemsg(mp);
26598 			return (EPIPE);
26599 		}
26600 
26601 		msize = msgdsize(mp);
26602 
26603 		mutex_enter(&tcp->tcp_non_sq_lock);
26604 		tcp->tcp_squeue_bytes += msize;
26605 		/*
26606 		 * Squeue Flow Control
26607 		 */
26608 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
26609 			tcp_setqfull(tcp);
26610 		}
26611 		mutex_exit(&tcp->tcp_non_sq_lock);
26612 
26613 		/*
26614 		 * The application may pass in an address in the msghdr, but
26615 		 * we ignore the address on connection-oriented sockets.
26616 		 * Just like BSD this code does not generate an error for
26617 		 * TCP (a CONNREQUIRED socket) when sending to an address
26618 		 * passed in with sendto/sendmsg. Instead the data is
26619 		 * delivered on the connection as if no address had been
26620 		 * supplied.
26621 		 */
26622 		CONN_INC_REF(connp);
26623 
26624 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
26625 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
26626 			    tcp_output_urgent, connp, tcp_squeue_flag,
26627 			    SQTAG_TCP_OUTPUT);
26628 		} else {
26629 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
26630 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
26631 		}
26632 
26633 		return (0);
26634 
26635 	default:
26636 		ASSERT(0);
26637 	}
26638 
26639 	freemsg(mp);
26640 	return (0);
26641 }
26642 
26643 /* ARGSUSED */
26644 void
26645 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
26646 {
26647 	int len;
26648 	uint32_t msize;
26649 	conn_t *connp = (conn_t *)arg;
26650 	tcp_t *tcp = connp->conn_tcp;
26651 
26652 	msize = msgdsize(mp);
26653 
26654 	len = msize - 1;
26655 	if (len < 0) {
26656 		freemsg(mp);
26657 		return;
26658 	}
26659 
26660 	/*
26661 	 * Try to force urgent data out on the wire. Even if we have unsent
26662 	 * data this will at least send the urgent flag.
26663 	 * XXX does not handle more flag correctly.
26664 	 */
26665 	len += tcp->tcp_unsent;
26666 	len += tcp->tcp_snxt;
26667 	tcp->tcp_urg = len;
26668 	tcp->tcp_valid_bits |= TCP_URG_VALID;
26669 
26670 	/* Bypass tcp protocol for fused tcp loopback */
26671 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
26672 		return;
26673 
26674 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
26675 	if (DB_TYPE(mp) != M_DATA) {
26676 		mblk_t *mp1 = mp;
26677 		ASSERT(!IPCL_IS_NONSTR(connp));
26678 		mp = mp->b_cont;
26679 		freeb(mp1);
26680 	}
26681 	tcp_wput_data(tcp, mp, B_TRUE);
26682 }
26683 
26684 /* ARGSUSED */
26685 int
26686 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26687     socklen_t *addrlenp, cred_t *cr)
26688 {
26689 	conn_t	*connp = (conn_t *)proto_handle;
26690 	tcp_t	*tcp = connp->conn_tcp;
26691 
26692 	ASSERT(connp->conn_upper_handle != NULL);
26693 	/* All Solaris components should pass a cred for this operation. */
26694 	ASSERT(cr != NULL);
26695 
26696 	ASSERT(tcp != NULL);
26697 
26698 	return (tcp_do_getpeername(tcp, addr, addrlenp));
26699 }
26700 
26701 /* ARGSUSED */
26702 int
26703 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26704     socklen_t *addrlenp, cred_t *cr)
26705 {
26706 	conn_t	*connp = (conn_t *)proto_handle;
26707 	tcp_t	*tcp = connp->conn_tcp;
26708 
26709 	/* All Solaris components should pass a cred for this operation. */
26710 	ASSERT(cr != NULL);
26711 
26712 	ASSERT(connp->conn_upper_handle != NULL);
26713 
26714 	return (tcp_do_getsockname(tcp, addr, addrlenp));
26715 }
26716 
26717 /*
26718  * tcp_fallback
26719  *
26720  * A direct socket is falling back to using STREAMS. The queue
26721  * that is being passed down was created using tcp_open() with
26722  * the SO_FALLBACK flag set. As a result, the queue is not
26723  * associated with a conn, and the q_ptrs instead contain the
26724  * dev and minor area that should be used.
26725  *
26726  * The 'issocket' flag indicates whether the FireEngine
26727  * optimizations should be used. The common case would be that
26728  * optimizations are enabled, and they might be subsequently
26729  * disabled using the _SIOCSOCKFALLBACK ioctl.
26730  */
26731 
26732 /*
26733  * An active connection is falling back to TPI. Gather all the information
26734  * required by the STREAM head and TPI sonode and send it up.
26735  */
26736 void
26737 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
26738     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
26739 {
26740 	conn_t			*connp = tcp->tcp_connp;
26741 	struct stroptions	*stropt;
26742 	struct T_capability_ack tca;
26743 	struct sockaddr_in6	laddr, faddr;
26744 	socklen_t 		laddrlen, faddrlen;
26745 	short			opts;
26746 	int			error;
26747 	mblk_t			*mp;
26748 
26749 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
26750 	connp->conn_minor_arena = WR(q)->q_ptr;
26751 
26752 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
26753 
26754 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
26755 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
26756 
26757 	WR(q)->q_qinfo = &tcp_sock_winit;
26758 
26759 	if (!issocket)
26760 		tcp_use_pure_tpi(tcp);
26761 
26762 	/*
26763 	 * free the helper stream
26764 	 */
26765 	ip_free_helper_stream(connp);
26766 
26767 	/*
26768 	 * Notify the STREAM head about options
26769 	 */
26770 	DB_TYPE(stropt_mp) = M_SETOPTS;
26771 	stropt = (struct stroptions *)stropt_mp->b_rptr;
26772 	stropt_mp->b_wptr += sizeof (struct stroptions);
26773 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
26774 
26775 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
26776 	    tcp->tcp_tcps->tcps_wroff_xtra);
26777 	if (tcp->tcp_snd_sack_ok)
26778 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
26779 	stropt->so_hiwat = tcp->tcp_fused ?
26780 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
26781 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
26782 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
26783 
26784 	putnext(RD(q), stropt_mp);
26785 
26786 	/*
26787 	 * Collect the information needed to sync with the sonode
26788 	 */
26789 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
26790 
26791 	laddrlen = faddrlen = sizeof (sin6_t);
26792 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
26793 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
26794 	if (error != 0)
26795 		faddrlen = 0;
26796 
26797 	opts = 0;
26798 	if (tcp->tcp_oobinline)
26799 		opts |= SO_OOBINLINE;
26800 	if (tcp->tcp_dontroute)
26801 		opts |= SO_DONTROUTE;
26802 
26803 	/*
26804 	 * Notify the socket that the protocol is now quiescent,
26805 	 * and it's therefore safe move data from the socket
26806 	 * to the stream head.
26807 	 */
26808 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
26809 	    (struct sockaddr *)&laddr, laddrlen,
26810 	    (struct sockaddr *)&faddr, faddrlen, opts);
26811 
26812 	while ((mp = tcp->tcp_rcv_list) != NULL) {
26813 		tcp->tcp_rcv_list = mp->b_next;
26814 		mp->b_next = NULL;
26815 		putnext(q, mp);
26816 	}
26817 	tcp->tcp_rcv_last_head = NULL;
26818 	tcp->tcp_rcv_last_tail = NULL;
26819 	tcp->tcp_rcv_cnt = 0;
26820 }
26821 
26822 /*
26823  * An eager is falling back to TPI. All we have to do is send
26824  * up a T_CONN_IND.
26825  */
26826 void
26827 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
26828 {
26829 	tcp_t *listener = eager->tcp_listener;
26830 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
26831 
26832 	ASSERT(listener != NULL);
26833 	ASSERT(mp != NULL);
26834 
26835 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
26836 
26837 	/*
26838 	 * TLI/XTI applications will get confused by
26839 	 * sending eager as an option since it violates
26840 	 * the option semantics. So remove the eager as
26841 	 * option since TLI/XTI app doesn't need it anyway.
26842 	 */
26843 	if (!direct_sockfs) {
26844 		struct T_conn_ind *conn_ind;
26845 
26846 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
26847 		conn_ind->OPT_length = 0;
26848 		conn_ind->OPT_offset = 0;
26849 	}
26850 
26851 	/*
26852 	 * Sockfs guarantees that the listener will not be closed
26853 	 * during fallback. So we can safely use the listener's queue.
26854 	 */
26855 	putnext(listener->tcp_rq, mp);
26856 }
26857 
26858 int
26859 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
26860     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
26861 {
26862 	tcp_t			*tcp;
26863 	conn_t 			*connp = (conn_t *)proto_handle;
26864 	int			error;
26865 	mblk_t			*stropt_mp;
26866 	mblk_t			*ordrel_mp;
26867 
26868 	tcp = connp->conn_tcp;
26869 
26870 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
26871 	    NULL);
26872 
26873 	/* Pre-allocate the T_ordrel_ind mblk. */
26874 	ASSERT(tcp->tcp_ordrel_mp == NULL);
26875 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
26876 	    STR_NOSIG, NULL);
26877 	ordrel_mp->b_datap->db_type = M_PROTO;
26878 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
26879 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
26880 
26881 	/*
26882 	 * Enter the squeue so that no new packets can come in
26883 	 */
26884 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
26885 	if (error != 0) {
26886 		/* failed to enter, free all the pre-allocated messages. */
26887 		freeb(stropt_mp);
26888 		freeb(ordrel_mp);
26889 		/*
26890 		 * We cannot process the eager, so at least send out a
26891 		 * RST so the peer can reconnect.
26892 		 */
26893 		if (tcp->tcp_listener != NULL) {
26894 			(void) tcp_eager_blowoff(tcp->tcp_listener,
26895 			    tcp->tcp_conn_req_seqnum);
26896 		}
26897 		return (ENOMEM);
26898 	}
26899 
26900 	/*
26901 	 * Both endpoints must be of the same type (either STREAMS or
26902 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
26903 	 * we have to unfuse.
26904 	 */
26905 	if (tcp->tcp_fused)
26906 		tcp_unfuse(tcp);
26907 
26908 	/*
26909 	 * No longer a direct socket
26910 	 */
26911 	connp->conn_flags &= ~IPCL_NONSTR;
26912 	tcp->tcp_ordrel_mp = ordrel_mp;
26913 
26914 	if (tcp->tcp_listener != NULL) {
26915 		/* The eager will deal with opts when accept() is called */
26916 		freeb(stropt_mp);
26917 		tcp_fallback_eager(tcp, direct_sockfs);
26918 	} else {
26919 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
26920 		    quiesced_cb);
26921 	}
26922 
26923 	/*
26924 	 * There should be atleast two ref's (IP + TCP)
26925 	 */
26926 	ASSERT(connp->conn_ref >= 2);
26927 	squeue_synch_exit(connp->conn_sqp, connp);
26928 
26929 	return (0);
26930 }
26931 
26932 /* ARGSUSED */
26933 static void
26934 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
26935 {
26936 	conn_t 	*connp = (conn_t *)arg;
26937 	tcp_t	*tcp = connp->conn_tcp;
26938 
26939 	freemsg(mp);
26940 
26941 	if (tcp->tcp_fused)
26942 		tcp_unfuse(tcp);
26943 
26944 	if (tcp_xmit_end(tcp) != 0) {
26945 		/*
26946 		 * We were crossing FINs and got a reset from
26947 		 * the other side. Just ignore it.
26948 		 */
26949 		if (tcp->tcp_debug) {
26950 			(void) strlog(TCP_MOD_ID, 0, 1,
26951 			    SL_ERROR|SL_TRACE,
26952 			    "tcp_shutdown_output() out of state %s",
26953 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
26954 		}
26955 	}
26956 }
26957 
26958 /* ARGSUSED */
26959 int
26960 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
26961 {
26962 	conn_t  *connp = (conn_t *)proto_handle;
26963 	tcp_t   *tcp = connp->conn_tcp;
26964 
26965 	ASSERT(connp->conn_upper_handle != NULL);
26966 
26967 	/* All Solaris components should pass a cred for this operation. */
26968 	ASSERT(cr != NULL);
26969 
26970 	/*
26971 	 * X/Open requires that we check the connected state.
26972 	 */
26973 	if (tcp->tcp_state < TCPS_SYN_SENT)
26974 		return (ENOTCONN);
26975 
26976 	/* shutdown the send side */
26977 	if (how != SHUT_RD) {
26978 		mblk_t *bp;
26979 
26980 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
26981 		CONN_INC_REF(connp);
26982 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
26983 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
26984 
26985 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
26986 		    SOCK_OPCTL_SHUT_SEND, 0);
26987 	}
26988 
26989 	/* shutdown the recv side */
26990 	if (how != SHUT_WR)
26991 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
26992 		    SOCK_OPCTL_SHUT_RECV, 0);
26993 
26994 	return (0);
26995 }
26996 
26997 /*
26998  * SOP_LISTEN() calls into tcp_listen().
26999  */
27000 /* ARGSUSED */
27001 int
27002 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27003 {
27004 	conn_t	*connp = (conn_t *)proto_handle;
27005 	int 	error;
27006 	squeue_t *sqp = connp->conn_sqp;
27007 
27008 	ASSERT(connp->conn_upper_handle != NULL);
27009 
27010 	/* All Solaris components should pass a cred for this operation. */
27011 	ASSERT(cr != NULL);
27012 
27013 	error = squeue_synch_enter(sqp, connp, NULL);
27014 	if (error != 0) {
27015 		/* failed to enter */
27016 		return (ENOBUFS);
27017 	}
27018 
27019 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
27020 	if (error == 0) {
27021 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27022 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27023 	} else if (error < 0) {
27024 		if (error == -TOUTSTATE)
27025 			error = EINVAL;
27026 		else
27027 			error = proto_tlitosyserr(-error);
27028 	}
27029 	squeue_synch_exit(sqp, connp);
27030 	return (error);
27031 }
27032 
27033 static int
27034 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
27035     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
27036 {
27037 	tcp_t		*tcp = connp->conn_tcp;
27038 	int		error = 0;
27039 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27040 
27041 	/* All Solaris components should pass a cred for this operation. */
27042 	ASSERT(cr != NULL);
27043 
27044 	if (tcp->tcp_state >= TCPS_BOUND) {
27045 		if ((tcp->tcp_state == TCPS_BOUND ||
27046 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27047 			/*
27048 			 * Handle listen() increasing backlog.
27049 			 * This is more "liberal" then what the TPI spec
27050 			 * requires but is needed to avoid a t_unbind
27051 			 * when handling listen() since the port number
27052 			 * might be "stolen" between the unbind and bind.
27053 			 */
27054 			goto do_listen;
27055 		}
27056 		if (tcp->tcp_debug) {
27057 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27058 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27059 		}
27060 		return (-TOUTSTATE);
27061 	} else {
27062 		if (sa == NULL) {
27063 			sin6_t	addr;
27064 			sin_t *sin;
27065 			sin6_t *sin6;
27066 
27067 			ASSERT(IPCL_IS_NONSTR(connp));
27068 
27069 			/* Do an implicit bind: Request for a generic port. */
27070 			if (tcp->tcp_family == AF_INET) {
27071 				len = sizeof (sin_t);
27072 				sin = (sin_t *)&addr;
27073 				*sin = sin_null;
27074 				sin->sin_family = AF_INET;
27075 				tcp->tcp_ipversion = IPV4_VERSION;
27076 			} else {
27077 				ASSERT(tcp->tcp_family == AF_INET6);
27078 				len = sizeof (sin6_t);
27079 				sin6 = (sin6_t *)&addr;
27080 				*sin6 = sin6_null;
27081 				sin6->sin6_family = AF_INET6;
27082 				tcp->tcp_ipversion = IPV6_VERSION;
27083 			}
27084 			sa = (struct sockaddr *)&addr;
27085 		}
27086 
27087 		error = tcp_bind_check(connp, sa, len, cr,
27088 		    bind_to_req_port_only);
27089 		if (error)
27090 			return (error);
27091 		/* Fall through and do the fanout insertion */
27092 	}
27093 
27094 do_listen:
27095 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27096 	tcp->tcp_conn_req_max = backlog;
27097 	if (tcp->tcp_conn_req_max) {
27098 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27099 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27100 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27101 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27102 		/*
27103 		 * If this is a listener, do not reset the eager list
27104 		 * and other stuffs.  Note that we don't check if the
27105 		 * existing eager list meets the new tcp_conn_req_max
27106 		 * requirement.
27107 		 */
27108 		if (tcp->tcp_state != TCPS_LISTEN) {
27109 			tcp->tcp_state = TCPS_LISTEN;
27110 			/* Initialize the chain. Don't need the eager_lock */
27111 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27112 			tcp->tcp_eager_next_drop_q0 = tcp;
27113 			tcp->tcp_eager_prev_drop_q0 = tcp;
27114 			tcp->tcp_second_ctimer_threshold =
27115 			    tcps->tcps_ip_abort_linterval;
27116 		}
27117 	}
27118 
27119 	/*
27120 	 * We can call ip_bind directly, the processing continues
27121 	 * in tcp_post_ip_bind().
27122 	 *
27123 	 * We need to make sure that the conn_recv is set to a non-null
27124 	 * value before we insert the conn into the classifier table.
27125 	 * This is to avoid a race with an incoming packet which does an
27126 	 * ipcl_classify().
27127 	 */
27128 	connp->conn_recv = tcp_conn_request;
27129 	if (tcp->tcp_family == AF_INET) {
27130 		error = ip_proto_bind_laddr_v4(connp, NULL,
27131 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27132 	} else {
27133 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27134 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27135 	}
27136 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27137 }
27138 
27139 void
27140 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27141 {
27142 	conn_t  *connp = (conn_t *)proto_handle;
27143 	tcp_t	*tcp = connp->conn_tcp;
27144 	mblk_t *mp;
27145 	int error;
27146 
27147 	ASSERT(connp->conn_upper_handle != NULL);
27148 
27149 	/*
27150 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
27151 	 * is currently running.
27152 	 */
27153 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27154 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
27155 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
27156 		return;
27157 	}
27158 	tcp->tcp_rsrv_mp = NULL;
27159 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27160 
27161 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
27162 	ASSERT(error == 0);
27163 
27164 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27165 	tcp->tcp_rsrv_mp = mp;
27166 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27167 
27168 	if (tcp->tcp_fused) {
27169 		tcp_fuse_backenable(tcp);
27170 	} else {
27171 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27172 		/*
27173 		 * Send back a window update immediately if TCP is above
27174 		 * ESTABLISHED state and the increase of the rcv window
27175 		 * that the other side knows is at least 1 MSS after flow
27176 		 * control is lifted.
27177 		 */
27178 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27179 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
27180 			tcp_xmit_ctl(NULL, tcp,
27181 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27182 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27183 		}
27184 	}
27185 
27186 	squeue_synch_exit(connp->conn_sqp, connp);
27187 }
27188 
27189 /* ARGSUSED */
27190 int
27191 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27192     int mode, int32_t *rvalp, cred_t *cr)
27193 {
27194 	conn_t  	*connp = (conn_t *)proto_handle;
27195 	int		error;
27196 
27197 	ASSERT(connp->conn_upper_handle != NULL);
27198 
27199 	/* All Solaris components should pass a cred for this operation. */
27200 	ASSERT(cr != NULL);
27201 
27202 	switch (cmd) {
27203 		case ND_SET:
27204 		case ND_GET:
27205 		case TCP_IOC_DEFAULT_Q:
27206 		case _SIOCSOCKFALLBACK:
27207 		case TCP_IOC_ABORT_CONN:
27208 		case TI_GETPEERNAME:
27209 		case TI_GETMYNAME:
27210 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27211 			    cmd));
27212 			error = EINVAL;
27213 			break;
27214 		default:
27215 			/*
27216 			 * Pass on to IP using helper stream
27217 			 */
27218 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
27219 			    cmd, arg, mode, cr, rvalp);
27220 			break;
27221 	}
27222 	return (error);
27223 }
27224 
27225 sock_downcalls_t sock_tcp_downcalls = {
27226 	tcp_activate,
27227 	tcp_accept,
27228 	tcp_bind,
27229 	tcp_listen,
27230 	tcp_connect,
27231 	tcp_getpeername,
27232 	tcp_getsockname,
27233 	tcp_getsockopt,
27234 	tcp_setsockopt,
27235 	tcp_sendmsg,
27236 	NULL,
27237 	NULL,
27238 	NULL,
27239 	tcp_shutdown,
27240 	tcp_clr_flowctrl,
27241 	tcp_ioctl,
27242 	tcp_close,
27243 };
27244