xref: /titanic_50/usr/src/uts/common/inet/tcp/tcp.c (revision a0a37ffd5d0a0633388be45f72bc231ea81d544d)
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_CLOSED)
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_LISTEN) {
12364 		/*
12365 		 * If listener has closed, it would have caused a
12366 		 * a cleanup/blowoff to happen for the eager. We
12367 		 * just need to return.
12368 		 */
12369 		freemsg(mp);
12370 		return;
12371 	}
12372 
12373 
12374 	/*
12375 	 * if the conn_req_q is full defer passing up the
12376 	 * T_CONN_IND until space is availabe after t_accept()
12377 	 * processing
12378 	 */
12379 	mutex_enter(&listener->tcp_eager_lock);
12380 
12381 	/*
12382 	 * Take the eager out, if it is in the list of droppable eagers
12383 	 * as we are here because the 3W handshake is over.
12384 	 */
12385 	MAKE_UNDROPPABLE(tcp);
12386 
12387 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12388 		tcp_t *tail;
12389 
12390 		/*
12391 		 * The eager already has an extra ref put in tcp_rput_data
12392 		 * so that it stays till accept comes back even though it
12393 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12394 		 */
12395 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12396 		listener->tcp_conn_req_cnt_q0--;
12397 		listener->tcp_conn_req_cnt_q++;
12398 
12399 		/* Move from SYN_RCVD to ESTABLISHED list  */
12400 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12401 		    tcp->tcp_eager_prev_q0;
12402 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12403 		    tcp->tcp_eager_next_q0;
12404 		tcp->tcp_eager_prev_q0 = NULL;
12405 		tcp->tcp_eager_next_q0 = NULL;
12406 
12407 		/*
12408 		 * Insert at end of the queue because sockfs
12409 		 * sends down T_CONN_RES in chronological
12410 		 * order. Leaving the older conn indications
12411 		 * at front of the queue helps reducing search
12412 		 * time.
12413 		 */
12414 		tail = listener->tcp_eager_last_q;
12415 		if (tail != NULL)
12416 			tail->tcp_eager_next_q = tcp;
12417 		else
12418 			listener->tcp_eager_next_q = tcp;
12419 		listener->tcp_eager_last_q = tcp;
12420 		tcp->tcp_eager_next_q = NULL;
12421 		/*
12422 		 * Delay sending up the T_conn_ind until we are
12423 		 * done with the eager. Once we have have sent up
12424 		 * the T_conn_ind, the accept can potentially complete
12425 		 * any time and release the refhold we have on the eager.
12426 		 */
12427 		need_send_conn_ind = B_TRUE;
12428 	} else {
12429 		/*
12430 		 * Defer connection on q0 and set deferred
12431 		 * connection bit true
12432 		 */
12433 		tcp->tcp_conn_def_q0 = B_TRUE;
12434 
12435 		/* take tcp out of q0 ... */
12436 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12437 		    tcp->tcp_eager_next_q0;
12438 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12439 		    tcp->tcp_eager_prev_q0;
12440 
12441 		/* ... and place it at the end of q0 */
12442 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12443 		tcp->tcp_eager_next_q0 = listener;
12444 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12445 		listener->tcp_eager_prev_q0 = tcp;
12446 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12447 	}
12448 
12449 	/* we have timed out before */
12450 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12451 		tcp->tcp_syn_rcvd_timeout = 0;
12452 		listener->tcp_syn_rcvd_timeout--;
12453 		if (listener->tcp_syn_defense &&
12454 		    listener->tcp_syn_rcvd_timeout <=
12455 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12456 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12457 		    listener->tcp_last_rcv_lbolt)) {
12458 			/*
12459 			 * Turn off the defense mode if we
12460 			 * believe the SYN attack is over.
12461 			 */
12462 			listener->tcp_syn_defense = B_FALSE;
12463 			if (listener->tcp_ip_addr_cache) {
12464 				kmem_free((void *)listener->tcp_ip_addr_cache,
12465 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12466 				listener->tcp_ip_addr_cache = NULL;
12467 			}
12468 		}
12469 	}
12470 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12471 	if (addr_cache != NULL) {
12472 		/*
12473 		 * We have finished a 3-way handshake with this
12474 		 * remote host. This proves the IP addr is good.
12475 		 * Cache it!
12476 		 */
12477 		addr_cache[IP_ADDR_CACHE_HASH(
12478 		    tcp->tcp_remote)] = tcp->tcp_remote;
12479 	}
12480 	mutex_exit(&listener->tcp_eager_lock);
12481 	if (need_send_conn_ind)
12482 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12483 }
12484 
12485 /*
12486  * Send the newconn notification to ulp. The eager is blown off if the
12487  * notification fails.
12488  */
12489 static void
12490 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12491 {
12492 	if (IPCL_IS_NONSTR(lconnp)) {
12493 		cred_t	*cr;
12494 		pid_t	cpid;
12495 
12496 		cr = msg_getcred(mp, &cpid);
12497 
12498 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12499 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12500 		    lconnp->conn_tcp);
12501 
12502 		/* Keep the message around in case of a fallback to TPI */
12503 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12504 
12505 		/*
12506 		 * Notify the ULP about the newconn. It is guaranteed that no
12507 		 * tcp_accept() call will be made for the eager if the
12508 		 * notification fails, so it's safe to blow it off in that
12509 		 * case.
12510 		 *
12511 		 * The upper handle will be assigned when tcp_accept() is
12512 		 * called.
12513 		 */
12514 		if ((*lconnp->conn_upcalls->su_newconn)
12515 		    (lconnp->conn_upper_handle,
12516 		    (sock_lower_handle_t)econnp,
12517 		    &sock_tcp_downcalls, cr, cpid,
12518 		    &econnp->conn_upcalls) == NULL) {
12519 			/* Failed to allocate a socket */
12520 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12521 			    tcpEstabResets);
12522 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12523 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12524 		}
12525 	} else {
12526 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12527 	}
12528 }
12529 
12530 mblk_t *
12531 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12532     uint_t *ifindexp, ip6_pkt_t *ippp)
12533 {
12534 	ip_pktinfo_t	*pinfo;
12535 	ip6_t		*ip6h;
12536 	uchar_t		*rptr;
12537 	mblk_t		*first_mp = mp;
12538 	boolean_t	mctl_present = B_FALSE;
12539 	uint_t 		ifindex = 0;
12540 	ip6_pkt_t	ipp;
12541 	uint_t		ipvers;
12542 	uint_t		ip_hdr_len;
12543 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12544 
12545 	rptr = mp->b_rptr;
12546 	ASSERT(OK_32PTR(rptr));
12547 	ASSERT(tcp != NULL);
12548 	ipp.ipp_fields = 0;
12549 
12550 	switch DB_TYPE(mp) {
12551 	case M_CTL:
12552 		mp = mp->b_cont;
12553 		if (mp == NULL) {
12554 			freemsg(first_mp);
12555 			return (NULL);
12556 		}
12557 		if (DB_TYPE(mp) != M_DATA) {
12558 			freemsg(first_mp);
12559 			return (NULL);
12560 		}
12561 		mctl_present = B_TRUE;
12562 		break;
12563 	case M_DATA:
12564 		break;
12565 	default:
12566 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12567 		freemsg(mp);
12568 		return (NULL);
12569 	}
12570 	ipvers = IPH_HDR_VERSION(rptr);
12571 	if (ipvers == IPV4_VERSION) {
12572 		if (tcp == NULL) {
12573 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12574 			goto done;
12575 		}
12576 
12577 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12578 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12579 
12580 		/*
12581 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12582 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12583 		 */
12584 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12585 		    mctl_present) {
12586 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12587 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12588 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12589 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12590 				ipp.ipp_fields |= IPPF_IFINDEX;
12591 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12592 				ifindex = pinfo->ip_pkt_ifindex;
12593 			}
12594 			freeb(first_mp);
12595 			mctl_present = B_FALSE;
12596 		}
12597 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12598 	} else {
12599 		ip6h = (ip6_t *)rptr;
12600 
12601 		ASSERT(ipvers == IPV6_VERSION);
12602 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12603 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12604 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12605 
12606 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12607 			uint8_t	nexthdrp;
12608 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12609 
12610 			/* Look for ifindex information */
12611 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12612 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12613 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12614 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12615 					freemsg(first_mp);
12616 					return (NULL);
12617 				}
12618 
12619 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12620 					ASSERT(ip6i->ip6i_ifindex != 0);
12621 					ipp.ipp_fields |= IPPF_IFINDEX;
12622 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12623 					ifindex = ip6i->ip6i_ifindex;
12624 				}
12625 				rptr = (uchar_t *)&ip6i[1];
12626 				mp->b_rptr = rptr;
12627 				if (rptr == mp->b_wptr) {
12628 					mblk_t *mp1;
12629 					mp1 = mp->b_cont;
12630 					freeb(mp);
12631 					mp = mp1;
12632 					rptr = mp->b_rptr;
12633 				}
12634 				if (MBLKL(mp) < IPV6_HDR_LEN +
12635 				    sizeof (tcph_t)) {
12636 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12637 					freemsg(first_mp);
12638 					return (NULL);
12639 				}
12640 				ip6h = (ip6_t *)rptr;
12641 			}
12642 
12643 			/*
12644 			 * Find any potentially interesting extension headers
12645 			 * as well as the length of the IPv6 + extension
12646 			 * headers.
12647 			 */
12648 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12649 			/* Verify if this is a TCP packet */
12650 			if (nexthdrp != IPPROTO_TCP) {
12651 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12652 				freemsg(first_mp);
12653 				return (NULL);
12654 			}
12655 		} else {
12656 			ip_hdr_len = IPV6_HDR_LEN;
12657 		}
12658 	}
12659 
12660 done:
12661 	if (ipversp != NULL)
12662 		*ipversp = ipvers;
12663 	if (ip_hdr_lenp != NULL)
12664 		*ip_hdr_lenp = ip_hdr_len;
12665 	if (ippp != NULL)
12666 		*ippp = ipp;
12667 	if (ifindexp != NULL)
12668 		*ifindexp = ifindex;
12669 	if (mctl_present) {
12670 		freeb(first_mp);
12671 	}
12672 	return (mp);
12673 }
12674 
12675 /*
12676  * Handle M_DATA messages from IP. Its called directly from IP via
12677  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12678  * in this path.
12679  *
12680  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12681  * v4 and v6), we are called through tcp_input() and a M_CTL can
12682  * be present for options but tcp_find_pktinfo() deals with it. We
12683  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12684  *
12685  * The first argument is always the connp/tcp to which the mp belongs.
12686  * There are no exceptions to this rule. The caller has already put
12687  * a reference on this connp/tcp and once tcp_rput_data() returns,
12688  * the squeue will do the refrele.
12689  *
12690  * The TH_SYN for the listener directly go to tcp_conn_request via
12691  * squeue.
12692  *
12693  * sqp: NULL = recursive, sqp != NULL means called from squeue
12694  */
12695 void
12696 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12697 {
12698 	int32_t		bytes_acked;
12699 	int32_t		gap;
12700 	mblk_t		*mp1;
12701 	uint_t		flags;
12702 	uint32_t	new_swnd = 0;
12703 	uchar_t		*iphdr;
12704 	uchar_t		*rptr;
12705 	int32_t		rgap;
12706 	uint32_t	seg_ack;
12707 	int		seg_len;
12708 	uint_t		ip_hdr_len;
12709 	uint32_t	seg_seq;
12710 	tcph_t		*tcph;
12711 	int		urp;
12712 	tcp_opt_t	tcpopt;
12713 	uint_t		ipvers;
12714 	ip6_pkt_t	ipp;
12715 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12716 	uint32_t	cwnd;
12717 	uint32_t	add;
12718 	int		npkt;
12719 	int		mss;
12720 	conn_t		*connp = (conn_t *)arg;
12721 	squeue_t	*sqp = (squeue_t *)arg2;
12722 	tcp_t		*tcp = connp->conn_tcp;
12723 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12724 
12725 	/*
12726 	 * RST from fused tcp loopback peer should trigger an unfuse.
12727 	 */
12728 	if (tcp->tcp_fused) {
12729 		TCP_STAT(tcps, tcp_fusion_aborted);
12730 		tcp_unfuse(tcp);
12731 	}
12732 
12733 	iphdr = mp->b_rptr;
12734 	rptr = mp->b_rptr;
12735 	ASSERT(OK_32PTR(rptr));
12736 
12737 	/*
12738 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12739 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12740 	 * necessary information.
12741 	 */
12742 	if (IPCL_IS_TCP4(connp)) {
12743 		ipvers = IPV4_VERSION;
12744 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12745 	} else {
12746 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12747 		    NULL, &ipp);
12748 		if (mp == NULL) {
12749 			TCP_STAT(tcps, tcp_rput_v6_error);
12750 			return;
12751 		}
12752 		iphdr = mp->b_rptr;
12753 		rptr = mp->b_rptr;
12754 	}
12755 	ASSERT(DB_TYPE(mp) == M_DATA);
12756 	ASSERT(mp->b_next == NULL);
12757 
12758 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12759 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12760 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12761 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12762 	seg_len = (int)(mp->b_wptr - rptr) -
12763 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12764 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12765 		do {
12766 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12767 			    (uintptr_t)INT_MAX);
12768 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12769 		} while ((mp1 = mp1->b_cont) != NULL &&
12770 		    mp1->b_datap->db_type == M_DATA);
12771 	}
12772 
12773 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12774 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12775 		    seg_len, tcph);
12776 		return;
12777 	}
12778 
12779 	if (sqp != NULL) {
12780 		/*
12781 		 * This is the correct place to update tcp_last_recv_time. Note
12782 		 * that it is also updated for tcp structure that belongs to
12783 		 * global and listener queues which do not really need updating.
12784 		 * But that should not cause any harm.  And it is updated for
12785 		 * all kinds of incoming segments, not only for data segments.
12786 		 */
12787 		tcp->tcp_last_recv_time = lbolt;
12788 	}
12789 
12790 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12791 
12792 	BUMP_LOCAL(tcp->tcp_ibsegs);
12793 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12794 
12795 	if ((flags & TH_URG) && sqp != NULL) {
12796 		/*
12797 		 * TCP can't handle urgent pointers that arrive before
12798 		 * the connection has been accept()ed since it can't
12799 		 * buffer OOB data.  Discard segment if this happens.
12800 		 *
12801 		 * We can't just rely on a non-null tcp_listener to indicate
12802 		 * that the accept() has completed since unlinking of the
12803 		 * eager and completion of the accept are not atomic.
12804 		 * tcp_detached, when it is not set (B_FALSE) indicates
12805 		 * that the accept() has completed.
12806 		 *
12807 		 * Nor can it reassemble urgent pointers, so discard
12808 		 * if it's not the next segment expected.
12809 		 *
12810 		 * Otherwise, collapse chain into one mblk (discard if
12811 		 * that fails).  This makes sure the headers, retransmitted
12812 		 * data, and new data all are in the same mblk.
12813 		 */
12814 		ASSERT(mp != NULL);
12815 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12816 			freemsg(mp);
12817 			return;
12818 		}
12819 		/* Update pointers into message */
12820 		iphdr = rptr = mp->b_rptr;
12821 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12822 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12823 			/*
12824 			 * Since we can't handle any data with this urgent
12825 			 * pointer that is out of sequence, we expunge
12826 			 * the data.  This allows us to still register
12827 			 * the urgent mark and generate the M_PCSIG,
12828 			 * which we can do.
12829 			 */
12830 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12831 			seg_len = 0;
12832 		}
12833 	}
12834 
12835 	switch (tcp->tcp_state) {
12836 	case TCPS_SYN_SENT:
12837 		if (flags & TH_ACK) {
12838 			/*
12839 			 * Note that our stack cannot send data before a
12840 			 * connection is established, therefore the
12841 			 * following check is valid.  Otherwise, it has
12842 			 * to be changed.
12843 			 */
12844 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12845 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12846 				freemsg(mp);
12847 				if (flags & TH_RST)
12848 					return;
12849 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12850 				    tcp, seg_ack, 0, TH_RST);
12851 				return;
12852 			}
12853 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12854 		}
12855 		if (flags & TH_RST) {
12856 			freemsg(mp);
12857 			if (flags & TH_ACK)
12858 				(void) tcp_clean_death(tcp,
12859 				    ECONNREFUSED, 13);
12860 			return;
12861 		}
12862 		if (!(flags & TH_SYN)) {
12863 			freemsg(mp);
12864 			return;
12865 		}
12866 
12867 		/* Process all TCP options. */
12868 		tcp_process_options(tcp, tcph);
12869 		/*
12870 		 * The following changes our rwnd to be a multiple of the
12871 		 * MIN(peer MSS, our MSS) for performance reason.
12872 		 */
12873 		(void) tcp_rwnd_set(tcp,
12874 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
12875 
12876 		/* Is the other end ECN capable? */
12877 		if (tcp->tcp_ecn_ok) {
12878 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12879 				tcp->tcp_ecn_ok = B_FALSE;
12880 			}
12881 		}
12882 		/*
12883 		 * Clear ECN flags because it may interfere with later
12884 		 * processing.
12885 		 */
12886 		flags &= ~(TH_ECE|TH_CWR);
12887 
12888 		tcp->tcp_irs = seg_seq;
12889 		tcp->tcp_rack = seg_seq;
12890 		tcp->tcp_rnxt = seg_seq + 1;
12891 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12892 		if (!TCP_IS_DETACHED(tcp)) {
12893 			/* Allocate room for SACK options if needed. */
12894 			if (tcp->tcp_snd_sack_ok) {
12895 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12896 				    tcp->tcp_hdr_len +
12897 				    TCPOPT_MAX_SACK_LEN +
12898 				    (tcp->tcp_loopback ? 0 :
12899 				    tcps->tcps_wroff_xtra));
12900 			} else {
12901 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12902 				    tcp->tcp_hdr_len +
12903 				    (tcp->tcp_loopback ? 0 :
12904 				    tcps->tcps_wroff_xtra));
12905 			}
12906 		}
12907 		if (flags & TH_ACK) {
12908 			/*
12909 			 * If we can't get the confirmation upstream, pretend
12910 			 * we didn't even see this one.
12911 			 *
12912 			 * XXX: how can we pretend we didn't see it if we
12913 			 * have updated rnxt et. al.
12914 			 *
12915 			 * For loopback we defer sending up the T_CONN_CON
12916 			 * until after some checks below.
12917 			 */
12918 			mp1 = NULL;
12919 			/*
12920 			 * tcp_sendmsg() checks tcp_state without entering
12921 			 * the squeue so tcp_state should be updated before
12922 			 * sending up connection confirmation
12923 			 */
12924 			tcp->tcp_state = TCPS_ESTABLISHED;
12925 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12926 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12927 				tcp->tcp_state = TCPS_SYN_SENT;
12928 				freemsg(mp);
12929 				return;
12930 			}
12931 			/* SYN was acked - making progress */
12932 			if (tcp->tcp_ipversion == IPV6_VERSION)
12933 				tcp->tcp_ip_forward_progress = B_TRUE;
12934 
12935 			/* One for the SYN */
12936 			tcp->tcp_suna = tcp->tcp_iss + 1;
12937 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12938 
12939 			/*
12940 			 * If SYN was retransmitted, need to reset all
12941 			 * retransmission info.  This is because this
12942 			 * segment will be treated as a dup ACK.
12943 			 */
12944 			if (tcp->tcp_rexmit) {
12945 				tcp->tcp_rexmit = B_FALSE;
12946 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12947 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12948 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12949 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12950 				tcp->tcp_ms_we_have_waited = 0;
12951 
12952 				/*
12953 				 * Set tcp_cwnd back to 1 MSS, per
12954 				 * recommendation from
12955 				 * draft-floyd-incr-init-win-01.txt,
12956 				 * Increasing TCP's Initial Window.
12957 				 */
12958 				tcp->tcp_cwnd = tcp->tcp_mss;
12959 			}
12960 
12961 			tcp->tcp_swl1 = seg_seq;
12962 			tcp->tcp_swl2 = seg_ack;
12963 
12964 			new_swnd = BE16_TO_U16(tcph->th_win);
12965 			tcp->tcp_swnd = new_swnd;
12966 			if (new_swnd > tcp->tcp_max_swnd)
12967 				tcp->tcp_max_swnd = new_swnd;
12968 
12969 			/*
12970 			 * Always send the three-way handshake ack immediately
12971 			 * in order to make the connection complete as soon as
12972 			 * possible on the accepting host.
12973 			 */
12974 			flags |= TH_ACK_NEEDED;
12975 
12976 			/*
12977 			 * Special case for loopback.  At this point we have
12978 			 * received SYN-ACK from the remote endpoint.  In
12979 			 * order to ensure that both endpoints reach the
12980 			 * fused state prior to any data exchange, the final
12981 			 * ACK needs to be sent before we indicate T_CONN_CON
12982 			 * to the module upstream.
12983 			 */
12984 			if (tcp->tcp_loopback) {
12985 				mblk_t *ack_mp;
12986 
12987 				ASSERT(!tcp->tcp_unfusable);
12988 				ASSERT(mp1 != NULL);
12989 				/*
12990 				 * For loopback, we always get a pure SYN-ACK
12991 				 * and only need to send back the final ACK
12992 				 * with no data (this is because the other
12993 				 * tcp is ours and we don't do T/TCP).  This
12994 				 * final ACK triggers the passive side to
12995 				 * perform fusion in ESTABLISHED state.
12996 				 */
12997 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12998 					if (tcp->tcp_ack_tid != 0) {
12999 						(void) TCP_TIMER_CANCEL(tcp,
13000 						    tcp->tcp_ack_tid);
13001 						tcp->tcp_ack_tid = 0;
13002 					}
13003 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13004 					BUMP_LOCAL(tcp->tcp_obsegs);
13005 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13006 
13007 					if (!IPCL_IS_NONSTR(connp)) {
13008 						/* Send up T_CONN_CON */
13009 						putnext(tcp->tcp_rq, mp1);
13010 					} else {
13011 						cred_t	*cr;
13012 						pid_t	cpid;
13013 
13014 						cr = msg_getcred(mp1, &cpid);
13015 						(*connp->conn_upcalls->
13016 						    su_connected)
13017 						    (connp->conn_upper_handle,
13018 						    tcp->tcp_connid, cr, cpid);
13019 						freemsg(mp1);
13020 					}
13021 
13022 					freemsg(mp);
13023 					return;
13024 				}
13025 				/*
13026 				 * Forget fusion; we need to handle more
13027 				 * complex cases below.  Send the deferred
13028 				 * T_CONN_CON message upstream and proceed
13029 				 * as usual.  Mark this tcp as not capable
13030 				 * of fusion.
13031 				 */
13032 				TCP_STAT(tcps, tcp_fusion_unfusable);
13033 				tcp->tcp_unfusable = B_TRUE;
13034 				if (!IPCL_IS_NONSTR(connp)) {
13035 					putnext(tcp->tcp_rq, mp1);
13036 				} else {
13037 					cred_t	*cr;
13038 					pid_t	cpid;
13039 
13040 					cr = msg_getcred(mp1, &cpid);
13041 					(*connp->conn_upcalls->su_connected)
13042 					    (connp->conn_upper_handle,
13043 					    tcp->tcp_connid, cr, cpid);
13044 					freemsg(mp1);
13045 				}
13046 			}
13047 
13048 			/*
13049 			 * Check to see if there is data to be sent.  If
13050 			 * yes, set the transmit flag.  Then check to see
13051 			 * if received data processing needs to be done.
13052 			 * If not, go straight to xmit_check.  This short
13053 			 * cut is OK as we don't support T/TCP.
13054 			 */
13055 			if (tcp->tcp_unsent)
13056 				flags |= TH_XMIT_NEEDED;
13057 
13058 			if (seg_len == 0 && !(flags & TH_URG)) {
13059 				freemsg(mp);
13060 				goto xmit_check;
13061 			}
13062 
13063 			flags &= ~TH_SYN;
13064 			seg_seq++;
13065 			break;
13066 		}
13067 		tcp->tcp_state = TCPS_SYN_RCVD;
13068 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13069 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13070 		if (mp1) {
13071 			/*
13072 			 * See comment in tcp_conn_request() for why we use
13073 			 * the open() time pid here.
13074 			 */
13075 			DB_CPID(mp1) = tcp->tcp_cpid;
13076 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13077 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13078 		}
13079 		freemsg(mp);
13080 		return;
13081 	case TCPS_SYN_RCVD:
13082 		if (flags & TH_ACK) {
13083 			/*
13084 			 * In this state, a SYN|ACK packet is either bogus
13085 			 * because the other side must be ACKing our SYN which
13086 			 * indicates it has seen the ACK for their SYN and
13087 			 * shouldn't retransmit it or we're crossing SYNs
13088 			 * on active open.
13089 			 */
13090 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13091 				freemsg(mp);
13092 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13093 				    tcp, seg_ack, 0, TH_RST);
13094 				return;
13095 			}
13096 			/*
13097 			 * NOTE: RFC 793 pg. 72 says this should be
13098 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13099 			 * but that would mean we have an ack that ignored
13100 			 * our SYN.
13101 			 */
13102 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13103 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13104 				freemsg(mp);
13105 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13106 				    tcp, seg_ack, 0, TH_RST);
13107 				return;
13108 			}
13109 		}
13110 		break;
13111 	case TCPS_LISTEN:
13112 		/*
13113 		 * Only a TLI listener can come through this path when a
13114 		 * acceptor is going back to be a listener and a packet
13115 		 * for the acceptor hits the classifier. For a socket
13116 		 * listener, this can never happen because a listener
13117 		 * can never accept connection on itself and hence a
13118 		 * socket acceptor can not go back to being a listener.
13119 		 */
13120 		ASSERT(!TCP_IS_SOCKET(tcp));
13121 		/*FALLTHRU*/
13122 	case TCPS_CLOSED:
13123 	case TCPS_BOUND: {
13124 		conn_t	*new_connp;
13125 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13126 
13127 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13128 		if (new_connp != NULL) {
13129 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13130 			return;
13131 		}
13132 		/* We failed to classify. For now just drop the packet */
13133 		freemsg(mp);
13134 		return;
13135 	}
13136 	case TCPS_IDLE:
13137 		/*
13138 		 * Handle the case where the tcp_clean_death() has happened
13139 		 * on a connection (application hasn't closed yet) but a packet
13140 		 * was already queued on squeue before tcp_clean_death()
13141 		 * was processed. Calling tcp_clean_death() twice on same
13142 		 * connection can result in weird behaviour.
13143 		 */
13144 		freemsg(mp);
13145 		return;
13146 	default:
13147 		break;
13148 	}
13149 
13150 	/*
13151 	 * Already on the correct queue/perimeter.
13152 	 * If this is a detached connection and not an eager
13153 	 * connection hanging off a listener then new data
13154 	 * (past the FIN) will cause a reset.
13155 	 * We do a special check here where it
13156 	 * is out of the main line, rather than check
13157 	 * if we are detached every time we see new
13158 	 * data down below.
13159 	 */
13160 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13161 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13162 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13163 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13164 
13165 		freemsg(mp);
13166 		/*
13167 		 * This could be an SSL closure alert. We're detached so just
13168 		 * acknowledge it this last time.
13169 		 */
13170 		if (tcp->tcp_kssl_ctx != NULL) {
13171 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13172 			tcp->tcp_kssl_ctx = NULL;
13173 
13174 			tcp->tcp_rnxt += seg_len;
13175 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13176 			flags |= TH_ACK_NEEDED;
13177 			goto ack_check;
13178 		}
13179 
13180 		tcp_xmit_ctl("new data when detached", tcp,
13181 		    tcp->tcp_snxt, 0, TH_RST);
13182 		(void) tcp_clean_death(tcp, EPROTO, 12);
13183 		return;
13184 	}
13185 
13186 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13187 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13188 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13189 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13190 
13191 	if (tcp->tcp_snd_ts_ok) {
13192 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13193 			/*
13194 			 * This segment is not acceptable.
13195 			 * Drop it and send back an ACK.
13196 			 */
13197 			freemsg(mp);
13198 			flags |= TH_ACK_NEEDED;
13199 			goto ack_check;
13200 		}
13201 	} else if (tcp->tcp_snd_sack_ok) {
13202 		ASSERT(tcp->tcp_sack_info != NULL);
13203 		tcpopt.tcp = tcp;
13204 		/*
13205 		 * SACK info in already updated in tcp_parse_options.  Ignore
13206 		 * all other TCP options...
13207 		 */
13208 		(void) tcp_parse_options(tcph, &tcpopt);
13209 	}
13210 try_again:;
13211 	mss = tcp->tcp_mss;
13212 	gap = seg_seq - tcp->tcp_rnxt;
13213 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13214 	/*
13215 	 * gap is the amount of sequence space between what we expect to see
13216 	 * and what we got for seg_seq.  A positive value for gap means
13217 	 * something got lost.  A negative value means we got some old stuff.
13218 	 */
13219 	if (gap < 0) {
13220 		/* Old stuff present.  Is the SYN in there? */
13221 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13222 		    (seg_len != 0)) {
13223 			flags &= ~TH_SYN;
13224 			seg_seq++;
13225 			urp--;
13226 			/* Recompute the gaps after noting the SYN. */
13227 			goto try_again;
13228 		}
13229 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13230 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13231 		    (seg_len > -gap ? -gap : seg_len));
13232 		/* Remove the old stuff from seg_len. */
13233 		seg_len += gap;
13234 		/*
13235 		 * Anything left?
13236 		 * Make sure to check for unack'd FIN when rest of data
13237 		 * has been previously ack'd.
13238 		 */
13239 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13240 			/*
13241 			 * Resets are only valid if they lie within our offered
13242 			 * window.  If the RST bit is set, we just ignore this
13243 			 * segment.
13244 			 */
13245 			if (flags & TH_RST) {
13246 				freemsg(mp);
13247 				return;
13248 			}
13249 
13250 			/*
13251 			 * The arriving of dup data packets indicate that we
13252 			 * may have postponed an ack for too long, or the other
13253 			 * side's RTT estimate is out of shape. Start acking
13254 			 * more often.
13255 			 */
13256 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13257 			    tcp->tcp_rack_cnt >= 1 &&
13258 			    tcp->tcp_rack_abs_max > 2) {
13259 				tcp->tcp_rack_abs_max--;
13260 			}
13261 			tcp->tcp_rack_cur_max = 1;
13262 
13263 			/*
13264 			 * This segment is "unacceptable".  None of its
13265 			 * sequence space lies within our advertized window.
13266 			 *
13267 			 * Adjust seg_len to the original value for tracing.
13268 			 */
13269 			seg_len -= gap;
13270 			if (tcp->tcp_debug) {
13271 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13272 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13273 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13274 				    "seg_len %d, rnxt %u, snxt %u, %s",
13275 				    gap, rgap, flags, seg_seq, seg_ack,
13276 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13277 				    tcp_display(tcp, NULL,
13278 				    DISP_ADDR_AND_PORT));
13279 			}
13280 
13281 			/*
13282 			 * Arrange to send an ACK in response to the
13283 			 * unacceptable segment per RFC 793 page 69. There
13284 			 * is only one small difference between ours and the
13285 			 * acceptability test in the RFC - we accept ACK-only
13286 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13287 			 * will be generated.
13288 			 *
13289 			 * Note that we have to ACK an ACK-only packet at least
13290 			 * for stacks that send 0-length keep-alives with
13291 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13292 			 * section 4.2.3.6. As long as we don't ever generate
13293 			 * an unacceptable packet in response to an incoming
13294 			 * packet that is unacceptable, it should not cause
13295 			 * "ACK wars".
13296 			 */
13297 			flags |=  TH_ACK_NEEDED;
13298 
13299 			/*
13300 			 * Continue processing this segment in order to use the
13301 			 * ACK information it contains, but skip all other
13302 			 * sequence-number processing.	Processing the ACK
13303 			 * information is necessary in order to
13304 			 * re-synchronize connections that may have lost
13305 			 * synchronization.
13306 			 *
13307 			 * We clear seg_len and flag fields related to
13308 			 * sequence number processing as they are not
13309 			 * to be trusted for an unacceptable segment.
13310 			 */
13311 			seg_len = 0;
13312 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13313 			goto process_ack;
13314 		}
13315 
13316 		/* Fix seg_seq, and chew the gap off the front. */
13317 		seg_seq = tcp->tcp_rnxt;
13318 		urp += gap;
13319 		do {
13320 			mblk_t	*mp2;
13321 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13322 			    (uintptr_t)UINT_MAX);
13323 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13324 			if (gap > 0) {
13325 				mp->b_rptr = mp->b_wptr - gap;
13326 				break;
13327 			}
13328 			mp2 = mp;
13329 			mp = mp->b_cont;
13330 			freeb(mp2);
13331 		} while (gap < 0);
13332 		/*
13333 		 * If the urgent data has already been acknowledged, we
13334 		 * should ignore TH_URG below
13335 		 */
13336 		if (urp < 0)
13337 			flags &= ~TH_URG;
13338 	}
13339 	/*
13340 	 * rgap is the amount of stuff received out of window.  A negative
13341 	 * value is the amount out of window.
13342 	 */
13343 	if (rgap < 0) {
13344 		mblk_t	*mp2;
13345 
13346 		if (tcp->tcp_rwnd == 0) {
13347 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13348 		} else {
13349 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13350 			UPDATE_MIB(&tcps->tcps_mib,
13351 			    tcpInDataPastWinBytes, -rgap);
13352 		}
13353 
13354 		/*
13355 		 * seg_len does not include the FIN, so if more than
13356 		 * just the FIN is out of window, we act like we don't
13357 		 * see it.  (If just the FIN is out of window, rgap
13358 		 * will be zero and we will go ahead and acknowledge
13359 		 * the FIN.)
13360 		 */
13361 		flags &= ~TH_FIN;
13362 
13363 		/* Fix seg_len and make sure there is something left. */
13364 		seg_len += rgap;
13365 		if (seg_len <= 0) {
13366 			/*
13367 			 * Resets are only valid if they lie within our offered
13368 			 * window.  If the RST bit is set, we just ignore this
13369 			 * segment.
13370 			 */
13371 			if (flags & TH_RST) {
13372 				freemsg(mp);
13373 				return;
13374 			}
13375 
13376 			/* Per RFC 793, we need to send back an ACK. */
13377 			flags |= TH_ACK_NEEDED;
13378 
13379 			/*
13380 			 * Send SIGURG as soon as possible i.e. even
13381 			 * if the TH_URG was delivered in a window probe
13382 			 * packet (which will be unacceptable).
13383 			 *
13384 			 * We generate a signal if none has been generated
13385 			 * for this connection or if this is a new urgent
13386 			 * byte. Also send a zero-length "unmarked" message
13387 			 * to inform SIOCATMARK that this is not the mark.
13388 			 *
13389 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13390 			 * is sent up. This plus the check for old data
13391 			 * (gap >= 0) handles the wraparound of the sequence
13392 			 * number space without having to always track the
13393 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13394 			 * this max in its rcv_up variable).
13395 			 *
13396 			 * This prevents duplicate SIGURGS due to a "late"
13397 			 * zero-window probe when the T_EXDATA_IND has already
13398 			 * been sent up.
13399 			 */
13400 			if ((flags & TH_URG) &&
13401 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13402 			    tcp->tcp_urp_last))) {
13403 				if (IPCL_IS_NONSTR(connp)) {
13404 					if (!TCP_IS_DETACHED(tcp)) {
13405 						(*connp->conn_upcalls->
13406 						    su_signal_oob)
13407 						    (connp->conn_upper_handle,
13408 						    urp);
13409 					}
13410 				} else {
13411 					mp1 = allocb(0, BPRI_MED);
13412 					if (mp1 == NULL) {
13413 						freemsg(mp);
13414 						return;
13415 					}
13416 					if (!TCP_IS_DETACHED(tcp) &&
13417 					    !putnextctl1(tcp->tcp_rq,
13418 					    M_PCSIG, SIGURG)) {
13419 						/* Try again on the rexmit. */
13420 						freemsg(mp1);
13421 						freemsg(mp);
13422 						return;
13423 					}
13424 					/*
13425 					 * If the next byte would be the mark
13426 					 * then mark with MARKNEXT else mark
13427 					 * with NOTMARKNEXT.
13428 					 */
13429 					if (gap == 0 && urp == 0)
13430 						mp1->b_flag |= MSGMARKNEXT;
13431 					else
13432 						mp1->b_flag |= MSGNOTMARKNEXT;
13433 					freemsg(tcp->tcp_urp_mark_mp);
13434 					tcp->tcp_urp_mark_mp = mp1;
13435 					flags |= TH_SEND_URP_MARK;
13436 				}
13437 				tcp->tcp_urp_last_valid = B_TRUE;
13438 				tcp->tcp_urp_last = urp + seg_seq;
13439 			}
13440 			/*
13441 			 * If this is a zero window probe, continue to
13442 			 * process the ACK part.  But we need to set seg_len
13443 			 * to 0 to avoid data processing.  Otherwise just
13444 			 * drop the segment and send back an ACK.
13445 			 */
13446 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13447 				flags &= ~(TH_SYN | TH_URG);
13448 				seg_len = 0;
13449 				goto process_ack;
13450 			} else {
13451 				freemsg(mp);
13452 				goto ack_check;
13453 			}
13454 		}
13455 		/* Pitch out of window stuff off the end. */
13456 		rgap = seg_len;
13457 		mp2 = mp;
13458 		do {
13459 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13460 			    (uintptr_t)INT_MAX);
13461 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13462 			if (rgap < 0) {
13463 				mp2->b_wptr += rgap;
13464 				if ((mp1 = mp2->b_cont) != NULL) {
13465 					mp2->b_cont = NULL;
13466 					freemsg(mp1);
13467 				}
13468 				break;
13469 			}
13470 		} while ((mp2 = mp2->b_cont) != NULL);
13471 	}
13472 ok:;
13473 	/*
13474 	 * TCP should check ECN info for segments inside the window only.
13475 	 * Therefore the check should be done here.
13476 	 */
13477 	if (tcp->tcp_ecn_ok) {
13478 		if (flags & TH_CWR) {
13479 			tcp->tcp_ecn_echo_on = B_FALSE;
13480 		}
13481 		/*
13482 		 * Note that both ECN_CE and CWR can be set in the
13483 		 * same segment.  In this case, we once again turn
13484 		 * on ECN_ECHO.
13485 		 */
13486 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13487 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13488 
13489 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13490 				tcp->tcp_ecn_echo_on = B_TRUE;
13491 			}
13492 		} else {
13493 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13494 
13495 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13496 			    htonl(IPH_ECN_CE << 20)) {
13497 				tcp->tcp_ecn_echo_on = B_TRUE;
13498 			}
13499 		}
13500 	}
13501 
13502 	/*
13503 	 * Check whether we can update tcp_ts_recent.  This test is
13504 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13505 	 * Extensions for High Performance: An Update", Internet Draft.
13506 	 */
13507 	if (tcp->tcp_snd_ts_ok &&
13508 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13509 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13510 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13511 		tcp->tcp_last_rcv_lbolt = lbolt64;
13512 	}
13513 
13514 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13515 		/*
13516 		 * FIN in an out of order segment.  We record this in
13517 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13518 		 * Clear the FIN so that any check on FIN flag will fail.
13519 		 * Remember that FIN also counts in the sequence number
13520 		 * space.  So we need to ack out of order FIN only segments.
13521 		 */
13522 		if (flags & TH_FIN) {
13523 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13524 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13525 			flags &= ~TH_FIN;
13526 			flags |= TH_ACK_NEEDED;
13527 		}
13528 		if (seg_len > 0) {
13529 			/* Fill in the SACK blk list. */
13530 			if (tcp->tcp_snd_sack_ok) {
13531 				ASSERT(tcp->tcp_sack_info != NULL);
13532 				tcp_sack_insert(tcp->tcp_sack_list,
13533 				    seg_seq, seg_seq + seg_len,
13534 				    &(tcp->tcp_num_sack_blk));
13535 			}
13536 
13537 			/*
13538 			 * Attempt reassembly and see if we have something
13539 			 * ready to go.
13540 			 */
13541 			mp = tcp_reass(tcp, mp, seg_seq);
13542 			/* Always ack out of order packets */
13543 			flags |= TH_ACK_NEEDED | TH_PUSH;
13544 			if (mp) {
13545 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13546 				    (uintptr_t)INT_MAX);
13547 				seg_len = mp->b_cont ? msgdsize(mp) :
13548 				    (int)(mp->b_wptr - mp->b_rptr);
13549 				seg_seq = tcp->tcp_rnxt;
13550 				/*
13551 				 * A gap is filled and the seq num and len
13552 				 * of the gap match that of a previously
13553 				 * received FIN, put the FIN flag back in.
13554 				 */
13555 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13556 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13557 					flags |= TH_FIN;
13558 					tcp->tcp_valid_bits &=
13559 					    ~TCP_OFO_FIN_VALID;
13560 				}
13561 			} else {
13562 				/*
13563 				 * Keep going even with NULL mp.
13564 				 * There may be a useful ACK or something else
13565 				 * we don't want to miss.
13566 				 *
13567 				 * But TCP should not perform fast retransmit
13568 				 * because of the ack number.  TCP uses
13569 				 * seg_len == 0 to determine if it is a pure
13570 				 * ACK.  And this is not a pure ACK.
13571 				 */
13572 				seg_len = 0;
13573 				ofo_seg = B_TRUE;
13574 			}
13575 		}
13576 	} else if (seg_len > 0) {
13577 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13578 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13579 		/*
13580 		 * If an out of order FIN was received before, and the seq
13581 		 * num and len of the new segment match that of the FIN,
13582 		 * put the FIN flag back in.
13583 		 */
13584 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13585 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13586 			flags |= TH_FIN;
13587 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13588 		}
13589 	}
13590 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13591 	if (flags & TH_RST) {
13592 		freemsg(mp);
13593 		switch (tcp->tcp_state) {
13594 		case TCPS_SYN_RCVD:
13595 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13596 			break;
13597 		case TCPS_ESTABLISHED:
13598 		case TCPS_FIN_WAIT_1:
13599 		case TCPS_FIN_WAIT_2:
13600 		case TCPS_CLOSE_WAIT:
13601 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13602 			break;
13603 		case TCPS_CLOSING:
13604 		case TCPS_LAST_ACK:
13605 			(void) tcp_clean_death(tcp, 0, 16);
13606 			break;
13607 		default:
13608 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13609 			(void) tcp_clean_death(tcp, ENXIO, 17);
13610 			break;
13611 		}
13612 		return;
13613 	}
13614 	if (flags & TH_SYN) {
13615 		/*
13616 		 * See RFC 793, Page 71
13617 		 *
13618 		 * The seq number must be in the window as it should
13619 		 * be "fixed" above.  If it is outside window, it should
13620 		 * be already rejected.  Note that we allow seg_seq to be
13621 		 * rnxt + rwnd because we want to accept 0 window probe.
13622 		 */
13623 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13624 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13625 		freemsg(mp);
13626 		/*
13627 		 * If the ACK flag is not set, just use our snxt as the
13628 		 * seq number of the RST segment.
13629 		 */
13630 		if (!(flags & TH_ACK)) {
13631 			seg_ack = tcp->tcp_snxt;
13632 		}
13633 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13634 		    TH_RST|TH_ACK);
13635 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13636 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13637 		return;
13638 	}
13639 	/*
13640 	 * urp could be -1 when the urp field in the packet is 0
13641 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13642 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13643 	 */
13644 	if (flags & TH_URG && urp >= 0) {
13645 		if (!tcp->tcp_urp_last_valid ||
13646 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13647 			if (IPCL_IS_NONSTR(connp)) {
13648 				if (!TCP_IS_DETACHED(tcp)) {
13649 					(*connp->conn_upcalls->su_signal_oob)
13650 					    (connp->conn_upper_handle, urp);
13651 				}
13652 			} else {
13653 				/*
13654 				 * If we haven't generated the signal yet for
13655 				 * this urgent pointer value, do it now.  Also,
13656 				 * send up a zero-length M_DATA indicating
13657 				 * whether or not this is the mark. The latter
13658 				 * is not needed when a T_EXDATA_IND is sent up.
13659 				 * However, if there are allocation failures
13660 				 * this code relies on the sender retransmitting
13661 				 * and the socket code for determining the mark
13662 				 * should not block waiting for the peer to
13663 				 * transmit. Thus, for simplicity we always
13664 				 * send up the mark indication.
13665 				 */
13666 				mp1 = allocb(0, BPRI_MED);
13667 				if (mp1 == NULL) {
13668 					freemsg(mp);
13669 					return;
13670 				}
13671 				if (!TCP_IS_DETACHED(tcp) &&
13672 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13673 				    SIGURG)) {
13674 					/* Try again on the rexmit. */
13675 					freemsg(mp1);
13676 					freemsg(mp);
13677 					return;
13678 				}
13679 				/*
13680 				 * Mark with NOTMARKNEXT for now.
13681 				 * The code below will change this to MARKNEXT
13682 				 * if we are at the mark.
13683 				 *
13684 				 * If there are allocation failures (e.g. in
13685 				 * dupmsg below) the next time tcp_rput_data
13686 				 * sees the urgent segment it will send up the
13687 				 * MSGMARKNEXT message.
13688 				 */
13689 				mp1->b_flag |= MSGNOTMARKNEXT;
13690 				freemsg(tcp->tcp_urp_mark_mp);
13691 				tcp->tcp_urp_mark_mp = mp1;
13692 				flags |= TH_SEND_URP_MARK;
13693 #ifdef DEBUG
13694 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13695 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13696 				    "last %x, %s",
13697 				    seg_seq, urp, tcp->tcp_urp_last,
13698 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13699 #endif /* DEBUG */
13700 			}
13701 			tcp->tcp_urp_last_valid = B_TRUE;
13702 			tcp->tcp_urp_last = urp + seg_seq;
13703 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13704 			/*
13705 			 * An allocation failure prevented the previous
13706 			 * tcp_rput_data from sending up the allocated
13707 			 * MSG*MARKNEXT message - send it up this time
13708 			 * around.
13709 			 */
13710 			flags |= TH_SEND_URP_MARK;
13711 		}
13712 
13713 		/*
13714 		 * If the urgent byte is in this segment, make sure that it is
13715 		 * all by itself.  This makes it much easier to deal with the
13716 		 * possibility of an allocation failure on the T_exdata_ind.
13717 		 * Note that seg_len is the number of bytes in the segment, and
13718 		 * urp is the offset into the segment of the urgent byte.
13719 		 * urp < seg_len means that the urgent byte is in this segment.
13720 		 */
13721 		if (urp < seg_len) {
13722 			if (seg_len != 1) {
13723 				uint32_t  tmp_rnxt;
13724 				/*
13725 				 * Break it up and feed it back in.
13726 				 * Re-attach the IP header.
13727 				 */
13728 				mp->b_rptr = iphdr;
13729 				if (urp > 0) {
13730 					/*
13731 					 * There is stuff before the urgent
13732 					 * byte.
13733 					 */
13734 					mp1 = dupmsg(mp);
13735 					if (!mp1) {
13736 						/*
13737 						 * Trim from urgent byte on.
13738 						 * The rest will come back.
13739 						 */
13740 						(void) adjmsg(mp,
13741 						    urp - seg_len);
13742 						tcp_rput_data(connp,
13743 						    mp, NULL);
13744 						return;
13745 					}
13746 					(void) adjmsg(mp1, urp - seg_len);
13747 					/* Feed this piece back in. */
13748 					tmp_rnxt = tcp->tcp_rnxt;
13749 					tcp_rput_data(connp, mp1, NULL);
13750 					/*
13751 					 * If the data passed back in was not
13752 					 * processed (ie: bad ACK) sending
13753 					 * the remainder back in will cause a
13754 					 * loop. In this case, drop the
13755 					 * packet and let the sender try
13756 					 * sending a good packet.
13757 					 */
13758 					if (tmp_rnxt == tcp->tcp_rnxt) {
13759 						freemsg(mp);
13760 						return;
13761 					}
13762 				}
13763 				if (urp != seg_len - 1) {
13764 					uint32_t  tmp_rnxt;
13765 					/*
13766 					 * There is stuff after the urgent
13767 					 * byte.
13768 					 */
13769 					mp1 = dupmsg(mp);
13770 					if (!mp1) {
13771 						/*
13772 						 * Trim everything beyond the
13773 						 * urgent byte.  The rest will
13774 						 * come back.
13775 						 */
13776 						(void) adjmsg(mp,
13777 						    urp + 1 - seg_len);
13778 						tcp_rput_data(connp,
13779 						    mp, NULL);
13780 						return;
13781 					}
13782 					(void) adjmsg(mp1, urp + 1 - seg_len);
13783 					tmp_rnxt = tcp->tcp_rnxt;
13784 					tcp_rput_data(connp, mp1, NULL);
13785 					/*
13786 					 * If the data passed back in was not
13787 					 * processed (ie: bad ACK) sending
13788 					 * the remainder back in will cause a
13789 					 * loop. In this case, drop the
13790 					 * packet and let the sender try
13791 					 * sending a good packet.
13792 					 */
13793 					if (tmp_rnxt == tcp->tcp_rnxt) {
13794 						freemsg(mp);
13795 						return;
13796 					}
13797 				}
13798 				tcp_rput_data(connp, mp, NULL);
13799 				return;
13800 			}
13801 			/*
13802 			 * This segment contains only the urgent byte.  We
13803 			 * have to allocate the T_exdata_ind, if we can.
13804 			 */
13805 			if (IPCL_IS_NONSTR(connp)) {
13806 				int error;
13807 
13808 				(*connp->conn_upcalls->su_recv)
13809 				    (connp->conn_upper_handle, mp, seg_len,
13810 				    MSG_OOB, &error, NULL);
13811 				/*
13812 				 * We should never be in middle of a
13813 				 * fallback, the squeue guarantees that.
13814 				 */
13815 				ASSERT(error != EOPNOTSUPP);
13816 				mp = NULL;
13817 				goto update_ack;
13818 			} else if (!tcp->tcp_urp_mp) {
13819 				struct T_exdata_ind *tei;
13820 				mp1 = allocb(sizeof (struct T_exdata_ind),
13821 				    BPRI_MED);
13822 				if (!mp1) {
13823 					/*
13824 					 * Sigh... It'll be back.
13825 					 * Generate any MSG*MARK message now.
13826 					 */
13827 					freemsg(mp);
13828 					seg_len = 0;
13829 					if (flags & TH_SEND_URP_MARK) {
13830 
13831 
13832 						ASSERT(tcp->tcp_urp_mark_mp);
13833 						tcp->tcp_urp_mark_mp->b_flag &=
13834 						    ~MSGNOTMARKNEXT;
13835 						tcp->tcp_urp_mark_mp->b_flag |=
13836 						    MSGMARKNEXT;
13837 					}
13838 					goto ack_check;
13839 				}
13840 				mp1->b_datap->db_type = M_PROTO;
13841 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13842 				tei->PRIM_type = T_EXDATA_IND;
13843 				tei->MORE_flag = 0;
13844 				mp1->b_wptr = (uchar_t *)&tei[1];
13845 				tcp->tcp_urp_mp = mp1;
13846 #ifdef DEBUG
13847 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13848 				    "tcp_rput: allocated exdata_ind %s",
13849 				    tcp_display(tcp, NULL,
13850 				    DISP_PORT_ONLY));
13851 #endif /* DEBUG */
13852 				/*
13853 				 * There is no need to send a separate MSG*MARK
13854 				 * message since the T_EXDATA_IND will be sent
13855 				 * now.
13856 				 */
13857 				flags &= ~TH_SEND_URP_MARK;
13858 				freemsg(tcp->tcp_urp_mark_mp);
13859 				tcp->tcp_urp_mark_mp = NULL;
13860 			}
13861 			/*
13862 			 * Now we are all set.  On the next putnext upstream,
13863 			 * tcp_urp_mp will be non-NULL and will get prepended
13864 			 * to what has to be this piece containing the urgent
13865 			 * byte.  If for any reason we abort this segment below,
13866 			 * if it comes back, we will have this ready, or it
13867 			 * will get blown off in close.
13868 			 */
13869 		} else if (urp == seg_len) {
13870 			/*
13871 			 * The urgent byte is the next byte after this sequence
13872 			 * number. If there is data it is marked with
13873 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13874 			 * since it is not needed. Otherwise, if the code
13875 			 * above just allocated a zero-length tcp_urp_mark_mp
13876 			 * message, that message is tagged with MSGMARKNEXT.
13877 			 * Sending up these MSGMARKNEXT messages makes
13878 			 * SIOCATMARK work correctly even though
13879 			 * the T_EXDATA_IND will not be sent up until the
13880 			 * urgent byte arrives.
13881 			 */
13882 			if (seg_len != 0) {
13883 				flags |= TH_MARKNEXT_NEEDED;
13884 				freemsg(tcp->tcp_urp_mark_mp);
13885 				tcp->tcp_urp_mark_mp = NULL;
13886 				flags &= ~TH_SEND_URP_MARK;
13887 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13888 				flags |= TH_SEND_URP_MARK;
13889 				tcp->tcp_urp_mark_mp->b_flag &=
13890 				    ~MSGNOTMARKNEXT;
13891 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13892 			}
13893 #ifdef DEBUG
13894 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13895 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13896 			    seg_len, flags,
13897 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13898 #endif /* DEBUG */
13899 		}
13900 #ifdef DEBUG
13901 		else {
13902 			/* Data left until we hit mark */
13903 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13904 			    "tcp_rput: URP %d bytes left, %s",
13905 			    urp - seg_len, tcp_display(tcp, NULL,
13906 			    DISP_PORT_ONLY));
13907 		}
13908 #endif /* DEBUG */
13909 	}
13910 
13911 process_ack:
13912 	if (!(flags & TH_ACK)) {
13913 		freemsg(mp);
13914 		goto xmit_check;
13915 	}
13916 	}
13917 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13918 
13919 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13920 		tcp->tcp_ip_forward_progress = B_TRUE;
13921 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13922 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13923 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13924 			/* 3-way handshake complete - pass up the T_CONN_IND */
13925 			tcp_t	*listener = tcp->tcp_listener;
13926 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13927 
13928 			tcp->tcp_tconnind_started = B_TRUE;
13929 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13930 			/*
13931 			 * We are here means eager is fine but it can
13932 			 * get a TH_RST at any point between now and till
13933 			 * accept completes and disappear. We need to
13934 			 * ensure that reference to eager is valid after
13935 			 * we get out of eager's perimeter. So we do
13936 			 * an extra refhold.
13937 			 */
13938 			CONN_INC_REF(connp);
13939 
13940 			/*
13941 			 * The listener also exists because of the refhold
13942 			 * done in tcp_conn_request. Its possible that it
13943 			 * might have closed. We will check that once we
13944 			 * get inside listeners context.
13945 			 */
13946 			CONN_INC_REF(listener->tcp_connp);
13947 			if (listener->tcp_connp->conn_sqp ==
13948 			    connp->conn_sqp) {
13949 				/*
13950 				 * We optimize by not calling an SQUEUE_ENTER
13951 				 * on the listener since we know that the
13952 				 * listener and eager squeues are the same.
13953 				 * We are able to make this check safely only
13954 				 * because neither the eager nor the listener
13955 				 * can change its squeue. Only an active connect
13956 				 * can change its squeue
13957 				 */
13958 				tcp_send_conn_ind(listener->tcp_connp, mp,
13959 				    listener->tcp_connp->conn_sqp);
13960 				CONN_DEC_REF(listener->tcp_connp);
13961 			} else if (!tcp->tcp_loopback) {
13962 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
13963 				    mp, tcp_send_conn_ind,
13964 				    listener->tcp_connp, SQ_FILL,
13965 				    SQTAG_TCP_CONN_IND);
13966 			} else {
13967 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
13968 				    mp, tcp_send_conn_ind,
13969 				    listener->tcp_connp, SQ_PROCESS,
13970 				    SQTAG_TCP_CONN_IND);
13971 			}
13972 		}
13973 
13974 		/*
13975 		 * We are seeing the final ack in the three way
13976 		 * hand shake of a active open'ed connection
13977 		 * so we must send up a T_CONN_CON
13978 		 *
13979 		 * tcp_sendmsg() checks tcp_state without entering
13980 		 * the squeue so tcp_state should be updated before
13981 		 * sending up connection confirmation.
13982 		 */
13983 		tcp->tcp_state = TCPS_ESTABLISHED;
13984 		if (tcp->tcp_active_open) {
13985 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13986 				freemsg(mp);
13987 				tcp->tcp_state = TCPS_SYN_RCVD;
13988 				return;
13989 			}
13990 			/*
13991 			 * Don't fuse the loopback endpoints for
13992 			 * simultaneous active opens.
13993 			 */
13994 			if (tcp->tcp_loopback) {
13995 				TCP_STAT(tcps, tcp_fusion_unfusable);
13996 				tcp->tcp_unfusable = B_TRUE;
13997 			}
13998 		}
13999 
14000 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14001 		bytes_acked--;
14002 		/* SYN was acked - making progress */
14003 		if (tcp->tcp_ipversion == IPV6_VERSION)
14004 			tcp->tcp_ip_forward_progress = B_TRUE;
14005 
14006 		/*
14007 		 * If SYN was retransmitted, need to reset all
14008 		 * retransmission info as this segment will be
14009 		 * treated as a dup ACK.
14010 		 */
14011 		if (tcp->tcp_rexmit) {
14012 			tcp->tcp_rexmit = B_FALSE;
14013 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14014 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14015 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14016 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14017 			tcp->tcp_ms_we_have_waited = 0;
14018 			tcp->tcp_cwnd = mss;
14019 		}
14020 
14021 		/*
14022 		 * We set the send window to zero here.
14023 		 * This is needed if there is data to be
14024 		 * processed already on the queue.
14025 		 * Later (at swnd_update label), the
14026 		 * "new_swnd > tcp_swnd" condition is satisfied
14027 		 * the XMIT_NEEDED flag is set in the current
14028 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14029 		 * called if there is already data on queue in
14030 		 * this state.
14031 		 */
14032 		tcp->tcp_swnd = 0;
14033 
14034 		if (new_swnd > tcp->tcp_max_swnd)
14035 			tcp->tcp_max_swnd = new_swnd;
14036 		tcp->tcp_swl1 = seg_seq;
14037 		tcp->tcp_swl2 = seg_ack;
14038 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14039 
14040 		/* Fuse when both sides are in ESTABLISHED state */
14041 		if (tcp->tcp_loopback && do_tcp_fusion)
14042 			tcp_fuse(tcp, iphdr, tcph);
14043 
14044 	}
14045 	/* This code follows 4.4BSD-Lite2 mostly. */
14046 	if (bytes_acked < 0)
14047 		goto est;
14048 
14049 	/*
14050 	 * If TCP is ECN capable and the congestion experience bit is
14051 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14052 	 * done once per window (or more loosely, per RTT).
14053 	 */
14054 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14055 		tcp->tcp_cwr = B_FALSE;
14056 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14057 		if (!tcp->tcp_cwr) {
14058 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14059 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14060 			tcp->tcp_cwnd = npkt * mss;
14061 			/*
14062 			 * If the cwnd is 0, use the timer to clock out
14063 			 * new segments.  This is required by the ECN spec.
14064 			 */
14065 			if (npkt == 0) {
14066 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14067 				/*
14068 				 * This makes sure that when the ACK comes
14069 				 * back, we will increase tcp_cwnd by 1 MSS.
14070 				 */
14071 				tcp->tcp_cwnd_cnt = 0;
14072 			}
14073 			tcp->tcp_cwr = B_TRUE;
14074 			/*
14075 			 * This marks the end of the current window of in
14076 			 * flight data.  That is why we don't use
14077 			 * tcp_suna + tcp_swnd.  Only data in flight can
14078 			 * provide ECN info.
14079 			 */
14080 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14081 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14082 		}
14083 	}
14084 
14085 	mp1 = tcp->tcp_xmit_head;
14086 	if (bytes_acked == 0) {
14087 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14088 			int dupack_cnt;
14089 
14090 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14091 			/*
14092 			 * Fast retransmit.  When we have seen exactly three
14093 			 * identical ACKs while we have unacked data
14094 			 * outstanding we take it as a hint that our peer
14095 			 * dropped something.
14096 			 *
14097 			 * If TCP is retransmitting, don't do fast retransmit.
14098 			 */
14099 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14100 			    ! tcp->tcp_rexmit) {
14101 				/* Do Limited Transmit */
14102 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14103 				    tcps->tcps_dupack_fast_retransmit) {
14104 					/*
14105 					 * RFC 3042
14106 					 *
14107 					 * What we need to do is temporarily
14108 					 * increase tcp_cwnd so that new
14109 					 * data can be sent if it is allowed
14110 					 * by the receive window (tcp_rwnd).
14111 					 * tcp_wput_data() will take care of
14112 					 * the rest.
14113 					 *
14114 					 * If the connection is SACK capable,
14115 					 * only do limited xmit when there
14116 					 * is SACK info.
14117 					 *
14118 					 * Note how tcp_cwnd is incremented.
14119 					 * The first dup ACK will increase
14120 					 * it by 1 MSS.  The second dup ACK
14121 					 * will increase it by 2 MSS.  This
14122 					 * means that only 1 new segment will
14123 					 * be sent for each dup ACK.
14124 					 */
14125 					if (tcp->tcp_unsent > 0 &&
14126 					    (!tcp->tcp_snd_sack_ok ||
14127 					    (tcp->tcp_snd_sack_ok &&
14128 					    tcp->tcp_notsack_list != NULL))) {
14129 						tcp->tcp_cwnd += mss <<
14130 						    (tcp->tcp_dupack_cnt - 1);
14131 						flags |= TH_LIMIT_XMIT;
14132 					}
14133 				} else if (dupack_cnt ==
14134 				    tcps->tcps_dupack_fast_retransmit) {
14135 
14136 				/*
14137 				 * If we have reduced tcp_ssthresh
14138 				 * because of ECN, do not reduce it again
14139 				 * unless it is already one window of data
14140 				 * away.  After one window of data, tcp_cwr
14141 				 * should then be cleared.  Note that
14142 				 * for non ECN capable connection, tcp_cwr
14143 				 * should always be false.
14144 				 *
14145 				 * Adjust cwnd since the duplicate
14146 				 * ack indicates that a packet was
14147 				 * dropped (due to congestion.)
14148 				 */
14149 				if (!tcp->tcp_cwr) {
14150 					npkt = ((tcp->tcp_snxt -
14151 					    tcp->tcp_suna) >> 1) / mss;
14152 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14153 					    mss;
14154 					tcp->tcp_cwnd = (npkt +
14155 					    tcp->tcp_dupack_cnt) * mss;
14156 				}
14157 				if (tcp->tcp_ecn_ok) {
14158 					tcp->tcp_cwr = B_TRUE;
14159 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14160 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14161 				}
14162 
14163 				/*
14164 				 * We do Hoe's algorithm.  Refer to her
14165 				 * paper "Improving the Start-up Behavior
14166 				 * of a Congestion Control Scheme for TCP,"
14167 				 * appeared in SIGCOMM'96.
14168 				 *
14169 				 * Save highest seq no we have sent so far.
14170 				 * Be careful about the invisible FIN byte.
14171 				 */
14172 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14173 				    (tcp->tcp_unsent == 0)) {
14174 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14175 				} else {
14176 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14177 				}
14178 
14179 				/*
14180 				 * Do not allow bursty traffic during.
14181 				 * fast recovery.  Refer to Fall and Floyd's
14182 				 * paper "Simulation-based Comparisons of
14183 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14184 				 * This is a best current practise.
14185 				 */
14186 				tcp->tcp_snd_burst = TCP_CWND_SS;
14187 
14188 				/*
14189 				 * For SACK:
14190 				 * Calculate tcp_pipe, which is the
14191 				 * estimated number of bytes in
14192 				 * network.
14193 				 *
14194 				 * tcp_fack is the highest sack'ed seq num
14195 				 * TCP has received.
14196 				 *
14197 				 * tcp_pipe is explained in the above quoted
14198 				 * Fall and Floyd's paper.  tcp_fack is
14199 				 * explained in Mathis and Mahdavi's
14200 				 * "Forward Acknowledgment: Refining TCP
14201 				 * Congestion Control" in SIGCOMM '96.
14202 				 */
14203 				if (tcp->tcp_snd_sack_ok) {
14204 					ASSERT(tcp->tcp_sack_info != NULL);
14205 					if (tcp->tcp_notsack_list != NULL) {
14206 						tcp->tcp_pipe = tcp->tcp_snxt -
14207 						    tcp->tcp_fack;
14208 						tcp->tcp_sack_snxt = seg_ack;
14209 						flags |= TH_NEED_SACK_REXMIT;
14210 					} else {
14211 						/*
14212 						 * Always initialize tcp_pipe
14213 						 * even though we don't have
14214 						 * any SACK info.  If later
14215 						 * we get SACK info and
14216 						 * tcp_pipe is not initialized,
14217 						 * funny things will happen.
14218 						 */
14219 						tcp->tcp_pipe =
14220 						    tcp->tcp_cwnd_ssthresh;
14221 					}
14222 				} else {
14223 					flags |= TH_REXMIT_NEEDED;
14224 				} /* tcp_snd_sack_ok */
14225 
14226 				} else {
14227 					/*
14228 					 * Here we perform congestion
14229 					 * avoidance, but NOT slow start.
14230 					 * This is known as the Fast
14231 					 * Recovery Algorithm.
14232 					 */
14233 					if (tcp->tcp_snd_sack_ok &&
14234 					    tcp->tcp_notsack_list != NULL) {
14235 						flags |= TH_NEED_SACK_REXMIT;
14236 						tcp->tcp_pipe -= mss;
14237 						if (tcp->tcp_pipe < 0)
14238 							tcp->tcp_pipe = 0;
14239 					} else {
14240 					/*
14241 					 * We know that one more packet has
14242 					 * left the pipe thus we can update
14243 					 * cwnd.
14244 					 */
14245 					cwnd = tcp->tcp_cwnd + mss;
14246 					if (cwnd > tcp->tcp_cwnd_max)
14247 						cwnd = tcp->tcp_cwnd_max;
14248 					tcp->tcp_cwnd = cwnd;
14249 					if (tcp->tcp_unsent > 0)
14250 						flags |= TH_XMIT_NEEDED;
14251 					}
14252 				}
14253 			}
14254 		} else if (tcp->tcp_zero_win_probe) {
14255 			/*
14256 			 * If the window has opened, need to arrange
14257 			 * to send additional data.
14258 			 */
14259 			if (new_swnd != 0) {
14260 				/* tcp_suna != tcp_snxt */
14261 				/* Packet contains a window update */
14262 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14263 				tcp->tcp_zero_win_probe = 0;
14264 				tcp->tcp_timer_backoff = 0;
14265 				tcp->tcp_ms_we_have_waited = 0;
14266 
14267 				/*
14268 				 * Transmit starting with tcp_suna since
14269 				 * the one byte probe is not ack'ed.
14270 				 * If TCP has sent more than one identical
14271 				 * probe, tcp_rexmit will be set.  That means
14272 				 * tcp_ss_rexmit() will send out the one
14273 				 * byte along with new data.  Otherwise,
14274 				 * fake the retransmission.
14275 				 */
14276 				flags |= TH_XMIT_NEEDED;
14277 				if (!tcp->tcp_rexmit) {
14278 					tcp->tcp_rexmit = B_TRUE;
14279 					tcp->tcp_dupack_cnt = 0;
14280 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14281 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14282 				}
14283 			}
14284 		}
14285 		goto swnd_update;
14286 	}
14287 
14288 	/*
14289 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14290 	 * If the ACK value acks something that we have not yet sent, it might
14291 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14292 	 * other side.
14293 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14294 	 * state is handled above, so we can always just drop the segment and
14295 	 * send an ACK here.
14296 	 *
14297 	 * Should we send ACKs in response to ACK only segments?
14298 	 */
14299 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14300 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14301 		/* drop the received segment */
14302 		freemsg(mp);
14303 
14304 		/*
14305 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14306 		 * greater than 0, check if the number of such
14307 		 * bogus ACks is greater than that count.  If yes,
14308 		 * don't send back any ACK.  This prevents TCP from
14309 		 * getting into an ACK storm if somehow an attacker
14310 		 * successfully spoofs an acceptable segment to our
14311 		 * peer.
14312 		 */
14313 		if (tcp_drop_ack_unsent_cnt > 0 &&
14314 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14315 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14316 			return;
14317 		}
14318 		mp = tcp_ack_mp(tcp);
14319 		if (mp != NULL) {
14320 			BUMP_LOCAL(tcp->tcp_obsegs);
14321 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14322 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14323 		}
14324 		return;
14325 	}
14326 
14327 	/*
14328 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14329 	 * blocks that are covered by this ACK.
14330 	 */
14331 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14332 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14333 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14334 	}
14335 
14336 	/*
14337 	 * If we got an ACK after fast retransmit, check to see
14338 	 * if it is a partial ACK.  If it is not and the congestion
14339 	 * window was inflated to account for the other side's
14340 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14341 	 */
14342 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14343 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14344 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14345 			tcp->tcp_dupack_cnt = 0;
14346 			/*
14347 			 * Restore the orig tcp_cwnd_ssthresh after
14348 			 * fast retransmit phase.
14349 			 */
14350 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14351 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14352 			}
14353 			tcp->tcp_rexmit_max = seg_ack;
14354 			tcp->tcp_cwnd_cnt = 0;
14355 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14356 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14357 
14358 			/*
14359 			 * Remove all notsack info to avoid confusion with
14360 			 * the next fast retrasnmit/recovery phase.
14361 			 */
14362 			if (tcp->tcp_snd_sack_ok &&
14363 			    tcp->tcp_notsack_list != NULL) {
14364 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14365 			}
14366 		} else {
14367 			if (tcp->tcp_snd_sack_ok &&
14368 			    tcp->tcp_notsack_list != NULL) {
14369 				flags |= TH_NEED_SACK_REXMIT;
14370 				tcp->tcp_pipe -= mss;
14371 				if (tcp->tcp_pipe < 0)
14372 					tcp->tcp_pipe = 0;
14373 			} else {
14374 				/*
14375 				 * Hoe's algorithm:
14376 				 *
14377 				 * Retransmit the unack'ed segment and
14378 				 * restart fast recovery.  Note that we
14379 				 * need to scale back tcp_cwnd to the
14380 				 * original value when we started fast
14381 				 * recovery.  This is to prevent overly
14382 				 * aggressive behaviour in sending new
14383 				 * segments.
14384 				 */
14385 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14386 				    tcps->tcps_dupack_fast_retransmit * mss;
14387 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14388 				flags |= TH_REXMIT_NEEDED;
14389 			}
14390 		}
14391 	} else {
14392 		tcp->tcp_dupack_cnt = 0;
14393 		if (tcp->tcp_rexmit) {
14394 			/*
14395 			 * TCP is retranmitting.  If the ACK ack's all
14396 			 * outstanding data, update tcp_rexmit_max and
14397 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14398 			 * to the correct value.
14399 			 *
14400 			 * Note that SEQ_LEQ() is used.  This is to avoid
14401 			 * unnecessary fast retransmit caused by dup ACKs
14402 			 * received when TCP does slow start retransmission
14403 			 * after a time out.  During this phase, TCP may
14404 			 * send out segments which are already received.
14405 			 * This causes dup ACKs to be sent back.
14406 			 */
14407 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14408 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14409 					tcp->tcp_rexmit_nxt = seg_ack;
14410 				}
14411 				if (seg_ack != tcp->tcp_rexmit_max) {
14412 					flags |= TH_XMIT_NEEDED;
14413 				}
14414 			} else {
14415 				tcp->tcp_rexmit = B_FALSE;
14416 				tcp->tcp_xmit_zc_clean = B_FALSE;
14417 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14418 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14419 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14420 			}
14421 			tcp->tcp_ms_we_have_waited = 0;
14422 		}
14423 	}
14424 
14425 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14426 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14427 	tcp->tcp_suna = seg_ack;
14428 	if (tcp->tcp_zero_win_probe != 0) {
14429 		tcp->tcp_zero_win_probe = 0;
14430 		tcp->tcp_timer_backoff = 0;
14431 	}
14432 
14433 	/*
14434 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14435 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14436 	 * will not reach here.
14437 	 */
14438 	if (mp1 == NULL) {
14439 		goto fin_acked;
14440 	}
14441 
14442 	/*
14443 	 * Update the congestion window.
14444 	 *
14445 	 * If TCP is not ECN capable or TCP is ECN capable but the
14446 	 * congestion experience bit is not set, increase the tcp_cwnd as
14447 	 * usual.
14448 	 */
14449 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14450 		cwnd = tcp->tcp_cwnd;
14451 		add = mss;
14452 
14453 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14454 			/*
14455 			 * This is to prevent an increase of less than 1 MSS of
14456 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14457 			 * may send out tinygrams in order to preserve mblk
14458 			 * boundaries.
14459 			 *
14460 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14461 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14462 			 * increased by 1 MSS for every RTTs.
14463 			 */
14464 			if (tcp->tcp_cwnd_cnt <= 0) {
14465 				tcp->tcp_cwnd_cnt = cwnd + add;
14466 			} else {
14467 				tcp->tcp_cwnd_cnt -= add;
14468 				add = 0;
14469 			}
14470 		}
14471 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14472 	}
14473 
14474 	/* See if the latest urgent data has been acknowledged */
14475 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14476 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14477 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14478 
14479 	/* Can we update the RTT estimates? */
14480 	if (tcp->tcp_snd_ts_ok) {
14481 		/* Ignore zero timestamp echo-reply. */
14482 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14483 			tcp_set_rto(tcp, (int32_t)lbolt -
14484 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14485 		}
14486 
14487 		/* If needed, restart the timer. */
14488 		if (tcp->tcp_set_timer == 1) {
14489 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14490 			tcp->tcp_set_timer = 0;
14491 		}
14492 		/*
14493 		 * Update tcp_csuna in case the other side stops sending
14494 		 * us timestamps.
14495 		 */
14496 		tcp->tcp_csuna = tcp->tcp_snxt;
14497 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14498 		/*
14499 		 * An ACK sequence we haven't seen before, so get the RTT
14500 		 * and update the RTO. But first check if the timestamp is
14501 		 * valid to use.
14502 		 */
14503 		if ((mp1->b_next != NULL) &&
14504 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14505 			tcp_set_rto(tcp, (int32_t)lbolt -
14506 			    (int32_t)(intptr_t)mp1->b_prev);
14507 		else
14508 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14509 
14510 		/* Remeber the last sequence to be ACKed */
14511 		tcp->tcp_csuna = seg_ack;
14512 		if (tcp->tcp_set_timer == 1) {
14513 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14514 			tcp->tcp_set_timer = 0;
14515 		}
14516 	} else {
14517 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14518 	}
14519 
14520 	/* Eat acknowledged bytes off the xmit queue. */
14521 	for (;;) {
14522 		mblk_t	*mp2;
14523 		uchar_t	*wptr;
14524 
14525 		wptr = mp1->b_wptr;
14526 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14527 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14528 		if (bytes_acked < 0) {
14529 			mp1->b_rptr = wptr + bytes_acked;
14530 			/*
14531 			 * Set a new timestamp if all the bytes timed by the
14532 			 * old timestamp have been ack'ed.
14533 			 */
14534 			if (SEQ_GT(seg_ack,
14535 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14536 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14537 				mp1->b_next = NULL;
14538 			}
14539 			break;
14540 		}
14541 		mp1->b_next = NULL;
14542 		mp1->b_prev = NULL;
14543 		mp2 = mp1;
14544 		mp1 = mp1->b_cont;
14545 
14546 		/*
14547 		 * This notification is required for some zero-copy
14548 		 * clients to maintain a copy semantic. After the data
14549 		 * is ack'ed, client is safe to modify or reuse the buffer.
14550 		 */
14551 		if (tcp->tcp_snd_zcopy_aware &&
14552 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14553 			tcp_zcopy_notify(tcp);
14554 		freeb(mp2);
14555 		if (bytes_acked == 0) {
14556 			if (mp1 == NULL) {
14557 				/* Everything is ack'ed, clear the tail. */
14558 				tcp->tcp_xmit_tail = NULL;
14559 				/*
14560 				 * Cancel the timer unless we are still
14561 				 * waiting for an ACK for the FIN packet.
14562 				 */
14563 				if (tcp->tcp_timer_tid != 0 &&
14564 				    tcp->tcp_snxt == tcp->tcp_suna) {
14565 					(void) TCP_TIMER_CANCEL(tcp,
14566 					    tcp->tcp_timer_tid);
14567 					tcp->tcp_timer_tid = 0;
14568 				}
14569 				goto pre_swnd_update;
14570 			}
14571 			if (mp2 != tcp->tcp_xmit_tail)
14572 				break;
14573 			tcp->tcp_xmit_tail = mp1;
14574 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14575 			    (uintptr_t)INT_MAX);
14576 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14577 			    mp1->b_rptr);
14578 			break;
14579 		}
14580 		if (mp1 == NULL) {
14581 			/*
14582 			 * More was acked but there is nothing more
14583 			 * outstanding.  This means that the FIN was
14584 			 * just acked or that we're talking to a clown.
14585 			 */
14586 fin_acked:
14587 			ASSERT(tcp->tcp_fin_sent);
14588 			tcp->tcp_xmit_tail = NULL;
14589 			if (tcp->tcp_fin_sent) {
14590 				/* FIN was acked - making progress */
14591 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14592 				    !tcp->tcp_fin_acked)
14593 					tcp->tcp_ip_forward_progress = B_TRUE;
14594 				tcp->tcp_fin_acked = B_TRUE;
14595 				if (tcp->tcp_linger_tid != 0 &&
14596 				    TCP_TIMER_CANCEL(tcp,
14597 				    tcp->tcp_linger_tid) >= 0) {
14598 					tcp_stop_lingering(tcp);
14599 					freemsg(mp);
14600 					mp = NULL;
14601 				}
14602 			} else {
14603 				/*
14604 				 * We should never get here because
14605 				 * we have already checked that the
14606 				 * number of bytes ack'ed should be
14607 				 * smaller than or equal to what we
14608 				 * have sent so far (it is the
14609 				 * acceptability check of the ACK).
14610 				 * We can only get here if the send
14611 				 * queue is corrupted.
14612 				 *
14613 				 * Terminate the connection and
14614 				 * panic the system.  It is better
14615 				 * for us to panic instead of
14616 				 * continuing to avoid other disaster.
14617 				 */
14618 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14619 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14620 				panic("Memory corruption "
14621 				    "detected for connection %s.",
14622 				    tcp_display(tcp, NULL,
14623 				    DISP_ADDR_AND_PORT));
14624 				/*NOTREACHED*/
14625 			}
14626 			goto pre_swnd_update;
14627 		}
14628 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14629 	}
14630 	if (tcp->tcp_unsent) {
14631 		flags |= TH_XMIT_NEEDED;
14632 	}
14633 pre_swnd_update:
14634 	tcp->tcp_xmit_head = mp1;
14635 swnd_update:
14636 	/*
14637 	 * The following check is different from most other implementations.
14638 	 * For bi-directional transfer, when segments are dropped, the
14639 	 * "normal" check will not accept a window update in those
14640 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14641 	 * segments which are outside receiver's window.  As TCP accepts
14642 	 * the ack in those retransmitted segments, if the window update in
14643 	 * the same segment is not accepted, TCP will incorrectly calculates
14644 	 * that it can send more segments.  This can create a deadlock
14645 	 * with the receiver if its window becomes zero.
14646 	 */
14647 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14648 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14649 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14650 		/*
14651 		 * The criteria for update is:
14652 		 *
14653 		 * 1. the segment acknowledges some data.  Or
14654 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14655 		 * 3. the segment is not old and the advertised window is
14656 		 * larger than the previous advertised window.
14657 		 */
14658 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14659 			flags |= TH_XMIT_NEEDED;
14660 		tcp->tcp_swnd = new_swnd;
14661 		if (new_swnd > tcp->tcp_max_swnd)
14662 			tcp->tcp_max_swnd = new_swnd;
14663 		tcp->tcp_swl1 = seg_seq;
14664 		tcp->tcp_swl2 = seg_ack;
14665 	}
14666 est:
14667 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14668 
14669 		switch (tcp->tcp_state) {
14670 		case TCPS_FIN_WAIT_1:
14671 			if (tcp->tcp_fin_acked) {
14672 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14673 				/*
14674 				 * We implement the non-standard BSD/SunOS
14675 				 * FIN_WAIT_2 flushing algorithm.
14676 				 * If there is no user attached to this
14677 				 * TCP endpoint, then this TCP struct
14678 				 * could hang around forever in FIN_WAIT_2
14679 				 * state if the peer forgets to send us
14680 				 * a FIN.  To prevent this, we wait only
14681 				 * 2*MSL (a convenient time value) for
14682 				 * the FIN to arrive.  If it doesn't show up,
14683 				 * we flush the TCP endpoint.  This algorithm,
14684 				 * though a violation of RFC-793, has worked
14685 				 * for over 10 years in BSD systems.
14686 				 * Note: SunOS 4.x waits 675 seconds before
14687 				 * flushing the FIN_WAIT_2 connection.
14688 				 */
14689 				TCP_TIMER_RESTART(tcp,
14690 				    tcps->tcps_fin_wait_2_flush_interval);
14691 			}
14692 			break;
14693 		case TCPS_FIN_WAIT_2:
14694 			break;	/* Shutdown hook? */
14695 		case TCPS_LAST_ACK:
14696 			freemsg(mp);
14697 			if (tcp->tcp_fin_acked) {
14698 				(void) tcp_clean_death(tcp, 0, 19);
14699 				return;
14700 			}
14701 			goto xmit_check;
14702 		case TCPS_CLOSING:
14703 			if (tcp->tcp_fin_acked) {
14704 				tcp->tcp_state = TCPS_TIME_WAIT;
14705 				/*
14706 				 * Unconditionally clear the exclusive binding
14707 				 * bit so this TIME-WAIT connection won't
14708 				 * interfere with new ones.
14709 				 */
14710 				tcp->tcp_exclbind = 0;
14711 				if (!TCP_IS_DETACHED(tcp)) {
14712 					TCP_TIMER_RESTART(tcp,
14713 					    tcps->tcps_time_wait_interval);
14714 				} else {
14715 					tcp_time_wait_append(tcp);
14716 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14717 				}
14718 			}
14719 			/*FALLTHRU*/
14720 		case TCPS_CLOSE_WAIT:
14721 			freemsg(mp);
14722 			goto xmit_check;
14723 		default:
14724 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14725 			break;
14726 		}
14727 	}
14728 	if (flags & TH_FIN) {
14729 		/* Make sure we ack the fin */
14730 		flags |= TH_ACK_NEEDED;
14731 		if (!tcp->tcp_fin_rcvd) {
14732 			tcp->tcp_fin_rcvd = B_TRUE;
14733 			tcp->tcp_rnxt++;
14734 			tcph = tcp->tcp_tcph;
14735 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14736 
14737 			/*
14738 			 * Generate the ordrel_ind at the end unless we
14739 			 * are an eager guy.
14740 			 * In the eager case tcp_rsrv will do this when run
14741 			 * after tcp_accept is done.
14742 			 */
14743 			if (tcp->tcp_listener == NULL &&
14744 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14745 				flags |= TH_ORDREL_NEEDED;
14746 			switch (tcp->tcp_state) {
14747 			case TCPS_SYN_RCVD:
14748 			case TCPS_ESTABLISHED:
14749 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14750 				/* Keepalive? */
14751 				break;
14752 			case TCPS_FIN_WAIT_1:
14753 				if (!tcp->tcp_fin_acked) {
14754 					tcp->tcp_state = TCPS_CLOSING;
14755 					break;
14756 				}
14757 				/* FALLTHRU */
14758 			case TCPS_FIN_WAIT_2:
14759 				tcp->tcp_state = TCPS_TIME_WAIT;
14760 				/*
14761 				 * Unconditionally clear the exclusive binding
14762 				 * bit so this TIME-WAIT connection won't
14763 				 * interfere with new ones.
14764 				 */
14765 				tcp->tcp_exclbind = 0;
14766 				if (!TCP_IS_DETACHED(tcp)) {
14767 					TCP_TIMER_RESTART(tcp,
14768 					    tcps->tcps_time_wait_interval);
14769 				} else {
14770 					tcp_time_wait_append(tcp);
14771 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14772 				}
14773 				if (seg_len) {
14774 					/*
14775 					 * implies data piggybacked on FIN.
14776 					 * break to handle data.
14777 					 */
14778 					break;
14779 				}
14780 				freemsg(mp);
14781 				goto ack_check;
14782 			}
14783 		}
14784 	}
14785 	if (mp == NULL)
14786 		goto xmit_check;
14787 	if (seg_len == 0) {
14788 		freemsg(mp);
14789 		goto xmit_check;
14790 	}
14791 	if (mp->b_rptr == mp->b_wptr) {
14792 		/*
14793 		 * The header has been consumed, so we remove the
14794 		 * zero-length mblk here.
14795 		 */
14796 		mp1 = mp;
14797 		mp = mp->b_cont;
14798 		freeb(mp1);
14799 	}
14800 update_ack:
14801 	tcph = tcp->tcp_tcph;
14802 	tcp->tcp_rack_cnt++;
14803 	{
14804 		uint32_t cur_max;
14805 
14806 		cur_max = tcp->tcp_rack_cur_max;
14807 		if (tcp->tcp_rack_cnt >= cur_max) {
14808 			/*
14809 			 * We have more unacked data than we should - send
14810 			 * an ACK now.
14811 			 */
14812 			flags |= TH_ACK_NEEDED;
14813 			cur_max++;
14814 			if (cur_max > tcp->tcp_rack_abs_max)
14815 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14816 			else
14817 				tcp->tcp_rack_cur_max = cur_max;
14818 		} else if (TCP_IS_DETACHED(tcp)) {
14819 			/* We don't have an ACK timer for detached TCP. */
14820 			flags |= TH_ACK_NEEDED;
14821 		} else if (seg_len < mss) {
14822 			/*
14823 			 * If we get a segment that is less than an mss, and we
14824 			 * already have unacknowledged data, and the amount
14825 			 * unacknowledged is not a multiple of mss, then we
14826 			 * better generate an ACK now.  Otherwise, this may be
14827 			 * the tail piece of a transaction, and we would rather
14828 			 * wait for the response.
14829 			 */
14830 			uint32_t udif;
14831 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14832 			    (uintptr_t)INT_MAX);
14833 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14834 			if (udif && (udif % mss))
14835 				flags |= TH_ACK_NEEDED;
14836 			else
14837 				flags |= TH_ACK_TIMER_NEEDED;
14838 		} else {
14839 			/* Start delayed ack timer */
14840 			flags |= TH_ACK_TIMER_NEEDED;
14841 		}
14842 	}
14843 	tcp->tcp_rnxt += seg_len;
14844 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14845 
14846 	if (mp == NULL)
14847 		goto xmit_check;
14848 
14849 	/* Update SACK list */
14850 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14851 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14852 		    &(tcp->tcp_num_sack_blk));
14853 	}
14854 
14855 	if (tcp->tcp_urp_mp) {
14856 		tcp->tcp_urp_mp->b_cont = mp;
14857 		mp = tcp->tcp_urp_mp;
14858 		tcp->tcp_urp_mp = NULL;
14859 		/* Ready for a new signal. */
14860 		tcp->tcp_urp_last_valid = B_FALSE;
14861 #ifdef DEBUG
14862 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14863 		    "tcp_rput: sending exdata_ind %s",
14864 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14865 #endif /* DEBUG */
14866 	}
14867 
14868 	/*
14869 	 * Check for ancillary data changes compared to last segment.
14870 	 */
14871 	if (tcp->tcp_ipv6_recvancillary != 0) {
14872 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14873 		ASSERT(mp != NULL);
14874 	}
14875 
14876 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14877 		/*
14878 		 * Side queue inbound data until the accept happens.
14879 		 * tcp_accept/tcp_rput drains this when the accept happens.
14880 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14881 		 * T_EXDATA_IND) it is queued on b_next.
14882 		 * XXX Make urgent data use this. Requires:
14883 		 *	Removing tcp_listener check for TH_URG
14884 		 *	Making M_PCPROTO and MARK messages skip the eager case
14885 		 */
14886 
14887 		if (tcp->tcp_kssl_pending) {
14888 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
14889 			    mblk_t *, mp);
14890 			tcp_kssl_input(tcp, mp);
14891 		} else {
14892 			tcp_rcv_enqueue(tcp, mp, seg_len);
14893 		}
14894 	} else {
14895 		if (mp->b_datap->db_type != M_DATA ||
14896 		    (flags & TH_MARKNEXT_NEEDED)) {
14897 			if (IPCL_IS_NONSTR(connp)) {
14898 				int error;
14899 
14900 				if ((*connp->conn_upcalls->su_recv)
14901 				    (connp->conn_upper_handle, mp,
14902 				    seg_len, 0, &error, NULL) <= 0) {
14903 					/*
14904 					 * We should never be in middle of a
14905 					 * fallback, the squeue guarantees that.
14906 					 */
14907 					ASSERT(error != EOPNOTSUPP);
14908 					if (error == ENOSPC)
14909 						tcp->tcp_rwnd -= seg_len;
14910 				}
14911 			} else if (tcp->tcp_rcv_list != NULL) {
14912 				flags |= tcp_rcv_drain(tcp);
14913 			}
14914 			ASSERT(tcp->tcp_rcv_list == NULL ||
14915 			    tcp->tcp_fused_sigurg);
14916 
14917 			if (flags & TH_MARKNEXT_NEEDED) {
14918 #ifdef DEBUG
14919 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14920 				    "tcp_rput: sending MSGMARKNEXT %s",
14921 				    tcp_display(tcp, NULL,
14922 				    DISP_PORT_ONLY));
14923 #endif /* DEBUG */
14924 				mp->b_flag |= MSGMARKNEXT;
14925 				flags &= ~TH_MARKNEXT_NEEDED;
14926 			}
14927 
14928 			/* Does this need SSL processing first? */
14929 			if ((tcp->tcp_kssl_ctx != NULL) &&
14930 			    (DB_TYPE(mp) == M_DATA)) {
14931 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
14932 				    mblk_t *, mp);
14933 				tcp_kssl_input(tcp, mp);
14934 			} else if (!IPCL_IS_NONSTR(connp)) {
14935 				/* Already handled non-STREAMS case. */
14936 				putnext(tcp->tcp_rq, mp);
14937 				if (!canputnext(tcp->tcp_rq))
14938 					tcp->tcp_rwnd -= seg_len;
14939 			}
14940 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
14941 		    (DB_TYPE(mp) == M_DATA)) {
14942 			/* Does this need SSL processing first? */
14943 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
14944 			tcp_kssl_input(tcp, mp);
14945 		} else if (IPCL_IS_NONSTR(connp)) {
14946 			/* Non-STREAMS socket */
14947 			boolean_t push = flags & (TH_PUSH|TH_FIN);
14948 			int	error;
14949 
14950 			if ((*connp->conn_upcalls->su_recv)(
14951 			    connp->conn_upper_handle,
14952 			    mp, seg_len, 0, &error, &push) <= 0) {
14953 				/*
14954 				 * We should never be in middle of a
14955 				 * fallback, the squeue guarantees that.
14956 				 */
14957 				ASSERT(error != EOPNOTSUPP);
14958 				if (error == ENOSPC)
14959 					tcp->tcp_rwnd -= seg_len;
14960 			} else if (push) {
14961 				/*
14962 				 * PUSH bit set and sockfs is not
14963 				 * flow controlled
14964 				 */
14965 				flags |= tcp_rwnd_reopen(tcp);
14966 			}
14967 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14968 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
14969 			if (tcp->tcp_rcv_list != NULL) {
14970 				/*
14971 				 * Enqueue the new segment first and then
14972 				 * call tcp_rcv_drain() to send all data
14973 				 * up.  The other way to do this is to
14974 				 * send all queued data up and then call
14975 				 * putnext() to send the new segment up.
14976 				 * This way can remove the else part later
14977 				 * on.
14978 				 *
14979 				 * We don't do this to avoid one more call to
14980 				 * canputnext() as tcp_rcv_drain() needs to
14981 				 * call canputnext().
14982 				 */
14983 				tcp_rcv_enqueue(tcp, mp, seg_len);
14984 				flags |= tcp_rcv_drain(tcp);
14985 			} else {
14986 				putnext(tcp->tcp_rq, mp);
14987 				if (!canputnext(tcp->tcp_rq))
14988 					tcp->tcp_rwnd -= seg_len;
14989 			}
14990 		} else {
14991 			/*
14992 			 * Enqueue all packets when processing an mblk
14993 			 * from the co queue and also enqueue normal packets.
14994 			 */
14995 			tcp_rcv_enqueue(tcp, mp, seg_len);
14996 		}
14997 		/*
14998 		 * Make sure the timer is running if we have data waiting
14999 		 * for a push bit. This provides resiliency against
15000 		 * implementations that do not correctly generate push bits.
15001 		 */
15002 		if (!IPCL_IS_NONSTR(connp) && tcp->tcp_rcv_list != NULL &&
15003 		    tcp->tcp_push_tid == 0) {
15004 			/*
15005 			 * The connection may be closed at this point, so don't
15006 			 * do anything for a detached tcp.
15007 			 */
15008 			if (!TCP_IS_DETACHED(tcp))
15009 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15010 				    tcp_push_timer,
15011 				    MSEC_TO_TICK(
15012 				    tcps->tcps_push_timer_interval));
15013 		}
15014 	}
15015 
15016 xmit_check:
15017 	/* Is there anything left to do? */
15018 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15019 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15020 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15021 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15022 		goto done;
15023 
15024 	/* Any transmit work to do and a non-zero window? */
15025 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15026 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15027 		if (flags & TH_REXMIT_NEEDED) {
15028 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15029 
15030 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15031 			if (snd_size > mss)
15032 				snd_size = mss;
15033 			if (snd_size > tcp->tcp_swnd)
15034 				snd_size = tcp->tcp_swnd;
15035 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15036 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15037 			    B_TRUE);
15038 
15039 			if (mp1 != NULL) {
15040 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15041 				tcp->tcp_csuna = tcp->tcp_snxt;
15042 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15043 				UPDATE_MIB(&tcps->tcps_mib,
15044 				    tcpRetransBytes, snd_size);
15045 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15046 			}
15047 		}
15048 		if (flags & TH_NEED_SACK_REXMIT) {
15049 			tcp_sack_rxmit(tcp, &flags);
15050 		}
15051 		/*
15052 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15053 		 * out new segment.  Note that tcp_rexmit should not be
15054 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15055 		 */
15056 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15057 			if (!tcp->tcp_rexmit) {
15058 				tcp_wput_data(tcp, NULL, B_FALSE);
15059 			} else {
15060 				tcp_ss_rexmit(tcp);
15061 			}
15062 		}
15063 		/*
15064 		 * Adjust tcp_cwnd back to normal value after sending
15065 		 * new data segments.
15066 		 */
15067 		if (flags & TH_LIMIT_XMIT) {
15068 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15069 			/*
15070 			 * This will restart the timer.  Restarting the
15071 			 * timer is used to avoid a timeout before the
15072 			 * limited transmitted segment's ACK gets back.
15073 			 */
15074 			if (tcp->tcp_xmit_head != NULL)
15075 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15076 		}
15077 
15078 		/* Anything more to do? */
15079 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15080 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15081 			goto done;
15082 	}
15083 ack_check:
15084 	if (flags & TH_SEND_URP_MARK) {
15085 		ASSERT(tcp->tcp_urp_mark_mp);
15086 		ASSERT(!IPCL_IS_NONSTR(connp));
15087 		/*
15088 		 * Send up any queued data and then send the mark message
15089 		 */
15090 		if (tcp->tcp_rcv_list != NULL) {
15091 			flags |= tcp_rcv_drain(tcp);
15092 
15093 		}
15094 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15095 		mp1 = tcp->tcp_urp_mark_mp;
15096 		tcp->tcp_urp_mark_mp = NULL;
15097 		putnext(tcp->tcp_rq, mp1);
15098 #ifdef DEBUG
15099 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15100 		    "tcp_rput: sending zero-length %s %s",
15101 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15102 		    "MSGNOTMARKNEXT"),
15103 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15104 #endif /* DEBUG */
15105 		flags &= ~TH_SEND_URP_MARK;
15106 	}
15107 	if (flags & TH_ACK_NEEDED) {
15108 		/*
15109 		 * Time to send an ack for some reason.
15110 		 */
15111 		mp1 = tcp_ack_mp(tcp);
15112 
15113 		if (mp1 != NULL) {
15114 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15115 			BUMP_LOCAL(tcp->tcp_obsegs);
15116 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15117 		}
15118 		if (tcp->tcp_ack_tid != 0) {
15119 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15120 			tcp->tcp_ack_tid = 0;
15121 		}
15122 	}
15123 	if (flags & TH_ACK_TIMER_NEEDED) {
15124 		/*
15125 		 * Arrange for deferred ACK or push wait timeout.
15126 		 * Start timer if it is not already running.
15127 		 */
15128 		if (tcp->tcp_ack_tid == 0) {
15129 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15130 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15131 			    (clock_t)tcps->tcps_local_dack_interval :
15132 			    (clock_t)tcps->tcps_deferred_ack_interval));
15133 		}
15134 	}
15135 	if (flags & TH_ORDREL_NEEDED) {
15136 		/*
15137 		 * Send up the ordrel_ind unless we are an eager guy.
15138 		 * In the eager case tcp_rsrv will do this when run
15139 		 * after tcp_accept is done.
15140 		 */
15141 		ASSERT(tcp->tcp_listener == NULL);
15142 
15143 		if (IPCL_IS_NONSTR(connp)) {
15144 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15145 			tcp->tcp_ordrel_done = B_TRUE;
15146 			(*connp->conn_upcalls->su_opctl)
15147 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15148 			goto done;
15149 		}
15150 
15151 		if (tcp->tcp_rcv_list != NULL) {
15152 			/*
15153 			 * Push any mblk(s) enqueued from co processing.
15154 			 */
15155 			flags |= tcp_rcv_drain(tcp);
15156 		}
15157 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15158 
15159 		mp1 = tcp->tcp_ordrel_mp;
15160 		tcp->tcp_ordrel_mp = NULL;
15161 		tcp->tcp_ordrel_done = B_TRUE;
15162 		putnext(tcp->tcp_rq, mp1);
15163 	}
15164 done:
15165 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15166 }
15167 
15168 /*
15169  * This function does PAWS protection check. Returns B_TRUE if the
15170  * segment passes the PAWS test, else returns B_FALSE.
15171  */
15172 boolean_t
15173 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15174 {
15175 	uint8_t	flags;
15176 	int	options;
15177 	uint8_t *up;
15178 
15179 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15180 	/*
15181 	 * If timestamp option is aligned nicely, get values inline,
15182 	 * otherwise call general routine to parse.  Only do that
15183 	 * if timestamp is the only option.
15184 	 */
15185 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15186 	    TCPOPT_REAL_TS_LEN &&
15187 	    OK_32PTR((up = ((uint8_t *)tcph) +
15188 	    TCP_MIN_HEADER_LENGTH)) &&
15189 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15190 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15191 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15192 
15193 		options = TCP_OPT_TSTAMP_PRESENT;
15194 	} else {
15195 		if (tcp->tcp_snd_sack_ok) {
15196 			tcpoptp->tcp = tcp;
15197 		} else {
15198 			tcpoptp->tcp = NULL;
15199 		}
15200 		options = tcp_parse_options(tcph, tcpoptp);
15201 	}
15202 
15203 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15204 		/*
15205 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15206 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15207 		 */
15208 		if ((flags & TH_RST) == 0 &&
15209 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15210 		    tcp->tcp_ts_recent)) {
15211 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15212 			    PAWS_TIMEOUT)) {
15213 				/* This segment is not acceptable. */
15214 				return (B_FALSE);
15215 			} else {
15216 				/*
15217 				 * Connection has been idle for
15218 				 * too long.  Reset the timestamp
15219 				 * and assume the segment is valid.
15220 				 */
15221 				tcp->tcp_ts_recent =
15222 				    tcpoptp->tcp_opt_ts_val;
15223 			}
15224 		}
15225 	} else {
15226 		/*
15227 		 * If we don't get a timestamp on every packet, we
15228 		 * figure we can't really trust 'em, so we stop sending
15229 		 * and parsing them.
15230 		 */
15231 		tcp->tcp_snd_ts_ok = B_FALSE;
15232 
15233 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15234 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15235 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15236 		/*
15237 		 * Adjust the tcp_mss accordingly. We also need to
15238 		 * adjust tcp_cwnd here in accordance with the new mss.
15239 		 * But we avoid doing a slow start here so as to not
15240 		 * to lose on the transfer rate built up so far.
15241 		 */
15242 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15243 		if (tcp->tcp_snd_sack_ok) {
15244 			ASSERT(tcp->tcp_sack_info != NULL);
15245 			tcp->tcp_max_sack_blk = 4;
15246 		}
15247 	}
15248 	return (B_TRUE);
15249 }
15250 
15251 /*
15252  * Attach ancillary data to a received TCP segments for the
15253  * ancillary pieces requested by the application that are
15254  * different than they were in the previous data segment.
15255  *
15256  * Save the "current" values once memory allocation is ok so that
15257  * when memory allocation fails we can just wait for the next data segment.
15258  */
15259 static mblk_t *
15260 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15261 {
15262 	struct T_optdata_ind *todi;
15263 	int optlen;
15264 	uchar_t *optptr;
15265 	struct T_opthdr *toh;
15266 	uint_t addflag;	/* Which pieces to add */
15267 	mblk_t *mp1;
15268 
15269 	optlen = 0;
15270 	addflag = 0;
15271 	/* If app asked for pktinfo and the index has changed ... */
15272 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15273 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15274 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15275 		optlen += sizeof (struct T_opthdr) +
15276 		    sizeof (struct in6_pktinfo);
15277 		addflag |= TCP_IPV6_RECVPKTINFO;
15278 	}
15279 	/* If app asked for hoplimit and it has changed ... */
15280 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15281 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15282 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15283 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15284 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15285 	}
15286 	/* If app asked for tclass and it has changed ... */
15287 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15288 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15289 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15290 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15291 		addflag |= TCP_IPV6_RECVTCLASS;
15292 	}
15293 	/*
15294 	 * If app asked for hopbyhop headers and it has changed ...
15295 	 * For security labels, note that (1) security labels can't change on
15296 	 * a connected socket at all, (2) we're connected to at most one peer,
15297 	 * (3) if anything changes, then it must be some other extra option.
15298 	 */
15299 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15300 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15301 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15302 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15303 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15304 		    tcp->tcp_label_len;
15305 		addflag |= TCP_IPV6_RECVHOPOPTS;
15306 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15307 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15308 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15309 			return (mp);
15310 	}
15311 	/* If app asked for dst headers before routing headers ... */
15312 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15313 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15314 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15315 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15316 		optlen += sizeof (struct T_opthdr) +
15317 		    ipp->ipp_rtdstoptslen;
15318 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15319 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15320 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15321 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15322 			return (mp);
15323 	}
15324 	/* If app asked for routing headers and it has changed ... */
15325 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15326 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15327 	    (ipp->ipp_fields & IPPF_RTHDR),
15328 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15329 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15330 		addflag |= TCP_IPV6_RECVRTHDR;
15331 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15332 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15333 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15334 			return (mp);
15335 	}
15336 	/* If app asked for dest headers and it has changed ... */
15337 	if ((tcp->tcp_ipv6_recvancillary &
15338 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15339 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15340 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15341 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15342 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15343 		addflag |= TCP_IPV6_RECVDSTOPTS;
15344 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15345 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15346 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15347 			return (mp);
15348 	}
15349 
15350 	if (optlen == 0) {
15351 		/* Nothing to add */
15352 		return (mp);
15353 	}
15354 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15355 	if (mp1 == NULL) {
15356 		/*
15357 		 * Defer sending ancillary data until the next TCP segment
15358 		 * arrives.
15359 		 */
15360 		return (mp);
15361 	}
15362 	mp1->b_cont = mp;
15363 	mp = mp1;
15364 	mp->b_wptr += sizeof (*todi) + optlen;
15365 	mp->b_datap->db_type = M_PROTO;
15366 	todi = (struct T_optdata_ind *)mp->b_rptr;
15367 	todi->PRIM_type = T_OPTDATA_IND;
15368 	todi->DATA_flag = 1;	/* MORE data */
15369 	todi->OPT_length = optlen;
15370 	todi->OPT_offset = sizeof (*todi);
15371 	optptr = (uchar_t *)&todi[1];
15372 	/*
15373 	 * If app asked for pktinfo and the index has changed ...
15374 	 * Note that the local address never changes for the connection.
15375 	 */
15376 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15377 		struct in6_pktinfo *pkti;
15378 
15379 		toh = (struct T_opthdr *)optptr;
15380 		toh->level = IPPROTO_IPV6;
15381 		toh->name = IPV6_PKTINFO;
15382 		toh->len = sizeof (*toh) + sizeof (*pkti);
15383 		toh->status = 0;
15384 		optptr += sizeof (*toh);
15385 		pkti = (struct in6_pktinfo *)optptr;
15386 		if (tcp->tcp_ipversion == IPV6_VERSION)
15387 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15388 		else
15389 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15390 			    &pkti->ipi6_addr);
15391 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15392 		optptr += sizeof (*pkti);
15393 		ASSERT(OK_32PTR(optptr));
15394 		/* Save as "last" value */
15395 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15396 	}
15397 	/* If app asked for hoplimit and it has changed ... */
15398 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15399 		toh = (struct T_opthdr *)optptr;
15400 		toh->level = IPPROTO_IPV6;
15401 		toh->name = IPV6_HOPLIMIT;
15402 		toh->len = sizeof (*toh) + sizeof (uint_t);
15403 		toh->status = 0;
15404 		optptr += sizeof (*toh);
15405 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15406 		optptr += sizeof (uint_t);
15407 		ASSERT(OK_32PTR(optptr));
15408 		/* Save as "last" value */
15409 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15410 	}
15411 	/* If app asked for tclass and it has changed ... */
15412 	if (addflag & TCP_IPV6_RECVTCLASS) {
15413 		toh = (struct T_opthdr *)optptr;
15414 		toh->level = IPPROTO_IPV6;
15415 		toh->name = IPV6_TCLASS;
15416 		toh->len = sizeof (*toh) + sizeof (uint_t);
15417 		toh->status = 0;
15418 		optptr += sizeof (*toh);
15419 		*(uint_t *)optptr = ipp->ipp_tclass;
15420 		optptr += sizeof (uint_t);
15421 		ASSERT(OK_32PTR(optptr));
15422 		/* Save as "last" value */
15423 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15424 	}
15425 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15426 		toh = (struct T_opthdr *)optptr;
15427 		toh->level = IPPROTO_IPV6;
15428 		toh->name = IPV6_HOPOPTS;
15429 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15430 		    tcp->tcp_label_len;
15431 		toh->status = 0;
15432 		optptr += sizeof (*toh);
15433 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15434 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15435 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15436 		ASSERT(OK_32PTR(optptr));
15437 		/* Save as last value */
15438 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15439 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15440 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15441 	}
15442 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15443 		toh = (struct T_opthdr *)optptr;
15444 		toh->level = IPPROTO_IPV6;
15445 		toh->name = IPV6_RTHDRDSTOPTS;
15446 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15447 		toh->status = 0;
15448 		optptr += sizeof (*toh);
15449 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15450 		optptr += ipp->ipp_rtdstoptslen;
15451 		ASSERT(OK_32PTR(optptr));
15452 		/* Save as last value */
15453 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15454 		    &tcp->tcp_rtdstoptslen,
15455 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15456 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15457 	}
15458 	if (addflag & TCP_IPV6_RECVRTHDR) {
15459 		toh = (struct T_opthdr *)optptr;
15460 		toh->level = IPPROTO_IPV6;
15461 		toh->name = IPV6_RTHDR;
15462 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15463 		toh->status = 0;
15464 		optptr += sizeof (*toh);
15465 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15466 		optptr += ipp->ipp_rthdrlen;
15467 		ASSERT(OK_32PTR(optptr));
15468 		/* Save as last value */
15469 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15470 		    (ipp->ipp_fields & IPPF_RTHDR),
15471 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15472 	}
15473 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15474 		toh = (struct T_opthdr *)optptr;
15475 		toh->level = IPPROTO_IPV6;
15476 		toh->name = IPV6_DSTOPTS;
15477 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15478 		toh->status = 0;
15479 		optptr += sizeof (*toh);
15480 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15481 		optptr += ipp->ipp_dstoptslen;
15482 		ASSERT(OK_32PTR(optptr));
15483 		/* Save as last value */
15484 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15485 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15486 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15487 	}
15488 	ASSERT(optptr == mp->b_wptr);
15489 	return (mp);
15490 }
15491 
15492 /*
15493  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15494  * messages.
15495  */
15496 void
15497 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15498 {
15499 	uchar_t	*rptr = mp->b_rptr;
15500 	queue_t	*q = tcp->tcp_rq;
15501 	struct T_error_ack *tea;
15502 
15503 	switch (mp->b_datap->db_type) {
15504 	case M_PROTO:
15505 	case M_PCPROTO:
15506 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15507 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15508 			break;
15509 		tea = (struct T_error_ack *)rptr;
15510 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15511 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15512 		    tea->ERROR_prim != T_BIND_REQ);
15513 		switch (tea->PRIM_type) {
15514 		case T_ERROR_ACK:
15515 			if (tcp->tcp_debug) {
15516 				(void) strlog(TCP_MOD_ID, 0, 1,
15517 				    SL_TRACE|SL_ERROR,
15518 				    "tcp_rput_other: case T_ERROR_ACK, "
15519 				    "ERROR_prim == %d",
15520 				    tea->ERROR_prim);
15521 			}
15522 			switch (tea->ERROR_prim) {
15523 			case T_SVR4_OPTMGMT_REQ:
15524 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15525 					/* T_OPTMGMT_REQ generated by TCP */
15526 					printf("T_SVR4_OPTMGMT_REQ failed "
15527 					    "%d/%d - dropped (cnt %d)\n",
15528 					    tea->TLI_error, tea->UNIX_error,
15529 					    tcp->tcp_drop_opt_ack_cnt);
15530 					freemsg(mp);
15531 					tcp->tcp_drop_opt_ack_cnt--;
15532 					return;
15533 				}
15534 				break;
15535 			}
15536 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15537 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15538 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15539 				    "- dropped (cnt %d)\n",
15540 				    tea->TLI_error, tea->UNIX_error,
15541 				    tcp->tcp_drop_opt_ack_cnt);
15542 				freemsg(mp);
15543 				tcp->tcp_drop_opt_ack_cnt--;
15544 				return;
15545 			}
15546 			break;
15547 		case T_OPTMGMT_ACK:
15548 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15549 				/* T_OPTMGMT_REQ generated by TCP */
15550 				freemsg(mp);
15551 				tcp->tcp_drop_opt_ack_cnt--;
15552 				return;
15553 			}
15554 			break;
15555 		default:
15556 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15557 			break;
15558 		}
15559 		break;
15560 	case M_FLUSH:
15561 		if (*rptr & FLUSHR)
15562 			flushq(q, FLUSHDATA);
15563 		break;
15564 	default:
15565 		/* M_CTL will be directly sent to tcp_icmp_error() */
15566 		ASSERT(DB_TYPE(mp) != M_CTL);
15567 		break;
15568 	}
15569 	/*
15570 	 * Make sure we set this bit before sending the ACK for
15571 	 * bind. Otherwise accept could possibly run and free
15572 	 * this tcp struct.
15573 	 */
15574 	ASSERT(q != NULL);
15575 	putnext(q, mp);
15576 }
15577 
15578 /* ARGSUSED */
15579 static void
15580 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15581 {
15582 	conn_t	*connp = (conn_t *)arg;
15583 	tcp_t	*tcp = connp->conn_tcp;
15584 	queue_t	*q = tcp->tcp_rq;
15585 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15586 
15587 	ASSERT(!IPCL_IS_NONSTR(connp));
15588 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15589 	tcp->tcp_rsrv_mp = mp;
15590 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15591 
15592 	TCP_STAT(tcps, tcp_rsrv_calls);
15593 
15594 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15595 		return;
15596 	}
15597 
15598 	if (tcp->tcp_fused) {
15599 		tcp_fuse_backenable(tcp);
15600 		return;
15601 	}
15602 
15603 	if (canputnext(q)) {
15604 		/* Not flow-controlled, open rwnd */
15605 		tcp->tcp_rwnd = q->q_hiwat;
15606 
15607 		/*
15608 		 * Send back a window update immediately if TCP is above
15609 		 * ESTABLISHED state and the increase of the rcv window
15610 		 * that the other side knows is at least 1 MSS after flow
15611 		 * control is lifted.
15612 		 */
15613 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15614 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
15615 			tcp_xmit_ctl(NULL, tcp,
15616 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15617 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15618 		}
15619 	}
15620 }
15621 
15622 /*
15623  * The read side service routine is called mostly when we get back-enabled as a
15624  * result of flow control relief.  Since we don't actually queue anything in
15625  * TCP, we have no data to send out of here.  What we do is clear the receive
15626  * window, and send out a window update.
15627  */
15628 static void
15629 tcp_rsrv(queue_t *q)
15630 {
15631 	conn_t		*connp = Q_TO_CONN(q);
15632 	tcp_t		*tcp = connp->conn_tcp;
15633 	mblk_t		*mp;
15634 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15635 
15636 	/* No code does a putq on the read side */
15637 	ASSERT(q->q_first == NULL);
15638 
15639 	/* Nothing to do for the default queue */
15640 	if (q == tcps->tcps_g_q) {
15641 		return;
15642 	}
15643 
15644 	/*
15645 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15646 	 * been run.  So just return.
15647 	 */
15648 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15649 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15650 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15651 		return;
15652 	}
15653 	tcp->tcp_rsrv_mp = NULL;
15654 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15655 
15656 	CONN_INC_REF(connp);
15657 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15658 	    SQ_PROCESS, SQTAG_TCP_RSRV);
15659 }
15660 
15661 /*
15662  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15663  * We do not allow the receive window to shrink.  After setting rwnd,
15664  * set the flow control hiwat of the stream.
15665  *
15666  * This function is called in 2 cases:
15667  *
15668  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15669  *    connection (passive open) and in tcp_rput_data() for active connect.
15670  *    This is called after tcp_mss_set() when the desired MSS value is known.
15671  *    This makes sure that our window size is a mutiple of the other side's
15672  *    MSS.
15673  * 2) Handling SO_RCVBUF option.
15674  *
15675  * It is ASSUMED that the requested size is a multiple of the current MSS.
15676  *
15677  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15678  * user requests so.
15679  */
15680 static int
15681 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15682 {
15683 	uint32_t	mss = tcp->tcp_mss;
15684 	uint32_t	old_max_rwnd;
15685 	uint32_t	max_transmittable_rwnd;
15686 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15687 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15688 
15689 	if (tcp->tcp_fused) {
15690 		size_t sth_hiwat;
15691 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15692 
15693 		ASSERT(peer_tcp != NULL);
15694 		/*
15695 		 * Record the stream head's high water mark for
15696 		 * this endpoint; this is used for flow-control
15697 		 * purposes in tcp_fuse_output().
15698 		 */
15699 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15700 		if (!tcp_detached) {
15701 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15702 			    sth_hiwat);
15703 			if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
15704 				conn_t *connp = tcp->tcp_connp;
15705 				struct sock_proto_props sopp;
15706 
15707 				sopp.sopp_flags = SOCKOPT_RCVTHRESH;
15708 				sopp.sopp_rcvthresh = sth_hiwat >> 3;
15709 
15710 				(*connp->conn_upcalls->su_set_proto_props)
15711 				    (connp->conn_upper_handle, &sopp);
15712 			}
15713 		}
15714 
15715 		/*
15716 		 * In the fusion case, the maxpsz stream head value of
15717 		 * our peer is set according to its send buffer size
15718 		 * and our receive buffer size; since the latter may
15719 		 * have changed we need to update the peer's maxpsz.
15720 		 */
15721 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15722 		return (rwnd);
15723 	}
15724 
15725 	if (tcp_detached) {
15726 		old_max_rwnd = tcp->tcp_rwnd;
15727 	} else {
15728 		old_max_rwnd = tcp->tcp_recv_hiwater;
15729 	}
15730 
15731 	/*
15732 	 * Insist on a receive window that is at least
15733 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15734 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15735 	 * and delayed acknowledgement.
15736 	 */
15737 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
15738 
15739 	/*
15740 	 * If window size info has already been exchanged, TCP should not
15741 	 * shrink the window.  Shrinking window is doable if done carefully.
15742 	 * We may add that support later.  But so far there is not a real
15743 	 * need to do that.
15744 	 */
15745 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15746 		/* MSS may have changed, do a round up again. */
15747 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15748 	}
15749 
15750 	/*
15751 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15752 	 * can be applied even before the window scale option is decided.
15753 	 */
15754 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15755 	if (rwnd > max_transmittable_rwnd) {
15756 		rwnd = max_transmittable_rwnd -
15757 		    (max_transmittable_rwnd % mss);
15758 		if (rwnd < mss)
15759 			rwnd = max_transmittable_rwnd;
15760 		/*
15761 		 * If we're over the limit we may have to back down tcp_rwnd.
15762 		 * The increment below won't work for us. So we set all three
15763 		 * here and the increment below will have no effect.
15764 		 */
15765 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15766 	}
15767 	if (tcp->tcp_localnet) {
15768 		tcp->tcp_rack_abs_max =
15769 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
15770 	} else {
15771 		/*
15772 		 * For a remote host on a different subnet (through a router),
15773 		 * we ack every other packet to be conforming to RFC1122.
15774 		 * tcp_deferred_acks_max is default to 2.
15775 		 */
15776 		tcp->tcp_rack_abs_max =
15777 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
15778 	}
15779 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15780 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15781 	else
15782 		tcp->tcp_rack_cur_max = 0;
15783 	/*
15784 	 * Increment the current rwnd by the amount the maximum grew (we
15785 	 * can not overwrite it since we might be in the middle of a
15786 	 * connection.)
15787 	 */
15788 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15789 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15790 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15791 		tcp->tcp_cwnd_max = rwnd;
15792 
15793 	if (tcp_detached)
15794 		return (rwnd);
15795 	/*
15796 	 * We set the maximum receive window into rq->q_hiwat if it is
15797 	 * a STREAMS socket.
15798 	 * This is not actually used for flow control.
15799 	 */
15800 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
15801 		tcp->tcp_rq->q_hiwat = rwnd;
15802 	tcp->tcp_recv_hiwater = rwnd;
15803 	/*
15804 	 * Set the STREAM head high water mark. This doesn't have to be
15805 	 * here, since we are simply using default values, but we would
15806 	 * prefer to choose these values algorithmically, with a likely
15807 	 * relationship to rwnd.
15808 	 */
15809 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15810 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
15811 	return (rwnd);
15812 }
15813 
15814 /*
15815  * Return SNMP stuff in buffer in mpdata.
15816  */
15817 mblk_t *
15818 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15819 {
15820 	mblk_t			*mpdata;
15821 	mblk_t			*mp_conn_ctl = NULL;
15822 	mblk_t			*mp_conn_tail;
15823 	mblk_t			*mp_attr_ctl = NULL;
15824 	mblk_t			*mp_attr_tail;
15825 	mblk_t			*mp6_conn_ctl = NULL;
15826 	mblk_t			*mp6_conn_tail;
15827 	mblk_t			*mp6_attr_ctl = NULL;
15828 	mblk_t			*mp6_attr_tail;
15829 	struct opthdr		*optp;
15830 	mib2_tcpConnEntry_t	tce;
15831 	mib2_tcp6ConnEntry_t	tce6;
15832 	mib2_transportMLPEntry_t mlp;
15833 	connf_t			*connfp;
15834 	int			i;
15835 	boolean_t 		ispriv;
15836 	zoneid_t 		zoneid;
15837 	int			v4_conn_idx;
15838 	int			v6_conn_idx;
15839 	conn_t			*connp = Q_TO_CONN(q);
15840 	tcp_stack_t		*tcps;
15841 	ip_stack_t		*ipst;
15842 	mblk_t			*mp2ctl;
15843 
15844 	/*
15845 	 * make a copy of the original message
15846 	 */
15847 	mp2ctl = copymsg(mpctl);
15848 
15849 	if (mpctl == NULL ||
15850 	    (mpdata = mpctl->b_cont) == NULL ||
15851 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15852 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
15853 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
15854 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
15855 		freemsg(mp_conn_ctl);
15856 		freemsg(mp_attr_ctl);
15857 		freemsg(mp6_conn_ctl);
15858 		freemsg(mp6_attr_ctl);
15859 		freemsg(mpctl);
15860 		freemsg(mp2ctl);
15861 		return (NULL);
15862 	}
15863 
15864 	ipst = connp->conn_netstack->netstack_ip;
15865 	tcps = connp->conn_netstack->netstack_tcp;
15866 
15867 	/* build table of connections -- need count in fixed part */
15868 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
15869 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
15870 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
15871 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
15872 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
15873 
15874 	ispriv =
15875 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15876 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15877 
15878 	v4_conn_idx = v6_conn_idx = 0;
15879 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
15880 
15881 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15882 		ipst = tcps->tcps_netstack->netstack_ip;
15883 
15884 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
15885 
15886 		connp = NULL;
15887 
15888 		while ((connp =
15889 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15890 			tcp_t *tcp;
15891 			boolean_t needattr;
15892 
15893 			if (connp->conn_zoneid != zoneid)
15894 				continue;	/* not in this zone */
15895 
15896 			tcp = connp->conn_tcp;
15897 			UPDATE_MIB(&tcps->tcps_mib,
15898 			    tcpHCInSegs, tcp->tcp_ibsegs);
15899 			tcp->tcp_ibsegs = 0;
15900 			UPDATE_MIB(&tcps->tcps_mib,
15901 			    tcpHCOutSegs, tcp->tcp_obsegs);
15902 			tcp->tcp_obsegs = 0;
15903 
15904 			tce6.tcp6ConnState = tce.tcpConnState =
15905 			    tcp_snmp_state(tcp);
15906 			if (tce.tcpConnState == MIB2_TCP_established ||
15907 			    tce.tcpConnState == MIB2_TCP_closeWait)
15908 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
15909 
15910 			needattr = B_FALSE;
15911 			bzero(&mlp, sizeof (mlp));
15912 			if (connp->conn_mlp_type != mlptSingle) {
15913 				if (connp->conn_mlp_type == mlptShared ||
15914 				    connp->conn_mlp_type == mlptBoth)
15915 					mlp.tme_flags |= MIB2_TMEF_SHARED;
15916 				if (connp->conn_mlp_type == mlptPrivate ||
15917 				    connp->conn_mlp_type == mlptBoth)
15918 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
15919 				needattr = B_TRUE;
15920 			}
15921 			if (connp->conn_anon_mlp) {
15922 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
15923 				needattr = B_TRUE;
15924 			}
15925 			if (connp->conn_mac_exempt) {
15926 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
15927 				needattr = B_TRUE;
15928 			}
15929 			if (connp->conn_fully_bound &&
15930 			    connp->conn_effective_cred != NULL) {
15931 				ts_label_t *tsl;
15932 
15933 				tsl = crgetlabel(connp->conn_effective_cred);
15934 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
15935 				mlp.tme_doi = label2doi(tsl);
15936 				mlp.tme_label = *label2bslabel(tsl);
15937 				needattr = B_TRUE;
15938 			}
15939 
15940 			/* Create a message to report on IPv6 entries */
15941 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15942 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15943 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15944 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15945 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15946 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15947 			/* Don't want just anybody seeing these... */
15948 			if (ispriv) {
15949 				tce6.tcp6ConnEntryInfo.ce_snxt =
15950 				    tcp->tcp_snxt;
15951 				tce6.tcp6ConnEntryInfo.ce_suna =
15952 				    tcp->tcp_suna;
15953 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15954 				    tcp->tcp_rnxt;
15955 				tce6.tcp6ConnEntryInfo.ce_rack =
15956 				    tcp->tcp_rack;
15957 			} else {
15958 				/*
15959 				 * Netstat, unfortunately, uses this to
15960 				 * get send/receive queue sizes.  How to fix?
15961 				 * Why not compute the difference only?
15962 				 */
15963 				tce6.tcp6ConnEntryInfo.ce_snxt =
15964 				    tcp->tcp_snxt - tcp->tcp_suna;
15965 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
15966 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15967 				    tcp->tcp_rnxt - tcp->tcp_rack;
15968 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
15969 			}
15970 
15971 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15972 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15973 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
15974 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
15975 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
15976 
15977 			tce6.tcp6ConnCreationProcess =
15978 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
15979 			    tcp->tcp_cpid;
15980 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
15981 
15982 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
15983 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
15984 
15985 			mlp.tme_connidx = v6_conn_idx++;
15986 			if (needattr)
15987 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
15988 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
15989 			}
15990 			/*
15991 			 * Create an IPv4 table entry for IPv4 entries and also
15992 			 * for IPv6 entries which are bound to in6addr_any
15993 			 * but don't have IPV6_V6ONLY set.
15994 			 * (i.e. anything an IPv4 peer could connect to)
15995 			 */
15996 			if (tcp->tcp_ipversion == IPV4_VERSION ||
15997 			    (tcp->tcp_state <= TCPS_LISTEN &&
15998 			    !tcp->tcp_connp->conn_ipv6_v6only &&
15999 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16000 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16001 					tce.tcpConnRemAddress = INADDR_ANY;
16002 					tce.tcpConnLocalAddress = INADDR_ANY;
16003 				} else {
16004 					tce.tcpConnRemAddress =
16005 					    tcp->tcp_remote;
16006 					tce.tcpConnLocalAddress =
16007 					    tcp->tcp_ip_src;
16008 				}
16009 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16010 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16011 				/* Don't want just anybody seeing these... */
16012 				if (ispriv) {
16013 					tce.tcpConnEntryInfo.ce_snxt =
16014 					    tcp->tcp_snxt;
16015 					tce.tcpConnEntryInfo.ce_suna =
16016 					    tcp->tcp_suna;
16017 					tce.tcpConnEntryInfo.ce_rnxt =
16018 					    tcp->tcp_rnxt;
16019 					tce.tcpConnEntryInfo.ce_rack =
16020 					    tcp->tcp_rack;
16021 				} else {
16022 					/*
16023 					 * Netstat, unfortunately, uses this to
16024 					 * get send/receive queue sizes.  How
16025 					 * to fix?
16026 					 * Why not compute the difference only?
16027 					 */
16028 					tce.tcpConnEntryInfo.ce_snxt =
16029 					    tcp->tcp_snxt - tcp->tcp_suna;
16030 					tce.tcpConnEntryInfo.ce_suna = 0;
16031 					tce.tcpConnEntryInfo.ce_rnxt =
16032 					    tcp->tcp_rnxt - tcp->tcp_rack;
16033 					tce.tcpConnEntryInfo.ce_rack = 0;
16034 				}
16035 
16036 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16037 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16038 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16039 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16040 				tce.tcpConnEntryInfo.ce_state =
16041 				    tcp->tcp_state;
16042 
16043 				tce.tcpConnCreationProcess =
16044 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16045 				    tcp->tcp_cpid;
16046 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16047 
16048 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16049 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16050 
16051 				mlp.tme_connidx = v4_conn_idx++;
16052 				if (needattr)
16053 					(void) snmp_append_data2(
16054 					    mp_attr_ctl->b_cont,
16055 					    &mp_attr_tail, (char *)&mlp,
16056 					    sizeof (mlp));
16057 			}
16058 		}
16059 	}
16060 
16061 	/* fixed length structure for IPv4 and IPv6 counters */
16062 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16063 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16064 	    sizeof (mib2_tcp6ConnEntry_t));
16065 	/* synchronize 32- and 64-bit counters */
16066 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16067 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16068 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16069 	optp->level = MIB2_TCP;
16070 	optp->name = 0;
16071 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16072 	    sizeof (tcps->tcps_mib));
16073 	optp->len = msgdsize(mpdata);
16074 	qreply(q, mpctl);
16075 
16076 	/* table of connections... */
16077 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16078 	    sizeof (struct T_optmgmt_ack)];
16079 	optp->level = MIB2_TCP;
16080 	optp->name = MIB2_TCP_CONN;
16081 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16082 	qreply(q, mp_conn_ctl);
16083 
16084 	/* table of MLP attributes... */
16085 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16086 	    sizeof (struct T_optmgmt_ack)];
16087 	optp->level = MIB2_TCP;
16088 	optp->name = EXPER_XPORT_MLP;
16089 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16090 	if (optp->len == 0)
16091 		freemsg(mp_attr_ctl);
16092 	else
16093 		qreply(q, mp_attr_ctl);
16094 
16095 	/* table of IPv6 connections... */
16096 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16097 	    sizeof (struct T_optmgmt_ack)];
16098 	optp->level = MIB2_TCP6;
16099 	optp->name = MIB2_TCP6_CONN;
16100 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16101 	qreply(q, mp6_conn_ctl);
16102 
16103 	/* table of IPv6 MLP attributes... */
16104 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16105 	    sizeof (struct T_optmgmt_ack)];
16106 	optp->level = MIB2_TCP6;
16107 	optp->name = EXPER_XPORT_MLP;
16108 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16109 	if (optp->len == 0)
16110 		freemsg(mp6_attr_ctl);
16111 	else
16112 		qreply(q, mp6_attr_ctl);
16113 	return (mp2ctl);
16114 }
16115 
16116 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16117 /* ARGSUSED */
16118 int
16119 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16120 {
16121 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16122 
16123 	switch (level) {
16124 	case MIB2_TCP:
16125 		switch (name) {
16126 		case 13:
16127 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16128 				return (0);
16129 			/* TODO: delete entry defined by tce */
16130 			return (1);
16131 		default:
16132 			return (0);
16133 		}
16134 	default:
16135 		return (1);
16136 	}
16137 }
16138 
16139 /* Translate TCP state to MIB2 TCP state. */
16140 static int
16141 tcp_snmp_state(tcp_t *tcp)
16142 {
16143 	if (tcp == NULL)
16144 		return (0);
16145 
16146 	switch (tcp->tcp_state) {
16147 	case TCPS_CLOSED:
16148 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16149 	case TCPS_BOUND:
16150 		return (MIB2_TCP_closed);
16151 	case TCPS_LISTEN:
16152 		return (MIB2_TCP_listen);
16153 	case TCPS_SYN_SENT:
16154 		return (MIB2_TCP_synSent);
16155 	case TCPS_SYN_RCVD:
16156 		return (MIB2_TCP_synReceived);
16157 	case TCPS_ESTABLISHED:
16158 		return (MIB2_TCP_established);
16159 	case TCPS_CLOSE_WAIT:
16160 		return (MIB2_TCP_closeWait);
16161 	case TCPS_FIN_WAIT_1:
16162 		return (MIB2_TCP_finWait1);
16163 	case TCPS_CLOSING:
16164 		return (MIB2_TCP_closing);
16165 	case TCPS_LAST_ACK:
16166 		return (MIB2_TCP_lastAck);
16167 	case TCPS_FIN_WAIT_2:
16168 		return (MIB2_TCP_finWait2);
16169 	case TCPS_TIME_WAIT:
16170 		return (MIB2_TCP_timeWait);
16171 	default:
16172 		return (0);
16173 	}
16174 }
16175 
16176 /*
16177  * tcp_timer is the timer service routine.  It handles the retransmission,
16178  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16179  * from the state of the tcp instance what kind of action needs to be done
16180  * at the time it is called.
16181  */
16182 static void
16183 tcp_timer(void *arg)
16184 {
16185 	mblk_t		*mp;
16186 	clock_t		first_threshold;
16187 	clock_t		second_threshold;
16188 	clock_t		ms;
16189 	uint32_t	mss;
16190 	conn_t		*connp = (conn_t *)arg;
16191 	tcp_t		*tcp = connp->conn_tcp;
16192 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16193 
16194 	tcp->tcp_timer_tid = 0;
16195 
16196 	if (tcp->tcp_fused)
16197 		return;
16198 
16199 	first_threshold =  tcp->tcp_first_timer_threshold;
16200 	second_threshold = tcp->tcp_second_timer_threshold;
16201 	switch (tcp->tcp_state) {
16202 	case TCPS_IDLE:
16203 	case TCPS_BOUND:
16204 	case TCPS_LISTEN:
16205 		return;
16206 	case TCPS_SYN_RCVD: {
16207 		tcp_t	*listener = tcp->tcp_listener;
16208 
16209 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16210 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16211 			/* it's our first timeout */
16212 			tcp->tcp_syn_rcvd_timeout = 1;
16213 			mutex_enter(&listener->tcp_eager_lock);
16214 			listener->tcp_syn_rcvd_timeout++;
16215 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16216 				/*
16217 				 * Make this eager available for drop if we
16218 				 * need to drop one to accomodate a new
16219 				 * incoming SYN request.
16220 				 */
16221 				MAKE_DROPPABLE(listener, tcp);
16222 			}
16223 			if (!listener->tcp_syn_defense &&
16224 			    (listener->tcp_syn_rcvd_timeout >
16225 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16226 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16227 				/* We may be under attack. Put on a defense. */
16228 				listener->tcp_syn_defense = B_TRUE;
16229 				cmn_err(CE_WARN, "High TCP connect timeout "
16230 				    "rate! System (port %d) may be under a "
16231 				    "SYN flood attack!",
16232 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16233 
16234 				listener->tcp_ip_addr_cache = kmem_zalloc(
16235 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16236 				    KM_NOSLEEP);
16237 			}
16238 			mutex_exit(&listener->tcp_eager_lock);
16239 		} else if (listener != NULL) {
16240 			mutex_enter(&listener->tcp_eager_lock);
16241 			tcp->tcp_syn_rcvd_timeout++;
16242 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16243 			    !tcp->tcp_closemp_used) {
16244 				/*
16245 				 * This is our second timeout. Put the tcp in
16246 				 * the list of droppable eagers to allow it to
16247 				 * be dropped, if needed. We don't check
16248 				 * whether tcp_dontdrop is set or not to
16249 				 * protect ourselve from a SYN attack where a
16250 				 * remote host can spoof itself as one of the
16251 				 * good IP source and continue to hold
16252 				 * resources too long.
16253 				 */
16254 				MAKE_DROPPABLE(listener, tcp);
16255 			}
16256 			mutex_exit(&listener->tcp_eager_lock);
16257 		}
16258 	}
16259 		/* FALLTHRU */
16260 	case TCPS_SYN_SENT:
16261 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16262 		second_threshold = tcp->tcp_second_ctimer_threshold;
16263 		break;
16264 	case TCPS_ESTABLISHED:
16265 	case TCPS_FIN_WAIT_1:
16266 	case TCPS_CLOSING:
16267 	case TCPS_CLOSE_WAIT:
16268 	case TCPS_LAST_ACK:
16269 		/* If we have data to rexmit */
16270 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16271 			clock_t	time_to_wait;
16272 
16273 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16274 			if (!tcp->tcp_xmit_head)
16275 				break;
16276 			time_to_wait = lbolt -
16277 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16278 			time_to_wait = tcp->tcp_rto -
16279 			    TICK_TO_MSEC(time_to_wait);
16280 			/*
16281 			 * If the timer fires too early, 1 clock tick earlier,
16282 			 * restart the timer.
16283 			 */
16284 			if (time_to_wait > msec_per_tick) {
16285 				TCP_STAT(tcps, tcp_timer_fire_early);
16286 				TCP_TIMER_RESTART(tcp, time_to_wait);
16287 				return;
16288 			}
16289 			/*
16290 			 * When we probe zero windows, we force the swnd open.
16291 			 * If our peer acks with a closed window swnd will be
16292 			 * set to zero by tcp_rput(). As long as we are
16293 			 * receiving acks tcp_rput will
16294 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16295 			 * first and second interval actions.  NOTE: the timer
16296 			 * interval is allowed to continue its exponential
16297 			 * backoff.
16298 			 */
16299 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16300 				if (tcp->tcp_debug) {
16301 					(void) strlog(TCP_MOD_ID, 0, 1,
16302 					    SL_TRACE, "tcp_timer: zero win");
16303 				}
16304 			} else {
16305 				/*
16306 				 * After retransmission, we need to do
16307 				 * slow start.  Set the ssthresh to one
16308 				 * half of current effective window and
16309 				 * cwnd to one MSS.  Also reset
16310 				 * tcp_cwnd_cnt.
16311 				 *
16312 				 * Note that if tcp_ssthresh is reduced because
16313 				 * of ECN, do not reduce it again unless it is
16314 				 * already one window of data away (tcp_cwr
16315 				 * should then be cleared) or this is a
16316 				 * timeout for a retransmitted segment.
16317 				 */
16318 				uint32_t npkt;
16319 
16320 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16321 					npkt = ((tcp->tcp_timer_backoff ?
16322 					    tcp->tcp_cwnd_ssthresh :
16323 					    tcp->tcp_snxt -
16324 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16325 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16326 					    tcp->tcp_mss;
16327 				}
16328 				tcp->tcp_cwnd = tcp->tcp_mss;
16329 				tcp->tcp_cwnd_cnt = 0;
16330 				if (tcp->tcp_ecn_ok) {
16331 					tcp->tcp_cwr = B_TRUE;
16332 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16333 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16334 				}
16335 			}
16336 			break;
16337 		}
16338 		/*
16339 		 * We have something to send yet we cannot send.  The
16340 		 * reason can be:
16341 		 *
16342 		 * 1. Zero send window: we need to do zero window probe.
16343 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16344 		 * segments.
16345 		 * 3. SWS avoidance: receiver may have shrunk window,
16346 		 * reset our knowledge.
16347 		 *
16348 		 * Note that condition 2 can happen with either 1 or
16349 		 * 3.  But 1 and 3 are exclusive.
16350 		 */
16351 		if (tcp->tcp_unsent != 0) {
16352 			if (tcp->tcp_cwnd == 0) {
16353 				/*
16354 				 * Set tcp_cwnd to 1 MSS so that a
16355 				 * new segment can be sent out.  We
16356 				 * are "clocking out" new data when
16357 				 * the network is really congested.
16358 				 */
16359 				ASSERT(tcp->tcp_ecn_ok);
16360 				tcp->tcp_cwnd = tcp->tcp_mss;
16361 			}
16362 			if (tcp->tcp_swnd == 0) {
16363 				/* Extend window for zero window probe */
16364 				tcp->tcp_swnd++;
16365 				tcp->tcp_zero_win_probe = B_TRUE;
16366 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
16367 			} else {
16368 				/*
16369 				 * Handle timeout from sender SWS avoidance.
16370 				 * Reset our knowledge of the max send window
16371 				 * since the receiver might have reduced its
16372 				 * receive buffer.  Avoid setting tcp_max_swnd
16373 				 * to one since that will essentially disable
16374 				 * the SWS checks.
16375 				 *
16376 				 * Note that since we don't have a SWS
16377 				 * state variable, if the timeout is set
16378 				 * for ECN but not for SWS, this
16379 				 * code will also be executed.  This is
16380 				 * fine as tcp_max_swnd is updated
16381 				 * constantly and it will not affect
16382 				 * anything.
16383 				 */
16384 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16385 			}
16386 			tcp_wput_data(tcp, NULL, B_FALSE);
16387 			return;
16388 		}
16389 		/* Is there a FIN that needs to be to re retransmitted? */
16390 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16391 		    !tcp->tcp_fin_acked)
16392 			break;
16393 		/* Nothing to do, return without restarting timer. */
16394 		TCP_STAT(tcps, tcp_timer_fire_miss);
16395 		return;
16396 	case TCPS_FIN_WAIT_2:
16397 		/*
16398 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16399 		 * We waited some time for for peer's FIN, but it hasn't
16400 		 * arrived.  We flush the connection now to avoid
16401 		 * case where the peer has rebooted.
16402 		 */
16403 		if (TCP_IS_DETACHED(tcp)) {
16404 			(void) tcp_clean_death(tcp, 0, 23);
16405 		} else {
16406 			TCP_TIMER_RESTART(tcp,
16407 			    tcps->tcps_fin_wait_2_flush_interval);
16408 		}
16409 		return;
16410 	case TCPS_TIME_WAIT:
16411 		(void) tcp_clean_death(tcp, 0, 24);
16412 		return;
16413 	default:
16414 		if (tcp->tcp_debug) {
16415 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16416 			    "tcp_timer: strange state (%d) %s",
16417 			    tcp->tcp_state, tcp_display(tcp, NULL,
16418 			    DISP_PORT_ONLY));
16419 		}
16420 		return;
16421 	}
16422 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16423 		/*
16424 		 * For zero window probe, we need to send indefinitely,
16425 		 * unless we have not heard from the other side for some
16426 		 * time...
16427 		 */
16428 		if ((tcp->tcp_zero_win_probe == 0) ||
16429 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16430 		    second_threshold)) {
16431 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
16432 			/*
16433 			 * If TCP is in SYN_RCVD state, send back a
16434 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16435 			 * should be zero in TCPS_SYN_RCVD state.
16436 			 */
16437 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16438 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16439 				    "in SYN_RCVD",
16440 				    tcp, tcp->tcp_snxt,
16441 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16442 			}
16443 			(void) tcp_clean_death(tcp,
16444 			    tcp->tcp_client_errno ?
16445 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16446 			return;
16447 		} else {
16448 			/*
16449 			 * Set tcp_ms_we_have_waited to second_threshold
16450 			 * so that in next timeout, we will do the above
16451 			 * check (lbolt - tcp_last_recv_time).  This is
16452 			 * also to avoid overflow.
16453 			 *
16454 			 * We don't need to decrement tcp_timer_backoff
16455 			 * to avoid overflow because it will be decremented
16456 			 * later if new timeout value is greater than
16457 			 * tcp_rexmit_interval_max.  In the case when
16458 			 * tcp_rexmit_interval_max is greater than
16459 			 * second_threshold, it means that we will wait
16460 			 * longer than second_threshold to send the next
16461 			 * window probe.
16462 			 */
16463 			tcp->tcp_ms_we_have_waited = second_threshold;
16464 		}
16465 	} else if (ms > first_threshold) {
16466 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16467 		    tcp->tcp_xmit_head != NULL) {
16468 			tcp->tcp_xmit_head =
16469 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16470 		}
16471 		/*
16472 		 * We have been retransmitting for too long...  The RTT
16473 		 * we calculated is probably incorrect.  Reinitialize it.
16474 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16475 		 * tcp_rtt_update so that we won't accidentally cache a
16476 		 * bad value.  But only do this if this is not a zero
16477 		 * window probe.
16478 		 */
16479 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16480 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16481 			    (tcp->tcp_rtt_sa >> 5);
16482 			tcp->tcp_rtt_sa = 0;
16483 			tcp_ip_notify(tcp);
16484 			tcp->tcp_rtt_update = 0;
16485 		}
16486 	}
16487 	tcp->tcp_timer_backoff++;
16488 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16489 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16490 	    tcps->tcps_rexmit_interval_min) {
16491 		/*
16492 		 * This means the original RTO is tcp_rexmit_interval_min.
16493 		 * So we will use tcp_rexmit_interval_min as the RTO value
16494 		 * and do the backoff.
16495 		 */
16496 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
16497 	} else {
16498 		ms <<= tcp->tcp_timer_backoff;
16499 	}
16500 	if (ms > tcps->tcps_rexmit_interval_max) {
16501 		ms = tcps->tcps_rexmit_interval_max;
16502 		/*
16503 		 * ms is at max, decrement tcp_timer_backoff to avoid
16504 		 * overflow.
16505 		 */
16506 		tcp->tcp_timer_backoff--;
16507 	}
16508 	tcp->tcp_ms_we_have_waited += ms;
16509 	if (tcp->tcp_zero_win_probe == 0) {
16510 		tcp->tcp_rto = ms;
16511 	}
16512 	TCP_TIMER_RESTART(tcp, ms);
16513 	/*
16514 	 * This is after a timeout and tcp_rto is backed off.  Set
16515 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16516 	 * restart the timer with a correct value.
16517 	 */
16518 	tcp->tcp_set_timer = 1;
16519 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16520 	if (mss > tcp->tcp_mss)
16521 		mss = tcp->tcp_mss;
16522 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16523 		mss = tcp->tcp_swnd;
16524 
16525 	if ((mp = tcp->tcp_xmit_head) != NULL)
16526 		mp->b_prev = (mblk_t *)lbolt;
16527 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16528 	    B_TRUE);
16529 
16530 	/*
16531 	 * When slow start after retransmission begins, start with
16532 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16533 	 * start phase.  tcp_snd_burst controls how many segments
16534 	 * can be sent because of an ack.
16535 	 */
16536 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16537 	tcp->tcp_snd_burst = TCP_CWND_SS;
16538 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16539 	    (tcp->tcp_unsent == 0)) {
16540 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16541 	} else {
16542 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16543 	}
16544 	tcp->tcp_rexmit = B_TRUE;
16545 	tcp->tcp_dupack_cnt = 0;
16546 
16547 	/*
16548 	 * Remove all rexmit SACK blk to start from fresh.
16549 	 */
16550 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16551 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16552 		tcp->tcp_num_notsack_blk = 0;
16553 		tcp->tcp_cnt_notsack_list = 0;
16554 	}
16555 	if (mp == NULL) {
16556 		return;
16557 	}
16558 	/*
16559 	 * Attach credentials to retransmitted initial SYNs.
16560 	 * In theory we should use the credentials from the connect()
16561 	 * call to ensure that getpeerucred() on the peer will be correct.
16562 	 * But we assume that SYN's are not dropped for loopback connections.
16563 	 */
16564 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16565 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp), tcp->tcp_cpid);
16566 	}
16567 
16568 	tcp->tcp_csuna = tcp->tcp_snxt;
16569 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
16570 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
16571 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16572 
16573 }
16574 
16575 static int
16576 tcp_do_unbind(conn_t *connp)
16577 {
16578 	tcp_t *tcp = connp->conn_tcp;
16579 	int error = 0;
16580 
16581 	switch (tcp->tcp_state) {
16582 	case TCPS_BOUND:
16583 	case TCPS_LISTEN:
16584 		break;
16585 	default:
16586 		return (-TOUTSTATE);
16587 	}
16588 
16589 	/*
16590 	 * Need to clean up all the eagers since after the unbind, segments
16591 	 * will no longer be delivered to this listener stream.
16592 	 */
16593 	mutex_enter(&tcp->tcp_eager_lock);
16594 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16595 		tcp_eager_cleanup(tcp, 0);
16596 	}
16597 	mutex_exit(&tcp->tcp_eager_lock);
16598 
16599 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16600 		tcp->tcp_ipha->ipha_src = 0;
16601 	} else {
16602 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16603 	}
16604 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16605 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16606 	tcp_bind_hash_remove(tcp);
16607 	tcp->tcp_state = TCPS_IDLE;
16608 	tcp->tcp_mdt = B_FALSE;
16609 
16610 	connp = tcp->tcp_connp;
16611 	connp->conn_mdt_ok = B_FALSE;
16612 	ipcl_hash_remove(connp);
16613 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16614 
16615 	return (error);
16616 }
16617 
16618 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16619 static void
16620 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
16621 {
16622 	int error = tcp_do_unbind(tcp->tcp_connp);
16623 
16624 	if (error > 0) {
16625 		tcp_err_ack(tcp, mp, TSYSERR, error);
16626 	} else if (error < 0) {
16627 		tcp_err_ack(tcp, mp, -error, 0);
16628 	} else {
16629 		/* Send M_FLUSH according to TPI */
16630 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16631 
16632 		mp = mi_tpi_ok_ack_alloc(mp);
16633 		putnext(tcp->tcp_rq, mp);
16634 	}
16635 }
16636 
16637 /*
16638  * Don't let port fall into the privileged range.
16639  * Since the extra privileged ports can be arbitrary we also
16640  * ensure that we exclude those from consideration.
16641  * tcp_g_epriv_ports is not sorted thus we loop over it until
16642  * there are no changes.
16643  *
16644  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16645  * but instead the code relies on:
16646  * - the fact that the address of the array and its size never changes
16647  * - the atomic assignment of the elements of the array
16648  *
16649  * Returns 0 if there are no more ports available.
16650  *
16651  * TS note: skip multilevel ports.
16652  */
16653 static in_port_t
16654 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16655 {
16656 	int i;
16657 	boolean_t restart = B_FALSE;
16658 	tcp_stack_t *tcps = tcp->tcp_tcps;
16659 
16660 	if (random && tcp_random_anon_port != 0) {
16661 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16662 		    sizeof (in_port_t));
16663 		/*
16664 		 * Unless changed by a sys admin, the smallest anon port
16665 		 * is 32768 and the largest anon port is 65535.  It is
16666 		 * very likely (50%) for the random port to be smaller
16667 		 * than the smallest anon port.  When that happens,
16668 		 * add port % (anon port range) to the smallest anon
16669 		 * port to get the random port.  It should fall into the
16670 		 * valid anon port range.
16671 		 */
16672 		if (port < tcps->tcps_smallest_anon_port) {
16673 			port = tcps->tcps_smallest_anon_port +
16674 			    port % (tcps->tcps_largest_anon_port -
16675 			    tcps->tcps_smallest_anon_port);
16676 		}
16677 	}
16678 
16679 retry:
16680 	if (port < tcps->tcps_smallest_anon_port)
16681 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16682 
16683 	if (port > tcps->tcps_largest_anon_port) {
16684 		if (restart)
16685 			return (0);
16686 		restart = B_TRUE;
16687 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16688 	}
16689 
16690 	if (port < tcps->tcps_smallest_nonpriv_port)
16691 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
16692 
16693 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
16694 		if (port == tcps->tcps_g_epriv_ports[i]) {
16695 			port++;
16696 			/*
16697 			 * Make sure whether the port is in the
16698 			 * valid range.
16699 			 */
16700 			goto retry;
16701 		}
16702 	}
16703 	if (is_system_labeled() &&
16704 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
16705 	    IPPROTO_TCP, B_TRUE)) != 0) {
16706 		port = i;
16707 		goto retry;
16708 	}
16709 	return (port);
16710 }
16711 
16712 /*
16713  * Return the next anonymous port in the privileged port range for
16714  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16715  * downwards.  This is the same behavior as documented in the userland
16716  * library call rresvport(3N).
16717  *
16718  * TS note: skip multilevel ports.
16719  */
16720 static in_port_t
16721 tcp_get_next_priv_port(const tcp_t *tcp)
16722 {
16723 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16724 	in_port_t nextport;
16725 	boolean_t restart = B_FALSE;
16726 	tcp_stack_t *tcps = tcp->tcp_tcps;
16727 retry:
16728 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
16729 	    next_priv_port >= IPPORT_RESERVED) {
16730 		next_priv_port = IPPORT_RESERVED - 1;
16731 		if (restart)
16732 			return (0);
16733 		restart = B_TRUE;
16734 	}
16735 	if (is_system_labeled() &&
16736 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
16737 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
16738 		next_priv_port = nextport;
16739 		goto retry;
16740 	}
16741 	return (next_priv_port--);
16742 }
16743 
16744 /* The write side r/w procedure. */
16745 
16746 #if CCS_STATS
16747 struct {
16748 	struct {
16749 		int64_t count, bytes;
16750 	} tot, hit;
16751 } wrw_stats;
16752 #endif
16753 
16754 /*
16755  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16756  * messages.
16757  */
16758 /* ARGSUSED */
16759 static void
16760 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16761 {
16762 	conn_t	*connp = (conn_t *)arg;
16763 	tcp_t	*tcp = connp->conn_tcp;
16764 	queue_t	*q = tcp->tcp_wq;
16765 
16766 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16767 	/*
16768 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16769 	 * Once the close starts, streamhead and sockfs will not let any data
16770 	 * packets come down (close ensures that there are no threads using the
16771 	 * queue and no new threads will come down) but since qprocsoff()
16772 	 * hasn't happened yet, a M_FLUSH or some non data message might
16773 	 * get reflected back (in response to our own FLUSHRW) and get
16774 	 * processed after tcp_close() is done. The conn would still be valid
16775 	 * because a ref would have added but we need to check the state
16776 	 * before actually processing the packet.
16777 	 */
16778 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16779 		freemsg(mp);
16780 		return;
16781 	}
16782 
16783 	switch (DB_TYPE(mp)) {
16784 	case M_IOCDATA:
16785 		tcp_wput_iocdata(tcp, mp);
16786 		break;
16787 	case M_FLUSH:
16788 		tcp_wput_flush(tcp, mp);
16789 		break;
16790 	default:
16791 		CALL_IP_WPUT(connp, q, mp);
16792 		break;
16793 	}
16794 }
16795 
16796 /*
16797  * The TCP fast path write put procedure.
16798  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16799  */
16800 /* ARGSUSED */
16801 void
16802 tcp_output(void *arg, mblk_t *mp, void *arg2)
16803 {
16804 	int		len;
16805 	int		hdrlen;
16806 	int		plen;
16807 	mblk_t		*mp1;
16808 	uchar_t		*rptr;
16809 	uint32_t	snxt;
16810 	tcph_t		*tcph;
16811 	struct datab	*db;
16812 	uint32_t	suna;
16813 	uint32_t	mss;
16814 	ipaddr_t	*dst;
16815 	ipaddr_t	*src;
16816 	uint32_t	sum;
16817 	int		usable;
16818 	conn_t		*connp = (conn_t *)arg;
16819 	tcp_t		*tcp = connp->conn_tcp;
16820 	uint32_t	msize;
16821 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16822 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
16823 
16824 	/*
16825 	 * Try and ASSERT the minimum possible references on the
16826 	 * conn early enough. Since we are executing on write side,
16827 	 * the connection is obviously not detached and that means
16828 	 * there is a ref each for TCP and IP. Since we are behind
16829 	 * the squeue, the minimum references needed are 3. If the
16830 	 * conn is in classifier hash list, there should be an
16831 	 * extra ref for that (we check both the possibilities).
16832 	 */
16833 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16834 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16835 
16836 	ASSERT(DB_TYPE(mp) == M_DATA);
16837 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
16838 
16839 	mutex_enter(&tcp->tcp_non_sq_lock);
16840 	tcp->tcp_squeue_bytes -= msize;
16841 	mutex_exit(&tcp->tcp_non_sq_lock);
16842 
16843 	/* Check to see if this connection wants to be re-fused. */
16844 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
16845 		if (tcp->tcp_ipversion == IPV4_VERSION) {
16846 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
16847 			    &tcp->tcp_saved_tcph);
16848 		} else {
16849 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
16850 			    &tcp->tcp_saved_tcph);
16851 		}
16852 	}
16853 	/* Bypass tcp protocol for fused tcp loopback */
16854 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
16855 		return;
16856 
16857 	mss = tcp->tcp_mss;
16858 	if (tcp->tcp_xmit_zc_clean)
16859 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16860 
16861 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16862 	len = (int)(mp->b_wptr - mp->b_rptr);
16863 
16864 	/*
16865 	 * Criteria for fast path:
16866 	 *
16867 	 *   1. no unsent data
16868 	 *   2. single mblk in request
16869 	 *   3. connection established
16870 	 *   4. data in mblk
16871 	 *   5. len <= mss
16872 	 *   6. no tcp_valid bits
16873 	 */
16874 	if ((tcp->tcp_unsent != 0) ||
16875 	    (tcp->tcp_cork) ||
16876 	    (mp->b_cont != NULL) ||
16877 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16878 	    (len == 0) ||
16879 	    (len > mss) ||
16880 	    (tcp->tcp_valid_bits != 0)) {
16881 		tcp_wput_data(tcp, mp, B_FALSE);
16882 		return;
16883 	}
16884 
16885 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16886 	ASSERT(tcp->tcp_fin_sent == 0);
16887 
16888 	/* queue new packet onto retransmission queue */
16889 	if (tcp->tcp_xmit_head == NULL) {
16890 		tcp->tcp_xmit_head = mp;
16891 	} else {
16892 		tcp->tcp_xmit_last->b_cont = mp;
16893 	}
16894 	tcp->tcp_xmit_last = mp;
16895 	tcp->tcp_xmit_tail = mp;
16896 
16897 	/* find out how much we can send */
16898 	/* BEGIN CSTYLED */
16899 	/*
16900 	 *    un-acked	   usable
16901 	 *  |--------------|-----------------|
16902 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
16903 	 */
16904 	/* END CSTYLED */
16905 
16906 	/* start sending from tcp_snxt */
16907 	snxt = tcp->tcp_snxt;
16908 
16909 	/*
16910 	 * Check to see if this connection has been idled for some
16911 	 * time and no ACK is expected.  If it is, we need to slow
16912 	 * start again to get back the connection's "self-clock" as
16913 	 * described in VJ's paper.
16914 	 *
16915 	 * Refer to the comment in tcp_mss_set() for the calculation
16916 	 * of tcp_cwnd after idle.
16917 	 */
16918 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16919 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16920 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
16921 	}
16922 
16923 	usable = tcp->tcp_swnd;		/* tcp window size */
16924 	if (usable > tcp->tcp_cwnd)
16925 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16926 	usable -= snxt;		/* subtract stuff already sent */
16927 	suna = tcp->tcp_suna;
16928 	usable += suna;
16929 	/* usable can be < 0 if the congestion window is smaller */
16930 	if (len > usable) {
16931 		/* Can't send complete M_DATA in one shot */
16932 		goto slow;
16933 	}
16934 
16935 	mutex_enter(&tcp->tcp_non_sq_lock);
16936 	if (tcp->tcp_flow_stopped &&
16937 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16938 		tcp_clrqfull(tcp);
16939 	}
16940 	mutex_exit(&tcp->tcp_non_sq_lock);
16941 
16942 	/*
16943 	 * determine if anything to send (Nagle).
16944 	 *
16945 	 *   1. len < tcp_mss (i.e. small)
16946 	 *   2. unacknowledged data present
16947 	 *   3. len < nagle limit
16948 	 *   4. last packet sent < nagle limit (previous packet sent)
16949 	 */
16950 	if ((len < mss) && (snxt != suna) &&
16951 	    (len < (int)tcp->tcp_naglim) &&
16952 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
16953 		/*
16954 		 * This was the first unsent packet and normally
16955 		 * mss < xmit_hiwater so there is no need to worry
16956 		 * about flow control. The next packet will go
16957 		 * through the flow control check in tcp_wput_data().
16958 		 */
16959 		/* leftover work from above */
16960 		tcp->tcp_unsent = len;
16961 		tcp->tcp_xmit_tail_unsent = len;
16962 
16963 		return;
16964 	}
16965 
16966 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
16967 
16968 	if (snxt == suna) {
16969 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16970 	}
16971 
16972 	/* we have always sent something */
16973 	tcp->tcp_rack_cnt = 0;
16974 
16975 	tcp->tcp_snxt = snxt + len;
16976 	tcp->tcp_rack = tcp->tcp_rnxt;
16977 
16978 	if ((mp1 = dupb(mp)) == 0)
16979 		goto no_memory;
16980 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
16981 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
16982 
16983 	/* adjust tcp header information */
16984 	tcph = tcp->tcp_tcph;
16985 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
16986 
16987 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
16988 	sum = (sum >> 16) + (sum & 0xFFFF);
16989 	U16_TO_ABE16(sum, tcph->th_sum);
16990 
16991 	U32_TO_ABE32(snxt, tcph->th_seq);
16992 
16993 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16994 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16995 	BUMP_LOCAL(tcp->tcp_obsegs);
16996 
16997 	/* Update the latest receive window size in TCP header. */
16998 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
16999 	    tcph->th_win);
17000 
17001 	tcp->tcp_last_sent_len = (ushort_t)len;
17002 
17003 	plen = len + tcp->tcp_hdr_len;
17004 
17005 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17006 		tcp->tcp_ipha->ipha_length = htons(plen);
17007 	} else {
17008 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17009 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17010 	}
17011 
17012 	/* see if we need to allocate a mblk for the headers */
17013 	hdrlen = tcp->tcp_hdr_len;
17014 	rptr = mp1->b_rptr - hdrlen;
17015 	db = mp1->b_datap;
17016 	if ((db->db_ref != 2) || rptr < db->db_base ||
17017 	    (!OK_32PTR(rptr))) {
17018 		/* NOTE: we assume allocb returns an OK_32PTR */
17019 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17020 		    tcps->tcps_wroff_xtra, BPRI_MED);
17021 		if (!mp) {
17022 			freemsg(mp1);
17023 			goto no_memory;
17024 		}
17025 		mp->b_cont = mp1;
17026 		mp1 = mp;
17027 		/* Leave room for Link Level header */
17028 		/* hdrlen = tcp->tcp_hdr_len; */
17029 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17030 		mp1->b_wptr = &rptr[hdrlen];
17031 	}
17032 	mp1->b_rptr = rptr;
17033 
17034 	/* Fill in the timestamp option. */
17035 	if (tcp->tcp_snd_ts_ok) {
17036 		U32_TO_BE32((uint32_t)lbolt,
17037 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17038 		U32_TO_BE32(tcp->tcp_ts_recent,
17039 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17040 	} else {
17041 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17042 	}
17043 
17044 	/* copy header into outgoing packet */
17045 	dst = (ipaddr_t *)rptr;
17046 	src = (ipaddr_t *)tcp->tcp_iphc;
17047 	dst[0] = src[0];
17048 	dst[1] = src[1];
17049 	dst[2] = src[2];
17050 	dst[3] = src[3];
17051 	dst[4] = src[4];
17052 	dst[5] = src[5];
17053 	dst[6] = src[6];
17054 	dst[7] = src[7];
17055 	dst[8] = src[8];
17056 	dst[9] = src[9];
17057 	if (hdrlen -= 40) {
17058 		hdrlen >>= 2;
17059 		dst += 10;
17060 		src += 10;
17061 		do {
17062 			*dst++ = *src++;
17063 		} while (--hdrlen);
17064 	}
17065 
17066 	/*
17067 	 * Set the ECN info in the TCP header.  Note that this
17068 	 * is not the template header.
17069 	 */
17070 	if (tcp->tcp_ecn_ok) {
17071 		SET_ECT(tcp, rptr);
17072 
17073 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17074 		if (tcp->tcp_ecn_echo_on)
17075 			tcph->th_flags[0] |= TH_ECE;
17076 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17077 			tcph->th_flags[0] |= TH_CWR;
17078 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17079 		}
17080 	}
17081 
17082 	if (tcp->tcp_ip_forward_progress) {
17083 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17084 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17085 		tcp->tcp_ip_forward_progress = B_FALSE;
17086 	}
17087 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17088 	return;
17089 
17090 	/*
17091 	 * If we ran out of memory, we pretend to have sent the packet
17092 	 * and that it was lost on the wire.
17093 	 */
17094 no_memory:
17095 	return;
17096 
17097 slow:
17098 	/* leftover work from above */
17099 	tcp->tcp_unsent = len;
17100 	tcp->tcp_xmit_tail_unsent = len;
17101 	tcp_wput_data(tcp, NULL, B_FALSE);
17102 }
17103 
17104 /* ARGSUSED */
17105 void
17106 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17107 {
17108 	conn_t			*connp = (conn_t *)arg;
17109 	tcp_t			*tcp = connp->conn_tcp;
17110 	queue_t			*q = tcp->tcp_rq;
17111 	struct tcp_options	*tcpopt;
17112 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17113 
17114 	/* socket options */
17115 	uint_t 			sopp_flags;
17116 	ssize_t			sopp_rxhiwat;
17117 	ssize_t			sopp_maxblk;
17118 	ushort_t		sopp_wroff;
17119 	ushort_t		sopp_tail;
17120 	ushort_t		sopp_copyopt;
17121 
17122 	tcpopt = (struct tcp_options *)mp->b_rptr;
17123 
17124 	/*
17125 	 * Drop the eager's ref on the listener, that was placed when
17126 	 * this eager began life in tcp_conn_request.
17127 	 */
17128 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17129 	if (IPCL_IS_NONSTR(connp)) {
17130 		/* Safe to free conn_ind message */
17131 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17132 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17133 	}
17134 
17135 	tcp->tcp_detached = B_FALSE;
17136 
17137 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17138 		/*
17139 		 * Someone blewoff the eager before we could finish
17140 		 * the accept.
17141 		 *
17142 		 * The only reason eager exists it because we put in
17143 		 * a ref on it when conn ind went up. We need to send
17144 		 * a disconnect indication up while the last reference
17145 		 * on the eager will be dropped by the squeue when we
17146 		 * return.
17147 		 */
17148 		ASSERT(tcp->tcp_listener == NULL);
17149 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17150 			if (IPCL_IS_NONSTR(connp)) {
17151 				ASSERT(tcp->tcp_issocket);
17152 				(*connp->conn_upcalls->su_disconnected)(
17153 				    connp->conn_upper_handle, tcp->tcp_connid,
17154 				    ECONNREFUSED);
17155 				freemsg(mp);
17156 			} else {
17157 				struct	T_discon_ind	*tdi;
17158 
17159 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17160 				/*
17161 				 * Let us reuse the incoming mblk to avoid
17162 				 * memory allocation failure problems. We know
17163 				 * that the size of the incoming mblk i.e.
17164 				 * stroptions is greater than sizeof
17165 				 * T_discon_ind. So the reallocb below can't
17166 				 * fail.
17167 				 */
17168 				freemsg(mp->b_cont);
17169 				mp->b_cont = NULL;
17170 				ASSERT(DB_REF(mp) == 1);
17171 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17172 				    B_FALSE);
17173 				ASSERT(mp != NULL);
17174 				DB_TYPE(mp) = M_PROTO;
17175 				((union T_primitives *)mp->b_rptr)->type =
17176 				    T_DISCON_IND;
17177 				tdi = (struct T_discon_ind *)mp->b_rptr;
17178 				if (tcp->tcp_issocket) {
17179 					tdi->DISCON_reason = ECONNREFUSED;
17180 					tdi->SEQ_number = 0;
17181 				} else {
17182 					tdi->DISCON_reason = ENOPROTOOPT;
17183 					tdi->SEQ_number =
17184 					    tcp->tcp_conn_req_seqnum;
17185 				}
17186 				mp->b_wptr = mp->b_rptr +
17187 				    sizeof (struct T_discon_ind);
17188 				putnext(q, mp);
17189 				return;
17190 			}
17191 		}
17192 		if (tcp->tcp_hard_binding) {
17193 			tcp->tcp_hard_binding = B_FALSE;
17194 			tcp->tcp_hard_bound = B_TRUE;
17195 		}
17196 		return;
17197 	}
17198 
17199 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17200 		int boundif = tcpopt->to_boundif;
17201 		uint_t len = sizeof (int);
17202 
17203 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17204 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17205 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17206 	}
17207 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17208 		uint_t on = 1;
17209 		uint_t len = sizeof (uint_t);
17210 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17211 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17212 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17213 	}
17214 
17215 	/*
17216 	 * For a loopback connection with tcp_direct_sockfs on, note that
17217 	 * we don't have to protect tcp_rcv_list yet because synchronous
17218 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17219 	 * possibly race with us.
17220 	 */
17221 
17222 	/*
17223 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17224 	 * properly.  This is the first time we know of the acceptor'
17225 	 * queue.  So we do it here.
17226 	 *
17227 	 * XXX
17228 	 */
17229 	if (tcp->tcp_rcv_list == NULL) {
17230 		/*
17231 		 * Recv queue is empty, tcp_rwnd should not have changed.
17232 		 * That means it should be equal to the listener's tcp_rwnd.
17233 		 */
17234 		if (!IPCL_IS_NONSTR(connp))
17235 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17236 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17237 	} else {
17238 #ifdef DEBUG
17239 		mblk_t *tmp;
17240 		mblk_t	*mp1;
17241 		uint_t	cnt = 0;
17242 
17243 		mp1 = tcp->tcp_rcv_list;
17244 		while ((tmp = mp1) != NULL) {
17245 			mp1 = tmp->b_next;
17246 			cnt += msgdsize(tmp);
17247 		}
17248 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17249 #endif
17250 		/* There is some data, add them back to get the max. */
17251 		if (!IPCL_IS_NONSTR(connp))
17252 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17253 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17254 	}
17255 	/*
17256 	 * This is the first time we run on the correct
17257 	 * queue after tcp_accept. So fix all the q parameters
17258 	 * here.
17259 	 */
17260 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17261 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17262 
17263 	/*
17264 	 * Record the stream head's high water mark for this endpoint;
17265 	 * this is used for flow-control purposes.
17266 	 */
17267 	sopp_rxhiwat = tcp->tcp_fused ?
17268 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17269 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
17270 
17271 	/*
17272 	 * Determine what write offset value to use depending on SACK and
17273 	 * whether the endpoint is fused or not.
17274 	 */
17275 	if (tcp->tcp_fused) {
17276 		ASSERT(tcp->tcp_loopback);
17277 		ASSERT(tcp->tcp_loopback_peer != NULL);
17278 		/*
17279 		 * For fused tcp loopback, set the stream head's write
17280 		 * offset value to zero since we won't be needing any room
17281 		 * for TCP/IP headers.  This would also improve performance
17282 		 * since it would reduce the amount of work done by kmem.
17283 		 * Non-fused tcp loopback case is handled separately below.
17284 		 */
17285 		sopp_wroff = 0;
17286 		/*
17287 		 * Update the peer's transmit parameters according to
17288 		 * our recently calculated high water mark value.
17289 		 */
17290 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17291 	} else if (tcp->tcp_snd_sack_ok) {
17292 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17293 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17294 	} else {
17295 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17296 		    tcps->tcps_wroff_xtra);
17297 	}
17298 
17299 	/*
17300 	 * If this is endpoint is handling SSL, then reserve extra
17301 	 * offset and space at the end.
17302 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17303 	 * overriding the previous setting. The extra cost of signing and
17304 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17305 	 * instead of a single contiguous one by the stream head
17306 	 * largely outweighs the statistical reduction of ACKs, when
17307 	 * applicable. The peer will also save on decryption and verification
17308 	 * costs.
17309 	 */
17310 	if (tcp->tcp_kssl_ctx != NULL) {
17311 		sopp_wroff += SSL3_WROFFSET;
17312 
17313 		sopp_flags |= SOCKOPT_TAIL;
17314 		sopp_tail = SSL3_MAX_TAIL_LEN;
17315 
17316 		sopp_flags |= SOCKOPT_ZCOPY;
17317 		sopp_copyopt = ZCVMUNSAFE;
17318 
17319 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
17320 	}
17321 
17322 	/* Send the options up */
17323 	if (IPCL_IS_NONSTR(connp)) {
17324 		struct sock_proto_props sopp;
17325 
17326 		sopp.sopp_flags = sopp_flags;
17327 		sopp.sopp_wroff = sopp_wroff;
17328 		sopp.sopp_maxblk = sopp_maxblk;
17329 		sopp.sopp_rxhiwat = sopp_rxhiwat;
17330 		if (sopp_flags & SOCKOPT_TAIL) {
17331 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17332 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
17333 			sopp.sopp_tail = sopp_tail;
17334 			sopp.sopp_zcopyflag = sopp_copyopt;
17335 		}
17336 		(*connp->conn_upcalls->su_set_proto_props)
17337 		    (connp->conn_upper_handle, &sopp);
17338 	} else {
17339 		struct stroptions *stropt;
17340 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17341 		if (stropt_mp == NULL) {
17342 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
17343 			return;
17344 		}
17345 		DB_TYPE(stropt_mp) = M_SETOPTS;
17346 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17347 		stropt_mp->b_wptr += sizeof (struct stroptions);
17348 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
17349 		stropt->so_hiwat = sopp_rxhiwat;
17350 		stropt->so_wroff = sopp_wroff;
17351 		stropt->so_maxblk = sopp_maxblk;
17352 
17353 		if (sopp_flags & SOCKOPT_TAIL) {
17354 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17355 
17356 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
17357 			stropt->so_tail = sopp_tail;
17358 			stropt->so_copyopt = sopp_copyopt;
17359 		}
17360 
17361 		/* Send the options up */
17362 		putnext(q, stropt_mp);
17363 	}
17364 
17365 	freemsg(mp);
17366 	/*
17367 	 * Pass up any data and/or a fin that has been received.
17368 	 *
17369 	 * Adjust receive window in case it had decreased
17370 	 * (because there is data <=> tcp_rcv_list != NULL)
17371 	 * while the connection was detached. Note that
17372 	 * in case the eager was flow-controlled, w/o this
17373 	 * code, the rwnd may never open up again!
17374 	 */
17375 	if (tcp->tcp_rcv_list != NULL) {
17376 		if (IPCL_IS_NONSTR(connp)) {
17377 			mblk_t *mp;
17378 			int space_left;
17379 			int error;
17380 			boolean_t push = B_TRUE;
17381 
17382 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
17383 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
17384 			    &push) >= 0) {
17385 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17386 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17387 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17388 					tcp_xmit_ctl(NULL,
17389 					    tcp, (tcp->tcp_swnd == 0) ?
17390 					    tcp->tcp_suna : tcp->tcp_snxt,
17391 					    tcp->tcp_rnxt, TH_ACK);
17392 				}
17393 			}
17394 			while ((mp = tcp->tcp_rcv_list) != NULL) {
17395 				push = B_TRUE;
17396 				tcp->tcp_rcv_list = mp->b_next;
17397 				mp->b_next = NULL;
17398 				space_left = (*connp->conn_upcalls->su_recv)
17399 				    (connp->conn_upper_handle, mp, msgdsize(mp),
17400 				    0, &error, &push);
17401 				if (space_left < 0) {
17402 					/*
17403 					 * We should never be in middle of a
17404 					 * fallback, the squeue guarantees that.
17405 					 */
17406 					ASSERT(error != EOPNOTSUPP);
17407 				}
17408 			}
17409 			tcp->tcp_rcv_last_head = NULL;
17410 			tcp->tcp_rcv_last_tail = NULL;
17411 			tcp->tcp_rcv_cnt = 0;
17412 		} else {
17413 			/* We drain directly in case of fused tcp loopback */
17414 
17415 			if (!tcp->tcp_fused && canputnext(q)) {
17416 				tcp->tcp_rwnd = q->q_hiwat;
17417 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17418 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17419 					tcp_xmit_ctl(NULL,
17420 					    tcp, (tcp->tcp_swnd == 0) ?
17421 					    tcp->tcp_suna : tcp->tcp_snxt,
17422 					    tcp->tcp_rnxt, TH_ACK);
17423 				}
17424 			}
17425 
17426 			(void) tcp_rcv_drain(tcp);
17427 		}
17428 
17429 		/*
17430 		 * For fused tcp loopback, back-enable peer endpoint
17431 		 * if it's currently flow-controlled.
17432 		 */
17433 		if (tcp->tcp_fused) {
17434 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17435 
17436 			ASSERT(peer_tcp != NULL);
17437 			ASSERT(peer_tcp->tcp_fused);
17438 			/*
17439 			 * In order to change the peer's tcp_flow_stopped,
17440 			 * we need to take locks for both end points. The
17441 			 * highest address is taken first.
17442 			 */
17443 			if (peer_tcp > tcp) {
17444 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
17445 				mutex_enter(&tcp->tcp_non_sq_lock);
17446 			} else {
17447 				mutex_enter(&tcp->tcp_non_sq_lock);
17448 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
17449 			}
17450 			if (peer_tcp->tcp_flow_stopped) {
17451 				tcp_clrqfull(peer_tcp);
17452 				TCP_STAT(tcps, tcp_fusion_backenabled);
17453 			}
17454 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17455 			mutex_exit(&tcp->tcp_non_sq_lock);
17456 		}
17457 	}
17458 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17459 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17460 		tcp->tcp_ordrel_done = B_TRUE;
17461 		if (IPCL_IS_NONSTR(connp)) {
17462 			ASSERT(tcp->tcp_ordrel_mp == NULL);
17463 			(*connp->conn_upcalls->su_opctl)(
17464 			    connp->conn_upper_handle,
17465 			    SOCK_OPCTL_SHUT_RECV, 0);
17466 		} else {
17467 			mp = tcp->tcp_ordrel_mp;
17468 			tcp->tcp_ordrel_mp = NULL;
17469 			putnext(q, mp);
17470 		}
17471 	}
17472 	if (tcp->tcp_hard_binding) {
17473 		tcp->tcp_hard_binding = B_FALSE;
17474 		tcp->tcp_hard_bound = B_TRUE;
17475 	}
17476 
17477 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
17478 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
17479 	    tcp->tcp_loopback_peer != NULL &&
17480 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
17481 		tcp_fuse_syncstr_enable_pair(tcp);
17482 	}
17483 
17484 	if (tcp->tcp_ka_enabled) {
17485 		tcp->tcp_ka_last_intrvl = 0;
17486 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17487 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17488 	}
17489 
17490 	/*
17491 	 * At this point, eager is fully established and will
17492 	 * have the following references -
17493 	 *
17494 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17495 	 * 1 reference for the squeue which will be dropped by the squeue as
17496 	 *	soon as this function returns.
17497 	 * There will be 1 additonal reference for being in classifier
17498 	 *	hash list provided something bad hasn't happened.
17499 	 */
17500 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17501 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17502 }
17503 
17504 /*
17505  * The function called through squeue to get behind listener's perimeter to
17506  * send a deffered conn_ind.
17507  */
17508 /* ARGSUSED */
17509 void
17510 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17511 {
17512 	conn_t	*connp = (conn_t *)arg;
17513 	tcp_t *listener = connp->conn_tcp;
17514 	struct T_conn_ind *conn_ind;
17515 	tcp_t *tcp;
17516 
17517 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
17518 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17519 	    conn_ind->OPT_length);
17520 
17521 	if (listener->tcp_state != TCPS_LISTEN) {
17522 		/*
17523 		 * If listener has closed, it would have caused a
17524 		 * a cleanup/blowoff to happen for the eager, so
17525 		 * we don't need to do anything more.
17526 		 */
17527 		freemsg(mp);
17528 		return;
17529 	}
17530 
17531 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
17532 }
17533 
17534 /* ARGSUSED */
17535 static int
17536 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
17537 {
17538 	tcp_t *listener, *eager;
17539 	mblk_t *opt_mp;
17540 	struct tcp_options *tcpopt;
17541 
17542 	listener = lconnp->conn_tcp;
17543 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17544 	eager = econnp->conn_tcp;
17545 	ASSERT(eager->tcp_listener != NULL);
17546 
17547 	ASSERT(eager->tcp_rq != NULL);
17548 
17549 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
17550 	if (opt_mp == NULL) {
17551 		return (-TPROTO);
17552 	}
17553 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
17554 	eager->tcp_issocket = B_TRUE;
17555 
17556 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17557 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17558 	ASSERT(econnp->conn_netstack ==
17559 	    listener->tcp_connp->conn_netstack);
17560 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
17561 
17562 	/* Put the ref for IP */
17563 	CONN_INC_REF(econnp);
17564 
17565 	/*
17566 	 * We should have minimum of 3 references on the conn
17567 	 * at this point. One each for TCP and IP and one for
17568 	 * the T_conn_ind that was sent up when the 3-way handshake
17569 	 * completed. In the normal case we would also have another
17570 	 * reference (making a total of 4) for the conn being in the
17571 	 * classifier hash list. However the eager could have received
17572 	 * an RST subsequently and tcp_closei_local could have removed
17573 	 * the eager from the classifier hash list, hence we can't
17574 	 * assert that reference.
17575 	 */
17576 	ASSERT(econnp->conn_ref >= 3);
17577 
17578 	opt_mp->b_datap->db_type = M_SETOPTS;
17579 	opt_mp->b_wptr += sizeof (struct tcp_options);
17580 
17581 	/*
17582 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17583 	 * from listener to acceptor.
17584 	 */
17585 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
17586 	tcpopt->to_flags = 0;
17587 
17588 	if (listener->tcp_bound_if != 0) {
17589 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
17590 		tcpopt->to_boundif = listener->tcp_bound_if;
17591 	}
17592 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17593 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
17594 	}
17595 
17596 	mutex_enter(&listener->tcp_eager_lock);
17597 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17598 
17599 		tcp_t *tail;
17600 		tcp_t *tcp;
17601 		mblk_t *mp1;
17602 
17603 		tcp = listener->tcp_eager_prev_q0;
17604 		/*
17605 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
17606 		 * deferred T_conn_ind queue. We need to get to the head
17607 		 * of the queue in order to send up T_conn_ind the same
17608 		 * order as how the 3WHS is completed.
17609 		 */
17610 		while (tcp != listener) {
17611 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17612 			    !tcp->tcp_kssl_pending)
17613 				break;
17614 			else
17615 				tcp = tcp->tcp_eager_prev_q0;
17616 		}
17617 		/* None of the pending eagers can be sent up now */
17618 		if (tcp == listener)
17619 			goto no_more_eagers;
17620 
17621 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17622 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17623 		/* Move from q0 to q */
17624 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17625 		listener->tcp_conn_req_cnt_q0--;
17626 		listener->tcp_conn_req_cnt_q++;
17627 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17628 		    tcp->tcp_eager_prev_q0;
17629 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17630 		    tcp->tcp_eager_next_q0;
17631 		tcp->tcp_eager_prev_q0 = NULL;
17632 		tcp->tcp_eager_next_q0 = NULL;
17633 		tcp->tcp_conn_def_q0 = B_FALSE;
17634 
17635 		/* Make sure the tcp isn't in the list of droppables */
17636 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
17637 		    tcp->tcp_eager_prev_drop_q0 == NULL);
17638 
17639 		/*
17640 		 * Insert at end of the queue because sockfs sends
17641 		 * down T_CONN_RES in chronological order. Leaving
17642 		 * the older conn indications at front of the queue
17643 		 * helps reducing search time.
17644 		 */
17645 		tail = listener->tcp_eager_last_q;
17646 		if (tail != NULL) {
17647 			tail->tcp_eager_next_q = tcp;
17648 		} else {
17649 			listener->tcp_eager_next_q = tcp;
17650 		}
17651 		listener->tcp_eager_last_q = tcp;
17652 		tcp->tcp_eager_next_q = NULL;
17653 
17654 		/* Need to get inside the listener perimeter */
17655 		CONN_INC_REF(listener->tcp_connp);
17656 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
17657 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
17658 		    SQTAG_TCP_SEND_PENDING);
17659 	}
17660 no_more_eagers:
17661 	tcp_eager_unlink(eager);
17662 	mutex_exit(&listener->tcp_eager_lock);
17663 
17664 	/*
17665 	 * At this point, the eager is detached from the listener
17666 	 * but we still have an extra refs on eager (apart from the
17667 	 * usual tcp references). The ref was placed in tcp_rput_data
17668 	 * before sending the conn_ind in tcp_send_conn_ind.
17669 	 * The ref will be dropped in tcp_accept_finish().
17670 	 */
17671 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
17672 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
17673 	return (0);
17674 }
17675 
17676 int
17677 tcp_accept(sock_lower_handle_t lproto_handle,
17678     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
17679     cred_t *cr)
17680 {
17681 	conn_t *lconnp, *econnp;
17682 	tcp_t *listener, *eager;
17683 	tcp_stack_t	*tcps;
17684 
17685 	lconnp = (conn_t *)lproto_handle;
17686 	listener = lconnp->conn_tcp;
17687 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17688 	econnp = (conn_t *)eproto_handle;
17689 	eager = econnp->conn_tcp;
17690 	ASSERT(eager->tcp_listener != NULL);
17691 	tcps = eager->tcp_tcps;
17692 
17693 	/*
17694 	 * It is OK to manipulate these fields outside the eager's squeue
17695 	 * because they will not start being used until tcp_accept_finish
17696 	 * has been called.
17697 	 */
17698 	ASSERT(lconnp->conn_upper_handle != NULL);
17699 	ASSERT(econnp->conn_upper_handle == NULL);
17700 	econnp->conn_upper_handle = sock_handle;
17701 	econnp->conn_upcalls = lconnp->conn_upcalls;
17702 	ASSERT(IPCL_IS_NONSTR(econnp));
17703 	/*
17704 	 * Create helper stream if it is a non-TPI TCP connection.
17705 	 */
17706 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
17707 		ip1dbg(("tcp_accept: create of IP helper stream"
17708 		    " failed\n"));
17709 		return (EPROTO);
17710 	}
17711 	eager->tcp_rq = econnp->conn_rq;
17712 	eager->tcp_wq = econnp->conn_wq;
17713 
17714 	ASSERT(eager->tcp_rq != NULL);
17715 
17716 	return (tcp_accept_common(lconnp, econnp, cr));
17717 }
17718 
17719 
17720 /*
17721  * This is the STREAMS entry point for T_CONN_RES coming down on
17722  * Acceptor STREAM when  sockfs listener does accept processing.
17723  * Read the block comment on top of tcp_conn_request().
17724  */
17725 void
17726 tcp_tpi_accept(queue_t *q, mblk_t *mp)
17727 {
17728 	queue_t *rq = RD(q);
17729 	struct T_conn_res *conn_res;
17730 	tcp_t *eager;
17731 	tcp_t *listener;
17732 	struct T_ok_ack *ok;
17733 	t_scalar_t PRIM_type;
17734 	conn_t *econnp;
17735 	cred_t *cr;
17736 
17737 	ASSERT(DB_TYPE(mp) == M_PROTO);
17738 
17739 	/*
17740 	 * All Solaris components should pass a db_credp
17741 	 * for this TPI message, hence we ASSERT.
17742 	 * But in case there is some other M_PROTO that looks
17743 	 * like a TPI message sent by some other kernel
17744 	 * component, we check and return an error.
17745 	 */
17746 	cr = msg_getcred(mp, NULL);
17747 	ASSERT(cr != NULL);
17748 	if (cr == NULL) {
17749 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
17750 		if (mp != NULL)
17751 			putnext(rq, mp);
17752 		return;
17753 	}
17754 	conn_res = (struct T_conn_res *)mp->b_rptr;
17755 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17756 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17757 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17758 		if (mp != NULL)
17759 			putnext(rq, mp);
17760 		return;
17761 	}
17762 	switch (conn_res->PRIM_type) {
17763 	case O_T_CONN_RES:
17764 	case T_CONN_RES:
17765 		/*
17766 		 * We pass up an err ack if allocb fails. This will
17767 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17768 		 * tcp_eager_blowoff to be called. sockfs will then call
17769 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17770 		 * we need to do the allocb up here because we have to
17771 		 * make sure rq->q_qinfo->qi_qclose still points to the
17772 		 * correct function (tcp_tpi_close_accept) in case allocb
17773 		 * fails.
17774 		 */
17775 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17776 		    &eager, conn_res->OPT_length);
17777 		PRIM_type = conn_res->PRIM_type;
17778 		mp->b_datap->db_type = M_PCPROTO;
17779 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17780 		ok = (struct T_ok_ack *)mp->b_rptr;
17781 		ok->PRIM_type = T_OK_ACK;
17782 		ok->CORRECT_prim = PRIM_type;
17783 		econnp = eager->tcp_connp;
17784 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
17785 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
17786 		eager->tcp_rq = rq;
17787 		eager->tcp_wq = q;
17788 		rq->q_ptr = econnp;
17789 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
17790 		q->q_ptr = econnp;
17791 		q->q_qinfo = &tcp_winit;
17792 		listener = eager->tcp_listener;
17793 
17794 		if (tcp_accept_common(listener->tcp_connp,
17795 		    econnp, cr) < 0) {
17796 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17797 			if (mp != NULL)
17798 				putnext(rq, mp);
17799 			return;
17800 		}
17801 
17802 		/*
17803 		 * Send the new local address also up to sockfs. There
17804 		 * should already be enough space in the mp that came
17805 		 * down from soaccept().
17806 		 */
17807 		if (eager->tcp_family == AF_INET) {
17808 			sin_t *sin;
17809 
17810 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17811 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17812 			sin = (sin_t *)mp->b_wptr;
17813 			mp->b_wptr += sizeof (sin_t);
17814 			sin->sin_family = AF_INET;
17815 			sin->sin_port = eager->tcp_lport;
17816 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17817 		} else {
17818 			sin6_t *sin6;
17819 
17820 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17821 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17822 			sin6 = (sin6_t *)mp->b_wptr;
17823 			mp->b_wptr += sizeof (sin6_t);
17824 			sin6->sin6_family = AF_INET6;
17825 			sin6->sin6_port = eager->tcp_lport;
17826 			if (eager->tcp_ipversion == IPV4_VERSION) {
17827 				sin6->sin6_flowinfo = 0;
17828 				IN6_IPADDR_TO_V4MAPPED(
17829 				    eager->tcp_ipha->ipha_src,
17830 				    &sin6->sin6_addr);
17831 			} else {
17832 				ASSERT(eager->tcp_ip6h != NULL);
17833 				sin6->sin6_flowinfo =
17834 				    eager->tcp_ip6h->ip6_vcf &
17835 				    ~IPV6_VERS_AND_FLOW_MASK;
17836 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17837 			}
17838 			sin6->sin6_scope_id = 0;
17839 			sin6->__sin6_src_id = 0;
17840 		}
17841 
17842 		putnext(rq, mp);
17843 		return;
17844 	default:
17845 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17846 		if (mp != NULL)
17847 			putnext(rq, mp);
17848 		return;
17849 	}
17850 }
17851 
17852 static int
17853 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17854 {
17855 	sin_t *sin = (sin_t *)sa;
17856 	sin6_t *sin6 = (sin6_t *)sa;
17857 
17858 	switch (tcp->tcp_family) {
17859 	case AF_INET:
17860 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17861 
17862 		if (*salenp < sizeof (sin_t))
17863 			return (EINVAL);
17864 
17865 		*sin = sin_null;
17866 		sin->sin_family = AF_INET;
17867 		if (tcp->tcp_state >= TCPS_BOUND) {
17868 			sin->sin_port = tcp->tcp_lport;
17869 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
17870 		}
17871 		*salenp = sizeof (sin_t);
17872 		break;
17873 
17874 	case AF_INET6:
17875 		if (*salenp < sizeof (sin6_t))
17876 			return (EINVAL);
17877 
17878 		*sin6 = sin6_null;
17879 		sin6->sin6_family = AF_INET6;
17880 		if (tcp->tcp_state >= TCPS_BOUND) {
17881 			sin6->sin6_port = tcp->tcp_lport;
17882 			if (tcp->tcp_ipversion == IPV4_VERSION) {
17883 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
17884 				    &sin6->sin6_addr);
17885 			} else {
17886 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
17887 			}
17888 		}
17889 		*salenp = sizeof (sin6_t);
17890 		break;
17891 	}
17892 
17893 	return (0);
17894 }
17895 
17896 static int
17897 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17898 {
17899 	sin_t *sin = (sin_t *)sa;
17900 	sin6_t *sin6 = (sin6_t *)sa;
17901 
17902 	if (tcp->tcp_state < TCPS_SYN_RCVD)
17903 		return (ENOTCONN);
17904 
17905 	switch (tcp->tcp_family) {
17906 	case AF_INET:
17907 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17908 
17909 		if (*salenp < sizeof (sin_t))
17910 			return (EINVAL);
17911 
17912 		*sin = sin_null;
17913 		sin->sin_family = AF_INET;
17914 		sin->sin_port = tcp->tcp_fport;
17915 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
17916 		    sin->sin_addr.s_addr);
17917 		*salenp = sizeof (sin_t);
17918 		break;
17919 
17920 	case AF_INET6:
17921 		if (*salenp < sizeof (sin6_t))
17922 			return (EINVAL);
17923 
17924 		*sin6 = sin6_null;
17925 		sin6->sin6_family = AF_INET6;
17926 		sin6->sin6_port = tcp->tcp_fport;
17927 		sin6->sin6_addr = tcp->tcp_remote_v6;
17928 		if (tcp->tcp_ipversion == IPV6_VERSION) {
17929 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
17930 			    ~IPV6_VERS_AND_FLOW_MASK;
17931 		}
17932 		*salenp = sizeof (sin6_t);
17933 		break;
17934 	}
17935 
17936 	return (0);
17937 }
17938 
17939 /*
17940  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
17941  */
17942 static void
17943 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
17944 {
17945 	void	*data;
17946 	mblk_t	*datamp = mp->b_cont;
17947 	tcp_t	*tcp = Q_TO_TCP(q);
17948 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
17949 
17950 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
17951 		cmdp->cb_error = EPROTO;
17952 		qreply(q, mp);
17953 		return;
17954 	}
17955 
17956 	data = datamp->b_rptr;
17957 
17958 	switch (cmdp->cb_cmd) {
17959 	case TI_GETPEERNAME:
17960 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
17961 		break;
17962 	case TI_GETMYNAME:
17963 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
17964 		break;
17965 	default:
17966 		cmdp->cb_error = EINVAL;
17967 		break;
17968 	}
17969 
17970 	qreply(q, mp);
17971 }
17972 
17973 void
17974 tcp_wput(queue_t *q, mblk_t *mp)
17975 {
17976 	conn_t	*connp = Q_TO_CONN(q);
17977 	tcp_t	*tcp;
17978 	void (*output_proc)();
17979 	t_scalar_t type;
17980 	uchar_t *rptr;
17981 	struct iocblk	*iocp;
17982 	size_t size;
17983 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17984 
17985 	ASSERT(connp->conn_ref >= 2);
17986 
17987 	switch (DB_TYPE(mp)) {
17988 	case M_DATA:
17989 		tcp = connp->conn_tcp;
17990 		ASSERT(tcp != NULL);
17991 
17992 		size = msgdsize(mp);
17993 
17994 		mutex_enter(&tcp->tcp_non_sq_lock);
17995 		tcp->tcp_squeue_bytes += size;
17996 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
17997 			tcp_setqfull(tcp);
17998 		}
17999 		mutex_exit(&tcp->tcp_non_sq_lock);
18000 
18001 		CONN_INC_REF(connp);
18002 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18003 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18004 		return;
18005 
18006 	case M_CMD:
18007 		tcp_wput_cmdblk(q, mp);
18008 		return;
18009 
18010 	case M_PROTO:
18011 	case M_PCPROTO:
18012 		/*
18013 		 * if it is a snmp message, don't get behind the squeue
18014 		 */
18015 		tcp = connp->conn_tcp;
18016 		rptr = mp->b_rptr;
18017 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18018 			type = ((union T_primitives *)rptr)->type;
18019 		} else {
18020 			if (tcp->tcp_debug) {
18021 				(void) strlog(TCP_MOD_ID, 0, 1,
18022 				    SL_ERROR|SL_TRACE,
18023 				    "tcp_wput_proto, dropping one...");
18024 			}
18025 			freemsg(mp);
18026 			return;
18027 		}
18028 		if (type == T_SVR4_OPTMGMT_REQ) {
18029 			/*
18030 			 * All Solaris components should pass a db_credp
18031 			 * for this TPI message, hence we ASSERT.
18032 			 * But in case there is some other M_PROTO that looks
18033 			 * like a TPI message sent by some other kernel
18034 			 * component, we check and return an error.
18035 			 */
18036 			cred_t	*cr = msg_getcred(mp, NULL);
18037 
18038 			ASSERT(cr != NULL);
18039 			if (cr == NULL) {
18040 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18041 				return;
18042 			}
18043 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18044 			    cr)) {
18045 				/*
18046 				 * This was a SNMP request
18047 				 */
18048 				return;
18049 			} else {
18050 				output_proc = tcp_wput_proto;
18051 			}
18052 		} else {
18053 			output_proc = tcp_wput_proto;
18054 		}
18055 		break;
18056 	case M_IOCTL:
18057 		/*
18058 		 * Most ioctls can be processed right away without going via
18059 		 * squeues - process them right here. Those that do require
18060 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18061 		 * are processed by tcp_wput_ioctl().
18062 		 */
18063 		iocp = (struct iocblk *)mp->b_rptr;
18064 		tcp = connp->conn_tcp;
18065 
18066 		switch (iocp->ioc_cmd) {
18067 		case TCP_IOC_ABORT_CONN:
18068 			tcp_ioctl_abort_conn(q, mp);
18069 			return;
18070 		case TI_GETPEERNAME:
18071 		case TI_GETMYNAME:
18072 			mi_copyin(q, mp, NULL,
18073 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18074 			return;
18075 		case ND_SET:
18076 			/* nd_getset does the necessary checks */
18077 		case ND_GET:
18078 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18079 				CALL_IP_WPUT(connp, q, mp);
18080 				return;
18081 			}
18082 			qreply(q, mp);
18083 			return;
18084 		case TCP_IOC_DEFAULT_Q:
18085 			/*
18086 			 * Wants to be the default wq. Check the credentials
18087 			 * first, the rest is executed via squeue.
18088 			 */
18089 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18090 				iocp->ioc_error = EPERM;
18091 				iocp->ioc_count = 0;
18092 				mp->b_datap->db_type = M_IOCACK;
18093 				qreply(q, mp);
18094 				return;
18095 			}
18096 			output_proc = tcp_wput_ioctl;
18097 			break;
18098 		default:
18099 			output_proc = tcp_wput_ioctl;
18100 			break;
18101 		}
18102 		break;
18103 	default:
18104 		output_proc = tcp_wput_nondata;
18105 		break;
18106 	}
18107 
18108 	CONN_INC_REF(connp);
18109 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18110 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18111 }
18112 
18113 /*
18114  * Initial STREAMS write side put() procedure for sockets. It tries to
18115  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18116  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18117  * are handled by tcp_wput() as usual.
18118  *
18119  * All further messages will also be handled by tcp_wput() because we cannot
18120  * be sure that the above short cut is safe later.
18121  */
18122 static void
18123 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18124 {
18125 	conn_t			*connp = Q_TO_CONN(wq);
18126 	tcp_t			*tcp = connp->conn_tcp;
18127 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18128 
18129 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18130 	wq->q_qinfo = &tcp_winit;
18131 
18132 	ASSERT(IPCL_IS_TCP(connp));
18133 	ASSERT(TCP_IS_SOCKET(tcp));
18134 
18135 	if (DB_TYPE(mp) == M_PCPROTO &&
18136 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18137 	    car->PRIM_type == T_CAPABILITY_REQ) {
18138 		tcp_capability_req(tcp, mp);
18139 		return;
18140 	}
18141 
18142 	tcp_wput(wq, mp);
18143 }
18144 
18145 /* ARGSUSED */
18146 static void
18147 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18148 {
18149 #ifdef DEBUG
18150 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18151 #endif
18152 	freemsg(mp);
18153 }
18154 
18155 static boolean_t
18156 tcp_zcopy_check(tcp_t *tcp)
18157 {
18158 	conn_t	*connp = tcp->tcp_connp;
18159 	ire_t	*ire;
18160 	boolean_t	zc_enabled = B_FALSE;
18161 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18162 
18163 	if (do_tcpzcopy == 2)
18164 		zc_enabled = B_TRUE;
18165 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18166 	    IPCL_IS_CONNECTED(connp) &&
18167 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18168 	    connp->conn_dontroute == 0 &&
18169 	    !connp->conn_nexthop_set &&
18170 	    connp->conn_outgoing_ill == NULL &&
18171 	    do_tcpzcopy == 1) {
18172 		/*
18173 		 * the checks above  closely resemble the fast path checks
18174 		 * in tcp_send_data().
18175 		 */
18176 		mutex_enter(&connp->conn_lock);
18177 		ire = connp->conn_ire_cache;
18178 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18179 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18180 			IRE_REFHOLD(ire);
18181 			if (ire->ire_stq != NULL) {
18182 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18183 
18184 				zc_enabled = ill && (ill->ill_capabilities &
18185 				    ILL_CAPAB_ZEROCOPY) &&
18186 				    (ill->ill_zerocopy_capab->
18187 				    ill_zerocopy_flags != 0);
18188 			}
18189 			IRE_REFRELE(ire);
18190 		}
18191 		mutex_exit(&connp->conn_lock);
18192 	}
18193 	tcp->tcp_snd_zcopy_on = zc_enabled;
18194 	if (!TCP_IS_DETACHED(tcp)) {
18195 		if (zc_enabled) {
18196 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18197 			    ZCVMSAFE);
18198 			TCP_STAT(tcps, tcp_zcopy_on);
18199 		} else {
18200 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18201 			    ZCVMUNSAFE);
18202 			TCP_STAT(tcps, tcp_zcopy_off);
18203 		}
18204 	}
18205 	return (zc_enabled);
18206 }
18207 
18208 static mblk_t *
18209 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18210 {
18211 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18212 
18213 	if (do_tcpzcopy == 2)
18214 		return (bp);
18215 	else if (tcp->tcp_snd_zcopy_on) {
18216 		tcp->tcp_snd_zcopy_on = B_FALSE;
18217 		if (!TCP_IS_DETACHED(tcp)) {
18218 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18219 			    ZCVMUNSAFE);
18220 			TCP_STAT(tcps, tcp_zcopy_disable);
18221 		}
18222 	}
18223 	return (tcp_zcopy_backoff(tcp, bp, 0));
18224 }
18225 
18226 /*
18227  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18228  * the original desballoca'ed segmapped mblk.
18229  */
18230 static mblk_t *
18231 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18232 {
18233 	mblk_t *head, *tail, *nbp;
18234 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18235 
18236 	if (IS_VMLOANED_MBLK(bp)) {
18237 		TCP_STAT(tcps, tcp_zcopy_backoff);
18238 		if ((head = copyb(bp)) == NULL) {
18239 			/* fail to backoff; leave it for the next backoff */
18240 			tcp->tcp_xmit_zc_clean = B_FALSE;
18241 			return (bp);
18242 		}
18243 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18244 			if (fix_xmitlist)
18245 				tcp_zcopy_notify(tcp);
18246 			else
18247 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18248 		}
18249 		nbp = bp->b_cont;
18250 		if (fix_xmitlist) {
18251 			head->b_prev = bp->b_prev;
18252 			head->b_next = bp->b_next;
18253 			if (tcp->tcp_xmit_tail == bp)
18254 				tcp->tcp_xmit_tail = head;
18255 		}
18256 		bp->b_next = NULL;
18257 		bp->b_prev = NULL;
18258 		freeb(bp);
18259 	} else {
18260 		head = bp;
18261 		nbp = bp->b_cont;
18262 	}
18263 	tail = head;
18264 	while (nbp) {
18265 		if (IS_VMLOANED_MBLK(nbp)) {
18266 			TCP_STAT(tcps, tcp_zcopy_backoff);
18267 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18268 				tcp->tcp_xmit_zc_clean = B_FALSE;
18269 				tail->b_cont = nbp;
18270 				return (head);
18271 			}
18272 			tail = tail->b_cont;
18273 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18274 				if (fix_xmitlist)
18275 					tcp_zcopy_notify(tcp);
18276 				else
18277 					tail->b_datap->db_struioflag |=
18278 					    STRUIO_ZCNOTIFY;
18279 			}
18280 			bp = nbp;
18281 			nbp = nbp->b_cont;
18282 			if (fix_xmitlist) {
18283 				tail->b_prev = bp->b_prev;
18284 				tail->b_next = bp->b_next;
18285 				if (tcp->tcp_xmit_tail == bp)
18286 					tcp->tcp_xmit_tail = tail;
18287 			}
18288 			bp->b_next = NULL;
18289 			bp->b_prev = NULL;
18290 			freeb(bp);
18291 		} else {
18292 			tail->b_cont = nbp;
18293 			tail = nbp;
18294 			nbp = nbp->b_cont;
18295 		}
18296 	}
18297 	if (fix_xmitlist) {
18298 		tcp->tcp_xmit_last = tail;
18299 		tcp->tcp_xmit_zc_clean = B_TRUE;
18300 	}
18301 	return (head);
18302 }
18303 
18304 static void
18305 tcp_zcopy_notify(tcp_t *tcp)
18306 {
18307 	struct stdata	*stp;
18308 	conn_t *connp;
18309 
18310 	if (tcp->tcp_detached)
18311 		return;
18312 	connp = tcp->tcp_connp;
18313 	if (IPCL_IS_NONSTR(connp)) {
18314 		(*connp->conn_upcalls->su_zcopy_notify)
18315 		    (connp->conn_upper_handle);
18316 		return;
18317 	}
18318 	stp = STREAM(tcp->tcp_rq);
18319 	mutex_enter(&stp->sd_lock);
18320 	stp->sd_flag |= STZCNOTIFY;
18321 	cv_broadcast(&stp->sd_zcopy_wait);
18322 	mutex_exit(&stp->sd_lock);
18323 }
18324 
18325 static boolean_t
18326 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18327 {
18328 	ire_t	*ire;
18329 	conn_t	*connp = tcp->tcp_connp;
18330 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18331 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18332 
18333 	mutex_enter(&connp->conn_lock);
18334 	ire = connp->conn_ire_cache;
18335 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18336 
18337 	if ((ire != NULL) &&
18338 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18339 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18340 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18341 		IRE_REFHOLD(ire);
18342 		mutex_exit(&connp->conn_lock);
18343 	} else {
18344 		boolean_t cached = B_FALSE;
18345 		ts_label_t *tsl;
18346 
18347 		/* force a recheck later on */
18348 		tcp->tcp_ire_ill_check_done = B_FALSE;
18349 
18350 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18351 		connp->conn_ire_cache = NULL;
18352 		mutex_exit(&connp->conn_lock);
18353 
18354 		if (ire != NULL)
18355 			IRE_REFRELE_NOTR(ire);
18356 
18357 		tsl = crgetlabel(CONN_CRED(connp));
18358 		ire = (dst ?
18359 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18360 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18361 		    connp->conn_zoneid, tsl, ipst));
18362 
18363 		if (ire == NULL) {
18364 			TCP_STAT(tcps, tcp_ire_null);
18365 			return (B_FALSE);
18366 		}
18367 
18368 		IRE_REFHOLD_NOTR(ire);
18369 
18370 		mutex_enter(&connp->conn_lock);
18371 		if (CONN_CACHE_IRE(connp)) {
18372 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18373 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18374 				TCP_CHECK_IREINFO(tcp, ire);
18375 				connp->conn_ire_cache = ire;
18376 				cached = B_TRUE;
18377 			}
18378 			rw_exit(&ire->ire_bucket->irb_lock);
18379 		}
18380 		mutex_exit(&connp->conn_lock);
18381 
18382 		/*
18383 		 * We can continue to use the ire but since it was
18384 		 * not cached, we should drop the extra reference.
18385 		 */
18386 		if (!cached)
18387 			IRE_REFRELE_NOTR(ire);
18388 
18389 		/*
18390 		 * Rampart note: no need to select a new label here, since
18391 		 * labels are not allowed to change during the life of a TCP
18392 		 * connection.
18393 		 */
18394 	}
18395 
18396 	*irep = ire;
18397 
18398 	return (B_TRUE);
18399 }
18400 
18401 /*
18402  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18403  *
18404  * 0 = success;
18405  * 1 = failed to find ire and ill.
18406  */
18407 static boolean_t
18408 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18409 {
18410 	ipha_t		*ipha;
18411 	ipaddr_t	dst;
18412 	ire_t		*ire;
18413 	ill_t		*ill;
18414 	mblk_t		*ire_fp_mp;
18415 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18416 
18417 	if (mp != NULL)
18418 		ipha = (ipha_t *)mp->b_rptr;
18419 	else
18420 		ipha = tcp->tcp_ipha;
18421 	dst = ipha->ipha_dst;
18422 
18423 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18424 		return (B_FALSE);
18425 
18426 	if ((ire->ire_flags & RTF_MULTIRT) ||
18427 	    (ire->ire_stq == NULL) ||
18428 	    (ire->ire_nce == NULL) ||
18429 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18430 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18431 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18432 		TCP_STAT(tcps, tcp_ip_ire_send);
18433 		IRE_REFRELE(ire);
18434 		return (B_FALSE);
18435 	}
18436 
18437 	ill = ire_to_ill(ire);
18438 	ASSERT(ill != NULL);
18439 
18440 	if (!tcp->tcp_ire_ill_check_done) {
18441 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18442 		tcp->tcp_ire_ill_check_done = B_TRUE;
18443 	}
18444 
18445 	*irep = ire;
18446 	*illp = ill;
18447 
18448 	return (B_TRUE);
18449 }
18450 
18451 static void
18452 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18453 {
18454 	ipha_t		*ipha;
18455 	ipaddr_t	src;
18456 	ipaddr_t	dst;
18457 	uint32_t	cksum;
18458 	ire_t		*ire;
18459 	uint16_t	*up;
18460 	ill_t		*ill;
18461 	conn_t		*connp = tcp->tcp_connp;
18462 	uint32_t	hcksum_txflags = 0;
18463 	mblk_t		*ire_fp_mp;
18464 	uint_t		ire_fp_mp_len;
18465 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18466 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18467 	cred_t		*cr;
18468 	pid_t		cpid;
18469 
18470 	ASSERT(DB_TYPE(mp) == M_DATA);
18471 
18472 	/*
18473 	 * Here we need to handle the overloading of the cred_t for
18474 	 * both getpeerucred and TX.
18475 	 * If this is a SYN then the caller already set db_credp so
18476 	 * that getpeerucred will work. But if TX is in use we might have
18477 	 * a conn_effective_cred which is different, and we need to use that
18478 	 * cred to make TX use the correct label and label dependent route.
18479 	 */
18480 	if (is_system_labeled()) {
18481 		cr = msg_getcred(mp, &cpid);
18482 		if (cr == NULL || connp->conn_effective_cred != NULL)
18483 			mblk_setcred(mp, CONN_CRED(connp), cpid);
18484 	}
18485 
18486 	ipha = (ipha_t *)mp->b_rptr;
18487 	src = ipha->ipha_src;
18488 	dst = ipha->ipha_dst;
18489 
18490 	ASSERT(q != NULL);
18491 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
18492 
18493 	/*
18494 	 * Drop off fast path for IPv6 and also if options are present or
18495 	 * we need to resolve a TS label.
18496 	 */
18497 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18498 	    !IPCL_IS_CONNECTED(connp) ||
18499 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18500 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18501 	    !connp->conn_ulp_labeled ||
18502 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18503 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18504 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18505 		if (tcp->tcp_snd_zcopy_aware)
18506 			mp = tcp_zcopy_disable(tcp, mp);
18507 		TCP_STAT(tcps, tcp_ip_send);
18508 		CALL_IP_WPUT(connp, q, mp);
18509 		return;
18510 	}
18511 
18512 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18513 		if (tcp->tcp_snd_zcopy_aware)
18514 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18515 		CALL_IP_WPUT(connp, q, mp);
18516 		return;
18517 	}
18518 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18519 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18520 
18521 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18522 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18523 #ifndef _BIG_ENDIAN
18524 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18525 #endif
18526 
18527 	/*
18528 	 * Check to see if we need to re-enable LSO/MDT for this connection
18529 	 * because it was previously disabled due to changes in the ill;
18530 	 * note that by doing it here, this re-enabling only applies when
18531 	 * the packet is not dispatched through CALL_IP_WPUT().
18532 	 *
18533 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18534 	 * case, since that's how we ended up here.  For IPv6, we do the
18535 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18536 	 */
18537 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18538 		/*
18539 		 * Restore LSO for this connection, so that next time around
18540 		 * it is eligible to go through tcp_lsosend() path again.
18541 		 */
18542 		TCP_STAT(tcps, tcp_lso_enabled);
18543 		tcp->tcp_lso = B_TRUE;
18544 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18545 		    "interface %s\n", (void *)connp, ill->ill_name));
18546 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18547 		/*
18548 		 * Restore MDT for this connection, so that next time around
18549 		 * it is eligible to go through tcp_multisend() path again.
18550 		 */
18551 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18552 		tcp->tcp_mdt = B_TRUE;
18553 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18554 		    "interface %s\n", (void *)connp, ill->ill_name));
18555 	}
18556 
18557 	if (tcp->tcp_snd_zcopy_aware) {
18558 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18559 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18560 			mp = tcp_zcopy_disable(tcp, mp);
18561 		/*
18562 		 * we shouldn't need to reset ipha as the mp containing
18563 		 * ipha should never be a zero-copy mp.
18564 		 */
18565 	}
18566 
18567 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18568 		ASSERT(ill->ill_hcksum_capab != NULL);
18569 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18570 	}
18571 
18572 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18573 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18574 
18575 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18576 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18577 
18578 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18579 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18580 
18581 	/* Software checksum? */
18582 	if (DB_CKSUMFLAGS(mp) == 0) {
18583 		TCP_STAT(tcps, tcp_out_sw_cksum);
18584 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18585 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18586 	}
18587 
18588 	/* Calculate IP header checksum if hardware isn't capable */
18589 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18590 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18591 		    ((uint16_t *)ipha)[4]);
18592 	}
18593 
18594 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18595 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18596 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18597 
18598 	UPDATE_OB_PKT_COUNT(ire);
18599 	ire->ire_last_used_time = lbolt;
18600 
18601 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18602 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18603 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18604 	    ntohs(ipha->ipha_length));
18605 
18606 	DTRACE_PROBE4(ip4__physical__out__start,
18607 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
18608 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
18609 	    ipst->ips_ipv4firewall_physical_out,
18610 	    NULL, ill, ipha, mp, mp, 0, ipst);
18611 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18612 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
18613 
18614 	if (mp != NULL) {
18615 		if (ipst->ips_ipobs_enabled) {
18616 			zoneid_t szone;
18617 
18618 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
18619 			    ipst, ALL_ZONES);
18620 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
18621 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
18622 		}
18623 
18624 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
18625 	}
18626 
18627 	IRE_REFRELE(ire);
18628 }
18629 
18630 /*
18631  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18632  * if the receiver shrinks the window, i.e. moves the right window to the
18633  * left, the we should not send new data, but should retransmit normally the
18634  * old unacked data between suna and suna + swnd. We might has sent data
18635  * that is now outside the new window, pretend that we didn't send  it.
18636  */
18637 static void
18638 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18639 {
18640 	uint32_t	snxt = tcp->tcp_snxt;
18641 	mblk_t		*xmit_tail;
18642 	int32_t		offset;
18643 
18644 	ASSERT(shrunk_count > 0);
18645 
18646 	/* Pretend we didn't send the data outside the window */
18647 	snxt -= shrunk_count;
18648 
18649 	/* Get the mblk and the offset in it per the shrunk window */
18650 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18651 
18652 	ASSERT(xmit_tail != NULL);
18653 
18654 	/* Reset all the values per the now shrunk window */
18655 	tcp->tcp_snxt = snxt;
18656 	tcp->tcp_xmit_tail = xmit_tail;
18657 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18658 	    offset;
18659 	tcp->tcp_unsent += shrunk_count;
18660 
18661 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18662 		/*
18663 		 * Make sure the timer is running so that we will probe a zero
18664 		 * window.
18665 		 */
18666 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18667 }
18668 
18669 
18670 /*
18671  * The TCP normal data output path.
18672  * NOTE: the logic of the fast path is duplicated from this function.
18673  */
18674 static void
18675 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18676 {
18677 	int		len;
18678 	mblk_t		*local_time;
18679 	mblk_t		*mp1;
18680 	uint32_t	snxt;
18681 	int		tail_unsent;
18682 	int		tcpstate;
18683 	int		usable = 0;
18684 	mblk_t		*xmit_tail;
18685 	queue_t		*q = tcp->tcp_wq;
18686 	int32_t		mss;
18687 	int32_t		num_sack_blk = 0;
18688 	int32_t		tcp_hdr_len;
18689 	int32_t		tcp_tcp_hdr_len;
18690 	int		mdt_thres;
18691 	int		rc;
18692 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18693 	ip_stack_t	*ipst;
18694 
18695 	tcpstate = tcp->tcp_state;
18696 	if (mp == NULL) {
18697 		/*
18698 		 * tcp_wput_data() with NULL mp should only be called when
18699 		 * there is unsent data.
18700 		 */
18701 		ASSERT(tcp->tcp_unsent > 0);
18702 		/* Really tacky... but we need this for detached closes. */
18703 		len = tcp->tcp_unsent;
18704 		goto data_null;
18705 	}
18706 
18707 #if CCS_STATS
18708 	wrw_stats.tot.count++;
18709 	wrw_stats.tot.bytes += msgdsize(mp);
18710 #endif
18711 	ASSERT(mp->b_datap->db_type == M_DATA);
18712 	/*
18713 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18714 	 * or before a connection attempt has begun.
18715 	 */
18716 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18717 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18718 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18719 #ifdef DEBUG
18720 			cmn_err(CE_WARN,
18721 			    "tcp_wput_data: data after ordrel, %s",
18722 			    tcp_display(tcp, NULL,
18723 			    DISP_ADDR_AND_PORT));
18724 #else
18725 			if (tcp->tcp_debug) {
18726 				(void) strlog(TCP_MOD_ID, 0, 1,
18727 				    SL_TRACE|SL_ERROR,
18728 				    "tcp_wput_data: data after ordrel, %s\n",
18729 				    tcp_display(tcp, NULL,
18730 				    DISP_ADDR_AND_PORT));
18731 			}
18732 #endif /* DEBUG */
18733 		}
18734 		if (tcp->tcp_snd_zcopy_aware &&
18735 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18736 			tcp_zcopy_notify(tcp);
18737 		freemsg(mp);
18738 		mutex_enter(&tcp->tcp_non_sq_lock);
18739 		if (tcp->tcp_flow_stopped &&
18740 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18741 			tcp_clrqfull(tcp);
18742 		}
18743 		mutex_exit(&tcp->tcp_non_sq_lock);
18744 		return;
18745 	}
18746 
18747 	/* Strip empties */
18748 	for (;;) {
18749 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18750 		    (uintptr_t)INT_MAX);
18751 		len = (int)(mp->b_wptr - mp->b_rptr);
18752 		if (len > 0)
18753 			break;
18754 		mp1 = mp;
18755 		mp = mp->b_cont;
18756 		freeb(mp1);
18757 		if (!mp) {
18758 			return;
18759 		}
18760 	}
18761 
18762 	/* If we are the first on the list ... */
18763 	if (tcp->tcp_xmit_head == NULL) {
18764 		tcp->tcp_xmit_head = mp;
18765 		tcp->tcp_xmit_tail = mp;
18766 		tcp->tcp_xmit_tail_unsent = len;
18767 	} else {
18768 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18769 		struct datab *dp;
18770 
18771 		mp1 = tcp->tcp_xmit_last;
18772 		if (len < tcp_tx_pull_len &&
18773 		    (dp = mp1->b_datap)->db_ref == 1 &&
18774 		    dp->db_lim - mp1->b_wptr >= len) {
18775 			ASSERT(len > 0);
18776 			ASSERT(!mp1->b_cont);
18777 			if (len == 1) {
18778 				*mp1->b_wptr++ = *mp->b_rptr;
18779 			} else {
18780 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18781 				mp1->b_wptr += len;
18782 			}
18783 			if (mp1 == tcp->tcp_xmit_tail)
18784 				tcp->tcp_xmit_tail_unsent += len;
18785 			mp1->b_cont = mp->b_cont;
18786 			if (tcp->tcp_snd_zcopy_aware &&
18787 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18788 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18789 			freeb(mp);
18790 			mp = mp1;
18791 		} else {
18792 			tcp->tcp_xmit_last->b_cont = mp;
18793 		}
18794 		len += tcp->tcp_unsent;
18795 	}
18796 
18797 	/* Tack on however many more positive length mblks we have */
18798 	if ((mp1 = mp->b_cont) != NULL) {
18799 		do {
18800 			int tlen;
18801 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18802 			    (uintptr_t)INT_MAX);
18803 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18804 			if (tlen <= 0) {
18805 				mp->b_cont = mp1->b_cont;
18806 				freeb(mp1);
18807 			} else {
18808 				len += tlen;
18809 				mp = mp1;
18810 			}
18811 		} while ((mp1 = mp->b_cont) != NULL);
18812 	}
18813 	tcp->tcp_xmit_last = mp;
18814 	tcp->tcp_unsent = len;
18815 
18816 	if (urgent)
18817 		usable = 1;
18818 
18819 data_null:
18820 	snxt = tcp->tcp_snxt;
18821 	xmit_tail = tcp->tcp_xmit_tail;
18822 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18823 
18824 	/*
18825 	 * Note that tcp_mss has been adjusted to take into account the
18826 	 * timestamp option if applicable.  Because SACK options do not
18827 	 * appear in every TCP segments and they are of variable lengths,
18828 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18829 	 * the actual segment length when we need to send a segment which
18830 	 * includes SACK options.
18831 	 */
18832 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18833 		int32_t	opt_len;
18834 
18835 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18836 		    tcp->tcp_num_sack_blk);
18837 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18838 		    2 + TCPOPT_HEADER_LEN;
18839 		mss = tcp->tcp_mss - opt_len;
18840 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18841 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18842 	} else {
18843 		mss = tcp->tcp_mss;
18844 		tcp_hdr_len = tcp->tcp_hdr_len;
18845 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18846 	}
18847 
18848 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18849 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18850 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18851 	}
18852 	if (tcpstate == TCPS_SYN_RCVD) {
18853 		/*
18854 		 * The three-way connection establishment handshake is not
18855 		 * complete yet. We want to queue the data for transmission
18856 		 * after entering ESTABLISHED state (RFC793). A jump to
18857 		 * "done" label effectively leaves data on the queue.
18858 		 */
18859 		goto done;
18860 	} else {
18861 		int usable_r;
18862 
18863 		/*
18864 		 * In the special case when cwnd is zero, which can only
18865 		 * happen if the connection is ECN capable, return now.
18866 		 * New segments is sent using tcp_timer().  The timer
18867 		 * is set in tcp_rput_data().
18868 		 */
18869 		if (tcp->tcp_cwnd == 0) {
18870 			/*
18871 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18872 			 * finished.
18873 			 */
18874 			ASSERT(tcp->tcp_ecn_ok ||
18875 			    tcp->tcp_state < TCPS_ESTABLISHED);
18876 			return;
18877 		}
18878 
18879 		/* NOTE: trouble if xmitting while SYN not acked? */
18880 		usable_r = snxt - tcp->tcp_suna;
18881 		usable_r = tcp->tcp_swnd - usable_r;
18882 
18883 		/*
18884 		 * Check if the receiver has shrunk the window.  If
18885 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18886 		 * cannot be set as there is unsent data, so FIN cannot
18887 		 * be sent out.  Otherwise, we need to take into account
18888 		 * of FIN as it consumes an "invisible" sequence number.
18889 		 */
18890 		ASSERT(tcp->tcp_fin_sent == 0);
18891 		if (usable_r < 0) {
18892 			/*
18893 			 * The receiver has shrunk the window and we have sent
18894 			 * -usable_r date beyond the window, re-adjust.
18895 			 *
18896 			 * If TCP window scaling is enabled, there can be
18897 			 * round down error as the advertised receive window
18898 			 * is actually right shifted n bits.  This means that
18899 			 * the lower n bits info is wiped out.  It will look
18900 			 * like the window is shrunk.  Do a check here to
18901 			 * see if the shrunk amount is actually within the
18902 			 * error in window calculation.  If it is, just
18903 			 * return.  Note that this check is inside the
18904 			 * shrunk window check.  This makes sure that even
18905 			 * though tcp_process_shrunk_swnd() is not called,
18906 			 * we will stop further processing.
18907 			 */
18908 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18909 				tcp_process_shrunk_swnd(tcp, -usable_r);
18910 			}
18911 			return;
18912 		}
18913 
18914 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18915 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18916 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18917 
18918 		/* usable = MIN(usable, unsent) */
18919 		if (usable_r > len)
18920 			usable_r = len;
18921 
18922 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18923 		if (usable_r > 0) {
18924 			usable = usable_r;
18925 		} else {
18926 			/* Bypass all other unnecessary processing. */
18927 			goto done;
18928 		}
18929 	}
18930 
18931 	local_time = (mblk_t *)lbolt;
18932 
18933 	/*
18934 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18935 	 * BSD.  This is more in line with the true intent of Nagle.
18936 	 *
18937 	 * The conditions are:
18938 	 * 1. The amount of unsent data (or amount of data which can be
18939 	 *    sent, whichever is smaller) is less than Nagle limit.
18940 	 * 2. The last sent size is also less than Nagle limit.
18941 	 * 3. There is unack'ed data.
18942 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18943 	 *    Nagle algorithm.  This reduces the probability that urgent
18944 	 *    bytes get "merged" together.
18945 	 * 5. The app has not closed the connection.  This eliminates the
18946 	 *    wait time of the receiving side waiting for the last piece of
18947 	 *    (small) data.
18948 	 *
18949 	 * If all are satisified, exit without sending anything.  Note
18950 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18951 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18952 	 * 4095).
18953 	 */
18954 	if (usable < (int)tcp->tcp_naglim &&
18955 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18956 	    snxt != tcp->tcp_suna &&
18957 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18958 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18959 		goto done;
18960 	}
18961 
18962 	/*
18963 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
18964 	 * is set, then we have to force TCP not to send partial segment
18965 	 * (smaller than MSS bytes). We are calculating the usable now
18966 	 * based on full mss and will save the rest of remaining data for
18967 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
18968 	 * something to do zero window probe.
18969 	 */
18970 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
18971 		if (usable < mss)
18972 			goto done;
18973 		usable = (usable / mss) * mss;
18974 	}
18975 
18976 	/* Update the latest receive window size in TCP header. */
18977 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18978 	    tcp->tcp_tcph->th_win);
18979 
18980 	/*
18981 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
18982 	 *
18983 	 * 1. Simple TCP/IP{v4,v6} (no options).
18984 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18985 	 * 3. If the TCP connection is in ESTABLISHED state.
18986 	 * 4. The TCP is not detached.
18987 	 *
18988 	 * If any of the above conditions have changed during the
18989 	 * connection, stop using LSO/MDT and restore the stream head
18990 	 * parameters accordingly.
18991 	 */
18992 	ipst = tcps->tcps_netstack->netstack_ip;
18993 
18994 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
18995 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
18996 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
18997 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18998 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
18999 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19000 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19001 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19002 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19003 		if (tcp->tcp_lso) {
19004 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19005 			tcp->tcp_lso = B_FALSE;
19006 		} else {
19007 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19008 			tcp->tcp_mdt = B_FALSE;
19009 		}
19010 
19011 		/* Anything other than detached is considered pathological */
19012 		if (!TCP_IS_DETACHED(tcp)) {
19013 			if (tcp->tcp_lso)
19014 				TCP_STAT(tcps, tcp_lso_disabled);
19015 			else
19016 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19017 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19018 		}
19019 	}
19020 
19021 	/* Use MDT if sendable amount is greater than the threshold */
19022 	if (tcp->tcp_mdt &&
19023 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19024 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19025 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19026 	    (tcp->tcp_valid_bits == 0 ||
19027 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19028 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19029 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19030 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19031 		    local_time, mdt_thres);
19032 	} else {
19033 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19034 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19035 		    local_time, INT_MAX);
19036 	}
19037 
19038 	/* Pretend that all we were trying to send really got sent */
19039 	if (rc < 0 && tail_unsent < 0) {
19040 		do {
19041 			xmit_tail = xmit_tail->b_cont;
19042 			xmit_tail->b_prev = local_time;
19043 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19044 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19045 			tail_unsent += (int)(xmit_tail->b_wptr -
19046 			    xmit_tail->b_rptr);
19047 		} while (tail_unsent < 0);
19048 	}
19049 done:;
19050 	tcp->tcp_xmit_tail = xmit_tail;
19051 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19052 	len = tcp->tcp_snxt - snxt;
19053 	if (len) {
19054 		/*
19055 		 * If new data was sent, need to update the notsack
19056 		 * list, which is, afterall, data blocks that have
19057 		 * not been sack'ed by the receiver.  New data is
19058 		 * not sack'ed.
19059 		 */
19060 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19061 			/* len is a negative value. */
19062 			tcp->tcp_pipe -= len;
19063 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19064 			    tcp->tcp_snxt, snxt,
19065 			    &(tcp->tcp_num_notsack_blk),
19066 			    &(tcp->tcp_cnt_notsack_list));
19067 		}
19068 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19069 		tcp->tcp_rack = tcp->tcp_rnxt;
19070 		tcp->tcp_rack_cnt = 0;
19071 		if ((snxt + len) == tcp->tcp_suna) {
19072 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19073 		}
19074 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19075 		/*
19076 		 * Didn't send anything. Make sure the timer is running
19077 		 * so that we will probe a zero window.
19078 		 */
19079 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19080 	}
19081 	/* Note that len is the amount we just sent but with a negative sign */
19082 	tcp->tcp_unsent += len;
19083 	mutex_enter(&tcp->tcp_non_sq_lock);
19084 	if (tcp->tcp_flow_stopped) {
19085 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19086 			tcp_clrqfull(tcp);
19087 		}
19088 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19089 		tcp_setqfull(tcp);
19090 	}
19091 	mutex_exit(&tcp->tcp_non_sq_lock);
19092 }
19093 
19094 /*
19095  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19096  * outgoing TCP header with the template header, as well as other
19097  * options such as time-stamp, ECN and/or SACK.
19098  */
19099 static void
19100 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19101 {
19102 	tcph_t *tcp_tmpl, *tcp_h;
19103 	uint32_t *dst, *src;
19104 	int hdrlen;
19105 
19106 	ASSERT(OK_32PTR(rptr));
19107 
19108 	/* Template header */
19109 	tcp_tmpl = tcp->tcp_tcph;
19110 
19111 	/* Header of outgoing packet */
19112 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19113 
19114 	/* dst and src are opaque 32-bit fields, used for copying */
19115 	dst = (uint32_t *)rptr;
19116 	src = (uint32_t *)tcp->tcp_iphc;
19117 	hdrlen = tcp->tcp_hdr_len;
19118 
19119 	/* Fill time-stamp option if needed */
19120 	if (tcp->tcp_snd_ts_ok) {
19121 		U32_TO_BE32((uint32_t)now,
19122 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19123 		U32_TO_BE32(tcp->tcp_ts_recent,
19124 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19125 	} else {
19126 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19127 	}
19128 
19129 	/*
19130 	 * Copy the template header; is this really more efficient than
19131 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19132 	 * but perhaps not for other scenarios.
19133 	 */
19134 	dst[0] = src[0];
19135 	dst[1] = src[1];
19136 	dst[2] = src[2];
19137 	dst[3] = src[3];
19138 	dst[4] = src[4];
19139 	dst[5] = src[5];
19140 	dst[6] = src[6];
19141 	dst[7] = src[7];
19142 	dst[8] = src[8];
19143 	dst[9] = src[9];
19144 	if (hdrlen -= 40) {
19145 		hdrlen >>= 2;
19146 		dst += 10;
19147 		src += 10;
19148 		do {
19149 			*dst++ = *src++;
19150 		} while (--hdrlen);
19151 	}
19152 
19153 	/*
19154 	 * Set the ECN info in the TCP header if it is not a zero
19155 	 * window probe.  Zero window probe is only sent in
19156 	 * tcp_wput_data() and tcp_timer().
19157 	 */
19158 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19159 		SET_ECT(tcp, rptr);
19160 
19161 		if (tcp->tcp_ecn_echo_on)
19162 			tcp_h->th_flags[0] |= TH_ECE;
19163 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19164 			tcp_h->th_flags[0] |= TH_CWR;
19165 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19166 		}
19167 	}
19168 
19169 	/* Fill in SACK options */
19170 	if (num_sack_blk > 0) {
19171 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19172 		sack_blk_t *tmp;
19173 		int32_t	i;
19174 
19175 		wptr[0] = TCPOPT_NOP;
19176 		wptr[1] = TCPOPT_NOP;
19177 		wptr[2] = TCPOPT_SACK;
19178 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19179 		    sizeof (sack_blk_t);
19180 		wptr += TCPOPT_REAL_SACK_LEN;
19181 
19182 		tmp = tcp->tcp_sack_list;
19183 		for (i = 0; i < num_sack_blk; i++) {
19184 			U32_TO_BE32(tmp[i].begin, wptr);
19185 			wptr += sizeof (tcp_seq);
19186 			U32_TO_BE32(tmp[i].end, wptr);
19187 			wptr += sizeof (tcp_seq);
19188 		}
19189 		tcp_h->th_offset_and_rsrvd[0] +=
19190 		    ((num_sack_blk * 2 + 1) << 4);
19191 	}
19192 }
19193 
19194 /*
19195  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19196  * the destination address and SAP attribute, and if necessary, the
19197  * hardware checksum offload attribute to a Multidata message.
19198  */
19199 static int
19200 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19201     const uint32_t start, const uint32_t stuff, const uint32_t end,
19202     const uint32_t flags, tcp_stack_t *tcps)
19203 {
19204 	/* Add global destination address & SAP attribute */
19205 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19206 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19207 		    "destination address+SAP\n"));
19208 
19209 		if (dlmp != NULL)
19210 			TCP_STAT(tcps, tcp_mdt_allocfail);
19211 		return (-1);
19212 	}
19213 
19214 	/* Add global hwcksum attribute */
19215 	if (hwcksum &&
19216 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19217 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19218 		    "checksum attribute\n"));
19219 
19220 		TCP_STAT(tcps, tcp_mdt_allocfail);
19221 		return (-1);
19222 	}
19223 
19224 	return (0);
19225 }
19226 
19227 /*
19228  * Smaller and private version of pdescinfo_t used specifically for TCP,
19229  * which allows for only two payload spans per packet.
19230  */
19231 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19232 
19233 /*
19234  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19235  * scheme, and returns one the following:
19236  *
19237  * -1 = failed allocation.
19238  *  0 = success; burst count reached, or usable send window is too small,
19239  *      and that we'd rather wait until later before sending again.
19240  */
19241 static int
19242 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19243     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19244     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19245     const int mdt_thres)
19246 {
19247 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19248 	multidata_t	*mmd;
19249 	uint_t		obsegs, obbytes, hdr_frag_sz;
19250 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19251 	int		num_burst_seg, max_pld;
19252 	pdesc_t		*pkt;
19253 	tcp_pdescinfo_t	tcp_pkt_info;
19254 	pdescinfo_t	*pkt_info;
19255 	int		pbuf_idx, pbuf_idx_nxt;
19256 	int		seg_len, len, spill, af;
19257 	boolean_t	add_buffer, zcopy, clusterwide;
19258 	boolean_t	rconfirm = B_FALSE;
19259 	boolean_t	done = B_FALSE;
19260 	uint32_t	cksum;
19261 	uint32_t	hwcksum_flags;
19262 	ire_t		*ire = NULL;
19263 	ill_t		*ill;
19264 	ipha_t		*ipha;
19265 	ip6_t		*ip6h;
19266 	ipaddr_t	src, dst;
19267 	ill_zerocopy_capab_t *zc_cap = NULL;
19268 	uint16_t	*up;
19269 	int		err;
19270 	conn_t		*connp;
19271 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19272 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19273 	int		usable_mmd, tail_unsent_mmd;
19274 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19275 	mblk_t		*xmit_tail_mmd;
19276 	netstackid_t	stack_id;
19277 
19278 #ifdef	_BIG_ENDIAN
19279 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19280 #else
19281 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19282 #endif
19283 
19284 #define	PREP_NEW_MULTIDATA() {			\
19285 	mmd = NULL;				\
19286 	md_mp = md_hbuf = NULL;			\
19287 	cur_hdr_off = 0;			\
19288 	max_pld = tcp->tcp_mdt_max_pld;		\
19289 	pbuf_idx = pbuf_idx_nxt = -1;		\
19290 	add_buffer = B_TRUE;			\
19291 	zcopy = B_FALSE;			\
19292 }
19293 
19294 #define	PREP_NEW_PBUF() {			\
19295 	md_pbuf = md_pbuf_nxt = NULL;		\
19296 	pbuf_idx = pbuf_idx_nxt = -1;		\
19297 	cur_pld_off = 0;			\
19298 	first_snxt = *snxt;			\
19299 	ASSERT(*tail_unsent > 0);		\
19300 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19301 }
19302 
19303 	ASSERT(mdt_thres >= mss);
19304 	ASSERT(*usable > 0 && *usable > mdt_thres);
19305 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19306 	ASSERT(!TCP_IS_DETACHED(tcp));
19307 	ASSERT(tcp->tcp_valid_bits == 0 ||
19308 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19309 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19310 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19311 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19312 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19313 
19314 	connp = tcp->tcp_connp;
19315 	ASSERT(connp != NULL);
19316 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19317 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19318 
19319 	stack_id = connp->conn_netstack->netstack_stackid;
19320 
19321 	usable_mmd = tail_unsent_mmd = 0;
19322 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
19323 	xmit_tail_mmd = NULL;
19324 	/*
19325 	 * Note that tcp will only declare at most 2 payload spans per
19326 	 * packet, which is much lower than the maximum allowable number
19327 	 * of packet spans per Multidata.  For this reason, we use the
19328 	 * privately declared and smaller descriptor info structure, in
19329 	 * order to save some stack space.
19330 	 */
19331 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19332 
19333 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19334 	if (af == AF_INET) {
19335 		dst = tcp->tcp_ipha->ipha_dst;
19336 		src = tcp->tcp_ipha->ipha_src;
19337 		ASSERT(!CLASSD(dst));
19338 	}
19339 	ASSERT(af == AF_INET ||
19340 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19341 
19342 	obsegs = obbytes = 0;
19343 	num_burst_seg = tcp->tcp_snd_burst;
19344 	md_mp_head = NULL;
19345 	PREP_NEW_MULTIDATA();
19346 
19347 	/*
19348 	 * Before we go on further, make sure there is an IRE that we can
19349 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19350 	 * in proceeding any further, and we should just hand everything
19351 	 * off to the legacy path.
19352 	 */
19353 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19354 		goto legacy_send_no_md;
19355 
19356 	ASSERT(ire != NULL);
19357 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19358 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19359 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19360 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19361 	/*
19362 	 * If we do support loopback for MDT (which requires modifications
19363 	 * to the receiving paths), the following assertions should go away,
19364 	 * and we would be sending the Multidata to loopback conn later on.
19365 	 */
19366 	ASSERT(!IRE_IS_LOCAL(ire));
19367 	ASSERT(ire->ire_stq != NULL);
19368 
19369 	ill = ire_to_ill(ire);
19370 	ASSERT(ill != NULL);
19371 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19372 
19373 	if (!tcp->tcp_ire_ill_check_done) {
19374 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19375 		tcp->tcp_ire_ill_check_done = B_TRUE;
19376 	}
19377 
19378 	/*
19379 	 * If the underlying interface conditions have changed, or if the
19380 	 * new interface does not support MDT, go back to legacy path.
19381 	 */
19382 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19383 		/* don't go through this path anymore for this connection */
19384 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19385 		tcp->tcp_mdt = B_FALSE;
19386 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19387 		    "interface %s\n", (void *)connp, ill->ill_name));
19388 		/* IRE will be released prior to returning */
19389 		goto legacy_send_no_md;
19390 	}
19391 
19392 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19393 		zc_cap = ill->ill_zerocopy_capab;
19394 
19395 	/*
19396 	 * Check if we can take tcp fast-path. Note that "incomplete"
19397 	 * ire's (where the link-layer for next hop is not resolved
19398 	 * or where the fast-path header in nce_fp_mp is not available
19399 	 * yet) are sent down the legacy (slow) path.
19400 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19401 	 */
19402 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19403 		/* IRE will be released prior to returning */
19404 		goto legacy_send_no_md;
19405 	}
19406 
19407 	/* go to legacy path if interface doesn't support zerocopy */
19408 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19409 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19410 		/* IRE will be released prior to returning */
19411 		goto legacy_send_no_md;
19412 	}
19413 
19414 	/* does the interface support hardware checksum offload? */
19415 	hwcksum_flags = 0;
19416 	if (ILL_HCKSUM_CAPABLE(ill) &&
19417 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19418 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19419 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19420 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19421 		    HCKSUM_IPHDRCKSUM)
19422 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19423 
19424 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19425 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19426 			hwcksum_flags |= HCK_FULLCKSUM;
19427 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19428 		    HCKSUM_INET_PARTIAL)
19429 			hwcksum_flags |= HCK_PARTIALCKSUM;
19430 	}
19431 
19432 	/*
19433 	 * Each header fragment consists of the leading extra space,
19434 	 * followed by the TCP/IP header, and the trailing extra space.
19435 	 * We make sure that each header fragment begins on a 32-bit
19436 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19437 	 * aligned in tcp_mdt_update).
19438 	 */
19439 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19440 	    tcp->tcp_mdt_hdr_tail), 4);
19441 
19442 	/* are we starting from the beginning of data block? */
19443 	if (*tail_unsent == 0) {
19444 		*xmit_tail = (*xmit_tail)->b_cont;
19445 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19446 		*tail_unsent = (int)MBLKL(*xmit_tail);
19447 	}
19448 
19449 	/*
19450 	 * Here we create one or more Multidata messages, each made up of
19451 	 * one header buffer and up to N payload buffers.  This entire
19452 	 * operation is done within two loops:
19453 	 *
19454 	 * The outer loop mostly deals with creating the Multidata message,
19455 	 * as well as the header buffer that gets added to it.  It also
19456 	 * links the Multidata messages together such that all of them can
19457 	 * be sent down to the lower layer in a single putnext call; this
19458 	 * linking behavior depends on the tcp_mdt_chain tunable.
19459 	 *
19460 	 * The inner loop takes an existing Multidata message, and adds
19461 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19462 	 * packetizes those buffers by filling up the corresponding header
19463 	 * buffer fragments with the proper IP and TCP headers, and by
19464 	 * describing the layout of each packet in the packet descriptors
19465 	 * that get added to the Multidata.
19466 	 */
19467 	do {
19468 		/*
19469 		 * If usable send window is too small, or data blocks in
19470 		 * transmit list are smaller than our threshold (i.e. app
19471 		 * performs large writes followed by small ones), we hand
19472 		 * off the control over to the legacy path.  Note that we'll
19473 		 * get back the control once it encounters a large block.
19474 		 */
19475 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19476 		    (*xmit_tail)->b_cont != NULL &&
19477 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19478 			/* send down what we've got so far */
19479 			if (md_mp_head != NULL) {
19480 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19481 				    obsegs, obbytes, &rconfirm);
19482 			}
19483 			/*
19484 			 * Pass control over to tcp_send(), but tell it to
19485 			 * return to us once a large-size transmission is
19486 			 * possible.
19487 			 */
19488 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19489 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19490 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19491 			    tail_unsent, xmit_tail, local_time,
19492 			    mdt_thres)) <= 0) {
19493 				/* burst count reached, or alloc failed */
19494 				IRE_REFRELE(ire);
19495 				return (err);
19496 			}
19497 
19498 			/* tcp_send() may have sent everything, so check */
19499 			if (*usable <= 0) {
19500 				IRE_REFRELE(ire);
19501 				return (0);
19502 			}
19503 
19504 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19505 			/*
19506 			 * We may have delivered the Multidata, so make sure
19507 			 * to re-initialize before the next round.
19508 			 */
19509 			md_mp_head = NULL;
19510 			obsegs = obbytes = 0;
19511 			num_burst_seg = tcp->tcp_snd_burst;
19512 			PREP_NEW_MULTIDATA();
19513 
19514 			/* are we starting from the beginning of data block? */
19515 			if (*tail_unsent == 0) {
19516 				*xmit_tail = (*xmit_tail)->b_cont;
19517 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19518 				    (uintptr_t)INT_MAX);
19519 				*tail_unsent = (int)MBLKL(*xmit_tail);
19520 			}
19521 		}
19522 		/*
19523 		 * Record current values for parameters we may need to pass
19524 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
19525 		 * each iteration of the outer loop (each multidata message
19526 		 * creation). If we have a failure in the inner loop, we send
19527 		 * any complete multidata messages we have before reverting
19528 		 * to using the traditional non-md path.
19529 		 */
19530 		snxt_mmd = *snxt;
19531 		usable_mmd = *usable;
19532 		xmit_tail_mmd = *xmit_tail;
19533 		tail_unsent_mmd = *tail_unsent;
19534 		obsegs_mmd = obsegs;
19535 		obbytes_mmd = obbytes;
19536 
19537 		/*
19538 		 * max_pld limits the number of mblks in tcp's transmit
19539 		 * queue that can be added to a Multidata message.  Once
19540 		 * this counter reaches zero, no more additional mblks
19541 		 * can be added to it.  What happens afterwards depends
19542 		 * on whether or not we are set to chain the Multidata
19543 		 * messages.  If we are to link them together, reset
19544 		 * max_pld to its original value (tcp_mdt_max_pld) and
19545 		 * prepare to create a new Multidata message which will
19546 		 * get linked to md_mp_head.  Else, leave it alone and
19547 		 * let the inner loop break on its own.
19548 		 */
19549 		if (tcp_mdt_chain && max_pld == 0)
19550 			PREP_NEW_MULTIDATA();
19551 
19552 		/* adding a payload buffer; re-initialize values */
19553 		if (add_buffer)
19554 			PREP_NEW_PBUF();
19555 
19556 		/*
19557 		 * If we don't have a Multidata, either because we just
19558 		 * (re)entered this outer loop, or after we branched off
19559 		 * to tcp_send above, setup the Multidata and header
19560 		 * buffer to be used.
19561 		 */
19562 		if (md_mp == NULL) {
19563 			int md_hbuflen;
19564 			uint32_t start, stuff;
19565 
19566 			/*
19567 			 * Calculate Multidata header buffer size large enough
19568 			 * to hold all of the headers that can possibly be
19569 			 * sent at this moment.  We'd rather over-estimate
19570 			 * the size than running out of space; this is okay
19571 			 * since this buffer is small anyway.
19572 			 */
19573 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19574 
19575 			/*
19576 			 * Start and stuff offset for partial hardware
19577 			 * checksum offload; these are currently for IPv4.
19578 			 * For full checksum offload, they are set to zero.
19579 			 */
19580 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19581 				if (af == AF_INET) {
19582 					start = IP_SIMPLE_HDR_LENGTH;
19583 					stuff = IP_SIMPLE_HDR_LENGTH +
19584 					    TCP_CHECKSUM_OFFSET;
19585 				} else {
19586 					start = IPV6_HDR_LEN;
19587 					stuff = IPV6_HDR_LEN +
19588 					    TCP_CHECKSUM_OFFSET;
19589 				}
19590 			} else {
19591 				start = stuff = 0;
19592 			}
19593 
19594 			/*
19595 			 * Create the header buffer, Multidata, as well as
19596 			 * any necessary attributes (destination address,
19597 			 * SAP and hardware checksum offload) that should
19598 			 * be associated with the Multidata message.
19599 			 */
19600 			ASSERT(cur_hdr_off == 0);
19601 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19602 			    ((md_hbuf->b_wptr += md_hbuflen),
19603 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19604 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19605 			    /* fastpath mblk */
19606 			    ire->ire_nce->nce_res_mp,
19607 			    /* hardware checksum enabled */
19608 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19609 			    /* hardware checksum offsets */
19610 			    start, stuff, 0,
19611 			    /* hardware checksum flag */
19612 			    hwcksum_flags, tcps) != 0)) {
19613 legacy_send:
19614 				/*
19615 				 * We arrive here from a failure within the
19616 				 * inner (packetizer) loop or we fail one of
19617 				 * the conditionals above. We restore the
19618 				 * previously checkpointed values for:
19619 				 *    xmit_tail
19620 				 *    usable
19621 				 *    tail_unsent
19622 				 *    snxt
19623 				 *    obbytes
19624 				 *    obsegs
19625 				 * We should then be able to dispatch any
19626 				 * complete multidata before reverting to the
19627 				 * traditional path with consistent parameters
19628 				 * (the inner loop updates these as it
19629 				 * iterates).
19630 				 */
19631 				*xmit_tail = xmit_tail_mmd;
19632 				*usable = usable_mmd;
19633 				*tail_unsent = tail_unsent_mmd;
19634 				*snxt = snxt_mmd;
19635 				obbytes = obbytes_mmd;
19636 				obsegs = obsegs_mmd;
19637 				if (md_mp != NULL) {
19638 					/* Unlink message from the chain */
19639 					if (md_mp_head != NULL) {
19640 						err = (intptr_t)rmvb(md_mp_head,
19641 						    md_mp);
19642 						/*
19643 						 * We can't assert that rmvb
19644 						 * did not return -1, since we
19645 						 * may get here before linkb
19646 						 * happens.  We do, however,
19647 						 * check if we just removed the
19648 						 * only element in the list.
19649 						 */
19650 						if (err == 0)
19651 							md_mp_head = NULL;
19652 					}
19653 					/* md_hbuf gets freed automatically */
19654 					TCP_STAT(tcps, tcp_mdt_discarded);
19655 					freeb(md_mp);
19656 				} else {
19657 					/* Either allocb or mmd_alloc failed */
19658 					TCP_STAT(tcps, tcp_mdt_allocfail);
19659 					if (md_hbuf != NULL)
19660 						freeb(md_hbuf);
19661 				}
19662 
19663 				/* send down what we've got so far */
19664 				if (md_mp_head != NULL) {
19665 					tcp_multisend_data(tcp, ire, ill,
19666 					    md_mp_head, obsegs, obbytes,
19667 					    &rconfirm);
19668 				}
19669 legacy_send_no_md:
19670 				if (ire != NULL)
19671 					IRE_REFRELE(ire);
19672 				/*
19673 				 * Too bad; let the legacy path handle this.
19674 				 * We specify INT_MAX for the threshold, since
19675 				 * we gave up with the Multidata processings
19676 				 * and let the old path have it all.
19677 				 */
19678 				TCP_STAT(tcps, tcp_mdt_legacy_all);
19679 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19680 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19681 				    snxt, tail_unsent, xmit_tail, local_time,
19682 				    INT_MAX));
19683 			}
19684 
19685 			/* link to any existing ones, if applicable */
19686 			TCP_STAT(tcps, tcp_mdt_allocd);
19687 			if (md_mp_head == NULL) {
19688 				md_mp_head = md_mp;
19689 			} else if (tcp_mdt_chain) {
19690 				TCP_STAT(tcps, tcp_mdt_linked);
19691 				linkb(md_mp_head, md_mp);
19692 			}
19693 		}
19694 
19695 		ASSERT(md_mp_head != NULL);
19696 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19697 		ASSERT(md_mp != NULL && mmd != NULL);
19698 		ASSERT(md_hbuf != NULL);
19699 
19700 		/*
19701 		 * Packetize the transmittable portion of the data block;
19702 		 * each data block is essentially added to the Multidata
19703 		 * as a payload buffer.  We also deal with adding more
19704 		 * than one payload buffers, which happens when the remaining
19705 		 * packetized portion of the current payload buffer is less
19706 		 * than MSS, while the next data block in transmit queue
19707 		 * has enough data to make up for one.  This "spillover"
19708 		 * case essentially creates a split-packet, where portions
19709 		 * of the packet's payload fragments may span across two
19710 		 * virtually discontiguous address blocks.
19711 		 */
19712 		seg_len = mss;
19713 		do {
19714 			len = seg_len;
19715 
19716 			/* one must remain NULL for DTRACE_IP_FASTPATH */
19717 			ipha = NULL;
19718 			ip6h = NULL;
19719 
19720 			ASSERT(len > 0);
19721 			ASSERT(max_pld >= 0);
19722 			ASSERT(!add_buffer || cur_pld_off == 0);
19723 
19724 			/*
19725 			 * First time around for this payload buffer; note
19726 			 * in the case of a spillover, the following has
19727 			 * been done prior to adding the split-packet
19728 			 * descriptor to Multidata, and we don't want to
19729 			 * repeat the process.
19730 			 */
19731 			if (add_buffer) {
19732 				ASSERT(mmd != NULL);
19733 				ASSERT(md_pbuf == NULL);
19734 				ASSERT(md_pbuf_nxt == NULL);
19735 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19736 
19737 				/*
19738 				 * Have we reached the limit?  We'd get to
19739 				 * this case when we're not chaining the
19740 				 * Multidata messages together, and since
19741 				 * we're done, terminate this loop.
19742 				 */
19743 				if (max_pld == 0)
19744 					break; /* done */
19745 
19746 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19747 					TCP_STAT(tcps, tcp_mdt_allocfail);
19748 					goto legacy_send; /* out_of_mem */
19749 				}
19750 
19751 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19752 				    zc_cap != NULL) {
19753 					if (!ip_md_zcopy_attr(mmd, NULL,
19754 					    zc_cap->ill_zerocopy_flags)) {
19755 						freeb(md_pbuf);
19756 						TCP_STAT(tcps,
19757 						    tcp_mdt_allocfail);
19758 						/* out_of_mem */
19759 						goto legacy_send;
19760 					}
19761 					zcopy = B_TRUE;
19762 				}
19763 
19764 				md_pbuf->b_rptr += base_pld_off;
19765 
19766 				/*
19767 				 * Add a payload buffer to the Multidata; this
19768 				 * operation must not fail, or otherwise our
19769 				 * logic in this routine is broken.  There
19770 				 * is no memory allocation done by the
19771 				 * routine, so any returned failure simply
19772 				 * tells us that we've done something wrong.
19773 				 *
19774 				 * A failure tells us that either we're adding
19775 				 * the same payload buffer more than once, or
19776 				 * we're trying to add more buffers than
19777 				 * allowed (max_pld calculation is wrong).
19778 				 * None of the above cases should happen, and
19779 				 * we panic because either there's horrible
19780 				 * heap corruption, and/or programming mistake.
19781 				 */
19782 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19783 				if (pbuf_idx < 0) {
19784 					cmn_err(CE_PANIC, "tcp_multisend: "
19785 					    "payload buffer logic error "
19786 					    "detected for tcp %p mmd %p "
19787 					    "pbuf %p (%d)\n",
19788 					    (void *)tcp, (void *)mmd,
19789 					    (void *)md_pbuf, pbuf_idx);
19790 				}
19791 
19792 				ASSERT(max_pld > 0);
19793 				--max_pld;
19794 				add_buffer = B_FALSE;
19795 			}
19796 
19797 			ASSERT(md_mp_head != NULL);
19798 			ASSERT(md_pbuf != NULL);
19799 			ASSERT(md_pbuf_nxt == NULL);
19800 			ASSERT(pbuf_idx != -1);
19801 			ASSERT(pbuf_idx_nxt == -1);
19802 			ASSERT(*usable > 0);
19803 
19804 			/*
19805 			 * We spillover to the next payload buffer only
19806 			 * if all of the following is true:
19807 			 *
19808 			 *   1. There is not enough data on the current
19809 			 *	payload buffer to make up `len',
19810 			 *   2. We are allowed to send `len',
19811 			 *   3. The next payload buffer length is large
19812 			 *	enough to accomodate `spill'.
19813 			 */
19814 			if ((spill = len - *tail_unsent) > 0 &&
19815 			    *usable >= len &&
19816 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19817 			    max_pld > 0) {
19818 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19819 				if (md_pbuf_nxt == NULL) {
19820 					TCP_STAT(tcps, tcp_mdt_allocfail);
19821 					goto legacy_send; /* out_of_mem */
19822 				}
19823 
19824 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19825 				    zc_cap != NULL) {
19826 					if (!ip_md_zcopy_attr(mmd, NULL,
19827 					    zc_cap->ill_zerocopy_flags)) {
19828 						freeb(md_pbuf_nxt);
19829 						TCP_STAT(tcps,
19830 						    tcp_mdt_allocfail);
19831 						/* out_of_mem */
19832 						goto legacy_send;
19833 					}
19834 					zcopy = B_TRUE;
19835 				}
19836 
19837 				/*
19838 				 * See comments above on the first call to
19839 				 * mmd_addpldbuf for explanation on the panic.
19840 				 */
19841 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19842 				if (pbuf_idx_nxt < 0) {
19843 					panic("tcp_multisend: "
19844 					    "next payload buffer logic error "
19845 					    "detected for tcp %p mmd %p "
19846 					    "pbuf %p (%d)\n",
19847 					    (void *)tcp, (void *)mmd,
19848 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19849 				}
19850 
19851 				ASSERT(max_pld > 0);
19852 				--max_pld;
19853 			} else if (spill > 0) {
19854 				/*
19855 				 * If there's a spillover, but the following
19856 				 * xmit_tail couldn't give us enough octets
19857 				 * to reach "len", then stop the current
19858 				 * Multidata creation and let the legacy
19859 				 * tcp_send() path take over.  We don't want
19860 				 * to send the tiny segment as part of this
19861 				 * Multidata for performance reasons; instead,
19862 				 * we let the legacy path deal with grouping
19863 				 * it with the subsequent small mblks.
19864 				 */
19865 				if (*usable >= len &&
19866 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19867 					max_pld = 0;
19868 					break;	/* done */
19869 				}
19870 
19871 				/*
19872 				 * We can't spillover, and we are near
19873 				 * the end of the current payload buffer,
19874 				 * so send what's left.
19875 				 */
19876 				ASSERT(*tail_unsent > 0);
19877 				len = *tail_unsent;
19878 			}
19879 
19880 			/* tail_unsent is negated if there is a spillover */
19881 			*tail_unsent -= len;
19882 			*usable -= len;
19883 			ASSERT(*usable >= 0);
19884 
19885 			if (*usable < mss)
19886 				seg_len = *usable;
19887 			/*
19888 			 * Sender SWS avoidance; see comments in tcp_send();
19889 			 * everything else is the same, except that we only
19890 			 * do this here if there is no more data to be sent
19891 			 * following the current xmit_tail.  We don't check
19892 			 * for 1-byte urgent data because we shouldn't get
19893 			 * here if TCP_URG_VALID is set.
19894 			 */
19895 			if (*usable > 0 && *usable < mss &&
19896 			    ((md_pbuf_nxt == NULL &&
19897 			    (*xmit_tail)->b_cont == NULL) ||
19898 			    (md_pbuf_nxt != NULL &&
19899 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19900 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19901 			    (tcp->tcp_unsent -
19902 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19903 			    !tcp->tcp_zero_win_probe) {
19904 				if ((*snxt + len) == tcp->tcp_snxt &&
19905 				    (*snxt + len) == tcp->tcp_suna) {
19906 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19907 				}
19908 				done = B_TRUE;
19909 			}
19910 
19911 			/*
19912 			 * Prime pump for IP's checksumming on our behalf;
19913 			 * include the adjustment for a source route if any.
19914 			 * Do this only for software/partial hardware checksum
19915 			 * offload, as this field gets zeroed out later for
19916 			 * the full hardware checksum offload case.
19917 			 */
19918 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19919 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19920 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19921 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19922 			}
19923 
19924 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19925 			*snxt += len;
19926 
19927 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19928 			/*
19929 			 * We set the PUSH bit only if TCP has no more buffered
19930 			 * data to be transmitted (or if sender SWS avoidance
19931 			 * takes place), as opposed to setting it for every
19932 			 * last packet in the burst.
19933 			 */
19934 			if (done ||
19935 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19936 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19937 
19938 			/*
19939 			 * Set FIN bit if this is our last segment; snxt
19940 			 * already includes its length, and it will not
19941 			 * be adjusted after this point.
19942 			 */
19943 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19944 			    *snxt == tcp->tcp_fss) {
19945 				if (!tcp->tcp_fin_acked) {
19946 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19947 					BUMP_MIB(&tcps->tcps_mib,
19948 					    tcpOutControl);
19949 				}
19950 				if (!tcp->tcp_fin_sent) {
19951 					tcp->tcp_fin_sent = B_TRUE;
19952 					/*
19953 					 * tcp state must be ESTABLISHED
19954 					 * in order for us to get here in
19955 					 * the first place.
19956 					 */
19957 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19958 
19959 					/*
19960 					 * Upon returning from this routine,
19961 					 * tcp_wput_data() will set tcp_snxt
19962 					 * to be equal to snxt + tcp_fin_sent.
19963 					 * This is essentially the same as
19964 					 * setting it to tcp_fss + 1.
19965 					 */
19966 				}
19967 			}
19968 
19969 			tcp->tcp_last_sent_len = (ushort_t)len;
19970 
19971 			len += tcp_hdr_len;
19972 			if (tcp->tcp_ipversion == IPV4_VERSION)
19973 				tcp->tcp_ipha->ipha_length = htons(len);
19974 			else
19975 				tcp->tcp_ip6h->ip6_plen = htons(len -
19976 				    ((char *)&tcp->tcp_ip6h[1] -
19977 				    tcp->tcp_iphc));
19978 
19979 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19980 
19981 			/* setup header fragment */
19982 			PDESC_HDR_ADD(pkt_info,
19983 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19984 			    tcp->tcp_mdt_hdr_head,		/* head room */
19985 			    tcp_hdr_len,			/* len */
19986 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19987 
19988 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
19989 			    hdr_frag_sz);
19990 			ASSERT(MBLKIN(md_hbuf,
19991 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
19992 			    PDESC_HDRSIZE(pkt_info)));
19993 
19994 			/* setup first payload fragment */
19995 			PDESC_PLD_INIT(pkt_info);
19996 			PDESC_PLD_SPAN_ADD(pkt_info,
19997 			    pbuf_idx,				/* index */
19998 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
19999 			    tcp->tcp_last_sent_len);		/* len */
20000 
20001 			/* create a split-packet in case of a spillover */
20002 			if (md_pbuf_nxt != NULL) {
20003 				ASSERT(spill > 0);
20004 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20005 				ASSERT(!add_buffer);
20006 
20007 				md_pbuf = md_pbuf_nxt;
20008 				md_pbuf_nxt = NULL;
20009 				pbuf_idx = pbuf_idx_nxt;
20010 				pbuf_idx_nxt = -1;
20011 				cur_pld_off = spill;
20012 
20013 				/* trim out first payload fragment */
20014 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20015 
20016 				/* setup second payload fragment */
20017 				PDESC_PLD_SPAN_ADD(pkt_info,
20018 				    pbuf_idx,			/* index */
20019 				    md_pbuf->b_rptr,		/* start */
20020 				    spill);			/* len */
20021 
20022 				if ((*xmit_tail)->b_next == NULL) {
20023 					/*
20024 					 * Store the lbolt used for RTT
20025 					 * estimation. We can only record one
20026 					 * timestamp per mblk so we do it when
20027 					 * we reach the end of the payload
20028 					 * buffer.  Also we only take a new
20029 					 * timestamp sample when the previous
20030 					 * timed data from the same mblk has
20031 					 * been ack'ed.
20032 					 */
20033 					(*xmit_tail)->b_prev = local_time;
20034 					(*xmit_tail)->b_next =
20035 					    (mblk_t *)(uintptr_t)first_snxt;
20036 				}
20037 
20038 				first_snxt = *snxt - spill;
20039 
20040 				/*
20041 				 * Advance xmit_tail; usable could be 0 by
20042 				 * the time we got here, but we made sure
20043 				 * above that we would only spillover to
20044 				 * the next data block if usable includes
20045 				 * the spilled-over amount prior to the
20046 				 * subtraction.  Therefore, we are sure
20047 				 * that xmit_tail->b_cont can't be NULL.
20048 				 */
20049 				ASSERT((*xmit_tail)->b_cont != NULL);
20050 				*xmit_tail = (*xmit_tail)->b_cont;
20051 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20052 				    (uintptr_t)INT_MAX);
20053 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20054 			} else {
20055 				cur_pld_off += tcp->tcp_last_sent_len;
20056 			}
20057 
20058 			/*
20059 			 * Fill in the header using the template header, and
20060 			 * add options such as time-stamp, ECN and/or SACK,
20061 			 * as needed.
20062 			 */
20063 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20064 			    (clock_t)local_time, num_sack_blk);
20065 
20066 			/* take care of some IP header businesses */
20067 			if (af == AF_INET) {
20068 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20069 
20070 				ASSERT(OK_32PTR((uchar_t *)ipha));
20071 				ASSERT(PDESC_HDRL(pkt_info) >=
20072 				    IP_SIMPLE_HDR_LENGTH);
20073 				ASSERT(ipha->ipha_version_and_hdr_length ==
20074 				    IP_SIMPLE_HDR_VERSION);
20075 
20076 				/*
20077 				 * Assign ident value for current packet; see
20078 				 * related comments in ip_wput_ire() about the
20079 				 * contract private interface with clustering
20080 				 * group.
20081 				 */
20082 				clusterwide = B_FALSE;
20083 				if (cl_inet_ipident != NULL) {
20084 					ASSERT(cl_inet_isclusterwide != NULL);
20085 					if ((*cl_inet_isclusterwide)(stack_id,
20086 					    IPPROTO_IP, AF_INET,
20087 					    (uint8_t *)(uintptr_t)src, NULL)) {
20088 						ipha->ipha_ident =
20089 						    (*cl_inet_ipident)(stack_id,
20090 						    IPPROTO_IP, AF_INET,
20091 						    (uint8_t *)(uintptr_t)src,
20092 						    (uint8_t *)(uintptr_t)dst,
20093 						    NULL);
20094 						clusterwide = B_TRUE;
20095 					}
20096 				}
20097 
20098 				if (!clusterwide) {
20099 					ipha->ipha_ident = (uint16_t)
20100 					    atomic_add_32_nv(
20101 						&ire->ire_ident, 1);
20102 				}
20103 #ifndef _BIG_ENDIAN
20104 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20105 				    (ipha->ipha_ident >> 8);
20106 #endif
20107 			} else {
20108 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20109 
20110 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20111 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20112 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20113 				ASSERT(PDESC_HDRL(pkt_info) >=
20114 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20115 				    TCP_CHECKSUM_SIZE));
20116 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20117 
20118 				if (tcp->tcp_ip_forward_progress) {
20119 					rconfirm = B_TRUE;
20120 					tcp->tcp_ip_forward_progress = B_FALSE;
20121 				}
20122 			}
20123 
20124 			/* at least one payload span, and at most two */
20125 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20126 
20127 			/* add the packet descriptor to Multidata */
20128 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20129 			    KM_NOSLEEP)) == NULL) {
20130 				/*
20131 				 * Any failure other than ENOMEM indicates
20132 				 * that we have passed in invalid pkt_info
20133 				 * or parameters to mmd_addpdesc, which must
20134 				 * not happen.
20135 				 *
20136 				 * EINVAL is a result of failure on boundary
20137 				 * checks against the pkt_info contents.  It
20138 				 * should not happen, and we panic because
20139 				 * either there's horrible heap corruption,
20140 				 * and/or programming mistake.
20141 				 */
20142 				if (err != ENOMEM) {
20143 					cmn_err(CE_PANIC, "tcp_multisend: "
20144 					    "pdesc logic error detected for "
20145 					    "tcp %p mmd %p pinfo %p (%d)\n",
20146 					    (void *)tcp, (void *)mmd,
20147 					    (void *)pkt_info, err);
20148 				}
20149 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20150 				goto legacy_send; /* out_of_mem */
20151 			}
20152 			ASSERT(pkt != NULL);
20153 
20154 			/* calculate IP header and TCP checksums */
20155 			if (af == AF_INET) {
20156 				/* calculate pseudo-header checksum */
20157 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20158 				    (src >> 16) + (src & 0xFFFF);
20159 
20160 				/* offset for TCP header checksum */
20161 				up = IPH_TCPH_CHECKSUMP(ipha,
20162 				    IP_SIMPLE_HDR_LENGTH);
20163 			} else {
20164 				up = (uint16_t *)&ip6h->ip6_src;
20165 
20166 				/* calculate pseudo-header checksum */
20167 				cksum = up[0] + up[1] + up[2] + up[3] +
20168 				    up[4] + up[5] + up[6] + up[7] +
20169 				    up[8] + up[9] + up[10] + up[11] +
20170 				    up[12] + up[13] + up[14] + up[15];
20171 
20172 				/* Fold the initial sum */
20173 				cksum = (cksum & 0xffff) + (cksum >> 16);
20174 
20175 				up = (uint16_t *)(((uchar_t *)ip6h) +
20176 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20177 			}
20178 
20179 			if (hwcksum_flags & HCK_FULLCKSUM) {
20180 				/* clear checksum field for hardware */
20181 				*up = 0;
20182 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20183 				uint32_t sum;
20184 
20185 				/* pseudo-header checksumming */
20186 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20187 				sum = (sum & 0xFFFF) + (sum >> 16);
20188 				*up = (sum & 0xFFFF) + (sum >> 16);
20189 			} else {
20190 				/* software checksumming */
20191 				TCP_STAT(tcps, tcp_out_sw_cksum);
20192 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20193 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20194 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20195 				    cksum + IP_TCP_CSUM_COMP);
20196 				if (*up == 0)
20197 					*up = 0xFFFF;
20198 			}
20199 
20200 			/* IPv4 header checksum */
20201 			if (af == AF_INET) {
20202 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20203 					ipha->ipha_hdr_checksum = 0;
20204 				} else {
20205 					IP_HDR_CKSUM(ipha, cksum,
20206 					    ((uint32_t *)ipha)[0],
20207 					    ((uint16_t *)ipha)[4]);
20208 				}
20209 			}
20210 
20211 			if (af == AF_INET &&
20212 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20213 			    af == AF_INET6 &&
20214 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20215 				mblk_t	*mp, *mp1;
20216 				uchar_t	*hdr_rptr, *hdr_wptr;
20217 				uchar_t	*pld_rptr, *pld_wptr;
20218 
20219 				/*
20220 				 * We reconstruct a pseudo packet for the hooks
20221 				 * framework using mmd_transform_link().
20222 				 * If it is a split packet we pullup the
20223 				 * payload. FW_HOOKS expects a pkt comprising
20224 				 * of two mblks: a header and the payload.
20225 				 */
20226 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20227 					TCP_STAT(tcps, tcp_mdt_allocfail);
20228 					goto legacy_send;
20229 				}
20230 
20231 				if (pkt_info->pld_cnt > 1) {
20232 					/* split payload, more than one pld */
20233 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20234 					    NULL) {
20235 						freemsg(mp);
20236 						TCP_STAT(tcps,
20237 						    tcp_mdt_allocfail);
20238 						goto legacy_send;
20239 					}
20240 					freemsg(mp->b_cont);
20241 					mp->b_cont = mp1;
20242 				} else {
20243 					mp1 = mp->b_cont;
20244 				}
20245 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20246 
20247 				/*
20248 				 * Remember the message offsets. This is so we
20249 				 * can detect changes when we return from the
20250 				 * FW_HOOKS callbacks.
20251 				 */
20252 				hdr_rptr = mp->b_rptr;
20253 				hdr_wptr = mp->b_wptr;
20254 				pld_rptr = mp->b_cont->b_rptr;
20255 				pld_wptr = mp->b_cont->b_wptr;
20256 
20257 				if (af == AF_INET) {
20258 					DTRACE_PROBE4(
20259 					    ip4__physical__out__start,
20260 					    ill_t *, NULL,
20261 					    ill_t *, ill,
20262 					    ipha_t *, ipha,
20263 					    mblk_t *, mp);
20264 					FW_HOOKS(
20265 					    ipst->ips_ip4_physical_out_event,
20266 					    ipst->ips_ipv4firewall_physical_out,
20267 					    NULL, ill, ipha, mp, mp, 0, ipst);
20268 					DTRACE_PROBE1(
20269 					    ip4__physical__out__end,
20270 					    mblk_t *, mp);
20271 				} else {
20272 					DTRACE_PROBE4(
20273 					    ip6__physical__out_start,
20274 					    ill_t *, NULL,
20275 					    ill_t *, ill,
20276 					    ip6_t *, ip6h,
20277 					    mblk_t *, mp);
20278 					FW_HOOKS6(
20279 					    ipst->ips_ip6_physical_out_event,
20280 					    ipst->ips_ipv6firewall_physical_out,
20281 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20282 					DTRACE_PROBE1(
20283 					    ip6__physical__out__end,
20284 					    mblk_t *, mp);
20285 				}
20286 
20287 				if (mp == NULL ||
20288 				    (mp1 = mp->b_cont) == NULL ||
20289 				    mp->b_rptr != hdr_rptr ||
20290 				    mp->b_wptr != hdr_wptr ||
20291 				    mp1->b_rptr != pld_rptr ||
20292 				    mp1->b_wptr != pld_wptr ||
20293 				    mp1->b_cont != NULL) {
20294 					/*
20295 					 * We abandon multidata processing and
20296 					 * return to the normal path, either
20297 					 * when a packet is blocked, or when
20298 					 * the boundaries of header buffer or
20299 					 * payload buffer have been changed by
20300 					 * FW_HOOKS[6].
20301 					 */
20302 					if (mp != NULL)
20303 						freemsg(mp);
20304 					goto legacy_send;
20305 				}
20306 				/* Finished with the pseudo packet */
20307 				freemsg(mp);
20308 			}
20309 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
20310 			    ill, ipha, ip6h);
20311 			/* advance header offset */
20312 			cur_hdr_off += hdr_frag_sz;
20313 
20314 			obbytes += tcp->tcp_last_sent_len;
20315 			++obsegs;
20316 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20317 		    *tail_unsent > 0);
20318 
20319 		if ((*xmit_tail)->b_next == NULL) {
20320 			/*
20321 			 * Store the lbolt used for RTT estimation. We can only
20322 			 * record one timestamp per mblk so we do it when we
20323 			 * reach the end of the payload buffer. Also we only
20324 			 * take a new timestamp sample when the previous timed
20325 			 * data from the same mblk has been ack'ed.
20326 			 */
20327 			(*xmit_tail)->b_prev = local_time;
20328 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20329 		}
20330 
20331 		ASSERT(*tail_unsent >= 0);
20332 		if (*tail_unsent > 0) {
20333 			/*
20334 			 * We got here because we broke out of the above
20335 			 * loop due to of one of the following cases:
20336 			 *
20337 			 *   1. len < adjusted MSS (i.e. small),
20338 			 *   2. Sender SWS avoidance,
20339 			 *   3. max_pld is zero.
20340 			 *
20341 			 * We are done for this Multidata, so trim our
20342 			 * last payload buffer (if any) accordingly.
20343 			 */
20344 			if (md_pbuf != NULL)
20345 				md_pbuf->b_wptr -= *tail_unsent;
20346 		} else if (*usable > 0) {
20347 			*xmit_tail = (*xmit_tail)->b_cont;
20348 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20349 			    (uintptr_t)INT_MAX);
20350 			*tail_unsent = (int)MBLKL(*xmit_tail);
20351 			add_buffer = B_TRUE;
20352 		}
20353 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20354 	    (tcp_mdt_chain || max_pld > 0));
20355 
20356 	if (md_mp_head != NULL) {
20357 		/* send everything down */
20358 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20359 		    &rconfirm);
20360 	}
20361 
20362 #undef PREP_NEW_MULTIDATA
20363 #undef PREP_NEW_PBUF
20364 #undef IPVER
20365 
20366 	IRE_REFRELE(ire);
20367 	return (0);
20368 }
20369 
20370 /*
20371  * A wrapper function for sending one or more Multidata messages down to
20372  * the module below ip; this routine does not release the reference of the
20373  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20374  */
20375 static void
20376 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20377     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20378 {
20379 	uint64_t delta;
20380 	nce_t *nce;
20381 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20382 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20383 
20384 	ASSERT(ire != NULL && ill != NULL);
20385 	ASSERT(ire->ire_stq != NULL);
20386 	ASSERT(md_mp_head != NULL);
20387 	ASSERT(rconfirm != NULL);
20388 
20389 	/* adjust MIBs and IRE timestamp */
20390 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
20391 	tcp->tcp_obsegs += obsegs;
20392 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20393 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20394 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20395 
20396 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20397 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20398 	} else {
20399 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20400 	}
20401 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20402 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20403 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20404 
20405 	ire->ire_ob_pkt_count += obsegs;
20406 	if (ire->ire_ipif != NULL)
20407 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20408 	ire->ire_last_used_time = lbolt;
20409 
20410 	if (ipst->ips_ipobs_enabled) {
20411 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
20412 		pdesc_t *dl_pkt;
20413 		pdescinfo_t pinfo;
20414 		mblk_t *nmp;
20415 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
20416 
20417 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
20418 		    (dl_pkt != NULL);
20419 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
20420 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
20421 				continue;
20422 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
20423 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
20424 			freemsg(nmp);
20425 		}
20426 	}
20427 
20428 	/* send it down */
20429 	putnext(ire->ire_stq, md_mp_head);
20430 
20431 	/* we're done for TCP/IPv4 */
20432 	if (tcp->tcp_ipversion == IPV4_VERSION)
20433 		return;
20434 
20435 	nce = ire->ire_nce;
20436 
20437 	ASSERT(nce != NULL);
20438 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20439 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20440 
20441 	/* reachability confirmation? */
20442 	if (*rconfirm) {
20443 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20444 		if (nce->nce_state != ND_REACHABLE) {
20445 			mutex_enter(&nce->nce_lock);
20446 			nce->nce_state = ND_REACHABLE;
20447 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20448 			mutex_exit(&nce->nce_lock);
20449 			(void) untimeout(nce->nce_timeout_id);
20450 			if (ip_debug > 2) {
20451 				/* ip1dbg */
20452 				pr_addr_dbg("tcp_multisend_data: state "
20453 				    "for %s changed to REACHABLE\n",
20454 				    AF_INET6, &ire->ire_addr_v6);
20455 			}
20456 		}
20457 		/* reset transport reachability confirmation */
20458 		*rconfirm = B_FALSE;
20459 	}
20460 
20461 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20462 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20463 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20464 
20465 	if (delta > (uint64_t)ill->ill_reachable_time) {
20466 		mutex_enter(&nce->nce_lock);
20467 		switch (nce->nce_state) {
20468 		case ND_REACHABLE:
20469 		case ND_STALE:
20470 			/*
20471 			 * ND_REACHABLE is identical to ND_STALE in this
20472 			 * specific case. If reachable time has expired for
20473 			 * this neighbor (delta is greater than reachable
20474 			 * time), conceptually, the neighbor cache is no
20475 			 * longer in REACHABLE state, but already in STALE
20476 			 * state.  So the correct transition here is to
20477 			 * ND_DELAY.
20478 			 */
20479 			nce->nce_state = ND_DELAY;
20480 			mutex_exit(&nce->nce_lock);
20481 			NDP_RESTART_TIMER(nce,
20482 			    ipst->ips_delay_first_probe_time);
20483 			if (ip_debug > 3) {
20484 				/* ip2dbg */
20485 				pr_addr_dbg("tcp_multisend_data: state "
20486 				    "for %s changed to DELAY\n",
20487 				    AF_INET6, &ire->ire_addr_v6);
20488 			}
20489 			break;
20490 		case ND_DELAY:
20491 		case ND_PROBE:
20492 			mutex_exit(&nce->nce_lock);
20493 			/* Timers have already started */
20494 			break;
20495 		case ND_UNREACHABLE:
20496 			/*
20497 			 * ndp timer has detected that this nce is
20498 			 * unreachable and initiated deleting this nce
20499 			 * and all its associated IREs. This is a race
20500 			 * where we found the ire before it was deleted
20501 			 * and have just sent out a packet using this
20502 			 * unreachable nce.
20503 			 */
20504 			mutex_exit(&nce->nce_lock);
20505 			break;
20506 		default:
20507 			ASSERT(0);
20508 		}
20509 	}
20510 }
20511 
20512 /*
20513  * Derived from tcp_send_data().
20514  */
20515 static void
20516 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20517     int num_lso_seg)
20518 {
20519 	ipha_t		*ipha;
20520 	mblk_t		*ire_fp_mp;
20521 	uint_t		ire_fp_mp_len;
20522 	uint32_t	hcksum_txflags = 0;
20523 	ipaddr_t	src;
20524 	ipaddr_t	dst;
20525 	uint32_t	cksum;
20526 	uint16_t	*up;
20527 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20528 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20529 
20530 	ASSERT(DB_TYPE(mp) == M_DATA);
20531 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20532 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20533 	ASSERT(tcp->tcp_connp != NULL);
20534 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20535 
20536 	ipha = (ipha_t *)mp->b_rptr;
20537 	src = ipha->ipha_src;
20538 	dst = ipha->ipha_dst;
20539 
20540 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
20541 
20542 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20543 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20544 	    num_lso_seg);
20545 #ifndef _BIG_ENDIAN
20546 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20547 #endif
20548 	if (tcp->tcp_snd_zcopy_aware) {
20549 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20550 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20551 			mp = tcp_zcopy_disable(tcp, mp);
20552 	}
20553 
20554 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20555 		ASSERT(ill->ill_hcksum_capab != NULL);
20556 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20557 	}
20558 
20559 	/*
20560 	 * Since the TCP checksum should be recalculated by h/w, we can just
20561 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20562 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20563 	 * The partial pseudo-header excludes TCP length, that was calculated
20564 	 * in tcp_send(), so to zero *up before further processing.
20565 	 */
20566 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20567 
20568 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20569 	*up = 0;
20570 
20571 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20572 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20573 
20574 	/*
20575 	 * Append LSO flags and mss to the mp.
20576 	 */
20577 	lso_info_set(mp, mss, HW_LSO);
20578 
20579 	ipha->ipha_fragment_offset_and_flags |=
20580 	    (uint32_t)htons(ire->ire_frag_flag);
20581 
20582 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20583 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20584 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20585 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20586 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20587 
20588 	UPDATE_OB_PKT_COUNT(ire);
20589 	ire->ire_last_used_time = lbolt;
20590 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20591 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20592 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20593 	    ntohs(ipha->ipha_length));
20594 
20595 	DTRACE_PROBE4(ip4__physical__out__start,
20596 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
20597 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
20598 	    ipst->ips_ipv4firewall_physical_out, NULL,
20599 	    ill, ipha, mp, mp, 0, ipst);
20600 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20601 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
20602 
20603 	if (mp != NULL) {
20604 		if (ipst->ips_ipobs_enabled) {
20605 			zoneid_t szone;
20606 
20607 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
20608 			    ipst, ALL_ZONES);
20609 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
20610 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
20611 		}
20612 
20613 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
20614 	}
20615 }
20616 
20617 /*
20618  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20619  * scheme, and returns one of the following:
20620  *
20621  * -1 = failed allocation.
20622  *  0 = success; burst count reached, or usable send window is too small,
20623  *      and that we'd rather wait until later before sending again.
20624  *  1 = success; we are called from tcp_multisend(), and both usable send
20625  *      window and tail_unsent are greater than the MDT threshold, and thus
20626  *      Multidata Transmit should be used instead.
20627  */
20628 static int
20629 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20630     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20631     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20632     const int mdt_thres)
20633 {
20634 	int num_burst_seg = tcp->tcp_snd_burst;
20635 	ire_t		*ire = NULL;
20636 	ill_t		*ill = NULL;
20637 	mblk_t		*ire_fp_mp = NULL;
20638 	uint_t		ire_fp_mp_len = 0;
20639 	int		num_lso_seg = 1;
20640 	uint_t		lso_usable;
20641 	boolean_t	do_lso_send = B_FALSE;
20642 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20643 
20644 	/*
20645 	 * Check LSO capability before any further work. And the similar check
20646 	 * need to be done in for(;;) loop.
20647 	 * LSO will be deployed when therer is more than one mss of available
20648 	 * data and a burst transmission is allowed.
20649 	 */
20650 	if (tcp->tcp_lso &&
20651 	    (tcp->tcp_valid_bits == 0 ||
20652 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20653 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20654 		/*
20655 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20656 		 * Double check LSO usability before going further, since the
20657 		 * underlying interface could have been changed. In case of any
20658 		 * change of LSO capability, set tcp_ire_ill_check_done to
20659 		 * B_FALSE to force to check the ILL with the next send.
20660 		 */
20661 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
20662 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
20663 			/*
20664 			 * Enable LSO with this transmission.
20665 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
20666 			 * IRE_REFRELE(ire) should be called before return.
20667 			 */
20668 			do_lso_send = B_TRUE;
20669 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
20670 			ire_fp_mp_len = MBLKL(ire_fp_mp);
20671 			/* Round up to multiple of 4 */
20672 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
20673 		} else {
20674 			tcp->tcp_lso = B_FALSE;
20675 			tcp->tcp_ire_ill_check_done = B_FALSE;
20676 			do_lso_send = B_FALSE;
20677 			ill = NULL;
20678 		}
20679 	}
20680 
20681 	for (;;) {
20682 		struct datab	*db;
20683 		tcph_t		*tcph;
20684 		uint32_t	sum;
20685 		mblk_t		*mp, *mp1;
20686 		uchar_t		*rptr;
20687 		int		len;
20688 
20689 		/*
20690 		 * If we're called by tcp_multisend(), and the amount of
20691 		 * sendable data as well as the size of current xmit_tail
20692 		 * is beyond the MDT threshold, return to the caller and
20693 		 * let the large data transmit be done using MDT.
20694 		 */
20695 		if (*usable > 0 && *usable > mdt_thres &&
20696 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20697 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20698 			ASSERT(tcp->tcp_mdt);
20699 			return (1);	/* success; do large send */
20700 		}
20701 
20702 		if (num_burst_seg == 0)
20703 			break;		/* success; burst count reached */
20704 
20705 		/*
20706 		 * Calculate the maximum payload length we can send in *one*
20707 		 * time.
20708 		 */
20709 		if (do_lso_send) {
20710 			/*
20711 			 * Check whether need to do LSO any more.
20712 			 */
20713 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20714 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
20715 				lso_usable = MIN(lso_usable,
20716 				    num_burst_seg * mss);
20717 
20718 				num_lso_seg = lso_usable / mss;
20719 				if (lso_usable % mss) {
20720 					num_lso_seg++;
20721 					tcp->tcp_last_sent_len = (ushort_t)
20722 					    (lso_usable % mss);
20723 				} else {
20724 					tcp->tcp_last_sent_len = (ushort_t)mss;
20725 				}
20726 			} else {
20727 				do_lso_send = B_FALSE;
20728 				num_lso_seg = 1;
20729 				lso_usable = mss;
20730 			}
20731 		}
20732 
20733 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
20734 
20735 		/*
20736 		 * Adjust num_burst_seg here.
20737 		 */
20738 		num_burst_seg -= num_lso_seg;
20739 
20740 		len = mss;
20741 		if (len > *usable) {
20742 			ASSERT(do_lso_send == B_FALSE);
20743 
20744 			len = *usable;
20745 			if (len <= 0) {
20746 				/* Terminate the loop */
20747 				break;	/* success; too small */
20748 			}
20749 			/*
20750 			 * Sender silly-window avoidance.
20751 			 * Ignore this if we are going to send a
20752 			 * zero window probe out.
20753 			 *
20754 			 * TODO: force data into microscopic window?
20755 			 *	==> (!pushed || (unsent > usable))
20756 			 */
20757 			if (len < (tcp->tcp_max_swnd >> 1) &&
20758 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20759 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20760 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20761 				/*
20762 				 * If the retransmit timer is not running
20763 				 * we start it so that we will retransmit
20764 				 * in the case when the the receiver has
20765 				 * decremented the window.
20766 				 */
20767 				if (*snxt == tcp->tcp_snxt &&
20768 				    *snxt == tcp->tcp_suna) {
20769 					/*
20770 					 * We are not supposed to send
20771 					 * anything.  So let's wait a little
20772 					 * bit longer before breaking SWS
20773 					 * avoidance.
20774 					 *
20775 					 * What should the value be?
20776 					 * Suggestion: MAX(init rexmit time,
20777 					 * tcp->tcp_rto)
20778 					 */
20779 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20780 				}
20781 				break;	/* success; too small */
20782 			}
20783 		}
20784 
20785 		tcph = tcp->tcp_tcph;
20786 
20787 		/*
20788 		 * The reason to adjust len here is that we need to set flags
20789 		 * and calculate checksum.
20790 		 */
20791 		if (do_lso_send)
20792 			len = lso_usable;
20793 
20794 		*usable -= len; /* Approximate - can be adjusted later */
20795 		if (*usable > 0)
20796 			tcph->th_flags[0] = TH_ACK;
20797 		else
20798 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20799 
20800 		/*
20801 		 * Prime pump for IP's checksumming on our behalf
20802 		 * Include the adjustment for a source route if any.
20803 		 */
20804 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20805 		sum = (sum >> 16) + (sum & 0xFFFF);
20806 		U16_TO_ABE16(sum, tcph->th_sum);
20807 
20808 		U32_TO_ABE32(*snxt, tcph->th_seq);
20809 
20810 		/*
20811 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20812 		 * set.  For the case when TCP_FSS_VALID is the only valid
20813 		 * bit (normal active close), branch off only when we think
20814 		 * that the FIN flag needs to be set.  Note for this case,
20815 		 * that (snxt + len) may not reflect the actual seg_len,
20816 		 * as len may be further reduced in tcp_xmit_mp().  If len
20817 		 * gets modified, we will end up here again.
20818 		 */
20819 		if (tcp->tcp_valid_bits != 0 &&
20820 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20821 		    ((*snxt + len) == tcp->tcp_fss))) {
20822 			uchar_t		*prev_rptr;
20823 			uint32_t	prev_snxt = tcp->tcp_snxt;
20824 
20825 			if (*tail_unsent == 0) {
20826 				ASSERT((*xmit_tail)->b_cont != NULL);
20827 				*xmit_tail = (*xmit_tail)->b_cont;
20828 				prev_rptr = (*xmit_tail)->b_rptr;
20829 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20830 				    (*xmit_tail)->b_rptr);
20831 			} else {
20832 				prev_rptr = (*xmit_tail)->b_rptr;
20833 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20834 				    *tail_unsent;
20835 			}
20836 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20837 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20838 			/* Restore tcp_snxt so we get amount sent right. */
20839 			tcp->tcp_snxt = prev_snxt;
20840 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20841 				/*
20842 				 * If the previous timestamp is still in use,
20843 				 * don't stomp on it.
20844 				 */
20845 				if ((*xmit_tail)->b_next == NULL) {
20846 					(*xmit_tail)->b_prev = local_time;
20847 					(*xmit_tail)->b_next =
20848 					    (mblk_t *)(uintptr_t)(*snxt);
20849 				}
20850 			} else
20851 				(*xmit_tail)->b_rptr = prev_rptr;
20852 
20853 			if (mp == NULL) {
20854 				if (ire != NULL)
20855 					IRE_REFRELE(ire);
20856 				return (-1);
20857 			}
20858 			mp1 = mp->b_cont;
20859 
20860 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
20861 				tcp->tcp_last_sent_len = (ushort_t)len;
20862 			while (mp1->b_cont) {
20863 				*xmit_tail = (*xmit_tail)->b_cont;
20864 				(*xmit_tail)->b_prev = local_time;
20865 				(*xmit_tail)->b_next =
20866 				    (mblk_t *)(uintptr_t)(*snxt);
20867 				mp1 = mp1->b_cont;
20868 			}
20869 			*snxt += len;
20870 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20871 			BUMP_LOCAL(tcp->tcp_obsegs);
20872 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20873 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20874 			tcp_send_data(tcp, q, mp);
20875 			continue;
20876 		}
20877 
20878 		*snxt += len;	/* Adjust later if we don't send all of len */
20879 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20880 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20881 
20882 		if (*tail_unsent) {
20883 			/* Are the bytes above us in flight? */
20884 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20885 			if (rptr != (*xmit_tail)->b_rptr) {
20886 				*tail_unsent -= len;
20887 				if (len <= mss) /* LSO is unusable */
20888 					tcp->tcp_last_sent_len = (ushort_t)len;
20889 				len += tcp_hdr_len;
20890 				if (tcp->tcp_ipversion == IPV4_VERSION)
20891 					tcp->tcp_ipha->ipha_length = htons(len);
20892 				else
20893 					tcp->tcp_ip6h->ip6_plen =
20894 					    htons(len -
20895 					    ((char *)&tcp->tcp_ip6h[1] -
20896 					    tcp->tcp_iphc));
20897 				mp = dupb(*xmit_tail);
20898 				if (mp == NULL) {
20899 					if (ire != NULL)
20900 						IRE_REFRELE(ire);
20901 					return (-1);	/* out_of_mem */
20902 				}
20903 				mp->b_rptr = rptr;
20904 				/*
20905 				 * If the old timestamp is no longer in use,
20906 				 * sample a new timestamp now.
20907 				 */
20908 				if ((*xmit_tail)->b_next == NULL) {
20909 					(*xmit_tail)->b_prev = local_time;
20910 					(*xmit_tail)->b_next =
20911 					    (mblk_t *)(uintptr_t)(*snxt-len);
20912 				}
20913 				goto must_alloc;
20914 			}
20915 		} else {
20916 			*xmit_tail = (*xmit_tail)->b_cont;
20917 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20918 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20919 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20920 			    (*xmit_tail)->b_rptr);
20921 		}
20922 
20923 		(*xmit_tail)->b_prev = local_time;
20924 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20925 
20926 		*tail_unsent -= len;
20927 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
20928 			tcp->tcp_last_sent_len = (ushort_t)len;
20929 
20930 		len += tcp_hdr_len;
20931 		if (tcp->tcp_ipversion == IPV4_VERSION)
20932 			tcp->tcp_ipha->ipha_length = htons(len);
20933 		else
20934 			tcp->tcp_ip6h->ip6_plen = htons(len -
20935 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20936 
20937 		mp = dupb(*xmit_tail);
20938 		if (mp == NULL) {
20939 			if (ire != NULL)
20940 				IRE_REFRELE(ire);
20941 			return (-1);	/* out_of_mem */
20942 		}
20943 
20944 		len = tcp_hdr_len;
20945 		/*
20946 		 * There are four reasons to allocate a new hdr mblk:
20947 		 *  1) The bytes above us are in use by another packet
20948 		 *  2) We don't have good alignment
20949 		 *  3) The mblk is being shared
20950 		 *  4) We don't have enough room for a header
20951 		 */
20952 		rptr = mp->b_rptr - len;
20953 		if (!OK_32PTR(rptr) ||
20954 		    ((db = mp->b_datap), db->db_ref != 2) ||
20955 		    rptr < db->db_base + ire_fp_mp_len) {
20956 			/* NOTE: we assume allocb returns an OK_32PTR */
20957 
20958 		must_alloc:;
20959 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20960 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
20961 			if (mp1 == NULL) {
20962 				freemsg(mp);
20963 				if (ire != NULL)
20964 					IRE_REFRELE(ire);
20965 				return (-1);	/* out_of_mem */
20966 			}
20967 			mp1->b_cont = mp;
20968 			mp = mp1;
20969 			/* Leave room for Link Level header */
20970 			len = tcp_hdr_len;
20971 			rptr =
20972 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
20973 			mp->b_wptr = &rptr[len];
20974 		}
20975 
20976 		/*
20977 		 * Fill in the header using the template header, and add
20978 		 * options such as time-stamp, ECN and/or SACK, as needed.
20979 		 */
20980 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20981 
20982 		mp->b_rptr = rptr;
20983 
20984 		if (*tail_unsent) {
20985 			int spill = *tail_unsent;
20986 
20987 			mp1 = mp->b_cont;
20988 			if (mp1 == NULL)
20989 				mp1 = mp;
20990 
20991 			/*
20992 			 * If we're a little short, tack on more mblks until
20993 			 * there is no more spillover.
20994 			 */
20995 			while (spill < 0) {
20996 				mblk_t *nmp;
20997 				int nmpsz;
20998 
20999 				nmp = (*xmit_tail)->b_cont;
21000 				nmpsz = MBLKL(nmp);
21001 
21002 				/*
21003 				 * Excess data in mblk; can we split it?
21004 				 * If MDT is enabled for the connection,
21005 				 * keep on splitting as this is a transient
21006 				 * send path.
21007 				 */
21008 				if (!do_lso_send && !tcp->tcp_mdt &&
21009 				    (spill + nmpsz > 0)) {
21010 					/*
21011 					 * Don't split if stream head was
21012 					 * told to break up larger writes
21013 					 * into smaller ones.
21014 					 */
21015 					if (tcp->tcp_maxpsz > 0)
21016 						break;
21017 
21018 					/*
21019 					 * Next mblk is less than SMSS/2
21020 					 * rounded up to nearest 64-byte;
21021 					 * let it get sent as part of the
21022 					 * next segment.
21023 					 */
21024 					if (tcp->tcp_localnet &&
21025 					    !tcp->tcp_cork &&
21026 					    (nmpsz < roundup((mss >> 1), 64)))
21027 						break;
21028 				}
21029 
21030 				*xmit_tail = nmp;
21031 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21032 				/* Stash for rtt use later */
21033 				(*xmit_tail)->b_prev = local_time;
21034 				(*xmit_tail)->b_next =
21035 				    (mblk_t *)(uintptr_t)(*snxt - len);
21036 				mp1->b_cont = dupb(*xmit_tail);
21037 				mp1 = mp1->b_cont;
21038 
21039 				spill += nmpsz;
21040 				if (mp1 == NULL) {
21041 					*tail_unsent = spill;
21042 					freemsg(mp);
21043 					if (ire != NULL)
21044 						IRE_REFRELE(ire);
21045 					return (-1);	/* out_of_mem */
21046 				}
21047 			}
21048 
21049 			/* Trim back any surplus on the last mblk */
21050 			if (spill >= 0) {
21051 				mp1->b_wptr -= spill;
21052 				*tail_unsent = spill;
21053 			} else {
21054 				/*
21055 				 * We did not send everything we could in
21056 				 * order to remain within the b_cont limit.
21057 				 */
21058 				*usable -= spill;
21059 				*snxt += spill;
21060 				tcp->tcp_last_sent_len += spill;
21061 				UPDATE_MIB(&tcps->tcps_mib,
21062 				    tcpOutDataBytes, spill);
21063 				/*
21064 				 * Adjust the checksum
21065 				 */
21066 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21067 				sum += spill;
21068 				sum = (sum >> 16) + (sum & 0xFFFF);
21069 				U16_TO_ABE16(sum, tcph->th_sum);
21070 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21071 					sum = ntohs(
21072 					    ((ipha_t *)rptr)->ipha_length) +
21073 					    spill;
21074 					((ipha_t *)rptr)->ipha_length =
21075 					    htons(sum);
21076 				} else {
21077 					sum = ntohs(
21078 					    ((ip6_t *)rptr)->ip6_plen) +
21079 					    spill;
21080 					((ip6_t *)rptr)->ip6_plen =
21081 					    htons(sum);
21082 				}
21083 				*tail_unsent = 0;
21084 			}
21085 		}
21086 		if (tcp->tcp_ip_forward_progress) {
21087 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21088 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21089 			tcp->tcp_ip_forward_progress = B_FALSE;
21090 		}
21091 
21092 		if (do_lso_send) {
21093 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21094 			    num_lso_seg);
21095 			tcp->tcp_obsegs += num_lso_seg;
21096 
21097 			TCP_STAT(tcps, tcp_lso_times);
21098 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21099 		} else {
21100 			tcp_send_data(tcp, q, mp);
21101 			BUMP_LOCAL(tcp->tcp_obsegs);
21102 		}
21103 	}
21104 
21105 	if (ire != NULL)
21106 		IRE_REFRELE(ire);
21107 	return (0);
21108 }
21109 
21110 /* Unlink and return any mblk that looks like it contains a MDT info */
21111 static mblk_t *
21112 tcp_mdt_info_mp(mblk_t *mp)
21113 {
21114 	mblk_t	*prev_mp;
21115 
21116 	for (;;) {
21117 		prev_mp = mp;
21118 		/* no more to process? */
21119 		if ((mp = mp->b_cont) == NULL)
21120 			break;
21121 
21122 		switch (DB_TYPE(mp)) {
21123 		case M_CTL:
21124 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21125 				continue;
21126 			ASSERT(prev_mp != NULL);
21127 			prev_mp->b_cont = mp->b_cont;
21128 			mp->b_cont = NULL;
21129 			return (mp);
21130 		default:
21131 			break;
21132 		}
21133 	}
21134 	return (mp);
21135 }
21136 
21137 /* MDT info update routine, called when IP notifies us about MDT */
21138 static void
21139 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21140 {
21141 	boolean_t prev_state;
21142 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21143 
21144 	/*
21145 	 * IP is telling us to abort MDT on this connection?  We know
21146 	 * this because the capability is only turned off when IP
21147 	 * encounters some pathological cases, e.g. link-layer change
21148 	 * where the new driver doesn't support MDT, or in situation
21149 	 * where MDT usage on the link-layer has been switched off.
21150 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21151 	 * if the link-layer doesn't support MDT, and if it does, it
21152 	 * will indicate that the feature is to be turned on.
21153 	 */
21154 	prev_state = tcp->tcp_mdt;
21155 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21156 	if (!tcp->tcp_mdt && !first) {
21157 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21158 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21159 		    (void *)tcp->tcp_connp));
21160 	}
21161 
21162 	/*
21163 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21164 	 * so disable MDT otherwise.  The checks are done here
21165 	 * and in tcp_wput_data().
21166 	 */
21167 	if (tcp->tcp_mdt &&
21168 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21169 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21170 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21171 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21172 		tcp->tcp_mdt = B_FALSE;
21173 
21174 	if (tcp->tcp_mdt) {
21175 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21176 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21177 			    "version (%d), expected version is %d",
21178 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21179 			tcp->tcp_mdt = B_FALSE;
21180 			return;
21181 		}
21182 
21183 		/*
21184 		 * We need the driver to be able to handle at least three
21185 		 * spans per packet in order for tcp MDT to be utilized.
21186 		 * The first is for the header portion, while the rest are
21187 		 * needed to handle a packet that straddles across two
21188 		 * virtually non-contiguous buffers; a typical tcp packet
21189 		 * therefore consists of only two spans.  Note that we take
21190 		 * a zero as "don't care".
21191 		 */
21192 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21193 		    mdt_capab->ill_mdt_span_limit < 3) {
21194 			tcp->tcp_mdt = B_FALSE;
21195 			return;
21196 		}
21197 
21198 		/* a zero means driver wants default value */
21199 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21200 		    tcps->tcps_mdt_max_pbufs);
21201 		if (tcp->tcp_mdt_max_pld == 0)
21202 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21203 
21204 		/* ensure 32-bit alignment */
21205 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21206 		    mdt_capab->ill_mdt_hdr_head), 4);
21207 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21208 		    mdt_capab->ill_mdt_hdr_tail), 4);
21209 
21210 		if (!first && !prev_state) {
21211 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21212 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21213 			    (void *)tcp->tcp_connp));
21214 		}
21215 	}
21216 }
21217 
21218 /* Unlink and return any mblk that looks like it contains a LSO info */
21219 static mblk_t *
21220 tcp_lso_info_mp(mblk_t *mp)
21221 {
21222 	mblk_t	*prev_mp;
21223 
21224 	for (;;) {
21225 		prev_mp = mp;
21226 		/* no more to process? */
21227 		if ((mp = mp->b_cont) == NULL)
21228 			break;
21229 
21230 		switch (DB_TYPE(mp)) {
21231 		case M_CTL:
21232 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21233 				continue;
21234 			ASSERT(prev_mp != NULL);
21235 			prev_mp->b_cont = mp->b_cont;
21236 			mp->b_cont = NULL;
21237 			return (mp);
21238 		default:
21239 			break;
21240 		}
21241 	}
21242 
21243 	return (mp);
21244 }
21245 
21246 /* LSO info update routine, called when IP notifies us about LSO */
21247 static void
21248 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21249 {
21250 	tcp_stack_t *tcps = tcp->tcp_tcps;
21251 
21252 	/*
21253 	 * IP is telling us to abort LSO on this connection?  We know
21254 	 * this because the capability is only turned off when IP
21255 	 * encounters some pathological cases, e.g. link-layer change
21256 	 * where the new NIC/driver doesn't support LSO, or in situation
21257 	 * where LSO usage on the link-layer has been switched off.
21258 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21259 	 * if the link-layer doesn't support LSO, and if it does, it
21260 	 * will indicate that the feature is to be turned on.
21261 	 */
21262 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21263 	TCP_STAT(tcps, tcp_lso_enabled);
21264 
21265 	/*
21266 	 * We currently only support LSO on simple TCP/IPv4,
21267 	 * so disable LSO otherwise.  The checks are done here
21268 	 * and in tcp_wput_data().
21269 	 */
21270 	if (tcp->tcp_lso &&
21271 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21272 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21273 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21274 		tcp->tcp_lso = B_FALSE;
21275 		TCP_STAT(tcps, tcp_lso_disabled);
21276 	} else {
21277 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21278 		    lso_capab->ill_lso_max);
21279 	}
21280 }
21281 
21282 static void
21283 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21284 {
21285 	conn_t *connp = tcp->tcp_connp;
21286 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21287 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21288 
21289 	ASSERT(ire != NULL);
21290 
21291 	/*
21292 	 * We may be in the fastpath here, and although we essentially do
21293 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21294 	 * we try to keep things as brief as possible.  After all, these
21295 	 * are only best-effort checks, and we do more thorough ones prior
21296 	 * to calling tcp_send()/tcp_multisend().
21297 	 */
21298 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21299 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21300 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21301 	    !(ire->ire_flags & RTF_MULTIRT) &&
21302 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21303 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21304 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21305 			/* Cache the result */
21306 			connp->conn_lso_ok = B_TRUE;
21307 
21308 			ASSERT(ill->ill_lso_capab != NULL);
21309 			if (!ill->ill_lso_capab->ill_lso_on) {
21310 				ill->ill_lso_capab->ill_lso_on = 1;
21311 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21312 				    "LSO for interface %s\n", (void *)connp,
21313 				    ill->ill_name));
21314 			}
21315 			tcp_lso_update(tcp, ill->ill_lso_capab);
21316 		} else if (ipst->ips_ip_multidata_outbound &&
21317 		    ILL_MDT_CAPABLE(ill)) {
21318 			/* Cache the result */
21319 			connp->conn_mdt_ok = B_TRUE;
21320 
21321 			ASSERT(ill->ill_mdt_capab != NULL);
21322 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21323 				ill->ill_mdt_capab->ill_mdt_on = 1;
21324 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21325 				    "MDT for interface %s\n", (void *)connp,
21326 				    ill->ill_name));
21327 			}
21328 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21329 		}
21330 	}
21331 
21332 	/*
21333 	 * The goal is to reduce the number of generated tcp segments by
21334 	 * setting the maxpsz multiplier to 0; this will have an affect on
21335 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21336 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21337 	 * of outbound segments and incoming ACKs, thus allowing for better
21338 	 * network and system performance.  In contrast the legacy behavior
21339 	 * may result in sending less than SMSS size, because the last mblk
21340 	 * for some packets may have more data than needed to make up SMSS,
21341 	 * and the legacy code refused to "split" it.
21342 	 *
21343 	 * We apply the new behavior on following situations:
21344 	 *
21345 	 *   1) Loopback connections,
21346 	 *   2) Connections in which the remote peer is not on local subnet,
21347 	 *   3) Local subnet connections over the bge interface (see below).
21348 	 *
21349 	 * Ideally, we would like this behavior to apply for interfaces other
21350 	 * than bge.  However, doing so would negatively impact drivers which
21351 	 * perform dynamic mapping and unmapping of DMA resources, which are
21352 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21353 	 * packet will be generated by tcp).  The bge driver does not suffer
21354 	 * from this, as it copies the mblks into pre-mapped buffers, and
21355 	 * therefore does not require more I/O resources than before.
21356 	 *
21357 	 * Otherwise, this behavior is present on all network interfaces when
21358 	 * the destination endpoint is non-local, since reducing the number
21359 	 * of packets in general is good for the network.
21360 	 *
21361 	 * TODO We need to remove this hard-coded conditional for bge once
21362 	 *	a better "self-tuning" mechanism, or a way to comprehend
21363 	 *	the driver transmit strategy is devised.  Until the solution
21364 	 *	is found and well understood, we live with this hack.
21365 	 */
21366 	if (!tcp_static_maxpsz &&
21367 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21368 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21369 		/* override the default value */
21370 		tcp->tcp_maxpsz = 0;
21371 
21372 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21373 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21374 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21375 	}
21376 
21377 	/* set the stream head parameters accordingly */
21378 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21379 }
21380 
21381 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21382 static void
21383 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21384 {
21385 	uchar_t	fval = *mp->b_rptr;
21386 	mblk_t	*tail;
21387 	queue_t	*q = tcp->tcp_wq;
21388 
21389 	/* TODO: How should flush interact with urgent data? */
21390 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21391 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21392 		/*
21393 		 * Flush only data that has not yet been put on the wire.  If
21394 		 * we flush data that we have already transmitted, life, as we
21395 		 * know it, may come to an end.
21396 		 */
21397 		tail = tcp->tcp_xmit_tail;
21398 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21399 		tcp->tcp_xmit_tail_unsent = 0;
21400 		tcp->tcp_unsent = 0;
21401 		if (tail->b_wptr != tail->b_rptr)
21402 			tail = tail->b_cont;
21403 		if (tail) {
21404 			mblk_t **excess = &tcp->tcp_xmit_head;
21405 			for (;;) {
21406 				mblk_t *mp1 = *excess;
21407 				if (mp1 == tail)
21408 					break;
21409 				tcp->tcp_xmit_tail = mp1;
21410 				tcp->tcp_xmit_last = mp1;
21411 				excess = &mp1->b_cont;
21412 			}
21413 			*excess = NULL;
21414 			tcp_close_mpp(&tail);
21415 			if (tcp->tcp_snd_zcopy_aware)
21416 				tcp_zcopy_notify(tcp);
21417 		}
21418 		/*
21419 		 * We have no unsent data, so unsent must be less than
21420 		 * tcp_xmit_lowater, so re-enable flow.
21421 		 */
21422 		mutex_enter(&tcp->tcp_non_sq_lock);
21423 		if (tcp->tcp_flow_stopped) {
21424 			tcp_clrqfull(tcp);
21425 		}
21426 		mutex_exit(&tcp->tcp_non_sq_lock);
21427 	}
21428 	/*
21429 	 * TODO: you can't just flush these, you have to increase rwnd for one
21430 	 * thing.  For another, how should urgent data interact?
21431 	 */
21432 	if (fval & FLUSHR) {
21433 		*mp->b_rptr = fval & ~FLUSHW;
21434 		/* XXX */
21435 		qreply(q, mp);
21436 		return;
21437 	}
21438 	freemsg(mp);
21439 }
21440 
21441 /*
21442  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21443  * messages.
21444  */
21445 static void
21446 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21447 {
21448 	mblk_t	*mp1;
21449 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
21450 	STRUCT_HANDLE(strbuf, sb);
21451 	queue_t *q = tcp->tcp_wq;
21452 	int	error;
21453 	uint_t	addrlen;
21454 
21455 	/* Make sure it is one of ours. */
21456 	switch (iocp->ioc_cmd) {
21457 	case TI_GETMYNAME:
21458 	case TI_GETPEERNAME:
21459 		break;
21460 	default:
21461 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21462 		return;
21463 	}
21464 	switch (mi_copy_state(q, mp, &mp1)) {
21465 	case -1:
21466 		return;
21467 	case MI_COPY_CASE(MI_COPY_IN, 1):
21468 		break;
21469 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21470 		/* Copy out the strbuf. */
21471 		mi_copyout(q, mp);
21472 		return;
21473 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21474 		/* All done. */
21475 		mi_copy_done(q, mp, 0);
21476 		return;
21477 	default:
21478 		mi_copy_done(q, mp, EPROTO);
21479 		return;
21480 	}
21481 	/* Check alignment of the strbuf */
21482 	if (!OK_32PTR(mp1->b_rptr)) {
21483 		mi_copy_done(q, mp, EINVAL);
21484 		return;
21485 	}
21486 
21487 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
21488 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21489 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21490 		mi_copy_done(q, mp, EINVAL);
21491 		return;
21492 	}
21493 
21494 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21495 	if (mp1 == NULL)
21496 		return;
21497 
21498 	switch (iocp->ioc_cmd) {
21499 	case TI_GETMYNAME:
21500 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
21501 		break;
21502 	case TI_GETPEERNAME:
21503 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
21504 		break;
21505 	}
21506 
21507 	if (error != 0) {
21508 		mi_copy_done(q, mp, error);
21509 	} else {
21510 		mp1->b_wptr += addrlen;
21511 		STRUCT_FSET(sb, len, addrlen);
21512 
21513 		/* Copy out the address */
21514 		mi_copyout(q, mp);
21515 	}
21516 }
21517 
21518 static void
21519 tcp_disable_direct_sockfs(tcp_t *tcp)
21520 {
21521 #ifdef	_ILP32
21522 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
21523 #else
21524 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21525 #endif
21526 	/*
21527 	 * Insert this socket into the acceptor hash.
21528 	 * We might need it for T_CONN_RES message
21529 	 */
21530 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21531 
21532 	if (tcp->tcp_fused) {
21533 		/*
21534 		 * This is a fused loopback tcp; disable
21535 		 * read-side synchronous streams interface
21536 		 * and drain any queued data.  It is okay
21537 		 * to do this for non-synchronous streams
21538 		 * fused tcp as well.
21539 		 */
21540 		tcp_fuse_disable_pair(tcp, B_FALSE);
21541 	}
21542 	tcp->tcp_issocket = B_FALSE;
21543 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
21544 }
21545 
21546 /*
21547  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21548  * messages.
21549  */
21550 /* ARGSUSED */
21551 static void
21552 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21553 {
21554 	conn_t 	*connp = (conn_t *)arg;
21555 	tcp_t	*tcp = connp->conn_tcp;
21556 	queue_t	*q = tcp->tcp_wq;
21557 	struct iocblk	*iocp;
21558 
21559 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21560 	/*
21561 	 * Try and ASSERT the minimum possible references on the
21562 	 * conn early enough. Since we are executing on write side,
21563 	 * the connection is obviously not detached and that means
21564 	 * there is a ref each for TCP and IP. Since we are behind
21565 	 * the squeue, the minimum references needed are 3. If the
21566 	 * conn is in classifier hash list, there should be an
21567 	 * extra ref for that (we check both the possibilities).
21568 	 */
21569 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21570 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21571 
21572 	iocp = (struct iocblk *)mp->b_rptr;
21573 	switch (iocp->ioc_cmd) {
21574 	case TCP_IOC_DEFAULT_Q:
21575 		/* Wants to be the default wq. */
21576 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21577 			iocp->ioc_error = EPERM;
21578 			iocp->ioc_count = 0;
21579 			mp->b_datap->db_type = M_IOCACK;
21580 			qreply(q, mp);
21581 			return;
21582 		}
21583 		tcp_def_q_set(tcp, mp);
21584 		return;
21585 	case _SIOCSOCKFALLBACK:
21586 		/*
21587 		 * Either sockmod is about to be popped and the socket
21588 		 * would now be treated as a plain stream, or a module
21589 		 * is about to be pushed so we could no longer use read-
21590 		 * side synchronous streams for fused loopback tcp.
21591 		 * Drain any queued data and disable direct sockfs
21592 		 * interface from now on.
21593 		 */
21594 		if (!tcp->tcp_issocket) {
21595 			DB_TYPE(mp) = M_IOCNAK;
21596 			iocp->ioc_error = EINVAL;
21597 		} else {
21598 			tcp_disable_direct_sockfs(tcp);
21599 			DB_TYPE(mp) = M_IOCACK;
21600 			iocp->ioc_error = 0;
21601 		}
21602 		iocp->ioc_count = 0;
21603 		iocp->ioc_rval = 0;
21604 		qreply(q, mp);
21605 		return;
21606 	}
21607 	CALL_IP_WPUT(connp, q, mp);
21608 }
21609 
21610 /*
21611  * This routine is called by tcp_wput() to handle all TPI requests.
21612  */
21613 /* ARGSUSED */
21614 static void
21615 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21616 {
21617 	conn_t 	*connp = (conn_t *)arg;
21618 	tcp_t	*tcp = connp->conn_tcp;
21619 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21620 	uchar_t *rptr;
21621 	t_scalar_t type;
21622 	cred_t *cr;
21623 
21624 	/*
21625 	 * Try and ASSERT the minimum possible references on the
21626 	 * conn early enough. Since we are executing on write side,
21627 	 * the connection is obviously not detached and that means
21628 	 * there is a ref each for TCP and IP. Since we are behind
21629 	 * the squeue, the minimum references needed are 3. If the
21630 	 * conn is in classifier hash list, there should be an
21631 	 * extra ref for that (we check both the possibilities).
21632 	 */
21633 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21634 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21635 
21636 	rptr = mp->b_rptr;
21637 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21638 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21639 		type = ((union T_primitives *)rptr)->type;
21640 		if (type == T_EXDATA_REQ) {
21641 			tcp_output_urgent(connp, mp->b_cont, arg2);
21642 			freeb(mp);
21643 		} else if (type != T_DATA_REQ) {
21644 			goto non_urgent_data;
21645 		} else {
21646 			/* TODO: options, flags, ... from user */
21647 			/* Set length to zero for reclamation below */
21648 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21649 			freeb(mp);
21650 		}
21651 		return;
21652 	} else {
21653 		if (tcp->tcp_debug) {
21654 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21655 			    "tcp_wput_proto, dropping one...");
21656 		}
21657 		freemsg(mp);
21658 		return;
21659 	}
21660 
21661 non_urgent_data:
21662 
21663 	switch ((int)tprim->type) {
21664 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21665 		/*
21666 		 * save the kssl_ent_t from the next block, and convert this
21667 		 * back to a normal bind_req.
21668 		 */
21669 		if (mp->b_cont != NULL) {
21670 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21671 
21672 			if (tcp->tcp_kssl_ent != NULL) {
21673 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21674 				    KSSL_NO_PROXY);
21675 				tcp->tcp_kssl_ent = NULL;
21676 			}
21677 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21678 			    sizeof (kssl_ent_t));
21679 			kssl_hold_ent(tcp->tcp_kssl_ent);
21680 			freemsg(mp->b_cont);
21681 			mp->b_cont = NULL;
21682 		}
21683 		tprim->type = T_BIND_REQ;
21684 
21685 	/* FALLTHROUGH */
21686 	case O_T_BIND_REQ:	/* bind request */
21687 	case T_BIND_REQ:	/* new semantics bind request */
21688 		tcp_tpi_bind(tcp, mp);
21689 		break;
21690 	case T_UNBIND_REQ:	/* unbind request */
21691 		tcp_tpi_unbind(tcp, mp);
21692 		break;
21693 	case O_T_CONN_RES:	/* old connection response XXX */
21694 	case T_CONN_RES:	/* connection response */
21695 		tcp_tli_accept(tcp, mp);
21696 		break;
21697 	case T_CONN_REQ:	/* connection request */
21698 		tcp_tpi_connect(tcp, mp);
21699 		break;
21700 	case T_DISCON_REQ:	/* disconnect request */
21701 		tcp_disconnect(tcp, mp);
21702 		break;
21703 	case T_CAPABILITY_REQ:
21704 		tcp_capability_req(tcp, mp);	/* capability request */
21705 		break;
21706 	case T_INFO_REQ:	/* information request */
21707 		tcp_info_req(tcp, mp);
21708 		break;
21709 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21710 	case T_OPTMGMT_REQ:
21711 		/*
21712 		 * Note:  no support for snmpcom_req() through new
21713 		 * T_OPTMGMT_REQ. See comments in ip.c
21714 		 */
21715 
21716 		/*
21717 		 * All Solaris components should pass a db_credp
21718 		 * for this TPI message, hence we ASSERT.
21719 		 * But in case there is some other M_PROTO that looks
21720 		 * like a TPI message sent by some other kernel
21721 		 * component, we check and return an error.
21722 		 */
21723 		cr = msg_getcred(mp, NULL);
21724 		ASSERT(cr != NULL);
21725 		if (cr == NULL) {
21726 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
21727 			return;
21728 		}
21729 		/*
21730 		 * If EINPROGRESS is returned, the request has been queued
21731 		 * for subsequent processing by ip_restart_optmgmt(), which
21732 		 * will do the CONN_DEC_REF().
21733 		 */
21734 		CONN_INC_REF(connp);
21735 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
21736 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21737 			    B_TRUE) != EINPROGRESS) {
21738 				CONN_DEC_REF(connp);
21739 			}
21740 		} else {
21741 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21742 			    B_TRUE) != EINPROGRESS) {
21743 				CONN_DEC_REF(connp);
21744 			}
21745 		}
21746 		break;
21747 
21748 	case T_UNITDATA_REQ:	/* unitdata request */
21749 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21750 		break;
21751 	case T_ORDREL_REQ:	/* orderly release req */
21752 		freemsg(mp);
21753 
21754 		if (tcp->tcp_fused)
21755 			tcp_unfuse(tcp);
21756 
21757 		if (tcp_xmit_end(tcp) != 0) {
21758 			/*
21759 			 * We were crossing FINs and got a reset from
21760 			 * the other side. Just ignore it.
21761 			 */
21762 			if (tcp->tcp_debug) {
21763 				(void) strlog(TCP_MOD_ID, 0, 1,
21764 				    SL_ERROR|SL_TRACE,
21765 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21766 				    "state %s",
21767 				    tcp_display(tcp, NULL,
21768 				    DISP_ADDR_AND_PORT));
21769 			}
21770 		}
21771 		break;
21772 	case T_ADDR_REQ:
21773 		tcp_addr_req(tcp, mp);
21774 		break;
21775 	default:
21776 		if (tcp->tcp_debug) {
21777 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21778 			    "tcp_wput_proto, bogus TPI msg, type %d",
21779 			    tprim->type);
21780 		}
21781 		/*
21782 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21783 		 * to recover.
21784 		 */
21785 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21786 		break;
21787 	}
21788 }
21789 
21790 /*
21791  * The TCP write service routine should never be called...
21792  */
21793 /* ARGSUSED */
21794 static void
21795 tcp_wsrv(queue_t *q)
21796 {
21797 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
21798 
21799 	TCP_STAT(tcps, tcp_wsrv_called);
21800 }
21801 
21802 /* Non overlapping byte exchanger */
21803 static void
21804 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21805 {
21806 	uchar_t	uch;
21807 
21808 	while (len-- > 0) {
21809 		uch = a[len];
21810 		a[len] = b[len];
21811 		b[len] = uch;
21812 	}
21813 }
21814 
21815 /*
21816  * Send out a control packet on the tcp connection specified.  This routine
21817  * is typically called where we need a simple ACK or RST generated.
21818  */
21819 static void
21820 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21821 {
21822 	uchar_t		*rptr;
21823 	tcph_t		*tcph;
21824 	ipha_t		*ipha = NULL;
21825 	ip6_t		*ip6h = NULL;
21826 	uint32_t	sum;
21827 	int		tcp_hdr_len;
21828 	int		tcp_ip_hdr_len;
21829 	mblk_t		*mp;
21830 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21831 
21832 	/*
21833 	 * Save sum for use in source route later.
21834 	 */
21835 	ASSERT(tcp != NULL);
21836 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21837 	tcp_hdr_len = tcp->tcp_hdr_len;
21838 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21839 
21840 	/* If a text string is passed in with the request, pass it to strlog. */
21841 	if (str != NULL && tcp->tcp_debug) {
21842 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21843 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21844 		    str, seq, ack, ctl);
21845 	}
21846 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
21847 	    BPRI_MED);
21848 	if (mp == NULL) {
21849 		return;
21850 	}
21851 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
21852 	mp->b_rptr = rptr;
21853 	mp->b_wptr = &rptr[tcp_hdr_len];
21854 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21855 
21856 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21857 		ipha = (ipha_t *)rptr;
21858 		ipha->ipha_length = htons(tcp_hdr_len);
21859 	} else {
21860 		ip6h = (ip6_t *)rptr;
21861 		ASSERT(tcp != NULL);
21862 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21863 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21864 	}
21865 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21866 	tcph->th_flags[0] = (uint8_t)ctl;
21867 	if (ctl & TH_RST) {
21868 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
21869 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
21870 		/*
21871 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21872 		 */
21873 		if (tcp->tcp_snd_ts_ok &&
21874 		    tcp->tcp_state > TCPS_SYN_SENT) {
21875 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21876 			*(mp->b_wptr) = TCPOPT_EOL;
21877 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21878 				ipha->ipha_length = htons(tcp_hdr_len -
21879 				    TCPOPT_REAL_TS_LEN);
21880 			} else {
21881 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21882 				    TCPOPT_REAL_TS_LEN);
21883 			}
21884 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21885 			sum -= TCPOPT_REAL_TS_LEN;
21886 		}
21887 	}
21888 	if (ctl & TH_ACK) {
21889 		if (tcp->tcp_snd_ts_ok) {
21890 			U32_TO_BE32(lbolt,
21891 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21892 			U32_TO_BE32(tcp->tcp_ts_recent,
21893 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21894 		}
21895 
21896 		/* Update the latest receive window size in TCP header. */
21897 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21898 		    tcph->th_win);
21899 		tcp->tcp_rack = ack;
21900 		tcp->tcp_rack_cnt = 0;
21901 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
21902 	}
21903 	BUMP_LOCAL(tcp->tcp_obsegs);
21904 	U32_TO_BE32(seq, tcph->th_seq);
21905 	U32_TO_BE32(ack, tcph->th_ack);
21906 	/*
21907 	 * Include the adjustment for a source route if any.
21908 	 */
21909 	sum = (sum >> 16) + (sum & 0xFFFF);
21910 	U16_TO_BE16(sum, tcph->th_sum);
21911 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21912 }
21913 
21914 /*
21915  * If this routine returns B_TRUE, TCP can generate a RST in response
21916  * to a segment.  If it returns B_FALSE, TCP should not respond.
21917  */
21918 static boolean_t
21919 tcp_send_rst_chk(tcp_stack_t *tcps)
21920 {
21921 	clock_t	now;
21922 
21923 	/*
21924 	 * TCP needs to protect itself from generating too many RSTs.
21925 	 * This can be a DoS attack by sending us random segments
21926 	 * soliciting RSTs.
21927 	 *
21928 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21929 	 * in each 1 second interval.  In this way, TCP still generate
21930 	 * RSTs in normal cases but when under attack, the impact is
21931 	 * limited.
21932 	 */
21933 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
21934 		now = lbolt;
21935 		/* lbolt can wrap around. */
21936 		if ((tcps->tcps_last_rst_intrvl > now) ||
21937 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
21938 		    1*SECONDS)) {
21939 			tcps->tcps_last_rst_intrvl = now;
21940 			tcps->tcps_rst_cnt = 1;
21941 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
21942 			return (B_FALSE);
21943 		}
21944 	}
21945 	return (B_TRUE);
21946 }
21947 
21948 /*
21949  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21950  */
21951 static void
21952 tcp_ip_ire_mark_advice(tcp_t *tcp)
21953 {
21954 	mblk_t *mp;
21955 	ipic_t *ipic;
21956 
21957 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21958 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21959 		    &ipic);
21960 	} else {
21961 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21962 		    &ipic);
21963 	}
21964 	if (mp == NULL)
21965 		return;
21966 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21967 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21968 }
21969 
21970 /*
21971  * Return an IP advice ioctl mblk and set ipic to be the pointer
21972  * to the advice structure.
21973  */
21974 static mblk_t *
21975 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21976 {
21977 	struct iocblk *ioc;
21978 	mblk_t *mp, *mp1;
21979 
21980 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21981 	if (mp == NULL)
21982 		return (NULL);
21983 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21984 	*ipic = (ipic_t *)mp->b_rptr;
21985 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21986 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21987 
21988 	bcopy(addr, *ipic + 1, addr_len);
21989 
21990 	(*ipic)->ipic_addr_length = addr_len;
21991 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21992 
21993 	mp1 = mkiocb(IP_IOCTL);
21994 	if (mp1 == NULL) {
21995 		freemsg(mp);
21996 		return (NULL);
21997 	}
21998 	mp1->b_cont = mp;
21999 	ioc = (struct iocblk *)mp1->b_rptr;
22000 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22001 
22002 	return (mp1);
22003 }
22004 
22005 /*
22006  * Generate a reset based on an inbound packet, connp is set by caller
22007  * when RST is in response to an unexpected inbound packet for which
22008  * there is active tcp state in the system.
22009  *
22010  * IPSEC NOTE : Try to send the reply with the same protection as it came
22011  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22012  * the packet will go out at the same level of protection as it came in by
22013  * converting the IPSEC_IN to IPSEC_OUT.
22014  */
22015 static void
22016 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22017     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22018     tcp_stack_t *tcps, conn_t *connp)
22019 {
22020 	ipha_t		*ipha = NULL;
22021 	ip6_t		*ip6h = NULL;
22022 	ushort_t	len;
22023 	tcph_t		*tcph;
22024 	int		i;
22025 	mblk_t		*ipsec_mp;
22026 	boolean_t	mctl_present;
22027 	ipic_t		*ipic;
22028 	ipaddr_t	v4addr;
22029 	in6_addr_t	v6addr;
22030 	int		addr_len;
22031 	void		*addr;
22032 	queue_t		*q = tcps->tcps_g_q;
22033 	tcp_t		*tcp;
22034 	cred_t		*cr;
22035 	pid_t		pid;
22036 	mblk_t		*nmp;
22037 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22038 
22039 	if (tcps->tcps_g_q == NULL) {
22040 		/*
22041 		 * For non-zero stackids the default queue isn't created
22042 		 * until the first open, thus there can be a need to send
22043 		 * a reset before then. But we can't do that, hence we just
22044 		 * drop the packet. Later during boot, when the default queue
22045 		 * has been setup, a retransmitted packet from the peer
22046 		 * will result in a reset.
22047 		 */
22048 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22049 		    GLOBAL_NETSTACKID);
22050 		freemsg(mp);
22051 		return;
22052 	}
22053 
22054 	if (connp != NULL)
22055 		tcp = connp->conn_tcp;
22056 	else
22057 		tcp = Q_TO_TCP(q);
22058 
22059 	if (!tcp_send_rst_chk(tcps)) {
22060 		tcps->tcps_rst_unsent++;
22061 		freemsg(mp);
22062 		return;
22063 	}
22064 
22065 	if (mp->b_datap->db_type == M_CTL) {
22066 		ipsec_mp = mp;
22067 		mp = mp->b_cont;
22068 		mctl_present = B_TRUE;
22069 	} else {
22070 		ipsec_mp = mp;
22071 		mctl_present = B_FALSE;
22072 	}
22073 
22074 	if (str && q && tcps->tcps_dbg) {
22075 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22076 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22077 		    "flags 0x%x",
22078 		    str, seq, ack, ctl);
22079 	}
22080 	if (mp->b_datap->db_ref != 1) {
22081 		mblk_t *mp1 = copyb(mp);
22082 		freemsg(mp);
22083 		mp = mp1;
22084 		if (!mp) {
22085 			if (mctl_present)
22086 				freeb(ipsec_mp);
22087 			return;
22088 		} else {
22089 			if (mctl_present) {
22090 				ipsec_mp->b_cont = mp;
22091 			} else {
22092 				ipsec_mp = mp;
22093 			}
22094 		}
22095 	} else if (mp->b_cont) {
22096 		freemsg(mp->b_cont);
22097 		mp->b_cont = NULL;
22098 	}
22099 	/*
22100 	 * We skip reversing source route here.
22101 	 * (for now we replace all IP options with EOL)
22102 	 */
22103 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22104 		ipha = (ipha_t *)mp->b_rptr;
22105 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22106 			mp->b_rptr[i] = IPOPT_EOL;
22107 		/*
22108 		 * Make sure that src address isn't flagrantly invalid.
22109 		 * Not all broadcast address checking for the src address
22110 		 * is possible, since we don't know the netmask of the src
22111 		 * addr.  No check for destination address is done, since
22112 		 * IP will not pass up a packet with a broadcast dest
22113 		 * address to TCP.  Similar checks are done below for IPv6.
22114 		 */
22115 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22116 		    CLASSD(ipha->ipha_src)) {
22117 			freemsg(ipsec_mp);
22118 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22119 			return;
22120 		}
22121 	} else {
22122 		ip6h = (ip6_t *)mp->b_rptr;
22123 
22124 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22125 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22126 			freemsg(ipsec_mp);
22127 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22128 			return;
22129 		}
22130 
22131 		/* Remove any extension headers assuming partial overlay */
22132 		if (ip_hdr_len > IPV6_HDR_LEN) {
22133 			uint8_t *to;
22134 
22135 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22136 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22137 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22138 			ip_hdr_len = IPV6_HDR_LEN;
22139 			ip6h = (ip6_t *)mp->b_rptr;
22140 			ip6h->ip6_nxt = IPPROTO_TCP;
22141 		}
22142 	}
22143 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22144 	if (tcph->th_flags[0] & TH_RST) {
22145 		freemsg(ipsec_mp);
22146 		return;
22147 	}
22148 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22149 	len = ip_hdr_len + sizeof (tcph_t);
22150 	mp->b_wptr = &mp->b_rptr[len];
22151 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22152 		ipha->ipha_length = htons(len);
22153 		/* Swap addresses */
22154 		v4addr = ipha->ipha_src;
22155 		ipha->ipha_src = ipha->ipha_dst;
22156 		ipha->ipha_dst = v4addr;
22157 		ipha->ipha_ident = 0;
22158 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22159 		addr_len = IP_ADDR_LEN;
22160 		addr = &v4addr;
22161 	} else {
22162 		/* No ip6i_t in this case */
22163 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22164 		/* Swap addresses */
22165 		v6addr = ip6h->ip6_src;
22166 		ip6h->ip6_src = ip6h->ip6_dst;
22167 		ip6h->ip6_dst = v6addr;
22168 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22169 		addr_len = IPV6_ADDR_LEN;
22170 		addr = &v6addr;
22171 	}
22172 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22173 	U32_TO_BE32(ack, tcph->th_ack);
22174 	U32_TO_BE32(seq, tcph->th_seq);
22175 	U16_TO_BE16(0, tcph->th_win);
22176 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22177 	tcph->th_flags[0] = (uint8_t)ctl;
22178 	if (ctl & TH_RST) {
22179 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22180 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22181 	}
22182 
22183 	/* IP trusts us to set up labels when required. */
22184 	if (is_system_labeled() && (cr = msg_getcred(mp, &pid)) != NULL &&
22185 	    crgetlabel(cr) != NULL) {
22186 		int err;
22187 
22188 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22189 			err = tsol_check_label(cr, &mp,
22190 			    tcp->tcp_connp->conn_mac_exempt,
22191 			    tcps->tcps_netstack->netstack_ip, pid);
22192 		else
22193 			err = tsol_check_label_v6(cr, &mp,
22194 			    tcp->tcp_connp->conn_mac_exempt,
22195 			    tcps->tcps_netstack->netstack_ip, pid);
22196 		if (mctl_present)
22197 			ipsec_mp->b_cont = mp;
22198 		else
22199 			ipsec_mp = mp;
22200 		if (err != 0) {
22201 			freemsg(ipsec_mp);
22202 			return;
22203 		}
22204 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22205 			ipha = (ipha_t *)mp->b_rptr;
22206 		} else {
22207 			ip6h = (ip6_t *)mp->b_rptr;
22208 		}
22209 	}
22210 
22211 	if (mctl_present) {
22212 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22213 
22214 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22215 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22216 			return;
22217 		}
22218 	}
22219 	if (zoneid == ALL_ZONES)
22220 		zoneid = GLOBAL_ZONEID;
22221 
22222 	/* Add the zoneid so ip_output routes it properly */
22223 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22224 		freemsg(ipsec_mp);
22225 		return;
22226 	}
22227 	ipsec_mp = nmp;
22228 
22229 	/*
22230 	 * NOTE:  one might consider tracing a TCP packet here, but
22231 	 * this function has no active TCP state and no tcp structure
22232 	 * that has a trace buffer.  If we traced here, we would have
22233 	 * to keep a local trace buffer in tcp_record_trace().
22234 	 *
22235 	 * TSol note: The mblk that contains the incoming packet was
22236 	 * reused by tcp_xmit_listener_reset, so it already contains
22237 	 * the right credentials and we don't need to call mblk_setcred.
22238 	 * Also the conn's cred is not right since it is associated
22239 	 * with tcps_g_q.
22240 	 */
22241 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22242 
22243 	/*
22244 	 * Tell IP to mark the IRE used for this destination temporary.
22245 	 * This way, we can limit our exposure to DoS attack because IP
22246 	 * creates an IRE for each destination.  If there are too many,
22247 	 * the time to do any routing lookup will be extremely long.  And
22248 	 * the lookup can be in interrupt context.
22249 	 *
22250 	 * Note that in normal circumstances, this marking should not
22251 	 * affect anything.  It would be nice if only 1 message is
22252 	 * needed to inform IP that the IRE created for this RST should
22253 	 * not be added to the cache table.  But there is currently
22254 	 * not such communication mechanism between TCP and IP.  So
22255 	 * the best we can do now is to send the advice ioctl to IP
22256 	 * to mark the IRE temporary.
22257 	 */
22258 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22259 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22260 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22261 	}
22262 }
22263 
22264 /*
22265  * Initiate closedown sequence on an active connection.  (May be called as
22266  * writer.)  Return value zero for OK return, non-zero for error return.
22267  */
22268 static int
22269 tcp_xmit_end(tcp_t *tcp)
22270 {
22271 	ipic_t	*ipic;
22272 	mblk_t	*mp;
22273 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22274 
22275 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22276 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22277 		/*
22278 		 * Invalid state, only states TCPS_SYN_RCVD,
22279 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22280 		 */
22281 		return (-1);
22282 	}
22283 
22284 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22285 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22286 	/*
22287 	 * If there is nothing more unsent, send the FIN now.
22288 	 * Otherwise, it will go out with the last segment.
22289 	 */
22290 	if (tcp->tcp_unsent == 0) {
22291 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22292 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22293 
22294 		if (mp) {
22295 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22296 		} else {
22297 			/*
22298 			 * Couldn't allocate msg.  Pretend we got it out.
22299 			 * Wait for rexmit timeout.
22300 			 */
22301 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22302 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22303 		}
22304 
22305 		/*
22306 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22307 		 * changed.
22308 		 */
22309 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22310 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22311 		}
22312 	} else {
22313 		/*
22314 		 * If tcp->tcp_cork is set, then the data will not get sent,
22315 		 * so we have to check that and unset it first.
22316 		 */
22317 		if (tcp->tcp_cork)
22318 			tcp->tcp_cork = B_FALSE;
22319 		tcp_wput_data(tcp, NULL, B_FALSE);
22320 	}
22321 
22322 	/*
22323 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22324 	 * is 0, don't update the cache.
22325 	 */
22326 	if (tcps->tcps_rtt_updates == 0 ||
22327 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22328 		return (0);
22329 
22330 	/*
22331 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22332 	 * different from the destination.
22333 	 */
22334 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22335 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22336 			return (0);
22337 		}
22338 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22339 		    &ipic);
22340 	} else {
22341 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22342 		    &tcp->tcp_ip6h->ip6_dst))) {
22343 			return (0);
22344 		}
22345 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22346 		    &ipic);
22347 	}
22348 
22349 	/* Record route attributes in the IRE for use by future connections. */
22350 	if (mp == NULL)
22351 		return (0);
22352 
22353 	/*
22354 	 * We do not have a good algorithm to update ssthresh at this time.
22355 	 * So don't do any update.
22356 	 */
22357 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22358 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22359 
22360 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22361 
22362 	return (0);
22363 }
22364 
22365 /* ARGSUSED */
22366 void
22367 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
22368 {
22369 	conn_t *connp = (conn_t *)arg;
22370 	mblk_t *mp1;
22371 	tcp_t *tcp = connp->conn_tcp;
22372 	tcp_xmit_reset_event_t *eventp;
22373 
22374 	ASSERT(mp->b_datap->db_type == M_PROTO &&
22375 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
22376 
22377 	if (tcp->tcp_state != TCPS_LISTEN) {
22378 		freemsg(mp);
22379 		return;
22380 	}
22381 
22382 	mp1 = mp->b_cont;
22383 	mp->b_cont = NULL;
22384 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
22385 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
22386 	    connp->conn_netstack);
22387 
22388 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
22389 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
22390 	freemsg(mp);
22391 }
22392 
22393 /*
22394  * Generate a "no listener here" RST in response to an "unknown" segment.
22395  * connp is set by caller when RST is in response to an unexpected
22396  * inbound packet for which there is active tcp state in the system.
22397  * Note that we are reusing the incoming mp to construct the outgoing RST.
22398  */
22399 void
22400 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22401     tcp_stack_t *tcps, conn_t *connp)
22402 {
22403 	uchar_t		*rptr;
22404 	uint32_t	seg_len;
22405 	tcph_t		*tcph;
22406 	uint32_t	seg_seq;
22407 	uint32_t	seg_ack;
22408 	uint_t		flags;
22409 	mblk_t		*ipsec_mp;
22410 	ipha_t 		*ipha;
22411 	ip6_t 		*ip6h;
22412 	boolean_t	mctl_present = B_FALSE;
22413 	boolean_t	check = B_TRUE;
22414 	boolean_t	policy_present;
22415 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22416 
22417 	TCP_STAT(tcps, tcp_no_listener);
22418 
22419 	ipsec_mp = mp;
22420 
22421 	if (mp->b_datap->db_type == M_CTL) {
22422 		ipsec_in_t *ii;
22423 
22424 		mctl_present = B_TRUE;
22425 		mp = mp->b_cont;
22426 
22427 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22428 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22429 		if (ii->ipsec_in_dont_check) {
22430 			check = B_FALSE;
22431 			if (!ii->ipsec_in_secure) {
22432 				freeb(ipsec_mp);
22433 				mctl_present = B_FALSE;
22434 				ipsec_mp = mp;
22435 			}
22436 		}
22437 	}
22438 
22439 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22440 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22441 		ipha = (ipha_t *)mp->b_rptr;
22442 		ip6h = NULL;
22443 	} else {
22444 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22445 		ipha = NULL;
22446 		ip6h = (ip6_t *)mp->b_rptr;
22447 	}
22448 
22449 	if (check && policy_present) {
22450 		/*
22451 		 * The conn_t parameter is NULL because we already know
22452 		 * nobody's home.
22453 		 */
22454 		ipsec_mp = ipsec_check_global_policy(
22455 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22456 		    tcps->tcps_netstack);
22457 		if (ipsec_mp == NULL)
22458 			return;
22459 	}
22460 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22461 		DTRACE_PROBE2(
22462 		    tx__ip__log__error__nolistener__tcp,
22463 		    char *, "Could not reply with RST to mp(1)",
22464 		    mblk_t *, mp);
22465 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22466 		freemsg(ipsec_mp);
22467 		return;
22468 	}
22469 
22470 	rptr = mp->b_rptr;
22471 
22472 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22473 	seg_seq = BE32_TO_U32(tcph->th_seq);
22474 	seg_ack = BE32_TO_U32(tcph->th_ack);
22475 	flags = tcph->th_flags[0];
22476 
22477 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22478 	if (flags & TH_RST) {
22479 		freemsg(ipsec_mp);
22480 	} else if (flags & TH_ACK) {
22481 		tcp_xmit_early_reset("no tcp, reset",
22482 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22483 		    connp);
22484 	} else {
22485 		if (flags & TH_SYN) {
22486 			seg_len++;
22487 		} else {
22488 			/*
22489 			 * Here we violate the RFC.  Note that a normal
22490 			 * TCP will never send a segment without the ACK
22491 			 * flag, except for RST or SYN segment.  This
22492 			 * segment is neither.  Just drop it on the
22493 			 * floor.
22494 			 */
22495 			freemsg(ipsec_mp);
22496 			tcps->tcps_rst_unsent++;
22497 			return;
22498 		}
22499 
22500 		tcp_xmit_early_reset("no tcp, reset/ack",
22501 		    ipsec_mp, 0, seg_seq + seg_len,
22502 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22503 	}
22504 }
22505 
22506 /*
22507  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22508  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22509  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22510  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22511  * otherwise it will dup partial mblks.)
22512  * Otherwise, an appropriate ACK packet will be generated.  This
22513  * routine is not usually called to send new data for the first time.  It
22514  * is mostly called out of the timer for retransmits, and to generate ACKs.
22515  *
22516  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22517  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22518  * of the original mblk chain will be returned in *offset and *end_mp.
22519  */
22520 mblk_t *
22521 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22522     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22523     boolean_t rexmit)
22524 {
22525 	int	data_length;
22526 	int32_t	off = 0;
22527 	uint_t	flags;
22528 	mblk_t	*mp1;
22529 	mblk_t	*mp2;
22530 	uchar_t	*rptr;
22531 	tcph_t	*tcph;
22532 	int32_t	num_sack_blk = 0;
22533 	int32_t	sack_opt_len = 0;
22534 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22535 
22536 	/* Allocate for our maximum TCP header + link-level */
22537 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22538 	    tcps->tcps_wroff_xtra, BPRI_MED);
22539 	if (!mp1)
22540 		return (NULL);
22541 	data_length = 0;
22542 
22543 	/*
22544 	 * Note that tcp_mss has been adjusted to take into account the
22545 	 * timestamp option if applicable.  Because SACK options do not
22546 	 * appear in every TCP segments and they are of variable lengths,
22547 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22548 	 * the actual segment length when we need to send a segment which
22549 	 * includes SACK options.
22550 	 */
22551 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22552 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22553 		    tcp->tcp_num_sack_blk);
22554 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22555 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22556 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22557 			max_to_send -= sack_opt_len;
22558 	}
22559 
22560 	if (offset != NULL) {
22561 		off = *offset;
22562 		/* We use offset as an indicator that end_mp is not NULL. */
22563 		*end_mp = NULL;
22564 	}
22565 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22566 		/* This could be faster with cooperation from downstream */
22567 		if (mp2 != mp1 && !sendall &&
22568 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22569 		    max_to_send)
22570 			/*
22571 			 * Don't send the next mblk since the whole mblk
22572 			 * does not fit.
22573 			 */
22574 			break;
22575 		mp2->b_cont = dupb(mp);
22576 		mp2 = mp2->b_cont;
22577 		if (!mp2) {
22578 			freemsg(mp1);
22579 			return (NULL);
22580 		}
22581 		mp2->b_rptr += off;
22582 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22583 		    (uintptr_t)INT_MAX);
22584 
22585 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22586 		if (data_length > max_to_send) {
22587 			mp2->b_wptr -= data_length - max_to_send;
22588 			data_length = max_to_send;
22589 			off = mp2->b_wptr - mp->b_rptr;
22590 			break;
22591 		} else {
22592 			off = 0;
22593 		}
22594 	}
22595 	if (offset != NULL) {
22596 		*offset = off;
22597 		*end_mp = mp;
22598 	}
22599 	if (seg_len != NULL) {
22600 		*seg_len = data_length;
22601 	}
22602 
22603 	/* Update the latest receive window size in TCP header. */
22604 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22605 	    tcp->tcp_tcph->th_win);
22606 
22607 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22608 	mp1->b_rptr = rptr;
22609 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22610 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22611 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22612 	U32_TO_ABE32(seq, tcph->th_seq);
22613 
22614 	/*
22615 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22616 	 * that this function was called from tcp_wput_data. Thus, when called
22617 	 * to retransmit data the setting of the PUSH bit may appear some
22618 	 * what random in that it might get set when it should not. This
22619 	 * should not pose any performance issues.
22620 	 */
22621 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22622 	    tcp->tcp_unsent == data_length)) {
22623 		flags = TH_ACK | TH_PUSH;
22624 	} else {
22625 		flags = TH_ACK;
22626 	}
22627 
22628 	if (tcp->tcp_ecn_ok) {
22629 		if (tcp->tcp_ecn_echo_on)
22630 			flags |= TH_ECE;
22631 
22632 		/*
22633 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22634 		 * There is no TCP flow control for non-data segments, and
22635 		 * only data segment is transmitted reliably.
22636 		 */
22637 		if (data_length > 0 && !rexmit) {
22638 			SET_ECT(tcp, rptr);
22639 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22640 				flags |= TH_CWR;
22641 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22642 			}
22643 		}
22644 	}
22645 
22646 	if (tcp->tcp_valid_bits) {
22647 		uint32_t u1;
22648 
22649 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22650 		    seq == tcp->tcp_iss) {
22651 			uchar_t	*wptr;
22652 
22653 			/*
22654 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22655 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22656 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22657 			 * our SYN is not ack'ed but the app closes this
22658 			 * TCP connection.
22659 			 */
22660 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22661 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22662 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22663 
22664 			/*
22665 			 * Tack on the MSS option.  It is always needed
22666 			 * for both active and passive open.
22667 			 *
22668 			 * MSS option value should be interface MTU - MIN
22669 			 * TCP/IP header according to RFC 793 as it means
22670 			 * the maximum segment size TCP can receive.  But
22671 			 * to get around some broken middle boxes/end hosts
22672 			 * out there, we allow the option value to be the
22673 			 * same as the MSS option size on the peer side.
22674 			 * In this way, the other side will not send
22675 			 * anything larger than they can receive.
22676 			 *
22677 			 * Note that for SYN_SENT state, the ndd param
22678 			 * tcp_use_smss_as_mss_opt has no effect as we
22679 			 * don't know the peer's MSS option value. So
22680 			 * the only case we need to take care of is in
22681 			 * SYN_RCVD state, which is done later.
22682 			 */
22683 			wptr = mp1->b_wptr;
22684 			wptr[0] = TCPOPT_MAXSEG;
22685 			wptr[1] = TCPOPT_MAXSEG_LEN;
22686 			wptr += 2;
22687 			u1 = tcp->tcp_if_mtu -
22688 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22689 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22690 			    TCP_MIN_HEADER_LENGTH;
22691 			U16_TO_BE16(u1, wptr);
22692 			mp1->b_wptr = wptr + 2;
22693 			/* Update the offset to cover the additional word */
22694 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22695 
22696 			/*
22697 			 * Note that the following way of filling in
22698 			 * TCP options are not optimal.  Some NOPs can
22699 			 * be saved.  But there is no need at this time
22700 			 * to optimize it.  When it is needed, we will
22701 			 * do it.
22702 			 */
22703 			switch (tcp->tcp_state) {
22704 			case TCPS_SYN_SENT:
22705 				flags = TH_SYN;
22706 
22707 				if (tcp->tcp_snd_ts_ok) {
22708 					uint32_t llbolt = (uint32_t)lbolt;
22709 
22710 					wptr = mp1->b_wptr;
22711 					wptr[0] = TCPOPT_NOP;
22712 					wptr[1] = TCPOPT_NOP;
22713 					wptr[2] = TCPOPT_TSTAMP;
22714 					wptr[3] = TCPOPT_TSTAMP_LEN;
22715 					wptr += 4;
22716 					U32_TO_BE32(llbolt, wptr);
22717 					wptr += 4;
22718 					ASSERT(tcp->tcp_ts_recent == 0);
22719 					U32_TO_BE32(0L, wptr);
22720 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22721 					tcph->th_offset_and_rsrvd[0] +=
22722 					    (3 << 4);
22723 				}
22724 
22725 				/*
22726 				 * Set up all the bits to tell other side
22727 				 * we are ECN capable.
22728 				 */
22729 				if (tcp->tcp_ecn_ok) {
22730 					flags |= (TH_ECE | TH_CWR);
22731 				}
22732 				break;
22733 			case TCPS_SYN_RCVD:
22734 				flags |= TH_SYN;
22735 
22736 				/*
22737 				 * Reset the MSS option value to be SMSS
22738 				 * We should probably add back the bytes
22739 				 * for timestamp option and IPsec.  We
22740 				 * don't do that as this is a workaround
22741 				 * for broken middle boxes/end hosts, it
22742 				 * is better for us to be more cautious.
22743 				 * They may not take these things into
22744 				 * account in their SMSS calculation.  Thus
22745 				 * the peer's calculated SMSS may be smaller
22746 				 * than what it can be.  This should be OK.
22747 				 */
22748 				if (tcps->tcps_use_smss_as_mss_opt) {
22749 					u1 = tcp->tcp_mss;
22750 					U16_TO_BE16(u1, wptr);
22751 				}
22752 
22753 				/*
22754 				 * If the other side is ECN capable, reply
22755 				 * that we are also ECN capable.
22756 				 */
22757 				if (tcp->tcp_ecn_ok)
22758 					flags |= TH_ECE;
22759 				break;
22760 			default:
22761 				/*
22762 				 * The above ASSERT() makes sure that this
22763 				 * must be FIN-WAIT-1 state.  Our SYN has
22764 				 * not been ack'ed so retransmit it.
22765 				 */
22766 				flags |= TH_SYN;
22767 				break;
22768 			}
22769 
22770 			if (tcp->tcp_snd_ws_ok) {
22771 				wptr = mp1->b_wptr;
22772 				wptr[0] =  TCPOPT_NOP;
22773 				wptr[1] =  TCPOPT_WSCALE;
22774 				wptr[2] =  TCPOPT_WS_LEN;
22775 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22776 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22777 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22778 			}
22779 
22780 			if (tcp->tcp_snd_sack_ok) {
22781 				wptr = mp1->b_wptr;
22782 				wptr[0] = TCPOPT_NOP;
22783 				wptr[1] = TCPOPT_NOP;
22784 				wptr[2] = TCPOPT_SACK_PERMITTED;
22785 				wptr[3] = TCPOPT_SACK_OK_LEN;
22786 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22787 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22788 			}
22789 
22790 			/* allocb() of adequate mblk assures space */
22791 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22792 			    (uintptr_t)INT_MAX);
22793 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22794 			/*
22795 			 * Get IP set to checksum on our behalf
22796 			 * Include the adjustment for a source route if any.
22797 			 */
22798 			u1 += tcp->tcp_sum;
22799 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22800 			U16_TO_BE16(u1, tcph->th_sum);
22801 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22802 		}
22803 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22804 		    (seq + data_length) == tcp->tcp_fss) {
22805 			if (!tcp->tcp_fin_acked) {
22806 				flags |= TH_FIN;
22807 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22808 			}
22809 			if (!tcp->tcp_fin_sent) {
22810 				tcp->tcp_fin_sent = B_TRUE;
22811 				switch (tcp->tcp_state) {
22812 				case TCPS_SYN_RCVD:
22813 				case TCPS_ESTABLISHED:
22814 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22815 					break;
22816 				case TCPS_CLOSE_WAIT:
22817 					tcp->tcp_state = TCPS_LAST_ACK;
22818 					break;
22819 				}
22820 				if (tcp->tcp_suna == tcp->tcp_snxt)
22821 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22822 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22823 			}
22824 		}
22825 		/*
22826 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22827 		 * is smaller than seq, u1 will become a very huge value.
22828 		 * So the comparison will fail.  Also note that tcp_urp
22829 		 * should be positive, see RFC 793 page 17.
22830 		 */
22831 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22832 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22833 		    u1 < (uint32_t)(64 * 1024)) {
22834 			flags |= TH_URG;
22835 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
22836 			U32_TO_ABE16(u1, tcph->th_urp);
22837 		}
22838 	}
22839 	tcph->th_flags[0] = (uchar_t)flags;
22840 	tcp->tcp_rack = tcp->tcp_rnxt;
22841 	tcp->tcp_rack_cnt = 0;
22842 
22843 	if (tcp->tcp_snd_ts_ok) {
22844 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22845 			uint32_t llbolt = (uint32_t)lbolt;
22846 
22847 			U32_TO_BE32(llbolt,
22848 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22849 			U32_TO_BE32(tcp->tcp_ts_recent,
22850 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22851 		}
22852 	}
22853 
22854 	if (num_sack_blk > 0) {
22855 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22856 		sack_blk_t *tmp;
22857 		int32_t	i;
22858 
22859 		wptr[0] = TCPOPT_NOP;
22860 		wptr[1] = TCPOPT_NOP;
22861 		wptr[2] = TCPOPT_SACK;
22862 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22863 		    sizeof (sack_blk_t);
22864 		wptr += TCPOPT_REAL_SACK_LEN;
22865 
22866 		tmp = tcp->tcp_sack_list;
22867 		for (i = 0; i < num_sack_blk; i++) {
22868 			U32_TO_BE32(tmp[i].begin, wptr);
22869 			wptr += sizeof (tcp_seq);
22870 			U32_TO_BE32(tmp[i].end, wptr);
22871 			wptr += sizeof (tcp_seq);
22872 		}
22873 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22874 	}
22875 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22876 	data_length += (int)(mp1->b_wptr - rptr);
22877 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22878 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22879 	} else {
22880 		ip6_t *ip6 = (ip6_t *)(rptr +
22881 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22882 		    sizeof (ip6i_t) : 0));
22883 
22884 		ip6->ip6_plen = htons(data_length -
22885 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22886 	}
22887 
22888 	/*
22889 	 * Prime pump for IP
22890 	 * Include the adjustment for a source route if any.
22891 	 */
22892 	data_length -= tcp->tcp_ip_hdr_len;
22893 	data_length += tcp->tcp_sum;
22894 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22895 	U16_TO_ABE16(data_length, tcph->th_sum);
22896 	if (tcp->tcp_ip_forward_progress) {
22897 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22898 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22899 		tcp->tcp_ip_forward_progress = B_FALSE;
22900 	}
22901 	return (mp1);
22902 }
22903 
22904 /* This function handles the push timeout. */
22905 void
22906 tcp_push_timer(void *arg)
22907 {
22908 	conn_t	*connp = (conn_t *)arg;
22909 	tcp_t *tcp = connp->conn_tcp;
22910 
22911 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
22912 
22913 	ASSERT(tcp->tcp_listener == NULL);
22914 
22915 	ASSERT(!IPCL_IS_NONSTR(connp));
22916 
22917 	/*
22918 	 * We need to plug synchronous streams during our drain to prevent
22919 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
22920 	 */
22921 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
22922 	tcp->tcp_push_tid = 0;
22923 
22924 	if (tcp->tcp_rcv_list != NULL &&
22925 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
22926 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22927 
22928 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
22929 }
22930 
22931 /*
22932  * This function handles delayed ACK timeout.
22933  */
22934 static void
22935 tcp_ack_timer(void *arg)
22936 {
22937 	conn_t	*connp = (conn_t *)arg;
22938 	tcp_t *tcp = connp->conn_tcp;
22939 	mblk_t *mp;
22940 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22941 
22942 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
22943 
22944 	tcp->tcp_ack_tid = 0;
22945 
22946 	if (tcp->tcp_fused)
22947 		return;
22948 
22949 	/*
22950 	 * Do not send ACK if there is no outstanding unack'ed data.
22951 	 */
22952 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22953 		return;
22954 	}
22955 
22956 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22957 		/*
22958 		 * Make sure we don't allow deferred ACKs to result in
22959 		 * timer-based ACKing.  If we have held off an ACK
22960 		 * when there was more than an mss here, and the timer
22961 		 * goes off, we have to worry about the possibility
22962 		 * that the sender isn't doing slow-start, or is out
22963 		 * of step with us for some other reason.  We fall
22964 		 * permanently back in the direction of
22965 		 * ACK-every-other-packet as suggested in RFC 1122.
22966 		 */
22967 		if (tcp->tcp_rack_abs_max > 2)
22968 			tcp->tcp_rack_abs_max--;
22969 		tcp->tcp_rack_cur_max = 2;
22970 	}
22971 	mp = tcp_ack_mp(tcp);
22972 
22973 	if (mp != NULL) {
22974 		BUMP_LOCAL(tcp->tcp_obsegs);
22975 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22976 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
22977 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22978 	}
22979 }
22980 
22981 
22982 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22983 static mblk_t *
22984 tcp_ack_mp(tcp_t *tcp)
22985 {
22986 	uint32_t	seq_no;
22987 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22988 
22989 	/*
22990 	 * There are a few cases to be considered while setting the sequence no.
22991 	 * Essentially, we can come here while processing an unacceptable pkt
22992 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
22993 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
22994 	 * If we are here for a zero window probe, stick with suna. In all
22995 	 * other cases, we check if suna + swnd encompasses snxt and set
22996 	 * the sequence number to snxt, if so. If snxt falls outside the
22997 	 * window (the receiver probably shrunk its window), we will go with
22998 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
22999 	 * receiver.
23000 	 */
23001 	if (tcp->tcp_zero_win_probe) {
23002 		seq_no = tcp->tcp_suna;
23003 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23004 		ASSERT(tcp->tcp_swnd == 0);
23005 		seq_no = tcp->tcp_snxt;
23006 	} else {
23007 		seq_no = SEQ_GT(tcp->tcp_snxt,
23008 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23009 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23010 	}
23011 
23012 	if (tcp->tcp_valid_bits) {
23013 		/*
23014 		 * For the complex case where we have to send some
23015 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23016 		 */
23017 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23018 		    NULL, B_FALSE));
23019 	} else {
23020 		/* Generate a simple ACK */
23021 		int	data_length;
23022 		uchar_t	*rptr;
23023 		tcph_t	*tcph;
23024 		mblk_t	*mp1;
23025 		int32_t	tcp_hdr_len;
23026 		int32_t	tcp_tcp_hdr_len;
23027 		int32_t	num_sack_blk = 0;
23028 		int32_t sack_opt_len;
23029 
23030 		/*
23031 		 * Allocate space for TCP + IP headers
23032 		 * and link-level header
23033 		 */
23034 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23035 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23036 			    tcp->tcp_num_sack_blk);
23037 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23038 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23039 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23040 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23041 		} else {
23042 			tcp_hdr_len = tcp->tcp_hdr_len;
23043 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23044 		}
23045 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23046 		if (!mp1)
23047 			return (NULL);
23048 
23049 		/* Update the latest receive window size in TCP header. */
23050 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23051 		    tcp->tcp_tcph->th_win);
23052 		/* copy in prototype TCP + IP header */
23053 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23054 		mp1->b_rptr = rptr;
23055 		mp1->b_wptr = rptr + tcp_hdr_len;
23056 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23057 
23058 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23059 
23060 		/* Set the TCP sequence number. */
23061 		U32_TO_ABE32(seq_no, tcph->th_seq);
23062 
23063 		/* Set up the TCP flag field. */
23064 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23065 		if (tcp->tcp_ecn_echo_on)
23066 			tcph->th_flags[0] |= TH_ECE;
23067 
23068 		tcp->tcp_rack = tcp->tcp_rnxt;
23069 		tcp->tcp_rack_cnt = 0;
23070 
23071 		/* fill in timestamp option if in use */
23072 		if (tcp->tcp_snd_ts_ok) {
23073 			uint32_t llbolt = (uint32_t)lbolt;
23074 
23075 			U32_TO_BE32(llbolt,
23076 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23077 			U32_TO_BE32(tcp->tcp_ts_recent,
23078 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23079 		}
23080 
23081 		/* Fill in SACK options */
23082 		if (num_sack_blk > 0) {
23083 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23084 			sack_blk_t *tmp;
23085 			int32_t	i;
23086 
23087 			wptr[0] = TCPOPT_NOP;
23088 			wptr[1] = TCPOPT_NOP;
23089 			wptr[2] = TCPOPT_SACK;
23090 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23091 			    sizeof (sack_blk_t);
23092 			wptr += TCPOPT_REAL_SACK_LEN;
23093 
23094 			tmp = tcp->tcp_sack_list;
23095 			for (i = 0; i < num_sack_blk; i++) {
23096 				U32_TO_BE32(tmp[i].begin, wptr);
23097 				wptr += sizeof (tcp_seq);
23098 				U32_TO_BE32(tmp[i].end, wptr);
23099 				wptr += sizeof (tcp_seq);
23100 			}
23101 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23102 			    << 4);
23103 		}
23104 
23105 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23106 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23107 		} else {
23108 			/* Check for ip6i_t header in sticky hdrs */
23109 			ip6_t *ip6 = (ip6_t *)(rptr +
23110 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23111 			    sizeof (ip6i_t) : 0));
23112 
23113 			ip6->ip6_plen = htons(tcp_hdr_len -
23114 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23115 		}
23116 
23117 		/*
23118 		 * Prime pump for checksum calculation in IP.  Include the
23119 		 * adjustment for a source route if any.
23120 		 */
23121 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23122 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23123 		U16_TO_ABE16(data_length, tcph->th_sum);
23124 
23125 		if (tcp->tcp_ip_forward_progress) {
23126 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23127 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23128 			tcp->tcp_ip_forward_progress = B_FALSE;
23129 		}
23130 		return (mp1);
23131 	}
23132 }
23133 
23134 /*
23135  * Hash list insertion routine for tcp_t structures. Each hash bucket
23136  * contains a list of tcp_t entries, and each entry is bound to a unique
23137  * port. If there are multiple tcp_t's that are bound to the same port, then
23138  * one of them will be linked into the hash bucket list, and the rest will
23139  * hang off of that one entry. For each port, entries bound to a specific IP
23140  * address will be inserted before those those bound to INADDR_ANY.
23141  */
23142 static void
23143 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23144 {
23145 	tcp_t	**tcpp;
23146 	tcp_t	*tcpnext;
23147 	tcp_t	*tcphash;
23148 
23149 	if (tcp->tcp_ptpbhn != NULL) {
23150 		ASSERT(!caller_holds_lock);
23151 		tcp_bind_hash_remove(tcp);
23152 	}
23153 	tcpp = &tbf->tf_tcp;
23154 	if (!caller_holds_lock) {
23155 		mutex_enter(&tbf->tf_lock);
23156 	} else {
23157 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23158 	}
23159 	tcphash = tcpp[0];
23160 	tcpnext = NULL;
23161 	if (tcphash != NULL) {
23162 		/* Look for an entry using the same port */
23163 		while ((tcphash = tcpp[0]) != NULL &&
23164 		    tcp->tcp_lport != tcphash->tcp_lport)
23165 			tcpp = &(tcphash->tcp_bind_hash);
23166 
23167 		/* The port was not found, just add to the end */
23168 		if (tcphash == NULL)
23169 			goto insert;
23170 
23171 		/*
23172 		 * OK, there already exists an entry bound to the
23173 		 * same port.
23174 		 *
23175 		 * If the new tcp bound to the INADDR_ANY address
23176 		 * and the first one in the list is not bound to
23177 		 * INADDR_ANY we skip all entries until we find the
23178 		 * first one bound to INADDR_ANY.
23179 		 * This makes sure that applications binding to a
23180 		 * specific address get preference over those binding to
23181 		 * INADDR_ANY.
23182 		 */
23183 		tcpnext = tcphash;
23184 		tcphash = NULL;
23185 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23186 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23187 			while ((tcpnext = tcpp[0]) != NULL &&
23188 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23189 				tcpp = &(tcpnext->tcp_bind_hash_port);
23190 
23191 			if (tcpnext) {
23192 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23193 				tcphash = tcpnext->tcp_bind_hash;
23194 				if (tcphash != NULL) {
23195 					tcphash->tcp_ptpbhn =
23196 					    &(tcp->tcp_bind_hash);
23197 					tcpnext->tcp_bind_hash = NULL;
23198 				}
23199 			}
23200 		} else {
23201 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23202 			tcphash = tcpnext->tcp_bind_hash;
23203 			if (tcphash != NULL) {
23204 				tcphash->tcp_ptpbhn =
23205 				    &(tcp->tcp_bind_hash);
23206 				tcpnext->tcp_bind_hash = NULL;
23207 			}
23208 		}
23209 	}
23210 insert:
23211 	tcp->tcp_bind_hash_port = tcpnext;
23212 	tcp->tcp_bind_hash = tcphash;
23213 	tcp->tcp_ptpbhn = tcpp;
23214 	tcpp[0] = tcp;
23215 	if (!caller_holds_lock)
23216 		mutex_exit(&tbf->tf_lock);
23217 }
23218 
23219 /*
23220  * Hash list removal routine for tcp_t structures.
23221  */
23222 static void
23223 tcp_bind_hash_remove(tcp_t *tcp)
23224 {
23225 	tcp_t	*tcpnext;
23226 	kmutex_t *lockp;
23227 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23228 
23229 	if (tcp->tcp_ptpbhn == NULL)
23230 		return;
23231 
23232 	/*
23233 	 * Extract the lock pointer in case there are concurrent
23234 	 * hash_remove's for this instance.
23235 	 */
23236 	ASSERT(tcp->tcp_lport != 0);
23237 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23238 
23239 	ASSERT(lockp != NULL);
23240 	mutex_enter(lockp);
23241 	if (tcp->tcp_ptpbhn) {
23242 		tcpnext = tcp->tcp_bind_hash_port;
23243 		if (tcpnext != NULL) {
23244 			tcp->tcp_bind_hash_port = NULL;
23245 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23246 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23247 			if (tcpnext->tcp_bind_hash != NULL) {
23248 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23249 				    &(tcpnext->tcp_bind_hash);
23250 				tcp->tcp_bind_hash = NULL;
23251 			}
23252 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23253 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23254 			tcp->tcp_bind_hash = NULL;
23255 		}
23256 		*tcp->tcp_ptpbhn = tcpnext;
23257 		tcp->tcp_ptpbhn = NULL;
23258 	}
23259 	mutex_exit(lockp);
23260 }
23261 
23262 
23263 /*
23264  * Hash list lookup routine for tcp_t structures.
23265  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23266  */
23267 static tcp_t *
23268 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23269 {
23270 	tf_t	*tf;
23271 	tcp_t	*tcp;
23272 
23273 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23274 	mutex_enter(&tf->tf_lock);
23275 	for (tcp = tf->tf_tcp; tcp != NULL;
23276 	    tcp = tcp->tcp_acceptor_hash) {
23277 		if (tcp->tcp_acceptor_id == id) {
23278 			CONN_INC_REF(tcp->tcp_connp);
23279 			mutex_exit(&tf->tf_lock);
23280 			return (tcp);
23281 		}
23282 	}
23283 	mutex_exit(&tf->tf_lock);
23284 	return (NULL);
23285 }
23286 
23287 
23288 /*
23289  * Hash list insertion routine for tcp_t structures.
23290  */
23291 void
23292 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23293 {
23294 	tf_t	*tf;
23295 	tcp_t	**tcpp;
23296 	tcp_t	*tcpnext;
23297 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23298 
23299 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23300 
23301 	if (tcp->tcp_ptpahn != NULL)
23302 		tcp_acceptor_hash_remove(tcp);
23303 	tcpp = &tf->tf_tcp;
23304 	mutex_enter(&tf->tf_lock);
23305 	tcpnext = tcpp[0];
23306 	if (tcpnext)
23307 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23308 	tcp->tcp_acceptor_hash = tcpnext;
23309 	tcp->tcp_ptpahn = tcpp;
23310 	tcpp[0] = tcp;
23311 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23312 	mutex_exit(&tf->tf_lock);
23313 }
23314 
23315 /*
23316  * Hash list removal routine for tcp_t structures.
23317  */
23318 static void
23319 tcp_acceptor_hash_remove(tcp_t *tcp)
23320 {
23321 	tcp_t	*tcpnext;
23322 	kmutex_t *lockp;
23323 
23324 	/*
23325 	 * Extract the lock pointer in case there are concurrent
23326 	 * hash_remove's for this instance.
23327 	 */
23328 	lockp = tcp->tcp_acceptor_lockp;
23329 
23330 	if (tcp->tcp_ptpahn == NULL)
23331 		return;
23332 
23333 	ASSERT(lockp != NULL);
23334 	mutex_enter(lockp);
23335 	if (tcp->tcp_ptpahn) {
23336 		tcpnext = tcp->tcp_acceptor_hash;
23337 		if (tcpnext) {
23338 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23339 			tcp->tcp_acceptor_hash = NULL;
23340 		}
23341 		*tcp->tcp_ptpahn = tcpnext;
23342 		tcp->tcp_ptpahn = NULL;
23343 	}
23344 	mutex_exit(lockp);
23345 	tcp->tcp_acceptor_lockp = NULL;
23346 }
23347 
23348 /*
23349  * Type three generator adapted from the random() function in 4.4 BSD:
23350  */
23351 
23352 /*
23353  * Copyright (c) 1983, 1993
23354  *	The Regents of the University of California.  All rights reserved.
23355  *
23356  * Redistribution and use in source and binary forms, with or without
23357  * modification, are permitted provided that the following conditions
23358  * are met:
23359  * 1. Redistributions of source code must retain the above copyright
23360  *    notice, this list of conditions and the following disclaimer.
23361  * 2. Redistributions in binary form must reproduce the above copyright
23362  *    notice, this list of conditions and the following disclaimer in the
23363  *    documentation and/or other materials provided with the distribution.
23364  * 3. All advertising materials mentioning features or use of this software
23365  *    must display the following acknowledgement:
23366  *	This product includes software developed by the University of
23367  *	California, Berkeley and its contributors.
23368  * 4. Neither the name of the University nor the names of its contributors
23369  *    may be used to endorse or promote products derived from this software
23370  *    without specific prior written permission.
23371  *
23372  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23373  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23374  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23375  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23376  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23377  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23378  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23379  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23380  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23381  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23382  * SUCH DAMAGE.
23383  */
23384 
23385 /* Type 3 -- x**31 + x**3 + 1 */
23386 #define	DEG_3		31
23387 #define	SEP_3		3
23388 
23389 
23390 /* Protected by tcp_random_lock */
23391 static int tcp_randtbl[DEG_3 + 1];
23392 
23393 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23394 static int *tcp_random_rptr = &tcp_randtbl[1];
23395 
23396 static int *tcp_random_state = &tcp_randtbl[1];
23397 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23398 
23399 kmutex_t tcp_random_lock;
23400 
23401 void
23402 tcp_random_init(void)
23403 {
23404 	int i;
23405 	hrtime_t hrt;
23406 	time_t wallclock;
23407 	uint64_t result;
23408 
23409 	/*
23410 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23411 	 * a longlong, which may contain resolution down to nanoseconds.
23412 	 * The current time will either be a 32-bit or a 64-bit quantity.
23413 	 * XOR the two together in a 64-bit result variable.
23414 	 * Convert the result to a 32-bit value by multiplying the high-order
23415 	 * 32-bits by the low-order 32-bits.
23416 	 */
23417 
23418 	hrt = gethrtime();
23419 	(void) drv_getparm(TIME, &wallclock);
23420 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23421 	mutex_enter(&tcp_random_lock);
23422 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23423 	    (result & 0xffffffff);
23424 
23425 	for (i = 1; i < DEG_3; i++)
23426 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23427 		    + 12345;
23428 	tcp_random_fptr = &tcp_random_state[SEP_3];
23429 	tcp_random_rptr = &tcp_random_state[0];
23430 	mutex_exit(&tcp_random_lock);
23431 	for (i = 0; i < 10 * DEG_3; i++)
23432 		(void) tcp_random();
23433 }
23434 
23435 /*
23436  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23437  * This range is selected to be approximately centered on TCP_ISS / 2,
23438  * and easy to compute. We get this value by generating a 32-bit random
23439  * number, selecting out the high-order 17 bits, and then adding one so
23440  * that we never return zero.
23441  */
23442 int
23443 tcp_random(void)
23444 {
23445 	int i;
23446 
23447 	mutex_enter(&tcp_random_lock);
23448 	*tcp_random_fptr += *tcp_random_rptr;
23449 
23450 	/*
23451 	 * The high-order bits are more random than the low-order bits,
23452 	 * so we select out the high-order 17 bits and add one so that
23453 	 * we never return zero.
23454 	 */
23455 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23456 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23457 		tcp_random_fptr = tcp_random_state;
23458 		++tcp_random_rptr;
23459 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23460 		tcp_random_rptr = tcp_random_state;
23461 
23462 	mutex_exit(&tcp_random_lock);
23463 	return (i);
23464 }
23465 
23466 static int
23467 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23468     int *t_errorp, int *sys_errorp)
23469 {
23470 	int error;
23471 	int is_absreq_failure;
23472 	t_scalar_t *opt_lenp;
23473 	t_scalar_t opt_offset;
23474 	int prim_type;
23475 	struct T_conn_req *tcreqp;
23476 	struct T_conn_res *tcresp;
23477 	cred_t *cr;
23478 
23479 	/*
23480 	 * All Solaris components should pass a db_credp
23481 	 * for this TPI message, hence we ASSERT.
23482 	 * But in case there is some other M_PROTO that looks
23483 	 * like a TPI message sent by some other kernel
23484 	 * component, we check and return an error.
23485 	 */
23486 	cr = msg_getcred(mp, NULL);
23487 	ASSERT(cr != NULL);
23488 	if (cr == NULL)
23489 		return (-1);
23490 
23491 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23492 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23493 	    prim_type == T_CONN_RES);
23494 
23495 	switch (prim_type) {
23496 	case T_CONN_REQ:
23497 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23498 		opt_offset = tcreqp->OPT_offset;
23499 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23500 		break;
23501 	case O_T_CONN_RES:
23502 	case T_CONN_RES:
23503 		tcresp = (struct T_conn_res *)mp->b_rptr;
23504 		opt_offset = tcresp->OPT_offset;
23505 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23506 		break;
23507 	}
23508 
23509 	*t_errorp = 0;
23510 	*sys_errorp = 0;
23511 	*do_disconnectp = 0;
23512 
23513 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23514 	    opt_offset, cr, &tcp_opt_obj,
23515 	    NULL, &is_absreq_failure);
23516 
23517 	switch (error) {
23518 	case  0:		/* no error */
23519 		ASSERT(is_absreq_failure == 0);
23520 		return (0);
23521 	case ENOPROTOOPT:
23522 		*t_errorp = TBADOPT;
23523 		break;
23524 	case EACCES:
23525 		*t_errorp = TACCES;
23526 		break;
23527 	default:
23528 		*t_errorp = TSYSERR; *sys_errorp = error;
23529 		break;
23530 	}
23531 	if (is_absreq_failure != 0) {
23532 		/*
23533 		 * The connection request should get the local ack
23534 		 * T_OK_ACK and then a T_DISCON_IND.
23535 		 */
23536 		*do_disconnectp = 1;
23537 	}
23538 	return (-1);
23539 }
23540 
23541 /*
23542  * Split this function out so that if the secret changes, I'm okay.
23543  *
23544  * Initialize the tcp_iss_cookie and tcp_iss_key.
23545  */
23546 
23547 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23548 
23549 static void
23550 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
23551 {
23552 	struct {
23553 		int32_t current_time;
23554 		uint32_t randnum;
23555 		uint16_t pad;
23556 		uint8_t ether[6];
23557 		uint8_t passwd[PASSWD_SIZE];
23558 	} tcp_iss_cookie;
23559 	time_t t;
23560 
23561 	/*
23562 	 * Start with the current absolute time.
23563 	 */
23564 	(void) drv_getparm(TIME, &t);
23565 	tcp_iss_cookie.current_time = t;
23566 
23567 	/*
23568 	 * XXX - Need a more random number per RFC 1750, not this crap.
23569 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23570 	 */
23571 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23572 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23573 
23574 	/*
23575 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23576 	 * as a good template.
23577 	 */
23578 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23579 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23580 
23581 	/*
23582 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23583 	 */
23584 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23585 
23586 	/*
23587 	 * See 4010593 if this section becomes a problem again,
23588 	 * but the local ethernet address is useful here.
23589 	 */
23590 	(void) localetheraddr(NULL,
23591 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23592 
23593 	/*
23594 	 * Hash 'em all together.  The MD5Final is called per-connection.
23595 	 */
23596 	mutex_enter(&tcps->tcps_iss_key_lock);
23597 	MD5Init(&tcps->tcps_iss_key);
23598 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
23599 	    sizeof (tcp_iss_cookie));
23600 	mutex_exit(&tcps->tcps_iss_key_lock);
23601 }
23602 
23603 /*
23604  * Set the RFC 1948 pass phrase
23605  */
23606 /* ARGSUSED */
23607 static int
23608 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23609     cred_t *cr)
23610 {
23611 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23612 
23613 	/*
23614 	 * Basically, value contains a new pass phrase.  Pass it along!
23615 	 */
23616 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
23617 	return (0);
23618 }
23619 
23620 /* ARGSUSED */
23621 static int
23622 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23623 {
23624 	bzero(buf, sizeof (tcp_sack_info_t));
23625 	return (0);
23626 }
23627 
23628 /* ARGSUSED */
23629 static int
23630 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23631 {
23632 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23633 	return (0);
23634 }
23635 
23636 /*
23637  * Make sure we wait until the default queue is setup, yet allow
23638  * tcp_g_q_create() to open a TCP stream.
23639  * We need to allow tcp_g_q_create() do do an open
23640  * of tcp, hence we compare curhread.
23641  * All others have to wait until the tcps_g_q has been
23642  * setup.
23643  */
23644 void
23645 tcp_g_q_setup(tcp_stack_t *tcps)
23646 {
23647 	mutex_enter(&tcps->tcps_g_q_lock);
23648 	if (tcps->tcps_g_q != NULL) {
23649 		mutex_exit(&tcps->tcps_g_q_lock);
23650 		return;
23651 	}
23652 	if (tcps->tcps_g_q_creator == NULL) {
23653 		/* This thread will set it up */
23654 		tcps->tcps_g_q_creator = curthread;
23655 		mutex_exit(&tcps->tcps_g_q_lock);
23656 		tcp_g_q_create(tcps);
23657 		mutex_enter(&tcps->tcps_g_q_lock);
23658 		ASSERT(tcps->tcps_g_q_creator == curthread);
23659 		tcps->tcps_g_q_creator = NULL;
23660 		cv_signal(&tcps->tcps_g_q_cv);
23661 		ASSERT(tcps->tcps_g_q != NULL);
23662 		mutex_exit(&tcps->tcps_g_q_lock);
23663 		return;
23664 	}
23665 	/* Everybody but the creator has to wait */
23666 	if (tcps->tcps_g_q_creator != curthread) {
23667 		while (tcps->tcps_g_q == NULL)
23668 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
23669 	}
23670 	mutex_exit(&tcps->tcps_g_q_lock);
23671 }
23672 
23673 #define	IP	"ip"
23674 
23675 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
23676 
23677 /*
23678  * Create a default tcp queue here instead of in strplumb
23679  */
23680 void
23681 tcp_g_q_create(tcp_stack_t *tcps)
23682 {
23683 	int error;
23684 	ldi_handle_t	lh = NULL;
23685 	ldi_ident_t	li = NULL;
23686 	int		rval;
23687 	cred_t		*cr;
23688 	major_t IP_MAJ;
23689 
23690 #ifdef NS_DEBUG
23691 	(void) printf("tcp_g_q_create()\n");
23692 #endif
23693 
23694 	IP_MAJ = ddi_name_to_major(IP);
23695 
23696 	ASSERT(tcps->tcps_g_q_creator == curthread);
23697 
23698 	error = ldi_ident_from_major(IP_MAJ, &li);
23699 	if (error) {
23700 #ifdef DEBUG
23701 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
23702 		    error);
23703 #endif
23704 		return;
23705 	}
23706 
23707 	cr = zone_get_kcred(netstackid_to_zoneid(
23708 	    tcps->tcps_netstack->netstack_stackid));
23709 	ASSERT(cr != NULL);
23710 	/*
23711 	 * We set the tcp default queue to IPv6 because IPv4 falls
23712 	 * back to IPv6 when it can't find a client, but
23713 	 * IPv6 does not fall back to IPv4.
23714 	 */
23715 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
23716 	if (error) {
23717 #ifdef DEBUG
23718 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
23719 		    error);
23720 #endif
23721 		goto out;
23722 	}
23723 
23724 	/*
23725 	 * This ioctl causes the tcp framework to cache a pointer to
23726 	 * this stream, so we don't want to close the stream after
23727 	 * this operation.
23728 	 * Use the kernel credentials that are for the zone we're in.
23729 	 */
23730 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
23731 	    (intptr_t)0, FKIOCTL, cr, &rval);
23732 	if (error) {
23733 #ifdef DEBUG
23734 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
23735 		    "error %d\n", error);
23736 #endif
23737 		goto out;
23738 	}
23739 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
23740 	lh = NULL;
23741 out:
23742 	/* Close layered handles */
23743 	if (li)
23744 		ldi_ident_release(li);
23745 	/* Keep cred around until _inactive needs it */
23746 	tcps->tcps_g_q_cr = cr;
23747 }
23748 
23749 /*
23750  * We keep tcp_g_q set until all other tcp_t's in the zone
23751  * has gone away, and then when tcp_g_q_inactive() is called
23752  * we clear it.
23753  */
23754 void
23755 tcp_g_q_destroy(tcp_stack_t *tcps)
23756 {
23757 #ifdef NS_DEBUG
23758 	(void) printf("tcp_g_q_destroy()for stack %d\n",
23759 	    tcps->tcps_netstack->netstack_stackid);
23760 #endif
23761 
23762 	if (tcps->tcps_g_q == NULL) {
23763 		return;	/* Nothing to cleanup */
23764 	}
23765 	/*
23766 	 * Drop reference corresponding to the default queue.
23767 	 * This reference was added from tcp_open when the default queue
23768 	 * was created, hence we compensate for this extra drop in
23769 	 * tcp_g_q_close. If the refcnt drops to zero here it means
23770 	 * the default queue was the last one to be open, in which
23771 	 * case, then tcp_g_q_inactive will be
23772 	 * called as a result of the refrele.
23773 	 */
23774 	TCPS_REFRELE(tcps);
23775 }
23776 
23777 /*
23778  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23779  * Run by tcp_q_q_inactive using a taskq.
23780  */
23781 static void
23782 tcp_g_q_close(void *arg)
23783 {
23784 	tcp_stack_t *tcps = arg;
23785 	int error;
23786 	ldi_handle_t	lh = NULL;
23787 	ldi_ident_t	li = NULL;
23788 	cred_t		*cr;
23789 	major_t IP_MAJ;
23790 
23791 	IP_MAJ = ddi_name_to_major(IP);
23792 
23793 #ifdef NS_DEBUG
23794 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
23795 	    tcps->tcps_netstack->netstack_stackid,
23796 	    tcps->tcps_netstack->netstack_refcnt);
23797 #endif
23798 	lh = tcps->tcps_g_q_lh;
23799 	if (lh == NULL)
23800 		return;	/* Nothing to cleanup */
23801 
23802 	ASSERT(tcps->tcps_refcnt == 1);
23803 	ASSERT(tcps->tcps_g_q != NULL);
23804 
23805 	error = ldi_ident_from_major(IP_MAJ, &li);
23806 	if (error) {
23807 #ifdef DEBUG
23808 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
23809 		    error);
23810 #endif
23811 		return;
23812 	}
23813 
23814 	cr = tcps->tcps_g_q_cr;
23815 	tcps->tcps_g_q_cr = NULL;
23816 	ASSERT(cr != NULL);
23817 
23818 	/*
23819 	 * Make sure we can break the recursion when tcp_close decrements
23820 	 * the reference count causing g_q_inactive to be called again.
23821 	 */
23822 	tcps->tcps_g_q_lh = NULL;
23823 
23824 	/* close the default queue */
23825 	(void) ldi_close(lh, FREAD|FWRITE, cr);
23826 	/*
23827 	 * At this point in time tcps and the rest of netstack_t might
23828 	 * have been deleted.
23829 	 */
23830 	tcps = NULL;
23831 
23832 	/* Close layered handles */
23833 	ldi_ident_release(li);
23834 	crfree(cr);
23835 }
23836 
23837 /*
23838  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23839  *
23840  * Have to ensure that the ldi routines are not used by an
23841  * interrupt thread by using a taskq.
23842  */
23843 void
23844 tcp_g_q_inactive(tcp_stack_t *tcps)
23845 {
23846 	if (tcps->tcps_g_q_lh == NULL)
23847 		return;	/* Nothing to cleanup */
23848 
23849 	ASSERT(tcps->tcps_refcnt == 0);
23850 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
23851 
23852 	if (servicing_interrupt()) {
23853 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
23854 		    (void *) tcps, TQ_SLEEP);
23855 	} else {
23856 		tcp_g_q_close(tcps);
23857 	}
23858 }
23859 
23860 /*
23861  * Called by IP when IP is loaded into the kernel
23862  */
23863 void
23864 tcp_ddi_g_init(void)
23865 {
23866 	tcp_timercache = kmem_cache_create("tcp_timercache",
23867 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23868 	    NULL, NULL, NULL, NULL, NULL, 0);
23869 
23870 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23871 	    sizeof (tcp_sack_info_t), 0,
23872 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23873 
23874 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23875 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23876 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23877 
23878 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23879 
23880 	/* Initialize the random number generator */
23881 	tcp_random_init();
23882 
23883 	/* A single callback independently of how many netstacks we have */
23884 	ip_squeue_init(tcp_squeue_add);
23885 
23886 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
23887 
23888 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
23889 	    TASKQ_PREPOPULATE);
23890 
23891 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
23892 
23893 	/*
23894 	 * We want to be informed each time a stack is created or
23895 	 * destroyed in the kernel, so we can maintain the
23896 	 * set of tcp_stack_t's.
23897 	 */
23898 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
23899 	    tcp_stack_fini);
23900 }
23901 
23902 
23903 #define	INET_NAME	"ip"
23904 
23905 /*
23906  * Initialize the TCP stack instance.
23907  */
23908 static void *
23909 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
23910 {
23911 	tcp_stack_t	*tcps;
23912 	tcpparam_t	*pa;
23913 	int		i;
23914 	int		error = 0;
23915 	major_t		major;
23916 
23917 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
23918 	tcps->tcps_netstack = ns;
23919 
23920 	/* Initialize locks */
23921 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23922 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
23923 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23924 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23925 
23926 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
23927 	tcps->tcps_g_epriv_ports[0] = 2049;
23928 	tcps->tcps_g_epriv_ports[1] = 4045;
23929 	tcps->tcps_min_anonpriv_port = 512;
23930 
23931 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
23932 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
23933 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
23934 	    TCP_FANOUT_SIZE, KM_SLEEP);
23935 
23936 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
23937 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
23938 		    MUTEX_DEFAULT, NULL);
23939 	}
23940 
23941 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
23942 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
23943 		    MUTEX_DEFAULT, NULL);
23944 	}
23945 
23946 	/* TCP's IPsec code calls the packet dropper. */
23947 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
23948 
23949 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
23950 	tcps->tcps_params = pa;
23951 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
23952 
23953 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
23954 	    A_CNT(lcl_tcp_param_arr), tcps);
23955 
23956 	/*
23957 	 * Note: To really walk the device tree you need the devinfo
23958 	 * pointer to your device which is only available after probe/attach.
23959 	 * The following is safe only because it uses ddi_root_node()
23960 	 */
23961 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23962 	    tcp_opt_obj.odb_opt_arr_cnt);
23963 
23964 	/*
23965 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23966 	 * by the boot scripts.
23967 	 *
23968 	 * Use NULL name, as the name is caught by the new lockstats.
23969 	 *
23970 	 * Initialize with some random, non-guessable string, like the global
23971 	 * T_INFO_ACK.
23972 	 */
23973 
23974 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23975 	    sizeof (tcp_g_t_info_ack), tcps);
23976 
23977 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
23978 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
23979 
23980 	major = mod_name_to_major(INET_NAME);
23981 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
23982 	ASSERT(error == 0);
23983 	return (tcps);
23984 }
23985 
23986 /*
23987  * Called when the IP module is about to be unloaded.
23988  */
23989 void
23990 tcp_ddi_g_destroy(void)
23991 {
23992 	tcp_g_kstat_fini(tcp_g_kstat);
23993 	tcp_g_kstat = NULL;
23994 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
23995 
23996 	mutex_destroy(&tcp_random_lock);
23997 
23998 	kmem_cache_destroy(tcp_timercache);
23999 	kmem_cache_destroy(tcp_sack_info_cache);
24000 	kmem_cache_destroy(tcp_iphc_cache);
24001 
24002 	netstack_unregister(NS_TCP);
24003 	taskq_destroy(tcp_taskq);
24004 }
24005 
24006 /*
24007  * Shut down the TCP stack instance.
24008  */
24009 /* ARGSUSED */
24010 static void
24011 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24012 {
24013 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24014 
24015 	tcp_g_q_destroy(tcps);
24016 }
24017 
24018 /*
24019  * Free the TCP stack instance.
24020  */
24021 static void
24022 tcp_stack_fini(netstackid_t stackid, void *arg)
24023 {
24024 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24025 	int i;
24026 
24027 	nd_free(&tcps->tcps_g_nd);
24028 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24029 	tcps->tcps_params = NULL;
24030 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24031 	tcps->tcps_wroff_xtra_param = NULL;
24032 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24033 	tcps->tcps_mdt_head_param = NULL;
24034 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24035 	tcps->tcps_mdt_tail_param = NULL;
24036 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24037 	tcps->tcps_mdt_max_pbufs_param = NULL;
24038 
24039 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24040 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24041 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24042 	}
24043 
24044 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24045 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24046 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24047 	}
24048 
24049 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24050 	tcps->tcps_bind_fanout = NULL;
24051 
24052 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24053 	tcps->tcps_acceptor_fanout = NULL;
24054 
24055 	mutex_destroy(&tcps->tcps_iss_key_lock);
24056 	mutex_destroy(&tcps->tcps_g_q_lock);
24057 	cv_destroy(&tcps->tcps_g_q_cv);
24058 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24059 
24060 	ip_drop_unregister(&tcps->tcps_dropper);
24061 
24062 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24063 	tcps->tcps_kstat = NULL;
24064 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24065 
24066 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24067 	tcps->tcps_mibkp = NULL;
24068 
24069 	ldi_ident_release(tcps->tcps_ldi_ident);
24070 	kmem_free(tcps, sizeof (*tcps));
24071 }
24072 
24073 /*
24074  * Generate ISS, taking into account NDD changes may happen halfway through.
24075  * (If the iss is not zero, set it.)
24076  */
24077 
24078 static void
24079 tcp_iss_init(tcp_t *tcp)
24080 {
24081 	MD5_CTX context;
24082 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24083 	uint32_t answer[4];
24084 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24085 
24086 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24087 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24088 	switch (tcps->tcps_strong_iss) {
24089 	case 2:
24090 		mutex_enter(&tcps->tcps_iss_key_lock);
24091 		context = tcps->tcps_iss_key;
24092 		mutex_exit(&tcps->tcps_iss_key_lock);
24093 		arg.ports = tcp->tcp_ports;
24094 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24095 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24096 			    &arg.src);
24097 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24098 			    &arg.dst);
24099 		} else {
24100 			arg.src = tcp->tcp_ip6h->ip6_src;
24101 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24102 		}
24103 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24104 		MD5Final((uchar_t *)answer, &context);
24105 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24106 		/*
24107 		 * Now that we've hashed into a unique per-connection sequence
24108 		 * space, add a random increment per strong_iss == 1.  So I
24109 		 * guess we'll have to...
24110 		 */
24111 		/* FALLTHRU */
24112 	case 1:
24113 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24114 		break;
24115 	default:
24116 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24117 		break;
24118 	}
24119 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24120 	tcp->tcp_fss = tcp->tcp_iss - 1;
24121 	tcp->tcp_suna = tcp->tcp_iss;
24122 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24123 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24124 	tcp->tcp_csuna = tcp->tcp_snxt;
24125 }
24126 
24127 /*
24128  * Exported routine for extracting active tcp connection status.
24129  *
24130  * This is used by the Solaris Cluster Networking software to
24131  * gather a list of connections that need to be forwarded to
24132  * specific nodes in the cluster when configuration changes occur.
24133  *
24134  * The callback is invoked for each tcp_t structure from all netstacks,
24135  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24136  * from the netstack with the specified stack_id. Returning
24137  * non-zero from the callback routine terminates the search.
24138  */
24139 int
24140 cl_tcp_walk_list(netstackid_t stack_id,
24141     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24142 {
24143 	netstack_handle_t nh;
24144 	netstack_t *ns;
24145 	int ret = 0;
24146 
24147 	if (stack_id >= 0) {
24148 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24149 			return (EINVAL);
24150 
24151 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24152 		    ns->netstack_tcp);
24153 		netstack_rele(ns);
24154 		return (ret);
24155 	}
24156 
24157 	netstack_next_init(&nh);
24158 	while ((ns = netstack_next(&nh)) != NULL) {
24159 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24160 		    ns->netstack_tcp);
24161 		netstack_rele(ns);
24162 	}
24163 	netstack_next_fini(&nh);
24164 	return (ret);
24165 }
24166 
24167 static int
24168 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
24169     tcp_stack_t *tcps)
24170 {
24171 	tcp_t *tcp;
24172 	cl_tcp_info_t	cl_tcpi;
24173 	connf_t	*connfp;
24174 	conn_t	*connp;
24175 	int	i;
24176 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24177 
24178 	ASSERT(callback != NULL);
24179 
24180 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24181 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
24182 		connp = NULL;
24183 
24184 		while ((connp =
24185 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24186 
24187 			tcp = connp->conn_tcp;
24188 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24189 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24190 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24191 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24192 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24193 			/*
24194 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24195 			 * addresses. They are copied implicitly below as
24196 			 * mapped addresses.
24197 			 */
24198 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24199 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24200 				cl_tcpi.cl_tcpi_faddr =
24201 				    tcp->tcp_ipha->ipha_dst;
24202 			} else {
24203 				cl_tcpi.cl_tcpi_faddr_v6 =
24204 				    tcp->tcp_ip6h->ip6_dst;
24205 			}
24206 
24207 			/*
24208 			 * If the callback returns non-zero
24209 			 * we terminate the traversal.
24210 			 */
24211 			if ((*callback)(&cl_tcpi, arg) != 0) {
24212 				CONN_DEC_REF(tcp->tcp_connp);
24213 				return (1);
24214 			}
24215 		}
24216 	}
24217 
24218 	return (0);
24219 }
24220 
24221 /*
24222  * Macros used for accessing the different types of sockaddr
24223  * structures inside a tcp_ioc_abort_conn_t.
24224  */
24225 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24226 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24227 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24228 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24229 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24230 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24231 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24232 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24233 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24234 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24235 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24236 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24237 
24238 /*
24239  * Return the correct error code to mimic the behavior
24240  * of a connection reset.
24241  */
24242 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24243 		switch ((state)) {		\
24244 		case TCPS_SYN_SENT:		\
24245 		case TCPS_SYN_RCVD:		\
24246 			(err) = ECONNREFUSED;	\
24247 			break;			\
24248 		case TCPS_ESTABLISHED:		\
24249 		case TCPS_FIN_WAIT_1:		\
24250 		case TCPS_FIN_WAIT_2:		\
24251 		case TCPS_CLOSE_WAIT:		\
24252 			(err) = ECONNRESET;	\
24253 			break;			\
24254 		case TCPS_CLOSING:		\
24255 		case TCPS_LAST_ACK:		\
24256 		case TCPS_TIME_WAIT:		\
24257 			(err) = 0;		\
24258 			break;			\
24259 		default:			\
24260 			(err) = ENXIO;		\
24261 		}				\
24262 	}
24263 
24264 /*
24265  * Check if a tcp structure matches the info in acp.
24266  */
24267 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24268 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24269 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24270 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24271 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24272 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24273 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24274 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24275 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24276 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24277 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24278 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24279 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24280 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24281 	&(tcp)->tcp_ip_src_v6)) &&				\
24282 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24283 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24284 	&(tcp)->tcp_remote_v6)) &&				\
24285 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24286 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24287 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24288 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24289 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24290 	(acp)->ac_end >= (tcp)->tcp_state))
24291 
24292 #define	TCP_AC_MATCH(acp, tcp)					\
24293 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24294 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24295 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24296 
24297 /*
24298  * Build a message containing a tcp_ioc_abort_conn_t structure
24299  * which is filled in with information from acp and tp.
24300  */
24301 static mblk_t *
24302 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24303 {
24304 	mblk_t *mp;
24305 	tcp_ioc_abort_conn_t *tacp;
24306 
24307 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24308 	if (mp == NULL)
24309 		return (NULL);
24310 
24311 	mp->b_datap->db_type = M_CTL;
24312 
24313 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24314 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24315 	    sizeof (uint32_t));
24316 
24317 	tacp->ac_start = acp->ac_start;
24318 	tacp->ac_end = acp->ac_end;
24319 	tacp->ac_zoneid = acp->ac_zoneid;
24320 
24321 	if (acp->ac_local.ss_family == AF_INET) {
24322 		tacp->ac_local.ss_family = AF_INET;
24323 		tacp->ac_remote.ss_family = AF_INET;
24324 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24325 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24326 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24327 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24328 	} else {
24329 		tacp->ac_local.ss_family = AF_INET6;
24330 		tacp->ac_remote.ss_family = AF_INET6;
24331 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24332 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24333 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24334 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24335 	}
24336 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24337 	return (mp);
24338 }
24339 
24340 /*
24341  * Print a tcp_ioc_abort_conn_t structure.
24342  */
24343 static void
24344 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24345 {
24346 	char lbuf[128];
24347 	char rbuf[128];
24348 	sa_family_t af;
24349 	in_port_t lport, rport;
24350 	ushort_t logflags;
24351 
24352 	af = acp->ac_local.ss_family;
24353 
24354 	if (af == AF_INET) {
24355 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24356 		    lbuf, 128);
24357 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24358 		    rbuf, 128);
24359 		lport = ntohs(TCP_AC_V4LPORT(acp));
24360 		rport = ntohs(TCP_AC_V4RPORT(acp));
24361 	} else {
24362 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24363 		    lbuf, 128);
24364 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24365 		    rbuf, 128);
24366 		lport = ntohs(TCP_AC_V6LPORT(acp));
24367 		rport = ntohs(TCP_AC_V6RPORT(acp));
24368 	}
24369 
24370 	logflags = SL_TRACE | SL_NOTE;
24371 	/*
24372 	 * Don't print this message to the console if the operation was done
24373 	 * to a non-global zone.
24374 	 */
24375 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24376 		logflags |= SL_CONSOLE;
24377 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24378 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24379 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24380 	    acp->ac_start, acp->ac_end);
24381 }
24382 
24383 /*
24384  * Called inside tcp_rput when a message built using
24385  * tcp_ioctl_abort_build_msg is put into a queue.
24386  * Note that when we get here there is no wildcard in acp any more.
24387  */
24388 static void
24389 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24390 {
24391 	tcp_ioc_abort_conn_t *acp;
24392 
24393 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24394 	if (tcp->tcp_state <= acp->ac_end) {
24395 		/*
24396 		 * If we get here, we are already on the correct
24397 		 * squeue. This ioctl follows the following path
24398 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24399 		 * ->tcp_ioctl_abort->squeue_enter (if on a
24400 		 * different squeue)
24401 		 */
24402 		int errcode;
24403 
24404 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24405 		(void) tcp_clean_death(tcp, errcode, 26);
24406 	}
24407 	freemsg(mp);
24408 }
24409 
24410 /*
24411  * Abort all matching connections on a hash chain.
24412  */
24413 static int
24414 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24415     boolean_t exact, tcp_stack_t *tcps)
24416 {
24417 	int nmatch, err = 0;
24418 	tcp_t *tcp;
24419 	MBLKP mp, last, listhead = NULL;
24420 	conn_t	*tconnp;
24421 	connf_t	*connfp;
24422 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24423 
24424 	connfp = &ipst->ips_ipcl_conn_fanout[index];
24425 
24426 startover:
24427 	nmatch = 0;
24428 
24429 	mutex_enter(&connfp->connf_lock);
24430 	for (tconnp = connfp->connf_head; tconnp != NULL;
24431 	    tconnp = tconnp->conn_next) {
24432 		tcp = tconnp->conn_tcp;
24433 		if (TCP_AC_MATCH(acp, tcp)) {
24434 			CONN_INC_REF(tcp->tcp_connp);
24435 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24436 			if (mp == NULL) {
24437 				err = ENOMEM;
24438 				CONN_DEC_REF(tcp->tcp_connp);
24439 				break;
24440 			}
24441 			mp->b_prev = (mblk_t *)tcp;
24442 
24443 			if (listhead == NULL) {
24444 				listhead = mp;
24445 				last = mp;
24446 			} else {
24447 				last->b_next = mp;
24448 				last = mp;
24449 			}
24450 			nmatch++;
24451 			if (exact)
24452 				break;
24453 		}
24454 
24455 		/* Avoid holding lock for too long. */
24456 		if (nmatch >= 500)
24457 			break;
24458 	}
24459 	mutex_exit(&connfp->connf_lock);
24460 
24461 	/* Pass mp into the correct tcp */
24462 	while ((mp = listhead) != NULL) {
24463 		listhead = listhead->b_next;
24464 		tcp = (tcp_t *)mp->b_prev;
24465 		mp->b_next = mp->b_prev = NULL;
24466 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
24467 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
24468 	}
24469 
24470 	*count += nmatch;
24471 	if (nmatch >= 500 && err == 0)
24472 		goto startover;
24473 	return (err);
24474 }
24475 
24476 /*
24477  * Abort all connections that matches the attributes specified in acp.
24478  */
24479 static int
24480 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
24481 {
24482 	sa_family_t af;
24483 	uint32_t  ports;
24484 	uint16_t *pports;
24485 	int err = 0, count = 0;
24486 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24487 	int index = -1;
24488 	ushort_t logflags;
24489 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24490 
24491 	af = acp->ac_local.ss_family;
24492 
24493 	if (af == AF_INET) {
24494 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24495 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24496 			pports = (uint16_t *)&ports;
24497 			pports[1] = TCP_AC_V4LPORT(acp);
24498 			pports[0] = TCP_AC_V4RPORT(acp);
24499 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24500 		}
24501 	} else {
24502 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24503 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24504 			pports = (uint16_t *)&ports;
24505 			pports[1] = TCP_AC_V6LPORT(acp);
24506 			pports[0] = TCP_AC_V6RPORT(acp);
24507 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24508 		}
24509 	}
24510 
24511 	/*
24512 	 * For cases where remote addr, local port, and remote port are non-
24513 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24514 	 */
24515 	if (index != -1) {
24516 		err = tcp_ioctl_abort_bucket(acp, index,
24517 		    &count, exact, tcps);
24518 	} else {
24519 		/*
24520 		 * loop through all entries for wildcard case
24521 		 */
24522 		for (index = 0;
24523 		    index < ipst->ips_ipcl_conn_fanout_size;
24524 		    index++) {
24525 			err = tcp_ioctl_abort_bucket(acp, index,
24526 			    &count, exact, tcps);
24527 			if (err != 0)
24528 				break;
24529 		}
24530 	}
24531 
24532 	logflags = SL_TRACE | SL_NOTE;
24533 	/*
24534 	 * Don't print this message to the console if the operation was done
24535 	 * to a non-global zone.
24536 	 */
24537 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24538 		logflags |= SL_CONSOLE;
24539 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24540 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24541 	if (err == 0 && count == 0)
24542 		err = ENOENT;
24543 	return (err);
24544 }
24545 
24546 /*
24547  * Process the TCP_IOC_ABORT_CONN ioctl request.
24548  */
24549 static void
24550 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24551 {
24552 	int	err;
24553 	IOCP    iocp;
24554 	MBLKP   mp1;
24555 	sa_family_t laf, raf;
24556 	tcp_ioc_abort_conn_t *acp;
24557 	zone_t		*zptr;
24558 	conn_t		*connp = Q_TO_CONN(q);
24559 	zoneid_t	zoneid = connp->conn_zoneid;
24560 	tcp_t		*tcp = connp->conn_tcp;
24561 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24562 
24563 	iocp = (IOCP)mp->b_rptr;
24564 
24565 	if ((mp1 = mp->b_cont) == NULL ||
24566 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24567 		err = EINVAL;
24568 		goto out;
24569 	}
24570 
24571 	/* check permissions */
24572 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
24573 		err = EPERM;
24574 		goto out;
24575 	}
24576 
24577 	if (mp1->b_cont != NULL) {
24578 		freemsg(mp1->b_cont);
24579 		mp1->b_cont = NULL;
24580 	}
24581 
24582 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24583 	laf = acp->ac_local.ss_family;
24584 	raf = acp->ac_remote.ss_family;
24585 
24586 	/* check that a zone with the supplied zoneid exists */
24587 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24588 		zptr = zone_find_by_id(zoneid);
24589 		if (zptr != NULL) {
24590 			zone_rele(zptr);
24591 		} else {
24592 			err = EINVAL;
24593 			goto out;
24594 		}
24595 	}
24596 
24597 	/*
24598 	 * For exclusive stacks we set the zoneid to zero
24599 	 * to make TCP operate as if in the global zone.
24600 	 */
24601 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
24602 		acp->ac_zoneid = GLOBAL_ZONEID;
24603 
24604 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24605 	    acp->ac_start > acp->ac_end || laf != raf ||
24606 	    (laf != AF_INET && laf != AF_INET6)) {
24607 		err = EINVAL;
24608 		goto out;
24609 	}
24610 
24611 	tcp_ioctl_abort_dump(acp);
24612 	err = tcp_ioctl_abort(acp, tcps);
24613 
24614 out:
24615 	if (mp1 != NULL) {
24616 		freemsg(mp1);
24617 		mp->b_cont = NULL;
24618 	}
24619 
24620 	if (err != 0)
24621 		miocnak(q, mp, 0, err);
24622 	else
24623 		miocack(q, mp, 0, 0);
24624 }
24625 
24626 /*
24627  * tcp_time_wait_processing() handles processing of incoming packets when
24628  * the tcp is in the TIME_WAIT state.
24629  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24630  * on the time wait list.
24631  */
24632 void
24633 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24634     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24635 {
24636 	int32_t		bytes_acked;
24637 	int32_t		gap;
24638 	int32_t		rgap;
24639 	tcp_opt_t	tcpopt;
24640 	uint_t		flags;
24641 	uint32_t	new_swnd = 0;
24642 	conn_t		*connp;
24643 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24644 
24645 	BUMP_LOCAL(tcp->tcp_ibsegs);
24646 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
24647 
24648 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24649 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24650 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24651 	if (tcp->tcp_snd_ts_ok) {
24652 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24653 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24654 			    tcp->tcp_rnxt, TH_ACK);
24655 			goto done;
24656 		}
24657 	}
24658 	gap = seg_seq - tcp->tcp_rnxt;
24659 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24660 	if (gap < 0) {
24661 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
24662 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
24663 		    (seg_len > -gap ? -gap : seg_len));
24664 		seg_len += gap;
24665 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24666 			if (flags & TH_RST) {
24667 				goto done;
24668 			}
24669 			if ((flags & TH_FIN) && seg_len == -1) {
24670 				/*
24671 				 * When TCP receives a duplicate FIN in
24672 				 * TIME_WAIT state, restart the 2 MSL timer.
24673 				 * See page 73 in RFC 793. Make sure this TCP
24674 				 * is already on the TIME_WAIT list. If not,
24675 				 * just restart the timer.
24676 				 */
24677 				if (TCP_IS_DETACHED(tcp)) {
24678 					if (tcp_time_wait_remove(tcp, NULL) ==
24679 					    B_TRUE) {
24680 						tcp_time_wait_append(tcp);
24681 						TCP_DBGSTAT(tcps,
24682 						    tcp_rput_time_wait);
24683 					}
24684 				} else {
24685 					ASSERT(tcp != NULL);
24686 					TCP_TIMER_RESTART(tcp,
24687 					    tcps->tcps_time_wait_interval);
24688 				}
24689 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24690 				    tcp->tcp_rnxt, TH_ACK);
24691 				goto done;
24692 			}
24693 			flags |=  TH_ACK_NEEDED;
24694 			seg_len = 0;
24695 			goto process_ack;
24696 		}
24697 
24698 		/* Fix seg_seq, and chew the gap off the front. */
24699 		seg_seq = tcp->tcp_rnxt;
24700 	}
24701 
24702 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24703 		/*
24704 		 * Make sure that when we accept the connection, pick
24705 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24706 		 * old connection.
24707 		 *
24708 		 * The next ISS generated is equal to tcp_iss_incr_extra
24709 		 * + ISS_INCR/2 + other components depending on the
24710 		 * value of tcp_strong_iss.  We pre-calculate the new
24711 		 * ISS here and compare with tcp_snxt to determine if
24712 		 * we need to make adjustment to tcp_iss_incr_extra.
24713 		 *
24714 		 * The above calculation is ugly and is a
24715 		 * waste of CPU cycles...
24716 		 */
24717 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
24718 		int32_t adj;
24719 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24720 
24721 		switch (tcps->tcps_strong_iss) {
24722 		case 2: {
24723 			/* Add time and MD5 components. */
24724 			uint32_t answer[4];
24725 			struct {
24726 				uint32_t ports;
24727 				in6_addr_t src;
24728 				in6_addr_t dst;
24729 			} arg;
24730 			MD5_CTX context;
24731 
24732 			mutex_enter(&tcps->tcps_iss_key_lock);
24733 			context = tcps->tcps_iss_key;
24734 			mutex_exit(&tcps->tcps_iss_key_lock);
24735 			arg.ports = tcp->tcp_ports;
24736 			/* We use MAPPED addresses in tcp_iss_init */
24737 			arg.src = tcp->tcp_ip_src_v6;
24738 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24739 				IN6_IPADDR_TO_V4MAPPED(
24740 				    tcp->tcp_ipha->ipha_dst,
24741 				    &arg.dst);
24742 			} else {
24743 				arg.dst =
24744 				    tcp->tcp_ip6h->ip6_dst;
24745 			}
24746 			MD5Update(&context, (uchar_t *)&arg,
24747 			    sizeof (arg));
24748 			MD5Final((uchar_t *)answer, &context);
24749 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24750 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24751 			break;
24752 		}
24753 		case 1:
24754 			/* Add time component and min random (i.e. 1). */
24755 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24756 			break;
24757 		default:
24758 			/* Add only time component. */
24759 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24760 			break;
24761 		}
24762 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24763 			/*
24764 			 * New ISS not guaranteed to be ISS_INCR/2
24765 			 * ahead of the current tcp_snxt, so add the
24766 			 * difference to tcp_iss_incr_extra.
24767 			 */
24768 			tcps->tcps_iss_incr_extra += adj;
24769 		}
24770 		/*
24771 		 * If tcp_clean_death() can not perform the task now,
24772 		 * drop the SYN packet and let the other side re-xmit.
24773 		 * Otherwise pass the SYN packet back in, since the
24774 		 * old tcp state has been cleaned up or freed.
24775 		 */
24776 		if (tcp_clean_death(tcp, 0, 27) == -1)
24777 			goto done;
24778 		/*
24779 		 * We will come back to tcp_rput_data
24780 		 * on the global queue. Packets destined
24781 		 * for the global queue will be checked
24782 		 * with global policy. But the policy for
24783 		 * this packet has already been checked as
24784 		 * this was destined for the detached
24785 		 * connection. We need to bypass policy
24786 		 * check this time by attaching a dummy
24787 		 * ipsec_in with ipsec_in_dont_check set.
24788 		 */
24789 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
24790 		if (connp != NULL) {
24791 			TCP_STAT(tcps, tcp_time_wait_syn_success);
24792 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24793 			return;
24794 		}
24795 		goto done;
24796 	}
24797 
24798 	/*
24799 	 * rgap is the amount of stuff received out of window.  A negative
24800 	 * value is the amount out of window.
24801 	 */
24802 	if (rgap < 0) {
24803 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
24804 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
24805 		/* Fix seg_len and make sure there is something left. */
24806 		seg_len += rgap;
24807 		if (seg_len <= 0) {
24808 			if (flags & TH_RST) {
24809 				goto done;
24810 			}
24811 			flags |=  TH_ACK_NEEDED;
24812 			seg_len = 0;
24813 			goto process_ack;
24814 		}
24815 	}
24816 	/*
24817 	 * Check whether we can update tcp_ts_recent.  This test is
24818 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24819 	 * Extensions for High Performance: An Update", Internet Draft.
24820 	 */
24821 	if (tcp->tcp_snd_ts_ok &&
24822 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24823 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24824 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24825 		tcp->tcp_last_rcv_lbolt = lbolt64;
24826 	}
24827 
24828 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24829 		/* Always ack out of order packets */
24830 		flags |= TH_ACK_NEEDED;
24831 		seg_len = 0;
24832 	} else if (seg_len > 0) {
24833 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
24834 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
24835 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
24836 	}
24837 	if (flags & TH_RST) {
24838 		(void) tcp_clean_death(tcp, 0, 28);
24839 		goto done;
24840 	}
24841 	if (flags & TH_SYN) {
24842 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24843 		    TH_RST|TH_ACK);
24844 		/*
24845 		 * Do not delete the TCP structure if it is in
24846 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24847 		 */
24848 		goto done;
24849 	}
24850 process_ack:
24851 	if (flags & TH_ACK) {
24852 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24853 		if (bytes_acked <= 0) {
24854 			if (bytes_acked == 0 && seg_len == 0 &&
24855 			    new_swnd == tcp->tcp_swnd)
24856 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
24857 		} else {
24858 			/* Acks something not sent */
24859 			flags |= TH_ACK_NEEDED;
24860 		}
24861 	}
24862 	if (flags & TH_ACK_NEEDED) {
24863 		/*
24864 		 * Time to send an ack for some reason.
24865 		 */
24866 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24867 		    tcp->tcp_rnxt, TH_ACK);
24868 	}
24869 done:
24870 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24871 		DB_CKSUMSTART(mp) = 0;
24872 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24873 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
24874 	}
24875 	freemsg(mp);
24876 }
24877 
24878 /*
24879  * TCP Timers Implementation.
24880  */
24881 timeout_id_t
24882 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24883 {
24884 	mblk_t *mp;
24885 	tcp_timer_t *tcpt;
24886 	tcp_t *tcp = connp->conn_tcp;
24887 
24888 	ASSERT(connp->conn_sqp != NULL);
24889 
24890 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
24891 
24892 	if (tcp->tcp_timercache == NULL) {
24893 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24894 	} else {
24895 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
24896 		mp = tcp->tcp_timercache;
24897 		tcp->tcp_timercache = mp->b_next;
24898 		mp->b_next = NULL;
24899 		ASSERT(mp->b_wptr == NULL);
24900 	}
24901 
24902 	CONN_INC_REF(connp);
24903 	tcpt = (tcp_timer_t *)mp->b_rptr;
24904 	tcpt->connp = connp;
24905 	tcpt->tcpt_proc = f;
24906 	/*
24907 	 * TCP timers are normal timeouts. Plus, they do not require more than
24908 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
24909 	 * rounding up the expiration to the next resolution boundary, we can
24910 	 * batch timers in the callout subsystem to make TCP timers more
24911 	 * efficient. The roundup also protects short timers from expiring too
24912 	 * early before they have a chance to be cancelled.
24913 	 */
24914 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
24915 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
24916 
24917 	return ((timeout_id_t)mp);
24918 }
24919 
24920 static void
24921 tcp_timer_callback(void *arg)
24922 {
24923 	mblk_t *mp = (mblk_t *)arg;
24924 	tcp_timer_t *tcpt;
24925 	conn_t	*connp;
24926 
24927 	tcpt = (tcp_timer_t *)mp->b_rptr;
24928 	connp = tcpt->connp;
24929 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
24930 	    SQ_FILL, SQTAG_TCP_TIMER);
24931 }
24932 
24933 static void
24934 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24935 {
24936 	tcp_timer_t *tcpt;
24937 	conn_t *connp = (conn_t *)arg;
24938 	tcp_t *tcp = connp->conn_tcp;
24939 
24940 	tcpt = (tcp_timer_t *)mp->b_rptr;
24941 	ASSERT(connp == tcpt->connp);
24942 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24943 
24944 	/*
24945 	 * If the TCP has reached the closed state, don't proceed any
24946 	 * further. This TCP logically does not exist on the system.
24947 	 * tcpt_proc could for example access queues, that have already
24948 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24949 	 */
24950 	if (tcp->tcp_state != TCPS_CLOSED) {
24951 		(*tcpt->tcpt_proc)(connp);
24952 	} else {
24953 		tcp->tcp_timer_tid = 0;
24954 	}
24955 	tcp_timer_free(connp->conn_tcp, mp);
24956 }
24957 
24958 /*
24959  * There is potential race with untimeout and the handler firing at the same
24960  * time. The mblock may be freed by the handler while we are trying to use
24961  * it. But since both should execute on the same squeue, this race should not
24962  * occur.
24963  */
24964 clock_t
24965 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24966 {
24967 	mblk_t	*mp = (mblk_t *)id;
24968 	tcp_timer_t *tcpt;
24969 	clock_t delta;
24970 
24971 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
24972 
24973 	if (mp == NULL)
24974 		return (-1);
24975 
24976 	tcpt = (tcp_timer_t *)mp->b_rptr;
24977 	ASSERT(tcpt->connp == connp);
24978 
24979 	delta = untimeout_default(tcpt->tcpt_tid, 0);
24980 
24981 	if (delta >= 0) {
24982 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
24983 		tcp_timer_free(connp->conn_tcp, mp);
24984 		CONN_DEC_REF(connp);
24985 	}
24986 
24987 	return (delta);
24988 }
24989 
24990 /*
24991  * Allocate space for the timer event. The allocation looks like mblk, but it is
24992  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24993  *
24994  * Dealing with failures: If we can't allocate from the timer cache we try
24995  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24996  * points to b_rptr.
24997  * If we can't allocate anything using allocb_tryhard(), we perform a last
24998  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24999  * save the actual allocation size in b_datap.
25000  */
25001 mblk_t *
25002 tcp_timermp_alloc(int kmflags)
25003 {
25004 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25005 	    kmflags & ~KM_PANIC);
25006 
25007 	if (mp != NULL) {
25008 		mp->b_next = mp->b_prev = NULL;
25009 		mp->b_rptr = (uchar_t *)(&mp[1]);
25010 		mp->b_wptr = NULL;
25011 		mp->b_datap = NULL;
25012 		mp->b_queue = NULL;
25013 		mp->b_cont = NULL;
25014 	} else if (kmflags & KM_PANIC) {
25015 		/*
25016 		 * Failed to allocate memory for the timer. Try allocating from
25017 		 * dblock caches.
25018 		 */
25019 		/* ipclassifier calls this from a constructor - hence no tcps */
25020 		TCP_G_STAT(tcp_timermp_allocfail);
25021 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25022 		if (mp == NULL) {
25023 			size_t size = 0;
25024 			/*
25025 			 * Memory is really low. Try tryhard allocation.
25026 			 *
25027 			 * ipclassifier calls this from a constructor -
25028 			 * hence no tcps
25029 			 */
25030 			TCP_G_STAT(tcp_timermp_allocdblfail);
25031 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25032 			    sizeof (tcp_timer_t), &size, kmflags);
25033 			mp->b_rptr = (uchar_t *)(&mp[1]);
25034 			mp->b_next = mp->b_prev = NULL;
25035 			mp->b_wptr = (uchar_t *)-1;
25036 			mp->b_datap = (dblk_t *)size;
25037 			mp->b_queue = NULL;
25038 			mp->b_cont = NULL;
25039 		}
25040 		ASSERT(mp->b_wptr != NULL);
25041 	}
25042 	/* ipclassifier calls this from a constructor - hence no tcps */
25043 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25044 
25045 	return (mp);
25046 }
25047 
25048 /*
25049  * Free per-tcp timer cache.
25050  * It can only contain entries from tcp_timercache.
25051  */
25052 void
25053 tcp_timermp_free(tcp_t *tcp)
25054 {
25055 	mblk_t *mp;
25056 
25057 	while ((mp = tcp->tcp_timercache) != NULL) {
25058 		ASSERT(mp->b_wptr == NULL);
25059 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25060 		kmem_cache_free(tcp_timercache, mp);
25061 	}
25062 }
25063 
25064 /*
25065  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25066  * events there already (currently at most two events are cached).
25067  * If the event is not allocated from the timer cache, free it right away.
25068  */
25069 static void
25070 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25071 {
25072 	mblk_t *mp1 = tcp->tcp_timercache;
25073 
25074 	if (mp->b_wptr != NULL) {
25075 		/*
25076 		 * This allocation is not from a timer cache, free it right
25077 		 * away.
25078 		 */
25079 		if (mp->b_wptr != (uchar_t *)-1)
25080 			freeb(mp);
25081 		else
25082 			kmem_free(mp, (size_t)mp->b_datap);
25083 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25084 		/* Cache this timer block for future allocations */
25085 		mp->b_rptr = (uchar_t *)(&mp[1]);
25086 		mp->b_next = mp1;
25087 		tcp->tcp_timercache = mp;
25088 	} else {
25089 		kmem_cache_free(tcp_timercache, mp);
25090 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25091 	}
25092 }
25093 
25094 /*
25095  * End of TCP Timers implementation.
25096  */
25097 
25098 /*
25099  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25100  * on the specified backing STREAMS q. Note, the caller may make the
25101  * decision to call based on the tcp_t.tcp_flow_stopped value which
25102  * when check outside the q's lock is only an advisory check ...
25103  */
25104 void
25105 tcp_setqfull(tcp_t *tcp)
25106 {
25107 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25108 	conn_t	*connp = tcp->tcp_connp;
25109 
25110 	if (tcp->tcp_closed)
25111 		return;
25112 
25113 	if (IPCL_IS_NONSTR(connp)) {
25114 		(*connp->conn_upcalls->su_txq_full)
25115 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25116 		tcp->tcp_flow_stopped = B_TRUE;
25117 	} else {
25118 		queue_t *q = tcp->tcp_wq;
25119 
25120 		if (!(q->q_flag & QFULL)) {
25121 			mutex_enter(QLOCK(q));
25122 			if (!(q->q_flag & QFULL)) {
25123 				/* still need to set QFULL */
25124 				q->q_flag |= QFULL;
25125 				tcp->tcp_flow_stopped = B_TRUE;
25126 				mutex_exit(QLOCK(q));
25127 				TCP_STAT(tcps, tcp_flwctl_on);
25128 			} else {
25129 				mutex_exit(QLOCK(q));
25130 			}
25131 		}
25132 	}
25133 }
25134 
25135 void
25136 tcp_clrqfull(tcp_t *tcp)
25137 {
25138 	conn_t  *connp = tcp->tcp_connp;
25139 
25140 	if (tcp->tcp_closed)
25141 		return;
25142 
25143 	if (IPCL_IS_NONSTR(connp)) {
25144 		(*connp->conn_upcalls->su_txq_full)
25145 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25146 		tcp->tcp_flow_stopped = B_FALSE;
25147 	} else {
25148 		queue_t *q = tcp->tcp_wq;
25149 
25150 		if (q->q_flag & QFULL) {
25151 			mutex_enter(QLOCK(q));
25152 			if (q->q_flag & QFULL) {
25153 				q->q_flag &= ~QFULL;
25154 				tcp->tcp_flow_stopped = B_FALSE;
25155 				mutex_exit(QLOCK(q));
25156 				if (q->q_flag & QWANTW)
25157 					qbackenable(q, 0);
25158 			} else {
25159 				mutex_exit(QLOCK(q));
25160 			}
25161 		}
25162 	}
25163 }
25164 
25165 /*
25166  * kstats related to squeues i.e. not per IP instance
25167  */
25168 static void *
25169 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
25170 {
25171 	kstat_t *ksp;
25172 
25173 	tcp_g_stat_t template = {
25174 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
25175 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
25176 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
25177 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
25178 	};
25179 
25180 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
25181 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25182 	    KSTAT_FLAG_VIRTUAL);
25183 
25184 	if (ksp == NULL)
25185 		return (NULL);
25186 
25187 	bcopy(&template, tcp_g_statp, sizeof (template));
25188 	ksp->ks_data = (void *)tcp_g_statp;
25189 
25190 	kstat_install(ksp);
25191 	return (ksp);
25192 }
25193 
25194 static void
25195 tcp_g_kstat_fini(kstat_t *ksp)
25196 {
25197 	if (ksp != NULL) {
25198 		kstat_delete(ksp);
25199 	}
25200 }
25201 
25202 
25203 static void *
25204 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
25205 {
25206 	kstat_t *ksp;
25207 
25208 	tcp_stat_t template = {
25209 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
25210 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
25211 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
25212 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
25213 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
25214 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
25215 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
25216 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
25217 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
25218 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
25219 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
25220 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
25221 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
25222 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
25223 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
25224 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
25225 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
25226 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
25227 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
25228 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
25229 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
25230 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
25231 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
25232 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
25233 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
25234 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
25235 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
25236 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
25237 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
25238 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
25239 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
25240 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
25241 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
25242 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
25243 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
25244 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
25245 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
25246 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
25247 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
25248 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
25249 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
25250 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
25251 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
25252 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
25253 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
25254 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
25255 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
25256 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
25257 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
25258 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
25259 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
25260 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
25261 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
25262 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
25263 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
25264 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
25265 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
25266 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
25267 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
25268 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
25269 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
25270 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
25271 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
25272 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
25273 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
25274 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
25275 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
25276 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
25277 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
25278 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
25279 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
25280 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
25281 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
25282 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
25283 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
25284 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
25285 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
25286 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
25287 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
25288 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
25289 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
25290 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
25291 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
25292 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
25293 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
25294 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
25295 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
25296 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
25297 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
25298 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
25299 	};
25300 
25301 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
25302 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25303 	    KSTAT_FLAG_VIRTUAL, stackid);
25304 
25305 	if (ksp == NULL)
25306 		return (NULL);
25307 
25308 	bcopy(&template, tcps_statisticsp, sizeof (template));
25309 	ksp->ks_data = (void *)tcps_statisticsp;
25310 	ksp->ks_private = (void *)(uintptr_t)stackid;
25311 
25312 	kstat_install(ksp);
25313 	return (ksp);
25314 }
25315 
25316 static void
25317 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
25318 {
25319 	if (ksp != NULL) {
25320 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25321 		kstat_delete_netstack(ksp, stackid);
25322 	}
25323 }
25324 
25325 /*
25326  * TCP Kstats implementation
25327  */
25328 static void *
25329 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
25330 {
25331 	kstat_t	*ksp;
25332 
25333 	tcp_named_kstat_t template = {
25334 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25335 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25336 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25337 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25338 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25339 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25340 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25341 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25342 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25343 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25344 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25345 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25346 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25347 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25348 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25349 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25350 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25351 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25352 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25353 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25354 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25355 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25356 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25357 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25358 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25359 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25360 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25361 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25362 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25363 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25364 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25365 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25366 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25367 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25368 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25369 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25370 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25371 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25372 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25373 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25374 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25375 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25376 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25377 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25378 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25379 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25380 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25381 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25382 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25383 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25384 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25385 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25386 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25387 	};
25388 
25389 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
25390 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
25391 
25392 	if (ksp == NULL)
25393 		return (NULL);
25394 
25395 	template.rtoAlgorithm.value.ui32 = 4;
25396 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
25397 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
25398 	template.maxConn.value.i32 = -1;
25399 
25400 	bcopy(&template, ksp->ks_data, sizeof (template));
25401 	ksp->ks_update = tcp_kstat_update;
25402 	ksp->ks_private = (void *)(uintptr_t)stackid;
25403 
25404 	kstat_install(ksp);
25405 	return (ksp);
25406 }
25407 
25408 static void
25409 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
25410 {
25411 	if (ksp != NULL) {
25412 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25413 		kstat_delete_netstack(ksp, stackid);
25414 	}
25415 }
25416 
25417 static int
25418 tcp_kstat_update(kstat_t *kp, int rw)
25419 {
25420 	tcp_named_kstat_t *tcpkp;
25421 	tcp_t		*tcp;
25422 	connf_t		*connfp;
25423 	conn_t		*connp;
25424 	int 		i;
25425 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
25426 	netstack_t	*ns;
25427 	tcp_stack_t	*tcps;
25428 	ip_stack_t	*ipst;
25429 
25430 	if ((kp == NULL) || (kp->ks_data == NULL))
25431 		return (EIO);
25432 
25433 	if (rw == KSTAT_WRITE)
25434 		return (EACCES);
25435 
25436 	ns = netstack_find_by_stackid(stackid);
25437 	if (ns == NULL)
25438 		return (-1);
25439 	tcps = ns->netstack_tcp;
25440 	if (tcps == NULL) {
25441 		netstack_rele(ns);
25442 		return (-1);
25443 	}
25444 
25445 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25446 
25447 	tcpkp->currEstab.value.ui32 = 0;
25448 
25449 	ipst = ns->netstack_ip;
25450 
25451 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25452 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25453 		connp = NULL;
25454 		while ((connp =
25455 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25456 			tcp = connp->conn_tcp;
25457 			switch (tcp_snmp_state(tcp)) {
25458 			case MIB2_TCP_established:
25459 			case MIB2_TCP_closeWait:
25460 				tcpkp->currEstab.value.ui32++;
25461 				break;
25462 			}
25463 		}
25464 	}
25465 
25466 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
25467 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
25468 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
25469 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
25470 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
25471 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
25472 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
25473 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
25474 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
25475 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
25476 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
25477 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
25478 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
25479 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
25480 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
25481 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
25482 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
25483 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
25484 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
25485 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
25486 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
25487 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
25488 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
25489 	tcpkp->inDataInorderSegs.value.ui32 =
25490 	    tcps->tcps_mib.tcpInDataInorderSegs;
25491 	tcpkp->inDataInorderBytes.value.ui32 =
25492 	    tcps->tcps_mib.tcpInDataInorderBytes;
25493 	tcpkp->inDataUnorderSegs.value.ui32 =
25494 	    tcps->tcps_mib.tcpInDataUnorderSegs;
25495 	tcpkp->inDataUnorderBytes.value.ui32 =
25496 	    tcps->tcps_mib.tcpInDataUnorderBytes;
25497 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
25498 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
25499 	tcpkp->inDataPartDupSegs.value.ui32 =
25500 	    tcps->tcps_mib.tcpInDataPartDupSegs;
25501 	tcpkp->inDataPartDupBytes.value.ui32 =
25502 	    tcps->tcps_mib.tcpInDataPartDupBytes;
25503 	tcpkp->inDataPastWinSegs.value.ui32 =
25504 	    tcps->tcps_mib.tcpInDataPastWinSegs;
25505 	tcpkp->inDataPastWinBytes.value.ui32 =
25506 	    tcps->tcps_mib.tcpInDataPastWinBytes;
25507 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
25508 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
25509 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
25510 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
25511 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
25512 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
25513 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
25514 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
25515 	tcpkp->timKeepaliveProbe.value.ui32 =
25516 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
25517 	tcpkp->timKeepaliveDrop.value.ui32 =
25518 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
25519 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
25520 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
25521 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
25522 	tcpkp->outSackRetransSegs.value.ui32 =
25523 	    tcps->tcps_mib.tcpOutSackRetransSegs;
25524 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
25525 
25526 	netstack_rele(ns);
25527 	return (0);
25528 }
25529 
25530 void
25531 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25532 {
25533 	uint16_t	hdr_len;
25534 	ipha_t		*ipha;
25535 	uint8_t		*nexthdrp;
25536 	tcph_t		*tcph;
25537 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
25538 
25539 	/* Already has an eager */
25540 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25541 		TCP_STAT(tcps, tcp_reinput_syn);
25542 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25543 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
25544 		return;
25545 	}
25546 
25547 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25548 	case IPV4_VERSION:
25549 		ipha = (ipha_t *)mp->b_rptr;
25550 		hdr_len = IPH_HDR_LENGTH(ipha);
25551 		break;
25552 	case IPV6_VERSION:
25553 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25554 		    &hdr_len, &nexthdrp)) {
25555 			CONN_DEC_REF(connp);
25556 			freemsg(mp);
25557 			return;
25558 		}
25559 		break;
25560 	}
25561 
25562 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25563 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25564 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25565 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25566 	}
25567 
25568 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25569 	    SQ_FILL, SQTAG_TCP_REINPUT);
25570 }
25571 
25572 static int
25573 tcp_squeue_switch(int val)
25574 {
25575 	int rval = SQ_FILL;
25576 
25577 	switch (val) {
25578 	case 1:
25579 		rval = SQ_NODRAIN;
25580 		break;
25581 	case 2:
25582 		rval = SQ_PROCESS;
25583 		break;
25584 	default:
25585 		break;
25586 	}
25587 	return (rval);
25588 }
25589 
25590 /*
25591  * This is called once for each squeue - globally for all stack
25592  * instances.
25593  */
25594 static void
25595 tcp_squeue_add(squeue_t *sqp)
25596 {
25597 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25598 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
25599 
25600 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25601 	tcp_time_wait->tcp_time_wait_tid =
25602 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
25603 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
25604 	    CALLOUT_FLAG_ROUNDUP);
25605 	if (tcp_free_list_max_cnt == 0) {
25606 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25607 		    max_ncpus : boot_max_ncpus);
25608 
25609 		/*
25610 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25611 		 */
25612 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25613 		    (tcp_ncpus * sizeof (tcp_t) * 100);
25614 	}
25615 	tcp_time_wait->tcp_free_list_cnt = 0;
25616 }
25617 
25618 static int
25619 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
25620 {
25621 	mblk_t	*ire_mp = NULL;
25622 	mblk_t	*syn_mp;
25623 	mblk_t	*mdti;
25624 	mblk_t	*lsoi;
25625 	int	retval;
25626 	tcph_t	*tcph;
25627 	cred_t	*ecr;
25628 	ts_label_t	*tsl;
25629 	uint32_t	mss;
25630 	queue_t	*q = tcp->tcp_rq;
25631 	conn_t	*connp = tcp->tcp_connp;
25632 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25633 
25634 	if (error == 0) {
25635 		/*
25636 		 * Adapt Multidata information, if any.  The
25637 		 * following tcp_mdt_update routine will free
25638 		 * the message.
25639 		 */
25640 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
25641 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
25642 			    b_rptr)->mdt_capab, B_TRUE);
25643 			freemsg(mdti);
25644 		}
25645 
25646 		/*
25647 		 * Check to update LSO information with tcp, and
25648 		 * tcp_lso_update routine will free the message.
25649 		 */
25650 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
25651 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
25652 			    b_rptr)->lso_capab);
25653 			freemsg(lsoi);
25654 		}
25655 
25656 		/* Get the IRE, if we had requested for it */
25657 		if (mp != NULL)
25658 			ire_mp = tcp_ire_mp(&mp);
25659 
25660 		if (tcp->tcp_hard_binding) {
25661 			tcp->tcp_hard_binding = B_FALSE;
25662 			tcp->tcp_hard_bound = B_TRUE;
25663 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
25664 			if (retval != 0) {
25665 				error = EADDRINUSE;
25666 				goto bind_failed;
25667 			}
25668 		} else {
25669 			if (ire_mp != NULL)
25670 				freeb(ire_mp);
25671 			goto after_syn_sent;
25672 		}
25673 
25674 		retval = tcp_adapt_ire(tcp, ire_mp);
25675 		if (ire_mp != NULL)
25676 			freeb(ire_mp);
25677 		if (retval == 0) {
25678 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
25679 			    ENETUNREACH : EADDRNOTAVAIL);
25680 			goto ipcl_rm;
25681 		}
25682 		/*
25683 		 * Don't let an endpoint connect to itself.
25684 		 * Also checked in tcp_connect() but that
25685 		 * check can't handle the case when the
25686 		 * local IP address is INADDR_ANY.
25687 		 */
25688 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25689 			if ((tcp->tcp_ipha->ipha_dst ==
25690 			    tcp->tcp_ipha->ipha_src) &&
25691 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25692 			    tcp->tcp_tcph->th_fport))) {
25693 				error = EADDRNOTAVAIL;
25694 				goto ipcl_rm;
25695 			}
25696 		} else {
25697 			if (IN6_ARE_ADDR_EQUAL(
25698 			    &tcp->tcp_ip6h->ip6_dst,
25699 			    &tcp->tcp_ip6h->ip6_src) &&
25700 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25701 			    tcp->tcp_tcph->th_fport))) {
25702 				error = EADDRNOTAVAIL;
25703 				goto ipcl_rm;
25704 			}
25705 		}
25706 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
25707 		/*
25708 		 * This should not be possible!  Just for
25709 		 * defensive coding...
25710 		 */
25711 		if (tcp->tcp_state != TCPS_SYN_SENT)
25712 			goto after_syn_sent;
25713 
25714 		if (is_system_labeled() &&
25715 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
25716 			error = EHOSTUNREACH;
25717 			goto ipcl_rm;
25718 		}
25719 
25720 		/*
25721 		 * tcp_adapt_ire() does not adjust
25722 		 * for TCP/IP header length.
25723 		 */
25724 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
25725 
25726 		/*
25727 		 * Just make sure our rwnd is at
25728 		 * least tcp_recv_hiwat_mss * MSS
25729 		 * large, and round up to the nearest
25730 		 * MSS.
25731 		 *
25732 		 * We do the round up here because
25733 		 * we need to get the interface
25734 		 * MTU first before we can do the
25735 		 * round up.
25736 		 */
25737 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
25738 		    tcps->tcps_recv_hiwat_minmss * mss);
25739 		if (!IPCL_IS_NONSTR(connp))
25740 			q->q_hiwat = tcp->tcp_rwnd;
25741 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
25742 		tcp_set_ws_value(tcp);
25743 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
25744 		    tcp->tcp_tcph->th_win);
25745 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
25746 			tcp->tcp_snd_ws_ok = B_TRUE;
25747 
25748 		/*
25749 		 * Set tcp_snd_ts_ok to true
25750 		 * so that tcp_xmit_mp will
25751 		 * include the timestamp
25752 		 * option in the SYN segment.
25753 		 */
25754 		if (tcps->tcps_tstamp_always ||
25755 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
25756 			tcp->tcp_snd_ts_ok = B_TRUE;
25757 		}
25758 
25759 		/*
25760 		 * tcp_snd_sack_ok can be set in
25761 		 * tcp_adapt_ire() if the sack metric
25762 		 * is set.  So check it here also.
25763 		 */
25764 		if (tcps->tcps_sack_permitted == 2 ||
25765 		    tcp->tcp_snd_sack_ok) {
25766 			if (tcp->tcp_sack_info == NULL) {
25767 				tcp->tcp_sack_info =
25768 				    kmem_cache_alloc(tcp_sack_info_cache,
25769 				    KM_SLEEP);
25770 			}
25771 			tcp->tcp_snd_sack_ok = B_TRUE;
25772 		}
25773 
25774 		/*
25775 		 * Should we use ECN?  Note that the current
25776 		 * default value (SunOS 5.9) of tcp_ecn_permitted
25777 		 * is 1.  The reason for doing this is that there
25778 		 * are equipments out there that will drop ECN
25779 		 * enabled IP packets.  Setting it to 1 avoids
25780 		 * compatibility problems.
25781 		 */
25782 		if (tcps->tcps_ecn_permitted == 2)
25783 			tcp->tcp_ecn_ok = B_TRUE;
25784 
25785 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
25786 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
25787 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
25788 		if (syn_mp) {
25789 			/*
25790 			 * cr contains the cred from the thread calling
25791 			 * connect().
25792 			 *
25793 			 * If no thread cred is available, use the
25794 			 * socket creator's cred instead. If still no
25795 			 * cred, drop the request rather than risk a
25796 			 * panic on production systems.
25797 			 */
25798 			if (cr == NULL) {
25799 				cr = CONN_CRED(connp);
25800 				pid = tcp->tcp_cpid;
25801 				ASSERT(cr != NULL);
25802 				if (cr != NULL) {
25803 					mblk_setcred(syn_mp, cr, pid);
25804 				} else {
25805 					error = ECONNABORTED;
25806 					goto ipcl_rm;
25807 				}
25808 
25809 			/*
25810 			 * If an effective security label exists for
25811 			 * the connection, create a copy of the thread's
25812 			 * cred but with the effective label attached.
25813 			 */
25814 			} else if (is_system_labeled() &&
25815 			    connp->conn_effective_cred != NULL &&
25816 			    (tsl = crgetlabel(connp->
25817 			    conn_effective_cred)) != NULL) {
25818 				if ((ecr = copycred_from_tslabel(cr,
25819 				    tsl, KM_NOSLEEP)) == NULL) {
25820 					error = ENOMEM;
25821 					goto ipcl_rm;
25822 				}
25823 				mblk_setcred(syn_mp, ecr, pid);
25824 				crfree(ecr);
25825 
25826 			/*
25827 			 * Default to using the thread's cred unchanged.
25828 			 */
25829 			} else {
25830 				mblk_setcred(syn_mp, cr, pid);
25831 			}
25832 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
25833 		}
25834 	after_syn_sent:
25835 		if (mp != NULL) {
25836 			ASSERT(mp->b_cont == NULL);
25837 			freeb(mp);
25838 		}
25839 		return (error);
25840 	} else {
25841 		/* error */
25842 		if (tcp->tcp_debug) {
25843 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
25844 			    "tcp_post_ip_bind: error == %d", error);
25845 		}
25846 		if (mp != NULL) {
25847 			freeb(mp);
25848 		}
25849 	}
25850 
25851 ipcl_rm:
25852 	/*
25853 	 * Need to unbind with classifier since we were just
25854 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
25855 	 */
25856 	tcp->tcp_hard_bound = B_FALSE;
25857 	tcp->tcp_hard_binding = B_FALSE;
25858 
25859 	ipcl_hash_remove(connp);
25860 
25861 bind_failed:
25862 	tcp->tcp_state = TCPS_IDLE;
25863 	if (tcp->tcp_ipversion == IPV4_VERSION)
25864 		tcp->tcp_ipha->ipha_src = 0;
25865 	else
25866 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
25867 	/*
25868 	 * Copy of the src addr. in tcp_t is needed since
25869 	 * the lookup funcs. can only look at tcp_t
25870 	 */
25871 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
25872 
25873 	tcph = tcp->tcp_tcph;
25874 	tcph->th_lport[0] = 0;
25875 	tcph->th_lport[1] = 0;
25876 	tcp_bind_hash_remove(tcp);
25877 	bzero(&connp->u_port, sizeof (connp->u_port));
25878 	/* blow away saved option results if any */
25879 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
25880 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
25881 
25882 	conn_delete_ire(tcp->tcp_connp, NULL);
25883 
25884 	return (error);
25885 }
25886 
25887 static int
25888 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
25889     boolean_t bind_to_req_port_only, cred_t *cr)
25890 {
25891 	in_port_t	mlp_port;
25892 	mlp_type_t 	addrtype, mlptype;
25893 	boolean_t	user_specified;
25894 	in_port_t	allocated_port;
25895 	in_port_t	requested_port = *requested_port_ptr;
25896 	conn_t		*connp;
25897 	zone_t		*zone;
25898 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25899 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
25900 
25901 	/*
25902 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
25903 	 */
25904 	if (cr == NULL)
25905 		cr = tcp->tcp_cred;
25906 	/*
25907 	 * Get a valid port (within the anonymous range and should not
25908 	 * be a privileged one) to use if the user has not given a port.
25909 	 * If multiple threads are here, they may all start with
25910 	 * with the same initial port. But, it should be fine as long as
25911 	 * tcp_bindi will ensure that no two threads will be assigned
25912 	 * the same port.
25913 	 *
25914 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
25915 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
25916 	 * unless TCP_ANONPRIVBIND option is set.
25917 	 */
25918 	mlptype = mlptSingle;
25919 	mlp_port = requested_port;
25920 	if (requested_port == 0) {
25921 		requested_port = tcp->tcp_anon_priv_bind ?
25922 		    tcp_get_next_priv_port(tcp) :
25923 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
25924 		    tcp, B_TRUE);
25925 		if (requested_port == 0) {
25926 			return (-TNOADDR);
25927 		}
25928 		user_specified = B_FALSE;
25929 
25930 		/*
25931 		 * If the user went through one of the RPC interfaces to create
25932 		 * this socket and RPC is MLP in this zone, then give him an
25933 		 * anonymous MLP.
25934 		 */
25935 		connp = tcp->tcp_connp;
25936 		if (connp->conn_anon_mlp && is_system_labeled()) {
25937 			zone = crgetzone(cr);
25938 			addrtype = tsol_mlp_addr_type(zone->zone_id,
25939 			    IPV6_VERSION, &v6addr,
25940 			    tcps->tcps_netstack->netstack_ip);
25941 			if (addrtype == mlptSingle) {
25942 				return (-TNOADDR);
25943 			}
25944 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25945 			    PMAPPORT, addrtype);
25946 			mlp_port = PMAPPORT;
25947 		}
25948 	} else {
25949 		int i;
25950 		boolean_t priv = B_FALSE;
25951 
25952 		/*
25953 		 * If the requested_port is in the well-known privileged range,
25954 		 * verify that the stream was opened by a privileged user.
25955 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
25956 		 * but instead the code relies on:
25957 		 * - the fact that the address of the array and its size never
25958 		 *   changes
25959 		 * - the atomic assignment of the elements of the array
25960 		 */
25961 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
25962 			priv = B_TRUE;
25963 		} else {
25964 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
25965 				if (requested_port ==
25966 				    tcps->tcps_g_epriv_ports[i]) {
25967 					priv = B_TRUE;
25968 					break;
25969 				}
25970 			}
25971 		}
25972 		if (priv) {
25973 			if (secpolicy_net_privaddr(cr, requested_port,
25974 			    IPPROTO_TCP) != 0) {
25975 				if (tcp->tcp_debug) {
25976 					(void) strlog(TCP_MOD_ID, 0, 1,
25977 					    SL_ERROR|SL_TRACE,
25978 					    "tcp_bind: no priv for port %d",
25979 					    requested_port);
25980 				}
25981 				return (-TACCES);
25982 			}
25983 		}
25984 		user_specified = B_TRUE;
25985 
25986 		connp = tcp->tcp_connp;
25987 		if (is_system_labeled()) {
25988 			zone = crgetzone(cr);
25989 			addrtype = tsol_mlp_addr_type(zone->zone_id,
25990 			    IPV6_VERSION, &v6addr,
25991 			    tcps->tcps_netstack->netstack_ip);
25992 			if (addrtype == mlptSingle) {
25993 				return (-TNOADDR);
25994 			}
25995 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25996 			    requested_port, addrtype);
25997 		}
25998 	}
25999 
26000 	if (mlptype != mlptSingle) {
26001 		if (secpolicy_net_bindmlp(cr) != 0) {
26002 			if (tcp->tcp_debug) {
26003 				(void) strlog(TCP_MOD_ID, 0, 1,
26004 				    SL_ERROR|SL_TRACE,
26005 				    "tcp_bind: no priv for multilevel port %d",
26006 				    requested_port);
26007 			}
26008 			return (-TACCES);
26009 		}
26010 
26011 		/*
26012 		 * If we're specifically binding a shared IP address and the
26013 		 * port is MLP on shared addresses, then check to see if this
26014 		 * zone actually owns the MLP.  Reject if not.
26015 		 */
26016 		if (mlptype == mlptShared && addrtype == mlptShared) {
26017 			/*
26018 			 * No need to handle exclusive-stack zones since
26019 			 * ALL_ZONES only applies to the shared stack.
26020 			 */
26021 			zoneid_t mlpzone;
26022 
26023 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26024 			    htons(mlp_port));
26025 			if (connp->conn_zoneid != mlpzone) {
26026 				if (tcp->tcp_debug) {
26027 					(void) strlog(TCP_MOD_ID, 0, 1,
26028 					    SL_ERROR|SL_TRACE,
26029 					    "tcp_bind: attempt to bind port "
26030 					    "%d on shared addr in zone %d "
26031 					    "(should be %d)",
26032 					    mlp_port, connp->conn_zoneid,
26033 					    mlpzone);
26034 				}
26035 				return (-TACCES);
26036 			}
26037 		}
26038 
26039 		if (!user_specified) {
26040 			int err;
26041 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26042 			    requested_port, B_TRUE);
26043 			if (err != 0) {
26044 				if (tcp->tcp_debug) {
26045 					(void) strlog(TCP_MOD_ID, 0, 1,
26046 					    SL_ERROR|SL_TRACE,
26047 					    "tcp_bind: cannot establish anon "
26048 					    "MLP for port %d",
26049 					    requested_port);
26050 				}
26051 				return (err);
26052 			}
26053 			connp->conn_anon_port = B_TRUE;
26054 		}
26055 		connp->conn_mlp_type = mlptype;
26056 	}
26057 
26058 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26059 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26060 
26061 	if (allocated_port == 0) {
26062 		connp->conn_mlp_type = mlptSingle;
26063 		if (connp->conn_anon_port) {
26064 			connp->conn_anon_port = B_FALSE;
26065 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26066 			    requested_port, B_FALSE);
26067 		}
26068 		if (bind_to_req_port_only) {
26069 			if (tcp->tcp_debug) {
26070 				(void) strlog(TCP_MOD_ID, 0, 1,
26071 				    SL_ERROR|SL_TRACE,
26072 				    "tcp_bind: requested addr busy");
26073 			}
26074 			return (-TADDRBUSY);
26075 		} else {
26076 			/* If we are out of ports, fail the bind. */
26077 			if (tcp->tcp_debug) {
26078 				(void) strlog(TCP_MOD_ID, 0, 1,
26079 				    SL_ERROR|SL_TRACE,
26080 				    "tcp_bind: out of ports?");
26081 			}
26082 			return (-TNOADDR);
26083 		}
26084 	}
26085 
26086 	/* Pass the allocated port back */
26087 	*requested_port_ptr = allocated_port;
26088 	return (0);
26089 }
26090 
26091 static int
26092 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26093     boolean_t bind_to_req_port_only)
26094 {
26095 	tcp_t	*tcp = connp->conn_tcp;
26096 	sin_t	*sin;
26097 	sin6_t  *sin6;
26098 	in_port_t requested_port;
26099 	ipaddr_t	v4addr;
26100 	in6_addr_t	v6addr;
26101 	uint_t	origipversion;
26102 	int	error = 0;
26103 
26104 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26105 
26106 	if (tcp->tcp_state == TCPS_BOUND) {
26107 		return (0);
26108 	} else if (tcp->tcp_state > TCPS_BOUND) {
26109 		if (tcp->tcp_debug) {
26110 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26111 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26112 		}
26113 		return (-TOUTSTATE);
26114 	}
26115 	origipversion = tcp->tcp_ipversion;
26116 
26117 	ASSERT(sa != NULL && len != 0);
26118 
26119 	if (!OK_32PTR((char *)sa)) {
26120 		if (tcp->tcp_debug) {
26121 			(void) strlog(TCP_MOD_ID, 0, 1,
26122 			    SL_ERROR|SL_TRACE,
26123 			    "tcp_bind: bad address parameter, "
26124 			    "address %p, len %d",
26125 			    (void *)sa, len);
26126 		}
26127 		return (-TPROTO);
26128 	}
26129 
26130 	switch (len) {
26131 	case sizeof (sin_t):	/* Complete IPv4 address */
26132 		sin = (sin_t *)sa;
26133 		/*
26134 		 * With sockets sockfs will accept bogus sin_family in
26135 		 * bind() and replace it with the family used in the socket
26136 		 * call.
26137 		 */
26138 		if (sin->sin_family != AF_INET ||
26139 		    tcp->tcp_family != AF_INET) {
26140 			return (EAFNOSUPPORT);
26141 		}
26142 		requested_port = ntohs(sin->sin_port);
26143 		tcp->tcp_ipversion = IPV4_VERSION;
26144 		v4addr = sin->sin_addr.s_addr;
26145 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26146 		break;
26147 
26148 	case sizeof (sin6_t): /* Complete IPv6 address */
26149 		sin6 = (sin6_t *)sa;
26150 		if (sin6->sin6_family != AF_INET6 ||
26151 		    tcp->tcp_family != AF_INET6) {
26152 			return (EAFNOSUPPORT);
26153 		}
26154 		requested_port = ntohs(sin6->sin6_port);
26155 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26156 		    IPV4_VERSION : IPV6_VERSION;
26157 		v6addr = sin6->sin6_addr;
26158 		break;
26159 
26160 	default:
26161 		if (tcp->tcp_debug) {
26162 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26163 			    "tcp_bind: bad address length, %d", len);
26164 		}
26165 		return (EAFNOSUPPORT);
26166 		/* return (-TBADADDR); */
26167 	}
26168 
26169 	tcp->tcp_bound_source_v6 = v6addr;
26170 
26171 	/* Check for change in ipversion */
26172 	if (origipversion != tcp->tcp_ipversion) {
26173 		ASSERT(tcp->tcp_family == AF_INET6);
26174 		error = tcp->tcp_ipversion == IPV6_VERSION ?
26175 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26176 		if (error) {
26177 			return (ENOMEM);
26178 		}
26179 	}
26180 
26181 	/*
26182 	 * Initialize family specific fields. Copy of the src addr.
26183 	 * in tcp_t is needed for the lookup funcs.
26184 	 */
26185 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26186 		tcp->tcp_ip6h->ip6_src = v6addr;
26187 	} else {
26188 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
26189 	}
26190 	tcp->tcp_ip_src_v6 = v6addr;
26191 
26192 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
26193 
26194 	error = tcp_bind_select_lport(tcp, &requested_port,
26195 	    bind_to_req_port_only, cr);
26196 
26197 	return (error);
26198 }
26199 
26200 /*
26201  * Return unix error is tli error is TSYSERR, otherwise return a negative
26202  * tli error.
26203  */
26204 int
26205 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26206     boolean_t bind_to_req_port_only)
26207 {
26208 	int error;
26209 	tcp_t *tcp = connp->conn_tcp;
26210 
26211 	if (tcp->tcp_state >= TCPS_BOUND) {
26212 		if (tcp->tcp_debug) {
26213 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26214 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26215 		}
26216 		return (-TOUTSTATE);
26217 	}
26218 
26219 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
26220 	if (error != 0)
26221 		return (error);
26222 
26223 	ASSERT(tcp->tcp_state == TCPS_BOUND);
26224 
26225 	tcp->tcp_conn_req_max = 0;
26226 
26227 	if (tcp->tcp_family == AF_INET6) {
26228 		ASSERT(tcp->tcp_connp->conn_af_isv6);
26229 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
26230 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
26231 	} else {
26232 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
26233 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
26234 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
26235 	}
26236 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
26237 }
26238 
26239 int
26240 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
26241     socklen_t len, cred_t *cr)
26242 {
26243 	int 		error;
26244 	conn_t		*connp = (conn_t *)proto_handle;
26245 	squeue_t	*sqp = connp->conn_sqp;
26246 
26247 	/* All Solaris components should pass a cred for this operation. */
26248 	ASSERT(cr != NULL);
26249 
26250 	ASSERT(sqp != NULL);
26251 	ASSERT(connp->conn_upper_handle != NULL);
26252 
26253 	error = squeue_synch_enter(sqp, connp, NULL);
26254 	if (error != 0) {
26255 		/* failed to enter */
26256 		return (ENOSR);
26257 	}
26258 
26259 	/* binding to a NULL address really means unbind */
26260 	if (sa == NULL) {
26261 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
26262 			error = tcp_do_unbind(connp);
26263 		else
26264 			error = EINVAL;
26265 	} else {
26266 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
26267 	}
26268 
26269 	squeue_synch_exit(sqp, connp);
26270 
26271 	if (error < 0) {
26272 		if (error == -TOUTSTATE)
26273 			error = EINVAL;
26274 		else
26275 			error = proto_tlitosyserr(-error);
26276 	}
26277 
26278 	return (error);
26279 }
26280 
26281 /*
26282  * If the return value from this function is positive, it's a UNIX error.
26283  * Otherwise, if it's negative, then the absolute value is a TLI error.
26284  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
26285  */
26286 int
26287 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
26288     cred_t *cr, pid_t pid)
26289 {
26290 	tcp_t		*tcp = connp->conn_tcp;
26291 	sin_t		*sin = (sin_t *)sa;
26292 	sin6_t		*sin6 = (sin6_t *)sa;
26293 	ipaddr_t	*dstaddrp;
26294 	in_port_t	dstport;
26295 	uint_t		srcid;
26296 	int		error = 0;
26297 
26298 	switch (len) {
26299 	default:
26300 		/*
26301 		 * Should never happen
26302 		 */
26303 		return (EINVAL);
26304 
26305 	case sizeof (sin_t):
26306 		sin = (sin_t *)sa;
26307 		if (sin->sin_port == 0) {
26308 			return (-TBADADDR);
26309 		}
26310 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
26311 			return (EAFNOSUPPORT);
26312 		}
26313 		break;
26314 
26315 	case sizeof (sin6_t):
26316 		sin6 = (sin6_t *)sa;
26317 		if (sin6->sin6_port == 0) {
26318 			return (-TBADADDR);
26319 		}
26320 		break;
26321 	}
26322 	/*
26323 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
26324 	 * make sure that the template IP header in the tcp structure is an
26325 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
26326 	 * need to this before we call tcp_bindi() so that the port lookup
26327 	 * code will look for ports in the correct port space (IPv4 and
26328 	 * IPv6 have separate port spaces).
26329 	 */
26330 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
26331 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26332 		int err = 0;
26333 
26334 		err = tcp_header_init_ipv4(tcp);
26335 			if (err != 0) {
26336 				error = ENOMEM;
26337 				goto connect_failed;
26338 			}
26339 		if (tcp->tcp_lport != 0)
26340 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
26341 	}
26342 
26343 	switch (tcp->tcp_state) {
26344 	case TCPS_LISTEN:
26345 		/*
26346 		 * Listening sockets are not allowed to issue connect().
26347 		 */
26348 		if (IPCL_IS_NONSTR(connp))
26349 			return (EOPNOTSUPP);
26350 		/* FALLTHRU */
26351 	case TCPS_IDLE:
26352 		/*
26353 		 * We support quick connect, refer to comments in
26354 		 * tcp_connect_*()
26355 		 */
26356 		/* FALLTHRU */
26357 	case TCPS_BOUND:
26358 		/*
26359 		 * We must bump the generation before the operation start.
26360 		 * This is done to ensure that any upcall made later on sends
26361 		 * up the right generation to the socket.
26362 		 */
26363 		SOCK_CONNID_BUMP(tcp->tcp_connid);
26364 
26365 		if (tcp->tcp_family == AF_INET6) {
26366 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26367 				return (tcp_connect_ipv6(tcp,
26368 				    &sin6->sin6_addr,
26369 				    sin6->sin6_port, sin6->sin6_flowinfo,
26370 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
26371 				    cr, pid));
26372 			}
26373 			/*
26374 			 * Destination adress is mapped IPv6 address.
26375 			 * Source bound address should be unspecified or
26376 			 * IPv6 mapped address as well.
26377 			 */
26378 			if (!IN6_IS_ADDR_UNSPECIFIED(
26379 			    &tcp->tcp_bound_source_v6) &&
26380 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
26381 				return (EADDRNOTAVAIL);
26382 			}
26383 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
26384 			dstport = sin6->sin6_port;
26385 			srcid = sin6->__sin6_src_id;
26386 		} else {
26387 			dstaddrp = &sin->sin_addr.s_addr;
26388 			dstport = sin->sin_port;
26389 			srcid = 0;
26390 		}
26391 
26392 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
26393 		    pid);
26394 		break;
26395 	default:
26396 		return (-TOUTSTATE);
26397 	}
26398 	/*
26399 	 * Note: Code below is the "failure" case
26400 	 */
26401 connect_failed:
26402 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26403 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26404 	return (error);
26405 }
26406 
26407 int
26408 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
26409     socklen_t len, sock_connid_t *id, cred_t *cr)
26410 {
26411 	conn_t		*connp = (conn_t *)proto_handle;
26412 	tcp_t		*tcp = connp->conn_tcp;
26413 	squeue_t	*sqp = connp->conn_sqp;
26414 	int		error;
26415 
26416 	ASSERT(connp->conn_upper_handle != NULL);
26417 
26418 	/* All Solaris components should pass a cred for this operation. */
26419 	ASSERT(cr != NULL);
26420 
26421 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
26422 	if (error != 0) {
26423 		return (error);
26424 	}
26425 
26426 	error = squeue_synch_enter(sqp, connp, NULL);
26427 	if (error != 0) {
26428 		/* failed to enter */
26429 		return (ENOSR);
26430 	}
26431 
26432 	/*
26433 	 * TCP supports quick connect, so no need to do an implicit bind
26434 	 */
26435 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
26436 	if (error == 0) {
26437 		*id = connp->conn_tcp->tcp_connid;
26438 	} else if (error < 0) {
26439 		if (error == -TOUTSTATE) {
26440 			switch (connp->conn_tcp->tcp_state) {
26441 			case TCPS_SYN_SENT:
26442 				error = EALREADY;
26443 				break;
26444 			case TCPS_ESTABLISHED:
26445 				error = EISCONN;
26446 				break;
26447 			case TCPS_LISTEN:
26448 				error = EOPNOTSUPP;
26449 				break;
26450 			default:
26451 				error = EINVAL;
26452 				break;
26453 			}
26454 		} else {
26455 			error = proto_tlitosyserr(-error);
26456 		}
26457 	}
26458 done:
26459 	squeue_synch_exit(sqp, connp);
26460 
26461 	return ((error == 0) ? EINPROGRESS : error);
26462 }
26463 
26464 /* ARGSUSED */
26465 sock_lower_handle_t
26466 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
26467     uint_t *smodep, int *errorp, int flags, cred_t *credp)
26468 {
26469 	conn_t		*connp;
26470 	boolean_t	isv6 = family == AF_INET6;
26471 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
26472 	    (proto != 0 && proto != IPPROTO_TCP)) {
26473 		*errorp = EPROTONOSUPPORT;
26474 		return (NULL);
26475 	}
26476 
26477 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
26478 	if (connp == NULL) {
26479 		return (NULL);
26480 	}
26481 
26482 	/*
26483 	 * Put the ref for TCP. Ref for IP was already put
26484 	 * by ipcl_conn_create. Also Make the conn_t globally
26485 	 * visible to walkers
26486 	 */
26487 	mutex_enter(&connp->conn_lock);
26488 	CONN_INC_REF_LOCKED(connp);
26489 	ASSERT(connp->conn_ref == 2);
26490 	connp->conn_state_flags &= ~CONN_INCIPIENT;
26491 
26492 	connp->conn_flags |= IPCL_NONSTR;
26493 	mutex_exit(&connp->conn_lock);
26494 
26495 	ASSERT(errorp != NULL);
26496 	*errorp = 0;
26497 	*sock_downcalls = &sock_tcp_downcalls;
26498 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
26499 	    SM_SENDFILESUPP;
26500 
26501 	return ((sock_lower_handle_t)connp);
26502 }
26503 
26504 /* ARGSUSED */
26505 void
26506 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
26507     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
26508 {
26509 	conn_t *connp = (conn_t *)proto_handle;
26510 	struct sock_proto_props sopp;
26511 
26512 	ASSERT(connp->conn_upper_handle == NULL);
26513 
26514 	/* All Solaris components should pass a cred for this operation. */
26515 	ASSERT(cr != NULL);
26516 
26517 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
26518 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
26519 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
26520 
26521 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
26522 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
26523 	sopp.sopp_maxpsz = INFPSZ;
26524 	sopp.sopp_maxblk = INFPSZ;
26525 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
26526 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
26527 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
26528 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
26529 	    tcp_rinfo.mi_minpsz;
26530 
26531 	connp->conn_upcalls = sock_upcalls;
26532 	connp->conn_upper_handle = sock_handle;
26533 
26534 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
26535 }
26536 
26537 /* ARGSUSED */
26538 int
26539 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
26540 {
26541 	conn_t *connp = (conn_t *)proto_handle;
26542 
26543 	ASSERT(connp->conn_upper_handle != NULL);
26544 
26545 	/* All Solaris components should pass a cred for this operation. */
26546 	ASSERT(cr != NULL);
26547 
26548 	tcp_close_common(connp, flags);
26549 
26550 	ip_free_helper_stream(connp);
26551 
26552 	/*
26553 	 * Drop IP's reference on the conn. This is the last reference
26554 	 * on the connp if the state was less than established. If the
26555 	 * connection has gone into timewait state, then we will have
26556 	 * one ref for the TCP and one more ref (total of two) for the
26557 	 * classifier connected hash list (a timewait connections stays
26558 	 * in connected hash till closed).
26559 	 *
26560 	 * We can't assert the references because there might be other
26561 	 * transient reference places because of some walkers or queued
26562 	 * packets in squeue for the timewait state.
26563 	 */
26564 	CONN_DEC_REF(connp);
26565 	return (0);
26566 }
26567 
26568 /* ARGSUSED */
26569 int
26570 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
26571     cred_t *cr)
26572 {
26573 	tcp_t		*tcp;
26574 	uint32_t	msize;
26575 	conn_t *connp = (conn_t *)proto_handle;
26576 	int32_t		tcpstate;
26577 
26578 	/* All Solaris components should pass a cred for this operation. */
26579 	ASSERT(cr != NULL);
26580 
26581 	ASSERT(connp->conn_ref >= 2);
26582 	ASSERT(connp->conn_upper_handle != NULL);
26583 
26584 	if (msg->msg_controllen != 0) {
26585 		return (EOPNOTSUPP);
26586 
26587 	}
26588 	switch (DB_TYPE(mp)) {
26589 	case M_DATA:
26590 		tcp = connp->conn_tcp;
26591 		ASSERT(tcp != NULL);
26592 
26593 		tcpstate = tcp->tcp_state;
26594 		if (tcpstate < TCPS_ESTABLISHED) {
26595 			freemsg(mp);
26596 			return (ENOTCONN);
26597 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
26598 			freemsg(mp);
26599 			return (EPIPE);
26600 		}
26601 
26602 		msize = msgdsize(mp);
26603 
26604 		mutex_enter(&tcp->tcp_non_sq_lock);
26605 		tcp->tcp_squeue_bytes += msize;
26606 		/*
26607 		 * Squeue Flow Control
26608 		 */
26609 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
26610 			tcp_setqfull(tcp);
26611 		}
26612 		mutex_exit(&tcp->tcp_non_sq_lock);
26613 
26614 		/*
26615 		 * The application may pass in an address in the msghdr, but
26616 		 * we ignore the address on connection-oriented sockets.
26617 		 * Just like BSD this code does not generate an error for
26618 		 * TCP (a CONNREQUIRED socket) when sending to an address
26619 		 * passed in with sendto/sendmsg. Instead the data is
26620 		 * delivered on the connection as if no address had been
26621 		 * supplied.
26622 		 */
26623 		CONN_INC_REF(connp);
26624 
26625 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
26626 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
26627 			    tcp_output_urgent, connp, tcp_squeue_flag,
26628 			    SQTAG_TCP_OUTPUT);
26629 		} else {
26630 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
26631 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
26632 		}
26633 
26634 		return (0);
26635 
26636 	default:
26637 		ASSERT(0);
26638 	}
26639 
26640 	freemsg(mp);
26641 	return (0);
26642 }
26643 
26644 /* ARGSUSED */
26645 void
26646 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
26647 {
26648 	int len;
26649 	uint32_t msize;
26650 	conn_t *connp = (conn_t *)arg;
26651 	tcp_t *tcp = connp->conn_tcp;
26652 
26653 	msize = msgdsize(mp);
26654 
26655 	len = msize - 1;
26656 	if (len < 0) {
26657 		freemsg(mp);
26658 		return;
26659 	}
26660 
26661 	/*
26662 	 * Try to force urgent data out on the wire.
26663 	 * Even if we have unsent data this will
26664 	 * at least send the urgent flag.
26665 	 * XXX does not handle more flag correctly.
26666 	 */
26667 	len += tcp->tcp_unsent;
26668 	len += tcp->tcp_snxt;
26669 	tcp->tcp_urg = len;
26670 	tcp->tcp_valid_bits |= TCP_URG_VALID;
26671 
26672 	/* Bypass tcp protocol for fused tcp loopback */
26673 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
26674 		return;
26675 	tcp_wput_data(tcp, mp, B_TRUE);
26676 }
26677 
26678 /* ARGSUSED */
26679 int
26680 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26681     socklen_t *addrlenp, cred_t *cr)
26682 {
26683 	conn_t	*connp = (conn_t *)proto_handle;
26684 	tcp_t	*tcp = connp->conn_tcp;
26685 
26686 	ASSERT(connp->conn_upper_handle != NULL);
26687 	/* All Solaris components should pass a cred for this operation. */
26688 	ASSERT(cr != NULL);
26689 
26690 	ASSERT(tcp != NULL);
26691 
26692 	return (tcp_do_getpeername(tcp, addr, addrlenp));
26693 }
26694 
26695 /* ARGSUSED */
26696 int
26697 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26698     socklen_t *addrlenp, cred_t *cr)
26699 {
26700 	conn_t	*connp = (conn_t *)proto_handle;
26701 	tcp_t	*tcp = connp->conn_tcp;
26702 
26703 	/* All Solaris components should pass a cred for this operation. */
26704 	ASSERT(cr != NULL);
26705 
26706 	ASSERT(connp->conn_upper_handle != NULL);
26707 
26708 	return (tcp_do_getsockname(tcp, addr, addrlenp));
26709 }
26710 
26711 /*
26712  * tcp_fallback
26713  *
26714  * A direct socket is falling back to using STREAMS. The queue
26715  * that is being passed down was created using tcp_open() with
26716  * the SO_FALLBACK flag set. As a result, the queue is not
26717  * associated with a conn, and the q_ptrs instead contain the
26718  * dev and minor area that should be used.
26719  *
26720  * The 'direct_sockfs' flag indicates whether the FireEngine
26721  * optimizations should be used. The common case would be that
26722  * optimizations are enabled, and they might be subsequently
26723  * disabled using the _SIOCSOCKFALLBACK ioctl.
26724  */
26725 
26726 /*
26727  * An active connection is falling back to TPI. Gather all the information
26728  * required by the STREAM head and TPI sonode and send it up.
26729  */
26730 void
26731 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
26732     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
26733 {
26734 	conn_t			*connp = tcp->tcp_connp;
26735 	struct stroptions	*stropt;
26736 	struct T_capability_ack tca;
26737 	struct sockaddr_in6	laddr, faddr;
26738 	socklen_t 		laddrlen, faddrlen;
26739 	short			opts;
26740 	int			error;
26741 	mblk_t			*mp;
26742 
26743 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
26744 	connp->conn_minor_arena = WR(q)->q_ptr;
26745 
26746 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
26747 
26748 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
26749 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
26750 
26751 	WR(q)->q_qinfo = &tcp_sock_winit;
26752 
26753 	if (!direct_sockfs)
26754 		tcp_disable_direct_sockfs(tcp);
26755 
26756 	/*
26757 	 * free the helper stream
26758 	 */
26759 	ip_free_helper_stream(connp);
26760 
26761 	/*
26762 	 * Notify the STREAM head about options
26763 	 */
26764 	DB_TYPE(stropt_mp) = M_SETOPTS;
26765 	stropt = (struct stroptions *)stropt_mp->b_rptr;
26766 	stropt_mp->b_wptr += sizeof (struct stroptions);
26767 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
26768 
26769 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
26770 	    tcp->tcp_tcps->tcps_wroff_xtra);
26771 	if (tcp->tcp_snd_sack_ok)
26772 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
26773 	stropt->so_hiwat = tcp->tcp_fused ?
26774 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
26775 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
26776 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
26777 
26778 	putnext(RD(q), stropt_mp);
26779 
26780 	/*
26781 	 * Collect the information needed to sync with the sonode
26782 	 */
26783 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
26784 
26785 	laddrlen = faddrlen = sizeof (sin6_t);
26786 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
26787 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
26788 	if (error != 0)
26789 		faddrlen = 0;
26790 
26791 	opts = 0;
26792 	if (tcp->tcp_oobinline)
26793 		opts |= SO_OOBINLINE;
26794 	if (tcp->tcp_dontroute)
26795 		opts |= SO_DONTROUTE;
26796 
26797 	/*
26798 	 * Notify the socket that the protocol is now quiescent,
26799 	 * and it's therefore safe move data from the socket
26800 	 * to the stream head.
26801 	 */
26802 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
26803 	    (struct sockaddr *)&laddr, laddrlen,
26804 	    (struct sockaddr *)&faddr, faddrlen, opts);
26805 
26806 	while ((mp = tcp->tcp_rcv_list) != NULL) {
26807 		tcp->tcp_rcv_list = mp->b_next;
26808 		mp->b_next = NULL;
26809 		putnext(q, mp);
26810 	}
26811 	tcp->tcp_rcv_last_head = NULL;
26812 	tcp->tcp_rcv_last_tail = NULL;
26813 	tcp->tcp_rcv_cnt = 0;
26814 }
26815 
26816 /*
26817  * An eager is falling back to TPI. All we have to do is send
26818  * up a T_CONN_IND.
26819  */
26820 void
26821 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
26822 {
26823 	tcp_t *listener = eager->tcp_listener;
26824 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
26825 
26826 	ASSERT(listener != NULL);
26827 	ASSERT(mp != NULL);
26828 
26829 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
26830 
26831 	/*
26832 	 * TLI/XTI applications will get confused by
26833 	 * sending eager as an option since it violates
26834 	 * the option semantics. So remove the eager as
26835 	 * option since TLI/XTI app doesn't need it anyway.
26836 	 */
26837 	if (!direct_sockfs) {
26838 		struct T_conn_ind *conn_ind;
26839 
26840 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
26841 		conn_ind->OPT_length = 0;
26842 		conn_ind->OPT_offset = 0;
26843 	}
26844 
26845 	/*
26846 	 * Sockfs guarantees that the listener will not be closed
26847 	 * during fallback. So we can safely use the listener's queue.
26848 	 */
26849 	putnext(listener->tcp_rq, mp);
26850 }
26851 
26852 int
26853 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
26854     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
26855 {
26856 	tcp_t			*tcp;
26857 	conn_t 			*connp = (conn_t *)proto_handle;
26858 	int			error;
26859 	mblk_t			*stropt_mp;
26860 	mblk_t			*ordrel_mp;
26861 	mblk_t			*fused_sigurp_mp;
26862 
26863 	tcp = connp->conn_tcp;
26864 
26865 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
26866 	    NULL);
26867 
26868 	/* Pre-allocate the T_ordrel_ind mblk. */
26869 	ASSERT(tcp->tcp_ordrel_mp == NULL);
26870 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
26871 	    STR_NOSIG, NULL);
26872 	ordrel_mp->b_datap->db_type = M_PROTO;
26873 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
26874 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
26875 
26876 	/* Pre-allocate the M_PCSIG used by fusion */
26877 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
26878 
26879 	/*
26880 	 * Enter the squeue so that no new packets can come in
26881 	 */
26882 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
26883 	if (error != 0) {
26884 		/* failed to enter, free all the pre-allocated messages. */
26885 		freeb(stropt_mp);
26886 		freeb(ordrel_mp);
26887 		freeb(fused_sigurp_mp);
26888 		/*
26889 		 * We cannot process the eager, so at least send out a
26890 		 * RST so the peer can reconnect.
26891 		 */
26892 		if (tcp->tcp_listener != NULL) {
26893 			(void) tcp_eager_blowoff(tcp->tcp_listener,
26894 			    tcp->tcp_conn_req_seqnum);
26895 		}
26896 		return (ENOMEM);
26897 	}
26898 
26899 	/*
26900 	 * No longer a direct socket
26901 	 */
26902 	connp->conn_flags &= ~IPCL_NONSTR;
26903 
26904 	tcp->tcp_ordrel_mp = ordrel_mp;
26905 
26906 	if (tcp->tcp_fused) {
26907 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
26908 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
26909 	} else {
26910 		freeb(fused_sigurp_mp);
26911 	}
26912 
26913 	if (tcp->tcp_listener != NULL) {
26914 		/* The eager will deal with opts when accept() is called */
26915 		freeb(stropt_mp);
26916 		tcp_fallback_eager(tcp, direct_sockfs);
26917 	} else {
26918 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
26919 		    quiesced_cb);
26920 	}
26921 
26922 	/*
26923 	 * There should be atleast two ref's (IP + TCP)
26924 	 */
26925 	ASSERT(connp->conn_ref >= 2);
26926 	squeue_synch_exit(connp->conn_sqp, connp);
26927 
26928 	return (0);
26929 }
26930 
26931 /* ARGSUSED */
26932 static void
26933 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
26934 {
26935 	conn_t 	*connp = (conn_t *)arg;
26936 	tcp_t	*tcp = connp->conn_tcp;
26937 
26938 	freemsg(mp);
26939 
26940 	if (tcp->tcp_fused)
26941 		tcp_unfuse(tcp);
26942 
26943 	if (tcp_xmit_end(tcp) != 0) {
26944 		/*
26945 		 * We were crossing FINs and got a reset from
26946 		 * the other side. Just ignore it.
26947 		 */
26948 		if (tcp->tcp_debug) {
26949 			(void) strlog(TCP_MOD_ID, 0, 1,
26950 			    SL_ERROR|SL_TRACE,
26951 			    "tcp_shutdown_output() out of state %s",
26952 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
26953 		}
26954 	}
26955 }
26956 
26957 /* ARGSUSED */
26958 int
26959 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
26960 {
26961 	conn_t  *connp = (conn_t *)proto_handle;
26962 	tcp_t   *tcp = connp->conn_tcp;
26963 
26964 	ASSERT(connp->conn_upper_handle != NULL);
26965 
26966 	/* All Solaris components should pass a cred for this operation. */
26967 	ASSERT(cr != NULL);
26968 
26969 	/*
26970 	 * X/Open requires that we check the connected state.
26971 	 */
26972 	if (tcp->tcp_state < TCPS_SYN_SENT)
26973 		return (ENOTCONN);
26974 
26975 	/* shutdown the send side */
26976 	if (how != SHUT_RD) {
26977 		mblk_t *bp;
26978 
26979 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
26980 		CONN_INC_REF(connp);
26981 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
26982 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
26983 
26984 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
26985 		    SOCK_OPCTL_SHUT_SEND, 0);
26986 	}
26987 
26988 	/* shutdown the recv side */
26989 	if (how != SHUT_WR)
26990 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
26991 		    SOCK_OPCTL_SHUT_RECV, 0);
26992 
26993 	return (0);
26994 }
26995 
26996 /*
26997  * SOP_LISTEN() calls into tcp_listen().
26998  */
26999 /* ARGSUSED */
27000 int
27001 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27002 {
27003 	conn_t	*connp = (conn_t *)proto_handle;
27004 	int 	error;
27005 	squeue_t *sqp = connp->conn_sqp;
27006 
27007 	ASSERT(connp->conn_upper_handle != NULL);
27008 
27009 	/* All Solaris components should pass a cred for this operation. */
27010 	ASSERT(cr != NULL);
27011 
27012 	error = squeue_synch_enter(sqp, connp, NULL);
27013 	if (error != 0) {
27014 		/* failed to enter */
27015 		return (ENOBUFS);
27016 	}
27017 
27018 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
27019 	if (error == 0) {
27020 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27021 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27022 	} else if (error < 0) {
27023 		if (error == -TOUTSTATE)
27024 			error = EINVAL;
27025 		else
27026 			error = proto_tlitosyserr(-error);
27027 	}
27028 	squeue_synch_exit(sqp, connp);
27029 	return (error);
27030 }
27031 
27032 static int
27033 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
27034     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
27035 {
27036 	tcp_t		*tcp = connp->conn_tcp;
27037 	int		error = 0;
27038 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27039 
27040 	/* All Solaris components should pass a cred for this operation. */
27041 	ASSERT(cr != NULL);
27042 
27043 	if (tcp->tcp_state >= TCPS_BOUND) {
27044 		if ((tcp->tcp_state == TCPS_BOUND ||
27045 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27046 			/*
27047 			 * Handle listen() increasing backlog.
27048 			 * This is more "liberal" then what the TPI spec
27049 			 * requires but is needed to avoid a t_unbind
27050 			 * when handling listen() since the port number
27051 			 * might be "stolen" between the unbind and bind.
27052 			 */
27053 			goto do_listen;
27054 		}
27055 		if (tcp->tcp_debug) {
27056 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27057 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27058 		}
27059 		return (-TOUTSTATE);
27060 	} else {
27061 		if (sa == NULL) {
27062 			sin6_t	addr;
27063 			sin_t *sin;
27064 			sin6_t *sin6;
27065 
27066 			ASSERT(IPCL_IS_NONSTR(connp));
27067 
27068 			/* Do an implicit bind: Request for a generic port. */
27069 			if (tcp->tcp_family == AF_INET) {
27070 				len = sizeof (sin_t);
27071 				sin = (sin_t *)&addr;
27072 				*sin = sin_null;
27073 				sin->sin_family = AF_INET;
27074 				tcp->tcp_ipversion = IPV4_VERSION;
27075 			} else {
27076 				ASSERT(tcp->tcp_family == AF_INET6);
27077 				len = sizeof (sin6_t);
27078 				sin6 = (sin6_t *)&addr;
27079 				*sin6 = sin6_null;
27080 				sin6->sin6_family = AF_INET6;
27081 				tcp->tcp_ipversion = IPV6_VERSION;
27082 			}
27083 			sa = (struct sockaddr *)&addr;
27084 		}
27085 
27086 		error = tcp_bind_check(connp, sa, len, cr,
27087 		    bind_to_req_port_only);
27088 		if (error)
27089 			return (error);
27090 		/* Fall through and do the fanout insertion */
27091 	}
27092 
27093 do_listen:
27094 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27095 	tcp->tcp_conn_req_max = backlog;
27096 	if (tcp->tcp_conn_req_max) {
27097 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27098 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27099 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27100 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27101 		/*
27102 		 * If this is a listener, do not reset the eager list
27103 		 * and other stuffs.  Note that we don't check if the
27104 		 * existing eager list meets the new tcp_conn_req_max
27105 		 * requirement.
27106 		 */
27107 		if (tcp->tcp_state != TCPS_LISTEN) {
27108 			tcp->tcp_state = TCPS_LISTEN;
27109 			/* Initialize the chain. Don't need the eager_lock */
27110 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27111 			tcp->tcp_eager_next_drop_q0 = tcp;
27112 			tcp->tcp_eager_prev_drop_q0 = tcp;
27113 			tcp->tcp_second_ctimer_threshold =
27114 			    tcps->tcps_ip_abort_linterval;
27115 		}
27116 	}
27117 
27118 	/*
27119 	 * We can call ip_bind directly, the processing continues
27120 	 * in tcp_post_ip_bind().
27121 	 *
27122 	 * We need to make sure that the conn_recv is set to a non-null
27123 	 * value before we insert the conn into the classifier table.
27124 	 * This is to avoid a race with an incoming packet which does an
27125 	 * ipcl_classify().
27126 	 */
27127 	connp->conn_recv = tcp_conn_request;
27128 	if (tcp->tcp_family == AF_INET) {
27129 		error = ip_proto_bind_laddr_v4(connp, NULL,
27130 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27131 	} else {
27132 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27133 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27134 	}
27135 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27136 }
27137 
27138 void
27139 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27140 {
27141 	conn_t  *connp = (conn_t *)proto_handle;
27142 	tcp_t	*tcp = connp->conn_tcp;
27143 	mblk_t *mp;
27144 	int error;
27145 
27146 	ASSERT(connp->conn_upper_handle != NULL);
27147 
27148 	/*
27149 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
27150 	 * is currently running.
27151 	 */
27152 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27153 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
27154 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
27155 		return;
27156 	}
27157 	tcp->tcp_rsrv_mp = NULL;
27158 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27159 
27160 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
27161 	ASSERT(error == 0);
27162 
27163 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27164 	tcp->tcp_rsrv_mp = mp;
27165 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27166 
27167 	if (tcp->tcp_fused) {
27168 		tcp_fuse_backenable(tcp);
27169 	} else {
27170 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27171 		/*
27172 		 * Send back a window update immediately if TCP is above
27173 		 * ESTABLISHED state and the increase of the rcv window
27174 		 * that the other side knows is at least 1 MSS after flow
27175 		 * control is lifted.
27176 		 */
27177 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27178 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
27179 			tcp_xmit_ctl(NULL, tcp,
27180 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27181 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27182 		}
27183 	}
27184 
27185 	squeue_synch_exit(connp->conn_sqp, connp);
27186 }
27187 
27188 /* ARGSUSED */
27189 int
27190 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27191     int mode, int32_t *rvalp, cred_t *cr)
27192 {
27193 	conn_t  	*connp = (conn_t *)proto_handle;
27194 	int		error;
27195 
27196 	ASSERT(connp->conn_upper_handle != NULL);
27197 
27198 	/* All Solaris components should pass a cred for this operation. */
27199 	ASSERT(cr != NULL);
27200 
27201 	switch (cmd) {
27202 		case ND_SET:
27203 		case ND_GET:
27204 		case TCP_IOC_DEFAULT_Q:
27205 		case _SIOCSOCKFALLBACK:
27206 		case TCP_IOC_ABORT_CONN:
27207 		case TI_GETPEERNAME:
27208 		case TI_GETMYNAME:
27209 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27210 			    cmd));
27211 			error = EINVAL;
27212 			break;
27213 		default:
27214 			/*
27215 			 * Pass on to IP using helper stream
27216 			 */
27217 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
27218 			    cmd, arg, mode, cr, rvalp);
27219 			break;
27220 	}
27221 	return (error);
27222 }
27223 
27224 sock_downcalls_t sock_tcp_downcalls = {
27225 	tcp_activate,
27226 	tcp_accept,
27227 	tcp_bind,
27228 	tcp_listen,
27229 	tcp_connect,
27230 	tcp_getpeername,
27231 	tcp_getsockname,
27232 	tcp_getsockopt,
27233 	tcp_setsockopt,
27234 	tcp_sendmsg,
27235 	NULL,
27236 	NULL,
27237 	NULL,
27238 	tcp_shutdown,
27239 	tcp_clr_flowctrl,
27240 	tcp_ioctl,
27241 	tcp_close,
27242 };
27243