xref: /titanic_51/usr/src/uts/common/inet/tcp/tcp.c (revision 050fa54035f294ec6c58427086e7635a70d94e07)
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 mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
778 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
779 static void	tcp_reinit(tcp_t *tcp);
780 static void	tcp_reinit_values(tcp_t *tcp);
781 
782 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
783 static uint_t	tcp_rcv_drain(tcp_t *tcp);
784 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
785 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
786 static void	tcp_ss_rexmit(tcp_t *tcp);
787 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
788 static void	tcp_process_options(tcp_t *, tcph_t *);
789 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
790 static void	tcp_rsrv(queue_t *q);
791 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
792 static int	tcp_snmp_state(tcp_t *tcp);
793 static void	tcp_timer(void *arg);
794 static void	tcp_timer_callback(void *);
795 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
796     boolean_t random);
797 static in_port_t tcp_get_next_priv_port(const tcp_t *);
798 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
799 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
800 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
801 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
802 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
803 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
804 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
805 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
806 		    const int num_sack_blk, int *usable, uint_t *snxt,
807 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
808 		    const int mdt_thres);
809 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
810 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
811 		    const int num_sack_blk, int *usable, uint_t *snxt,
812 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
813 		    const int mdt_thres);
814 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
815 		    int num_sack_blk);
816 static void	tcp_wsrv(queue_t *q);
817 static int	tcp_xmit_end(tcp_t *tcp);
818 static void	tcp_ack_timer(void *arg);
819 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
820 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
821 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
822 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
823 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
824 		    uint32_t ack, int ctl);
825 static int	setmaxps(queue_t *q, int maxpsz);
826 static void	tcp_set_rto(tcp_t *, time_t);
827 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
828 		    boolean_t, boolean_t);
829 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
830 		    boolean_t ipsec_mctl);
831 static int	tcp_build_hdrs(tcp_t *);
832 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
833 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
834 		    tcph_t *tcph);
835 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
836 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
837 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
838 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
839 		    const boolean_t, const uint32_t, const uint32_t,
840 		    const uint32_t, const uint32_t, tcp_stack_t *);
841 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
842 		    const uint_t, const uint_t, boolean_t *);
843 static mblk_t	*tcp_lso_info_mp(mblk_t *);
844 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
845 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
846 extern mblk_t	*tcp_timermp_alloc(int);
847 extern void	tcp_timermp_free(tcp_t *);
848 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
849 static void	tcp_stop_lingering(tcp_t *tcp);
850 static void	tcp_close_linger_timeout(void *arg);
851 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
852 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
853 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
854 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
855 static void	tcp_g_kstat_fini(kstat_t *);
856 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
857 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
858 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
859 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
860 static int	tcp_kstat_update(kstat_t *kp, int rw);
861 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
862 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
863 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
864 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
865 			tcph_t *tcph, mblk_t *idmp);
866 static int	tcp_squeue_switch(int);
867 
868 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
869 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
870 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
871 static int	tcp_tpi_close(queue_t *, int);
872 static int	tcp_tpi_close_accept(queue_t *);
873 
874 static void	tcp_squeue_add(squeue_t *);
875 static boolean_t tcp_zcopy_check(tcp_t *);
876 static void	tcp_zcopy_notify(tcp_t *);
877 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
878 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
879 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
880 
881 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
882 
883 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
884 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
885 
886 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
887 	    sock_upper_handle_t, cred_t *);
888 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
889 static int tcp_post_ip_bind(tcp_t *, mblk_t *, int, cred_t *, pid_t);
890 static int tcp_do_listen(conn_t *, struct sockaddr *, socklen_t, int, cred_t *,
891     boolean_t);
892 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
893     cred_t *, pid_t);
894 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
895     boolean_t);
896 static int tcp_do_unbind(conn_t *);
897 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
898     boolean_t);
899 
900 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_t *);
901 
902 /*
903  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
904  *
905  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
906  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
907  * (defined in tcp.h) needs to be filled in and passed into the kernel
908  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
909  * structure contains the four-tuple of a TCP connection and a range of TCP
910  * states (specified by ac_start and ac_end). The use of wildcard addresses
911  * and ports is allowed. Connections with a matching four tuple and a state
912  * within the specified range will be aborted. The valid states for the
913  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
914  * inclusive.
915  *
916  * An application which has its connection aborted by this ioctl will receive
917  * an error that is dependent on the connection state at the time of the abort.
918  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
919  * though a RST packet has been received.  If the connection state is equal to
920  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
921  * and all resources associated with the connection will be freed.
922  */
923 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
924 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
925 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
926 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
927 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
928 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
929     boolean_t, tcp_stack_t *);
930 
931 static struct module_info tcp_rinfo =  {
932 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
933 };
934 
935 static struct module_info tcp_winfo =  {
936 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
937 };
938 
939 /*
940  * Entry points for TCP as a device. The normal case which supports
941  * the TCP functionality.
942  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
943  */
944 struct qinit tcp_rinitv4 = {
945 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
946 };
947 
948 struct qinit tcp_rinitv6 = {
949 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
950 };
951 
952 struct qinit tcp_winit = {
953 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
954 };
955 
956 /* Initial entry point for TCP in socket mode. */
957 struct qinit tcp_sock_winit = {
958 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
959 };
960 
961 /* TCP entry point during fallback */
962 struct qinit tcp_fallback_sock_winit = {
963 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
964 };
965 
966 /*
967  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
968  * an accept. Avoid allocating data structures since eager has already
969  * been created.
970  */
971 struct qinit tcp_acceptor_rinit = {
972 	NULL, (pfi_t)tcp_rsrv, NULL, tcp_tpi_close_accept, NULL, &tcp_winfo
973 };
974 
975 struct qinit tcp_acceptor_winit = {
976 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
977 };
978 
979 /*
980  * Entry points for TCP loopback (read side only)
981  * The open routine is only used for reopens, thus no need to
982  * have a separate one for tcp_openv6.
983  */
984 struct qinit tcp_loopback_rinit = {
985 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, (pfi_t)0,
986 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
987 };
988 
989 /* For AF_INET aka /dev/tcp */
990 struct streamtab tcpinfov4 = {
991 	&tcp_rinitv4, &tcp_winit
992 };
993 
994 /* For AF_INET6 aka /dev/tcp6 */
995 struct streamtab tcpinfov6 = {
996 	&tcp_rinitv6, &tcp_winit
997 };
998 
999 sock_downcalls_t sock_tcp_downcalls;
1000 
1001 /*
1002  * Have to ensure that tcp_g_q_close is not done by an
1003  * interrupt thread.
1004  */
1005 static taskq_t *tcp_taskq;
1006 
1007 /* Setable only in /etc/system. Move to ndd? */
1008 boolean_t tcp_icmp_source_quench = B_FALSE;
1009 
1010 /*
1011  * Following assumes TPI alignment requirements stay along 32 bit
1012  * boundaries
1013  */
1014 #define	ROUNDUP32(x) \
1015 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1016 
1017 /* Template for response to info request. */
1018 static struct T_info_ack tcp_g_t_info_ack = {
1019 	T_INFO_ACK,		/* PRIM_type */
1020 	0,			/* TSDU_size */
1021 	T_INFINITE,		/* ETSDU_size */
1022 	T_INVALID,		/* CDATA_size */
1023 	T_INVALID,		/* DDATA_size */
1024 	sizeof (sin_t),		/* ADDR_size */
1025 	0,			/* OPT_size - not initialized here */
1026 	TIDUSZ,			/* TIDU_size */
1027 	T_COTS_ORD,		/* SERV_type */
1028 	TCPS_IDLE,		/* CURRENT_state */
1029 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1030 };
1031 
1032 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1033 	T_INFO_ACK,		/* PRIM_type */
1034 	0,			/* TSDU_size */
1035 	T_INFINITE,		/* ETSDU_size */
1036 	T_INVALID,		/* CDATA_size */
1037 	T_INVALID,		/* DDATA_size */
1038 	sizeof (sin6_t),	/* ADDR_size */
1039 	0,			/* OPT_size - not initialized here */
1040 	TIDUSZ,		/* TIDU_size */
1041 	T_COTS_ORD,		/* SERV_type */
1042 	TCPS_IDLE,		/* CURRENT_state */
1043 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1044 };
1045 
1046 #define	MS	1L
1047 #define	SECONDS	(1000 * MS)
1048 #define	MINUTES	(60 * SECONDS)
1049 #define	HOURS	(60 * MINUTES)
1050 #define	DAYS	(24 * HOURS)
1051 
1052 #define	PARAM_MAX (~(uint32_t)0)
1053 
1054 /* Max size IP datagram is 64k - 1 */
1055 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1056 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1057 /* Max of the above */
1058 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1059 
1060 /* Largest TCP port number */
1061 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1062 
1063 /*
1064  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1065  * layer header.  It has to be a multiple of 4.
1066  */
1067 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1068 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1069 
1070 /*
1071  * All of these are alterable, within the min/max values given, at run time.
1072  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1073  * per the TCP spec.
1074  */
1075 /* BEGIN CSTYLED */
1076 static tcpparam_t	lcl_tcp_param_arr[] = {
1077  /*min		max		value		name */
1078  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1079  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1080  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1081  { 1,		1024,		1,		"tcp_conn_req_min" },
1082  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1083  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1084  { 0,		10,		0,		"tcp_debug" },
1085  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1086  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1087  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1088  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1089  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1090  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1091  { 1,		255,		64,		"tcp_ipv4_ttl"},
1092  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1093  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1094  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1095  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1096  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1097  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1098  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1099  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1100  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1101  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1102  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1103  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1104  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1105  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1106  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1107  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1108  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1109  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1110  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1111  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1112  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1113  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1114  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1115 /*
1116  * Question:  What default value should I set for tcp_strong_iss?
1117  */
1118  { 0,		2,		1,		"tcp_strong_iss"},
1119  { 0,		65536,		20,		"tcp_rtt_updates"},
1120  { 0,		1,		1,		"tcp_wscale_always"},
1121  { 0,		1,		0,		"tcp_tstamp_always"},
1122  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1123  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1124  { 0,		16,		2,		"tcp_deferred_acks_max"},
1125  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1126  { 1,		4,		4,		"tcp_slow_start_initial"},
1127  { 0,		2,		2,		"tcp_sack_permitted"},
1128  { 0,		1,		1,		"tcp_compression_enabled"},
1129  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1130  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1131  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1132  { 0,		1,		0,		"tcp_rev_src_routes"},
1133  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1134  { 0,		16,		8,		"tcp_local_dacks_max"},
1135  { 0,		2,		1,		"tcp_ecn_permitted"},
1136  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1137  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1138  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1139  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1140  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1141 };
1142 /* END CSTYLED */
1143 
1144 /*
1145  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1146  * each header fragment in the header buffer.  Each parameter value has
1147  * to be a multiple of 4 (32-bit aligned).
1148  */
1149 static tcpparam_t lcl_tcp_mdt_head_param =
1150 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1151 static tcpparam_t lcl_tcp_mdt_tail_param =
1152 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1153 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1154 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1155 
1156 /*
1157  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1158  * the maximum number of payload buffers associated per Multidata.
1159  */
1160 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1161 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1162 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1163 
1164 /* Round up the value to the nearest mss. */
1165 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1166 
1167 /*
1168  * Set ECN capable transport (ECT) code point in IP header.
1169  *
1170  * Note that there are 2 ECT code points '01' and '10', which are called
1171  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1172  * point ECT(0) for TCP as described in RFC 2481.
1173  */
1174 #define	SET_ECT(tcp, iph) \
1175 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1176 		/* We need to clear the code point first. */ \
1177 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1178 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1179 	} else { \
1180 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1181 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1182 	}
1183 
1184 /*
1185  * The format argument to pass to tcp_display().
1186  * DISP_PORT_ONLY means that the returned string has only port info.
1187  * DISP_ADDR_AND_PORT means that the returned string also contains the
1188  * remote and local IP address.
1189  */
1190 #define	DISP_PORT_ONLY		1
1191 #define	DISP_ADDR_AND_PORT	2
1192 
1193 #define	IS_VMLOANED_MBLK(mp) \
1194 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1195 
1196 
1197 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1198 boolean_t tcp_mdt_chain = B_TRUE;
1199 
1200 /*
1201  * MDT threshold in the form of effective send MSS multiplier; we take
1202  * the MDT path if the amount of unsent data exceeds the threshold value
1203  * (default threshold is 1*SMSS).
1204  */
1205 uint_t tcp_mdt_smss_threshold = 1;
1206 
1207 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1208 
1209 /*
1210  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1211  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1212  * determined dynamically during tcp_adapt_ire(), which is the default.
1213  */
1214 boolean_t tcp_static_maxpsz = B_FALSE;
1215 
1216 /* Setable in /etc/system */
1217 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1218 uint32_t tcp_random_anon_port = 1;
1219 
1220 /*
1221  * To reach to an eager in Q0 which can be dropped due to an incoming
1222  * new SYN request when Q0 is full, a new doubly linked list is
1223  * introduced. This list allows to select an eager from Q0 in O(1) time.
1224  * This is needed to avoid spending too much time walking through the
1225  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1226  * this new list has to be a member of Q0.
1227  * This list is headed by listener's tcp_t. When the list is empty,
1228  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1229  * of listener's tcp_t point to listener's tcp_t itself.
1230  *
1231  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1232  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1233  * These macros do not affect the eager's membership to Q0.
1234  */
1235 
1236 
1237 #define	MAKE_DROPPABLE(listener, eager)					\
1238 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1239 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1240 		    = (eager);						\
1241 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1242 		(eager)->tcp_eager_next_drop_q0 =			\
1243 		    (listener)->tcp_eager_next_drop_q0;			\
1244 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1245 	}
1246 
1247 #define	MAKE_UNDROPPABLE(eager)						\
1248 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1249 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1250 		    = (eager)->tcp_eager_prev_drop_q0;			\
1251 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1252 		    = (eager)->tcp_eager_next_drop_q0;			\
1253 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1254 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1255 	}
1256 
1257 /*
1258  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1259  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1260  * data, TCP will not respond with an ACK.  RFC 793 requires that
1261  * TCP responds with an ACK for such a bogus ACK.  By not following
1262  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1263  * an attacker successfully spoofs an acceptable segment to our
1264  * peer; or when our peer is "confused."
1265  */
1266 uint32_t tcp_drop_ack_unsent_cnt = 10;
1267 
1268 /*
1269  * Hook functions to enable cluster networking
1270  * On non-clustered systems these vectors must always be NULL.
1271  */
1272 
1273 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1274 			    sa_family_t addr_family, uint8_t *laddrp,
1275 			    in_port_t lport, void *args) = NULL;
1276 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1277 			    sa_family_t addr_family, uint8_t *laddrp,
1278 			    in_port_t lport, void *args) = NULL;
1279 
1280 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1281 			    boolean_t is_outgoing,
1282 			    sa_family_t addr_family,
1283 			    uint8_t *laddrp, in_port_t lport,
1284 			    uint8_t *faddrp, in_port_t fport,
1285 			    void *args) = NULL;
1286 
1287 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1288 			    sa_family_t addr_family, uint8_t *laddrp,
1289 			    in_port_t lport, uint8_t *faddrp,
1290 			    in_port_t fport, void *args) = NULL;
1291 
1292 /*
1293  * The following are defined in ip.c
1294  */
1295 extern int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
1296 			    sa_family_t addr_family, uint8_t *laddrp,
1297 			    void *args);
1298 extern uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
1299 			    sa_family_t addr_family, uint8_t *laddrp,
1300 			    uint8_t *faddrp, void *args);
1301 
1302 
1303 /*
1304  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1305  */
1306 #define	CL_INET_CONNECT(connp, tcp, is_outgoing, err) {		\
1307 	(err) = 0;						\
1308 	if (cl_inet_connect2 != NULL) {				\
1309 		/*						\
1310 		 * Running in cluster mode - register active connection	\
1311 		 * information						\
1312 		 */							\
1313 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1314 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1315 				(err) = (*cl_inet_connect2)(		\
1316 				    (connp)->conn_netstack->netstack_stackid,\
1317 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1318 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1319 				    (in_port_t)(tcp)->tcp_lport,	\
1320 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1321 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1322 			}						\
1323 		} else {						\
1324 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1325 			    &(tcp)->tcp_ip6h->ip6_src)) {		\
1326 				(err) = (*cl_inet_connect2)(		\
1327 				    (connp)->conn_netstack->netstack_stackid,\
1328 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1329 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1330 				    (in_port_t)(tcp)->tcp_lport,	\
1331 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1332 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1333 			}						\
1334 		}							\
1335 	}								\
1336 }
1337 
1338 #define	CL_INET_DISCONNECT(connp, tcp)	{				\
1339 	if (cl_inet_disconnect != NULL) {				\
1340 		/*							\
1341 		 * Running in cluster mode - deregister active		\
1342 		 * connection information				\
1343 		 */							\
1344 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1345 			if ((tcp)->tcp_ip_src != 0) {			\
1346 				(*cl_inet_disconnect)(			\
1347 				    (connp)->conn_netstack->netstack_stackid,\
1348 				    IPPROTO_TCP, AF_INET,		\
1349 				    (uint8_t *)(&((tcp)->tcp_ip_src)),	\
1350 				    (in_port_t)(tcp)->tcp_lport,	\
1351 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1352 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1353 			}						\
1354 		} else {						\
1355 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1356 			    &(tcp)->tcp_ip_src_v6)) {			\
1357 				(*cl_inet_disconnect)(			\
1358 				    (connp)->conn_netstack->netstack_stackid,\
1359 				    IPPROTO_TCP, AF_INET6,		\
1360 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1361 				    (in_port_t)(tcp)->tcp_lport,	\
1362 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1363 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1364 			}						\
1365 		}							\
1366 	}								\
1367 }
1368 
1369 /*
1370  * Cluster networking hook for traversing current connection list.
1371  * This routine is used to extract the current list of live connections
1372  * which must continue to to be dispatched to this node.
1373  */
1374 int cl_tcp_walk_list(netstackid_t stack_id,
1375     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1376 
1377 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1378     void *arg, tcp_stack_t *tcps);
1379 
1380 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1381 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1382 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1383 	    ip6_t *, ip6h, int, 0);
1384 
1385 /*
1386  * Figure out the value of window scale opton.  Note that the rwnd is
1387  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1388  * We cannot find the scale value and then do a round up of tcp_rwnd
1389  * because the scale value may not be correct after that.
1390  *
1391  * Set the compiler flag to make this function inline.
1392  */
1393 static void
1394 tcp_set_ws_value(tcp_t *tcp)
1395 {
1396 	int i;
1397 	uint32_t rwnd = tcp->tcp_rwnd;
1398 
1399 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1400 	    i++, rwnd >>= 1)
1401 		;
1402 	tcp->tcp_rcv_ws = i;
1403 }
1404 
1405 /*
1406  * Remove a connection from the list of detached TIME_WAIT connections.
1407  * It returns B_FALSE if it can't remove the connection from the list
1408  * as the connection has already been removed from the list due to an
1409  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1410  */
1411 static boolean_t
1412 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1413 {
1414 	boolean_t	locked = B_FALSE;
1415 
1416 	if (tcp_time_wait == NULL) {
1417 		tcp_time_wait = *((tcp_squeue_priv_t **)
1418 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1419 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1420 		locked = B_TRUE;
1421 	} else {
1422 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1423 	}
1424 
1425 	if (tcp->tcp_time_wait_expire == 0) {
1426 		ASSERT(tcp->tcp_time_wait_next == NULL);
1427 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1428 		if (locked)
1429 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1430 		return (B_FALSE);
1431 	}
1432 	ASSERT(TCP_IS_DETACHED(tcp));
1433 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1434 
1435 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1436 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1437 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1438 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1439 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1440 			    NULL;
1441 		} else {
1442 			tcp_time_wait->tcp_time_wait_tail = NULL;
1443 		}
1444 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1445 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1446 		ASSERT(tcp->tcp_time_wait_next == NULL);
1447 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1448 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1449 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1450 	} else {
1451 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1452 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1453 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1454 		    tcp->tcp_time_wait_next;
1455 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1456 		    tcp->tcp_time_wait_prev;
1457 	}
1458 	tcp->tcp_time_wait_next = NULL;
1459 	tcp->tcp_time_wait_prev = NULL;
1460 	tcp->tcp_time_wait_expire = 0;
1461 
1462 	if (locked)
1463 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1464 	return (B_TRUE);
1465 }
1466 
1467 /*
1468  * Add a connection to the list of detached TIME_WAIT connections
1469  * and set its time to expire.
1470  */
1471 static void
1472 tcp_time_wait_append(tcp_t *tcp)
1473 {
1474 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1475 	tcp_squeue_priv_t *tcp_time_wait =
1476 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1477 	    SQPRIVATE_TCP));
1478 
1479 	tcp_timers_stop(tcp);
1480 
1481 	/* Freed above */
1482 	ASSERT(tcp->tcp_timer_tid == 0);
1483 	ASSERT(tcp->tcp_ack_tid == 0);
1484 
1485 	/* must have happened at the time of detaching the tcp */
1486 	ASSERT(tcp->tcp_ptpahn == NULL);
1487 	ASSERT(tcp->tcp_flow_stopped == 0);
1488 	ASSERT(tcp->tcp_time_wait_next == NULL);
1489 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1490 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1491 	ASSERT(tcp->tcp_listener == NULL);
1492 
1493 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1494 	/*
1495 	 * The value computed below in tcp->tcp_time_wait_expire may
1496 	 * appear negative or wrap around. That is ok since our
1497 	 * interest is only in the difference between the current lbolt
1498 	 * value and tcp->tcp_time_wait_expire. But the value should not
1499 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1500 	 * The corresponding comparison in tcp_time_wait_collector() uses
1501 	 * modular arithmetic.
1502 	 */
1503 	tcp->tcp_time_wait_expire +=
1504 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1505 	if (tcp->tcp_time_wait_expire == 0)
1506 		tcp->tcp_time_wait_expire = 1;
1507 
1508 	ASSERT(TCP_IS_DETACHED(tcp));
1509 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1510 	ASSERT(tcp->tcp_time_wait_next == NULL);
1511 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1512 	TCP_DBGSTAT(tcps, tcp_time_wait);
1513 
1514 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1515 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1516 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1517 		tcp_time_wait->tcp_time_wait_head = tcp;
1518 	} else {
1519 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1520 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1521 		    TCPS_TIME_WAIT);
1522 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1523 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1524 	}
1525 	tcp_time_wait->tcp_time_wait_tail = tcp;
1526 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1527 }
1528 
1529 /* ARGSUSED */
1530 void
1531 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1532 {
1533 	conn_t	*connp = (conn_t *)arg;
1534 	tcp_t	*tcp = connp->conn_tcp;
1535 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1536 
1537 	ASSERT(tcp != NULL);
1538 	if (tcp->tcp_state == TCPS_CLOSED) {
1539 		return;
1540 	}
1541 
1542 	ASSERT((tcp->tcp_family == AF_INET &&
1543 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1544 	    (tcp->tcp_family == AF_INET6 &&
1545 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1546 	    tcp->tcp_ipversion == IPV6_VERSION)));
1547 	ASSERT(!tcp->tcp_listener);
1548 
1549 	TCP_STAT(tcps, tcp_time_wait_reap);
1550 	ASSERT(TCP_IS_DETACHED(tcp));
1551 
1552 	/*
1553 	 * Because they have no upstream client to rebind or tcp_close()
1554 	 * them later, we axe the connection here and now.
1555 	 */
1556 	tcp_close_detached(tcp);
1557 }
1558 
1559 /*
1560  * Remove cached/latched IPsec references.
1561  */
1562 void
1563 tcp_ipsec_cleanup(tcp_t *tcp)
1564 {
1565 	conn_t		*connp = tcp->tcp_connp;
1566 
1567 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1568 
1569 	if (connp->conn_latch != NULL) {
1570 		IPLATCH_REFRELE(connp->conn_latch,
1571 		    connp->conn_netstack);
1572 		connp->conn_latch = NULL;
1573 	}
1574 	if (connp->conn_policy != NULL) {
1575 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1576 		connp->conn_policy = NULL;
1577 	}
1578 }
1579 
1580 /*
1581  * Cleaup before placing on free list.
1582  * Disassociate from the netstack/tcp_stack_t since the freelist
1583  * is per squeue and not per netstack.
1584  */
1585 void
1586 tcp_cleanup(tcp_t *tcp)
1587 {
1588 	mblk_t		*mp;
1589 	char		*tcp_iphc;
1590 	int		tcp_iphc_len;
1591 	int		tcp_hdr_grown;
1592 	tcp_sack_info_t	*tcp_sack_info;
1593 	conn_t		*connp = tcp->tcp_connp;
1594 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1595 	netstack_t	*ns = tcps->tcps_netstack;
1596 	mblk_t		*tcp_rsrv_mp;
1597 
1598 	tcp_bind_hash_remove(tcp);
1599 
1600 	/* Cleanup that which needs the netstack first */
1601 	tcp_ipsec_cleanup(tcp);
1602 
1603 	tcp_free(tcp);
1604 
1605 	/* Release any SSL context */
1606 	if (tcp->tcp_kssl_ent != NULL) {
1607 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1608 		tcp->tcp_kssl_ent = NULL;
1609 	}
1610 
1611 	if (tcp->tcp_kssl_ctx != NULL) {
1612 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1613 		tcp->tcp_kssl_ctx = NULL;
1614 	}
1615 	tcp->tcp_kssl_pending = B_FALSE;
1616 
1617 	conn_delete_ire(connp, NULL);
1618 
1619 	/*
1620 	 * Since we will bzero the entire structure, we need to
1621 	 * remove it and reinsert it in global hash list. We
1622 	 * know the walkers can't get to this conn because we
1623 	 * had set CONDEMNED flag earlier and checked reference
1624 	 * under conn_lock so walker won't pick it and when we
1625 	 * go the ipcl_globalhash_remove() below, no walker
1626 	 * can get to it.
1627 	 */
1628 	ipcl_globalhash_remove(connp);
1629 
1630 	/*
1631 	 * Now it is safe to decrement the reference counts.
1632 	 * This might be the last reference on the netstack and TCPS
1633 	 * in which case it will cause the tcp_g_q_close and
1634 	 * the freeing of the IP Instance.
1635 	 */
1636 	connp->conn_netstack = NULL;
1637 	netstack_rele(ns);
1638 	ASSERT(tcps != NULL);
1639 	tcp->tcp_tcps = NULL;
1640 	TCPS_REFRELE(tcps);
1641 
1642 	/* Save some state */
1643 	mp = tcp->tcp_timercache;
1644 
1645 	tcp_sack_info = tcp->tcp_sack_info;
1646 	tcp_iphc = tcp->tcp_iphc;
1647 	tcp_iphc_len = tcp->tcp_iphc_len;
1648 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1649 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1650 
1651 	if (connp->conn_cred != NULL) {
1652 		crfree(connp->conn_cred);
1653 		connp->conn_cred = NULL;
1654 	}
1655 	if (connp->conn_effective_cred != NULL) {
1656 		crfree(connp->conn_effective_cred);
1657 		connp->conn_effective_cred = NULL;
1658 	}
1659 	ipcl_conn_cleanup(connp);
1660 	connp->conn_flags = IPCL_TCPCONN;
1661 	bzero(tcp, sizeof (tcp_t));
1662 
1663 	/* restore the state */
1664 	tcp->tcp_timercache = mp;
1665 
1666 	tcp->tcp_sack_info = tcp_sack_info;
1667 	tcp->tcp_iphc = tcp_iphc;
1668 	tcp->tcp_iphc_len = tcp_iphc_len;
1669 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1670 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1671 
1672 	tcp->tcp_connp = connp;
1673 
1674 	ASSERT(connp->conn_tcp == tcp);
1675 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1676 	connp->conn_state_flags = CONN_INCIPIENT;
1677 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1678 	ASSERT(connp->conn_ref == 1);
1679 }
1680 
1681 /*
1682  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1683  * is done forwards from the head.
1684  * This walks all stack instances since
1685  * tcp_time_wait remains global across all stacks.
1686  */
1687 /* ARGSUSED */
1688 void
1689 tcp_time_wait_collector(void *arg)
1690 {
1691 	tcp_t *tcp;
1692 	clock_t now;
1693 	mblk_t *mp;
1694 	conn_t *connp;
1695 	kmutex_t *lock;
1696 	boolean_t removed;
1697 
1698 	squeue_t *sqp = (squeue_t *)arg;
1699 	tcp_squeue_priv_t *tcp_time_wait =
1700 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1701 
1702 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1703 	tcp_time_wait->tcp_time_wait_tid = 0;
1704 
1705 	if (tcp_time_wait->tcp_free_list != NULL &&
1706 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1707 		TCP_G_STAT(tcp_freelist_cleanup);
1708 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1709 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1710 			tcp->tcp_time_wait_next = NULL;
1711 			tcp_time_wait->tcp_free_list_cnt--;
1712 			ASSERT(tcp->tcp_tcps == NULL);
1713 			CONN_DEC_REF(tcp->tcp_connp);
1714 		}
1715 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1716 	}
1717 
1718 	/*
1719 	 * In order to reap time waits reliably, we should use a
1720 	 * source of time that is not adjustable by the user -- hence
1721 	 * the call to ddi_get_lbolt().
1722 	 */
1723 	now = ddi_get_lbolt();
1724 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1725 		/*
1726 		 * Compare times using modular arithmetic, since
1727 		 * lbolt can wrapover.
1728 		 */
1729 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1730 			break;
1731 		}
1732 
1733 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1734 		ASSERT(removed);
1735 
1736 		connp = tcp->tcp_connp;
1737 		ASSERT(connp->conn_fanout != NULL);
1738 		lock = &connp->conn_fanout->connf_lock;
1739 		/*
1740 		 * This is essentially a TW reclaim fast path optimization for
1741 		 * performance where the timewait collector checks under the
1742 		 * fanout lock (so that no one else can get access to the
1743 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1744 		 * the classifier hash list. If ref count is indeed 2, we can
1745 		 * just remove the conn under the fanout lock and avoid
1746 		 * cleaning up the conn under the squeue, provided that
1747 		 * clustering callbacks are not enabled. If clustering is
1748 		 * enabled, we need to make the clustering callback before
1749 		 * setting the CONDEMNED flag and after dropping all locks and
1750 		 * so we forego this optimization and fall back to the slow
1751 		 * path. Also please see the comments in tcp_closei_local
1752 		 * regarding the refcnt logic.
1753 		 *
1754 		 * Since we are holding the tcp_time_wait_lock, its better
1755 		 * not to block on the fanout_lock because other connections
1756 		 * can't add themselves to time_wait list. So we do a
1757 		 * tryenter instead of mutex_enter.
1758 		 */
1759 		if (mutex_tryenter(lock)) {
1760 			mutex_enter(&connp->conn_lock);
1761 			if ((connp->conn_ref == 2) &&
1762 			    (cl_inet_disconnect == NULL)) {
1763 				ipcl_hash_remove_locked(connp,
1764 				    connp->conn_fanout);
1765 				/*
1766 				 * Set the CONDEMNED flag now itself so that
1767 				 * the refcnt cannot increase due to any
1768 				 * walker. But we have still not cleaned up
1769 				 * conn_ire_cache. This is still ok since
1770 				 * we are going to clean it up in tcp_cleanup
1771 				 * immediately and any interface unplumb
1772 				 * thread will wait till the ire is blown away
1773 				 */
1774 				connp->conn_state_flags |= CONN_CONDEMNED;
1775 				mutex_exit(lock);
1776 				mutex_exit(&connp->conn_lock);
1777 				if (tcp_time_wait->tcp_free_list_cnt <
1778 				    tcp_free_list_max_cnt) {
1779 					/* Add to head of tcp_free_list */
1780 					mutex_exit(
1781 					    &tcp_time_wait->tcp_time_wait_lock);
1782 					tcp_cleanup(tcp);
1783 					ASSERT(connp->conn_latch == NULL);
1784 					ASSERT(connp->conn_policy == NULL);
1785 					ASSERT(tcp->tcp_tcps == NULL);
1786 					ASSERT(connp->conn_netstack == NULL);
1787 
1788 					mutex_enter(
1789 					    &tcp_time_wait->tcp_time_wait_lock);
1790 					tcp->tcp_time_wait_next =
1791 					    tcp_time_wait->tcp_free_list;
1792 					tcp_time_wait->tcp_free_list = tcp;
1793 					tcp_time_wait->tcp_free_list_cnt++;
1794 					continue;
1795 				} else {
1796 					/* Do not add to tcp_free_list */
1797 					mutex_exit(
1798 					    &tcp_time_wait->tcp_time_wait_lock);
1799 					tcp_bind_hash_remove(tcp);
1800 					conn_delete_ire(tcp->tcp_connp, NULL);
1801 					tcp_ipsec_cleanup(tcp);
1802 					CONN_DEC_REF(tcp->tcp_connp);
1803 				}
1804 			} else {
1805 				CONN_INC_REF_LOCKED(connp);
1806 				mutex_exit(lock);
1807 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1808 				mutex_exit(&connp->conn_lock);
1809 				/*
1810 				 * We can reuse the closemp here since conn has
1811 				 * detached (otherwise we wouldn't even be in
1812 				 * time_wait list). tcp_closemp_used can safely
1813 				 * be changed without taking a lock as no other
1814 				 * thread can concurrently access it at this
1815 				 * point in the connection lifecycle.
1816 				 */
1817 
1818 				if (tcp->tcp_closemp.b_prev == NULL)
1819 					tcp->tcp_closemp_used = B_TRUE;
1820 				else
1821 					cmn_err(CE_PANIC,
1822 					    "tcp_timewait_collector: "
1823 					    "concurrent use of tcp_closemp: "
1824 					    "connp %p tcp %p\n", (void *)connp,
1825 					    (void *)tcp);
1826 
1827 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1828 				mp = &tcp->tcp_closemp;
1829 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1830 				    tcp_timewait_output, connp,
1831 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1832 			}
1833 		} else {
1834 			mutex_enter(&connp->conn_lock);
1835 			CONN_INC_REF_LOCKED(connp);
1836 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1837 			mutex_exit(&connp->conn_lock);
1838 			/*
1839 			 * We can reuse the closemp here since conn has
1840 			 * detached (otherwise we wouldn't even be in
1841 			 * time_wait list). tcp_closemp_used can safely
1842 			 * be changed without taking a lock as no other
1843 			 * thread can concurrently access it at this
1844 			 * point in the connection lifecycle.
1845 			 */
1846 
1847 			if (tcp->tcp_closemp.b_prev == NULL)
1848 				tcp->tcp_closemp_used = B_TRUE;
1849 			else
1850 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1851 				    "concurrent use of tcp_closemp: "
1852 				    "connp %p tcp %p\n", (void *)connp,
1853 				    (void *)tcp);
1854 
1855 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1856 			mp = &tcp->tcp_closemp;
1857 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1858 			    tcp_timewait_output, connp,
1859 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1860 		}
1861 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1862 	}
1863 
1864 	if (tcp_time_wait->tcp_free_list != NULL)
1865 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1866 
1867 	tcp_time_wait->tcp_time_wait_tid =
1868 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1869 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1870 	    CALLOUT_FLAG_ROUNDUP);
1871 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1872 }
1873 
1874 /*
1875  * Reply to a clients T_CONN_RES TPI message. This function
1876  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1877  * on the acceptor STREAM and processed in tcp_wput_accept().
1878  * Read the block comment on top of tcp_conn_request().
1879  */
1880 static void
1881 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1882 {
1883 	tcp_t	*acceptor;
1884 	tcp_t	*eager;
1885 	tcp_t   *tcp;
1886 	struct T_conn_res	*tcr;
1887 	t_uscalar_t	acceptor_id;
1888 	t_scalar_t	seqnum;
1889 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1890 	struct tcp_options *tcpopt;
1891 	mblk_t	*ok_mp;
1892 	mblk_t	*mp1;
1893 	tcp_stack_t	*tcps = listener->tcp_tcps;
1894 	int	error;
1895 
1896 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1897 		tcp_err_ack(listener, mp, TPROTO, 0);
1898 		return;
1899 	}
1900 	tcr = (struct T_conn_res *)mp->b_rptr;
1901 
1902 	/*
1903 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1904 	 * read side queue of the streams device underneath us i.e. the
1905 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1906 	 * look it up in the queue_hash.  Under LP64 it sends down the
1907 	 * minor_t of the accepting endpoint.
1908 	 *
1909 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1910 	 * fanout hash lock is held.
1911 	 * This prevents any thread from entering the acceptor queue from
1912 	 * below (since it has not been hard bound yet i.e. any inbound
1913 	 * packets will arrive on the listener or default tcp queue and
1914 	 * go through tcp_lookup).
1915 	 * The CONN_INC_REF will prevent the acceptor from closing.
1916 	 *
1917 	 * XXX It is still possible for a tli application to send down data
1918 	 * on the accepting stream while another thread calls t_accept.
1919 	 * This should not be a problem for well-behaved applications since
1920 	 * the T_OK_ACK is sent after the queue swapping is completed.
1921 	 *
1922 	 * If the accepting fd is the same as the listening fd, avoid
1923 	 * queue hash lookup since that will return an eager listener in a
1924 	 * already established state.
1925 	 */
1926 	acceptor_id = tcr->ACCEPTOR_id;
1927 	mutex_enter(&listener->tcp_eager_lock);
1928 	if (listener->tcp_acceptor_id == acceptor_id) {
1929 		eager = listener->tcp_eager_next_q;
1930 		/* only count how many T_CONN_INDs so don't count q0 */
1931 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1932 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1933 			mutex_exit(&listener->tcp_eager_lock);
1934 			tcp_err_ack(listener, mp, TBADF, 0);
1935 			return;
1936 		}
1937 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1938 			/* Throw away all the eagers on q0. */
1939 			tcp_eager_cleanup(listener, 1);
1940 		}
1941 		if (listener->tcp_syn_defense) {
1942 			listener->tcp_syn_defense = B_FALSE;
1943 			if (listener->tcp_ip_addr_cache != NULL) {
1944 				kmem_free(listener->tcp_ip_addr_cache,
1945 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1946 				listener->tcp_ip_addr_cache = NULL;
1947 			}
1948 		}
1949 		/*
1950 		 * Transfer tcp_conn_req_max to the eager so that when
1951 		 * a disconnect occurs we can revert the endpoint to the
1952 		 * listen state.
1953 		 */
1954 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1955 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1956 		/*
1957 		 * Get a reference on the acceptor just like the
1958 		 * tcp_acceptor_hash_lookup below.
1959 		 */
1960 		acceptor = listener;
1961 		CONN_INC_REF(acceptor->tcp_connp);
1962 	} else {
1963 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1964 		if (acceptor == NULL) {
1965 			if (listener->tcp_debug) {
1966 				(void) strlog(TCP_MOD_ID, 0, 1,
1967 				    SL_ERROR|SL_TRACE,
1968 				    "tcp_accept: did not find acceptor 0x%x\n",
1969 				    acceptor_id);
1970 			}
1971 			mutex_exit(&listener->tcp_eager_lock);
1972 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1973 			return;
1974 		}
1975 		/*
1976 		 * Verify acceptor state. The acceptable states for an acceptor
1977 		 * include TCPS_IDLE and TCPS_BOUND.
1978 		 */
1979 		switch (acceptor->tcp_state) {
1980 		case TCPS_IDLE:
1981 			/* FALLTHRU */
1982 		case TCPS_BOUND:
1983 			break;
1984 		default:
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 	/* The listener must be in TCPS_LISTEN */
1993 	if (listener->tcp_state != TCPS_LISTEN) {
1994 		CONN_DEC_REF(acceptor->tcp_connp);
1995 		mutex_exit(&listener->tcp_eager_lock);
1996 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
1997 		return;
1998 	}
1999 
2000 	/*
2001 	 * Rendezvous with an eager connection request packet hanging off
2002 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2003 	 * tcp structure when the connection packet arrived in
2004 	 * tcp_conn_request().
2005 	 */
2006 	seqnum = tcr->SEQ_number;
2007 	eager = listener;
2008 	do {
2009 		eager = eager->tcp_eager_next_q;
2010 		if (eager == NULL) {
2011 			CONN_DEC_REF(acceptor->tcp_connp);
2012 			mutex_exit(&listener->tcp_eager_lock);
2013 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2014 			return;
2015 		}
2016 	} while (eager->tcp_conn_req_seqnum != seqnum);
2017 	mutex_exit(&listener->tcp_eager_lock);
2018 
2019 	/*
2020 	 * At this point, both acceptor and listener have 2 ref
2021 	 * that they begin with. Acceptor has one additional ref
2022 	 * we placed in lookup while listener has 3 additional
2023 	 * ref for being behind the squeue (tcp_accept() is
2024 	 * done on listener's squeue); being in classifier hash;
2025 	 * and eager's ref on listener.
2026 	 */
2027 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2028 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2029 
2030 	/*
2031 	 * The eager at this point is set in its own squeue and
2032 	 * could easily have been killed (tcp_accept_finish will
2033 	 * deal with that) because of a TH_RST so we can only
2034 	 * ASSERT for a single ref.
2035 	 */
2036 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2037 
2038 	/* Pre allocate the stroptions mblk also */
2039 	opt_mp = allocb(MAX(sizeof (struct tcp_options),
2040 	    sizeof (struct T_conn_res)), BPRI_HI);
2041 	if (opt_mp == NULL) {
2042 		CONN_DEC_REF(acceptor->tcp_connp);
2043 		CONN_DEC_REF(eager->tcp_connp);
2044 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2045 		return;
2046 	}
2047 	DB_TYPE(opt_mp) = M_SETOPTS;
2048 	opt_mp->b_wptr += sizeof (struct tcp_options);
2049 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
2050 	tcpopt->to_flags = 0;
2051 
2052 	/*
2053 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2054 	 * from listener to acceptor.
2055 	 */
2056 	if (listener->tcp_bound_if != 0) {
2057 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
2058 		tcpopt->to_boundif = listener->tcp_bound_if;
2059 	}
2060 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2061 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
2062 	}
2063 
2064 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2065 	if ((mp1 = copymsg(mp)) == NULL) {
2066 		CONN_DEC_REF(acceptor->tcp_connp);
2067 		CONN_DEC_REF(eager->tcp_connp);
2068 		freemsg(opt_mp);
2069 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2070 		return;
2071 	}
2072 
2073 	tcr = (struct T_conn_res *)mp1->b_rptr;
2074 
2075 	/*
2076 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2077 	 * which allocates a larger mblk and appends the new
2078 	 * local address to the ok_ack.  The address is copied by
2079 	 * soaccept() for getsockname().
2080 	 */
2081 	{
2082 		int extra;
2083 
2084 		extra = (eager->tcp_family == AF_INET) ?
2085 		    sizeof (sin_t) : sizeof (sin6_t);
2086 
2087 		/*
2088 		 * Try to re-use mp, if possible.  Otherwise, allocate
2089 		 * an mblk and return it as ok_mp.  In any case, mp
2090 		 * is no longer usable upon return.
2091 		 */
2092 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2093 			CONN_DEC_REF(acceptor->tcp_connp);
2094 			CONN_DEC_REF(eager->tcp_connp);
2095 			freemsg(opt_mp);
2096 			/* Original mp has been freed by now, so use mp1 */
2097 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2098 			return;
2099 		}
2100 
2101 		mp = NULL;	/* We should never use mp after this point */
2102 
2103 		switch (extra) {
2104 		case sizeof (sin_t): {
2105 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2106 
2107 				ok_mp->b_wptr += extra;
2108 				sin->sin_family = AF_INET;
2109 				sin->sin_port = eager->tcp_lport;
2110 				sin->sin_addr.s_addr =
2111 				    eager->tcp_ipha->ipha_src;
2112 				break;
2113 			}
2114 		case sizeof (sin6_t): {
2115 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2116 
2117 				ok_mp->b_wptr += extra;
2118 				sin6->sin6_family = AF_INET6;
2119 				sin6->sin6_port = eager->tcp_lport;
2120 				if (eager->tcp_ipversion == IPV4_VERSION) {
2121 					sin6->sin6_flowinfo = 0;
2122 					IN6_IPADDR_TO_V4MAPPED(
2123 					    eager->tcp_ipha->ipha_src,
2124 					    &sin6->sin6_addr);
2125 				} else {
2126 					ASSERT(eager->tcp_ip6h != NULL);
2127 					sin6->sin6_flowinfo =
2128 					    eager->tcp_ip6h->ip6_vcf &
2129 					    ~IPV6_VERS_AND_FLOW_MASK;
2130 					sin6->sin6_addr =
2131 					    eager->tcp_ip6h->ip6_src;
2132 				}
2133 				sin6->sin6_scope_id = 0;
2134 				sin6->__sin6_src_id = 0;
2135 				break;
2136 			}
2137 		default:
2138 			break;
2139 		}
2140 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2141 	}
2142 
2143 	/*
2144 	 * If there are no options we know that the T_CONN_RES will
2145 	 * succeed. However, we can't send the T_OK_ACK upstream until
2146 	 * the tcp_accept_swap is done since it would be dangerous to
2147 	 * let the application start using the new fd prior to the swap.
2148 	 */
2149 	error = tcp_accept_swap(listener, acceptor, eager);
2150 	if (error != 0) {
2151 		CONN_DEC_REF(acceptor->tcp_connp);
2152 		CONN_DEC_REF(eager->tcp_connp);
2153 		freemsg(ok_mp);
2154 		/* Original mp has been freed by now, so use mp1 */
2155 		tcp_err_ack(listener, mp1, TSYSERR, error);
2156 		return;
2157 	}
2158 
2159 	/*
2160 	 * tcp_accept_swap unlinks eager from listener but does not drop
2161 	 * the eager's reference on the listener.
2162 	 */
2163 	ASSERT(eager->tcp_listener == NULL);
2164 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2165 
2166 	/*
2167 	 * The eager is now associated with its own queue. Insert in
2168 	 * the hash so that the connection can be reused for a future
2169 	 * T_CONN_RES.
2170 	 */
2171 	tcp_acceptor_hash_insert(acceptor_id, eager);
2172 
2173 	/*
2174 	 * We now do the processing of options with T_CONN_RES.
2175 	 * We delay till now since we wanted to have queue to pass to
2176 	 * option processing routines that points back to the right
2177 	 * instance structure which does not happen until after
2178 	 * tcp_accept_swap().
2179 	 *
2180 	 * Note:
2181 	 * The sanity of the logic here assumes that whatever options
2182 	 * are appropriate to inherit from listner=>eager are done
2183 	 * before this point, and whatever were to be overridden (or not)
2184 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2185 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2186 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2187 	 * This may not be true at this point in time but can be fixed
2188 	 * independently. This option processing code starts with
2189 	 * the instantiated acceptor instance and the final queue at
2190 	 * this point.
2191 	 */
2192 
2193 	if (tcr->OPT_length != 0) {
2194 		/* Options to process */
2195 		int t_error = 0;
2196 		int sys_error = 0;
2197 		int do_disconnect = 0;
2198 
2199 		if (tcp_conprim_opt_process(eager, mp1,
2200 		    &do_disconnect, &t_error, &sys_error) < 0) {
2201 			eager->tcp_accept_error = 1;
2202 			if (do_disconnect) {
2203 				/*
2204 				 * An option failed which does not allow
2205 				 * connection to be accepted.
2206 				 *
2207 				 * We allow T_CONN_RES to succeed and
2208 				 * put a T_DISCON_IND on the eager queue.
2209 				 */
2210 				ASSERT(t_error == 0 && sys_error == 0);
2211 				eager->tcp_send_discon_ind = 1;
2212 			} else {
2213 				ASSERT(t_error != 0);
2214 				freemsg(ok_mp);
2215 				/*
2216 				 * Original mp was either freed or set
2217 				 * to ok_mp above, so use mp1 instead.
2218 				 */
2219 				tcp_err_ack(listener, mp1, t_error, sys_error);
2220 				goto finish;
2221 			}
2222 		}
2223 		/*
2224 		 * Most likely success in setting options (except if
2225 		 * eager->tcp_send_discon_ind set).
2226 		 * mp1 option buffer represented by OPT_length/offset
2227 		 * potentially modified and contains results of setting
2228 		 * options at this point
2229 		 */
2230 	}
2231 
2232 	/* We no longer need mp1, since all options processing has passed */
2233 	freemsg(mp1);
2234 
2235 	putnext(listener->tcp_rq, ok_mp);
2236 
2237 	mutex_enter(&listener->tcp_eager_lock);
2238 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2239 		tcp_t	*tail;
2240 		mblk_t	*conn_ind;
2241 
2242 		/*
2243 		 * This path should not be executed if listener and
2244 		 * acceptor streams are the same.
2245 		 */
2246 		ASSERT(listener != acceptor);
2247 
2248 		tcp = listener->tcp_eager_prev_q0;
2249 		/*
2250 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2251 		 * deferred T_conn_ind queue. We need to get to the head of
2252 		 * the queue in order to send up T_conn_ind the same order as
2253 		 * how the 3WHS is completed.
2254 		 */
2255 		while (tcp != listener) {
2256 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2257 				break;
2258 			else
2259 				tcp = tcp->tcp_eager_prev_q0;
2260 		}
2261 		ASSERT(tcp != listener);
2262 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2263 		ASSERT(conn_ind != NULL);
2264 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2265 
2266 		/* Move from q0 to q */
2267 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2268 		listener->tcp_conn_req_cnt_q0--;
2269 		listener->tcp_conn_req_cnt_q++;
2270 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2271 		    tcp->tcp_eager_prev_q0;
2272 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2273 		    tcp->tcp_eager_next_q0;
2274 		tcp->tcp_eager_prev_q0 = NULL;
2275 		tcp->tcp_eager_next_q0 = NULL;
2276 		tcp->tcp_conn_def_q0 = B_FALSE;
2277 
2278 		/* Make sure the tcp isn't in the list of droppables */
2279 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2280 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2281 
2282 		/*
2283 		 * Insert at end of the queue because sockfs sends
2284 		 * down T_CONN_RES in chronological order. Leaving
2285 		 * the older conn indications at front of the queue
2286 		 * helps reducing search time.
2287 		 */
2288 		tail = listener->tcp_eager_last_q;
2289 		if (tail != NULL)
2290 			tail->tcp_eager_next_q = tcp;
2291 		else
2292 			listener->tcp_eager_next_q = tcp;
2293 		listener->tcp_eager_last_q = tcp;
2294 		tcp->tcp_eager_next_q = NULL;
2295 		mutex_exit(&listener->tcp_eager_lock);
2296 		putnext(tcp->tcp_rq, conn_ind);
2297 	} else {
2298 		mutex_exit(&listener->tcp_eager_lock);
2299 	}
2300 
2301 	/*
2302 	 * Done with the acceptor - free it
2303 	 *
2304 	 * Note: from this point on, no access to listener should be made
2305 	 * as listener can be equal to acceptor.
2306 	 */
2307 finish:
2308 	ASSERT(acceptor->tcp_detached);
2309 	ASSERT(tcps->tcps_g_q != NULL);
2310 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2311 	acceptor->tcp_rq = tcps->tcps_g_q;
2312 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2313 	(void) tcp_clean_death(acceptor, 0, 2);
2314 	CONN_DEC_REF(acceptor->tcp_connp);
2315 
2316 	/*
2317 	 * In case we already received a FIN we have to make tcp_rput send
2318 	 * the ordrel_ind. This will also send up a window update if the window
2319 	 * has opened up.
2320 	 *
2321 	 * In the normal case of a successful connection acceptance
2322 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2323 	 * indication that this was just accepted. This tells tcp_rput to
2324 	 * pass up any data queued in tcp_rcv_list.
2325 	 *
2326 	 * In the fringe case where options sent with T_CONN_RES failed and
2327 	 * we required, we would be indicating a T_DISCON_IND to blow
2328 	 * away this connection.
2329 	 */
2330 
2331 	/*
2332 	 * XXX: we currently have a problem if XTI application closes the
2333 	 * acceptor stream in between. This problem exists in on10-gate also
2334 	 * and is well know but nothing can be done short of major rewrite
2335 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2336 	 * eager same squeue as listener (we can distinguish non socket
2337 	 * listeners at the time of handling a SYN in tcp_conn_request)
2338 	 * and do most of the work that tcp_accept_finish does here itself
2339 	 * and then get behind the acceptor squeue to access the acceptor
2340 	 * queue.
2341 	 */
2342 	/*
2343 	 * We already have a ref on tcp so no need to do one before squeue_enter
2344 	 */
2345 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2346 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2347 }
2348 
2349 /*
2350  * Swap information between the eager and acceptor for a TLI/XTI client.
2351  * The sockfs accept is done on the acceptor stream and control goes
2352  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2353  * called. In either case, both the eager and listener are in their own
2354  * perimeter (squeue) and the code has to deal with potential race.
2355  *
2356  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2357  */
2358 static int
2359 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2360 {
2361 	conn_t	*econnp, *aconnp;
2362 	cred_t	*effective_cred = NULL;
2363 
2364 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2365 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2366 	ASSERT(!eager->tcp_hard_bound);
2367 	ASSERT(!TCP_IS_SOCKET(acceptor));
2368 	ASSERT(!TCP_IS_SOCKET(eager));
2369 	ASSERT(!TCP_IS_SOCKET(listener));
2370 
2371 	econnp = eager->tcp_connp;
2372 	aconnp = acceptor->tcp_connp;
2373 
2374 	/*
2375 	 * Trusted Extensions may need to use a security label that is
2376 	 * different from the acceptor's label on MLP and MAC-Exempt
2377 	 * sockets. If this is the case, the required security label
2378 	 * already exists in econnp->conn_effective_cred. Use this label
2379 	 * to generate a new effective cred for the acceptor.
2380 	 *
2381 	 * We allow for potential application level retry attempts by
2382 	 * checking for transient errors before modifying eager.
2383 	 */
2384 	if (is_system_labeled() &&
2385 	    aconnp->conn_cred != NULL && econnp->conn_effective_cred != NULL) {
2386 		effective_cred = copycred_from_tslabel(aconnp->conn_cred,
2387 		    crgetlabel(econnp->conn_effective_cred), KM_NOSLEEP);
2388 		if (effective_cred == NULL)
2389 			return (ENOMEM);
2390 	}
2391 
2392 	acceptor->tcp_detached = B_TRUE;
2393 	/*
2394 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2395 	 * the acceptor id.
2396 	 */
2397 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2398 
2399 	/* remove eager from listen list... */
2400 	mutex_enter(&listener->tcp_eager_lock);
2401 	tcp_eager_unlink(eager);
2402 	ASSERT(eager->tcp_eager_next_q == NULL &&
2403 	    eager->tcp_eager_last_q == NULL);
2404 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2405 	    eager->tcp_eager_prev_q0 == NULL);
2406 	mutex_exit(&listener->tcp_eager_lock);
2407 	eager->tcp_rq = acceptor->tcp_rq;
2408 	eager->tcp_wq = acceptor->tcp_wq;
2409 
2410 	eager->tcp_rq->q_ptr = econnp;
2411 	eager->tcp_wq->q_ptr = econnp;
2412 
2413 	/*
2414 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2415 	 * which might be a different squeue from our peer TCP instance.
2416 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2417 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2418 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2419 	 * above reach global visibility prior to the clearing of tcp_detached.
2420 	 */
2421 	membar_producer();
2422 	eager->tcp_detached = B_FALSE;
2423 
2424 	ASSERT(eager->tcp_ack_tid == 0);
2425 
2426 	econnp->conn_dev = aconnp->conn_dev;
2427 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2428 
2429 	ASSERT(econnp->conn_minor_arena != NULL);
2430 	if (eager->tcp_cred != NULL)
2431 		crfree(eager->tcp_cred);
2432 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2433 	if (econnp->conn_effective_cred != NULL)
2434 		crfree(econnp->conn_effective_cred);
2435 	econnp->conn_effective_cred = effective_cred;
2436 	aconnp->conn_cred = NULL;
2437 	ASSERT(aconnp->conn_effective_cred == NULL);
2438 
2439 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2440 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2441 
2442 	econnp->conn_zoneid = aconnp->conn_zoneid;
2443 	econnp->conn_allzones = aconnp->conn_allzones;
2444 
2445 	aconnp->conn_mac_exempt = B_FALSE;
2446 
2447 	/* Do the IPC initialization */
2448 	CONN_INC_REF(econnp);
2449 
2450 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2451 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2452 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2453 
2454 	/* Done with old IPC. Drop its ref on its connp */
2455 	CONN_DEC_REF(aconnp);
2456 	return (0);
2457 }
2458 
2459 
2460 /*
2461  * Adapt to the information, such as rtt and rtt_sd, provided from the
2462  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2463  *
2464  * Checks for multicast and broadcast destination address.
2465  * Returns zero on failure; non-zero if ok.
2466  *
2467  * Note that the MSS calculation here is based on the info given in
2468  * the IRE.  We do not do any calculation based on TCP options.  They
2469  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2470  * knows which options to use.
2471  *
2472  * Note on how TCP gets its parameters for a connection.
2473  *
2474  * When a tcp_t structure is allocated, it gets all the default parameters.
2475  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2476  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2477  * default.
2478  *
2479  * An incoming SYN with a multicast or broadcast destination address, is dropped
2480  * in 1 of 2 places.
2481  *
2482  * 1. If the packet was received over the wire it is dropped in
2483  * ip_rput_process_broadcast()
2484  *
2485  * 2. If the packet was received through internal IP loopback, i.e. the packet
2486  * was generated and received on the same machine, it is dropped in
2487  * ip_wput_local()
2488  *
2489  * An incoming SYN with a multicast or broadcast source address is always
2490  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2491  * reject an attempt to connect to a broadcast or multicast (destination)
2492  * address.
2493  */
2494 static int
2495 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2496 {
2497 	ire_t		*ire;
2498 	ire_t		*sire = NULL;
2499 	iulp_t		*ire_uinfo = NULL;
2500 	uint32_t	mss_max;
2501 	uint32_t	mss;
2502 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2503 	conn_t		*connp = tcp->tcp_connp;
2504 	boolean_t	ire_cacheable = B_FALSE;
2505 	zoneid_t	zoneid = connp->conn_zoneid;
2506 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2507 	    MATCH_IRE_SECATTR;
2508 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2509 	ill_t		*ill = NULL;
2510 	boolean_t	incoming = (ire_mp == NULL);
2511 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2512 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2513 
2514 	ASSERT(connp->conn_ire_cache == NULL);
2515 
2516 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2517 
2518 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2519 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2520 			return (0);
2521 		}
2522 		/*
2523 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2524 		 * for the destination with the nexthop as gateway.
2525 		 * ire_ctable_lookup() is used because this particular
2526 		 * ire, if it exists, will be marked private.
2527 		 * If that is not available, use the interface ire
2528 		 * for the nexthop.
2529 		 *
2530 		 * TSol: tcp_update_label will detect label mismatches based
2531 		 * only on the destination's label, but that would not
2532 		 * detect label mismatches based on the security attributes
2533 		 * of routes or next hop gateway. Hence we need to pass the
2534 		 * label to ire_ftable_lookup below in order to locate the
2535 		 * right prefix (and/or) ire cache. Similarly we also need
2536 		 * pass the label to the ire_cache_lookup below to locate
2537 		 * the right ire that also matches on the label.
2538 		 */
2539 		if (tcp->tcp_connp->conn_nexthop_set) {
2540 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2541 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2542 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2543 			    ipst);
2544 			if (ire == NULL) {
2545 				ire = ire_ftable_lookup(
2546 				    tcp->tcp_connp->conn_nexthop_v4,
2547 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2548 				    tsl, match_flags, ipst);
2549 				if (ire == NULL)
2550 					return (0);
2551 			} else {
2552 				ire_uinfo = &ire->ire_uinfo;
2553 			}
2554 		} else {
2555 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2556 			    zoneid, tsl, ipst);
2557 			if (ire != NULL) {
2558 				ire_cacheable = B_TRUE;
2559 				ire_uinfo = (ire_mp != NULL) ?
2560 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2561 				    &ire->ire_uinfo;
2562 
2563 			} else {
2564 				if (ire_mp == NULL) {
2565 					ire = ire_ftable_lookup(
2566 					    tcp->tcp_connp->conn_rem,
2567 					    0, 0, 0, NULL, &sire, zoneid, 0,
2568 					    tsl, (MATCH_IRE_RECURSIVE |
2569 					    MATCH_IRE_DEFAULT), ipst);
2570 					if (ire == NULL)
2571 						return (0);
2572 					ire_uinfo = (sire != NULL) ?
2573 					    &sire->ire_uinfo :
2574 					    &ire->ire_uinfo;
2575 				} else {
2576 					ire = (ire_t *)ire_mp->b_rptr;
2577 					ire_uinfo =
2578 					    &((ire_t *)
2579 					    ire_mp->b_rptr)->ire_uinfo;
2580 				}
2581 			}
2582 		}
2583 		ASSERT(ire != NULL);
2584 
2585 		if ((ire->ire_src_addr == INADDR_ANY) ||
2586 		    (ire->ire_type & IRE_BROADCAST)) {
2587 			/*
2588 			 * ire->ire_mp is non null when ire_mp passed in is used
2589 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2590 			 */
2591 			if (ire->ire_mp == NULL)
2592 				ire_refrele(ire);
2593 			if (sire != NULL)
2594 				ire_refrele(sire);
2595 			return (0);
2596 		}
2597 
2598 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2599 			ipaddr_t src_addr;
2600 
2601 			/*
2602 			 * ip_bind_connected() has stored the correct source
2603 			 * address in conn_src.
2604 			 */
2605 			src_addr = tcp->tcp_connp->conn_src;
2606 			tcp->tcp_ipha->ipha_src = src_addr;
2607 			/*
2608 			 * Copy of the src addr. in tcp_t is needed
2609 			 * for the lookup funcs.
2610 			 */
2611 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2612 		}
2613 		/*
2614 		 * Set the fragment bit so that IP will tell us if the MTU
2615 		 * should change. IP tells us the latest setting of
2616 		 * ip_path_mtu_discovery through ire_frag_flag.
2617 		 */
2618 		if (ipst->ips_ip_path_mtu_discovery) {
2619 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2620 			    htons(IPH_DF);
2621 		}
2622 		/*
2623 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2624 		 * for IP_NEXTHOP. No cache ire has been found for the
2625 		 * destination and we are working with the nexthop's
2626 		 * interface ire. Since we need to forward all packets
2627 		 * to the nexthop first, we "blindly" set tcp_localnet
2628 		 * to false, eventhough the destination may also be
2629 		 * onlink.
2630 		 */
2631 		if (ire_uinfo == NULL)
2632 			tcp->tcp_localnet = 0;
2633 		else
2634 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2635 	} else {
2636 		/*
2637 		 * For incoming connection ire_mp = NULL
2638 		 * For outgoing connection ire_mp != NULL
2639 		 * Technically we should check conn_incoming_ill
2640 		 * when ire_mp is NULL and conn_outgoing_ill when
2641 		 * ire_mp is non-NULL. But this is performance
2642 		 * critical path and for IPV*_BOUND_IF, outgoing
2643 		 * and incoming ill are always set to the same value.
2644 		 */
2645 		ill_t	*dst_ill = NULL;
2646 		ipif_t  *dst_ipif = NULL;
2647 
2648 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2649 
2650 		if (connp->conn_outgoing_ill != NULL) {
2651 			/* Outgoing or incoming path */
2652 			int   err;
2653 
2654 			dst_ill = conn_get_held_ill(connp,
2655 			    &connp->conn_outgoing_ill, &err);
2656 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2657 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2658 				return (0);
2659 			}
2660 			match_flags |= MATCH_IRE_ILL;
2661 			dst_ipif = dst_ill->ill_ipif;
2662 		}
2663 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2664 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2665 
2666 		if (ire != NULL) {
2667 			ire_cacheable = B_TRUE;
2668 			ire_uinfo = (ire_mp != NULL) ?
2669 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2670 			    &ire->ire_uinfo;
2671 		} else {
2672 			if (ire_mp == NULL) {
2673 				ire = ire_ftable_lookup_v6(
2674 				    &tcp->tcp_connp->conn_remv6,
2675 				    0, 0, 0, dst_ipif, &sire, zoneid,
2676 				    0, tsl, match_flags, ipst);
2677 				if (ire == NULL) {
2678 					if (dst_ill != NULL)
2679 						ill_refrele(dst_ill);
2680 					return (0);
2681 				}
2682 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2683 				    &ire->ire_uinfo;
2684 			} else {
2685 				ire = (ire_t *)ire_mp->b_rptr;
2686 				ire_uinfo =
2687 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2688 			}
2689 		}
2690 		if (dst_ill != NULL)
2691 			ill_refrele(dst_ill);
2692 
2693 		ASSERT(ire != NULL);
2694 		ASSERT(ire_uinfo != NULL);
2695 
2696 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2697 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2698 			/*
2699 			 * ire->ire_mp is non null when ire_mp passed in is used
2700 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2701 			 */
2702 			if (ire->ire_mp == NULL)
2703 				ire_refrele(ire);
2704 			if (sire != NULL)
2705 				ire_refrele(sire);
2706 			return (0);
2707 		}
2708 
2709 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2710 			in6_addr_t	src_addr;
2711 
2712 			/*
2713 			 * ip_bind_connected_v6() has stored the correct source
2714 			 * address per IPv6 addr. selection policy in
2715 			 * conn_src_v6.
2716 			 */
2717 			src_addr = tcp->tcp_connp->conn_srcv6;
2718 
2719 			tcp->tcp_ip6h->ip6_src = src_addr;
2720 			/*
2721 			 * Copy of the src addr. in tcp_t is needed
2722 			 * for the lookup funcs.
2723 			 */
2724 			tcp->tcp_ip_src_v6 = src_addr;
2725 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2726 			    &connp->conn_srcv6));
2727 		}
2728 		tcp->tcp_localnet =
2729 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2730 	}
2731 
2732 	/*
2733 	 * This allows applications to fail quickly when connections are made
2734 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2735 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2736 	 */
2737 	if ((ire->ire_flags & RTF_REJECT) &&
2738 	    (ire->ire_flags & RTF_PRIVATE))
2739 		goto error;
2740 
2741 	/*
2742 	 * Make use of the cached rtt and rtt_sd values to calculate the
2743 	 * initial RTO.  Note that they are already initialized in
2744 	 * tcp_init_values().
2745 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2746 	 * IP_NEXTHOP, but instead are using the interface ire for the
2747 	 * nexthop, then we do not use the ire_uinfo from that ire to
2748 	 * do any initializations.
2749 	 */
2750 	if (ire_uinfo != NULL) {
2751 		if (ire_uinfo->iulp_rtt != 0) {
2752 			clock_t	rto;
2753 
2754 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2755 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2756 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2757 			    tcps->tcps_rexmit_interval_extra +
2758 			    (tcp->tcp_rtt_sa >> 5);
2759 
2760 			if (rto > tcps->tcps_rexmit_interval_max) {
2761 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2762 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2763 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2764 			} else {
2765 				tcp->tcp_rto = rto;
2766 			}
2767 		}
2768 		if (ire_uinfo->iulp_ssthresh != 0)
2769 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2770 		else
2771 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2772 		if (ire_uinfo->iulp_spipe > 0) {
2773 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2774 			    tcps->tcps_max_buf);
2775 			if (tcps->tcps_snd_lowat_fraction != 0)
2776 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2777 				    tcps->tcps_snd_lowat_fraction;
2778 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2779 		}
2780 		/*
2781 		 * Note that up till now, acceptor always inherits receive
2782 		 * window from the listener.  But if there is a metrics
2783 		 * associated with a host, we should use that instead of
2784 		 * inheriting it from listener. Thus we need to pass this
2785 		 * info back to the caller.
2786 		 */
2787 		if (ire_uinfo->iulp_rpipe > 0) {
2788 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2789 			    tcps->tcps_max_buf);
2790 		}
2791 
2792 		if (ire_uinfo->iulp_rtomax > 0) {
2793 			tcp->tcp_second_timer_threshold =
2794 			    ire_uinfo->iulp_rtomax;
2795 		}
2796 
2797 		/*
2798 		 * Use the metric option settings, iulp_tstamp_ok and
2799 		 * iulp_wscale_ok, only for active open. What this means
2800 		 * is that if the other side uses timestamp or window
2801 		 * scale option, TCP will also use those options. That
2802 		 * is for passive open.  If the application sets a
2803 		 * large window, window scale is enabled regardless of
2804 		 * the value in iulp_wscale_ok.  This is the behavior
2805 		 * since 2.6.  So we keep it.
2806 		 * The only case left in passive open processing is the
2807 		 * check for SACK.
2808 		 * For ECN, it should probably be like SACK.  But the
2809 		 * current value is binary, so we treat it like the other
2810 		 * cases.  The metric only controls active open.For passive
2811 		 * open, the ndd param, tcp_ecn_permitted, controls the
2812 		 * behavior.
2813 		 */
2814 		if (!tcp_detached) {
2815 			/*
2816 			 * The if check means that the following can only
2817 			 * be turned on by the metrics only IRE, but not off.
2818 			 */
2819 			if (ire_uinfo->iulp_tstamp_ok)
2820 				tcp->tcp_snd_ts_ok = B_TRUE;
2821 			if (ire_uinfo->iulp_wscale_ok)
2822 				tcp->tcp_snd_ws_ok = B_TRUE;
2823 			if (ire_uinfo->iulp_sack == 2)
2824 				tcp->tcp_snd_sack_ok = B_TRUE;
2825 			if (ire_uinfo->iulp_ecn_ok)
2826 				tcp->tcp_ecn_ok = B_TRUE;
2827 		} else {
2828 			/*
2829 			 * Passive open.
2830 			 *
2831 			 * As above, the if check means that SACK can only be
2832 			 * turned on by the metric only IRE.
2833 			 */
2834 			if (ire_uinfo->iulp_sack > 0) {
2835 				tcp->tcp_snd_sack_ok = B_TRUE;
2836 			}
2837 		}
2838 	}
2839 
2840 
2841 	/*
2842 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2843 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2844 	 * length of all those options exceeds 28 bytes.  But because
2845 	 * of the tcp_mss_min check below, we may not have a problem if
2846 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2847 	 * the negative problem still exists.  And the check defeats PMTUd.
2848 	 * In fact, if PMTUd finds that the MSS should be smaller than
2849 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2850 	 * value.
2851 	 *
2852 	 * We do not deal with that now.  All those problems related to
2853 	 * PMTUd will be fixed later.
2854 	 */
2855 	ASSERT(ire->ire_max_frag != 0);
2856 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2857 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2858 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2859 			mss = MIN(mss, IPV6_MIN_MTU);
2860 		}
2861 	}
2862 
2863 	/* Sanity check for MSS value. */
2864 	if (tcp->tcp_ipversion == IPV4_VERSION)
2865 		mss_max = tcps->tcps_mss_max_ipv4;
2866 	else
2867 		mss_max = tcps->tcps_mss_max_ipv6;
2868 
2869 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2870 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2871 		/*
2872 		 * After receiving an ICMPv6 "packet too big" message with a
2873 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2874 		 * will insert a 8-byte fragment header in every packet; we
2875 		 * reduce the MSS by that amount here.
2876 		 */
2877 		mss -= sizeof (ip6_frag_t);
2878 	}
2879 
2880 	if (tcp->tcp_ipsec_overhead == 0)
2881 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2882 
2883 	mss -= tcp->tcp_ipsec_overhead;
2884 
2885 	if (mss < tcps->tcps_mss_min)
2886 		mss = tcps->tcps_mss_min;
2887 	if (mss > mss_max)
2888 		mss = mss_max;
2889 
2890 	/* Note that this is the maximum MSS, excluding all options. */
2891 	tcp->tcp_mss = mss;
2892 
2893 	/*
2894 	 * Initialize the ISS here now that we have the full connection ID.
2895 	 * The RFC 1948 method of initial sequence number generation requires
2896 	 * knowledge of the full connection ID before setting the ISS.
2897 	 */
2898 
2899 	tcp_iss_init(tcp);
2900 
2901 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2902 		tcp->tcp_loopback = B_TRUE;
2903 
2904 	if (sire != NULL)
2905 		IRE_REFRELE(sire);
2906 
2907 	/*
2908 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2909 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2910 	 */
2911 	if (tcp->tcp_loopback ||
2912 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2913 		/*
2914 		 * For incoming, see if this tcp may be MDT-capable.  For
2915 		 * outgoing, this process has been taken care of through
2916 		 * tcp_rput_other.
2917 		 */
2918 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2919 		tcp->tcp_ire_ill_check_done = B_TRUE;
2920 	}
2921 
2922 	mutex_enter(&connp->conn_lock);
2923 	/*
2924 	 * Make sure that conn is not marked incipient
2925 	 * for incoming connections. A blind
2926 	 * removal of incipient flag is cheaper than
2927 	 * check and removal.
2928 	 */
2929 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2930 
2931 	/*
2932 	 * Must not cache forwarding table routes
2933 	 * or recache an IRE after the conn_t has
2934 	 * had conn_ire_cache cleared and is flagged
2935 	 * unusable, (see the CONN_CACHE_IRE() macro).
2936 	 */
2937 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2938 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2939 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2940 			connp->conn_ire_cache = ire;
2941 			IRE_UNTRACE_REF(ire);
2942 			rw_exit(&ire->ire_bucket->irb_lock);
2943 			mutex_exit(&connp->conn_lock);
2944 			return (1);
2945 		}
2946 		rw_exit(&ire->ire_bucket->irb_lock);
2947 	}
2948 	mutex_exit(&connp->conn_lock);
2949 
2950 	if (ire->ire_mp == NULL)
2951 		ire_refrele(ire);
2952 	return (1);
2953 
2954 error:
2955 	if (ire->ire_mp == NULL)
2956 		ire_refrele(ire);
2957 	if (sire != NULL)
2958 		ire_refrele(sire);
2959 	return (0);
2960 }
2961 
2962 static void
2963 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2964 {
2965 	int	error;
2966 	conn_t	*connp = tcp->tcp_connp;
2967 	struct sockaddr	*sa;
2968 	mblk_t  *mp1;
2969 	struct T_bind_req *tbr;
2970 	int	backlog;
2971 	socklen_t	len;
2972 	sin_t	*sin;
2973 	sin6_t	*sin6;
2974 	cred_t		*cr;
2975 
2976 	/*
2977 	 * All Solaris components should pass a db_credp
2978 	 * for this TPI message, hence we ASSERT.
2979 	 * But in case there is some other M_PROTO that looks
2980 	 * like a TPI message sent by some other kernel
2981 	 * component, we check and return an error.
2982 	 */
2983 	cr = msg_getcred(mp, NULL);
2984 	ASSERT(cr != NULL);
2985 	if (cr == NULL) {
2986 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2987 		return;
2988 	}
2989 
2990 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2991 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2992 		if (tcp->tcp_debug) {
2993 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2994 			    "tcp_tpi_bind: bad req, len %u",
2995 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2996 		}
2997 		tcp_err_ack(tcp, mp, TPROTO, 0);
2998 		return;
2999 	}
3000 	/* Make sure the largest address fits */
3001 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3002 	if (mp1 == NULL) {
3003 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3004 		return;
3005 	}
3006 	mp = mp1;
3007 	tbr = (struct T_bind_req *)mp->b_rptr;
3008 
3009 	backlog = tbr->CONIND_number;
3010 	len = tbr->ADDR_length;
3011 
3012 	switch (len) {
3013 	case 0:		/* request for a generic port */
3014 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3015 		if (tcp->tcp_family == AF_INET) {
3016 			tbr->ADDR_length = sizeof (sin_t);
3017 			sin = (sin_t *)&tbr[1];
3018 			*sin = sin_null;
3019 			sin->sin_family = AF_INET;
3020 			sa = (struct sockaddr *)sin;
3021 			len = sizeof (sin_t);
3022 			mp->b_wptr = (uchar_t *)&sin[1];
3023 		} else {
3024 			ASSERT(tcp->tcp_family == AF_INET6);
3025 			tbr->ADDR_length = sizeof (sin6_t);
3026 			sin6 = (sin6_t *)&tbr[1];
3027 			*sin6 = sin6_null;
3028 			sin6->sin6_family = AF_INET6;
3029 			sa = (struct sockaddr *)sin6;
3030 			len = sizeof (sin6_t);
3031 			mp->b_wptr = (uchar_t *)&sin6[1];
3032 		}
3033 		break;
3034 
3035 	case sizeof (sin_t):    /* Complete IPv4 address */
3036 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
3037 		    sizeof (sin_t));
3038 		break;
3039 
3040 	case sizeof (sin6_t): /* Complete IPv6 address */
3041 		sa = (struct sockaddr *)mi_offset_param(mp,
3042 		    tbr->ADDR_offset, sizeof (sin6_t));
3043 		break;
3044 
3045 	default:
3046 		if (tcp->tcp_debug) {
3047 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3048 			    "tcp_tpi_bind: bad address length, %d",
3049 			    tbr->ADDR_length);
3050 		}
3051 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3052 		return;
3053 	}
3054 
3055 	if (backlog > 0) {
3056 		error = tcp_do_listen(connp, sa, len, backlog, DB_CRED(mp),
3057 		    tbr->PRIM_type != O_T_BIND_REQ);
3058 	} else {
3059 		error = tcp_do_bind(connp, sa, len, DB_CRED(mp),
3060 		    tbr->PRIM_type != O_T_BIND_REQ);
3061 	}
3062 done:
3063 	if (error > 0) {
3064 		tcp_err_ack(tcp, mp, TSYSERR, error);
3065 	} else if (error < 0) {
3066 		tcp_err_ack(tcp, mp, -error, 0);
3067 	} else {
3068 		/*
3069 		 * Update port information as sockfs/tpi needs it for checking
3070 		 */
3071 		if (tcp->tcp_family == AF_INET) {
3072 			sin = (sin_t *)sa;
3073 			sin->sin_port = tcp->tcp_lport;
3074 		} else {
3075 			sin6 = (sin6_t *)sa;
3076 			sin6->sin6_port = tcp->tcp_lport;
3077 		}
3078 		mp->b_datap->db_type = M_PCPROTO;
3079 		tbr->PRIM_type = T_BIND_ACK;
3080 		putnext(tcp->tcp_rq, mp);
3081 	}
3082 }
3083 
3084 /*
3085  * If the "bind_to_req_port_only" parameter is set, if the requested port
3086  * number is available, return it, If not return 0
3087  *
3088  * If "bind_to_req_port_only" parameter is not set and
3089  * If the requested port number is available, return it.  If not, return
3090  * the first anonymous port we happen across.  If no anonymous ports are
3091  * available, return 0. addr is the requested local address, if any.
3092  *
3093  * In either case, when succeeding update the tcp_t to record the port number
3094  * and insert it in the bind hash table.
3095  *
3096  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3097  * without setting SO_REUSEADDR. This is needed so that they
3098  * can be viewed as two independent transport protocols.
3099  */
3100 static in_port_t
3101 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3102     int reuseaddr, boolean_t quick_connect,
3103     boolean_t bind_to_req_port_only, boolean_t user_specified)
3104 {
3105 	/* number of times we have run around the loop */
3106 	int count = 0;
3107 	/* maximum number of times to run around the loop */
3108 	int loopmax;
3109 	conn_t *connp = tcp->tcp_connp;
3110 	zoneid_t zoneid = connp->conn_zoneid;
3111 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3112 
3113 	/*
3114 	 * Lookup for free addresses is done in a loop and "loopmax"
3115 	 * influences how long we spin in the loop
3116 	 */
3117 	if (bind_to_req_port_only) {
3118 		/*
3119 		 * If the requested port is busy, don't bother to look
3120 		 * for a new one. Setting loop maximum count to 1 has
3121 		 * that effect.
3122 		 */
3123 		loopmax = 1;
3124 	} else {
3125 		/*
3126 		 * If the requested port is busy, look for a free one
3127 		 * in the anonymous port range.
3128 		 * Set loopmax appropriately so that one does not look
3129 		 * forever in the case all of the anonymous ports are in use.
3130 		 */
3131 		if (tcp->tcp_anon_priv_bind) {
3132 			/*
3133 			 * loopmax =
3134 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3135 			 */
3136 			loopmax = IPPORT_RESERVED -
3137 			    tcps->tcps_min_anonpriv_port;
3138 		} else {
3139 			loopmax = (tcps->tcps_largest_anon_port -
3140 			    tcps->tcps_smallest_anon_port + 1);
3141 		}
3142 	}
3143 	do {
3144 		uint16_t	lport;
3145 		tf_t		*tbf;
3146 		tcp_t		*ltcp;
3147 		conn_t		*lconnp;
3148 
3149 		lport = htons(port);
3150 
3151 		/*
3152 		 * Ensure that the tcp_t is not currently in the bind hash.
3153 		 * Hold the lock on the hash bucket to ensure that
3154 		 * the duplicate check plus the insertion is an atomic
3155 		 * operation.
3156 		 *
3157 		 * This function does an inline lookup on the bind hash list
3158 		 * Make sure that we access only members of tcp_t
3159 		 * and that we don't look at tcp_tcp, since we are not
3160 		 * doing a CONN_INC_REF.
3161 		 */
3162 		tcp_bind_hash_remove(tcp);
3163 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3164 		mutex_enter(&tbf->tf_lock);
3165 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3166 		    ltcp = ltcp->tcp_bind_hash) {
3167 			if (lport == ltcp->tcp_lport)
3168 				break;
3169 		}
3170 
3171 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3172 			boolean_t not_socket;
3173 			boolean_t exclbind;
3174 
3175 			lconnp = ltcp->tcp_connp;
3176 
3177 			/*
3178 			 * On a labeled system, we must treat bindings to ports
3179 			 * on shared IP addresses by sockets with MAC exemption
3180 			 * privilege as being in all zones, as there's
3181 			 * otherwise no way to identify the right receiver.
3182 			 */
3183 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3184 			    IPCL_ZONE_MATCH(connp,
3185 			    ltcp->tcp_connp->conn_zoneid)) &&
3186 			    !lconnp->conn_mac_exempt &&
3187 			    !connp->conn_mac_exempt)
3188 				continue;
3189 
3190 			/*
3191 			 * If TCP_EXCLBIND is set for either the bound or
3192 			 * binding endpoint, the semantics of bind
3193 			 * is changed according to the following.
3194 			 *
3195 			 * spec = specified address (v4 or v6)
3196 			 * unspec = unspecified address (v4 or v6)
3197 			 * A = specified addresses are different for endpoints
3198 			 *
3199 			 * bound	bind to		allowed
3200 			 * -------------------------------------
3201 			 * unspec	unspec		no
3202 			 * unspec	spec		no
3203 			 * spec		unspec		no
3204 			 * spec		spec		yes if A
3205 			 *
3206 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3207 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3208 			 *
3209 			 * Note:
3210 			 *
3211 			 * 1. Because of TLI semantics, an endpoint can go
3212 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3213 			 * TCPS_BOUND, depending on whether it is originally
3214 			 * a listener or not.  That is why we need to check
3215 			 * for states greater than or equal to TCPS_BOUND
3216 			 * here.
3217 			 *
3218 			 * 2. Ideally, we should only check for state equals
3219 			 * to TCPS_LISTEN. And the following check should be
3220 			 * added.
3221 			 *
3222 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3223 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3224 			 *		...
3225 			 * }
3226 			 *
3227 			 * The semantics will be changed to this.  If the
3228 			 * endpoint on the list is in state not equal to
3229 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3230 			 * set, let the bind succeed.
3231 			 *
3232 			 * Because of (1), we cannot do that for TLI
3233 			 * endpoints.  But we can do that for socket endpoints.
3234 			 * If in future, we can change this going back
3235 			 * semantics, we can use the above check for TLI also.
3236 			 */
3237 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3238 			    TCP_IS_SOCKET(tcp));
3239 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3240 
3241 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3242 			    (exclbind && (not_socket ||
3243 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3244 				if (V6_OR_V4_INADDR_ANY(
3245 				    ltcp->tcp_bound_source_v6) ||
3246 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3247 				    IN6_ARE_ADDR_EQUAL(laddr,
3248 				    &ltcp->tcp_bound_source_v6)) {
3249 					break;
3250 				}
3251 				continue;
3252 			}
3253 
3254 			/*
3255 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3256 			 * have disjoint port number spaces, if *_EXCLBIND
3257 			 * is not set and only if the application binds to a
3258 			 * specific port. We use the same autoassigned port
3259 			 * number space for IPv4 and IPv6 sockets.
3260 			 */
3261 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3262 			    bind_to_req_port_only)
3263 				continue;
3264 
3265 			/*
3266 			 * Ideally, we should make sure that the source
3267 			 * address, remote address, and remote port in the
3268 			 * four tuple for this tcp-connection is unique.
3269 			 * However, trying to find out the local source
3270 			 * address would require too much code duplication
3271 			 * with IP, since IP needs needs to have that code
3272 			 * to support userland TCP implementations.
3273 			 */
3274 			if (quick_connect &&
3275 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3276 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3277 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3278 			    &ltcp->tcp_remote_v6)))
3279 				continue;
3280 
3281 			if (!reuseaddr) {
3282 				/*
3283 				 * No socket option SO_REUSEADDR.
3284 				 * If existing port is bound to
3285 				 * a non-wildcard IP address
3286 				 * and the requesting stream is
3287 				 * bound to a distinct
3288 				 * different IP addresses
3289 				 * (non-wildcard, also), keep
3290 				 * going.
3291 				 */
3292 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3293 				    !V6_OR_V4_INADDR_ANY(
3294 				    ltcp->tcp_bound_source_v6) &&
3295 				    !IN6_ARE_ADDR_EQUAL(laddr,
3296 				    &ltcp->tcp_bound_source_v6))
3297 					continue;
3298 				if (ltcp->tcp_state >= TCPS_BOUND) {
3299 					/*
3300 					 * This port is being used and
3301 					 * its state is >= TCPS_BOUND,
3302 					 * so we can't bind to it.
3303 					 */
3304 					break;
3305 				}
3306 			} else {
3307 				/*
3308 				 * socket option SO_REUSEADDR is set on the
3309 				 * binding tcp_t.
3310 				 *
3311 				 * If two streams are bound to
3312 				 * same IP address or both addr
3313 				 * and bound source are wildcards
3314 				 * (INADDR_ANY), we want to stop
3315 				 * searching.
3316 				 * We have found a match of IP source
3317 				 * address and source port, which is
3318 				 * refused regardless of the
3319 				 * SO_REUSEADDR setting, so we break.
3320 				 */
3321 				if (IN6_ARE_ADDR_EQUAL(laddr,
3322 				    &ltcp->tcp_bound_source_v6) &&
3323 				    (ltcp->tcp_state == TCPS_LISTEN ||
3324 				    ltcp->tcp_state == TCPS_BOUND))
3325 					break;
3326 			}
3327 		}
3328 		if (ltcp != NULL) {
3329 			/* The port number is busy */
3330 			mutex_exit(&tbf->tf_lock);
3331 		} else {
3332 			/*
3333 			 * This port is ours. Insert in fanout and mark as
3334 			 * bound to prevent others from getting the port
3335 			 * number.
3336 			 */
3337 			tcp->tcp_state = TCPS_BOUND;
3338 			tcp->tcp_lport = htons(port);
3339 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3340 
3341 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3342 			    tcp->tcp_lport)] == tbf);
3343 			tcp_bind_hash_insert(tbf, tcp, 1);
3344 
3345 			mutex_exit(&tbf->tf_lock);
3346 
3347 			/*
3348 			 * We don't want tcp_next_port_to_try to "inherit"
3349 			 * a port number supplied by the user in a bind.
3350 			 */
3351 			if (user_specified)
3352 				return (port);
3353 
3354 			/*
3355 			 * This is the only place where tcp_next_port_to_try
3356 			 * is updated. After the update, it may or may not
3357 			 * be in the valid range.
3358 			 */
3359 			if (!tcp->tcp_anon_priv_bind)
3360 				tcps->tcps_next_port_to_try = port + 1;
3361 			return (port);
3362 		}
3363 
3364 		if (tcp->tcp_anon_priv_bind) {
3365 			port = tcp_get_next_priv_port(tcp);
3366 		} else {
3367 			if (count == 0 && user_specified) {
3368 				/*
3369 				 * We may have to return an anonymous port. So
3370 				 * get one to start with.
3371 				 */
3372 				port =
3373 				    tcp_update_next_port(
3374 				    tcps->tcps_next_port_to_try,
3375 				    tcp, B_TRUE);
3376 				user_specified = B_FALSE;
3377 			} else {
3378 				port = tcp_update_next_port(port + 1, tcp,
3379 				    B_FALSE);
3380 			}
3381 		}
3382 		if (port == 0)
3383 			break;
3384 
3385 		/*
3386 		 * Don't let this loop run forever in the case where
3387 		 * all of the anonymous ports are in use.
3388 		 */
3389 	} while (++count < loopmax);
3390 	return (0);
3391 }
3392 
3393 /*
3394  * tcp_clean_death / tcp_close_detached must not be called more than once
3395  * on a tcp. Thus every function that potentially calls tcp_clean_death
3396  * must check for the tcp state before calling tcp_clean_death.
3397  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3398  * tcp_timer_handler, all check for the tcp state.
3399  */
3400 /* ARGSUSED */
3401 void
3402 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3403 {
3404 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3405 
3406 	freemsg(mp);
3407 	if (tcp->tcp_state > TCPS_BOUND)
3408 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3409 		    ETIMEDOUT, 5);
3410 }
3411 
3412 /*
3413  * We are dying for some reason.  Try to do it gracefully.  (May be called
3414  * as writer.)
3415  *
3416  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3417  * done by a service procedure).
3418  * TBD - Should the return value distinguish between the tcp_t being
3419  * freed and it being reinitialized?
3420  */
3421 static int
3422 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3423 {
3424 	mblk_t	*mp;
3425 	queue_t	*q;
3426 	conn_t	*connp = tcp->tcp_connp;
3427 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3428 
3429 	TCP_CLD_STAT(tag);
3430 
3431 #if TCP_TAG_CLEAN_DEATH
3432 	tcp->tcp_cleandeathtag = tag;
3433 #endif
3434 
3435 	if (tcp->tcp_fused)
3436 		tcp_unfuse(tcp);
3437 
3438 	if (tcp->tcp_linger_tid != 0 &&
3439 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3440 		tcp_stop_lingering(tcp);
3441 	}
3442 
3443 	ASSERT(tcp != NULL);
3444 	ASSERT((tcp->tcp_family == AF_INET &&
3445 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3446 	    (tcp->tcp_family == AF_INET6 &&
3447 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3448 	    tcp->tcp_ipversion == IPV6_VERSION)));
3449 
3450 	if (TCP_IS_DETACHED(tcp)) {
3451 		if (tcp->tcp_hard_binding) {
3452 			/*
3453 			 * Its an eager that we are dealing with. We close the
3454 			 * eager but in case a conn_ind has already gone to the
3455 			 * listener, let tcp_accept_finish() send a discon_ind
3456 			 * to the listener and drop the last reference. If the
3457 			 * listener doesn't even know about the eager i.e. the
3458 			 * conn_ind hasn't gone up, blow away the eager and drop
3459 			 * the last reference as well. If the conn_ind has gone
3460 			 * up, state should be BOUND. tcp_accept_finish
3461 			 * will figure out that the connection has received a
3462 			 * RST and will send a DISCON_IND to the application.
3463 			 */
3464 			tcp_closei_local(tcp);
3465 			if (!tcp->tcp_tconnind_started) {
3466 				CONN_DEC_REF(connp);
3467 			} else {
3468 				tcp->tcp_state = TCPS_BOUND;
3469 			}
3470 		} else {
3471 			tcp_close_detached(tcp);
3472 		}
3473 		return (0);
3474 	}
3475 
3476 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3477 
3478 	q = tcp->tcp_rq;
3479 
3480 	/* Trash all inbound data */
3481 	if (!IPCL_IS_NONSTR(connp)) {
3482 		ASSERT(q != NULL);
3483 		flushq(q, FLUSHALL);
3484 	}
3485 
3486 	/*
3487 	 * If we are at least part way open and there is error
3488 	 * (err==0 implies no error)
3489 	 * notify our client by a T_DISCON_IND.
3490 	 */
3491 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3492 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3493 		    !TCP_IS_SOCKET(tcp)) {
3494 			/*
3495 			 * Send M_FLUSH according to TPI. Because sockets will
3496 			 * (and must) ignore FLUSHR we do that only for TPI
3497 			 * endpoints and sockets in STREAMS mode.
3498 			 */
3499 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3500 		}
3501 		if (tcp->tcp_debug) {
3502 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3503 			    "tcp_clean_death: discon err %d", err);
3504 		}
3505 		if (IPCL_IS_NONSTR(connp)) {
3506 			/* Direct socket, use upcall */
3507 			(*connp->conn_upcalls->su_disconnected)(
3508 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3509 		} else {
3510 			mp = mi_tpi_discon_ind(NULL, err, 0);
3511 			if (mp != NULL) {
3512 				putnext(q, mp);
3513 			} else {
3514 				if (tcp->tcp_debug) {
3515 					(void) strlog(TCP_MOD_ID, 0, 1,
3516 					    SL_ERROR|SL_TRACE,
3517 					    "tcp_clean_death, sending M_ERROR");
3518 				}
3519 				(void) putnextctl1(q, M_ERROR, EPROTO);
3520 			}
3521 		}
3522 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3523 			/* SYN_SENT or SYN_RCVD */
3524 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3525 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3526 			/* ESTABLISHED or CLOSE_WAIT */
3527 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3528 		}
3529 	}
3530 
3531 	tcp_reinit(tcp);
3532 	if (IPCL_IS_NONSTR(connp))
3533 		(void) tcp_do_unbind(connp);
3534 
3535 	return (-1);
3536 }
3537 
3538 /*
3539  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3540  * to expire, stop the wait and finish the close.
3541  */
3542 static void
3543 tcp_stop_lingering(tcp_t *tcp)
3544 {
3545 	clock_t	delta = 0;
3546 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3547 
3548 	tcp->tcp_linger_tid = 0;
3549 	if (tcp->tcp_state > TCPS_LISTEN) {
3550 		tcp_acceptor_hash_remove(tcp);
3551 		mutex_enter(&tcp->tcp_non_sq_lock);
3552 		if (tcp->tcp_flow_stopped) {
3553 			tcp_clrqfull(tcp);
3554 		}
3555 		mutex_exit(&tcp->tcp_non_sq_lock);
3556 
3557 		if (tcp->tcp_timer_tid != 0) {
3558 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3559 			tcp->tcp_timer_tid = 0;
3560 		}
3561 		/*
3562 		 * Need to cancel those timers which will not be used when
3563 		 * TCP is detached.  This has to be done before the tcp_wq
3564 		 * is set to the global queue.
3565 		 */
3566 		tcp_timers_stop(tcp);
3567 
3568 		tcp->tcp_detached = B_TRUE;
3569 		ASSERT(tcps->tcps_g_q != NULL);
3570 		tcp->tcp_rq = tcps->tcps_g_q;
3571 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3572 
3573 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3574 			tcp_time_wait_append(tcp);
3575 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3576 			goto finish;
3577 		}
3578 
3579 		/*
3580 		 * If delta is zero the timer event wasn't executed and was
3581 		 * successfully canceled. In this case we need to restart it
3582 		 * with the minimal delta possible.
3583 		 */
3584 		if (delta >= 0) {
3585 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3586 			    delta ? delta : 1);
3587 		}
3588 	} else {
3589 		tcp_closei_local(tcp);
3590 		CONN_DEC_REF(tcp->tcp_connp);
3591 	}
3592 finish:
3593 	/* Signal closing thread that it can complete close */
3594 	mutex_enter(&tcp->tcp_closelock);
3595 	tcp->tcp_detached = B_TRUE;
3596 	ASSERT(tcps->tcps_g_q != NULL);
3597 
3598 	tcp->tcp_rq = tcps->tcps_g_q;
3599 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3600 
3601 	tcp->tcp_closed = 1;
3602 	cv_signal(&tcp->tcp_closecv);
3603 	mutex_exit(&tcp->tcp_closelock);
3604 }
3605 
3606 /*
3607  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3608  * expires.
3609  */
3610 static void
3611 tcp_close_linger_timeout(void *arg)
3612 {
3613 	conn_t	*connp = (conn_t *)arg;
3614 	tcp_t 	*tcp = connp->conn_tcp;
3615 
3616 	tcp->tcp_client_errno = ETIMEDOUT;
3617 	tcp_stop_lingering(tcp);
3618 }
3619 
3620 static void
3621 tcp_close_common(conn_t *connp, int flags)
3622 {
3623 	tcp_t		*tcp = connp->conn_tcp;
3624 	mblk_t 		*mp = &tcp->tcp_closemp;
3625 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3626 	mblk_t		*bp;
3627 
3628 	ASSERT(connp->conn_ref >= 2);
3629 
3630 	/*
3631 	 * Mark the conn as closing. ill_pending_mp_add will not
3632 	 * add any mp to the pending mp list, after this conn has
3633 	 * started closing. Same for sq_pending_mp_add
3634 	 */
3635 	mutex_enter(&connp->conn_lock);
3636 	connp->conn_state_flags |= CONN_CLOSING;
3637 	if (connp->conn_oper_pending_ill != NULL)
3638 		conn_ioctl_cleanup_reqd = B_TRUE;
3639 	CONN_INC_REF_LOCKED(connp);
3640 	mutex_exit(&connp->conn_lock);
3641 	tcp->tcp_closeflags = (uint8_t)flags;
3642 	ASSERT(connp->conn_ref >= 3);
3643 
3644 	/*
3645 	 * tcp_closemp_used is used below without any protection of a lock
3646 	 * as we don't expect any one else to use it concurrently at this
3647 	 * point otherwise it would be a major defect.
3648 	 */
3649 
3650 	if (mp->b_prev == NULL)
3651 		tcp->tcp_closemp_used = B_TRUE;
3652 	else
3653 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3654 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3655 
3656 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3657 
3658 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3659 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3660 
3661 	mutex_enter(&tcp->tcp_closelock);
3662 	while (!tcp->tcp_closed) {
3663 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3664 			/*
3665 			 * The cv_wait_sig() was interrupted. We now do the
3666 			 * following:
3667 			 *
3668 			 * 1) If the endpoint was lingering, we allow this
3669 			 * to be interrupted by cancelling the linger timeout
3670 			 * and closing normally.
3671 			 *
3672 			 * 2) Revert to calling cv_wait()
3673 			 *
3674 			 * We revert to using cv_wait() to avoid an
3675 			 * infinite loop which can occur if the calling
3676 			 * thread is higher priority than the squeue worker
3677 			 * thread and is bound to the same cpu.
3678 			 */
3679 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3680 				mutex_exit(&tcp->tcp_closelock);
3681 				/* Entering squeue, bump ref count. */
3682 				CONN_INC_REF(connp);
3683 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3684 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3685 				    tcp_linger_interrupted, connp,
3686 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3687 				mutex_enter(&tcp->tcp_closelock);
3688 			}
3689 			break;
3690 		}
3691 	}
3692 	while (!tcp->tcp_closed)
3693 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3694 	mutex_exit(&tcp->tcp_closelock);
3695 
3696 	/*
3697 	 * In the case of listener streams that have eagers in the q or q0
3698 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3699 	 * tcp_wq of the eagers point to our queues. By waiting for the
3700 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3701 	 * up their queue pointers and also dropped their references to us.
3702 	 */
3703 	if (tcp->tcp_wait_for_eagers) {
3704 		mutex_enter(&connp->conn_lock);
3705 		while (connp->conn_ref != 1) {
3706 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3707 		}
3708 		mutex_exit(&connp->conn_lock);
3709 	}
3710 	/*
3711 	 * ioctl cleanup. The mp is queued in the
3712 	 * ill_pending_mp or in the sq_pending_mp.
3713 	 */
3714 	if (conn_ioctl_cleanup_reqd)
3715 		conn_ioctl_cleanup(connp);
3716 
3717 	tcp->tcp_cpid = -1;
3718 }
3719 
3720 static int
3721 tcp_tpi_close(queue_t *q, int flags)
3722 {
3723 	conn_t		*connp;
3724 
3725 	ASSERT(WR(q)->q_next == NULL);
3726 
3727 	if (flags & SO_FALLBACK) {
3728 		/*
3729 		 * stream is being closed while in fallback
3730 		 * simply free the resources that were allocated
3731 		 */
3732 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3733 		qprocsoff(q);
3734 		goto done;
3735 	}
3736 
3737 	connp = Q_TO_CONN(q);
3738 	/*
3739 	 * We are being closed as /dev/tcp or /dev/tcp6.
3740 	 */
3741 	tcp_close_common(connp, flags);
3742 
3743 	qprocsoff(q);
3744 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3745 
3746 	/*
3747 	 * Drop IP's reference on the conn. This is the last reference
3748 	 * on the connp if the state was less than established. If the
3749 	 * connection has gone into timewait state, then we will have
3750 	 * one ref for the TCP and one more ref (total of two) for the
3751 	 * classifier connected hash list (a timewait connections stays
3752 	 * in connected hash till closed).
3753 	 *
3754 	 * We can't assert the references because there might be other
3755 	 * transient reference places because of some walkers or queued
3756 	 * packets in squeue for the timewait state.
3757 	 */
3758 	CONN_DEC_REF(connp);
3759 done:
3760 	q->q_ptr = WR(q)->q_ptr = NULL;
3761 	return (0);
3762 }
3763 
3764 static int
3765 tcp_tpi_close_accept(queue_t *q)
3766 {
3767 	vmem_t	*minor_arena;
3768 	dev_t	conn_dev;
3769 
3770 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3771 
3772 	/*
3773 	 * We had opened an acceptor STREAM for sockfs which is
3774 	 * now being closed due to some error.
3775 	 */
3776 	qprocsoff(q);
3777 
3778 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3779 	conn_dev = (dev_t)RD(q)->q_ptr;
3780 	ASSERT(minor_arena != NULL);
3781 	ASSERT(conn_dev != 0);
3782 	inet_minor_free(minor_arena, conn_dev);
3783 	q->q_ptr = WR(q)->q_ptr = NULL;
3784 	return (0);
3785 }
3786 
3787 /*
3788  * Called by tcp_close() routine via squeue when lingering is
3789  * interrupted by a signal.
3790  */
3791 
3792 /* ARGSUSED */
3793 static void
3794 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3795 {
3796 	conn_t	*connp = (conn_t *)arg;
3797 	tcp_t	*tcp = connp->conn_tcp;
3798 
3799 	freeb(mp);
3800 	if (tcp->tcp_linger_tid != 0 &&
3801 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3802 		tcp_stop_lingering(tcp);
3803 		tcp->tcp_client_errno = EINTR;
3804 	}
3805 }
3806 
3807 /*
3808  * Called by streams close routine via squeues when our client blows off her
3809  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3810  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3811  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3812  * acked.
3813  *
3814  * NOTE: tcp_close potentially returns error when lingering.
3815  * However, the stream head currently does not pass these errors
3816  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3817  * errors to the application (from tsleep()) and not errors
3818  * like ECONNRESET caused by receiving a reset packet.
3819  */
3820 
3821 /* ARGSUSED */
3822 static void
3823 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3824 {
3825 	char	*msg;
3826 	conn_t	*connp = (conn_t *)arg;
3827 	tcp_t	*tcp = connp->conn_tcp;
3828 	clock_t	delta = 0;
3829 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3830 
3831 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3832 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3833 
3834 	mutex_enter(&tcp->tcp_eager_lock);
3835 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3836 		/* Cleanup for listener */
3837 		tcp_eager_cleanup(tcp, 0);
3838 		tcp->tcp_wait_for_eagers = 1;
3839 	}
3840 	mutex_exit(&tcp->tcp_eager_lock);
3841 
3842 	connp->conn_mdt_ok = B_FALSE;
3843 	tcp->tcp_mdt = B_FALSE;
3844 
3845 	connp->conn_lso_ok = B_FALSE;
3846 	tcp->tcp_lso = B_FALSE;
3847 
3848 	msg = NULL;
3849 	switch (tcp->tcp_state) {
3850 	case TCPS_CLOSED:
3851 	case TCPS_IDLE:
3852 	case TCPS_BOUND:
3853 	case TCPS_LISTEN:
3854 		break;
3855 	case TCPS_SYN_SENT:
3856 		msg = "tcp_close, during connect";
3857 		break;
3858 	case TCPS_SYN_RCVD:
3859 		/*
3860 		 * Close during the connect 3-way handshake
3861 		 * but here there may or may not be pending data
3862 		 * already on queue. Process almost same as in
3863 		 * the ESTABLISHED state.
3864 		 */
3865 		/* FALLTHRU */
3866 	default:
3867 		if (tcp->tcp_fused)
3868 			tcp_unfuse(tcp);
3869 
3870 		/*
3871 		 * If SO_LINGER has set a zero linger time, abort the
3872 		 * connection with a reset.
3873 		 */
3874 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3875 			msg = "tcp_close, zero lingertime";
3876 			break;
3877 		}
3878 
3879 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3880 		/*
3881 		 * Abort connection if there is unread data queued.
3882 		 */
3883 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3884 			msg = "tcp_close, unread data";
3885 			break;
3886 		}
3887 		/*
3888 		 * tcp_hard_bound is now cleared thus all packets go through
3889 		 * tcp_lookup. This fact is used by tcp_detach below.
3890 		 *
3891 		 * We have done a qwait() above which could have possibly
3892 		 * drained more messages in turn causing transition to a
3893 		 * different state. Check whether we have to do the rest
3894 		 * of the processing or not.
3895 		 */
3896 		if (tcp->tcp_state <= TCPS_LISTEN)
3897 			break;
3898 
3899 		/*
3900 		 * Transmit the FIN before detaching the tcp_t.
3901 		 * After tcp_detach returns this queue/perimeter
3902 		 * no longer owns the tcp_t thus others can modify it.
3903 		 */
3904 		(void) tcp_xmit_end(tcp);
3905 
3906 		/*
3907 		 * If lingering on close then wait until the fin is acked,
3908 		 * the SO_LINGER time passes, or a reset is sent/received.
3909 		 */
3910 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3911 		    !(tcp->tcp_fin_acked) &&
3912 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3913 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3914 				tcp->tcp_client_errno = EWOULDBLOCK;
3915 			} else if (tcp->tcp_client_errno == 0) {
3916 
3917 				ASSERT(tcp->tcp_linger_tid == 0);
3918 
3919 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3920 				    tcp_close_linger_timeout,
3921 				    tcp->tcp_lingertime * hz);
3922 
3923 				/* tcp_close_linger_timeout will finish close */
3924 				if (tcp->tcp_linger_tid == 0)
3925 					tcp->tcp_client_errno = ENOSR;
3926 				else
3927 					return;
3928 			}
3929 
3930 			/*
3931 			 * Check if we need to detach or just close
3932 			 * the instance.
3933 			 */
3934 			if (tcp->tcp_state <= TCPS_LISTEN)
3935 				break;
3936 		}
3937 
3938 		/*
3939 		 * Make sure that no other thread will access the tcp_rq of
3940 		 * this instance (through lookups etc.) as tcp_rq will go
3941 		 * away shortly.
3942 		 */
3943 		tcp_acceptor_hash_remove(tcp);
3944 
3945 		mutex_enter(&tcp->tcp_non_sq_lock);
3946 		if (tcp->tcp_flow_stopped) {
3947 			tcp_clrqfull(tcp);
3948 		}
3949 		mutex_exit(&tcp->tcp_non_sq_lock);
3950 
3951 		if (tcp->tcp_timer_tid != 0) {
3952 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3953 			tcp->tcp_timer_tid = 0;
3954 		}
3955 		/*
3956 		 * Need to cancel those timers which will not be used when
3957 		 * TCP is detached.  This has to be done before the tcp_wq
3958 		 * is set to the global queue.
3959 		 */
3960 		tcp_timers_stop(tcp);
3961 
3962 		tcp->tcp_detached = B_TRUE;
3963 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3964 			tcp_time_wait_append(tcp);
3965 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3966 			ASSERT(connp->conn_ref >= 3);
3967 			goto finish;
3968 		}
3969 
3970 		/*
3971 		 * If delta is zero the timer event wasn't executed and was
3972 		 * successfully canceled. In this case we need to restart it
3973 		 * with the minimal delta possible.
3974 		 */
3975 		if (delta >= 0)
3976 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3977 			    delta ? delta : 1);
3978 
3979 		ASSERT(connp->conn_ref >= 3);
3980 		goto finish;
3981 	}
3982 
3983 	/* Detach did not complete. Still need to remove q from stream. */
3984 	if (msg) {
3985 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3986 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3987 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3988 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3989 		    tcp->tcp_state == TCPS_SYN_RCVD)
3990 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3991 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3992 	}
3993 
3994 	tcp_closei_local(tcp);
3995 	CONN_DEC_REF(connp);
3996 	ASSERT(connp->conn_ref >= 2);
3997 
3998 finish:
3999 	/*
4000 	 * Although packets are always processed on the correct
4001 	 * tcp's perimeter and access is serialized via squeue's,
4002 	 * IP still needs a queue when sending packets in time_wait
4003 	 * state so use WR(tcps_g_q) till ip_output() can be
4004 	 * changed to deal with just connp. For read side, we
4005 	 * could have set tcp_rq to NULL but there are some cases
4006 	 * in tcp_rput_data() from early days of this code which
4007 	 * do a putnext without checking if tcp is closed. Those
4008 	 * need to be identified before both tcp_rq and tcp_wq
4009 	 * can be set to NULL and tcps_g_q can disappear forever.
4010 	 */
4011 	mutex_enter(&tcp->tcp_closelock);
4012 	/*
4013 	 * Don't change the queues in the case of a listener that has
4014 	 * eagers in its q or q0. It could surprise the eagers.
4015 	 * Instead wait for the eagers outside the squeue.
4016 	 */
4017 	if (!tcp->tcp_wait_for_eagers) {
4018 		tcp->tcp_detached = B_TRUE;
4019 		/*
4020 		 * When default queue is closing we set tcps_g_q to NULL
4021 		 * after the close is done.
4022 		 */
4023 		ASSERT(tcps->tcps_g_q != NULL);
4024 		tcp->tcp_rq = tcps->tcps_g_q;
4025 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4026 	}
4027 
4028 	/* Signal tcp_close() to finish closing. */
4029 	tcp->tcp_closed = 1;
4030 	cv_signal(&tcp->tcp_closecv);
4031 	mutex_exit(&tcp->tcp_closelock);
4032 }
4033 
4034 /*
4035  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4036  * Some stream heads get upset if they see these later on as anything but NULL.
4037  */
4038 static void
4039 tcp_close_mpp(mblk_t **mpp)
4040 {
4041 	mblk_t	*mp;
4042 
4043 	if ((mp = *mpp) != NULL) {
4044 		do {
4045 			mp->b_next = NULL;
4046 			mp->b_prev = NULL;
4047 		} while ((mp = mp->b_cont) != NULL);
4048 
4049 		mp = *mpp;
4050 		*mpp = NULL;
4051 		freemsg(mp);
4052 	}
4053 }
4054 
4055 /* Do detached close. */
4056 static void
4057 tcp_close_detached(tcp_t *tcp)
4058 {
4059 	if (tcp->tcp_fused)
4060 		tcp_unfuse(tcp);
4061 
4062 	/*
4063 	 * Clustering code serializes TCP disconnect callbacks and
4064 	 * cluster tcp list walks by blocking a TCP disconnect callback
4065 	 * if a cluster tcp list walk is in progress. This ensures
4066 	 * accurate accounting of TCPs in the cluster code even though
4067 	 * the TCP list walk itself is not atomic.
4068 	 */
4069 	tcp_closei_local(tcp);
4070 	CONN_DEC_REF(tcp->tcp_connp);
4071 }
4072 
4073 /*
4074  * Stop all TCP timers, and free the timer mblks if requested.
4075  */
4076 void
4077 tcp_timers_stop(tcp_t *tcp)
4078 {
4079 	if (tcp->tcp_timer_tid != 0) {
4080 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4081 		tcp->tcp_timer_tid = 0;
4082 	}
4083 	if (tcp->tcp_ka_tid != 0) {
4084 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4085 		tcp->tcp_ka_tid = 0;
4086 	}
4087 	if (tcp->tcp_ack_tid != 0) {
4088 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4089 		tcp->tcp_ack_tid = 0;
4090 	}
4091 	if (tcp->tcp_push_tid != 0) {
4092 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4093 		tcp->tcp_push_tid = 0;
4094 	}
4095 }
4096 
4097 /*
4098  * The tcp_t is going away. Remove it from all lists and set it
4099  * to TCPS_CLOSED. The freeing up of memory is deferred until
4100  * tcp_inactive. This is needed since a thread in tcp_rput might have
4101  * done a CONN_INC_REF on this structure before it was removed from the
4102  * hashes.
4103  */
4104 static void
4105 tcp_closei_local(tcp_t *tcp)
4106 {
4107 	ire_t 	*ire;
4108 	conn_t	*connp = tcp->tcp_connp;
4109 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4110 
4111 	if (!TCP_IS_SOCKET(tcp))
4112 		tcp_acceptor_hash_remove(tcp);
4113 
4114 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4115 	tcp->tcp_ibsegs = 0;
4116 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4117 	tcp->tcp_obsegs = 0;
4118 
4119 	/*
4120 	 * If we are an eager connection hanging off a listener that
4121 	 * hasn't formally accepted the connection yet, get off his
4122 	 * list and blow off any data that we have accumulated.
4123 	 */
4124 	if (tcp->tcp_listener != NULL) {
4125 		tcp_t	*listener = tcp->tcp_listener;
4126 		mutex_enter(&listener->tcp_eager_lock);
4127 		/*
4128 		 * tcp_tconnind_started == B_TRUE means that the
4129 		 * conn_ind has already gone to listener. At
4130 		 * this point, eager will be closed but we
4131 		 * leave it in listeners eager list so that
4132 		 * if listener decides to close without doing
4133 		 * accept, we can clean this up. In tcp_wput_accept
4134 		 * we take care of the case of accept on closed
4135 		 * eager.
4136 		 */
4137 		if (!tcp->tcp_tconnind_started) {
4138 			tcp_eager_unlink(tcp);
4139 			mutex_exit(&listener->tcp_eager_lock);
4140 			/*
4141 			 * We don't want to have any pointers to the
4142 			 * listener queue, after we have released our
4143 			 * reference on the listener
4144 			 */
4145 			ASSERT(tcps->tcps_g_q != NULL);
4146 			tcp->tcp_rq = tcps->tcps_g_q;
4147 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4148 			CONN_DEC_REF(listener->tcp_connp);
4149 		} else {
4150 			mutex_exit(&listener->tcp_eager_lock);
4151 		}
4152 	}
4153 
4154 	/* Stop all the timers */
4155 	tcp_timers_stop(tcp);
4156 
4157 	if (tcp->tcp_state == TCPS_LISTEN) {
4158 		if (tcp->tcp_ip_addr_cache) {
4159 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4160 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4161 			tcp->tcp_ip_addr_cache = NULL;
4162 		}
4163 	}
4164 	mutex_enter(&tcp->tcp_non_sq_lock);
4165 	if (tcp->tcp_flow_stopped)
4166 		tcp_clrqfull(tcp);
4167 	mutex_exit(&tcp->tcp_non_sq_lock);
4168 
4169 	tcp_bind_hash_remove(tcp);
4170 	/*
4171 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4172 	 * is trying to remove this tcp from the time wait list, we will
4173 	 * block in tcp_time_wait_remove while trying to acquire the
4174 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4175 	 * requires the ipcl_hash_remove to be ordered after the
4176 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4177 	 */
4178 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4179 		(void) tcp_time_wait_remove(tcp, NULL);
4180 	CL_INET_DISCONNECT(connp, tcp);
4181 	ipcl_hash_remove(connp);
4182 
4183 	/*
4184 	 * Delete the cached ire in conn_ire_cache and also mark
4185 	 * the conn as CONDEMNED
4186 	 */
4187 	mutex_enter(&connp->conn_lock);
4188 	connp->conn_state_flags |= CONN_CONDEMNED;
4189 	ire = connp->conn_ire_cache;
4190 	connp->conn_ire_cache = NULL;
4191 	mutex_exit(&connp->conn_lock);
4192 	if (ire != NULL)
4193 		IRE_REFRELE_NOTR(ire);
4194 
4195 	/* Need to cleanup any pending ioctls */
4196 	ASSERT(tcp->tcp_time_wait_next == NULL);
4197 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4198 	ASSERT(tcp->tcp_time_wait_expire == 0);
4199 	tcp->tcp_state = TCPS_CLOSED;
4200 
4201 	/* Release any SSL context */
4202 	if (tcp->tcp_kssl_ent != NULL) {
4203 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4204 		tcp->tcp_kssl_ent = NULL;
4205 	}
4206 	if (tcp->tcp_kssl_ctx != NULL) {
4207 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4208 		tcp->tcp_kssl_ctx = NULL;
4209 	}
4210 	tcp->tcp_kssl_pending = B_FALSE;
4211 
4212 	tcp_ipsec_cleanup(tcp);
4213 }
4214 
4215 /*
4216  * tcp is dying (called from ipcl_conn_destroy and error cases).
4217  * Free the tcp_t in either case.
4218  */
4219 void
4220 tcp_free(tcp_t *tcp)
4221 {
4222 	mblk_t	*mp;
4223 	ip6_pkt_t	*ipp;
4224 
4225 	ASSERT(tcp != NULL);
4226 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4227 
4228 	tcp->tcp_rq = NULL;
4229 	tcp->tcp_wq = NULL;
4230 
4231 	tcp_close_mpp(&tcp->tcp_xmit_head);
4232 	tcp_close_mpp(&tcp->tcp_reass_head);
4233 	if (tcp->tcp_rcv_list != NULL) {
4234 		/* Free b_next chain */
4235 		tcp_close_mpp(&tcp->tcp_rcv_list);
4236 	}
4237 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4238 		freemsg(mp);
4239 	}
4240 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4241 		freemsg(mp);
4242 	}
4243 
4244 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4245 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4246 		freeb(tcp->tcp_fused_sigurg_mp);
4247 		tcp->tcp_fused_sigurg_mp = NULL;
4248 	}
4249 
4250 	if (tcp->tcp_ordrel_mp != NULL) {
4251 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4252 		freeb(tcp->tcp_ordrel_mp);
4253 		tcp->tcp_ordrel_mp = NULL;
4254 	}
4255 
4256 	if (tcp->tcp_sack_info != NULL) {
4257 		if (tcp->tcp_notsack_list != NULL) {
4258 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4259 		}
4260 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4261 	}
4262 
4263 	if (tcp->tcp_hopopts != NULL) {
4264 		mi_free(tcp->tcp_hopopts);
4265 		tcp->tcp_hopopts = NULL;
4266 		tcp->tcp_hopoptslen = 0;
4267 	}
4268 	ASSERT(tcp->tcp_hopoptslen == 0);
4269 	if (tcp->tcp_dstopts != NULL) {
4270 		mi_free(tcp->tcp_dstopts);
4271 		tcp->tcp_dstopts = NULL;
4272 		tcp->tcp_dstoptslen = 0;
4273 	}
4274 	ASSERT(tcp->tcp_dstoptslen == 0);
4275 	if (tcp->tcp_rtdstopts != NULL) {
4276 		mi_free(tcp->tcp_rtdstopts);
4277 		tcp->tcp_rtdstopts = NULL;
4278 		tcp->tcp_rtdstoptslen = 0;
4279 	}
4280 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4281 	if (tcp->tcp_rthdr != NULL) {
4282 		mi_free(tcp->tcp_rthdr);
4283 		tcp->tcp_rthdr = NULL;
4284 		tcp->tcp_rthdrlen = 0;
4285 	}
4286 	ASSERT(tcp->tcp_rthdrlen == 0);
4287 
4288 	ipp = &tcp->tcp_sticky_ipp;
4289 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4290 	    IPPF_RTHDR))
4291 		ip6_pkt_free(ipp);
4292 
4293 	/*
4294 	 * Free memory associated with the tcp/ip header template.
4295 	 */
4296 
4297 	if (tcp->tcp_iphc != NULL)
4298 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4299 
4300 	/*
4301 	 * Following is really a blowing away a union.
4302 	 * It happens to have exactly two members of identical size
4303 	 * the following code is enough.
4304 	 */
4305 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4306 }
4307 
4308 
4309 /*
4310  * Put a connection confirmation message upstream built from the
4311  * address information within 'iph' and 'tcph'.  Report our success or failure.
4312  */
4313 static boolean_t
4314 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4315     mblk_t **defermp)
4316 {
4317 	sin_t	sin;
4318 	sin6_t	sin6;
4319 	mblk_t	*mp;
4320 	char	*optp = NULL;
4321 	int	optlen = 0;
4322 
4323 	if (defermp != NULL)
4324 		*defermp = NULL;
4325 
4326 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4327 		/*
4328 		 * Return in T_CONN_CON results of option negotiation through
4329 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4330 		 * negotiation, then what is received from remote end needs
4331 		 * to be taken into account but there is no such thing (yet?)
4332 		 * in our TCP/IP.
4333 		 * Note: We do not use mi_offset_param() here as
4334 		 * tcp_opts_conn_req contents do not directly come from
4335 		 * an application and are either generated in kernel or
4336 		 * from user input that was already verified.
4337 		 */
4338 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4339 		optp = (char *)(mp->b_rptr +
4340 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4341 		optlen = (int)
4342 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4343 	}
4344 
4345 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4346 		ipha_t *ipha = (ipha_t *)iphdr;
4347 
4348 		/* packet is IPv4 */
4349 		if (tcp->tcp_family == AF_INET) {
4350 			sin = sin_null;
4351 			sin.sin_addr.s_addr = ipha->ipha_src;
4352 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4353 			sin.sin_family = AF_INET;
4354 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4355 			    (int)sizeof (sin_t), optp, optlen);
4356 		} else {
4357 			sin6 = sin6_null;
4358 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4359 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4360 			sin6.sin6_family = AF_INET6;
4361 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4362 			    (int)sizeof (sin6_t), optp, optlen);
4363 
4364 		}
4365 	} else {
4366 		ip6_t	*ip6h = (ip6_t *)iphdr;
4367 
4368 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4369 		ASSERT(tcp->tcp_family == AF_INET6);
4370 		sin6 = sin6_null;
4371 		sin6.sin6_addr = ip6h->ip6_src;
4372 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4373 		sin6.sin6_family = AF_INET6;
4374 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4375 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4376 		    (int)sizeof (sin6_t), optp, optlen);
4377 	}
4378 
4379 	if (!mp)
4380 		return (B_FALSE);
4381 
4382 	mblk_copycred(mp, idmp);
4383 
4384 	if (defermp == NULL) {
4385 		conn_t *connp = tcp->tcp_connp;
4386 		if (IPCL_IS_NONSTR(connp)) {
4387 			cred_t *cr;
4388 			pid_t cpid;
4389 
4390 			cr = msg_getcred(mp, &cpid);
4391 			(*connp->conn_upcalls->su_connected)
4392 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4393 			    cpid);
4394 			freemsg(mp);
4395 		} else {
4396 			putnext(tcp->tcp_rq, mp);
4397 		}
4398 	} else {
4399 		*defermp = mp;
4400 	}
4401 
4402 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4403 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4404 	return (B_TRUE);
4405 }
4406 
4407 /*
4408  * Defense for the SYN attack -
4409  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4410  *    one from the list of droppable eagers. This list is a subset of q0.
4411  *    see comments before the definition of MAKE_DROPPABLE().
4412  * 2. Don't drop a SYN request before its first timeout. This gives every
4413  *    request at least til the first timeout to complete its 3-way handshake.
4414  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4415  *    requests currently on the queue that has timed out. This will be used
4416  *    as an indicator of whether an attack is under way, so that appropriate
4417  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4418  *    either when eager goes into ESTABLISHED, or gets freed up.)
4419  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4420  *    # of timeout drops back to <= q0len/32 => SYN alert off
4421  */
4422 static boolean_t
4423 tcp_drop_q0(tcp_t *tcp)
4424 {
4425 	tcp_t	*eager;
4426 	mblk_t	*mp;
4427 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4428 
4429 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4430 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4431 
4432 	/* Pick oldest eager from the list of droppable eagers */
4433 	eager = tcp->tcp_eager_prev_drop_q0;
4434 
4435 	/* If list is empty. return B_FALSE */
4436 	if (eager == tcp) {
4437 		return (B_FALSE);
4438 	}
4439 
4440 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4441 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4442 		return (B_FALSE);
4443 
4444 	/*
4445 	 * Take this eager out from the list of droppable eagers since we are
4446 	 * going to drop it.
4447 	 */
4448 	MAKE_UNDROPPABLE(eager);
4449 
4450 	if (tcp->tcp_debug) {
4451 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4452 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4453 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4454 		    tcp->tcp_conn_req_cnt_q0,
4455 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4456 	}
4457 
4458 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4459 
4460 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4461 	CONN_INC_REF(eager->tcp_connp);
4462 
4463 	/* Mark the IRE created for this SYN request temporary */
4464 	tcp_ip_ire_mark_advice(eager);
4465 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4466 	    tcp_clean_death_wrapper, eager->tcp_connp,
4467 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4468 
4469 	return (B_TRUE);
4470 }
4471 
4472 int
4473 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4474     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4475 {
4476 	tcp_t 		*ltcp = lconnp->conn_tcp;
4477 	tcp_t		*tcp = connp->conn_tcp;
4478 	mblk_t		*tpi_mp;
4479 	ipha_t		*ipha;
4480 	ip6_t		*ip6h;
4481 	sin6_t 		sin6;
4482 	in6_addr_t 	v6dst;
4483 	int		err;
4484 	int		ifindex = 0;
4485 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4486 
4487 	if (ipvers == IPV4_VERSION) {
4488 		ipha = (ipha_t *)mp->b_rptr;
4489 
4490 		connp->conn_send = ip_output;
4491 		connp->conn_recv = tcp_input;
4492 
4493 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4494 		    &connp->conn_bound_source_v6);
4495 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4496 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4497 
4498 		sin6 = sin6_null;
4499 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4500 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4501 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4502 		sin6.sin6_family = AF_INET6;
4503 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4504 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4505 		if (tcp->tcp_recvdstaddr) {
4506 			sin6_t	sin6d;
4507 
4508 			sin6d = sin6_null;
4509 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4510 			    &sin6d.sin6_addr);
4511 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4512 			sin6d.sin6_family = AF_INET;
4513 			tpi_mp = mi_tpi_extconn_ind(NULL,
4514 			    (char *)&sin6d, sizeof (sin6_t),
4515 			    (char *)&tcp,
4516 			    (t_scalar_t)sizeof (intptr_t),
4517 			    (char *)&sin6d, sizeof (sin6_t),
4518 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4519 		} else {
4520 			tpi_mp = mi_tpi_conn_ind(NULL,
4521 			    (char *)&sin6, sizeof (sin6_t),
4522 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4523 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4524 		}
4525 	} else {
4526 		ip6h = (ip6_t *)mp->b_rptr;
4527 
4528 		connp->conn_send = ip_output_v6;
4529 		connp->conn_recv = tcp_input;
4530 
4531 		connp->conn_bound_source_v6 = ip6h->ip6_dst;
4532 		connp->conn_srcv6 = ip6h->ip6_dst;
4533 		connp->conn_remv6 = ip6h->ip6_src;
4534 
4535 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4536 		ifindex = (int)DB_CKSUMSTUFF(mp);
4537 		DB_CKSUMSTUFF(mp) = 0;
4538 
4539 		sin6 = sin6_null;
4540 		sin6.sin6_addr = ip6h->ip6_src;
4541 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4542 		sin6.sin6_family = AF_INET6;
4543 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4544 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4545 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4546 
4547 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4548 			/* Pass up the scope_id of remote addr */
4549 			sin6.sin6_scope_id = ifindex;
4550 		} else {
4551 			sin6.sin6_scope_id = 0;
4552 		}
4553 		if (tcp->tcp_recvdstaddr) {
4554 			sin6_t	sin6d;
4555 
4556 			sin6d = sin6_null;
4557 			sin6.sin6_addr = ip6h->ip6_dst;
4558 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4559 			sin6d.sin6_family = AF_INET;
4560 			tpi_mp = mi_tpi_extconn_ind(NULL,
4561 			    (char *)&sin6d, sizeof (sin6_t),
4562 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4563 			    (char *)&sin6d, sizeof (sin6_t),
4564 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4565 		} else {
4566 			tpi_mp = mi_tpi_conn_ind(NULL,
4567 			    (char *)&sin6, sizeof (sin6_t),
4568 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4569 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4570 		}
4571 	}
4572 
4573 	if (tpi_mp == NULL)
4574 		return (ENOMEM);
4575 
4576 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4577 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4578 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4579 	connp->conn_fully_bound = B_FALSE;
4580 
4581 	/* Inherit information from the "parent" */
4582 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4583 	tcp->tcp_family = ltcp->tcp_family;
4584 
4585 	tcp->tcp_wq = ltcp->tcp_wq;
4586 	tcp->tcp_rq = ltcp->tcp_rq;
4587 
4588 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4589 	tcp->tcp_detached = B_TRUE;
4590 	SOCK_CONNID_INIT(tcp->tcp_connid);
4591 	if ((err = tcp_init_values(tcp)) != 0) {
4592 		freemsg(tpi_mp);
4593 		return (err);
4594 	}
4595 
4596 	if (ipvers == IPV4_VERSION) {
4597 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4598 			freemsg(tpi_mp);
4599 			return (err);
4600 		}
4601 		ASSERT(tcp->tcp_ipha != NULL);
4602 	} else {
4603 		/* ifindex must be already set */
4604 		ASSERT(ifindex != 0);
4605 
4606 		if (ltcp->tcp_bound_if != 0)
4607 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4608 		else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src))
4609 			tcp->tcp_bound_if = ifindex;
4610 
4611 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4612 		tcp->tcp_recvifindex = 0;
4613 		tcp->tcp_recvhops = 0xffffffffU;
4614 		ASSERT(tcp->tcp_ip6h != NULL);
4615 	}
4616 
4617 	tcp->tcp_lport = ltcp->tcp_lport;
4618 
4619 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4620 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4621 			/*
4622 			 * Listener had options of some sort; eager inherits.
4623 			 * Free up the eager template and allocate one
4624 			 * of the right size.
4625 			 */
4626 			if (tcp->tcp_hdr_grown) {
4627 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4628 			} else {
4629 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4630 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4631 			}
4632 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4633 			    KM_NOSLEEP);
4634 			if (tcp->tcp_iphc == NULL) {
4635 				tcp->tcp_iphc_len = 0;
4636 				freemsg(tpi_mp);
4637 				return (ENOMEM);
4638 			}
4639 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4640 			tcp->tcp_hdr_grown = B_TRUE;
4641 		}
4642 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4643 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4644 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4645 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4646 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4647 
4648 		/*
4649 		 * Copy the IP+TCP header template from listener to eager
4650 		 */
4651 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4652 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4653 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4654 			    IPPROTO_RAW) {
4655 				tcp->tcp_ip6h =
4656 				    (ip6_t *)(tcp->tcp_iphc +
4657 				    sizeof (ip6i_t));
4658 			} else {
4659 				tcp->tcp_ip6h =
4660 				    (ip6_t *)(tcp->tcp_iphc);
4661 			}
4662 			tcp->tcp_ipha = NULL;
4663 		} else {
4664 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4665 			tcp->tcp_ip6h = NULL;
4666 		}
4667 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4668 		    tcp->tcp_ip_hdr_len);
4669 	} else {
4670 		/*
4671 		 * only valid case when ipversion of listener and
4672 		 * eager differ is when listener is IPv6 and
4673 		 * eager is IPv4.
4674 		 * Eager header template has been initialized to the
4675 		 * maximum v4 header sizes, which includes space for
4676 		 * TCP and IP options.
4677 		 */
4678 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4679 		    (tcp->tcp_ipversion == IPV4_VERSION));
4680 		ASSERT(tcp->tcp_iphc_len >=
4681 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4682 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4683 		/* copy IP header fields individually */
4684 		tcp->tcp_ipha->ipha_ttl =
4685 		    ltcp->tcp_ip6h->ip6_hops;
4686 		bcopy(ltcp->tcp_tcph->th_lport,
4687 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4688 	}
4689 
4690 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4691 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4692 	    sizeof (in_port_t));
4693 
4694 	if (ltcp->tcp_lport == 0) {
4695 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4696 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4697 		    sizeof (in_port_t));
4698 	}
4699 
4700 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4701 		ASSERT(ipha != NULL);
4702 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4703 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4704 
4705 		/* Source routing option copyover (reverse it) */
4706 		if (tcps->tcps_rev_src_routes)
4707 			tcp_opt_reverse(tcp, ipha);
4708 	} else {
4709 		ASSERT(ip6h != NULL);
4710 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4711 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4712 	}
4713 
4714 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4715 	ASSERT(!tcp->tcp_tconnind_started);
4716 	/*
4717 	 * If the SYN contains a credential, it's a loopback packet; attach
4718 	 * the credential to the TPI message.
4719 	 */
4720 	mblk_copycred(tpi_mp, idmp);
4721 
4722 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4723 
4724 	/* Inherit the listener's SSL protection state */
4725 
4726 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4727 		kssl_hold_ent(tcp->tcp_kssl_ent);
4728 		tcp->tcp_kssl_pending = B_TRUE;
4729 	}
4730 
4731 	/* Inherit the listener's non-STREAMS flag */
4732 	if (IPCL_IS_NONSTR(lconnp)) {
4733 		connp->conn_flags |= IPCL_NONSTR;
4734 	}
4735 
4736 	return (0);
4737 }
4738 
4739 
4740 int
4741 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4742     tcph_t *tcph, mblk_t *idmp)
4743 {
4744 	tcp_t 		*ltcp = lconnp->conn_tcp;
4745 	tcp_t		*tcp = connp->conn_tcp;
4746 	sin_t		sin;
4747 	mblk_t		*tpi_mp = NULL;
4748 	int		err;
4749 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4750 
4751 	sin = sin_null;
4752 	sin.sin_addr.s_addr = ipha->ipha_src;
4753 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4754 	sin.sin_family = AF_INET;
4755 	if (ltcp->tcp_recvdstaddr) {
4756 		sin_t	sind;
4757 
4758 		sind = sin_null;
4759 		sind.sin_addr.s_addr = ipha->ipha_dst;
4760 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4761 		sind.sin_family = AF_INET;
4762 		tpi_mp = mi_tpi_extconn_ind(NULL,
4763 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4764 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4765 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4766 	} else {
4767 		tpi_mp = mi_tpi_conn_ind(NULL,
4768 		    (char *)&sin, sizeof (sin_t),
4769 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4770 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4771 	}
4772 
4773 	if (tpi_mp == NULL) {
4774 		return (ENOMEM);
4775 	}
4776 
4777 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4778 	connp->conn_send = ip_output;
4779 	connp->conn_recv = tcp_input;
4780 	connp->conn_fully_bound = B_FALSE;
4781 
4782 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4783 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4784 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4785 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4786 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4787 
4788 	/* Inherit information from the "parent" */
4789 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4790 	tcp->tcp_family = ltcp->tcp_family;
4791 	tcp->tcp_wq = ltcp->tcp_wq;
4792 	tcp->tcp_rq = ltcp->tcp_rq;
4793 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4794 	tcp->tcp_detached = B_TRUE;
4795 	SOCK_CONNID_INIT(tcp->tcp_connid);
4796 	if ((err = tcp_init_values(tcp)) != 0) {
4797 		freemsg(tpi_mp);
4798 		return (err);
4799 	}
4800 
4801 	/*
4802 	 * Let's make sure that eager tcp template has enough space to
4803 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4804 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4805 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4806 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4807 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4808 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4809 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4810 	 */
4811 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4812 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4813 
4814 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4815 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4816 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4817 	tcp->tcp_ttl = ltcp->tcp_ttl;
4818 	tcp->tcp_tos = ltcp->tcp_tos;
4819 
4820 	/* Copy the IP+TCP header template from listener to eager */
4821 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4822 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4823 	tcp->tcp_ip6h = NULL;
4824 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4825 	    tcp->tcp_ip_hdr_len);
4826 
4827 	/* Initialize the IP addresses and Ports */
4828 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4829 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4830 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4831 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4832 
4833 	/* Source routing option copyover (reverse it) */
4834 	if (tcps->tcps_rev_src_routes)
4835 		tcp_opt_reverse(tcp, ipha);
4836 
4837 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4838 	ASSERT(!tcp->tcp_tconnind_started);
4839 
4840 	/*
4841 	 * If the SYN contains a credential, it's a loopback packet; attach
4842 	 * the credential to the TPI message.
4843 	 */
4844 	mblk_copycred(tpi_mp, idmp);
4845 
4846 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4847 
4848 	/* Inherit the listener's SSL protection state */
4849 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4850 		kssl_hold_ent(tcp->tcp_kssl_ent);
4851 		tcp->tcp_kssl_pending = B_TRUE;
4852 	}
4853 
4854 	/* Inherit the listener's non-STREAMS flag */
4855 	if (IPCL_IS_NONSTR(lconnp)) {
4856 		connp->conn_flags |= IPCL_NONSTR;
4857 	}
4858 
4859 	return (0);
4860 }
4861 
4862 /*
4863  * sets up conn for ipsec.
4864  * if the first mblk is M_CTL it is consumed and mpp is updated.
4865  * in case of error mpp is freed.
4866  */
4867 conn_t *
4868 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4869 {
4870 	conn_t 		*connp = tcp->tcp_connp;
4871 	conn_t 		*econnp;
4872 	squeue_t 	*new_sqp;
4873 	mblk_t 		*first_mp = *mpp;
4874 	mblk_t		*mp = *mpp;
4875 	boolean_t	mctl_present = B_FALSE;
4876 	uint_t		ipvers;
4877 
4878 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4879 	if (econnp == NULL) {
4880 		freemsg(first_mp);
4881 		return (NULL);
4882 	}
4883 	if (DB_TYPE(mp) == M_CTL) {
4884 		if (mp->b_cont == NULL ||
4885 		    mp->b_cont->b_datap->db_type != M_DATA) {
4886 			freemsg(first_mp);
4887 			return (NULL);
4888 		}
4889 		mp = mp->b_cont;
4890 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4891 			freemsg(first_mp);
4892 			return (NULL);
4893 		}
4894 
4895 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4896 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4897 		mctl_present = B_TRUE;
4898 	} else {
4899 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4900 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4901 	}
4902 
4903 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4904 	DB_CKSUMSTART(mp) = 0;
4905 
4906 	ASSERT(OK_32PTR(mp->b_rptr));
4907 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4908 	if (ipvers == IPV4_VERSION) {
4909 		uint16_t  	*up;
4910 		uint32_t	ports;
4911 		ipha_t		*ipha;
4912 
4913 		ipha = (ipha_t *)mp->b_rptr;
4914 		up = (uint16_t *)((uchar_t *)ipha +
4915 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4916 		ports = *(uint32_t *)up;
4917 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4918 		    ipha->ipha_dst, ipha->ipha_src, ports);
4919 	} else {
4920 		uint16_t  	*up;
4921 		uint32_t	ports;
4922 		uint16_t	ip_hdr_len;
4923 		uint8_t		*nexthdrp;
4924 		ip6_t 		*ip6h;
4925 		tcph_t		*tcph;
4926 
4927 		ip6h = (ip6_t *)mp->b_rptr;
4928 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4929 			ip_hdr_len = IPV6_HDR_LEN;
4930 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4931 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4932 			CONN_DEC_REF(econnp);
4933 			freemsg(first_mp);
4934 			return (NULL);
4935 		}
4936 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4937 		up = (uint16_t *)tcph->th_lport;
4938 		ports = *(uint32_t *)up;
4939 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4940 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4941 	}
4942 
4943 	/*
4944 	 * The caller already ensured that there is a sqp present.
4945 	 */
4946 	econnp->conn_sqp = new_sqp;
4947 	econnp->conn_initial_sqp = new_sqp;
4948 
4949 	if (connp->conn_policy != NULL) {
4950 		ipsec_in_t *ii;
4951 		ii = (ipsec_in_t *)(first_mp->b_rptr);
4952 		ASSERT(ii->ipsec_in_policy == NULL);
4953 		IPPH_REFHOLD(connp->conn_policy);
4954 		ii->ipsec_in_policy = connp->conn_policy;
4955 
4956 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
4957 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
4958 			CONN_DEC_REF(econnp);
4959 			freemsg(first_mp);
4960 			return (NULL);
4961 		}
4962 	}
4963 
4964 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
4965 		CONN_DEC_REF(econnp);
4966 		freemsg(first_mp);
4967 		return (NULL);
4968 	}
4969 
4970 	/*
4971 	 * If we know we have some policy, pass the "IPSEC"
4972 	 * options size TCP uses this adjust the MSS.
4973 	 */
4974 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
4975 	if (mctl_present) {
4976 		freeb(first_mp);
4977 		*mpp = mp;
4978 	}
4979 
4980 	return (econnp);
4981 }
4982 
4983 /*
4984  * tcp_get_conn/tcp_free_conn
4985  *
4986  * tcp_get_conn is used to get a clean tcp connection structure.
4987  * It tries to reuse the connections put on the freelist by the
4988  * time_wait_collector failing which it goes to kmem_cache. This
4989  * way has two benefits compared to just allocating from and
4990  * freeing to kmem_cache.
4991  * 1) The time_wait_collector can free (which includes the cleanup)
4992  * outside the squeue. So when the interrupt comes, we have a clean
4993  * connection sitting in the freelist. Obviously, this buys us
4994  * performance.
4995  *
4996  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
4997  * has multiple disadvantages - tying up the squeue during alloc, and the
4998  * fact that IPSec policy initialization has to happen here which
4999  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5000  * But allocating the conn/tcp in IP land is also not the best since
5001  * we can't check the 'q' and 'q0' which are protected by squeue and
5002  * blindly allocate memory which might have to be freed here if we are
5003  * not allowed to accept the connection. By using the freelist and
5004  * putting the conn/tcp back in freelist, we don't pay a penalty for
5005  * allocating memory without checking 'q/q0' and freeing it if we can't
5006  * accept the connection.
5007  *
5008  * Care should be taken to put the conn back in the same squeue's freelist
5009  * from which it was allocated. Best results are obtained if conn is
5010  * allocated from listener's squeue and freed to the same. Time wait
5011  * collector will free up the freelist is the connection ends up sitting
5012  * there for too long.
5013  */
5014 void *
5015 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5016 {
5017 	tcp_t			*tcp = NULL;
5018 	conn_t			*connp = NULL;
5019 	squeue_t		*sqp = (squeue_t *)arg;
5020 	tcp_squeue_priv_t 	*tcp_time_wait;
5021 	netstack_t		*ns;
5022 	mblk_t			*tcp_rsrv_mp = NULL;
5023 
5024 	tcp_time_wait =
5025 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5026 
5027 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5028 	tcp = tcp_time_wait->tcp_free_list;
5029 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5030 	if (tcp != NULL) {
5031 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5032 		tcp_time_wait->tcp_free_list_cnt--;
5033 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5034 		tcp->tcp_time_wait_next = NULL;
5035 		connp = tcp->tcp_connp;
5036 		connp->conn_flags |= IPCL_REUSED;
5037 
5038 		ASSERT(tcp->tcp_tcps == NULL);
5039 		ASSERT(connp->conn_netstack == NULL);
5040 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5041 		ns = tcps->tcps_netstack;
5042 		netstack_hold(ns);
5043 		connp->conn_netstack = ns;
5044 		tcp->tcp_tcps = tcps;
5045 		TCPS_REFHOLD(tcps);
5046 		ipcl_globalhash_insert(connp);
5047 		return ((void *)connp);
5048 	}
5049 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5050 	/*
5051 	 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
5052 	 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
5053 	 */
5054 	tcp_rsrv_mp = allocb(0, BPRI_HI);
5055 	if (tcp_rsrv_mp == NULL)
5056 		return (NULL);
5057 
5058 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5059 	    tcps->tcps_netstack)) == NULL) {
5060 		freeb(tcp_rsrv_mp);
5061 		return (NULL);
5062 	}
5063 
5064 	tcp = connp->conn_tcp;
5065 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
5066 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5067 
5068 	tcp->tcp_tcps = tcps;
5069 	TCPS_REFHOLD(tcps);
5070 
5071 	return ((void *)connp);
5072 }
5073 
5074 /*
5075  * Update the cached label for the given tcp_t.  This should be called once per
5076  * connection, and before any packets are sent or tcp_process_options is
5077  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5078  */
5079 static boolean_t
5080 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5081 {
5082 	conn_t *connp = tcp->tcp_connp;
5083 
5084 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5085 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5086 		int added;
5087 
5088 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5089 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5090 			return (B_FALSE);
5091 
5092 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5093 		if (added == -1)
5094 			return (B_FALSE);
5095 		tcp->tcp_hdr_len += added;
5096 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5097 		tcp->tcp_ip_hdr_len += added;
5098 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5099 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5100 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5101 			    tcp->tcp_hdr_len);
5102 			if (added == -1)
5103 				return (B_FALSE);
5104 			tcp->tcp_hdr_len += added;
5105 			tcp->tcp_tcph = (tcph_t *)
5106 			    ((uchar_t *)tcp->tcp_tcph + added);
5107 			tcp->tcp_ip_hdr_len += added;
5108 		}
5109 	} else {
5110 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5111 
5112 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5113 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5114 			return (B_FALSE);
5115 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5116 		    &tcp->tcp_label_len, optbuf) != 0)
5117 			return (B_FALSE);
5118 		if (tcp_build_hdrs(tcp) != 0)
5119 			return (B_FALSE);
5120 	}
5121 
5122 	connp->conn_ulp_labeled = 1;
5123 
5124 	return (B_TRUE);
5125 }
5126 
5127 /* BEGIN CSTYLED */
5128 /*
5129  *
5130  * The sockfs ACCEPT path:
5131  * =======================
5132  *
5133  * The eager is now established in its own perimeter as soon as SYN is
5134  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5135  * completes the accept processing on the acceptor STREAM. The sending
5136  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5137  * listener but a TLI/XTI listener completes the accept processing
5138  * on the listener perimeter.
5139  *
5140  * Common control flow for 3 way handshake:
5141  * ----------------------------------------
5142  *
5143  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5144  *					-> tcp_conn_request()
5145  *
5146  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5147  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5148  *
5149  * Sockfs ACCEPT Path:
5150  * -------------------
5151  *
5152  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5153  * as STREAM entry point)
5154  *
5155  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5156  *
5157  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5158  * association (we are not behind eager's squeue but sockfs is protecting us
5159  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5160  * is changed to point at tcp_wput().
5161  *
5162  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5163  * listener (done on listener's perimeter).
5164  *
5165  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5166  * accept.
5167  *
5168  * TLI/XTI client ACCEPT path:
5169  * ---------------------------
5170  *
5171  * soaccept() sends T_CONN_RES on the listener STREAM.
5172  *
5173  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5174  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5175  *
5176  * Locks:
5177  * ======
5178  *
5179  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5180  * and listeners->tcp_eager_next_q.
5181  *
5182  * Referencing:
5183  * ============
5184  *
5185  * 1) We start out in tcp_conn_request by eager placing a ref on
5186  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5187  *
5188  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5189  * doing so we place a ref on the eager. This ref is finally dropped at the
5190  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5191  * reference is dropped by the squeue framework.
5192  *
5193  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5194  *
5195  * The reference must be released by the same entity that added the reference
5196  * In the above scheme, the eager is the entity that adds and releases the
5197  * references. Note that tcp_accept_finish executes in the squeue of the eager
5198  * (albeit after it is attached to the acceptor stream). Though 1. executes
5199  * in the listener's squeue, the eager is nascent at this point and the
5200  * reference can be considered to have been added on behalf of the eager.
5201  *
5202  * Eager getting a Reset or listener closing:
5203  * ==========================================
5204  *
5205  * Once the listener and eager are linked, the listener never does the unlink.
5206  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5207  * a message on all eager perimeter. The eager then does the unlink, clears
5208  * any pointers to the listener's queue and drops the reference to the
5209  * listener. The listener waits in tcp_close outside the squeue until its
5210  * refcount has dropped to 1. This ensures that the listener has waited for
5211  * all eagers to clear their association with the listener.
5212  *
5213  * Similarly, if eager decides to go away, it can unlink itself and close.
5214  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5215  * the reference to eager is still valid because of the extra ref we put
5216  * in tcp_send_conn_ind.
5217  *
5218  * Listener can always locate the eager under the protection
5219  * of the listener->tcp_eager_lock, and then do a refhold
5220  * on the eager during the accept processing.
5221  *
5222  * The acceptor stream accesses the eager in the accept processing
5223  * based on the ref placed on eager before sending T_conn_ind.
5224  * The only entity that can negate this refhold is a listener close
5225  * which is mutually exclusive with an active acceptor stream.
5226  *
5227  * Eager's reference on the listener
5228  * ===================================
5229  *
5230  * If the accept happens (even on a closed eager) the eager drops its
5231  * reference on the listener at the start of tcp_accept_finish. If the
5232  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5233  * the reference is dropped in tcp_closei_local. If the listener closes,
5234  * the reference is dropped in tcp_eager_kill. In all cases the reference
5235  * is dropped while executing in the eager's context (squeue).
5236  */
5237 /* END CSTYLED */
5238 
5239 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5240 
5241 /*
5242  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5243  * tcp_rput_data will not see any SYN packets.
5244  */
5245 /* ARGSUSED */
5246 void
5247 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5248 {
5249 	tcph_t		*tcph;
5250 	uint32_t	seg_seq;
5251 	tcp_t		*eager;
5252 	uint_t		ipvers;
5253 	ipha_t		*ipha;
5254 	ip6_t		*ip6h;
5255 	int		err;
5256 	conn_t		*econnp = NULL;
5257 	squeue_t	*new_sqp;
5258 	mblk_t		*mp1;
5259 	uint_t 		ip_hdr_len;
5260 	conn_t		*connp = (conn_t *)arg;
5261 	tcp_t		*tcp = connp->conn_tcp;
5262 	cred_t		*credp;
5263 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5264 	ip_stack_t	*ipst;
5265 
5266 	if (tcp->tcp_state != TCPS_LISTEN)
5267 		goto error2;
5268 
5269 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5270 
5271 	mutex_enter(&tcp->tcp_eager_lock);
5272 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5273 		mutex_exit(&tcp->tcp_eager_lock);
5274 		TCP_STAT(tcps, tcp_listendrop);
5275 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5276 		if (tcp->tcp_debug) {
5277 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5278 			    "tcp_conn_request: listen backlog (max=%d) "
5279 			    "overflow (%d pending) on %s",
5280 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5281 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5282 		}
5283 		goto error2;
5284 	}
5285 
5286 	if (tcp->tcp_conn_req_cnt_q0 >=
5287 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5288 		/*
5289 		 * Q0 is full. Drop a pending half-open req from the queue
5290 		 * to make room for the new SYN req. Also mark the time we
5291 		 * drop a SYN.
5292 		 *
5293 		 * A more aggressive defense against SYN attack will
5294 		 * be to set the "tcp_syn_defense" flag now.
5295 		 */
5296 		TCP_STAT(tcps, tcp_listendropq0);
5297 		tcp->tcp_last_rcv_lbolt = lbolt64;
5298 		if (!tcp_drop_q0(tcp)) {
5299 			mutex_exit(&tcp->tcp_eager_lock);
5300 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5301 			if (tcp->tcp_debug) {
5302 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5303 				    "tcp_conn_request: listen half-open queue "
5304 				    "(max=%d) full (%d pending) on %s",
5305 				    tcps->tcps_conn_req_max_q0,
5306 				    tcp->tcp_conn_req_cnt_q0,
5307 				    tcp_display(tcp, NULL,
5308 				    DISP_PORT_ONLY));
5309 			}
5310 			goto error2;
5311 		}
5312 	}
5313 	mutex_exit(&tcp->tcp_eager_lock);
5314 
5315 	/*
5316 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5317 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5318 	 * link local address.  If IPSec is enabled, db_struioflag has
5319 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5320 	 * otherwise an error case if neither of them is set.
5321 	 */
5322 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5323 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5324 		DB_CKSUMSTART(mp) = 0;
5325 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5326 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5327 		if (econnp == NULL)
5328 			goto error2;
5329 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5330 		econnp->conn_sqp = new_sqp;
5331 		econnp->conn_initial_sqp = new_sqp;
5332 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5333 		/*
5334 		 * mp is updated in tcp_get_ipsec_conn().
5335 		 */
5336 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5337 		if (econnp == NULL) {
5338 			/*
5339 			 * mp freed by tcp_get_ipsec_conn.
5340 			 */
5341 			return;
5342 		}
5343 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5344 	} else {
5345 		goto error2;
5346 	}
5347 
5348 	ASSERT(DB_TYPE(mp) == M_DATA);
5349 
5350 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5351 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5352 	ASSERT(OK_32PTR(mp->b_rptr));
5353 	if (ipvers == IPV4_VERSION) {
5354 		ipha = (ipha_t *)mp->b_rptr;
5355 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5356 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5357 	} else {
5358 		ip6h = (ip6_t *)mp->b_rptr;
5359 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5360 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5361 	}
5362 
5363 	if (tcp->tcp_family == AF_INET) {
5364 		ASSERT(ipvers == IPV4_VERSION);
5365 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5366 	} else {
5367 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5368 	}
5369 
5370 	if (err)
5371 		goto error3;
5372 
5373 	eager = econnp->conn_tcp;
5374 	ASSERT(eager->tcp_ordrel_mp == NULL);
5375 
5376 	if (!IPCL_IS_NONSTR(econnp)) {
5377 		/*
5378 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
5379 		 * at close time, we will always have that to send up.
5380 		 * Otherwise, we need to do special handling in case the
5381 		 * allocation fails at that time.
5382 		 */
5383 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5384 			goto error3;
5385 	}
5386 	/* Inherit various TCP parameters from the listener */
5387 	eager->tcp_naglim = tcp->tcp_naglim;
5388 	eager->tcp_first_timer_threshold = tcp->tcp_first_timer_threshold;
5389 	eager->tcp_second_timer_threshold = tcp->tcp_second_timer_threshold;
5390 
5391 	eager->tcp_first_ctimer_threshold = tcp->tcp_first_ctimer_threshold;
5392 	eager->tcp_second_ctimer_threshold = tcp->tcp_second_ctimer_threshold;
5393 
5394 	/*
5395 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5396 	 * If it does not, the eager's receive window will be set to the
5397 	 * listener's receive window later in this function.
5398 	 */
5399 	eager->tcp_rwnd = 0;
5400 
5401 	/*
5402 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5403 	 * calling tcp_process_options() where tcp_mss_set() is called
5404 	 * to set the initial cwnd.
5405 	 */
5406 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5407 
5408 	/*
5409 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5410 	 * zone id before the accept is completed in tcp_wput_accept().
5411 	 */
5412 	econnp->conn_zoneid = connp->conn_zoneid;
5413 	econnp->conn_allzones = connp->conn_allzones;
5414 
5415 	/* Copy nexthop information from listener to eager */
5416 	if (connp->conn_nexthop_set) {
5417 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5418 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5419 	}
5420 
5421 	/*
5422 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5423 	 * eager is accepted
5424 	 */
5425 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5426 	crhold(credp);
5427 
5428 	ASSERT(econnp->conn_effective_cred == NULL);
5429 	if (is_system_labeled()) {
5430 		cred_t *cr;
5431 		ts_label_t *tsl;
5432 
5433 		/*
5434 		 * If this is an MLP connection or a MAC-Exempt connection
5435 		 * with an unlabeled node, packets are to be
5436 		 * exchanged using the security label of the received
5437 		 * SYN packet instead of the server application's label.
5438 		 */
5439 		if ((cr = msg_getcred(mp, NULL)) != NULL &&
5440 		    (tsl = crgetlabel(cr)) != NULL &&
5441 		    (connp->conn_mlp_type != mlptSingle ||
5442 		    (connp->conn_mac_exempt == B_TRUE &&
5443 		    (tsl->tsl_flags & TSLF_UNLABELED)))) {
5444 			if ((econnp->conn_effective_cred =
5445 			    copycred_from_tslabel(econnp->conn_cred,
5446 			    tsl, KM_NOSLEEP)) != NULL) {
5447 				DTRACE_PROBE2(
5448 				    syn_accept_peerlabel,
5449 				    conn_t *, econnp, cred_t *,
5450 				    econnp->conn_effective_cred);
5451 			} else {
5452 				DTRACE_PROBE3(
5453 				    tx__ip__log__error__set__eagercred__tcp,
5454 				    char *,
5455 				    "SYN mp(1) label on eager connp(2) failed",
5456 				    mblk_t *, mp, conn_t *, econnp);
5457 				goto error3;
5458 			}
5459 		} else {
5460 			DTRACE_PROBE2(syn_accept, conn_t *,
5461 			    econnp, cred_t *, econnp->conn_cred)
5462 		}
5463 
5464 		/*
5465 		 * Verify the destination is allowed to receive packets
5466 		 * at the security label of the SYN-ACK we are generating.
5467 		 * tsol_check_dest() may create a new effective cred for
5468 		 * this connection with a modified label or label flags.
5469 		 */
5470 		if (IN6_IS_ADDR_V4MAPPED(&econnp->conn_remv6)) {
5471 			uint32_t dst;
5472 			IN6_V4MAPPED_TO_IPADDR(&econnp->conn_remv6, dst);
5473 			err = tsol_check_dest(CONN_CRED(econnp), &dst,
5474 			    IPV4_VERSION, B_FALSE, &cr);
5475 		} else {
5476 			err = tsol_check_dest(CONN_CRED(econnp),
5477 			    &econnp->conn_remv6, IPV6_VERSION,
5478 			    B_FALSE, &cr);
5479 		}
5480 		if (err != 0)
5481 			goto error3;
5482 		if (cr != NULL) {
5483 			if (econnp->conn_effective_cred != NULL)
5484 				crfree(econnp->conn_effective_cred);
5485 			econnp->conn_effective_cred = cr;
5486 		}
5487 
5488 		/*
5489 		 * Generate the security label to be used in the text of
5490 		 * this connection's outgoing packets.
5491 		 */
5492 		if (!tcp_update_label(eager, CONN_CRED(econnp))) {
5493 			DTRACE_PROBE3(
5494 			    tx__ip__log__error__connrequest__tcp,
5495 			    char *, "eager connp(1) label on SYN mp(2) failed",
5496 			    conn_t *, econnp, mblk_t *, mp);
5497 			goto error3;
5498 		}
5499 	}
5500 
5501 	eager->tcp_hard_binding = B_TRUE;
5502 
5503 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5504 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5505 
5506 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5507 	if (err != 0) {
5508 		tcp_bind_hash_remove(eager);
5509 		goto error3;
5510 	}
5511 
5512 	/*
5513 	 * No need to check for multicast destination since ip will only pass
5514 	 * up multicasts to those that have expressed interest
5515 	 * TODO: what about rejecting broadcasts?
5516 	 * Also check that source is not a multicast or broadcast address.
5517 	 */
5518 	eager->tcp_state = TCPS_SYN_RCVD;
5519 
5520 
5521 	/*
5522 	 * There should be no ire in the mp as we are being called after
5523 	 * receiving the SYN.
5524 	 */
5525 	ASSERT(tcp_ire_mp(&mp) == NULL);
5526 
5527 	/*
5528 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5529 	 */
5530 
5531 	if (tcp_adapt_ire(eager, NULL) == 0) {
5532 		/* Undo the bind_hash_insert */
5533 		tcp_bind_hash_remove(eager);
5534 		goto error3;
5535 	}
5536 
5537 	/* Process all TCP options. */
5538 	tcp_process_options(eager, tcph);
5539 
5540 	/* Is the other end ECN capable? */
5541 	if (tcps->tcps_ecn_permitted >= 1 &&
5542 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5543 		eager->tcp_ecn_ok = B_TRUE;
5544 	}
5545 
5546 	/*
5547 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5548 	 * window size changed via SO_RCVBUF option.  First round up the
5549 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5550 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5551 	 * setting.
5552 	 *
5553 	 * Note if there is a rpipe metric associated with the remote host,
5554 	 * we should not inherit receive window size from listener.
5555 	 */
5556 	eager->tcp_rwnd = MSS_ROUNDUP(
5557 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5558 	    eager->tcp_rwnd), eager->tcp_mss);
5559 	if (eager->tcp_snd_ws_ok)
5560 		tcp_set_ws_value(eager);
5561 	/*
5562 	 * Note that this is the only place tcp_rwnd_set() is called for
5563 	 * accepting a connection.  We need to call it here instead of
5564 	 * after the 3-way handshake because we need to tell the other
5565 	 * side our rwnd in the SYN-ACK segment.
5566 	 */
5567 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5568 
5569 	/*
5570 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5571 	 * via soaccept()->soinheritoptions() which essentially applies
5572 	 * all the listener options to the new STREAM. The options that we
5573 	 * need to take care of are:
5574 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5575 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5576 	 * SO_SNDBUF, SO_RCVBUF.
5577 	 *
5578 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5579 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5580 	 *		tcp_maxpsz_set() gets called later from
5581 	 *		tcp_accept_finish(), the option takes effect.
5582 	 *
5583 	 */
5584 	/* Set the TCP options */
5585 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5586 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5587 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5588 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5589 	eager->tcp_oobinline = tcp->tcp_oobinline;
5590 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5591 	eager->tcp_broadcast = tcp->tcp_broadcast;
5592 	eager->tcp_useloopback = tcp->tcp_useloopback;
5593 	eager->tcp_dontroute = tcp->tcp_dontroute;
5594 	eager->tcp_debug = tcp->tcp_debug;
5595 	eager->tcp_linger = tcp->tcp_linger;
5596 	eager->tcp_lingertime = tcp->tcp_lingertime;
5597 	if (tcp->tcp_ka_enabled)
5598 		eager->tcp_ka_enabled = 1;
5599 
5600 	/* Set the IP options */
5601 	econnp->conn_broadcast = connp->conn_broadcast;
5602 	econnp->conn_loopback = connp->conn_loopback;
5603 	econnp->conn_dontroute = connp->conn_dontroute;
5604 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5605 
5606 	/* Put a ref on the listener for the eager. */
5607 	CONN_INC_REF(connp);
5608 	mutex_enter(&tcp->tcp_eager_lock);
5609 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5610 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5611 	tcp->tcp_eager_next_q0 = eager;
5612 	eager->tcp_eager_prev_q0 = tcp;
5613 
5614 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5615 	eager->tcp_listener = tcp;
5616 	eager->tcp_saved_listener = tcp;
5617 
5618 	/*
5619 	 * Tag this detached tcp vector for later retrieval
5620 	 * by our listener client in tcp_accept().
5621 	 */
5622 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5623 	tcp->tcp_conn_req_cnt_q0++;
5624 	if (++tcp->tcp_conn_req_seqnum == -1) {
5625 		/*
5626 		 * -1 is "special" and defined in TPI as something
5627 		 * that should never be used in T_CONN_IND
5628 		 */
5629 		++tcp->tcp_conn_req_seqnum;
5630 	}
5631 	mutex_exit(&tcp->tcp_eager_lock);
5632 
5633 	if (tcp->tcp_syn_defense) {
5634 		/* Don't drop the SYN that comes from a good IP source */
5635 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5636 		if (addr_cache != NULL && eager->tcp_remote ==
5637 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5638 			eager->tcp_dontdrop = B_TRUE;
5639 		}
5640 	}
5641 
5642 	/*
5643 	 * We need to insert the eager in its own perimeter but as soon
5644 	 * as we do that, we expose the eager to the classifier and
5645 	 * should not touch any field outside the eager's perimeter.
5646 	 * So do all the work necessary before inserting the eager
5647 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5648 	 * will succeed but undo everything if it fails.
5649 	 */
5650 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5651 	eager->tcp_irs = seg_seq;
5652 	eager->tcp_rack = seg_seq;
5653 	eager->tcp_rnxt = seg_seq + 1;
5654 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5655 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5656 	eager->tcp_state = TCPS_SYN_RCVD;
5657 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5658 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5659 	if (mp1 == NULL) {
5660 		/*
5661 		 * Increment the ref count as we are going to
5662 		 * enqueueing an mp in squeue
5663 		 */
5664 		CONN_INC_REF(econnp);
5665 		goto error;
5666 	}
5667 
5668 	/*
5669 	 * Note that in theory this should use the current pid
5670 	 * so that getpeerucred on the client returns the actual listener
5671 	 * that does accept. But accept() hasn't been called yet. We could use
5672 	 * the pid of the process that did bind/listen on the server.
5673 	 * However, with common usage like inetd() the bind/listen can be done
5674 	 * by a different process than the accept().
5675 	 * Hence we do the simple thing of using the open pid here.
5676 	 * Note that db_credp is set later in tcp_send_data().
5677 	 */
5678 	mblk_setcred(mp1, credp, tcp->tcp_cpid);
5679 	eager->tcp_cpid = tcp->tcp_cpid;
5680 	eager->tcp_open_time = lbolt64;
5681 
5682 	/*
5683 	 * We need to start the rto timer. In normal case, we start
5684 	 * the timer after sending the packet on the wire (or at
5685 	 * least believing that packet was sent by waiting for
5686 	 * CALL_IP_WPUT() to return). Since this is the first packet
5687 	 * being sent on the wire for the eager, our initial tcp_rto
5688 	 * is at least tcp_rexmit_interval_min which is a fairly
5689 	 * large value to allow the algorithm to adjust slowly to large
5690 	 * fluctuations of RTT during first few transmissions.
5691 	 *
5692 	 * Starting the timer first and then sending the packet in this
5693 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5694 	 * is of the order of several 100ms and starting the timer
5695 	 * first and then sending the packet will result in difference
5696 	 * of few micro seconds.
5697 	 *
5698 	 * Without this optimization, we are forced to hold the fanout
5699 	 * lock across the ipcl_bind_insert() and sending the packet
5700 	 * so that we don't race against an incoming packet (maybe RST)
5701 	 * for this eager.
5702 	 *
5703 	 * It is necessary to acquire an extra reference on the eager
5704 	 * at this point and hold it until after tcp_send_data() to
5705 	 * ensure against an eager close race.
5706 	 */
5707 
5708 	CONN_INC_REF(eager->tcp_connp);
5709 
5710 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5711 
5712 	/*
5713 	 * Insert the eager in its own perimeter now. We are ready to deal
5714 	 * with any packets on eager.
5715 	 */
5716 	if (eager->tcp_ipversion == IPV4_VERSION) {
5717 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5718 			goto error;
5719 		}
5720 	} else {
5721 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5722 			goto error;
5723 		}
5724 	}
5725 
5726 	/* mark conn as fully-bound */
5727 	econnp->conn_fully_bound = B_TRUE;
5728 
5729 	/* Send the SYN-ACK */
5730 	tcp_send_data(eager, eager->tcp_wq, mp1);
5731 	CONN_DEC_REF(eager->tcp_connp);
5732 	freemsg(mp);
5733 
5734 	return;
5735 error:
5736 	freemsg(mp1);
5737 	eager->tcp_closemp_used = B_TRUE;
5738 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5739 	mp1 = &eager->tcp_closemp;
5740 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5741 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5742 
5743 	/*
5744 	 * If a connection already exists, send the mp to that connections so
5745 	 * that it can be appropriately dealt with.
5746 	 */
5747 	ipst = tcps->tcps_netstack->netstack_ip;
5748 
5749 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5750 		if (!IPCL_IS_CONNECTED(econnp)) {
5751 			/*
5752 			 * Something bad happened. ipcl_conn_insert()
5753 			 * failed because a connection already existed
5754 			 * in connected hash but we can't find it
5755 			 * anymore (someone blew it away). Just
5756 			 * free this message and hopefully remote
5757 			 * will retransmit at which time the SYN can be
5758 			 * treated as a new connection or dealth with
5759 			 * a TH_RST if a connection already exists.
5760 			 */
5761 			CONN_DEC_REF(econnp);
5762 			freemsg(mp);
5763 		} else {
5764 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5765 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5766 		}
5767 	} else {
5768 		/* Nobody wants this packet */
5769 		freemsg(mp);
5770 	}
5771 	return;
5772 error3:
5773 	CONN_DEC_REF(econnp);
5774 error2:
5775 	freemsg(mp);
5776 }
5777 
5778 /*
5779  * In an ideal case of vertical partition in NUMA architecture, its
5780  * beneficial to have the listener and all the incoming connections
5781  * tied to the same squeue. The other constraint is that incoming
5782  * connections should be tied to the squeue attached to interrupted
5783  * CPU for obvious locality reason so this leaves the listener to
5784  * be tied to the same squeue. Our only problem is that when listener
5785  * is binding, the CPU that will get interrupted by the NIC whose
5786  * IP address the listener is binding to is not even known. So
5787  * the code below allows us to change that binding at the time the
5788  * CPU is interrupted by virtue of incoming connection's squeue.
5789  *
5790  * This is usefull only in case of a listener bound to a specific IP
5791  * address. For other kind of listeners, they get bound the
5792  * very first time and there is no attempt to rebind them.
5793  */
5794 void
5795 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5796 {
5797 	conn_t		*connp = (conn_t *)arg;
5798 	squeue_t	*sqp = (squeue_t *)arg2;
5799 	squeue_t	*new_sqp;
5800 	uint32_t	conn_flags;
5801 
5802 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5803 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5804 	} else {
5805 		goto done;
5806 	}
5807 
5808 	if (connp->conn_fanout == NULL)
5809 		goto done;
5810 
5811 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5812 		mutex_enter(&connp->conn_fanout->connf_lock);
5813 		mutex_enter(&connp->conn_lock);
5814 		/*
5815 		 * No one from read or write side can access us now
5816 		 * except for already queued packets on this squeue.
5817 		 * But since we haven't changed the squeue yet, they
5818 		 * can't execute. If they are processed after we have
5819 		 * changed the squeue, they are sent back to the
5820 		 * correct squeue down below.
5821 		 * But a listner close can race with processing of
5822 		 * incoming SYN. If incoming SYN processing changes
5823 		 * the squeue then the listener close which is waiting
5824 		 * to enter the squeue would operate on the wrong
5825 		 * squeue. Hence we don't change the squeue here unless
5826 		 * the refcount is exactly the minimum refcount. The
5827 		 * minimum refcount of 4 is counted as - 1 each for
5828 		 * TCP and IP, 1 for being in the classifier hash, and
5829 		 * 1 for the mblk being processed.
5830 		 */
5831 
5832 		if (connp->conn_ref != 4 ||
5833 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5834 			mutex_exit(&connp->conn_lock);
5835 			mutex_exit(&connp->conn_fanout->connf_lock);
5836 			goto done;
5837 		}
5838 		if (connp->conn_sqp != new_sqp) {
5839 			while (connp->conn_sqp != new_sqp)
5840 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5841 		}
5842 
5843 		do {
5844 			conn_flags = connp->conn_flags;
5845 			conn_flags |= IPCL_FULLY_BOUND;
5846 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5847 			    conn_flags);
5848 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5849 
5850 		mutex_exit(&connp->conn_fanout->connf_lock);
5851 		mutex_exit(&connp->conn_lock);
5852 	}
5853 
5854 done:
5855 	if (connp->conn_sqp != sqp) {
5856 		CONN_INC_REF(connp);
5857 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5858 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5859 	} else {
5860 		tcp_conn_request(connp, mp, sqp);
5861 	}
5862 }
5863 
5864 /*
5865  * Successful connect request processing begins when our client passes
5866  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5867  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5868  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5869  *   upstream <- tcp_rput()		<- IP
5870  * After various error checks are completed, tcp_tpi_connect() lays
5871  * the target address and port into the composite header template,
5872  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5873  * request followed by an IRE request, and passes the three mblk message
5874  * down to IP looking like this:
5875  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5876  * Processing continues in tcp_rput() when we receive the following message:
5877  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5878  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5879  * to fire off the connection request, and then passes the T_OK_ACK mblk
5880  * upstream that we filled in below.  There are, of course, numerous
5881  * error conditions along the way which truncate the processing described
5882  * above.
5883  */
5884 static void
5885 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5886 {
5887 	sin_t		*sin;
5888 	queue_t		*q = tcp->tcp_wq;
5889 	struct T_conn_req	*tcr;
5890 	struct sockaddr	*sa;
5891 	socklen_t	len;
5892 	int		error;
5893 	cred_t		*cr;
5894 	pid_t		cpid;
5895 
5896 	/*
5897 	 * All Solaris components should pass a db_credp
5898 	 * for this TPI message, hence we ASSERT.
5899 	 * But in case there is some other M_PROTO that looks
5900 	 * like a TPI message sent by some other kernel
5901 	 * component, we check and return an error.
5902 	 */
5903 	cr = msg_getcred(mp, &cpid);
5904 	ASSERT(cr != NULL);
5905 	if (cr == NULL) {
5906 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5907 		return;
5908 	}
5909 
5910 	tcr = (struct T_conn_req *)mp->b_rptr;
5911 
5912 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5913 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5914 		tcp_err_ack(tcp, mp, TPROTO, 0);
5915 		return;
5916 	}
5917 
5918 	/*
5919 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5920 	 * will always have that to send up.  Otherwise, we need to do
5921 	 * special handling in case the allocation fails at that time.
5922 	 * If the end point is TPI, the tcp_t can be reused and the
5923 	 * tcp_ordrel_mp may be allocated already.
5924 	 */
5925 	if (tcp->tcp_ordrel_mp == NULL) {
5926 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5927 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5928 			return;
5929 		}
5930 	}
5931 
5932 	/*
5933 	 * Determine packet type based on type of address passed in
5934 	 * the request should contain an IPv4 or IPv6 address.
5935 	 * Make sure that address family matches the type of
5936 	 * family of the the address passed down
5937 	 */
5938 	switch (tcr->DEST_length) {
5939 	default:
5940 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5941 		return;
5942 
5943 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5944 		/*
5945 		 * XXX: The check for valid DEST_length was not there
5946 		 * in earlier releases and some buggy
5947 		 * TLI apps (e.g Sybase) got away with not feeding
5948 		 * in sin_zero part of address.
5949 		 * We allow that bug to keep those buggy apps humming.
5950 		 * Test suites require the check on DEST_length.
5951 		 * We construct a new mblk with valid DEST_length
5952 		 * free the original so the rest of the code does
5953 		 * not have to keep track of this special shorter
5954 		 * length address case.
5955 		 */
5956 		mblk_t *nmp;
5957 		struct T_conn_req *ntcr;
5958 		sin_t *nsin;
5959 
5960 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5961 		    tcr->OPT_length, BPRI_HI);
5962 		if (nmp == NULL) {
5963 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5964 			return;
5965 		}
5966 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5967 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5968 		ntcr->PRIM_type = T_CONN_REQ;
5969 		ntcr->DEST_length = sizeof (sin_t);
5970 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5971 
5972 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5973 		*nsin = sin_null;
5974 		/* Get pointer to shorter address to copy from original mp */
5975 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5976 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5977 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5978 			freemsg(nmp);
5979 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5980 			return;
5981 		}
5982 		nsin->sin_family = sin->sin_family;
5983 		nsin->sin_port = sin->sin_port;
5984 		nsin->sin_addr = sin->sin_addr;
5985 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5986 		nmp->b_wptr = (uchar_t *)&nsin[1];
5987 		if (tcr->OPT_length != 0) {
5988 			ntcr->OPT_length = tcr->OPT_length;
5989 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5990 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5991 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5992 			    tcr->OPT_length);
5993 			nmp->b_wptr += tcr->OPT_length;
5994 		}
5995 		freemsg(mp);	/* original mp freed */
5996 		mp = nmp;	/* re-initialize original variables */
5997 		tcr = ntcr;
5998 	}
5999 	/* FALLTHRU */
6000 
6001 	case sizeof (sin_t):
6002 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6003 		    sizeof (sin_t));
6004 		len = sizeof (sin_t);
6005 		break;
6006 
6007 	case sizeof (sin6_t):
6008 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6009 		    sizeof (sin6_t));
6010 		len = sizeof (sin6_t);
6011 		break;
6012 	}
6013 
6014 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6015 	if (error != 0) {
6016 		tcp_err_ack(tcp, mp, TSYSERR, error);
6017 		return;
6018 	}
6019 
6020 	/*
6021 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6022 	 * should key on their sequence number and cut them loose.
6023 	 */
6024 
6025 	/*
6026 	 * If options passed in, feed it for verification and handling
6027 	 */
6028 	if (tcr->OPT_length != 0) {
6029 		mblk_t	*ok_mp;
6030 		mblk_t	*discon_mp;
6031 		mblk_t  *conn_opts_mp;
6032 		int t_error, sys_error, do_disconnect;
6033 
6034 		conn_opts_mp = NULL;
6035 
6036 		if (tcp_conprim_opt_process(tcp, mp,
6037 		    &do_disconnect, &t_error, &sys_error) < 0) {
6038 			if (do_disconnect) {
6039 				ASSERT(t_error == 0 && sys_error == 0);
6040 				discon_mp = mi_tpi_discon_ind(NULL,
6041 				    ECONNREFUSED, 0);
6042 				if (!discon_mp) {
6043 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6044 					    TSYSERR, ENOMEM);
6045 					return;
6046 				}
6047 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6048 				if (!ok_mp) {
6049 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6050 					    TSYSERR, ENOMEM);
6051 					return;
6052 				}
6053 				qreply(q, ok_mp);
6054 				qreply(q, discon_mp); /* no flush! */
6055 			} else {
6056 				ASSERT(t_error != 0);
6057 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6058 				    sys_error);
6059 			}
6060 			return;
6061 		}
6062 		/*
6063 		 * Success in setting options, the mp option buffer represented
6064 		 * by OPT_length/offset has been potentially modified and
6065 		 * contains results of option processing. We copy it in
6066 		 * another mp to save it for potentially influencing returning
6067 		 * it in T_CONN_CONN.
6068 		 */
6069 		if (tcr->OPT_length != 0) { /* there are resulting options */
6070 			conn_opts_mp = copyb(mp);
6071 			if (!conn_opts_mp) {
6072 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6073 				    TSYSERR, ENOMEM);
6074 				return;
6075 			}
6076 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6077 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6078 			/*
6079 			 * Note:
6080 			 * These resulting option negotiation can include any
6081 			 * end-to-end negotiation options but there no such
6082 			 * thing (yet?) in our TCP/IP.
6083 			 */
6084 		}
6085 	}
6086 
6087 	/* call the non-TPI version */
6088 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
6089 	if (error < 0) {
6090 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6091 	} else if (error > 0) {
6092 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6093 	} else {
6094 		mp = mi_tpi_ok_ack_alloc(mp);
6095 	}
6096 
6097 	/*
6098 	 * Note: Code below is the "failure" case
6099 	 */
6100 	/* return error ack and blow away saved option results if any */
6101 connect_failed:
6102 	if (mp != NULL)
6103 		putnext(tcp->tcp_rq, mp);
6104 	else {
6105 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6106 		    TSYSERR, ENOMEM);
6107 	}
6108 }
6109 
6110 /*
6111  * Handle connect to IPv4 destinations, including connections for AF_INET6
6112  * sockets connecting to IPv4 mapped IPv6 destinations.
6113  */
6114 static int
6115 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6116     uint_t srcid, cred_t *cr, pid_t pid)
6117 {
6118 	tcph_t	*tcph;
6119 	mblk_t	*mp;
6120 	ipaddr_t dstaddr = *dstaddrp;
6121 	int32_t	oldstate;
6122 	uint16_t lport;
6123 	int	error = 0;
6124 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6125 
6126 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6127 
6128 	/* Check for attempt to connect to INADDR_ANY */
6129 	if (dstaddr == INADDR_ANY)  {
6130 		/*
6131 		 * SunOS 4.x and 4.3 BSD allow an application
6132 		 * to connect a TCP socket to INADDR_ANY.
6133 		 * When they do this, the kernel picks the
6134 		 * address of one interface and uses it
6135 		 * instead.  The kernel usually ends up
6136 		 * picking the address of the loopback
6137 		 * interface.  This is an undocumented feature.
6138 		 * However, we provide the same thing here
6139 		 * in order to have source and binary
6140 		 * compatibility with SunOS 4.x.
6141 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6142 		 * generate the T_CONN_CON.
6143 		 */
6144 		dstaddr = htonl(INADDR_LOOPBACK);
6145 		*dstaddrp = dstaddr;
6146 	}
6147 
6148 	/* Handle __sin6_src_id if socket not bound to an IP address */
6149 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6150 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6151 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6152 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6153 		    tcp->tcp_ipha->ipha_src);
6154 	}
6155 
6156 	/*
6157 	 * Don't let an endpoint connect to itself.  Note that
6158 	 * the test here does not catch the case where the
6159 	 * source IP addr was left unspecified by the user. In
6160 	 * this case, the source addr is set in tcp_adapt_ire()
6161 	 * using the reply to the T_BIND message that we send
6162 	 * down to IP here and the check is repeated in tcp_rput_other.
6163 	 */
6164 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6165 	    dstport == tcp->tcp_lport) {
6166 		error = -TBADADDR;
6167 		goto failed;
6168 	}
6169 
6170 	/*
6171 	 * Verify the destination is allowed to receive packets
6172 	 * at the security label of the connection we are initiating.
6173 	 * tsol_check_dest() may create a new effective cred for this
6174 	 * connection with a modified label or label flags.
6175 	 */
6176 	if (is_system_labeled()) {
6177 		ASSERT(tcp->tcp_connp->conn_effective_cred == NULL);
6178 		if ((error = tsol_check_dest(CONN_CRED(tcp->tcp_connp),
6179 		    &dstaddr, IPV4_VERSION, tcp->tcp_connp->conn_mac_exempt,
6180 		    &tcp->tcp_connp->conn_effective_cred)) != 0) {
6181 			if (error != EHOSTUNREACH)
6182 				error = -TSYSERR;
6183 			goto failed;
6184 		}
6185 	}
6186 
6187 	tcp->tcp_ipha->ipha_dst = dstaddr;
6188 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6189 
6190 	/*
6191 	 * Massage a source route if any putting the first hop
6192 	 * in iph_dst. Compute a starting value for the checksum which
6193 	 * takes into account that the original iph_dst should be
6194 	 * included in the checksum but that ip will include the
6195 	 * first hop in the source route in the tcp checksum.
6196 	 */
6197 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6198 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6199 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6200 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6201 	if ((int)tcp->tcp_sum < 0)
6202 		tcp->tcp_sum--;
6203 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6204 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6205 	    (tcp->tcp_sum >> 16));
6206 	tcph = tcp->tcp_tcph;
6207 	*(uint16_t *)tcph->th_fport = dstport;
6208 	tcp->tcp_fport = dstport;
6209 
6210 	oldstate = tcp->tcp_state;
6211 	/*
6212 	 * At this point the remote destination address and remote port fields
6213 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6214 	 * have to see which state tcp was in so we can take apropriate action.
6215 	 */
6216 	if (oldstate == TCPS_IDLE) {
6217 		/*
6218 		 * We support a quick connect capability here, allowing
6219 		 * clients to transition directly from IDLE to SYN_SENT
6220 		 * tcp_bindi will pick an unused port, insert the connection
6221 		 * in the bind hash and transition to BOUND state.
6222 		 */
6223 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6224 		    tcp, B_TRUE);
6225 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6226 		    B_FALSE, B_FALSE);
6227 		if (lport == 0) {
6228 			error = -TNOADDR;
6229 			goto failed;
6230 		}
6231 	}
6232 	tcp->tcp_state = TCPS_SYN_SENT;
6233 
6234 	mp = allocb(sizeof (ire_t), BPRI_HI);
6235 	if (mp == NULL) {
6236 		tcp->tcp_state = oldstate;
6237 		error = ENOMEM;
6238 		goto failed;
6239 	}
6240 
6241 	mp->b_wptr += sizeof (ire_t);
6242 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6243 	tcp->tcp_hard_binding = 1;
6244 
6245 	/*
6246 	 * We need to make sure that the conn_recv is set to a non-null
6247 	 * value before we insert the conn_t into the classifier table.
6248 	 * This is to avoid a race with an incoming packet which does
6249 	 * an ipcl_classify().
6250 	 */
6251 	tcp->tcp_connp->conn_recv = tcp_input;
6252 
6253 	if (tcp->tcp_family == AF_INET) {
6254 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6255 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6256 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6257 	} else {
6258 		in6_addr_t v6src;
6259 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6260 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6261 		} else {
6262 			v6src = tcp->tcp_ip6h->ip6_src;
6263 		}
6264 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6265 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6266 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6267 	}
6268 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6269 	tcp->tcp_active_open = 1;
6270 
6271 
6272 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6273 failed:
6274 	/* return error ack and blow away saved option results if any */
6275 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6276 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6277 	return (error);
6278 }
6279 
6280 /*
6281  * Handle connect to IPv6 destinations.
6282  */
6283 static int
6284 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6285     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6286 {
6287 	tcph_t	*tcph;
6288 	mblk_t	*mp;
6289 	ip6_rthdr_t *rth;
6290 	int32_t  oldstate;
6291 	uint16_t lport;
6292 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6293 	int	error = 0;
6294 	conn_t	*connp = tcp->tcp_connp;
6295 
6296 	ASSERT(tcp->tcp_family == AF_INET6);
6297 
6298 	/*
6299 	 * If we're here, it means that the destination address is a native
6300 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6301 	 * reason why it might not be IPv6 is if the socket was bound to an
6302 	 * IPv4-mapped IPv6 address.
6303 	 */
6304 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6305 		return (-TBADADDR);
6306 	}
6307 
6308 	/*
6309 	 * Interpret a zero destination to mean loopback.
6310 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6311 	 * generate the T_CONN_CON.
6312 	 */
6313 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6314 		*dstaddrp = ipv6_loopback;
6315 	}
6316 
6317 	/* Handle __sin6_src_id if socket not bound to an IP address */
6318 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6319 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6320 		    connp->conn_zoneid, tcps->tcps_netstack);
6321 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6322 	}
6323 
6324 	/*
6325 	 * Take care of the scope_id now and add ip6i_t
6326 	 * if ip6i_t is not already allocated through TCP
6327 	 * sticky options. At this point tcp_ip6h does not
6328 	 * have dst info, thus use dstaddrp.
6329 	 */
6330 	if (scope_id != 0 &&
6331 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6332 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6333 		ip6i_t  *ip6i;
6334 
6335 		ipp->ipp_ifindex = scope_id;
6336 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6337 
6338 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6339 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6340 			/* Already allocated */
6341 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6342 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6343 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6344 		} else {
6345 			int reterr;
6346 
6347 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6348 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6349 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6350 			reterr = tcp_build_hdrs(tcp);
6351 			if (reterr != 0)
6352 				goto failed;
6353 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6354 		}
6355 	}
6356 
6357 	/*
6358 	 * Don't let an endpoint connect to itself.  Note that
6359 	 * the test here does not catch the case where the
6360 	 * source IP addr was left unspecified by the user. In
6361 	 * this case, the source addr is set in tcp_adapt_ire()
6362 	 * using the reply to the T_BIND message that we send
6363 	 * down to IP here and the check is repeated in tcp_rput_other.
6364 	 */
6365 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6366 	    (dstport == tcp->tcp_lport)) {
6367 		error = -TBADADDR;
6368 		goto failed;
6369 	}
6370 
6371 	/*
6372 	 * Verify the destination is allowed to receive packets
6373 	 * at the security label of the connection we are initiating.
6374 	 * check_dest may create a new effective cred for this
6375 	 * connection with a modified label or label flags.
6376 	 */
6377 	if (is_system_labeled()) {
6378 		ASSERT(tcp->tcp_connp->conn_effective_cred == NULL);
6379 		if ((error = tsol_check_dest(CONN_CRED(tcp->tcp_connp),
6380 		    dstaddrp, IPV6_VERSION, tcp->tcp_connp->conn_mac_exempt,
6381 		    &tcp->tcp_connp->conn_effective_cred)) != 0) {
6382 			if (error != EHOSTUNREACH)
6383 				error = -TSYSERR;
6384 			goto failed;
6385 		}
6386 	}
6387 
6388 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6389 	tcp->tcp_remote_v6 = *dstaddrp;
6390 	tcp->tcp_ip6h->ip6_vcf =
6391 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6392 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6393 
6394 	/*
6395 	 * Massage a routing header (if present) putting the first hop
6396 	 * in ip6_dst. Compute a starting value for the checksum which
6397 	 * takes into account that the original ip6_dst should be
6398 	 * included in the checksum but that ip will include the
6399 	 * first hop in the source route in the tcp checksum.
6400 	 */
6401 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6402 	if (rth != NULL) {
6403 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6404 		    tcps->tcps_netstack);
6405 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6406 		    (tcp->tcp_sum >> 16));
6407 	} else {
6408 		tcp->tcp_sum = 0;
6409 	}
6410 
6411 	tcph = tcp->tcp_tcph;
6412 	*(uint16_t *)tcph->th_fport = dstport;
6413 	tcp->tcp_fport = dstport;
6414 
6415 	oldstate = tcp->tcp_state;
6416 	/*
6417 	 * At this point the remote destination address and remote port fields
6418 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6419 	 * have to see which state tcp was in so we can take apropriate action.
6420 	 */
6421 	if (oldstate == TCPS_IDLE) {
6422 		/*
6423 		 * We support a quick connect capability here, allowing
6424 		 * clients to transition directly from IDLE to SYN_SENT
6425 		 * tcp_bindi will pick an unused port, insert the connection
6426 		 * in the bind hash and transition to BOUND state.
6427 		 */
6428 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6429 		    tcp, B_TRUE);
6430 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6431 		    B_FALSE, B_FALSE);
6432 		if (lport == 0) {
6433 			error = -TNOADDR;
6434 			goto failed;
6435 		}
6436 	}
6437 	tcp->tcp_state = TCPS_SYN_SENT;
6438 
6439 	mp = allocb(sizeof (ire_t), BPRI_HI);
6440 	if (mp != NULL) {
6441 		in6_addr_t v6src;
6442 
6443 		mp->b_wptr += sizeof (ire_t);
6444 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6445 
6446 		tcp->tcp_hard_binding = 1;
6447 
6448 		/*
6449 		 * We need to make sure that the conn_recv is set to a non-null
6450 		 * value before we insert the conn_t into the classifier table.
6451 		 * This is to avoid a race with an incoming packet which does
6452 		 * an ipcl_classify().
6453 		 */
6454 		tcp->tcp_connp->conn_recv = tcp_input;
6455 
6456 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6457 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6458 		} else {
6459 			v6src = tcp->tcp_ip6h->ip6_src;
6460 		}
6461 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6462 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6463 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6464 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6465 		tcp->tcp_active_open = 1;
6466 
6467 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6468 	}
6469 	/* Error case */
6470 	tcp->tcp_state = oldstate;
6471 	error = ENOMEM;
6472 
6473 failed:
6474 	/* return error ack and blow away saved option results if any */
6475 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6476 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6477 	return (error);
6478 }
6479 
6480 /*
6481  * We need a stream q for detached closing tcp connections
6482  * to use.  Our client hereby indicates that this q is the
6483  * one to use.
6484  */
6485 static void
6486 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6487 {
6488 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6489 	queue_t	*q = tcp->tcp_wq;
6490 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6491 
6492 #ifdef NS_DEBUG
6493 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6494 	    tcps->tcps_netstack->netstack_stackid);
6495 #endif
6496 	mp->b_datap->db_type = M_IOCACK;
6497 	iocp->ioc_count = 0;
6498 	mutex_enter(&tcps->tcps_g_q_lock);
6499 	if (tcps->tcps_g_q != NULL) {
6500 		mutex_exit(&tcps->tcps_g_q_lock);
6501 		iocp->ioc_error = EALREADY;
6502 	} else {
6503 		int error = 0;
6504 		conn_t *connp = tcp->tcp_connp;
6505 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6506 
6507 		tcps->tcps_g_q = tcp->tcp_rq;
6508 		mutex_exit(&tcps->tcps_g_q_lock);
6509 		iocp->ioc_error = 0;
6510 		iocp->ioc_rval = 0;
6511 		/*
6512 		 * We are passing tcp_sticky_ipp as NULL
6513 		 * as it is not useful for tcp_default queue
6514 		 *
6515 		 * Set conn_recv just in case.
6516 		 */
6517 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6518 
6519 		ASSERT(connp->conn_af_isv6);
6520 		connp->conn_ulp = IPPROTO_TCP;
6521 
6522 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6523 		    NULL || connp->conn_mac_exempt) {
6524 			error = -TBADADDR;
6525 		} else {
6526 			connp->conn_srcv6 = ipv6_all_zeros;
6527 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6528 		}
6529 
6530 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6531 	}
6532 	qreply(q, mp);
6533 }
6534 
6535 static int
6536 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6537 {
6538 	tcp_t	*ltcp = NULL;
6539 	conn_t	*connp;
6540 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6541 
6542 	/*
6543 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6544 	 * when the stream is in BOUND state. Do not send a reset,
6545 	 * since the destination IP address is not valid, and it can
6546 	 * be the initialized value of all zeros (broadcast address).
6547 	 *
6548 	 * XXX There won't be any pending bind request to IP.
6549 	 */
6550 	if (tcp->tcp_state <= TCPS_BOUND) {
6551 		if (tcp->tcp_debug) {
6552 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6553 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6554 		}
6555 		return (TOUTSTATE);
6556 	}
6557 
6558 
6559 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6560 
6561 		/*
6562 		 * According to TPI, for non-listeners, ignore seqnum
6563 		 * and disconnect.
6564 		 * Following interpretation of -1 seqnum is historical
6565 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6566 		 * a valid seqnum should not be -1).
6567 		 *
6568 		 *	-1 means disconnect everything
6569 		 *	regardless even on a listener.
6570 		 */
6571 
6572 		int old_state = tcp->tcp_state;
6573 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6574 
6575 		/*
6576 		 * The connection can't be on the tcp_time_wait_head list
6577 		 * since it is not detached.
6578 		 */
6579 		ASSERT(tcp->tcp_time_wait_next == NULL);
6580 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6581 		ASSERT(tcp->tcp_time_wait_expire == 0);
6582 		ltcp = NULL;
6583 		/*
6584 		 * If it used to be a listener, check to make sure no one else
6585 		 * has taken the port before switching back to LISTEN state.
6586 		 */
6587 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6588 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6589 			    tcp->tcp_ipha->ipha_src,
6590 			    tcp->tcp_connp->conn_zoneid, ipst);
6591 			if (connp != NULL)
6592 				ltcp = connp->conn_tcp;
6593 		} else {
6594 			/* Allow tcp_bound_if listeners? */
6595 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6596 			    &tcp->tcp_ip6h->ip6_src, 0,
6597 			    tcp->tcp_connp->conn_zoneid, ipst);
6598 			if (connp != NULL)
6599 				ltcp = connp->conn_tcp;
6600 		}
6601 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6602 			tcp->tcp_state = TCPS_LISTEN;
6603 		} else if (old_state > TCPS_BOUND) {
6604 			tcp->tcp_conn_req_max = 0;
6605 			tcp->tcp_state = TCPS_BOUND;
6606 		}
6607 		if (ltcp != NULL)
6608 			CONN_DEC_REF(ltcp->tcp_connp);
6609 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6610 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6611 		} else if (old_state == TCPS_ESTABLISHED ||
6612 		    old_state == TCPS_CLOSE_WAIT) {
6613 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6614 		}
6615 
6616 		if (tcp->tcp_fused)
6617 			tcp_unfuse(tcp);
6618 
6619 		mutex_enter(&tcp->tcp_eager_lock);
6620 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6621 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6622 			tcp_eager_cleanup(tcp, 0);
6623 		}
6624 		mutex_exit(&tcp->tcp_eager_lock);
6625 
6626 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6627 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6628 
6629 		tcp_reinit(tcp);
6630 
6631 		return (0);
6632 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6633 		return (TBADSEQ);
6634 	}
6635 	return (0);
6636 }
6637 
6638 /*
6639  * Our client hereby directs us to reject the connection request
6640  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6641  * of sending the appropriate RST, not an ICMP error.
6642  */
6643 static void
6644 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6645 {
6646 	t_scalar_t seqnum;
6647 	int	error;
6648 
6649 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6650 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6651 		tcp_err_ack(tcp, mp, TPROTO, 0);
6652 		return;
6653 	}
6654 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6655 	error = tcp_disconnect_common(tcp, seqnum);
6656 	if (error != 0)
6657 		tcp_err_ack(tcp, mp, error, 0);
6658 	else {
6659 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6660 			/* Send M_FLUSH according to TPI */
6661 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6662 		}
6663 		mp = mi_tpi_ok_ack_alloc(mp);
6664 		if (mp)
6665 			putnext(tcp->tcp_rq, mp);
6666 	}
6667 }
6668 
6669 /*
6670  * Diagnostic routine used to return a string associated with the tcp state.
6671  * Note that if the caller does not supply a buffer, it will use an internal
6672  * static string.  This means that if multiple threads call this function at
6673  * the same time, output can be corrupted...  Note also that this function
6674  * does not check the size of the supplied buffer.  The caller has to make
6675  * sure that it is big enough.
6676  */
6677 static char *
6678 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6679 {
6680 	char		buf1[30];
6681 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6682 	char		*buf;
6683 	char		*cp;
6684 	in6_addr_t	local, remote;
6685 	char		local_addrbuf[INET6_ADDRSTRLEN];
6686 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6687 
6688 	if (sup_buf != NULL)
6689 		buf = sup_buf;
6690 	else
6691 		buf = priv_buf;
6692 
6693 	if (tcp == NULL)
6694 		return ("NULL_TCP");
6695 	switch (tcp->tcp_state) {
6696 	case TCPS_CLOSED:
6697 		cp = "TCP_CLOSED";
6698 		break;
6699 	case TCPS_IDLE:
6700 		cp = "TCP_IDLE";
6701 		break;
6702 	case TCPS_BOUND:
6703 		cp = "TCP_BOUND";
6704 		break;
6705 	case TCPS_LISTEN:
6706 		cp = "TCP_LISTEN";
6707 		break;
6708 	case TCPS_SYN_SENT:
6709 		cp = "TCP_SYN_SENT";
6710 		break;
6711 	case TCPS_SYN_RCVD:
6712 		cp = "TCP_SYN_RCVD";
6713 		break;
6714 	case TCPS_ESTABLISHED:
6715 		cp = "TCP_ESTABLISHED";
6716 		break;
6717 	case TCPS_CLOSE_WAIT:
6718 		cp = "TCP_CLOSE_WAIT";
6719 		break;
6720 	case TCPS_FIN_WAIT_1:
6721 		cp = "TCP_FIN_WAIT_1";
6722 		break;
6723 	case TCPS_CLOSING:
6724 		cp = "TCP_CLOSING";
6725 		break;
6726 	case TCPS_LAST_ACK:
6727 		cp = "TCP_LAST_ACK";
6728 		break;
6729 	case TCPS_FIN_WAIT_2:
6730 		cp = "TCP_FIN_WAIT_2";
6731 		break;
6732 	case TCPS_TIME_WAIT:
6733 		cp = "TCP_TIME_WAIT";
6734 		break;
6735 	default:
6736 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6737 		cp = buf1;
6738 		break;
6739 	}
6740 	switch (format) {
6741 	case DISP_ADDR_AND_PORT:
6742 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6743 			/*
6744 			 * Note that we use the remote address in the tcp_b
6745 			 * structure.  This means that it will print out
6746 			 * the real destination address, not the next hop's
6747 			 * address if source routing is used.
6748 			 */
6749 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6750 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6751 
6752 		} else {
6753 			local = tcp->tcp_ip_src_v6;
6754 			remote = tcp->tcp_remote_v6;
6755 		}
6756 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6757 		    sizeof (local_addrbuf));
6758 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6759 		    sizeof (remote_addrbuf));
6760 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6761 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6762 		    ntohs(tcp->tcp_fport), cp);
6763 		break;
6764 	case DISP_PORT_ONLY:
6765 	default:
6766 		(void) mi_sprintf(buf, "[%u, %u] %s",
6767 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6768 		break;
6769 	}
6770 
6771 	return (buf);
6772 }
6773 
6774 /*
6775  * Called via squeue to get on to eager's perimeter. It sends a
6776  * TH_RST if eager is in the fanout table. The listener wants the
6777  * eager to disappear either by means of tcp_eager_blowoff() or
6778  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6779  * called (via squeue) if the eager cannot be inserted in the
6780  * fanout table in tcp_conn_request().
6781  */
6782 /* ARGSUSED */
6783 void
6784 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6785 {
6786 	conn_t	*econnp = (conn_t *)arg;
6787 	tcp_t	*eager = econnp->conn_tcp;
6788 	tcp_t	*listener = eager->tcp_listener;
6789 	tcp_stack_t	*tcps = eager->tcp_tcps;
6790 
6791 	/*
6792 	 * We could be called because listener is closing. Since
6793 	 * the eager is using listener's queue's, its not safe.
6794 	 * Better use the default queue just to send the TH_RST
6795 	 * out.
6796 	 */
6797 	ASSERT(tcps->tcps_g_q != NULL);
6798 	eager->tcp_rq = tcps->tcps_g_q;
6799 	eager->tcp_wq = WR(tcps->tcps_g_q);
6800 
6801 	/*
6802 	 * An eager's conn_fanout will be NULL if it's a duplicate
6803 	 * for an existing 4-tuples in the conn fanout table.
6804 	 * We don't want to send an RST out in such case.
6805 	 */
6806 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6807 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6808 		    eager, eager->tcp_snxt, 0, TH_RST);
6809 	}
6810 
6811 	/* We are here because listener wants this eager gone */
6812 	if (listener != NULL) {
6813 		mutex_enter(&listener->tcp_eager_lock);
6814 		tcp_eager_unlink(eager);
6815 		if (eager->tcp_tconnind_started) {
6816 			/*
6817 			 * The eager has sent a conn_ind up to the
6818 			 * listener but listener decides to close
6819 			 * instead. We need to drop the extra ref
6820 			 * placed on eager in tcp_rput_data() before
6821 			 * sending the conn_ind to listener.
6822 			 */
6823 			CONN_DEC_REF(econnp);
6824 		}
6825 		mutex_exit(&listener->tcp_eager_lock);
6826 		CONN_DEC_REF(listener->tcp_connp);
6827 	}
6828 
6829 	if (eager->tcp_state > TCPS_BOUND)
6830 		tcp_close_detached(eager);
6831 }
6832 
6833 /*
6834  * Reset any eager connection hanging off this listener marked
6835  * with 'seqnum' and then reclaim it's resources.
6836  */
6837 static boolean_t
6838 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6839 {
6840 	tcp_t	*eager;
6841 	mblk_t 	*mp;
6842 	tcp_stack_t	*tcps = listener->tcp_tcps;
6843 
6844 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6845 	eager = listener;
6846 	mutex_enter(&listener->tcp_eager_lock);
6847 	do {
6848 		eager = eager->tcp_eager_next_q;
6849 		if (eager == NULL) {
6850 			mutex_exit(&listener->tcp_eager_lock);
6851 			return (B_FALSE);
6852 		}
6853 	} while (eager->tcp_conn_req_seqnum != seqnum);
6854 
6855 	if (eager->tcp_closemp_used) {
6856 		mutex_exit(&listener->tcp_eager_lock);
6857 		return (B_TRUE);
6858 	}
6859 	eager->tcp_closemp_used = B_TRUE;
6860 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6861 	CONN_INC_REF(eager->tcp_connp);
6862 	mutex_exit(&listener->tcp_eager_lock);
6863 	mp = &eager->tcp_closemp;
6864 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6865 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6866 	return (B_TRUE);
6867 }
6868 
6869 /*
6870  * Reset any eager connection hanging off this listener
6871  * and then reclaim it's resources.
6872  */
6873 static void
6874 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6875 {
6876 	tcp_t	*eager;
6877 	mblk_t	*mp;
6878 	tcp_stack_t	*tcps = listener->tcp_tcps;
6879 
6880 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6881 
6882 	if (!q0_only) {
6883 		/* First cleanup q */
6884 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6885 		eager = listener->tcp_eager_next_q;
6886 		while (eager != NULL) {
6887 			if (!eager->tcp_closemp_used) {
6888 				eager->tcp_closemp_used = B_TRUE;
6889 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6890 				CONN_INC_REF(eager->tcp_connp);
6891 				mp = &eager->tcp_closemp;
6892 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6893 				    tcp_eager_kill, eager->tcp_connp,
6894 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6895 			}
6896 			eager = eager->tcp_eager_next_q;
6897 		}
6898 	}
6899 	/* Then cleanup q0 */
6900 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6901 	eager = listener->tcp_eager_next_q0;
6902 	while (eager != listener) {
6903 		if (!eager->tcp_closemp_used) {
6904 			eager->tcp_closemp_used = B_TRUE;
6905 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6906 			CONN_INC_REF(eager->tcp_connp);
6907 			mp = &eager->tcp_closemp;
6908 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6909 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6910 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6911 		}
6912 		eager = eager->tcp_eager_next_q0;
6913 	}
6914 }
6915 
6916 /*
6917  * If we are an eager connection hanging off a listener that hasn't
6918  * formally accepted the connection yet, get off his list and blow off
6919  * any data that we have accumulated.
6920  */
6921 static void
6922 tcp_eager_unlink(tcp_t *tcp)
6923 {
6924 	tcp_t	*listener = tcp->tcp_listener;
6925 
6926 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6927 	ASSERT(listener != NULL);
6928 	if (tcp->tcp_eager_next_q0 != NULL) {
6929 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6930 
6931 		/* Remove the eager tcp from q0 */
6932 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6933 		    tcp->tcp_eager_prev_q0;
6934 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6935 		    tcp->tcp_eager_next_q0;
6936 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6937 		listener->tcp_conn_req_cnt_q0--;
6938 
6939 		tcp->tcp_eager_next_q0 = NULL;
6940 		tcp->tcp_eager_prev_q0 = NULL;
6941 
6942 		/*
6943 		 * Take the eager out, if it is in the list of droppable
6944 		 * eagers.
6945 		 */
6946 		MAKE_UNDROPPABLE(tcp);
6947 
6948 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6949 			/* we have timed out before */
6950 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6951 			listener->tcp_syn_rcvd_timeout--;
6952 		}
6953 	} else {
6954 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6955 		tcp_t	*prev = NULL;
6956 
6957 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6958 			if (tcpp[0] == tcp) {
6959 				if (listener->tcp_eager_last_q == tcp) {
6960 					/*
6961 					 * If we are unlinking the last
6962 					 * element on the list, adjust
6963 					 * tail pointer. Set tail pointer
6964 					 * to nil when list is empty.
6965 					 */
6966 					ASSERT(tcp->tcp_eager_next_q == NULL);
6967 					if (listener->tcp_eager_last_q ==
6968 					    listener->tcp_eager_next_q) {
6969 						listener->tcp_eager_last_q =
6970 						    NULL;
6971 					} else {
6972 						/*
6973 						 * We won't get here if there
6974 						 * is only one eager in the
6975 						 * list.
6976 						 */
6977 						ASSERT(prev != NULL);
6978 						listener->tcp_eager_last_q =
6979 						    prev;
6980 					}
6981 				}
6982 				tcpp[0] = tcp->tcp_eager_next_q;
6983 				tcp->tcp_eager_next_q = NULL;
6984 				tcp->tcp_eager_last_q = NULL;
6985 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6986 				listener->tcp_conn_req_cnt_q--;
6987 				break;
6988 			}
6989 			prev = tcpp[0];
6990 		}
6991 	}
6992 	tcp->tcp_listener = NULL;
6993 }
6994 
6995 /* Shorthand to generate and send TPI error acks to our client */
6996 static void
6997 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6998 {
6999 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7000 		putnext(tcp->tcp_rq, mp);
7001 }
7002 
7003 /* Shorthand to generate and send TPI error acks to our client */
7004 static void
7005 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7006     int t_error, int sys_error)
7007 {
7008 	struct T_error_ack	*teackp;
7009 
7010 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7011 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7012 		teackp = (struct T_error_ack *)mp->b_rptr;
7013 		teackp->ERROR_prim = primitive;
7014 		teackp->TLI_error = t_error;
7015 		teackp->UNIX_error = sys_error;
7016 		putnext(tcp->tcp_rq, mp);
7017 	}
7018 }
7019 
7020 /*
7021  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7022  * but instead the code relies on:
7023  * - the fact that the address of the array and its size never changes
7024  * - the atomic assignment of the elements of the array
7025  */
7026 /* ARGSUSED */
7027 static int
7028 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7029 {
7030 	int i;
7031 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7032 
7033 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7034 		if (tcps->tcps_g_epriv_ports[i] != 0)
7035 			(void) mi_mpprintf(mp, "%d ",
7036 			    tcps->tcps_g_epriv_ports[i]);
7037 	}
7038 	return (0);
7039 }
7040 
7041 /*
7042  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7043  * threads from changing it at the same time.
7044  */
7045 /* ARGSUSED */
7046 static int
7047 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7048     cred_t *cr)
7049 {
7050 	long	new_value;
7051 	int	i;
7052 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7053 
7054 	/*
7055 	 * Fail the request if the new value does not lie within the
7056 	 * port number limits.
7057 	 */
7058 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7059 	    new_value <= 0 || new_value >= 65536) {
7060 		return (EINVAL);
7061 	}
7062 
7063 	mutex_enter(&tcps->tcps_epriv_port_lock);
7064 	/* Check if the value is already in the list */
7065 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7066 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7067 			mutex_exit(&tcps->tcps_epriv_port_lock);
7068 			return (EEXIST);
7069 		}
7070 	}
7071 	/* Find an empty slot */
7072 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7073 		if (tcps->tcps_g_epriv_ports[i] == 0)
7074 			break;
7075 	}
7076 	if (i == tcps->tcps_g_num_epriv_ports) {
7077 		mutex_exit(&tcps->tcps_epriv_port_lock);
7078 		return (EOVERFLOW);
7079 	}
7080 	/* Set the new value */
7081 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7082 	mutex_exit(&tcps->tcps_epriv_port_lock);
7083 	return (0);
7084 }
7085 
7086 /*
7087  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7088  * threads from changing it at the same time.
7089  */
7090 /* ARGSUSED */
7091 static int
7092 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7093     cred_t *cr)
7094 {
7095 	long	new_value;
7096 	int	i;
7097 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7098 
7099 	/*
7100 	 * Fail the request if the new value does not lie within the
7101 	 * port number limits.
7102 	 */
7103 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7104 	    new_value >= 65536) {
7105 		return (EINVAL);
7106 	}
7107 
7108 	mutex_enter(&tcps->tcps_epriv_port_lock);
7109 	/* Check that the value is already in the list */
7110 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7111 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7112 			break;
7113 	}
7114 	if (i == tcps->tcps_g_num_epriv_ports) {
7115 		mutex_exit(&tcps->tcps_epriv_port_lock);
7116 		return (ESRCH);
7117 	}
7118 	/* Clear the value */
7119 	tcps->tcps_g_epriv_ports[i] = 0;
7120 	mutex_exit(&tcps->tcps_epriv_port_lock);
7121 	return (0);
7122 }
7123 
7124 /* Return the TPI/TLI equivalent of our current tcp_state */
7125 static int
7126 tcp_tpistate(tcp_t *tcp)
7127 {
7128 	switch (tcp->tcp_state) {
7129 	case TCPS_IDLE:
7130 		return (TS_UNBND);
7131 	case TCPS_LISTEN:
7132 		/*
7133 		 * Return whether there are outstanding T_CONN_IND waiting
7134 		 * for the matching T_CONN_RES. Therefore don't count q0.
7135 		 */
7136 		if (tcp->tcp_conn_req_cnt_q > 0)
7137 			return (TS_WRES_CIND);
7138 		else
7139 			return (TS_IDLE);
7140 	case TCPS_BOUND:
7141 		return (TS_IDLE);
7142 	case TCPS_SYN_SENT:
7143 		return (TS_WCON_CREQ);
7144 	case TCPS_SYN_RCVD:
7145 		/*
7146 		 * Note: assumption: this has to the active open SYN_RCVD.
7147 		 * The passive instance is detached in SYN_RCVD stage of
7148 		 * incoming connection processing so we cannot get request
7149 		 * for T_info_ack on it.
7150 		 */
7151 		return (TS_WACK_CRES);
7152 	case TCPS_ESTABLISHED:
7153 		return (TS_DATA_XFER);
7154 	case TCPS_CLOSE_WAIT:
7155 		return (TS_WREQ_ORDREL);
7156 	case TCPS_FIN_WAIT_1:
7157 		return (TS_WIND_ORDREL);
7158 	case TCPS_FIN_WAIT_2:
7159 		return (TS_WIND_ORDREL);
7160 
7161 	case TCPS_CLOSING:
7162 	case TCPS_LAST_ACK:
7163 	case TCPS_TIME_WAIT:
7164 	case TCPS_CLOSED:
7165 		/*
7166 		 * Following TS_WACK_DREQ7 is a rendition of "not
7167 		 * yet TS_IDLE" TPI state. There is no best match to any
7168 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7169 		 * choose a value chosen that will map to TLI/XTI level
7170 		 * state of TSTATECHNG (state is process of changing) which
7171 		 * captures what this dummy state represents.
7172 		 */
7173 		return (TS_WACK_DREQ7);
7174 	default:
7175 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7176 		    tcp->tcp_state, tcp_display(tcp, NULL,
7177 		    DISP_PORT_ONLY));
7178 		return (TS_UNBND);
7179 	}
7180 }
7181 
7182 static void
7183 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7184 {
7185 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7186 
7187 	if (tcp->tcp_family == AF_INET6)
7188 		*tia = tcp_g_t_info_ack_v6;
7189 	else
7190 		*tia = tcp_g_t_info_ack;
7191 	tia->CURRENT_state = tcp_tpistate(tcp);
7192 	tia->OPT_size = tcp_max_optsize;
7193 	if (tcp->tcp_mss == 0) {
7194 		/* Not yet set - tcp_open does not set mss */
7195 		if (tcp->tcp_ipversion == IPV4_VERSION)
7196 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7197 		else
7198 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7199 	} else {
7200 		tia->TIDU_size = tcp->tcp_mss;
7201 	}
7202 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7203 }
7204 
7205 static void
7206 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7207     t_uscalar_t cap_bits1)
7208 {
7209 	tcap->CAP_bits1 = 0;
7210 
7211 	if (cap_bits1 & TC1_INFO) {
7212 		tcp_copy_info(&tcap->INFO_ack, tcp);
7213 		tcap->CAP_bits1 |= TC1_INFO;
7214 	}
7215 
7216 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7217 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7218 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7219 	}
7220 
7221 }
7222 
7223 /*
7224  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7225  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7226  * tcp_g_t_info_ack.  The current state of the stream is copied from
7227  * tcp_state.
7228  */
7229 static void
7230 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7231 {
7232 	t_uscalar_t		cap_bits1;
7233 	struct T_capability_ack	*tcap;
7234 
7235 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7236 		freemsg(mp);
7237 		return;
7238 	}
7239 
7240 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7241 
7242 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7243 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7244 	if (mp == NULL)
7245 		return;
7246 
7247 	tcap = (struct T_capability_ack *)mp->b_rptr;
7248 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7249 
7250 	putnext(tcp->tcp_rq, mp);
7251 }
7252 
7253 /*
7254  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7255  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7256  * The current state of the stream is copied from tcp_state.
7257  */
7258 static void
7259 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7260 {
7261 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7262 	    T_INFO_ACK);
7263 	if (!mp) {
7264 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7265 		return;
7266 	}
7267 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7268 	putnext(tcp->tcp_rq, mp);
7269 }
7270 
7271 /* Respond to the TPI addr request */
7272 static void
7273 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7274 {
7275 	sin_t	*sin;
7276 	mblk_t	*ackmp;
7277 	struct T_addr_ack *taa;
7278 
7279 	/* Make it large enough for worst case */
7280 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7281 	    2 * sizeof (sin6_t), 1);
7282 	if (ackmp == NULL) {
7283 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7284 		return;
7285 	}
7286 
7287 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7288 		tcp_addr_req_ipv6(tcp, ackmp);
7289 		return;
7290 	}
7291 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7292 
7293 	bzero(taa, sizeof (struct T_addr_ack));
7294 	ackmp->b_wptr = (uchar_t *)&taa[1];
7295 
7296 	taa->PRIM_type = T_ADDR_ACK;
7297 	ackmp->b_datap->db_type = M_PCPROTO;
7298 
7299 	/*
7300 	 * Note: Following code assumes 32 bit alignment of basic
7301 	 * data structures like sin_t and struct T_addr_ack.
7302 	 */
7303 	if (tcp->tcp_state >= TCPS_BOUND) {
7304 		/*
7305 		 * Fill in local address
7306 		 */
7307 		taa->LOCADDR_length = sizeof (sin_t);
7308 		taa->LOCADDR_offset = sizeof (*taa);
7309 
7310 		sin = (sin_t *)&taa[1];
7311 
7312 		/* Fill zeroes and then intialize non-zero fields */
7313 		*sin = sin_null;
7314 
7315 		sin->sin_family = AF_INET;
7316 
7317 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7318 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7319 
7320 		ackmp->b_wptr = (uchar_t *)&sin[1];
7321 
7322 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7323 			/*
7324 			 * Fill in Remote address
7325 			 */
7326 			taa->REMADDR_length = sizeof (sin_t);
7327 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7328 			    taa->LOCADDR_length);
7329 
7330 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7331 			*sin = sin_null;
7332 			sin->sin_family = AF_INET;
7333 			sin->sin_addr.s_addr = tcp->tcp_remote;
7334 			sin->sin_port = tcp->tcp_fport;
7335 
7336 			ackmp->b_wptr = (uchar_t *)&sin[1];
7337 		}
7338 	}
7339 	putnext(tcp->tcp_rq, ackmp);
7340 }
7341 
7342 /* Assumes that tcp_addr_req gets enough space and alignment */
7343 static void
7344 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7345 {
7346 	sin6_t	*sin6;
7347 	struct T_addr_ack *taa;
7348 
7349 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7350 	ASSERT(OK_32PTR(ackmp->b_rptr));
7351 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7352 	    2 * sizeof (sin6_t));
7353 
7354 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7355 
7356 	bzero(taa, sizeof (struct T_addr_ack));
7357 	ackmp->b_wptr = (uchar_t *)&taa[1];
7358 
7359 	taa->PRIM_type = T_ADDR_ACK;
7360 	ackmp->b_datap->db_type = M_PCPROTO;
7361 
7362 	/*
7363 	 * Note: Following code assumes 32 bit alignment of basic
7364 	 * data structures like sin6_t and struct T_addr_ack.
7365 	 */
7366 	if (tcp->tcp_state >= TCPS_BOUND) {
7367 		/*
7368 		 * Fill in local address
7369 		 */
7370 		taa->LOCADDR_length = sizeof (sin6_t);
7371 		taa->LOCADDR_offset = sizeof (*taa);
7372 
7373 		sin6 = (sin6_t *)&taa[1];
7374 		*sin6 = sin6_null;
7375 
7376 		sin6->sin6_family = AF_INET6;
7377 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7378 		sin6->sin6_port = tcp->tcp_lport;
7379 
7380 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7381 
7382 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7383 			/*
7384 			 * Fill in Remote address
7385 			 */
7386 			taa->REMADDR_length = sizeof (sin6_t);
7387 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7388 			    taa->LOCADDR_length);
7389 
7390 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7391 			*sin6 = sin6_null;
7392 			sin6->sin6_family = AF_INET6;
7393 			sin6->sin6_flowinfo =
7394 			    tcp->tcp_ip6h->ip6_vcf &
7395 			    ~IPV6_VERS_AND_FLOW_MASK;
7396 			sin6->sin6_addr = tcp->tcp_remote_v6;
7397 			sin6->sin6_port = tcp->tcp_fport;
7398 
7399 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7400 		}
7401 	}
7402 	putnext(tcp->tcp_rq, ackmp);
7403 }
7404 
7405 /*
7406  * Handle reinitialization of a tcp structure.
7407  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7408  */
7409 static void
7410 tcp_reinit(tcp_t *tcp)
7411 {
7412 	mblk_t	*mp;
7413 	int 	err;
7414 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7415 
7416 	TCP_STAT(tcps, tcp_reinit_calls);
7417 
7418 	/* tcp_reinit should never be called for detached tcp_t's */
7419 	ASSERT(tcp->tcp_listener == NULL);
7420 	ASSERT((tcp->tcp_family == AF_INET &&
7421 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7422 	    (tcp->tcp_family == AF_INET6 &&
7423 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7424 	    tcp->tcp_ipversion == IPV6_VERSION)));
7425 
7426 	/* Cancel outstanding timers */
7427 	tcp_timers_stop(tcp);
7428 
7429 	/*
7430 	 * Reset everything in the state vector, after updating global
7431 	 * MIB data from instance counters.
7432 	 */
7433 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7434 	tcp->tcp_ibsegs = 0;
7435 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7436 	tcp->tcp_obsegs = 0;
7437 
7438 	tcp_close_mpp(&tcp->tcp_xmit_head);
7439 	if (tcp->tcp_snd_zcopy_aware)
7440 		tcp_zcopy_notify(tcp);
7441 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7442 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7443 	mutex_enter(&tcp->tcp_non_sq_lock);
7444 	if (tcp->tcp_flow_stopped &&
7445 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7446 		tcp_clrqfull(tcp);
7447 	}
7448 	mutex_exit(&tcp->tcp_non_sq_lock);
7449 	tcp_close_mpp(&tcp->tcp_reass_head);
7450 	tcp->tcp_reass_tail = NULL;
7451 	if (tcp->tcp_rcv_list != NULL) {
7452 		/* Free b_next chain */
7453 		tcp_close_mpp(&tcp->tcp_rcv_list);
7454 		tcp->tcp_rcv_last_head = NULL;
7455 		tcp->tcp_rcv_last_tail = NULL;
7456 		tcp->tcp_rcv_cnt = 0;
7457 	}
7458 	tcp->tcp_rcv_last_tail = NULL;
7459 
7460 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7461 		freemsg(mp);
7462 		tcp->tcp_urp_mp = NULL;
7463 	}
7464 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7465 		freemsg(mp);
7466 		tcp->tcp_urp_mark_mp = NULL;
7467 	}
7468 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7469 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7470 		freeb(tcp->tcp_fused_sigurg_mp);
7471 		tcp->tcp_fused_sigurg_mp = NULL;
7472 	}
7473 	if (tcp->tcp_ordrel_mp != NULL) {
7474 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7475 		freeb(tcp->tcp_ordrel_mp);
7476 		tcp->tcp_ordrel_mp = NULL;
7477 	}
7478 
7479 	/*
7480 	 * Following is a union with two members which are
7481 	 * identical types and size so the following cleanup
7482 	 * is enough.
7483 	 */
7484 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7485 
7486 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7487 
7488 	/*
7489 	 * The connection can't be on the tcp_time_wait_head list
7490 	 * since it is not detached.
7491 	 */
7492 	ASSERT(tcp->tcp_time_wait_next == NULL);
7493 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7494 	ASSERT(tcp->tcp_time_wait_expire == 0);
7495 
7496 	if (tcp->tcp_kssl_pending) {
7497 		tcp->tcp_kssl_pending = B_FALSE;
7498 
7499 		/* Don't reset if the initialized by bind. */
7500 		if (tcp->tcp_kssl_ent != NULL) {
7501 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7502 			    KSSL_NO_PROXY);
7503 		}
7504 	}
7505 	if (tcp->tcp_kssl_ctx != NULL) {
7506 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7507 		tcp->tcp_kssl_ctx = NULL;
7508 	}
7509 
7510 	/*
7511 	 * Reset/preserve other values
7512 	 */
7513 	tcp_reinit_values(tcp);
7514 	ipcl_hash_remove(tcp->tcp_connp);
7515 	conn_delete_ire(tcp->tcp_connp, NULL);
7516 	tcp_ipsec_cleanup(tcp);
7517 
7518 	if (tcp->tcp_connp->conn_effective_cred != NULL) {
7519 		crfree(tcp->tcp_connp->conn_effective_cred);
7520 		tcp->tcp_connp->conn_effective_cred = NULL;
7521 	}
7522 
7523 	if (tcp->tcp_conn_req_max != 0) {
7524 		/*
7525 		 * This is the case when a TLI program uses the same
7526 		 * transport end point to accept a connection.  This
7527 		 * makes the TCP both a listener and acceptor.  When
7528 		 * this connection is closed, we need to set the state
7529 		 * back to TCPS_LISTEN.  Make sure that the eager list
7530 		 * is reinitialized.
7531 		 *
7532 		 * Note that this stream is still bound to the four
7533 		 * tuples of the previous connection in IP.  If a new
7534 		 * SYN with different foreign address comes in, IP will
7535 		 * not find it and will send it to the global queue.  In
7536 		 * the global queue, TCP will do a tcp_lookup_listener()
7537 		 * to find this stream.  This works because this stream
7538 		 * is only removed from connected hash.
7539 		 *
7540 		 */
7541 		tcp->tcp_state = TCPS_LISTEN;
7542 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7543 		tcp->tcp_eager_next_drop_q0 = tcp;
7544 		tcp->tcp_eager_prev_drop_q0 = tcp;
7545 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7546 		if (tcp->tcp_family == AF_INET6) {
7547 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7548 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7549 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7550 		} else {
7551 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7552 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7553 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7554 		}
7555 	} else {
7556 		tcp->tcp_state = TCPS_BOUND;
7557 	}
7558 
7559 	/*
7560 	 * Initialize to default values
7561 	 * Can't fail since enough header template space already allocated
7562 	 * at open().
7563 	 */
7564 	err = tcp_init_values(tcp);
7565 	ASSERT(err == 0);
7566 	/* Restore state in tcp_tcph */
7567 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7568 	if (tcp->tcp_ipversion == IPV4_VERSION)
7569 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7570 	else
7571 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7572 	/*
7573 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7574 	 * since the lookup funcs can only lookup on tcp_t
7575 	 */
7576 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7577 
7578 	ASSERT(tcp->tcp_ptpbhn != NULL);
7579 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7580 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7581 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7582 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7583 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7584 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7585 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7586 }
7587 
7588 /*
7589  * Force values to zero that need be zero.
7590  * Do not touch values asociated with the BOUND or LISTEN state
7591  * since the connection will end up in that state after the reinit.
7592  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7593  * structure!
7594  */
7595 static void
7596 tcp_reinit_values(tcp)
7597 	tcp_t *tcp;
7598 {
7599 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7600 
7601 #ifndef	lint
7602 #define	DONTCARE(x)
7603 #define	PRESERVE(x)
7604 #else
7605 #define	DONTCARE(x)	((x) = (x))
7606 #define	PRESERVE(x)	((x) = (x))
7607 #endif	/* lint */
7608 
7609 	PRESERVE(tcp->tcp_bind_hash_port);
7610 	PRESERVE(tcp->tcp_bind_hash);
7611 	PRESERVE(tcp->tcp_ptpbhn);
7612 	PRESERVE(tcp->tcp_acceptor_hash);
7613 	PRESERVE(tcp->tcp_ptpahn);
7614 
7615 	/* Should be ASSERT NULL on these with new code! */
7616 	ASSERT(tcp->tcp_time_wait_next == NULL);
7617 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7618 	ASSERT(tcp->tcp_time_wait_expire == 0);
7619 	PRESERVE(tcp->tcp_state);
7620 	PRESERVE(tcp->tcp_rq);
7621 	PRESERVE(tcp->tcp_wq);
7622 
7623 	ASSERT(tcp->tcp_xmit_head == NULL);
7624 	ASSERT(tcp->tcp_xmit_last == NULL);
7625 	ASSERT(tcp->tcp_unsent == 0);
7626 	ASSERT(tcp->tcp_xmit_tail == NULL);
7627 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7628 
7629 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7630 	tcp->tcp_suna = 0;			/* Displayed in mib */
7631 	tcp->tcp_swnd = 0;
7632 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7633 
7634 	ASSERT(tcp->tcp_ibsegs == 0);
7635 	ASSERT(tcp->tcp_obsegs == 0);
7636 
7637 	if (tcp->tcp_iphc != NULL) {
7638 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7639 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7640 	}
7641 
7642 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7643 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7644 	DONTCARE(tcp->tcp_ipha);
7645 	DONTCARE(tcp->tcp_ip6h);
7646 	DONTCARE(tcp->tcp_ip_hdr_len);
7647 	DONTCARE(tcp->tcp_tcph);
7648 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7649 	tcp->tcp_valid_bits = 0;
7650 
7651 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7652 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7653 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7654 	tcp->tcp_last_rcv_lbolt = 0;
7655 
7656 	tcp->tcp_init_cwnd = 0;
7657 
7658 	tcp->tcp_urp_last_valid = 0;
7659 	tcp->tcp_hard_binding = 0;
7660 	tcp->tcp_hard_bound = 0;
7661 	PRESERVE(tcp->tcp_cred);
7662 	PRESERVE(tcp->tcp_cpid);
7663 	PRESERVE(tcp->tcp_open_time);
7664 	PRESERVE(tcp->tcp_exclbind);
7665 
7666 	tcp->tcp_fin_acked = 0;
7667 	tcp->tcp_fin_rcvd = 0;
7668 	tcp->tcp_fin_sent = 0;
7669 	tcp->tcp_ordrel_done = 0;
7670 
7671 	tcp->tcp_debug = 0;
7672 	tcp->tcp_dontroute = 0;
7673 	tcp->tcp_broadcast = 0;
7674 
7675 	tcp->tcp_useloopback = 0;
7676 	tcp->tcp_reuseaddr = 0;
7677 	tcp->tcp_oobinline = 0;
7678 	tcp->tcp_dgram_errind = 0;
7679 
7680 	tcp->tcp_detached = 0;
7681 	tcp->tcp_bind_pending = 0;
7682 	tcp->tcp_unbind_pending = 0;
7683 
7684 	tcp->tcp_snd_ws_ok = B_FALSE;
7685 	tcp->tcp_snd_ts_ok = B_FALSE;
7686 	tcp->tcp_linger = 0;
7687 	tcp->tcp_ka_enabled = 0;
7688 	tcp->tcp_zero_win_probe = 0;
7689 
7690 	tcp->tcp_loopback = 0;
7691 	tcp->tcp_refuse = 0;
7692 	tcp->tcp_localnet = 0;
7693 	tcp->tcp_syn_defense = 0;
7694 	tcp->tcp_set_timer = 0;
7695 
7696 	tcp->tcp_active_open = 0;
7697 	tcp->tcp_rexmit = B_FALSE;
7698 	tcp->tcp_xmit_zc_clean = B_FALSE;
7699 
7700 	tcp->tcp_snd_sack_ok = B_FALSE;
7701 	PRESERVE(tcp->tcp_recvdstaddr);
7702 	tcp->tcp_hwcksum = B_FALSE;
7703 
7704 	tcp->tcp_ire_ill_check_done = B_FALSE;
7705 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7706 
7707 	tcp->tcp_mdt = B_FALSE;
7708 	tcp->tcp_mdt_hdr_head = 0;
7709 	tcp->tcp_mdt_hdr_tail = 0;
7710 
7711 	tcp->tcp_conn_def_q0 = 0;
7712 	tcp->tcp_ip_forward_progress = B_FALSE;
7713 	tcp->tcp_anon_priv_bind = 0;
7714 	tcp->tcp_ecn_ok = B_FALSE;
7715 
7716 	tcp->tcp_cwr = B_FALSE;
7717 	tcp->tcp_ecn_echo_on = B_FALSE;
7718 
7719 	if (tcp->tcp_sack_info != NULL) {
7720 		if (tcp->tcp_notsack_list != NULL) {
7721 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7722 		}
7723 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7724 		tcp->tcp_sack_info = NULL;
7725 	}
7726 
7727 	tcp->tcp_rcv_ws = 0;
7728 	tcp->tcp_snd_ws = 0;
7729 	tcp->tcp_ts_recent = 0;
7730 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7731 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7732 	tcp->tcp_if_mtu = 0;
7733 
7734 	ASSERT(tcp->tcp_reass_head == NULL);
7735 	ASSERT(tcp->tcp_reass_tail == NULL);
7736 
7737 	tcp->tcp_cwnd_cnt = 0;
7738 
7739 	ASSERT(tcp->tcp_rcv_list == NULL);
7740 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7741 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7742 	ASSERT(tcp->tcp_rcv_cnt == 0);
7743 
7744 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7745 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7746 	tcp->tcp_csuna = 0;
7747 
7748 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7749 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7750 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7751 	tcp->tcp_rtt_update = 0;
7752 
7753 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7754 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7755 
7756 	tcp->tcp_rack = 0;			/* Displayed in mib */
7757 	tcp->tcp_rack_cnt = 0;
7758 	tcp->tcp_rack_cur_max = 0;
7759 	tcp->tcp_rack_abs_max = 0;
7760 
7761 	tcp->tcp_max_swnd = 0;
7762 
7763 	ASSERT(tcp->tcp_listener == NULL);
7764 
7765 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7766 
7767 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7768 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7769 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7770 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7771 
7772 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7773 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7774 	PRESERVE(tcp->tcp_conn_req_max);
7775 	PRESERVE(tcp->tcp_conn_req_seqnum);
7776 
7777 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7778 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7779 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7780 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7781 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7782 
7783 	tcp->tcp_lingertime = 0;
7784 
7785 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7786 	ASSERT(tcp->tcp_urp_mp == NULL);
7787 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7788 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7789 
7790 	ASSERT(tcp->tcp_eager_next_q == NULL);
7791 	ASSERT(tcp->tcp_eager_last_q == NULL);
7792 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7793 	    tcp->tcp_eager_prev_q0 == NULL) ||
7794 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7795 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7796 
7797 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7798 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7799 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7800 
7801 	tcp->tcp_client_errno = 0;
7802 
7803 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7804 
7805 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7806 
7807 	PRESERVE(tcp->tcp_bound_source_v6);
7808 	tcp->tcp_last_sent_len = 0;
7809 	tcp->tcp_dupack_cnt = 0;
7810 
7811 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7812 	PRESERVE(tcp->tcp_lport);
7813 
7814 	PRESERVE(tcp->tcp_acceptor_lockp);
7815 
7816 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7817 	PRESERVE(tcp->tcp_acceptor_id);
7818 	DONTCARE(tcp->tcp_ipsec_overhead);
7819 
7820 	PRESERVE(tcp->tcp_family);
7821 	if (tcp->tcp_family == AF_INET6) {
7822 		tcp->tcp_ipversion = IPV6_VERSION;
7823 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7824 	} else {
7825 		tcp->tcp_ipversion = IPV4_VERSION;
7826 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7827 	}
7828 
7829 	tcp->tcp_bound_if = 0;
7830 	tcp->tcp_ipv6_recvancillary = 0;
7831 	tcp->tcp_recvifindex = 0;
7832 	tcp->tcp_recvhops = 0;
7833 	tcp->tcp_closed = 0;
7834 	tcp->tcp_cleandeathtag = 0;
7835 	if (tcp->tcp_hopopts != NULL) {
7836 		mi_free(tcp->tcp_hopopts);
7837 		tcp->tcp_hopopts = NULL;
7838 		tcp->tcp_hopoptslen = 0;
7839 	}
7840 	ASSERT(tcp->tcp_hopoptslen == 0);
7841 	if (tcp->tcp_dstopts != NULL) {
7842 		mi_free(tcp->tcp_dstopts);
7843 		tcp->tcp_dstopts = NULL;
7844 		tcp->tcp_dstoptslen = 0;
7845 	}
7846 	ASSERT(tcp->tcp_dstoptslen == 0);
7847 	if (tcp->tcp_rtdstopts != NULL) {
7848 		mi_free(tcp->tcp_rtdstopts);
7849 		tcp->tcp_rtdstopts = NULL;
7850 		tcp->tcp_rtdstoptslen = 0;
7851 	}
7852 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7853 	if (tcp->tcp_rthdr != NULL) {
7854 		mi_free(tcp->tcp_rthdr);
7855 		tcp->tcp_rthdr = NULL;
7856 		tcp->tcp_rthdrlen = 0;
7857 	}
7858 	ASSERT(tcp->tcp_rthdrlen == 0);
7859 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7860 
7861 	/* Reset fusion-related fields */
7862 	tcp->tcp_fused = B_FALSE;
7863 	tcp->tcp_unfusable = B_FALSE;
7864 	tcp->tcp_fused_sigurg = B_FALSE;
7865 	tcp->tcp_direct_sockfs = B_FALSE;
7866 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7867 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7868 	tcp->tcp_loopback_peer = NULL;
7869 	tcp->tcp_fuse_rcv_hiwater = 0;
7870 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7871 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7872 
7873 	tcp->tcp_lso = B_FALSE;
7874 
7875 	tcp->tcp_in_ack_unsent = 0;
7876 	tcp->tcp_cork = B_FALSE;
7877 	tcp->tcp_tconnind_started = B_FALSE;
7878 
7879 	PRESERVE(tcp->tcp_squeue_bytes);
7880 
7881 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7882 	ASSERT(!tcp->tcp_kssl_pending);
7883 	PRESERVE(tcp->tcp_kssl_ent);
7884 
7885 	tcp->tcp_closemp_used = B_FALSE;
7886 
7887 	PRESERVE(tcp->tcp_rsrv_mp);
7888 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7889 
7890 #ifdef DEBUG
7891 	DONTCARE(tcp->tcmp_stk[0]);
7892 #endif
7893 
7894 	PRESERVE(tcp->tcp_connid);
7895 
7896 
7897 #undef	DONTCARE
7898 #undef	PRESERVE
7899 }
7900 
7901 /*
7902  * Allocate necessary resources and initialize state vector.
7903  * Guaranteed not to fail so that when an error is returned,
7904  * the caller doesn't need to do any additional cleanup.
7905  */
7906 int
7907 tcp_init(tcp_t *tcp, queue_t *q)
7908 {
7909 	int	err;
7910 
7911 	tcp->tcp_rq = q;
7912 	tcp->tcp_wq = WR(q);
7913 	tcp->tcp_state = TCPS_IDLE;
7914 	if ((err = tcp_init_values(tcp)) != 0)
7915 		tcp_timers_stop(tcp);
7916 	return (err);
7917 }
7918 
7919 static int
7920 tcp_init_values(tcp_t *tcp)
7921 {
7922 	int	err;
7923 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7924 
7925 	ASSERT((tcp->tcp_family == AF_INET &&
7926 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7927 	    (tcp->tcp_family == AF_INET6 &&
7928 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7929 	    tcp->tcp_ipversion == IPV6_VERSION)));
7930 
7931 	/*
7932 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7933 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7934 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7935 	 * during first few transmissions of a connection as seen in slow
7936 	 * links.
7937 	 */
7938 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7939 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7940 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7941 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7942 	    tcps->tcps_conn_grace_period;
7943 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7944 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7945 	tcp->tcp_timer_backoff = 0;
7946 	tcp->tcp_ms_we_have_waited = 0;
7947 	tcp->tcp_last_recv_time = lbolt;
7948 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7949 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7950 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7951 
7952 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7953 
7954 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7955 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7956 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7957 	/*
7958 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7959 	 * passive open.
7960 	 */
7961 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7962 
7963 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7964 
7965 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7966 
7967 	tcp->tcp_mdt_hdr_head = 0;
7968 	tcp->tcp_mdt_hdr_tail = 0;
7969 
7970 	/* Reset fusion-related fields */
7971 	tcp->tcp_fused = B_FALSE;
7972 	tcp->tcp_unfusable = B_FALSE;
7973 	tcp->tcp_fused_sigurg = B_FALSE;
7974 	tcp->tcp_direct_sockfs = B_FALSE;
7975 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7976 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7977 	tcp->tcp_loopback_peer = NULL;
7978 	tcp->tcp_fuse_rcv_hiwater = 0;
7979 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7980 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7981 
7982 	/* Initialize the header template */
7983 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7984 		err = tcp_header_init_ipv4(tcp);
7985 	} else {
7986 		err = tcp_header_init_ipv6(tcp);
7987 	}
7988 	if (err)
7989 		return (err);
7990 
7991 	/*
7992 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7993 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7994 	 */
7995 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7996 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7997 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
7998 
7999 	tcp->tcp_cork = B_FALSE;
8000 	/*
8001 	 * Init the tcp_debug option.  This value determines whether TCP
8002 	 * calls strlog() to print out debug messages.  Doing this
8003 	 * initialization here means that this value is not inherited thru
8004 	 * tcp_reinit().
8005 	 */
8006 	tcp->tcp_debug = tcps->tcps_dbg;
8007 
8008 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8009 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8010 
8011 	return (0);
8012 }
8013 
8014 /*
8015  * Initialize the IPv4 header. Loses any record of any IP options.
8016  */
8017 static int
8018 tcp_header_init_ipv4(tcp_t *tcp)
8019 {
8020 	tcph_t		*tcph;
8021 	uint32_t	sum;
8022 	conn_t		*connp;
8023 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8024 
8025 	/*
8026 	 * This is a simple initialization. If there's
8027 	 * already a template, it should never be too small,
8028 	 * so reuse it.  Otherwise, allocate space for the new one.
8029 	 */
8030 	if (tcp->tcp_iphc == NULL) {
8031 		ASSERT(tcp->tcp_iphc_len == 0);
8032 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8033 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8034 		if (tcp->tcp_iphc == NULL) {
8035 			tcp->tcp_iphc_len = 0;
8036 			return (ENOMEM);
8037 		}
8038 	}
8039 
8040 	/* options are gone; may need a new label */
8041 	connp = tcp->tcp_connp;
8042 	connp->conn_mlp_type = mlptSingle;
8043 	connp->conn_ulp_labeled = !is_system_labeled();
8044 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8045 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8046 	tcp->tcp_ip6h = NULL;
8047 	tcp->tcp_ipversion = IPV4_VERSION;
8048 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8049 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8050 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8051 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8052 	tcp->tcp_ipha->ipha_version_and_hdr_length
8053 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8054 	tcp->tcp_ipha->ipha_ident = 0;
8055 
8056 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8057 	tcp->tcp_tos = 0;
8058 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8059 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8060 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8061 
8062 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8063 	tcp->tcp_tcph = tcph;
8064 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8065 	/*
8066 	 * IP wants our header length in the checksum field to
8067 	 * allow it to perform a single pseudo-header+checksum
8068 	 * calculation on behalf of TCP.
8069 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8070 	 */
8071 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8072 	sum = (sum >> 16) + (sum & 0xFFFF);
8073 	U16_TO_ABE16(sum, tcph->th_sum);
8074 	return (0);
8075 }
8076 
8077 /*
8078  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8079  */
8080 static int
8081 tcp_header_init_ipv6(tcp_t *tcp)
8082 {
8083 	tcph_t	*tcph;
8084 	uint32_t	sum;
8085 	conn_t	*connp;
8086 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8087 
8088 	/*
8089 	 * This is a simple initialization. If there's
8090 	 * already a template, it should never be too small,
8091 	 * so reuse it. Otherwise, allocate space for the new one.
8092 	 * Ensure that there is enough space to "downgrade" the tcp_t
8093 	 * to an IPv4 tcp_t. This requires having space for a full load
8094 	 * of IPv4 options, as well as a full load of TCP options
8095 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8096 	 * than a v6 header and a TCP header with a full load of TCP options
8097 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8098 	 * We want to avoid reallocation in the "downgraded" case when
8099 	 * processing outbound IPv4 options.
8100 	 */
8101 	if (tcp->tcp_iphc == NULL) {
8102 		ASSERT(tcp->tcp_iphc_len == 0);
8103 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8104 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8105 		if (tcp->tcp_iphc == NULL) {
8106 			tcp->tcp_iphc_len = 0;
8107 			return (ENOMEM);
8108 		}
8109 	}
8110 
8111 	/* options are gone; may need a new label */
8112 	connp = tcp->tcp_connp;
8113 	connp->conn_mlp_type = mlptSingle;
8114 	connp->conn_ulp_labeled = !is_system_labeled();
8115 
8116 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8117 	tcp->tcp_ipversion = IPV6_VERSION;
8118 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8119 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8120 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8121 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8122 	tcp->tcp_ipha = NULL;
8123 
8124 	/* Initialize the header template */
8125 
8126 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8127 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8128 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8129 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8130 
8131 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8132 	tcp->tcp_tcph = tcph;
8133 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8134 	/*
8135 	 * IP wants our header length in the checksum field to
8136 	 * allow it to perform a single psuedo-header+checksum
8137 	 * calculation on behalf of TCP.
8138 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8139 	 */
8140 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8141 	sum = (sum >> 16) + (sum & 0xFFFF);
8142 	U16_TO_ABE16(sum, tcph->th_sum);
8143 	return (0);
8144 }
8145 
8146 /* At minimum we need 8 bytes in the TCP header for the lookup */
8147 #define	ICMP_MIN_TCP_HDR	8
8148 
8149 /*
8150  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8151  * passed up by IP. The message is always received on the correct tcp_t.
8152  * Assumes that IP has pulled up everything up to and including the ICMP header.
8153  */
8154 void
8155 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8156 {
8157 	icmph_t *icmph;
8158 	ipha_t	*ipha;
8159 	int	iph_hdr_length;
8160 	tcph_t	*tcph;
8161 	boolean_t ipsec_mctl = B_FALSE;
8162 	boolean_t secure;
8163 	mblk_t *first_mp = mp;
8164 	int32_t new_mss;
8165 	uint32_t ratio;
8166 	size_t mp_size = MBLKL(mp);
8167 	uint32_t seg_seq;
8168 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8169 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8170 
8171 	/* Assume IP provides aligned packets - otherwise toss */
8172 	if (!OK_32PTR(mp->b_rptr)) {
8173 		freemsg(mp);
8174 		return;
8175 	}
8176 
8177 	/*
8178 	 * Since ICMP errors are normal data marked with M_CTL when sent
8179 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8180 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8181 	 */
8182 	if ((mp_size == sizeof (ipsec_info_t)) &&
8183 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8184 		ASSERT(mp->b_cont != NULL);
8185 		mp = mp->b_cont;
8186 		/* IP should have done this */
8187 		ASSERT(OK_32PTR(mp->b_rptr));
8188 		mp_size = MBLKL(mp);
8189 		ipsec_mctl = B_TRUE;
8190 	}
8191 
8192 	/*
8193 	 * Verify that we have a complete outer IP header. If not, drop it.
8194 	 */
8195 	if (mp_size < sizeof (ipha_t)) {
8196 noticmpv4:
8197 		freemsg(first_mp);
8198 		return;
8199 	}
8200 
8201 	ipha = (ipha_t *)mp->b_rptr;
8202 	/*
8203 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8204 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8205 	 */
8206 	switch (IPH_HDR_VERSION(ipha)) {
8207 	case IPV6_VERSION:
8208 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8209 		return;
8210 	case IPV4_VERSION:
8211 		break;
8212 	default:
8213 		goto noticmpv4;
8214 	}
8215 
8216 	/* Skip past the outer IP and ICMP headers */
8217 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8218 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8219 	/*
8220 	 * If we don't have the correct outer IP header length or if the ULP
8221 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8222 	 * send it upstream.
8223 	 */
8224 	if (iph_hdr_length < sizeof (ipha_t) ||
8225 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8226 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8227 		goto noticmpv4;
8228 	}
8229 	ipha = (ipha_t *)&icmph[1];
8230 
8231 	/* Skip past the inner IP and find the ULP header */
8232 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8233 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8234 	/*
8235 	 * If we don't have the correct inner IP header length or if the ULP
8236 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8237 	 * bytes of TCP header, drop it.
8238 	 */
8239 	if (iph_hdr_length < sizeof (ipha_t) ||
8240 	    ipha->ipha_protocol != IPPROTO_TCP ||
8241 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8242 		goto noticmpv4;
8243 	}
8244 
8245 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8246 		if (ipsec_mctl) {
8247 			secure = ipsec_in_is_secure(first_mp);
8248 		} else {
8249 			secure = B_FALSE;
8250 		}
8251 		if (secure) {
8252 			/*
8253 			 * If we are willing to accept this in clear
8254 			 * we don't have to verify policy.
8255 			 */
8256 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8257 				if (!tcp_check_policy(tcp, first_mp,
8258 				    ipha, NULL, secure, ipsec_mctl)) {
8259 					/*
8260 					 * tcp_check_policy called
8261 					 * ip_drop_packet() on failure.
8262 					 */
8263 					return;
8264 				}
8265 			}
8266 		}
8267 	} else if (ipsec_mctl) {
8268 		/*
8269 		 * This is a hard_bound connection. IP has already
8270 		 * verified policy. We don't have to do it again.
8271 		 */
8272 		freeb(first_mp);
8273 		first_mp = mp;
8274 		ipsec_mctl = B_FALSE;
8275 	}
8276 
8277 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8278 	/*
8279 	 * TCP SHOULD check that the TCP sequence number contained in
8280 	 * payload of the ICMP error message is within the range
8281 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8282 	 */
8283 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8284 		/*
8285 		 * The ICMP message is bogus, just drop it.  But if this is
8286 		 * an ICMP too big message, IP has already changed
8287 		 * the ire_max_frag to the bogus value.  We need to change
8288 		 * it back.
8289 		 */
8290 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8291 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8292 			conn_t *connp = tcp->tcp_connp;
8293 			ire_t *ire;
8294 			int flag;
8295 
8296 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8297 				flag = tcp->tcp_ipha->
8298 				    ipha_fragment_offset_and_flags;
8299 			} else {
8300 				flag = 0;
8301 			}
8302 			mutex_enter(&connp->conn_lock);
8303 			if ((ire = connp->conn_ire_cache) != NULL) {
8304 				mutex_enter(&ire->ire_lock);
8305 				mutex_exit(&connp->conn_lock);
8306 				ire->ire_max_frag = tcp->tcp_if_mtu;
8307 				ire->ire_frag_flag |= flag;
8308 				mutex_exit(&ire->ire_lock);
8309 			} else {
8310 				mutex_exit(&connp->conn_lock);
8311 			}
8312 		}
8313 		goto noticmpv4;
8314 	}
8315 
8316 	switch (icmph->icmph_type) {
8317 	case ICMP_DEST_UNREACHABLE:
8318 		switch (icmph->icmph_code) {
8319 		case ICMP_FRAGMENTATION_NEEDED:
8320 			/*
8321 			 * Reduce the MSS based on the new MTU.  This will
8322 			 * eliminate any fragmentation locally.
8323 			 * N.B.  There may well be some funny side-effects on
8324 			 * the local send policy and the remote receive policy.
8325 			 * Pending further research, we provide
8326 			 * tcp_ignore_path_mtu just in case this proves
8327 			 * disastrous somewhere.
8328 			 *
8329 			 * After updating the MSS, retransmit part of the
8330 			 * dropped segment using the new mss by calling
8331 			 * tcp_wput_data().  Need to adjust all those
8332 			 * params to make sure tcp_wput_data() work properly.
8333 			 */
8334 			if (tcps->tcps_ignore_path_mtu ||
8335 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8336 				break;
8337 
8338 			/*
8339 			 * Decrease the MSS by time stamp options
8340 			 * IP options and IPSEC options. tcp_hdr_len
8341 			 * includes time stamp option and IP option
8342 			 * length.  Note that new_mss may be negative
8343 			 * if tcp_ipsec_overhead is large and the
8344 			 * icmph_du_mtu is the minimum value, which is 68.
8345 			 */
8346 			new_mss = ntohs(icmph->icmph_du_mtu) -
8347 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8348 
8349 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8350 			    new_mss);
8351 
8352 			/*
8353 			 * Only update the MSS if the new one is
8354 			 * smaller than the previous one.  This is
8355 			 * to avoid problems when getting multiple
8356 			 * ICMP errors for the same MTU.
8357 			 */
8358 			if (new_mss >= tcp->tcp_mss)
8359 				break;
8360 
8361 			/*
8362 			 * Note that we are using the template header's DF
8363 			 * bit in the fast path sending.  So we need to compare
8364 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8365 			 * And stop doing IPv4 PMTUd if new_mss is less than
8366 			 * MAX(tcps_mss_min, ip_pmtu_min).
8367 			 */
8368 			if (new_mss < tcps->tcps_mss_min ||
8369 			    new_mss < ipst->ips_ip_pmtu_min) {
8370 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8371 				    0;
8372 			}
8373 
8374 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8375 			ASSERT(ratio >= 1);
8376 			tcp_mss_set(tcp, new_mss, B_TRUE);
8377 
8378 			/*
8379 			 * Make sure we have something to
8380 			 * send.
8381 			 */
8382 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8383 			    (tcp->tcp_xmit_head != NULL)) {
8384 				/*
8385 				 * Shrink tcp_cwnd in
8386 				 * proportion to the old MSS/new MSS.
8387 				 */
8388 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8389 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8390 				    (tcp->tcp_unsent == 0)) {
8391 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8392 				} else {
8393 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8394 				}
8395 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8396 				tcp->tcp_rexmit = B_TRUE;
8397 				tcp->tcp_dupack_cnt = 0;
8398 				tcp->tcp_snd_burst = TCP_CWND_SS;
8399 				tcp_ss_rexmit(tcp);
8400 			}
8401 			break;
8402 		case ICMP_PORT_UNREACHABLE:
8403 		case ICMP_PROTOCOL_UNREACHABLE:
8404 			switch (tcp->tcp_state) {
8405 			case TCPS_SYN_SENT:
8406 			case TCPS_SYN_RCVD:
8407 				/*
8408 				 * ICMP can snipe away incipient
8409 				 * TCP connections as long as
8410 				 * seq number is same as initial
8411 				 * send seq number.
8412 				 */
8413 				if (seg_seq == tcp->tcp_iss) {
8414 					(void) tcp_clean_death(tcp,
8415 					    ECONNREFUSED, 6);
8416 				}
8417 				break;
8418 			}
8419 			break;
8420 		case ICMP_HOST_UNREACHABLE:
8421 		case ICMP_NET_UNREACHABLE:
8422 			/* Record the error in case we finally time out. */
8423 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8424 				tcp->tcp_client_errno = EHOSTUNREACH;
8425 			else
8426 				tcp->tcp_client_errno = ENETUNREACH;
8427 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8428 				if (tcp->tcp_listener != NULL &&
8429 				    tcp->tcp_listener->tcp_syn_defense) {
8430 					/*
8431 					 * Ditch the half-open connection if we
8432 					 * suspect a SYN attack is under way.
8433 					 */
8434 					tcp_ip_ire_mark_advice(tcp);
8435 					(void) tcp_clean_death(tcp,
8436 					    tcp->tcp_client_errno, 7);
8437 				}
8438 			}
8439 			break;
8440 		default:
8441 			break;
8442 		}
8443 		break;
8444 	case ICMP_SOURCE_QUENCH: {
8445 		/*
8446 		 * use a global boolean to control
8447 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8448 		 * The default is false.
8449 		 */
8450 		if (tcp_icmp_source_quench) {
8451 			/*
8452 			 * Reduce the sending rate as if we got a
8453 			 * retransmit timeout
8454 			 */
8455 			uint32_t npkt;
8456 
8457 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8458 			    tcp->tcp_mss;
8459 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8460 			tcp->tcp_cwnd = tcp->tcp_mss;
8461 			tcp->tcp_cwnd_cnt = 0;
8462 		}
8463 		break;
8464 	}
8465 	}
8466 	freemsg(first_mp);
8467 }
8468 
8469 /*
8470  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8471  * error messages passed up by IP.
8472  * Assumes that IP has pulled up all the extension headers as well
8473  * as the ICMPv6 header.
8474  */
8475 static void
8476 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8477 {
8478 	icmp6_t *icmp6;
8479 	ip6_t	*ip6h;
8480 	uint16_t	iph_hdr_length;
8481 	tcpha_t	*tcpha;
8482 	uint8_t	*nexthdrp;
8483 	uint32_t new_mss;
8484 	uint32_t ratio;
8485 	boolean_t secure;
8486 	mblk_t *first_mp = mp;
8487 	size_t mp_size;
8488 	uint32_t seg_seq;
8489 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8490 
8491 	/*
8492 	 * The caller has determined if this is an IPSEC_IN packet and
8493 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8494 	 */
8495 	if (ipsec_mctl)
8496 		mp = mp->b_cont;
8497 
8498 	mp_size = MBLKL(mp);
8499 
8500 	/*
8501 	 * Verify that we have a complete IP header. If not, send it upstream.
8502 	 */
8503 	if (mp_size < sizeof (ip6_t)) {
8504 noticmpv6:
8505 		freemsg(first_mp);
8506 		return;
8507 	}
8508 
8509 	/*
8510 	 * Verify this is an ICMPV6 packet, else send it upstream.
8511 	 */
8512 	ip6h = (ip6_t *)mp->b_rptr;
8513 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8514 		iph_hdr_length = IPV6_HDR_LEN;
8515 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8516 	    &nexthdrp) ||
8517 	    *nexthdrp != IPPROTO_ICMPV6) {
8518 		goto noticmpv6;
8519 	}
8520 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8521 	ip6h = (ip6_t *)&icmp6[1];
8522 	/*
8523 	 * Verify if we have a complete ICMP and inner IP header.
8524 	 */
8525 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8526 		goto noticmpv6;
8527 
8528 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8529 		goto noticmpv6;
8530 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8531 	/*
8532 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8533 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8534 	 * packet.
8535 	 */
8536 	if ((*nexthdrp != IPPROTO_TCP) ||
8537 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8538 		goto noticmpv6;
8539 	}
8540 
8541 	/*
8542 	 * ICMP errors come on the right queue or come on
8543 	 * listener/global queue for detached connections and
8544 	 * get switched to the right queue. If it comes on the
8545 	 * right queue, policy check has already been done by IP
8546 	 * and thus free the first_mp without verifying the policy.
8547 	 * If it has come for a non-hard bound connection, we need
8548 	 * to verify policy as IP may not have done it.
8549 	 */
8550 	if (!tcp->tcp_hard_bound) {
8551 		if (ipsec_mctl) {
8552 			secure = ipsec_in_is_secure(first_mp);
8553 		} else {
8554 			secure = B_FALSE;
8555 		}
8556 		if (secure) {
8557 			/*
8558 			 * If we are willing to accept this in clear
8559 			 * we don't have to verify policy.
8560 			 */
8561 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8562 				if (!tcp_check_policy(tcp, first_mp,
8563 				    NULL, ip6h, secure, ipsec_mctl)) {
8564 					/*
8565 					 * tcp_check_policy called
8566 					 * ip_drop_packet() on failure.
8567 					 */
8568 					return;
8569 				}
8570 			}
8571 		}
8572 	} else if (ipsec_mctl) {
8573 		/*
8574 		 * This is a hard_bound connection. IP has already
8575 		 * verified policy. We don't have to do it again.
8576 		 */
8577 		freeb(first_mp);
8578 		first_mp = mp;
8579 		ipsec_mctl = B_FALSE;
8580 	}
8581 
8582 	seg_seq = ntohl(tcpha->tha_seq);
8583 	/*
8584 	 * TCP SHOULD check that the TCP sequence number contained in
8585 	 * payload of the ICMP error message is within the range
8586 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8587 	 */
8588 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8589 		/*
8590 		 * If the ICMP message is bogus, should we kill the
8591 		 * connection, or should we just drop the bogus ICMP
8592 		 * message? It would probably make more sense to just
8593 		 * drop the message so that if this one managed to get
8594 		 * in, the real connection should not suffer.
8595 		 */
8596 		goto noticmpv6;
8597 	}
8598 
8599 	switch (icmp6->icmp6_type) {
8600 	case ICMP6_PACKET_TOO_BIG:
8601 		/*
8602 		 * Reduce the MSS based on the new MTU.  This will
8603 		 * eliminate any fragmentation locally.
8604 		 * N.B.  There may well be some funny side-effects on
8605 		 * the local send policy and the remote receive policy.
8606 		 * Pending further research, we provide
8607 		 * tcp_ignore_path_mtu just in case this proves
8608 		 * disastrous somewhere.
8609 		 *
8610 		 * After updating the MSS, retransmit part of the
8611 		 * dropped segment using the new mss by calling
8612 		 * tcp_wput_data().  Need to adjust all those
8613 		 * params to make sure tcp_wput_data() work properly.
8614 		 */
8615 		if (tcps->tcps_ignore_path_mtu)
8616 			break;
8617 
8618 		/*
8619 		 * Decrease the MSS by time stamp options
8620 		 * IP options and IPSEC options. tcp_hdr_len
8621 		 * includes time stamp option and IP option
8622 		 * length.
8623 		 */
8624 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8625 		    tcp->tcp_ipsec_overhead;
8626 
8627 		/*
8628 		 * Only update the MSS if the new one is
8629 		 * smaller than the previous one.  This is
8630 		 * to avoid problems when getting multiple
8631 		 * ICMP errors for the same MTU.
8632 		 */
8633 		if (new_mss >= tcp->tcp_mss)
8634 			break;
8635 
8636 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8637 		ASSERT(ratio >= 1);
8638 		tcp_mss_set(tcp, new_mss, B_TRUE);
8639 
8640 		/*
8641 		 * Make sure we have something to
8642 		 * send.
8643 		 */
8644 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8645 		    (tcp->tcp_xmit_head != NULL)) {
8646 			/*
8647 			 * Shrink tcp_cwnd in
8648 			 * proportion to the old MSS/new MSS.
8649 			 */
8650 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8651 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8652 			    (tcp->tcp_unsent == 0)) {
8653 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8654 			} else {
8655 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8656 			}
8657 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8658 			tcp->tcp_rexmit = B_TRUE;
8659 			tcp->tcp_dupack_cnt = 0;
8660 			tcp->tcp_snd_burst = TCP_CWND_SS;
8661 			tcp_ss_rexmit(tcp);
8662 		}
8663 		break;
8664 
8665 	case ICMP6_DST_UNREACH:
8666 		switch (icmp6->icmp6_code) {
8667 		case ICMP6_DST_UNREACH_NOPORT:
8668 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8669 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8670 			    (seg_seq == tcp->tcp_iss)) {
8671 				(void) tcp_clean_death(tcp,
8672 				    ECONNREFUSED, 8);
8673 			}
8674 			break;
8675 
8676 		case ICMP6_DST_UNREACH_ADMIN:
8677 		case ICMP6_DST_UNREACH_NOROUTE:
8678 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8679 		case ICMP6_DST_UNREACH_ADDR:
8680 			/* Record the error in case we finally time out. */
8681 			tcp->tcp_client_errno = EHOSTUNREACH;
8682 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8683 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8684 			    (seg_seq == tcp->tcp_iss)) {
8685 				if (tcp->tcp_listener != NULL &&
8686 				    tcp->tcp_listener->tcp_syn_defense) {
8687 					/*
8688 					 * Ditch the half-open connection if we
8689 					 * suspect a SYN attack is under way.
8690 					 */
8691 					tcp_ip_ire_mark_advice(tcp);
8692 					(void) tcp_clean_death(tcp,
8693 					    tcp->tcp_client_errno, 9);
8694 				}
8695 			}
8696 
8697 
8698 			break;
8699 		default:
8700 			break;
8701 		}
8702 		break;
8703 
8704 	case ICMP6_PARAM_PROB:
8705 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8706 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8707 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8708 		    (uchar_t *)nexthdrp) {
8709 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8710 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8711 				(void) tcp_clean_death(tcp,
8712 				    ECONNREFUSED, 10);
8713 			}
8714 			break;
8715 		}
8716 		break;
8717 
8718 	case ICMP6_TIME_EXCEEDED:
8719 	default:
8720 		break;
8721 	}
8722 	freemsg(first_mp);
8723 }
8724 
8725 /*
8726  * Notify IP that we are having trouble with this connection.  IP should
8727  * blow the IRE away and start over.
8728  */
8729 static void
8730 tcp_ip_notify(tcp_t *tcp)
8731 {
8732 	struct iocblk	*iocp;
8733 	ipid_t	*ipid;
8734 	mblk_t	*mp;
8735 
8736 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8737 	if (tcp->tcp_ipversion == IPV6_VERSION)
8738 		return;
8739 
8740 	mp = mkiocb(IP_IOCTL);
8741 	if (mp == NULL)
8742 		return;
8743 
8744 	iocp = (struct iocblk *)mp->b_rptr;
8745 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8746 
8747 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8748 	if (!mp->b_cont) {
8749 		freeb(mp);
8750 		return;
8751 	}
8752 
8753 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8754 	mp->b_cont->b_wptr += iocp->ioc_count;
8755 	bzero(ipid, sizeof (*ipid));
8756 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8757 	ipid->ipid_ire_type = IRE_CACHE;
8758 	ipid->ipid_addr_offset = sizeof (ipid_t);
8759 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8760 	/*
8761 	 * Note: in the case of source routing we want to blow away the
8762 	 * route to the first source route hop.
8763 	 */
8764 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8765 	    sizeof (tcp->tcp_ipha->ipha_dst));
8766 
8767 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8768 }
8769 
8770 /* Unlink and return any mblk that looks like it contains an ire */
8771 static mblk_t *
8772 tcp_ire_mp(mblk_t **mpp)
8773 {
8774 	mblk_t 	*mp = *mpp;
8775 	mblk_t	*prev_mp = NULL;
8776 
8777 	for (;;) {
8778 		switch (DB_TYPE(mp)) {
8779 		case IRE_DB_TYPE:
8780 		case IRE_DB_REQ_TYPE:
8781 			if (mp == *mpp) {
8782 				*mpp = mp->b_cont;
8783 			} else {
8784 				prev_mp->b_cont = mp->b_cont;
8785 			}
8786 			mp->b_cont = NULL;
8787 			return (mp);
8788 		default:
8789 			break;
8790 		}
8791 		prev_mp = mp;
8792 		mp = mp->b_cont;
8793 		if (mp == NULL)
8794 			break;
8795 	}
8796 	return (mp);
8797 }
8798 
8799 /*
8800  * Timer callback routine for keepalive probe.  We do a fake resend of
8801  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8802  * check to see if we have heard anything from the other end for the last
8803  * RTO period.  If we have, set the timer to expire for another
8804  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8805  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8806  * the timeout if we have not heard from the other side.  If for more than
8807  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8808  * kill the connection unless the keepalive abort threshold is 0.  In
8809  * that case, we will probe "forever."
8810  */
8811 static void
8812 tcp_keepalive_killer(void *arg)
8813 {
8814 	mblk_t	*mp;
8815 	conn_t	*connp = (conn_t *)arg;
8816 	tcp_t  	*tcp = connp->conn_tcp;
8817 	int32_t	firetime;
8818 	int32_t	idletime;
8819 	int32_t	ka_intrvl;
8820 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8821 
8822 	tcp->tcp_ka_tid = 0;
8823 
8824 	if (tcp->tcp_fused)
8825 		return;
8826 
8827 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8828 	ka_intrvl = tcp->tcp_ka_interval;
8829 
8830 	/*
8831 	 * Keepalive probe should only be sent if the application has not
8832 	 * done a close on the connection.
8833 	 */
8834 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8835 		return;
8836 	}
8837 	/* Timer fired too early, restart it. */
8838 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8839 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8840 		    MSEC_TO_TICK(ka_intrvl));
8841 		return;
8842 	}
8843 
8844 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8845 	/*
8846 	 * If we have not heard from the other side for a long
8847 	 * time, kill the connection unless the keepalive abort
8848 	 * threshold is 0.  In that case, we will probe "forever."
8849 	 */
8850 	if (tcp->tcp_ka_abort_thres != 0 &&
8851 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8852 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8853 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8854 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8855 		return;
8856 	}
8857 
8858 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8859 	    idletime >= ka_intrvl) {
8860 		/* Fake resend of last ACKed byte. */
8861 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8862 
8863 		if (mp1 != NULL) {
8864 			*mp1->b_wptr++ = '\0';
8865 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8866 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8867 			freeb(mp1);
8868 			/*
8869 			 * if allocation failed, fall through to start the
8870 			 * timer back.
8871 			 */
8872 			if (mp != NULL) {
8873 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8874 				BUMP_MIB(&tcps->tcps_mib,
8875 				    tcpTimKeepaliveProbe);
8876 				if (tcp->tcp_ka_last_intrvl != 0) {
8877 					int max;
8878 					/*
8879 					 * We should probe again at least
8880 					 * in ka_intrvl, but not more than
8881 					 * tcp_rexmit_interval_max.
8882 					 */
8883 					max = tcps->tcps_rexmit_interval_max;
8884 					firetime = MIN(ka_intrvl - 1,
8885 					    tcp->tcp_ka_last_intrvl << 1);
8886 					if (firetime > max)
8887 						firetime = max;
8888 				} else {
8889 					firetime = tcp->tcp_rto;
8890 				}
8891 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8892 				    tcp_keepalive_killer,
8893 				    MSEC_TO_TICK(firetime));
8894 				tcp->tcp_ka_last_intrvl = firetime;
8895 				return;
8896 			}
8897 		}
8898 	} else {
8899 		tcp->tcp_ka_last_intrvl = 0;
8900 	}
8901 
8902 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8903 	if ((firetime = ka_intrvl - idletime) < 0) {
8904 		firetime = ka_intrvl;
8905 	}
8906 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8907 	    MSEC_TO_TICK(firetime));
8908 }
8909 
8910 int
8911 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8912 {
8913 	queue_t	*q = tcp->tcp_rq;
8914 	int32_t	mss = tcp->tcp_mss;
8915 	int	maxpsz;
8916 	conn_t	*connp = tcp->tcp_connp;
8917 
8918 	if (TCP_IS_DETACHED(tcp))
8919 		return (mss);
8920 	if (tcp->tcp_fused) {
8921 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8922 		mss = INFPSZ;
8923 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8924 		/*
8925 		 * Set the sd_qn_maxpsz according to the socket send buffer
8926 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8927 		 * instruct the stream head to copyin user data into contiguous
8928 		 * kernel-allocated buffers without breaking it up into smaller
8929 		 * chunks.  We round up the buffer size to the nearest SMSS.
8930 		 */
8931 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8932 		if (tcp->tcp_kssl_ctx == NULL)
8933 			mss = INFPSZ;
8934 		else
8935 			mss = SSL3_MAX_RECORD_LEN;
8936 	} else {
8937 		/*
8938 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8939 		 * (and a multiple of the mss).  This instructs the stream
8940 		 * head to break down larger than SMSS writes into SMSS-
8941 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8942 		 */
8943 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8944 		maxpsz = tcp->tcp_maxpsz * mss;
8945 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8946 			maxpsz = tcp->tcp_xmit_hiwater/2;
8947 			/* Round up to nearest mss */
8948 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8949 		}
8950 	}
8951 
8952 	(void) proto_set_maxpsz(q, connp, maxpsz);
8953 	if (!(IPCL_IS_NONSTR(connp))) {
8954 		/* XXX do it in set_maxpsz()? */
8955 		tcp->tcp_wq->q_maxpsz = maxpsz;
8956 	}
8957 
8958 	if (set_maxblk)
8959 		(void) proto_set_tx_maxblk(q, connp, mss);
8960 	return (mss);
8961 }
8962 
8963 /*
8964  * Extract option values from a tcp header.  We put any found values into the
8965  * tcpopt struct and return a bitmask saying which options were found.
8966  */
8967 static int
8968 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8969 {
8970 	uchar_t		*endp;
8971 	int		len;
8972 	uint32_t	mss;
8973 	uchar_t		*up = (uchar_t *)tcph;
8974 	int		found = 0;
8975 	int32_t		sack_len;
8976 	tcp_seq		sack_begin, sack_end;
8977 	tcp_t		*tcp;
8978 
8979 	endp = up + TCP_HDR_LENGTH(tcph);
8980 	up += TCP_MIN_HEADER_LENGTH;
8981 	while (up < endp) {
8982 		len = endp - up;
8983 		switch (*up) {
8984 		case TCPOPT_EOL:
8985 			break;
8986 
8987 		case TCPOPT_NOP:
8988 			up++;
8989 			continue;
8990 
8991 		case TCPOPT_MAXSEG:
8992 			if (len < TCPOPT_MAXSEG_LEN ||
8993 			    up[1] != TCPOPT_MAXSEG_LEN)
8994 				break;
8995 
8996 			mss = BE16_TO_U16(up+2);
8997 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8998 			tcpopt->tcp_opt_mss = mss;
8999 			found |= TCP_OPT_MSS_PRESENT;
9000 
9001 			up += TCPOPT_MAXSEG_LEN;
9002 			continue;
9003 
9004 		case TCPOPT_WSCALE:
9005 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9006 				break;
9007 
9008 			if (up[2] > TCP_MAX_WINSHIFT)
9009 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9010 			else
9011 				tcpopt->tcp_opt_wscale = up[2];
9012 			found |= TCP_OPT_WSCALE_PRESENT;
9013 
9014 			up += TCPOPT_WS_LEN;
9015 			continue;
9016 
9017 		case TCPOPT_SACK_PERMITTED:
9018 			if (len < TCPOPT_SACK_OK_LEN ||
9019 			    up[1] != TCPOPT_SACK_OK_LEN)
9020 				break;
9021 			found |= TCP_OPT_SACK_OK_PRESENT;
9022 			up += TCPOPT_SACK_OK_LEN;
9023 			continue;
9024 
9025 		case TCPOPT_SACK:
9026 			if (len <= 2 || up[1] <= 2 || len < up[1])
9027 				break;
9028 
9029 			/* If TCP is not interested in SACK blks... */
9030 			if ((tcp = tcpopt->tcp) == NULL) {
9031 				up += up[1];
9032 				continue;
9033 			}
9034 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9035 			up += TCPOPT_HEADER_LEN;
9036 
9037 			/*
9038 			 * If the list is empty, allocate one and assume
9039 			 * nothing is sack'ed.
9040 			 */
9041 			ASSERT(tcp->tcp_sack_info != NULL);
9042 			if (tcp->tcp_notsack_list == NULL) {
9043 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9044 				    tcp->tcp_suna, tcp->tcp_snxt,
9045 				    &(tcp->tcp_num_notsack_blk),
9046 				    &(tcp->tcp_cnt_notsack_list));
9047 
9048 				/*
9049 				 * Make sure tcp_notsack_list is not NULL.
9050 				 * This happens when kmem_alloc(KM_NOSLEEP)
9051 				 * returns NULL.
9052 				 */
9053 				if (tcp->tcp_notsack_list == NULL) {
9054 					up += sack_len;
9055 					continue;
9056 				}
9057 				tcp->tcp_fack = tcp->tcp_suna;
9058 			}
9059 
9060 			while (sack_len > 0) {
9061 				if (up + 8 > endp) {
9062 					up = endp;
9063 					break;
9064 				}
9065 				sack_begin = BE32_TO_U32(up);
9066 				up += 4;
9067 				sack_end = BE32_TO_U32(up);
9068 				up += 4;
9069 				sack_len -= 8;
9070 				/*
9071 				 * Bounds checking.  Make sure the SACK
9072 				 * info is within tcp_suna and tcp_snxt.
9073 				 * If this SACK blk is out of bound, ignore
9074 				 * it but continue to parse the following
9075 				 * blks.
9076 				 */
9077 				if (SEQ_LEQ(sack_end, sack_begin) ||
9078 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9079 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9080 					continue;
9081 				}
9082 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9083 				    sack_begin, sack_end,
9084 				    &(tcp->tcp_num_notsack_blk),
9085 				    &(tcp->tcp_cnt_notsack_list));
9086 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9087 					tcp->tcp_fack = sack_end;
9088 				}
9089 			}
9090 			found |= TCP_OPT_SACK_PRESENT;
9091 			continue;
9092 
9093 		case TCPOPT_TSTAMP:
9094 			if (len < TCPOPT_TSTAMP_LEN ||
9095 			    up[1] != TCPOPT_TSTAMP_LEN)
9096 				break;
9097 
9098 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9099 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9100 
9101 			found |= TCP_OPT_TSTAMP_PRESENT;
9102 
9103 			up += TCPOPT_TSTAMP_LEN;
9104 			continue;
9105 
9106 		default:
9107 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9108 				break;
9109 			up += up[1];
9110 			continue;
9111 		}
9112 		break;
9113 	}
9114 	return (found);
9115 }
9116 
9117 /*
9118  * Set the mss associated with a particular tcp based on its current value,
9119  * and a new one passed in. Observe minimums and maximums, and reset
9120  * other state variables that we want to view as multiples of mss.
9121  *
9122  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9123  * highwater marks etc. need to be initialized or adjusted.
9124  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9125  *    packet arrives.
9126  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9127  *    ICMP6_PACKET_TOO_BIG arrives.
9128  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9129  *    to increase the MSS to use the extra bytes available.
9130  *
9131  * Callers except tcp_paws_check() ensure that they only reduce mss.
9132  */
9133 static void
9134 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9135 {
9136 	uint32_t	mss_max;
9137 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9138 
9139 	if (tcp->tcp_ipversion == IPV4_VERSION)
9140 		mss_max = tcps->tcps_mss_max_ipv4;
9141 	else
9142 		mss_max = tcps->tcps_mss_max_ipv6;
9143 
9144 	if (mss < tcps->tcps_mss_min)
9145 		mss = tcps->tcps_mss_min;
9146 	if (mss > mss_max)
9147 		mss = mss_max;
9148 	/*
9149 	 * Unless naglim has been set by our client to
9150 	 * a non-mss value, force naglim to track mss.
9151 	 * This can help to aggregate small writes.
9152 	 */
9153 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9154 		tcp->tcp_naglim = mss;
9155 	/*
9156 	 * TCP should be able to buffer at least 4 MSS data for obvious
9157 	 * performance reason.
9158 	 */
9159 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9160 		tcp->tcp_xmit_hiwater = mss << 2;
9161 
9162 	/*
9163 	 * Set the xmit_lowater to at least twice of MSS.
9164 	 */
9165 	if ((mss << 1) > tcp->tcp_xmit_lowater)
9166 		tcp->tcp_xmit_lowater = mss << 1;
9167 
9168 	if (do_ss) {
9169 		/*
9170 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9171 		 * changing due to a reduction in MTU, presumably as a
9172 		 * result of a new path component, reset cwnd to its
9173 		 * "initial" value, as a multiple of the new mss.
9174 		 */
9175 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9176 	} else {
9177 		/*
9178 		 * Called by tcp_paws_check(), the mss increased
9179 		 * marginally to allow use of space previously taken
9180 		 * by the timestamp option. It would be inappropriate
9181 		 * to apply slow start or tcp_init_cwnd values to
9182 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9183 		 */
9184 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9185 		tcp->tcp_cwnd_cnt = 0;
9186 	}
9187 	tcp->tcp_mss = mss;
9188 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9189 }
9190 
9191 /* For /dev/tcp aka AF_INET open */
9192 static int
9193 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9194 {
9195 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9196 }
9197 
9198 /* For /dev/tcp6 aka AF_INET6 open */
9199 static int
9200 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9201 {
9202 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9203 }
9204 
9205 static conn_t *
9206 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9207     boolean_t issocket, int *errorp)
9208 {
9209 	tcp_t		*tcp = NULL;
9210 	conn_t		*connp;
9211 	int		err;
9212 	zoneid_t	zoneid;
9213 	tcp_stack_t	*tcps;
9214 	squeue_t	*sqp;
9215 
9216 	ASSERT(errorp != NULL);
9217 	/*
9218 	 * Find the proper zoneid and netstack.
9219 	 */
9220 	/*
9221 	 * Special case for install: miniroot needs to be able to
9222 	 * access files via NFS as though it were always in the
9223 	 * global zone.
9224 	 */
9225 	if (credp == kcred && nfs_global_client_only != 0) {
9226 		zoneid = GLOBAL_ZONEID;
9227 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9228 		    netstack_tcp;
9229 		ASSERT(tcps != NULL);
9230 	} else {
9231 		netstack_t *ns;
9232 
9233 		ns = netstack_find_by_cred(credp);
9234 		ASSERT(ns != NULL);
9235 		tcps = ns->netstack_tcp;
9236 		ASSERT(tcps != NULL);
9237 
9238 		/*
9239 		 * For exclusive stacks we set the zoneid to zero
9240 		 * to make TCP operate as if in the global zone.
9241 		 */
9242 		if (tcps->tcps_netstack->netstack_stackid !=
9243 		    GLOBAL_NETSTACKID)
9244 			zoneid = GLOBAL_ZONEID;
9245 		else
9246 			zoneid = crgetzoneid(credp);
9247 	}
9248 	/*
9249 	 * For stackid zero this is done from strplumb.c, but
9250 	 * non-zero stackids are handled here.
9251 	 */
9252 	if (tcps->tcps_g_q == NULL &&
9253 	    tcps->tcps_netstack->netstack_stackid !=
9254 	    GLOBAL_NETSTACKID) {
9255 		tcp_g_q_setup(tcps);
9256 	}
9257 
9258 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9259 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9260 	/*
9261 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9262 	 * so we drop it by one.
9263 	 */
9264 	netstack_rele(tcps->tcps_netstack);
9265 	if (connp == NULL) {
9266 		*errorp = ENOSR;
9267 		return (NULL);
9268 	}
9269 	connp->conn_sqp = sqp;
9270 	connp->conn_initial_sqp = connp->conn_sqp;
9271 	tcp = connp->conn_tcp;
9272 
9273 	if (isv6) {
9274 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9275 		connp->conn_send = ip_output_v6;
9276 		connp->conn_af_isv6 = B_TRUE;
9277 		connp->conn_pkt_isv6 = B_TRUE;
9278 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9279 		tcp->tcp_ipversion = IPV6_VERSION;
9280 		tcp->tcp_family = AF_INET6;
9281 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9282 	} else {
9283 		connp->conn_flags |= IPCL_TCP4;
9284 		connp->conn_send = ip_output;
9285 		connp->conn_af_isv6 = B_FALSE;
9286 		connp->conn_pkt_isv6 = B_FALSE;
9287 		tcp->tcp_ipversion = IPV4_VERSION;
9288 		tcp->tcp_family = AF_INET;
9289 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9290 	}
9291 
9292 	/*
9293 	 * TCP keeps a copy of cred for cache locality reasons but
9294 	 * we put a reference only once. If connp->conn_cred
9295 	 * becomes invalid, tcp_cred should also be set to NULL.
9296 	 */
9297 	tcp->tcp_cred = connp->conn_cred = credp;
9298 	crhold(connp->conn_cred);
9299 	tcp->tcp_cpid = curproc->p_pid;
9300 	tcp->tcp_open_time = lbolt64;
9301 	connp->conn_zoneid = zoneid;
9302 	connp->conn_mlp_type = mlptSingle;
9303 	connp->conn_ulp_labeled = !is_system_labeled();
9304 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9305 	ASSERT(tcp->tcp_tcps == tcps);
9306 
9307 	/*
9308 	 * If the caller has the process-wide flag set, then default to MAC
9309 	 * exempt mode.  This allows read-down to unlabeled hosts.
9310 	 */
9311 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9312 		connp->conn_mac_exempt = B_TRUE;
9313 
9314 	connp->conn_dev = NULL;
9315 	if (issocket) {
9316 		connp->conn_flags |= IPCL_SOCKET;
9317 		tcp->tcp_issocket = 1;
9318 	}
9319 
9320 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9321 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9322 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9323 
9324 	/* Non-zero default values */
9325 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9326 
9327 	if (q == NULL) {
9328 		/*
9329 		 * Create a helper stream for non-STREAMS socket.
9330 		 */
9331 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9332 		if (err != 0) {
9333 			ip1dbg(("tcp_create_common: create of IP helper stream "
9334 			    "failed\n"));
9335 			CONN_DEC_REF(connp);
9336 			*errorp = err;
9337 			return (NULL);
9338 		}
9339 		q = connp->conn_rq;
9340 	} else {
9341 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9342 	}
9343 
9344 	SOCK_CONNID_INIT(tcp->tcp_connid);
9345 	err = tcp_init(tcp, q);
9346 	if (err != 0) {
9347 		CONN_DEC_REF(connp);
9348 		*errorp = err;
9349 		return (NULL);
9350 	}
9351 
9352 	return (connp);
9353 }
9354 
9355 static int
9356 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9357     boolean_t isv6)
9358 {
9359 	tcp_t		*tcp = NULL;
9360 	conn_t		*connp = NULL;
9361 	int		err;
9362 	vmem_t		*minor_arena = NULL;
9363 	dev_t		conn_dev;
9364 	boolean_t	issocket;
9365 
9366 	if (q->q_ptr != NULL)
9367 		return (0);
9368 
9369 	if (sflag == MODOPEN)
9370 		return (EINVAL);
9371 
9372 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9373 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9374 		minor_arena = ip_minor_arena_la;
9375 	} else {
9376 		/*
9377 		 * Either minor numbers in the large arena were exhausted
9378 		 * or a non socket application is doing the open.
9379 		 * Try to allocate from the small arena.
9380 		 */
9381 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9382 			return (EBUSY);
9383 		}
9384 		minor_arena = ip_minor_arena_sa;
9385 	}
9386 
9387 	ASSERT(minor_arena != NULL);
9388 
9389 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9390 
9391 	if (flag & SO_FALLBACK) {
9392 		/*
9393 		 * Non streams socket needs a stream to fallback to
9394 		 */
9395 		RD(q)->q_ptr = (void *)conn_dev;
9396 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9397 		WR(q)->q_ptr = (void *)minor_arena;
9398 		qprocson(q);
9399 		return (0);
9400 	} else if (flag & SO_ACCEPTOR) {
9401 		q->q_qinfo = &tcp_acceptor_rinit;
9402 		/*
9403 		 * the conn_dev and minor_arena will be subsequently used by
9404 		 * tcp_wput_accept() and tcp_tpi_close_accept() to figure out
9405 		 * the minor device number for this connection from the q_ptr.
9406 		 */
9407 		RD(q)->q_ptr = (void *)conn_dev;
9408 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9409 		WR(q)->q_ptr = (void *)minor_arena;
9410 		qprocson(q);
9411 		return (0);
9412 	}
9413 
9414 	issocket = flag & SO_SOCKSTR;
9415 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9416 
9417 	if (connp == NULL) {
9418 		inet_minor_free(minor_arena, conn_dev);
9419 		q->q_ptr = WR(q)->q_ptr = NULL;
9420 		return (err);
9421 	}
9422 
9423 	q->q_ptr = WR(q)->q_ptr = connp;
9424 
9425 	connp->conn_dev = conn_dev;
9426 	connp->conn_minor_arena = minor_arena;
9427 
9428 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9429 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9430 
9431 	tcp = connp->conn_tcp;
9432 
9433 	if (issocket) {
9434 		WR(q)->q_qinfo = &tcp_sock_winit;
9435 	} else {
9436 #ifdef  _ILP32
9437 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9438 #else
9439 		tcp->tcp_acceptor_id = conn_dev;
9440 #endif  /* _ILP32 */
9441 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9442 	}
9443 
9444 	/*
9445 	 * Put the ref for TCP. Ref for IP was already put
9446 	 * by ipcl_conn_create. Also Make the conn_t globally
9447 	 * visible to walkers
9448 	 */
9449 	mutex_enter(&connp->conn_lock);
9450 	CONN_INC_REF_LOCKED(connp);
9451 	ASSERT(connp->conn_ref == 2);
9452 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9453 	mutex_exit(&connp->conn_lock);
9454 
9455 	qprocson(q);
9456 	return (0);
9457 }
9458 
9459 /*
9460  * Some TCP options can be "set" by requesting them in the option
9461  * buffer. This is needed for XTI feature test though we do not
9462  * allow it in general. We interpret that this mechanism is more
9463  * applicable to OSI protocols and need not be allowed in general.
9464  * This routine filters out options for which it is not allowed (most)
9465  * and lets through those (few) for which it is. [ The XTI interface
9466  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9467  * ever implemented will have to be allowed here ].
9468  */
9469 static boolean_t
9470 tcp_allow_connopt_set(int level, int name)
9471 {
9472 
9473 	switch (level) {
9474 	case IPPROTO_TCP:
9475 		switch (name) {
9476 		case TCP_NODELAY:
9477 			return (B_TRUE);
9478 		default:
9479 			return (B_FALSE);
9480 		}
9481 		/*NOTREACHED*/
9482 	default:
9483 		return (B_FALSE);
9484 	}
9485 	/*NOTREACHED*/
9486 }
9487 
9488 /*
9489  * this routine gets default values of certain options whose default
9490  * values are maintained by protocol specific code
9491  */
9492 /* ARGSUSED */
9493 int
9494 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9495 {
9496 	int32_t	*i1 = (int32_t *)ptr;
9497 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9498 
9499 	switch (level) {
9500 	case IPPROTO_TCP:
9501 		switch (name) {
9502 		case TCP_NOTIFY_THRESHOLD:
9503 			*i1 = tcps->tcps_ip_notify_interval;
9504 			break;
9505 		case TCP_ABORT_THRESHOLD:
9506 			*i1 = tcps->tcps_ip_abort_interval;
9507 			break;
9508 		case TCP_CONN_NOTIFY_THRESHOLD:
9509 			*i1 = tcps->tcps_ip_notify_cinterval;
9510 			break;
9511 		case TCP_CONN_ABORT_THRESHOLD:
9512 			*i1 = tcps->tcps_ip_abort_cinterval;
9513 			break;
9514 		default:
9515 			return (-1);
9516 		}
9517 		break;
9518 	case IPPROTO_IP:
9519 		switch (name) {
9520 		case IP_TTL:
9521 			*i1 = tcps->tcps_ipv4_ttl;
9522 			break;
9523 		default:
9524 			return (-1);
9525 		}
9526 		break;
9527 	case IPPROTO_IPV6:
9528 		switch (name) {
9529 		case IPV6_UNICAST_HOPS:
9530 			*i1 = tcps->tcps_ipv6_hoplimit;
9531 			break;
9532 		default:
9533 			return (-1);
9534 		}
9535 		break;
9536 	default:
9537 		return (-1);
9538 	}
9539 	return (sizeof (int));
9540 }
9541 
9542 static int
9543 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9544 {
9545 	int		*i1 = (int *)ptr;
9546 	tcp_t		*tcp = connp->conn_tcp;
9547 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9548 
9549 	switch (level) {
9550 	case SOL_SOCKET:
9551 		switch (name) {
9552 		case SO_LINGER:	{
9553 			struct linger *lgr = (struct linger *)ptr;
9554 
9555 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9556 			lgr->l_linger = tcp->tcp_lingertime;
9557 			}
9558 			return (sizeof (struct linger));
9559 		case SO_DEBUG:
9560 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9561 			break;
9562 		case SO_KEEPALIVE:
9563 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9564 			break;
9565 		case SO_DONTROUTE:
9566 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9567 			break;
9568 		case SO_USELOOPBACK:
9569 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9570 			break;
9571 		case SO_BROADCAST:
9572 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9573 			break;
9574 		case SO_REUSEADDR:
9575 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9576 			break;
9577 		case SO_OOBINLINE:
9578 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9579 			break;
9580 		case SO_DGRAM_ERRIND:
9581 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9582 			break;
9583 		case SO_TYPE:
9584 			*i1 = SOCK_STREAM;
9585 			break;
9586 		case SO_SNDBUF:
9587 			*i1 = tcp->tcp_xmit_hiwater;
9588 			break;
9589 		case SO_RCVBUF:
9590 			*i1 = tcp->tcp_recv_hiwater;
9591 			break;
9592 		case SO_SND_COPYAVOID:
9593 			*i1 = tcp->tcp_snd_zcopy_on ?
9594 			    SO_SND_COPYAVOID : 0;
9595 			break;
9596 		case SO_ALLZONES:
9597 			*i1 = connp->conn_allzones ? 1 : 0;
9598 			break;
9599 		case SO_ANON_MLP:
9600 			*i1 = connp->conn_anon_mlp;
9601 			break;
9602 		case SO_MAC_EXEMPT:
9603 			*i1 = connp->conn_mac_exempt;
9604 			break;
9605 		case SO_EXCLBIND:
9606 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9607 			break;
9608 		case SO_PROTOTYPE:
9609 			*i1 = IPPROTO_TCP;
9610 			break;
9611 		case SO_DOMAIN:
9612 			*i1 = tcp->tcp_family;
9613 			break;
9614 		case SO_ACCEPTCONN:
9615 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9616 		default:
9617 			return (-1);
9618 		}
9619 		break;
9620 	case IPPROTO_TCP:
9621 		switch (name) {
9622 		case TCP_NODELAY:
9623 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9624 			break;
9625 		case TCP_MAXSEG:
9626 			*i1 = tcp->tcp_mss;
9627 			break;
9628 		case TCP_NOTIFY_THRESHOLD:
9629 			*i1 = (int)tcp->tcp_first_timer_threshold;
9630 			break;
9631 		case TCP_ABORT_THRESHOLD:
9632 			*i1 = tcp->tcp_second_timer_threshold;
9633 			break;
9634 		case TCP_CONN_NOTIFY_THRESHOLD:
9635 			*i1 = tcp->tcp_first_ctimer_threshold;
9636 			break;
9637 		case TCP_CONN_ABORT_THRESHOLD:
9638 			*i1 = tcp->tcp_second_ctimer_threshold;
9639 			break;
9640 		case TCP_RECVDSTADDR:
9641 			*i1 = tcp->tcp_recvdstaddr;
9642 			break;
9643 		case TCP_ANONPRIVBIND:
9644 			*i1 = tcp->tcp_anon_priv_bind;
9645 			break;
9646 		case TCP_EXCLBIND:
9647 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9648 			break;
9649 		case TCP_INIT_CWND:
9650 			*i1 = tcp->tcp_init_cwnd;
9651 			break;
9652 		case TCP_KEEPALIVE_THRESHOLD:
9653 			*i1 = tcp->tcp_ka_interval;
9654 			break;
9655 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9656 			*i1 = tcp->tcp_ka_abort_thres;
9657 			break;
9658 		case TCP_CORK:
9659 			*i1 = tcp->tcp_cork;
9660 			break;
9661 		default:
9662 			return (-1);
9663 		}
9664 		break;
9665 	case IPPROTO_IP:
9666 		if (tcp->tcp_family != AF_INET)
9667 			return (-1);
9668 		switch (name) {
9669 		case IP_OPTIONS:
9670 		case T_IP_OPTIONS: {
9671 			/*
9672 			 * This is compatible with BSD in that in only return
9673 			 * the reverse source route with the final destination
9674 			 * as the last entry. The first 4 bytes of the option
9675 			 * will contain the final destination.
9676 			 */
9677 			int	opt_len;
9678 
9679 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9680 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9681 			ASSERT(opt_len >= 0);
9682 			/* Caller ensures enough space */
9683 			if (opt_len > 0) {
9684 				/*
9685 				 * TODO: Do we have to handle getsockopt on an
9686 				 * initiator as well?
9687 				 */
9688 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9689 			}
9690 			return (0);
9691 			}
9692 		case IP_TOS:
9693 		case T_IP_TOS:
9694 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9695 			break;
9696 		case IP_TTL:
9697 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9698 			break;
9699 		case IP_NEXTHOP:
9700 			/* Handled at IP level */
9701 			return (-EINVAL);
9702 		default:
9703 			return (-1);
9704 		}
9705 		break;
9706 	case IPPROTO_IPV6:
9707 		/*
9708 		 * IPPROTO_IPV6 options are only supported for sockets
9709 		 * that are using IPv6 on the wire.
9710 		 */
9711 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9712 			return (-1);
9713 		}
9714 		switch (name) {
9715 		case IPV6_UNICAST_HOPS:
9716 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9717 			break;	/* goto sizeof (int) option return */
9718 		case IPV6_BOUND_IF:
9719 			/* Zero if not set */
9720 			*i1 = tcp->tcp_bound_if;
9721 			break;	/* goto sizeof (int) option return */
9722 		case IPV6_RECVPKTINFO:
9723 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9724 				*i1 = 1;
9725 			else
9726 				*i1 = 0;
9727 			break;	/* goto sizeof (int) option return */
9728 		case IPV6_RECVTCLASS:
9729 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9730 				*i1 = 1;
9731 			else
9732 				*i1 = 0;
9733 			break;	/* goto sizeof (int) option return */
9734 		case IPV6_RECVHOPLIMIT:
9735 			if (tcp->tcp_ipv6_recvancillary &
9736 			    TCP_IPV6_RECVHOPLIMIT)
9737 				*i1 = 1;
9738 			else
9739 				*i1 = 0;
9740 			break;	/* goto sizeof (int) option return */
9741 		case IPV6_RECVHOPOPTS:
9742 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9743 				*i1 = 1;
9744 			else
9745 				*i1 = 0;
9746 			break;	/* goto sizeof (int) option return */
9747 		case IPV6_RECVDSTOPTS:
9748 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9749 				*i1 = 1;
9750 			else
9751 				*i1 = 0;
9752 			break;	/* goto sizeof (int) option return */
9753 		case _OLD_IPV6_RECVDSTOPTS:
9754 			if (tcp->tcp_ipv6_recvancillary &
9755 			    TCP_OLD_IPV6_RECVDSTOPTS)
9756 				*i1 = 1;
9757 			else
9758 				*i1 = 0;
9759 			break;	/* goto sizeof (int) option return */
9760 		case IPV6_RECVRTHDR:
9761 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9762 				*i1 = 1;
9763 			else
9764 				*i1 = 0;
9765 			break;	/* goto sizeof (int) option return */
9766 		case IPV6_RECVRTHDRDSTOPTS:
9767 			if (tcp->tcp_ipv6_recvancillary &
9768 			    TCP_IPV6_RECVRTDSTOPTS)
9769 				*i1 = 1;
9770 			else
9771 				*i1 = 0;
9772 			break;	/* goto sizeof (int) option return */
9773 		case IPV6_PKTINFO: {
9774 			/* XXX assumes that caller has room for max size! */
9775 			struct in6_pktinfo *pkti;
9776 
9777 			pkti = (struct in6_pktinfo *)ptr;
9778 			if (ipp->ipp_fields & IPPF_IFINDEX)
9779 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9780 			else
9781 				pkti->ipi6_ifindex = 0;
9782 			if (ipp->ipp_fields & IPPF_ADDR)
9783 				pkti->ipi6_addr = ipp->ipp_addr;
9784 			else
9785 				pkti->ipi6_addr = ipv6_all_zeros;
9786 			return (sizeof (struct in6_pktinfo));
9787 		}
9788 		case IPV6_TCLASS:
9789 			if (ipp->ipp_fields & IPPF_TCLASS)
9790 				*i1 = ipp->ipp_tclass;
9791 			else
9792 				*i1 = IPV6_FLOW_TCLASS(
9793 				    IPV6_DEFAULT_VERS_AND_FLOW);
9794 			break;	/* goto sizeof (int) option return */
9795 		case IPV6_NEXTHOP: {
9796 			sin6_t *sin6 = (sin6_t *)ptr;
9797 
9798 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9799 				return (0);
9800 			*sin6 = sin6_null;
9801 			sin6->sin6_family = AF_INET6;
9802 			sin6->sin6_addr = ipp->ipp_nexthop;
9803 			return (sizeof (sin6_t));
9804 		}
9805 		case IPV6_HOPOPTS:
9806 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9807 				return (0);
9808 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9809 				return (0);
9810 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9811 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9812 			if (tcp->tcp_label_len > 0) {
9813 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9814 				ptr[1] = (ipp->ipp_hopoptslen -
9815 				    tcp->tcp_label_len + 7) / 8 - 1;
9816 			}
9817 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9818 		case IPV6_RTHDRDSTOPTS:
9819 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9820 				return (0);
9821 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9822 			return (ipp->ipp_rtdstoptslen);
9823 		case IPV6_RTHDR:
9824 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9825 				return (0);
9826 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9827 			return (ipp->ipp_rthdrlen);
9828 		case IPV6_DSTOPTS:
9829 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9830 				return (0);
9831 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9832 			return (ipp->ipp_dstoptslen);
9833 		case IPV6_SRC_PREFERENCES:
9834 			return (ip6_get_src_preferences(connp,
9835 			    (uint32_t *)ptr));
9836 		case IPV6_PATHMTU: {
9837 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9838 
9839 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9840 				return (-1);
9841 
9842 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9843 			    connp->conn_fport, mtuinfo,
9844 			    connp->conn_netstack));
9845 		}
9846 		default:
9847 			return (-1);
9848 		}
9849 		break;
9850 	default:
9851 		return (-1);
9852 	}
9853 	return (sizeof (int));
9854 }
9855 
9856 /*
9857  * TCP routine to get the values of options.
9858  */
9859 int
9860 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9861 {
9862 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9863 }
9864 
9865 /* returns UNIX error, the optlen is a value-result arg */
9866 int
9867 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9868     void *optvalp, socklen_t *optlen, cred_t *cr)
9869 {
9870 	conn_t		*connp = (conn_t *)proto_handle;
9871 	squeue_t	*sqp = connp->conn_sqp;
9872 	int		error;
9873 	t_uscalar_t	max_optbuf_len;
9874 	void		*optvalp_buf;
9875 	int		len;
9876 
9877 	ASSERT(connp->conn_upper_handle != NULL);
9878 
9879 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9880 	    tcp_opt_obj.odb_opt_des_arr,
9881 	    tcp_opt_obj.odb_opt_arr_cnt,
9882 	    tcp_opt_obj.odb_topmost_tpiprovider,
9883 	    B_FALSE, B_TRUE, cr);
9884 	if (error != 0) {
9885 		if (error < 0) {
9886 			error = proto_tlitosyserr(-error);
9887 		}
9888 		return (error);
9889 	}
9890 
9891 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9892 
9893 	error = squeue_synch_enter(sqp, connp, NULL);
9894 	if (error == ENOMEM) {
9895 		return (ENOMEM);
9896 	}
9897 
9898 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9899 	squeue_synch_exit(sqp, connp);
9900 
9901 	if (len < 0) {
9902 		/*
9903 		 * Pass on to IP
9904 		 */
9905 		kmem_free(optvalp_buf, max_optbuf_len);
9906 		return (ip_get_options(connp, level, option_name,
9907 		    optvalp, optlen, cr));
9908 	} else {
9909 		/*
9910 		 * update optlen and copy option value
9911 		 */
9912 		t_uscalar_t size = MIN(len, *optlen);
9913 		bcopy(optvalp_buf, optvalp, size);
9914 		bcopy(&size, optlen, sizeof (size));
9915 
9916 		kmem_free(optvalp_buf, max_optbuf_len);
9917 		return (0);
9918 	}
9919 }
9920 
9921 /*
9922  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9923  * Parameters are assumed to be verified by the caller.
9924  */
9925 /* ARGSUSED */
9926 int
9927 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9928     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9929     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9930 {
9931 	tcp_t	*tcp = connp->conn_tcp;
9932 	int	*i1 = (int *)invalp;
9933 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9934 	boolean_t checkonly;
9935 	int	reterr;
9936 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9937 
9938 	switch (optset_context) {
9939 	case SETFN_OPTCOM_CHECKONLY:
9940 		checkonly = B_TRUE;
9941 		/*
9942 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9943 		 * inlen != 0 implies value supplied and
9944 		 * 	we have to "pretend" to set it.
9945 		 * inlen == 0 implies that there is no
9946 		 * 	value part in T_CHECK request and just validation
9947 		 * done elsewhere should be enough, we just return here.
9948 		 */
9949 		if (inlen == 0) {
9950 			*outlenp = 0;
9951 			return (0);
9952 		}
9953 		break;
9954 	case SETFN_OPTCOM_NEGOTIATE:
9955 		checkonly = B_FALSE;
9956 		break;
9957 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9958 	case SETFN_CONN_NEGOTIATE:
9959 		checkonly = B_FALSE;
9960 		/*
9961 		 * Negotiating local and "association-related" options
9962 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9963 		 * primitives is allowed by XTI, but we choose
9964 		 * to not implement this style negotiation for Internet
9965 		 * protocols (We interpret it is a must for OSI world but
9966 		 * optional for Internet protocols) for all options.
9967 		 * [ Will do only for the few options that enable test
9968 		 * suites that our XTI implementation of this feature
9969 		 * works for transports that do allow it ]
9970 		 */
9971 		if (!tcp_allow_connopt_set(level, name)) {
9972 			*outlenp = 0;
9973 			return (EINVAL);
9974 		}
9975 		break;
9976 	default:
9977 		/*
9978 		 * We should never get here
9979 		 */
9980 		*outlenp = 0;
9981 		return (EINVAL);
9982 	}
9983 
9984 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9985 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9986 
9987 	/*
9988 	 * For TCP, we should have no ancillary data sent down
9989 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9990 	 * has to be zero.
9991 	 */
9992 	ASSERT(thisdg_attrs == NULL);
9993 
9994 	/*
9995 	 * For fixed length options, no sanity check
9996 	 * of passed in length is done. It is assumed *_optcom_req()
9997 	 * routines do the right thing.
9998 	 */
9999 	switch (level) {
10000 	case SOL_SOCKET:
10001 		switch (name) {
10002 		case SO_LINGER: {
10003 			struct linger *lgr = (struct linger *)invalp;
10004 
10005 			if (!checkonly) {
10006 				if (lgr->l_onoff) {
10007 					tcp->tcp_linger = 1;
10008 					tcp->tcp_lingertime = lgr->l_linger;
10009 				} else {
10010 					tcp->tcp_linger = 0;
10011 					tcp->tcp_lingertime = 0;
10012 				}
10013 				/* struct copy */
10014 				*(struct linger *)outvalp = *lgr;
10015 			} else {
10016 				if (!lgr->l_onoff) {
10017 					((struct linger *)
10018 					    outvalp)->l_onoff = 0;
10019 					((struct linger *)
10020 					    outvalp)->l_linger = 0;
10021 				} else {
10022 					/* struct copy */
10023 					*(struct linger *)outvalp = *lgr;
10024 				}
10025 			}
10026 			*outlenp = sizeof (struct linger);
10027 			return (0);
10028 		}
10029 		case SO_DEBUG:
10030 			if (!checkonly)
10031 				tcp->tcp_debug = onoff;
10032 			break;
10033 		case SO_KEEPALIVE:
10034 			if (checkonly) {
10035 				/* check only case */
10036 				break;
10037 			}
10038 
10039 			if (!onoff) {
10040 				if (tcp->tcp_ka_enabled) {
10041 					if (tcp->tcp_ka_tid != 0) {
10042 						(void) TCP_TIMER_CANCEL(tcp,
10043 						    tcp->tcp_ka_tid);
10044 						tcp->tcp_ka_tid = 0;
10045 					}
10046 					tcp->tcp_ka_enabled = 0;
10047 				}
10048 				break;
10049 			}
10050 			if (!tcp->tcp_ka_enabled) {
10051 				/* Crank up the keepalive timer */
10052 				tcp->tcp_ka_last_intrvl = 0;
10053 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10054 				    tcp_keepalive_killer,
10055 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10056 				tcp->tcp_ka_enabled = 1;
10057 			}
10058 			break;
10059 		case SO_DONTROUTE:
10060 			/*
10061 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10062 			 * only of interest to IP.  We track them here only so
10063 			 * that we can report their current value.
10064 			 */
10065 			if (!checkonly) {
10066 				tcp->tcp_dontroute = onoff;
10067 				tcp->tcp_connp->conn_dontroute = onoff;
10068 			}
10069 			break;
10070 		case SO_USELOOPBACK:
10071 			if (!checkonly) {
10072 				tcp->tcp_useloopback = onoff;
10073 				tcp->tcp_connp->conn_loopback = onoff;
10074 			}
10075 			break;
10076 		case SO_BROADCAST:
10077 			if (!checkonly) {
10078 				tcp->tcp_broadcast = onoff;
10079 				tcp->tcp_connp->conn_broadcast = onoff;
10080 			}
10081 			break;
10082 		case SO_REUSEADDR:
10083 			if (!checkonly) {
10084 				tcp->tcp_reuseaddr = onoff;
10085 				tcp->tcp_connp->conn_reuseaddr = onoff;
10086 			}
10087 			break;
10088 		case SO_OOBINLINE:
10089 			if (!checkonly) {
10090 				tcp->tcp_oobinline = onoff;
10091 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10092 					proto_set_rx_oob_opt(connp, onoff);
10093 			}
10094 			break;
10095 		case SO_DGRAM_ERRIND:
10096 			if (!checkonly)
10097 				tcp->tcp_dgram_errind = onoff;
10098 			break;
10099 		case SO_SNDBUF: {
10100 			if (*i1 > tcps->tcps_max_buf) {
10101 				*outlenp = 0;
10102 				return (ENOBUFS);
10103 			}
10104 			if (checkonly)
10105 				break;
10106 
10107 			tcp->tcp_xmit_hiwater = *i1;
10108 			if (tcps->tcps_snd_lowat_fraction != 0)
10109 				tcp->tcp_xmit_lowater =
10110 				    tcp->tcp_xmit_hiwater /
10111 				    tcps->tcps_snd_lowat_fraction;
10112 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10113 			/*
10114 			 * If we are flow-controlled, recheck the condition.
10115 			 * There are apps that increase SO_SNDBUF size when
10116 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10117 			 * control condition to be lifted right away.
10118 			 */
10119 			mutex_enter(&tcp->tcp_non_sq_lock);
10120 			if (tcp->tcp_flow_stopped &&
10121 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10122 				tcp_clrqfull(tcp);
10123 			}
10124 			mutex_exit(&tcp->tcp_non_sq_lock);
10125 			break;
10126 		}
10127 		case SO_RCVBUF:
10128 			if (*i1 > tcps->tcps_max_buf) {
10129 				*outlenp = 0;
10130 				return (ENOBUFS);
10131 			}
10132 			/* Silently ignore zero */
10133 			if (!checkonly && *i1 != 0) {
10134 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10135 				(void) tcp_rwnd_set(tcp, *i1);
10136 			}
10137 			/*
10138 			 * XXX should we return the rwnd here
10139 			 * and tcp_opt_get ?
10140 			 */
10141 			break;
10142 		case SO_SND_COPYAVOID:
10143 			if (!checkonly) {
10144 				/* we only allow enable at most once for now */
10145 				if (tcp->tcp_loopback ||
10146 				    (tcp->tcp_kssl_ctx != NULL) ||
10147 				    (!tcp->tcp_snd_zcopy_aware &&
10148 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10149 					*outlenp = 0;
10150 					return (EOPNOTSUPP);
10151 				}
10152 				tcp->tcp_snd_zcopy_aware = 1;
10153 			}
10154 			break;
10155 		case SO_RCVTIMEO:
10156 		case SO_SNDTIMEO:
10157 			/*
10158 			 * Pass these two options in order for third part
10159 			 * protocol usage. Here just return directly.
10160 			 */
10161 			return (0);
10162 		case SO_ALLZONES:
10163 			/* Pass option along to IP level for handling */
10164 			return (-EINVAL);
10165 		case SO_ANON_MLP:
10166 			/* Pass option along to IP level for handling */
10167 			return (-EINVAL);
10168 		case SO_MAC_EXEMPT:
10169 			/* Pass option along to IP level for handling */
10170 			return (-EINVAL);
10171 		case SO_EXCLBIND:
10172 			if (!checkonly)
10173 				tcp->tcp_exclbind = onoff;
10174 			break;
10175 		default:
10176 			*outlenp = 0;
10177 			return (EINVAL);
10178 		}
10179 		break;
10180 	case IPPROTO_TCP:
10181 		switch (name) {
10182 		case TCP_NODELAY:
10183 			if (!checkonly)
10184 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10185 			break;
10186 		case TCP_NOTIFY_THRESHOLD:
10187 			if (!checkonly)
10188 				tcp->tcp_first_timer_threshold = *i1;
10189 			break;
10190 		case TCP_ABORT_THRESHOLD:
10191 			if (!checkonly)
10192 				tcp->tcp_second_timer_threshold = *i1;
10193 			break;
10194 		case TCP_CONN_NOTIFY_THRESHOLD:
10195 			if (!checkonly)
10196 				tcp->tcp_first_ctimer_threshold = *i1;
10197 			break;
10198 		case TCP_CONN_ABORT_THRESHOLD:
10199 			if (!checkonly)
10200 				tcp->tcp_second_ctimer_threshold = *i1;
10201 			break;
10202 		case TCP_RECVDSTADDR:
10203 			if (tcp->tcp_state > TCPS_LISTEN)
10204 				return (EOPNOTSUPP);
10205 			if (!checkonly)
10206 				tcp->tcp_recvdstaddr = onoff;
10207 			break;
10208 		case TCP_ANONPRIVBIND:
10209 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10210 			    IPPROTO_TCP)) != 0) {
10211 				*outlenp = 0;
10212 				return (reterr);
10213 			}
10214 			if (!checkonly) {
10215 				tcp->tcp_anon_priv_bind = onoff;
10216 			}
10217 			break;
10218 		case TCP_EXCLBIND:
10219 			if (!checkonly)
10220 				tcp->tcp_exclbind = onoff;
10221 			break;	/* goto sizeof (int) option return */
10222 		case TCP_INIT_CWND: {
10223 			uint32_t init_cwnd = *((uint32_t *)invalp);
10224 
10225 			if (checkonly)
10226 				break;
10227 
10228 			/*
10229 			 * Only allow socket with network configuration
10230 			 * privilege to set the initial cwnd to be larger
10231 			 * than allowed by RFC 3390.
10232 			 */
10233 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10234 				tcp->tcp_init_cwnd = init_cwnd;
10235 				break;
10236 			}
10237 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10238 				*outlenp = 0;
10239 				return (reterr);
10240 			}
10241 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10242 				*outlenp = 0;
10243 				return (EINVAL);
10244 			}
10245 			tcp->tcp_init_cwnd = init_cwnd;
10246 			break;
10247 		}
10248 		case TCP_KEEPALIVE_THRESHOLD:
10249 			if (checkonly)
10250 				break;
10251 
10252 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10253 			    *i1 > tcps->tcps_keepalive_interval_high) {
10254 				*outlenp = 0;
10255 				return (EINVAL);
10256 			}
10257 			if (*i1 != tcp->tcp_ka_interval) {
10258 				tcp->tcp_ka_interval = *i1;
10259 				/*
10260 				 * Check if we need to restart the
10261 				 * keepalive timer.
10262 				 */
10263 				if (tcp->tcp_ka_tid != 0) {
10264 					ASSERT(tcp->tcp_ka_enabled);
10265 					(void) TCP_TIMER_CANCEL(tcp,
10266 					    tcp->tcp_ka_tid);
10267 					tcp->tcp_ka_last_intrvl = 0;
10268 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10269 					    tcp_keepalive_killer,
10270 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10271 				}
10272 			}
10273 			break;
10274 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10275 			if (!checkonly) {
10276 				if (*i1 <
10277 				    tcps->tcps_keepalive_abort_interval_low ||
10278 				    *i1 >
10279 				    tcps->tcps_keepalive_abort_interval_high) {
10280 					*outlenp = 0;
10281 					return (EINVAL);
10282 				}
10283 				tcp->tcp_ka_abort_thres = *i1;
10284 			}
10285 			break;
10286 		case TCP_CORK:
10287 			if (!checkonly) {
10288 				/*
10289 				 * if tcp->tcp_cork was set and is now
10290 				 * being unset, we have to make sure that
10291 				 * the remaining data gets sent out. Also
10292 				 * unset tcp->tcp_cork so that tcp_wput_data()
10293 				 * can send data even if it is less than mss
10294 				 */
10295 				if (tcp->tcp_cork && onoff == 0 &&
10296 				    tcp->tcp_unsent > 0) {
10297 					tcp->tcp_cork = B_FALSE;
10298 					tcp_wput_data(tcp, NULL, B_FALSE);
10299 				}
10300 				tcp->tcp_cork = onoff;
10301 			}
10302 			break;
10303 		default:
10304 			*outlenp = 0;
10305 			return (EINVAL);
10306 		}
10307 		break;
10308 	case IPPROTO_IP:
10309 		if (tcp->tcp_family != AF_INET) {
10310 			*outlenp = 0;
10311 			return (ENOPROTOOPT);
10312 		}
10313 		switch (name) {
10314 		case IP_OPTIONS:
10315 		case T_IP_OPTIONS:
10316 			reterr = tcp_opt_set_header(tcp, checkonly,
10317 			    invalp, inlen);
10318 			if (reterr) {
10319 				*outlenp = 0;
10320 				return (reterr);
10321 			}
10322 			/* OK return - copy input buffer into output buffer */
10323 			if (invalp != outvalp) {
10324 				/* don't trust bcopy for identical src/dst */
10325 				bcopy(invalp, outvalp, inlen);
10326 			}
10327 			*outlenp = inlen;
10328 			return (0);
10329 		case IP_TOS:
10330 		case T_IP_TOS:
10331 			if (!checkonly) {
10332 				tcp->tcp_ipha->ipha_type_of_service =
10333 				    (uchar_t)*i1;
10334 				tcp->tcp_tos = (uchar_t)*i1;
10335 			}
10336 			break;
10337 		case IP_TTL:
10338 			if (!checkonly) {
10339 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10340 				tcp->tcp_ttl = (uchar_t)*i1;
10341 			}
10342 			break;
10343 		case IP_BOUND_IF:
10344 		case IP_NEXTHOP:
10345 			/* Handled at the IP level */
10346 			return (-EINVAL);
10347 		case IP_SEC_OPT:
10348 			/*
10349 			 * We should not allow policy setting after
10350 			 * we start listening for connections.
10351 			 */
10352 			if (tcp->tcp_state == TCPS_LISTEN) {
10353 				return (EINVAL);
10354 			} else {
10355 				/* Handled at the IP level */
10356 				return (-EINVAL);
10357 			}
10358 		default:
10359 			*outlenp = 0;
10360 			return (EINVAL);
10361 		}
10362 		break;
10363 	case IPPROTO_IPV6: {
10364 		ip6_pkt_t		*ipp;
10365 
10366 		/*
10367 		 * IPPROTO_IPV6 options are only supported for sockets
10368 		 * that are using IPv6 on the wire.
10369 		 */
10370 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10371 			*outlenp = 0;
10372 			return (ENOPROTOOPT);
10373 		}
10374 		/*
10375 		 * Only sticky options; no ancillary data
10376 		 */
10377 		ipp = &tcp->tcp_sticky_ipp;
10378 
10379 		switch (name) {
10380 		case IPV6_UNICAST_HOPS:
10381 			/* -1 means use default */
10382 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10383 				*outlenp = 0;
10384 				return (EINVAL);
10385 			}
10386 			if (!checkonly) {
10387 				if (*i1 == -1) {
10388 					tcp->tcp_ip6h->ip6_hops =
10389 					    ipp->ipp_unicast_hops =
10390 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10391 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10392 					/* Pass modified value to IP. */
10393 					*i1 = tcp->tcp_ip6h->ip6_hops;
10394 				} else {
10395 					tcp->tcp_ip6h->ip6_hops =
10396 					    ipp->ipp_unicast_hops =
10397 					    (uint8_t)*i1;
10398 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10399 				}
10400 				reterr = tcp_build_hdrs(tcp);
10401 				if (reterr != 0)
10402 					return (reterr);
10403 			}
10404 			break;
10405 		case IPV6_BOUND_IF:
10406 			if (!checkonly) {
10407 				tcp->tcp_bound_if = *i1;
10408 				PASS_OPT_TO_IP(connp);
10409 			}
10410 			break;
10411 		/*
10412 		 * Set boolean switches for ancillary data delivery
10413 		 */
10414 		case IPV6_RECVPKTINFO:
10415 			if (!checkonly) {
10416 				if (onoff)
10417 					tcp->tcp_ipv6_recvancillary |=
10418 					    TCP_IPV6_RECVPKTINFO;
10419 				else
10420 					tcp->tcp_ipv6_recvancillary &=
10421 					    ~TCP_IPV6_RECVPKTINFO;
10422 				/* Force it to be sent up with the next msg */
10423 				tcp->tcp_recvifindex = 0;
10424 				PASS_OPT_TO_IP(connp);
10425 			}
10426 			break;
10427 		case IPV6_RECVTCLASS:
10428 			if (!checkonly) {
10429 				if (onoff)
10430 					tcp->tcp_ipv6_recvancillary |=
10431 					    TCP_IPV6_RECVTCLASS;
10432 				else
10433 					tcp->tcp_ipv6_recvancillary &=
10434 					    ~TCP_IPV6_RECVTCLASS;
10435 				PASS_OPT_TO_IP(connp);
10436 			}
10437 			break;
10438 		case IPV6_RECVHOPLIMIT:
10439 			if (!checkonly) {
10440 				if (onoff)
10441 					tcp->tcp_ipv6_recvancillary |=
10442 					    TCP_IPV6_RECVHOPLIMIT;
10443 				else
10444 					tcp->tcp_ipv6_recvancillary &=
10445 					    ~TCP_IPV6_RECVHOPLIMIT;
10446 				/* Force it to be sent up with the next msg */
10447 				tcp->tcp_recvhops = 0xffffffffU;
10448 				PASS_OPT_TO_IP(connp);
10449 			}
10450 			break;
10451 		case IPV6_RECVHOPOPTS:
10452 			if (!checkonly) {
10453 				if (onoff)
10454 					tcp->tcp_ipv6_recvancillary |=
10455 					    TCP_IPV6_RECVHOPOPTS;
10456 				else
10457 					tcp->tcp_ipv6_recvancillary &=
10458 					    ~TCP_IPV6_RECVHOPOPTS;
10459 				PASS_OPT_TO_IP(connp);
10460 			}
10461 			break;
10462 		case IPV6_RECVDSTOPTS:
10463 			if (!checkonly) {
10464 				if (onoff)
10465 					tcp->tcp_ipv6_recvancillary |=
10466 					    TCP_IPV6_RECVDSTOPTS;
10467 				else
10468 					tcp->tcp_ipv6_recvancillary &=
10469 					    ~TCP_IPV6_RECVDSTOPTS;
10470 				PASS_OPT_TO_IP(connp);
10471 			}
10472 			break;
10473 		case _OLD_IPV6_RECVDSTOPTS:
10474 			if (!checkonly) {
10475 				if (onoff)
10476 					tcp->tcp_ipv6_recvancillary |=
10477 					    TCP_OLD_IPV6_RECVDSTOPTS;
10478 				else
10479 					tcp->tcp_ipv6_recvancillary &=
10480 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10481 			}
10482 			break;
10483 		case IPV6_RECVRTHDR:
10484 			if (!checkonly) {
10485 				if (onoff)
10486 					tcp->tcp_ipv6_recvancillary |=
10487 					    TCP_IPV6_RECVRTHDR;
10488 				else
10489 					tcp->tcp_ipv6_recvancillary &=
10490 					    ~TCP_IPV6_RECVRTHDR;
10491 				PASS_OPT_TO_IP(connp);
10492 			}
10493 			break;
10494 		case IPV6_RECVRTHDRDSTOPTS:
10495 			if (!checkonly) {
10496 				if (onoff)
10497 					tcp->tcp_ipv6_recvancillary |=
10498 					    TCP_IPV6_RECVRTDSTOPTS;
10499 				else
10500 					tcp->tcp_ipv6_recvancillary &=
10501 					    ~TCP_IPV6_RECVRTDSTOPTS;
10502 				PASS_OPT_TO_IP(connp);
10503 			}
10504 			break;
10505 		case IPV6_PKTINFO:
10506 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10507 				return (EINVAL);
10508 			if (checkonly)
10509 				break;
10510 
10511 			if (inlen == 0) {
10512 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10513 			} else {
10514 				struct in6_pktinfo *pkti;
10515 
10516 				pkti = (struct in6_pktinfo *)invalp;
10517 				/*
10518 				 * RFC 3542 states that ipi6_addr must be
10519 				 * the unspecified address when setting the
10520 				 * IPV6_PKTINFO sticky socket option on a
10521 				 * TCP socket.
10522 				 */
10523 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10524 					return (EINVAL);
10525 				/*
10526 				 * IP will validate the source address and
10527 				 * interface index.
10528 				 */
10529 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10530 					reterr = ip_set_options(tcp->tcp_connp,
10531 					    level, name, invalp, inlen, cr);
10532 				} else {
10533 					reterr = ip6_set_pktinfo(cr,
10534 					    tcp->tcp_connp, pkti);
10535 				}
10536 				if (reterr != 0)
10537 					return (reterr);
10538 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10539 				ipp->ipp_addr = pkti->ipi6_addr;
10540 				if (ipp->ipp_ifindex != 0)
10541 					ipp->ipp_fields |= IPPF_IFINDEX;
10542 				else
10543 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10544 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10545 					ipp->ipp_fields |= IPPF_ADDR;
10546 				else
10547 					ipp->ipp_fields &= ~IPPF_ADDR;
10548 			}
10549 			reterr = tcp_build_hdrs(tcp);
10550 			if (reterr != 0)
10551 				return (reterr);
10552 			break;
10553 		case IPV6_TCLASS:
10554 			if (inlen != 0 && inlen != sizeof (int))
10555 				return (EINVAL);
10556 			if (checkonly)
10557 				break;
10558 
10559 			if (inlen == 0) {
10560 				ipp->ipp_fields &= ~IPPF_TCLASS;
10561 			} else {
10562 				if (*i1 > 255 || *i1 < -1)
10563 					return (EINVAL);
10564 				if (*i1 == -1) {
10565 					ipp->ipp_tclass = 0;
10566 					*i1 = 0;
10567 				} else {
10568 					ipp->ipp_tclass = *i1;
10569 				}
10570 				ipp->ipp_fields |= IPPF_TCLASS;
10571 			}
10572 			reterr = tcp_build_hdrs(tcp);
10573 			if (reterr != 0)
10574 				return (reterr);
10575 			break;
10576 		case IPV6_NEXTHOP:
10577 			/*
10578 			 * IP will verify that the nexthop is reachable
10579 			 * and fail for sticky options.
10580 			 */
10581 			if (inlen != 0 && inlen != sizeof (sin6_t))
10582 				return (EINVAL);
10583 			if (checkonly)
10584 				break;
10585 
10586 			if (inlen == 0) {
10587 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10588 			} else {
10589 				sin6_t *sin6 = (sin6_t *)invalp;
10590 
10591 				if (sin6->sin6_family != AF_INET6)
10592 					return (EAFNOSUPPORT);
10593 				if (IN6_IS_ADDR_V4MAPPED(
10594 				    &sin6->sin6_addr))
10595 					return (EADDRNOTAVAIL);
10596 				ipp->ipp_nexthop = sin6->sin6_addr;
10597 				if (!IN6_IS_ADDR_UNSPECIFIED(
10598 				    &ipp->ipp_nexthop))
10599 					ipp->ipp_fields |= IPPF_NEXTHOP;
10600 				else
10601 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10602 			}
10603 			reterr = tcp_build_hdrs(tcp);
10604 			if (reterr != 0)
10605 				return (reterr);
10606 			PASS_OPT_TO_IP(connp);
10607 			break;
10608 		case IPV6_HOPOPTS: {
10609 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10610 
10611 			/*
10612 			 * Sanity checks - minimum size, size a multiple of
10613 			 * eight bytes, and matching size passed in.
10614 			 */
10615 			if (inlen != 0 &&
10616 			    inlen != (8 * (hopts->ip6h_len + 1)))
10617 				return (EINVAL);
10618 
10619 			if (checkonly)
10620 				break;
10621 
10622 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10623 			    (uchar_t **)&ipp->ipp_hopopts,
10624 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10625 			if (reterr != 0)
10626 				return (reterr);
10627 			if (ipp->ipp_hopoptslen == 0)
10628 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10629 			else
10630 				ipp->ipp_fields |= IPPF_HOPOPTS;
10631 			reterr = tcp_build_hdrs(tcp);
10632 			if (reterr != 0)
10633 				return (reterr);
10634 			break;
10635 		}
10636 		case IPV6_RTHDRDSTOPTS: {
10637 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10638 
10639 			/*
10640 			 * Sanity checks - minimum size, size a multiple of
10641 			 * eight bytes, and matching size passed in.
10642 			 */
10643 			if (inlen != 0 &&
10644 			    inlen != (8 * (dopts->ip6d_len + 1)))
10645 				return (EINVAL);
10646 
10647 			if (checkonly)
10648 				break;
10649 
10650 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10651 			    (uchar_t **)&ipp->ipp_rtdstopts,
10652 			    &ipp->ipp_rtdstoptslen, 0);
10653 			if (reterr != 0)
10654 				return (reterr);
10655 			if (ipp->ipp_rtdstoptslen == 0)
10656 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10657 			else
10658 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10659 			reterr = tcp_build_hdrs(tcp);
10660 			if (reterr != 0)
10661 				return (reterr);
10662 			break;
10663 		}
10664 		case IPV6_DSTOPTS: {
10665 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10666 
10667 			/*
10668 			 * Sanity checks - minimum size, size a multiple of
10669 			 * eight bytes, and matching size passed in.
10670 			 */
10671 			if (inlen != 0 &&
10672 			    inlen != (8 * (dopts->ip6d_len + 1)))
10673 				return (EINVAL);
10674 
10675 			if (checkonly)
10676 				break;
10677 
10678 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10679 			    (uchar_t **)&ipp->ipp_dstopts,
10680 			    &ipp->ipp_dstoptslen, 0);
10681 			if (reterr != 0)
10682 				return (reterr);
10683 			if (ipp->ipp_dstoptslen == 0)
10684 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10685 			else
10686 				ipp->ipp_fields |= IPPF_DSTOPTS;
10687 			reterr = tcp_build_hdrs(tcp);
10688 			if (reterr != 0)
10689 				return (reterr);
10690 			break;
10691 		}
10692 		case IPV6_RTHDR: {
10693 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10694 
10695 			/*
10696 			 * Sanity checks - minimum size, size a multiple of
10697 			 * eight bytes, and matching size passed in.
10698 			 */
10699 			if (inlen != 0 &&
10700 			    inlen != (8 * (rt->ip6r_len + 1)))
10701 				return (EINVAL);
10702 
10703 			if (checkonly)
10704 				break;
10705 
10706 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10707 			    (uchar_t **)&ipp->ipp_rthdr,
10708 			    &ipp->ipp_rthdrlen, 0);
10709 			if (reterr != 0)
10710 				return (reterr);
10711 			if (ipp->ipp_rthdrlen == 0)
10712 				ipp->ipp_fields &= ~IPPF_RTHDR;
10713 			else
10714 				ipp->ipp_fields |= IPPF_RTHDR;
10715 			reterr = tcp_build_hdrs(tcp);
10716 			if (reterr != 0)
10717 				return (reterr);
10718 			break;
10719 		}
10720 		case IPV6_V6ONLY:
10721 			if (!checkonly) {
10722 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10723 			}
10724 			break;
10725 		case IPV6_USE_MIN_MTU:
10726 			if (inlen != sizeof (int))
10727 				return (EINVAL);
10728 
10729 			if (*i1 < -1 || *i1 > 1)
10730 				return (EINVAL);
10731 
10732 			if (checkonly)
10733 				break;
10734 
10735 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10736 			ipp->ipp_use_min_mtu = *i1;
10737 			break;
10738 		case IPV6_SEC_OPT:
10739 			/*
10740 			 * We should not allow policy setting after
10741 			 * we start listening for connections.
10742 			 */
10743 			if (tcp->tcp_state == TCPS_LISTEN) {
10744 				return (EINVAL);
10745 			} else {
10746 				/* Handled at the IP level */
10747 				return (-EINVAL);
10748 			}
10749 		case IPV6_SRC_PREFERENCES:
10750 			if (inlen != sizeof (uint32_t))
10751 				return (EINVAL);
10752 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10753 			    *(uint32_t *)invalp);
10754 			if (reterr != 0) {
10755 				*outlenp = 0;
10756 				return (reterr);
10757 			}
10758 			break;
10759 		default:
10760 			*outlenp = 0;
10761 			return (EINVAL);
10762 		}
10763 		break;
10764 	}		/* end IPPROTO_IPV6 */
10765 	default:
10766 		*outlenp = 0;
10767 		return (EINVAL);
10768 	}
10769 	/*
10770 	 * Common case of OK return with outval same as inval
10771 	 */
10772 	if (invalp != outvalp) {
10773 		/* don't trust bcopy for identical src/dst */
10774 		(void) bcopy(invalp, outvalp, inlen);
10775 	}
10776 	*outlenp = inlen;
10777 	return (0);
10778 }
10779 
10780 /* ARGSUSED */
10781 int
10782 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10783     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10784     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10785 {
10786 	conn_t	*connp =  Q_TO_CONN(q);
10787 
10788 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10789 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10790 }
10791 
10792 int
10793 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10794     const void *optvalp, socklen_t optlen, cred_t *cr)
10795 {
10796 	conn_t		*connp = (conn_t *)proto_handle;
10797 	squeue_t	*sqp = connp->conn_sqp;
10798 	int		error;
10799 
10800 	ASSERT(connp->conn_upper_handle != NULL);
10801 	/*
10802 	 * Entering the squeue synchronously can result in a context switch,
10803 	 * which can cause a rather sever performance degradation. So we try to
10804 	 * handle whatever options we can without entering the squeue.
10805 	 */
10806 	if (level == IPPROTO_TCP) {
10807 		switch (option_name) {
10808 		case TCP_NODELAY:
10809 			if (optlen != sizeof (int32_t))
10810 				return (EINVAL);
10811 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10812 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10813 			    connp->conn_tcp->tcp_mss;
10814 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10815 			return (0);
10816 		default:
10817 			break;
10818 		}
10819 	}
10820 
10821 	error = squeue_synch_enter(sqp, connp, NULL);
10822 	if (error == ENOMEM) {
10823 		return (ENOMEM);
10824 	}
10825 
10826 	error = proto_opt_check(level, option_name, optlen, NULL,
10827 	    tcp_opt_obj.odb_opt_des_arr,
10828 	    tcp_opt_obj.odb_opt_arr_cnt,
10829 	    tcp_opt_obj.odb_topmost_tpiprovider,
10830 	    B_TRUE, B_FALSE, cr);
10831 
10832 	if (error != 0) {
10833 		if (error < 0) {
10834 			error = proto_tlitosyserr(-error);
10835 		}
10836 		squeue_synch_exit(sqp, connp);
10837 		return (error);
10838 	}
10839 
10840 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10841 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10842 	    NULL, cr, NULL);
10843 	squeue_synch_exit(sqp, connp);
10844 
10845 	if (error < 0) {
10846 		/*
10847 		 * Pass on to ip
10848 		 */
10849 		error = ip_set_options(connp, level, option_name, optvalp,
10850 		    optlen, cr);
10851 	}
10852 	return (error);
10853 }
10854 
10855 /*
10856  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10857  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10858  * headers, and the maximum size tcp header (to avoid reallocation
10859  * on the fly for additional tcp options).
10860  * Returns failure if can't allocate memory.
10861  */
10862 static int
10863 tcp_build_hdrs(tcp_t *tcp)
10864 {
10865 	char	*hdrs;
10866 	uint_t	hdrs_len;
10867 	ip6i_t	*ip6i;
10868 	char	buf[TCP_MAX_HDR_LENGTH];
10869 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10870 	in6_addr_t src, dst;
10871 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10872 	conn_t *connp = tcp->tcp_connp;
10873 
10874 	/*
10875 	 * save the existing tcp header and source/dest IP addresses
10876 	 */
10877 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10878 	src = tcp->tcp_ip6h->ip6_src;
10879 	dst = tcp->tcp_ip6h->ip6_dst;
10880 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10881 	ASSERT(hdrs_len != 0);
10882 	if (hdrs_len > tcp->tcp_iphc_len) {
10883 		/* Need to reallocate */
10884 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10885 		if (hdrs == NULL)
10886 			return (ENOMEM);
10887 		if (tcp->tcp_iphc != NULL) {
10888 			if (tcp->tcp_hdr_grown) {
10889 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10890 			} else {
10891 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10892 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10893 			}
10894 			tcp->tcp_iphc_len = 0;
10895 		}
10896 		ASSERT(tcp->tcp_iphc_len == 0);
10897 		tcp->tcp_iphc = hdrs;
10898 		tcp->tcp_iphc_len = hdrs_len;
10899 		tcp->tcp_hdr_grown = B_TRUE;
10900 	}
10901 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10902 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10903 
10904 	/* Set header fields not in ipp */
10905 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10906 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10907 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10908 	} else {
10909 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10910 	}
10911 	/*
10912 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10913 	 *
10914 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10915 	 */
10916 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10917 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10918 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10919 
10920 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10921 
10922 	tcp->tcp_ip6h->ip6_src = src;
10923 	tcp->tcp_ip6h->ip6_dst = dst;
10924 
10925 	/*
10926 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10927 	 * the default value for TCP.
10928 	 */
10929 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10930 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10931 
10932 	/*
10933 	 * If we're setting extension headers after a connection
10934 	 * has been established, and if we have a routing header
10935 	 * among the extension headers, call ip_massage_options_v6 to
10936 	 * manipulate the routing header/ip6_dst set the checksum
10937 	 * difference in the tcp header template.
10938 	 * (This happens in tcp_connect_ipv6 if the routing header
10939 	 * is set prior to the connect.)
10940 	 * Set the tcp_sum to zero first in case we've cleared a
10941 	 * routing header or don't have one at all.
10942 	 */
10943 	tcp->tcp_sum = 0;
10944 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10945 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10946 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10947 		    (uint8_t *)tcp->tcp_tcph);
10948 		if (rth != NULL) {
10949 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10950 			    rth, tcps->tcps_netstack);
10951 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10952 			    (tcp->tcp_sum >> 16));
10953 		}
10954 	}
10955 
10956 	/* Try to get everything in a single mblk */
10957 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10958 	    hdrs_len + tcps->tcps_wroff_xtra);
10959 	return (0);
10960 }
10961 
10962 /*
10963  * Transfer any source route option from ipha to buf/dst in reversed form.
10964  */
10965 static int
10966 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10967 {
10968 	ipoptp_t	opts;
10969 	uchar_t		*opt;
10970 	uint8_t		optval;
10971 	uint8_t		optlen;
10972 	uint32_t	len = 0;
10973 
10974 	for (optval = ipoptp_first(&opts, ipha);
10975 	    optval != IPOPT_EOL;
10976 	    optval = ipoptp_next(&opts)) {
10977 		opt = opts.ipoptp_cur;
10978 		optlen = opts.ipoptp_len;
10979 		switch (optval) {
10980 			int	off1, off2;
10981 		case IPOPT_SSRR:
10982 		case IPOPT_LSRR:
10983 
10984 			/* Reverse source route */
10985 			/*
10986 			 * First entry should be the next to last one in the
10987 			 * current source route (the last entry is our
10988 			 * address.)
10989 			 * The last entry should be the final destination.
10990 			 */
10991 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10992 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10993 			off1 = IPOPT_MINOFF_SR - 1;
10994 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10995 			if (off2 < 0) {
10996 				/* No entries in source route */
10997 				break;
10998 			}
10999 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11000 			/*
11001 			 * Note: use src since ipha has not had its src
11002 			 * and dst reversed (it is in the state it was
11003 			 * received.
11004 			 */
11005 			bcopy(&ipha->ipha_src, buf + off2,
11006 			    IP_ADDR_LEN);
11007 			off2 -= IP_ADDR_LEN;
11008 
11009 			while (off2 > 0) {
11010 				bcopy(opt + off2, buf + off1,
11011 				    IP_ADDR_LEN);
11012 				off1 += IP_ADDR_LEN;
11013 				off2 -= IP_ADDR_LEN;
11014 			}
11015 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11016 			buf += optlen;
11017 			len += optlen;
11018 			break;
11019 		}
11020 	}
11021 done:
11022 	/* Pad the resulting options */
11023 	while (len & 0x3) {
11024 		*buf++ = IPOPT_EOL;
11025 		len++;
11026 	}
11027 	return (len);
11028 }
11029 
11030 
11031 /*
11032  * Extract and revert a source route from ipha (if any)
11033  * and then update the relevant fields in both tcp_t and the standard header.
11034  */
11035 static void
11036 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11037 {
11038 	char	buf[TCP_MAX_HDR_LENGTH];
11039 	uint_t	tcph_len;
11040 	int	len;
11041 
11042 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11043 	len = IPH_HDR_LENGTH(ipha);
11044 	if (len == IP_SIMPLE_HDR_LENGTH)
11045 		/* Nothing to do */
11046 		return;
11047 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11048 	    (len & 0x3))
11049 		return;
11050 
11051 	tcph_len = tcp->tcp_tcp_hdr_len;
11052 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11053 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11054 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11055 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11056 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11057 	len += IP_SIMPLE_HDR_LENGTH;
11058 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11059 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11060 	if ((int)tcp->tcp_sum < 0)
11061 		tcp->tcp_sum--;
11062 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11063 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11064 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11065 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11066 	tcp->tcp_ip_hdr_len = len;
11067 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11068 	    (IP_VERSION << 4) | (len >> 2);
11069 	len += tcph_len;
11070 	tcp->tcp_hdr_len = len;
11071 }
11072 
11073 /*
11074  * Copy the standard header into its new location,
11075  * lay in the new options and then update the relevant
11076  * fields in both tcp_t and the standard header.
11077  */
11078 static int
11079 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11080 {
11081 	uint_t	tcph_len;
11082 	uint8_t	*ip_optp;
11083 	tcph_t	*new_tcph;
11084 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11085 	conn_t	*connp = tcp->tcp_connp;
11086 
11087 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11088 		return (EINVAL);
11089 
11090 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11091 		return (EINVAL);
11092 
11093 	if (checkonly) {
11094 		/*
11095 		 * do not really set, just pretend to - T_CHECK
11096 		 */
11097 		return (0);
11098 	}
11099 
11100 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11101 	if (tcp->tcp_label_len > 0) {
11102 		int padlen;
11103 		uint8_t opt;
11104 
11105 		/* convert list termination to no-ops */
11106 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11107 		ip_optp += ip_optp[IPOPT_OLEN];
11108 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11109 		while (--padlen >= 0)
11110 			*ip_optp++ = opt;
11111 	}
11112 	tcph_len = tcp->tcp_tcp_hdr_len;
11113 	new_tcph = (tcph_t *)(ip_optp + len);
11114 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11115 	tcp->tcp_tcph = new_tcph;
11116 	bcopy(ptr, ip_optp, len);
11117 
11118 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11119 
11120 	tcp->tcp_ip_hdr_len = len;
11121 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11122 	    (IP_VERSION << 4) | (len >> 2);
11123 	tcp->tcp_hdr_len = len + tcph_len;
11124 	if (!TCP_IS_DETACHED(tcp)) {
11125 		/* Always allocate room for all options. */
11126 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11127 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11128 	}
11129 	return (0);
11130 }
11131 
11132 /* Get callback routine passed to nd_load by tcp_param_register */
11133 /* ARGSUSED */
11134 static int
11135 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11136 {
11137 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11138 
11139 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11140 	return (0);
11141 }
11142 
11143 /*
11144  * Walk through the param array specified registering each element with the
11145  * named dispatch handler.
11146  */
11147 static boolean_t
11148 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11149 {
11150 	for (; cnt-- > 0; tcppa++) {
11151 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11152 			if (!nd_load(ndp, tcppa->tcp_param_name,
11153 			    tcp_param_get, tcp_param_set,
11154 			    (caddr_t)tcppa)) {
11155 				nd_free(ndp);
11156 				return (B_FALSE);
11157 			}
11158 		}
11159 	}
11160 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11161 	    KM_SLEEP);
11162 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11163 	    sizeof (tcpparam_t));
11164 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11165 	    tcp_param_get, tcp_param_set_aligned,
11166 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11167 		nd_free(ndp);
11168 		return (B_FALSE);
11169 	}
11170 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11171 	    KM_SLEEP);
11172 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11173 	    sizeof (tcpparam_t));
11174 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11175 	    tcp_param_get, tcp_param_set_aligned,
11176 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11177 		nd_free(ndp);
11178 		return (B_FALSE);
11179 	}
11180 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11181 	    KM_SLEEP);
11182 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11183 	    sizeof (tcpparam_t));
11184 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11185 	    tcp_param_get, tcp_param_set_aligned,
11186 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11187 		nd_free(ndp);
11188 		return (B_FALSE);
11189 	}
11190 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11191 	    KM_SLEEP);
11192 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11193 	    sizeof (tcpparam_t));
11194 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11195 	    tcp_param_get, tcp_param_set_aligned,
11196 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11197 		nd_free(ndp);
11198 		return (B_FALSE);
11199 	}
11200 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11201 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11202 		nd_free(ndp);
11203 		return (B_FALSE);
11204 	}
11205 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11206 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11207 		nd_free(ndp);
11208 		return (B_FALSE);
11209 	}
11210 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11211 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11212 		nd_free(ndp);
11213 		return (B_FALSE);
11214 	}
11215 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11216 	    tcp_1948_phrase_set, NULL)) {
11217 		nd_free(ndp);
11218 		return (B_FALSE);
11219 	}
11220 	/*
11221 	 * Dummy ndd variables - only to convey obsolescence information
11222 	 * through printing of their name (no get or set routines)
11223 	 * XXX Remove in future releases ?
11224 	 */
11225 	if (!nd_load(ndp,
11226 	    "tcp_close_wait_interval(obsoleted - "
11227 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11228 		nd_free(ndp);
11229 		return (B_FALSE);
11230 	}
11231 	return (B_TRUE);
11232 }
11233 
11234 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11235 /* ARGSUSED */
11236 static int
11237 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11238     cred_t *cr)
11239 {
11240 	long new_value;
11241 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11242 
11243 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11244 	    new_value < tcppa->tcp_param_min ||
11245 	    new_value > tcppa->tcp_param_max) {
11246 		return (EINVAL);
11247 	}
11248 	/*
11249 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11250 	 * round it up.  For future 64 bit requirement, we actually make it
11251 	 * a multiple of 8.
11252 	 */
11253 	if (new_value & 0x7) {
11254 		new_value = (new_value & ~0x7) + 0x8;
11255 	}
11256 	tcppa->tcp_param_val = new_value;
11257 	return (0);
11258 }
11259 
11260 /* Set callback routine passed to nd_load by tcp_param_register */
11261 /* ARGSUSED */
11262 static int
11263 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11264 {
11265 	long	new_value;
11266 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11267 
11268 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11269 	    new_value < tcppa->tcp_param_min ||
11270 	    new_value > tcppa->tcp_param_max) {
11271 		return (EINVAL);
11272 	}
11273 	tcppa->tcp_param_val = new_value;
11274 	return (0);
11275 }
11276 
11277 /*
11278  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11279  * is filled, return as much as we can.  The message passed in may be
11280  * multi-part, chained using b_cont.  "start" is the starting sequence
11281  * number for this piece.
11282  */
11283 static mblk_t *
11284 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11285 {
11286 	uint32_t	end;
11287 	mblk_t		*mp1;
11288 	mblk_t		*mp2;
11289 	mblk_t		*next_mp;
11290 	uint32_t	u1;
11291 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11292 
11293 	/* Walk through all the new pieces. */
11294 	do {
11295 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11296 		    (uintptr_t)INT_MAX);
11297 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11298 		next_mp = mp->b_cont;
11299 		if (start == end) {
11300 			/* Empty.  Blast it. */
11301 			freeb(mp);
11302 			continue;
11303 		}
11304 		mp->b_cont = NULL;
11305 		TCP_REASS_SET_SEQ(mp, start);
11306 		TCP_REASS_SET_END(mp, end);
11307 		mp1 = tcp->tcp_reass_tail;
11308 		if (!mp1) {
11309 			tcp->tcp_reass_tail = mp;
11310 			tcp->tcp_reass_head = mp;
11311 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11312 			UPDATE_MIB(&tcps->tcps_mib,
11313 			    tcpInDataUnorderBytes, end - start);
11314 			continue;
11315 		}
11316 		/* New stuff completely beyond tail? */
11317 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11318 			/* Link it on end. */
11319 			mp1->b_cont = mp;
11320 			tcp->tcp_reass_tail = mp;
11321 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11322 			UPDATE_MIB(&tcps->tcps_mib,
11323 			    tcpInDataUnorderBytes, end - start);
11324 			continue;
11325 		}
11326 		mp1 = tcp->tcp_reass_head;
11327 		u1 = TCP_REASS_SEQ(mp1);
11328 		/* New stuff at the front? */
11329 		if (SEQ_LT(start, u1)) {
11330 			/* Yes... Check for overlap. */
11331 			mp->b_cont = mp1;
11332 			tcp->tcp_reass_head = mp;
11333 			tcp_reass_elim_overlap(tcp, mp);
11334 			continue;
11335 		}
11336 		/*
11337 		 * The new piece fits somewhere between the head and tail.
11338 		 * We find our slot, where mp1 precedes us and mp2 trails.
11339 		 */
11340 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11341 			u1 = TCP_REASS_SEQ(mp2);
11342 			if (SEQ_LEQ(start, u1))
11343 				break;
11344 		}
11345 		/* Link ourselves in */
11346 		mp->b_cont = mp2;
11347 		mp1->b_cont = mp;
11348 
11349 		/* Trim overlap with following mblk(s) first */
11350 		tcp_reass_elim_overlap(tcp, mp);
11351 
11352 		/* Trim overlap with preceding mblk */
11353 		tcp_reass_elim_overlap(tcp, mp1);
11354 
11355 	} while (start = end, mp = next_mp);
11356 	mp1 = tcp->tcp_reass_head;
11357 	/* Anything ready to go? */
11358 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11359 		return (NULL);
11360 	/* Eat what we can off the queue */
11361 	for (;;) {
11362 		mp = mp1->b_cont;
11363 		end = TCP_REASS_END(mp1);
11364 		TCP_REASS_SET_SEQ(mp1, 0);
11365 		TCP_REASS_SET_END(mp1, 0);
11366 		if (!mp) {
11367 			tcp->tcp_reass_tail = NULL;
11368 			break;
11369 		}
11370 		if (end != TCP_REASS_SEQ(mp)) {
11371 			mp1->b_cont = NULL;
11372 			break;
11373 		}
11374 		mp1 = mp;
11375 	}
11376 	mp1 = tcp->tcp_reass_head;
11377 	tcp->tcp_reass_head = mp;
11378 	return (mp1);
11379 }
11380 
11381 /* Eliminate any overlap that mp may have over later mblks */
11382 static void
11383 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11384 {
11385 	uint32_t	end;
11386 	mblk_t		*mp1;
11387 	uint32_t	u1;
11388 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11389 
11390 	end = TCP_REASS_END(mp);
11391 	while ((mp1 = mp->b_cont) != NULL) {
11392 		u1 = TCP_REASS_SEQ(mp1);
11393 		if (!SEQ_GT(end, u1))
11394 			break;
11395 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11396 			mp->b_wptr -= end - u1;
11397 			TCP_REASS_SET_END(mp, u1);
11398 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11399 			UPDATE_MIB(&tcps->tcps_mib,
11400 			    tcpInDataPartDupBytes, end - u1);
11401 			break;
11402 		}
11403 		mp->b_cont = mp1->b_cont;
11404 		TCP_REASS_SET_SEQ(mp1, 0);
11405 		TCP_REASS_SET_END(mp1, 0);
11406 		freeb(mp1);
11407 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11408 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11409 	}
11410 	if (!mp1)
11411 		tcp->tcp_reass_tail = mp;
11412 }
11413 
11414 static uint_t
11415 tcp_rwnd_reopen(tcp_t *tcp)
11416 {
11417 	uint_t ret = 0;
11418 	uint_t thwin;
11419 
11420 	/* Learn the latest rwnd information that we sent to the other side. */
11421 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11422 	    << tcp->tcp_rcv_ws;
11423 	/* This is peer's calculated send window (our receive window). */
11424 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11425 	/*
11426 	 * Increase the receive window to max.  But we need to do receiver
11427 	 * SWS avoidance.  This means that we need to check the increase of
11428 	 * of receive window is at least 1 MSS.
11429 	 */
11430 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11431 		/*
11432 		 * If the window that the other side knows is less than max
11433 		 * deferred acks segments, send an update immediately.
11434 		 */
11435 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11436 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11437 			ret = TH_ACK_NEEDED;
11438 		}
11439 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11440 	}
11441 	return (ret);
11442 }
11443 
11444 /*
11445  * Send up all messages queued on tcp_rcv_list.
11446  */
11447 static uint_t
11448 tcp_rcv_drain(tcp_t *tcp)
11449 {
11450 	mblk_t *mp;
11451 	uint_t ret = 0;
11452 #ifdef DEBUG
11453 	uint_t cnt = 0;
11454 #endif
11455 	queue_t	*q = tcp->tcp_rq;
11456 
11457 	/* Can't drain on an eager connection */
11458 	if (tcp->tcp_listener != NULL)
11459 		return (ret);
11460 
11461 	/* Can't be a non-STREAMS connection */
11462 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
11463 
11464 	/* No need for the push timer now. */
11465 	if (tcp->tcp_push_tid != 0) {
11466 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11467 		tcp->tcp_push_tid = 0;
11468 	}
11469 
11470 	/*
11471 	 * Handle two cases here: we are currently fused or we were
11472 	 * previously fused and have some urgent data to be delivered
11473 	 * upstream.  The latter happens because we either ran out of
11474 	 * memory or were detached and therefore sending the SIGURG was
11475 	 * deferred until this point.  In either case we pass control
11476 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11477 	 * some work.
11478 	 */
11479 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11480 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11481 		    tcp->tcp_fused_sigurg_mp != NULL);
11482 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11483 		    &tcp->tcp_fused_sigurg_mp))
11484 			return (ret);
11485 	}
11486 
11487 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11488 		tcp->tcp_rcv_list = mp->b_next;
11489 		mp->b_next = NULL;
11490 #ifdef DEBUG
11491 		cnt += msgdsize(mp);
11492 #endif
11493 		/* Does this need SSL processing first? */
11494 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11495 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11496 			    mblk_t *, mp);
11497 			tcp_kssl_input(tcp, mp);
11498 			continue;
11499 		}
11500 		putnext(q, mp);
11501 	}
11502 #ifdef DEBUG
11503 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11504 #endif
11505 	tcp->tcp_rcv_last_head = NULL;
11506 	tcp->tcp_rcv_last_tail = NULL;
11507 	tcp->tcp_rcv_cnt = 0;
11508 
11509 	if (canputnext(q))
11510 		return (tcp_rwnd_reopen(tcp));
11511 
11512 	return (ret);
11513 }
11514 
11515 /*
11516  * Queue data on tcp_rcv_list which is a b_next chain.
11517  * tcp_rcv_last_head/tail is the last element of this chain.
11518  * Each element of the chain is a b_cont chain.
11519  *
11520  * M_DATA messages are added to the current element.
11521  * Other messages are added as new (b_next) elements.
11522  */
11523 void
11524 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11525 {
11526 	ASSERT(seg_len == msgdsize(mp));
11527 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11528 
11529 	if (tcp->tcp_rcv_list == NULL) {
11530 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11531 		tcp->tcp_rcv_list = mp;
11532 		tcp->tcp_rcv_last_head = mp;
11533 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11534 		tcp->tcp_rcv_last_tail->b_cont = mp;
11535 	} else {
11536 		tcp->tcp_rcv_last_head->b_next = mp;
11537 		tcp->tcp_rcv_last_head = mp;
11538 	}
11539 
11540 	while (mp->b_cont)
11541 		mp = mp->b_cont;
11542 
11543 	tcp->tcp_rcv_last_tail = mp;
11544 	tcp->tcp_rcv_cnt += seg_len;
11545 	tcp->tcp_rwnd -= seg_len;
11546 }
11547 
11548 /*
11549  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11550  *
11551  * This is the default entry function into TCP on the read side. TCP is
11552  * always entered via squeue i.e. using squeue's for mutual exclusion.
11553  * When classifier does a lookup to find the tcp, it also puts a reference
11554  * on the conn structure associated so the tcp is guaranteed to exist
11555  * when we come here. We still need to check the state because it might
11556  * as well has been closed. The squeue processing function i.e. squeue_enter,
11557  * is responsible for doing the CONN_DEC_REF.
11558  *
11559  * Apart from the default entry point, IP also sends packets directly to
11560  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11561  * connections.
11562  */
11563 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11564 void
11565 tcp_input(void *arg, mblk_t *mp, void *arg2)
11566 {
11567 	conn_t	*connp = (conn_t *)arg;
11568 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11569 
11570 	/* arg2 is the sqp */
11571 	ASSERT(arg2 != NULL);
11572 	ASSERT(mp != NULL);
11573 
11574 	/*
11575 	 * Don't accept any input on a closed tcp as this TCP logically does
11576 	 * not exist on the system. Don't proceed further with this TCP.
11577 	 * For eg. this packet could trigger another close of this tcp
11578 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11579 	 * tcp_clean_death / tcp_closei_local must be called at most once
11580 	 * on a TCP. In this case we need to refeed the packet into the
11581 	 * classifier and figure out where the packet should go. Need to
11582 	 * preserve the recv_ill somehow. Until we figure that out, for
11583 	 * now just drop the packet if we can't classify the packet.
11584 	 */
11585 	if (tcp->tcp_state == TCPS_CLOSED ||
11586 	    tcp->tcp_state == TCPS_BOUND) {
11587 		conn_t	*new_connp;
11588 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11589 
11590 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11591 		if (new_connp != NULL) {
11592 			tcp_reinput(new_connp, mp, arg2);
11593 			return;
11594 		}
11595 		/* We failed to classify. For now just drop the packet */
11596 		freemsg(mp);
11597 		return;
11598 	}
11599 
11600 	if (DB_TYPE(mp) != M_DATA) {
11601 		tcp_rput_common(tcp, mp);
11602 		return;
11603 	}
11604 
11605 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11606 		squeue_t	*final_sqp;
11607 
11608 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11609 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11610 		DB_CKSUMSTART(mp) = 0;
11611 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11612 		    connp->conn_final_sqp == NULL &&
11613 		    tcp_outbound_squeue_switch) {
11614 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11615 			connp->conn_final_sqp = final_sqp;
11616 			if (connp->conn_final_sqp != connp->conn_sqp) {
11617 				CONN_INC_REF(connp);
11618 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11619 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11620 				    tcp_rput_data, connp, ip_squeue_flag,
11621 				    SQTAG_CONNECT_FINISH);
11622 				return;
11623 			}
11624 		}
11625 	}
11626 	tcp_rput_data(connp, mp, arg2);
11627 }
11628 
11629 /*
11630  * The read side put procedure.
11631  * The packets passed up by ip are assume to be aligned according to
11632  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11633  */
11634 static void
11635 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11636 {
11637 	/*
11638 	 * tcp_rput_data() does not expect M_CTL except for the case
11639 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11640 	 * type. Need to make sure that any other M_CTLs don't make
11641 	 * it to tcp_rput_data since it is not expecting any and doesn't
11642 	 * check for it.
11643 	 */
11644 	if (DB_TYPE(mp) == M_CTL) {
11645 		switch (*(uint32_t *)(mp->b_rptr)) {
11646 		case TCP_IOC_ABORT_CONN:
11647 			/*
11648 			 * Handle connection abort request.
11649 			 */
11650 			tcp_ioctl_abort_handler(tcp, mp);
11651 			return;
11652 		case IPSEC_IN:
11653 			/*
11654 			 * Only secure icmp arrive in TCP and they
11655 			 * don't go through data path.
11656 			 */
11657 			tcp_icmp_error(tcp, mp);
11658 			return;
11659 		case IN_PKTINFO:
11660 			/*
11661 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11662 			 * sockets that are receiving IPv4 traffic. tcp
11663 			 */
11664 			ASSERT(tcp->tcp_family == AF_INET6);
11665 			ASSERT(tcp->tcp_ipv6_recvancillary &
11666 			    TCP_IPV6_RECVPKTINFO);
11667 			tcp_rput_data(tcp->tcp_connp, mp,
11668 			    tcp->tcp_connp->conn_sqp);
11669 			return;
11670 		case MDT_IOC_INFO_UPDATE:
11671 			/*
11672 			 * Handle Multidata information update; the
11673 			 * following routine will free the message.
11674 			 */
11675 			if (tcp->tcp_connp->conn_mdt_ok) {
11676 				tcp_mdt_update(tcp,
11677 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11678 				    B_FALSE);
11679 			}
11680 			freemsg(mp);
11681 			return;
11682 		case LSO_IOC_INFO_UPDATE:
11683 			/*
11684 			 * Handle LSO information update; the following
11685 			 * routine will free the message.
11686 			 */
11687 			if (tcp->tcp_connp->conn_lso_ok) {
11688 				tcp_lso_update(tcp,
11689 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11690 			}
11691 			freemsg(mp);
11692 			return;
11693 		default:
11694 			/*
11695 			 * tcp_icmp_err() will process the M_CTL packets.
11696 			 * Non-ICMP packets, if any, will be discarded in
11697 			 * tcp_icmp_err(). We will process the ICMP packet
11698 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11699 			 * incoming ICMP packet may result in changing
11700 			 * the tcp_mss, which we would need if we have
11701 			 * packets to retransmit.
11702 			 */
11703 			tcp_icmp_error(tcp, mp);
11704 			return;
11705 		}
11706 	}
11707 
11708 	/* No point processing the message if tcp is already closed */
11709 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11710 		freemsg(mp);
11711 		return;
11712 	}
11713 
11714 	tcp_rput_other(tcp, mp);
11715 }
11716 
11717 
11718 /* The minimum of smoothed mean deviation in RTO calculation. */
11719 #define	TCP_SD_MIN	400
11720 
11721 /*
11722  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11723  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11724  * are the same as those in Appendix A.2 of that paper.
11725  *
11726  * m = new measurement
11727  * sa = smoothed RTT average (8 * average estimates).
11728  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11729  */
11730 static void
11731 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11732 {
11733 	long m = TICK_TO_MSEC(rtt);
11734 	clock_t sa = tcp->tcp_rtt_sa;
11735 	clock_t sv = tcp->tcp_rtt_sd;
11736 	clock_t rto;
11737 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11738 
11739 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11740 	tcp->tcp_rtt_update++;
11741 
11742 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11743 	if (sa != 0) {
11744 		/*
11745 		 * Update average estimator:
11746 		 *	new rtt = 7/8 old rtt + 1/8 Error
11747 		 */
11748 
11749 		/* m is now Error in estimate. */
11750 		m -= sa >> 3;
11751 		if ((sa += m) <= 0) {
11752 			/*
11753 			 * Don't allow the smoothed average to be negative.
11754 			 * We use 0 to denote reinitialization of the
11755 			 * variables.
11756 			 */
11757 			sa = 1;
11758 		}
11759 
11760 		/*
11761 		 * Update deviation estimator:
11762 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11763 		 */
11764 		if (m < 0)
11765 			m = -m;
11766 		m -= sv >> 2;
11767 		sv += m;
11768 	} else {
11769 		/*
11770 		 * This follows BSD's implementation.  So the reinitialized
11771 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11772 		 * link is bandwidth dominated, doubling the window size
11773 		 * during slow start means doubling the RTT.  We want to be
11774 		 * more conservative when we reinitialize our estimates.  3
11775 		 * is just a convenient number.
11776 		 */
11777 		sa = m << 3;
11778 		sv = m << 1;
11779 	}
11780 	if (sv < TCP_SD_MIN) {
11781 		/*
11782 		 * We do not know that if sa captures the delay ACK
11783 		 * effect as in a long train of segments, a receiver
11784 		 * does not delay its ACKs.  So set the minimum of sv
11785 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11786 		 * of BSD DATO.  That means the minimum of mean
11787 		 * deviation is 100 ms.
11788 		 *
11789 		 */
11790 		sv = TCP_SD_MIN;
11791 	}
11792 	tcp->tcp_rtt_sa = sa;
11793 	tcp->tcp_rtt_sd = sv;
11794 	/*
11795 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11796 	 *
11797 	 * Add tcp_rexmit_interval extra in case of extreme environment
11798 	 * where the algorithm fails to work.  The default value of
11799 	 * tcp_rexmit_interval_extra should be 0.
11800 	 *
11801 	 * As we use a finer grained clock than BSD and update
11802 	 * RTO for every ACKs, add in another .25 of RTT to the
11803 	 * deviation of RTO to accomodate burstiness of 1/4 of
11804 	 * window size.
11805 	 */
11806 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11807 
11808 	if (rto > tcps->tcps_rexmit_interval_max) {
11809 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11810 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11811 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11812 	} else {
11813 		tcp->tcp_rto = rto;
11814 	}
11815 
11816 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11817 	tcp->tcp_timer_backoff = 0;
11818 }
11819 
11820 /*
11821  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11822  * send queue which starts at the given seq. no.
11823  *
11824  * Parameters:
11825  *	tcp_t *tcp: the tcp instance pointer.
11826  *	uint32_t seq: the starting seq. no of the requested segment.
11827  *	int32_t *off: after the execution, *off will be the offset to
11828  *		the returned mblk which points to the requested seq no.
11829  *		It is the caller's responsibility to send in a non-null off.
11830  *
11831  * Return:
11832  *	A mblk_t pointer pointing to the requested segment in send queue.
11833  */
11834 static mblk_t *
11835 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11836 {
11837 	int32_t	cnt;
11838 	mblk_t	*mp;
11839 
11840 	/* Defensive coding.  Make sure we don't send incorrect data. */
11841 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
11842 		return (NULL);
11843 
11844 	cnt = seq - tcp->tcp_suna;
11845 	mp = tcp->tcp_xmit_head;
11846 	while (cnt > 0 && mp != NULL) {
11847 		cnt -= mp->b_wptr - mp->b_rptr;
11848 		if (cnt < 0) {
11849 			cnt += mp->b_wptr - mp->b_rptr;
11850 			break;
11851 		}
11852 		mp = mp->b_cont;
11853 	}
11854 	ASSERT(mp != NULL);
11855 	*off = cnt;
11856 	return (mp);
11857 }
11858 
11859 /*
11860  * This function handles all retransmissions if SACK is enabled for this
11861  * connection.  First it calculates how many segments can be retransmitted
11862  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11863  * segments.  A segment is eligible if sack_cnt for that segment is greater
11864  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11865  * all eligible segments, it checks to see if TCP can send some new segments
11866  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11867  *
11868  * Parameters:
11869  *	tcp_t *tcp: the tcp structure of the connection.
11870  *	uint_t *flags: in return, appropriate value will be set for
11871  *	tcp_rput_data().
11872  */
11873 static void
11874 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11875 {
11876 	notsack_blk_t	*notsack_blk;
11877 	int32_t		usable_swnd;
11878 	int32_t		mss;
11879 	uint32_t	seg_len;
11880 	mblk_t		*xmit_mp;
11881 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11882 
11883 	ASSERT(tcp->tcp_sack_info != NULL);
11884 	ASSERT(tcp->tcp_notsack_list != NULL);
11885 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11886 
11887 	/* Defensive coding in case there is a bug... */
11888 	if (tcp->tcp_notsack_list == NULL) {
11889 		return;
11890 	}
11891 	notsack_blk = tcp->tcp_notsack_list;
11892 	mss = tcp->tcp_mss;
11893 
11894 	/*
11895 	 * Limit the num of outstanding data in the network to be
11896 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11897 	 */
11898 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11899 
11900 	/* At least retransmit 1 MSS of data. */
11901 	if (usable_swnd <= 0) {
11902 		usable_swnd = mss;
11903 	}
11904 
11905 	/* Make sure no new RTT samples will be taken. */
11906 	tcp->tcp_csuna = tcp->tcp_snxt;
11907 
11908 	notsack_blk = tcp->tcp_notsack_list;
11909 	while (usable_swnd > 0) {
11910 		mblk_t		*snxt_mp, *tmp_mp;
11911 		tcp_seq		begin = tcp->tcp_sack_snxt;
11912 		tcp_seq		end;
11913 		int32_t		off;
11914 
11915 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11916 			if (SEQ_GT(notsack_blk->end, begin) &&
11917 			    (notsack_blk->sack_cnt >=
11918 			    tcps->tcps_dupack_fast_retransmit)) {
11919 				end = notsack_blk->end;
11920 				if (SEQ_LT(begin, notsack_blk->begin)) {
11921 					begin = notsack_blk->begin;
11922 				}
11923 				break;
11924 			}
11925 		}
11926 		/*
11927 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11928 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11929 		 * set to tcp_cwnd_ssthresh.
11930 		 */
11931 		if (notsack_blk == NULL) {
11932 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11933 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11934 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11935 				ASSERT(tcp->tcp_cwnd > 0);
11936 				return;
11937 			} else {
11938 				usable_swnd = usable_swnd / mss;
11939 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11940 				    MAX(usable_swnd * mss, mss);
11941 				*flags |= TH_XMIT_NEEDED;
11942 				return;
11943 			}
11944 		}
11945 
11946 		/*
11947 		 * Note that we may send more than usable_swnd allows here
11948 		 * because of round off, but no more than 1 MSS of data.
11949 		 */
11950 		seg_len = end - begin;
11951 		if (seg_len > mss)
11952 			seg_len = mss;
11953 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11954 		ASSERT(snxt_mp != NULL);
11955 		/* This should not happen.  Defensive coding again... */
11956 		if (snxt_mp == NULL) {
11957 			return;
11958 		}
11959 
11960 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11961 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11962 		if (xmit_mp == NULL)
11963 			return;
11964 
11965 		usable_swnd -= seg_len;
11966 		tcp->tcp_pipe += seg_len;
11967 		tcp->tcp_sack_snxt = begin + seg_len;
11968 
11969 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11970 
11971 		/*
11972 		 * Update the send timestamp to avoid false retransmission.
11973 		 */
11974 		snxt_mp->b_prev = (mblk_t *)lbolt;
11975 
11976 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
11977 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
11978 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
11979 		/*
11980 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11981 		 * This happens when new data sent during fast recovery is
11982 		 * also lost.  If TCP retransmits those new data, it needs
11983 		 * to extend SACK recover phase to avoid starting another
11984 		 * fast retransmit/recovery unnecessarily.
11985 		 */
11986 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11987 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11988 		}
11989 	}
11990 }
11991 
11992 /*
11993  * This function handles policy checking at TCP level for non-hard_bound/
11994  * detached connections.
11995  */
11996 static boolean_t
11997 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
11998     boolean_t secure, boolean_t mctl_present)
11999 {
12000 	ipsec_latch_t *ipl = NULL;
12001 	ipsec_action_t *act = NULL;
12002 	mblk_t *data_mp;
12003 	ipsec_in_t *ii;
12004 	const char *reason;
12005 	kstat_named_t *counter;
12006 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12007 	ipsec_stack_t	*ipss;
12008 	ip_stack_t	*ipst;
12009 
12010 	ASSERT(mctl_present || !secure);
12011 
12012 	ASSERT((ipha == NULL && ip6h != NULL) ||
12013 	    (ip6h == NULL && ipha != NULL));
12014 
12015 	/*
12016 	 * We don't necessarily have an ipsec_in_act action to verify
12017 	 * policy because of assymetrical policy where we have only
12018 	 * outbound policy and no inbound policy (possible with global
12019 	 * policy).
12020 	 */
12021 	if (!secure) {
12022 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12023 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12024 			return (B_TRUE);
12025 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12026 		    "tcp_check_policy", ipha, ip6h, secure,
12027 		    tcps->tcps_netstack);
12028 		ipss = tcps->tcps_netstack->netstack_ipsec;
12029 
12030 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12031 		    DROPPER(ipss, ipds_tcp_clear),
12032 		    &tcps->tcps_dropper);
12033 		return (B_FALSE);
12034 	}
12035 
12036 	/*
12037 	 * We have a secure packet.
12038 	 */
12039 	if (act == NULL) {
12040 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12041 		    "tcp_check_policy", ipha, ip6h, secure,
12042 		    tcps->tcps_netstack);
12043 		ipss = tcps->tcps_netstack->netstack_ipsec;
12044 
12045 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12046 		    DROPPER(ipss, ipds_tcp_secure),
12047 		    &tcps->tcps_dropper);
12048 		return (B_FALSE);
12049 	}
12050 
12051 	/*
12052 	 * XXX This whole routine is currently incorrect.  ipl should
12053 	 * be set to the latch pointer, but is currently not set, so
12054 	 * we initialize it to NULL to avoid picking up random garbage.
12055 	 */
12056 	if (ipl == NULL)
12057 		return (B_TRUE);
12058 
12059 	data_mp = first_mp->b_cont;
12060 
12061 	ii = (ipsec_in_t *)first_mp->b_rptr;
12062 
12063 	ipst = tcps->tcps_netstack->netstack_ip;
12064 
12065 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12066 	    &counter, tcp->tcp_connp)) {
12067 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12068 		return (B_TRUE);
12069 	}
12070 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12071 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12072 	    reason);
12073 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12074 
12075 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12076 	    &tcps->tcps_dropper);
12077 	return (B_FALSE);
12078 }
12079 
12080 /*
12081  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12082  * retransmission after a timeout.
12083  *
12084  * To limit the number of duplicate segments, we limit the number of segment
12085  * to be sent in one time to tcp_snd_burst, the burst variable.
12086  */
12087 static void
12088 tcp_ss_rexmit(tcp_t *tcp)
12089 {
12090 	uint32_t	snxt;
12091 	uint32_t	smax;
12092 	int32_t		win;
12093 	int32_t		mss;
12094 	int32_t		off;
12095 	int32_t		burst = tcp->tcp_snd_burst;
12096 	mblk_t		*snxt_mp;
12097 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12098 
12099 	/*
12100 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12101 	 * all unack'ed segments.
12102 	 */
12103 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12104 		smax = tcp->tcp_rexmit_max;
12105 		snxt = tcp->tcp_rexmit_nxt;
12106 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12107 			snxt = tcp->tcp_suna;
12108 		}
12109 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12110 		win -= snxt - tcp->tcp_suna;
12111 		mss = tcp->tcp_mss;
12112 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12113 
12114 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12115 		    (burst > 0) && (snxt_mp != NULL)) {
12116 			mblk_t	*xmit_mp;
12117 			mblk_t	*old_snxt_mp = snxt_mp;
12118 			uint32_t cnt = mss;
12119 
12120 			if (win < cnt) {
12121 				cnt = win;
12122 			}
12123 			if (SEQ_GT(snxt + cnt, smax)) {
12124 				cnt = smax - snxt;
12125 			}
12126 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12127 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12128 			if (xmit_mp == NULL)
12129 				return;
12130 
12131 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12132 
12133 			snxt += cnt;
12134 			win -= cnt;
12135 			/*
12136 			 * Update the send timestamp to avoid false
12137 			 * retransmission.
12138 			 */
12139 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12140 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12141 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12142 
12143 			tcp->tcp_rexmit_nxt = snxt;
12144 			burst--;
12145 		}
12146 		/*
12147 		 * If we have transmitted all we have at the time
12148 		 * we started the retranmission, we can leave
12149 		 * the rest of the job to tcp_wput_data().  But we
12150 		 * need to check the send window first.  If the
12151 		 * win is not 0, go on with tcp_wput_data().
12152 		 */
12153 		if (SEQ_LT(snxt, smax) || win == 0) {
12154 			return;
12155 		}
12156 	}
12157 	/* Only call tcp_wput_data() if there is data to be sent. */
12158 	if (tcp->tcp_unsent) {
12159 		tcp_wput_data(tcp, NULL, B_FALSE);
12160 	}
12161 }
12162 
12163 /*
12164  * Process all TCP option in SYN segment.  Note that this function should
12165  * be called after tcp_adapt_ire() is called so that the necessary info
12166  * from IRE is already set in the tcp structure.
12167  *
12168  * This function sets up the correct tcp_mss value according to the
12169  * MSS option value and our header size.  It also sets up the window scale
12170  * and timestamp values, and initialize SACK info blocks.  But it does not
12171  * change receive window size after setting the tcp_mss value.  The caller
12172  * should do the appropriate change.
12173  */
12174 void
12175 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12176 {
12177 	int options;
12178 	tcp_opt_t tcpopt;
12179 	uint32_t mss_max;
12180 	char *tmp_tcph;
12181 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12182 
12183 	tcpopt.tcp = NULL;
12184 	options = tcp_parse_options(tcph, &tcpopt);
12185 
12186 	/*
12187 	 * Process MSS option.  Note that MSS option value does not account
12188 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12189 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12190 	 * IPv6.
12191 	 */
12192 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12193 		if (tcp->tcp_ipversion == IPV4_VERSION)
12194 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12195 		else
12196 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12197 	} else {
12198 		if (tcp->tcp_ipversion == IPV4_VERSION)
12199 			mss_max = tcps->tcps_mss_max_ipv4;
12200 		else
12201 			mss_max = tcps->tcps_mss_max_ipv6;
12202 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12203 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12204 		else if (tcpopt.tcp_opt_mss > mss_max)
12205 			tcpopt.tcp_opt_mss = mss_max;
12206 	}
12207 
12208 	/* Process Window Scale option. */
12209 	if (options & TCP_OPT_WSCALE_PRESENT) {
12210 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12211 		tcp->tcp_snd_ws_ok = B_TRUE;
12212 	} else {
12213 		tcp->tcp_snd_ws = B_FALSE;
12214 		tcp->tcp_snd_ws_ok = B_FALSE;
12215 		tcp->tcp_rcv_ws = B_FALSE;
12216 	}
12217 
12218 	/* Process Timestamp option. */
12219 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12220 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12221 		tmp_tcph = (char *)tcp->tcp_tcph;
12222 
12223 		tcp->tcp_snd_ts_ok = B_TRUE;
12224 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12225 		tcp->tcp_last_rcv_lbolt = lbolt64;
12226 		ASSERT(OK_32PTR(tmp_tcph));
12227 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12228 
12229 		/* Fill in our template header with basic timestamp option. */
12230 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12231 		tmp_tcph[0] = TCPOPT_NOP;
12232 		tmp_tcph[1] = TCPOPT_NOP;
12233 		tmp_tcph[2] = TCPOPT_TSTAMP;
12234 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12235 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12236 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12237 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12238 	} else {
12239 		tcp->tcp_snd_ts_ok = B_FALSE;
12240 	}
12241 
12242 	/*
12243 	 * Process SACK options.  If SACK is enabled for this connection,
12244 	 * then allocate the SACK info structure.  Note the following ways
12245 	 * when tcp_snd_sack_ok is set to true.
12246 	 *
12247 	 * For active connection: in tcp_adapt_ire() called in
12248 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12249 	 * is checked.
12250 	 *
12251 	 * For passive connection: in tcp_adapt_ire() called in
12252 	 * tcp_accept_comm().
12253 	 *
12254 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12255 	 * That check makes sure that if we did not send a SACK OK option,
12256 	 * we will not enable SACK for this connection even though the other
12257 	 * side sends us SACK OK option.  For active connection, the SACK
12258 	 * info structure has already been allocated.  So we need to free
12259 	 * it if SACK is disabled.
12260 	 */
12261 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12262 	    (tcp->tcp_snd_sack_ok ||
12263 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12264 		/* This should be true only in the passive case. */
12265 		if (tcp->tcp_sack_info == NULL) {
12266 			ASSERT(TCP_IS_DETACHED(tcp));
12267 			tcp->tcp_sack_info =
12268 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12269 		}
12270 		if (tcp->tcp_sack_info == NULL) {
12271 			tcp->tcp_snd_sack_ok = B_FALSE;
12272 		} else {
12273 			tcp->tcp_snd_sack_ok = B_TRUE;
12274 			if (tcp->tcp_snd_ts_ok) {
12275 				tcp->tcp_max_sack_blk = 3;
12276 			} else {
12277 				tcp->tcp_max_sack_blk = 4;
12278 			}
12279 		}
12280 	} else {
12281 		/*
12282 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12283 		 * no SACK info will be used for this
12284 		 * connection.  This assumes that SACK usage
12285 		 * permission is negotiated.  This may need
12286 		 * to be changed once this is clarified.
12287 		 */
12288 		if (tcp->tcp_sack_info != NULL) {
12289 			ASSERT(tcp->tcp_notsack_list == NULL);
12290 			kmem_cache_free(tcp_sack_info_cache,
12291 			    tcp->tcp_sack_info);
12292 			tcp->tcp_sack_info = NULL;
12293 		}
12294 		tcp->tcp_snd_sack_ok = B_FALSE;
12295 	}
12296 
12297 	/*
12298 	 * Now we know the exact TCP/IP header length, subtract
12299 	 * that from tcp_mss to get our side's MSS.
12300 	 */
12301 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12302 	/*
12303 	 * Here we assume that the other side's header size will be equal to
12304 	 * our header size.  We calculate the real MSS accordingly.  Need to
12305 	 * take into additional stuffs IPsec puts in.
12306 	 *
12307 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12308 	 */
12309 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12310 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12311 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12312 
12313 	/*
12314 	 * Set MSS to the smaller one of both ends of the connection.
12315 	 * We should not have called tcp_mss_set() before, but our
12316 	 * side of the MSS should have been set to a proper value
12317 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12318 	 * STREAM head parameters properly.
12319 	 *
12320 	 * If we have a larger-than-16-bit window but the other side
12321 	 * didn't want to do window scale, tcp_rwnd_set() will take
12322 	 * care of that.
12323 	 */
12324 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12325 }
12326 
12327 /*
12328  * Sends the T_CONN_IND to the listener. The caller calls this
12329  * functions via squeue to get inside the listener's perimeter
12330  * once the 3 way hand shake is done a T_CONN_IND needs to be
12331  * sent. As an optimization, the caller can call this directly
12332  * if listener's perimeter is same as eager's.
12333  */
12334 /* ARGSUSED */
12335 void
12336 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12337 {
12338 	conn_t			*lconnp = (conn_t *)arg;
12339 	tcp_t			*listener = lconnp->conn_tcp;
12340 	tcp_t			*tcp;
12341 	struct T_conn_ind	*conn_ind;
12342 	ipaddr_t 		*addr_cache;
12343 	boolean_t		need_send_conn_ind = B_FALSE;
12344 	tcp_stack_t		*tcps = listener->tcp_tcps;
12345 
12346 	/* retrieve the eager */
12347 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12348 	ASSERT(conn_ind->OPT_offset != 0 &&
12349 	    conn_ind->OPT_length == sizeof (intptr_t));
12350 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12351 	    conn_ind->OPT_length);
12352 
12353 	/*
12354 	 * TLI/XTI applications will get confused by
12355 	 * sending eager as an option since it violates
12356 	 * the option semantics. So remove the eager as
12357 	 * option since TLI/XTI app doesn't need it anyway.
12358 	 */
12359 	if (!TCP_IS_SOCKET(listener)) {
12360 		conn_ind->OPT_length = 0;
12361 		conn_ind->OPT_offset = 0;
12362 	}
12363 	if (listener->tcp_state == TCPS_CLOSED ||
12364 	    TCP_IS_DETACHED(listener)) {
12365 		/*
12366 		 * If listener has closed, it would have caused a
12367 		 * a cleanup/blowoff to happen for the eager. We
12368 		 * just need to return.
12369 		 */
12370 		freemsg(mp);
12371 		return;
12372 	}
12373 
12374 
12375 	/*
12376 	 * if the conn_req_q is full defer passing up the
12377 	 * T_CONN_IND until space is availabe after t_accept()
12378 	 * processing
12379 	 */
12380 	mutex_enter(&listener->tcp_eager_lock);
12381 
12382 	/*
12383 	 * Take the eager out, if it is in the list of droppable eagers
12384 	 * as we are here because the 3W handshake is over.
12385 	 */
12386 	MAKE_UNDROPPABLE(tcp);
12387 
12388 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12389 		tcp_t *tail;
12390 
12391 		/*
12392 		 * The eager already has an extra ref put in tcp_rput_data
12393 		 * so that it stays till accept comes back even though it
12394 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12395 		 */
12396 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12397 		listener->tcp_conn_req_cnt_q0--;
12398 		listener->tcp_conn_req_cnt_q++;
12399 
12400 		/* Move from SYN_RCVD to ESTABLISHED list  */
12401 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12402 		    tcp->tcp_eager_prev_q0;
12403 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12404 		    tcp->tcp_eager_next_q0;
12405 		tcp->tcp_eager_prev_q0 = NULL;
12406 		tcp->tcp_eager_next_q0 = NULL;
12407 
12408 		/*
12409 		 * Insert at end of the queue because sockfs
12410 		 * sends down T_CONN_RES in chronological
12411 		 * order. Leaving the older conn indications
12412 		 * at front of the queue helps reducing search
12413 		 * time.
12414 		 */
12415 		tail = listener->tcp_eager_last_q;
12416 		if (tail != NULL)
12417 			tail->tcp_eager_next_q = tcp;
12418 		else
12419 			listener->tcp_eager_next_q = tcp;
12420 		listener->tcp_eager_last_q = tcp;
12421 		tcp->tcp_eager_next_q = NULL;
12422 		/*
12423 		 * Delay sending up the T_conn_ind until we are
12424 		 * done with the eager. Once we have have sent up
12425 		 * the T_conn_ind, the accept can potentially complete
12426 		 * any time and release the refhold we have on the eager.
12427 		 */
12428 		need_send_conn_ind = B_TRUE;
12429 	} else {
12430 		/*
12431 		 * Defer connection on q0 and set deferred
12432 		 * connection bit true
12433 		 */
12434 		tcp->tcp_conn_def_q0 = B_TRUE;
12435 
12436 		/* take tcp out of q0 ... */
12437 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12438 		    tcp->tcp_eager_next_q0;
12439 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12440 		    tcp->tcp_eager_prev_q0;
12441 
12442 		/* ... and place it at the end of q0 */
12443 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12444 		tcp->tcp_eager_next_q0 = listener;
12445 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12446 		listener->tcp_eager_prev_q0 = tcp;
12447 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12448 	}
12449 
12450 	/* we have timed out before */
12451 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12452 		tcp->tcp_syn_rcvd_timeout = 0;
12453 		listener->tcp_syn_rcvd_timeout--;
12454 		if (listener->tcp_syn_defense &&
12455 		    listener->tcp_syn_rcvd_timeout <=
12456 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12457 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12458 		    listener->tcp_last_rcv_lbolt)) {
12459 			/*
12460 			 * Turn off the defense mode if we
12461 			 * believe the SYN attack is over.
12462 			 */
12463 			listener->tcp_syn_defense = B_FALSE;
12464 			if (listener->tcp_ip_addr_cache) {
12465 				kmem_free((void *)listener->tcp_ip_addr_cache,
12466 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12467 				listener->tcp_ip_addr_cache = NULL;
12468 			}
12469 		}
12470 	}
12471 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12472 	if (addr_cache != NULL) {
12473 		/*
12474 		 * We have finished a 3-way handshake with this
12475 		 * remote host. This proves the IP addr is good.
12476 		 * Cache it!
12477 		 */
12478 		addr_cache[IP_ADDR_CACHE_HASH(
12479 		    tcp->tcp_remote)] = tcp->tcp_remote;
12480 	}
12481 	mutex_exit(&listener->tcp_eager_lock);
12482 	if (need_send_conn_ind)
12483 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12484 }
12485 
12486 /*
12487  * Send the newconn notification to ulp. The eager is blown off if the
12488  * notification fails.
12489  */
12490 static void
12491 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12492 {
12493 	if (IPCL_IS_NONSTR(lconnp)) {
12494 		cred_t	*cr;
12495 		pid_t	cpid;
12496 
12497 		cr = msg_getcred(mp, &cpid);
12498 
12499 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12500 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12501 		    lconnp->conn_tcp);
12502 
12503 		/* Keep the message around in case of a fallback to TPI */
12504 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12505 
12506 		/*
12507 		 * Notify the ULP about the newconn. It is guaranteed that no
12508 		 * tcp_accept() call will be made for the eager if the
12509 		 * notification fails, so it's safe to blow it off in that
12510 		 * case.
12511 		 *
12512 		 * The upper handle will be assigned when tcp_accept() is
12513 		 * called.
12514 		 */
12515 		if ((*lconnp->conn_upcalls->su_newconn)
12516 		    (lconnp->conn_upper_handle,
12517 		    (sock_lower_handle_t)econnp,
12518 		    &sock_tcp_downcalls, cr, cpid,
12519 		    &econnp->conn_upcalls) == NULL) {
12520 			/* Failed to allocate a socket */
12521 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12522 			    tcpEstabResets);
12523 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12524 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12525 		}
12526 	} else {
12527 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12528 	}
12529 }
12530 
12531 mblk_t *
12532 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12533     uint_t *ifindexp, ip6_pkt_t *ippp)
12534 {
12535 	ip_pktinfo_t	*pinfo;
12536 	ip6_t		*ip6h;
12537 	uchar_t		*rptr;
12538 	mblk_t		*first_mp = mp;
12539 	boolean_t	mctl_present = B_FALSE;
12540 	uint_t 		ifindex = 0;
12541 	ip6_pkt_t	ipp;
12542 	uint_t		ipvers;
12543 	uint_t		ip_hdr_len;
12544 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12545 
12546 	rptr = mp->b_rptr;
12547 	ASSERT(OK_32PTR(rptr));
12548 	ASSERT(tcp != NULL);
12549 	ipp.ipp_fields = 0;
12550 
12551 	switch DB_TYPE(mp) {
12552 	case M_CTL:
12553 		mp = mp->b_cont;
12554 		if (mp == NULL) {
12555 			freemsg(first_mp);
12556 			return (NULL);
12557 		}
12558 		if (DB_TYPE(mp) != M_DATA) {
12559 			freemsg(first_mp);
12560 			return (NULL);
12561 		}
12562 		mctl_present = B_TRUE;
12563 		break;
12564 	case M_DATA:
12565 		break;
12566 	default:
12567 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12568 		freemsg(mp);
12569 		return (NULL);
12570 	}
12571 	ipvers = IPH_HDR_VERSION(rptr);
12572 	if (ipvers == IPV4_VERSION) {
12573 		if (tcp == NULL) {
12574 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12575 			goto done;
12576 		}
12577 
12578 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12579 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12580 
12581 		/*
12582 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12583 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12584 		 */
12585 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12586 		    mctl_present) {
12587 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12588 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12589 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12590 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12591 				ipp.ipp_fields |= IPPF_IFINDEX;
12592 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12593 				ifindex = pinfo->ip_pkt_ifindex;
12594 			}
12595 			freeb(first_mp);
12596 			mctl_present = B_FALSE;
12597 		}
12598 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12599 	} else {
12600 		ip6h = (ip6_t *)rptr;
12601 
12602 		ASSERT(ipvers == IPV6_VERSION);
12603 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12604 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12605 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12606 
12607 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12608 			uint8_t	nexthdrp;
12609 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12610 
12611 			/* Look for ifindex information */
12612 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12613 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12614 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12615 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12616 					freemsg(first_mp);
12617 					return (NULL);
12618 				}
12619 
12620 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12621 					ASSERT(ip6i->ip6i_ifindex != 0);
12622 					ipp.ipp_fields |= IPPF_IFINDEX;
12623 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12624 					ifindex = ip6i->ip6i_ifindex;
12625 				}
12626 				rptr = (uchar_t *)&ip6i[1];
12627 				mp->b_rptr = rptr;
12628 				if (rptr == mp->b_wptr) {
12629 					mblk_t *mp1;
12630 					mp1 = mp->b_cont;
12631 					freeb(mp);
12632 					mp = mp1;
12633 					rptr = mp->b_rptr;
12634 				}
12635 				if (MBLKL(mp) < IPV6_HDR_LEN +
12636 				    sizeof (tcph_t)) {
12637 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12638 					freemsg(first_mp);
12639 					return (NULL);
12640 				}
12641 				ip6h = (ip6_t *)rptr;
12642 			}
12643 
12644 			/*
12645 			 * Find any potentially interesting extension headers
12646 			 * as well as the length of the IPv6 + extension
12647 			 * headers.
12648 			 */
12649 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12650 			/* Verify if this is a TCP packet */
12651 			if (nexthdrp != IPPROTO_TCP) {
12652 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12653 				freemsg(first_mp);
12654 				return (NULL);
12655 			}
12656 		} else {
12657 			ip_hdr_len = IPV6_HDR_LEN;
12658 		}
12659 	}
12660 
12661 done:
12662 	if (ipversp != NULL)
12663 		*ipversp = ipvers;
12664 	if (ip_hdr_lenp != NULL)
12665 		*ip_hdr_lenp = ip_hdr_len;
12666 	if (ippp != NULL)
12667 		*ippp = ipp;
12668 	if (ifindexp != NULL)
12669 		*ifindexp = ifindex;
12670 	if (mctl_present) {
12671 		freeb(first_mp);
12672 	}
12673 	return (mp);
12674 }
12675 
12676 /*
12677  * Handle M_DATA messages from IP. Its called directly from IP via
12678  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12679  * in this path.
12680  *
12681  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12682  * v4 and v6), we are called through tcp_input() and a M_CTL can
12683  * be present for options but tcp_find_pktinfo() deals with it. We
12684  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12685  *
12686  * The first argument is always the connp/tcp to which the mp belongs.
12687  * There are no exceptions to this rule. The caller has already put
12688  * a reference on this connp/tcp and once tcp_rput_data() returns,
12689  * the squeue will do the refrele.
12690  *
12691  * The TH_SYN for the listener directly go to tcp_conn_request via
12692  * squeue.
12693  *
12694  * sqp: NULL = recursive, sqp != NULL means called from squeue
12695  */
12696 void
12697 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12698 {
12699 	int32_t		bytes_acked;
12700 	int32_t		gap;
12701 	mblk_t		*mp1;
12702 	uint_t		flags;
12703 	uint32_t	new_swnd = 0;
12704 	uchar_t		*iphdr;
12705 	uchar_t		*rptr;
12706 	int32_t		rgap;
12707 	uint32_t	seg_ack;
12708 	int		seg_len;
12709 	uint_t		ip_hdr_len;
12710 	uint32_t	seg_seq;
12711 	tcph_t		*tcph;
12712 	int		urp;
12713 	tcp_opt_t	tcpopt;
12714 	uint_t		ipvers;
12715 	ip6_pkt_t	ipp;
12716 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12717 	uint32_t	cwnd;
12718 	uint32_t	add;
12719 	int		npkt;
12720 	int		mss;
12721 	conn_t		*connp = (conn_t *)arg;
12722 	squeue_t	*sqp = (squeue_t *)arg2;
12723 	tcp_t		*tcp = connp->conn_tcp;
12724 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12725 
12726 	/*
12727 	 * RST from fused tcp loopback peer should trigger an unfuse.
12728 	 */
12729 	if (tcp->tcp_fused) {
12730 		TCP_STAT(tcps, tcp_fusion_aborted);
12731 		tcp_unfuse(tcp);
12732 	}
12733 
12734 	iphdr = mp->b_rptr;
12735 	rptr = mp->b_rptr;
12736 	ASSERT(OK_32PTR(rptr));
12737 
12738 	/*
12739 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12740 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12741 	 * necessary information.
12742 	 */
12743 	if (IPCL_IS_TCP4(connp)) {
12744 		ipvers = IPV4_VERSION;
12745 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12746 	} else {
12747 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12748 		    NULL, &ipp);
12749 		if (mp == NULL) {
12750 			TCP_STAT(tcps, tcp_rput_v6_error);
12751 			return;
12752 		}
12753 		iphdr = mp->b_rptr;
12754 		rptr = mp->b_rptr;
12755 	}
12756 	ASSERT(DB_TYPE(mp) == M_DATA);
12757 	ASSERT(mp->b_next == NULL);
12758 
12759 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12760 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12761 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12762 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12763 	seg_len = (int)(mp->b_wptr - rptr) -
12764 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12765 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12766 		do {
12767 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12768 			    (uintptr_t)INT_MAX);
12769 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12770 		} while ((mp1 = mp1->b_cont) != NULL &&
12771 		    mp1->b_datap->db_type == M_DATA);
12772 	}
12773 
12774 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12775 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12776 		    seg_len, tcph);
12777 		return;
12778 	}
12779 
12780 	if (sqp != NULL) {
12781 		/*
12782 		 * This is the correct place to update tcp_last_recv_time. Note
12783 		 * that it is also updated for tcp structure that belongs to
12784 		 * global and listener queues which do not really need updating.
12785 		 * But that should not cause any harm.  And it is updated for
12786 		 * all kinds of incoming segments, not only for data segments.
12787 		 */
12788 		tcp->tcp_last_recv_time = lbolt;
12789 	}
12790 
12791 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12792 
12793 	BUMP_LOCAL(tcp->tcp_ibsegs);
12794 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12795 
12796 	if ((flags & TH_URG) && sqp != NULL) {
12797 		/*
12798 		 * TCP can't handle urgent pointers that arrive before
12799 		 * the connection has been accept()ed since it can't
12800 		 * buffer OOB data.  Discard segment if this happens.
12801 		 *
12802 		 * We can't just rely on a non-null tcp_listener to indicate
12803 		 * that the accept() has completed since unlinking of the
12804 		 * eager and completion of the accept are not atomic.
12805 		 * tcp_detached, when it is not set (B_FALSE) indicates
12806 		 * that the accept() has completed.
12807 		 *
12808 		 * Nor can it reassemble urgent pointers, so discard
12809 		 * if it's not the next segment expected.
12810 		 *
12811 		 * Otherwise, collapse chain into one mblk (discard if
12812 		 * that fails).  This makes sure the headers, retransmitted
12813 		 * data, and new data all are in the same mblk.
12814 		 */
12815 		ASSERT(mp != NULL);
12816 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12817 			freemsg(mp);
12818 			return;
12819 		}
12820 		/* Update pointers into message */
12821 		iphdr = rptr = mp->b_rptr;
12822 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12823 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12824 			/*
12825 			 * Since we can't handle any data with this urgent
12826 			 * pointer that is out of sequence, we expunge
12827 			 * the data.  This allows us to still register
12828 			 * the urgent mark and generate the M_PCSIG,
12829 			 * which we can do.
12830 			 */
12831 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12832 			seg_len = 0;
12833 		}
12834 	}
12835 
12836 	switch (tcp->tcp_state) {
12837 	case TCPS_SYN_SENT:
12838 		if (flags & TH_ACK) {
12839 			/*
12840 			 * Note that our stack cannot send data before a
12841 			 * connection is established, therefore the
12842 			 * following check is valid.  Otherwise, it has
12843 			 * to be changed.
12844 			 */
12845 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12846 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12847 				freemsg(mp);
12848 				if (flags & TH_RST)
12849 					return;
12850 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12851 				    tcp, seg_ack, 0, TH_RST);
12852 				return;
12853 			}
12854 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12855 		}
12856 		if (flags & TH_RST) {
12857 			freemsg(mp);
12858 			if (flags & TH_ACK)
12859 				(void) tcp_clean_death(tcp,
12860 				    ECONNREFUSED, 13);
12861 			return;
12862 		}
12863 		if (!(flags & TH_SYN)) {
12864 			freemsg(mp);
12865 			return;
12866 		}
12867 
12868 		/* Process all TCP options. */
12869 		tcp_process_options(tcp, tcph);
12870 		/*
12871 		 * The following changes our rwnd to be a multiple of the
12872 		 * MIN(peer MSS, our MSS) for performance reason.
12873 		 */
12874 		(void) tcp_rwnd_set(tcp,
12875 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
12876 
12877 		/* Is the other end ECN capable? */
12878 		if (tcp->tcp_ecn_ok) {
12879 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12880 				tcp->tcp_ecn_ok = B_FALSE;
12881 			}
12882 		}
12883 		/*
12884 		 * Clear ECN flags because it may interfere with later
12885 		 * processing.
12886 		 */
12887 		flags &= ~(TH_ECE|TH_CWR);
12888 
12889 		tcp->tcp_irs = seg_seq;
12890 		tcp->tcp_rack = seg_seq;
12891 		tcp->tcp_rnxt = seg_seq + 1;
12892 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12893 		if (!TCP_IS_DETACHED(tcp)) {
12894 			/* Allocate room for SACK options if needed. */
12895 			if (tcp->tcp_snd_sack_ok) {
12896 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12897 				    tcp->tcp_hdr_len +
12898 				    TCPOPT_MAX_SACK_LEN +
12899 				    (tcp->tcp_loopback ? 0 :
12900 				    tcps->tcps_wroff_xtra));
12901 			} else {
12902 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12903 				    tcp->tcp_hdr_len +
12904 				    (tcp->tcp_loopback ? 0 :
12905 				    tcps->tcps_wroff_xtra));
12906 			}
12907 		}
12908 		if (flags & TH_ACK) {
12909 			/*
12910 			 * If we can't get the confirmation upstream, pretend
12911 			 * we didn't even see this one.
12912 			 *
12913 			 * XXX: how can we pretend we didn't see it if we
12914 			 * have updated rnxt et. al.
12915 			 *
12916 			 * For loopback we defer sending up the T_CONN_CON
12917 			 * until after some checks below.
12918 			 */
12919 			mp1 = NULL;
12920 			/*
12921 			 * tcp_sendmsg() checks tcp_state without entering
12922 			 * the squeue so tcp_state should be updated before
12923 			 * sending up connection confirmation
12924 			 */
12925 			tcp->tcp_state = TCPS_ESTABLISHED;
12926 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12927 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12928 				tcp->tcp_state = TCPS_SYN_SENT;
12929 				freemsg(mp);
12930 				return;
12931 			}
12932 			/* SYN was acked - making progress */
12933 			if (tcp->tcp_ipversion == IPV6_VERSION)
12934 				tcp->tcp_ip_forward_progress = B_TRUE;
12935 
12936 			/* One for the SYN */
12937 			tcp->tcp_suna = tcp->tcp_iss + 1;
12938 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12939 
12940 			/*
12941 			 * If SYN was retransmitted, need to reset all
12942 			 * retransmission info.  This is because this
12943 			 * segment will be treated as a dup ACK.
12944 			 */
12945 			if (tcp->tcp_rexmit) {
12946 				tcp->tcp_rexmit = B_FALSE;
12947 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12948 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12949 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12950 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12951 				tcp->tcp_ms_we_have_waited = 0;
12952 
12953 				/*
12954 				 * Set tcp_cwnd back to 1 MSS, per
12955 				 * recommendation from
12956 				 * draft-floyd-incr-init-win-01.txt,
12957 				 * Increasing TCP's Initial Window.
12958 				 */
12959 				tcp->tcp_cwnd = tcp->tcp_mss;
12960 			}
12961 
12962 			tcp->tcp_swl1 = seg_seq;
12963 			tcp->tcp_swl2 = seg_ack;
12964 
12965 			new_swnd = BE16_TO_U16(tcph->th_win);
12966 			tcp->tcp_swnd = new_swnd;
12967 			if (new_swnd > tcp->tcp_max_swnd)
12968 				tcp->tcp_max_swnd = new_swnd;
12969 
12970 			/*
12971 			 * Always send the three-way handshake ack immediately
12972 			 * in order to make the connection complete as soon as
12973 			 * possible on the accepting host.
12974 			 */
12975 			flags |= TH_ACK_NEEDED;
12976 
12977 			/*
12978 			 * Special case for loopback.  At this point we have
12979 			 * received SYN-ACK from the remote endpoint.  In
12980 			 * order to ensure that both endpoints reach the
12981 			 * fused state prior to any data exchange, the final
12982 			 * ACK needs to be sent before we indicate T_CONN_CON
12983 			 * to the module upstream.
12984 			 */
12985 			if (tcp->tcp_loopback) {
12986 				mblk_t *ack_mp;
12987 
12988 				ASSERT(!tcp->tcp_unfusable);
12989 				ASSERT(mp1 != NULL);
12990 				/*
12991 				 * For loopback, we always get a pure SYN-ACK
12992 				 * and only need to send back the final ACK
12993 				 * with no data (this is because the other
12994 				 * tcp is ours and we don't do T/TCP).  This
12995 				 * final ACK triggers the passive side to
12996 				 * perform fusion in ESTABLISHED state.
12997 				 */
12998 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12999 					if (tcp->tcp_ack_tid != 0) {
13000 						(void) TCP_TIMER_CANCEL(tcp,
13001 						    tcp->tcp_ack_tid);
13002 						tcp->tcp_ack_tid = 0;
13003 					}
13004 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13005 					BUMP_LOCAL(tcp->tcp_obsegs);
13006 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13007 
13008 					if (!IPCL_IS_NONSTR(connp)) {
13009 						/* Send up T_CONN_CON */
13010 						putnext(tcp->tcp_rq, mp1);
13011 					} else {
13012 						cred_t	*cr;
13013 						pid_t	cpid;
13014 
13015 						cr = msg_getcred(mp1, &cpid);
13016 						(*connp->conn_upcalls->
13017 						    su_connected)
13018 						    (connp->conn_upper_handle,
13019 						    tcp->tcp_connid, cr, cpid);
13020 						freemsg(mp1);
13021 					}
13022 
13023 					freemsg(mp);
13024 					return;
13025 				}
13026 				/*
13027 				 * Forget fusion; we need to handle more
13028 				 * complex cases below.  Send the deferred
13029 				 * T_CONN_CON message upstream and proceed
13030 				 * as usual.  Mark this tcp as not capable
13031 				 * of fusion.
13032 				 */
13033 				TCP_STAT(tcps, tcp_fusion_unfusable);
13034 				tcp->tcp_unfusable = B_TRUE;
13035 				if (!IPCL_IS_NONSTR(connp)) {
13036 					putnext(tcp->tcp_rq, mp1);
13037 				} else {
13038 					cred_t	*cr;
13039 					pid_t	cpid;
13040 
13041 					cr = msg_getcred(mp1, &cpid);
13042 					(*connp->conn_upcalls->su_connected)
13043 					    (connp->conn_upper_handle,
13044 					    tcp->tcp_connid, cr, cpid);
13045 					freemsg(mp1);
13046 				}
13047 			}
13048 
13049 			/*
13050 			 * Check to see if there is data to be sent.  If
13051 			 * yes, set the transmit flag.  Then check to see
13052 			 * if received data processing needs to be done.
13053 			 * If not, go straight to xmit_check.  This short
13054 			 * cut is OK as we don't support T/TCP.
13055 			 */
13056 			if (tcp->tcp_unsent)
13057 				flags |= TH_XMIT_NEEDED;
13058 
13059 			if (seg_len == 0 && !(flags & TH_URG)) {
13060 				freemsg(mp);
13061 				goto xmit_check;
13062 			}
13063 
13064 			flags &= ~TH_SYN;
13065 			seg_seq++;
13066 			break;
13067 		}
13068 		tcp->tcp_state = TCPS_SYN_RCVD;
13069 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13070 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13071 		if (mp1) {
13072 			/*
13073 			 * See comment in tcp_conn_request() for why we use
13074 			 * the open() time pid here.
13075 			 */
13076 			DB_CPID(mp1) = tcp->tcp_cpid;
13077 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13078 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13079 		}
13080 		freemsg(mp);
13081 		return;
13082 	case TCPS_SYN_RCVD:
13083 		if (flags & TH_ACK) {
13084 			/*
13085 			 * In this state, a SYN|ACK packet is either bogus
13086 			 * because the other side must be ACKing our SYN which
13087 			 * indicates it has seen the ACK for their SYN and
13088 			 * shouldn't retransmit it or we're crossing SYNs
13089 			 * on active open.
13090 			 */
13091 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13092 				freemsg(mp);
13093 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13094 				    tcp, seg_ack, 0, TH_RST);
13095 				return;
13096 			}
13097 			/*
13098 			 * NOTE: RFC 793 pg. 72 says this should be
13099 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13100 			 * but that would mean we have an ack that ignored
13101 			 * our SYN.
13102 			 */
13103 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13104 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13105 				freemsg(mp);
13106 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13107 				    tcp, seg_ack, 0, TH_RST);
13108 				return;
13109 			}
13110 		}
13111 		break;
13112 	case TCPS_LISTEN:
13113 		/*
13114 		 * Only a TLI listener can come through this path when a
13115 		 * acceptor is going back to be a listener and a packet
13116 		 * for the acceptor hits the classifier. For a socket
13117 		 * listener, this can never happen because a listener
13118 		 * can never accept connection on itself and hence a
13119 		 * socket acceptor can not go back to being a listener.
13120 		 */
13121 		ASSERT(!TCP_IS_SOCKET(tcp));
13122 		/*FALLTHRU*/
13123 	case TCPS_CLOSED:
13124 	case TCPS_BOUND: {
13125 		conn_t	*new_connp;
13126 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13127 
13128 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13129 		if (new_connp != NULL) {
13130 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13131 			return;
13132 		}
13133 		/* We failed to classify. For now just drop the packet */
13134 		freemsg(mp);
13135 		return;
13136 	}
13137 	case TCPS_IDLE:
13138 		/*
13139 		 * Handle the case where the tcp_clean_death() has happened
13140 		 * on a connection (application hasn't closed yet) but a packet
13141 		 * was already queued on squeue before tcp_clean_death()
13142 		 * was processed. Calling tcp_clean_death() twice on same
13143 		 * connection can result in weird behaviour.
13144 		 */
13145 		freemsg(mp);
13146 		return;
13147 	default:
13148 		break;
13149 	}
13150 
13151 	/*
13152 	 * Already on the correct queue/perimeter.
13153 	 * If this is a detached connection and not an eager
13154 	 * connection hanging off a listener then new data
13155 	 * (past the FIN) will cause a reset.
13156 	 * We do a special check here where it
13157 	 * is out of the main line, rather than check
13158 	 * if we are detached every time we see new
13159 	 * data down below.
13160 	 */
13161 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13162 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13163 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13164 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13165 
13166 		freemsg(mp);
13167 		/*
13168 		 * This could be an SSL closure alert. We're detached so just
13169 		 * acknowledge it this last time.
13170 		 */
13171 		if (tcp->tcp_kssl_ctx != NULL) {
13172 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13173 			tcp->tcp_kssl_ctx = NULL;
13174 
13175 			tcp->tcp_rnxt += seg_len;
13176 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13177 			flags |= TH_ACK_NEEDED;
13178 			goto ack_check;
13179 		}
13180 
13181 		tcp_xmit_ctl("new data when detached", tcp,
13182 		    tcp->tcp_snxt, 0, TH_RST);
13183 		(void) tcp_clean_death(tcp, EPROTO, 12);
13184 		return;
13185 	}
13186 
13187 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13188 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13189 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13190 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13191 
13192 	if (tcp->tcp_snd_ts_ok) {
13193 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13194 			/*
13195 			 * This segment is not acceptable.
13196 			 * Drop it and send back an ACK.
13197 			 */
13198 			freemsg(mp);
13199 			flags |= TH_ACK_NEEDED;
13200 			goto ack_check;
13201 		}
13202 	} else if (tcp->tcp_snd_sack_ok) {
13203 		ASSERT(tcp->tcp_sack_info != NULL);
13204 		tcpopt.tcp = tcp;
13205 		/*
13206 		 * SACK info in already updated in tcp_parse_options.  Ignore
13207 		 * all other TCP options...
13208 		 */
13209 		(void) tcp_parse_options(tcph, &tcpopt);
13210 	}
13211 try_again:;
13212 	mss = tcp->tcp_mss;
13213 	gap = seg_seq - tcp->tcp_rnxt;
13214 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13215 	/*
13216 	 * gap is the amount of sequence space between what we expect to see
13217 	 * and what we got for seg_seq.  A positive value for gap means
13218 	 * something got lost.  A negative value means we got some old stuff.
13219 	 */
13220 	if (gap < 0) {
13221 		/* Old stuff present.  Is the SYN in there? */
13222 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13223 		    (seg_len != 0)) {
13224 			flags &= ~TH_SYN;
13225 			seg_seq++;
13226 			urp--;
13227 			/* Recompute the gaps after noting the SYN. */
13228 			goto try_again;
13229 		}
13230 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13231 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13232 		    (seg_len > -gap ? -gap : seg_len));
13233 		/* Remove the old stuff from seg_len. */
13234 		seg_len += gap;
13235 		/*
13236 		 * Anything left?
13237 		 * Make sure to check for unack'd FIN when rest of data
13238 		 * has been previously ack'd.
13239 		 */
13240 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13241 			/*
13242 			 * Resets are only valid if they lie within our offered
13243 			 * window.  If the RST bit is set, we just ignore this
13244 			 * segment.
13245 			 */
13246 			if (flags & TH_RST) {
13247 				freemsg(mp);
13248 				return;
13249 			}
13250 
13251 			/*
13252 			 * The arriving of dup data packets indicate that we
13253 			 * may have postponed an ack for too long, or the other
13254 			 * side's RTT estimate is out of shape. Start acking
13255 			 * more often.
13256 			 */
13257 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13258 			    tcp->tcp_rack_cnt >= 1 &&
13259 			    tcp->tcp_rack_abs_max > 2) {
13260 				tcp->tcp_rack_abs_max--;
13261 			}
13262 			tcp->tcp_rack_cur_max = 1;
13263 
13264 			/*
13265 			 * This segment is "unacceptable".  None of its
13266 			 * sequence space lies within our advertized window.
13267 			 *
13268 			 * Adjust seg_len to the original value for tracing.
13269 			 */
13270 			seg_len -= gap;
13271 			if (tcp->tcp_debug) {
13272 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13273 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13274 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13275 				    "seg_len %d, rnxt %u, snxt %u, %s",
13276 				    gap, rgap, flags, seg_seq, seg_ack,
13277 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13278 				    tcp_display(tcp, NULL,
13279 				    DISP_ADDR_AND_PORT));
13280 			}
13281 
13282 			/*
13283 			 * Arrange to send an ACK in response to the
13284 			 * unacceptable segment per RFC 793 page 69. There
13285 			 * is only one small difference between ours and the
13286 			 * acceptability test in the RFC - we accept ACK-only
13287 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13288 			 * will be generated.
13289 			 *
13290 			 * Note that we have to ACK an ACK-only packet at least
13291 			 * for stacks that send 0-length keep-alives with
13292 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13293 			 * section 4.2.3.6. As long as we don't ever generate
13294 			 * an unacceptable packet in response to an incoming
13295 			 * packet that is unacceptable, it should not cause
13296 			 * "ACK wars".
13297 			 */
13298 			flags |=  TH_ACK_NEEDED;
13299 
13300 			/*
13301 			 * Continue processing this segment in order to use the
13302 			 * ACK information it contains, but skip all other
13303 			 * sequence-number processing.	Processing the ACK
13304 			 * information is necessary in order to
13305 			 * re-synchronize connections that may have lost
13306 			 * synchronization.
13307 			 *
13308 			 * We clear seg_len and flag fields related to
13309 			 * sequence number processing as they are not
13310 			 * to be trusted for an unacceptable segment.
13311 			 */
13312 			seg_len = 0;
13313 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13314 			goto process_ack;
13315 		}
13316 
13317 		/* Fix seg_seq, and chew the gap off the front. */
13318 		seg_seq = tcp->tcp_rnxt;
13319 		urp += gap;
13320 		do {
13321 			mblk_t	*mp2;
13322 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13323 			    (uintptr_t)UINT_MAX);
13324 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13325 			if (gap > 0) {
13326 				mp->b_rptr = mp->b_wptr - gap;
13327 				break;
13328 			}
13329 			mp2 = mp;
13330 			mp = mp->b_cont;
13331 			freeb(mp2);
13332 		} while (gap < 0);
13333 		/*
13334 		 * If the urgent data has already been acknowledged, we
13335 		 * should ignore TH_URG below
13336 		 */
13337 		if (urp < 0)
13338 			flags &= ~TH_URG;
13339 	}
13340 	/*
13341 	 * rgap is the amount of stuff received out of window.  A negative
13342 	 * value is the amount out of window.
13343 	 */
13344 	if (rgap < 0) {
13345 		mblk_t	*mp2;
13346 
13347 		if (tcp->tcp_rwnd == 0) {
13348 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13349 		} else {
13350 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13351 			UPDATE_MIB(&tcps->tcps_mib,
13352 			    tcpInDataPastWinBytes, -rgap);
13353 		}
13354 
13355 		/*
13356 		 * seg_len does not include the FIN, so if more than
13357 		 * just the FIN is out of window, we act like we don't
13358 		 * see it.  (If just the FIN is out of window, rgap
13359 		 * will be zero and we will go ahead and acknowledge
13360 		 * the FIN.)
13361 		 */
13362 		flags &= ~TH_FIN;
13363 
13364 		/* Fix seg_len and make sure there is something left. */
13365 		seg_len += rgap;
13366 		if (seg_len <= 0) {
13367 			/*
13368 			 * Resets are only valid if they lie within our offered
13369 			 * window.  If the RST bit is set, we just ignore this
13370 			 * segment.
13371 			 */
13372 			if (flags & TH_RST) {
13373 				freemsg(mp);
13374 				return;
13375 			}
13376 
13377 			/* Per RFC 793, we need to send back an ACK. */
13378 			flags |= TH_ACK_NEEDED;
13379 
13380 			/*
13381 			 * Send SIGURG as soon as possible i.e. even
13382 			 * if the TH_URG was delivered in a window probe
13383 			 * packet (which will be unacceptable).
13384 			 *
13385 			 * We generate a signal if none has been generated
13386 			 * for this connection or if this is a new urgent
13387 			 * byte. Also send a zero-length "unmarked" message
13388 			 * to inform SIOCATMARK that this is not the mark.
13389 			 *
13390 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13391 			 * is sent up. This plus the check for old data
13392 			 * (gap >= 0) handles the wraparound of the sequence
13393 			 * number space without having to always track the
13394 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13395 			 * this max in its rcv_up variable).
13396 			 *
13397 			 * This prevents duplicate SIGURGS due to a "late"
13398 			 * zero-window probe when the T_EXDATA_IND has already
13399 			 * been sent up.
13400 			 */
13401 			if ((flags & TH_URG) &&
13402 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13403 			    tcp->tcp_urp_last))) {
13404 				if (IPCL_IS_NONSTR(connp)) {
13405 					if (!TCP_IS_DETACHED(tcp)) {
13406 						(*connp->conn_upcalls->
13407 						    su_signal_oob)
13408 						    (connp->conn_upper_handle,
13409 						    urp);
13410 					}
13411 				} else {
13412 					mp1 = allocb(0, BPRI_MED);
13413 					if (mp1 == NULL) {
13414 						freemsg(mp);
13415 						return;
13416 					}
13417 					if (!TCP_IS_DETACHED(tcp) &&
13418 					    !putnextctl1(tcp->tcp_rq,
13419 					    M_PCSIG, SIGURG)) {
13420 						/* Try again on the rexmit. */
13421 						freemsg(mp1);
13422 						freemsg(mp);
13423 						return;
13424 					}
13425 					/*
13426 					 * If the next byte would be the mark
13427 					 * then mark with MARKNEXT else mark
13428 					 * with NOTMARKNEXT.
13429 					 */
13430 					if (gap == 0 && urp == 0)
13431 						mp1->b_flag |= MSGMARKNEXT;
13432 					else
13433 						mp1->b_flag |= MSGNOTMARKNEXT;
13434 					freemsg(tcp->tcp_urp_mark_mp);
13435 					tcp->tcp_urp_mark_mp = mp1;
13436 					flags |= TH_SEND_URP_MARK;
13437 				}
13438 				tcp->tcp_urp_last_valid = B_TRUE;
13439 				tcp->tcp_urp_last = urp + seg_seq;
13440 			}
13441 			/*
13442 			 * If this is a zero window probe, continue to
13443 			 * process the ACK part.  But we need to set seg_len
13444 			 * to 0 to avoid data processing.  Otherwise just
13445 			 * drop the segment and send back an ACK.
13446 			 */
13447 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13448 				flags &= ~(TH_SYN | TH_URG);
13449 				seg_len = 0;
13450 				goto process_ack;
13451 			} else {
13452 				freemsg(mp);
13453 				goto ack_check;
13454 			}
13455 		}
13456 		/* Pitch out of window stuff off the end. */
13457 		rgap = seg_len;
13458 		mp2 = mp;
13459 		do {
13460 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13461 			    (uintptr_t)INT_MAX);
13462 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13463 			if (rgap < 0) {
13464 				mp2->b_wptr += rgap;
13465 				if ((mp1 = mp2->b_cont) != NULL) {
13466 					mp2->b_cont = NULL;
13467 					freemsg(mp1);
13468 				}
13469 				break;
13470 			}
13471 		} while ((mp2 = mp2->b_cont) != NULL);
13472 	}
13473 ok:;
13474 	/*
13475 	 * TCP should check ECN info for segments inside the window only.
13476 	 * Therefore the check should be done here.
13477 	 */
13478 	if (tcp->tcp_ecn_ok) {
13479 		if (flags & TH_CWR) {
13480 			tcp->tcp_ecn_echo_on = B_FALSE;
13481 		}
13482 		/*
13483 		 * Note that both ECN_CE and CWR can be set in the
13484 		 * same segment.  In this case, we once again turn
13485 		 * on ECN_ECHO.
13486 		 */
13487 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13488 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13489 
13490 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13491 				tcp->tcp_ecn_echo_on = B_TRUE;
13492 			}
13493 		} else {
13494 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13495 
13496 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13497 			    htonl(IPH_ECN_CE << 20)) {
13498 				tcp->tcp_ecn_echo_on = B_TRUE;
13499 			}
13500 		}
13501 	}
13502 
13503 	/*
13504 	 * Check whether we can update tcp_ts_recent.  This test is
13505 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13506 	 * Extensions for High Performance: An Update", Internet Draft.
13507 	 */
13508 	if (tcp->tcp_snd_ts_ok &&
13509 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13510 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13511 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13512 		tcp->tcp_last_rcv_lbolt = lbolt64;
13513 	}
13514 
13515 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13516 		/*
13517 		 * FIN in an out of order segment.  We record this in
13518 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13519 		 * Clear the FIN so that any check on FIN flag will fail.
13520 		 * Remember that FIN also counts in the sequence number
13521 		 * space.  So we need to ack out of order FIN only segments.
13522 		 */
13523 		if (flags & TH_FIN) {
13524 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13525 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13526 			flags &= ~TH_FIN;
13527 			flags |= TH_ACK_NEEDED;
13528 		}
13529 		if (seg_len > 0) {
13530 			/* Fill in the SACK blk list. */
13531 			if (tcp->tcp_snd_sack_ok) {
13532 				ASSERT(tcp->tcp_sack_info != NULL);
13533 				tcp_sack_insert(tcp->tcp_sack_list,
13534 				    seg_seq, seg_seq + seg_len,
13535 				    &(tcp->tcp_num_sack_blk));
13536 			}
13537 
13538 			/*
13539 			 * Attempt reassembly and see if we have something
13540 			 * ready to go.
13541 			 */
13542 			mp = tcp_reass(tcp, mp, seg_seq);
13543 			/* Always ack out of order packets */
13544 			flags |= TH_ACK_NEEDED | TH_PUSH;
13545 			if (mp) {
13546 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13547 				    (uintptr_t)INT_MAX);
13548 				seg_len = mp->b_cont ? msgdsize(mp) :
13549 				    (int)(mp->b_wptr - mp->b_rptr);
13550 				seg_seq = tcp->tcp_rnxt;
13551 				/*
13552 				 * A gap is filled and the seq num and len
13553 				 * of the gap match that of a previously
13554 				 * received FIN, put the FIN flag back in.
13555 				 */
13556 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13557 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13558 					flags |= TH_FIN;
13559 					tcp->tcp_valid_bits &=
13560 					    ~TCP_OFO_FIN_VALID;
13561 				}
13562 			} else {
13563 				/*
13564 				 * Keep going even with NULL mp.
13565 				 * There may be a useful ACK or something else
13566 				 * we don't want to miss.
13567 				 *
13568 				 * But TCP should not perform fast retransmit
13569 				 * because of the ack number.  TCP uses
13570 				 * seg_len == 0 to determine if it is a pure
13571 				 * ACK.  And this is not a pure ACK.
13572 				 */
13573 				seg_len = 0;
13574 				ofo_seg = B_TRUE;
13575 			}
13576 		}
13577 	} else if (seg_len > 0) {
13578 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13579 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13580 		/*
13581 		 * If an out of order FIN was received before, and the seq
13582 		 * num and len of the new segment match that of the FIN,
13583 		 * put the FIN flag back in.
13584 		 */
13585 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13586 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13587 			flags |= TH_FIN;
13588 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13589 		}
13590 	}
13591 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13592 	if (flags & TH_RST) {
13593 		freemsg(mp);
13594 		switch (tcp->tcp_state) {
13595 		case TCPS_SYN_RCVD:
13596 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13597 			break;
13598 		case TCPS_ESTABLISHED:
13599 		case TCPS_FIN_WAIT_1:
13600 		case TCPS_FIN_WAIT_2:
13601 		case TCPS_CLOSE_WAIT:
13602 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13603 			break;
13604 		case TCPS_CLOSING:
13605 		case TCPS_LAST_ACK:
13606 			(void) tcp_clean_death(tcp, 0, 16);
13607 			break;
13608 		default:
13609 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13610 			(void) tcp_clean_death(tcp, ENXIO, 17);
13611 			break;
13612 		}
13613 		return;
13614 	}
13615 	if (flags & TH_SYN) {
13616 		/*
13617 		 * See RFC 793, Page 71
13618 		 *
13619 		 * The seq number must be in the window as it should
13620 		 * be "fixed" above.  If it is outside window, it should
13621 		 * be already rejected.  Note that we allow seg_seq to be
13622 		 * rnxt + rwnd because we want to accept 0 window probe.
13623 		 */
13624 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13625 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13626 		freemsg(mp);
13627 		/*
13628 		 * If the ACK flag is not set, just use our snxt as the
13629 		 * seq number of the RST segment.
13630 		 */
13631 		if (!(flags & TH_ACK)) {
13632 			seg_ack = tcp->tcp_snxt;
13633 		}
13634 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13635 		    TH_RST|TH_ACK);
13636 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13637 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13638 		return;
13639 	}
13640 	/*
13641 	 * urp could be -1 when the urp field in the packet is 0
13642 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13643 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13644 	 */
13645 	if (flags & TH_URG && urp >= 0) {
13646 		if (!tcp->tcp_urp_last_valid ||
13647 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13648 			if (IPCL_IS_NONSTR(connp)) {
13649 				if (!TCP_IS_DETACHED(tcp)) {
13650 					(*connp->conn_upcalls->su_signal_oob)
13651 					    (connp->conn_upper_handle, urp);
13652 				}
13653 			} else {
13654 				/*
13655 				 * If we haven't generated the signal yet for
13656 				 * this urgent pointer value, do it now.  Also,
13657 				 * send up a zero-length M_DATA indicating
13658 				 * whether or not this is the mark. The latter
13659 				 * is not needed when a T_EXDATA_IND is sent up.
13660 				 * However, if there are allocation failures
13661 				 * this code relies on the sender retransmitting
13662 				 * and the socket code for determining the mark
13663 				 * should not block waiting for the peer to
13664 				 * transmit. Thus, for simplicity we always
13665 				 * send up the mark indication.
13666 				 */
13667 				mp1 = allocb(0, BPRI_MED);
13668 				if (mp1 == NULL) {
13669 					freemsg(mp);
13670 					return;
13671 				}
13672 				if (!TCP_IS_DETACHED(tcp) &&
13673 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13674 				    SIGURG)) {
13675 					/* Try again on the rexmit. */
13676 					freemsg(mp1);
13677 					freemsg(mp);
13678 					return;
13679 				}
13680 				/*
13681 				 * Mark with NOTMARKNEXT for now.
13682 				 * The code below will change this to MARKNEXT
13683 				 * if we are at the mark.
13684 				 *
13685 				 * If there are allocation failures (e.g. in
13686 				 * dupmsg below) the next time tcp_rput_data
13687 				 * sees the urgent segment it will send up the
13688 				 * MSGMARKNEXT message.
13689 				 */
13690 				mp1->b_flag |= MSGNOTMARKNEXT;
13691 				freemsg(tcp->tcp_urp_mark_mp);
13692 				tcp->tcp_urp_mark_mp = mp1;
13693 				flags |= TH_SEND_URP_MARK;
13694 #ifdef DEBUG
13695 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13696 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13697 				    "last %x, %s",
13698 				    seg_seq, urp, tcp->tcp_urp_last,
13699 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13700 #endif /* DEBUG */
13701 			}
13702 			tcp->tcp_urp_last_valid = B_TRUE;
13703 			tcp->tcp_urp_last = urp + seg_seq;
13704 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13705 			/*
13706 			 * An allocation failure prevented the previous
13707 			 * tcp_rput_data from sending up the allocated
13708 			 * MSG*MARKNEXT message - send it up this time
13709 			 * around.
13710 			 */
13711 			flags |= TH_SEND_URP_MARK;
13712 		}
13713 
13714 		/*
13715 		 * If the urgent byte is in this segment, make sure that it is
13716 		 * all by itself.  This makes it much easier to deal with the
13717 		 * possibility of an allocation failure on the T_exdata_ind.
13718 		 * Note that seg_len is the number of bytes in the segment, and
13719 		 * urp is the offset into the segment of the urgent byte.
13720 		 * urp < seg_len means that the urgent byte is in this segment.
13721 		 */
13722 		if (urp < seg_len) {
13723 			if (seg_len != 1) {
13724 				uint32_t  tmp_rnxt;
13725 				/*
13726 				 * Break it up and feed it back in.
13727 				 * Re-attach the IP header.
13728 				 */
13729 				mp->b_rptr = iphdr;
13730 				if (urp > 0) {
13731 					/*
13732 					 * There is stuff before the urgent
13733 					 * byte.
13734 					 */
13735 					mp1 = dupmsg(mp);
13736 					if (!mp1) {
13737 						/*
13738 						 * Trim from urgent byte on.
13739 						 * The rest will come back.
13740 						 */
13741 						(void) adjmsg(mp,
13742 						    urp - seg_len);
13743 						tcp_rput_data(connp,
13744 						    mp, NULL);
13745 						return;
13746 					}
13747 					(void) adjmsg(mp1, urp - seg_len);
13748 					/* Feed this piece back in. */
13749 					tmp_rnxt = tcp->tcp_rnxt;
13750 					tcp_rput_data(connp, mp1, NULL);
13751 					/*
13752 					 * If the data passed back in was not
13753 					 * processed (ie: bad ACK) sending
13754 					 * the remainder back in will cause a
13755 					 * loop. In this case, drop the
13756 					 * packet and let the sender try
13757 					 * sending a good packet.
13758 					 */
13759 					if (tmp_rnxt == tcp->tcp_rnxt) {
13760 						freemsg(mp);
13761 						return;
13762 					}
13763 				}
13764 				if (urp != seg_len - 1) {
13765 					uint32_t  tmp_rnxt;
13766 					/*
13767 					 * There is stuff after the urgent
13768 					 * byte.
13769 					 */
13770 					mp1 = dupmsg(mp);
13771 					if (!mp1) {
13772 						/*
13773 						 * Trim everything beyond the
13774 						 * urgent byte.  The rest will
13775 						 * come back.
13776 						 */
13777 						(void) adjmsg(mp,
13778 						    urp + 1 - seg_len);
13779 						tcp_rput_data(connp,
13780 						    mp, NULL);
13781 						return;
13782 					}
13783 					(void) adjmsg(mp1, urp + 1 - seg_len);
13784 					tmp_rnxt = tcp->tcp_rnxt;
13785 					tcp_rput_data(connp, mp1, NULL);
13786 					/*
13787 					 * If the data passed back in was not
13788 					 * processed (ie: bad ACK) sending
13789 					 * the remainder back in will cause a
13790 					 * loop. In this case, drop the
13791 					 * packet and let the sender try
13792 					 * sending a good packet.
13793 					 */
13794 					if (tmp_rnxt == tcp->tcp_rnxt) {
13795 						freemsg(mp);
13796 						return;
13797 					}
13798 				}
13799 				tcp_rput_data(connp, mp, NULL);
13800 				return;
13801 			}
13802 			/*
13803 			 * This segment contains only the urgent byte.  We
13804 			 * have to allocate the T_exdata_ind, if we can.
13805 			 */
13806 			if (IPCL_IS_NONSTR(connp)) {
13807 				int error;
13808 
13809 				(*connp->conn_upcalls->su_recv)
13810 				    (connp->conn_upper_handle, mp, seg_len,
13811 				    MSG_OOB, &error, NULL);
13812 				/*
13813 				 * We should never be in middle of a
13814 				 * fallback, the squeue guarantees that.
13815 				 */
13816 				ASSERT(error != EOPNOTSUPP);
13817 				mp = NULL;
13818 				goto update_ack;
13819 			} else if (!tcp->tcp_urp_mp) {
13820 				struct T_exdata_ind *tei;
13821 				mp1 = allocb(sizeof (struct T_exdata_ind),
13822 				    BPRI_MED);
13823 				if (!mp1) {
13824 					/*
13825 					 * Sigh... It'll be back.
13826 					 * Generate any MSG*MARK message now.
13827 					 */
13828 					freemsg(mp);
13829 					seg_len = 0;
13830 					if (flags & TH_SEND_URP_MARK) {
13831 
13832 
13833 						ASSERT(tcp->tcp_urp_mark_mp);
13834 						tcp->tcp_urp_mark_mp->b_flag &=
13835 						    ~MSGNOTMARKNEXT;
13836 						tcp->tcp_urp_mark_mp->b_flag |=
13837 						    MSGMARKNEXT;
13838 					}
13839 					goto ack_check;
13840 				}
13841 				mp1->b_datap->db_type = M_PROTO;
13842 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13843 				tei->PRIM_type = T_EXDATA_IND;
13844 				tei->MORE_flag = 0;
13845 				mp1->b_wptr = (uchar_t *)&tei[1];
13846 				tcp->tcp_urp_mp = mp1;
13847 #ifdef DEBUG
13848 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13849 				    "tcp_rput: allocated exdata_ind %s",
13850 				    tcp_display(tcp, NULL,
13851 				    DISP_PORT_ONLY));
13852 #endif /* DEBUG */
13853 				/*
13854 				 * There is no need to send a separate MSG*MARK
13855 				 * message since the T_EXDATA_IND will be sent
13856 				 * now.
13857 				 */
13858 				flags &= ~TH_SEND_URP_MARK;
13859 				freemsg(tcp->tcp_urp_mark_mp);
13860 				tcp->tcp_urp_mark_mp = NULL;
13861 			}
13862 			/*
13863 			 * Now we are all set.  On the next putnext upstream,
13864 			 * tcp_urp_mp will be non-NULL and will get prepended
13865 			 * to what has to be this piece containing the urgent
13866 			 * byte.  If for any reason we abort this segment below,
13867 			 * if it comes back, we will have this ready, or it
13868 			 * will get blown off in close.
13869 			 */
13870 		} else if (urp == seg_len) {
13871 			/*
13872 			 * The urgent byte is the next byte after this sequence
13873 			 * number. If there is data it is marked with
13874 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13875 			 * since it is not needed. Otherwise, if the code
13876 			 * above just allocated a zero-length tcp_urp_mark_mp
13877 			 * message, that message is tagged with MSGMARKNEXT.
13878 			 * Sending up these MSGMARKNEXT messages makes
13879 			 * SIOCATMARK work correctly even though
13880 			 * the T_EXDATA_IND will not be sent up until the
13881 			 * urgent byte arrives.
13882 			 */
13883 			if (seg_len != 0) {
13884 				flags |= TH_MARKNEXT_NEEDED;
13885 				freemsg(tcp->tcp_urp_mark_mp);
13886 				tcp->tcp_urp_mark_mp = NULL;
13887 				flags &= ~TH_SEND_URP_MARK;
13888 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13889 				flags |= TH_SEND_URP_MARK;
13890 				tcp->tcp_urp_mark_mp->b_flag &=
13891 				    ~MSGNOTMARKNEXT;
13892 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13893 			}
13894 #ifdef DEBUG
13895 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13896 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13897 			    seg_len, flags,
13898 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13899 #endif /* DEBUG */
13900 		}
13901 #ifdef DEBUG
13902 		else {
13903 			/* Data left until we hit mark */
13904 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13905 			    "tcp_rput: URP %d bytes left, %s",
13906 			    urp - seg_len, tcp_display(tcp, NULL,
13907 			    DISP_PORT_ONLY));
13908 		}
13909 #endif /* DEBUG */
13910 	}
13911 
13912 process_ack:
13913 	if (!(flags & TH_ACK)) {
13914 		freemsg(mp);
13915 		goto xmit_check;
13916 	}
13917 	}
13918 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13919 
13920 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13921 		tcp->tcp_ip_forward_progress = B_TRUE;
13922 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13923 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13924 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13925 			/* 3-way handshake complete - pass up the T_CONN_IND */
13926 			tcp_t	*listener = tcp->tcp_listener;
13927 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13928 
13929 			tcp->tcp_tconnind_started = B_TRUE;
13930 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13931 			/*
13932 			 * We are here means eager is fine but it can
13933 			 * get a TH_RST at any point between now and till
13934 			 * accept completes and disappear. We need to
13935 			 * ensure that reference to eager is valid after
13936 			 * we get out of eager's perimeter. So we do
13937 			 * an extra refhold.
13938 			 */
13939 			CONN_INC_REF(connp);
13940 
13941 			/*
13942 			 * The listener also exists because of the refhold
13943 			 * done in tcp_conn_request. Its possible that it
13944 			 * might have closed. We will check that once we
13945 			 * get inside listeners context.
13946 			 */
13947 			CONN_INC_REF(listener->tcp_connp);
13948 			if (listener->tcp_connp->conn_sqp ==
13949 			    connp->conn_sqp) {
13950 				/*
13951 				 * We optimize by not calling an SQUEUE_ENTER
13952 				 * on the listener since we know that the
13953 				 * listener and eager squeues are the same.
13954 				 * We are able to make this check safely only
13955 				 * because neither the eager nor the listener
13956 				 * can change its squeue. Only an active connect
13957 				 * can change its squeue
13958 				 */
13959 				tcp_send_conn_ind(listener->tcp_connp, mp,
13960 				    listener->tcp_connp->conn_sqp);
13961 				CONN_DEC_REF(listener->tcp_connp);
13962 			} else if (!tcp->tcp_loopback) {
13963 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
13964 				    mp, tcp_send_conn_ind,
13965 				    listener->tcp_connp, SQ_FILL,
13966 				    SQTAG_TCP_CONN_IND);
13967 			} else {
13968 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
13969 				    mp, tcp_send_conn_ind,
13970 				    listener->tcp_connp, SQ_PROCESS,
13971 				    SQTAG_TCP_CONN_IND);
13972 			}
13973 		}
13974 
13975 		/*
13976 		 * We are seeing the final ack in the three way
13977 		 * hand shake of a active open'ed connection
13978 		 * so we must send up a T_CONN_CON
13979 		 *
13980 		 * tcp_sendmsg() checks tcp_state without entering
13981 		 * the squeue so tcp_state should be updated before
13982 		 * sending up connection confirmation.
13983 		 */
13984 		tcp->tcp_state = TCPS_ESTABLISHED;
13985 		if (tcp->tcp_active_open) {
13986 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13987 				freemsg(mp);
13988 				tcp->tcp_state = TCPS_SYN_RCVD;
13989 				return;
13990 			}
13991 			/*
13992 			 * Don't fuse the loopback endpoints for
13993 			 * simultaneous active opens.
13994 			 */
13995 			if (tcp->tcp_loopback) {
13996 				TCP_STAT(tcps, tcp_fusion_unfusable);
13997 				tcp->tcp_unfusable = B_TRUE;
13998 			}
13999 		}
14000 
14001 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14002 		bytes_acked--;
14003 		/* SYN was acked - making progress */
14004 		if (tcp->tcp_ipversion == IPV6_VERSION)
14005 			tcp->tcp_ip_forward_progress = B_TRUE;
14006 
14007 		/*
14008 		 * If SYN was retransmitted, need to reset all
14009 		 * retransmission info as this segment will be
14010 		 * treated as a dup ACK.
14011 		 */
14012 		if (tcp->tcp_rexmit) {
14013 			tcp->tcp_rexmit = B_FALSE;
14014 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14015 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14016 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14017 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14018 			tcp->tcp_ms_we_have_waited = 0;
14019 			tcp->tcp_cwnd = mss;
14020 		}
14021 
14022 		/*
14023 		 * We set the send window to zero here.
14024 		 * This is needed if there is data to be
14025 		 * processed already on the queue.
14026 		 * Later (at swnd_update label), the
14027 		 * "new_swnd > tcp_swnd" condition is satisfied
14028 		 * the XMIT_NEEDED flag is set in the current
14029 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14030 		 * called if there is already data on queue in
14031 		 * this state.
14032 		 */
14033 		tcp->tcp_swnd = 0;
14034 
14035 		if (new_swnd > tcp->tcp_max_swnd)
14036 			tcp->tcp_max_swnd = new_swnd;
14037 		tcp->tcp_swl1 = seg_seq;
14038 		tcp->tcp_swl2 = seg_ack;
14039 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14040 
14041 		/* Fuse when both sides are in ESTABLISHED state */
14042 		if (tcp->tcp_loopback && do_tcp_fusion)
14043 			tcp_fuse(tcp, iphdr, tcph);
14044 
14045 	}
14046 	/* This code follows 4.4BSD-Lite2 mostly. */
14047 	if (bytes_acked < 0)
14048 		goto est;
14049 
14050 	/*
14051 	 * If TCP is ECN capable and the congestion experience bit is
14052 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14053 	 * done once per window (or more loosely, per RTT).
14054 	 */
14055 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14056 		tcp->tcp_cwr = B_FALSE;
14057 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14058 		if (!tcp->tcp_cwr) {
14059 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14060 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14061 			tcp->tcp_cwnd = npkt * mss;
14062 			/*
14063 			 * If the cwnd is 0, use the timer to clock out
14064 			 * new segments.  This is required by the ECN spec.
14065 			 */
14066 			if (npkt == 0) {
14067 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14068 				/*
14069 				 * This makes sure that when the ACK comes
14070 				 * back, we will increase tcp_cwnd by 1 MSS.
14071 				 */
14072 				tcp->tcp_cwnd_cnt = 0;
14073 			}
14074 			tcp->tcp_cwr = B_TRUE;
14075 			/*
14076 			 * This marks the end of the current window of in
14077 			 * flight data.  That is why we don't use
14078 			 * tcp_suna + tcp_swnd.  Only data in flight can
14079 			 * provide ECN info.
14080 			 */
14081 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14082 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14083 		}
14084 	}
14085 
14086 	mp1 = tcp->tcp_xmit_head;
14087 	if (bytes_acked == 0) {
14088 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14089 			int dupack_cnt;
14090 
14091 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14092 			/*
14093 			 * Fast retransmit.  When we have seen exactly three
14094 			 * identical ACKs while we have unacked data
14095 			 * outstanding we take it as a hint that our peer
14096 			 * dropped something.
14097 			 *
14098 			 * If TCP is retransmitting, don't do fast retransmit.
14099 			 */
14100 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14101 			    ! tcp->tcp_rexmit) {
14102 				/* Do Limited Transmit */
14103 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14104 				    tcps->tcps_dupack_fast_retransmit) {
14105 					/*
14106 					 * RFC 3042
14107 					 *
14108 					 * What we need to do is temporarily
14109 					 * increase tcp_cwnd so that new
14110 					 * data can be sent if it is allowed
14111 					 * by the receive window (tcp_rwnd).
14112 					 * tcp_wput_data() will take care of
14113 					 * the rest.
14114 					 *
14115 					 * If the connection is SACK capable,
14116 					 * only do limited xmit when there
14117 					 * is SACK info.
14118 					 *
14119 					 * Note how tcp_cwnd is incremented.
14120 					 * The first dup ACK will increase
14121 					 * it by 1 MSS.  The second dup ACK
14122 					 * will increase it by 2 MSS.  This
14123 					 * means that only 1 new segment will
14124 					 * be sent for each dup ACK.
14125 					 */
14126 					if (tcp->tcp_unsent > 0 &&
14127 					    (!tcp->tcp_snd_sack_ok ||
14128 					    (tcp->tcp_snd_sack_ok &&
14129 					    tcp->tcp_notsack_list != NULL))) {
14130 						tcp->tcp_cwnd += mss <<
14131 						    (tcp->tcp_dupack_cnt - 1);
14132 						flags |= TH_LIMIT_XMIT;
14133 					}
14134 				} else if (dupack_cnt ==
14135 				    tcps->tcps_dupack_fast_retransmit) {
14136 
14137 				/*
14138 				 * If we have reduced tcp_ssthresh
14139 				 * because of ECN, do not reduce it again
14140 				 * unless it is already one window of data
14141 				 * away.  After one window of data, tcp_cwr
14142 				 * should then be cleared.  Note that
14143 				 * for non ECN capable connection, tcp_cwr
14144 				 * should always be false.
14145 				 *
14146 				 * Adjust cwnd since the duplicate
14147 				 * ack indicates that a packet was
14148 				 * dropped (due to congestion.)
14149 				 */
14150 				if (!tcp->tcp_cwr) {
14151 					npkt = ((tcp->tcp_snxt -
14152 					    tcp->tcp_suna) >> 1) / mss;
14153 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14154 					    mss;
14155 					tcp->tcp_cwnd = (npkt +
14156 					    tcp->tcp_dupack_cnt) * mss;
14157 				}
14158 				if (tcp->tcp_ecn_ok) {
14159 					tcp->tcp_cwr = B_TRUE;
14160 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14161 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14162 				}
14163 
14164 				/*
14165 				 * We do Hoe's algorithm.  Refer to her
14166 				 * paper "Improving the Start-up Behavior
14167 				 * of a Congestion Control Scheme for TCP,"
14168 				 * appeared in SIGCOMM'96.
14169 				 *
14170 				 * Save highest seq no we have sent so far.
14171 				 * Be careful about the invisible FIN byte.
14172 				 */
14173 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14174 				    (tcp->tcp_unsent == 0)) {
14175 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14176 				} else {
14177 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14178 				}
14179 
14180 				/*
14181 				 * Do not allow bursty traffic during.
14182 				 * fast recovery.  Refer to Fall and Floyd's
14183 				 * paper "Simulation-based Comparisons of
14184 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14185 				 * This is a best current practise.
14186 				 */
14187 				tcp->tcp_snd_burst = TCP_CWND_SS;
14188 
14189 				/*
14190 				 * For SACK:
14191 				 * Calculate tcp_pipe, which is the
14192 				 * estimated number of bytes in
14193 				 * network.
14194 				 *
14195 				 * tcp_fack is the highest sack'ed seq num
14196 				 * TCP has received.
14197 				 *
14198 				 * tcp_pipe is explained in the above quoted
14199 				 * Fall and Floyd's paper.  tcp_fack is
14200 				 * explained in Mathis and Mahdavi's
14201 				 * "Forward Acknowledgment: Refining TCP
14202 				 * Congestion Control" in SIGCOMM '96.
14203 				 */
14204 				if (tcp->tcp_snd_sack_ok) {
14205 					ASSERT(tcp->tcp_sack_info != NULL);
14206 					if (tcp->tcp_notsack_list != NULL) {
14207 						tcp->tcp_pipe = tcp->tcp_snxt -
14208 						    tcp->tcp_fack;
14209 						tcp->tcp_sack_snxt = seg_ack;
14210 						flags |= TH_NEED_SACK_REXMIT;
14211 					} else {
14212 						/*
14213 						 * Always initialize tcp_pipe
14214 						 * even though we don't have
14215 						 * any SACK info.  If later
14216 						 * we get SACK info and
14217 						 * tcp_pipe is not initialized,
14218 						 * funny things will happen.
14219 						 */
14220 						tcp->tcp_pipe =
14221 						    tcp->tcp_cwnd_ssthresh;
14222 					}
14223 				} else {
14224 					flags |= TH_REXMIT_NEEDED;
14225 				} /* tcp_snd_sack_ok */
14226 
14227 				} else {
14228 					/*
14229 					 * Here we perform congestion
14230 					 * avoidance, but NOT slow start.
14231 					 * This is known as the Fast
14232 					 * Recovery Algorithm.
14233 					 */
14234 					if (tcp->tcp_snd_sack_ok &&
14235 					    tcp->tcp_notsack_list != NULL) {
14236 						flags |= TH_NEED_SACK_REXMIT;
14237 						tcp->tcp_pipe -= mss;
14238 						if (tcp->tcp_pipe < 0)
14239 							tcp->tcp_pipe = 0;
14240 					} else {
14241 					/*
14242 					 * We know that one more packet has
14243 					 * left the pipe thus we can update
14244 					 * cwnd.
14245 					 */
14246 					cwnd = tcp->tcp_cwnd + mss;
14247 					if (cwnd > tcp->tcp_cwnd_max)
14248 						cwnd = tcp->tcp_cwnd_max;
14249 					tcp->tcp_cwnd = cwnd;
14250 					if (tcp->tcp_unsent > 0)
14251 						flags |= TH_XMIT_NEEDED;
14252 					}
14253 				}
14254 			}
14255 		} else if (tcp->tcp_zero_win_probe) {
14256 			/*
14257 			 * If the window has opened, need to arrange
14258 			 * to send additional data.
14259 			 */
14260 			if (new_swnd != 0) {
14261 				/* tcp_suna != tcp_snxt */
14262 				/* Packet contains a window update */
14263 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14264 				tcp->tcp_zero_win_probe = 0;
14265 				tcp->tcp_timer_backoff = 0;
14266 				tcp->tcp_ms_we_have_waited = 0;
14267 
14268 				/*
14269 				 * Transmit starting with tcp_suna since
14270 				 * the one byte probe is not ack'ed.
14271 				 * If TCP has sent more than one identical
14272 				 * probe, tcp_rexmit will be set.  That means
14273 				 * tcp_ss_rexmit() will send out the one
14274 				 * byte along with new data.  Otherwise,
14275 				 * fake the retransmission.
14276 				 */
14277 				flags |= TH_XMIT_NEEDED;
14278 				if (!tcp->tcp_rexmit) {
14279 					tcp->tcp_rexmit = B_TRUE;
14280 					tcp->tcp_dupack_cnt = 0;
14281 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14282 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14283 				}
14284 			}
14285 		}
14286 		goto swnd_update;
14287 	}
14288 
14289 	/*
14290 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14291 	 * If the ACK value acks something that we have not yet sent, it might
14292 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14293 	 * other side.
14294 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14295 	 * state is handled above, so we can always just drop the segment and
14296 	 * send an ACK here.
14297 	 *
14298 	 * Should we send ACKs in response to ACK only segments?
14299 	 */
14300 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14301 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14302 		/* drop the received segment */
14303 		freemsg(mp);
14304 
14305 		/*
14306 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14307 		 * greater than 0, check if the number of such
14308 		 * bogus ACks is greater than that count.  If yes,
14309 		 * don't send back any ACK.  This prevents TCP from
14310 		 * getting into an ACK storm if somehow an attacker
14311 		 * successfully spoofs an acceptable segment to our
14312 		 * peer.
14313 		 */
14314 		if (tcp_drop_ack_unsent_cnt > 0 &&
14315 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14316 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14317 			return;
14318 		}
14319 		mp = tcp_ack_mp(tcp);
14320 		if (mp != NULL) {
14321 			BUMP_LOCAL(tcp->tcp_obsegs);
14322 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14323 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14324 		}
14325 		return;
14326 	}
14327 
14328 	/*
14329 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14330 	 * blocks that are covered by this ACK.
14331 	 */
14332 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14333 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14334 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14335 	}
14336 
14337 	/*
14338 	 * If we got an ACK after fast retransmit, check to see
14339 	 * if it is a partial ACK.  If it is not and the congestion
14340 	 * window was inflated to account for the other side's
14341 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14342 	 */
14343 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14344 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14345 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14346 			tcp->tcp_dupack_cnt = 0;
14347 			/*
14348 			 * Restore the orig tcp_cwnd_ssthresh after
14349 			 * fast retransmit phase.
14350 			 */
14351 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14352 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14353 			}
14354 			tcp->tcp_rexmit_max = seg_ack;
14355 			tcp->tcp_cwnd_cnt = 0;
14356 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14357 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14358 
14359 			/*
14360 			 * Remove all notsack info to avoid confusion with
14361 			 * the next fast retrasnmit/recovery phase.
14362 			 */
14363 			if (tcp->tcp_snd_sack_ok &&
14364 			    tcp->tcp_notsack_list != NULL) {
14365 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14366 			}
14367 		} else {
14368 			if (tcp->tcp_snd_sack_ok &&
14369 			    tcp->tcp_notsack_list != NULL) {
14370 				flags |= TH_NEED_SACK_REXMIT;
14371 				tcp->tcp_pipe -= mss;
14372 				if (tcp->tcp_pipe < 0)
14373 					tcp->tcp_pipe = 0;
14374 			} else {
14375 				/*
14376 				 * Hoe's algorithm:
14377 				 *
14378 				 * Retransmit the unack'ed segment and
14379 				 * restart fast recovery.  Note that we
14380 				 * need to scale back tcp_cwnd to the
14381 				 * original value when we started fast
14382 				 * recovery.  This is to prevent overly
14383 				 * aggressive behaviour in sending new
14384 				 * segments.
14385 				 */
14386 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14387 				    tcps->tcps_dupack_fast_retransmit * mss;
14388 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14389 				flags |= TH_REXMIT_NEEDED;
14390 			}
14391 		}
14392 	} else {
14393 		tcp->tcp_dupack_cnt = 0;
14394 		if (tcp->tcp_rexmit) {
14395 			/*
14396 			 * TCP is retranmitting.  If the ACK ack's all
14397 			 * outstanding data, update tcp_rexmit_max and
14398 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14399 			 * to the correct value.
14400 			 *
14401 			 * Note that SEQ_LEQ() is used.  This is to avoid
14402 			 * unnecessary fast retransmit caused by dup ACKs
14403 			 * received when TCP does slow start retransmission
14404 			 * after a time out.  During this phase, TCP may
14405 			 * send out segments which are already received.
14406 			 * This causes dup ACKs to be sent back.
14407 			 */
14408 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14409 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14410 					tcp->tcp_rexmit_nxt = seg_ack;
14411 				}
14412 				if (seg_ack != tcp->tcp_rexmit_max) {
14413 					flags |= TH_XMIT_NEEDED;
14414 				}
14415 			} else {
14416 				tcp->tcp_rexmit = B_FALSE;
14417 				tcp->tcp_xmit_zc_clean = B_FALSE;
14418 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14419 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14420 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14421 			}
14422 			tcp->tcp_ms_we_have_waited = 0;
14423 		}
14424 	}
14425 
14426 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14427 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14428 	tcp->tcp_suna = seg_ack;
14429 	if (tcp->tcp_zero_win_probe != 0) {
14430 		tcp->tcp_zero_win_probe = 0;
14431 		tcp->tcp_timer_backoff = 0;
14432 	}
14433 
14434 	/*
14435 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14436 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14437 	 * will not reach here.
14438 	 */
14439 	if (mp1 == NULL) {
14440 		goto fin_acked;
14441 	}
14442 
14443 	/*
14444 	 * Update the congestion window.
14445 	 *
14446 	 * If TCP is not ECN capable or TCP is ECN capable but the
14447 	 * congestion experience bit is not set, increase the tcp_cwnd as
14448 	 * usual.
14449 	 */
14450 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14451 		cwnd = tcp->tcp_cwnd;
14452 		add = mss;
14453 
14454 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14455 			/*
14456 			 * This is to prevent an increase of less than 1 MSS of
14457 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14458 			 * may send out tinygrams in order to preserve mblk
14459 			 * boundaries.
14460 			 *
14461 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14462 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14463 			 * increased by 1 MSS for every RTTs.
14464 			 */
14465 			if (tcp->tcp_cwnd_cnt <= 0) {
14466 				tcp->tcp_cwnd_cnt = cwnd + add;
14467 			} else {
14468 				tcp->tcp_cwnd_cnt -= add;
14469 				add = 0;
14470 			}
14471 		}
14472 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14473 	}
14474 
14475 	/* See if the latest urgent data has been acknowledged */
14476 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14477 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14478 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14479 
14480 	/* Can we update the RTT estimates? */
14481 	if (tcp->tcp_snd_ts_ok) {
14482 		/* Ignore zero timestamp echo-reply. */
14483 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14484 			tcp_set_rto(tcp, (int32_t)lbolt -
14485 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14486 		}
14487 
14488 		/* If needed, restart the timer. */
14489 		if (tcp->tcp_set_timer == 1) {
14490 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14491 			tcp->tcp_set_timer = 0;
14492 		}
14493 		/*
14494 		 * Update tcp_csuna in case the other side stops sending
14495 		 * us timestamps.
14496 		 */
14497 		tcp->tcp_csuna = tcp->tcp_snxt;
14498 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14499 		/*
14500 		 * An ACK sequence we haven't seen before, so get the RTT
14501 		 * and update the RTO. But first check if the timestamp is
14502 		 * valid to use.
14503 		 */
14504 		if ((mp1->b_next != NULL) &&
14505 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14506 			tcp_set_rto(tcp, (int32_t)lbolt -
14507 			    (int32_t)(intptr_t)mp1->b_prev);
14508 		else
14509 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14510 
14511 		/* Remeber the last sequence to be ACKed */
14512 		tcp->tcp_csuna = seg_ack;
14513 		if (tcp->tcp_set_timer == 1) {
14514 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14515 			tcp->tcp_set_timer = 0;
14516 		}
14517 	} else {
14518 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14519 	}
14520 
14521 	/* Eat acknowledged bytes off the xmit queue. */
14522 	for (;;) {
14523 		mblk_t	*mp2;
14524 		uchar_t	*wptr;
14525 
14526 		wptr = mp1->b_wptr;
14527 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14528 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14529 		if (bytes_acked < 0) {
14530 			mp1->b_rptr = wptr + bytes_acked;
14531 			/*
14532 			 * Set a new timestamp if all the bytes timed by the
14533 			 * old timestamp have been ack'ed.
14534 			 */
14535 			if (SEQ_GT(seg_ack,
14536 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14537 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14538 				mp1->b_next = NULL;
14539 			}
14540 			break;
14541 		}
14542 		mp1->b_next = NULL;
14543 		mp1->b_prev = NULL;
14544 		mp2 = mp1;
14545 		mp1 = mp1->b_cont;
14546 
14547 		/*
14548 		 * This notification is required for some zero-copy
14549 		 * clients to maintain a copy semantic. After the data
14550 		 * is ack'ed, client is safe to modify or reuse the buffer.
14551 		 */
14552 		if (tcp->tcp_snd_zcopy_aware &&
14553 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14554 			tcp_zcopy_notify(tcp);
14555 		freeb(mp2);
14556 		if (bytes_acked == 0) {
14557 			if (mp1 == NULL) {
14558 				/* Everything is ack'ed, clear the tail. */
14559 				tcp->tcp_xmit_tail = NULL;
14560 				/*
14561 				 * Cancel the timer unless we are still
14562 				 * waiting for an ACK for the FIN packet.
14563 				 */
14564 				if (tcp->tcp_timer_tid != 0 &&
14565 				    tcp->tcp_snxt == tcp->tcp_suna) {
14566 					(void) TCP_TIMER_CANCEL(tcp,
14567 					    tcp->tcp_timer_tid);
14568 					tcp->tcp_timer_tid = 0;
14569 				}
14570 				goto pre_swnd_update;
14571 			}
14572 			if (mp2 != tcp->tcp_xmit_tail)
14573 				break;
14574 			tcp->tcp_xmit_tail = mp1;
14575 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14576 			    (uintptr_t)INT_MAX);
14577 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14578 			    mp1->b_rptr);
14579 			break;
14580 		}
14581 		if (mp1 == NULL) {
14582 			/*
14583 			 * More was acked but there is nothing more
14584 			 * outstanding.  This means that the FIN was
14585 			 * just acked or that we're talking to a clown.
14586 			 */
14587 fin_acked:
14588 			ASSERT(tcp->tcp_fin_sent);
14589 			tcp->tcp_xmit_tail = NULL;
14590 			if (tcp->tcp_fin_sent) {
14591 				/* FIN was acked - making progress */
14592 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14593 				    !tcp->tcp_fin_acked)
14594 					tcp->tcp_ip_forward_progress = B_TRUE;
14595 				tcp->tcp_fin_acked = B_TRUE;
14596 				if (tcp->tcp_linger_tid != 0 &&
14597 				    TCP_TIMER_CANCEL(tcp,
14598 				    tcp->tcp_linger_tid) >= 0) {
14599 					tcp_stop_lingering(tcp);
14600 					freemsg(mp);
14601 					mp = NULL;
14602 				}
14603 			} else {
14604 				/*
14605 				 * We should never get here because
14606 				 * we have already checked that the
14607 				 * number of bytes ack'ed should be
14608 				 * smaller than or equal to what we
14609 				 * have sent so far (it is the
14610 				 * acceptability check of the ACK).
14611 				 * We can only get here if the send
14612 				 * queue is corrupted.
14613 				 *
14614 				 * Terminate the connection and
14615 				 * panic the system.  It is better
14616 				 * for us to panic instead of
14617 				 * continuing to avoid other disaster.
14618 				 */
14619 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14620 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14621 				panic("Memory corruption "
14622 				    "detected for connection %s.",
14623 				    tcp_display(tcp, NULL,
14624 				    DISP_ADDR_AND_PORT));
14625 				/*NOTREACHED*/
14626 			}
14627 			goto pre_swnd_update;
14628 		}
14629 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14630 	}
14631 	if (tcp->tcp_unsent) {
14632 		flags |= TH_XMIT_NEEDED;
14633 	}
14634 pre_swnd_update:
14635 	tcp->tcp_xmit_head = mp1;
14636 swnd_update:
14637 	/*
14638 	 * The following check is different from most other implementations.
14639 	 * For bi-directional transfer, when segments are dropped, the
14640 	 * "normal" check will not accept a window update in those
14641 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14642 	 * segments which are outside receiver's window.  As TCP accepts
14643 	 * the ack in those retransmitted segments, if the window update in
14644 	 * the same segment is not accepted, TCP will incorrectly calculates
14645 	 * that it can send more segments.  This can create a deadlock
14646 	 * with the receiver if its window becomes zero.
14647 	 */
14648 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14649 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14650 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14651 		/*
14652 		 * The criteria for update is:
14653 		 *
14654 		 * 1. the segment acknowledges some data.  Or
14655 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14656 		 * 3. the segment is not old and the advertised window is
14657 		 * larger than the previous advertised window.
14658 		 */
14659 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14660 			flags |= TH_XMIT_NEEDED;
14661 		tcp->tcp_swnd = new_swnd;
14662 		if (new_swnd > tcp->tcp_max_swnd)
14663 			tcp->tcp_max_swnd = new_swnd;
14664 		tcp->tcp_swl1 = seg_seq;
14665 		tcp->tcp_swl2 = seg_ack;
14666 	}
14667 est:
14668 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14669 
14670 		switch (tcp->tcp_state) {
14671 		case TCPS_FIN_WAIT_1:
14672 			if (tcp->tcp_fin_acked) {
14673 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14674 				/*
14675 				 * We implement the non-standard BSD/SunOS
14676 				 * FIN_WAIT_2 flushing algorithm.
14677 				 * If there is no user attached to this
14678 				 * TCP endpoint, then this TCP struct
14679 				 * could hang around forever in FIN_WAIT_2
14680 				 * state if the peer forgets to send us
14681 				 * a FIN.  To prevent this, we wait only
14682 				 * 2*MSL (a convenient time value) for
14683 				 * the FIN to arrive.  If it doesn't show up,
14684 				 * we flush the TCP endpoint.  This algorithm,
14685 				 * though a violation of RFC-793, has worked
14686 				 * for over 10 years in BSD systems.
14687 				 * Note: SunOS 4.x waits 675 seconds before
14688 				 * flushing the FIN_WAIT_2 connection.
14689 				 */
14690 				TCP_TIMER_RESTART(tcp,
14691 				    tcps->tcps_fin_wait_2_flush_interval);
14692 			}
14693 			break;
14694 		case TCPS_FIN_WAIT_2:
14695 			break;	/* Shutdown hook? */
14696 		case TCPS_LAST_ACK:
14697 			freemsg(mp);
14698 			if (tcp->tcp_fin_acked) {
14699 				(void) tcp_clean_death(tcp, 0, 19);
14700 				return;
14701 			}
14702 			goto xmit_check;
14703 		case TCPS_CLOSING:
14704 			if (tcp->tcp_fin_acked) {
14705 				tcp->tcp_state = TCPS_TIME_WAIT;
14706 				/*
14707 				 * Unconditionally clear the exclusive binding
14708 				 * bit so this TIME-WAIT connection won't
14709 				 * interfere with new ones.
14710 				 */
14711 				tcp->tcp_exclbind = 0;
14712 				if (!TCP_IS_DETACHED(tcp)) {
14713 					TCP_TIMER_RESTART(tcp,
14714 					    tcps->tcps_time_wait_interval);
14715 				} else {
14716 					tcp_time_wait_append(tcp);
14717 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14718 				}
14719 			}
14720 			/*FALLTHRU*/
14721 		case TCPS_CLOSE_WAIT:
14722 			freemsg(mp);
14723 			goto xmit_check;
14724 		default:
14725 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14726 			break;
14727 		}
14728 	}
14729 	if (flags & TH_FIN) {
14730 		/* Make sure we ack the fin */
14731 		flags |= TH_ACK_NEEDED;
14732 		if (!tcp->tcp_fin_rcvd) {
14733 			tcp->tcp_fin_rcvd = B_TRUE;
14734 			tcp->tcp_rnxt++;
14735 			tcph = tcp->tcp_tcph;
14736 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14737 
14738 			/*
14739 			 * Generate the ordrel_ind at the end unless we
14740 			 * are an eager guy.
14741 			 * In the eager case tcp_rsrv will do this when run
14742 			 * after tcp_accept is done.
14743 			 */
14744 			if (tcp->tcp_listener == NULL &&
14745 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14746 				flags |= TH_ORDREL_NEEDED;
14747 			switch (tcp->tcp_state) {
14748 			case TCPS_SYN_RCVD:
14749 			case TCPS_ESTABLISHED:
14750 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14751 				/* Keepalive? */
14752 				break;
14753 			case TCPS_FIN_WAIT_1:
14754 				if (!tcp->tcp_fin_acked) {
14755 					tcp->tcp_state = TCPS_CLOSING;
14756 					break;
14757 				}
14758 				/* FALLTHRU */
14759 			case TCPS_FIN_WAIT_2:
14760 				tcp->tcp_state = TCPS_TIME_WAIT;
14761 				/*
14762 				 * Unconditionally clear the exclusive binding
14763 				 * bit so this TIME-WAIT connection won't
14764 				 * interfere with new ones.
14765 				 */
14766 				tcp->tcp_exclbind = 0;
14767 				if (!TCP_IS_DETACHED(tcp)) {
14768 					TCP_TIMER_RESTART(tcp,
14769 					    tcps->tcps_time_wait_interval);
14770 				} else {
14771 					tcp_time_wait_append(tcp);
14772 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14773 				}
14774 				if (seg_len) {
14775 					/*
14776 					 * implies data piggybacked on FIN.
14777 					 * break to handle data.
14778 					 */
14779 					break;
14780 				}
14781 				freemsg(mp);
14782 				goto ack_check;
14783 			}
14784 		}
14785 	}
14786 	if (mp == NULL)
14787 		goto xmit_check;
14788 	if (seg_len == 0) {
14789 		freemsg(mp);
14790 		goto xmit_check;
14791 	}
14792 	if (mp->b_rptr == mp->b_wptr) {
14793 		/*
14794 		 * The header has been consumed, so we remove the
14795 		 * zero-length mblk here.
14796 		 */
14797 		mp1 = mp;
14798 		mp = mp->b_cont;
14799 		freeb(mp1);
14800 	}
14801 update_ack:
14802 	tcph = tcp->tcp_tcph;
14803 	tcp->tcp_rack_cnt++;
14804 	{
14805 		uint32_t cur_max;
14806 
14807 		cur_max = tcp->tcp_rack_cur_max;
14808 		if (tcp->tcp_rack_cnt >= cur_max) {
14809 			/*
14810 			 * We have more unacked data than we should - send
14811 			 * an ACK now.
14812 			 */
14813 			flags |= TH_ACK_NEEDED;
14814 			cur_max++;
14815 			if (cur_max > tcp->tcp_rack_abs_max)
14816 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14817 			else
14818 				tcp->tcp_rack_cur_max = cur_max;
14819 		} else if (TCP_IS_DETACHED(tcp)) {
14820 			/* We don't have an ACK timer for detached TCP. */
14821 			flags |= TH_ACK_NEEDED;
14822 		} else if (seg_len < mss) {
14823 			/*
14824 			 * If we get a segment that is less than an mss, and we
14825 			 * already have unacknowledged data, and the amount
14826 			 * unacknowledged is not a multiple of mss, then we
14827 			 * better generate an ACK now.  Otherwise, this may be
14828 			 * the tail piece of a transaction, and we would rather
14829 			 * wait for the response.
14830 			 */
14831 			uint32_t udif;
14832 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14833 			    (uintptr_t)INT_MAX);
14834 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14835 			if (udif && (udif % mss))
14836 				flags |= TH_ACK_NEEDED;
14837 			else
14838 				flags |= TH_ACK_TIMER_NEEDED;
14839 		} else {
14840 			/* Start delayed ack timer */
14841 			flags |= TH_ACK_TIMER_NEEDED;
14842 		}
14843 	}
14844 	tcp->tcp_rnxt += seg_len;
14845 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14846 
14847 	if (mp == NULL)
14848 		goto xmit_check;
14849 
14850 	/* Update SACK list */
14851 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14852 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14853 		    &(tcp->tcp_num_sack_blk));
14854 	}
14855 
14856 	if (tcp->tcp_urp_mp) {
14857 		tcp->tcp_urp_mp->b_cont = mp;
14858 		mp = tcp->tcp_urp_mp;
14859 		tcp->tcp_urp_mp = NULL;
14860 		/* Ready for a new signal. */
14861 		tcp->tcp_urp_last_valid = B_FALSE;
14862 #ifdef DEBUG
14863 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14864 		    "tcp_rput: sending exdata_ind %s",
14865 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14866 #endif /* DEBUG */
14867 	}
14868 
14869 	/*
14870 	 * Check for ancillary data changes compared to last segment.
14871 	 */
14872 	if (tcp->tcp_ipv6_recvancillary != 0) {
14873 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14874 		ASSERT(mp != NULL);
14875 	}
14876 
14877 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14878 		/*
14879 		 * Side queue inbound data until the accept happens.
14880 		 * tcp_accept/tcp_rput drains this when the accept happens.
14881 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14882 		 * T_EXDATA_IND) it is queued on b_next.
14883 		 * XXX Make urgent data use this. Requires:
14884 		 *	Removing tcp_listener check for TH_URG
14885 		 *	Making M_PCPROTO and MARK messages skip the eager case
14886 		 */
14887 
14888 		if (tcp->tcp_kssl_pending) {
14889 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
14890 			    mblk_t *, mp);
14891 			tcp_kssl_input(tcp, mp);
14892 		} else {
14893 			tcp_rcv_enqueue(tcp, mp, seg_len);
14894 		}
14895 	} else {
14896 		if (mp->b_datap->db_type != M_DATA ||
14897 		    (flags & TH_MARKNEXT_NEEDED)) {
14898 			if (IPCL_IS_NONSTR(connp)) {
14899 				int error;
14900 
14901 				if ((*connp->conn_upcalls->su_recv)
14902 				    (connp->conn_upper_handle, mp,
14903 				    seg_len, 0, &error, NULL) <= 0) {
14904 					/*
14905 					 * We should never be in middle of a
14906 					 * fallback, the squeue guarantees that.
14907 					 */
14908 					ASSERT(error != EOPNOTSUPP);
14909 					if (error == ENOSPC)
14910 						tcp->tcp_rwnd -= seg_len;
14911 				}
14912 			} else if (tcp->tcp_rcv_list != NULL) {
14913 				flags |= tcp_rcv_drain(tcp);
14914 			}
14915 			ASSERT(tcp->tcp_rcv_list == NULL ||
14916 			    tcp->tcp_fused_sigurg);
14917 
14918 			if (flags & TH_MARKNEXT_NEEDED) {
14919 #ifdef DEBUG
14920 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14921 				    "tcp_rput: sending MSGMARKNEXT %s",
14922 				    tcp_display(tcp, NULL,
14923 				    DISP_PORT_ONLY));
14924 #endif /* DEBUG */
14925 				mp->b_flag |= MSGMARKNEXT;
14926 				flags &= ~TH_MARKNEXT_NEEDED;
14927 			}
14928 
14929 			/* Does this need SSL processing first? */
14930 			if ((tcp->tcp_kssl_ctx != NULL) &&
14931 			    (DB_TYPE(mp) == M_DATA)) {
14932 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
14933 				    mblk_t *, mp);
14934 				tcp_kssl_input(tcp, mp);
14935 			} else if (!IPCL_IS_NONSTR(connp)) {
14936 				/* Already handled non-STREAMS case. */
14937 				putnext(tcp->tcp_rq, mp);
14938 				if (!canputnext(tcp->tcp_rq))
14939 					tcp->tcp_rwnd -= seg_len;
14940 			}
14941 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
14942 		    (DB_TYPE(mp) == M_DATA)) {
14943 			/* Does this need SSL processing first? */
14944 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
14945 			tcp_kssl_input(tcp, mp);
14946 		} else if (IPCL_IS_NONSTR(connp)) {
14947 			/* Non-STREAMS socket */
14948 			boolean_t push = flags & (TH_PUSH|TH_FIN);
14949 			int	error;
14950 
14951 			if ((*connp->conn_upcalls->su_recv)(
14952 			    connp->conn_upper_handle,
14953 			    mp, seg_len, 0, &error, &push) <= 0) {
14954 				/*
14955 				 * We should never be in middle of a
14956 				 * fallback, the squeue guarantees that.
14957 				 */
14958 				ASSERT(error != EOPNOTSUPP);
14959 				if (error == ENOSPC)
14960 					tcp->tcp_rwnd -= seg_len;
14961 			} else if (push) {
14962 				/*
14963 				 * PUSH bit set and sockfs is not
14964 				 * flow controlled
14965 				 */
14966 				flags |= tcp_rwnd_reopen(tcp);
14967 			}
14968 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14969 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
14970 			if (tcp->tcp_rcv_list != NULL) {
14971 				/*
14972 				 * Enqueue the new segment first and then
14973 				 * call tcp_rcv_drain() to send all data
14974 				 * up.  The other way to do this is to
14975 				 * send all queued data up and then call
14976 				 * putnext() to send the new segment up.
14977 				 * This way can remove the else part later
14978 				 * on.
14979 				 *
14980 				 * We don't do this to avoid one more call to
14981 				 * canputnext() as tcp_rcv_drain() needs to
14982 				 * call canputnext().
14983 				 */
14984 				tcp_rcv_enqueue(tcp, mp, seg_len);
14985 				flags |= tcp_rcv_drain(tcp);
14986 			} else {
14987 				putnext(tcp->tcp_rq, mp);
14988 				if (!canputnext(tcp->tcp_rq))
14989 					tcp->tcp_rwnd -= seg_len;
14990 			}
14991 		} else {
14992 			/*
14993 			 * Enqueue all packets when processing an mblk
14994 			 * from the co queue and also enqueue normal packets.
14995 			 */
14996 			tcp_rcv_enqueue(tcp, mp, seg_len);
14997 		}
14998 		/*
14999 		 * Make sure the timer is running if we have data waiting
15000 		 * for a push bit. This provides resiliency against
15001 		 * implementations that do not correctly generate push bits.
15002 		 */
15003 		if (!IPCL_IS_NONSTR(connp) && tcp->tcp_rcv_list != NULL &&
15004 		    tcp->tcp_push_tid == 0) {
15005 			/*
15006 			 * The connection may be closed at this point, so don't
15007 			 * do anything for a detached tcp.
15008 			 */
15009 			if (!TCP_IS_DETACHED(tcp))
15010 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15011 				    tcp_push_timer,
15012 				    MSEC_TO_TICK(
15013 				    tcps->tcps_push_timer_interval));
15014 		}
15015 	}
15016 
15017 xmit_check:
15018 	/* Is there anything left to do? */
15019 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15020 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15021 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15022 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15023 		goto done;
15024 
15025 	/* Any transmit work to do and a non-zero window? */
15026 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15027 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15028 		if (flags & TH_REXMIT_NEEDED) {
15029 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15030 
15031 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15032 			if (snd_size > mss)
15033 				snd_size = mss;
15034 			if (snd_size > tcp->tcp_swnd)
15035 				snd_size = tcp->tcp_swnd;
15036 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15037 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15038 			    B_TRUE);
15039 
15040 			if (mp1 != NULL) {
15041 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15042 				tcp->tcp_csuna = tcp->tcp_snxt;
15043 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15044 				UPDATE_MIB(&tcps->tcps_mib,
15045 				    tcpRetransBytes, snd_size);
15046 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15047 			}
15048 		}
15049 		if (flags & TH_NEED_SACK_REXMIT) {
15050 			tcp_sack_rxmit(tcp, &flags);
15051 		}
15052 		/*
15053 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15054 		 * out new segment.  Note that tcp_rexmit should not be
15055 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15056 		 */
15057 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15058 			if (!tcp->tcp_rexmit) {
15059 				tcp_wput_data(tcp, NULL, B_FALSE);
15060 			} else {
15061 				tcp_ss_rexmit(tcp);
15062 			}
15063 		}
15064 		/*
15065 		 * Adjust tcp_cwnd back to normal value after sending
15066 		 * new data segments.
15067 		 */
15068 		if (flags & TH_LIMIT_XMIT) {
15069 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15070 			/*
15071 			 * This will restart the timer.  Restarting the
15072 			 * timer is used to avoid a timeout before the
15073 			 * limited transmitted segment's ACK gets back.
15074 			 */
15075 			if (tcp->tcp_xmit_head != NULL)
15076 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15077 		}
15078 
15079 		/* Anything more to do? */
15080 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15081 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15082 			goto done;
15083 	}
15084 ack_check:
15085 	if (flags & TH_SEND_URP_MARK) {
15086 		ASSERT(tcp->tcp_urp_mark_mp);
15087 		ASSERT(!IPCL_IS_NONSTR(connp));
15088 		/*
15089 		 * Send up any queued data and then send the mark message
15090 		 */
15091 		if (tcp->tcp_rcv_list != NULL) {
15092 			flags |= tcp_rcv_drain(tcp);
15093 
15094 		}
15095 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15096 		mp1 = tcp->tcp_urp_mark_mp;
15097 		tcp->tcp_urp_mark_mp = NULL;
15098 		putnext(tcp->tcp_rq, mp1);
15099 #ifdef DEBUG
15100 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15101 		    "tcp_rput: sending zero-length %s %s",
15102 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15103 		    "MSGNOTMARKNEXT"),
15104 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15105 #endif /* DEBUG */
15106 		flags &= ~TH_SEND_URP_MARK;
15107 	}
15108 	if (flags & TH_ACK_NEEDED) {
15109 		/*
15110 		 * Time to send an ack for some reason.
15111 		 */
15112 		mp1 = tcp_ack_mp(tcp);
15113 
15114 		if (mp1 != NULL) {
15115 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15116 			BUMP_LOCAL(tcp->tcp_obsegs);
15117 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15118 		}
15119 		if (tcp->tcp_ack_tid != 0) {
15120 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15121 			tcp->tcp_ack_tid = 0;
15122 		}
15123 	}
15124 	if (flags & TH_ACK_TIMER_NEEDED) {
15125 		/*
15126 		 * Arrange for deferred ACK or push wait timeout.
15127 		 * Start timer if it is not already running.
15128 		 */
15129 		if (tcp->tcp_ack_tid == 0) {
15130 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15131 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15132 			    (clock_t)tcps->tcps_local_dack_interval :
15133 			    (clock_t)tcps->tcps_deferred_ack_interval));
15134 		}
15135 	}
15136 	if (flags & TH_ORDREL_NEEDED) {
15137 		/*
15138 		 * Send up the ordrel_ind unless we are an eager guy.
15139 		 * In the eager case tcp_rsrv will do this when run
15140 		 * after tcp_accept is done.
15141 		 */
15142 		ASSERT(tcp->tcp_listener == NULL);
15143 
15144 		if (IPCL_IS_NONSTR(connp)) {
15145 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15146 			tcp->tcp_ordrel_done = B_TRUE;
15147 			(*connp->conn_upcalls->su_opctl)
15148 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15149 			goto done;
15150 		}
15151 
15152 		if (tcp->tcp_rcv_list != NULL) {
15153 			/*
15154 			 * Push any mblk(s) enqueued from co processing.
15155 			 */
15156 			flags |= tcp_rcv_drain(tcp);
15157 		}
15158 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15159 
15160 		mp1 = tcp->tcp_ordrel_mp;
15161 		tcp->tcp_ordrel_mp = NULL;
15162 		tcp->tcp_ordrel_done = B_TRUE;
15163 		putnext(tcp->tcp_rq, mp1);
15164 	}
15165 done:
15166 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15167 }
15168 
15169 /*
15170  * This function does PAWS protection check. Returns B_TRUE if the
15171  * segment passes the PAWS test, else returns B_FALSE.
15172  */
15173 boolean_t
15174 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15175 {
15176 	uint8_t	flags;
15177 	int	options;
15178 	uint8_t *up;
15179 
15180 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15181 	/*
15182 	 * If timestamp option is aligned nicely, get values inline,
15183 	 * otherwise call general routine to parse.  Only do that
15184 	 * if timestamp is the only option.
15185 	 */
15186 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15187 	    TCPOPT_REAL_TS_LEN &&
15188 	    OK_32PTR((up = ((uint8_t *)tcph) +
15189 	    TCP_MIN_HEADER_LENGTH)) &&
15190 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15191 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15192 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15193 
15194 		options = TCP_OPT_TSTAMP_PRESENT;
15195 	} else {
15196 		if (tcp->tcp_snd_sack_ok) {
15197 			tcpoptp->tcp = tcp;
15198 		} else {
15199 			tcpoptp->tcp = NULL;
15200 		}
15201 		options = tcp_parse_options(tcph, tcpoptp);
15202 	}
15203 
15204 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15205 		/*
15206 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15207 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15208 		 */
15209 		if ((flags & TH_RST) == 0 &&
15210 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15211 		    tcp->tcp_ts_recent)) {
15212 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15213 			    PAWS_TIMEOUT)) {
15214 				/* This segment is not acceptable. */
15215 				return (B_FALSE);
15216 			} else {
15217 				/*
15218 				 * Connection has been idle for
15219 				 * too long.  Reset the timestamp
15220 				 * and assume the segment is valid.
15221 				 */
15222 				tcp->tcp_ts_recent =
15223 				    tcpoptp->tcp_opt_ts_val;
15224 			}
15225 		}
15226 	} else {
15227 		/*
15228 		 * If we don't get a timestamp on every packet, we
15229 		 * figure we can't really trust 'em, so we stop sending
15230 		 * and parsing them.
15231 		 */
15232 		tcp->tcp_snd_ts_ok = B_FALSE;
15233 
15234 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15235 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15236 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15237 		/*
15238 		 * Adjust the tcp_mss accordingly. We also need to
15239 		 * adjust tcp_cwnd here in accordance with the new mss.
15240 		 * But we avoid doing a slow start here so as to not
15241 		 * to lose on the transfer rate built up so far.
15242 		 */
15243 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15244 		if (tcp->tcp_snd_sack_ok) {
15245 			ASSERT(tcp->tcp_sack_info != NULL);
15246 			tcp->tcp_max_sack_blk = 4;
15247 		}
15248 	}
15249 	return (B_TRUE);
15250 }
15251 
15252 /*
15253  * Attach ancillary data to a received TCP segments for the
15254  * ancillary pieces requested by the application that are
15255  * different than they were in the previous data segment.
15256  *
15257  * Save the "current" values once memory allocation is ok so that
15258  * when memory allocation fails we can just wait for the next data segment.
15259  */
15260 static mblk_t *
15261 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15262 {
15263 	struct T_optdata_ind *todi;
15264 	int optlen;
15265 	uchar_t *optptr;
15266 	struct T_opthdr *toh;
15267 	uint_t addflag;	/* Which pieces to add */
15268 	mblk_t *mp1;
15269 
15270 	optlen = 0;
15271 	addflag = 0;
15272 	/* If app asked for pktinfo and the index has changed ... */
15273 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15274 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15275 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15276 		optlen += sizeof (struct T_opthdr) +
15277 		    sizeof (struct in6_pktinfo);
15278 		addflag |= TCP_IPV6_RECVPKTINFO;
15279 	}
15280 	/* If app asked for hoplimit and it has changed ... */
15281 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15282 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15283 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15284 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15285 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15286 	}
15287 	/* If app asked for tclass and it has changed ... */
15288 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15289 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15290 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15291 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15292 		addflag |= TCP_IPV6_RECVTCLASS;
15293 	}
15294 	/*
15295 	 * If app asked for hopbyhop headers and it has changed ...
15296 	 * For security labels, note that (1) security labels can't change on
15297 	 * a connected socket at all, (2) we're connected to at most one peer,
15298 	 * (3) if anything changes, then it must be some other extra option.
15299 	 */
15300 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15301 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15302 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15303 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15304 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15305 		    tcp->tcp_label_len;
15306 		addflag |= TCP_IPV6_RECVHOPOPTS;
15307 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15308 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15309 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15310 			return (mp);
15311 	}
15312 	/* If app asked for dst headers before routing headers ... */
15313 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15314 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15315 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15316 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15317 		optlen += sizeof (struct T_opthdr) +
15318 		    ipp->ipp_rtdstoptslen;
15319 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15320 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15321 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15322 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15323 			return (mp);
15324 	}
15325 	/* If app asked for routing headers and it has changed ... */
15326 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15327 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15328 	    (ipp->ipp_fields & IPPF_RTHDR),
15329 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15330 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15331 		addflag |= TCP_IPV6_RECVRTHDR;
15332 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15333 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15334 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15335 			return (mp);
15336 	}
15337 	/* If app asked for dest headers and it has changed ... */
15338 	if ((tcp->tcp_ipv6_recvancillary &
15339 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15340 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15341 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15342 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15343 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15344 		addflag |= TCP_IPV6_RECVDSTOPTS;
15345 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15346 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15347 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15348 			return (mp);
15349 	}
15350 
15351 	if (optlen == 0) {
15352 		/* Nothing to add */
15353 		return (mp);
15354 	}
15355 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15356 	if (mp1 == NULL) {
15357 		/*
15358 		 * Defer sending ancillary data until the next TCP segment
15359 		 * arrives.
15360 		 */
15361 		return (mp);
15362 	}
15363 	mp1->b_cont = mp;
15364 	mp = mp1;
15365 	mp->b_wptr += sizeof (*todi) + optlen;
15366 	mp->b_datap->db_type = M_PROTO;
15367 	todi = (struct T_optdata_ind *)mp->b_rptr;
15368 	todi->PRIM_type = T_OPTDATA_IND;
15369 	todi->DATA_flag = 1;	/* MORE data */
15370 	todi->OPT_length = optlen;
15371 	todi->OPT_offset = sizeof (*todi);
15372 	optptr = (uchar_t *)&todi[1];
15373 	/*
15374 	 * If app asked for pktinfo and the index has changed ...
15375 	 * Note that the local address never changes for the connection.
15376 	 */
15377 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15378 		struct in6_pktinfo *pkti;
15379 
15380 		toh = (struct T_opthdr *)optptr;
15381 		toh->level = IPPROTO_IPV6;
15382 		toh->name = IPV6_PKTINFO;
15383 		toh->len = sizeof (*toh) + sizeof (*pkti);
15384 		toh->status = 0;
15385 		optptr += sizeof (*toh);
15386 		pkti = (struct in6_pktinfo *)optptr;
15387 		if (tcp->tcp_ipversion == IPV6_VERSION)
15388 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15389 		else
15390 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15391 			    &pkti->ipi6_addr);
15392 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15393 		optptr += sizeof (*pkti);
15394 		ASSERT(OK_32PTR(optptr));
15395 		/* Save as "last" value */
15396 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15397 	}
15398 	/* If app asked for hoplimit and it has changed ... */
15399 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15400 		toh = (struct T_opthdr *)optptr;
15401 		toh->level = IPPROTO_IPV6;
15402 		toh->name = IPV6_HOPLIMIT;
15403 		toh->len = sizeof (*toh) + sizeof (uint_t);
15404 		toh->status = 0;
15405 		optptr += sizeof (*toh);
15406 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15407 		optptr += sizeof (uint_t);
15408 		ASSERT(OK_32PTR(optptr));
15409 		/* Save as "last" value */
15410 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15411 	}
15412 	/* If app asked for tclass and it has changed ... */
15413 	if (addflag & TCP_IPV6_RECVTCLASS) {
15414 		toh = (struct T_opthdr *)optptr;
15415 		toh->level = IPPROTO_IPV6;
15416 		toh->name = IPV6_TCLASS;
15417 		toh->len = sizeof (*toh) + sizeof (uint_t);
15418 		toh->status = 0;
15419 		optptr += sizeof (*toh);
15420 		*(uint_t *)optptr = ipp->ipp_tclass;
15421 		optptr += sizeof (uint_t);
15422 		ASSERT(OK_32PTR(optptr));
15423 		/* Save as "last" value */
15424 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15425 	}
15426 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15427 		toh = (struct T_opthdr *)optptr;
15428 		toh->level = IPPROTO_IPV6;
15429 		toh->name = IPV6_HOPOPTS;
15430 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15431 		    tcp->tcp_label_len;
15432 		toh->status = 0;
15433 		optptr += sizeof (*toh);
15434 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15435 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15436 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15437 		ASSERT(OK_32PTR(optptr));
15438 		/* Save as last value */
15439 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15440 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15441 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15442 	}
15443 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15444 		toh = (struct T_opthdr *)optptr;
15445 		toh->level = IPPROTO_IPV6;
15446 		toh->name = IPV6_RTHDRDSTOPTS;
15447 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15448 		toh->status = 0;
15449 		optptr += sizeof (*toh);
15450 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15451 		optptr += ipp->ipp_rtdstoptslen;
15452 		ASSERT(OK_32PTR(optptr));
15453 		/* Save as last value */
15454 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15455 		    &tcp->tcp_rtdstoptslen,
15456 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15457 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15458 	}
15459 	if (addflag & TCP_IPV6_RECVRTHDR) {
15460 		toh = (struct T_opthdr *)optptr;
15461 		toh->level = IPPROTO_IPV6;
15462 		toh->name = IPV6_RTHDR;
15463 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15464 		toh->status = 0;
15465 		optptr += sizeof (*toh);
15466 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15467 		optptr += ipp->ipp_rthdrlen;
15468 		ASSERT(OK_32PTR(optptr));
15469 		/* Save as last value */
15470 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15471 		    (ipp->ipp_fields & IPPF_RTHDR),
15472 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15473 	}
15474 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15475 		toh = (struct T_opthdr *)optptr;
15476 		toh->level = IPPROTO_IPV6;
15477 		toh->name = IPV6_DSTOPTS;
15478 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15479 		toh->status = 0;
15480 		optptr += sizeof (*toh);
15481 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15482 		optptr += ipp->ipp_dstoptslen;
15483 		ASSERT(OK_32PTR(optptr));
15484 		/* Save as last value */
15485 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15486 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15487 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15488 	}
15489 	ASSERT(optptr == mp->b_wptr);
15490 	return (mp);
15491 }
15492 
15493 /*
15494  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15495  * messages.
15496  */
15497 void
15498 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15499 {
15500 	uchar_t	*rptr = mp->b_rptr;
15501 	queue_t	*q = tcp->tcp_rq;
15502 	struct T_error_ack *tea;
15503 
15504 	switch (mp->b_datap->db_type) {
15505 	case M_PROTO:
15506 	case M_PCPROTO:
15507 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15508 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15509 			break;
15510 		tea = (struct T_error_ack *)rptr;
15511 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15512 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15513 		    tea->ERROR_prim != T_BIND_REQ);
15514 		switch (tea->PRIM_type) {
15515 		case T_ERROR_ACK:
15516 			if (tcp->tcp_debug) {
15517 				(void) strlog(TCP_MOD_ID, 0, 1,
15518 				    SL_TRACE|SL_ERROR,
15519 				    "tcp_rput_other: case T_ERROR_ACK, "
15520 				    "ERROR_prim == %d",
15521 				    tea->ERROR_prim);
15522 			}
15523 			switch (tea->ERROR_prim) {
15524 			case T_SVR4_OPTMGMT_REQ:
15525 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15526 					/* T_OPTMGMT_REQ generated by TCP */
15527 					printf("T_SVR4_OPTMGMT_REQ failed "
15528 					    "%d/%d - dropped (cnt %d)\n",
15529 					    tea->TLI_error, tea->UNIX_error,
15530 					    tcp->tcp_drop_opt_ack_cnt);
15531 					freemsg(mp);
15532 					tcp->tcp_drop_opt_ack_cnt--;
15533 					return;
15534 				}
15535 				break;
15536 			}
15537 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15538 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15539 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15540 				    "- dropped (cnt %d)\n",
15541 				    tea->TLI_error, tea->UNIX_error,
15542 				    tcp->tcp_drop_opt_ack_cnt);
15543 				freemsg(mp);
15544 				tcp->tcp_drop_opt_ack_cnt--;
15545 				return;
15546 			}
15547 			break;
15548 		case T_OPTMGMT_ACK:
15549 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15550 				/* T_OPTMGMT_REQ generated by TCP */
15551 				freemsg(mp);
15552 				tcp->tcp_drop_opt_ack_cnt--;
15553 				return;
15554 			}
15555 			break;
15556 		default:
15557 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15558 			break;
15559 		}
15560 		break;
15561 	case M_FLUSH:
15562 		if (*rptr & FLUSHR)
15563 			flushq(q, FLUSHDATA);
15564 		break;
15565 	default:
15566 		/* M_CTL will be directly sent to tcp_icmp_error() */
15567 		ASSERT(DB_TYPE(mp) != M_CTL);
15568 		break;
15569 	}
15570 	/*
15571 	 * Make sure we set this bit before sending the ACK for
15572 	 * bind. Otherwise accept could possibly run and free
15573 	 * this tcp struct.
15574 	 */
15575 	ASSERT(q != NULL);
15576 	putnext(q, mp);
15577 }
15578 
15579 /* ARGSUSED */
15580 static void
15581 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15582 {
15583 	conn_t	*connp = (conn_t *)arg;
15584 	tcp_t	*tcp = connp->conn_tcp;
15585 	queue_t	*q = tcp->tcp_rq;
15586 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15587 
15588 	ASSERT(!IPCL_IS_NONSTR(connp));
15589 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15590 	tcp->tcp_rsrv_mp = mp;
15591 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15592 
15593 	TCP_STAT(tcps, tcp_rsrv_calls);
15594 
15595 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15596 		return;
15597 	}
15598 
15599 	if (tcp->tcp_fused) {
15600 		tcp_fuse_backenable(tcp);
15601 		return;
15602 	}
15603 
15604 	if (canputnext(q)) {
15605 		/* Not flow-controlled, open rwnd */
15606 		tcp->tcp_rwnd = q->q_hiwat;
15607 
15608 		/*
15609 		 * Send back a window update immediately if TCP is above
15610 		 * ESTABLISHED state and the increase of the rcv window
15611 		 * that the other side knows is at least 1 MSS after flow
15612 		 * control is lifted.
15613 		 */
15614 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15615 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
15616 			tcp_xmit_ctl(NULL, tcp,
15617 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15618 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15619 		}
15620 	}
15621 }
15622 
15623 /*
15624  * The read side service routine is called mostly when we get back-enabled as a
15625  * result of flow control relief.  Since we don't actually queue anything in
15626  * TCP, we have no data to send out of here.  What we do is clear the receive
15627  * window, and send out a window update.
15628  */
15629 static void
15630 tcp_rsrv(queue_t *q)
15631 {
15632 	conn_t		*connp = Q_TO_CONN(q);
15633 	tcp_t		*tcp = connp->conn_tcp;
15634 	mblk_t		*mp;
15635 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15636 
15637 	/* No code does a putq on the read side */
15638 	ASSERT(q->q_first == NULL);
15639 
15640 	/* Nothing to do for the default queue */
15641 	if (q == tcps->tcps_g_q) {
15642 		return;
15643 	}
15644 
15645 	/*
15646 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15647 	 * been run.  So just return.
15648 	 */
15649 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15650 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15651 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15652 		return;
15653 	}
15654 	tcp->tcp_rsrv_mp = NULL;
15655 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15656 
15657 	CONN_INC_REF(connp);
15658 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15659 	    SQ_PROCESS, SQTAG_TCP_RSRV);
15660 }
15661 
15662 /*
15663  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15664  * We do not allow the receive window to shrink.  After setting rwnd,
15665  * set the flow control hiwat of the stream.
15666  *
15667  * This function is called in 2 cases:
15668  *
15669  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15670  *    connection (passive open) and in tcp_rput_data() for active connect.
15671  *    This is called after tcp_mss_set() when the desired MSS value is known.
15672  *    This makes sure that our window size is a mutiple of the other side's
15673  *    MSS.
15674  * 2) Handling SO_RCVBUF option.
15675  *
15676  * It is ASSUMED that the requested size is a multiple of the current MSS.
15677  *
15678  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15679  * user requests so.
15680  */
15681 static int
15682 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15683 {
15684 	uint32_t	mss = tcp->tcp_mss;
15685 	uint32_t	old_max_rwnd;
15686 	uint32_t	max_transmittable_rwnd;
15687 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15688 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15689 
15690 	if (tcp->tcp_fused) {
15691 		size_t sth_hiwat;
15692 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15693 
15694 		ASSERT(peer_tcp != NULL);
15695 		/*
15696 		 * Record the stream head's high water mark for
15697 		 * this endpoint; this is used for flow-control
15698 		 * purposes in tcp_fuse_output().
15699 		 */
15700 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15701 		if (!tcp_detached) {
15702 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15703 			    sth_hiwat);
15704 			if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
15705 				conn_t *connp = tcp->tcp_connp;
15706 				struct sock_proto_props sopp;
15707 
15708 				sopp.sopp_flags = SOCKOPT_RCVTHRESH;
15709 				sopp.sopp_rcvthresh = sth_hiwat >> 3;
15710 
15711 				(*connp->conn_upcalls->su_set_proto_props)
15712 				    (connp->conn_upper_handle, &sopp);
15713 			}
15714 		}
15715 
15716 		/*
15717 		 * In the fusion case, the maxpsz stream head value of
15718 		 * our peer is set according to its send buffer size
15719 		 * and our receive buffer size; since the latter may
15720 		 * have changed we need to update the peer's maxpsz.
15721 		 */
15722 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15723 		return (rwnd);
15724 	}
15725 
15726 	if (tcp_detached) {
15727 		old_max_rwnd = tcp->tcp_rwnd;
15728 	} else {
15729 		old_max_rwnd = tcp->tcp_recv_hiwater;
15730 	}
15731 
15732 	/*
15733 	 * Insist on a receive window that is at least
15734 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15735 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15736 	 * and delayed acknowledgement.
15737 	 */
15738 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
15739 
15740 	/*
15741 	 * If window size info has already been exchanged, TCP should not
15742 	 * shrink the window.  Shrinking window is doable if done carefully.
15743 	 * We may add that support later.  But so far there is not a real
15744 	 * need to do that.
15745 	 */
15746 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15747 		/* MSS may have changed, do a round up again. */
15748 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15749 	}
15750 
15751 	/*
15752 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15753 	 * can be applied even before the window scale option is decided.
15754 	 */
15755 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15756 	if (rwnd > max_transmittable_rwnd) {
15757 		rwnd = max_transmittable_rwnd -
15758 		    (max_transmittable_rwnd % mss);
15759 		if (rwnd < mss)
15760 			rwnd = max_transmittable_rwnd;
15761 		/*
15762 		 * If we're over the limit we may have to back down tcp_rwnd.
15763 		 * The increment below won't work for us. So we set all three
15764 		 * here and the increment below will have no effect.
15765 		 */
15766 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15767 	}
15768 	if (tcp->tcp_localnet) {
15769 		tcp->tcp_rack_abs_max =
15770 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
15771 	} else {
15772 		/*
15773 		 * For a remote host on a different subnet (through a router),
15774 		 * we ack every other packet to be conforming to RFC1122.
15775 		 * tcp_deferred_acks_max is default to 2.
15776 		 */
15777 		tcp->tcp_rack_abs_max =
15778 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
15779 	}
15780 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15781 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15782 	else
15783 		tcp->tcp_rack_cur_max = 0;
15784 	/*
15785 	 * Increment the current rwnd by the amount the maximum grew (we
15786 	 * can not overwrite it since we might be in the middle of a
15787 	 * connection.)
15788 	 */
15789 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15790 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15791 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15792 		tcp->tcp_cwnd_max = rwnd;
15793 
15794 	if (tcp_detached)
15795 		return (rwnd);
15796 	/*
15797 	 * We set the maximum receive window into rq->q_hiwat if it is
15798 	 * a STREAMS socket.
15799 	 * This is not actually used for flow control.
15800 	 */
15801 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
15802 		tcp->tcp_rq->q_hiwat = rwnd;
15803 	tcp->tcp_recv_hiwater = rwnd;
15804 	/*
15805 	 * Set the STREAM head high water mark. This doesn't have to be
15806 	 * here, since we are simply using default values, but we would
15807 	 * prefer to choose these values algorithmically, with a likely
15808 	 * relationship to rwnd.
15809 	 */
15810 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15811 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
15812 	return (rwnd);
15813 }
15814 
15815 /*
15816  * Return SNMP stuff in buffer in mpdata.
15817  */
15818 mblk_t *
15819 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15820 {
15821 	mblk_t			*mpdata;
15822 	mblk_t			*mp_conn_ctl = NULL;
15823 	mblk_t			*mp_conn_tail;
15824 	mblk_t			*mp_attr_ctl = NULL;
15825 	mblk_t			*mp_attr_tail;
15826 	mblk_t			*mp6_conn_ctl = NULL;
15827 	mblk_t			*mp6_conn_tail;
15828 	mblk_t			*mp6_attr_ctl = NULL;
15829 	mblk_t			*mp6_attr_tail;
15830 	struct opthdr		*optp;
15831 	mib2_tcpConnEntry_t	tce;
15832 	mib2_tcp6ConnEntry_t	tce6;
15833 	mib2_transportMLPEntry_t mlp;
15834 	connf_t			*connfp;
15835 	int			i;
15836 	boolean_t 		ispriv;
15837 	zoneid_t 		zoneid;
15838 	int			v4_conn_idx;
15839 	int			v6_conn_idx;
15840 	conn_t			*connp = Q_TO_CONN(q);
15841 	tcp_stack_t		*tcps;
15842 	ip_stack_t		*ipst;
15843 	mblk_t			*mp2ctl;
15844 
15845 	/*
15846 	 * make a copy of the original message
15847 	 */
15848 	mp2ctl = copymsg(mpctl);
15849 
15850 	if (mpctl == NULL ||
15851 	    (mpdata = mpctl->b_cont) == NULL ||
15852 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15853 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
15854 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
15855 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
15856 		freemsg(mp_conn_ctl);
15857 		freemsg(mp_attr_ctl);
15858 		freemsg(mp6_conn_ctl);
15859 		freemsg(mp6_attr_ctl);
15860 		freemsg(mpctl);
15861 		freemsg(mp2ctl);
15862 		return (NULL);
15863 	}
15864 
15865 	ipst = connp->conn_netstack->netstack_ip;
15866 	tcps = connp->conn_netstack->netstack_tcp;
15867 
15868 	/* build table of connections -- need count in fixed part */
15869 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
15870 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
15871 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
15872 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
15873 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
15874 
15875 	ispriv =
15876 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15877 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15878 
15879 	v4_conn_idx = v6_conn_idx = 0;
15880 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
15881 
15882 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15883 		ipst = tcps->tcps_netstack->netstack_ip;
15884 
15885 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
15886 
15887 		connp = NULL;
15888 
15889 		while ((connp =
15890 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15891 			tcp_t *tcp;
15892 			boolean_t needattr;
15893 
15894 			if (connp->conn_zoneid != zoneid)
15895 				continue;	/* not in this zone */
15896 
15897 			tcp = connp->conn_tcp;
15898 			UPDATE_MIB(&tcps->tcps_mib,
15899 			    tcpHCInSegs, tcp->tcp_ibsegs);
15900 			tcp->tcp_ibsegs = 0;
15901 			UPDATE_MIB(&tcps->tcps_mib,
15902 			    tcpHCOutSegs, tcp->tcp_obsegs);
15903 			tcp->tcp_obsegs = 0;
15904 
15905 			tce6.tcp6ConnState = tce.tcpConnState =
15906 			    tcp_snmp_state(tcp);
15907 			if (tce.tcpConnState == MIB2_TCP_established ||
15908 			    tce.tcpConnState == MIB2_TCP_closeWait)
15909 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
15910 
15911 			needattr = B_FALSE;
15912 			bzero(&mlp, sizeof (mlp));
15913 			if (connp->conn_mlp_type != mlptSingle) {
15914 				if (connp->conn_mlp_type == mlptShared ||
15915 				    connp->conn_mlp_type == mlptBoth)
15916 					mlp.tme_flags |= MIB2_TMEF_SHARED;
15917 				if (connp->conn_mlp_type == mlptPrivate ||
15918 				    connp->conn_mlp_type == mlptBoth)
15919 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
15920 				needattr = B_TRUE;
15921 			}
15922 			if (connp->conn_anon_mlp) {
15923 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
15924 				needattr = B_TRUE;
15925 			}
15926 			if (connp->conn_mac_exempt) {
15927 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
15928 				needattr = B_TRUE;
15929 			}
15930 			if (connp->conn_fully_bound &&
15931 			    connp->conn_effective_cred != NULL) {
15932 				ts_label_t *tsl;
15933 
15934 				tsl = crgetlabel(connp->conn_effective_cred);
15935 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
15936 				mlp.tme_doi = label2doi(tsl);
15937 				mlp.tme_label = *label2bslabel(tsl);
15938 				needattr = B_TRUE;
15939 			}
15940 
15941 			/* Create a message to report on IPv6 entries */
15942 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15943 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15944 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15945 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15946 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15947 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15948 			/* Don't want just anybody seeing these... */
15949 			if (ispriv) {
15950 				tce6.tcp6ConnEntryInfo.ce_snxt =
15951 				    tcp->tcp_snxt;
15952 				tce6.tcp6ConnEntryInfo.ce_suna =
15953 				    tcp->tcp_suna;
15954 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15955 				    tcp->tcp_rnxt;
15956 				tce6.tcp6ConnEntryInfo.ce_rack =
15957 				    tcp->tcp_rack;
15958 			} else {
15959 				/*
15960 				 * Netstat, unfortunately, uses this to
15961 				 * get send/receive queue sizes.  How to fix?
15962 				 * Why not compute the difference only?
15963 				 */
15964 				tce6.tcp6ConnEntryInfo.ce_snxt =
15965 				    tcp->tcp_snxt - tcp->tcp_suna;
15966 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
15967 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15968 				    tcp->tcp_rnxt - tcp->tcp_rack;
15969 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
15970 			}
15971 
15972 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15973 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15974 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
15975 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
15976 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
15977 
15978 			tce6.tcp6ConnCreationProcess =
15979 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
15980 			    tcp->tcp_cpid;
15981 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
15982 
15983 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
15984 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
15985 
15986 			mlp.tme_connidx = v6_conn_idx++;
15987 			if (needattr)
15988 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
15989 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
15990 			}
15991 			/*
15992 			 * Create an IPv4 table entry for IPv4 entries and also
15993 			 * for IPv6 entries which are bound to in6addr_any
15994 			 * but don't have IPV6_V6ONLY set.
15995 			 * (i.e. anything an IPv4 peer could connect to)
15996 			 */
15997 			if (tcp->tcp_ipversion == IPV4_VERSION ||
15998 			    (tcp->tcp_state <= TCPS_LISTEN &&
15999 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16000 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16001 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16002 					tce.tcpConnRemAddress = INADDR_ANY;
16003 					tce.tcpConnLocalAddress = INADDR_ANY;
16004 				} else {
16005 					tce.tcpConnRemAddress =
16006 					    tcp->tcp_remote;
16007 					tce.tcpConnLocalAddress =
16008 					    tcp->tcp_ip_src;
16009 				}
16010 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16011 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16012 				/* Don't want just anybody seeing these... */
16013 				if (ispriv) {
16014 					tce.tcpConnEntryInfo.ce_snxt =
16015 					    tcp->tcp_snxt;
16016 					tce.tcpConnEntryInfo.ce_suna =
16017 					    tcp->tcp_suna;
16018 					tce.tcpConnEntryInfo.ce_rnxt =
16019 					    tcp->tcp_rnxt;
16020 					tce.tcpConnEntryInfo.ce_rack =
16021 					    tcp->tcp_rack;
16022 				} else {
16023 					/*
16024 					 * Netstat, unfortunately, uses this to
16025 					 * get send/receive queue sizes.  How
16026 					 * to fix?
16027 					 * Why not compute the difference only?
16028 					 */
16029 					tce.tcpConnEntryInfo.ce_snxt =
16030 					    tcp->tcp_snxt - tcp->tcp_suna;
16031 					tce.tcpConnEntryInfo.ce_suna = 0;
16032 					tce.tcpConnEntryInfo.ce_rnxt =
16033 					    tcp->tcp_rnxt - tcp->tcp_rack;
16034 					tce.tcpConnEntryInfo.ce_rack = 0;
16035 				}
16036 
16037 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16038 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16039 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16040 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16041 				tce.tcpConnEntryInfo.ce_state =
16042 				    tcp->tcp_state;
16043 
16044 				tce.tcpConnCreationProcess =
16045 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16046 				    tcp->tcp_cpid;
16047 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16048 
16049 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16050 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16051 
16052 				mlp.tme_connidx = v4_conn_idx++;
16053 				if (needattr)
16054 					(void) snmp_append_data2(
16055 					    mp_attr_ctl->b_cont,
16056 					    &mp_attr_tail, (char *)&mlp,
16057 					    sizeof (mlp));
16058 			}
16059 		}
16060 	}
16061 
16062 	/* fixed length structure for IPv4 and IPv6 counters */
16063 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16064 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16065 	    sizeof (mib2_tcp6ConnEntry_t));
16066 	/* synchronize 32- and 64-bit counters */
16067 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16068 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16069 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16070 	optp->level = MIB2_TCP;
16071 	optp->name = 0;
16072 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16073 	    sizeof (tcps->tcps_mib));
16074 	optp->len = msgdsize(mpdata);
16075 	qreply(q, mpctl);
16076 
16077 	/* table of connections... */
16078 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16079 	    sizeof (struct T_optmgmt_ack)];
16080 	optp->level = MIB2_TCP;
16081 	optp->name = MIB2_TCP_CONN;
16082 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16083 	qreply(q, mp_conn_ctl);
16084 
16085 	/* table of MLP attributes... */
16086 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16087 	    sizeof (struct T_optmgmt_ack)];
16088 	optp->level = MIB2_TCP;
16089 	optp->name = EXPER_XPORT_MLP;
16090 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16091 	if (optp->len == 0)
16092 		freemsg(mp_attr_ctl);
16093 	else
16094 		qreply(q, mp_attr_ctl);
16095 
16096 	/* table of IPv6 connections... */
16097 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16098 	    sizeof (struct T_optmgmt_ack)];
16099 	optp->level = MIB2_TCP6;
16100 	optp->name = MIB2_TCP6_CONN;
16101 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16102 	qreply(q, mp6_conn_ctl);
16103 
16104 	/* table of IPv6 MLP attributes... */
16105 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16106 	    sizeof (struct T_optmgmt_ack)];
16107 	optp->level = MIB2_TCP6;
16108 	optp->name = EXPER_XPORT_MLP;
16109 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16110 	if (optp->len == 0)
16111 		freemsg(mp6_attr_ctl);
16112 	else
16113 		qreply(q, mp6_attr_ctl);
16114 	return (mp2ctl);
16115 }
16116 
16117 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16118 /* ARGSUSED */
16119 int
16120 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16121 {
16122 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16123 
16124 	switch (level) {
16125 	case MIB2_TCP:
16126 		switch (name) {
16127 		case 13:
16128 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16129 				return (0);
16130 			/* TODO: delete entry defined by tce */
16131 			return (1);
16132 		default:
16133 			return (0);
16134 		}
16135 	default:
16136 		return (1);
16137 	}
16138 }
16139 
16140 /* Translate TCP state to MIB2 TCP state. */
16141 static int
16142 tcp_snmp_state(tcp_t *tcp)
16143 {
16144 	if (tcp == NULL)
16145 		return (0);
16146 
16147 	switch (tcp->tcp_state) {
16148 	case TCPS_CLOSED:
16149 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16150 	case TCPS_BOUND:
16151 		return (MIB2_TCP_closed);
16152 	case TCPS_LISTEN:
16153 		return (MIB2_TCP_listen);
16154 	case TCPS_SYN_SENT:
16155 		return (MIB2_TCP_synSent);
16156 	case TCPS_SYN_RCVD:
16157 		return (MIB2_TCP_synReceived);
16158 	case TCPS_ESTABLISHED:
16159 		return (MIB2_TCP_established);
16160 	case TCPS_CLOSE_WAIT:
16161 		return (MIB2_TCP_closeWait);
16162 	case TCPS_FIN_WAIT_1:
16163 		return (MIB2_TCP_finWait1);
16164 	case TCPS_CLOSING:
16165 		return (MIB2_TCP_closing);
16166 	case TCPS_LAST_ACK:
16167 		return (MIB2_TCP_lastAck);
16168 	case TCPS_FIN_WAIT_2:
16169 		return (MIB2_TCP_finWait2);
16170 	case TCPS_TIME_WAIT:
16171 		return (MIB2_TCP_timeWait);
16172 	default:
16173 		return (0);
16174 	}
16175 }
16176 
16177 /*
16178  * tcp_timer is the timer service routine.  It handles the retransmission,
16179  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16180  * from the state of the tcp instance what kind of action needs to be done
16181  * at the time it is called.
16182  */
16183 static void
16184 tcp_timer(void *arg)
16185 {
16186 	mblk_t		*mp;
16187 	clock_t		first_threshold;
16188 	clock_t		second_threshold;
16189 	clock_t		ms;
16190 	uint32_t	mss;
16191 	conn_t		*connp = (conn_t *)arg;
16192 	tcp_t		*tcp = connp->conn_tcp;
16193 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16194 
16195 	tcp->tcp_timer_tid = 0;
16196 
16197 	if (tcp->tcp_fused)
16198 		return;
16199 
16200 	first_threshold =  tcp->tcp_first_timer_threshold;
16201 	second_threshold = tcp->tcp_second_timer_threshold;
16202 	switch (tcp->tcp_state) {
16203 	case TCPS_IDLE:
16204 	case TCPS_BOUND:
16205 	case TCPS_LISTEN:
16206 		return;
16207 	case TCPS_SYN_RCVD: {
16208 		tcp_t	*listener = tcp->tcp_listener;
16209 
16210 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16211 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16212 			/* it's our first timeout */
16213 			tcp->tcp_syn_rcvd_timeout = 1;
16214 			mutex_enter(&listener->tcp_eager_lock);
16215 			listener->tcp_syn_rcvd_timeout++;
16216 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16217 				/*
16218 				 * Make this eager available for drop if we
16219 				 * need to drop one to accomodate a new
16220 				 * incoming SYN request.
16221 				 */
16222 				MAKE_DROPPABLE(listener, tcp);
16223 			}
16224 			if (!listener->tcp_syn_defense &&
16225 			    (listener->tcp_syn_rcvd_timeout >
16226 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16227 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16228 				/* We may be under attack. Put on a defense. */
16229 				listener->tcp_syn_defense = B_TRUE;
16230 				cmn_err(CE_WARN, "High TCP connect timeout "
16231 				    "rate! System (port %d) may be under a "
16232 				    "SYN flood attack!",
16233 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16234 
16235 				listener->tcp_ip_addr_cache = kmem_zalloc(
16236 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16237 				    KM_NOSLEEP);
16238 			}
16239 			mutex_exit(&listener->tcp_eager_lock);
16240 		} else if (listener != NULL) {
16241 			mutex_enter(&listener->tcp_eager_lock);
16242 			tcp->tcp_syn_rcvd_timeout++;
16243 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16244 			    !tcp->tcp_closemp_used) {
16245 				/*
16246 				 * This is our second timeout. Put the tcp in
16247 				 * the list of droppable eagers to allow it to
16248 				 * be dropped, if needed. We don't check
16249 				 * whether tcp_dontdrop is set or not to
16250 				 * protect ourselve from a SYN attack where a
16251 				 * remote host can spoof itself as one of the
16252 				 * good IP source and continue to hold
16253 				 * resources too long.
16254 				 */
16255 				MAKE_DROPPABLE(listener, tcp);
16256 			}
16257 			mutex_exit(&listener->tcp_eager_lock);
16258 		}
16259 	}
16260 		/* FALLTHRU */
16261 	case TCPS_SYN_SENT:
16262 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16263 		second_threshold = tcp->tcp_second_ctimer_threshold;
16264 		break;
16265 	case TCPS_ESTABLISHED:
16266 	case TCPS_FIN_WAIT_1:
16267 	case TCPS_CLOSING:
16268 	case TCPS_CLOSE_WAIT:
16269 	case TCPS_LAST_ACK:
16270 		/* If we have data to rexmit */
16271 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16272 			clock_t	time_to_wait;
16273 
16274 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16275 			if (!tcp->tcp_xmit_head)
16276 				break;
16277 			time_to_wait = lbolt -
16278 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16279 			time_to_wait = tcp->tcp_rto -
16280 			    TICK_TO_MSEC(time_to_wait);
16281 			/*
16282 			 * If the timer fires too early, 1 clock tick earlier,
16283 			 * restart the timer.
16284 			 */
16285 			if (time_to_wait > msec_per_tick) {
16286 				TCP_STAT(tcps, tcp_timer_fire_early);
16287 				TCP_TIMER_RESTART(tcp, time_to_wait);
16288 				return;
16289 			}
16290 			/*
16291 			 * When we probe zero windows, we force the swnd open.
16292 			 * If our peer acks with a closed window swnd will be
16293 			 * set to zero by tcp_rput(). As long as we are
16294 			 * receiving acks tcp_rput will
16295 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16296 			 * first and second interval actions.  NOTE: the timer
16297 			 * interval is allowed to continue its exponential
16298 			 * backoff.
16299 			 */
16300 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16301 				if (tcp->tcp_debug) {
16302 					(void) strlog(TCP_MOD_ID, 0, 1,
16303 					    SL_TRACE, "tcp_timer: zero win");
16304 				}
16305 			} else {
16306 				/*
16307 				 * After retransmission, we need to do
16308 				 * slow start.  Set the ssthresh to one
16309 				 * half of current effective window and
16310 				 * cwnd to one MSS.  Also reset
16311 				 * tcp_cwnd_cnt.
16312 				 *
16313 				 * Note that if tcp_ssthresh is reduced because
16314 				 * of ECN, do not reduce it again unless it is
16315 				 * already one window of data away (tcp_cwr
16316 				 * should then be cleared) or this is a
16317 				 * timeout for a retransmitted segment.
16318 				 */
16319 				uint32_t npkt;
16320 
16321 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16322 					npkt = ((tcp->tcp_timer_backoff ?
16323 					    tcp->tcp_cwnd_ssthresh :
16324 					    tcp->tcp_snxt -
16325 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16326 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16327 					    tcp->tcp_mss;
16328 				}
16329 				tcp->tcp_cwnd = tcp->tcp_mss;
16330 				tcp->tcp_cwnd_cnt = 0;
16331 				if (tcp->tcp_ecn_ok) {
16332 					tcp->tcp_cwr = B_TRUE;
16333 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16334 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16335 				}
16336 			}
16337 			break;
16338 		}
16339 		/*
16340 		 * We have something to send yet we cannot send.  The
16341 		 * reason can be:
16342 		 *
16343 		 * 1. Zero send window: we need to do zero window probe.
16344 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16345 		 * segments.
16346 		 * 3. SWS avoidance: receiver may have shrunk window,
16347 		 * reset our knowledge.
16348 		 *
16349 		 * Note that condition 2 can happen with either 1 or
16350 		 * 3.  But 1 and 3 are exclusive.
16351 		 */
16352 		if (tcp->tcp_unsent != 0) {
16353 			if (tcp->tcp_cwnd == 0) {
16354 				/*
16355 				 * Set tcp_cwnd to 1 MSS so that a
16356 				 * new segment can be sent out.  We
16357 				 * are "clocking out" new data when
16358 				 * the network is really congested.
16359 				 */
16360 				ASSERT(tcp->tcp_ecn_ok);
16361 				tcp->tcp_cwnd = tcp->tcp_mss;
16362 			}
16363 			if (tcp->tcp_swnd == 0) {
16364 				/* Extend window for zero window probe */
16365 				tcp->tcp_swnd++;
16366 				tcp->tcp_zero_win_probe = B_TRUE;
16367 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
16368 			} else {
16369 				/*
16370 				 * Handle timeout from sender SWS avoidance.
16371 				 * Reset our knowledge of the max send window
16372 				 * since the receiver might have reduced its
16373 				 * receive buffer.  Avoid setting tcp_max_swnd
16374 				 * to one since that will essentially disable
16375 				 * the SWS checks.
16376 				 *
16377 				 * Note that since we don't have a SWS
16378 				 * state variable, if the timeout is set
16379 				 * for ECN but not for SWS, this
16380 				 * code will also be executed.  This is
16381 				 * fine as tcp_max_swnd is updated
16382 				 * constantly and it will not affect
16383 				 * anything.
16384 				 */
16385 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16386 			}
16387 			tcp_wput_data(tcp, NULL, B_FALSE);
16388 			return;
16389 		}
16390 		/* Is there a FIN that needs to be to re retransmitted? */
16391 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16392 		    !tcp->tcp_fin_acked)
16393 			break;
16394 		/* Nothing to do, return without restarting timer. */
16395 		TCP_STAT(tcps, tcp_timer_fire_miss);
16396 		return;
16397 	case TCPS_FIN_WAIT_2:
16398 		/*
16399 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16400 		 * We waited some time for for peer's FIN, but it hasn't
16401 		 * arrived.  We flush the connection now to avoid
16402 		 * case where the peer has rebooted.
16403 		 */
16404 		if (TCP_IS_DETACHED(tcp)) {
16405 			(void) tcp_clean_death(tcp, 0, 23);
16406 		} else {
16407 			TCP_TIMER_RESTART(tcp,
16408 			    tcps->tcps_fin_wait_2_flush_interval);
16409 		}
16410 		return;
16411 	case TCPS_TIME_WAIT:
16412 		(void) tcp_clean_death(tcp, 0, 24);
16413 		return;
16414 	default:
16415 		if (tcp->tcp_debug) {
16416 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16417 			    "tcp_timer: strange state (%d) %s",
16418 			    tcp->tcp_state, tcp_display(tcp, NULL,
16419 			    DISP_PORT_ONLY));
16420 		}
16421 		return;
16422 	}
16423 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16424 		/*
16425 		 * For zero window probe, we need to send indefinitely,
16426 		 * unless we have not heard from the other side for some
16427 		 * time...
16428 		 */
16429 		if ((tcp->tcp_zero_win_probe == 0) ||
16430 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16431 		    second_threshold)) {
16432 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
16433 			/*
16434 			 * If TCP is in SYN_RCVD state, send back a
16435 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16436 			 * should be zero in TCPS_SYN_RCVD state.
16437 			 */
16438 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16439 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16440 				    "in SYN_RCVD",
16441 				    tcp, tcp->tcp_snxt,
16442 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16443 			}
16444 			(void) tcp_clean_death(tcp,
16445 			    tcp->tcp_client_errno ?
16446 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16447 			return;
16448 		} else {
16449 			/*
16450 			 * Set tcp_ms_we_have_waited to second_threshold
16451 			 * so that in next timeout, we will do the above
16452 			 * check (lbolt - tcp_last_recv_time).  This is
16453 			 * also to avoid overflow.
16454 			 *
16455 			 * We don't need to decrement tcp_timer_backoff
16456 			 * to avoid overflow because it will be decremented
16457 			 * later if new timeout value is greater than
16458 			 * tcp_rexmit_interval_max.  In the case when
16459 			 * tcp_rexmit_interval_max is greater than
16460 			 * second_threshold, it means that we will wait
16461 			 * longer than second_threshold to send the next
16462 			 * window probe.
16463 			 */
16464 			tcp->tcp_ms_we_have_waited = second_threshold;
16465 		}
16466 	} else if (ms > first_threshold) {
16467 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16468 		    tcp->tcp_xmit_head != NULL) {
16469 			tcp->tcp_xmit_head =
16470 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16471 		}
16472 		/*
16473 		 * We have been retransmitting for too long...  The RTT
16474 		 * we calculated is probably incorrect.  Reinitialize it.
16475 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16476 		 * tcp_rtt_update so that we won't accidentally cache a
16477 		 * bad value.  But only do this if this is not a zero
16478 		 * window probe.
16479 		 */
16480 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16481 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16482 			    (tcp->tcp_rtt_sa >> 5);
16483 			tcp->tcp_rtt_sa = 0;
16484 			tcp_ip_notify(tcp);
16485 			tcp->tcp_rtt_update = 0;
16486 		}
16487 	}
16488 	tcp->tcp_timer_backoff++;
16489 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16490 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16491 	    tcps->tcps_rexmit_interval_min) {
16492 		/*
16493 		 * This means the original RTO is tcp_rexmit_interval_min.
16494 		 * So we will use tcp_rexmit_interval_min as the RTO value
16495 		 * and do the backoff.
16496 		 */
16497 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
16498 	} else {
16499 		ms <<= tcp->tcp_timer_backoff;
16500 	}
16501 	if (ms > tcps->tcps_rexmit_interval_max) {
16502 		ms = tcps->tcps_rexmit_interval_max;
16503 		/*
16504 		 * ms is at max, decrement tcp_timer_backoff to avoid
16505 		 * overflow.
16506 		 */
16507 		tcp->tcp_timer_backoff--;
16508 	}
16509 	tcp->tcp_ms_we_have_waited += ms;
16510 	if (tcp->tcp_zero_win_probe == 0) {
16511 		tcp->tcp_rto = ms;
16512 	}
16513 	TCP_TIMER_RESTART(tcp, ms);
16514 	/*
16515 	 * This is after a timeout and tcp_rto is backed off.  Set
16516 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16517 	 * restart the timer with a correct value.
16518 	 */
16519 	tcp->tcp_set_timer = 1;
16520 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16521 	if (mss > tcp->tcp_mss)
16522 		mss = tcp->tcp_mss;
16523 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16524 		mss = tcp->tcp_swnd;
16525 
16526 	if ((mp = tcp->tcp_xmit_head) != NULL)
16527 		mp->b_prev = (mblk_t *)lbolt;
16528 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16529 	    B_TRUE);
16530 
16531 	/*
16532 	 * When slow start after retransmission begins, start with
16533 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16534 	 * start phase.  tcp_snd_burst controls how many segments
16535 	 * can be sent because of an ack.
16536 	 */
16537 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16538 	tcp->tcp_snd_burst = TCP_CWND_SS;
16539 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16540 	    (tcp->tcp_unsent == 0)) {
16541 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16542 	} else {
16543 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16544 	}
16545 	tcp->tcp_rexmit = B_TRUE;
16546 	tcp->tcp_dupack_cnt = 0;
16547 
16548 	/*
16549 	 * Remove all rexmit SACK blk to start from fresh.
16550 	 */
16551 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16552 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16553 		tcp->tcp_num_notsack_blk = 0;
16554 		tcp->tcp_cnt_notsack_list = 0;
16555 	}
16556 	if (mp == NULL) {
16557 		return;
16558 	}
16559 	/*
16560 	 * Attach credentials to retransmitted initial SYNs.
16561 	 * In theory we should use the credentials from the connect()
16562 	 * call to ensure that getpeerucred() on the peer will be correct.
16563 	 * But we assume that SYN's are not dropped for loopback connections.
16564 	 */
16565 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16566 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp), tcp->tcp_cpid);
16567 	}
16568 
16569 	tcp->tcp_csuna = tcp->tcp_snxt;
16570 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
16571 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
16572 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16573 
16574 }
16575 
16576 static int
16577 tcp_do_unbind(conn_t *connp)
16578 {
16579 	tcp_t *tcp = connp->conn_tcp;
16580 	int error = 0;
16581 
16582 	switch (tcp->tcp_state) {
16583 	case TCPS_BOUND:
16584 	case TCPS_LISTEN:
16585 		break;
16586 	default:
16587 		return (-TOUTSTATE);
16588 	}
16589 
16590 	/*
16591 	 * Need to clean up all the eagers since after the unbind, segments
16592 	 * will no longer be delivered to this listener stream.
16593 	 */
16594 	mutex_enter(&tcp->tcp_eager_lock);
16595 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16596 		tcp_eager_cleanup(tcp, 0);
16597 	}
16598 	mutex_exit(&tcp->tcp_eager_lock);
16599 
16600 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16601 		tcp->tcp_ipha->ipha_src = 0;
16602 	} else {
16603 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16604 	}
16605 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16606 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16607 	tcp_bind_hash_remove(tcp);
16608 	tcp->tcp_state = TCPS_IDLE;
16609 	tcp->tcp_mdt = B_FALSE;
16610 
16611 	connp = tcp->tcp_connp;
16612 	connp->conn_mdt_ok = B_FALSE;
16613 	ipcl_hash_remove(connp);
16614 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16615 
16616 	return (error);
16617 }
16618 
16619 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16620 static void
16621 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
16622 {
16623 	int error = tcp_do_unbind(tcp->tcp_connp);
16624 
16625 	if (error > 0) {
16626 		tcp_err_ack(tcp, mp, TSYSERR, error);
16627 	} else if (error < 0) {
16628 		tcp_err_ack(tcp, mp, -error, 0);
16629 	} else {
16630 		/* Send M_FLUSH according to TPI */
16631 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16632 
16633 		mp = mi_tpi_ok_ack_alloc(mp);
16634 		putnext(tcp->tcp_rq, mp);
16635 	}
16636 }
16637 
16638 /*
16639  * Don't let port fall into the privileged range.
16640  * Since the extra privileged ports can be arbitrary we also
16641  * ensure that we exclude those from consideration.
16642  * tcp_g_epriv_ports is not sorted thus we loop over it until
16643  * there are no changes.
16644  *
16645  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16646  * but instead the code relies on:
16647  * - the fact that the address of the array and its size never changes
16648  * - the atomic assignment of the elements of the array
16649  *
16650  * Returns 0 if there are no more ports available.
16651  *
16652  * TS note: skip multilevel ports.
16653  */
16654 static in_port_t
16655 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16656 {
16657 	int i;
16658 	boolean_t restart = B_FALSE;
16659 	tcp_stack_t *tcps = tcp->tcp_tcps;
16660 
16661 	if (random && tcp_random_anon_port != 0) {
16662 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16663 		    sizeof (in_port_t));
16664 		/*
16665 		 * Unless changed by a sys admin, the smallest anon port
16666 		 * is 32768 and the largest anon port is 65535.  It is
16667 		 * very likely (50%) for the random port to be smaller
16668 		 * than the smallest anon port.  When that happens,
16669 		 * add port % (anon port range) to the smallest anon
16670 		 * port to get the random port.  It should fall into the
16671 		 * valid anon port range.
16672 		 */
16673 		if (port < tcps->tcps_smallest_anon_port) {
16674 			port = tcps->tcps_smallest_anon_port +
16675 			    port % (tcps->tcps_largest_anon_port -
16676 			    tcps->tcps_smallest_anon_port);
16677 		}
16678 	}
16679 
16680 retry:
16681 	if (port < tcps->tcps_smallest_anon_port)
16682 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16683 
16684 	if (port > tcps->tcps_largest_anon_port) {
16685 		if (restart)
16686 			return (0);
16687 		restart = B_TRUE;
16688 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16689 	}
16690 
16691 	if (port < tcps->tcps_smallest_nonpriv_port)
16692 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
16693 
16694 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
16695 		if (port == tcps->tcps_g_epriv_ports[i]) {
16696 			port++;
16697 			/*
16698 			 * Make sure whether the port is in the
16699 			 * valid range.
16700 			 */
16701 			goto retry;
16702 		}
16703 	}
16704 	if (is_system_labeled() &&
16705 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
16706 	    IPPROTO_TCP, B_TRUE)) != 0) {
16707 		port = i;
16708 		goto retry;
16709 	}
16710 	return (port);
16711 }
16712 
16713 /*
16714  * Return the next anonymous port in the privileged port range for
16715  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16716  * downwards.  This is the same behavior as documented in the userland
16717  * library call rresvport(3N).
16718  *
16719  * TS note: skip multilevel ports.
16720  */
16721 static in_port_t
16722 tcp_get_next_priv_port(const tcp_t *tcp)
16723 {
16724 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16725 	in_port_t nextport;
16726 	boolean_t restart = B_FALSE;
16727 	tcp_stack_t *tcps = tcp->tcp_tcps;
16728 retry:
16729 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
16730 	    next_priv_port >= IPPORT_RESERVED) {
16731 		next_priv_port = IPPORT_RESERVED - 1;
16732 		if (restart)
16733 			return (0);
16734 		restart = B_TRUE;
16735 	}
16736 	if (is_system_labeled() &&
16737 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
16738 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
16739 		next_priv_port = nextport;
16740 		goto retry;
16741 	}
16742 	return (next_priv_port--);
16743 }
16744 
16745 /* The write side r/w procedure. */
16746 
16747 #if CCS_STATS
16748 struct {
16749 	struct {
16750 		int64_t count, bytes;
16751 	} tot, hit;
16752 } wrw_stats;
16753 #endif
16754 
16755 /*
16756  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16757  * messages.
16758  */
16759 /* ARGSUSED */
16760 static void
16761 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16762 {
16763 	conn_t	*connp = (conn_t *)arg;
16764 	tcp_t	*tcp = connp->conn_tcp;
16765 	queue_t	*q = tcp->tcp_wq;
16766 
16767 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16768 	/*
16769 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16770 	 * Once the close starts, streamhead and sockfs will not let any data
16771 	 * packets come down (close ensures that there are no threads using the
16772 	 * queue and no new threads will come down) but since qprocsoff()
16773 	 * hasn't happened yet, a M_FLUSH or some non data message might
16774 	 * get reflected back (in response to our own FLUSHRW) and get
16775 	 * processed after tcp_close() is done. The conn would still be valid
16776 	 * because a ref would have added but we need to check the state
16777 	 * before actually processing the packet.
16778 	 */
16779 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16780 		freemsg(mp);
16781 		return;
16782 	}
16783 
16784 	switch (DB_TYPE(mp)) {
16785 	case M_IOCDATA:
16786 		tcp_wput_iocdata(tcp, mp);
16787 		break;
16788 	case M_FLUSH:
16789 		tcp_wput_flush(tcp, mp);
16790 		break;
16791 	default:
16792 		CALL_IP_WPUT(connp, q, mp);
16793 		break;
16794 	}
16795 }
16796 
16797 /*
16798  * The TCP fast path write put procedure.
16799  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16800  */
16801 /* ARGSUSED */
16802 void
16803 tcp_output(void *arg, mblk_t *mp, void *arg2)
16804 {
16805 	int		len;
16806 	int		hdrlen;
16807 	int		plen;
16808 	mblk_t		*mp1;
16809 	uchar_t		*rptr;
16810 	uint32_t	snxt;
16811 	tcph_t		*tcph;
16812 	struct datab	*db;
16813 	uint32_t	suna;
16814 	uint32_t	mss;
16815 	ipaddr_t	*dst;
16816 	ipaddr_t	*src;
16817 	uint32_t	sum;
16818 	int		usable;
16819 	conn_t		*connp = (conn_t *)arg;
16820 	tcp_t		*tcp = connp->conn_tcp;
16821 	uint32_t	msize;
16822 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16823 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
16824 
16825 	/*
16826 	 * Try and ASSERT the minimum possible references on the
16827 	 * conn early enough. Since we are executing on write side,
16828 	 * the connection is obviously not detached and that means
16829 	 * there is a ref each for TCP and IP. Since we are behind
16830 	 * the squeue, the minimum references needed are 3. If the
16831 	 * conn is in classifier hash list, there should be an
16832 	 * extra ref for that (we check both the possibilities).
16833 	 */
16834 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16835 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16836 
16837 	ASSERT(DB_TYPE(mp) == M_DATA);
16838 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
16839 
16840 	mutex_enter(&tcp->tcp_non_sq_lock);
16841 	tcp->tcp_squeue_bytes -= msize;
16842 	mutex_exit(&tcp->tcp_non_sq_lock);
16843 
16844 	/* Check to see if this connection wants to be re-fused. */
16845 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
16846 		if (tcp->tcp_ipversion == IPV4_VERSION) {
16847 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
16848 			    &tcp->tcp_saved_tcph);
16849 		} else {
16850 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
16851 			    &tcp->tcp_saved_tcph);
16852 		}
16853 	}
16854 	/* Bypass tcp protocol for fused tcp loopback */
16855 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
16856 		return;
16857 
16858 	mss = tcp->tcp_mss;
16859 	if (tcp->tcp_xmit_zc_clean)
16860 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16861 
16862 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16863 	len = (int)(mp->b_wptr - mp->b_rptr);
16864 
16865 	/*
16866 	 * Criteria for fast path:
16867 	 *
16868 	 *   1. no unsent data
16869 	 *   2. single mblk in request
16870 	 *   3. connection established
16871 	 *   4. data in mblk
16872 	 *   5. len <= mss
16873 	 *   6. no tcp_valid bits
16874 	 */
16875 	if ((tcp->tcp_unsent != 0) ||
16876 	    (tcp->tcp_cork) ||
16877 	    (mp->b_cont != NULL) ||
16878 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16879 	    (len == 0) ||
16880 	    (len > mss) ||
16881 	    (tcp->tcp_valid_bits != 0)) {
16882 		tcp_wput_data(tcp, mp, B_FALSE);
16883 		return;
16884 	}
16885 
16886 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16887 	ASSERT(tcp->tcp_fin_sent == 0);
16888 
16889 	/* queue new packet onto retransmission queue */
16890 	if (tcp->tcp_xmit_head == NULL) {
16891 		tcp->tcp_xmit_head = mp;
16892 	} else {
16893 		tcp->tcp_xmit_last->b_cont = mp;
16894 	}
16895 	tcp->tcp_xmit_last = mp;
16896 	tcp->tcp_xmit_tail = mp;
16897 
16898 	/* find out how much we can send */
16899 	/* BEGIN CSTYLED */
16900 	/*
16901 	 *    un-acked	   usable
16902 	 *  |--------------|-----------------|
16903 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
16904 	 */
16905 	/* END CSTYLED */
16906 
16907 	/* start sending from tcp_snxt */
16908 	snxt = tcp->tcp_snxt;
16909 
16910 	/*
16911 	 * Check to see if this connection has been idled for some
16912 	 * time and no ACK is expected.  If it is, we need to slow
16913 	 * start again to get back the connection's "self-clock" as
16914 	 * described in VJ's paper.
16915 	 *
16916 	 * Refer to the comment in tcp_mss_set() for the calculation
16917 	 * of tcp_cwnd after idle.
16918 	 */
16919 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16920 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16921 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
16922 	}
16923 
16924 	usable = tcp->tcp_swnd;		/* tcp window size */
16925 	if (usable > tcp->tcp_cwnd)
16926 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16927 	usable -= snxt;		/* subtract stuff already sent */
16928 	suna = tcp->tcp_suna;
16929 	usable += suna;
16930 	/* usable can be < 0 if the congestion window is smaller */
16931 	if (len > usable) {
16932 		/* Can't send complete M_DATA in one shot */
16933 		goto slow;
16934 	}
16935 
16936 	mutex_enter(&tcp->tcp_non_sq_lock);
16937 	if (tcp->tcp_flow_stopped &&
16938 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16939 		tcp_clrqfull(tcp);
16940 	}
16941 	mutex_exit(&tcp->tcp_non_sq_lock);
16942 
16943 	/*
16944 	 * determine if anything to send (Nagle).
16945 	 *
16946 	 *   1. len < tcp_mss (i.e. small)
16947 	 *   2. unacknowledged data present
16948 	 *   3. len < nagle limit
16949 	 *   4. last packet sent < nagle limit (previous packet sent)
16950 	 */
16951 	if ((len < mss) && (snxt != suna) &&
16952 	    (len < (int)tcp->tcp_naglim) &&
16953 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
16954 		/*
16955 		 * This was the first unsent packet and normally
16956 		 * mss < xmit_hiwater so there is no need to worry
16957 		 * about flow control. The next packet will go
16958 		 * through the flow control check in tcp_wput_data().
16959 		 */
16960 		/* leftover work from above */
16961 		tcp->tcp_unsent = len;
16962 		tcp->tcp_xmit_tail_unsent = len;
16963 
16964 		return;
16965 	}
16966 
16967 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
16968 
16969 	if (snxt == suna) {
16970 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16971 	}
16972 
16973 	/* we have always sent something */
16974 	tcp->tcp_rack_cnt = 0;
16975 
16976 	tcp->tcp_snxt = snxt + len;
16977 	tcp->tcp_rack = tcp->tcp_rnxt;
16978 
16979 	if ((mp1 = dupb(mp)) == 0)
16980 		goto no_memory;
16981 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
16982 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
16983 
16984 	/* adjust tcp header information */
16985 	tcph = tcp->tcp_tcph;
16986 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
16987 
16988 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
16989 	sum = (sum >> 16) + (sum & 0xFFFF);
16990 	U16_TO_ABE16(sum, tcph->th_sum);
16991 
16992 	U32_TO_ABE32(snxt, tcph->th_seq);
16993 
16994 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16995 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16996 	BUMP_LOCAL(tcp->tcp_obsegs);
16997 
16998 	/* Update the latest receive window size in TCP header. */
16999 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17000 	    tcph->th_win);
17001 
17002 	tcp->tcp_last_sent_len = (ushort_t)len;
17003 
17004 	plen = len + tcp->tcp_hdr_len;
17005 
17006 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17007 		tcp->tcp_ipha->ipha_length = htons(plen);
17008 	} else {
17009 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17010 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17011 	}
17012 
17013 	/* see if we need to allocate a mblk for the headers */
17014 	hdrlen = tcp->tcp_hdr_len;
17015 	rptr = mp1->b_rptr - hdrlen;
17016 	db = mp1->b_datap;
17017 	if ((db->db_ref != 2) || rptr < db->db_base ||
17018 	    (!OK_32PTR(rptr))) {
17019 		/* NOTE: we assume allocb returns an OK_32PTR */
17020 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17021 		    tcps->tcps_wroff_xtra, BPRI_MED);
17022 		if (!mp) {
17023 			freemsg(mp1);
17024 			goto no_memory;
17025 		}
17026 		mp->b_cont = mp1;
17027 		mp1 = mp;
17028 		/* Leave room for Link Level header */
17029 		/* hdrlen = tcp->tcp_hdr_len; */
17030 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17031 		mp1->b_wptr = &rptr[hdrlen];
17032 	}
17033 	mp1->b_rptr = rptr;
17034 
17035 	/* Fill in the timestamp option. */
17036 	if (tcp->tcp_snd_ts_ok) {
17037 		U32_TO_BE32((uint32_t)lbolt,
17038 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17039 		U32_TO_BE32(tcp->tcp_ts_recent,
17040 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17041 	} else {
17042 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17043 	}
17044 
17045 	/* copy header into outgoing packet */
17046 	dst = (ipaddr_t *)rptr;
17047 	src = (ipaddr_t *)tcp->tcp_iphc;
17048 	dst[0] = src[0];
17049 	dst[1] = src[1];
17050 	dst[2] = src[2];
17051 	dst[3] = src[3];
17052 	dst[4] = src[4];
17053 	dst[5] = src[5];
17054 	dst[6] = src[6];
17055 	dst[7] = src[7];
17056 	dst[8] = src[8];
17057 	dst[9] = src[9];
17058 	if (hdrlen -= 40) {
17059 		hdrlen >>= 2;
17060 		dst += 10;
17061 		src += 10;
17062 		do {
17063 			*dst++ = *src++;
17064 		} while (--hdrlen);
17065 	}
17066 
17067 	/*
17068 	 * Set the ECN info in the TCP header.  Note that this
17069 	 * is not the template header.
17070 	 */
17071 	if (tcp->tcp_ecn_ok) {
17072 		SET_ECT(tcp, rptr);
17073 
17074 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17075 		if (tcp->tcp_ecn_echo_on)
17076 			tcph->th_flags[0] |= TH_ECE;
17077 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17078 			tcph->th_flags[0] |= TH_CWR;
17079 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17080 		}
17081 	}
17082 
17083 	if (tcp->tcp_ip_forward_progress) {
17084 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17085 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17086 		tcp->tcp_ip_forward_progress = B_FALSE;
17087 	}
17088 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17089 	return;
17090 
17091 	/*
17092 	 * If we ran out of memory, we pretend to have sent the packet
17093 	 * and that it was lost on the wire.
17094 	 */
17095 no_memory:
17096 	return;
17097 
17098 slow:
17099 	/* leftover work from above */
17100 	tcp->tcp_unsent = len;
17101 	tcp->tcp_xmit_tail_unsent = len;
17102 	tcp_wput_data(tcp, NULL, B_FALSE);
17103 }
17104 
17105 /* ARGSUSED */
17106 void
17107 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17108 {
17109 	conn_t			*connp = (conn_t *)arg;
17110 	tcp_t			*tcp = connp->conn_tcp;
17111 	queue_t			*q = tcp->tcp_rq;
17112 	struct tcp_options	*tcpopt;
17113 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17114 
17115 	/* socket options */
17116 	uint_t 			sopp_flags;
17117 	ssize_t			sopp_rxhiwat;
17118 	ssize_t			sopp_maxblk;
17119 	ushort_t		sopp_wroff;
17120 	ushort_t		sopp_tail;
17121 	ushort_t		sopp_copyopt;
17122 
17123 	tcpopt = (struct tcp_options *)mp->b_rptr;
17124 
17125 	/*
17126 	 * Drop the eager's ref on the listener, that was placed when
17127 	 * this eager began life in tcp_conn_request.
17128 	 */
17129 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17130 	if (IPCL_IS_NONSTR(connp)) {
17131 		/* Safe to free conn_ind message */
17132 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17133 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17134 	}
17135 
17136 	tcp->tcp_detached = B_FALSE;
17137 
17138 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17139 		/*
17140 		 * Someone blewoff the eager before we could finish
17141 		 * the accept.
17142 		 *
17143 		 * The only reason eager exists it because we put in
17144 		 * a ref on it when conn ind went up. We need to send
17145 		 * a disconnect indication up while the last reference
17146 		 * on the eager will be dropped by the squeue when we
17147 		 * return.
17148 		 */
17149 		ASSERT(tcp->tcp_listener == NULL);
17150 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17151 			if (IPCL_IS_NONSTR(connp)) {
17152 				ASSERT(tcp->tcp_issocket);
17153 				(*connp->conn_upcalls->su_disconnected)(
17154 				    connp->conn_upper_handle, tcp->tcp_connid,
17155 				    ECONNREFUSED);
17156 				freemsg(mp);
17157 			} else {
17158 				struct	T_discon_ind	*tdi;
17159 
17160 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17161 				/*
17162 				 * Let us reuse the incoming mblk to avoid
17163 				 * memory allocation failure problems. We know
17164 				 * that the size of the incoming mblk i.e.
17165 				 * stroptions is greater than sizeof
17166 				 * T_discon_ind. So the reallocb below can't
17167 				 * fail.
17168 				 */
17169 				freemsg(mp->b_cont);
17170 				mp->b_cont = NULL;
17171 				ASSERT(DB_REF(mp) == 1);
17172 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17173 				    B_FALSE);
17174 				ASSERT(mp != NULL);
17175 				DB_TYPE(mp) = M_PROTO;
17176 				((union T_primitives *)mp->b_rptr)->type =
17177 				    T_DISCON_IND;
17178 				tdi = (struct T_discon_ind *)mp->b_rptr;
17179 				if (tcp->tcp_issocket) {
17180 					tdi->DISCON_reason = ECONNREFUSED;
17181 					tdi->SEQ_number = 0;
17182 				} else {
17183 					tdi->DISCON_reason = ENOPROTOOPT;
17184 					tdi->SEQ_number =
17185 					    tcp->tcp_conn_req_seqnum;
17186 				}
17187 				mp->b_wptr = mp->b_rptr +
17188 				    sizeof (struct T_discon_ind);
17189 				putnext(q, mp);
17190 				return;
17191 			}
17192 		}
17193 		if (tcp->tcp_hard_binding) {
17194 			tcp->tcp_hard_binding = B_FALSE;
17195 			tcp->tcp_hard_bound = B_TRUE;
17196 		}
17197 		return;
17198 	}
17199 
17200 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17201 		int boundif = tcpopt->to_boundif;
17202 		uint_t len = sizeof (int);
17203 
17204 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17205 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17206 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17207 	}
17208 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17209 		uint_t on = 1;
17210 		uint_t len = sizeof (uint_t);
17211 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17212 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17213 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17214 	}
17215 
17216 	/*
17217 	 * For a loopback connection with tcp_direct_sockfs on, note that
17218 	 * we don't have to protect tcp_rcv_list yet because synchronous
17219 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17220 	 * possibly race with us.
17221 	 */
17222 
17223 	/*
17224 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17225 	 * properly.  This is the first time we know of the acceptor'
17226 	 * queue.  So we do it here.
17227 	 *
17228 	 * XXX
17229 	 */
17230 	if (tcp->tcp_rcv_list == NULL) {
17231 		/*
17232 		 * Recv queue is empty, tcp_rwnd should not have changed.
17233 		 * That means it should be equal to the listener's tcp_rwnd.
17234 		 */
17235 		if (!IPCL_IS_NONSTR(connp))
17236 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17237 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17238 	} else {
17239 #ifdef DEBUG
17240 		mblk_t *tmp;
17241 		mblk_t	*mp1;
17242 		uint_t	cnt = 0;
17243 
17244 		mp1 = tcp->tcp_rcv_list;
17245 		while ((tmp = mp1) != NULL) {
17246 			mp1 = tmp->b_next;
17247 			cnt += msgdsize(tmp);
17248 		}
17249 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17250 #endif
17251 		/* There is some data, add them back to get the max. */
17252 		if (!IPCL_IS_NONSTR(connp))
17253 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17254 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17255 	}
17256 	/*
17257 	 * This is the first time we run on the correct
17258 	 * queue after tcp_accept. So fix all the q parameters
17259 	 * here.
17260 	 */
17261 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17262 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17263 
17264 	/*
17265 	 * Record the stream head's high water mark for this endpoint;
17266 	 * this is used for flow-control purposes.
17267 	 */
17268 	sopp_rxhiwat = tcp->tcp_fused ?
17269 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17270 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
17271 
17272 	/*
17273 	 * Determine what write offset value to use depending on SACK and
17274 	 * whether the endpoint is fused or not.
17275 	 */
17276 	if (tcp->tcp_fused) {
17277 		ASSERT(tcp->tcp_loopback);
17278 		ASSERT(tcp->tcp_loopback_peer != NULL);
17279 		/*
17280 		 * For fused tcp loopback, set the stream head's write
17281 		 * offset value to zero since we won't be needing any room
17282 		 * for TCP/IP headers.  This would also improve performance
17283 		 * since it would reduce the amount of work done by kmem.
17284 		 * Non-fused tcp loopback case is handled separately below.
17285 		 */
17286 		sopp_wroff = 0;
17287 		/*
17288 		 * Update the peer's transmit parameters according to
17289 		 * our recently calculated high water mark value.
17290 		 */
17291 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17292 	} else if (tcp->tcp_snd_sack_ok) {
17293 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17294 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17295 	} else {
17296 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17297 		    tcps->tcps_wroff_xtra);
17298 	}
17299 
17300 	/*
17301 	 * If this is endpoint is handling SSL, then reserve extra
17302 	 * offset and space at the end.
17303 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17304 	 * overriding the previous setting. The extra cost of signing and
17305 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17306 	 * instead of a single contiguous one by the stream head
17307 	 * largely outweighs the statistical reduction of ACKs, when
17308 	 * applicable. The peer will also save on decryption and verification
17309 	 * costs.
17310 	 */
17311 	if (tcp->tcp_kssl_ctx != NULL) {
17312 		sopp_wroff += SSL3_WROFFSET;
17313 
17314 		sopp_flags |= SOCKOPT_TAIL;
17315 		sopp_tail = SSL3_MAX_TAIL_LEN;
17316 
17317 		sopp_flags |= SOCKOPT_ZCOPY;
17318 		sopp_copyopt = ZCVMUNSAFE;
17319 
17320 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
17321 	}
17322 
17323 	/* Send the options up */
17324 	if (IPCL_IS_NONSTR(connp)) {
17325 		struct sock_proto_props sopp;
17326 
17327 		sopp.sopp_flags = sopp_flags;
17328 		sopp.sopp_wroff = sopp_wroff;
17329 		sopp.sopp_maxblk = sopp_maxblk;
17330 		sopp.sopp_rxhiwat = sopp_rxhiwat;
17331 		if (sopp_flags & SOCKOPT_TAIL) {
17332 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17333 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
17334 			sopp.sopp_tail = sopp_tail;
17335 			sopp.sopp_zcopyflag = sopp_copyopt;
17336 		}
17337 		(*connp->conn_upcalls->su_set_proto_props)
17338 		    (connp->conn_upper_handle, &sopp);
17339 	} else {
17340 		struct stroptions *stropt;
17341 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17342 		if (stropt_mp == NULL) {
17343 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
17344 			return;
17345 		}
17346 		DB_TYPE(stropt_mp) = M_SETOPTS;
17347 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17348 		stropt_mp->b_wptr += sizeof (struct stroptions);
17349 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
17350 		stropt->so_hiwat = sopp_rxhiwat;
17351 		stropt->so_wroff = sopp_wroff;
17352 		stropt->so_maxblk = sopp_maxblk;
17353 
17354 		if (sopp_flags & SOCKOPT_TAIL) {
17355 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17356 
17357 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
17358 			stropt->so_tail = sopp_tail;
17359 			stropt->so_copyopt = sopp_copyopt;
17360 		}
17361 
17362 		/* Send the options up */
17363 		putnext(q, stropt_mp);
17364 	}
17365 
17366 	freemsg(mp);
17367 	/*
17368 	 * Pass up any data and/or a fin that has been received.
17369 	 *
17370 	 * Adjust receive window in case it had decreased
17371 	 * (because there is data <=> tcp_rcv_list != NULL)
17372 	 * while the connection was detached. Note that
17373 	 * in case the eager was flow-controlled, w/o this
17374 	 * code, the rwnd may never open up again!
17375 	 */
17376 	if (tcp->tcp_rcv_list != NULL) {
17377 		if (IPCL_IS_NONSTR(connp)) {
17378 			mblk_t *mp;
17379 			int space_left;
17380 			int error;
17381 			boolean_t push = B_TRUE;
17382 
17383 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
17384 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
17385 			    &push) >= 0) {
17386 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17387 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17388 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17389 					tcp_xmit_ctl(NULL,
17390 					    tcp, (tcp->tcp_swnd == 0) ?
17391 					    tcp->tcp_suna : tcp->tcp_snxt,
17392 					    tcp->tcp_rnxt, TH_ACK);
17393 				}
17394 			}
17395 			while ((mp = tcp->tcp_rcv_list) != NULL) {
17396 				push = B_TRUE;
17397 				tcp->tcp_rcv_list = mp->b_next;
17398 				mp->b_next = NULL;
17399 				space_left = (*connp->conn_upcalls->su_recv)
17400 				    (connp->conn_upper_handle, mp, msgdsize(mp),
17401 				    0, &error, &push);
17402 				if (space_left < 0) {
17403 					/*
17404 					 * We should never be in middle of a
17405 					 * fallback, the squeue guarantees that.
17406 					 */
17407 					ASSERT(error != EOPNOTSUPP);
17408 				}
17409 			}
17410 			tcp->tcp_rcv_last_head = NULL;
17411 			tcp->tcp_rcv_last_tail = NULL;
17412 			tcp->tcp_rcv_cnt = 0;
17413 		} else {
17414 			/* We drain directly in case of fused tcp loopback */
17415 
17416 			if (!tcp->tcp_fused && canputnext(q)) {
17417 				tcp->tcp_rwnd = q->q_hiwat;
17418 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17419 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17420 					tcp_xmit_ctl(NULL,
17421 					    tcp, (tcp->tcp_swnd == 0) ?
17422 					    tcp->tcp_suna : tcp->tcp_snxt,
17423 					    tcp->tcp_rnxt, TH_ACK);
17424 				}
17425 			}
17426 
17427 			(void) tcp_rcv_drain(tcp);
17428 		}
17429 
17430 		/*
17431 		 * For fused tcp loopback, back-enable peer endpoint
17432 		 * if it's currently flow-controlled.
17433 		 */
17434 		if (tcp->tcp_fused) {
17435 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17436 
17437 			ASSERT(peer_tcp != NULL);
17438 			ASSERT(peer_tcp->tcp_fused);
17439 			/*
17440 			 * In order to change the peer's tcp_flow_stopped,
17441 			 * we need to take locks for both end points. The
17442 			 * highest address is taken first.
17443 			 */
17444 			if (peer_tcp > tcp) {
17445 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
17446 				mutex_enter(&tcp->tcp_non_sq_lock);
17447 			} else {
17448 				mutex_enter(&tcp->tcp_non_sq_lock);
17449 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
17450 			}
17451 			if (peer_tcp->tcp_flow_stopped) {
17452 				tcp_clrqfull(peer_tcp);
17453 				TCP_STAT(tcps, tcp_fusion_backenabled);
17454 			}
17455 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17456 			mutex_exit(&tcp->tcp_non_sq_lock);
17457 		}
17458 	}
17459 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17460 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17461 		tcp->tcp_ordrel_done = B_TRUE;
17462 		if (IPCL_IS_NONSTR(connp)) {
17463 			ASSERT(tcp->tcp_ordrel_mp == NULL);
17464 			(*connp->conn_upcalls->su_opctl)(
17465 			    connp->conn_upper_handle,
17466 			    SOCK_OPCTL_SHUT_RECV, 0);
17467 		} else {
17468 			mp = tcp->tcp_ordrel_mp;
17469 			tcp->tcp_ordrel_mp = NULL;
17470 			putnext(q, mp);
17471 		}
17472 	}
17473 	if (tcp->tcp_hard_binding) {
17474 		tcp->tcp_hard_binding = B_FALSE;
17475 		tcp->tcp_hard_bound = B_TRUE;
17476 	}
17477 
17478 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
17479 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
17480 	    tcp->tcp_loopback_peer != NULL &&
17481 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
17482 		tcp_fuse_syncstr_enable_pair(tcp);
17483 	}
17484 
17485 	if (tcp->tcp_ka_enabled) {
17486 		tcp->tcp_ka_last_intrvl = 0;
17487 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17488 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17489 	}
17490 
17491 	/*
17492 	 * At this point, eager is fully established and will
17493 	 * have the following references -
17494 	 *
17495 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17496 	 * 1 reference for the squeue which will be dropped by the squeue as
17497 	 *	soon as this function returns.
17498 	 * There will be 1 additonal reference for being in classifier
17499 	 *	hash list provided something bad hasn't happened.
17500 	 */
17501 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17502 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17503 }
17504 
17505 /*
17506  * The function called through squeue to get behind listener's perimeter to
17507  * send a deffered conn_ind.
17508  */
17509 /* ARGSUSED */
17510 void
17511 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17512 {
17513 	conn_t	*connp = (conn_t *)arg;
17514 	tcp_t *listener = connp->conn_tcp;
17515 	struct T_conn_ind *conn_ind;
17516 	tcp_t *tcp;
17517 
17518 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
17519 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17520 	    conn_ind->OPT_length);
17521 
17522 	if (listener->tcp_state == TCPS_CLOSED ||
17523 	    TCP_IS_DETACHED(listener)) {
17524 		/*
17525 		 * If listener has closed, it would have caused a
17526 		 * a cleanup/blowoff to happen for the eager.
17527 		 *
17528 		 * We need to drop the ref on eager that was put
17529 		 * tcp_rput_data() before trying to send the conn_ind
17530 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17531 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17532 		 * listener is closed so we drop the ref.
17533 		 */
17534 		CONN_DEC_REF(tcp->tcp_connp);
17535 		freemsg(mp);
17536 		return;
17537 	}
17538 
17539 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
17540 }
17541 
17542 /* ARGSUSED */
17543 static int
17544 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
17545 {
17546 	tcp_t *listener, *eager;
17547 	mblk_t *opt_mp;
17548 	struct tcp_options *tcpopt;
17549 
17550 	listener = lconnp->conn_tcp;
17551 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17552 	eager = econnp->conn_tcp;
17553 	ASSERT(eager->tcp_listener != NULL);
17554 
17555 	ASSERT(eager->tcp_rq != NULL);
17556 
17557 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
17558 	if (opt_mp == NULL) {
17559 		return (-TPROTO);
17560 	}
17561 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
17562 	eager->tcp_issocket = B_TRUE;
17563 
17564 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17565 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17566 	ASSERT(econnp->conn_netstack ==
17567 	    listener->tcp_connp->conn_netstack);
17568 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
17569 
17570 	/* Put the ref for IP */
17571 	CONN_INC_REF(econnp);
17572 
17573 	/*
17574 	 * We should have minimum of 3 references on the conn
17575 	 * at this point. One each for TCP and IP and one for
17576 	 * the T_conn_ind that was sent up when the 3-way handshake
17577 	 * completed. In the normal case we would also have another
17578 	 * reference (making a total of 4) for the conn being in the
17579 	 * classifier hash list. However the eager could have received
17580 	 * an RST subsequently and tcp_closei_local could have removed
17581 	 * the eager from the classifier hash list, hence we can't
17582 	 * assert that reference.
17583 	 */
17584 	ASSERT(econnp->conn_ref >= 3);
17585 
17586 	opt_mp->b_datap->db_type = M_SETOPTS;
17587 	opt_mp->b_wptr += sizeof (struct tcp_options);
17588 
17589 	/*
17590 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17591 	 * from listener to acceptor.
17592 	 */
17593 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
17594 	tcpopt->to_flags = 0;
17595 
17596 	if (listener->tcp_bound_if != 0) {
17597 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
17598 		tcpopt->to_boundif = listener->tcp_bound_if;
17599 	}
17600 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17601 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
17602 	}
17603 
17604 	mutex_enter(&listener->tcp_eager_lock);
17605 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17606 
17607 		tcp_t *tail;
17608 		tcp_t *tcp;
17609 		mblk_t *mp1;
17610 
17611 		tcp = listener->tcp_eager_prev_q0;
17612 		/*
17613 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
17614 		 * deferred T_conn_ind queue. We need to get to the head
17615 		 * of the queue in order to send up T_conn_ind the same
17616 		 * order as how the 3WHS is completed.
17617 		 */
17618 		while (tcp != listener) {
17619 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17620 			    !tcp->tcp_kssl_pending)
17621 				break;
17622 			else
17623 				tcp = tcp->tcp_eager_prev_q0;
17624 		}
17625 		/* None of the pending eagers can be sent up now */
17626 		if (tcp == listener)
17627 			goto no_more_eagers;
17628 
17629 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17630 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17631 		/* Move from q0 to q */
17632 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17633 		listener->tcp_conn_req_cnt_q0--;
17634 		listener->tcp_conn_req_cnt_q++;
17635 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17636 		    tcp->tcp_eager_prev_q0;
17637 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17638 		    tcp->tcp_eager_next_q0;
17639 		tcp->tcp_eager_prev_q0 = NULL;
17640 		tcp->tcp_eager_next_q0 = NULL;
17641 		tcp->tcp_conn_def_q0 = B_FALSE;
17642 
17643 		/* Make sure the tcp isn't in the list of droppables */
17644 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
17645 		    tcp->tcp_eager_prev_drop_q0 == NULL);
17646 
17647 		/*
17648 		 * Insert at end of the queue because sockfs sends
17649 		 * down T_CONN_RES in chronological order. Leaving
17650 		 * the older conn indications at front of the queue
17651 		 * helps reducing search time.
17652 		 */
17653 		tail = listener->tcp_eager_last_q;
17654 		if (tail != NULL) {
17655 			tail->tcp_eager_next_q = tcp;
17656 		} else {
17657 			listener->tcp_eager_next_q = tcp;
17658 		}
17659 		listener->tcp_eager_last_q = tcp;
17660 		tcp->tcp_eager_next_q = NULL;
17661 
17662 		/* Need to get inside the listener perimeter */
17663 		CONN_INC_REF(listener->tcp_connp);
17664 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
17665 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
17666 		    SQTAG_TCP_SEND_PENDING);
17667 	}
17668 no_more_eagers:
17669 	tcp_eager_unlink(eager);
17670 	mutex_exit(&listener->tcp_eager_lock);
17671 
17672 	/*
17673 	 * At this point, the eager is detached from the listener
17674 	 * but we still have an extra refs on eager (apart from the
17675 	 * usual tcp references). The ref was placed in tcp_rput_data
17676 	 * before sending the conn_ind in tcp_send_conn_ind.
17677 	 * The ref will be dropped in tcp_accept_finish().
17678 	 */
17679 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
17680 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
17681 	return (0);
17682 }
17683 
17684 int
17685 tcp_accept(sock_lower_handle_t lproto_handle,
17686     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
17687     cred_t *cr)
17688 {
17689 	conn_t *lconnp, *econnp;
17690 	tcp_t *listener, *eager;
17691 	tcp_stack_t	*tcps;
17692 
17693 	lconnp = (conn_t *)lproto_handle;
17694 	listener = lconnp->conn_tcp;
17695 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17696 	econnp = (conn_t *)eproto_handle;
17697 	eager = econnp->conn_tcp;
17698 	ASSERT(eager->tcp_listener != NULL);
17699 	tcps = eager->tcp_tcps;
17700 
17701 	/*
17702 	 * It is OK to manipulate these fields outside the eager's squeue
17703 	 * because they will not start being used until tcp_accept_finish
17704 	 * has been called.
17705 	 */
17706 	ASSERT(lconnp->conn_upper_handle != NULL);
17707 	ASSERT(econnp->conn_upper_handle == NULL);
17708 	econnp->conn_upper_handle = sock_handle;
17709 	econnp->conn_upcalls = lconnp->conn_upcalls;
17710 	ASSERT(IPCL_IS_NONSTR(econnp));
17711 	/*
17712 	 * Create helper stream if it is a non-TPI TCP connection.
17713 	 */
17714 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
17715 		ip1dbg(("tcp_accept: create of IP helper stream"
17716 		    " failed\n"));
17717 		return (EPROTO);
17718 	}
17719 	eager->tcp_rq = econnp->conn_rq;
17720 	eager->tcp_wq = econnp->conn_wq;
17721 
17722 	ASSERT(eager->tcp_rq != NULL);
17723 
17724 	return (tcp_accept_common(lconnp, econnp, cr));
17725 }
17726 
17727 
17728 /*
17729  * This is the STREAMS entry point for T_CONN_RES coming down on
17730  * Acceptor STREAM when  sockfs listener does accept processing.
17731  * Read the block comment on top of tcp_conn_request().
17732  */
17733 void
17734 tcp_tpi_accept(queue_t *q, mblk_t *mp)
17735 {
17736 	queue_t *rq = RD(q);
17737 	struct T_conn_res *conn_res;
17738 	tcp_t *eager;
17739 	tcp_t *listener;
17740 	struct T_ok_ack *ok;
17741 	t_scalar_t PRIM_type;
17742 	conn_t *econnp;
17743 	cred_t *cr;
17744 
17745 	ASSERT(DB_TYPE(mp) == M_PROTO);
17746 
17747 	/*
17748 	 * All Solaris components should pass a db_credp
17749 	 * for this TPI message, hence we ASSERT.
17750 	 * But in case there is some other M_PROTO that looks
17751 	 * like a TPI message sent by some other kernel
17752 	 * component, we check and return an error.
17753 	 */
17754 	cr = msg_getcred(mp, NULL);
17755 	ASSERT(cr != NULL);
17756 	if (cr == NULL) {
17757 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
17758 		if (mp != NULL)
17759 			putnext(rq, mp);
17760 		return;
17761 	}
17762 	conn_res = (struct T_conn_res *)mp->b_rptr;
17763 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17764 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17765 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17766 		if (mp != NULL)
17767 			putnext(rq, mp);
17768 		return;
17769 	}
17770 	switch (conn_res->PRIM_type) {
17771 	case O_T_CONN_RES:
17772 	case T_CONN_RES:
17773 		/*
17774 		 * We pass up an err ack if allocb fails. This will
17775 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17776 		 * tcp_eager_blowoff to be called. sockfs will then call
17777 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17778 		 * we need to do the allocb up here because we have to
17779 		 * make sure rq->q_qinfo->qi_qclose still points to the
17780 		 * correct function (tcp_tpi_close_accept) in case allocb
17781 		 * fails.
17782 		 */
17783 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17784 		    &eager, conn_res->OPT_length);
17785 		PRIM_type = conn_res->PRIM_type;
17786 		mp->b_datap->db_type = M_PCPROTO;
17787 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17788 		ok = (struct T_ok_ack *)mp->b_rptr;
17789 		ok->PRIM_type = T_OK_ACK;
17790 		ok->CORRECT_prim = PRIM_type;
17791 		econnp = eager->tcp_connp;
17792 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
17793 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
17794 		eager->tcp_rq = rq;
17795 		eager->tcp_wq = q;
17796 		rq->q_ptr = econnp;
17797 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
17798 		q->q_ptr = econnp;
17799 		q->q_qinfo = &tcp_winit;
17800 		listener = eager->tcp_listener;
17801 
17802 		if (tcp_accept_common(listener->tcp_connp,
17803 		    econnp, cr) < 0) {
17804 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17805 			if (mp != NULL)
17806 				putnext(rq, mp);
17807 			return;
17808 		}
17809 
17810 		/*
17811 		 * Send the new local address also up to sockfs. There
17812 		 * should already be enough space in the mp that came
17813 		 * down from soaccept().
17814 		 */
17815 		if (eager->tcp_family == AF_INET) {
17816 			sin_t *sin;
17817 
17818 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17819 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17820 			sin = (sin_t *)mp->b_wptr;
17821 			mp->b_wptr += sizeof (sin_t);
17822 			sin->sin_family = AF_INET;
17823 			sin->sin_port = eager->tcp_lport;
17824 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17825 		} else {
17826 			sin6_t *sin6;
17827 
17828 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17829 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17830 			sin6 = (sin6_t *)mp->b_wptr;
17831 			mp->b_wptr += sizeof (sin6_t);
17832 			sin6->sin6_family = AF_INET6;
17833 			sin6->sin6_port = eager->tcp_lport;
17834 			if (eager->tcp_ipversion == IPV4_VERSION) {
17835 				sin6->sin6_flowinfo = 0;
17836 				IN6_IPADDR_TO_V4MAPPED(
17837 				    eager->tcp_ipha->ipha_src,
17838 				    &sin6->sin6_addr);
17839 			} else {
17840 				ASSERT(eager->tcp_ip6h != NULL);
17841 				sin6->sin6_flowinfo =
17842 				    eager->tcp_ip6h->ip6_vcf &
17843 				    ~IPV6_VERS_AND_FLOW_MASK;
17844 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17845 			}
17846 			sin6->sin6_scope_id = 0;
17847 			sin6->__sin6_src_id = 0;
17848 		}
17849 
17850 		putnext(rq, mp);
17851 		return;
17852 	default:
17853 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17854 		if (mp != NULL)
17855 			putnext(rq, mp);
17856 		return;
17857 	}
17858 }
17859 
17860 static int
17861 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17862 {
17863 	sin_t *sin = (sin_t *)sa;
17864 	sin6_t *sin6 = (sin6_t *)sa;
17865 
17866 	switch (tcp->tcp_family) {
17867 	case AF_INET:
17868 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17869 
17870 		if (*salenp < sizeof (sin_t))
17871 			return (EINVAL);
17872 
17873 		*sin = sin_null;
17874 		sin->sin_family = AF_INET;
17875 		if (tcp->tcp_state >= TCPS_BOUND) {
17876 			sin->sin_port = tcp->tcp_lport;
17877 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
17878 		}
17879 		*salenp = sizeof (sin_t);
17880 		break;
17881 
17882 	case AF_INET6:
17883 		if (*salenp < sizeof (sin6_t))
17884 			return (EINVAL);
17885 
17886 		*sin6 = sin6_null;
17887 		sin6->sin6_family = AF_INET6;
17888 		if (tcp->tcp_state >= TCPS_BOUND) {
17889 			sin6->sin6_port = tcp->tcp_lport;
17890 			if (tcp->tcp_ipversion == IPV4_VERSION) {
17891 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
17892 				    &sin6->sin6_addr);
17893 			} else {
17894 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
17895 			}
17896 		}
17897 		*salenp = sizeof (sin6_t);
17898 		break;
17899 	}
17900 
17901 	return (0);
17902 }
17903 
17904 static int
17905 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17906 {
17907 	sin_t *sin = (sin_t *)sa;
17908 	sin6_t *sin6 = (sin6_t *)sa;
17909 
17910 	if (tcp->tcp_state < TCPS_SYN_RCVD)
17911 		return (ENOTCONN);
17912 
17913 	switch (tcp->tcp_family) {
17914 	case AF_INET:
17915 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17916 
17917 		if (*salenp < sizeof (sin_t))
17918 			return (EINVAL);
17919 
17920 		*sin = sin_null;
17921 		sin->sin_family = AF_INET;
17922 		sin->sin_port = tcp->tcp_fport;
17923 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
17924 		    sin->sin_addr.s_addr);
17925 		*salenp = sizeof (sin_t);
17926 		break;
17927 
17928 	case AF_INET6:
17929 		if (*salenp < sizeof (sin6_t))
17930 			return (EINVAL);
17931 
17932 		*sin6 = sin6_null;
17933 		sin6->sin6_family = AF_INET6;
17934 		sin6->sin6_port = tcp->tcp_fport;
17935 		sin6->sin6_addr = tcp->tcp_remote_v6;
17936 		if (tcp->tcp_ipversion == IPV6_VERSION) {
17937 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
17938 			    ~IPV6_VERS_AND_FLOW_MASK;
17939 		}
17940 		*salenp = sizeof (sin6_t);
17941 		break;
17942 	}
17943 
17944 	return (0);
17945 }
17946 
17947 /*
17948  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
17949  */
17950 static void
17951 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
17952 {
17953 	void	*data;
17954 	mblk_t	*datamp = mp->b_cont;
17955 	tcp_t	*tcp = Q_TO_TCP(q);
17956 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
17957 
17958 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
17959 		cmdp->cb_error = EPROTO;
17960 		qreply(q, mp);
17961 		return;
17962 	}
17963 
17964 	data = datamp->b_rptr;
17965 
17966 	switch (cmdp->cb_cmd) {
17967 	case TI_GETPEERNAME:
17968 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
17969 		break;
17970 	case TI_GETMYNAME:
17971 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
17972 		break;
17973 	default:
17974 		cmdp->cb_error = EINVAL;
17975 		break;
17976 	}
17977 
17978 	qreply(q, mp);
17979 }
17980 
17981 void
17982 tcp_wput(queue_t *q, mblk_t *mp)
17983 {
17984 	conn_t	*connp = Q_TO_CONN(q);
17985 	tcp_t	*tcp;
17986 	void (*output_proc)();
17987 	t_scalar_t type;
17988 	uchar_t *rptr;
17989 	struct iocblk	*iocp;
17990 	size_t size;
17991 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17992 
17993 	ASSERT(connp->conn_ref >= 2);
17994 
17995 	switch (DB_TYPE(mp)) {
17996 	case M_DATA:
17997 		tcp = connp->conn_tcp;
17998 		ASSERT(tcp != NULL);
17999 
18000 		size = msgdsize(mp);
18001 
18002 		mutex_enter(&tcp->tcp_non_sq_lock);
18003 		tcp->tcp_squeue_bytes += size;
18004 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18005 			tcp_setqfull(tcp);
18006 		}
18007 		mutex_exit(&tcp->tcp_non_sq_lock);
18008 
18009 		CONN_INC_REF(connp);
18010 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18011 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18012 		return;
18013 
18014 	case M_CMD:
18015 		tcp_wput_cmdblk(q, mp);
18016 		return;
18017 
18018 	case M_PROTO:
18019 	case M_PCPROTO:
18020 		/*
18021 		 * if it is a snmp message, don't get behind the squeue
18022 		 */
18023 		tcp = connp->conn_tcp;
18024 		rptr = mp->b_rptr;
18025 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18026 			type = ((union T_primitives *)rptr)->type;
18027 		} else {
18028 			if (tcp->tcp_debug) {
18029 				(void) strlog(TCP_MOD_ID, 0, 1,
18030 				    SL_ERROR|SL_TRACE,
18031 				    "tcp_wput_proto, dropping one...");
18032 			}
18033 			freemsg(mp);
18034 			return;
18035 		}
18036 		if (type == T_SVR4_OPTMGMT_REQ) {
18037 			/*
18038 			 * All Solaris components should pass a db_credp
18039 			 * for this TPI message, hence we ASSERT.
18040 			 * But in case there is some other M_PROTO that looks
18041 			 * like a TPI message sent by some other kernel
18042 			 * component, we check and return an error.
18043 			 */
18044 			cred_t	*cr = msg_getcred(mp, NULL);
18045 
18046 			ASSERT(cr != NULL);
18047 			if (cr == NULL) {
18048 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18049 				return;
18050 			}
18051 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18052 			    cr)) {
18053 				/*
18054 				 * This was a SNMP request
18055 				 */
18056 				return;
18057 			} else {
18058 				output_proc = tcp_wput_proto;
18059 			}
18060 		} else {
18061 			output_proc = tcp_wput_proto;
18062 		}
18063 		break;
18064 	case M_IOCTL:
18065 		/*
18066 		 * Most ioctls can be processed right away without going via
18067 		 * squeues - process them right here. Those that do require
18068 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18069 		 * are processed by tcp_wput_ioctl().
18070 		 */
18071 		iocp = (struct iocblk *)mp->b_rptr;
18072 		tcp = connp->conn_tcp;
18073 
18074 		switch (iocp->ioc_cmd) {
18075 		case TCP_IOC_ABORT_CONN:
18076 			tcp_ioctl_abort_conn(q, mp);
18077 			return;
18078 		case TI_GETPEERNAME:
18079 		case TI_GETMYNAME:
18080 			mi_copyin(q, mp, NULL,
18081 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18082 			return;
18083 		case ND_SET:
18084 			/* nd_getset does the necessary checks */
18085 		case ND_GET:
18086 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18087 				CALL_IP_WPUT(connp, q, mp);
18088 				return;
18089 			}
18090 			qreply(q, mp);
18091 			return;
18092 		case TCP_IOC_DEFAULT_Q:
18093 			/*
18094 			 * Wants to be the default wq. Check the credentials
18095 			 * first, the rest is executed via squeue.
18096 			 */
18097 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18098 				iocp->ioc_error = EPERM;
18099 				iocp->ioc_count = 0;
18100 				mp->b_datap->db_type = M_IOCACK;
18101 				qreply(q, mp);
18102 				return;
18103 			}
18104 			output_proc = tcp_wput_ioctl;
18105 			break;
18106 		default:
18107 			output_proc = tcp_wput_ioctl;
18108 			break;
18109 		}
18110 		break;
18111 	default:
18112 		output_proc = tcp_wput_nondata;
18113 		break;
18114 	}
18115 
18116 	CONN_INC_REF(connp);
18117 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18118 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18119 }
18120 
18121 /*
18122  * Initial STREAMS write side put() procedure for sockets. It tries to
18123  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18124  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18125  * are handled by tcp_wput() as usual.
18126  *
18127  * All further messages will also be handled by tcp_wput() because we cannot
18128  * be sure that the above short cut is safe later.
18129  */
18130 static void
18131 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18132 {
18133 	conn_t			*connp = Q_TO_CONN(wq);
18134 	tcp_t			*tcp = connp->conn_tcp;
18135 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18136 
18137 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18138 	wq->q_qinfo = &tcp_winit;
18139 
18140 	ASSERT(IPCL_IS_TCP(connp));
18141 	ASSERT(TCP_IS_SOCKET(tcp));
18142 
18143 	if (DB_TYPE(mp) == M_PCPROTO &&
18144 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18145 	    car->PRIM_type == T_CAPABILITY_REQ) {
18146 		tcp_capability_req(tcp, mp);
18147 		return;
18148 	}
18149 
18150 	tcp_wput(wq, mp);
18151 }
18152 
18153 /* ARGSUSED */
18154 static void
18155 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18156 {
18157 #ifdef DEBUG
18158 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18159 #endif
18160 	freemsg(mp);
18161 }
18162 
18163 static boolean_t
18164 tcp_zcopy_check(tcp_t *tcp)
18165 {
18166 	conn_t	*connp = tcp->tcp_connp;
18167 	ire_t	*ire;
18168 	boolean_t	zc_enabled = B_FALSE;
18169 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18170 
18171 	if (do_tcpzcopy == 2)
18172 		zc_enabled = B_TRUE;
18173 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18174 	    IPCL_IS_CONNECTED(connp) &&
18175 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18176 	    connp->conn_dontroute == 0 &&
18177 	    !connp->conn_nexthop_set &&
18178 	    connp->conn_outgoing_ill == NULL &&
18179 	    do_tcpzcopy == 1) {
18180 		/*
18181 		 * the checks above  closely resemble the fast path checks
18182 		 * in tcp_send_data().
18183 		 */
18184 		mutex_enter(&connp->conn_lock);
18185 		ire = connp->conn_ire_cache;
18186 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18187 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18188 			IRE_REFHOLD(ire);
18189 			if (ire->ire_stq != NULL) {
18190 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18191 
18192 				zc_enabled = ill && (ill->ill_capabilities &
18193 				    ILL_CAPAB_ZEROCOPY) &&
18194 				    (ill->ill_zerocopy_capab->
18195 				    ill_zerocopy_flags != 0);
18196 			}
18197 			IRE_REFRELE(ire);
18198 		}
18199 		mutex_exit(&connp->conn_lock);
18200 	}
18201 	tcp->tcp_snd_zcopy_on = zc_enabled;
18202 	if (!TCP_IS_DETACHED(tcp)) {
18203 		if (zc_enabled) {
18204 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18205 			    ZCVMSAFE);
18206 			TCP_STAT(tcps, tcp_zcopy_on);
18207 		} else {
18208 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18209 			    ZCVMUNSAFE);
18210 			TCP_STAT(tcps, tcp_zcopy_off);
18211 		}
18212 	}
18213 	return (zc_enabled);
18214 }
18215 
18216 static mblk_t *
18217 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18218 {
18219 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18220 
18221 	if (do_tcpzcopy == 2)
18222 		return (bp);
18223 	else if (tcp->tcp_snd_zcopy_on) {
18224 		tcp->tcp_snd_zcopy_on = B_FALSE;
18225 		if (!TCP_IS_DETACHED(tcp)) {
18226 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18227 			    ZCVMUNSAFE);
18228 			TCP_STAT(tcps, tcp_zcopy_disable);
18229 		}
18230 	}
18231 	return (tcp_zcopy_backoff(tcp, bp, 0));
18232 }
18233 
18234 /*
18235  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18236  * the original desballoca'ed segmapped mblk.
18237  */
18238 static mblk_t *
18239 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18240 {
18241 	mblk_t *head, *tail, *nbp;
18242 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18243 
18244 	if (IS_VMLOANED_MBLK(bp)) {
18245 		TCP_STAT(tcps, tcp_zcopy_backoff);
18246 		if ((head = copyb(bp)) == NULL) {
18247 			/* fail to backoff; leave it for the next backoff */
18248 			tcp->tcp_xmit_zc_clean = B_FALSE;
18249 			return (bp);
18250 		}
18251 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18252 			if (fix_xmitlist)
18253 				tcp_zcopy_notify(tcp);
18254 			else
18255 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18256 		}
18257 		nbp = bp->b_cont;
18258 		if (fix_xmitlist) {
18259 			head->b_prev = bp->b_prev;
18260 			head->b_next = bp->b_next;
18261 			if (tcp->tcp_xmit_tail == bp)
18262 				tcp->tcp_xmit_tail = head;
18263 		}
18264 		bp->b_next = NULL;
18265 		bp->b_prev = NULL;
18266 		freeb(bp);
18267 	} else {
18268 		head = bp;
18269 		nbp = bp->b_cont;
18270 	}
18271 	tail = head;
18272 	while (nbp) {
18273 		if (IS_VMLOANED_MBLK(nbp)) {
18274 			TCP_STAT(tcps, tcp_zcopy_backoff);
18275 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18276 				tcp->tcp_xmit_zc_clean = B_FALSE;
18277 				tail->b_cont = nbp;
18278 				return (head);
18279 			}
18280 			tail = tail->b_cont;
18281 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18282 				if (fix_xmitlist)
18283 					tcp_zcopy_notify(tcp);
18284 				else
18285 					tail->b_datap->db_struioflag |=
18286 					    STRUIO_ZCNOTIFY;
18287 			}
18288 			bp = nbp;
18289 			nbp = nbp->b_cont;
18290 			if (fix_xmitlist) {
18291 				tail->b_prev = bp->b_prev;
18292 				tail->b_next = bp->b_next;
18293 				if (tcp->tcp_xmit_tail == bp)
18294 					tcp->tcp_xmit_tail = tail;
18295 			}
18296 			bp->b_next = NULL;
18297 			bp->b_prev = NULL;
18298 			freeb(bp);
18299 		} else {
18300 			tail->b_cont = nbp;
18301 			tail = nbp;
18302 			nbp = nbp->b_cont;
18303 		}
18304 	}
18305 	if (fix_xmitlist) {
18306 		tcp->tcp_xmit_last = tail;
18307 		tcp->tcp_xmit_zc_clean = B_TRUE;
18308 	}
18309 	return (head);
18310 }
18311 
18312 static void
18313 tcp_zcopy_notify(tcp_t *tcp)
18314 {
18315 	struct stdata	*stp;
18316 	conn_t *connp;
18317 
18318 	if (tcp->tcp_detached)
18319 		return;
18320 	connp = tcp->tcp_connp;
18321 	if (IPCL_IS_NONSTR(connp)) {
18322 		(*connp->conn_upcalls->su_zcopy_notify)
18323 		    (connp->conn_upper_handle);
18324 		return;
18325 	}
18326 	stp = STREAM(tcp->tcp_rq);
18327 	mutex_enter(&stp->sd_lock);
18328 	stp->sd_flag |= STZCNOTIFY;
18329 	cv_broadcast(&stp->sd_zcopy_wait);
18330 	mutex_exit(&stp->sd_lock);
18331 }
18332 
18333 static boolean_t
18334 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18335 {
18336 	ire_t	*ire;
18337 	conn_t	*connp = tcp->tcp_connp;
18338 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18339 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18340 
18341 	mutex_enter(&connp->conn_lock);
18342 	ire = connp->conn_ire_cache;
18343 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18344 
18345 	if ((ire != NULL) &&
18346 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18347 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18348 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18349 		IRE_REFHOLD(ire);
18350 		mutex_exit(&connp->conn_lock);
18351 	} else {
18352 		boolean_t cached = B_FALSE;
18353 		ts_label_t *tsl;
18354 
18355 		/* force a recheck later on */
18356 		tcp->tcp_ire_ill_check_done = B_FALSE;
18357 
18358 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18359 		connp->conn_ire_cache = NULL;
18360 		mutex_exit(&connp->conn_lock);
18361 
18362 		if (ire != NULL)
18363 			IRE_REFRELE_NOTR(ire);
18364 
18365 		tsl = crgetlabel(CONN_CRED(connp));
18366 		ire = (dst ?
18367 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18368 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18369 		    connp->conn_zoneid, tsl, ipst));
18370 
18371 		if (ire == NULL) {
18372 			TCP_STAT(tcps, tcp_ire_null);
18373 			return (B_FALSE);
18374 		}
18375 
18376 		IRE_REFHOLD_NOTR(ire);
18377 
18378 		mutex_enter(&connp->conn_lock);
18379 		if (CONN_CACHE_IRE(connp)) {
18380 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18381 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18382 				TCP_CHECK_IREINFO(tcp, ire);
18383 				connp->conn_ire_cache = ire;
18384 				cached = B_TRUE;
18385 			}
18386 			rw_exit(&ire->ire_bucket->irb_lock);
18387 		}
18388 		mutex_exit(&connp->conn_lock);
18389 
18390 		/*
18391 		 * We can continue to use the ire but since it was
18392 		 * not cached, we should drop the extra reference.
18393 		 */
18394 		if (!cached)
18395 			IRE_REFRELE_NOTR(ire);
18396 
18397 		/*
18398 		 * Rampart note: no need to select a new label here, since
18399 		 * labels are not allowed to change during the life of a TCP
18400 		 * connection.
18401 		 */
18402 	}
18403 
18404 	*irep = ire;
18405 
18406 	return (B_TRUE);
18407 }
18408 
18409 /*
18410  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18411  *
18412  * 0 = success;
18413  * 1 = failed to find ire and ill.
18414  */
18415 static boolean_t
18416 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18417 {
18418 	ipha_t		*ipha;
18419 	ipaddr_t	dst;
18420 	ire_t		*ire;
18421 	ill_t		*ill;
18422 	mblk_t		*ire_fp_mp;
18423 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18424 
18425 	if (mp != NULL)
18426 		ipha = (ipha_t *)mp->b_rptr;
18427 	else
18428 		ipha = tcp->tcp_ipha;
18429 	dst = ipha->ipha_dst;
18430 
18431 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18432 		return (B_FALSE);
18433 
18434 	if ((ire->ire_flags & RTF_MULTIRT) ||
18435 	    (ire->ire_stq == NULL) ||
18436 	    (ire->ire_nce == NULL) ||
18437 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18438 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18439 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18440 		TCP_STAT(tcps, tcp_ip_ire_send);
18441 		IRE_REFRELE(ire);
18442 		return (B_FALSE);
18443 	}
18444 
18445 	ill = ire_to_ill(ire);
18446 	ASSERT(ill != NULL);
18447 
18448 	if (!tcp->tcp_ire_ill_check_done) {
18449 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18450 		tcp->tcp_ire_ill_check_done = B_TRUE;
18451 	}
18452 
18453 	*irep = ire;
18454 	*illp = ill;
18455 
18456 	return (B_TRUE);
18457 }
18458 
18459 static void
18460 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18461 {
18462 	ipha_t		*ipha;
18463 	ipaddr_t	src;
18464 	ipaddr_t	dst;
18465 	uint32_t	cksum;
18466 	ire_t		*ire;
18467 	uint16_t	*up;
18468 	ill_t		*ill;
18469 	conn_t		*connp = tcp->tcp_connp;
18470 	uint32_t	hcksum_txflags = 0;
18471 	mblk_t		*ire_fp_mp;
18472 	uint_t		ire_fp_mp_len;
18473 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18474 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18475 	cred_t		*cr;
18476 	pid_t		cpid;
18477 
18478 	ASSERT(DB_TYPE(mp) == M_DATA);
18479 
18480 	/*
18481 	 * Here we need to handle the overloading of the cred_t for
18482 	 * both getpeerucred and TX.
18483 	 * If this is a SYN then the caller already set db_credp so
18484 	 * that getpeerucred will work. But if TX is in use we might have
18485 	 * a conn_effective_cred which is different, and we need to use that
18486 	 * cred to make TX use the correct label and label dependent route.
18487 	 */
18488 	if (is_system_labeled()) {
18489 		cr = msg_getcred(mp, &cpid);
18490 		if (cr == NULL || connp->conn_effective_cred != NULL)
18491 			mblk_setcred(mp, CONN_CRED(connp), cpid);
18492 	}
18493 
18494 	ipha = (ipha_t *)mp->b_rptr;
18495 	src = ipha->ipha_src;
18496 	dst = ipha->ipha_dst;
18497 
18498 	ASSERT(q != NULL);
18499 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
18500 
18501 	/*
18502 	 * Drop off fast path for IPv6 and also if options are present or
18503 	 * we need to resolve a TS label.
18504 	 */
18505 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18506 	    !IPCL_IS_CONNECTED(connp) ||
18507 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18508 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18509 	    !connp->conn_ulp_labeled ||
18510 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18511 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18512 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18513 		if (tcp->tcp_snd_zcopy_aware)
18514 			mp = tcp_zcopy_disable(tcp, mp);
18515 		TCP_STAT(tcps, tcp_ip_send);
18516 		CALL_IP_WPUT(connp, q, mp);
18517 		return;
18518 	}
18519 
18520 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18521 		if (tcp->tcp_snd_zcopy_aware)
18522 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18523 		CALL_IP_WPUT(connp, q, mp);
18524 		return;
18525 	}
18526 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18527 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18528 
18529 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18530 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18531 #ifndef _BIG_ENDIAN
18532 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18533 #endif
18534 
18535 	/*
18536 	 * Check to see if we need to re-enable LSO/MDT for this connection
18537 	 * because it was previously disabled due to changes in the ill;
18538 	 * note that by doing it here, this re-enabling only applies when
18539 	 * the packet is not dispatched through CALL_IP_WPUT().
18540 	 *
18541 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18542 	 * case, since that's how we ended up here.  For IPv6, we do the
18543 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18544 	 */
18545 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18546 		/*
18547 		 * Restore LSO for this connection, so that next time around
18548 		 * it is eligible to go through tcp_lsosend() path again.
18549 		 */
18550 		TCP_STAT(tcps, tcp_lso_enabled);
18551 		tcp->tcp_lso = B_TRUE;
18552 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18553 		    "interface %s\n", (void *)connp, ill->ill_name));
18554 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18555 		/*
18556 		 * Restore MDT for this connection, so that next time around
18557 		 * it is eligible to go through tcp_multisend() path again.
18558 		 */
18559 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18560 		tcp->tcp_mdt = B_TRUE;
18561 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18562 		    "interface %s\n", (void *)connp, ill->ill_name));
18563 	}
18564 
18565 	if (tcp->tcp_snd_zcopy_aware) {
18566 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18567 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18568 			mp = tcp_zcopy_disable(tcp, mp);
18569 		/*
18570 		 * we shouldn't need to reset ipha as the mp containing
18571 		 * ipha should never be a zero-copy mp.
18572 		 */
18573 	}
18574 
18575 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18576 		ASSERT(ill->ill_hcksum_capab != NULL);
18577 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18578 	}
18579 
18580 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18581 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18582 
18583 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18584 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18585 
18586 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18587 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18588 
18589 	/* Software checksum? */
18590 	if (DB_CKSUMFLAGS(mp) == 0) {
18591 		TCP_STAT(tcps, tcp_out_sw_cksum);
18592 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18593 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18594 	}
18595 
18596 	/* Calculate IP header checksum if hardware isn't capable */
18597 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18598 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18599 		    ((uint16_t *)ipha)[4]);
18600 	}
18601 
18602 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18603 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18604 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18605 
18606 	UPDATE_OB_PKT_COUNT(ire);
18607 	ire->ire_last_used_time = lbolt;
18608 
18609 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18610 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18611 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18612 	    ntohs(ipha->ipha_length));
18613 
18614 	DTRACE_PROBE4(ip4__physical__out__start,
18615 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
18616 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
18617 	    ipst->ips_ipv4firewall_physical_out,
18618 	    NULL, ill, ipha, mp, mp, 0, ipst);
18619 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18620 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
18621 
18622 	if (mp != NULL) {
18623 		if (ipst->ips_ipobs_enabled) {
18624 			zoneid_t szone;
18625 
18626 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
18627 			    ipst, ALL_ZONES);
18628 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
18629 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
18630 		}
18631 
18632 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
18633 	}
18634 
18635 	IRE_REFRELE(ire);
18636 }
18637 
18638 /*
18639  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18640  * if the receiver shrinks the window, i.e. moves the right window to the
18641  * left, the we should not send new data, but should retransmit normally the
18642  * old unacked data between suna and suna + swnd. We might has sent data
18643  * that is now outside the new window, pretend that we didn't send  it.
18644  */
18645 static void
18646 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18647 {
18648 	uint32_t	snxt = tcp->tcp_snxt;
18649 	mblk_t		*xmit_tail;
18650 	int32_t		offset;
18651 
18652 	ASSERT(shrunk_count > 0);
18653 
18654 	/* Pretend we didn't send the data outside the window */
18655 	snxt -= shrunk_count;
18656 
18657 	/* Get the mblk and the offset in it per the shrunk window */
18658 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18659 
18660 	ASSERT(xmit_tail != NULL);
18661 
18662 	/* Reset all the values per the now shrunk window */
18663 	tcp->tcp_snxt = snxt;
18664 	tcp->tcp_xmit_tail = xmit_tail;
18665 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18666 	    offset;
18667 	tcp->tcp_unsent += shrunk_count;
18668 
18669 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18670 		/*
18671 		 * Make sure the timer is running so that we will probe a zero
18672 		 * window.
18673 		 */
18674 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18675 }
18676 
18677 
18678 /*
18679  * The TCP normal data output path.
18680  * NOTE: the logic of the fast path is duplicated from this function.
18681  */
18682 static void
18683 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18684 {
18685 	int		len;
18686 	mblk_t		*local_time;
18687 	mblk_t		*mp1;
18688 	uint32_t	snxt;
18689 	int		tail_unsent;
18690 	int		tcpstate;
18691 	int		usable = 0;
18692 	mblk_t		*xmit_tail;
18693 	queue_t		*q = tcp->tcp_wq;
18694 	int32_t		mss;
18695 	int32_t		num_sack_blk = 0;
18696 	int32_t		tcp_hdr_len;
18697 	int32_t		tcp_tcp_hdr_len;
18698 	int		mdt_thres;
18699 	int		rc;
18700 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18701 	ip_stack_t	*ipst;
18702 
18703 	tcpstate = tcp->tcp_state;
18704 	if (mp == NULL) {
18705 		/*
18706 		 * tcp_wput_data() with NULL mp should only be called when
18707 		 * there is unsent data.
18708 		 */
18709 		ASSERT(tcp->tcp_unsent > 0);
18710 		/* Really tacky... but we need this for detached closes. */
18711 		len = tcp->tcp_unsent;
18712 		goto data_null;
18713 	}
18714 
18715 #if CCS_STATS
18716 	wrw_stats.tot.count++;
18717 	wrw_stats.tot.bytes += msgdsize(mp);
18718 #endif
18719 	ASSERT(mp->b_datap->db_type == M_DATA);
18720 	/*
18721 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18722 	 * or before a connection attempt has begun.
18723 	 */
18724 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18725 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18726 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18727 #ifdef DEBUG
18728 			cmn_err(CE_WARN,
18729 			    "tcp_wput_data: data after ordrel, %s",
18730 			    tcp_display(tcp, NULL,
18731 			    DISP_ADDR_AND_PORT));
18732 #else
18733 			if (tcp->tcp_debug) {
18734 				(void) strlog(TCP_MOD_ID, 0, 1,
18735 				    SL_TRACE|SL_ERROR,
18736 				    "tcp_wput_data: data after ordrel, %s\n",
18737 				    tcp_display(tcp, NULL,
18738 				    DISP_ADDR_AND_PORT));
18739 			}
18740 #endif /* DEBUG */
18741 		}
18742 		if (tcp->tcp_snd_zcopy_aware &&
18743 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18744 			tcp_zcopy_notify(tcp);
18745 		freemsg(mp);
18746 		mutex_enter(&tcp->tcp_non_sq_lock);
18747 		if (tcp->tcp_flow_stopped &&
18748 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18749 			tcp_clrqfull(tcp);
18750 		}
18751 		mutex_exit(&tcp->tcp_non_sq_lock);
18752 		return;
18753 	}
18754 
18755 	/* Strip empties */
18756 	for (;;) {
18757 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18758 		    (uintptr_t)INT_MAX);
18759 		len = (int)(mp->b_wptr - mp->b_rptr);
18760 		if (len > 0)
18761 			break;
18762 		mp1 = mp;
18763 		mp = mp->b_cont;
18764 		freeb(mp1);
18765 		if (!mp) {
18766 			return;
18767 		}
18768 	}
18769 
18770 	/* If we are the first on the list ... */
18771 	if (tcp->tcp_xmit_head == NULL) {
18772 		tcp->tcp_xmit_head = mp;
18773 		tcp->tcp_xmit_tail = mp;
18774 		tcp->tcp_xmit_tail_unsent = len;
18775 	} else {
18776 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18777 		struct datab *dp;
18778 
18779 		mp1 = tcp->tcp_xmit_last;
18780 		if (len < tcp_tx_pull_len &&
18781 		    (dp = mp1->b_datap)->db_ref == 1 &&
18782 		    dp->db_lim - mp1->b_wptr >= len) {
18783 			ASSERT(len > 0);
18784 			ASSERT(!mp1->b_cont);
18785 			if (len == 1) {
18786 				*mp1->b_wptr++ = *mp->b_rptr;
18787 			} else {
18788 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18789 				mp1->b_wptr += len;
18790 			}
18791 			if (mp1 == tcp->tcp_xmit_tail)
18792 				tcp->tcp_xmit_tail_unsent += len;
18793 			mp1->b_cont = mp->b_cont;
18794 			if (tcp->tcp_snd_zcopy_aware &&
18795 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18796 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18797 			freeb(mp);
18798 			mp = mp1;
18799 		} else {
18800 			tcp->tcp_xmit_last->b_cont = mp;
18801 		}
18802 		len += tcp->tcp_unsent;
18803 	}
18804 
18805 	/* Tack on however many more positive length mblks we have */
18806 	if ((mp1 = mp->b_cont) != NULL) {
18807 		do {
18808 			int tlen;
18809 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18810 			    (uintptr_t)INT_MAX);
18811 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18812 			if (tlen <= 0) {
18813 				mp->b_cont = mp1->b_cont;
18814 				freeb(mp1);
18815 			} else {
18816 				len += tlen;
18817 				mp = mp1;
18818 			}
18819 		} while ((mp1 = mp->b_cont) != NULL);
18820 	}
18821 	tcp->tcp_xmit_last = mp;
18822 	tcp->tcp_unsent = len;
18823 
18824 	if (urgent)
18825 		usable = 1;
18826 
18827 data_null:
18828 	snxt = tcp->tcp_snxt;
18829 	xmit_tail = tcp->tcp_xmit_tail;
18830 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18831 
18832 	/*
18833 	 * Note that tcp_mss has been adjusted to take into account the
18834 	 * timestamp option if applicable.  Because SACK options do not
18835 	 * appear in every TCP segments and they are of variable lengths,
18836 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18837 	 * the actual segment length when we need to send a segment which
18838 	 * includes SACK options.
18839 	 */
18840 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18841 		int32_t	opt_len;
18842 
18843 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18844 		    tcp->tcp_num_sack_blk);
18845 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18846 		    2 + TCPOPT_HEADER_LEN;
18847 		mss = tcp->tcp_mss - opt_len;
18848 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18849 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18850 	} else {
18851 		mss = tcp->tcp_mss;
18852 		tcp_hdr_len = tcp->tcp_hdr_len;
18853 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18854 	}
18855 
18856 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18857 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18858 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18859 	}
18860 	if (tcpstate == TCPS_SYN_RCVD) {
18861 		/*
18862 		 * The three-way connection establishment handshake is not
18863 		 * complete yet. We want to queue the data for transmission
18864 		 * after entering ESTABLISHED state (RFC793). A jump to
18865 		 * "done" label effectively leaves data on the queue.
18866 		 */
18867 		goto done;
18868 	} else {
18869 		int usable_r;
18870 
18871 		/*
18872 		 * In the special case when cwnd is zero, which can only
18873 		 * happen if the connection is ECN capable, return now.
18874 		 * New segments is sent using tcp_timer().  The timer
18875 		 * is set in tcp_rput_data().
18876 		 */
18877 		if (tcp->tcp_cwnd == 0) {
18878 			/*
18879 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18880 			 * finished.
18881 			 */
18882 			ASSERT(tcp->tcp_ecn_ok ||
18883 			    tcp->tcp_state < TCPS_ESTABLISHED);
18884 			return;
18885 		}
18886 
18887 		/* NOTE: trouble if xmitting while SYN not acked? */
18888 		usable_r = snxt - tcp->tcp_suna;
18889 		usable_r = tcp->tcp_swnd - usable_r;
18890 
18891 		/*
18892 		 * Check if the receiver has shrunk the window.  If
18893 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18894 		 * cannot be set as there is unsent data, so FIN cannot
18895 		 * be sent out.  Otherwise, we need to take into account
18896 		 * of FIN as it consumes an "invisible" sequence number.
18897 		 */
18898 		ASSERT(tcp->tcp_fin_sent == 0);
18899 		if (usable_r < 0) {
18900 			/*
18901 			 * The receiver has shrunk the window and we have sent
18902 			 * -usable_r date beyond the window, re-adjust.
18903 			 *
18904 			 * If TCP window scaling is enabled, there can be
18905 			 * round down error as the advertised receive window
18906 			 * is actually right shifted n bits.  This means that
18907 			 * the lower n bits info is wiped out.  It will look
18908 			 * like the window is shrunk.  Do a check here to
18909 			 * see if the shrunk amount is actually within the
18910 			 * error in window calculation.  If it is, just
18911 			 * return.  Note that this check is inside the
18912 			 * shrunk window check.  This makes sure that even
18913 			 * though tcp_process_shrunk_swnd() is not called,
18914 			 * we will stop further processing.
18915 			 */
18916 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18917 				tcp_process_shrunk_swnd(tcp, -usable_r);
18918 			}
18919 			return;
18920 		}
18921 
18922 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18923 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18924 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18925 
18926 		/* usable = MIN(usable, unsent) */
18927 		if (usable_r > len)
18928 			usable_r = len;
18929 
18930 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18931 		if (usable_r > 0) {
18932 			usable = usable_r;
18933 		} else {
18934 			/* Bypass all other unnecessary processing. */
18935 			goto done;
18936 		}
18937 	}
18938 
18939 	local_time = (mblk_t *)lbolt;
18940 
18941 	/*
18942 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18943 	 * BSD.  This is more in line with the true intent of Nagle.
18944 	 *
18945 	 * The conditions are:
18946 	 * 1. The amount of unsent data (or amount of data which can be
18947 	 *    sent, whichever is smaller) is less than Nagle limit.
18948 	 * 2. The last sent size is also less than Nagle limit.
18949 	 * 3. There is unack'ed data.
18950 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18951 	 *    Nagle algorithm.  This reduces the probability that urgent
18952 	 *    bytes get "merged" together.
18953 	 * 5. The app has not closed the connection.  This eliminates the
18954 	 *    wait time of the receiving side waiting for the last piece of
18955 	 *    (small) data.
18956 	 *
18957 	 * If all are satisified, exit without sending anything.  Note
18958 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18959 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18960 	 * 4095).
18961 	 */
18962 	if (usable < (int)tcp->tcp_naglim &&
18963 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18964 	    snxt != tcp->tcp_suna &&
18965 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18966 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18967 		goto done;
18968 	}
18969 
18970 	/*
18971 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
18972 	 * is set, then we have to force TCP not to send partial segment
18973 	 * (smaller than MSS bytes). We are calculating the usable now
18974 	 * based on full mss and will save the rest of remaining data for
18975 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
18976 	 * something to do zero window probe.
18977 	 */
18978 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
18979 		if (usable < mss)
18980 			goto done;
18981 		usable = (usable / mss) * mss;
18982 	}
18983 
18984 	/* Update the latest receive window size in TCP header. */
18985 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18986 	    tcp->tcp_tcph->th_win);
18987 
18988 	/*
18989 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
18990 	 *
18991 	 * 1. Simple TCP/IP{v4,v6} (no options).
18992 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18993 	 * 3. If the TCP connection is in ESTABLISHED state.
18994 	 * 4. The TCP is not detached.
18995 	 *
18996 	 * If any of the above conditions have changed during the
18997 	 * connection, stop using LSO/MDT and restore the stream head
18998 	 * parameters accordingly.
18999 	 */
19000 	ipst = tcps->tcps_netstack->netstack_ip;
19001 
19002 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19003 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19004 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19005 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19006 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19007 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19008 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19009 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19010 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19011 		if (tcp->tcp_lso) {
19012 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19013 			tcp->tcp_lso = B_FALSE;
19014 		} else {
19015 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19016 			tcp->tcp_mdt = B_FALSE;
19017 		}
19018 
19019 		/* Anything other than detached is considered pathological */
19020 		if (!TCP_IS_DETACHED(tcp)) {
19021 			if (tcp->tcp_lso)
19022 				TCP_STAT(tcps, tcp_lso_disabled);
19023 			else
19024 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19025 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19026 		}
19027 	}
19028 
19029 	/* Use MDT if sendable amount is greater than the threshold */
19030 	if (tcp->tcp_mdt &&
19031 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19032 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19033 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19034 	    (tcp->tcp_valid_bits == 0 ||
19035 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19036 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19037 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19038 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19039 		    local_time, mdt_thres);
19040 	} else {
19041 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19042 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19043 		    local_time, INT_MAX);
19044 	}
19045 
19046 	/* Pretend that all we were trying to send really got sent */
19047 	if (rc < 0 && tail_unsent < 0) {
19048 		do {
19049 			xmit_tail = xmit_tail->b_cont;
19050 			xmit_tail->b_prev = local_time;
19051 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19052 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19053 			tail_unsent += (int)(xmit_tail->b_wptr -
19054 			    xmit_tail->b_rptr);
19055 		} while (tail_unsent < 0);
19056 	}
19057 done:;
19058 	tcp->tcp_xmit_tail = xmit_tail;
19059 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19060 	len = tcp->tcp_snxt - snxt;
19061 	if (len) {
19062 		/*
19063 		 * If new data was sent, need to update the notsack
19064 		 * list, which is, afterall, data blocks that have
19065 		 * not been sack'ed by the receiver.  New data is
19066 		 * not sack'ed.
19067 		 */
19068 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19069 			/* len is a negative value. */
19070 			tcp->tcp_pipe -= len;
19071 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19072 			    tcp->tcp_snxt, snxt,
19073 			    &(tcp->tcp_num_notsack_blk),
19074 			    &(tcp->tcp_cnt_notsack_list));
19075 		}
19076 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19077 		tcp->tcp_rack = tcp->tcp_rnxt;
19078 		tcp->tcp_rack_cnt = 0;
19079 		if ((snxt + len) == tcp->tcp_suna) {
19080 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19081 		}
19082 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19083 		/*
19084 		 * Didn't send anything. Make sure the timer is running
19085 		 * so that we will probe a zero window.
19086 		 */
19087 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19088 	}
19089 	/* Note that len is the amount we just sent but with a negative sign */
19090 	tcp->tcp_unsent += len;
19091 	mutex_enter(&tcp->tcp_non_sq_lock);
19092 	if (tcp->tcp_flow_stopped) {
19093 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19094 			tcp_clrqfull(tcp);
19095 		}
19096 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19097 		tcp_setqfull(tcp);
19098 	}
19099 	mutex_exit(&tcp->tcp_non_sq_lock);
19100 }
19101 
19102 /*
19103  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19104  * outgoing TCP header with the template header, as well as other
19105  * options such as time-stamp, ECN and/or SACK.
19106  */
19107 static void
19108 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19109 {
19110 	tcph_t *tcp_tmpl, *tcp_h;
19111 	uint32_t *dst, *src;
19112 	int hdrlen;
19113 
19114 	ASSERT(OK_32PTR(rptr));
19115 
19116 	/* Template header */
19117 	tcp_tmpl = tcp->tcp_tcph;
19118 
19119 	/* Header of outgoing packet */
19120 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19121 
19122 	/* dst and src are opaque 32-bit fields, used for copying */
19123 	dst = (uint32_t *)rptr;
19124 	src = (uint32_t *)tcp->tcp_iphc;
19125 	hdrlen = tcp->tcp_hdr_len;
19126 
19127 	/* Fill time-stamp option if needed */
19128 	if (tcp->tcp_snd_ts_ok) {
19129 		U32_TO_BE32((uint32_t)now,
19130 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19131 		U32_TO_BE32(tcp->tcp_ts_recent,
19132 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19133 	} else {
19134 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19135 	}
19136 
19137 	/*
19138 	 * Copy the template header; is this really more efficient than
19139 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19140 	 * but perhaps not for other scenarios.
19141 	 */
19142 	dst[0] = src[0];
19143 	dst[1] = src[1];
19144 	dst[2] = src[2];
19145 	dst[3] = src[3];
19146 	dst[4] = src[4];
19147 	dst[5] = src[5];
19148 	dst[6] = src[6];
19149 	dst[7] = src[7];
19150 	dst[8] = src[8];
19151 	dst[9] = src[9];
19152 	if (hdrlen -= 40) {
19153 		hdrlen >>= 2;
19154 		dst += 10;
19155 		src += 10;
19156 		do {
19157 			*dst++ = *src++;
19158 		} while (--hdrlen);
19159 	}
19160 
19161 	/*
19162 	 * Set the ECN info in the TCP header if it is not a zero
19163 	 * window probe.  Zero window probe is only sent in
19164 	 * tcp_wput_data() and tcp_timer().
19165 	 */
19166 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19167 		SET_ECT(tcp, rptr);
19168 
19169 		if (tcp->tcp_ecn_echo_on)
19170 			tcp_h->th_flags[0] |= TH_ECE;
19171 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19172 			tcp_h->th_flags[0] |= TH_CWR;
19173 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19174 		}
19175 	}
19176 
19177 	/* Fill in SACK options */
19178 	if (num_sack_blk > 0) {
19179 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19180 		sack_blk_t *tmp;
19181 		int32_t	i;
19182 
19183 		wptr[0] = TCPOPT_NOP;
19184 		wptr[1] = TCPOPT_NOP;
19185 		wptr[2] = TCPOPT_SACK;
19186 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19187 		    sizeof (sack_blk_t);
19188 		wptr += TCPOPT_REAL_SACK_LEN;
19189 
19190 		tmp = tcp->tcp_sack_list;
19191 		for (i = 0; i < num_sack_blk; i++) {
19192 			U32_TO_BE32(tmp[i].begin, wptr);
19193 			wptr += sizeof (tcp_seq);
19194 			U32_TO_BE32(tmp[i].end, wptr);
19195 			wptr += sizeof (tcp_seq);
19196 		}
19197 		tcp_h->th_offset_and_rsrvd[0] +=
19198 		    ((num_sack_blk * 2 + 1) << 4);
19199 	}
19200 }
19201 
19202 /*
19203  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19204  * the destination address and SAP attribute, and if necessary, the
19205  * hardware checksum offload attribute to a Multidata message.
19206  */
19207 static int
19208 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19209     const uint32_t start, const uint32_t stuff, const uint32_t end,
19210     const uint32_t flags, tcp_stack_t *tcps)
19211 {
19212 	/* Add global destination address & SAP attribute */
19213 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19214 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19215 		    "destination address+SAP\n"));
19216 
19217 		if (dlmp != NULL)
19218 			TCP_STAT(tcps, tcp_mdt_allocfail);
19219 		return (-1);
19220 	}
19221 
19222 	/* Add global hwcksum attribute */
19223 	if (hwcksum &&
19224 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19225 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19226 		    "checksum attribute\n"));
19227 
19228 		TCP_STAT(tcps, tcp_mdt_allocfail);
19229 		return (-1);
19230 	}
19231 
19232 	return (0);
19233 }
19234 
19235 /*
19236  * Smaller and private version of pdescinfo_t used specifically for TCP,
19237  * which allows for only two payload spans per packet.
19238  */
19239 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19240 
19241 /*
19242  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19243  * scheme, and returns one the following:
19244  *
19245  * -1 = failed allocation.
19246  *  0 = success; burst count reached, or usable send window is too small,
19247  *      and that we'd rather wait until later before sending again.
19248  */
19249 static int
19250 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19251     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19252     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19253     const int mdt_thres)
19254 {
19255 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19256 	multidata_t	*mmd;
19257 	uint_t		obsegs, obbytes, hdr_frag_sz;
19258 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19259 	int		num_burst_seg, max_pld;
19260 	pdesc_t		*pkt;
19261 	tcp_pdescinfo_t	tcp_pkt_info;
19262 	pdescinfo_t	*pkt_info;
19263 	int		pbuf_idx, pbuf_idx_nxt;
19264 	int		seg_len, len, spill, af;
19265 	boolean_t	add_buffer, zcopy, clusterwide;
19266 	boolean_t	rconfirm = B_FALSE;
19267 	boolean_t	done = B_FALSE;
19268 	uint32_t	cksum;
19269 	uint32_t	hwcksum_flags;
19270 	ire_t		*ire = NULL;
19271 	ill_t		*ill;
19272 	ipha_t		*ipha;
19273 	ip6_t		*ip6h;
19274 	ipaddr_t	src, dst;
19275 	ill_zerocopy_capab_t *zc_cap = NULL;
19276 	uint16_t	*up;
19277 	int		err;
19278 	conn_t		*connp;
19279 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19280 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19281 	int		usable_mmd, tail_unsent_mmd;
19282 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19283 	mblk_t		*xmit_tail_mmd;
19284 	netstackid_t	stack_id;
19285 
19286 #ifdef	_BIG_ENDIAN
19287 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19288 #else
19289 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19290 #endif
19291 
19292 #define	PREP_NEW_MULTIDATA() {			\
19293 	mmd = NULL;				\
19294 	md_mp = md_hbuf = NULL;			\
19295 	cur_hdr_off = 0;			\
19296 	max_pld = tcp->tcp_mdt_max_pld;		\
19297 	pbuf_idx = pbuf_idx_nxt = -1;		\
19298 	add_buffer = B_TRUE;			\
19299 	zcopy = B_FALSE;			\
19300 }
19301 
19302 #define	PREP_NEW_PBUF() {			\
19303 	md_pbuf = md_pbuf_nxt = NULL;		\
19304 	pbuf_idx = pbuf_idx_nxt = -1;		\
19305 	cur_pld_off = 0;			\
19306 	first_snxt = *snxt;			\
19307 	ASSERT(*tail_unsent > 0);		\
19308 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19309 }
19310 
19311 	ASSERT(mdt_thres >= mss);
19312 	ASSERT(*usable > 0 && *usable > mdt_thres);
19313 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19314 	ASSERT(!TCP_IS_DETACHED(tcp));
19315 	ASSERT(tcp->tcp_valid_bits == 0 ||
19316 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19317 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19318 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19319 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19320 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19321 
19322 	connp = tcp->tcp_connp;
19323 	ASSERT(connp != NULL);
19324 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19325 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19326 
19327 	stack_id = connp->conn_netstack->netstack_stackid;
19328 
19329 	usable_mmd = tail_unsent_mmd = 0;
19330 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
19331 	xmit_tail_mmd = NULL;
19332 	/*
19333 	 * Note that tcp will only declare at most 2 payload spans per
19334 	 * packet, which is much lower than the maximum allowable number
19335 	 * of packet spans per Multidata.  For this reason, we use the
19336 	 * privately declared and smaller descriptor info structure, in
19337 	 * order to save some stack space.
19338 	 */
19339 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19340 
19341 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19342 	if (af == AF_INET) {
19343 		dst = tcp->tcp_ipha->ipha_dst;
19344 		src = tcp->tcp_ipha->ipha_src;
19345 		ASSERT(!CLASSD(dst));
19346 	}
19347 	ASSERT(af == AF_INET ||
19348 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19349 
19350 	obsegs = obbytes = 0;
19351 	num_burst_seg = tcp->tcp_snd_burst;
19352 	md_mp_head = NULL;
19353 	PREP_NEW_MULTIDATA();
19354 
19355 	/*
19356 	 * Before we go on further, make sure there is an IRE that we can
19357 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19358 	 * in proceeding any further, and we should just hand everything
19359 	 * off to the legacy path.
19360 	 */
19361 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19362 		goto legacy_send_no_md;
19363 
19364 	ASSERT(ire != NULL);
19365 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19366 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19367 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19368 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19369 	/*
19370 	 * If we do support loopback for MDT (which requires modifications
19371 	 * to the receiving paths), the following assertions should go away,
19372 	 * and we would be sending the Multidata to loopback conn later on.
19373 	 */
19374 	ASSERT(!IRE_IS_LOCAL(ire));
19375 	ASSERT(ire->ire_stq != NULL);
19376 
19377 	ill = ire_to_ill(ire);
19378 	ASSERT(ill != NULL);
19379 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19380 
19381 	if (!tcp->tcp_ire_ill_check_done) {
19382 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19383 		tcp->tcp_ire_ill_check_done = B_TRUE;
19384 	}
19385 
19386 	/*
19387 	 * If the underlying interface conditions have changed, or if the
19388 	 * new interface does not support MDT, go back to legacy path.
19389 	 */
19390 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19391 		/* don't go through this path anymore for this connection */
19392 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19393 		tcp->tcp_mdt = B_FALSE;
19394 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19395 		    "interface %s\n", (void *)connp, ill->ill_name));
19396 		/* IRE will be released prior to returning */
19397 		goto legacy_send_no_md;
19398 	}
19399 
19400 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19401 		zc_cap = ill->ill_zerocopy_capab;
19402 
19403 	/*
19404 	 * Check if we can take tcp fast-path. Note that "incomplete"
19405 	 * ire's (where the link-layer for next hop is not resolved
19406 	 * or where the fast-path header in nce_fp_mp is not available
19407 	 * yet) are sent down the legacy (slow) path.
19408 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19409 	 */
19410 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19411 		/* IRE will be released prior to returning */
19412 		goto legacy_send_no_md;
19413 	}
19414 
19415 	/* go to legacy path if interface doesn't support zerocopy */
19416 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19417 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19418 		/* IRE will be released prior to returning */
19419 		goto legacy_send_no_md;
19420 	}
19421 
19422 	/* does the interface support hardware checksum offload? */
19423 	hwcksum_flags = 0;
19424 	if (ILL_HCKSUM_CAPABLE(ill) &&
19425 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19426 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19427 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19428 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19429 		    HCKSUM_IPHDRCKSUM)
19430 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19431 
19432 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19433 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19434 			hwcksum_flags |= HCK_FULLCKSUM;
19435 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19436 		    HCKSUM_INET_PARTIAL)
19437 			hwcksum_flags |= HCK_PARTIALCKSUM;
19438 	}
19439 
19440 	/*
19441 	 * Each header fragment consists of the leading extra space,
19442 	 * followed by the TCP/IP header, and the trailing extra space.
19443 	 * We make sure that each header fragment begins on a 32-bit
19444 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19445 	 * aligned in tcp_mdt_update).
19446 	 */
19447 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19448 	    tcp->tcp_mdt_hdr_tail), 4);
19449 
19450 	/* are we starting from the beginning of data block? */
19451 	if (*tail_unsent == 0) {
19452 		*xmit_tail = (*xmit_tail)->b_cont;
19453 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19454 		*tail_unsent = (int)MBLKL(*xmit_tail);
19455 	}
19456 
19457 	/*
19458 	 * Here we create one or more Multidata messages, each made up of
19459 	 * one header buffer and up to N payload buffers.  This entire
19460 	 * operation is done within two loops:
19461 	 *
19462 	 * The outer loop mostly deals with creating the Multidata message,
19463 	 * as well as the header buffer that gets added to it.  It also
19464 	 * links the Multidata messages together such that all of them can
19465 	 * be sent down to the lower layer in a single putnext call; this
19466 	 * linking behavior depends on the tcp_mdt_chain tunable.
19467 	 *
19468 	 * The inner loop takes an existing Multidata message, and adds
19469 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19470 	 * packetizes those buffers by filling up the corresponding header
19471 	 * buffer fragments with the proper IP and TCP headers, and by
19472 	 * describing the layout of each packet in the packet descriptors
19473 	 * that get added to the Multidata.
19474 	 */
19475 	do {
19476 		/*
19477 		 * If usable send window is too small, or data blocks in
19478 		 * transmit list are smaller than our threshold (i.e. app
19479 		 * performs large writes followed by small ones), we hand
19480 		 * off the control over to the legacy path.  Note that we'll
19481 		 * get back the control once it encounters a large block.
19482 		 */
19483 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19484 		    (*xmit_tail)->b_cont != NULL &&
19485 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19486 			/* send down what we've got so far */
19487 			if (md_mp_head != NULL) {
19488 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19489 				    obsegs, obbytes, &rconfirm);
19490 			}
19491 			/*
19492 			 * Pass control over to tcp_send(), but tell it to
19493 			 * return to us once a large-size transmission is
19494 			 * possible.
19495 			 */
19496 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19497 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19498 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19499 			    tail_unsent, xmit_tail, local_time,
19500 			    mdt_thres)) <= 0) {
19501 				/* burst count reached, or alloc failed */
19502 				IRE_REFRELE(ire);
19503 				return (err);
19504 			}
19505 
19506 			/* tcp_send() may have sent everything, so check */
19507 			if (*usable <= 0) {
19508 				IRE_REFRELE(ire);
19509 				return (0);
19510 			}
19511 
19512 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19513 			/*
19514 			 * We may have delivered the Multidata, so make sure
19515 			 * to re-initialize before the next round.
19516 			 */
19517 			md_mp_head = NULL;
19518 			obsegs = obbytes = 0;
19519 			num_burst_seg = tcp->tcp_snd_burst;
19520 			PREP_NEW_MULTIDATA();
19521 
19522 			/* are we starting from the beginning of data block? */
19523 			if (*tail_unsent == 0) {
19524 				*xmit_tail = (*xmit_tail)->b_cont;
19525 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19526 				    (uintptr_t)INT_MAX);
19527 				*tail_unsent = (int)MBLKL(*xmit_tail);
19528 			}
19529 		}
19530 		/*
19531 		 * Record current values for parameters we may need to pass
19532 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
19533 		 * each iteration of the outer loop (each multidata message
19534 		 * creation). If we have a failure in the inner loop, we send
19535 		 * any complete multidata messages we have before reverting
19536 		 * to using the traditional non-md path.
19537 		 */
19538 		snxt_mmd = *snxt;
19539 		usable_mmd = *usable;
19540 		xmit_tail_mmd = *xmit_tail;
19541 		tail_unsent_mmd = *tail_unsent;
19542 		obsegs_mmd = obsegs;
19543 		obbytes_mmd = obbytes;
19544 
19545 		/*
19546 		 * max_pld limits the number of mblks in tcp's transmit
19547 		 * queue that can be added to a Multidata message.  Once
19548 		 * this counter reaches zero, no more additional mblks
19549 		 * can be added to it.  What happens afterwards depends
19550 		 * on whether or not we are set to chain the Multidata
19551 		 * messages.  If we are to link them together, reset
19552 		 * max_pld to its original value (tcp_mdt_max_pld) and
19553 		 * prepare to create a new Multidata message which will
19554 		 * get linked to md_mp_head.  Else, leave it alone and
19555 		 * let the inner loop break on its own.
19556 		 */
19557 		if (tcp_mdt_chain && max_pld == 0)
19558 			PREP_NEW_MULTIDATA();
19559 
19560 		/* adding a payload buffer; re-initialize values */
19561 		if (add_buffer)
19562 			PREP_NEW_PBUF();
19563 
19564 		/*
19565 		 * If we don't have a Multidata, either because we just
19566 		 * (re)entered this outer loop, or after we branched off
19567 		 * to tcp_send above, setup the Multidata and header
19568 		 * buffer to be used.
19569 		 */
19570 		if (md_mp == NULL) {
19571 			int md_hbuflen;
19572 			uint32_t start, stuff;
19573 
19574 			/*
19575 			 * Calculate Multidata header buffer size large enough
19576 			 * to hold all of the headers that can possibly be
19577 			 * sent at this moment.  We'd rather over-estimate
19578 			 * the size than running out of space; this is okay
19579 			 * since this buffer is small anyway.
19580 			 */
19581 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19582 
19583 			/*
19584 			 * Start and stuff offset for partial hardware
19585 			 * checksum offload; these are currently for IPv4.
19586 			 * For full checksum offload, they are set to zero.
19587 			 */
19588 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19589 				if (af == AF_INET) {
19590 					start = IP_SIMPLE_HDR_LENGTH;
19591 					stuff = IP_SIMPLE_HDR_LENGTH +
19592 					    TCP_CHECKSUM_OFFSET;
19593 				} else {
19594 					start = IPV6_HDR_LEN;
19595 					stuff = IPV6_HDR_LEN +
19596 					    TCP_CHECKSUM_OFFSET;
19597 				}
19598 			} else {
19599 				start = stuff = 0;
19600 			}
19601 
19602 			/*
19603 			 * Create the header buffer, Multidata, as well as
19604 			 * any necessary attributes (destination address,
19605 			 * SAP and hardware checksum offload) that should
19606 			 * be associated with the Multidata message.
19607 			 */
19608 			ASSERT(cur_hdr_off == 0);
19609 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19610 			    ((md_hbuf->b_wptr += md_hbuflen),
19611 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19612 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19613 			    /* fastpath mblk */
19614 			    ire->ire_nce->nce_res_mp,
19615 			    /* hardware checksum enabled */
19616 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19617 			    /* hardware checksum offsets */
19618 			    start, stuff, 0,
19619 			    /* hardware checksum flag */
19620 			    hwcksum_flags, tcps) != 0)) {
19621 legacy_send:
19622 				/*
19623 				 * We arrive here from a failure within the
19624 				 * inner (packetizer) loop or we fail one of
19625 				 * the conditionals above. We restore the
19626 				 * previously checkpointed values for:
19627 				 *    xmit_tail
19628 				 *    usable
19629 				 *    tail_unsent
19630 				 *    snxt
19631 				 *    obbytes
19632 				 *    obsegs
19633 				 * We should then be able to dispatch any
19634 				 * complete multidata before reverting to the
19635 				 * traditional path with consistent parameters
19636 				 * (the inner loop updates these as it
19637 				 * iterates).
19638 				 */
19639 				*xmit_tail = xmit_tail_mmd;
19640 				*usable = usable_mmd;
19641 				*tail_unsent = tail_unsent_mmd;
19642 				*snxt = snxt_mmd;
19643 				obbytes = obbytes_mmd;
19644 				obsegs = obsegs_mmd;
19645 				if (md_mp != NULL) {
19646 					/* Unlink message from the chain */
19647 					if (md_mp_head != NULL) {
19648 						err = (intptr_t)rmvb(md_mp_head,
19649 						    md_mp);
19650 						/*
19651 						 * We can't assert that rmvb
19652 						 * did not return -1, since we
19653 						 * may get here before linkb
19654 						 * happens.  We do, however,
19655 						 * check if we just removed the
19656 						 * only element in the list.
19657 						 */
19658 						if (err == 0)
19659 							md_mp_head = NULL;
19660 					}
19661 					/* md_hbuf gets freed automatically */
19662 					TCP_STAT(tcps, tcp_mdt_discarded);
19663 					freeb(md_mp);
19664 				} else {
19665 					/* Either allocb or mmd_alloc failed */
19666 					TCP_STAT(tcps, tcp_mdt_allocfail);
19667 					if (md_hbuf != NULL)
19668 						freeb(md_hbuf);
19669 				}
19670 
19671 				/* send down what we've got so far */
19672 				if (md_mp_head != NULL) {
19673 					tcp_multisend_data(tcp, ire, ill,
19674 					    md_mp_head, obsegs, obbytes,
19675 					    &rconfirm);
19676 				}
19677 legacy_send_no_md:
19678 				if (ire != NULL)
19679 					IRE_REFRELE(ire);
19680 				/*
19681 				 * Too bad; let the legacy path handle this.
19682 				 * We specify INT_MAX for the threshold, since
19683 				 * we gave up with the Multidata processings
19684 				 * and let the old path have it all.
19685 				 */
19686 				TCP_STAT(tcps, tcp_mdt_legacy_all);
19687 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19688 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19689 				    snxt, tail_unsent, xmit_tail, local_time,
19690 				    INT_MAX));
19691 			}
19692 
19693 			/* link to any existing ones, if applicable */
19694 			TCP_STAT(tcps, tcp_mdt_allocd);
19695 			if (md_mp_head == NULL) {
19696 				md_mp_head = md_mp;
19697 			} else if (tcp_mdt_chain) {
19698 				TCP_STAT(tcps, tcp_mdt_linked);
19699 				linkb(md_mp_head, md_mp);
19700 			}
19701 		}
19702 
19703 		ASSERT(md_mp_head != NULL);
19704 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19705 		ASSERT(md_mp != NULL && mmd != NULL);
19706 		ASSERT(md_hbuf != NULL);
19707 
19708 		/*
19709 		 * Packetize the transmittable portion of the data block;
19710 		 * each data block is essentially added to the Multidata
19711 		 * as a payload buffer.  We also deal with adding more
19712 		 * than one payload buffers, which happens when the remaining
19713 		 * packetized portion of the current payload buffer is less
19714 		 * than MSS, while the next data block in transmit queue
19715 		 * has enough data to make up for one.  This "spillover"
19716 		 * case essentially creates a split-packet, where portions
19717 		 * of the packet's payload fragments may span across two
19718 		 * virtually discontiguous address blocks.
19719 		 */
19720 		seg_len = mss;
19721 		do {
19722 			len = seg_len;
19723 
19724 			/* one must remain NULL for DTRACE_IP_FASTPATH */
19725 			ipha = NULL;
19726 			ip6h = NULL;
19727 
19728 			ASSERT(len > 0);
19729 			ASSERT(max_pld >= 0);
19730 			ASSERT(!add_buffer || cur_pld_off == 0);
19731 
19732 			/*
19733 			 * First time around for this payload buffer; note
19734 			 * in the case of a spillover, the following has
19735 			 * been done prior to adding the split-packet
19736 			 * descriptor to Multidata, and we don't want to
19737 			 * repeat the process.
19738 			 */
19739 			if (add_buffer) {
19740 				ASSERT(mmd != NULL);
19741 				ASSERT(md_pbuf == NULL);
19742 				ASSERT(md_pbuf_nxt == NULL);
19743 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19744 
19745 				/*
19746 				 * Have we reached the limit?  We'd get to
19747 				 * this case when we're not chaining the
19748 				 * Multidata messages together, and since
19749 				 * we're done, terminate this loop.
19750 				 */
19751 				if (max_pld == 0)
19752 					break; /* done */
19753 
19754 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19755 					TCP_STAT(tcps, tcp_mdt_allocfail);
19756 					goto legacy_send; /* out_of_mem */
19757 				}
19758 
19759 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19760 				    zc_cap != NULL) {
19761 					if (!ip_md_zcopy_attr(mmd, NULL,
19762 					    zc_cap->ill_zerocopy_flags)) {
19763 						freeb(md_pbuf);
19764 						TCP_STAT(tcps,
19765 						    tcp_mdt_allocfail);
19766 						/* out_of_mem */
19767 						goto legacy_send;
19768 					}
19769 					zcopy = B_TRUE;
19770 				}
19771 
19772 				md_pbuf->b_rptr += base_pld_off;
19773 
19774 				/*
19775 				 * Add a payload buffer to the Multidata; this
19776 				 * operation must not fail, or otherwise our
19777 				 * logic in this routine is broken.  There
19778 				 * is no memory allocation done by the
19779 				 * routine, so any returned failure simply
19780 				 * tells us that we've done something wrong.
19781 				 *
19782 				 * A failure tells us that either we're adding
19783 				 * the same payload buffer more than once, or
19784 				 * we're trying to add more buffers than
19785 				 * allowed (max_pld calculation is wrong).
19786 				 * None of the above cases should happen, and
19787 				 * we panic because either there's horrible
19788 				 * heap corruption, and/or programming mistake.
19789 				 */
19790 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19791 				if (pbuf_idx < 0) {
19792 					cmn_err(CE_PANIC, "tcp_multisend: "
19793 					    "payload buffer logic error "
19794 					    "detected for tcp %p mmd %p "
19795 					    "pbuf %p (%d)\n",
19796 					    (void *)tcp, (void *)mmd,
19797 					    (void *)md_pbuf, pbuf_idx);
19798 				}
19799 
19800 				ASSERT(max_pld > 0);
19801 				--max_pld;
19802 				add_buffer = B_FALSE;
19803 			}
19804 
19805 			ASSERT(md_mp_head != NULL);
19806 			ASSERT(md_pbuf != NULL);
19807 			ASSERT(md_pbuf_nxt == NULL);
19808 			ASSERT(pbuf_idx != -1);
19809 			ASSERT(pbuf_idx_nxt == -1);
19810 			ASSERT(*usable > 0);
19811 
19812 			/*
19813 			 * We spillover to the next payload buffer only
19814 			 * if all of the following is true:
19815 			 *
19816 			 *   1. There is not enough data on the current
19817 			 *	payload buffer to make up `len',
19818 			 *   2. We are allowed to send `len',
19819 			 *   3. The next payload buffer length is large
19820 			 *	enough to accomodate `spill'.
19821 			 */
19822 			if ((spill = len - *tail_unsent) > 0 &&
19823 			    *usable >= len &&
19824 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19825 			    max_pld > 0) {
19826 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19827 				if (md_pbuf_nxt == NULL) {
19828 					TCP_STAT(tcps, tcp_mdt_allocfail);
19829 					goto legacy_send; /* out_of_mem */
19830 				}
19831 
19832 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19833 				    zc_cap != NULL) {
19834 					if (!ip_md_zcopy_attr(mmd, NULL,
19835 					    zc_cap->ill_zerocopy_flags)) {
19836 						freeb(md_pbuf_nxt);
19837 						TCP_STAT(tcps,
19838 						    tcp_mdt_allocfail);
19839 						/* out_of_mem */
19840 						goto legacy_send;
19841 					}
19842 					zcopy = B_TRUE;
19843 				}
19844 
19845 				/*
19846 				 * See comments above on the first call to
19847 				 * mmd_addpldbuf for explanation on the panic.
19848 				 */
19849 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19850 				if (pbuf_idx_nxt < 0) {
19851 					panic("tcp_multisend: "
19852 					    "next payload buffer logic error "
19853 					    "detected for tcp %p mmd %p "
19854 					    "pbuf %p (%d)\n",
19855 					    (void *)tcp, (void *)mmd,
19856 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19857 				}
19858 
19859 				ASSERT(max_pld > 0);
19860 				--max_pld;
19861 			} else if (spill > 0) {
19862 				/*
19863 				 * If there's a spillover, but the following
19864 				 * xmit_tail couldn't give us enough octets
19865 				 * to reach "len", then stop the current
19866 				 * Multidata creation and let the legacy
19867 				 * tcp_send() path take over.  We don't want
19868 				 * to send the tiny segment as part of this
19869 				 * Multidata for performance reasons; instead,
19870 				 * we let the legacy path deal with grouping
19871 				 * it with the subsequent small mblks.
19872 				 */
19873 				if (*usable >= len &&
19874 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19875 					max_pld = 0;
19876 					break;	/* done */
19877 				}
19878 
19879 				/*
19880 				 * We can't spillover, and we are near
19881 				 * the end of the current payload buffer,
19882 				 * so send what's left.
19883 				 */
19884 				ASSERT(*tail_unsent > 0);
19885 				len = *tail_unsent;
19886 			}
19887 
19888 			/* tail_unsent is negated if there is a spillover */
19889 			*tail_unsent -= len;
19890 			*usable -= len;
19891 			ASSERT(*usable >= 0);
19892 
19893 			if (*usable < mss)
19894 				seg_len = *usable;
19895 			/*
19896 			 * Sender SWS avoidance; see comments in tcp_send();
19897 			 * everything else is the same, except that we only
19898 			 * do this here if there is no more data to be sent
19899 			 * following the current xmit_tail.  We don't check
19900 			 * for 1-byte urgent data because we shouldn't get
19901 			 * here if TCP_URG_VALID is set.
19902 			 */
19903 			if (*usable > 0 && *usable < mss &&
19904 			    ((md_pbuf_nxt == NULL &&
19905 			    (*xmit_tail)->b_cont == NULL) ||
19906 			    (md_pbuf_nxt != NULL &&
19907 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19908 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19909 			    (tcp->tcp_unsent -
19910 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19911 			    !tcp->tcp_zero_win_probe) {
19912 				if ((*snxt + len) == tcp->tcp_snxt &&
19913 				    (*snxt + len) == tcp->tcp_suna) {
19914 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19915 				}
19916 				done = B_TRUE;
19917 			}
19918 
19919 			/*
19920 			 * Prime pump for IP's checksumming on our behalf;
19921 			 * include the adjustment for a source route if any.
19922 			 * Do this only for software/partial hardware checksum
19923 			 * offload, as this field gets zeroed out later for
19924 			 * the full hardware checksum offload case.
19925 			 */
19926 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19927 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19928 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19929 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19930 			}
19931 
19932 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19933 			*snxt += len;
19934 
19935 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19936 			/*
19937 			 * We set the PUSH bit only if TCP has no more buffered
19938 			 * data to be transmitted (or if sender SWS avoidance
19939 			 * takes place), as opposed to setting it for every
19940 			 * last packet in the burst.
19941 			 */
19942 			if (done ||
19943 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19944 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19945 
19946 			/*
19947 			 * Set FIN bit if this is our last segment; snxt
19948 			 * already includes its length, and it will not
19949 			 * be adjusted after this point.
19950 			 */
19951 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19952 			    *snxt == tcp->tcp_fss) {
19953 				if (!tcp->tcp_fin_acked) {
19954 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19955 					BUMP_MIB(&tcps->tcps_mib,
19956 					    tcpOutControl);
19957 				}
19958 				if (!tcp->tcp_fin_sent) {
19959 					tcp->tcp_fin_sent = B_TRUE;
19960 					/*
19961 					 * tcp state must be ESTABLISHED
19962 					 * in order for us to get here in
19963 					 * the first place.
19964 					 */
19965 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19966 
19967 					/*
19968 					 * Upon returning from this routine,
19969 					 * tcp_wput_data() will set tcp_snxt
19970 					 * to be equal to snxt + tcp_fin_sent.
19971 					 * This is essentially the same as
19972 					 * setting it to tcp_fss + 1.
19973 					 */
19974 				}
19975 			}
19976 
19977 			tcp->tcp_last_sent_len = (ushort_t)len;
19978 
19979 			len += tcp_hdr_len;
19980 			if (tcp->tcp_ipversion == IPV4_VERSION)
19981 				tcp->tcp_ipha->ipha_length = htons(len);
19982 			else
19983 				tcp->tcp_ip6h->ip6_plen = htons(len -
19984 				    ((char *)&tcp->tcp_ip6h[1] -
19985 				    tcp->tcp_iphc));
19986 
19987 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19988 
19989 			/* setup header fragment */
19990 			PDESC_HDR_ADD(pkt_info,
19991 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19992 			    tcp->tcp_mdt_hdr_head,		/* head room */
19993 			    tcp_hdr_len,			/* len */
19994 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19995 
19996 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
19997 			    hdr_frag_sz);
19998 			ASSERT(MBLKIN(md_hbuf,
19999 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20000 			    PDESC_HDRSIZE(pkt_info)));
20001 
20002 			/* setup first payload fragment */
20003 			PDESC_PLD_INIT(pkt_info);
20004 			PDESC_PLD_SPAN_ADD(pkt_info,
20005 			    pbuf_idx,				/* index */
20006 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20007 			    tcp->tcp_last_sent_len);		/* len */
20008 
20009 			/* create a split-packet in case of a spillover */
20010 			if (md_pbuf_nxt != NULL) {
20011 				ASSERT(spill > 0);
20012 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20013 				ASSERT(!add_buffer);
20014 
20015 				md_pbuf = md_pbuf_nxt;
20016 				md_pbuf_nxt = NULL;
20017 				pbuf_idx = pbuf_idx_nxt;
20018 				pbuf_idx_nxt = -1;
20019 				cur_pld_off = spill;
20020 
20021 				/* trim out first payload fragment */
20022 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20023 
20024 				/* setup second payload fragment */
20025 				PDESC_PLD_SPAN_ADD(pkt_info,
20026 				    pbuf_idx,			/* index */
20027 				    md_pbuf->b_rptr,		/* start */
20028 				    spill);			/* len */
20029 
20030 				if ((*xmit_tail)->b_next == NULL) {
20031 					/*
20032 					 * Store the lbolt used for RTT
20033 					 * estimation. We can only record one
20034 					 * timestamp per mblk so we do it when
20035 					 * we reach the end of the payload
20036 					 * buffer.  Also we only take a new
20037 					 * timestamp sample when the previous
20038 					 * timed data from the same mblk has
20039 					 * been ack'ed.
20040 					 */
20041 					(*xmit_tail)->b_prev = local_time;
20042 					(*xmit_tail)->b_next =
20043 					    (mblk_t *)(uintptr_t)first_snxt;
20044 				}
20045 
20046 				first_snxt = *snxt - spill;
20047 
20048 				/*
20049 				 * Advance xmit_tail; usable could be 0 by
20050 				 * the time we got here, but we made sure
20051 				 * above that we would only spillover to
20052 				 * the next data block if usable includes
20053 				 * the spilled-over amount prior to the
20054 				 * subtraction.  Therefore, we are sure
20055 				 * that xmit_tail->b_cont can't be NULL.
20056 				 */
20057 				ASSERT((*xmit_tail)->b_cont != NULL);
20058 				*xmit_tail = (*xmit_tail)->b_cont;
20059 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20060 				    (uintptr_t)INT_MAX);
20061 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20062 			} else {
20063 				cur_pld_off += tcp->tcp_last_sent_len;
20064 			}
20065 
20066 			/*
20067 			 * Fill in the header using the template header, and
20068 			 * add options such as time-stamp, ECN and/or SACK,
20069 			 * as needed.
20070 			 */
20071 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20072 			    (clock_t)local_time, num_sack_blk);
20073 
20074 			/* take care of some IP header businesses */
20075 			if (af == AF_INET) {
20076 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20077 
20078 				ASSERT(OK_32PTR((uchar_t *)ipha));
20079 				ASSERT(PDESC_HDRL(pkt_info) >=
20080 				    IP_SIMPLE_HDR_LENGTH);
20081 				ASSERT(ipha->ipha_version_and_hdr_length ==
20082 				    IP_SIMPLE_HDR_VERSION);
20083 
20084 				/*
20085 				 * Assign ident value for current packet; see
20086 				 * related comments in ip_wput_ire() about the
20087 				 * contract private interface with clustering
20088 				 * group.
20089 				 */
20090 				clusterwide = B_FALSE;
20091 				if (cl_inet_ipident != NULL) {
20092 					ASSERT(cl_inet_isclusterwide != NULL);
20093 					if ((*cl_inet_isclusterwide)(stack_id,
20094 					    IPPROTO_IP, AF_INET,
20095 					    (uint8_t *)(uintptr_t)src, NULL)) {
20096 						ipha->ipha_ident =
20097 						    (*cl_inet_ipident)(stack_id,
20098 						    IPPROTO_IP, AF_INET,
20099 						    (uint8_t *)(uintptr_t)src,
20100 						    (uint8_t *)(uintptr_t)dst,
20101 						    NULL);
20102 						clusterwide = B_TRUE;
20103 					}
20104 				}
20105 
20106 				if (!clusterwide) {
20107 					ipha->ipha_ident = (uint16_t)
20108 					    atomic_add_32_nv(
20109 						&ire->ire_ident, 1);
20110 				}
20111 #ifndef _BIG_ENDIAN
20112 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20113 				    (ipha->ipha_ident >> 8);
20114 #endif
20115 			} else {
20116 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20117 
20118 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20119 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20120 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20121 				ASSERT(PDESC_HDRL(pkt_info) >=
20122 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20123 				    TCP_CHECKSUM_SIZE));
20124 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20125 
20126 				if (tcp->tcp_ip_forward_progress) {
20127 					rconfirm = B_TRUE;
20128 					tcp->tcp_ip_forward_progress = B_FALSE;
20129 				}
20130 			}
20131 
20132 			/* at least one payload span, and at most two */
20133 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20134 
20135 			/* add the packet descriptor to Multidata */
20136 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20137 			    KM_NOSLEEP)) == NULL) {
20138 				/*
20139 				 * Any failure other than ENOMEM indicates
20140 				 * that we have passed in invalid pkt_info
20141 				 * or parameters to mmd_addpdesc, which must
20142 				 * not happen.
20143 				 *
20144 				 * EINVAL is a result of failure on boundary
20145 				 * checks against the pkt_info contents.  It
20146 				 * should not happen, and we panic because
20147 				 * either there's horrible heap corruption,
20148 				 * and/or programming mistake.
20149 				 */
20150 				if (err != ENOMEM) {
20151 					cmn_err(CE_PANIC, "tcp_multisend: "
20152 					    "pdesc logic error detected for "
20153 					    "tcp %p mmd %p pinfo %p (%d)\n",
20154 					    (void *)tcp, (void *)mmd,
20155 					    (void *)pkt_info, err);
20156 				}
20157 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20158 				goto legacy_send; /* out_of_mem */
20159 			}
20160 			ASSERT(pkt != NULL);
20161 
20162 			/* calculate IP header and TCP checksums */
20163 			if (af == AF_INET) {
20164 				/* calculate pseudo-header checksum */
20165 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20166 				    (src >> 16) + (src & 0xFFFF);
20167 
20168 				/* offset for TCP header checksum */
20169 				up = IPH_TCPH_CHECKSUMP(ipha,
20170 				    IP_SIMPLE_HDR_LENGTH);
20171 			} else {
20172 				up = (uint16_t *)&ip6h->ip6_src;
20173 
20174 				/* calculate pseudo-header checksum */
20175 				cksum = up[0] + up[1] + up[2] + up[3] +
20176 				    up[4] + up[5] + up[6] + up[7] +
20177 				    up[8] + up[9] + up[10] + up[11] +
20178 				    up[12] + up[13] + up[14] + up[15];
20179 
20180 				/* Fold the initial sum */
20181 				cksum = (cksum & 0xffff) + (cksum >> 16);
20182 
20183 				up = (uint16_t *)(((uchar_t *)ip6h) +
20184 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20185 			}
20186 
20187 			if (hwcksum_flags & HCK_FULLCKSUM) {
20188 				/* clear checksum field for hardware */
20189 				*up = 0;
20190 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20191 				uint32_t sum;
20192 
20193 				/* pseudo-header checksumming */
20194 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20195 				sum = (sum & 0xFFFF) + (sum >> 16);
20196 				*up = (sum & 0xFFFF) + (sum >> 16);
20197 			} else {
20198 				/* software checksumming */
20199 				TCP_STAT(tcps, tcp_out_sw_cksum);
20200 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20201 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20202 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20203 				    cksum + IP_TCP_CSUM_COMP);
20204 				if (*up == 0)
20205 					*up = 0xFFFF;
20206 			}
20207 
20208 			/* IPv4 header checksum */
20209 			if (af == AF_INET) {
20210 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20211 					ipha->ipha_hdr_checksum = 0;
20212 				} else {
20213 					IP_HDR_CKSUM(ipha, cksum,
20214 					    ((uint32_t *)ipha)[0],
20215 					    ((uint16_t *)ipha)[4]);
20216 				}
20217 			}
20218 
20219 			if (af == AF_INET &&
20220 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20221 			    af == AF_INET6 &&
20222 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20223 				mblk_t	*mp, *mp1;
20224 				uchar_t	*hdr_rptr, *hdr_wptr;
20225 				uchar_t	*pld_rptr, *pld_wptr;
20226 
20227 				/*
20228 				 * We reconstruct a pseudo packet for the hooks
20229 				 * framework using mmd_transform_link().
20230 				 * If it is a split packet we pullup the
20231 				 * payload. FW_HOOKS expects a pkt comprising
20232 				 * of two mblks: a header and the payload.
20233 				 */
20234 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20235 					TCP_STAT(tcps, tcp_mdt_allocfail);
20236 					goto legacy_send;
20237 				}
20238 
20239 				if (pkt_info->pld_cnt > 1) {
20240 					/* split payload, more than one pld */
20241 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20242 					    NULL) {
20243 						freemsg(mp);
20244 						TCP_STAT(tcps,
20245 						    tcp_mdt_allocfail);
20246 						goto legacy_send;
20247 					}
20248 					freemsg(mp->b_cont);
20249 					mp->b_cont = mp1;
20250 				} else {
20251 					mp1 = mp->b_cont;
20252 				}
20253 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20254 
20255 				/*
20256 				 * Remember the message offsets. This is so we
20257 				 * can detect changes when we return from the
20258 				 * FW_HOOKS callbacks.
20259 				 */
20260 				hdr_rptr = mp->b_rptr;
20261 				hdr_wptr = mp->b_wptr;
20262 				pld_rptr = mp->b_cont->b_rptr;
20263 				pld_wptr = mp->b_cont->b_wptr;
20264 
20265 				if (af == AF_INET) {
20266 					DTRACE_PROBE4(
20267 					    ip4__physical__out__start,
20268 					    ill_t *, NULL,
20269 					    ill_t *, ill,
20270 					    ipha_t *, ipha,
20271 					    mblk_t *, mp);
20272 					FW_HOOKS(
20273 					    ipst->ips_ip4_physical_out_event,
20274 					    ipst->ips_ipv4firewall_physical_out,
20275 					    NULL, ill, ipha, mp, mp, 0, ipst);
20276 					DTRACE_PROBE1(
20277 					    ip4__physical__out__end,
20278 					    mblk_t *, mp);
20279 				} else {
20280 					DTRACE_PROBE4(
20281 					    ip6__physical__out_start,
20282 					    ill_t *, NULL,
20283 					    ill_t *, ill,
20284 					    ip6_t *, ip6h,
20285 					    mblk_t *, mp);
20286 					FW_HOOKS6(
20287 					    ipst->ips_ip6_physical_out_event,
20288 					    ipst->ips_ipv6firewall_physical_out,
20289 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20290 					DTRACE_PROBE1(
20291 					    ip6__physical__out__end,
20292 					    mblk_t *, mp);
20293 				}
20294 
20295 				if (mp == NULL ||
20296 				    (mp1 = mp->b_cont) == NULL ||
20297 				    mp->b_rptr != hdr_rptr ||
20298 				    mp->b_wptr != hdr_wptr ||
20299 				    mp1->b_rptr != pld_rptr ||
20300 				    mp1->b_wptr != pld_wptr ||
20301 				    mp1->b_cont != NULL) {
20302 					/*
20303 					 * We abandon multidata processing and
20304 					 * return to the normal path, either
20305 					 * when a packet is blocked, or when
20306 					 * the boundaries of header buffer or
20307 					 * payload buffer have been changed by
20308 					 * FW_HOOKS[6].
20309 					 */
20310 					if (mp != NULL)
20311 						freemsg(mp);
20312 					goto legacy_send;
20313 				}
20314 				/* Finished with the pseudo packet */
20315 				freemsg(mp);
20316 			}
20317 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
20318 			    ill, ipha, ip6h);
20319 			/* advance header offset */
20320 			cur_hdr_off += hdr_frag_sz;
20321 
20322 			obbytes += tcp->tcp_last_sent_len;
20323 			++obsegs;
20324 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20325 		    *tail_unsent > 0);
20326 
20327 		if ((*xmit_tail)->b_next == NULL) {
20328 			/*
20329 			 * Store the lbolt used for RTT estimation. We can only
20330 			 * record one timestamp per mblk so we do it when we
20331 			 * reach the end of the payload buffer. Also we only
20332 			 * take a new timestamp sample when the previous timed
20333 			 * data from the same mblk has been ack'ed.
20334 			 */
20335 			(*xmit_tail)->b_prev = local_time;
20336 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20337 		}
20338 
20339 		ASSERT(*tail_unsent >= 0);
20340 		if (*tail_unsent > 0) {
20341 			/*
20342 			 * We got here because we broke out of the above
20343 			 * loop due to of one of the following cases:
20344 			 *
20345 			 *   1. len < adjusted MSS (i.e. small),
20346 			 *   2. Sender SWS avoidance,
20347 			 *   3. max_pld is zero.
20348 			 *
20349 			 * We are done for this Multidata, so trim our
20350 			 * last payload buffer (if any) accordingly.
20351 			 */
20352 			if (md_pbuf != NULL)
20353 				md_pbuf->b_wptr -= *tail_unsent;
20354 		} else if (*usable > 0) {
20355 			*xmit_tail = (*xmit_tail)->b_cont;
20356 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20357 			    (uintptr_t)INT_MAX);
20358 			*tail_unsent = (int)MBLKL(*xmit_tail);
20359 			add_buffer = B_TRUE;
20360 		}
20361 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20362 	    (tcp_mdt_chain || max_pld > 0));
20363 
20364 	if (md_mp_head != NULL) {
20365 		/* send everything down */
20366 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20367 		    &rconfirm);
20368 	}
20369 
20370 #undef PREP_NEW_MULTIDATA
20371 #undef PREP_NEW_PBUF
20372 #undef IPVER
20373 
20374 	IRE_REFRELE(ire);
20375 	return (0);
20376 }
20377 
20378 /*
20379  * A wrapper function for sending one or more Multidata messages down to
20380  * the module below ip; this routine does not release the reference of the
20381  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20382  */
20383 static void
20384 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20385     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20386 {
20387 	uint64_t delta;
20388 	nce_t *nce;
20389 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20390 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20391 
20392 	ASSERT(ire != NULL && ill != NULL);
20393 	ASSERT(ire->ire_stq != NULL);
20394 	ASSERT(md_mp_head != NULL);
20395 	ASSERT(rconfirm != NULL);
20396 
20397 	/* adjust MIBs and IRE timestamp */
20398 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
20399 	tcp->tcp_obsegs += obsegs;
20400 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20401 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20402 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20403 
20404 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20405 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20406 	} else {
20407 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20408 	}
20409 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20410 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20411 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20412 
20413 	ire->ire_ob_pkt_count += obsegs;
20414 	if (ire->ire_ipif != NULL)
20415 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20416 	ire->ire_last_used_time = lbolt;
20417 
20418 	if (ipst->ips_ipobs_enabled) {
20419 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
20420 		pdesc_t *dl_pkt;
20421 		pdescinfo_t pinfo;
20422 		mblk_t *nmp;
20423 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
20424 
20425 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
20426 		    (dl_pkt != NULL);
20427 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
20428 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
20429 				continue;
20430 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
20431 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
20432 			freemsg(nmp);
20433 		}
20434 	}
20435 
20436 	/* send it down */
20437 	putnext(ire->ire_stq, md_mp_head);
20438 
20439 	/* we're done for TCP/IPv4 */
20440 	if (tcp->tcp_ipversion == IPV4_VERSION)
20441 		return;
20442 
20443 	nce = ire->ire_nce;
20444 
20445 	ASSERT(nce != NULL);
20446 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20447 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20448 
20449 	/* reachability confirmation? */
20450 	if (*rconfirm) {
20451 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20452 		if (nce->nce_state != ND_REACHABLE) {
20453 			mutex_enter(&nce->nce_lock);
20454 			nce->nce_state = ND_REACHABLE;
20455 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20456 			mutex_exit(&nce->nce_lock);
20457 			(void) untimeout(nce->nce_timeout_id);
20458 			if (ip_debug > 2) {
20459 				/* ip1dbg */
20460 				pr_addr_dbg("tcp_multisend_data: state "
20461 				    "for %s changed to REACHABLE\n",
20462 				    AF_INET6, &ire->ire_addr_v6);
20463 			}
20464 		}
20465 		/* reset transport reachability confirmation */
20466 		*rconfirm = B_FALSE;
20467 	}
20468 
20469 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20470 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20471 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20472 
20473 	if (delta > (uint64_t)ill->ill_reachable_time) {
20474 		mutex_enter(&nce->nce_lock);
20475 		switch (nce->nce_state) {
20476 		case ND_REACHABLE:
20477 		case ND_STALE:
20478 			/*
20479 			 * ND_REACHABLE is identical to ND_STALE in this
20480 			 * specific case. If reachable time has expired for
20481 			 * this neighbor (delta is greater than reachable
20482 			 * time), conceptually, the neighbor cache is no
20483 			 * longer in REACHABLE state, but already in STALE
20484 			 * state.  So the correct transition here is to
20485 			 * ND_DELAY.
20486 			 */
20487 			nce->nce_state = ND_DELAY;
20488 			mutex_exit(&nce->nce_lock);
20489 			NDP_RESTART_TIMER(nce,
20490 			    ipst->ips_delay_first_probe_time);
20491 			if (ip_debug > 3) {
20492 				/* ip2dbg */
20493 				pr_addr_dbg("tcp_multisend_data: state "
20494 				    "for %s changed to DELAY\n",
20495 				    AF_INET6, &ire->ire_addr_v6);
20496 			}
20497 			break;
20498 		case ND_DELAY:
20499 		case ND_PROBE:
20500 			mutex_exit(&nce->nce_lock);
20501 			/* Timers have already started */
20502 			break;
20503 		case ND_UNREACHABLE:
20504 			/*
20505 			 * ndp timer has detected that this nce is
20506 			 * unreachable and initiated deleting this nce
20507 			 * and all its associated IREs. This is a race
20508 			 * where we found the ire before it was deleted
20509 			 * and have just sent out a packet using this
20510 			 * unreachable nce.
20511 			 */
20512 			mutex_exit(&nce->nce_lock);
20513 			break;
20514 		default:
20515 			ASSERT(0);
20516 		}
20517 	}
20518 }
20519 
20520 /*
20521  * Derived from tcp_send_data().
20522  */
20523 static void
20524 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20525     int num_lso_seg)
20526 {
20527 	ipha_t		*ipha;
20528 	mblk_t		*ire_fp_mp;
20529 	uint_t		ire_fp_mp_len;
20530 	uint32_t	hcksum_txflags = 0;
20531 	ipaddr_t	src;
20532 	ipaddr_t	dst;
20533 	uint32_t	cksum;
20534 	uint16_t	*up;
20535 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20536 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20537 
20538 	ASSERT(DB_TYPE(mp) == M_DATA);
20539 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20540 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20541 	ASSERT(tcp->tcp_connp != NULL);
20542 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20543 
20544 	ipha = (ipha_t *)mp->b_rptr;
20545 	src = ipha->ipha_src;
20546 	dst = ipha->ipha_dst;
20547 
20548 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
20549 
20550 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20551 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20552 	    num_lso_seg);
20553 #ifndef _BIG_ENDIAN
20554 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20555 #endif
20556 	if (tcp->tcp_snd_zcopy_aware) {
20557 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20558 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20559 			mp = tcp_zcopy_disable(tcp, mp);
20560 	}
20561 
20562 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20563 		ASSERT(ill->ill_hcksum_capab != NULL);
20564 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20565 	}
20566 
20567 	/*
20568 	 * Since the TCP checksum should be recalculated by h/w, we can just
20569 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20570 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20571 	 * The partial pseudo-header excludes TCP length, that was calculated
20572 	 * in tcp_send(), so to zero *up before further processing.
20573 	 */
20574 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20575 
20576 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20577 	*up = 0;
20578 
20579 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20580 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20581 
20582 	/*
20583 	 * Append LSO flags and mss to the mp.
20584 	 */
20585 	lso_info_set(mp, mss, HW_LSO);
20586 
20587 	ipha->ipha_fragment_offset_and_flags |=
20588 	    (uint32_t)htons(ire->ire_frag_flag);
20589 
20590 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20591 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20592 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20593 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20594 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20595 
20596 	UPDATE_OB_PKT_COUNT(ire);
20597 	ire->ire_last_used_time = lbolt;
20598 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20599 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20600 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20601 	    ntohs(ipha->ipha_length));
20602 
20603 	DTRACE_PROBE4(ip4__physical__out__start,
20604 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
20605 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
20606 	    ipst->ips_ipv4firewall_physical_out, NULL,
20607 	    ill, ipha, mp, mp, 0, ipst);
20608 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20609 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
20610 
20611 	if (mp != NULL) {
20612 		if (ipst->ips_ipobs_enabled) {
20613 			zoneid_t szone;
20614 
20615 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
20616 			    ipst, ALL_ZONES);
20617 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
20618 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
20619 		}
20620 
20621 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
20622 	}
20623 }
20624 
20625 /*
20626  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20627  * scheme, and returns one of the following:
20628  *
20629  * -1 = failed allocation.
20630  *  0 = success; burst count reached, or usable send window is too small,
20631  *      and that we'd rather wait until later before sending again.
20632  *  1 = success; we are called from tcp_multisend(), and both usable send
20633  *      window and tail_unsent are greater than the MDT threshold, and thus
20634  *      Multidata Transmit should be used instead.
20635  */
20636 static int
20637 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20638     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20639     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20640     const int mdt_thres)
20641 {
20642 	int num_burst_seg = tcp->tcp_snd_burst;
20643 	ire_t		*ire = NULL;
20644 	ill_t		*ill = NULL;
20645 	mblk_t		*ire_fp_mp = NULL;
20646 	uint_t		ire_fp_mp_len = 0;
20647 	int		num_lso_seg = 1;
20648 	uint_t		lso_usable;
20649 	boolean_t	do_lso_send = B_FALSE;
20650 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20651 
20652 	/*
20653 	 * Check LSO capability before any further work. And the similar check
20654 	 * need to be done in for(;;) loop.
20655 	 * LSO will be deployed when therer is more than one mss of available
20656 	 * data and a burst transmission is allowed.
20657 	 */
20658 	if (tcp->tcp_lso &&
20659 	    (tcp->tcp_valid_bits == 0 ||
20660 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20661 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20662 		/*
20663 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20664 		 * Double check LSO usability before going further, since the
20665 		 * underlying interface could have been changed. In case of any
20666 		 * change of LSO capability, set tcp_ire_ill_check_done to
20667 		 * B_FALSE to force to check the ILL with the next send.
20668 		 */
20669 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
20670 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
20671 			/*
20672 			 * Enable LSO with this transmission.
20673 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
20674 			 * IRE_REFRELE(ire) should be called before return.
20675 			 */
20676 			do_lso_send = B_TRUE;
20677 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
20678 			ire_fp_mp_len = MBLKL(ire_fp_mp);
20679 			/* Round up to multiple of 4 */
20680 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
20681 		} else {
20682 			tcp->tcp_lso = B_FALSE;
20683 			tcp->tcp_ire_ill_check_done = B_FALSE;
20684 			do_lso_send = B_FALSE;
20685 			ill = NULL;
20686 		}
20687 	}
20688 
20689 	for (;;) {
20690 		struct datab	*db;
20691 		tcph_t		*tcph;
20692 		uint32_t	sum;
20693 		mblk_t		*mp, *mp1;
20694 		uchar_t		*rptr;
20695 		int		len;
20696 
20697 		/*
20698 		 * If we're called by tcp_multisend(), and the amount of
20699 		 * sendable data as well as the size of current xmit_tail
20700 		 * is beyond the MDT threshold, return to the caller and
20701 		 * let the large data transmit be done using MDT.
20702 		 */
20703 		if (*usable > 0 && *usable > mdt_thres &&
20704 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20705 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20706 			ASSERT(tcp->tcp_mdt);
20707 			return (1);	/* success; do large send */
20708 		}
20709 
20710 		if (num_burst_seg == 0)
20711 			break;		/* success; burst count reached */
20712 
20713 		/*
20714 		 * Calculate the maximum payload length we can send in *one*
20715 		 * time.
20716 		 */
20717 		if (do_lso_send) {
20718 			/*
20719 			 * Check whether need to do LSO any more.
20720 			 */
20721 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20722 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
20723 				lso_usable = MIN(lso_usable,
20724 				    num_burst_seg * mss);
20725 
20726 				num_lso_seg = lso_usable / mss;
20727 				if (lso_usable % mss) {
20728 					num_lso_seg++;
20729 					tcp->tcp_last_sent_len = (ushort_t)
20730 					    (lso_usable % mss);
20731 				} else {
20732 					tcp->tcp_last_sent_len = (ushort_t)mss;
20733 				}
20734 			} else {
20735 				do_lso_send = B_FALSE;
20736 				num_lso_seg = 1;
20737 				lso_usable = mss;
20738 			}
20739 		}
20740 
20741 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
20742 
20743 		/*
20744 		 * Adjust num_burst_seg here.
20745 		 */
20746 		num_burst_seg -= num_lso_seg;
20747 
20748 		len = mss;
20749 		if (len > *usable) {
20750 			ASSERT(do_lso_send == B_FALSE);
20751 
20752 			len = *usable;
20753 			if (len <= 0) {
20754 				/* Terminate the loop */
20755 				break;	/* success; too small */
20756 			}
20757 			/*
20758 			 * Sender silly-window avoidance.
20759 			 * Ignore this if we are going to send a
20760 			 * zero window probe out.
20761 			 *
20762 			 * TODO: force data into microscopic window?
20763 			 *	==> (!pushed || (unsent > usable))
20764 			 */
20765 			if (len < (tcp->tcp_max_swnd >> 1) &&
20766 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20767 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20768 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20769 				/*
20770 				 * If the retransmit timer is not running
20771 				 * we start it so that we will retransmit
20772 				 * in the case when the the receiver has
20773 				 * decremented the window.
20774 				 */
20775 				if (*snxt == tcp->tcp_snxt &&
20776 				    *snxt == tcp->tcp_suna) {
20777 					/*
20778 					 * We are not supposed to send
20779 					 * anything.  So let's wait a little
20780 					 * bit longer before breaking SWS
20781 					 * avoidance.
20782 					 *
20783 					 * What should the value be?
20784 					 * Suggestion: MAX(init rexmit time,
20785 					 * tcp->tcp_rto)
20786 					 */
20787 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20788 				}
20789 				break;	/* success; too small */
20790 			}
20791 		}
20792 
20793 		tcph = tcp->tcp_tcph;
20794 
20795 		/*
20796 		 * The reason to adjust len here is that we need to set flags
20797 		 * and calculate checksum.
20798 		 */
20799 		if (do_lso_send)
20800 			len = lso_usable;
20801 
20802 		*usable -= len; /* Approximate - can be adjusted later */
20803 		if (*usable > 0)
20804 			tcph->th_flags[0] = TH_ACK;
20805 		else
20806 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20807 
20808 		/*
20809 		 * Prime pump for IP's checksumming on our behalf
20810 		 * Include the adjustment for a source route if any.
20811 		 */
20812 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20813 		sum = (sum >> 16) + (sum & 0xFFFF);
20814 		U16_TO_ABE16(sum, tcph->th_sum);
20815 
20816 		U32_TO_ABE32(*snxt, tcph->th_seq);
20817 
20818 		/*
20819 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20820 		 * set.  For the case when TCP_FSS_VALID is the only valid
20821 		 * bit (normal active close), branch off only when we think
20822 		 * that the FIN flag needs to be set.  Note for this case,
20823 		 * that (snxt + len) may not reflect the actual seg_len,
20824 		 * as len may be further reduced in tcp_xmit_mp().  If len
20825 		 * gets modified, we will end up here again.
20826 		 */
20827 		if (tcp->tcp_valid_bits != 0 &&
20828 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20829 		    ((*snxt + len) == tcp->tcp_fss))) {
20830 			uchar_t		*prev_rptr;
20831 			uint32_t	prev_snxt = tcp->tcp_snxt;
20832 
20833 			if (*tail_unsent == 0) {
20834 				ASSERT((*xmit_tail)->b_cont != NULL);
20835 				*xmit_tail = (*xmit_tail)->b_cont;
20836 				prev_rptr = (*xmit_tail)->b_rptr;
20837 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20838 				    (*xmit_tail)->b_rptr);
20839 			} else {
20840 				prev_rptr = (*xmit_tail)->b_rptr;
20841 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20842 				    *tail_unsent;
20843 			}
20844 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20845 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20846 			/* Restore tcp_snxt so we get amount sent right. */
20847 			tcp->tcp_snxt = prev_snxt;
20848 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20849 				/*
20850 				 * If the previous timestamp is still in use,
20851 				 * don't stomp on it.
20852 				 */
20853 				if ((*xmit_tail)->b_next == NULL) {
20854 					(*xmit_tail)->b_prev = local_time;
20855 					(*xmit_tail)->b_next =
20856 					    (mblk_t *)(uintptr_t)(*snxt);
20857 				}
20858 			} else
20859 				(*xmit_tail)->b_rptr = prev_rptr;
20860 
20861 			if (mp == NULL) {
20862 				if (ire != NULL)
20863 					IRE_REFRELE(ire);
20864 				return (-1);
20865 			}
20866 			mp1 = mp->b_cont;
20867 
20868 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
20869 				tcp->tcp_last_sent_len = (ushort_t)len;
20870 			while (mp1->b_cont) {
20871 				*xmit_tail = (*xmit_tail)->b_cont;
20872 				(*xmit_tail)->b_prev = local_time;
20873 				(*xmit_tail)->b_next =
20874 				    (mblk_t *)(uintptr_t)(*snxt);
20875 				mp1 = mp1->b_cont;
20876 			}
20877 			*snxt += len;
20878 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20879 			BUMP_LOCAL(tcp->tcp_obsegs);
20880 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20881 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20882 			tcp_send_data(tcp, q, mp);
20883 			continue;
20884 		}
20885 
20886 		*snxt += len;	/* Adjust later if we don't send all of len */
20887 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20888 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20889 
20890 		if (*tail_unsent) {
20891 			/* Are the bytes above us in flight? */
20892 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20893 			if (rptr != (*xmit_tail)->b_rptr) {
20894 				*tail_unsent -= len;
20895 				if (len <= mss) /* LSO is unusable */
20896 					tcp->tcp_last_sent_len = (ushort_t)len;
20897 				len += tcp_hdr_len;
20898 				if (tcp->tcp_ipversion == IPV4_VERSION)
20899 					tcp->tcp_ipha->ipha_length = htons(len);
20900 				else
20901 					tcp->tcp_ip6h->ip6_plen =
20902 					    htons(len -
20903 					    ((char *)&tcp->tcp_ip6h[1] -
20904 					    tcp->tcp_iphc));
20905 				mp = dupb(*xmit_tail);
20906 				if (mp == NULL) {
20907 					if (ire != NULL)
20908 						IRE_REFRELE(ire);
20909 					return (-1);	/* out_of_mem */
20910 				}
20911 				mp->b_rptr = rptr;
20912 				/*
20913 				 * If the old timestamp is no longer in use,
20914 				 * sample a new timestamp now.
20915 				 */
20916 				if ((*xmit_tail)->b_next == NULL) {
20917 					(*xmit_tail)->b_prev = local_time;
20918 					(*xmit_tail)->b_next =
20919 					    (mblk_t *)(uintptr_t)(*snxt-len);
20920 				}
20921 				goto must_alloc;
20922 			}
20923 		} else {
20924 			*xmit_tail = (*xmit_tail)->b_cont;
20925 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20926 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20927 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20928 			    (*xmit_tail)->b_rptr);
20929 		}
20930 
20931 		(*xmit_tail)->b_prev = local_time;
20932 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20933 
20934 		*tail_unsent -= len;
20935 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
20936 			tcp->tcp_last_sent_len = (ushort_t)len;
20937 
20938 		len += tcp_hdr_len;
20939 		if (tcp->tcp_ipversion == IPV4_VERSION)
20940 			tcp->tcp_ipha->ipha_length = htons(len);
20941 		else
20942 			tcp->tcp_ip6h->ip6_plen = htons(len -
20943 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20944 
20945 		mp = dupb(*xmit_tail);
20946 		if (mp == NULL) {
20947 			if (ire != NULL)
20948 				IRE_REFRELE(ire);
20949 			return (-1);	/* out_of_mem */
20950 		}
20951 
20952 		len = tcp_hdr_len;
20953 		/*
20954 		 * There are four reasons to allocate a new hdr mblk:
20955 		 *  1) The bytes above us are in use by another packet
20956 		 *  2) We don't have good alignment
20957 		 *  3) The mblk is being shared
20958 		 *  4) We don't have enough room for a header
20959 		 */
20960 		rptr = mp->b_rptr - len;
20961 		if (!OK_32PTR(rptr) ||
20962 		    ((db = mp->b_datap), db->db_ref != 2) ||
20963 		    rptr < db->db_base + ire_fp_mp_len) {
20964 			/* NOTE: we assume allocb returns an OK_32PTR */
20965 
20966 		must_alloc:;
20967 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20968 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
20969 			if (mp1 == NULL) {
20970 				freemsg(mp);
20971 				if (ire != NULL)
20972 					IRE_REFRELE(ire);
20973 				return (-1);	/* out_of_mem */
20974 			}
20975 			mp1->b_cont = mp;
20976 			mp = mp1;
20977 			/* Leave room for Link Level header */
20978 			len = tcp_hdr_len;
20979 			rptr =
20980 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
20981 			mp->b_wptr = &rptr[len];
20982 		}
20983 
20984 		/*
20985 		 * Fill in the header using the template header, and add
20986 		 * options such as time-stamp, ECN and/or SACK, as needed.
20987 		 */
20988 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20989 
20990 		mp->b_rptr = rptr;
20991 
20992 		if (*tail_unsent) {
20993 			int spill = *tail_unsent;
20994 
20995 			mp1 = mp->b_cont;
20996 			if (mp1 == NULL)
20997 				mp1 = mp;
20998 
20999 			/*
21000 			 * If we're a little short, tack on more mblks until
21001 			 * there is no more spillover.
21002 			 */
21003 			while (spill < 0) {
21004 				mblk_t *nmp;
21005 				int nmpsz;
21006 
21007 				nmp = (*xmit_tail)->b_cont;
21008 				nmpsz = MBLKL(nmp);
21009 
21010 				/*
21011 				 * Excess data in mblk; can we split it?
21012 				 * If MDT is enabled for the connection,
21013 				 * keep on splitting as this is a transient
21014 				 * send path.
21015 				 */
21016 				if (!do_lso_send && !tcp->tcp_mdt &&
21017 				    (spill + nmpsz > 0)) {
21018 					/*
21019 					 * Don't split if stream head was
21020 					 * told to break up larger writes
21021 					 * into smaller ones.
21022 					 */
21023 					if (tcp->tcp_maxpsz > 0)
21024 						break;
21025 
21026 					/*
21027 					 * Next mblk is less than SMSS/2
21028 					 * rounded up to nearest 64-byte;
21029 					 * let it get sent as part of the
21030 					 * next segment.
21031 					 */
21032 					if (tcp->tcp_localnet &&
21033 					    !tcp->tcp_cork &&
21034 					    (nmpsz < roundup((mss >> 1), 64)))
21035 						break;
21036 				}
21037 
21038 				*xmit_tail = nmp;
21039 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21040 				/* Stash for rtt use later */
21041 				(*xmit_tail)->b_prev = local_time;
21042 				(*xmit_tail)->b_next =
21043 				    (mblk_t *)(uintptr_t)(*snxt - len);
21044 				mp1->b_cont = dupb(*xmit_tail);
21045 				mp1 = mp1->b_cont;
21046 
21047 				spill += nmpsz;
21048 				if (mp1 == NULL) {
21049 					*tail_unsent = spill;
21050 					freemsg(mp);
21051 					if (ire != NULL)
21052 						IRE_REFRELE(ire);
21053 					return (-1);	/* out_of_mem */
21054 				}
21055 			}
21056 
21057 			/* Trim back any surplus on the last mblk */
21058 			if (spill >= 0) {
21059 				mp1->b_wptr -= spill;
21060 				*tail_unsent = spill;
21061 			} else {
21062 				/*
21063 				 * We did not send everything we could in
21064 				 * order to remain within the b_cont limit.
21065 				 */
21066 				*usable -= spill;
21067 				*snxt += spill;
21068 				tcp->tcp_last_sent_len += spill;
21069 				UPDATE_MIB(&tcps->tcps_mib,
21070 				    tcpOutDataBytes, spill);
21071 				/*
21072 				 * Adjust the checksum
21073 				 */
21074 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21075 				sum += spill;
21076 				sum = (sum >> 16) + (sum & 0xFFFF);
21077 				U16_TO_ABE16(sum, tcph->th_sum);
21078 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21079 					sum = ntohs(
21080 					    ((ipha_t *)rptr)->ipha_length) +
21081 					    spill;
21082 					((ipha_t *)rptr)->ipha_length =
21083 					    htons(sum);
21084 				} else {
21085 					sum = ntohs(
21086 					    ((ip6_t *)rptr)->ip6_plen) +
21087 					    spill;
21088 					((ip6_t *)rptr)->ip6_plen =
21089 					    htons(sum);
21090 				}
21091 				*tail_unsent = 0;
21092 			}
21093 		}
21094 		if (tcp->tcp_ip_forward_progress) {
21095 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21096 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21097 			tcp->tcp_ip_forward_progress = B_FALSE;
21098 		}
21099 
21100 		if (do_lso_send) {
21101 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21102 			    num_lso_seg);
21103 			tcp->tcp_obsegs += num_lso_seg;
21104 
21105 			TCP_STAT(tcps, tcp_lso_times);
21106 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21107 		} else {
21108 			tcp_send_data(tcp, q, mp);
21109 			BUMP_LOCAL(tcp->tcp_obsegs);
21110 		}
21111 	}
21112 
21113 	if (ire != NULL)
21114 		IRE_REFRELE(ire);
21115 	return (0);
21116 }
21117 
21118 /* Unlink and return any mblk that looks like it contains a MDT info */
21119 static mblk_t *
21120 tcp_mdt_info_mp(mblk_t *mp)
21121 {
21122 	mblk_t	*prev_mp;
21123 
21124 	for (;;) {
21125 		prev_mp = mp;
21126 		/* no more to process? */
21127 		if ((mp = mp->b_cont) == NULL)
21128 			break;
21129 
21130 		switch (DB_TYPE(mp)) {
21131 		case M_CTL:
21132 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21133 				continue;
21134 			ASSERT(prev_mp != NULL);
21135 			prev_mp->b_cont = mp->b_cont;
21136 			mp->b_cont = NULL;
21137 			return (mp);
21138 		default:
21139 			break;
21140 		}
21141 	}
21142 	return (mp);
21143 }
21144 
21145 /* MDT info update routine, called when IP notifies us about MDT */
21146 static void
21147 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21148 {
21149 	boolean_t prev_state;
21150 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21151 
21152 	/*
21153 	 * IP is telling us to abort MDT on this connection?  We know
21154 	 * this because the capability is only turned off when IP
21155 	 * encounters some pathological cases, e.g. link-layer change
21156 	 * where the new driver doesn't support MDT, or in situation
21157 	 * where MDT usage on the link-layer has been switched off.
21158 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21159 	 * if the link-layer doesn't support MDT, and if it does, it
21160 	 * will indicate that the feature is to be turned on.
21161 	 */
21162 	prev_state = tcp->tcp_mdt;
21163 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21164 	if (!tcp->tcp_mdt && !first) {
21165 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21166 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21167 		    (void *)tcp->tcp_connp));
21168 	}
21169 
21170 	/*
21171 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21172 	 * so disable MDT otherwise.  The checks are done here
21173 	 * and in tcp_wput_data().
21174 	 */
21175 	if (tcp->tcp_mdt &&
21176 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21177 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21178 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21179 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21180 		tcp->tcp_mdt = B_FALSE;
21181 
21182 	if (tcp->tcp_mdt) {
21183 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21184 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21185 			    "version (%d), expected version is %d",
21186 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21187 			tcp->tcp_mdt = B_FALSE;
21188 			return;
21189 		}
21190 
21191 		/*
21192 		 * We need the driver to be able to handle at least three
21193 		 * spans per packet in order for tcp MDT to be utilized.
21194 		 * The first is for the header portion, while the rest are
21195 		 * needed to handle a packet that straddles across two
21196 		 * virtually non-contiguous buffers; a typical tcp packet
21197 		 * therefore consists of only two spans.  Note that we take
21198 		 * a zero as "don't care".
21199 		 */
21200 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21201 		    mdt_capab->ill_mdt_span_limit < 3) {
21202 			tcp->tcp_mdt = B_FALSE;
21203 			return;
21204 		}
21205 
21206 		/* a zero means driver wants default value */
21207 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21208 		    tcps->tcps_mdt_max_pbufs);
21209 		if (tcp->tcp_mdt_max_pld == 0)
21210 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21211 
21212 		/* ensure 32-bit alignment */
21213 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21214 		    mdt_capab->ill_mdt_hdr_head), 4);
21215 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21216 		    mdt_capab->ill_mdt_hdr_tail), 4);
21217 
21218 		if (!first && !prev_state) {
21219 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21220 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21221 			    (void *)tcp->tcp_connp));
21222 		}
21223 	}
21224 }
21225 
21226 /* Unlink and return any mblk that looks like it contains a LSO info */
21227 static mblk_t *
21228 tcp_lso_info_mp(mblk_t *mp)
21229 {
21230 	mblk_t	*prev_mp;
21231 
21232 	for (;;) {
21233 		prev_mp = mp;
21234 		/* no more to process? */
21235 		if ((mp = mp->b_cont) == NULL)
21236 			break;
21237 
21238 		switch (DB_TYPE(mp)) {
21239 		case M_CTL:
21240 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21241 				continue;
21242 			ASSERT(prev_mp != NULL);
21243 			prev_mp->b_cont = mp->b_cont;
21244 			mp->b_cont = NULL;
21245 			return (mp);
21246 		default:
21247 			break;
21248 		}
21249 	}
21250 
21251 	return (mp);
21252 }
21253 
21254 /* LSO info update routine, called when IP notifies us about LSO */
21255 static void
21256 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21257 {
21258 	tcp_stack_t *tcps = tcp->tcp_tcps;
21259 
21260 	/*
21261 	 * IP is telling us to abort LSO on this connection?  We know
21262 	 * this because the capability is only turned off when IP
21263 	 * encounters some pathological cases, e.g. link-layer change
21264 	 * where the new NIC/driver doesn't support LSO, or in situation
21265 	 * where LSO usage on the link-layer has been switched off.
21266 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21267 	 * if the link-layer doesn't support LSO, and if it does, it
21268 	 * will indicate that the feature is to be turned on.
21269 	 */
21270 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21271 	TCP_STAT(tcps, tcp_lso_enabled);
21272 
21273 	/*
21274 	 * We currently only support LSO on simple TCP/IPv4,
21275 	 * so disable LSO otherwise.  The checks are done here
21276 	 * and in tcp_wput_data().
21277 	 */
21278 	if (tcp->tcp_lso &&
21279 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21280 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21281 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21282 		tcp->tcp_lso = B_FALSE;
21283 		TCP_STAT(tcps, tcp_lso_disabled);
21284 	} else {
21285 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21286 		    lso_capab->ill_lso_max);
21287 	}
21288 }
21289 
21290 static void
21291 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21292 {
21293 	conn_t *connp = tcp->tcp_connp;
21294 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21295 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21296 
21297 	ASSERT(ire != NULL);
21298 
21299 	/*
21300 	 * We may be in the fastpath here, and although we essentially do
21301 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21302 	 * we try to keep things as brief as possible.  After all, these
21303 	 * are only best-effort checks, and we do more thorough ones prior
21304 	 * to calling tcp_send()/tcp_multisend().
21305 	 */
21306 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21307 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21308 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21309 	    !(ire->ire_flags & RTF_MULTIRT) &&
21310 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21311 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21312 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21313 			/* Cache the result */
21314 			connp->conn_lso_ok = B_TRUE;
21315 
21316 			ASSERT(ill->ill_lso_capab != NULL);
21317 			if (!ill->ill_lso_capab->ill_lso_on) {
21318 				ill->ill_lso_capab->ill_lso_on = 1;
21319 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21320 				    "LSO for interface %s\n", (void *)connp,
21321 				    ill->ill_name));
21322 			}
21323 			tcp_lso_update(tcp, ill->ill_lso_capab);
21324 		} else if (ipst->ips_ip_multidata_outbound &&
21325 		    ILL_MDT_CAPABLE(ill)) {
21326 			/* Cache the result */
21327 			connp->conn_mdt_ok = B_TRUE;
21328 
21329 			ASSERT(ill->ill_mdt_capab != NULL);
21330 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21331 				ill->ill_mdt_capab->ill_mdt_on = 1;
21332 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21333 				    "MDT for interface %s\n", (void *)connp,
21334 				    ill->ill_name));
21335 			}
21336 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21337 		}
21338 	}
21339 
21340 	/*
21341 	 * The goal is to reduce the number of generated tcp segments by
21342 	 * setting the maxpsz multiplier to 0; this will have an affect on
21343 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21344 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21345 	 * of outbound segments and incoming ACKs, thus allowing for better
21346 	 * network and system performance.  In contrast the legacy behavior
21347 	 * may result in sending less than SMSS size, because the last mblk
21348 	 * for some packets may have more data than needed to make up SMSS,
21349 	 * and the legacy code refused to "split" it.
21350 	 *
21351 	 * We apply the new behavior on following situations:
21352 	 *
21353 	 *   1) Loopback connections,
21354 	 *   2) Connections in which the remote peer is not on local subnet,
21355 	 *   3) Local subnet connections over the bge interface (see below).
21356 	 *
21357 	 * Ideally, we would like this behavior to apply for interfaces other
21358 	 * than bge.  However, doing so would negatively impact drivers which
21359 	 * perform dynamic mapping and unmapping of DMA resources, which are
21360 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21361 	 * packet will be generated by tcp).  The bge driver does not suffer
21362 	 * from this, as it copies the mblks into pre-mapped buffers, and
21363 	 * therefore does not require more I/O resources than before.
21364 	 *
21365 	 * Otherwise, this behavior is present on all network interfaces when
21366 	 * the destination endpoint is non-local, since reducing the number
21367 	 * of packets in general is good for the network.
21368 	 *
21369 	 * TODO We need to remove this hard-coded conditional for bge once
21370 	 *	a better "self-tuning" mechanism, or a way to comprehend
21371 	 *	the driver transmit strategy is devised.  Until the solution
21372 	 *	is found and well understood, we live with this hack.
21373 	 */
21374 	if (!tcp_static_maxpsz &&
21375 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21376 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21377 		/* override the default value */
21378 		tcp->tcp_maxpsz = 0;
21379 
21380 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21381 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21382 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21383 	}
21384 
21385 	/* set the stream head parameters accordingly */
21386 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21387 }
21388 
21389 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21390 static void
21391 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21392 {
21393 	uchar_t	fval = *mp->b_rptr;
21394 	mblk_t	*tail;
21395 	queue_t	*q = tcp->tcp_wq;
21396 
21397 	/* TODO: How should flush interact with urgent data? */
21398 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21399 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21400 		/*
21401 		 * Flush only data that has not yet been put on the wire.  If
21402 		 * we flush data that we have already transmitted, life, as we
21403 		 * know it, may come to an end.
21404 		 */
21405 		tail = tcp->tcp_xmit_tail;
21406 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21407 		tcp->tcp_xmit_tail_unsent = 0;
21408 		tcp->tcp_unsent = 0;
21409 		if (tail->b_wptr != tail->b_rptr)
21410 			tail = tail->b_cont;
21411 		if (tail) {
21412 			mblk_t **excess = &tcp->tcp_xmit_head;
21413 			for (;;) {
21414 				mblk_t *mp1 = *excess;
21415 				if (mp1 == tail)
21416 					break;
21417 				tcp->tcp_xmit_tail = mp1;
21418 				tcp->tcp_xmit_last = mp1;
21419 				excess = &mp1->b_cont;
21420 			}
21421 			*excess = NULL;
21422 			tcp_close_mpp(&tail);
21423 			if (tcp->tcp_snd_zcopy_aware)
21424 				tcp_zcopy_notify(tcp);
21425 		}
21426 		/*
21427 		 * We have no unsent data, so unsent must be less than
21428 		 * tcp_xmit_lowater, so re-enable flow.
21429 		 */
21430 		mutex_enter(&tcp->tcp_non_sq_lock);
21431 		if (tcp->tcp_flow_stopped) {
21432 			tcp_clrqfull(tcp);
21433 		}
21434 		mutex_exit(&tcp->tcp_non_sq_lock);
21435 	}
21436 	/*
21437 	 * TODO: you can't just flush these, you have to increase rwnd for one
21438 	 * thing.  For another, how should urgent data interact?
21439 	 */
21440 	if (fval & FLUSHR) {
21441 		*mp->b_rptr = fval & ~FLUSHW;
21442 		/* XXX */
21443 		qreply(q, mp);
21444 		return;
21445 	}
21446 	freemsg(mp);
21447 }
21448 
21449 /*
21450  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21451  * messages.
21452  */
21453 static void
21454 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21455 {
21456 	mblk_t	*mp1;
21457 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
21458 	STRUCT_HANDLE(strbuf, sb);
21459 	queue_t *q = tcp->tcp_wq;
21460 	int	error;
21461 	uint_t	addrlen;
21462 
21463 	/* Make sure it is one of ours. */
21464 	switch (iocp->ioc_cmd) {
21465 	case TI_GETMYNAME:
21466 	case TI_GETPEERNAME:
21467 		break;
21468 	default:
21469 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21470 		return;
21471 	}
21472 	switch (mi_copy_state(q, mp, &mp1)) {
21473 	case -1:
21474 		return;
21475 	case MI_COPY_CASE(MI_COPY_IN, 1):
21476 		break;
21477 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21478 		/* Copy out the strbuf. */
21479 		mi_copyout(q, mp);
21480 		return;
21481 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21482 		/* All done. */
21483 		mi_copy_done(q, mp, 0);
21484 		return;
21485 	default:
21486 		mi_copy_done(q, mp, EPROTO);
21487 		return;
21488 	}
21489 	/* Check alignment of the strbuf */
21490 	if (!OK_32PTR(mp1->b_rptr)) {
21491 		mi_copy_done(q, mp, EINVAL);
21492 		return;
21493 	}
21494 
21495 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
21496 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21497 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21498 		mi_copy_done(q, mp, EINVAL);
21499 		return;
21500 	}
21501 
21502 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21503 	if (mp1 == NULL)
21504 		return;
21505 
21506 	switch (iocp->ioc_cmd) {
21507 	case TI_GETMYNAME:
21508 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
21509 		break;
21510 	case TI_GETPEERNAME:
21511 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
21512 		break;
21513 	}
21514 
21515 	if (error != 0) {
21516 		mi_copy_done(q, mp, error);
21517 	} else {
21518 		mp1->b_wptr += addrlen;
21519 		STRUCT_FSET(sb, len, addrlen);
21520 
21521 		/* Copy out the address */
21522 		mi_copyout(q, mp);
21523 	}
21524 }
21525 
21526 static void
21527 tcp_disable_direct_sockfs(tcp_t *tcp)
21528 {
21529 #ifdef	_ILP32
21530 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
21531 #else
21532 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21533 #endif
21534 	/*
21535 	 * Insert this socket into the acceptor hash.
21536 	 * We might need it for T_CONN_RES message
21537 	 */
21538 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21539 
21540 	if (tcp->tcp_fused) {
21541 		/*
21542 		 * This is a fused loopback tcp; disable
21543 		 * read-side synchronous streams interface
21544 		 * and drain any queued data.  It is okay
21545 		 * to do this for non-synchronous streams
21546 		 * fused tcp as well.
21547 		 */
21548 		tcp_fuse_disable_pair(tcp, B_FALSE);
21549 	}
21550 	tcp->tcp_issocket = B_FALSE;
21551 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
21552 }
21553 
21554 /*
21555  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21556  * messages.
21557  */
21558 /* ARGSUSED */
21559 static void
21560 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21561 {
21562 	conn_t 	*connp = (conn_t *)arg;
21563 	tcp_t	*tcp = connp->conn_tcp;
21564 	queue_t	*q = tcp->tcp_wq;
21565 	struct iocblk	*iocp;
21566 
21567 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21568 	/*
21569 	 * Try and ASSERT the minimum possible references on the
21570 	 * conn early enough. Since we are executing on write side,
21571 	 * the connection is obviously not detached and that means
21572 	 * there is a ref each for TCP and IP. Since we are behind
21573 	 * the squeue, the minimum references needed are 3. If the
21574 	 * conn is in classifier hash list, there should be an
21575 	 * extra ref for that (we check both the possibilities).
21576 	 */
21577 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21578 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21579 
21580 	iocp = (struct iocblk *)mp->b_rptr;
21581 	switch (iocp->ioc_cmd) {
21582 	case TCP_IOC_DEFAULT_Q:
21583 		/* Wants to be the default wq. */
21584 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21585 			iocp->ioc_error = EPERM;
21586 			iocp->ioc_count = 0;
21587 			mp->b_datap->db_type = M_IOCACK;
21588 			qreply(q, mp);
21589 			return;
21590 		}
21591 		tcp_def_q_set(tcp, mp);
21592 		return;
21593 	case _SIOCSOCKFALLBACK:
21594 		/*
21595 		 * Either sockmod is about to be popped and the socket
21596 		 * would now be treated as a plain stream, or a module
21597 		 * is about to be pushed so we could no longer use read-
21598 		 * side synchronous streams for fused loopback tcp.
21599 		 * Drain any queued data and disable direct sockfs
21600 		 * interface from now on.
21601 		 */
21602 		if (!tcp->tcp_issocket) {
21603 			DB_TYPE(mp) = M_IOCNAK;
21604 			iocp->ioc_error = EINVAL;
21605 		} else {
21606 			tcp_disable_direct_sockfs(tcp);
21607 			DB_TYPE(mp) = M_IOCACK;
21608 			iocp->ioc_error = 0;
21609 		}
21610 		iocp->ioc_count = 0;
21611 		iocp->ioc_rval = 0;
21612 		qreply(q, mp);
21613 		return;
21614 	}
21615 	CALL_IP_WPUT(connp, q, mp);
21616 }
21617 
21618 /*
21619  * This routine is called by tcp_wput() to handle all TPI requests.
21620  */
21621 /* ARGSUSED */
21622 static void
21623 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21624 {
21625 	conn_t 	*connp = (conn_t *)arg;
21626 	tcp_t	*tcp = connp->conn_tcp;
21627 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21628 	uchar_t *rptr;
21629 	t_scalar_t type;
21630 	cred_t *cr;
21631 
21632 	/*
21633 	 * Try and ASSERT the minimum possible references on the
21634 	 * conn early enough. Since we are executing on write side,
21635 	 * the connection is obviously not detached and that means
21636 	 * there is a ref each for TCP and IP. Since we are behind
21637 	 * the squeue, the minimum references needed are 3. If the
21638 	 * conn is in classifier hash list, there should be an
21639 	 * extra ref for that (we check both the possibilities).
21640 	 */
21641 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21642 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21643 
21644 	rptr = mp->b_rptr;
21645 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21646 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21647 		type = ((union T_primitives *)rptr)->type;
21648 		if (type == T_EXDATA_REQ) {
21649 			tcp_output_urgent(connp, mp->b_cont, arg2);
21650 			freeb(mp);
21651 		} else if (type != T_DATA_REQ) {
21652 			goto non_urgent_data;
21653 		} else {
21654 			/* TODO: options, flags, ... from user */
21655 			/* Set length to zero for reclamation below */
21656 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21657 			freeb(mp);
21658 		}
21659 		return;
21660 	} else {
21661 		if (tcp->tcp_debug) {
21662 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21663 			    "tcp_wput_proto, dropping one...");
21664 		}
21665 		freemsg(mp);
21666 		return;
21667 	}
21668 
21669 non_urgent_data:
21670 
21671 	switch ((int)tprim->type) {
21672 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21673 		/*
21674 		 * save the kssl_ent_t from the next block, and convert this
21675 		 * back to a normal bind_req.
21676 		 */
21677 		if (mp->b_cont != NULL) {
21678 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21679 
21680 			if (tcp->tcp_kssl_ent != NULL) {
21681 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21682 				    KSSL_NO_PROXY);
21683 				tcp->tcp_kssl_ent = NULL;
21684 			}
21685 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21686 			    sizeof (kssl_ent_t));
21687 			kssl_hold_ent(tcp->tcp_kssl_ent);
21688 			freemsg(mp->b_cont);
21689 			mp->b_cont = NULL;
21690 		}
21691 		tprim->type = T_BIND_REQ;
21692 
21693 	/* FALLTHROUGH */
21694 	case O_T_BIND_REQ:	/* bind request */
21695 	case T_BIND_REQ:	/* new semantics bind request */
21696 		tcp_tpi_bind(tcp, mp);
21697 		break;
21698 	case T_UNBIND_REQ:	/* unbind request */
21699 		tcp_tpi_unbind(tcp, mp);
21700 		break;
21701 	case O_T_CONN_RES:	/* old connection response XXX */
21702 	case T_CONN_RES:	/* connection response */
21703 		tcp_tli_accept(tcp, mp);
21704 		break;
21705 	case T_CONN_REQ:	/* connection request */
21706 		tcp_tpi_connect(tcp, mp);
21707 		break;
21708 	case T_DISCON_REQ:	/* disconnect request */
21709 		tcp_disconnect(tcp, mp);
21710 		break;
21711 	case T_CAPABILITY_REQ:
21712 		tcp_capability_req(tcp, mp);	/* capability request */
21713 		break;
21714 	case T_INFO_REQ:	/* information request */
21715 		tcp_info_req(tcp, mp);
21716 		break;
21717 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21718 	case T_OPTMGMT_REQ:
21719 		/*
21720 		 * Note:  no support for snmpcom_req() through new
21721 		 * T_OPTMGMT_REQ. See comments in ip.c
21722 		 */
21723 
21724 		/*
21725 		 * All Solaris components should pass a db_credp
21726 		 * for this TPI message, hence we ASSERT.
21727 		 * But in case there is some other M_PROTO that looks
21728 		 * like a TPI message sent by some other kernel
21729 		 * component, we check and return an error.
21730 		 */
21731 		cr = msg_getcred(mp, NULL);
21732 		ASSERT(cr != NULL);
21733 		if (cr == NULL) {
21734 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
21735 			return;
21736 		}
21737 		/*
21738 		 * If EINPROGRESS is returned, the request has been queued
21739 		 * for subsequent processing by ip_restart_optmgmt(), which
21740 		 * will do the CONN_DEC_REF().
21741 		 */
21742 		CONN_INC_REF(connp);
21743 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
21744 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21745 			    B_TRUE) != EINPROGRESS) {
21746 				CONN_DEC_REF(connp);
21747 			}
21748 		} else {
21749 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21750 			    B_TRUE) != EINPROGRESS) {
21751 				CONN_DEC_REF(connp);
21752 			}
21753 		}
21754 		break;
21755 
21756 	case T_UNITDATA_REQ:	/* unitdata request */
21757 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21758 		break;
21759 	case T_ORDREL_REQ:	/* orderly release req */
21760 		freemsg(mp);
21761 
21762 		if (tcp->tcp_fused)
21763 			tcp_unfuse(tcp);
21764 
21765 		if (tcp_xmit_end(tcp) != 0) {
21766 			/*
21767 			 * We were crossing FINs and got a reset from
21768 			 * the other side. Just ignore it.
21769 			 */
21770 			if (tcp->tcp_debug) {
21771 				(void) strlog(TCP_MOD_ID, 0, 1,
21772 				    SL_ERROR|SL_TRACE,
21773 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21774 				    "state %s",
21775 				    tcp_display(tcp, NULL,
21776 				    DISP_ADDR_AND_PORT));
21777 			}
21778 		}
21779 		break;
21780 	case T_ADDR_REQ:
21781 		tcp_addr_req(tcp, mp);
21782 		break;
21783 	default:
21784 		if (tcp->tcp_debug) {
21785 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21786 			    "tcp_wput_proto, bogus TPI msg, type %d",
21787 			    tprim->type);
21788 		}
21789 		/*
21790 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21791 		 * to recover.
21792 		 */
21793 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21794 		break;
21795 	}
21796 }
21797 
21798 /*
21799  * The TCP write service routine should never be called...
21800  */
21801 /* ARGSUSED */
21802 static void
21803 tcp_wsrv(queue_t *q)
21804 {
21805 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
21806 
21807 	TCP_STAT(tcps, tcp_wsrv_called);
21808 }
21809 
21810 /* Non overlapping byte exchanger */
21811 static void
21812 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21813 {
21814 	uchar_t	uch;
21815 
21816 	while (len-- > 0) {
21817 		uch = a[len];
21818 		a[len] = b[len];
21819 		b[len] = uch;
21820 	}
21821 }
21822 
21823 /*
21824  * Send out a control packet on the tcp connection specified.  This routine
21825  * is typically called where we need a simple ACK or RST generated.
21826  */
21827 static void
21828 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21829 {
21830 	uchar_t		*rptr;
21831 	tcph_t		*tcph;
21832 	ipha_t		*ipha = NULL;
21833 	ip6_t		*ip6h = NULL;
21834 	uint32_t	sum;
21835 	int		tcp_hdr_len;
21836 	int		tcp_ip_hdr_len;
21837 	mblk_t		*mp;
21838 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21839 
21840 	/*
21841 	 * Save sum for use in source route later.
21842 	 */
21843 	ASSERT(tcp != NULL);
21844 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21845 	tcp_hdr_len = tcp->tcp_hdr_len;
21846 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21847 
21848 	/* If a text string is passed in with the request, pass it to strlog. */
21849 	if (str != NULL && tcp->tcp_debug) {
21850 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21851 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21852 		    str, seq, ack, ctl);
21853 	}
21854 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
21855 	    BPRI_MED);
21856 	if (mp == NULL) {
21857 		return;
21858 	}
21859 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
21860 	mp->b_rptr = rptr;
21861 	mp->b_wptr = &rptr[tcp_hdr_len];
21862 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21863 
21864 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21865 		ipha = (ipha_t *)rptr;
21866 		ipha->ipha_length = htons(tcp_hdr_len);
21867 	} else {
21868 		ip6h = (ip6_t *)rptr;
21869 		ASSERT(tcp != NULL);
21870 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21871 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21872 	}
21873 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21874 	tcph->th_flags[0] = (uint8_t)ctl;
21875 	if (ctl & TH_RST) {
21876 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
21877 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
21878 		/*
21879 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21880 		 */
21881 		if (tcp->tcp_snd_ts_ok &&
21882 		    tcp->tcp_state > TCPS_SYN_SENT) {
21883 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21884 			*(mp->b_wptr) = TCPOPT_EOL;
21885 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21886 				ipha->ipha_length = htons(tcp_hdr_len -
21887 				    TCPOPT_REAL_TS_LEN);
21888 			} else {
21889 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21890 				    TCPOPT_REAL_TS_LEN);
21891 			}
21892 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21893 			sum -= TCPOPT_REAL_TS_LEN;
21894 		}
21895 	}
21896 	if (ctl & TH_ACK) {
21897 		if (tcp->tcp_snd_ts_ok) {
21898 			U32_TO_BE32(lbolt,
21899 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21900 			U32_TO_BE32(tcp->tcp_ts_recent,
21901 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21902 		}
21903 
21904 		/* Update the latest receive window size in TCP header. */
21905 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21906 		    tcph->th_win);
21907 		tcp->tcp_rack = ack;
21908 		tcp->tcp_rack_cnt = 0;
21909 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
21910 	}
21911 	BUMP_LOCAL(tcp->tcp_obsegs);
21912 	U32_TO_BE32(seq, tcph->th_seq);
21913 	U32_TO_BE32(ack, tcph->th_ack);
21914 	/*
21915 	 * Include the adjustment for a source route if any.
21916 	 */
21917 	sum = (sum >> 16) + (sum & 0xFFFF);
21918 	U16_TO_BE16(sum, tcph->th_sum);
21919 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21920 }
21921 
21922 /*
21923  * If this routine returns B_TRUE, TCP can generate a RST in response
21924  * to a segment.  If it returns B_FALSE, TCP should not respond.
21925  */
21926 static boolean_t
21927 tcp_send_rst_chk(tcp_stack_t *tcps)
21928 {
21929 	clock_t	now;
21930 
21931 	/*
21932 	 * TCP needs to protect itself from generating too many RSTs.
21933 	 * This can be a DoS attack by sending us random segments
21934 	 * soliciting RSTs.
21935 	 *
21936 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21937 	 * in each 1 second interval.  In this way, TCP still generate
21938 	 * RSTs in normal cases but when under attack, the impact is
21939 	 * limited.
21940 	 */
21941 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
21942 		now = lbolt;
21943 		/* lbolt can wrap around. */
21944 		if ((tcps->tcps_last_rst_intrvl > now) ||
21945 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
21946 		    1*SECONDS)) {
21947 			tcps->tcps_last_rst_intrvl = now;
21948 			tcps->tcps_rst_cnt = 1;
21949 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
21950 			return (B_FALSE);
21951 		}
21952 	}
21953 	return (B_TRUE);
21954 }
21955 
21956 /*
21957  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21958  */
21959 static void
21960 tcp_ip_ire_mark_advice(tcp_t *tcp)
21961 {
21962 	mblk_t *mp;
21963 	ipic_t *ipic;
21964 
21965 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21966 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21967 		    &ipic);
21968 	} else {
21969 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21970 		    &ipic);
21971 	}
21972 	if (mp == NULL)
21973 		return;
21974 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21975 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21976 }
21977 
21978 /*
21979  * Return an IP advice ioctl mblk and set ipic to be the pointer
21980  * to the advice structure.
21981  */
21982 static mblk_t *
21983 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21984 {
21985 	struct iocblk *ioc;
21986 	mblk_t *mp, *mp1;
21987 
21988 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21989 	if (mp == NULL)
21990 		return (NULL);
21991 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21992 	*ipic = (ipic_t *)mp->b_rptr;
21993 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21994 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21995 
21996 	bcopy(addr, *ipic + 1, addr_len);
21997 
21998 	(*ipic)->ipic_addr_length = addr_len;
21999 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22000 
22001 	mp1 = mkiocb(IP_IOCTL);
22002 	if (mp1 == NULL) {
22003 		freemsg(mp);
22004 		return (NULL);
22005 	}
22006 	mp1->b_cont = mp;
22007 	ioc = (struct iocblk *)mp1->b_rptr;
22008 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22009 
22010 	return (mp1);
22011 }
22012 
22013 /*
22014  * Generate a reset based on an inbound packet, connp is set by caller
22015  * when RST is in response to an unexpected inbound packet for which
22016  * there is active tcp state in the system.
22017  *
22018  * IPSEC NOTE : Try to send the reply with the same protection as it came
22019  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22020  * the packet will go out at the same level of protection as it came in by
22021  * converting the IPSEC_IN to IPSEC_OUT.
22022  */
22023 static void
22024 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22025     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22026     tcp_stack_t *tcps, conn_t *connp)
22027 {
22028 	ipha_t		*ipha = NULL;
22029 	ip6_t		*ip6h = NULL;
22030 	ushort_t	len;
22031 	tcph_t		*tcph;
22032 	int		i;
22033 	mblk_t		*ipsec_mp;
22034 	boolean_t	mctl_present;
22035 	ipic_t		*ipic;
22036 	ipaddr_t	v4addr;
22037 	in6_addr_t	v6addr;
22038 	int		addr_len;
22039 	void		*addr;
22040 	queue_t		*q = tcps->tcps_g_q;
22041 	tcp_t		*tcp;
22042 	cred_t		*cr;
22043 	pid_t		pid;
22044 	mblk_t		*nmp;
22045 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22046 
22047 	if (tcps->tcps_g_q == NULL) {
22048 		/*
22049 		 * For non-zero stackids the default queue isn't created
22050 		 * until the first open, thus there can be a need to send
22051 		 * a reset before then. But we can't do that, hence we just
22052 		 * drop the packet. Later during boot, when the default queue
22053 		 * has been setup, a retransmitted packet from the peer
22054 		 * will result in a reset.
22055 		 */
22056 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22057 		    GLOBAL_NETSTACKID);
22058 		freemsg(mp);
22059 		return;
22060 	}
22061 
22062 	if (connp != NULL)
22063 		tcp = connp->conn_tcp;
22064 	else
22065 		tcp = Q_TO_TCP(q);
22066 
22067 	if (!tcp_send_rst_chk(tcps)) {
22068 		tcps->tcps_rst_unsent++;
22069 		freemsg(mp);
22070 		return;
22071 	}
22072 
22073 	if (mp->b_datap->db_type == M_CTL) {
22074 		ipsec_mp = mp;
22075 		mp = mp->b_cont;
22076 		mctl_present = B_TRUE;
22077 	} else {
22078 		ipsec_mp = mp;
22079 		mctl_present = B_FALSE;
22080 	}
22081 
22082 	if (str && q && tcps->tcps_dbg) {
22083 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22084 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22085 		    "flags 0x%x",
22086 		    str, seq, ack, ctl);
22087 	}
22088 	if (mp->b_datap->db_ref != 1) {
22089 		mblk_t *mp1 = copyb(mp);
22090 		freemsg(mp);
22091 		mp = mp1;
22092 		if (!mp) {
22093 			if (mctl_present)
22094 				freeb(ipsec_mp);
22095 			return;
22096 		} else {
22097 			if (mctl_present) {
22098 				ipsec_mp->b_cont = mp;
22099 			} else {
22100 				ipsec_mp = mp;
22101 			}
22102 		}
22103 	} else if (mp->b_cont) {
22104 		freemsg(mp->b_cont);
22105 		mp->b_cont = NULL;
22106 	}
22107 	/*
22108 	 * We skip reversing source route here.
22109 	 * (for now we replace all IP options with EOL)
22110 	 */
22111 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22112 		ipha = (ipha_t *)mp->b_rptr;
22113 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22114 			mp->b_rptr[i] = IPOPT_EOL;
22115 		/*
22116 		 * Make sure that src address isn't flagrantly invalid.
22117 		 * Not all broadcast address checking for the src address
22118 		 * is possible, since we don't know the netmask of the src
22119 		 * addr.  No check for destination address is done, since
22120 		 * IP will not pass up a packet with a broadcast dest
22121 		 * address to TCP.  Similar checks are done below for IPv6.
22122 		 */
22123 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22124 		    CLASSD(ipha->ipha_src)) {
22125 			freemsg(ipsec_mp);
22126 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22127 			return;
22128 		}
22129 	} else {
22130 		ip6h = (ip6_t *)mp->b_rptr;
22131 
22132 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22133 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22134 			freemsg(ipsec_mp);
22135 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22136 			return;
22137 		}
22138 
22139 		/* Remove any extension headers assuming partial overlay */
22140 		if (ip_hdr_len > IPV6_HDR_LEN) {
22141 			uint8_t *to;
22142 
22143 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22144 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22145 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22146 			ip_hdr_len = IPV6_HDR_LEN;
22147 			ip6h = (ip6_t *)mp->b_rptr;
22148 			ip6h->ip6_nxt = IPPROTO_TCP;
22149 		}
22150 	}
22151 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22152 	if (tcph->th_flags[0] & TH_RST) {
22153 		freemsg(ipsec_mp);
22154 		return;
22155 	}
22156 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22157 	len = ip_hdr_len + sizeof (tcph_t);
22158 	mp->b_wptr = &mp->b_rptr[len];
22159 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22160 		ipha->ipha_length = htons(len);
22161 		/* Swap addresses */
22162 		v4addr = ipha->ipha_src;
22163 		ipha->ipha_src = ipha->ipha_dst;
22164 		ipha->ipha_dst = v4addr;
22165 		ipha->ipha_ident = 0;
22166 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22167 		addr_len = IP_ADDR_LEN;
22168 		addr = &v4addr;
22169 	} else {
22170 		/* No ip6i_t in this case */
22171 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22172 		/* Swap addresses */
22173 		v6addr = ip6h->ip6_src;
22174 		ip6h->ip6_src = ip6h->ip6_dst;
22175 		ip6h->ip6_dst = v6addr;
22176 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22177 		addr_len = IPV6_ADDR_LEN;
22178 		addr = &v6addr;
22179 	}
22180 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22181 	U32_TO_BE32(ack, tcph->th_ack);
22182 	U32_TO_BE32(seq, tcph->th_seq);
22183 	U16_TO_BE16(0, tcph->th_win);
22184 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22185 	tcph->th_flags[0] = (uint8_t)ctl;
22186 	if (ctl & TH_RST) {
22187 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22188 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22189 	}
22190 
22191 	/* IP trusts us to set up labels when required. */
22192 	if (is_system_labeled() && (cr = msg_getcred(mp, &pid)) != NULL &&
22193 	    crgetlabel(cr) != NULL) {
22194 		int err;
22195 
22196 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22197 			err = tsol_check_label(cr, &mp,
22198 			    tcp->tcp_connp->conn_mac_exempt,
22199 			    tcps->tcps_netstack->netstack_ip, pid);
22200 		else
22201 			err = tsol_check_label_v6(cr, &mp,
22202 			    tcp->tcp_connp->conn_mac_exempt,
22203 			    tcps->tcps_netstack->netstack_ip, pid);
22204 		if (mctl_present)
22205 			ipsec_mp->b_cont = mp;
22206 		else
22207 			ipsec_mp = mp;
22208 		if (err != 0) {
22209 			freemsg(ipsec_mp);
22210 			return;
22211 		}
22212 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22213 			ipha = (ipha_t *)mp->b_rptr;
22214 		} else {
22215 			ip6h = (ip6_t *)mp->b_rptr;
22216 		}
22217 	}
22218 
22219 	if (mctl_present) {
22220 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22221 
22222 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22223 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22224 			return;
22225 		}
22226 	}
22227 	if (zoneid == ALL_ZONES)
22228 		zoneid = GLOBAL_ZONEID;
22229 
22230 	/* Add the zoneid so ip_output routes it properly */
22231 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22232 		freemsg(ipsec_mp);
22233 		return;
22234 	}
22235 	ipsec_mp = nmp;
22236 
22237 	/*
22238 	 * NOTE:  one might consider tracing a TCP packet here, but
22239 	 * this function has no active TCP state and no tcp structure
22240 	 * that has a trace buffer.  If we traced here, we would have
22241 	 * to keep a local trace buffer in tcp_record_trace().
22242 	 *
22243 	 * TSol note: The mblk that contains the incoming packet was
22244 	 * reused by tcp_xmit_listener_reset, so it already contains
22245 	 * the right credentials and we don't need to call mblk_setcred.
22246 	 * Also the conn's cred is not right since it is associated
22247 	 * with tcps_g_q.
22248 	 */
22249 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22250 
22251 	/*
22252 	 * Tell IP to mark the IRE used for this destination temporary.
22253 	 * This way, we can limit our exposure to DoS attack because IP
22254 	 * creates an IRE for each destination.  If there are too many,
22255 	 * the time to do any routing lookup will be extremely long.  And
22256 	 * the lookup can be in interrupt context.
22257 	 *
22258 	 * Note that in normal circumstances, this marking should not
22259 	 * affect anything.  It would be nice if only 1 message is
22260 	 * needed to inform IP that the IRE created for this RST should
22261 	 * not be added to the cache table.  But there is currently
22262 	 * not such communication mechanism between TCP and IP.  So
22263 	 * the best we can do now is to send the advice ioctl to IP
22264 	 * to mark the IRE temporary.
22265 	 */
22266 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22267 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22268 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22269 	}
22270 }
22271 
22272 /*
22273  * Initiate closedown sequence on an active connection.  (May be called as
22274  * writer.)  Return value zero for OK return, non-zero for error return.
22275  */
22276 static int
22277 tcp_xmit_end(tcp_t *tcp)
22278 {
22279 	ipic_t	*ipic;
22280 	mblk_t	*mp;
22281 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22282 
22283 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22284 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22285 		/*
22286 		 * Invalid state, only states TCPS_SYN_RCVD,
22287 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22288 		 */
22289 		return (-1);
22290 	}
22291 
22292 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22293 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22294 	/*
22295 	 * If there is nothing more unsent, send the FIN now.
22296 	 * Otherwise, it will go out with the last segment.
22297 	 */
22298 	if (tcp->tcp_unsent == 0) {
22299 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22300 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22301 
22302 		if (mp) {
22303 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22304 		} else {
22305 			/*
22306 			 * Couldn't allocate msg.  Pretend we got it out.
22307 			 * Wait for rexmit timeout.
22308 			 */
22309 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22310 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22311 		}
22312 
22313 		/*
22314 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22315 		 * changed.
22316 		 */
22317 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22318 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22319 		}
22320 	} else {
22321 		/*
22322 		 * If tcp->tcp_cork is set, then the data will not get sent,
22323 		 * so we have to check that and unset it first.
22324 		 */
22325 		if (tcp->tcp_cork)
22326 			tcp->tcp_cork = B_FALSE;
22327 		tcp_wput_data(tcp, NULL, B_FALSE);
22328 	}
22329 
22330 	/*
22331 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22332 	 * is 0, don't update the cache.
22333 	 */
22334 	if (tcps->tcps_rtt_updates == 0 ||
22335 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22336 		return (0);
22337 
22338 	/*
22339 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22340 	 * different from the destination.
22341 	 */
22342 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22343 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22344 			return (0);
22345 		}
22346 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22347 		    &ipic);
22348 	} else {
22349 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22350 		    &tcp->tcp_ip6h->ip6_dst))) {
22351 			return (0);
22352 		}
22353 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22354 		    &ipic);
22355 	}
22356 
22357 	/* Record route attributes in the IRE for use by future connections. */
22358 	if (mp == NULL)
22359 		return (0);
22360 
22361 	/*
22362 	 * We do not have a good algorithm to update ssthresh at this time.
22363 	 * So don't do any update.
22364 	 */
22365 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22366 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22367 
22368 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22369 
22370 	return (0);
22371 }
22372 
22373 /* ARGSUSED */
22374 void
22375 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
22376 {
22377 	conn_t *connp = (conn_t *)arg;
22378 	mblk_t *mp1;
22379 	tcp_t *tcp = connp->conn_tcp;
22380 	tcp_xmit_reset_event_t *eventp;
22381 
22382 	ASSERT(mp->b_datap->db_type == M_PROTO &&
22383 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
22384 
22385 	if (tcp->tcp_state != TCPS_LISTEN) {
22386 		freemsg(mp);
22387 		return;
22388 	}
22389 
22390 	mp1 = mp->b_cont;
22391 	mp->b_cont = NULL;
22392 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
22393 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
22394 	    connp->conn_netstack);
22395 
22396 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
22397 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
22398 	freemsg(mp);
22399 }
22400 
22401 /*
22402  * Generate a "no listener here" RST in response to an "unknown" segment.
22403  * connp is set by caller when RST is in response to an unexpected
22404  * inbound packet for which there is active tcp state in the system.
22405  * Note that we are reusing the incoming mp to construct the outgoing RST.
22406  */
22407 void
22408 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22409     tcp_stack_t *tcps, conn_t *connp)
22410 {
22411 	uchar_t		*rptr;
22412 	uint32_t	seg_len;
22413 	tcph_t		*tcph;
22414 	uint32_t	seg_seq;
22415 	uint32_t	seg_ack;
22416 	uint_t		flags;
22417 	mblk_t		*ipsec_mp;
22418 	ipha_t 		*ipha;
22419 	ip6_t 		*ip6h;
22420 	boolean_t	mctl_present = B_FALSE;
22421 	boolean_t	check = B_TRUE;
22422 	boolean_t	policy_present;
22423 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22424 
22425 	TCP_STAT(tcps, tcp_no_listener);
22426 
22427 	ipsec_mp = mp;
22428 
22429 	if (mp->b_datap->db_type == M_CTL) {
22430 		ipsec_in_t *ii;
22431 
22432 		mctl_present = B_TRUE;
22433 		mp = mp->b_cont;
22434 
22435 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22436 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22437 		if (ii->ipsec_in_dont_check) {
22438 			check = B_FALSE;
22439 			if (!ii->ipsec_in_secure) {
22440 				freeb(ipsec_mp);
22441 				mctl_present = B_FALSE;
22442 				ipsec_mp = mp;
22443 			}
22444 		}
22445 	}
22446 
22447 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22448 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22449 		ipha = (ipha_t *)mp->b_rptr;
22450 		ip6h = NULL;
22451 	} else {
22452 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22453 		ipha = NULL;
22454 		ip6h = (ip6_t *)mp->b_rptr;
22455 	}
22456 
22457 	if (check && policy_present) {
22458 		/*
22459 		 * The conn_t parameter is NULL because we already know
22460 		 * nobody's home.
22461 		 */
22462 		ipsec_mp = ipsec_check_global_policy(
22463 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22464 		    tcps->tcps_netstack);
22465 		if (ipsec_mp == NULL)
22466 			return;
22467 	}
22468 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22469 		DTRACE_PROBE2(
22470 		    tx__ip__log__error__nolistener__tcp,
22471 		    char *, "Could not reply with RST to mp(1)",
22472 		    mblk_t *, mp);
22473 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22474 		freemsg(ipsec_mp);
22475 		return;
22476 	}
22477 
22478 	rptr = mp->b_rptr;
22479 
22480 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22481 	seg_seq = BE32_TO_U32(tcph->th_seq);
22482 	seg_ack = BE32_TO_U32(tcph->th_ack);
22483 	flags = tcph->th_flags[0];
22484 
22485 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22486 	if (flags & TH_RST) {
22487 		freemsg(ipsec_mp);
22488 	} else if (flags & TH_ACK) {
22489 		tcp_xmit_early_reset("no tcp, reset",
22490 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22491 		    connp);
22492 	} else {
22493 		if (flags & TH_SYN) {
22494 			seg_len++;
22495 		} else {
22496 			/*
22497 			 * Here we violate the RFC.  Note that a normal
22498 			 * TCP will never send a segment without the ACK
22499 			 * flag, except for RST or SYN segment.  This
22500 			 * segment is neither.  Just drop it on the
22501 			 * floor.
22502 			 */
22503 			freemsg(ipsec_mp);
22504 			tcps->tcps_rst_unsent++;
22505 			return;
22506 		}
22507 
22508 		tcp_xmit_early_reset("no tcp, reset/ack",
22509 		    ipsec_mp, 0, seg_seq + seg_len,
22510 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22511 	}
22512 }
22513 
22514 /*
22515  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22516  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22517  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22518  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22519  * otherwise it will dup partial mblks.)
22520  * Otherwise, an appropriate ACK packet will be generated.  This
22521  * routine is not usually called to send new data for the first time.  It
22522  * is mostly called out of the timer for retransmits, and to generate ACKs.
22523  *
22524  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22525  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22526  * of the original mblk chain will be returned in *offset and *end_mp.
22527  */
22528 mblk_t *
22529 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22530     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22531     boolean_t rexmit)
22532 {
22533 	int	data_length;
22534 	int32_t	off = 0;
22535 	uint_t	flags;
22536 	mblk_t	*mp1;
22537 	mblk_t	*mp2;
22538 	uchar_t	*rptr;
22539 	tcph_t	*tcph;
22540 	int32_t	num_sack_blk = 0;
22541 	int32_t	sack_opt_len = 0;
22542 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22543 
22544 	/* Allocate for our maximum TCP header + link-level */
22545 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22546 	    tcps->tcps_wroff_xtra, BPRI_MED);
22547 	if (!mp1)
22548 		return (NULL);
22549 	data_length = 0;
22550 
22551 	/*
22552 	 * Note that tcp_mss has been adjusted to take into account the
22553 	 * timestamp option if applicable.  Because SACK options do not
22554 	 * appear in every TCP segments and they are of variable lengths,
22555 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22556 	 * the actual segment length when we need to send a segment which
22557 	 * includes SACK options.
22558 	 */
22559 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22560 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22561 		    tcp->tcp_num_sack_blk);
22562 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22563 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22564 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22565 			max_to_send -= sack_opt_len;
22566 	}
22567 
22568 	if (offset != NULL) {
22569 		off = *offset;
22570 		/* We use offset as an indicator that end_mp is not NULL. */
22571 		*end_mp = NULL;
22572 	}
22573 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22574 		/* This could be faster with cooperation from downstream */
22575 		if (mp2 != mp1 && !sendall &&
22576 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22577 		    max_to_send)
22578 			/*
22579 			 * Don't send the next mblk since the whole mblk
22580 			 * does not fit.
22581 			 */
22582 			break;
22583 		mp2->b_cont = dupb(mp);
22584 		mp2 = mp2->b_cont;
22585 		if (!mp2) {
22586 			freemsg(mp1);
22587 			return (NULL);
22588 		}
22589 		mp2->b_rptr += off;
22590 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22591 		    (uintptr_t)INT_MAX);
22592 
22593 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22594 		if (data_length > max_to_send) {
22595 			mp2->b_wptr -= data_length - max_to_send;
22596 			data_length = max_to_send;
22597 			off = mp2->b_wptr - mp->b_rptr;
22598 			break;
22599 		} else {
22600 			off = 0;
22601 		}
22602 	}
22603 	if (offset != NULL) {
22604 		*offset = off;
22605 		*end_mp = mp;
22606 	}
22607 	if (seg_len != NULL) {
22608 		*seg_len = data_length;
22609 	}
22610 
22611 	/* Update the latest receive window size in TCP header. */
22612 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22613 	    tcp->tcp_tcph->th_win);
22614 
22615 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22616 	mp1->b_rptr = rptr;
22617 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22618 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22619 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22620 	U32_TO_ABE32(seq, tcph->th_seq);
22621 
22622 	/*
22623 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22624 	 * that this function was called from tcp_wput_data. Thus, when called
22625 	 * to retransmit data the setting of the PUSH bit may appear some
22626 	 * what random in that it might get set when it should not. This
22627 	 * should not pose any performance issues.
22628 	 */
22629 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22630 	    tcp->tcp_unsent == data_length)) {
22631 		flags = TH_ACK | TH_PUSH;
22632 	} else {
22633 		flags = TH_ACK;
22634 	}
22635 
22636 	if (tcp->tcp_ecn_ok) {
22637 		if (tcp->tcp_ecn_echo_on)
22638 			flags |= TH_ECE;
22639 
22640 		/*
22641 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22642 		 * There is no TCP flow control for non-data segments, and
22643 		 * only data segment is transmitted reliably.
22644 		 */
22645 		if (data_length > 0 && !rexmit) {
22646 			SET_ECT(tcp, rptr);
22647 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22648 				flags |= TH_CWR;
22649 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22650 			}
22651 		}
22652 	}
22653 
22654 	if (tcp->tcp_valid_bits) {
22655 		uint32_t u1;
22656 
22657 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22658 		    seq == tcp->tcp_iss) {
22659 			uchar_t	*wptr;
22660 
22661 			/*
22662 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22663 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22664 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22665 			 * our SYN is not ack'ed but the app closes this
22666 			 * TCP connection.
22667 			 */
22668 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22669 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22670 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22671 
22672 			/*
22673 			 * Tack on the MSS option.  It is always needed
22674 			 * for both active and passive open.
22675 			 *
22676 			 * MSS option value should be interface MTU - MIN
22677 			 * TCP/IP header according to RFC 793 as it means
22678 			 * the maximum segment size TCP can receive.  But
22679 			 * to get around some broken middle boxes/end hosts
22680 			 * out there, we allow the option value to be the
22681 			 * same as the MSS option size on the peer side.
22682 			 * In this way, the other side will not send
22683 			 * anything larger than they can receive.
22684 			 *
22685 			 * Note that for SYN_SENT state, the ndd param
22686 			 * tcp_use_smss_as_mss_opt has no effect as we
22687 			 * don't know the peer's MSS option value. So
22688 			 * the only case we need to take care of is in
22689 			 * SYN_RCVD state, which is done later.
22690 			 */
22691 			wptr = mp1->b_wptr;
22692 			wptr[0] = TCPOPT_MAXSEG;
22693 			wptr[1] = TCPOPT_MAXSEG_LEN;
22694 			wptr += 2;
22695 			u1 = tcp->tcp_if_mtu -
22696 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22697 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22698 			    TCP_MIN_HEADER_LENGTH;
22699 			U16_TO_BE16(u1, wptr);
22700 			mp1->b_wptr = wptr + 2;
22701 			/* Update the offset to cover the additional word */
22702 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22703 
22704 			/*
22705 			 * Note that the following way of filling in
22706 			 * TCP options are not optimal.  Some NOPs can
22707 			 * be saved.  But there is no need at this time
22708 			 * to optimize it.  When it is needed, we will
22709 			 * do it.
22710 			 */
22711 			switch (tcp->tcp_state) {
22712 			case TCPS_SYN_SENT:
22713 				flags = TH_SYN;
22714 
22715 				if (tcp->tcp_snd_ts_ok) {
22716 					uint32_t llbolt = (uint32_t)lbolt;
22717 
22718 					wptr = mp1->b_wptr;
22719 					wptr[0] = TCPOPT_NOP;
22720 					wptr[1] = TCPOPT_NOP;
22721 					wptr[2] = TCPOPT_TSTAMP;
22722 					wptr[3] = TCPOPT_TSTAMP_LEN;
22723 					wptr += 4;
22724 					U32_TO_BE32(llbolt, wptr);
22725 					wptr += 4;
22726 					ASSERT(tcp->tcp_ts_recent == 0);
22727 					U32_TO_BE32(0L, wptr);
22728 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22729 					tcph->th_offset_and_rsrvd[0] +=
22730 					    (3 << 4);
22731 				}
22732 
22733 				/*
22734 				 * Set up all the bits to tell other side
22735 				 * we are ECN capable.
22736 				 */
22737 				if (tcp->tcp_ecn_ok) {
22738 					flags |= (TH_ECE | TH_CWR);
22739 				}
22740 				break;
22741 			case TCPS_SYN_RCVD:
22742 				flags |= TH_SYN;
22743 
22744 				/*
22745 				 * Reset the MSS option value to be SMSS
22746 				 * We should probably add back the bytes
22747 				 * for timestamp option and IPsec.  We
22748 				 * don't do that as this is a workaround
22749 				 * for broken middle boxes/end hosts, it
22750 				 * is better for us to be more cautious.
22751 				 * They may not take these things into
22752 				 * account in their SMSS calculation.  Thus
22753 				 * the peer's calculated SMSS may be smaller
22754 				 * than what it can be.  This should be OK.
22755 				 */
22756 				if (tcps->tcps_use_smss_as_mss_opt) {
22757 					u1 = tcp->tcp_mss;
22758 					U16_TO_BE16(u1, wptr);
22759 				}
22760 
22761 				/*
22762 				 * If the other side is ECN capable, reply
22763 				 * that we are also ECN capable.
22764 				 */
22765 				if (tcp->tcp_ecn_ok)
22766 					flags |= TH_ECE;
22767 				break;
22768 			default:
22769 				/*
22770 				 * The above ASSERT() makes sure that this
22771 				 * must be FIN-WAIT-1 state.  Our SYN has
22772 				 * not been ack'ed so retransmit it.
22773 				 */
22774 				flags |= TH_SYN;
22775 				break;
22776 			}
22777 
22778 			if (tcp->tcp_snd_ws_ok) {
22779 				wptr = mp1->b_wptr;
22780 				wptr[0] =  TCPOPT_NOP;
22781 				wptr[1] =  TCPOPT_WSCALE;
22782 				wptr[2] =  TCPOPT_WS_LEN;
22783 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22784 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22785 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22786 			}
22787 
22788 			if (tcp->tcp_snd_sack_ok) {
22789 				wptr = mp1->b_wptr;
22790 				wptr[0] = TCPOPT_NOP;
22791 				wptr[1] = TCPOPT_NOP;
22792 				wptr[2] = TCPOPT_SACK_PERMITTED;
22793 				wptr[3] = TCPOPT_SACK_OK_LEN;
22794 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22795 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22796 			}
22797 
22798 			/* allocb() of adequate mblk assures space */
22799 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22800 			    (uintptr_t)INT_MAX);
22801 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22802 			/*
22803 			 * Get IP set to checksum on our behalf
22804 			 * Include the adjustment for a source route if any.
22805 			 */
22806 			u1 += tcp->tcp_sum;
22807 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22808 			U16_TO_BE16(u1, tcph->th_sum);
22809 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22810 		}
22811 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22812 		    (seq + data_length) == tcp->tcp_fss) {
22813 			if (!tcp->tcp_fin_acked) {
22814 				flags |= TH_FIN;
22815 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22816 			}
22817 			if (!tcp->tcp_fin_sent) {
22818 				tcp->tcp_fin_sent = B_TRUE;
22819 				switch (tcp->tcp_state) {
22820 				case TCPS_SYN_RCVD:
22821 				case TCPS_ESTABLISHED:
22822 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22823 					break;
22824 				case TCPS_CLOSE_WAIT:
22825 					tcp->tcp_state = TCPS_LAST_ACK;
22826 					break;
22827 				}
22828 				if (tcp->tcp_suna == tcp->tcp_snxt)
22829 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22830 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22831 			}
22832 		}
22833 		/*
22834 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22835 		 * is smaller than seq, u1 will become a very huge value.
22836 		 * So the comparison will fail.  Also note that tcp_urp
22837 		 * should be positive, see RFC 793 page 17.
22838 		 */
22839 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22840 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22841 		    u1 < (uint32_t)(64 * 1024)) {
22842 			flags |= TH_URG;
22843 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
22844 			U32_TO_ABE16(u1, tcph->th_urp);
22845 		}
22846 	}
22847 	tcph->th_flags[0] = (uchar_t)flags;
22848 	tcp->tcp_rack = tcp->tcp_rnxt;
22849 	tcp->tcp_rack_cnt = 0;
22850 
22851 	if (tcp->tcp_snd_ts_ok) {
22852 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22853 			uint32_t llbolt = (uint32_t)lbolt;
22854 
22855 			U32_TO_BE32(llbolt,
22856 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22857 			U32_TO_BE32(tcp->tcp_ts_recent,
22858 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22859 		}
22860 	}
22861 
22862 	if (num_sack_blk > 0) {
22863 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22864 		sack_blk_t *tmp;
22865 		int32_t	i;
22866 
22867 		wptr[0] = TCPOPT_NOP;
22868 		wptr[1] = TCPOPT_NOP;
22869 		wptr[2] = TCPOPT_SACK;
22870 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22871 		    sizeof (sack_blk_t);
22872 		wptr += TCPOPT_REAL_SACK_LEN;
22873 
22874 		tmp = tcp->tcp_sack_list;
22875 		for (i = 0; i < num_sack_blk; i++) {
22876 			U32_TO_BE32(tmp[i].begin, wptr);
22877 			wptr += sizeof (tcp_seq);
22878 			U32_TO_BE32(tmp[i].end, wptr);
22879 			wptr += sizeof (tcp_seq);
22880 		}
22881 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22882 	}
22883 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22884 	data_length += (int)(mp1->b_wptr - rptr);
22885 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22886 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22887 	} else {
22888 		ip6_t *ip6 = (ip6_t *)(rptr +
22889 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22890 		    sizeof (ip6i_t) : 0));
22891 
22892 		ip6->ip6_plen = htons(data_length -
22893 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22894 	}
22895 
22896 	/*
22897 	 * Prime pump for IP
22898 	 * Include the adjustment for a source route if any.
22899 	 */
22900 	data_length -= tcp->tcp_ip_hdr_len;
22901 	data_length += tcp->tcp_sum;
22902 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22903 	U16_TO_ABE16(data_length, tcph->th_sum);
22904 	if (tcp->tcp_ip_forward_progress) {
22905 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22906 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22907 		tcp->tcp_ip_forward_progress = B_FALSE;
22908 	}
22909 	return (mp1);
22910 }
22911 
22912 /* This function handles the push timeout. */
22913 void
22914 tcp_push_timer(void *arg)
22915 {
22916 	conn_t	*connp = (conn_t *)arg;
22917 	tcp_t *tcp = connp->conn_tcp;
22918 
22919 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
22920 
22921 	ASSERT(tcp->tcp_listener == NULL);
22922 
22923 	ASSERT(!IPCL_IS_NONSTR(connp));
22924 
22925 	/*
22926 	 * We need to plug synchronous streams during our drain to prevent
22927 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
22928 	 */
22929 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
22930 	tcp->tcp_push_tid = 0;
22931 
22932 	if (tcp->tcp_rcv_list != NULL &&
22933 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
22934 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22935 
22936 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
22937 }
22938 
22939 /*
22940  * This function handles delayed ACK timeout.
22941  */
22942 static void
22943 tcp_ack_timer(void *arg)
22944 {
22945 	conn_t	*connp = (conn_t *)arg;
22946 	tcp_t *tcp = connp->conn_tcp;
22947 	mblk_t *mp;
22948 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22949 
22950 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
22951 
22952 	tcp->tcp_ack_tid = 0;
22953 
22954 	if (tcp->tcp_fused)
22955 		return;
22956 
22957 	/*
22958 	 * Do not send ACK if there is no outstanding unack'ed data.
22959 	 */
22960 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22961 		return;
22962 	}
22963 
22964 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22965 		/*
22966 		 * Make sure we don't allow deferred ACKs to result in
22967 		 * timer-based ACKing.  If we have held off an ACK
22968 		 * when there was more than an mss here, and the timer
22969 		 * goes off, we have to worry about the possibility
22970 		 * that the sender isn't doing slow-start, or is out
22971 		 * of step with us for some other reason.  We fall
22972 		 * permanently back in the direction of
22973 		 * ACK-every-other-packet as suggested in RFC 1122.
22974 		 */
22975 		if (tcp->tcp_rack_abs_max > 2)
22976 			tcp->tcp_rack_abs_max--;
22977 		tcp->tcp_rack_cur_max = 2;
22978 	}
22979 	mp = tcp_ack_mp(tcp);
22980 
22981 	if (mp != NULL) {
22982 		BUMP_LOCAL(tcp->tcp_obsegs);
22983 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22984 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
22985 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22986 	}
22987 }
22988 
22989 
22990 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22991 static mblk_t *
22992 tcp_ack_mp(tcp_t *tcp)
22993 {
22994 	uint32_t	seq_no;
22995 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22996 
22997 	/*
22998 	 * There are a few cases to be considered while setting the sequence no.
22999 	 * Essentially, we can come here while processing an unacceptable pkt
23000 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23001 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23002 	 * If we are here for a zero window probe, stick with suna. In all
23003 	 * other cases, we check if suna + swnd encompasses snxt and set
23004 	 * the sequence number to snxt, if so. If snxt falls outside the
23005 	 * window (the receiver probably shrunk its window), we will go with
23006 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23007 	 * receiver.
23008 	 */
23009 	if (tcp->tcp_zero_win_probe) {
23010 		seq_no = tcp->tcp_suna;
23011 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23012 		ASSERT(tcp->tcp_swnd == 0);
23013 		seq_no = tcp->tcp_snxt;
23014 	} else {
23015 		seq_no = SEQ_GT(tcp->tcp_snxt,
23016 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23017 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23018 	}
23019 
23020 	if (tcp->tcp_valid_bits) {
23021 		/*
23022 		 * For the complex case where we have to send some
23023 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23024 		 */
23025 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23026 		    NULL, B_FALSE));
23027 	} else {
23028 		/* Generate a simple ACK */
23029 		int	data_length;
23030 		uchar_t	*rptr;
23031 		tcph_t	*tcph;
23032 		mblk_t	*mp1;
23033 		int32_t	tcp_hdr_len;
23034 		int32_t	tcp_tcp_hdr_len;
23035 		int32_t	num_sack_blk = 0;
23036 		int32_t sack_opt_len;
23037 
23038 		/*
23039 		 * Allocate space for TCP + IP headers
23040 		 * and link-level header
23041 		 */
23042 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23043 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23044 			    tcp->tcp_num_sack_blk);
23045 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23046 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23047 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23048 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23049 		} else {
23050 			tcp_hdr_len = tcp->tcp_hdr_len;
23051 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23052 		}
23053 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23054 		if (!mp1)
23055 			return (NULL);
23056 
23057 		/* Update the latest receive window size in TCP header. */
23058 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23059 		    tcp->tcp_tcph->th_win);
23060 		/* copy in prototype TCP + IP header */
23061 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23062 		mp1->b_rptr = rptr;
23063 		mp1->b_wptr = rptr + tcp_hdr_len;
23064 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23065 
23066 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23067 
23068 		/* Set the TCP sequence number. */
23069 		U32_TO_ABE32(seq_no, tcph->th_seq);
23070 
23071 		/* Set up the TCP flag field. */
23072 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23073 		if (tcp->tcp_ecn_echo_on)
23074 			tcph->th_flags[0] |= TH_ECE;
23075 
23076 		tcp->tcp_rack = tcp->tcp_rnxt;
23077 		tcp->tcp_rack_cnt = 0;
23078 
23079 		/* fill in timestamp option if in use */
23080 		if (tcp->tcp_snd_ts_ok) {
23081 			uint32_t llbolt = (uint32_t)lbolt;
23082 
23083 			U32_TO_BE32(llbolt,
23084 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23085 			U32_TO_BE32(tcp->tcp_ts_recent,
23086 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23087 		}
23088 
23089 		/* Fill in SACK options */
23090 		if (num_sack_blk > 0) {
23091 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23092 			sack_blk_t *tmp;
23093 			int32_t	i;
23094 
23095 			wptr[0] = TCPOPT_NOP;
23096 			wptr[1] = TCPOPT_NOP;
23097 			wptr[2] = TCPOPT_SACK;
23098 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23099 			    sizeof (sack_blk_t);
23100 			wptr += TCPOPT_REAL_SACK_LEN;
23101 
23102 			tmp = tcp->tcp_sack_list;
23103 			for (i = 0; i < num_sack_blk; i++) {
23104 				U32_TO_BE32(tmp[i].begin, wptr);
23105 				wptr += sizeof (tcp_seq);
23106 				U32_TO_BE32(tmp[i].end, wptr);
23107 				wptr += sizeof (tcp_seq);
23108 			}
23109 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23110 			    << 4);
23111 		}
23112 
23113 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23114 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23115 		} else {
23116 			/* Check for ip6i_t header in sticky hdrs */
23117 			ip6_t *ip6 = (ip6_t *)(rptr +
23118 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23119 			    sizeof (ip6i_t) : 0));
23120 
23121 			ip6->ip6_plen = htons(tcp_hdr_len -
23122 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23123 		}
23124 
23125 		/*
23126 		 * Prime pump for checksum calculation in IP.  Include the
23127 		 * adjustment for a source route if any.
23128 		 */
23129 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23130 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23131 		U16_TO_ABE16(data_length, tcph->th_sum);
23132 
23133 		if (tcp->tcp_ip_forward_progress) {
23134 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23135 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23136 			tcp->tcp_ip_forward_progress = B_FALSE;
23137 		}
23138 		return (mp1);
23139 	}
23140 }
23141 
23142 /*
23143  * Hash list insertion routine for tcp_t structures. Each hash bucket
23144  * contains a list of tcp_t entries, and each entry is bound to a unique
23145  * port. If there are multiple tcp_t's that are bound to the same port, then
23146  * one of them will be linked into the hash bucket list, and the rest will
23147  * hang off of that one entry. For each port, entries bound to a specific IP
23148  * address will be inserted before those those bound to INADDR_ANY.
23149  */
23150 static void
23151 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23152 {
23153 	tcp_t	**tcpp;
23154 	tcp_t	*tcpnext;
23155 	tcp_t	*tcphash;
23156 
23157 	if (tcp->tcp_ptpbhn != NULL) {
23158 		ASSERT(!caller_holds_lock);
23159 		tcp_bind_hash_remove(tcp);
23160 	}
23161 	tcpp = &tbf->tf_tcp;
23162 	if (!caller_holds_lock) {
23163 		mutex_enter(&tbf->tf_lock);
23164 	} else {
23165 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23166 	}
23167 	tcphash = tcpp[0];
23168 	tcpnext = NULL;
23169 	if (tcphash != NULL) {
23170 		/* Look for an entry using the same port */
23171 		while ((tcphash = tcpp[0]) != NULL &&
23172 		    tcp->tcp_lport != tcphash->tcp_lport)
23173 			tcpp = &(tcphash->tcp_bind_hash);
23174 
23175 		/* The port was not found, just add to the end */
23176 		if (tcphash == NULL)
23177 			goto insert;
23178 
23179 		/*
23180 		 * OK, there already exists an entry bound to the
23181 		 * same port.
23182 		 *
23183 		 * If the new tcp bound to the INADDR_ANY address
23184 		 * and the first one in the list is not bound to
23185 		 * INADDR_ANY we skip all entries until we find the
23186 		 * first one bound to INADDR_ANY.
23187 		 * This makes sure that applications binding to a
23188 		 * specific address get preference over those binding to
23189 		 * INADDR_ANY.
23190 		 */
23191 		tcpnext = tcphash;
23192 		tcphash = NULL;
23193 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23194 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23195 			while ((tcpnext = tcpp[0]) != NULL &&
23196 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23197 				tcpp = &(tcpnext->tcp_bind_hash_port);
23198 
23199 			if (tcpnext) {
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 		} else {
23209 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23210 			tcphash = tcpnext->tcp_bind_hash;
23211 			if (tcphash != NULL) {
23212 				tcphash->tcp_ptpbhn =
23213 				    &(tcp->tcp_bind_hash);
23214 				tcpnext->tcp_bind_hash = NULL;
23215 			}
23216 		}
23217 	}
23218 insert:
23219 	tcp->tcp_bind_hash_port = tcpnext;
23220 	tcp->tcp_bind_hash = tcphash;
23221 	tcp->tcp_ptpbhn = tcpp;
23222 	tcpp[0] = tcp;
23223 	if (!caller_holds_lock)
23224 		mutex_exit(&tbf->tf_lock);
23225 }
23226 
23227 /*
23228  * Hash list removal routine for tcp_t structures.
23229  */
23230 static void
23231 tcp_bind_hash_remove(tcp_t *tcp)
23232 {
23233 	tcp_t	*tcpnext;
23234 	kmutex_t *lockp;
23235 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23236 
23237 	if (tcp->tcp_ptpbhn == NULL)
23238 		return;
23239 
23240 	/*
23241 	 * Extract the lock pointer in case there are concurrent
23242 	 * hash_remove's for this instance.
23243 	 */
23244 	ASSERT(tcp->tcp_lport != 0);
23245 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23246 
23247 	ASSERT(lockp != NULL);
23248 	mutex_enter(lockp);
23249 	if (tcp->tcp_ptpbhn) {
23250 		tcpnext = tcp->tcp_bind_hash_port;
23251 		if (tcpnext != NULL) {
23252 			tcp->tcp_bind_hash_port = NULL;
23253 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23254 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23255 			if (tcpnext->tcp_bind_hash != NULL) {
23256 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23257 				    &(tcpnext->tcp_bind_hash);
23258 				tcp->tcp_bind_hash = NULL;
23259 			}
23260 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23261 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23262 			tcp->tcp_bind_hash = NULL;
23263 		}
23264 		*tcp->tcp_ptpbhn = tcpnext;
23265 		tcp->tcp_ptpbhn = NULL;
23266 	}
23267 	mutex_exit(lockp);
23268 }
23269 
23270 
23271 /*
23272  * Hash list lookup routine for tcp_t structures.
23273  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23274  */
23275 static tcp_t *
23276 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23277 {
23278 	tf_t	*tf;
23279 	tcp_t	*tcp;
23280 
23281 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23282 	mutex_enter(&tf->tf_lock);
23283 	for (tcp = tf->tf_tcp; tcp != NULL;
23284 	    tcp = tcp->tcp_acceptor_hash) {
23285 		if (tcp->tcp_acceptor_id == id) {
23286 			CONN_INC_REF(tcp->tcp_connp);
23287 			mutex_exit(&tf->tf_lock);
23288 			return (tcp);
23289 		}
23290 	}
23291 	mutex_exit(&tf->tf_lock);
23292 	return (NULL);
23293 }
23294 
23295 
23296 /*
23297  * Hash list insertion routine for tcp_t structures.
23298  */
23299 void
23300 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23301 {
23302 	tf_t	*tf;
23303 	tcp_t	**tcpp;
23304 	tcp_t	*tcpnext;
23305 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23306 
23307 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23308 
23309 	if (tcp->tcp_ptpahn != NULL)
23310 		tcp_acceptor_hash_remove(tcp);
23311 	tcpp = &tf->tf_tcp;
23312 	mutex_enter(&tf->tf_lock);
23313 	tcpnext = tcpp[0];
23314 	if (tcpnext)
23315 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23316 	tcp->tcp_acceptor_hash = tcpnext;
23317 	tcp->tcp_ptpahn = tcpp;
23318 	tcpp[0] = tcp;
23319 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23320 	mutex_exit(&tf->tf_lock);
23321 }
23322 
23323 /*
23324  * Hash list removal routine for tcp_t structures.
23325  */
23326 static void
23327 tcp_acceptor_hash_remove(tcp_t *tcp)
23328 {
23329 	tcp_t	*tcpnext;
23330 	kmutex_t *lockp;
23331 
23332 	/*
23333 	 * Extract the lock pointer in case there are concurrent
23334 	 * hash_remove's for this instance.
23335 	 */
23336 	lockp = tcp->tcp_acceptor_lockp;
23337 
23338 	if (tcp->tcp_ptpahn == NULL)
23339 		return;
23340 
23341 	ASSERT(lockp != NULL);
23342 	mutex_enter(lockp);
23343 	if (tcp->tcp_ptpahn) {
23344 		tcpnext = tcp->tcp_acceptor_hash;
23345 		if (tcpnext) {
23346 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23347 			tcp->tcp_acceptor_hash = NULL;
23348 		}
23349 		*tcp->tcp_ptpahn = tcpnext;
23350 		tcp->tcp_ptpahn = NULL;
23351 	}
23352 	mutex_exit(lockp);
23353 	tcp->tcp_acceptor_lockp = NULL;
23354 }
23355 
23356 /*
23357  * Type three generator adapted from the random() function in 4.4 BSD:
23358  */
23359 
23360 /*
23361  * Copyright (c) 1983, 1993
23362  *	The Regents of the University of California.  All rights reserved.
23363  *
23364  * Redistribution and use in source and binary forms, with or without
23365  * modification, are permitted provided that the following conditions
23366  * are met:
23367  * 1. Redistributions of source code must retain the above copyright
23368  *    notice, this list of conditions and the following disclaimer.
23369  * 2. Redistributions in binary form must reproduce the above copyright
23370  *    notice, this list of conditions and the following disclaimer in the
23371  *    documentation and/or other materials provided with the distribution.
23372  * 3. All advertising materials mentioning features or use of this software
23373  *    must display the following acknowledgement:
23374  *	This product includes software developed by the University of
23375  *	California, Berkeley and its contributors.
23376  * 4. Neither the name of the University nor the names of its contributors
23377  *    may be used to endorse or promote products derived from this software
23378  *    without specific prior written permission.
23379  *
23380  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23381  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23382  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23383  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23384  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23385  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23386  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23387  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23388  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23389  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23390  * SUCH DAMAGE.
23391  */
23392 
23393 /* Type 3 -- x**31 + x**3 + 1 */
23394 #define	DEG_3		31
23395 #define	SEP_3		3
23396 
23397 
23398 /* Protected by tcp_random_lock */
23399 static int tcp_randtbl[DEG_3 + 1];
23400 
23401 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23402 static int *tcp_random_rptr = &tcp_randtbl[1];
23403 
23404 static int *tcp_random_state = &tcp_randtbl[1];
23405 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23406 
23407 kmutex_t tcp_random_lock;
23408 
23409 void
23410 tcp_random_init(void)
23411 {
23412 	int i;
23413 	hrtime_t hrt;
23414 	time_t wallclock;
23415 	uint64_t result;
23416 
23417 	/*
23418 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23419 	 * a longlong, which may contain resolution down to nanoseconds.
23420 	 * The current time will either be a 32-bit or a 64-bit quantity.
23421 	 * XOR the two together in a 64-bit result variable.
23422 	 * Convert the result to a 32-bit value by multiplying the high-order
23423 	 * 32-bits by the low-order 32-bits.
23424 	 */
23425 
23426 	hrt = gethrtime();
23427 	(void) drv_getparm(TIME, &wallclock);
23428 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23429 	mutex_enter(&tcp_random_lock);
23430 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23431 	    (result & 0xffffffff);
23432 
23433 	for (i = 1; i < DEG_3; i++)
23434 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23435 		    + 12345;
23436 	tcp_random_fptr = &tcp_random_state[SEP_3];
23437 	tcp_random_rptr = &tcp_random_state[0];
23438 	mutex_exit(&tcp_random_lock);
23439 	for (i = 0; i < 10 * DEG_3; i++)
23440 		(void) tcp_random();
23441 }
23442 
23443 /*
23444  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23445  * This range is selected to be approximately centered on TCP_ISS / 2,
23446  * and easy to compute. We get this value by generating a 32-bit random
23447  * number, selecting out the high-order 17 bits, and then adding one so
23448  * that we never return zero.
23449  */
23450 int
23451 tcp_random(void)
23452 {
23453 	int i;
23454 
23455 	mutex_enter(&tcp_random_lock);
23456 	*tcp_random_fptr += *tcp_random_rptr;
23457 
23458 	/*
23459 	 * The high-order bits are more random than the low-order bits,
23460 	 * so we select out the high-order 17 bits and add one so that
23461 	 * we never return zero.
23462 	 */
23463 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23464 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23465 		tcp_random_fptr = tcp_random_state;
23466 		++tcp_random_rptr;
23467 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23468 		tcp_random_rptr = tcp_random_state;
23469 
23470 	mutex_exit(&tcp_random_lock);
23471 	return (i);
23472 }
23473 
23474 static int
23475 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23476     int *t_errorp, int *sys_errorp)
23477 {
23478 	int error;
23479 	int is_absreq_failure;
23480 	t_scalar_t *opt_lenp;
23481 	t_scalar_t opt_offset;
23482 	int prim_type;
23483 	struct T_conn_req *tcreqp;
23484 	struct T_conn_res *tcresp;
23485 	cred_t *cr;
23486 
23487 	/*
23488 	 * All Solaris components should pass a db_credp
23489 	 * for this TPI message, hence we ASSERT.
23490 	 * But in case there is some other M_PROTO that looks
23491 	 * like a TPI message sent by some other kernel
23492 	 * component, we check and return an error.
23493 	 */
23494 	cr = msg_getcred(mp, NULL);
23495 	ASSERT(cr != NULL);
23496 	if (cr == NULL)
23497 		return (-1);
23498 
23499 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23500 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23501 	    prim_type == T_CONN_RES);
23502 
23503 	switch (prim_type) {
23504 	case T_CONN_REQ:
23505 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23506 		opt_offset = tcreqp->OPT_offset;
23507 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23508 		break;
23509 	case O_T_CONN_RES:
23510 	case T_CONN_RES:
23511 		tcresp = (struct T_conn_res *)mp->b_rptr;
23512 		opt_offset = tcresp->OPT_offset;
23513 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23514 		break;
23515 	}
23516 
23517 	*t_errorp = 0;
23518 	*sys_errorp = 0;
23519 	*do_disconnectp = 0;
23520 
23521 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23522 	    opt_offset, cr, &tcp_opt_obj,
23523 	    NULL, &is_absreq_failure);
23524 
23525 	switch (error) {
23526 	case  0:		/* no error */
23527 		ASSERT(is_absreq_failure == 0);
23528 		return (0);
23529 	case ENOPROTOOPT:
23530 		*t_errorp = TBADOPT;
23531 		break;
23532 	case EACCES:
23533 		*t_errorp = TACCES;
23534 		break;
23535 	default:
23536 		*t_errorp = TSYSERR; *sys_errorp = error;
23537 		break;
23538 	}
23539 	if (is_absreq_failure != 0) {
23540 		/*
23541 		 * The connection request should get the local ack
23542 		 * T_OK_ACK and then a T_DISCON_IND.
23543 		 */
23544 		*do_disconnectp = 1;
23545 	}
23546 	return (-1);
23547 }
23548 
23549 /*
23550  * Split this function out so that if the secret changes, I'm okay.
23551  *
23552  * Initialize the tcp_iss_cookie and tcp_iss_key.
23553  */
23554 
23555 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23556 
23557 static void
23558 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
23559 {
23560 	struct {
23561 		int32_t current_time;
23562 		uint32_t randnum;
23563 		uint16_t pad;
23564 		uint8_t ether[6];
23565 		uint8_t passwd[PASSWD_SIZE];
23566 	} tcp_iss_cookie;
23567 	time_t t;
23568 
23569 	/*
23570 	 * Start with the current absolute time.
23571 	 */
23572 	(void) drv_getparm(TIME, &t);
23573 	tcp_iss_cookie.current_time = t;
23574 
23575 	/*
23576 	 * XXX - Need a more random number per RFC 1750, not this crap.
23577 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23578 	 */
23579 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23580 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23581 
23582 	/*
23583 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23584 	 * as a good template.
23585 	 */
23586 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23587 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23588 
23589 	/*
23590 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23591 	 */
23592 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23593 
23594 	/*
23595 	 * See 4010593 if this section becomes a problem again,
23596 	 * but the local ethernet address is useful here.
23597 	 */
23598 	(void) localetheraddr(NULL,
23599 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23600 
23601 	/*
23602 	 * Hash 'em all together.  The MD5Final is called per-connection.
23603 	 */
23604 	mutex_enter(&tcps->tcps_iss_key_lock);
23605 	MD5Init(&tcps->tcps_iss_key);
23606 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
23607 	    sizeof (tcp_iss_cookie));
23608 	mutex_exit(&tcps->tcps_iss_key_lock);
23609 }
23610 
23611 /*
23612  * Set the RFC 1948 pass phrase
23613  */
23614 /* ARGSUSED */
23615 static int
23616 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23617     cred_t *cr)
23618 {
23619 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23620 
23621 	/*
23622 	 * Basically, value contains a new pass phrase.  Pass it along!
23623 	 */
23624 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
23625 	return (0);
23626 }
23627 
23628 /* ARGSUSED */
23629 static int
23630 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23631 {
23632 	bzero(buf, sizeof (tcp_sack_info_t));
23633 	return (0);
23634 }
23635 
23636 /* ARGSUSED */
23637 static int
23638 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23639 {
23640 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23641 	return (0);
23642 }
23643 
23644 /*
23645  * Make sure we wait until the default queue is setup, yet allow
23646  * tcp_g_q_create() to open a TCP stream.
23647  * We need to allow tcp_g_q_create() do do an open
23648  * of tcp, hence we compare curhread.
23649  * All others have to wait until the tcps_g_q has been
23650  * setup.
23651  */
23652 void
23653 tcp_g_q_setup(tcp_stack_t *tcps)
23654 {
23655 	mutex_enter(&tcps->tcps_g_q_lock);
23656 	if (tcps->tcps_g_q != NULL) {
23657 		mutex_exit(&tcps->tcps_g_q_lock);
23658 		return;
23659 	}
23660 	if (tcps->tcps_g_q_creator == NULL) {
23661 		/* This thread will set it up */
23662 		tcps->tcps_g_q_creator = curthread;
23663 		mutex_exit(&tcps->tcps_g_q_lock);
23664 		tcp_g_q_create(tcps);
23665 		mutex_enter(&tcps->tcps_g_q_lock);
23666 		ASSERT(tcps->tcps_g_q_creator == curthread);
23667 		tcps->tcps_g_q_creator = NULL;
23668 		cv_signal(&tcps->tcps_g_q_cv);
23669 		ASSERT(tcps->tcps_g_q != NULL);
23670 		mutex_exit(&tcps->tcps_g_q_lock);
23671 		return;
23672 	}
23673 	/* Everybody but the creator has to wait */
23674 	if (tcps->tcps_g_q_creator != curthread) {
23675 		while (tcps->tcps_g_q == NULL)
23676 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
23677 	}
23678 	mutex_exit(&tcps->tcps_g_q_lock);
23679 }
23680 
23681 #define	IP	"ip"
23682 
23683 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
23684 
23685 /*
23686  * Create a default tcp queue here instead of in strplumb
23687  */
23688 void
23689 tcp_g_q_create(tcp_stack_t *tcps)
23690 {
23691 	int error;
23692 	ldi_handle_t	lh = NULL;
23693 	ldi_ident_t	li = NULL;
23694 	int		rval;
23695 	cred_t		*cr;
23696 	major_t IP_MAJ;
23697 
23698 #ifdef NS_DEBUG
23699 	(void) printf("tcp_g_q_create()\n");
23700 #endif
23701 
23702 	IP_MAJ = ddi_name_to_major(IP);
23703 
23704 	ASSERT(tcps->tcps_g_q_creator == curthread);
23705 
23706 	error = ldi_ident_from_major(IP_MAJ, &li);
23707 	if (error) {
23708 #ifdef DEBUG
23709 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
23710 		    error);
23711 #endif
23712 		return;
23713 	}
23714 
23715 	cr = zone_get_kcred(netstackid_to_zoneid(
23716 	    tcps->tcps_netstack->netstack_stackid));
23717 	ASSERT(cr != NULL);
23718 	/*
23719 	 * We set the tcp default queue to IPv6 because IPv4 falls
23720 	 * back to IPv6 when it can't find a client, but
23721 	 * IPv6 does not fall back to IPv4.
23722 	 */
23723 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
23724 	if (error) {
23725 #ifdef DEBUG
23726 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
23727 		    error);
23728 #endif
23729 		goto out;
23730 	}
23731 
23732 	/*
23733 	 * This ioctl causes the tcp framework to cache a pointer to
23734 	 * this stream, so we don't want to close the stream after
23735 	 * this operation.
23736 	 * Use the kernel credentials that are for the zone we're in.
23737 	 */
23738 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
23739 	    (intptr_t)0, FKIOCTL, cr, &rval);
23740 	if (error) {
23741 #ifdef DEBUG
23742 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
23743 		    "error %d\n", error);
23744 #endif
23745 		goto out;
23746 	}
23747 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
23748 	lh = NULL;
23749 out:
23750 	/* Close layered handles */
23751 	if (li)
23752 		ldi_ident_release(li);
23753 	/* Keep cred around until _inactive needs it */
23754 	tcps->tcps_g_q_cr = cr;
23755 }
23756 
23757 /*
23758  * We keep tcp_g_q set until all other tcp_t's in the zone
23759  * has gone away, and then when tcp_g_q_inactive() is called
23760  * we clear it.
23761  */
23762 void
23763 tcp_g_q_destroy(tcp_stack_t *tcps)
23764 {
23765 #ifdef NS_DEBUG
23766 	(void) printf("tcp_g_q_destroy()for stack %d\n",
23767 	    tcps->tcps_netstack->netstack_stackid);
23768 #endif
23769 
23770 	if (tcps->tcps_g_q == NULL) {
23771 		return;	/* Nothing to cleanup */
23772 	}
23773 	/*
23774 	 * Drop reference corresponding to the default queue.
23775 	 * This reference was added from tcp_open when the default queue
23776 	 * was created, hence we compensate for this extra drop in
23777 	 * tcp_g_q_close. If the refcnt drops to zero here it means
23778 	 * the default queue was the last one to be open, in which
23779 	 * case, then tcp_g_q_inactive will be
23780 	 * called as a result of the refrele.
23781 	 */
23782 	TCPS_REFRELE(tcps);
23783 }
23784 
23785 /*
23786  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23787  * Run by tcp_q_q_inactive using a taskq.
23788  */
23789 static void
23790 tcp_g_q_close(void *arg)
23791 {
23792 	tcp_stack_t *tcps = arg;
23793 	int error;
23794 	ldi_handle_t	lh = NULL;
23795 	ldi_ident_t	li = NULL;
23796 	cred_t		*cr;
23797 	major_t IP_MAJ;
23798 
23799 	IP_MAJ = ddi_name_to_major(IP);
23800 
23801 #ifdef NS_DEBUG
23802 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
23803 	    tcps->tcps_netstack->netstack_stackid,
23804 	    tcps->tcps_netstack->netstack_refcnt);
23805 #endif
23806 	lh = tcps->tcps_g_q_lh;
23807 	if (lh == NULL)
23808 		return;	/* Nothing to cleanup */
23809 
23810 	ASSERT(tcps->tcps_refcnt == 1);
23811 	ASSERT(tcps->tcps_g_q != NULL);
23812 
23813 	error = ldi_ident_from_major(IP_MAJ, &li);
23814 	if (error) {
23815 #ifdef DEBUG
23816 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
23817 		    error);
23818 #endif
23819 		return;
23820 	}
23821 
23822 	cr = tcps->tcps_g_q_cr;
23823 	tcps->tcps_g_q_cr = NULL;
23824 	ASSERT(cr != NULL);
23825 
23826 	/*
23827 	 * Make sure we can break the recursion when tcp_close decrements
23828 	 * the reference count causing g_q_inactive to be called again.
23829 	 */
23830 	tcps->tcps_g_q_lh = NULL;
23831 
23832 	/* close the default queue */
23833 	(void) ldi_close(lh, FREAD|FWRITE, cr);
23834 	/*
23835 	 * At this point in time tcps and the rest of netstack_t might
23836 	 * have been deleted.
23837 	 */
23838 	tcps = NULL;
23839 
23840 	/* Close layered handles */
23841 	ldi_ident_release(li);
23842 	crfree(cr);
23843 }
23844 
23845 /*
23846  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23847  *
23848  * Have to ensure that the ldi routines are not used by an
23849  * interrupt thread by using a taskq.
23850  */
23851 void
23852 tcp_g_q_inactive(tcp_stack_t *tcps)
23853 {
23854 	if (tcps->tcps_g_q_lh == NULL)
23855 		return;	/* Nothing to cleanup */
23856 
23857 	ASSERT(tcps->tcps_refcnt == 0);
23858 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
23859 
23860 	if (servicing_interrupt()) {
23861 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
23862 		    (void *) tcps, TQ_SLEEP);
23863 	} else {
23864 		tcp_g_q_close(tcps);
23865 	}
23866 }
23867 
23868 /*
23869  * Called by IP when IP is loaded into the kernel
23870  */
23871 void
23872 tcp_ddi_g_init(void)
23873 {
23874 	tcp_timercache = kmem_cache_create("tcp_timercache",
23875 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23876 	    NULL, NULL, NULL, NULL, NULL, 0);
23877 
23878 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23879 	    sizeof (tcp_sack_info_t), 0,
23880 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23881 
23882 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23883 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23884 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23885 
23886 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23887 
23888 	/* Initialize the random number generator */
23889 	tcp_random_init();
23890 
23891 	/* A single callback independently of how many netstacks we have */
23892 	ip_squeue_init(tcp_squeue_add);
23893 
23894 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
23895 
23896 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
23897 	    TASKQ_PREPOPULATE);
23898 
23899 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
23900 
23901 	/*
23902 	 * We want to be informed each time a stack is created or
23903 	 * destroyed in the kernel, so we can maintain the
23904 	 * set of tcp_stack_t's.
23905 	 */
23906 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
23907 	    tcp_stack_fini);
23908 }
23909 
23910 
23911 #define	INET_NAME	"ip"
23912 
23913 /*
23914  * Initialize the TCP stack instance.
23915  */
23916 static void *
23917 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
23918 {
23919 	tcp_stack_t	*tcps;
23920 	tcpparam_t	*pa;
23921 	int		i;
23922 	int		error = 0;
23923 	major_t		major;
23924 
23925 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
23926 	tcps->tcps_netstack = ns;
23927 
23928 	/* Initialize locks */
23929 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23930 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
23931 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23932 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23933 
23934 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
23935 	tcps->tcps_g_epriv_ports[0] = 2049;
23936 	tcps->tcps_g_epriv_ports[1] = 4045;
23937 	tcps->tcps_min_anonpriv_port = 512;
23938 
23939 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
23940 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
23941 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
23942 	    TCP_FANOUT_SIZE, KM_SLEEP);
23943 
23944 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
23945 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
23946 		    MUTEX_DEFAULT, NULL);
23947 	}
23948 
23949 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
23950 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
23951 		    MUTEX_DEFAULT, NULL);
23952 	}
23953 
23954 	/* TCP's IPsec code calls the packet dropper. */
23955 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
23956 
23957 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
23958 	tcps->tcps_params = pa;
23959 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
23960 
23961 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
23962 	    A_CNT(lcl_tcp_param_arr), tcps);
23963 
23964 	/*
23965 	 * Note: To really walk the device tree you need the devinfo
23966 	 * pointer to your device which is only available after probe/attach.
23967 	 * The following is safe only because it uses ddi_root_node()
23968 	 */
23969 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23970 	    tcp_opt_obj.odb_opt_arr_cnt);
23971 
23972 	/*
23973 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23974 	 * by the boot scripts.
23975 	 *
23976 	 * Use NULL name, as the name is caught by the new lockstats.
23977 	 *
23978 	 * Initialize with some random, non-guessable string, like the global
23979 	 * T_INFO_ACK.
23980 	 */
23981 
23982 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23983 	    sizeof (tcp_g_t_info_ack), tcps);
23984 
23985 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
23986 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
23987 
23988 	major = mod_name_to_major(INET_NAME);
23989 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
23990 	ASSERT(error == 0);
23991 	return (tcps);
23992 }
23993 
23994 /*
23995  * Called when the IP module is about to be unloaded.
23996  */
23997 void
23998 tcp_ddi_g_destroy(void)
23999 {
24000 	tcp_g_kstat_fini(tcp_g_kstat);
24001 	tcp_g_kstat = NULL;
24002 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24003 
24004 	mutex_destroy(&tcp_random_lock);
24005 
24006 	kmem_cache_destroy(tcp_timercache);
24007 	kmem_cache_destroy(tcp_sack_info_cache);
24008 	kmem_cache_destroy(tcp_iphc_cache);
24009 
24010 	netstack_unregister(NS_TCP);
24011 	taskq_destroy(tcp_taskq);
24012 }
24013 
24014 /*
24015  * Shut down the TCP stack instance.
24016  */
24017 /* ARGSUSED */
24018 static void
24019 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24020 {
24021 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24022 
24023 	tcp_g_q_destroy(tcps);
24024 }
24025 
24026 /*
24027  * Free the TCP stack instance.
24028  */
24029 static void
24030 tcp_stack_fini(netstackid_t stackid, void *arg)
24031 {
24032 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24033 	int i;
24034 
24035 	nd_free(&tcps->tcps_g_nd);
24036 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24037 	tcps->tcps_params = NULL;
24038 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24039 	tcps->tcps_wroff_xtra_param = NULL;
24040 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24041 	tcps->tcps_mdt_head_param = NULL;
24042 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24043 	tcps->tcps_mdt_tail_param = NULL;
24044 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24045 	tcps->tcps_mdt_max_pbufs_param = NULL;
24046 
24047 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24048 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24049 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24050 	}
24051 
24052 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24053 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24054 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24055 	}
24056 
24057 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24058 	tcps->tcps_bind_fanout = NULL;
24059 
24060 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24061 	tcps->tcps_acceptor_fanout = NULL;
24062 
24063 	mutex_destroy(&tcps->tcps_iss_key_lock);
24064 	mutex_destroy(&tcps->tcps_g_q_lock);
24065 	cv_destroy(&tcps->tcps_g_q_cv);
24066 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24067 
24068 	ip_drop_unregister(&tcps->tcps_dropper);
24069 
24070 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24071 	tcps->tcps_kstat = NULL;
24072 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24073 
24074 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24075 	tcps->tcps_mibkp = NULL;
24076 
24077 	ldi_ident_release(tcps->tcps_ldi_ident);
24078 	kmem_free(tcps, sizeof (*tcps));
24079 }
24080 
24081 /*
24082  * Generate ISS, taking into account NDD changes may happen halfway through.
24083  * (If the iss is not zero, set it.)
24084  */
24085 
24086 static void
24087 tcp_iss_init(tcp_t *tcp)
24088 {
24089 	MD5_CTX context;
24090 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24091 	uint32_t answer[4];
24092 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24093 
24094 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24095 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24096 	switch (tcps->tcps_strong_iss) {
24097 	case 2:
24098 		mutex_enter(&tcps->tcps_iss_key_lock);
24099 		context = tcps->tcps_iss_key;
24100 		mutex_exit(&tcps->tcps_iss_key_lock);
24101 		arg.ports = tcp->tcp_ports;
24102 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24103 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24104 			    &arg.src);
24105 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24106 			    &arg.dst);
24107 		} else {
24108 			arg.src = tcp->tcp_ip6h->ip6_src;
24109 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24110 		}
24111 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24112 		MD5Final((uchar_t *)answer, &context);
24113 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24114 		/*
24115 		 * Now that we've hashed into a unique per-connection sequence
24116 		 * space, add a random increment per strong_iss == 1.  So I
24117 		 * guess we'll have to...
24118 		 */
24119 		/* FALLTHRU */
24120 	case 1:
24121 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24122 		break;
24123 	default:
24124 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24125 		break;
24126 	}
24127 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24128 	tcp->tcp_fss = tcp->tcp_iss - 1;
24129 	tcp->tcp_suna = tcp->tcp_iss;
24130 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24131 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24132 	tcp->tcp_csuna = tcp->tcp_snxt;
24133 }
24134 
24135 /*
24136  * Exported routine for extracting active tcp connection status.
24137  *
24138  * This is used by the Solaris Cluster Networking software to
24139  * gather a list of connections that need to be forwarded to
24140  * specific nodes in the cluster when configuration changes occur.
24141  *
24142  * The callback is invoked for each tcp_t structure from all netstacks,
24143  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24144  * from the netstack with the specified stack_id. Returning
24145  * non-zero from the callback routine terminates the search.
24146  */
24147 int
24148 cl_tcp_walk_list(netstackid_t stack_id,
24149     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24150 {
24151 	netstack_handle_t nh;
24152 	netstack_t *ns;
24153 	int ret = 0;
24154 
24155 	if (stack_id >= 0) {
24156 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24157 			return (EINVAL);
24158 
24159 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24160 		    ns->netstack_tcp);
24161 		netstack_rele(ns);
24162 		return (ret);
24163 	}
24164 
24165 	netstack_next_init(&nh);
24166 	while ((ns = netstack_next(&nh)) != NULL) {
24167 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24168 		    ns->netstack_tcp);
24169 		netstack_rele(ns);
24170 	}
24171 	netstack_next_fini(&nh);
24172 	return (ret);
24173 }
24174 
24175 static int
24176 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
24177     tcp_stack_t *tcps)
24178 {
24179 	tcp_t *tcp;
24180 	cl_tcp_info_t	cl_tcpi;
24181 	connf_t	*connfp;
24182 	conn_t	*connp;
24183 	int	i;
24184 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24185 
24186 	ASSERT(callback != NULL);
24187 
24188 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24189 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
24190 		connp = NULL;
24191 
24192 		while ((connp =
24193 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24194 
24195 			tcp = connp->conn_tcp;
24196 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24197 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24198 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24199 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24200 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24201 			/*
24202 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24203 			 * addresses. They are copied implicitly below as
24204 			 * mapped addresses.
24205 			 */
24206 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24207 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24208 				cl_tcpi.cl_tcpi_faddr =
24209 				    tcp->tcp_ipha->ipha_dst;
24210 			} else {
24211 				cl_tcpi.cl_tcpi_faddr_v6 =
24212 				    tcp->tcp_ip6h->ip6_dst;
24213 			}
24214 
24215 			/*
24216 			 * If the callback returns non-zero
24217 			 * we terminate the traversal.
24218 			 */
24219 			if ((*callback)(&cl_tcpi, arg) != 0) {
24220 				CONN_DEC_REF(tcp->tcp_connp);
24221 				return (1);
24222 			}
24223 		}
24224 	}
24225 
24226 	return (0);
24227 }
24228 
24229 /*
24230  * Macros used for accessing the different types of sockaddr
24231  * structures inside a tcp_ioc_abort_conn_t.
24232  */
24233 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24234 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24235 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24236 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24237 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24238 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24239 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24240 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24241 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24242 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24243 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24244 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24245 
24246 /*
24247  * Return the correct error code to mimic the behavior
24248  * of a connection reset.
24249  */
24250 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24251 		switch ((state)) {		\
24252 		case TCPS_SYN_SENT:		\
24253 		case TCPS_SYN_RCVD:		\
24254 			(err) = ECONNREFUSED;	\
24255 			break;			\
24256 		case TCPS_ESTABLISHED:		\
24257 		case TCPS_FIN_WAIT_1:		\
24258 		case TCPS_FIN_WAIT_2:		\
24259 		case TCPS_CLOSE_WAIT:		\
24260 			(err) = ECONNRESET;	\
24261 			break;			\
24262 		case TCPS_CLOSING:		\
24263 		case TCPS_LAST_ACK:		\
24264 		case TCPS_TIME_WAIT:		\
24265 			(err) = 0;		\
24266 			break;			\
24267 		default:			\
24268 			(err) = ENXIO;		\
24269 		}				\
24270 	}
24271 
24272 /*
24273  * Check if a tcp structure matches the info in acp.
24274  */
24275 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24276 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24277 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24278 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24279 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24280 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24281 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24282 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24283 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24284 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24285 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24286 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24287 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24288 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24289 	&(tcp)->tcp_ip_src_v6)) &&				\
24290 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24291 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24292 	&(tcp)->tcp_remote_v6)) &&				\
24293 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24294 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24295 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24296 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24297 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24298 	(acp)->ac_end >= (tcp)->tcp_state))
24299 
24300 #define	TCP_AC_MATCH(acp, tcp)					\
24301 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24302 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24303 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24304 
24305 /*
24306  * Build a message containing a tcp_ioc_abort_conn_t structure
24307  * which is filled in with information from acp and tp.
24308  */
24309 static mblk_t *
24310 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24311 {
24312 	mblk_t *mp;
24313 	tcp_ioc_abort_conn_t *tacp;
24314 
24315 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24316 	if (mp == NULL)
24317 		return (NULL);
24318 
24319 	mp->b_datap->db_type = M_CTL;
24320 
24321 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24322 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24323 	    sizeof (uint32_t));
24324 
24325 	tacp->ac_start = acp->ac_start;
24326 	tacp->ac_end = acp->ac_end;
24327 	tacp->ac_zoneid = acp->ac_zoneid;
24328 
24329 	if (acp->ac_local.ss_family == AF_INET) {
24330 		tacp->ac_local.ss_family = AF_INET;
24331 		tacp->ac_remote.ss_family = AF_INET;
24332 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24333 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24334 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24335 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24336 	} else {
24337 		tacp->ac_local.ss_family = AF_INET6;
24338 		tacp->ac_remote.ss_family = AF_INET6;
24339 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24340 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24341 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24342 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24343 	}
24344 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24345 	return (mp);
24346 }
24347 
24348 /*
24349  * Print a tcp_ioc_abort_conn_t structure.
24350  */
24351 static void
24352 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24353 {
24354 	char lbuf[128];
24355 	char rbuf[128];
24356 	sa_family_t af;
24357 	in_port_t lport, rport;
24358 	ushort_t logflags;
24359 
24360 	af = acp->ac_local.ss_family;
24361 
24362 	if (af == AF_INET) {
24363 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24364 		    lbuf, 128);
24365 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24366 		    rbuf, 128);
24367 		lport = ntohs(TCP_AC_V4LPORT(acp));
24368 		rport = ntohs(TCP_AC_V4RPORT(acp));
24369 	} else {
24370 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24371 		    lbuf, 128);
24372 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24373 		    rbuf, 128);
24374 		lport = ntohs(TCP_AC_V6LPORT(acp));
24375 		rport = ntohs(TCP_AC_V6RPORT(acp));
24376 	}
24377 
24378 	logflags = SL_TRACE | SL_NOTE;
24379 	/*
24380 	 * Don't print this message to the console if the operation was done
24381 	 * to a non-global zone.
24382 	 */
24383 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24384 		logflags |= SL_CONSOLE;
24385 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24386 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24387 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24388 	    acp->ac_start, acp->ac_end);
24389 }
24390 
24391 /*
24392  * Called inside tcp_rput when a message built using
24393  * tcp_ioctl_abort_build_msg is put into a queue.
24394  * Note that when we get here there is no wildcard in acp any more.
24395  */
24396 static void
24397 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24398 {
24399 	tcp_ioc_abort_conn_t *acp;
24400 
24401 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24402 	if (tcp->tcp_state <= acp->ac_end) {
24403 		/*
24404 		 * If we get here, we are already on the correct
24405 		 * squeue. This ioctl follows the following path
24406 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24407 		 * ->tcp_ioctl_abort->squeue_enter (if on a
24408 		 * different squeue)
24409 		 */
24410 		int errcode;
24411 
24412 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24413 		(void) tcp_clean_death(tcp, errcode, 26);
24414 	}
24415 	freemsg(mp);
24416 }
24417 
24418 /*
24419  * Abort all matching connections on a hash chain.
24420  */
24421 static int
24422 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24423     boolean_t exact, tcp_stack_t *tcps)
24424 {
24425 	int nmatch, err = 0;
24426 	tcp_t *tcp;
24427 	MBLKP mp, last, listhead = NULL;
24428 	conn_t	*tconnp;
24429 	connf_t	*connfp;
24430 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24431 
24432 	connfp = &ipst->ips_ipcl_conn_fanout[index];
24433 
24434 startover:
24435 	nmatch = 0;
24436 
24437 	mutex_enter(&connfp->connf_lock);
24438 	for (tconnp = connfp->connf_head; tconnp != NULL;
24439 	    tconnp = tconnp->conn_next) {
24440 		tcp = tconnp->conn_tcp;
24441 		if (TCP_AC_MATCH(acp, tcp)) {
24442 			CONN_INC_REF(tcp->tcp_connp);
24443 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24444 			if (mp == NULL) {
24445 				err = ENOMEM;
24446 				CONN_DEC_REF(tcp->tcp_connp);
24447 				break;
24448 			}
24449 			mp->b_prev = (mblk_t *)tcp;
24450 
24451 			if (listhead == NULL) {
24452 				listhead = mp;
24453 				last = mp;
24454 			} else {
24455 				last->b_next = mp;
24456 				last = mp;
24457 			}
24458 			nmatch++;
24459 			if (exact)
24460 				break;
24461 		}
24462 
24463 		/* Avoid holding lock for too long. */
24464 		if (nmatch >= 500)
24465 			break;
24466 	}
24467 	mutex_exit(&connfp->connf_lock);
24468 
24469 	/* Pass mp into the correct tcp */
24470 	while ((mp = listhead) != NULL) {
24471 		listhead = listhead->b_next;
24472 		tcp = (tcp_t *)mp->b_prev;
24473 		mp->b_next = mp->b_prev = NULL;
24474 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
24475 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
24476 	}
24477 
24478 	*count += nmatch;
24479 	if (nmatch >= 500 && err == 0)
24480 		goto startover;
24481 	return (err);
24482 }
24483 
24484 /*
24485  * Abort all connections that matches the attributes specified in acp.
24486  */
24487 static int
24488 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
24489 {
24490 	sa_family_t af;
24491 	uint32_t  ports;
24492 	uint16_t *pports;
24493 	int err = 0, count = 0;
24494 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24495 	int index = -1;
24496 	ushort_t logflags;
24497 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24498 
24499 	af = acp->ac_local.ss_family;
24500 
24501 	if (af == AF_INET) {
24502 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24503 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24504 			pports = (uint16_t *)&ports;
24505 			pports[1] = TCP_AC_V4LPORT(acp);
24506 			pports[0] = TCP_AC_V4RPORT(acp);
24507 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24508 		}
24509 	} else {
24510 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24511 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24512 			pports = (uint16_t *)&ports;
24513 			pports[1] = TCP_AC_V6LPORT(acp);
24514 			pports[0] = TCP_AC_V6RPORT(acp);
24515 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24516 		}
24517 	}
24518 
24519 	/*
24520 	 * For cases where remote addr, local port, and remote port are non-
24521 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24522 	 */
24523 	if (index != -1) {
24524 		err = tcp_ioctl_abort_bucket(acp, index,
24525 		    &count, exact, tcps);
24526 	} else {
24527 		/*
24528 		 * loop through all entries for wildcard case
24529 		 */
24530 		for (index = 0;
24531 		    index < ipst->ips_ipcl_conn_fanout_size;
24532 		    index++) {
24533 			err = tcp_ioctl_abort_bucket(acp, index,
24534 			    &count, exact, tcps);
24535 			if (err != 0)
24536 				break;
24537 		}
24538 	}
24539 
24540 	logflags = SL_TRACE | SL_NOTE;
24541 	/*
24542 	 * Don't print this message to the console if the operation was done
24543 	 * to a non-global zone.
24544 	 */
24545 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24546 		logflags |= SL_CONSOLE;
24547 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24548 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24549 	if (err == 0 && count == 0)
24550 		err = ENOENT;
24551 	return (err);
24552 }
24553 
24554 /*
24555  * Process the TCP_IOC_ABORT_CONN ioctl request.
24556  */
24557 static void
24558 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24559 {
24560 	int	err;
24561 	IOCP    iocp;
24562 	MBLKP   mp1;
24563 	sa_family_t laf, raf;
24564 	tcp_ioc_abort_conn_t *acp;
24565 	zone_t		*zptr;
24566 	conn_t		*connp = Q_TO_CONN(q);
24567 	zoneid_t	zoneid = connp->conn_zoneid;
24568 	tcp_t		*tcp = connp->conn_tcp;
24569 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24570 
24571 	iocp = (IOCP)mp->b_rptr;
24572 
24573 	if ((mp1 = mp->b_cont) == NULL ||
24574 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24575 		err = EINVAL;
24576 		goto out;
24577 	}
24578 
24579 	/* check permissions */
24580 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
24581 		err = EPERM;
24582 		goto out;
24583 	}
24584 
24585 	if (mp1->b_cont != NULL) {
24586 		freemsg(mp1->b_cont);
24587 		mp1->b_cont = NULL;
24588 	}
24589 
24590 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24591 	laf = acp->ac_local.ss_family;
24592 	raf = acp->ac_remote.ss_family;
24593 
24594 	/* check that a zone with the supplied zoneid exists */
24595 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24596 		zptr = zone_find_by_id(zoneid);
24597 		if (zptr != NULL) {
24598 			zone_rele(zptr);
24599 		} else {
24600 			err = EINVAL;
24601 			goto out;
24602 		}
24603 	}
24604 
24605 	/*
24606 	 * For exclusive stacks we set the zoneid to zero
24607 	 * to make TCP operate as if in the global zone.
24608 	 */
24609 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
24610 		acp->ac_zoneid = GLOBAL_ZONEID;
24611 
24612 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24613 	    acp->ac_start > acp->ac_end || laf != raf ||
24614 	    (laf != AF_INET && laf != AF_INET6)) {
24615 		err = EINVAL;
24616 		goto out;
24617 	}
24618 
24619 	tcp_ioctl_abort_dump(acp);
24620 	err = tcp_ioctl_abort(acp, tcps);
24621 
24622 out:
24623 	if (mp1 != NULL) {
24624 		freemsg(mp1);
24625 		mp->b_cont = NULL;
24626 	}
24627 
24628 	if (err != 0)
24629 		miocnak(q, mp, 0, err);
24630 	else
24631 		miocack(q, mp, 0, 0);
24632 }
24633 
24634 /*
24635  * tcp_time_wait_processing() handles processing of incoming packets when
24636  * the tcp is in the TIME_WAIT state.
24637  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24638  * on the time wait list.
24639  */
24640 void
24641 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24642     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24643 {
24644 	int32_t		bytes_acked;
24645 	int32_t		gap;
24646 	int32_t		rgap;
24647 	tcp_opt_t	tcpopt;
24648 	uint_t		flags;
24649 	uint32_t	new_swnd = 0;
24650 	conn_t		*connp;
24651 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24652 
24653 	BUMP_LOCAL(tcp->tcp_ibsegs);
24654 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
24655 
24656 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24657 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24658 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24659 	if (tcp->tcp_snd_ts_ok) {
24660 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24661 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24662 			    tcp->tcp_rnxt, TH_ACK);
24663 			goto done;
24664 		}
24665 	}
24666 	gap = seg_seq - tcp->tcp_rnxt;
24667 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24668 	if (gap < 0) {
24669 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
24670 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
24671 		    (seg_len > -gap ? -gap : seg_len));
24672 		seg_len += gap;
24673 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24674 			if (flags & TH_RST) {
24675 				goto done;
24676 			}
24677 			if ((flags & TH_FIN) && seg_len == -1) {
24678 				/*
24679 				 * When TCP receives a duplicate FIN in
24680 				 * TIME_WAIT state, restart the 2 MSL timer.
24681 				 * See page 73 in RFC 793. Make sure this TCP
24682 				 * is already on the TIME_WAIT list. If not,
24683 				 * just restart the timer.
24684 				 */
24685 				if (TCP_IS_DETACHED(tcp)) {
24686 					if (tcp_time_wait_remove(tcp, NULL) ==
24687 					    B_TRUE) {
24688 						tcp_time_wait_append(tcp);
24689 						TCP_DBGSTAT(tcps,
24690 						    tcp_rput_time_wait);
24691 					}
24692 				} else {
24693 					ASSERT(tcp != NULL);
24694 					TCP_TIMER_RESTART(tcp,
24695 					    tcps->tcps_time_wait_interval);
24696 				}
24697 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24698 				    tcp->tcp_rnxt, TH_ACK);
24699 				goto done;
24700 			}
24701 			flags |=  TH_ACK_NEEDED;
24702 			seg_len = 0;
24703 			goto process_ack;
24704 		}
24705 
24706 		/* Fix seg_seq, and chew the gap off the front. */
24707 		seg_seq = tcp->tcp_rnxt;
24708 	}
24709 
24710 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24711 		/*
24712 		 * Make sure that when we accept the connection, pick
24713 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24714 		 * old connection.
24715 		 *
24716 		 * The next ISS generated is equal to tcp_iss_incr_extra
24717 		 * + ISS_INCR/2 + other components depending on the
24718 		 * value of tcp_strong_iss.  We pre-calculate the new
24719 		 * ISS here and compare with tcp_snxt to determine if
24720 		 * we need to make adjustment to tcp_iss_incr_extra.
24721 		 *
24722 		 * The above calculation is ugly and is a
24723 		 * waste of CPU cycles...
24724 		 */
24725 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
24726 		int32_t adj;
24727 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24728 
24729 		switch (tcps->tcps_strong_iss) {
24730 		case 2: {
24731 			/* Add time and MD5 components. */
24732 			uint32_t answer[4];
24733 			struct {
24734 				uint32_t ports;
24735 				in6_addr_t src;
24736 				in6_addr_t dst;
24737 			} arg;
24738 			MD5_CTX context;
24739 
24740 			mutex_enter(&tcps->tcps_iss_key_lock);
24741 			context = tcps->tcps_iss_key;
24742 			mutex_exit(&tcps->tcps_iss_key_lock);
24743 			arg.ports = tcp->tcp_ports;
24744 			/* We use MAPPED addresses in tcp_iss_init */
24745 			arg.src = tcp->tcp_ip_src_v6;
24746 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24747 				IN6_IPADDR_TO_V4MAPPED(
24748 				    tcp->tcp_ipha->ipha_dst,
24749 				    &arg.dst);
24750 			} else {
24751 				arg.dst =
24752 				    tcp->tcp_ip6h->ip6_dst;
24753 			}
24754 			MD5Update(&context, (uchar_t *)&arg,
24755 			    sizeof (arg));
24756 			MD5Final((uchar_t *)answer, &context);
24757 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24758 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24759 			break;
24760 		}
24761 		case 1:
24762 			/* Add time component and min random (i.e. 1). */
24763 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24764 			break;
24765 		default:
24766 			/* Add only time component. */
24767 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24768 			break;
24769 		}
24770 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24771 			/*
24772 			 * New ISS not guaranteed to be ISS_INCR/2
24773 			 * ahead of the current tcp_snxt, so add the
24774 			 * difference to tcp_iss_incr_extra.
24775 			 */
24776 			tcps->tcps_iss_incr_extra += adj;
24777 		}
24778 		/*
24779 		 * If tcp_clean_death() can not perform the task now,
24780 		 * drop the SYN packet and let the other side re-xmit.
24781 		 * Otherwise pass the SYN packet back in, since the
24782 		 * old tcp state has been cleaned up or freed.
24783 		 */
24784 		if (tcp_clean_death(tcp, 0, 27) == -1)
24785 			goto done;
24786 		/*
24787 		 * We will come back to tcp_rput_data
24788 		 * on the global queue. Packets destined
24789 		 * for the global queue will be checked
24790 		 * with global policy. But the policy for
24791 		 * this packet has already been checked as
24792 		 * this was destined for the detached
24793 		 * connection. We need to bypass policy
24794 		 * check this time by attaching a dummy
24795 		 * ipsec_in with ipsec_in_dont_check set.
24796 		 */
24797 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
24798 		if (connp != NULL) {
24799 			TCP_STAT(tcps, tcp_time_wait_syn_success);
24800 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24801 			return;
24802 		}
24803 		goto done;
24804 	}
24805 
24806 	/*
24807 	 * rgap is the amount of stuff received out of window.  A negative
24808 	 * value is the amount out of window.
24809 	 */
24810 	if (rgap < 0) {
24811 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
24812 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
24813 		/* Fix seg_len and make sure there is something left. */
24814 		seg_len += rgap;
24815 		if (seg_len <= 0) {
24816 			if (flags & TH_RST) {
24817 				goto done;
24818 			}
24819 			flags |=  TH_ACK_NEEDED;
24820 			seg_len = 0;
24821 			goto process_ack;
24822 		}
24823 	}
24824 	/*
24825 	 * Check whether we can update tcp_ts_recent.  This test is
24826 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24827 	 * Extensions for High Performance: An Update", Internet Draft.
24828 	 */
24829 	if (tcp->tcp_snd_ts_ok &&
24830 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24831 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24832 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24833 		tcp->tcp_last_rcv_lbolt = lbolt64;
24834 	}
24835 
24836 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24837 		/* Always ack out of order packets */
24838 		flags |= TH_ACK_NEEDED;
24839 		seg_len = 0;
24840 	} else if (seg_len > 0) {
24841 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
24842 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
24843 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
24844 	}
24845 	if (flags & TH_RST) {
24846 		(void) tcp_clean_death(tcp, 0, 28);
24847 		goto done;
24848 	}
24849 	if (flags & TH_SYN) {
24850 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24851 		    TH_RST|TH_ACK);
24852 		/*
24853 		 * Do not delete the TCP structure if it is in
24854 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24855 		 */
24856 		goto done;
24857 	}
24858 process_ack:
24859 	if (flags & TH_ACK) {
24860 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24861 		if (bytes_acked <= 0) {
24862 			if (bytes_acked == 0 && seg_len == 0 &&
24863 			    new_swnd == tcp->tcp_swnd)
24864 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
24865 		} else {
24866 			/* Acks something not sent */
24867 			flags |= TH_ACK_NEEDED;
24868 		}
24869 	}
24870 	if (flags & TH_ACK_NEEDED) {
24871 		/*
24872 		 * Time to send an ack for some reason.
24873 		 */
24874 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24875 		    tcp->tcp_rnxt, TH_ACK);
24876 	}
24877 done:
24878 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24879 		DB_CKSUMSTART(mp) = 0;
24880 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24881 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
24882 	}
24883 	freemsg(mp);
24884 }
24885 
24886 /*
24887  * TCP Timers Implementation.
24888  */
24889 timeout_id_t
24890 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24891 {
24892 	mblk_t *mp;
24893 	tcp_timer_t *tcpt;
24894 	tcp_t *tcp = connp->conn_tcp;
24895 
24896 	ASSERT(connp->conn_sqp != NULL);
24897 
24898 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
24899 
24900 	if (tcp->tcp_timercache == NULL) {
24901 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24902 	} else {
24903 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
24904 		mp = tcp->tcp_timercache;
24905 		tcp->tcp_timercache = mp->b_next;
24906 		mp->b_next = NULL;
24907 		ASSERT(mp->b_wptr == NULL);
24908 	}
24909 
24910 	CONN_INC_REF(connp);
24911 	tcpt = (tcp_timer_t *)mp->b_rptr;
24912 	tcpt->connp = connp;
24913 	tcpt->tcpt_proc = f;
24914 	/*
24915 	 * TCP timers are normal timeouts. Plus, they do not require more than
24916 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
24917 	 * rounding up the expiration to the next resolution boundary, we can
24918 	 * batch timers in the callout subsystem to make TCP timers more
24919 	 * efficient. The roundup also protects short timers from expiring too
24920 	 * early before they have a chance to be cancelled.
24921 	 */
24922 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
24923 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
24924 
24925 	return ((timeout_id_t)mp);
24926 }
24927 
24928 static void
24929 tcp_timer_callback(void *arg)
24930 {
24931 	mblk_t *mp = (mblk_t *)arg;
24932 	tcp_timer_t *tcpt;
24933 	conn_t	*connp;
24934 
24935 	tcpt = (tcp_timer_t *)mp->b_rptr;
24936 	connp = tcpt->connp;
24937 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
24938 	    SQ_FILL, SQTAG_TCP_TIMER);
24939 }
24940 
24941 static void
24942 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24943 {
24944 	tcp_timer_t *tcpt;
24945 	conn_t *connp = (conn_t *)arg;
24946 	tcp_t *tcp = connp->conn_tcp;
24947 
24948 	tcpt = (tcp_timer_t *)mp->b_rptr;
24949 	ASSERT(connp == tcpt->connp);
24950 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24951 
24952 	/*
24953 	 * If the TCP has reached the closed state, don't proceed any
24954 	 * further. This TCP logically does not exist on the system.
24955 	 * tcpt_proc could for example access queues, that have already
24956 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24957 	 */
24958 	if (tcp->tcp_state != TCPS_CLOSED) {
24959 		(*tcpt->tcpt_proc)(connp);
24960 	} else {
24961 		tcp->tcp_timer_tid = 0;
24962 	}
24963 	tcp_timer_free(connp->conn_tcp, mp);
24964 }
24965 
24966 /*
24967  * There is potential race with untimeout and the handler firing at the same
24968  * time. The mblock may be freed by the handler while we are trying to use
24969  * it. But since both should execute on the same squeue, this race should not
24970  * occur.
24971  */
24972 clock_t
24973 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24974 {
24975 	mblk_t	*mp = (mblk_t *)id;
24976 	tcp_timer_t *tcpt;
24977 	clock_t delta;
24978 
24979 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
24980 
24981 	if (mp == NULL)
24982 		return (-1);
24983 
24984 	tcpt = (tcp_timer_t *)mp->b_rptr;
24985 	ASSERT(tcpt->connp == connp);
24986 
24987 	delta = untimeout_default(tcpt->tcpt_tid, 0);
24988 
24989 	if (delta >= 0) {
24990 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
24991 		tcp_timer_free(connp->conn_tcp, mp);
24992 		CONN_DEC_REF(connp);
24993 	}
24994 
24995 	return (delta);
24996 }
24997 
24998 /*
24999  * Allocate space for the timer event. The allocation looks like mblk, but it is
25000  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25001  *
25002  * Dealing with failures: If we can't allocate from the timer cache we try
25003  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25004  * points to b_rptr.
25005  * If we can't allocate anything using allocb_tryhard(), we perform a last
25006  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25007  * save the actual allocation size in b_datap.
25008  */
25009 mblk_t *
25010 tcp_timermp_alloc(int kmflags)
25011 {
25012 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25013 	    kmflags & ~KM_PANIC);
25014 
25015 	if (mp != NULL) {
25016 		mp->b_next = mp->b_prev = NULL;
25017 		mp->b_rptr = (uchar_t *)(&mp[1]);
25018 		mp->b_wptr = NULL;
25019 		mp->b_datap = NULL;
25020 		mp->b_queue = NULL;
25021 		mp->b_cont = NULL;
25022 	} else if (kmflags & KM_PANIC) {
25023 		/*
25024 		 * Failed to allocate memory for the timer. Try allocating from
25025 		 * dblock caches.
25026 		 */
25027 		/* ipclassifier calls this from a constructor - hence no tcps */
25028 		TCP_G_STAT(tcp_timermp_allocfail);
25029 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25030 		if (mp == NULL) {
25031 			size_t size = 0;
25032 			/*
25033 			 * Memory is really low. Try tryhard allocation.
25034 			 *
25035 			 * ipclassifier calls this from a constructor -
25036 			 * hence no tcps
25037 			 */
25038 			TCP_G_STAT(tcp_timermp_allocdblfail);
25039 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25040 			    sizeof (tcp_timer_t), &size, kmflags);
25041 			mp->b_rptr = (uchar_t *)(&mp[1]);
25042 			mp->b_next = mp->b_prev = NULL;
25043 			mp->b_wptr = (uchar_t *)-1;
25044 			mp->b_datap = (dblk_t *)size;
25045 			mp->b_queue = NULL;
25046 			mp->b_cont = NULL;
25047 		}
25048 		ASSERT(mp->b_wptr != NULL);
25049 	}
25050 	/* ipclassifier calls this from a constructor - hence no tcps */
25051 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25052 
25053 	return (mp);
25054 }
25055 
25056 /*
25057  * Free per-tcp timer cache.
25058  * It can only contain entries from tcp_timercache.
25059  */
25060 void
25061 tcp_timermp_free(tcp_t *tcp)
25062 {
25063 	mblk_t *mp;
25064 
25065 	while ((mp = tcp->tcp_timercache) != NULL) {
25066 		ASSERT(mp->b_wptr == NULL);
25067 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25068 		kmem_cache_free(tcp_timercache, mp);
25069 	}
25070 }
25071 
25072 /*
25073  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25074  * events there already (currently at most two events are cached).
25075  * If the event is not allocated from the timer cache, free it right away.
25076  */
25077 static void
25078 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25079 {
25080 	mblk_t *mp1 = tcp->tcp_timercache;
25081 
25082 	if (mp->b_wptr != NULL) {
25083 		/*
25084 		 * This allocation is not from a timer cache, free it right
25085 		 * away.
25086 		 */
25087 		if (mp->b_wptr != (uchar_t *)-1)
25088 			freeb(mp);
25089 		else
25090 			kmem_free(mp, (size_t)mp->b_datap);
25091 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25092 		/* Cache this timer block for future allocations */
25093 		mp->b_rptr = (uchar_t *)(&mp[1]);
25094 		mp->b_next = mp1;
25095 		tcp->tcp_timercache = mp;
25096 	} else {
25097 		kmem_cache_free(tcp_timercache, mp);
25098 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25099 	}
25100 }
25101 
25102 /*
25103  * End of TCP Timers implementation.
25104  */
25105 
25106 /*
25107  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25108  * on the specified backing STREAMS q. Note, the caller may make the
25109  * decision to call based on the tcp_t.tcp_flow_stopped value which
25110  * when check outside the q's lock is only an advisory check ...
25111  */
25112 void
25113 tcp_setqfull(tcp_t *tcp)
25114 {
25115 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25116 	conn_t	*connp = tcp->tcp_connp;
25117 
25118 	if (tcp->tcp_closed)
25119 		return;
25120 
25121 	if (IPCL_IS_NONSTR(connp)) {
25122 		(*connp->conn_upcalls->su_txq_full)
25123 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25124 		tcp->tcp_flow_stopped = B_TRUE;
25125 	} else {
25126 		queue_t *q = tcp->tcp_wq;
25127 
25128 		if (!(q->q_flag & QFULL)) {
25129 			mutex_enter(QLOCK(q));
25130 			if (!(q->q_flag & QFULL)) {
25131 				/* still need to set QFULL */
25132 				q->q_flag |= QFULL;
25133 				tcp->tcp_flow_stopped = B_TRUE;
25134 				mutex_exit(QLOCK(q));
25135 				TCP_STAT(tcps, tcp_flwctl_on);
25136 			} else {
25137 				mutex_exit(QLOCK(q));
25138 			}
25139 		}
25140 	}
25141 }
25142 
25143 void
25144 tcp_clrqfull(tcp_t *tcp)
25145 {
25146 	conn_t  *connp = tcp->tcp_connp;
25147 
25148 	if (tcp->tcp_closed)
25149 		return;
25150 
25151 	if (IPCL_IS_NONSTR(connp)) {
25152 		(*connp->conn_upcalls->su_txq_full)
25153 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25154 		tcp->tcp_flow_stopped = B_FALSE;
25155 	} else {
25156 		queue_t *q = tcp->tcp_wq;
25157 
25158 		if (q->q_flag & QFULL) {
25159 			mutex_enter(QLOCK(q));
25160 			if (q->q_flag & QFULL) {
25161 				q->q_flag &= ~QFULL;
25162 				tcp->tcp_flow_stopped = B_FALSE;
25163 				mutex_exit(QLOCK(q));
25164 				if (q->q_flag & QWANTW)
25165 					qbackenable(q, 0);
25166 			} else {
25167 				mutex_exit(QLOCK(q));
25168 			}
25169 		}
25170 	}
25171 }
25172 
25173 /*
25174  * kstats related to squeues i.e. not per IP instance
25175  */
25176 static void *
25177 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
25178 {
25179 	kstat_t *ksp;
25180 
25181 	tcp_g_stat_t template = {
25182 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
25183 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
25184 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
25185 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
25186 	};
25187 
25188 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
25189 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25190 	    KSTAT_FLAG_VIRTUAL);
25191 
25192 	if (ksp == NULL)
25193 		return (NULL);
25194 
25195 	bcopy(&template, tcp_g_statp, sizeof (template));
25196 	ksp->ks_data = (void *)tcp_g_statp;
25197 
25198 	kstat_install(ksp);
25199 	return (ksp);
25200 }
25201 
25202 static void
25203 tcp_g_kstat_fini(kstat_t *ksp)
25204 {
25205 	if (ksp != NULL) {
25206 		kstat_delete(ksp);
25207 	}
25208 }
25209 
25210 
25211 static void *
25212 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
25213 {
25214 	kstat_t *ksp;
25215 
25216 	tcp_stat_t template = {
25217 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
25218 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
25219 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
25220 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
25221 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
25222 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
25223 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
25224 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
25225 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
25226 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
25227 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
25228 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
25229 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
25230 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
25231 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
25232 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
25233 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
25234 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
25235 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
25236 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
25237 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
25238 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
25239 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
25240 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
25241 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
25242 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
25243 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
25244 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
25245 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
25246 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
25247 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
25248 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
25249 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
25250 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
25251 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
25252 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
25253 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
25254 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
25255 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
25256 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
25257 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
25258 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
25259 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
25260 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
25261 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
25262 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
25263 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
25264 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
25265 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
25266 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
25267 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
25268 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
25269 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
25270 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
25271 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
25272 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
25273 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
25274 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
25275 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
25276 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
25277 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
25278 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
25279 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
25280 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
25281 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
25282 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
25283 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
25284 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
25285 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
25286 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
25287 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
25288 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
25289 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
25290 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
25291 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
25292 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
25293 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
25294 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
25295 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
25296 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
25297 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
25298 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
25299 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
25300 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
25301 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
25302 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
25303 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
25304 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
25305 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
25306 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
25307 	};
25308 
25309 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
25310 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25311 	    KSTAT_FLAG_VIRTUAL, stackid);
25312 
25313 	if (ksp == NULL)
25314 		return (NULL);
25315 
25316 	bcopy(&template, tcps_statisticsp, sizeof (template));
25317 	ksp->ks_data = (void *)tcps_statisticsp;
25318 	ksp->ks_private = (void *)(uintptr_t)stackid;
25319 
25320 	kstat_install(ksp);
25321 	return (ksp);
25322 }
25323 
25324 static void
25325 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
25326 {
25327 	if (ksp != NULL) {
25328 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25329 		kstat_delete_netstack(ksp, stackid);
25330 	}
25331 }
25332 
25333 /*
25334  * TCP Kstats implementation
25335  */
25336 static void *
25337 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
25338 {
25339 	kstat_t	*ksp;
25340 
25341 	tcp_named_kstat_t template = {
25342 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25343 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25344 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25345 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25346 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25347 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25348 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25349 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25350 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25351 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25352 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25353 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25354 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25355 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25356 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25357 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25358 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25359 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25360 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25361 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25362 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25363 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25364 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25365 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25366 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25367 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25368 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25369 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25370 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25371 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25372 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25373 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25374 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25375 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25376 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25377 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25378 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25379 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25380 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25381 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25382 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25383 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25384 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25385 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25386 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25387 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25388 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25389 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25390 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25391 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25392 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25393 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25394 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25395 	};
25396 
25397 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
25398 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
25399 
25400 	if (ksp == NULL)
25401 		return (NULL);
25402 
25403 	template.rtoAlgorithm.value.ui32 = 4;
25404 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
25405 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
25406 	template.maxConn.value.i32 = -1;
25407 
25408 	bcopy(&template, ksp->ks_data, sizeof (template));
25409 	ksp->ks_update = tcp_kstat_update;
25410 	ksp->ks_private = (void *)(uintptr_t)stackid;
25411 
25412 	kstat_install(ksp);
25413 	return (ksp);
25414 }
25415 
25416 static void
25417 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
25418 {
25419 	if (ksp != NULL) {
25420 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25421 		kstat_delete_netstack(ksp, stackid);
25422 	}
25423 }
25424 
25425 static int
25426 tcp_kstat_update(kstat_t *kp, int rw)
25427 {
25428 	tcp_named_kstat_t *tcpkp;
25429 	tcp_t		*tcp;
25430 	connf_t		*connfp;
25431 	conn_t		*connp;
25432 	int 		i;
25433 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
25434 	netstack_t	*ns;
25435 	tcp_stack_t	*tcps;
25436 	ip_stack_t	*ipst;
25437 
25438 	if ((kp == NULL) || (kp->ks_data == NULL))
25439 		return (EIO);
25440 
25441 	if (rw == KSTAT_WRITE)
25442 		return (EACCES);
25443 
25444 	ns = netstack_find_by_stackid(stackid);
25445 	if (ns == NULL)
25446 		return (-1);
25447 	tcps = ns->netstack_tcp;
25448 	if (tcps == NULL) {
25449 		netstack_rele(ns);
25450 		return (-1);
25451 	}
25452 
25453 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25454 
25455 	tcpkp->currEstab.value.ui32 = 0;
25456 
25457 	ipst = ns->netstack_ip;
25458 
25459 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25460 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25461 		connp = NULL;
25462 		while ((connp =
25463 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25464 			tcp = connp->conn_tcp;
25465 			switch (tcp_snmp_state(tcp)) {
25466 			case MIB2_TCP_established:
25467 			case MIB2_TCP_closeWait:
25468 				tcpkp->currEstab.value.ui32++;
25469 				break;
25470 			}
25471 		}
25472 	}
25473 
25474 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
25475 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
25476 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
25477 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
25478 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
25479 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
25480 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
25481 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
25482 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
25483 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
25484 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
25485 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
25486 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
25487 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
25488 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
25489 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
25490 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
25491 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
25492 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
25493 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
25494 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
25495 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
25496 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
25497 	tcpkp->inDataInorderSegs.value.ui32 =
25498 	    tcps->tcps_mib.tcpInDataInorderSegs;
25499 	tcpkp->inDataInorderBytes.value.ui32 =
25500 	    tcps->tcps_mib.tcpInDataInorderBytes;
25501 	tcpkp->inDataUnorderSegs.value.ui32 =
25502 	    tcps->tcps_mib.tcpInDataUnorderSegs;
25503 	tcpkp->inDataUnorderBytes.value.ui32 =
25504 	    tcps->tcps_mib.tcpInDataUnorderBytes;
25505 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
25506 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
25507 	tcpkp->inDataPartDupSegs.value.ui32 =
25508 	    tcps->tcps_mib.tcpInDataPartDupSegs;
25509 	tcpkp->inDataPartDupBytes.value.ui32 =
25510 	    tcps->tcps_mib.tcpInDataPartDupBytes;
25511 	tcpkp->inDataPastWinSegs.value.ui32 =
25512 	    tcps->tcps_mib.tcpInDataPastWinSegs;
25513 	tcpkp->inDataPastWinBytes.value.ui32 =
25514 	    tcps->tcps_mib.tcpInDataPastWinBytes;
25515 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
25516 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
25517 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
25518 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
25519 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
25520 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
25521 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
25522 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
25523 	tcpkp->timKeepaliveProbe.value.ui32 =
25524 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
25525 	tcpkp->timKeepaliveDrop.value.ui32 =
25526 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
25527 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
25528 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
25529 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
25530 	tcpkp->outSackRetransSegs.value.ui32 =
25531 	    tcps->tcps_mib.tcpOutSackRetransSegs;
25532 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
25533 
25534 	netstack_rele(ns);
25535 	return (0);
25536 }
25537 
25538 void
25539 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25540 {
25541 	uint16_t	hdr_len;
25542 	ipha_t		*ipha;
25543 	uint8_t		*nexthdrp;
25544 	tcph_t		*tcph;
25545 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
25546 
25547 	/* Already has an eager */
25548 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25549 		TCP_STAT(tcps, tcp_reinput_syn);
25550 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25551 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
25552 		return;
25553 	}
25554 
25555 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25556 	case IPV4_VERSION:
25557 		ipha = (ipha_t *)mp->b_rptr;
25558 		hdr_len = IPH_HDR_LENGTH(ipha);
25559 		break;
25560 	case IPV6_VERSION:
25561 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25562 		    &hdr_len, &nexthdrp)) {
25563 			CONN_DEC_REF(connp);
25564 			freemsg(mp);
25565 			return;
25566 		}
25567 		break;
25568 	}
25569 
25570 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25571 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25572 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25573 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25574 	}
25575 
25576 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25577 	    SQ_FILL, SQTAG_TCP_REINPUT);
25578 }
25579 
25580 static int
25581 tcp_squeue_switch(int val)
25582 {
25583 	int rval = SQ_FILL;
25584 
25585 	switch (val) {
25586 	case 1:
25587 		rval = SQ_NODRAIN;
25588 		break;
25589 	case 2:
25590 		rval = SQ_PROCESS;
25591 		break;
25592 	default:
25593 		break;
25594 	}
25595 	return (rval);
25596 }
25597 
25598 /*
25599  * This is called once for each squeue - globally for all stack
25600  * instances.
25601  */
25602 static void
25603 tcp_squeue_add(squeue_t *sqp)
25604 {
25605 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25606 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
25607 
25608 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25609 	tcp_time_wait->tcp_time_wait_tid =
25610 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
25611 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
25612 	    CALLOUT_FLAG_ROUNDUP);
25613 	if (tcp_free_list_max_cnt == 0) {
25614 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25615 		    max_ncpus : boot_max_ncpus);
25616 
25617 		/*
25618 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25619 		 */
25620 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25621 		    (tcp_ncpus * sizeof (tcp_t) * 100);
25622 	}
25623 	tcp_time_wait->tcp_free_list_cnt = 0;
25624 }
25625 
25626 static int
25627 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
25628 {
25629 	mblk_t	*ire_mp = NULL;
25630 	mblk_t	*syn_mp;
25631 	mblk_t	*mdti;
25632 	mblk_t	*lsoi;
25633 	int	retval;
25634 	tcph_t	*tcph;
25635 	cred_t	*ecr;
25636 	ts_label_t	*tsl;
25637 	uint32_t	mss;
25638 	queue_t	*q = tcp->tcp_rq;
25639 	conn_t	*connp = tcp->tcp_connp;
25640 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25641 
25642 	if (error == 0) {
25643 		/*
25644 		 * Adapt Multidata information, if any.  The
25645 		 * following tcp_mdt_update routine will free
25646 		 * the message.
25647 		 */
25648 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
25649 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
25650 			    b_rptr)->mdt_capab, B_TRUE);
25651 			freemsg(mdti);
25652 		}
25653 
25654 		/*
25655 		 * Check to update LSO information with tcp, and
25656 		 * tcp_lso_update routine will free the message.
25657 		 */
25658 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
25659 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
25660 			    b_rptr)->lso_capab);
25661 			freemsg(lsoi);
25662 		}
25663 
25664 		/* Get the IRE, if we had requested for it */
25665 		if (mp != NULL)
25666 			ire_mp = tcp_ire_mp(&mp);
25667 
25668 		if (tcp->tcp_hard_binding) {
25669 			tcp->tcp_hard_binding = B_FALSE;
25670 			tcp->tcp_hard_bound = B_TRUE;
25671 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
25672 			if (retval != 0) {
25673 				error = EADDRINUSE;
25674 				goto bind_failed;
25675 			}
25676 		} else {
25677 			if (ire_mp != NULL)
25678 				freeb(ire_mp);
25679 			goto after_syn_sent;
25680 		}
25681 
25682 		retval = tcp_adapt_ire(tcp, ire_mp);
25683 		if (ire_mp != NULL)
25684 			freeb(ire_mp);
25685 		if (retval == 0) {
25686 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
25687 			    ENETUNREACH : EADDRNOTAVAIL);
25688 			goto ipcl_rm;
25689 		}
25690 		/*
25691 		 * Don't let an endpoint connect to itself.
25692 		 * Also checked in tcp_connect() but that
25693 		 * check can't handle the case when the
25694 		 * local IP address is INADDR_ANY.
25695 		 */
25696 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25697 			if ((tcp->tcp_ipha->ipha_dst ==
25698 			    tcp->tcp_ipha->ipha_src) &&
25699 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25700 			    tcp->tcp_tcph->th_fport))) {
25701 				error = EADDRNOTAVAIL;
25702 				goto ipcl_rm;
25703 			}
25704 		} else {
25705 			if (IN6_ARE_ADDR_EQUAL(
25706 			    &tcp->tcp_ip6h->ip6_dst,
25707 			    &tcp->tcp_ip6h->ip6_src) &&
25708 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25709 			    tcp->tcp_tcph->th_fport))) {
25710 				error = EADDRNOTAVAIL;
25711 				goto ipcl_rm;
25712 			}
25713 		}
25714 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
25715 		/*
25716 		 * This should not be possible!  Just for
25717 		 * defensive coding...
25718 		 */
25719 		if (tcp->tcp_state != TCPS_SYN_SENT)
25720 			goto after_syn_sent;
25721 
25722 		if (is_system_labeled() &&
25723 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
25724 			error = EHOSTUNREACH;
25725 			goto ipcl_rm;
25726 		}
25727 
25728 		/*
25729 		 * tcp_adapt_ire() does not adjust
25730 		 * for TCP/IP header length.
25731 		 */
25732 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
25733 
25734 		/*
25735 		 * Just make sure our rwnd is at
25736 		 * least tcp_recv_hiwat_mss * MSS
25737 		 * large, and round up to the nearest
25738 		 * MSS.
25739 		 *
25740 		 * We do the round up here because
25741 		 * we need to get the interface
25742 		 * MTU first before we can do the
25743 		 * round up.
25744 		 */
25745 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
25746 		    tcps->tcps_recv_hiwat_minmss * mss);
25747 		if (!IPCL_IS_NONSTR(connp))
25748 			q->q_hiwat = tcp->tcp_rwnd;
25749 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
25750 		tcp_set_ws_value(tcp);
25751 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
25752 		    tcp->tcp_tcph->th_win);
25753 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
25754 			tcp->tcp_snd_ws_ok = B_TRUE;
25755 
25756 		/*
25757 		 * Set tcp_snd_ts_ok to true
25758 		 * so that tcp_xmit_mp will
25759 		 * include the timestamp
25760 		 * option in the SYN segment.
25761 		 */
25762 		if (tcps->tcps_tstamp_always ||
25763 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
25764 			tcp->tcp_snd_ts_ok = B_TRUE;
25765 		}
25766 
25767 		/*
25768 		 * tcp_snd_sack_ok can be set in
25769 		 * tcp_adapt_ire() if the sack metric
25770 		 * is set.  So check it here also.
25771 		 */
25772 		if (tcps->tcps_sack_permitted == 2 ||
25773 		    tcp->tcp_snd_sack_ok) {
25774 			if (tcp->tcp_sack_info == NULL) {
25775 				tcp->tcp_sack_info =
25776 				    kmem_cache_alloc(tcp_sack_info_cache,
25777 				    KM_SLEEP);
25778 			}
25779 			tcp->tcp_snd_sack_ok = B_TRUE;
25780 		}
25781 
25782 		/*
25783 		 * Should we use ECN?  Note that the current
25784 		 * default value (SunOS 5.9) of tcp_ecn_permitted
25785 		 * is 1.  The reason for doing this is that there
25786 		 * are equipments out there that will drop ECN
25787 		 * enabled IP packets.  Setting it to 1 avoids
25788 		 * compatibility problems.
25789 		 */
25790 		if (tcps->tcps_ecn_permitted == 2)
25791 			tcp->tcp_ecn_ok = B_TRUE;
25792 
25793 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
25794 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
25795 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
25796 		if (syn_mp) {
25797 			/*
25798 			 * cr contains the cred from the thread calling
25799 			 * connect().
25800 			 *
25801 			 * If no thread cred is available, use the
25802 			 * socket creator's cred instead. If still no
25803 			 * cred, drop the request rather than risk a
25804 			 * panic on production systems.
25805 			 */
25806 			if (cr == NULL) {
25807 				cr = CONN_CRED(connp);
25808 				pid = tcp->tcp_cpid;
25809 				ASSERT(cr != NULL);
25810 				if (cr != NULL) {
25811 					mblk_setcred(syn_mp, cr, pid);
25812 				} else {
25813 					error = ECONNABORTED;
25814 					goto ipcl_rm;
25815 				}
25816 
25817 			/*
25818 			 * If an effective security label exists for
25819 			 * the connection, create a copy of the thread's
25820 			 * cred but with the effective label attached.
25821 			 */
25822 			} else if (is_system_labeled() &&
25823 			    connp->conn_effective_cred != NULL &&
25824 			    (tsl = crgetlabel(connp->
25825 			    conn_effective_cred)) != NULL) {
25826 				if ((ecr = copycred_from_tslabel(cr,
25827 				    tsl, KM_NOSLEEP)) == NULL) {
25828 					error = ENOMEM;
25829 					goto ipcl_rm;
25830 				}
25831 				mblk_setcred(syn_mp, ecr, pid);
25832 				crfree(ecr);
25833 
25834 			/*
25835 			 * Default to using the thread's cred unchanged.
25836 			 */
25837 			} else {
25838 				mblk_setcred(syn_mp, cr, pid);
25839 			}
25840 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
25841 		}
25842 	after_syn_sent:
25843 		if (mp != NULL) {
25844 			ASSERT(mp->b_cont == NULL);
25845 			freeb(mp);
25846 		}
25847 		return (error);
25848 	} else {
25849 		/* error */
25850 		if (tcp->tcp_debug) {
25851 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
25852 			    "tcp_post_ip_bind: error == %d", error);
25853 		}
25854 		if (mp != NULL) {
25855 			freeb(mp);
25856 		}
25857 	}
25858 
25859 ipcl_rm:
25860 	/*
25861 	 * Need to unbind with classifier since we were just
25862 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
25863 	 */
25864 	tcp->tcp_hard_bound = B_FALSE;
25865 	tcp->tcp_hard_binding = B_FALSE;
25866 
25867 	ipcl_hash_remove(connp);
25868 
25869 bind_failed:
25870 	tcp->tcp_state = TCPS_IDLE;
25871 	if (tcp->tcp_ipversion == IPV4_VERSION)
25872 		tcp->tcp_ipha->ipha_src = 0;
25873 	else
25874 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
25875 	/*
25876 	 * Copy of the src addr. in tcp_t is needed since
25877 	 * the lookup funcs. can only look at tcp_t
25878 	 */
25879 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
25880 
25881 	tcph = tcp->tcp_tcph;
25882 	tcph->th_lport[0] = 0;
25883 	tcph->th_lport[1] = 0;
25884 	tcp_bind_hash_remove(tcp);
25885 	bzero(&connp->u_port, sizeof (connp->u_port));
25886 	/* blow away saved option results if any */
25887 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
25888 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
25889 
25890 	conn_delete_ire(tcp->tcp_connp, NULL);
25891 
25892 	return (error);
25893 }
25894 
25895 static int
25896 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
25897     boolean_t bind_to_req_port_only, cred_t *cr)
25898 {
25899 	in_port_t	mlp_port;
25900 	mlp_type_t 	addrtype, mlptype;
25901 	boolean_t	user_specified;
25902 	in_port_t	allocated_port;
25903 	in_port_t	requested_port = *requested_port_ptr;
25904 	conn_t		*connp;
25905 	zone_t		*zone;
25906 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25907 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
25908 
25909 	/*
25910 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
25911 	 */
25912 	if (cr == NULL)
25913 		cr = tcp->tcp_cred;
25914 	/*
25915 	 * Get a valid port (within the anonymous range and should not
25916 	 * be a privileged one) to use if the user has not given a port.
25917 	 * If multiple threads are here, they may all start with
25918 	 * with the same initial port. But, it should be fine as long as
25919 	 * tcp_bindi will ensure that no two threads will be assigned
25920 	 * the same port.
25921 	 *
25922 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
25923 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
25924 	 * unless TCP_ANONPRIVBIND option is set.
25925 	 */
25926 	mlptype = mlptSingle;
25927 	mlp_port = requested_port;
25928 	if (requested_port == 0) {
25929 		requested_port = tcp->tcp_anon_priv_bind ?
25930 		    tcp_get_next_priv_port(tcp) :
25931 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
25932 		    tcp, B_TRUE);
25933 		if (requested_port == 0) {
25934 			return (-TNOADDR);
25935 		}
25936 		user_specified = B_FALSE;
25937 
25938 		/*
25939 		 * If the user went through one of the RPC interfaces to create
25940 		 * this socket and RPC is MLP in this zone, then give him an
25941 		 * anonymous MLP.
25942 		 */
25943 		connp = tcp->tcp_connp;
25944 		if (connp->conn_anon_mlp && is_system_labeled()) {
25945 			zone = crgetzone(cr);
25946 			addrtype = tsol_mlp_addr_type(zone->zone_id,
25947 			    IPV6_VERSION, &v6addr,
25948 			    tcps->tcps_netstack->netstack_ip);
25949 			if (addrtype == mlptSingle) {
25950 				return (-TNOADDR);
25951 			}
25952 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25953 			    PMAPPORT, addrtype);
25954 			mlp_port = PMAPPORT;
25955 		}
25956 	} else {
25957 		int i;
25958 		boolean_t priv = B_FALSE;
25959 
25960 		/*
25961 		 * If the requested_port is in the well-known privileged range,
25962 		 * verify that the stream was opened by a privileged user.
25963 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
25964 		 * but instead the code relies on:
25965 		 * - the fact that the address of the array and its size never
25966 		 *   changes
25967 		 * - the atomic assignment of the elements of the array
25968 		 */
25969 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
25970 			priv = B_TRUE;
25971 		} else {
25972 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
25973 				if (requested_port ==
25974 				    tcps->tcps_g_epriv_ports[i]) {
25975 					priv = B_TRUE;
25976 					break;
25977 				}
25978 			}
25979 		}
25980 		if (priv) {
25981 			if (secpolicy_net_privaddr(cr, requested_port,
25982 			    IPPROTO_TCP) != 0) {
25983 				if (tcp->tcp_debug) {
25984 					(void) strlog(TCP_MOD_ID, 0, 1,
25985 					    SL_ERROR|SL_TRACE,
25986 					    "tcp_bind: no priv for port %d",
25987 					    requested_port);
25988 				}
25989 				return (-TACCES);
25990 			}
25991 		}
25992 		user_specified = B_TRUE;
25993 
25994 		connp = tcp->tcp_connp;
25995 		if (is_system_labeled()) {
25996 			zone = crgetzone(cr);
25997 			addrtype = tsol_mlp_addr_type(zone->zone_id,
25998 			    IPV6_VERSION, &v6addr,
25999 			    tcps->tcps_netstack->netstack_ip);
26000 			if (addrtype == mlptSingle) {
26001 				return (-TNOADDR);
26002 			}
26003 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26004 			    requested_port, addrtype);
26005 		}
26006 	}
26007 
26008 	if (mlptype != mlptSingle) {
26009 		if (secpolicy_net_bindmlp(cr) != 0) {
26010 			if (tcp->tcp_debug) {
26011 				(void) strlog(TCP_MOD_ID, 0, 1,
26012 				    SL_ERROR|SL_TRACE,
26013 				    "tcp_bind: no priv for multilevel port %d",
26014 				    requested_port);
26015 			}
26016 			return (-TACCES);
26017 		}
26018 
26019 		/*
26020 		 * If we're specifically binding a shared IP address and the
26021 		 * port is MLP on shared addresses, then check to see if this
26022 		 * zone actually owns the MLP.  Reject if not.
26023 		 */
26024 		if (mlptype == mlptShared && addrtype == mlptShared) {
26025 			/*
26026 			 * No need to handle exclusive-stack zones since
26027 			 * ALL_ZONES only applies to the shared stack.
26028 			 */
26029 			zoneid_t mlpzone;
26030 
26031 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26032 			    htons(mlp_port));
26033 			if (connp->conn_zoneid != mlpzone) {
26034 				if (tcp->tcp_debug) {
26035 					(void) strlog(TCP_MOD_ID, 0, 1,
26036 					    SL_ERROR|SL_TRACE,
26037 					    "tcp_bind: attempt to bind port "
26038 					    "%d on shared addr in zone %d "
26039 					    "(should be %d)",
26040 					    mlp_port, connp->conn_zoneid,
26041 					    mlpzone);
26042 				}
26043 				return (-TACCES);
26044 			}
26045 		}
26046 
26047 		if (!user_specified) {
26048 			int err;
26049 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26050 			    requested_port, B_TRUE);
26051 			if (err != 0) {
26052 				if (tcp->tcp_debug) {
26053 					(void) strlog(TCP_MOD_ID, 0, 1,
26054 					    SL_ERROR|SL_TRACE,
26055 					    "tcp_bind: cannot establish anon "
26056 					    "MLP for port %d",
26057 					    requested_port);
26058 				}
26059 				return (err);
26060 			}
26061 			connp->conn_anon_port = B_TRUE;
26062 		}
26063 		connp->conn_mlp_type = mlptype;
26064 	}
26065 
26066 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26067 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26068 
26069 	if (allocated_port == 0) {
26070 		connp->conn_mlp_type = mlptSingle;
26071 		if (connp->conn_anon_port) {
26072 			connp->conn_anon_port = B_FALSE;
26073 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26074 			    requested_port, B_FALSE);
26075 		}
26076 		if (bind_to_req_port_only) {
26077 			if (tcp->tcp_debug) {
26078 				(void) strlog(TCP_MOD_ID, 0, 1,
26079 				    SL_ERROR|SL_TRACE,
26080 				    "tcp_bind: requested addr busy");
26081 			}
26082 			return (-TADDRBUSY);
26083 		} else {
26084 			/* If we are out of ports, fail the bind. */
26085 			if (tcp->tcp_debug) {
26086 				(void) strlog(TCP_MOD_ID, 0, 1,
26087 				    SL_ERROR|SL_TRACE,
26088 				    "tcp_bind: out of ports?");
26089 			}
26090 			return (-TNOADDR);
26091 		}
26092 	}
26093 
26094 	/* Pass the allocated port back */
26095 	*requested_port_ptr = allocated_port;
26096 	return (0);
26097 }
26098 
26099 static int
26100 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26101     boolean_t bind_to_req_port_only)
26102 {
26103 	tcp_t	*tcp = connp->conn_tcp;
26104 	sin_t	*sin;
26105 	sin6_t  *sin6;
26106 	in_port_t requested_port;
26107 	ipaddr_t	v4addr;
26108 	in6_addr_t	v6addr;
26109 	uint_t	origipversion;
26110 	int	error = 0;
26111 
26112 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26113 
26114 	if (tcp->tcp_state == TCPS_BOUND) {
26115 		return (0);
26116 	} else if (tcp->tcp_state > TCPS_BOUND) {
26117 		if (tcp->tcp_debug) {
26118 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26119 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26120 		}
26121 		return (-TOUTSTATE);
26122 	}
26123 	origipversion = tcp->tcp_ipversion;
26124 
26125 	ASSERT(sa != NULL && len != 0);
26126 
26127 	if (!OK_32PTR((char *)sa)) {
26128 		if (tcp->tcp_debug) {
26129 			(void) strlog(TCP_MOD_ID, 0, 1,
26130 			    SL_ERROR|SL_TRACE,
26131 			    "tcp_bind: bad address parameter, "
26132 			    "address %p, len %d",
26133 			    (void *)sa, len);
26134 		}
26135 		return (-TPROTO);
26136 	}
26137 
26138 	switch (len) {
26139 	case sizeof (sin_t):	/* Complete IPv4 address */
26140 		sin = (sin_t *)sa;
26141 		/*
26142 		 * With sockets sockfs will accept bogus sin_family in
26143 		 * bind() and replace it with the family used in the socket
26144 		 * call.
26145 		 */
26146 		if (sin->sin_family != AF_INET ||
26147 		    tcp->tcp_family != AF_INET) {
26148 			return (EAFNOSUPPORT);
26149 		}
26150 		requested_port = ntohs(sin->sin_port);
26151 		tcp->tcp_ipversion = IPV4_VERSION;
26152 		v4addr = sin->sin_addr.s_addr;
26153 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26154 		break;
26155 
26156 	case sizeof (sin6_t): /* Complete IPv6 address */
26157 		sin6 = (sin6_t *)sa;
26158 		if (sin6->sin6_family != AF_INET6 ||
26159 		    tcp->tcp_family != AF_INET6) {
26160 			return (EAFNOSUPPORT);
26161 		}
26162 		requested_port = ntohs(sin6->sin6_port);
26163 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26164 		    IPV4_VERSION : IPV6_VERSION;
26165 		v6addr = sin6->sin6_addr;
26166 		break;
26167 
26168 	default:
26169 		if (tcp->tcp_debug) {
26170 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26171 			    "tcp_bind: bad address length, %d", len);
26172 		}
26173 		return (EAFNOSUPPORT);
26174 		/* return (-TBADADDR); */
26175 	}
26176 
26177 	tcp->tcp_bound_source_v6 = v6addr;
26178 
26179 	/* Check for change in ipversion */
26180 	if (origipversion != tcp->tcp_ipversion) {
26181 		ASSERT(tcp->tcp_family == AF_INET6);
26182 		error = tcp->tcp_ipversion == IPV6_VERSION ?
26183 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26184 		if (error) {
26185 			return (ENOMEM);
26186 		}
26187 	}
26188 
26189 	/*
26190 	 * Initialize family specific fields. Copy of the src addr.
26191 	 * in tcp_t is needed for the lookup funcs.
26192 	 */
26193 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26194 		tcp->tcp_ip6h->ip6_src = v6addr;
26195 	} else {
26196 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
26197 	}
26198 	tcp->tcp_ip_src_v6 = v6addr;
26199 
26200 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
26201 
26202 	error = tcp_bind_select_lport(tcp, &requested_port,
26203 	    bind_to_req_port_only, cr);
26204 
26205 	return (error);
26206 }
26207 
26208 /*
26209  * Return unix error is tli error is TSYSERR, otherwise return a negative
26210  * tli error.
26211  */
26212 int
26213 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26214     boolean_t bind_to_req_port_only)
26215 {
26216 	int error;
26217 	tcp_t *tcp = connp->conn_tcp;
26218 
26219 	if (tcp->tcp_state >= TCPS_BOUND) {
26220 		if (tcp->tcp_debug) {
26221 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26222 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26223 		}
26224 		return (-TOUTSTATE);
26225 	}
26226 
26227 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
26228 	if (error != 0)
26229 		return (error);
26230 
26231 	ASSERT(tcp->tcp_state == TCPS_BOUND);
26232 
26233 	tcp->tcp_conn_req_max = 0;
26234 
26235 	if (tcp->tcp_family == AF_INET6) {
26236 		ASSERT(tcp->tcp_connp->conn_af_isv6);
26237 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
26238 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
26239 	} else {
26240 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
26241 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
26242 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
26243 	}
26244 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
26245 }
26246 
26247 int
26248 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
26249     socklen_t len, cred_t *cr)
26250 {
26251 	int 		error;
26252 	conn_t		*connp = (conn_t *)proto_handle;
26253 	squeue_t	*sqp = connp->conn_sqp;
26254 
26255 	/* All Solaris components should pass a cred for this operation. */
26256 	ASSERT(cr != NULL);
26257 
26258 	ASSERT(sqp != NULL);
26259 	ASSERT(connp->conn_upper_handle != NULL);
26260 
26261 	error = squeue_synch_enter(sqp, connp, NULL);
26262 	if (error != 0) {
26263 		/* failed to enter */
26264 		return (ENOSR);
26265 	}
26266 
26267 	/* binding to a NULL address really means unbind */
26268 	if (sa == NULL) {
26269 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
26270 			error = tcp_do_unbind(connp);
26271 		else
26272 			error = EINVAL;
26273 	} else {
26274 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
26275 	}
26276 
26277 	squeue_synch_exit(sqp, connp);
26278 
26279 	if (error < 0) {
26280 		if (error == -TOUTSTATE)
26281 			error = EINVAL;
26282 		else
26283 			error = proto_tlitosyserr(-error);
26284 	}
26285 
26286 	return (error);
26287 }
26288 
26289 /*
26290  * If the return value from this function is positive, it's a UNIX error.
26291  * Otherwise, if it's negative, then the absolute value is a TLI error.
26292  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
26293  */
26294 int
26295 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
26296     cred_t *cr, pid_t pid)
26297 {
26298 	tcp_t		*tcp = connp->conn_tcp;
26299 	sin_t		*sin = (sin_t *)sa;
26300 	sin6_t		*sin6 = (sin6_t *)sa;
26301 	ipaddr_t	*dstaddrp;
26302 	in_port_t	dstport;
26303 	uint_t		srcid;
26304 	int		error = 0;
26305 
26306 	switch (len) {
26307 	default:
26308 		/*
26309 		 * Should never happen
26310 		 */
26311 		return (EINVAL);
26312 
26313 	case sizeof (sin_t):
26314 		sin = (sin_t *)sa;
26315 		if (sin->sin_port == 0) {
26316 			return (-TBADADDR);
26317 		}
26318 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
26319 			return (EAFNOSUPPORT);
26320 		}
26321 		break;
26322 
26323 	case sizeof (sin6_t):
26324 		sin6 = (sin6_t *)sa;
26325 		if (sin6->sin6_port == 0) {
26326 			return (-TBADADDR);
26327 		}
26328 		break;
26329 	}
26330 	/*
26331 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
26332 	 * make sure that the template IP header in the tcp structure is an
26333 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
26334 	 * need to this before we call tcp_bindi() so that the port lookup
26335 	 * code will look for ports in the correct port space (IPv4 and
26336 	 * IPv6 have separate port spaces).
26337 	 */
26338 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
26339 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26340 		int err = 0;
26341 
26342 		err = tcp_header_init_ipv4(tcp);
26343 			if (err != 0) {
26344 				error = ENOMEM;
26345 				goto connect_failed;
26346 			}
26347 		if (tcp->tcp_lport != 0)
26348 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
26349 	}
26350 
26351 	switch (tcp->tcp_state) {
26352 	case TCPS_LISTEN:
26353 		/*
26354 		 * Listening sockets are not allowed to issue connect().
26355 		 */
26356 		if (IPCL_IS_NONSTR(connp))
26357 			return (EOPNOTSUPP);
26358 		/* FALLTHRU */
26359 	case TCPS_IDLE:
26360 		/*
26361 		 * We support quick connect, refer to comments in
26362 		 * tcp_connect_*()
26363 		 */
26364 		/* FALLTHRU */
26365 	case TCPS_BOUND:
26366 		/*
26367 		 * We must bump the generation before the operation start.
26368 		 * This is done to ensure that any upcall made later on sends
26369 		 * up the right generation to the socket.
26370 		 */
26371 		SOCK_CONNID_BUMP(tcp->tcp_connid);
26372 
26373 		if (tcp->tcp_family == AF_INET6) {
26374 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26375 				return (tcp_connect_ipv6(tcp,
26376 				    &sin6->sin6_addr,
26377 				    sin6->sin6_port, sin6->sin6_flowinfo,
26378 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
26379 				    cr, pid));
26380 			}
26381 			/*
26382 			 * Destination adress is mapped IPv6 address.
26383 			 * Source bound address should be unspecified or
26384 			 * IPv6 mapped address as well.
26385 			 */
26386 			if (!IN6_IS_ADDR_UNSPECIFIED(
26387 			    &tcp->tcp_bound_source_v6) &&
26388 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
26389 				return (EADDRNOTAVAIL);
26390 			}
26391 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
26392 			dstport = sin6->sin6_port;
26393 			srcid = sin6->__sin6_src_id;
26394 		} else {
26395 			dstaddrp = &sin->sin_addr.s_addr;
26396 			dstport = sin->sin_port;
26397 			srcid = 0;
26398 		}
26399 
26400 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
26401 		    pid);
26402 		break;
26403 	default:
26404 		return (-TOUTSTATE);
26405 	}
26406 	/*
26407 	 * Note: Code below is the "failure" case
26408 	 */
26409 connect_failed:
26410 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26411 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26412 	return (error);
26413 }
26414 
26415 int
26416 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
26417     socklen_t len, sock_connid_t *id, cred_t *cr)
26418 {
26419 	conn_t		*connp = (conn_t *)proto_handle;
26420 	tcp_t		*tcp = connp->conn_tcp;
26421 	squeue_t	*sqp = connp->conn_sqp;
26422 	int		error;
26423 
26424 	ASSERT(connp->conn_upper_handle != NULL);
26425 
26426 	/* All Solaris components should pass a cred for this operation. */
26427 	ASSERT(cr != NULL);
26428 
26429 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
26430 	if (error != 0) {
26431 		return (error);
26432 	}
26433 
26434 	error = squeue_synch_enter(sqp, connp, NULL);
26435 	if (error != 0) {
26436 		/* failed to enter */
26437 		return (ENOSR);
26438 	}
26439 
26440 	/*
26441 	 * TCP supports quick connect, so no need to do an implicit bind
26442 	 */
26443 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
26444 	if (error == 0) {
26445 		*id = connp->conn_tcp->tcp_connid;
26446 	} else if (error < 0) {
26447 		if (error == -TOUTSTATE) {
26448 			switch (connp->conn_tcp->tcp_state) {
26449 			case TCPS_SYN_SENT:
26450 				error = EALREADY;
26451 				break;
26452 			case TCPS_ESTABLISHED:
26453 				error = EISCONN;
26454 				break;
26455 			case TCPS_LISTEN:
26456 				error = EOPNOTSUPP;
26457 				break;
26458 			default:
26459 				error = EINVAL;
26460 				break;
26461 			}
26462 		} else {
26463 			error = proto_tlitosyserr(-error);
26464 		}
26465 	}
26466 done:
26467 	squeue_synch_exit(sqp, connp);
26468 
26469 	return ((error == 0) ? EINPROGRESS : error);
26470 }
26471 
26472 /* ARGSUSED */
26473 sock_lower_handle_t
26474 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
26475     uint_t *smodep, int *errorp, int flags, cred_t *credp)
26476 {
26477 	conn_t		*connp;
26478 	boolean_t	isv6 = family == AF_INET6;
26479 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
26480 	    (proto != 0 && proto != IPPROTO_TCP)) {
26481 		*errorp = EPROTONOSUPPORT;
26482 		return (NULL);
26483 	}
26484 
26485 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
26486 	if (connp == NULL) {
26487 		return (NULL);
26488 	}
26489 
26490 	/*
26491 	 * Put the ref for TCP. Ref for IP was already put
26492 	 * by ipcl_conn_create. Also Make the conn_t globally
26493 	 * visible to walkers
26494 	 */
26495 	mutex_enter(&connp->conn_lock);
26496 	CONN_INC_REF_LOCKED(connp);
26497 	ASSERT(connp->conn_ref == 2);
26498 	connp->conn_state_flags &= ~CONN_INCIPIENT;
26499 
26500 	connp->conn_flags |= IPCL_NONSTR;
26501 	mutex_exit(&connp->conn_lock);
26502 
26503 	ASSERT(errorp != NULL);
26504 	*errorp = 0;
26505 	*sock_downcalls = &sock_tcp_downcalls;
26506 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
26507 	    SM_SENDFILESUPP;
26508 
26509 	return ((sock_lower_handle_t)connp);
26510 }
26511 
26512 /* ARGSUSED */
26513 void
26514 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
26515     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
26516 {
26517 	conn_t *connp = (conn_t *)proto_handle;
26518 	struct sock_proto_props sopp;
26519 
26520 	ASSERT(connp->conn_upper_handle == NULL);
26521 
26522 	/* All Solaris components should pass a cred for this operation. */
26523 	ASSERT(cr != NULL);
26524 
26525 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
26526 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
26527 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
26528 
26529 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
26530 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
26531 	sopp.sopp_maxpsz = INFPSZ;
26532 	sopp.sopp_maxblk = INFPSZ;
26533 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
26534 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
26535 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
26536 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
26537 	    tcp_rinfo.mi_minpsz;
26538 
26539 	connp->conn_upcalls = sock_upcalls;
26540 	connp->conn_upper_handle = sock_handle;
26541 
26542 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
26543 }
26544 
26545 /* ARGSUSED */
26546 int
26547 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
26548 {
26549 	conn_t *connp = (conn_t *)proto_handle;
26550 
26551 	ASSERT(connp->conn_upper_handle != NULL);
26552 
26553 	/* All Solaris components should pass a cred for this operation. */
26554 	ASSERT(cr != NULL);
26555 
26556 	tcp_close_common(connp, flags);
26557 
26558 	ip_free_helper_stream(connp);
26559 
26560 	/*
26561 	 * Drop IP's reference on the conn. This is the last reference
26562 	 * on the connp if the state was less than established. If the
26563 	 * connection has gone into timewait state, then we will have
26564 	 * one ref for the TCP and one more ref (total of two) for the
26565 	 * classifier connected hash list (a timewait connections stays
26566 	 * in connected hash till closed).
26567 	 *
26568 	 * We can't assert the references because there might be other
26569 	 * transient reference places because of some walkers or queued
26570 	 * packets in squeue for the timewait state.
26571 	 */
26572 	CONN_DEC_REF(connp);
26573 	return (0);
26574 }
26575 
26576 /* ARGSUSED */
26577 int
26578 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
26579     cred_t *cr)
26580 {
26581 	tcp_t		*tcp;
26582 	uint32_t	msize;
26583 	conn_t *connp = (conn_t *)proto_handle;
26584 	int32_t		tcpstate;
26585 
26586 	/* All Solaris components should pass a cred for this operation. */
26587 	ASSERT(cr != NULL);
26588 
26589 	ASSERT(connp->conn_ref >= 2);
26590 	ASSERT(connp->conn_upper_handle != NULL);
26591 
26592 	if (msg->msg_controllen != 0) {
26593 		return (EOPNOTSUPP);
26594 
26595 	}
26596 	switch (DB_TYPE(mp)) {
26597 	case M_DATA:
26598 		tcp = connp->conn_tcp;
26599 		ASSERT(tcp != NULL);
26600 
26601 		tcpstate = tcp->tcp_state;
26602 		if (tcpstate < TCPS_ESTABLISHED) {
26603 			freemsg(mp);
26604 			return (ENOTCONN);
26605 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
26606 			freemsg(mp);
26607 			return (EPIPE);
26608 		}
26609 
26610 		msize = msgdsize(mp);
26611 
26612 		mutex_enter(&tcp->tcp_non_sq_lock);
26613 		tcp->tcp_squeue_bytes += msize;
26614 		/*
26615 		 * Squeue Flow Control
26616 		 */
26617 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
26618 			tcp_setqfull(tcp);
26619 		}
26620 		mutex_exit(&tcp->tcp_non_sq_lock);
26621 
26622 		/*
26623 		 * The application may pass in an address in the msghdr, but
26624 		 * we ignore the address on connection-oriented sockets.
26625 		 * Just like BSD this code does not generate an error for
26626 		 * TCP (a CONNREQUIRED socket) when sending to an address
26627 		 * passed in with sendto/sendmsg. Instead the data is
26628 		 * delivered on the connection as if no address had been
26629 		 * supplied.
26630 		 */
26631 		CONN_INC_REF(connp);
26632 
26633 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
26634 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
26635 			    tcp_output_urgent, connp, tcp_squeue_flag,
26636 			    SQTAG_TCP_OUTPUT);
26637 		} else {
26638 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
26639 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
26640 		}
26641 
26642 		return (0);
26643 
26644 	default:
26645 		ASSERT(0);
26646 	}
26647 
26648 	freemsg(mp);
26649 	return (0);
26650 }
26651 
26652 /* ARGSUSED */
26653 void
26654 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
26655 {
26656 	int len;
26657 	uint32_t msize;
26658 	conn_t *connp = (conn_t *)arg;
26659 	tcp_t *tcp = connp->conn_tcp;
26660 
26661 	msize = msgdsize(mp);
26662 
26663 	len = msize - 1;
26664 	if (len < 0) {
26665 		freemsg(mp);
26666 		return;
26667 	}
26668 
26669 	/*
26670 	 * Try to force urgent data out on the wire.
26671 	 * Even if we have unsent data this will
26672 	 * at least send the urgent flag.
26673 	 * XXX does not handle more flag correctly.
26674 	 */
26675 	len += tcp->tcp_unsent;
26676 	len += tcp->tcp_snxt;
26677 	tcp->tcp_urg = len;
26678 	tcp->tcp_valid_bits |= TCP_URG_VALID;
26679 
26680 	/* Bypass tcp protocol for fused tcp loopback */
26681 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
26682 		return;
26683 	tcp_wput_data(tcp, mp, B_TRUE);
26684 }
26685 
26686 /* ARGSUSED */
26687 int
26688 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26689     socklen_t *addrlenp, cred_t *cr)
26690 {
26691 	conn_t	*connp = (conn_t *)proto_handle;
26692 	tcp_t	*tcp = connp->conn_tcp;
26693 
26694 	ASSERT(connp->conn_upper_handle != NULL);
26695 	/* All Solaris components should pass a cred for this operation. */
26696 	ASSERT(cr != NULL);
26697 
26698 	ASSERT(tcp != NULL);
26699 
26700 	return (tcp_do_getpeername(tcp, addr, addrlenp));
26701 }
26702 
26703 /* ARGSUSED */
26704 int
26705 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26706     socklen_t *addrlenp, cred_t *cr)
26707 {
26708 	conn_t	*connp = (conn_t *)proto_handle;
26709 	tcp_t	*tcp = connp->conn_tcp;
26710 
26711 	/* All Solaris components should pass a cred for this operation. */
26712 	ASSERT(cr != NULL);
26713 
26714 	ASSERT(connp->conn_upper_handle != NULL);
26715 
26716 	return (tcp_do_getsockname(tcp, addr, addrlenp));
26717 }
26718 
26719 /*
26720  * tcp_fallback
26721  *
26722  * A direct socket is falling back to using STREAMS. The queue
26723  * that is being passed down was created using tcp_open() with
26724  * the SO_FALLBACK flag set. As a result, the queue is not
26725  * associated with a conn, and the q_ptrs instead contain the
26726  * dev and minor area that should be used.
26727  *
26728  * The 'direct_sockfs' flag indicates whether the FireEngine
26729  * optimizations should be used. The common case would be that
26730  * optimizations are enabled, and they might be subsequently
26731  * disabled using the _SIOCSOCKFALLBACK ioctl.
26732  */
26733 
26734 /*
26735  * An active connection is falling back to TPI. Gather all the information
26736  * required by the STREAM head and TPI sonode and send it up.
26737  */
26738 void
26739 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
26740     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
26741 {
26742 	conn_t			*connp = tcp->tcp_connp;
26743 	struct stroptions	*stropt;
26744 	struct T_capability_ack tca;
26745 	struct sockaddr_in6	laddr, faddr;
26746 	socklen_t 		laddrlen, faddrlen;
26747 	short			opts;
26748 	int			error;
26749 	mblk_t			*mp;
26750 
26751 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
26752 	connp->conn_minor_arena = WR(q)->q_ptr;
26753 
26754 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
26755 
26756 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
26757 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
26758 
26759 	WR(q)->q_qinfo = &tcp_sock_winit;
26760 
26761 	if (!direct_sockfs)
26762 		tcp_disable_direct_sockfs(tcp);
26763 
26764 	/*
26765 	 * free the helper stream
26766 	 */
26767 	ip_free_helper_stream(connp);
26768 
26769 	/*
26770 	 * Notify the STREAM head about options
26771 	 */
26772 	DB_TYPE(stropt_mp) = M_SETOPTS;
26773 	stropt = (struct stroptions *)stropt_mp->b_rptr;
26774 	stropt_mp->b_wptr += sizeof (struct stroptions);
26775 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
26776 
26777 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
26778 	    tcp->tcp_tcps->tcps_wroff_xtra);
26779 	if (tcp->tcp_snd_sack_ok)
26780 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
26781 	stropt->so_hiwat = tcp->tcp_fused ?
26782 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
26783 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
26784 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
26785 
26786 	putnext(RD(q), stropt_mp);
26787 
26788 	/*
26789 	 * Collect the information needed to sync with the sonode
26790 	 */
26791 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
26792 
26793 	laddrlen = faddrlen = sizeof (sin6_t);
26794 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
26795 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
26796 	if (error != 0)
26797 		faddrlen = 0;
26798 
26799 	opts = 0;
26800 	if (tcp->tcp_oobinline)
26801 		opts |= SO_OOBINLINE;
26802 	if (tcp->tcp_dontroute)
26803 		opts |= SO_DONTROUTE;
26804 
26805 	/*
26806 	 * Notify the socket that the protocol is now quiescent,
26807 	 * and it's therefore safe move data from the socket
26808 	 * to the stream head.
26809 	 */
26810 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
26811 	    (struct sockaddr *)&laddr, laddrlen,
26812 	    (struct sockaddr *)&faddr, faddrlen, opts);
26813 
26814 	while ((mp = tcp->tcp_rcv_list) != NULL) {
26815 		tcp->tcp_rcv_list = mp->b_next;
26816 		mp->b_next = NULL;
26817 		putnext(q, mp);
26818 	}
26819 	tcp->tcp_rcv_last_head = NULL;
26820 	tcp->tcp_rcv_last_tail = NULL;
26821 	tcp->tcp_rcv_cnt = 0;
26822 }
26823 
26824 /*
26825  * An eager is falling back to TPI. All we have to do is send
26826  * up a T_CONN_IND.
26827  */
26828 void
26829 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
26830 {
26831 	tcp_t *listener = eager->tcp_listener;
26832 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
26833 
26834 	ASSERT(listener != NULL);
26835 	ASSERT(mp != NULL);
26836 
26837 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
26838 
26839 	/*
26840 	 * TLI/XTI applications will get confused by
26841 	 * sending eager as an option since it violates
26842 	 * the option semantics. So remove the eager as
26843 	 * option since TLI/XTI app doesn't need it anyway.
26844 	 */
26845 	if (!direct_sockfs) {
26846 		struct T_conn_ind *conn_ind;
26847 
26848 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
26849 		conn_ind->OPT_length = 0;
26850 		conn_ind->OPT_offset = 0;
26851 	}
26852 
26853 	/*
26854 	 * Sockfs guarantees that the listener will not be closed
26855 	 * during fallback. So we can safely use the listener's queue.
26856 	 */
26857 	putnext(listener->tcp_rq, mp);
26858 }
26859 
26860 int
26861 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
26862     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
26863 {
26864 	tcp_t			*tcp;
26865 	conn_t 			*connp = (conn_t *)proto_handle;
26866 	int			error;
26867 	mblk_t			*stropt_mp;
26868 	mblk_t			*ordrel_mp;
26869 	mblk_t			*fused_sigurp_mp;
26870 
26871 	tcp = connp->conn_tcp;
26872 
26873 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
26874 	    NULL);
26875 
26876 	/* Pre-allocate the T_ordrel_ind mblk. */
26877 	ASSERT(tcp->tcp_ordrel_mp == NULL);
26878 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
26879 	    STR_NOSIG, NULL);
26880 	ordrel_mp->b_datap->db_type = M_PROTO;
26881 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
26882 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
26883 
26884 	/* Pre-allocate the M_PCSIG used by fusion */
26885 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
26886 
26887 	/*
26888 	 * Enter the squeue so that no new packets can come in
26889 	 */
26890 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
26891 	if (error != 0) {
26892 		/* failed to enter, free all the pre-allocated messages. */
26893 		freeb(stropt_mp);
26894 		freeb(ordrel_mp);
26895 		freeb(fused_sigurp_mp);
26896 		/*
26897 		 * We cannot process the eager, so at least send out a
26898 		 * RST so the peer can reconnect.
26899 		 */
26900 		if (tcp->tcp_listener != NULL) {
26901 			(void) tcp_eager_blowoff(tcp->tcp_listener,
26902 			    tcp->tcp_conn_req_seqnum);
26903 		}
26904 		return (ENOMEM);
26905 	}
26906 
26907 	/*
26908 	 * No longer a direct socket
26909 	 */
26910 	connp->conn_flags &= ~IPCL_NONSTR;
26911 
26912 	tcp->tcp_ordrel_mp = ordrel_mp;
26913 
26914 	if (tcp->tcp_fused) {
26915 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
26916 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
26917 	} else {
26918 		freeb(fused_sigurp_mp);
26919 	}
26920 
26921 	if (tcp->tcp_listener != NULL) {
26922 		/* The eager will deal with opts when accept() is called */
26923 		freeb(stropt_mp);
26924 		tcp_fallback_eager(tcp, direct_sockfs);
26925 	} else {
26926 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
26927 		    quiesced_cb);
26928 	}
26929 
26930 	/*
26931 	 * There should be atleast two ref's (IP + TCP)
26932 	 */
26933 	ASSERT(connp->conn_ref >= 2);
26934 	squeue_synch_exit(connp->conn_sqp, connp);
26935 
26936 	return (0);
26937 }
26938 
26939 /* ARGSUSED */
26940 static void
26941 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
26942 {
26943 	conn_t 	*connp = (conn_t *)arg;
26944 	tcp_t	*tcp = connp->conn_tcp;
26945 
26946 	freemsg(mp);
26947 
26948 	if (tcp->tcp_fused)
26949 		tcp_unfuse(tcp);
26950 
26951 	if (tcp_xmit_end(tcp) != 0) {
26952 		/*
26953 		 * We were crossing FINs and got a reset from
26954 		 * the other side. Just ignore it.
26955 		 */
26956 		if (tcp->tcp_debug) {
26957 			(void) strlog(TCP_MOD_ID, 0, 1,
26958 			    SL_ERROR|SL_TRACE,
26959 			    "tcp_shutdown_output() out of state %s",
26960 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
26961 		}
26962 	}
26963 }
26964 
26965 /* ARGSUSED */
26966 int
26967 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
26968 {
26969 	conn_t  *connp = (conn_t *)proto_handle;
26970 	tcp_t   *tcp = connp->conn_tcp;
26971 
26972 	ASSERT(connp->conn_upper_handle != NULL);
26973 
26974 	/* All Solaris components should pass a cred for this operation. */
26975 	ASSERT(cr != NULL);
26976 
26977 	/*
26978 	 * X/Open requires that we check the connected state.
26979 	 */
26980 	if (tcp->tcp_state < TCPS_SYN_SENT)
26981 		return (ENOTCONN);
26982 
26983 	/* shutdown the send side */
26984 	if (how != SHUT_RD) {
26985 		mblk_t *bp;
26986 
26987 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
26988 		CONN_INC_REF(connp);
26989 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
26990 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
26991 
26992 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
26993 		    SOCK_OPCTL_SHUT_SEND, 0);
26994 	}
26995 
26996 	/* shutdown the recv side */
26997 	if (how != SHUT_WR)
26998 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
26999 		    SOCK_OPCTL_SHUT_RECV, 0);
27000 
27001 	return (0);
27002 }
27003 
27004 /*
27005  * SOP_LISTEN() calls into tcp_listen().
27006  */
27007 /* ARGSUSED */
27008 int
27009 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27010 {
27011 	conn_t	*connp = (conn_t *)proto_handle;
27012 	int 	error;
27013 	squeue_t *sqp = connp->conn_sqp;
27014 
27015 	ASSERT(connp->conn_upper_handle != NULL);
27016 
27017 	/* All Solaris components should pass a cred for this operation. */
27018 	ASSERT(cr != NULL);
27019 
27020 	error = squeue_synch_enter(sqp, connp, NULL);
27021 	if (error != 0) {
27022 		/* failed to enter */
27023 		return (ENOBUFS);
27024 	}
27025 
27026 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
27027 	if (error == 0) {
27028 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27029 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27030 	} else if (error < 0) {
27031 		if (error == -TOUTSTATE)
27032 			error = EINVAL;
27033 		else
27034 			error = proto_tlitosyserr(-error);
27035 	}
27036 	squeue_synch_exit(sqp, connp);
27037 	return (error);
27038 }
27039 
27040 static int
27041 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
27042     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
27043 {
27044 	tcp_t		*tcp = connp->conn_tcp;
27045 	int		error = 0;
27046 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27047 
27048 	/* All Solaris components should pass a cred for this operation. */
27049 	ASSERT(cr != NULL);
27050 
27051 	if (tcp->tcp_state >= TCPS_BOUND) {
27052 		if ((tcp->tcp_state == TCPS_BOUND ||
27053 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27054 			/*
27055 			 * Handle listen() increasing backlog.
27056 			 * This is more "liberal" then what the TPI spec
27057 			 * requires but is needed to avoid a t_unbind
27058 			 * when handling listen() since the port number
27059 			 * might be "stolen" between the unbind and bind.
27060 			 */
27061 			goto do_listen;
27062 		}
27063 		if (tcp->tcp_debug) {
27064 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27065 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27066 		}
27067 		return (-TOUTSTATE);
27068 	} else {
27069 		if (sa == NULL) {
27070 			sin6_t	addr;
27071 			sin_t *sin;
27072 			sin6_t *sin6;
27073 
27074 			ASSERT(IPCL_IS_NONSTR(connp));
27075 
27076 			/* Do an implicit bind: Request for a generic port. */
27077 			if (tcp->tcp_family == AF_INET) {
27078 				len = sizeof (sin_t);
27079 				sin = (sin_t *)&addr;
27080 				*sin = sin_null;
27081 				sin->sin_family = AF_INET;
27082 				tcp->tcp_ipversion = IPV4_VERSION;
27083 			} else {
27084 				ASSERT(tcp->tcp_family == AF_INET6);
27085 				len = sizeof (sin6_t);
27086 				sin6 = (sin6_t *)&addr;
27087 				*sin6 = sin6_null;
27088 				sin6->sin6_family = AF_INET6;
27089 				tcp->tcp_ipversion = IPV6_VERSION;
27090 			}
27091 			sa = (struct sockaddr *)&addr;
27092 		}
27093 
27094 		error = tcp_bind_check(connp, sa, len, cr,
27095 		    bind_to_req_port_only);
27096 		if (error)
27097 			return (error);
27098 		/* Fall through and do the fanout insertion */
27099 	}
27100 
27101 do_listen:
27102 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27103 	tcp->tcp_conn_req_max = backlog;
27104 	if (tcp->tcp_conn_req_max) {
27105 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27106 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27107 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27108 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27109 		/*
27110 		 * If this is a listener, do not reset the eager list
27111 		 * and other stuffs.  Note that we don't check if the
27112 		 * existing eager list meets the new tcp_conn_req_max
27113 		 * requirement.
27114 		 */
27115 		if (tcp->tcp_state != TCPS_LISTEN) {
27116 			tcp->tcp_state = TCPS_LISTEN;
27117 			/* Initialize the chain. Don't need the eager_lock */
27118 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27119 			tcp->tcp_eager_next_drop_q0 = tcp;
27120 			tcp->tcp_eager_prev_drop_q0 = tcp;
27121 			tcp->tcp_second_ctimer_threshold =
27122 			    tcps->tcps_ip_abort_linterval;
27123 		}
27124 	}
27125 
27126 	/*
27127 	 * We can call ip_bind directly, the processing continues
27128 	 * in tcp_post_ip_bind().
27129 	 *
27130 	 * We need to make sure that the conn_recv is set to a non-null
27131 	 * value before we insert the conn into the classifier table.
27132 	 * This is to avoid a race with an incoming packet which does an
27133 	 * ipcl_classify().
27134 	 */
27135 	connp->conn_recv = tcp_conn_request;
27136 	if (tcp->tcp_family == AF_INET) {
27137 		error = ip_proto_bind_laddr_v4(connp, NULL,
27138 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27139 	} else {
27140 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27141 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27142 	}
27143 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27144 }
27145 
27146 void
27147 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27148 {
27149 	conn_t  *connp = (conn_t *)proto_handle;
27150 	tcp_t	*tcp = connp->conn_tcp;
27151 	mblk_t *mp;
27152 	int error;
27153 
27154 	ASSERT(connp->conn_upper_handle != NULL);
27155 
27156 	/*
27157 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
27158 	 * is currently running.
27159 	 */
27160 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27161 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
27162 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
27163 		return;
27164 	}
27165 	tcp->tcp_rsrv_mp = NULL;
27166 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27167 
27168 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
27169 	ASSERT(error == 0);
27170 
27171 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27172 	tcp->tcp_rsrv_mp = mp;
27173 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27174 
27175 	if (tcp->tcp_fused) {
27176 		tcp_fuse_backenable(tcp);
27177 	} else {
27178 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27179 		/*
27180 		 * Send back a window update immediately if TCP is above
27181 		 * ESTABLISHED state and the increase of the rcv window
27182 		 * that the other side knows is at least 1 MSS after flow
27183 		 * control is lifted.
27184 		 */
27185 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27186 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
27187 			tcp_xmit_ctl(NULL, tcp,
27188 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27189 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27190 		}
27191 	}
27192 
27193 	squeue_synch_exit(connp->conn_sqp, connp);
27194 }
27195 
27196 /* ARGSUSED */
27197 int
27198 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27199     int mode, int32_t *rvalp, cred_t *cr)
27200 {
27201 	conn_t  	*connp = (conn_t *)proto_handle;
27202 	int		error;
27203 
27204 	ASSERT(connp->conn_upper_handle != NULL);
27205 
27206 	/* All Solaris components should pass a cred for this operation. */
27207 	ASSERT(cr != NULL);
27208 
27209 	switch (cmd) {
27210 		case ND_SET:
27211 		case ND_GET:
27212 		case TCP_IOC_DEFAULT_Q:
27213 		case _SIOCSOCKFALLBACK:
27214 		case TCP_IOC_ABORT_CONN:
27215 		case TI_GETPEERNAME:
27216 		case TI_GETMYNAME:
27217 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27218 			    cmd));
27219 			error = EINVAL;
27220 			break;
27221 		default:
27222 			/*
27223 			 * Pass on to IP using helper stream
27224 			 */
27225 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
27226 			    cmd, arg, mode, cr, rvalp);
27227 			break;
27228 	}
27229 	return (error);
27230 }
27231 
27232 sock_downcalls_t sock_tcp_downcalls = {
27233 	tcp_activate,
27234 	tcp_accept,
27235 	tcp_bind,
27236 	tcp_listen,
27237 	tcp_connect,
27238 	tcp_getpeername,
27239 	tcp_getsockname,
27240 	tcp_getsockopt,
27241 	tcp_setsockopt,
27242 	tcp_sendmsg,
27243 	NULL,
27244 	NULL,
27245 	NULL,
27246 	tcp_shutdown,
27247 	tcp_clr_flowctrl,
27248 	tcp_ioctl,
27249 	tcp_close,
27250 };
27251