xref: /titanic_51/usr/src/uts/common/inet/tcp/tcp.c (revision 825277341c15b6b0d2c4b8b622ae7b1d2bdc0390)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #define	_SUN_TPI_VERSION 2
35 #include <sys/tihdr.h>
36 #include <sys/timod.h>
37 #include <sys/ddi.h>
38 #include <sys/sunddi.h>
39 #include <sys/suntpi.h>
40 #include <sys/xti_inet.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/sdt.h>
44 #include <sys/vtrace.h>
45 #include <sys/kmem.h>
46 #include <sys/ethernet.h>
47 #include <sys/cpuvar.h>
48 #include <sys/dlpi.h>
49 #include <sys/multidata.h>
50 #include <sys/multidata_impl.h>
51 #include <sys/pattr.h>
52 #include <sys/policy.h>
53 #include <sys/priv.h>
54 #include <sys/zone.h>
55 #include <sys/sunldi.h>
56 
57 #include <sys/errno.h>
58 #include <sys/signal.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/sockio.h>
62 #include <sys/isa_defs.h>
63 #include <sys/md5.h>
64 #include <sys/random.h>
65 #include <sys/uio.h>
66 #include <sys/systm.h>
67 #include <netinet/in.h>
68 #include <netinet/tcp.h>
69 #include <netinet/ip6.h>
70 #include <netinet/icmp6.h>
71 #include <net/if.h>
72 #include <net/route.h>
73 #include <inet/ipsec_impl.h>
74 
75 #include <inet/common.h>
76 #include <inet/ip.h>
77 #include <inet/ip_impl.h>
78 #include <inet/ip6.h>
79 #include <inet/ip_ndp.h>
80 #include <inet/proto_set.h>
81 #include <inet/mib2.h>
82 #include <inet/nd.h>
83 #include <inet/optcom.h>
84 #include <inet/snmpcom.h>
85 #include <inet/kstatcom.h>
86 #include <inet/tcp.h>
87 #include <inet/tcp_impl.h>
88 #include <inet/udp_impl.h>
89 #include <net/pfkeyv2.h>
90 #include <inet/ipsec_info.h>
91 #include <inet/ipdrop.h>
92 
93 #include <inet/ipclassifier.h>
94 #include <inet/ip_ire.h>
95 #include <inet/ip_ftable.h>
96 #include <inet/ip_if.h>
97 #include <inet/ipp_common.h>
98 #include <inet/ip_netinfo.h>
99 #include <sys/squeue_impl.h>
100 #include <sys/squeue.h>
101 #include <inet/kssl/ksslapi.h>
102 #include <sys/tsol/label.h>
103 #include <sys/tsol/tnet.h>
104 #include <rpc/pmap_prot.h>
105 #include <sys/callo.h>
106 
107 /*
108  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
109  *
110  * (Read the detailed design doc in PSARC case directory)
111  *
112  * The entire tcp state is contained in tcp_t and conn_t structure
113  * which are allocated in tandem using ipcl_conn_create() and passing
114  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
115  * the references on the tcp_t. The tcp_t structure is never compressed
116  * and packets always land on the correct TCP perimeter from the time
117  * eager is created till the time tcp_t dies (as such the old mentat
118  * TCP global queue is not used for detached state and no IPSEC checking
119  * is required). The global queue is still allocated to send out resets
120  * for connection which have no listeners and IP directly calls
121  * tcp_xmit_listeners_reset() which does any policy check.
122  *
123  * Protection and Synchronisation mechanism:
124  *
125  * The tcp data structure does not use any kind of lock for protecting
126  * its state but instead uses 'squeues' for mutual exclusion from various
127  * read and write side threads. To access a tcp member, the thread should
128  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
129  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
130  * can pass any tcp function having prototype of edesc_t as argument
131  * (different from traditional STREAMs model where packets come in only
132  * designated entry points). The list of functions that can be directly
133  * called via squeue are listed before the usual function prototype.
134  *
135  * Referencing:
136  *
137  * TCP is MT-Hot and we use a reference based scheme to make sure that the
138  * tcp structure doesn't disappear when its needed. When the application
139  * creates an outgoing connection or accepts an incoming connection, we
140  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
141  * The IP reference is just a symbolic reference since ip_tcpclose()
142  * looks at tcp structure after tcp_close_output() returns which could
143  * have dropped the last TCP reference. So as long as the connection is
144  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
145  * conn_t. The classifier puts its own reference when the connection is
146  * inserted in listen or connected hash. Anytime a thread needs to enter
147  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
148  * on write side or by doing a classify on read side and then puts a
149  * reference on the conn before doing squeue_enter/tryenter/fill. For
150  * read side, the classifier itself puts the reference under fanout lock
151  * to make sure that tcp can't disappear before it gets processed. The
152  * squeue will drop this reference automatically so the called function
153  * doesn't have to do a DEC_REF.
154  *
155  * Opening a new connection:
156  *
157  * The outgoing connection open is pretty simple. tcp_open() does the
158  * work in creating the conn/tcp structure and initializing it. The
159  * squeue assignment is done based on the CPU the application
160  * is running on. So for outbound connections, processing is always done
161  * on application CPU which might be different from the incoming CPU
162  * being interrupted by the NIC. An optimal way would be to figure out
163  * the NIC <-> CPU binding at listen time, and assign the outgoing
164  * connection to the squeue attached to the CPU that will be interrupted
165  * for incoming packets (we know the NIC based on the bind IP address).
166  * This might seem like a problem if more data is going out but the
167  * fact is that in most cases the transmit is ACK driven transmit where
168  * the outgoing data normally sits on TCP's xmit queue waiting to be
169  * transmitted.
170  *
171  * Accepting a connection:
172  *
173  * This is a more interesting case because of various races involved in
174  * establishing a eager in its own perimeter. Read the meta comment on
175  * top of tcp_conn_request(). But briefly, the squeue is picked by
176  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
177  *
178  * Closing a connection:
179  *
180  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
181  * via squeue to do the close and mark the tcp as detached if the connection
182  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
183  * reference but tcp_close() drop IP's reference always. So if tcp was
184  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
185  * and 1 because it is in classifier's connected hash. This is the condition
186  * we use to determine that its OK to clean up the tcp outside of squeue
187  * when time wait expires (check the ref under fanout and conn_lock and
188  * if it is 2, remove it from fanout hash and kill it).
189  *
190  * Although close just drops the necessary references and marks the
191  * tcp_detached state, tcp_close needs to know the tcp_detached has been
192  * set (under squeue) before letting the STREAM go away (because a
193  * inbound packet might attempt to go up the STREAM while the close
194  * has happened and tcp_detached is not set). So a special lock and
195  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
196  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
197  * tcp_detached.
198  *
199  * Special provisions and fast paths:
200  *
201  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
202  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
203  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
204  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
205  * check to send packets directly to tcp_rput_data via squeue. Everyone
206  * else comes through tcp_input() on the read side.
207  *
208  * We also make special provisions for sockfs by marking tcp_issocket
209  * whenever we have only sockfs on top of TCP. This allows us to skip
210  * putting the tcp in acceptor hash since a sockfs listener can never
211  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
212  * since eager has already been allocated and the accept now happens
213  * on acceptor STREAM. There is a big blob of comment on top of
214  * tcp_conn_request explaining the new accept. When socket is POP'd,
215  * sockfs sends us an ioctl to mark the fact and we go back to old
216  * behaviour. Once tcp_issocket is unset, its never set for the
217  * life of that connection.
218  *
219  * IPsec notes :
220  *
221  * Since a packet is always executed on the correct TCP perimeter
222  * all IPsec processing is defered to IP including checking new
223  * connections and setting IPSEC policies for new connection. The
224  * only exception is tcp_xmit_listeners_reset() which is called
225  * directly from IP and needs to policy check to see if TH_RST
226  * can be sent out.
227  *
228  * PFHooks notes :
229  *
230  * For mdt case, one meta buffer contains multiple packets. Mblks for every
231  * packet are assembled and passed to the hooks. When packets are blocked,
232  * or boundary of any packet is changed, the mdt processing is stopped, and
233  * packets of the meta buffer are send to the IP path one by one.
234  */
235 
236 /*
237  * Values for squeue switch:
238  * 1: SQ_NODRAIN
239  * 2: SQ_PROCESS
240  * 3: SQ_FILL
241  */
242 int tcp_squeue_wput = 2;	/* /etc/systems */
243 int tcp_squeue_flag;
244 
245 /*
246  * This controls how tiny a write must be before we try to copy it
247  * into the the mblk on the tail of the transmit queue.  Not much
248  * speedup is observed for values larger than sixteen.  Zero will
249  * disable the optimisation.
250  */
251 int tcp_tx_pull_len = 16;
252 
253 /*
254  * TCP Statistics.
255  *
256  * How TCP statistics work.
257  *
258  * There are two types of statistics invoked by two macros.
259  *
260  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
261  * supposed to be used in non MT-hot paths of the code.
262  *
263  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
264  * supposed to be used for DEBUG purposes and may be used on a hot path.
265  *
266  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
267  * (use "kstat tcp" to get them).
268  *
269  * There is also additional debugging facility that marks tcp_clean_death()
270  * instances and saves them in tcp_t structure. It is triggered by
271  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
272  * tcp_clean_death() calls that counts the number of times each tag was hit. It
273  * is triggered by TCP_CLD_COUNTERS define.
274  *
275  * How to add new counters.
276  *
277  * 1) Add a field in the tcp_stat structure describing your counter.
278  * 2) Add a line in the template in tcp_kstat2_init() with the name
279  *    of the counter.
280  *
281  *    IMPORTANT!! - make sure that both are in sync !!
282  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
283  *
284  * Please avoid using private counters which are not kstat-exported.
285  *
286  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
287  * in tcp_t structure.
288  *
289  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
290  */
291 
292 #ifndef TCP_DEBUG_COUNTER
293 #ifdef DEBUG
294 #define	TCP_DEBUG_COUNTER 1
295 #else
296 #define	TCP_DEBUG_COUNTER 0
297 #endif
298 #endif
299 
300 #define	TCP_CLD_COUNTERS 0
301 
302 #define	TCP_TAG_CLEAN_DEATH 1
303 #define	TCP_MAX_CLEAN_DEATH_TAG 32
304 
305 #ifdef lint
306 static int _lint_dummy_;
307 #endif
308 
309 #if TCP_CLD_COUNTERS
310 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
311 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
312 #elif defined(lint)
313 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
314 #else
315 #define	TCP_CLD_STAT(x)
316 #endif
317 
318 #if TCP_DEBUG_COUNTER
319 #define	TCP_DBGSTAT(tcps, x)	\
320 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
321 #define	TCP_G_DBGSTAT(x)	\
322 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
323 #elif defined(lint)
324 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
325 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
326 #else
327 #define	TCP_DBGSTAT(tcps, x)
328 #define	TCP_G_DBGSTAT(x)
329 #endif
330 
331 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
332 
333 tcp_g_stat_t	tcp_g_statistics;
334 kstat_t		*tcp_g_kstat;
335 
336 /*
337  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
338  * tcp write side.
339  */
340 #define	CALL_IP_WPUT(connp, q, mp) {					\
341 	ASSERT(((q)->q_flag & QREADR) == 0);				\
342 	TCP_DBGSTAT(connp->conn_netstack->netstack_tcp, tcp_ip_output);	\
343 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
344 }
345 
346 /* Macros for timestamp comparisons */
347 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
348 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
349 
350 /*
351  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
352  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
353  * by adding three components: a time component which grows by 1 every 4096
354  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
355  * a per-connection component which grows by 125000 for every new connection;
356  * and an "extra" component that grows by a random amount centered
357  * approximately on 64000.  This causes the the ISS generator to cycle every
358  * 4.89 hours if no TCP connections are made, and faster if connections are
359  * made.
360  *
361  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
362  * components: a time component which grows by 250000 every second; and
363  * a per-connection component which grows by 125000 for every new connections.
364  *
365  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
366  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
367  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
368  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
369  * password.
370  */
371 #define	ISS_INCR	250000
372 #define	ISS_NSEC_SHT	12
373 
374 static sin_t	sin_null;	/* Zero address for quick clears */
375 static sin6_t	sin6_null;	/* Zero address for quick clears */
376 
377 /*
378  * This implementation follows the 4.3BSD interpretation of the urgent
379  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
380  * incompatible changes in protocols like telnet and rlogin.
381  */
382 #define	TCP_OLD_URP_INTERPRETATION	1
383 
384 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
385 	(TCP_IS_DETACHED(tcp) && \
386 	    (!(tcp)->tcp_hard_binding))
387 
388 /*
389  * TCP reassembly macros.  We hide starting and ending sequence numbers in
390  * b_next and b_prev of messages on the reassembly queue.  The messages are
391  * chained using b_cont.  These macros are used in tcp_reass() so we don't
392  * have to see the ugly casts and assignments.
393  */
394 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
395 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
396 					(mblk_t *)(uintptr_t)(u))
397 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
398 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
399 					(mblk_t *)(uintptr_t)(u))
400 
401 /*
402  * Implementation of TCP Timers.
403  * =============================
404  *
405  * INTERFACE:
406  *
407  * There are two basic functions dealing with tcp timers:
408  *
409  *	timeout_id_t	tcp_timeout(connp, func, time)
410  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
411  *	TCP_TIMER_RESTART(tcp, intvl)
412  *
413  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
414  * after 'time' ticks passed. The function called by timeout() must adhere to
415  * the same restrictions as a driver soft interrupt handler - it must not sleep
416  * or call other functions that might sleep. The value returned is the opaque
417  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
418  * cancel the request. The call to tcp_timeout() may fail in which case it
419  * returns zero. This is different from the timeout(9F) function which never
420  * fails.
421  *
422  * The call-back function 'func' always receives 'connp' as its single
423  * argument. It is always executed in the squeue corresponding to the tcp
424  * structure. The tcp structure is guaranteed to be present at the time the
425  * call-back is called.
426  *
427  * NOTE: The call-back function 'func' is never called if tcp is in
428  * 	the TCPS_CLOSED state.
429  *
430  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
431  * request. locks acquired by the call-back routine should not be held across
432  * the call to tcp_timeout_cancel() or a deadlock may result.
433  *
434  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
435  * Otherwise, it returns an integer value greater than or equal to 0. In
436  * particular, if the call-back function is already placed on the squeue, it can
437  * not be canceled.
438  *
439  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
440  * 	within squeue context corresponding to the tcp instance. Since the
441  *	call-back is also called via the same squeue, there are no race
442  *	conditions described in untimeout(9F) manual page since all calls are
443  *	strictly serialized.
444  *
445  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
446  *	stored in tcp_timer_tid and starts a new one using
447  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
448  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
449  *	field.
450  *
451  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
452  *	call-back may still be called, so it is possible tcp_timer() will be
453  *	called several times. This should not be a problem since tcp_timer()
454  *	should always check the tcp instance state.
455  *
456  *
457  * IMPLEMENTATION:
458  *
459  * TCP timers are implemented using three-stage process. The call to
460  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
461  * when the timer expires. The tcp_timer_callback() arranges the call of the
462  * tcp_timer_handler() function via squeue corresponding to the tcp
463  * instance. The tcp_timer_handler() calls actual requested timeout call-back
464  * and passes tcp instance as an argument to it. Information is passed between
465  * stages using the tcp_timer_t structure which contains the connp pointer, the
466  * tcp call-back to call and the timeout id returned by the timeout(9F).
467  *
468  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
469  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
470  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
471  * returns the pointer to this mblk.
472  *
473  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
474  * looks like a normal mblk without actual dblk attached to it.
475  *
476  * To optimize performance each tcp instance holds a small cache of timer
477  * mblocks. In the current implementation it caches up to two timer mblocks per
478  * tcp instance. The cache is preserved over tcp frees and is only freed when
479  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
480  * timer processing happens on a corresponding squeue, the cache manipulation
481  * does not require any locks. Experiments show that majority of timer mblocks
482  * allocations are satisfied from the tcp cache and do not involve kmem calls.
483  *
484  * The tcp_timeout() places a refhold on the connp instance which guarantees
485  * that it will be present at the time the call-back function fires. The
486  * tcp_timer_handler() drops the reference after calling the call-back, so the
487  * call-back function does not need to manipulate the references explicitly.
488  */
489 
490 typedef struct tcp_timer_s {
491 	conn_t	*connp;
492 	void 	(*tcpt_proc)(void *);
493 	callout_id_t   tcpt_tid;
494 } tcp_timer_t;
495 
496 static kmem_cache_t *tcp_timercache;
497 kmem_cache_t	*tcp_sack_info_cache;
498 kmem_cache_t	*tcp_iphc_cache;
499 
500 /*
501  * For scalability, we must not run a timer for every TCP connection
502  * in TIME_WAIT state.  To see why, consider (for time wait interval of
503  * 4 minutes):
504  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
505  *
506  * This list is ordered by time, so you need only delete from the head
507  * until you get to entries which aren't old enough to delete yet.
508  * The list consists of only the detached TIME_WAIT connections.
509  *
510  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
511  * becomes detached TIME_WAIT (either by changing the state and already
512  * being detached or the other way around). This means that the TIME_WAIT
513  * state can be extended (up to doubled) if the connection doesn't become
514  * detached for a long time.
515  *
516  * The list manipulations (including tcp_time_wait_next/prev)
517  * are protected by the tcp_time_wait_lock. The content of the
518  * detached TIME_WAIT connections is protected by the normal perimeters.
519  *
520  * This list is per squeue and squeues are shared across the tcp_stack_t's.
521  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
522  * and conn_netstack.
523  * The tcp_t's that are added to tcp_free_list are disassociated and
524  * have NULL tcp_tcps and conn_netstack pointers.
525  */
526 typedef struct tcp_squeue_priv_s {
527 	kmutex_t	tcp_time_wait_lock;
528 	callout_id_t	tcp_time_wait_tid;
529 	tcp_t		*tcp_time_wait_head;
530 	tcp_t		*tcp_time_wait_tail;
531 	tcp_t		*tcp_free_list;
532 	uint_t		tcp_free_list_cnt;
533 } tcp_squeue_priv_t;
534 
535 /*
536  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
537  * Running it every 5 seconds seems to give the best results.
538  */
539 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
540 
541 /*
542  * To prevent memory hog, limit the number of entries in tcp_free_list
543  * to 1% of available memory / number of cpus
544  */
545 uint_t tcp_free_list_max_cnt = 0;
546 
547 #define	TCP_XMIT_LOWATER	4096
548 #define	TCP_XMIT_HIWATER	49152
549 #define	TCP_RECV_LOWATER	2048
550 #define	TCP_RECV_HIWATER	49152
551 
552 /*
553  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
554  */
555 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
556 
557 #define	TIDUSZ	4096	/* transport interface data unit size */
558 
559 /*
560  * Bind hash list size and has function.  It has to be a power of 2 for
561  * hashing.
562  */
563 #define	TCP_BIND_FANOUT_SIZE	512
564 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
565 /*
566  * Size of listen and acceptor hash list.  It has to be a power of 2 for
567  * hashing.
568  */
569 #define	TCP_FANOUT_SIZE		256
570 
571 #ifdef	_ILP32
572 #define	TCP_ACCEPTOR_HASH(accid)					\
573 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
574 #else
575 #define	TCP_ACCEPTOR_HASH(accid)					\
576 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
577 #endif	/* _ILP32 */
578 
579 #define	IP_ADDR_CACHE_SIZE	2048
580 #define	IP_ADDR_CACHE_HASH(faddr)					\
581 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
582 
583 /*
584  * TCP options struct returned from tcp_parse_options.
585  */
586 typedef struct tcp_opt_s {
587 	uint32_t	tcp_opt_mss;
588 	uint32_t	tcp_opt_wscale;
589 	uint32_t	tcp_opt_ts_val;
590 	uint32_t	tcp_opt_ts_ecr;
591 	tcp_t		*tcp;
592 } tcp_opt_t;
593 
594 /*
595  * TCP option struct passing information b/w lisenter and eager.
596  */
597 struct tcp_options {
598 	uint_t			to_flags;
599 	ssize_t			to_boundif;	/* IPV6_BOUND_IF */
600 };
601 
602 #define	TCPOPT_BOUNDIF		0x00000001	/* set IPV6_BOUND_IF */
603 #define	TCPOPT_RECVPKTINFO	0x00000002	/* set IPV6_RECVPKTINFO */
604 
605 /*
606  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
607  */
608 
609 #ifdef _BIG_ENDIAN
610 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
611 	(TCPOPT_TSTAMP << 8) | 10)
612 #else
613 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
614 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
615 #endif
616 
617 /*
618  * Flags returned from tcp_parse_options.
619  */
620 #define	TCP_OPT_MSS_PRESENT	1
621 #define	TCP_OPT_WSCALE_PRESENT	2
622 #define	TCP_OPT_TSTAMP_PRESENT	4
623 #define	TCP_OPT_SACK_OK_PRESENT	8
624 #define	TCP_OPT_SACK_PRESENT	16
625 
626 /* TCP option length */
627 #define	TCPOPT_NOP_LEN		1
628 #define	TCPOPT_MAXSEG_LEN	4
629 #define	TCPOPT_WS_LEN		3
630 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
631 #define	TCPOPT_TSTAMP_LEN	10
632 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
633 #define	TCPOPT_SACK_OK_LEN	2
634 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
635 #define	TCPOPT_REAL_SACK_LEN	4
636 #define	TCPOPT_MAX_SACK_LEN	36
637 #define	TCPOPT_HEADER_LEN	2
638 
639 /* TCP cwnd burst factor. */
640 #define	TCP_CWND_INFINITE	65535
641 #define	TCP_CWND_SS		3
642 #define	TCP_CWND_NORMAL		5
643 
644 /* Maximum TCP initial cwin (start/restart). */
645 #define	TCP_MAX_INIT_CWND	8
646 
647 /*
648  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
649  * either tcp_slow_start_initial or tcp_slow_start_after idle
650  * depending on the caller.  If the upper layer has not used the
651  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
652  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
653  * If the upper layer has changed set the tcp_init_cwnd, just use
654  * it to calculate the tcp_cwnd.
655  */
656 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
657 {									\
658 	if ((tcp)->tcp_init_cwnd == 0) {				\
659 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
660 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
661 	} else {							\
662 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
663 	}								\
664 	tcp->tcp_cwnd_cnt = 0;						\
665 }
666 
667 /* TCP Timer control structure */
668 typedef struct tcpt_s {
669 	pfv_t	tcpt_pfv;	/* The routine we are to call */
670 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
671 } tcpt_t;
672 
673 /*
674  * Functions called directly via squeue having a prototype of edesc_t.
675  */
676 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
677 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
678 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
679 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
680 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
681 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
682 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
683 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
684 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
685 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2);
686 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
687 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
688 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
689 
690 
691 /* Prototype for TCP functions */
692 static void	tcp_random_init(void);
693 int		tcp_random(void);
694 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
695 static int	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
696 		    tcp_t *eager);
697 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
698 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
699     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
700     boolean_t user_specified);
701 static void	tcp_closei_local(tcp_t *tcp);
702 static void	tcp_close_detached(tcp_t *tcp);
703 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
704 			mblk_t *idmp, mblk_t **defermp);
705 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
706 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
707 		    in_port_t dstport, uint_t srcid, cred_t *cr, pid_t pid);
708 static int 	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
709 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
710 		    uint32_t scope_id, cred_t *cr, pid_t pid);
711 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
712 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
713 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
714 static char	*tcp_display(tcp_t *tcp, char *, char);
715 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
716 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
717 static void	tcp_eager_unlink(tcp_t *tcp);
718 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
719 		    int unixerr);
720 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
721 		    int tlierr, int unixerr);
722 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
723 		    cred_t *cr);
724 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
725 		    char *value, caddr_t cp, cred_t *cr);
726 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
727 		    char *value, caddr_t cp, cred_t *cr);
728 static int	tcp_tpistate(tcp_t *tcp);
729 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
730     int caller_holds_lock);
731 static void	tcp_bind_hash_remove(tcp_t *tcp);
732 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
733 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
734 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
735 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
736 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
737 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
738 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
739 void		tcp_g_q_setup(tcp_stack_t *);
740 void		tcp_g_q_create(tcp_stack_t *);
741 void		tcp_g_q_destroy(tcp_stack_t *);
742 static int	tcp_header_init_ipv4(tcp_t *tcp);
743 static int	tcp_header_init_ipv6(tcp_t *tcp);
744 int		tcp_init(tcp_t *tcp, queue_t *q);
745 static int	tcp_init_values(tcp_t *tcp);
746 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
747 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
748 static void	tcp_ip_notify(tcp_t *tcp);
749 static mblk_t	*tcp_ire_mp(mblk_t **mpp);
750 static void	tcp_iss_init(tcp_t *tcp);
751 static void	tcp_keepalive_killer(void *arg);
752 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
753 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
754 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
755 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
756 static boolean_t tcp_allow_connopt_set(int level, int name);
757 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
758 int		tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
759 int		tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level,
760 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
761 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
762 		    mblk_t *mblk);
763 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
764 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
765 		    uchar_t *ptr, uint_t len);
766 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
767 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
768     tcp_stack_t *);
769 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
770 		    caddr_t cp, cred_t *cr);
771 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
772 		    caddr_t cp, cred_t *cr);
773 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
774 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
775 		    caddr_t cp, cred_t *cr);
776 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
777 static void	tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt);
778 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
779 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
780 static void	tcp_reinit(tcp_t *tcp);
781 static void	tcp_reinit_values(tcp_t *tcp);
782 
783 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
784 static uint_t	tcp_rcv_drain(tcp_t *tcp);
785 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
786 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
787 static void	tcp_ss_rexmit(tcp_t *tcp);
788 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
789 static void	tcp_process_options(tcp_t *, tcph_t *);
790 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
791 static void	tcp_rsrv(queue_t *q);
792 static int	tcp_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 /* For AF_INET aka /dev/tcp */
980 struct streamtab tcpinfov4 = {
981 	&tcp_rinitv4, &tcp_winit
982 };
983 
984 /* For AF_INET6 aka /dev/tcp6 */
985 struct streamtab tcpinfov6 = {
986 	&tcp_rinitv6, &tcp_winit
987 };
988 
989 sock_downcalls_t sock_tcp_downcalls;
990 
991 /*
992  * Have to ensure that tcp_g_q_close is not done by an
993  * interrupt thread.
994  */
995 static taskq_t *tcp_taskq;
996 
997 /* Setable only in /etc/system. Move to ndd? */
998 boolean_t tcp_icmp_source_quench = B_FALSE;
999 
1000 /*
1001  * Following assumes TPI alignment requirements stay along 32 bit
1002  * boundaries
1003  */
1004 #define	ROUNDUP32(x) \
1005 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1006 
1007 /* Template for response to info request. */
1008 static struct T_info_ack tcp_g_t_info_ack = {
1009 	T_INFO_ACK,		/* PRIM_type */
1010 	0,			/* TSDU_size */
1011 	T_INFINITE,		/* ETSDU_size */
1012 	T_INVALID,		/* CDATA_size */
1013 	T_INVALID,		/* DDATA_size */
1014 	sizeof (sin_t),		/* ADDR_size */
1015 	0,			/* OPT_size - not initialized here */
1016 	TIDUSZ,			/* TIDU_size */
1017 	T_COTS_ORD,		/* SERV_type */
1018 	TCPS_IDLE,		/* CURRENT_state */
1019 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1020 };
1021 
1022 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1023 	T_INFO_ACK,		/* PRIM_type */
1024 	0,			/* TSDU_size */
1025 	T_INFINITE,		/* ETSDU_size */
1026 	T_INVALID,		/* CDATA_size */
1027 	T_INVALID,		/* DDATA_size */
1028 	sizeof (sin6_t),	/* ADDR_size */
1029 	0,			/* OPT_size - not initialized here */
1030 	TIDUSZ,		/* TIDU_size */
1031 	T_COTS_ORD,		/* SERV_type */
1032 	TCPS_IDLE,		/* CURRENT_state */
1033 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1034 };
1035 
1036 #define	MS	1L
1037 #define	SECONDS	(1000 * MS)
1038 #define	MINUTES	(60 * SECONDS)
1039 #define	HOURS	(60 * MINUTES)
1040 #define	DAYS	(24 * HOURS)
1041 
1042 #define	PARAM_MAX (~(uint32_t)0)
1043 
1044 /* Max size IP datagram is 64k - 1 */
1045 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1046 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1047 /* Max of the above */
1048 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1049 
1050 /* Largest TCP port number */
1051 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1052 
1053 /*
1054  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1055  * layer header.  It has to be a multiple of 4.
1056  */
1057 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1058 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1059 
1060 /*
1061  * All of these are alterable, within the min/max values given, at run time.
1062  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1063  * per the TCP spec.
1064  */
1065 /* BEGIN CSTYLED */
1066 static tcpparam_t	lcl_tcp_param_arr[] = {
1067  /*min		max		value		name */
1068  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1069  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1070  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1071  { 1,		1024,		1,		"tcp_conn_req_min" },
1072  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1073  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1074  { 0,		10,		0,		"tcp_debug" },
1075  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1076  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1077  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1078  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1079  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1080  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1081  { 1,		255,		64,		"tcp_ipv4_ttl"},
1082  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1083  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1084  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1085  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1086  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1087  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1088  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1089  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1090  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1091  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1092  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1093  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1094  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1095  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1096  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1097  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1098  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1099  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1100  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1101  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1102  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1103  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1104  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1105 /*
1106  * Question:  What default value should I set for tcp_strong_iss?
1107  */
1108  { 0,		2,		1,		"tcp_strong_iss"},
1109  { 0,		65536,		20,		"tcp_rtt_updates"},
1110  { 0,		1,		1,		"tcp_wscale_always"},
1111  { 0,		1,		0,		"tcp_tstamp_always"},
1112  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1113  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1114  { 0,		16,		2,		"tcp_deferred_acks_max"},
1115  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1116  { 1,		4,		4,		"tcp_slow_start_initial"},
1117  { 0,		2,		2,		"tcp_sack_permitted"},
1118  { 0,		1,		1,		"tcp_compression_enabled"},
1119  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1120  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1121  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1122  { 0,		1,		0,		"tcp_rev_src_routes"},
1123  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1124  { 0,		16,		8,		"tcp_local_dacks_max"},
1125  { 0,		2,		1,		"tcp_ecn_permitted"},
1126  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1127  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1128  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1129  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1130  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1131 };
1132 /* END CSTYLED */
1133 
1134 /*
1135  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1136  * each header fragment in the header buffer.  Each parameter value has
1137  * to be a multiple of 4 (32-bit aligned).
1138  */
1139 static tcpparam_t lcl_tcp_mdt_head_param =
1140 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1141 static tcpparam_t lcl_tcp_mdt_tail_param =
1142 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1143 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1144 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1145 
1146 /*
1147  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1148  * the maximum number of payload buffers associated per Multidata.
1149  */
1150 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1151 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1152 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1153 
1154 /* Round up the value to the nearest mss. */
1155 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1156 
1157 /*
1158  * Set ECN capable transport (ECT) code point in IP header.
1159  *
1160  * Note that there are 2 ECT code points '01' and '10', which are called
1161  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1162  * point ECT(0) for TCP as described in RFC 2481.
1163  */
1164 #define	SET_ECT(tcp, iph) \
1165 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1166 		/* We need to clear the code point first. */ \
1167 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1168 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1169 	} else { \
1170 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1171 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1172 	}
1173 
1174 /*
1175  * The format argument to pass to tcp_display().
1176  * DISP_PORT_ONLY means that the returned string has only port info.
1177  * DISP_ADDR_AND_PORT means that the returned string also contains the
1178  * remote and local IP address.
1179  */
1180 #define	DISP_PORT_ONLY		1
1181 #define	DISP_ADDR_AND_PORT	2
1182 
1183 #define	IS_VMLOANED_MBLK(mp) \
1184 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1185 
1186 
1187 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1188 boolean_t tcp_mdt_chain = B_TRUE;
1189 
1190 /*
1191  * MDT threshold in the form of effective send MSS multiplier; we take
1192  * the MDT path if the amount of unsent data exceeds the threshold value
1193  * (default threshold is 1*SMSS).
1194  */
1195 uint_t tcp_mdt_smss_threshold = 1;
1196 
1197 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1198 
1199 /*
1200  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1201  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1202  * determined dynamically during tcp_adapt_ire(), which is the default.
1203  */
1204 boolean_t tcp_static_maxpsz = B_FALSE;
1205 
1206 /* Setable in /etc/system */
1207 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1208 uint32_t tcp_random_anon_port = 1;
1209 
1210 /*
1211  * To reach to an eager in Q0 which can be dropped due to an incoming
1212  * new SYN request when Q0 is full, a new doubly linked list is
1213  * introduced. This list allows to select an eager from Q0 in O(1) time.
1214  * This is needed to avoid spending too much time walking through the
1215  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1216  * this new list has to be a member of Q0.
1217  * This list is headed by listener's tcp_t. When the list is empty,
1218  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1219  * of listener's tcp_t point to listener's tcp_t itself.
1220  *
1221  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1222  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1223  * These macros do not affect the eager's membership to Q0.
1224  */
1225 
1226 
1227 #define	MAKE_DROPPABLE(listener, eager)					\
1228 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1229 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1230 		    = (eager);						\
1231 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1232 		(eager)->tcp_eager_next_drop_q0 =			\
1233 		    (listener)->tcp_eager_next_drop_q0;			\
1234 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1235 	}
1236 
1237 #define	MAKE_UNDROPPABLE(eager)						\
1238 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1239 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1240 		    = (eager)->tcp_eager_prev_drop_q0;			\
1241 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1242 		    = (eager)->tcp_eager_next_drop_q0;			\
1243 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1244 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1245 	}
1246 
1247 /*
1248  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1249  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1250  * data, TCP will not respond with an ACK.  RFC 793 requires that
1251  * TCP responds with an ACK for such a bogus ACK.  By not following
1252  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1253  * an attacker successfully spoofs an acceptable segment to our
1254  * peer; or when our peer is "confused."
1255  */
1256 uint32_t tcp_drop_ack_unsent_cnt = 10;
1257 
1258 /*
1259  * Hook functions to enable cluster networking
1260  * On non-clustered systems these vectors must always be NULL.
1261  */
1262 
1263 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1264 			    sa_family_t addr_family, uint8_t *laddrp,
1265 			    in_port_t lport, void *args) = NULL;
1266 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1267 			    sa_family_t addr_family, uint8_t *laddrp,
1268 			    in_port_t lport, void *args) = NULL;
1269 
1270 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1271 			    boolean_t is_outgoing,
1272 			    sa_family_t addr_family,
1273 			    uint8_t *laddrp, in_port_t lport,
1274 			    uint8_t *faddrp, in_port_t fport,
1275 			    void *args) = NULL;
1276 
1277 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1278 			    sa_family_t addr_family, uint8_t *laddrp,
1279 			    in_port_t lport, uint8_t *faddrp,
1280 			    in_port_t fport, void *args) = NULL;
1281 
1282 /*
1283  * The following are defined in ip.c
1284  */
1285 extern int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
1286 			    sa_family_t addr_family, uint8_t *laddrp,
1287 			    void *args);
1288 extern uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
1289 			    sa_family_t addr_family, uint8_t *laddrp,
1290 			    uint8_t *faddrp, void *args);
1291 
1292 
1293 /*
1294  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1295  */
1296 #define	CL_INET_CONNECT(connp, tcp, is_outgoing, err) {		\
1297 	(err) = 0;						\
1298 	if (cl_inet_connect2 != NULL) {				\
1299 		/*						\
1300 		 * Running in cluster mode - register active connection	\
1301 		 * information						\
1302 		 */							\
1303 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1304 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1305 				(err) = (*cl_inet_connect2)(		\
1306 				    (connp)->conn_netstack->netstack_stackid,\
1307 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1308 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1309 				    (in_port_t)(tcp)->tcp_lport,	\
1310 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1311 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1312 			}						\
1313 		} else {						\
1314 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1315 			    &(tcp)->tcp_ip6h->ip6_src)) {		\
1316 				(err) = (*cl_inet_connect2)(		\
1317 				    (connp)->conn_netstack->netstack_stackid,\
1318 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1319 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1320 				    (in_port_t)(tcp)->tcp_lport,	\
1321 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1322 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1323 			}						\
1324 		}							\
1325 	}								\
1326 }
1327 
1328 #define	CL_INET_DISCONNECT(connp, tcp)	{				\
1329 	if (cl_inet_disconnect != NULL) {				\
1330 		/*							\
1331 		 * Running in cluster mode - deregister active		\
1332 		 * connection information				\
1333 		 */							\
1334 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1335 			if ((tcp)->tcp_ip_src != 0) {			\
1336 				(*cl_inet_disconnect)(			\
1337 				    (connp)->conn_netstack->netstack_stackid,\
1338 				    IPPROTO_TCP, AF_INET,		\
1339 				    (uint8_t *)(&((tcp)->tcp_ip_src)),	\
1340 				    (in_port_t)(tcp)->tcp_lport,	\
1341 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1342 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1343 			}						\
1344 		} else {						\
1345 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1346 			    &(tcp)->tcp_ip_src_v6)) {			\
1347 				(*cl_inet_disconnect)(			\
1348 				    (connp)->conn_netstack->netstack_stackid,\
1349 				    IPPROTO_TCP, AF_INET6,		\
1350 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1351 				    (in_port_t)(tcp)->tcp_lport,	\
1352 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1353 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1354 			}						\
1355 		}							\
1356 	}								\
1357 }
1358 
1359 /*
1360  * Cluster networking hook for traversing current connection list.
1361  * This routine is used to extract the current list of live connections
1362  * which must continue to to be dispatched to this node.
1363  */
1364 int cl_tcp_walk_list(netstackid_t stack_id,
1365     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1366 
1367 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1368     void *arg, tcp_stack_t *tcps);
1369 
1370 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1371 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1372 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1373 	    ip6_t *, ip6h, int, 0);
1374 
1375 static void
1376 tcp_set_recv_threshold(tcp_t *tcp, uint32_t new_rcvthresh)
1377 {
1378 	uint32_t default_threshold = SOCKET_RECVHIWATER >> 3;
1379 
1380 	if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
1381 		conn_t *connp = tcp->tcp_connp;
1382 		struct sock_proto_props sopp;
1383 
1384 		/*
1385 		 * only increase rcvthresh upto default_threshold
1386 		 */
1387 		if (new_rcvthresh > default_threshold)
1388 			new_rcvthresh = default_threshold;
1389 
1390 		sopp.sopp_flags = SOCKOPT_RCVTHRESH;
1391 		sopp.sopp_rcvthresh = new_rcvthresh;
1392 
1393 		(*connp->conn_upcalls->su_set_proto_props)
1394 		    (connp->conn_upper_handle, &sopp);
1395 	}
1396 }
1397 /*
1398  * Figure out the value of window scale opton.  Note that the rwnd is
1399  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1400  * We cannot find the scale value and then do a round up of tcp_rwnd
1401  * because the scale value may not be correct after that.
1402  *
1403  * Set the compiler flag to make this function inline.
1404  */
1405 static void
1406 tcp_set_ws_value(tcp_t *tcp)
1407 {
1408 	int i;
1409 	uint32_t rwnd = tcp->tcp_rwnd;
1410 
1411 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1412 	    i++, rwnd >>= 1)
1413 		;
1414 	tcp->tcp_rcv_ws = i;
1415 }
1416 
1417 /*
1418  * Remove a connection from the list of detached TIME_WAIT connections.
1419  * It returns B_FALSE if it can't remove the connection from the list
1420  * as the connection has already been removed from the list due to an
1421  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1422  */
1423 static boolean_t
1424 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1425 {
1426 	boolean_t	locked = B_FALSE;
1427 
1428 	if (tcp_time_wait == NULL) {
1429 		tcp_time_wait = *((tcp_squeue_priv_t **)
1430 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1431 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1432 		locked = B_TRUE;
1433 	} else {
1434 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1435 	}
1436 
1437 	if (tcp->tcp_time_wait_expire == 0) {
1438 		ASSERT(tcp->tcp_time_wait_next == NULL);
1439 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1440 		if (locked)
1441 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1442 		return (B_FALSE);
1443 	}
1444 	ASSERT(TCP_IS_DETACHED(tcp));
1445 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1446 
1447 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1448 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1449 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1450 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1451 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1452 			    NULL;
1453 		} else {
1454 			tcp_time_wait->tcp_time_wait_tail = NULL;
1455 		}
1456 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1457 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1458 		ASSERT(tcp->tcp_time_wait_next == NULL);
1459 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1460 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1461 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1462 	} else {
1463 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1464 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1465 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1466 		    tcp->tcp_time_wait_next;
1467 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1468 		    tcp->tcp_time_wait_prev;
1469 	}
1470 	tcp->tcp_time_wait_next = NULL;
1471 	tcp->tcp_time_wait_prev = NULL;
1472 	tcp->tcp_time_wait_expire = 0;
1473 
1474 	if (locked)
1475 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1476 	return (B_TRUE);
1477 }
1478 
1479 /*
1480  * Add a connection to the list of detached TIME_WAIT connections
1481  * and set its time to expire.
1482  */
1483 static void
1484 tcp_time_wait_append(tcp_t *tcp)
1485 {
1486 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1487 	tcp_squeue_priv_t *tcp_time_wait =
1488 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1489 	    SQPRIVATE_TCP));
1490 
1491 	tcp_timers_stop(tcp);
1492 
1493 	/* Freed above */
1494 	ASSERT(tcp->tcp_timer_tid == 0);
1495 	ASSERT(tcp->tcp_ack_tid == 0);
1496 
1497 	/* must have happened at the time of detaching the tcp */
1498 	ASSERT(tcp->tcp_ptpahn == NULL);
1499 	ASSERT(tcp->tcp_flow_stopped == 0);
1500 	ASSERT(tcp->tcp_time_wait_next == NULL);
1501 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1502 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1503 	ASSERT(tcp->tcp_listener == NULL);
1504 
1505 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1506 	/*
1507 	 * The value computed below in tcp->tcp_time_wait_expire may
1508 	 * appear negative or wrap around. That is ok since our
1509 	 * interest is only in the difference between the current lbolt
1510 	 * value and tcp->tcp_time_wait_expire. But the value should not
1511 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1512 	 * The corresponding comparison in tcp_time_wait_collector() uses
1513 	 * modular arithmetic.
1514 	 */
1515 	tcp->tcp_time_wait_expire +=
1516 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1517 	if (tcp->tcp_time_wait_expire == 0)
1518 		tcp->tcp_time_wait_expire = 1;
1519 
1520 	ASSERT(TCP_IS_DETACHED(tcp));
1521 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1522 	ASSERT(tcp->tcp_time_wait_next == NULL);
1523 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1524 	TCP_DBGSTAT(tcps, tcp_time_wait);
1525 
1526 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1527 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1528 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1529 		tcp_time_wait->tcp_time_wait_head = tcp;
1530 	} else {
1531 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1532 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1533 		    TCPS_TIME_WAIT);
1534 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1535 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1536 	}
1537 	tcp_time_wait->tcp_time_wait_tail = tcp;
1538 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1539 }
1540 
1541 /* ARGSUSED */
1542 void
1543 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1544 {
1545 	conn_t	*connp = (conn_t *)arg;
1546 	tcp_t	*tcp = connp->conn_tcp;
1547 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1548 
1549 	ASSERT(tcp != NULL);
1550 	if (tcp->tcp_state == TCPS_CLOSED) {
1551 		return;
1552 	}
1553 
1554 	ASSERT((tcp->tcp_family == AF_INET &&
1555 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1556 	    (tcp->tcp_family == AF_INET6 &&
1557 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1558 	    tcp->tcp_ipversion == IPV6_VERSION)));
1559 	ASSERT(!tcp->tcp_listener);
1560 
1561 	TCP_STAT(tcps, tcp_time_wait_reap);
1562 	ASSERT(TCP_IS_DETACHED(tcp));
1563 
1564 	/*
1565 	 * Because they have no upstream client to rebind or tcp_close()
1566 	 * them later, we axe the connection here and now.
1567 	 */
1568 	tcp_close_detached(tcp);
1569 }
1570 
1571 /*
1572  * Remove cached/latched IPsec references.
1573  */
1574 void
1575 tcp_ipsec_cleanup(tcp_t *tcp)
1576 {
1577 	conn_t		*connp = tcp->tcp_connp;
1578 
1579 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1580 
1581 	if (connp->conn_latch != NULL) {
1582 		IPLATCH_REFRELE(connp->conn_latch,
1583 		    connp->conn_netstack);
1584 		connp->conn_latch = NULL;
1585 	}
1586 	if (connp->conn_policy != NULL) {
1587 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1588 		connp->conn_policy = NULL;
1589 	}
1590 }
1591 
1592 /*
1593  * Cleaup before placing on free list.
1594  * Disassociate from the netstack/tcp_stack_t since the freelist
1595  * is per squeue and not per netstack.
1596  */
1597 void
1598 tcp_cleanup(tcp_t *tcp)
1599 {
1600 	mblk_t		*mp;
1601 	char		*tcp_iphc;
1602 	int		tcp_iphc_len;
1603 	int		tcp_hdr_grown;
1604 	tcp_sack_info_t	*tcp_sack_info;
1605 	conn_t		*connp = tcp->tcp_connp;
1606 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1607 	netstack_t	*ns = tcps->tcps_netstack;
1608 	mblk_t		*tcp_rsrv_mp;
1609 
1610 	tcp_bind_hash_remove(tcp);
1611 
1612 	/* Cleanup that which needs the netstack first */
1613 	tcp_ipsec_cleanup(tcp);
1614 
1615 	tcp_free(tcp);
1616 
1617 	/* Release any SSL context */
1618 	if (tcp->tcp_kssl_ent != NULL) {
1619 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1620 		tcp->tcp_kssl_ent = NULL;
1621 	}
1622 
1623 	if (tcp->tcp_kssl_ctx != NULL) {
1624 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1625 		tcp->tcp_kssl_ctx = NULL;
1626 	}
1627 	tcp->tcp_kssl_pending = B_FALSE;
1628 
1629 	conn_delete_ire(connp, NULL);
1630 
1631 	/*
1632 	 * Since we will bzero the entire structure, we need to
1633 	 * remove it and reinsert it in global hash list. We
1634 	 * know the walkers can't get to this conn because we
1635 	 * had set CONDEMNED flag earlier and checked reference
1636 	 * under conn_lock so walker won't pick it and when we
1637 	 * go the ipcl_globalhash_remove() below, no walker
1638 	 * can get to it.
1639 	 */
1640 	ipcl_globalhash_remove(connp);
1641 
1642 	/*
1643 	 * Now it is safe to decrement the reference counts.
1644 	 * This might be the last reference on the netstack and TCPS
1645 	 * in which case it will cause the tcp_g_q_close and
1646 	 * the freeing of the IP Instance.
1647 	 */
1648 	connp->conn_netstack = NULL;
1649 	netstack_rele(ns);
1650 	ASSERT(tcps != NULL);
1651 	tcp->tcp_tcps = NULL;
1652 	TCPS_REFRELE(tcps);
1653 
1654 	/* Save some state */
1655 	mp = tcp->tcp_timercache;
1656 
1657 	tcp_sack_info = tcp->tcp_sack_info;
1658 	tcp_iphc = tcp->tcp_iphc;
1659 	tcp_iphc_len = tcp->tcp_iphc_len;
1660 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1661 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1662 
1663 	if (connp->conn_cred != NULL) {
1664 		crfree(connp->conn_cred);
1665 		connp->conn_cred = NULL;
1666 	}
1667 	if (connp->conn_effective_cred != NULL) {
1668 		crfree(connp->conn_effective_cred);
1669 		connp->conn_effective_cred = NULL;
1670 	}
1671 	ipcl_conn_cleanup(connp);
1672 	connp->conn_flags = IPCL_TCPCONN;
1673 	bzero(tcp, sizeof (tcp_t));
1674 
1675 	/* restore the state */
1676 	tcp->tcp_timercache = mp;
1677 
1678 	tcp->tcp_sack_info = tcp_sack_info;
1679 	tcp->tcp_iphc = tcp_iphc;
1680 	tcp->tcp_iphc_len = tcp_iphc_len;
1681 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1682 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1683 
1684 	tcp->tcp_connp = connp;
1685 
1686 	ASSERT(connp->conn_tcp == tcp);
1687 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1688 	connp->conn_state_flags = CONN_INCIPIENT;
1689 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1690 	ASSERT(connp->conn_ref == 1);
1691 }
1692 
1693 /*
1694  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1695  * is done forwards from the head.
1696  * This walks all stack instances since
1697  * tcp_time_wait remains global across all stacks.
1698  */
1699 /* ARGSUSED */
1700 void
1701 tcp_time_wait_collector(void *arg)
1702 {
1703 	tcp_t *tcp;
1704 	clock_t now;
1705 	mblk_t *mp;
1706 	conn_t *connp;
1707 	kmutex_t *lock;
1708 	boolean_t removed;
1709 
1710 	squeue_t *sqp = (squeue_t *)arg;
1711 	tcp_squeue_priv_t *tcp_time_wait =
1712 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1713 
1714 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1715 	tcp_time_wait->tcp_time_wait_tid = 0;
1716 
1717 	if (tcp_time_wait->tcp_free_list != NULL &&
1718 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1719 		TCP_G_STAT(tcp_freelist_cleanup);
1720 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1721 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1722 			tcp->tcp_time_wait_next = NULL;
1723 			tcp_time_wait->tcp_free_list_cnt--;
1724 			ASSERT(tcp->tcp_tcps == NULL);
1725 			CONN_DEC_REF(tcp->tcp_connp);
1726 		}
1727 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1728 	}
1729 
1730 	/*
1731 	 * In order to reap time waits reliably, we should use a
1732 	 * source of time that is not adjustable by the user -- hence
1733 	 * the call to ddi_get_lbolt().
1734 	 */
1735 	now = ddi_get_lbolt();
1736 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1737 		/*
1738 		 * Compare times using modular arithmetic, since
1739 		 * lbolt can wrapover.
1740 		 */
1741 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1742 			break;
1743 		}
1744 
1745 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1746 		ASSERT(removed);
1747 
1748 		connp = tcp->tcp_connp;
1749 		ASSERT(connp->conn_fanout != NULL);
1750 		lock = &connp->conn_fanout->connf_lock;
1751 		/*
1752 		 * This is essentially a TW reclaim fast path optimization for
1753 		 * performance where the timewait collector checks under the
1754 		 * fanout lock (so that no one else can get access to the
1755 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1756 		 * the classifier hash list. If ref count is indeed 2, we can
1757 		 * just remove the conn under the fanout lock and avoid
1758 		 * cleaning up the conn under the squeue, provided that
1759 		 * clustering callbacks are not enabled. If clustering is
1760 		 * enabled, we need to make the clustering callback before
1761 		 * setting the CONDEMNED flag and after dropping all locks and
1762 		 * so we forego this optimization and fall back to the slow
1763 		 * path. Also please see the comments in tcp_closei_local
1764 		 * regarding the refcnt logic.
1765 		 *
1766 		 * Since we are holding the tcp_time_wait_lock, its better
1767 		 * not to block on the fanout_lock because other connections
1768 		 * can't add themselves to time_wait list. So we do a
1769 		 * tryenter instead of mutex_enter.
1770 		 */
1771 		if (mutex_tryenter(lock)) {
1772 			mutex_enter(&connp->conn_lock);
1773 			if ((connp->conn_ref == 2) &&
1774 			    (cl_inet_disconnect == NULL)) {
1775 				ipcl_hash_remove_locked(connp,
1776 				    connp->conn_fanout);
1777 				/*
1778 				 * Set the CONDEMNED flag now itself so that
1779 				 * the refcnt cannot increase due to any
1780 				 * walker. But we have still not cleaned up
1781 				 * conn_ire_cache. This is still ok since
1782 				 * we are going to clean it up in tcp_cleanup
1783 				 * immediately and any interface unplumb
1784 				 * thread will wait till the ire is blown away
1785 				 */
1786 				connp->conn_state_flags |= CONN_CONDEMNED;
1787 				mutex_exit(lock);
1788 				mutex_exit(&connp->conn_lock);
1789 				if (tcp_time_wait->tcp_free_list_cnt <
1790 				    tcp_free_list_max_cnt) {
1791 					/* Add to head of tcp_free_list */
1792 					mutex_exit(
1793 					    &tcp_time_wait->tcp_time_wait_lock);
1794 					tcp_cleanup(tcp);
1795 					ASSERT(connp->conn_latch == NULL);
1796 					ASSERT(connp->conn_policy == NULL);
1797 					ASSERT(tcp->tcp_tcps == NULL);
1798 					ASSERT(connp->conn_netstack == NULL);
1799 
1800 					mutex_enter(
1801 					    &tcp_time_wait->tcp_time_wait_lock);
1802 					tcp->tcp_time_wait_next =
1803 					    tcp_time_wait->tcp_free_list;
1804 					tcp_time_wait->tcp_free_list = tcp;
1805 					tcp_time_wait->tcp_free_list_cnt++;
1806 					continue;
1807 				} else {
1808 					/* Do not add to tcp_free_list */
1809 					mutex_exit(
1810 					    &tcp_time_wait->tcp_time_wait_lock);
1811 					tcp_bind_hash_remove(tcp);
1812 					conn_delete_ire(tcp->tcp_connp, NULL);
1813 					tcp_ipsec_cleanup(tcp);
1814 					CONN_DEC_REF(tcp->tcp_connp);
1815 				}
1816 			} else {
1817 				CONN_INC_REF_LOCKED(connp);
1818 				mutex_exit(lock);
1819 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1820 				mutex_exit(&connp->conn_lock);
1821 				/*
1822 				 * We can reuse the closemp here since conn has
1823 				 * detached (otherwise we wouldn't even be in
1824 				 * time_wait list). tcp_closemp_used can safely
1825 				 * be changed without taking a lock as no other
1826 				 * thread can concurrently access it at this
1827 				 * point in the connection lifecycle.
1828 				 */
1829 
1830 				if (tcp->tcp_closemp.b_prev == NULL)
1831 					tcp->tcp_closemp_used = B_TRUE;
1832 				else
1833 					cmn_err(CE_PANIC,
1834 					    "tcp_timewait_collector: "
1835 					    "concurrent use of tcp_closemp: "
1836 					    "connp %p tcp %p\n", (void *)connp,
1837 					    (void *)tcp);
1838 
1839 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1840 				mp = &tcp->tcp_closemp;
1841 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1842 				    tcp_timewait_output, connp,
1843 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1844 			}
1845 		} else {
1846 			mutex_enter(&connp->conn_lock);
1847 			CONN_INC_REF_LOCKED(connp);
1848 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1849 			mutex_exit(&connp->conn_lock);
1850 			/*
1851 			 * We can reuse the closemp here since conn has
1852 			 * detached (otherwise we wouldn't even be in
1853 			 * time_wait list). tcp_closemp_used can safely
1854 			 * be changed without taking a lock as no other
1855 			 * thread can concurrently access it at this
1856 			 * point in the connection lifecycle.
1857 			 */
1858 
1859 			if (tcp->tcp_closemp.b_prev == NULL)
1860 				tcp->tcp_closemp_used = B_TRUE;
1861 			else
1862 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1863 				    "concurrent use of tcp_closemp: "
1864 				    "connp %p tcp %p\n", (void *)connp,
1865 				    (void *)tcp);
1866 
1867 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1868 			mp = &tcp->tcp_closemp;
1869 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1870 			    tcp_timewait_output, connp,
1871 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1872 		}
1873 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1874 	}
1875 
1876 	if (tcp_time_wait->tcp_free_list != NULL)
1877 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1878 
1879 	tcp_time_wait->tcp_time_wait_tid =
1880 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1881 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1882 	    CALLOUT_FLAG_ROUNDUP);
1883 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1884 }
1885 
1886 /*
1887  * Reply to a clients T_CONN_RES TPI message. This function
1888  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1889  * on the acceptor STREAM and processed in tcp_wput_accept().
1890  * Read the block comment on top of tcp_conn_request().
1891  */
1892 static void
1893 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1894 {
1895 	tcp_t	*acceptor;
1896 	tcp_t	*eager;
1897 	tcp_t   *tcp;
1898 	struct T_conn_res	*tcr;
1899 	t_uscalar_t	acceptor_id;
1900 	t_scalar_t	seqnum;
1901 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1902 	struct tcp_options *tcpopt;
1903 	mblk_t	*ok_mp;
1904 	mblk_t	*mp1;
1905 	tcp_stack_t	*tcps = listener->tcp_tcps;
1906 	int	error;
1907 
1908 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1909 		tcp_err_ack(listener, mp, TPROTO, 0);
1910 		return;
1911 	}
1912 	tcr = (struct T_conn_res *)mp->b_rptr;
1913 
1914 	/*
1915 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1916 	 * read side queue of the streams device underneath us i.e. the
1917 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1918 	 * look it up in the queue_hash.  Under LP64 it sends down the
1919 	 * minor_t of the accepting endpoint.
1920 	 *
1921 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1922 	 * fanout hash lock is held.
1923 	 * This prevents any thread from entering the acceptor queue from
1924 	 * below (since it has not been hard bound yet i.e. any inbound
1925 	 * packets will arrive on the listener or default tcp queue and
1926 	 * go through tcp_lookup).
1927 	 * The CONN_INC_REF will prevent the acceptor from closing.
1928 	 *
1929 	 * XXX It is still possible for a tli application to send down data
1930 	 * on the accepting stream while another thread calls t_accept.
1931 	 * This should not be a problem for well-behaved applications since
1932 	 * the T_OK_ACK is sent after the queue swapping is completed.
1933 	 *
1934 	 * If the accepting fd is the same as the listening fd, avoid
1935 	 * queue hash lookup since that will return an eager listener in a
1936 	 * already established state.
1937 	 */
1938 	acceptor_id = tcr->ACCEPTOR_id;
1939 	mutex_enter(&listener->tcp_eager_lock);
1940 	if (listener->tcp_acceptor_id == acceptor_id) {
1941 		eager = listener->tcp_eager_next_q;
1942 		/* only count how many T_CONN_INDs so don't count q0 */
1943 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1944 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1945 			mutex_exit(&listener->tcp_eager_lock);
1946 			tcp_err_ack(listener, mp, TBADF, 0);
1947 			return;
1948 		}
1949 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1950 			/* Throw away all the eagers on q0. */
1951 			tcp_eager_cleanup(listener, 1);
1952 		}
1953 		if (listener->tcp_syn_defense) {
1954 			listener->tcp_syn_defense = B_FALSE;
1955 			if (listener->tcp_ip_addr_cache != NULL) {
1956 				kmem_free(listener->tcp_ip_addr_cache,
1957 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1958 				listener->tcp_ip_addr_cache = NULL;
1959 			}
1960 		}
1961 		/*
1962 		 * Transfer tcp_conn_req_max to the eager so that when
1963 		 * a disconnect occurs we can revert the endpoint to the
1964 		 * listen state.
1965 		 */
1966 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1967 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1968 		/*
1969 		 * Get a reference on the acceptor just like the
1970 		 * tcp_acceptor_hash_lookup below.
1971 		 */
1972 		acceptor = listener;
1973 		CONN_INC_REF(acceptor->tcp_connp);
1974 	} else {
1975 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1976 		if (acceptor == NULL) {
1977 			if (listener->tcp_debug) {
1978 				(void) strlog(TCP_MOD_ID, 0, 1,
1979 				    SL_ERROR|SL_TRACE,
1980 				    "tcp_accept: did not find acceptor 0x%x\n",
1981 				    acceptor_id);
1982 			}
1983 			mutex_exit(&listener->tcp_eager_lock);
1984 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1985 			return;
1986 		}
1987 		/*
1988 		 * Verify acceptor state. The acceptable states for an acceptor
1989 		 * include TCPS_IDLE and TCPS_BOUND.
1990 		 */
1991 		switch (acceptor->tcp_state) {
1992 		case TCPS_IDLE:
1993 			/* FALLTHRU */
1994 		case TCPS_BOUND:
1995 			break;
1996 		default:
1997 			CONN_DEC_REF(acceptor->tcp_connp);
1998 			mutex_exit(&listener->tcp_eager_lock);
1999 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2000 			return;
2001 		}
2002 	}
2003 
2004 	/* The listener must be in TCPS_LISTEN */
2005 	if (listener->tcp_state != TCPS_LISTEN) {
2006 		CONN_DEC_REF(acceptor->tcp_connp);
2007 		mutex_exit(&listener->tcp_eager_lock);
2008 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2009 		return;
2010 	}
2011 
2012 	/*
2013 	 * Rendezvous with an eager connection request packet hanging off
2014 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2015 	 * tcp structure when the connection packet arrived in
2016 	 * tcp_conn_request().
2017 	 */
2018 	seqnum = tcr->SEQ_number;
2019 	eager = listener;
2020 	do {
2021 		eager = eager->tcp_eager_next_q;
2022 		if (eager == NULL) {
2023 			CONN_DEC_REF(acceptor->tcp_connp);
2024 			mutex_exit(&listener->tcp_eager_lock);
2025 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2026 			return;
2027 		}
2028 	} while (eager->tcp_conn_req_seqnum != seqnum);
2029 	mutex_exit(&listener->tcp_eager_lock);
2030 
2031 	/*
2032 	 * At this point, both acceptor and listener have 2 ref
2033 	 * that they begin with. Acceptor has one additional ref
2034 	 * we placed in lookup while listener has 3 additional
2035 	 * ref for being behind the squeue (tcp_accept() is
2036 	 * done on listener's squeue); being in classifier hash;
2037 	 * and eager's ref on listener.
2038 	 */
2039 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2040 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2041 
2042 	/*
2043 	 * The eager at this point is set in its own squeue and
2044 	 * could easily have been killed (tcp_accept_finish will
2045 	 * deal with that) because of a TH_RST so we can only
2046 	 * ASSERT for a single ref.
2047 	 */
2048 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2049 
2050 	/* Pre allocate the stroptions mblk also */
2051 	opt_mp = allocb(MAX(sizeof (struct tcp_options),
2052 	    sizeof (struct T_conn_res)), BPRI_HI);
2053 	if (opt_mp == NULL) {
2054 		CONN_DEC_REF(acceptor->tcp_connp);
2055 		CONN_DEC_REF(eager->tcp_connp);
2056 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2057 		return;
2058 	}
2059 	DB_TYPE(opt_mp) = M_SETOPTS;
2060 	opt_mp->b_wptr += sizeof (struct tcp_options);
2061 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
2062 	tcpopt->to_flags = 0;
2063 
2064 	/*
2065 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2066 	 * from listener to acceptor.
2067 	 */
2068 	if (listener->tcp_bound_if != 0) {
2069 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
2070 		tcpopt->to_boundif = listener->tcp_bound_if;
2071 	}
2072 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2073 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
2074 	}
2075 
2076 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2077 	if ((mp1 = copymsg(mp)) == NULL) {
2078 		CONN_DEC_REF(acceptor->tcp_connp);
2079 		CONN_DEC_REF(eager->tcp_connp);
2080 		freemsg(opt_mp);
2081 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2082 		return;
2083 	}
2084 
2085 	tcr = (struct T_conn_res *)mp1->b_rptr;
2086 
2087 	/*
2088 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2089 	 * which allocates a larger mblk and appends the new
2090 	 * local address to the ok_ack.  The address is copied by
2091 	 * soaccept() for getsockname().
2092 	 */
2093 	{
2094 		int extra;
2095 
2096 		extra = (eager->tcp_family == AF_INET) ?
2097 		    sizeof (sin_t) : sizeof (sin6_t);
2098 
2099 		/*
2100 		 * Try to re-use mp, if possible.  Otherwise, allocate
2101 		 * an mblk and return it as ok_mp.  In any case, mp
2102 		 * is no longer usable upon return.
2103 		 */
2104 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2105 			CONN_DEC_REF(acceptor->tcp_connp);
2106 			CONN_DEC_REF(eager->tcp_connp);
2107 			freemsg(opt_mp);
2108 			/* Original mp has been freed by now, so use mp1 */
2109 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2110 			return;
2111 		}
2112 
2113 		mp = NULL;	/* We should never use mp after this point */
2114 
2115 		switch (extra) {
2116 		case sizeof (sin_t): {
2117 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2118 
2119 				ok_mp->b_wptr += extra;
2120 				sin->sin_family = AF_INET;
2121 				sin->sin_port = eager->tcp_lport;
2122 				sin->sin_addr.s_addr =
2123 				    eager->tcp_ipha->ipha_src;
2124 				break;
2125 			}
2126 		case sizeof (sin6_t): {
2127 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2128 
2129 				ok_mp->b_wptr += extra;
2130 				sin6->sin6_family = AF_INET6;
2131 				sin6->sin6_port = eager->tcp_lport;
2132 				if (eager->tcp_ipversion == IPV4_VERSION) {
2133 					sin6->sin6_flowinfo = 0;
2134 					IN6_IPADDR_TO_V4MAPPED(
2135 					    eager->tcp_ipha->ipha_src,
2136 					    &sin6->sin6_addr);
2137 				} else {
2138 					ASSERT(eager->tcp_ip6h != NULL);
2139 					sin6->sin6_flowinfo =
2140 					    eager->tcp_ip6h->ip6_vcf &
2141 					    ~IPV6_VERS_AND_FLOW_MASK;
2142 					sin6->sin6_addr =
2143 					    eager->tcp_ip6h->ip6_src;
2144 				}
2145 				sin6->sin6_scope_id = 0;
2146 				sin6->__sin6_src_id = 0;
2147 				break;
2148 			}
2149 		default:
2150 			break;
2151 		}
2152 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2153 	}
2154 
2155 	/*
2156 	 * If there are no options we know that the T_CONN_RES will
2157 	 * succeed. However, we can't send the T_OK_ACK upstream until
2158 	 * the tcp_accept_swap is done since it would be dangerous to
2159 	 * let the application start using the new fd prior to the swap.
2160 	 */
2161 	error = tcp_accept_swap(listener, acceptor, eager);
2162 	if (error != 0) {
2163 		CONN_DEC_REF(acceptor->tcp_connp);
2164 		CONN_DEC_REF(eager->tcp_connp);
2165 		freemsg(ok_mp);
2166 		/* Original mp has been freed by now, so use mp1 */
2167 		tcp_err_ack(listener, mp1, TSYSERR, error);
2168 		return;
2169 	}
2170 
2171 	/*
2172 	 * tcp_accept_swap unlinks eager from listener but does not drop
2173 	 * the eager's reference on the listener.
2174 	 */
2175 	ASSERT(eager->tcp_listener == NULL);
2176 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2177 
2178 	/*
2179 	 * The eager is now associated with its own queue. Insert in
2180 	 * the hash so that the connection can be reused for a future
2181 	 * T_CONN_RES.
2182 	 */
2183 	tcp_acceptor_hash_insert(acceptor_id, eager);
2184 
2185 	/*
2186 	 * We now do the processing of options with T_CONN_RES.
2187 	 * We delay till now since we wanted to have queue to pass to
2188 	 * option processing routines that points back to the right
2189 	 * instance structure which does not happen until after
2190 	 * tcp_accept_swap().
2191 	 *
2192 	 * Note:
2193 	 * The sanity of the logic here assumes that whatever options
2194 	 * are appropriate to inherit from listner=>eager are done
2195 	 * before this point, and whatever were to be overridden (or not)
2196 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2197 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2198 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2199 	 * This may not be true at this point in time but can be fixed
2200 	 * independently. This option processing code starts with
2201 	 * the instantiated acceptor instance and the final queue at
2202 	 * this point.
2203 	 */
2204 
2205 	if (tcr->OPT_length != 0) {
2206 		/* Options to process */
2207 		int t_error = 0;
2208 		int sys_error = 0;
2209 		int do_disconnect = 0;
2210 
2211 		if (tcp_conprim_opt_process(eager, mp1,
2212 		    &do_disconnect, &t_error, &sys_error) < 0) {
2213 			eager->tcp_accept_error = 1;
2214 			if (do_disconnect) {
2215 				/*
2216 				 * An option failed which does not allow
2217 				 * connection to be accepted.
2218 				 *
2219 				 * We allow T_CONN_RES to succeed and
2220 				 * put a T_DISCON_IND on the eager queue.
2221 				 */
2222 				ASSERT(t_error == 0 && sys_error == 0);
2223 				eager->tcp_send_discon_ind = 1;
2224 			} else {
2225 				ASSERT(t_error != 0);
2226 				freemsg(ok_mp);
2227 				/*
2228 				 * Original mp was either freed or set
2229 				 * to ok_mp above, so use mp1 instead.
2230 				 */
2231 				tcp_err_ack(listener, mp1, t_error, sys_error);
2232 				goto finish;
2233 			}
2234 		}
2235 		/*
2236 		 * Most likely success in setting options (except if
2237 		 * eager->tcp_send_discon_ind set).
2238 		 * mp1 option buffer represented by OPT_length/offset
2239 		 * potentially modified and contains results of setting
2240 		 * options at this point
2241 		 */
2242 	}
2243 
2244 	/* We no longer need mp1, since all options processing has passed */
2245 	freemsg(mp1);
2246 
2247 	putnext(listener->tcp_rq, ok_mp);
2248 
2249 	mutex_enter(&listener->tcp_eager_lock);
2250 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2251 		tcp_t	*tail;
2252 		mblk_t	*conn_ind;
2253 
2254 		/*
2255 		 * This path should not be executed if listener and
2256 		 * acceptor streams are the same.
2257 		 */
2258 		ASSERT(listener != acceptor);
2259 
2260 		tcp = listener->tcp_eager_prev_q0;
2261 		/*
2262 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2263 		 * deferred T_conn_ind queue. We need to get to the head of
2264 		 * the queue in order to send up T_conn_ind the same order as
2265 		 * how the 3WHS is completed.
2266 		 */
2267 		while (tcp != listener) {
2268 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2269 				break;
2270 			else
2271 				tcp = tcp->tcp_eager_prev_q0;
2272 		}
2273 		ASSERT(tcp != listener);
2274 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2275 		ASSERT(conn_ind != NULL);
2276 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2277 
2278 		/* Move from q0 to q */
2279 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2280 		listener->tcp_conn_req_cnt_q0--;
2281 		listener->tcp_conn_req_cnt_q++;
2282 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2283 		    tcp->tcp_eager_prev_q0;
2284 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2285 		    tcp->tcp_eager_next_q0;
2286 		tcp->tcp_eager_prev_q0 = NULL;
2287 		tcp->tcp_eager_next_q0 = NULL;
2288 		tcp->tcp_conn_def_q0 = B_FALSE;
2289 
2290 		/* Make sure the tcp isn't in the list of droppables */
2291 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2292 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2293 
2294 		/*
2295 		 * Insert at end of the queue because sockfs sends
2296 		 * down T_CONN_RES in chronological order. Leaving
2297 		 * the older conn indications at front of the queue
2298 		 * helps reducing search time.
2299 		 */
2300 		tail = listener->tcp_eager_last_q;
2301 		if (tail != NULL)
2302 			tail->tcp_eager_next_q = tcp;
2303 		else
2304 			listener->tcp_eager_next_q = tcp;
2305 		listener->tcp_eager_last_q = tcp;
2306 		tcp->tcp_eager_next_q = NULL;
2307 		mutex_exit(&listener->tcp_eager_lock);
2308 		putnext(tcp->tcp_rq, conn_ind);
2309 	} else {
2310 		mutex_exit(&listener->tcp_eager_lock);
2311 	}
2312 
2313 	/*
2314 	 * Done with the acceptor - free it
2315 	 *
2316 	 * Note: from this point on, no access to listener should be made
2317 	 * as listener can be equal to acceptor.
2318 	 */
2319 finish:
2320 	ASSERT(acceptor->tcp_detached);
2321 	ASSERT(tcps->tcps_g_q != NULL);
2322 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2323 	acceptor->tcp_rq = tcps->tcps_g_q;
2324 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2325 	(void) tcp_clean_death(acceptor, 0, 2);
2326 	CONN_DEC_REF(acceptor->tcp_connp);
2327 
2328 	/*
2329 	 * In case we already received a FIN we have to make tcp_rput send
2330 	 * the ordrel_ind. This will also send up a window update if the window
2331 	 * has opened up.
2332 	 *
2333 	 * In the normal case of a successful connection acceptance
2334 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2335 	 * indication that this was just accepted. This tells tcp_rput to
2336 	 * pass up any data queued in tcp_rcv_list.
2337 	 *
2338 	 * In the fringe case where options sent with T_CONN_RES failed and
2339 	 * we required, we would be indicating a T_DISCON_IND to blow
2340 	 * away this connection.
2341 	 */
2342 
2343 	/*
2344 	 * XXX: we currently have a problem if XTI application closes the
2345 	 * acceptor stream in between. This problem exists in on10-gate also
2346 	 * and is well know but nothing can be done short of major rewrite
2347 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2348 	 * eager same squeue as listener (we can distinguish non socket
2349 	 * listeners at the time of handling a SYN in tcp_conn_request)
2350 	 * and do most of the work that tcp_accept_finish does here itself
2351 	 * and then get behind the acceptor squeue to access the acceptor
2352 	 * queue.
2353 	 */
2354 	/*
2355 	 * We already have a ref on tcp so no need to do one before squeue_enter
2356 	 */
2357 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2358 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2359 }
2360 
2361 /*
2362  * Swap information between the eager and acceptor for a TLI/XTI client.
2363  * The sockfs accept is done on the acceptor stream and control goes
2364  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2365  * called. In either case, both the eager and listener are in their own
2366  * perimeter (squeue) and the code has to deal with potential race.
2367  *
2368  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2369  */
2370 static int
2371 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2372 {
2373 	conn_t	*econnp, *aconnp;
2374 	cred_t	*effective_cred = NULL;
2375 
2376 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2377 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2378 	ASSERT(!eager->tcp_hard_bound);
2379 	ASSERT(!TCP_IS_SOCKET(acceptor));
2380 	ASSERT(!TCP_IS_SOCKET(eager));
2381 	ASSERT(!TCP_IS_SOCKET(listener));
2382 
2383 	econnp = eager->tcp_connp;
2384 	aconnp = acceptor->tcp_connp;
2385 
2386 	/*
2387 	 * Trusted Extensions may need to use a security label that is
2388 	 * different from the acceptor's label on MLP and MAC-Exempt
2389 	 * sockets. If this is the case, the required security label
2390 	 * already exists in econnp->conn_effective_cred. Use this label
2391 	 * to generate a new effective cred for the acceptor.
2392 	 *
2393 	 * We allow for potential application level retry attempts by
2394 	 * checking for transient errors before modifying eager.
2395 	 */
2396 	if (is_system_labeled() &&
2397 	    aconnp->conn_cred != NULL && econnp->conn_effective_cred != NULL) {
2398 		effective_cred = copycred_from_tslabel(aconnp->conn_cred,
2399 		    crgetlabel(econnp->conn_effective_cred), KM_NOSLEEP);
2400 		if (effective_cred == NULL)
2401 			return (ENOMEM);
2402 	}
2403 
2404 	acceptor->tcp_detached = B_TRUE;
2405 	/*
2406 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2407 	 * the acceptor id.
2408 	 */
2409 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2410 
2411 	/* remove eager from listen list... */
2412 	mutex_enter(&listener->tcp_eager_lock);
2413 	tcp_eager_unlink(eager);
2414 	ASSERT(eager->tcp_eager_next_q == NULL &&
2415 	    eager->tcp_eager_last_q == NULL);
2416 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2417 	    eager->tcp_eager_prev_q0 == NULL);
2418 	mutex_exit(&listener->tcp_eager_lock);
2419 	eager->tcp_rq = acceptor->tcp_rq;
2420 	eager->tcp_wq = acceptor->tcp_wq;
2421 
2422 	eager->tcp_rq->q_ptr = econnp;
2423 	eager->tcp_wq->q_ptr = econnp;
2424 
2425 	/*
2426 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2427 	 * which might be a different squeue from our peer TCP instance.
2428 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2429 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2430 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2431 	 * above reach global visibility prior to the clearing of tcp_detached.
2432 	 */
2433 	membar_producer();
2434 	eager->tcp_detached = B_FALSE;
2435 
2436 	ASSERT(eager->tcp_ack_tid == 0);
2437 
2438 	econnp->conn_dev = aconnp->conn_dev;
2439 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2440 
2441 	ASSERT(econnp->conn_minor_arena != NULL);
2442 	if (eager->tcp_cred != NULL)
2443 		crfree(eager->tcp_cred);
2444 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2445 	if (econnp->conn_effective_cred != NULL)
2446 		crfree(econnp->conn_effective_cred);
2447 	econnp->conn_effective_cred = effective_cred;
2448 	aconnp->conn_cred = NULL;
2449 	ASSERT(aconnp->conn_effective_cred == NULL);
2450 
2451 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2452 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2453 
2454 	econnp->conn_zoneid = aconnp->conn_zoneid;
2455 	econnp->conn_allzones = aconnp->conn_allzones;
2456 
2457 	aconnp->conn_mac_mode = CONN_MAC_DEFAULT;
2458 
2459 	/* Do the IPC initialization */
2460 	CONN_INC_REF(econnp);
2461 
2462 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2463 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2464 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2465 
2466 	/* Done with old IPC. Drop its ref on its connp */
2467 	CONN_DEC_REF(aconnp);
2468 	return (0);
2469 }
2470 
2471 
2472 /*
2473  * Adapt to the information, such as rtt and rtt_sd, provided from the
2474  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2475  *
2476  * Checks for multicast and broadcast destination address.
2477  * Returns zero on failure; non-zero if ok.
2478  *
2479  * Note that the MSS calculation here is based on the info given in
2480  * the IRE.  We do not do any calculation based on TCP options.  They
2481  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2482  * knows which options to use.
2483  *
2484  * Note on how TCP gets its parameters for a connection.
2485  *
2486  * When a tcp_t structure is allocated, it gets all the default parameters.
2487  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2488  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2489  * default.
2490  *
2491  * An incoming SYN with a multicast or broadcast destination address, is dropped
2492  * in 1 of 2 places.
2493  *
2494  * 1. If the packet was received over the wire it is dropped in
2495  * ip_rput_process_broadcast()
2496  *
2497  * 2. If the packet was received through internal IP loopback, i.e. the packet
2498  * was generated and received on the same machine, it is dropped in
2499  * ip_wput_local()
2500  *
2501  * An incoming SYN with a multicast or broadcast source address is always
2502  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2503  * reject an attempt to connect to a broadcast or multicast (destination)
2504  * address.
2505  */
2506 static int
2507 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2508 {
2509 	ire_t		*ire;
2510 	ire_t		*sire = NULL;
2511 	iulp_t		*ire_uinfo = NULL;
2512 	uint32_t	mss_max;
2513 	uint32_t	mss;
2514 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2515 	conn_t		*connp = tcp->tcp_connp;
2516 	boolean_t	ire_cacheable = B_FALSE;
2517 	zoneid_t	zoneid = connp->conn_zoneid;
2518 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2519 	    MATCH_IRE_SECATTR;
2520 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2521 	ill_t		*ill = NULL;
2522 	boolean_t	incoming = (ire_mp == NULL);
2523 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2524 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2525 
2526 	ASSERT(connp->conn_ire_cache == NULL);
2527 
2528 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2529 
2530 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2531 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2532 			return (0);
2533 		}
2534 		/*
2535 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2536 		 * for the destination with the nexthop as gateway.
2537 		 * ire_ctable_lookup() is used because this particular
2538 		 * ire, if it exists, will be marked private.
2539 		 * If that is not available, use the interface ire
2540 		 * for the nexthop.
2541 		 *
2542 		 * TSol: tcp_update_label will detect label mismatches based
2543 		 * only on the destination's label, but that would not
2544 		 * detect label mismatches based on the security attributes
2545 		 * of routes or next hop gateway. Hence we need to pass the
2546 		 * label to ire_ftable_lookup below in order to locate the
2547 		 * right prefix (and/or) ire cache. Similarly we also need
2548 		 * pass the label to the ire_cache_lookup below to locate
2549 		 * the right ire that also matches on the label.
2550 		 */
2551 		if (tcp->tcp_connp->conn_nexthop_set) {
2552 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2553 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2554 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2555 			    ipst);
2556 			if (ire == NULL) {
2557 				ire = ire_ftable_lookup(
2558 				    tcp->tcp_connp->conn_nexthop_v4,
2559 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2560 				    tsl, match_flags, ipst);
2561 				if (ire == NULL)
2562 					return (0);
2563 			} else {
2564 				ire_uinfo = &ire->ire_uinfo;
2565 			}
2566 		} else {
2567 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2568 			    zoneid, tsl, ipst);
2569 			if (ire != NULL) {
2570 				ire_cacheable = B_TRUE;
2571 				ire_uinfo = (ire_mp != NULL) ?
2572 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2573 				    &ire->ire_uinfo;
2574 
2575 			} else {
2576 				if (ire_mp == NULL) {
2577 					ire = ire_ftable_lookup(
2578 					    tcp->tcp_connp->conn_rem,
2579 					    0, 0, 0, NULL, &sire, zoneid, 0,
2580 					    tsl, (MATCH_IRE_RECURSIVE |
2581 					    MATCH_IRE_DEFAULT), ipst);
2582 					if (ire == NULL)
2583 						return (0);
2584 					ire_uinfo = (sire != NULL) ?
2585 					    &sire->ire_uinfo :
2586 					    &ire->ire_uinfo;
2587 				} else {
2588 					ire = (ire_t *)ire_mp->b_rptr;
2589 					ire_uinfo =
2590 					    &((ire_t *)
2591 					    ire_mp->b_rptr)->ire_uinfo;
2592 				}
2593 			}
2594 		}
2595 		ASSERT(ire != NULL);
2596 
2597 		if ((ire->ire_src_addr == INADDR_ANY) ||
2598 		    (ire->ire_type & IRE_BROADCAST)) {
2599 			/*
2600 			 * ire->ire_mp is non null when ire_mp passed in is used
2601 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2602 			 */
2603 			if (ire->ire_mp == NULL)
2604 				ire_refrele(ire);
2605 			if (sire != NULL)
2606 				ire_refrele(sire);
2607 			return (0);
2608 		}
2609 
2610 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2611 			ipaddr_t src_addr;
2612 
2613 			/*
2614 			 * ip_bind_connected() has stored the correct source
2615 			 * address in conn_src.
2616 			 */
2617 			src_addr = tcp->tcp_connp->conn_src;
2618 			tcp->tcp_ipha->ipha_src = src_addr;
2619 			/*
2620 			 * Copy of the src addr. in tcp_t is needed
2621 			 * for the lookup funcs.
2622 			 */
2623 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2624 		}
2625 		/*
2626 		 * Set the fragment bit so that IP will tell us if the MTU
2627 		 * should change. IP tells us the latest setting of
2628 		 * ip_path_mtu_discovery through ire_frag_flag.
2629 		 */
2630 		if (ipst->ips_ip_path_mtu_discovery) {
2631 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2632 			    htons(IPH_DF);
2633 		}
2634 		/*
2635 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2636 		 * for IP_NEXTHOP. No cache ire has been found for the
2637 		 * destination and we are working with the nexthop's
2638 		 * interface ire. Since we need to forward all packets
2639 		 * to the nexthop first, we "blindly" set tcp_localnet
2640 		 * to false, eventhough the destination may also be
2641 		 * onlink.
2642 		 */
2643 		if (ire_uinfo == NULL)
2644 			tcp->tcp_localnet = 0;
2645 		else
2646 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2647 	} else {
2648 		/*
2649 		 * For incoming connection ire_mp = NULL
2650 		 * For outgoing connection ire_mp != NULL
2651 		 * Technically we should check conn_incoming_ill
2652 		 * when ire_mp is NULL and conn_outgoing_ill when
2653 		 * ire_mp is non-NULL. But this is performance
2654 		 * critical path and for IPV*_BOUND_IF, outgoing
2655 		 * and incoming ill are always set to the same value.
2656 		 */
2657 		ill_t	*dst_ill = NULL;
2658 		ipif_t  *dst_ipif = NULL;
2659 
2660 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2661 
2662 		if (connp->conn_outgoing_ill != NULL) {
2663 			/* Outgoing or incoming path */
2664 			int   err;
2665 
2666 			dst_ill = conn_get_held_ill(connp,
2667 			    &connp->conn_outgoing_ill, &err);
2668 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2669 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2670 				return (0);
2671 			}
2672 			match_flags |= MATCH_IRE_ILL;
2673 			dst_ipif = dst_ill->ill_ipif;
2674 		}
2675 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2676 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2677 
2678 		if (ire != NULL) {
2679 			ire_cacheable = B_TRUE;
2680 			ire_uinfo = (ire_mp != NULL) ?
2681 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2682 			    &ire->ire_uinfo;
2683 		} else {
2684 			if (ire_mp == NULL) {
2685 				ire = ire_ftable_lookup_v6(
2686 				    &tcp->tcp_connp->conn_remv6,
2687 				    0, 0, 0, dst_ipif, &sire, zoneid,
2688 				    0, tsl, match_flags, ipst);
2689 				if (ire == NULL) {
2690 					if (dst_ill != NULL)
2691 						ill_refrele(dst_ill);
2692 					return (0);
2693 				}
2694 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2695 				    &ire->ire_uinfo;
2696 			} else {
2697 				ire = (ire_t *)ire_mp->b_rptr;
2698 				ire_uinfo =
2699 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2700 			}
2701 		}
2702 		if (dst_ill != NULL)
2703 			ill_refrele(dst_ill);
2704 
2705 		ASSERT(ire != NULL);
2706 		ASSERT(ire_uinfo != NULL);
2707 
2708 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2709 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2710 			/*
2711 			 * ire->ire_mp is non null when ire_mp passed in is used
2712 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2713 			 */
2714 			if (ire->ire_mp == NULL)
2715 				ire_refrele(ire);
2716 			if (sire != NULL)
2717 				ire_refrele(sire);
2718 			return (0);
2719 		}
2720 
2721 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2722 			in6_addr_t	src_addr;
2723 
2724 			/*
2725 			 * ip_bind_connected_v6() has stored the correct source
2726 			 * address per IPv6 addr. selection policy in
2727 			 * conn_src_v6.
2728 			 */
2729 			src_addr = tcp->tcp_connp->conn_srcv6;
2730 
2731 			tcp->tcp_ip6h->ip6_src = src_addr;
2732 			/*
2733 			 * Copy of the src addr. in tcp_t is needed
2734 			 * for the lookup funcs.
2735 			 */
2736 			tcp->tcp_ip_src_v6 = src_addr;
2737 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2738 			    &connp->conn_srcv6));
2739 		}
2740 		tcp->tcp_localnet =
2741 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2742 	}
2743 
2744 	/*
2745 	 * This allows applications to fail quickly when connections are made
2746 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2747 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2748 	 */
2749 	if ((ire->ire_flags & RTF_REJECT) &&
2750 	    (ire->ire_flags & RTF_PRIVATE))
2751 		goto error;
2752 
2753 	/*
2754 	 * Make use of the cached rtt and rtt_sd values to calculate the
2755 	 * initial RTO.  Note that they are already initialized in
2756 	 * tcp_init_values().
2757 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2758 	 * IP_NEXTHOP, but instead are using the interface ire for the
2759 	 * nexthop, then we do not use the ire_uinfo from that ire to
2760 	 * do any initializations.
2761 	 */
2762 	if (ire_uinfo != NULL) {
2763 		if (ire_uinfo->iulp_rtt != 0) {
2764 			clock_t	rto;
2765 
2766 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2767 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2768 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2769 			    tcps->tcps_rexmit_interval_extra +
2770 			    (tcp->tcp_rtt_sa >> 5);
2771 
2772 			if (rto > tcps->tcps_rexmit_interval_max) {
2773 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2774 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2775 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2776 			} else {
2777 				tcp->tcp_rto = rto;
2778 			}
2779 		}
2780 		if (ire_uinfo->iulp_ssthresh != 0)
2781 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2782 		else
2783 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2784 		if (ire_uinfo->iulp_spipe > 0) {
2785 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2786 			    tcps->tcps_max_buf);
2787 			if (tcps->tcps_snd_lowat_fraction != 0)
2788 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2789 				    tcps->tcps_snd_lowat_fraction;
2790 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2791 		}
2792 		/*
2793 		 * Note that up till now, acceptor always inherits receive
2794 		 * window from the listener.  But if there is a metrics
2795 		 * associated with a host, we should use that instead of
2796 		 * inheriting it from listener. Thus we need to pass this
2797 		 * info back to the caller.
2798 		 */
2799 		if (ire_uinfo->iulp_rpipe > 0) {
2800 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2801 			    tcps->tcps_max_buf);
2802 		}
2803 
2804 		if (ire_uinfo->iulp_rtomax > 0) {
2805 			tcp->tcp_second_timer_threshold =
2806 			    ire_uinfo->iulp_rtomax;
2807 		}
2808 
2809 		/*
2810 		 * Use the metric option settings, iulp_tstamp_ok and
2811 		 * iulp_wscale_ok, only for active open. What this means
2812 		 * is that if the other side uses timestamp or window
2813 		 * scale option, TCP will also use those options. That
2814 		 * is for passive open.  If the application sets a
2815 		 * large window, window scale is enabled regardless of
2816 		 * the value in iulp_wscale_ok.  This is the behavior
2817 		 * since 2.6.  So we keep it.
2818 		 * The only case left in passive open processing is the
2819 		 * check for SACK.
2820 		 * For ECN, it should probably be like SACK.  But the
2821 		 * current value is binary, so we treat it like the other
2822 		 * cases.  The metric only controls active open.For passive
2823 		 * open, the ndd param, tcp_ecn_permitted, controls the
2824 		 * behavior.
2825 		 */
2826 		if (!tcp_detached) {
2827 			/*
2828 			 * The if check means that the following can only
2829 			 * be turned on by the metrics only IRE, but not off.
2830 			 */
2831 			if (ire_uinfo->iulp_tstamp_ok)
2832 				tcp->tcp_snd_ts_ok = B_TRUE;
2833 			if (ire_uinfo->iulp_wscale_ok)
2834 				tcp->tcp_snd_ws_ok = B_TRUE;
2835 			if (ire_uinfo->iulp_sack == 2)
2836 				tcp->tcp_snd_sack_ok = B_TRUE;
2837 			if (ire_uinfo->iulp_ecn_ok)
2838 				tcp->tcp_ecn_ok = B_TRUE;
2839 		} else {
2840 			/*
2841 			 * Passive open.
2842 			 *
2843 			 * As above, the if check means that SACK can only be
2844 			 * turned on by the metric only IRE.
2845 			 */
2846 			if (ire_uinfo->iulp_sack > 0) {
2847 				tcp->tcp_snd_sack_ok = B_TRUE;
2848 			}
2849 		}
2850 	}
2851 
2852 
2853 	/*
2854 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2855 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2856 	 * length of all those options exceeds 28 bytes.  But because
2857 	 * of the tcp_mss_min check below, we may not have a problem if
2858 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2859 	 * the negative problem still exists.  And the check defeats PMTUd.
2860 	 * In fact, if PMTUd finds that the MSS should be smaller than
2861 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2862 	 * value.
2863 	 *
2864 	 * We do not deal with that now.  All those problems related to
2865 	 * PMTUd will be fixed later.
2866 	 */
2867 	ASSERT(ire->ire_max_frag != 0);
2868 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2869 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2870 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2871 			mss = MIN(mss, IPV6_MIN_MTU);
2872 		}
2873 	}
2874 
2875 	/* Sanity check for MSS value. */
2876 	if (tcp->tcp_ipversion == IPV4_VERSION)
2877 		mss_max = tcps->tcps_mss_max_ipv4;
2878 	else
2879 		mss_max = tcps->tcps_mss_max_ipv6;
2880 
2881 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2882 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2883 		/*
2884 		 * After receiving an ICMPv6 "packet too big" message with a
2885 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2886 		 * will insert a 8-byte fragment header in every packet; we
2887 		 * reduce the MSS by that amount here.
2888 		 */
2889 		mss -= sizeof (ip6_frag_t);
2890 	}
2891 
2892 	if (tcp->tcp_ipsec_overhead == 0)
2893 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2894 
2895 	mss -= tcp->tcp_ipsec_overhead;
2896 
2897 	if (mss < tcps->tcps_mss_min)
2898 		mss = tcps->tcps_mss_min;
2899 	if (mss > mss_max)
2900 		mss = mss_max;
2901 
2902 	/* Note that this is the maximum MSS, excluding all options. */
2903 	tcp->tcp_mss = mss;
2904 
2905 	/*
2906 	 * Initialize the ISS here now that we have the full connection ID.
2907 	 * The RFC 1948 method of initial sequence number generation requires
2908 	 * knowledge of the full connection ID before setting the ISS.
2909 	 */
2910 
2911 	tcp_iss_init(tcp);
2912 
2913 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2914 		tcp->tcp_loopback = B_TRUE;
2915 
2916 	if (sire != NULL)
2917 		IRE_REFRELE(sire);
2918 
2919 	/*
2920 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2921 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2922 	 */
2923 	if (tcp->tcp_loopback ||
2924 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2925 		/*
2926 		 * For incoming, see if this tcp may be MDT-capable.  For
2927 		 * outgoing, this process has been taken care of through
2928 		 * tcp_rput_other.
2929 		 */
2930 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2931 		tcp->tcp_ire_ill_check_done = B_TRUE;
2932 	}
2933 
2934 	mutex_enter(&connp->conn_lock);
2935 	/*
2936 	 * Make sure that conn is not marked incipient
2937 	 * for incoming connections. A blind
2938 	 * removal of incipient flag is cheaper than
2939 	 * check and removal.
2940 	 */
2941 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2942 
2943 	/*
2944 	 * Must not cache forwarding table routes
2945 	 * or recache an IRE after the conn_t has
2946 	 * had conn_ire_cache cleared and is flagged
2947 	 * unusable, (see the CONN_CACHE_IRE() macro).
2948 	 */
2949 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2950 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2951 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2952 			connp->conn_ire_cache = ire;
2953 			IRE_UNTRACE_REF(ire);
2954 			rw_exit(&ire->ire_bucket->irb_lock);
2955 			mutex_exit(&connp->conn_lock);
2956 			return (1);
2957 		}
2958 		rw_exit(&ire->ire_bucket->irb_lock);
2959 	}
2960 	mutex_exit(&connp->conn_lock);
2961 
2962 	if (ire->ire_mp == NULL)
2963 		ire_refrele(ire);
2964 	return (1);
2965 
2966 error:
2967 	if (ire->ire_mp == NULL)
2968 		ire_refrele(ire);
2969 	if (sire != NULL)
2970 		ire_refrele(sire);
2971 	return (0);
2972 }
2973 
2974 static void
2975 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2976 {
2977 	int	error;
2978 	conn_t	*connp = tcp->tcp_connp;
2979 	struct sockaddr	*sa;
2980 	mblk_t  *mp1;
2981 	struct T_bind_req *tbr;
2982 	int	backlog;
2983 	socklen_t	len;
2984 	sin_t	*sin;
2985 	sin6_t	*sin6;
2986 	cred_t		*cr;
2987 
2988 	/*
2989 	 * All Solaris components should pass a db_credp
2990 	 * for this TPI message, hence we ASSERT.
2991 	 * But in case there is some other M_PROTO that looks
2992 	 * like a TPI message sent by some other kernel
2993 	 * component, we check and return an error.
2994 	 */
2995 	cr = msg_getcred(mp, NULL);
2996 	ASSERT(cr != NULL);
2997 	if (cr == NULL) {
2998 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2999 		return;
3000 	}
3001 
3002 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3003 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3004 		if (tcp->tcp_debug) {
3005 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3006 			    "tcp_tpi_bind: bad req, len %u",
3007 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3008 		}
3009 		tcp_err_ack(tcp, mp, TPROTO, 0);
3010 		return;
3011 	}
3012 	/* Make sure the largest address fits */
3013 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3014 	if (mp1 == NULL) {
3015 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3016 		return;
3017 	}
3018 	mp = mp1;
3019 	tbr = (struct T_bind_req *)mp->b_rptr;
3020 
3021 	backlog = tbr->CONIND_number;
3022 	len = tbr->ADDR_length;
3023 
3024 	switch (len) {
3025 	case 0:		/* request for a generic port */
3026 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3027 		if (tcp->tcp_family == AF_INET) {
3028 			tbr->ADDR_length = sizeof (sin_t);
3029 			sin = (sin_t *)&tbr[1];
3030 			*sin = sin_null;
3031 			sin->sin_family = AF_INET;
3032 			sa = (struct sockaddr *)sin;
3033 			len = sizeof (sin_t);
3034 			mp->b_wptr = (uchar_t *)&sin[1];
3035 		} else {
3036 			ASSERT(tcp->tcp_family == AF_INET6);
3037 			tbr->ADDR_length = sizeof (sin6_t);
3038 			sin6 = (sin6_t *)&tbr[1];
3039 			*sin6 = sin6_null;
3040 			sin6->sin6_family = AF_INET6;
3041 			sa = (struct sockaddr *)sin6;
3042 			len = sizeof (sin6_t);
3043 			mp->b_wptr = (uchar_t *)&sin6[1];
3044 		}
3045 		break;
3046 
3047 	case sizeof (sin_t):    /* Complete IPv4 address */
3048 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
3049 		    sizeof (sin_t));
3050 		break;
3051 
3052 	case sizeof (sin6_t): /* Complete IPv6 address */
3053 		sa = (struct sockaddr *)mi_offset_param(mp,
3054 		    tbr->ADDR_offset, sizeof (sin6_t));
3055 		break;
3056 
3057 	default:
3058 		if (tcp->tcp_debug) {
3059 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3060 			    "tcp_tpi_bind: bad address length, %d",
3061 			    tbr->ADDR_length);
3062 		}
3063 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3064 		return;
3065 	}
3066 
3067 	if (backlog > 0) {
3068 		error = tcp_do_listen(connp, sa, len, backlog, DB_CRED(mp),
3069 		    tbr->PRIM_type != O_T_BIND_REQ);
3070 	} else {
3071 		error = tcp_do_bind(connp, sa, len, DB_CRED(mp),
3072 		    tbr->PRIM_type != O_T_BIND_REQ);
3073 	}
3074 done:
3075 	if (error > 0) {
3076 		tcp_err_ack(tcp, mp, TSYSERR, error);
3077 	} else if (error < 0) {
3078 		tcp_err_ack(tcp, mp, -error, 0);
3079 	} else {
3080 		/*
3081 		 * Update port information as sockfs/tpi needs it for checking
3082 		 */
3083 		if (tcp->tcp_family == AF_INET) {
3084 			sin = (sin_t *)sa;
3085 			sin->sin_port = tcp->tcp_lport;
3086 		} else {
3087 			sin6 = (sin6_t *)sa;
3088 			sin6->sin6_port = tcp->tcp_lport;
3089 		}
3090 		mp->b_datap->db_type = M_PCPROTO;
3091 		tbr->PRIM_type = T_BIND_ACK;
3092 		putnext(tcp->tcp_rq, mp);
3093 	}
3094 }
3095 
3096 /*
3097  * If the "bind_to_req_port_only" parameter is set, if the requested port
3098  * number is available, return it, If not return 0
3099  *
3100  * If "bind_to_req_port_only" parameter is not set and
3101  * If the requested port number is available, return it.  If not, return
3102  * the first anonymous port we happen across.  If no anonymous ports are
3103  * available, return 0. addr is the requested local address, if any.
3104  *
3105  * In either case, when succeeding update the tcp_t to record the port number
3106  * and insert it in the bind hash table.
3107  *
3108  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3109  * without setting SO_REUSEADDR. This is needed so that they
3110  * can be viewed as two independent transport protocols.
3111  */
3112 static in_port_t
3113 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3114     int reuseaddr, boolean_t quick_connect,
3115     boolean_t bind_to_req_port_only, boolean_t user_specified)
3116 {
3117 	/* number of times we have run around the loop */
3118 	int count = 0;
3119 	/* maximum number of times to run around the loop */
3120 	int loopmax;
3121 	conn_t *connp = tcp->tcp_connp;
3122 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3123 
3124 	/*
3125 	 * Lookup for free addresses is done in a loop and "loopmax"
3126 	 * influences how long we spin in the loop
3127 	 */
3128 	if (bind_to_req_port_only) {
3129 		/*
3130 		 * If the requested port is busy, don't bother to look
3131 		 * for a new one. Setting loop maximum count to 1 has
3132 		 * that effect.
3133 		 */
3134 		loopmax = 1;
3135 	} else {
3136 		/*
3137 		 * If the requested port is busy, look for a free one
3138 		 * in the anonymous port range.
3139 		 * Set loopmax appropriately so that one does not look
3140 		 * forever in the case all of the anonymous ports are in use.
3141 		 */
3142 		if (tcp->tcp_anon_priv_bind) {
3143 			/*
3144 			 * loopmax =
3145 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3146 			 */
3147 			loopmax = IPPORT_RESERVED -
3148 			    tcps->tcps_min_anonpriv_port;
3149 		} else {
3150 			loopmax = (tcps->tcps_largest_anon_port -
3151 			    tcps->tcps_smallest_anon_port + 1);
3152 		}
3153 	}
3154 	do {
3155 		uint16_t	lport;
3156 		tf_t		*tbf;
3157 		tcp_t		*ltcp;
3158 		conn_t		*lconnp;
3159 
3160 		lport = htons(port);
3161 
3162 		/*
3163 		 * Ensure that the tcp_t is not currently in the bind hash.
3164 		 * Hold the lock on the hash bucket to ensure that
3165 		 * the duplicate check plus the insertion is an atomic
3166 		 * operation.
3167 		 *
3168 		 * This function does an inline lookup on the bind hash list
3169 		 * Make sure that we access only members of tcp_t
3170 		 * and that we don't look at tcp_tcp, since we are not
3171 		 * doing a CONN_INC_REF.
3172 		 */
3173 		tcp_bind_hash_remove(tcp);
3174 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3175 		mutex_enter(&tbf->tf_lock);
3176 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3177 		    ltcp = ltcp->tcp_bind_hash) {
3178 			if (lport == ltcp->tcp_lport)
3179 				break;
3180 		}
3181 
3182 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3183 			boolean_t not_socket;
3184 			boolean_t exclbind;
3185 
3186 			lconnp = ltcp->tcp_connp;
3187 
3188 			/*
3189 			 * On a labeled system, we must treat bindings to ports
3190 			 * on shared IP addresses by sockets with MAC exemption
3191 			 * privilege as being in all zones, as there's
3192 			 * otherwise no way to identify the right receiver.
3193 			 */
3194 			if (!IPCL_BIND_ZONE_MATCH(ltcp->tcp_connp, connp))
3195 				continue;
3196 
3197 			/*
3198 			 * If TCP_EXCLBIND is set for either the bound or
3199 			 * binding endpoint, the semantics of bind
3200 			 * is changed according to the following.
3201 			 *
3202 			 * spec = specified address (v4 or v6)
3203 			 * unspec = unspecified address (v4 or v6)
3204 			 * A = specified addresses are different for endpoints
3205 			 *
3206 			 * bound	bind to		allowed
3207 			 * -------------------------------------
3208 			 * unspec	unspec		no
3209 			 * unspec	spec		no
3210 			 * spec		unspec		no
3211 			 * spec		spec		yes if A
3212 			 *
3213 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3214 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3215 			 *
3216 			 * Note:
3217 			 *
3218 			 * 1. Because of TLI semantics, an endpoint can go
3219 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3220 			 * TCPS_BOUND, depending on whether it is originally
3221 			 * a listener or not.  That is why we need to check
3222 			 * for states greater than or equal to TCPS_BOUND
3223 			 * here.
3224 			 *
3225 			 * 2. Ideally, we should only check for state equals
3226 			 * to TCPS_LISTEN. And the following check should be
3227 			 * added.
3228 			 *
3229 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3230 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3231 			 *		...
3232 			 * }
3233 			 *
3234 			 * The semantics will be changed to this.  If the
3235 			 * endpoint on the list is in state not equal to
3236 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3237 			 * set, let the bind succeed.
3238 			 *
3239 			 * Because of (1), we cannot do that for TLI
3240 			 * endpoints.  But we can do that for socket endpoints.
3241 			 * If in future, we can change this going back
3242 			 * semantics, we can use the above check for TLI also.
3243 			 */
3244 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3245 			    TCP_IS_SOCKET(tcp));
3246 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3247 
3248 			if ((lconnp->conn_mac_mode != CONN_MAC_DEFAULT) ||
3249 			    (connp->conn_mac_mode != CONN_MAC_DEFAULT) ||
3250 			    (exclbind && (not_socket ||
3251 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3252 				if (V6_OR_V4_INADDR_ANY(
3253 				    ltcp->tcp_bound_source_v6) ||
3254 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3255 				    IN6_ARE_ADDR_EQUAL(laddr,
3256 				    &ltcp->tcp_bound_source_v6)) {
3257 					break;
3258 				}
3259 				continue;
3260 			}
3261 
3262 			/*
3263 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3264 			 * have disjoint port number spaces, if *_EXCLBIND
3265 			 * is not set and only if the application binds to a
3266 			 * specific port. We use the same autoassigned port
3267 			 * number space for IPv4 and IPv6 sockets.
3268 			 */
3269 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3270 			    bind_to_req_port_only)
3271 				continue;
3272 
3273 			/*
3274 			 * Ideally, we should make sure that the source
3275 			 * address, remote address, and remote port in the
3276 			 * four tuple for this tcp-connection is unique.
3277 			 * However, trying to find out the local source
3278 			 * address would require too much code duplication
3279 			 * with IP, since IP needs needs to have that code
3280 			 * to support userland TCP implementations.
3281 			 */
3282 			if (quick_connect &&
3283 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3284 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3285 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3286 			    &ltcp->tcp_remote_v6)))
3287 				continue;
3288 
3289 			if (!reuseaddr) {
3290 				/*
3291 				 * No socket option SO_REUSEADDR.
3292 				 * If existing port is bound to
3293 				 * a non-wildcard IP address
3294 				 * and the requesting stream is
3295 				 * bound to a distinct
3296 				 * different IP addresses
3297 				 * (non-wildcard, also), keep
3298 				 * going.
3299 				 */
3300 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3301 				    !V6_OR_V4_INADDR_ANY(
3302 				    ltcp->tcp_bound_source_v6) &&
3303 				    !IN6_ARE_ADDR_EQUAL(laddr,
3304 				    &ltcp->tcp_bound_source_v6))
3305 					continue;
3306 				if (ltcp->tcp_state >= TCPS_BOUND) {
3307 					/*
3308 					 * This port is being used and
3309 					 * its state is >= TCPS_BOUND,
3310 					 * so we can't bind to it.
3311 					 */
3312 					break;
3313 				}
3314 			} else {
3315 				/*
3316 				 * socket option SO_REUSEADDR is set on the
3317 				 * binding tcp_t.
3318 				 *
3319 				 * If two streams are bound to
3320 				 * same IP address or both addr
3321 				 * and bound source are wildcards
3322 				 * (INADDR_ANY), we want to stop
3323 				 * searching.
3324 				 * We have found a match of IP source
3325 				 * address and source port, which is
3326 				 * refused regardless of the
3327 				 * SO_REUSEADDR setting, so we break.
3328 				 */
3329 				if (IN6_ARE_ADDR_EQUAL(laddr,
3330 				    &ltcp->tcp_bound_source_v6) &&
3331 				    (ltcp->tcp_state == TCPS_LISTEN ||
3332 				    ltcp->tcp_state == TCPS_BOUND))
3333 					break;
3334 			}
3335 		}
3336 		if (ltcp != NULL) {
3337 			/* The port number is busy */
3338 			mutex_exit(&tbf->tf_lock);
3339 		} else {
3340 			/*
3341 			 * This port is ours. Insert in fanout and mark as
3342 			 * bound to prevent others from getting the port
3343 			 * number.
3344 			 */
3345 			tcp->tcp_state = TCPS_BOUND;
3346 			tcp->tcp_lport = htons(port);
3347 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3348 
3349 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3350 			    tcp->tcp_lport)] == tbf);
3351 			tcp_bind_hash_insert(tbf, tcp, 1);
3352 
3353 			mutex_exit(&tbf->tf_lock);
3354 
3355 			/*
3356 			 * We don't want tcp_next_port_to_try to "inherit"
3357 			 * a port number supplied by the user in a bind.
3358 			 */
3359 			if (user_specified)
3360 				return (port);
3361 
3362 			/*
3363 			 * This is the only place where tcp_next_port_to_try
3364 			 * is updated. After the update, it may or may not
3365 			 * be in the valid range.
3366 			 */
3367 			if (!tcp->tcp_anon_priv_bind)
3368 				tcps->tcps_next_port_to_try = port + 1;
3369 			return (port);
3370 		}
3371 
3372 		if (tcp->tcp_anon_priv_bind) {
3373 			port = tcp_get_next_priv_port(tcp);
3374 		} else {
3375 			if (count == 0 && user_specified) {
3376 				/*
3377 				 * We may have to return an anonymous port. So
3378 				 * get one to start with.
3379 				 */
3380 				port =
3381 				    tcp_update_next_port(
3382 				    tcps->tcps_next_port_to_try,
3383 				    tcp, B_TRUE);
3384 				user_specified = B_FALSE;
3385 			} else {
3386 				port = tcp_update_next_port(port + 1, tcp,
3387 				    B_FALSE);
3388 			}
3389 		}
3390 		if (port == 0)
3391 			break;
3392 
3393 		/*
3394 		 * Don't let this loop run forever in the case where
3395 		 * all of the anonymous ports are in use.
3396 		 */
3397 	} while (++count < loopmax);
3398 	return (0);
3399 }
3400 
3401 /*
3402  * tcp_clean_death / tcp_close_detached must not be called more than once
3403  * on a tcp. Thus every function that potentially calls tcp_clean_death
3404  * must check for the tcp state before calling tcp_clean_death.
3405  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3406  * tcp_timer_handler, all check for the tcp state.
3407  */
3408 /* ARGSUSED */
3409 void
3410 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3411 {
3412 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3413 
3414 	freemsg(mp);
3415 	if (tcp->tcp_state > TCPS_BOUND)
3416 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3417 		    ETIMEDOUT, 5);
3418 }
3419 
3420 /*
3421  * We are dying for some reason.  Try to do it gracefully.  (May be called
3422  * as writer.)
3423  *
3424  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3425  * done by a service procedure).
3426  * TBD - Should the return value distinguish between the tcp_t being
3427  * freed and it being reinitialized?
3428  */
3429 static int
3430 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3431 {
3432 	mblk_t	*mp;
3433 	queue_t	*q;
3434 	conn_t	*connp = tcp->tcp_connp;
3435 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3436 
3437 	TCP_CLD_STAT(tag);
3438 
3439 #if TCP_TAG_CLEAN_DEATH
3440 	tcp->tcp_cleandeathtag = tag;
3441 #endif
3442 
3443 	if (tcp->tcp_fused)
3444 		tcp_unfuse(tcp);
3445 
3446 	if (tcp->tcp_linger_tid != 0 &&
3447 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3448 		tcp_stop_lingering(tcp);
3449 	}
3450 
3451 	ASSERT(tcp != NULL);
3452 	ASSERT((tcp->tcp_family == AF_INET &&
3453 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3454 	    (tcp->tcp_family == AF_INET6 &&
3455 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3456 	    tcp->tcp_ipversion == IPV6_VERSION)));
3457 
3458 	if (TCP_IS_DETACHED(tcp)) {
3459 		if (tcp->tcp_hard_binding) {
3460 			/*
3461 			 * Its an eager that we are dealing with. We close the
3462 			 * eager but in case a conn_ind has already gone to the
3463 			 * listener, let tcp_accept_finish() send a discon_ind
3464 			 * to the listener and drop the last reference. If the
3465 			 * listener doesn't even know about the eager i.e. the
3466 			 * conn_ind hasn't gone up, blow away the eager and drop
3467 			 * the last reference as well. If the conn_ind has gone
3468 			 * up, state should be BOUND. tcp_accept_finish
3469 			 * will figure out that the connection has received a
3470 			 * RST and will send a DISCON_IND to the application.
3471 			 */
3472 			tcp_closei_local(tcp);
3473 			if (!tcp->tcp_tconnind_started) {
3474 				CONN_DEC_REF(connp);
3475 			} else {
3476 				tcp->tcp_state = TCPS_BOUND;
3477 			}
3478 		} else {
3479 			tcp_close_detached(tcp);
3480 		}
3481 		return (0);
3482 	}
3483 
3484 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3485 
3486 	q = tcp->tcp_rq;
3487 
3488 	/* Trash all inbound data */
3489 	if (!IPCL_IS_NONSTR(connp)) {
3490 		ASSERT(q != NULL);
3491 		flushq(q, FLUSHALL);
3492 	}
3493 
3494 	/*
3495 	 * If we are at least part way open and there is error
3496 	 * (err==0 implies no error)
3497 	 * notify our client by a T_DISCON_IND.
3498 	 */
3499 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3500 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3501 		    !TCP_IS_SOCKET(tcp)) {
3502 			/*
3503 			 * Send M_FLUSH according to TPI. Because sockets will
3504 			 * (and must) ignore FLUSHR we do that only for TPI
3505 			 * endpoints and sockets in STREAMS mode.
3506 			 */
3507 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3508 		}
3509 		if (tcp->tcp_debug) {
3510 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3511 			    "tcp_clean_death: discon err %d", err);
3512 		}
3513 		if (IPCL_IS_NONSTR(connp)) {
3514 			/* Direct socket, use upcall */
3515 			(*connp->conn_upcalls->su_disconnected)(
3516 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3517 		} else {
3518 			mp = mi_tpi_discon_ind(NULL, err, 0);
3519 			if (mp != NULL) {
3520 				putnext(q, mp);
3521 			} else {
3522 				if (tcp->tcp_debug) {
3523 					(void) strlog(TCP_MOD_ID, 0, 1,
3524 					    SL_ERROR|SL_TRACE,
3525 					    "tcp_clean_death, sending M_ERROR");
3526 				}
3527 				(void) putnextctl1(q, M_ERROR, EPROTO);
3528 			}
3529 		}
3530 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3531 			/* SYN_SENT or SYN_RCVD */
3532 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3533 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3534 			/* ESTABLISHED or CLOSE_WAIT */
3535 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3536 		}
3537 	}
3538 
3539 	tcp_reinit(tcp);
3540 	if (IPCL_IS_NONSTR(connp))
3541 		(void) tcp_do_unbind(connp);
3542 
3543 	return (-1);
3544 }
3545 
3546 /*
3547  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3548  * to expire, stop the wait and finish the close.
3549  */
3550 static void
3551 tcp_stop_lingering(tcp_t *tcp)
3552 {
3553 	clock_t	delta = 0;
3554 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3555 
3556 	tcp->tcp_linger_tid = 0;
3557 	if (tcp->tcp_state > TCPS_LISTEN) {
3558 		tcp_acceptor_hash_remove(tcp);
3559 		mutex_enter(&tcp->tcp_non_sq_lock);
3560 		if (tcp->tcp_flow_stopped) {
3561 			tcp_clrqfull(tcp);
3562 		}
3563 		mutex_exit(&tcp->tcp_non_sq_lock);
3564 
3565 		if (tcp->tcp_timer_tid != 0) {
3566 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3567 			tcp->tcp_timer_tid = 0;
3568 		}
3569 		/*
3570 		 * Need to cancel those timers which will not be used when
3571 		 * TCP is detached.  This has to be done before the tcp_wq
3572 		 * is set to the global queue.
3573 		 */
3574 		tcp_timers_stop(tcp);
3575 
3576 		tcp->tcp_detached = B_TRUE;
3577 		ASSERT(tcps->tcps_g_q != NULL);
3578 		tcp->tcp_rq = tcps->tcps_g_q;
3579 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3580 
3581 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3582 			tcp_time_wait_append(tcp);
3583 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3584 			goto finish;
3585 		}
3586 
3587 		/*
3588 		 * If delta is zero the timer event wasn't executed and was
3589 		 * successfully canceled. In this case we need to restart it
3590 		 * with the minimal delta possible.
3591 		 */
3592 		if (delta >= 0) {
3593 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3594 			    delta ? delta : 1);
3595 		}
3596 	} else {
3597 		tcp_closei_local(tcp);
3598 		CONN_DEC_REF(tcp->tcp_connp);
3599 	}
3600 finish:
3601 	/* Signal closing thread that it can complete close */
3602 	mutex_enter(&tcp->tcp_closelock);
3603 	tcp->tcp_detached = B_TRUE;
3604 	ASSERT(tcps->tcps_g_q != NULL);
3605 
3606 	tcp->tcp_rq = tcps->tcps_g_q;
3607 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3608 
3609 	tcp->tcp_closed = 1;
3610 	cv_signal(&tcp->tcp_closecv);
3611 	mutex_exit(&tcp->tcp_closelock);
3612 }
3613 
3614 /*
3615  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3616  * expires.
3617  */
3618 static void
3619 tcp_close_linger_timeout(void *arg)
3620 {
3621 	conn_t	*connp = (conn_t *)arg;
3622 	tcp_t 	*tcp = connp->conn_tcp;
3623 
3624 	tcp->tcp_client_errno = ETIMEDOUT;
3625 	tcp_stop_lingering(tcp);
3626 }
3627 
3628 static void
3629 tcp_close_common(conn_t *connp, int flags)
3630 {
3631 	tcp_t		*tcp = connp->conn_tcp;
3632 	mblk_t 		*mp = &tcp->tcp_closemp;
3633 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3634 	mblk_t		*bp;
3635 
3636 	ASSERT(connp->conn_ref >= 2);
3637 
3638 	/*
3639 	 * Mark the conn as closing. ill_pending_mp_add will not
3640 	 * add any mp to the pending mp list, after this conn has
3641 	 * started closing. Same for sq_pending_mp_add
3642 	 */
3643 	mutex_enter(&connp->conn_lock);
3644 	connp->conn_state_flags |= CONN_CLOSING;
3645 	if (connp->conn_oper_pending_ill != NULL)
3646 		conn_ioctl_cleanup_reqd = B_TRUE;
3647 	CONN_INC_REF_LOCKED(connp);
3648 	mutex_exit(&connp->conn_lock);
3649 	tcp->tcp_closeflags = (uint8_t)flags;
3650 	ASSERT(connp->conn_ref >= 3);
3651 
3652 	/*
3653 	 * tcp_closemp_used is used below without any protection of a lock
3654 	 * as we don't expect any one else to use it concurrently at this
3655 	 * point otherwise it would be a major defect.
3656 	 */
3657 
3658 	if (mp->b_prev == NULL)
3659 		tcp->tcp_closemp_used = B_TRUE;
3660 	else
3661 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3662 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3663 
3664 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3665 
3666 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3667 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3668 
3669 	mutex_enter(&tcp->tcp_closelock);
3670 	while (!tcp->tcp_closed) {
3671 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3672 			/*
3673 			 * The cv_wait_sig() was interrupted. We now do the
3674 			 * following:
3675 			 *
3676 			 * 1) If the endpoint was lingering, we allow this
3677 			 * to be interrupted by cancelling the linger timeout
3678 			 * and closing normally.
3679 			 *
3680 			 * 2) Revert to calling cv_wait()
3681 			 *
3682 			 * We revert to using cv_wait() to avoid an
3683 			 * infinite loop which can occur if the calling
3684 			 * thread is higher priority than the squeue worker
3685 			 * thread and is bound to the same cpu.
3686 			 */
3687 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3688 				mutex_exit(&tcp->tcp_closelock);
3689 				/* Entering squeue, bump ref count. */
3690 				CONN_INC_REF(connp);
3691 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3692 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3693 				    tcp_linger_interrupted, connp,
3694 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3695 				mutex_enter(&tcp->tcp_closelock);
3696 			}
3697 			break;
3698 		}
3699 	}
3700 	while (!tcp->tcp_closed)
3701 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3702 	mutex_exit(&tcp->tcp_closelock);
3703 
3704 	/*
3705 	 * In the case of listener streams that have eagers in the q or q0
3706 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3707 	 * tcp_wq of the eagers point to our queues. By waiting for the
3708 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3709 	 * up their queue pointers and also dropped their references to us.
3710 	 */
3711 	if (tcp->tcp_wait_for_eagers) {
3712 		mutex_enter(&connp->conn_lock);
3713 		while (connp->conn_ref != 1) {
3714 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3715 		}
3716 		mutex_exit(&connp->conn_lock);
3717 	}
3718 	/*
3719 	 * ioctl cleanup. The mp is queued in the
3720 	 * ill_pending_mp or in the sq_pending_mp.
3721 	 */
3722 	if (conn_ioctl_cleanup_reqd)
3723 		conn_ioctl_cleanup(connp);
3724 
3725 	tcp->tcp_cpid = -1;
3726 }
3727 
3728 static int
3729 tcp_tpi_close(queue_t *q, int flags)
3730 {
3731 	conn_t		*connp;
3732 
3733 	ASSERT(WR(q)->q_next == NULL);
3734 
3735 	if (flags & SO_FALLBACK) {
3736 		/*
3737 		 * stream is being closed while in fallback
3738 		 * simply free the resources that were allocated
3739 		 */
3740 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3741 		qprocsoff(q);
3742 		goto done;
3743 	}
3744 
3745 	connp = Q_TO_CONN(q);
3746 	/*
3747 	 * We are being closed as /dev/tcp or /dev/tcp6.
3748 	 */
3749 	tcp_close_common(connp, flags);
3750 
3751 	qprocsoff(q);
3752 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3753 
3754 	/*
3755 	 * Drop IP's reference on the conn. This is the last reference
3756 	 * on the connp if the state was less than established. If the
3757 	 * connection has gone into timewait state, then we will have
3758 	 * one ref for the TCP and one more ref (total of two) for the
3759 	 * classifier connected hash list (a timewait connections stays
3760 	 * in connected hash till closed).
3761 	 *
3762 	 * We can't assert the references because there might be other
3763 	 * transient reference places because of some walkers or queued
3764 	 * packets in squeue for the timewait state.
3765 	 */
3766 	CONN_DEC_REF(connp);
3767 done:
3768 	q->q_ptr = WR(q)->q_ptr = NULL;
3769 	return (0);
3770 }
3771 
3772 static int
3773 tcp_tpi_close_accept(queue_t *q)
3774 {
3775 	vmem_t	*minor_arena;
3776 	dev_t	conn_dev;
3777 
3778 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3779 
3780 	/*
3781 	 * We had opened an acceptor STREAM for sockfs which is
3782 	 * now being closed due to some error.
3783 	 */
3784 	qprocsoff(q);
3785 
3786 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3787 	conn_dev = (dev_t)RD(q)->q_ptr;
3788 	ASSERT(minor_arena != NULL);
3789 	ASSERT(conn_dev != 0);
3790 	inet_minor_free(minor_arena, conn_dev);
3791 	q->q_ptr = WR(q)->q_ptr = NULL;
3792 	return (0);
3793 }
3794 
3795 /*
3796  * Called by tcp_close() routine via squeue when lingering is
3797  * interrupted by a signal.
3798  */
3799 
3800 /* ARGSUSED */
3801 static void
3802 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3803 {
3804 	conn_t	*connp = (conn_t *)arg;
3805 	tcp_t	*tcp = connp->conn_tcp;
3806 
3807 	freeb(mp);
3808 	if (tcp->tcp_linger_tid != 0 &&
3809 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3810 		tcp_stop_lingering(tcp);
3811 		tcp->tcp_client_errno = EINTR;
3812 	}
3813 }
3814 
3815 /*
3816  * Called by streams close routine via squeues when our client blows off her
3817  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3818  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3819  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3820  * acked.
3821  *
3822  * NOTE: tcp_close potentially returns error when lingering.
3823  * However, the stream head currently does not pass these errors
3824  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3825  * errors to the application (from tsleep()) and not errors
3826  * like ECONNRESET caused by receiving a reset packet.
3827  */
3828 
3829 /* ARGSUSED */
3830 static void
3831 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3832 {
3833 	char	*msg;
3834 	conn_t	*connp = (conn_t *)arg;
3835 	tcp_t	*tcp = connp->conn_tcp;
3836 	clock_t	delta = 0;
3837 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3838 
3839 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3840 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3841 
3842 	mutex_enter(&tcp->tcp_eager_lock);
3843 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3844 		/* Cleanup for listener */
3845 		tcp_eager_cleanup(tcp, 0);
3846 		tcp->tcp_wait_for_eagers = 1;
3847 	}
3848 	mutex_exit(&tcp->tcp_eager_lock);
3849 
3850 	connp->conn_mdt_ok = B_FALSE;
3851 	tcp->tcp_mdt = B_FALSE;
3852 
3853 	connp->conn_lso_ok = B_FALSE;
3854 	tcp->tcp_lso = B_FALSE;
3855 
3856 	msg = NULL;
3857 	switch (tcp->tcp_state) {
3858 	case TCPS_CLOSED:
3859 	case TCPS_IDLE:
3860 	case TCPS_BOUND:
3861 	case TCPS_LISTEN:
3862 		break;
3863 	case TCPS_SYN_SENT:
3864 		msg = "tcp_close, during connect";
3865 		break;
3866 	case TCPS_SYN_RCVD:
3867 		/*
3868 		 * Close during the connect 3-way handshake
3869 		 * but here there may or may not be pending data
3870 		 * already on queue. Process almost same as in
3871 		 * the ESTABLISHED state.
3872 		 */
3873 		/* FALLTHRU */
3874 	default:
3875 		if (tcp->tcp_fused)
3876 			tcp_unfuse(tcp);
3877 
3878 		/*
3879 		 * If SO_LINGER has set a zero linger time, abort the
3880 		 * connection with a reset.
3881 		 */
3882 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3883 			msg = "tcp_close, zero lingertime";
3884 			break;
3885 		}
3886 
3887 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3888 		/*
3889 		 * Abort connection if there is unread data queued.
3890 		 */
3891 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3892 			msg = "tcp_close, unread data";
3893 			break;
3894 		}
3895 		/*
3896 		 * tcp_hard_bound is now cleared thus all packets go through
3897 		 * tcp_lookup. This fact is used by tcp_detach below.
3898 		 *
3899 		 * We have done a qwait() above which could have possibly
3900 		 * drained more messages in turn causing transition to a
3901 		 * different state. Check whether we have to do the rest
3902 		 * of the processing or not.
3903 		 */
3904 		if (tcp->tcp_state <= TCPS_LISTEN)
3905 			break;
3906 
3907 		/*
3908 		 * Transmit the FIN before detaching the tcp_t.
3909 		 * After tcp_detach returns this queue/perimeter
3910 		 * no longer owns the tcp_t thus others can modify it.
3911 		 */
3912 		(void) tcp_xmit_end(tcp);
3913 
3914 		/*
3915 		 * If lingering on close then wait until the fin is acked,
3916 		 * the SO_LINGER time passes, or a reset is sent/received.
3917 		 */
3918 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3919 		    !(tcp->tcp_fin_acked) &&
3920 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3921 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3922 				tcp->tcp_client_errno = EWOULDBLOCK;
3923 			} else if (tcp->tcp_client_errno == 0) {
3924 
3925 				ASSERT(tcp->tcp_linger_tid == 0);
3926 
3927 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3928 				    tcp_close_linger_timeout,
3929 				    tcp->tcp_lingertime * hz);
3930 
3931 				/* tcp_close_linger_timeout will finish close */
3932 				if (tcp->tcp_linger_tid == 0)
3933 					tcp->tcp_client_errno = ENOSR;
3934 				else
3935 					return;
3936 			}
3937 
3938 			/*
3939 			 * Check if we need to detach or just close
3940 			 * the instance.
3941 			 */
3942 			if (tcp->tcp_state <= TCPS_LISTEN)
3943 				break;
3944 		}
3945 
3946 		/*
3947 		 * Make sure that no other thread will access the tcp_rq of
3948 		 * this instance (through lookups etc.) as tcp_rq will go
3949 		 * away shortly.
3950 		 */
3951 		tcp_acceptor_hash_remove(tcp);
3952 
3953 		mutex_enter(&tcp->tcp_non_sq_lock);
3954 		if (tcp->tcp_flow_stopped) {
3955 			tcp_clrqfull(tcp);
3956 		}
3957 		mutex_exit(&tcp->tcp_non_sq_lock);
3958 
3959 		if (tcp->tcp_timer_tid != 0) {
3960 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3961 			tcp->tcp_timer_tid = 0;
3962 		}
3963 		/*
3964 		 * Need to cancel those timers which will not be used when
3965 		 * TCP is detached.  This has to be done before the tcp_wq
3966 		 * is set to the global queue.
3967 		 */
3968 		tcp_timers_stop(tcp);
3969 
3970 		tcp->tcp_detached = B_TRUE;
3971 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3972 			tcp_time_wait_append(tcp);
3973 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3974 			ASSERT(connp->conn_ref >= 3);
3975 			goto finish;
3976 		}
3977 
3978 		/*
3979 		 * If delta is zero the timer event wasn't executed and was
3980 		 * successfully canceled. In this case we need to restart it
3981 		 * with the minimal delta possible.
3982 		 */
3983 		if (delta >= 0)
3984 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3985 			    delta ? delta : 1);
3986 
3987 		ASSERT(connp->conn_ref >= 3);
3988 		goto finish;
3989 	}
3990 
3991 	/* Detach did not complete. Still need to remove q from stream. */
3992 	if (msg) {
3993 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3994 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3995 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3996 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3997 		    tcp->tcp_state == TCPS_SYN_RCVD)
3998 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3999 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4000 	}
4001 
4002 	tcp_closei_local(tcp);
4003 	CONN_DEC_REF(connp);
4004 	ASSERT(connp->conn_ref >= 2);
4005 
4006 finish:
4007 	/*
4008 	 * Although packets are always processed on the correct
4009 	 * tcp's perimeter and access is serialized via squeue's,
4010 	 * IP still needs a queue when sending packets in time_wait
4011 	 * state so use WR(tcps_g_q) till ip_output() can be
4012 	 * changed to deal with just connp. For read side, we
4013 	 * could have set tcp_rq to NULL but there are some cases
4014 	 * in tcp_rput_data() from early days of this code which
4015 	 * do a putnext without checking if tcp is closed. Those
4016 	 * need to be identified before both tcp_rq and tcp_wq
4017 	 * can be set to NULL and tcps_g_q can disappear forever.
4018 	 */
4019 	mutex_enter(&tcp->tcp_closelock);
4020 	/*
4021 	 * Don't change the queues in the case of a listener that has
4022 	 * eagers in its q or q0. It could surprise the eagers.
4023 	 * Instead wait for the eagers outside the squeue.
4024 	 */
4025 	if (!tcp->tcp_wait_for_eagers) {
4026 		tcp->tcp_detached = B_TRUE;
4027 		/*
4028 		 * When default queue is closing we set tcps_g_q to NULL
4029 		 * after the close is done.
4030 		 */
4031 		ASSERT(tcps->tcps_g_q != NULL);
4032 		tcp->tcp_rq = tcps->tcps_g_q;
4033 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4034 	}
4035 
4036 	/* Signal tcp_close() to finish closing. */
4037 	tcp->tcp_closed = 1;
4038 	cv_signal(&tcp->tcp_closecv);
4039 	mutex_exit(&tcp->tcp_closelock);
4040 }
4041 
4042 /*
4043  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4044  * Some stream heads get upset if they see these later on as anything but NULL.
4045  */
4046 static void
4047 tcp_close_mpp(mblk_t **mpp)
4048 {
4049 	mblk_t	*mp;
4050 
4051 	if ((mp = *mpp) != NULL) {
4052 		do {
4053 			mp->b_next = NULL;
4054 			mp->b_prev = NULL;
4055 		} while ((mp = mp->b_cont) != NULL);
4056 
4057 		mp = *mpp;
4058 		*mpp = NULL;
4059 		freemsg(mp);
4060 	}
4061 }
4062 
4063 /* Do detached close. */
4064 static void
4065 tcp_close_detached(tcp_t *tcp)
4066 {
4067 	if (tcp->tcp_fused)
4068 		tcp_unfuse(tcp);
4069 
4070 	/*
4071 	 * Clustering code serializes TCP disconnect callbacks and
4072 	 * cluster tcp list walks by blocking a TCP disconnect callback
4073 	 * if a cluster tcp list walk is in progress. This ensures
4074 	 * accurate accounting of TCPs in the cluster code even though
4075 	 * the TCP list walk itself is not atomic.
4076 	 */
4077 	tcp_closei_local(tcp);
4078 	CONN_DEC_REF(tcp->tcp_connp);
4079 }
4080 
4081 /*
4082  * Stop all TCP timers, and free the timer mblks if requested.
4083  */
4084 void
4085 tcp_timers_stop(tcp_t *tcp)
4086 {
4087 	if (tcp->tcp_timer_tid != 0) {
4088 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4089 		tcp->tcp_timer_tid = 0;
4090 	}
4091 	if (tcp->tcp_ka_tid != 0) {
4092 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4093 		tcp->tcp_ka_tid = 0;
4094 	}
4095 	if (tcp->tcp_ack_tid != 0) {
4096 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4097 		tcp->tcp_ack_tid = 0;
4098 	}
4099 	if (tcp->tcp_push_tid != 0) {
4100 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4101 		tcp->tcp_push_tid = 0;
4102 	}
4103 }
4104 
4105 /*
4106  * The tcp_t is going away. Remove it from all lists and set it
4107  * to TCPS_CLOSED. The freeing up of memory is deferred until
4108  * tcp_inactive. This is needed since a thread in tcp_rput might have
4109  * done a CONN_INC_REF on this structure before it was removed from the
4110  * hashes.
4111  */
4112 static void
4113 tcp_closei_local(tcp_t *tcp)
4114 {
4115 	ire_t 	*ire;
4116 	conn_t	*connp = tcp->tcp_connp;
4117 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4118 
4119 	if (!TCP_IS_SOCKET(tcp))
4120 		tcp_acceptor_hash_remove(tcp);
4121 
4122 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4123 	tcp->tcp_ibsegs = 0;
4124 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4125 	tcp->tcp_obsegs = 0;
4126 
4127 	/*
4128 	 * If we are an eager connection hanging off a listener that
4129 	 * hasn't formally accepted the connection yet, get off his
4130 	 * list and blow off any data that we have accumulated.
4131 	 */
4132 	if (tcp->tcp_listener != NULL) {
4133 		tcp_t	*listener = tcp->tcp_listener;
4134 		mutex_enter(&listener->tcp_eager_lock);
4135 		/*
4136 		 * tcp_tconnind_started == B_TRUE means that the
4137 		 * conn_ind has already gone to listener. At
4138 		 * this point, eager will be closed but we
4139 		 * leave it in listeners eager list so that
4140 		 * if listener decides to close without doing
4141 		 * accept, we can clean this up. In tcp_wput_accept
4142 		 * we take care of the case of accept on closed
4143 		 * eager.
4144 		 */
4145 		if (!tcp->tcp_tconnind_started) {
4146 			tcp_eager_unlink(tcp);
4147 			mutex_exit(&listener->tcp_eager_lock);
4148 			/*
4149 			 * We don't want to have any pointers to the
4150 			 * listener queue, after we have released our
4151 			 * reference on the listener
4152 			 */
4153 			ASSERT(tcps->tcps_g_q != NULL);
4154 			tcp->tcp_rq = tcps->tcps_g_q;
4155 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4156 			CONN_DEC_REF(listener->tcp_connp);
4157 		} else {
4158 			mutex_exit(&listener->tcp_eager_lock);
4159 		}
4160 	}
4161 
4162 	/* Stop all the timers */
4163 	tcp_timers_stop(tcp);
4164 
4165 	if (tcp->tcp_state == TCPS_LISTEN) {
4166 		if (tcp->tcp_ip_addr_cache) {
4167 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4168 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4169 			tcp->tcp_ip_addr_cache = NULL;
4170 		}
4171 	}
4172 	mutex_enter(&tcp->tcp_non_sq_lock);
4173 	if (tcp->tcp_flow_stopped)
4174 		tcp_clrqfull(tcp);
4175 	mutex_exit(&tcp->tcp_non_sq_lock);
4176 
4177 	tcp_bind_hash_remove(tcp);
4178 	/*
4179 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4180 	 * is trying to remove this tcp from the time wait list, we will
4181 	 * block in tcp_time_wait_remove while trying to acquire the
4182 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4183 	 * requires the ipcl_hash_remove to be ordered after the
4184 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4185 	 */
4186 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4187 		(void) tcp_time_wait_remove(tcp, NULL);
4188 	CL_INET_DISCONNECT(connp, tcp);
4189 	ipcl_hash_remove(connp);
4190 
4191 	/*
4192 	 * Delete the cached ire in conn_ire_cache and also mark
4193 	 * the conn as CONDEMNED
4194 	 */
4195 	mutex_enter(&connp->conn_lock);
4196 	connp->conn_state_flags |= CONN_CONDEMNED;
4197 	ire = connp->conn_ire_cache;
4198 	connp->conn_ire_cache = NULL;
4199 	mutex_exit(&connp->conn_lock);
4200 	if (ire != NULL)
4201 		IRE_REFRELE_NOTR(ire);
4202 
4203 	/* Need to cleanup any pending ioctls */
4204 	ASSERT(tcp->tcp_time_wait_next == NULL);
4205 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4206 	ASSERT(tcp->tcp_time_wait_expire == 0);
4207 	tcp->tcp_state = TCPS_CLOSED;
4208 
4209 	/* Release any SSL context */
4210 	if (tcp->tcp_kssl_ent != NULL) {
4211 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4212 		tcp->tcp_kssl_ent = NULL;
4213 	}
4214 	if (tcp->tcp_kssl_ctx != NULL) {
4215 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4216 		tcp->tcp_kssl_ctx = NULL;
4217 	}
4218 	tcp->tcp_kssl_pending = B_FALSE;
4219 
4220 	tcp_ipsec_cleanup(tcp);
4221 }
4222 
4223 /*
4224  * tcp is dying (called from ipcl_conn_destroy and error cases).
4225  * Free the tcp_t in either case.
4226  */
4227 void
4228 tcp_free(tcp_t *tcp)
4229 {
4230 	mblk_t	*mp;
4231 	ip6_pkt_t	*ipp;
4232 
4233 	ASSERT(tcp != NULL);
4234 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4235 
4236 	tcp->tcp_rq = NULL;
4237 	tcp->tcp_wq = NULL;
4238 
4239 	tcp_close_mpp(&tcp->tcp_xmit_head);
4240 	tcp_close_mpp(&tcp->tcp_reass_head);
4241 	if (tcp->tcp_rcv_list != NULL) {
4242 		/* Free b_next chain */
4243 		tcp_close_mpp(&tcp->tcp_rcv_list);
4244 	}
4245 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4246 		freemsg(mp);
4247 	}
4248 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4249 		freemsg(mp);
4250 	}
4251 
4252 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4253 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4254 		freeb(tcp->tcp_fused_sigurg_mp);
4255 		tcp->tcp_fused_sigurg_mp = NULL;
4256 	}
4257 
4258 	if (tcp->tcp_ordrel_mp != NULL) {
4259 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4260 		freeb(tcp->tcp_ordrel_mp);
4261 		tcp->tcp_ordrel_mp = NULL;
4262 	}
4263 
4264 	if (tcp->tcp_sack_info != NULL) {
4265 		if (tcp->tcp_notsack_list != NULL) {
4266 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
4267 			    tcp);
4268 		}
4269 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4270 	}
4271 
4272 	if (tcp->tcp_hopopts != NULL) {
4273 		mi_free(tcp->tcp_hopopts);
4274 		tcp->tcp_hopopts = NULL;
4275 		tcp->tcp_hopoptslen = 0;
4276 	}
4277 	ASSERT(tcp->tcp_hopoptslen == 0);
4278 	if (tcp->tcp_dstopts != NULL) {
4279 		mi_free(tcp->tcp_dstopts);
4280 		tcp->tcp_dstopts = NULL;
4281 		tcp->tcp_dstoptslen = 0;
4282 	}
4283 	ASSERT(tcp->tcp_dstoptslen == 0);
4284 	if (tcp->tcp_rtdstopts != NULL) {
4285 		mi_free(tcp->tcp_rtdstopts);
4286 		tcp->tcp_rtdstopts = NULL;
4287 		tcp->tcp_rtdstoptslen = 0;
4288 	}
4289 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4290 	if (tcp->tcp_rthdr != NULL) {
4291 		mi_free(tcp->tcp_rthdr);
4292 		tcp->tcp_rthdr = NULL;
4293 		tcp->tcp_rthdrlen = 0;
4294 	}
4295 	ASSERT(tcp->tcp_rthdrlen == 0);
4296 
4297 	ipp = &tcp->tcp_sticky_ipp;
4298 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4299 	    IPPF_RTHDR))
4300 		ip6_pkt_free(ipp);
4301 
4302 	/*
4303 	 * Free memory associated with the tcp/ip header template.
4304 	 */
4305 
4306 	if (tcp->tcp_iphc != NULL)
4307 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4308 
4309 	/*
4310 	 * Following is really a blowing away a union.
4311 	 * It happens to have exactly two members of identical size
4312 	 * the following code is enough.
4313 	 */
4314 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4315 }
4316 
4317 
4318 /*
4319  * Put a connection confirmation message upstream built from the
4320  * address information within 'iph' and 'tcph'.  Report our success or failure.
4321  */
4322 static boolean_t
4323 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4324     mblk_t **defermp)
4325 {
4326 	sin_t	sin;
4327 	sin6_t	sin6;
4328 	mblk_t	*mp;
4329 	char	*optp = NULL;
4330 	int	optlen = 0;
4331 
4332 	if (defermp != NULL)
4333 		*defermp = NULL;
4334 
4335 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4336 		/*
4337 		 * Return in T_CONN_CON results of option negotiation through
4338 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4339 		 * negotiation, then what is received from remote end needs
4340 		 * to be taken into account but there is no such thing (yet?)
4341 		 * in our TCP/IP.
4342 		 * Note: We do not use mi_offset_param() here as
4343 		 * tcp_opts_conn_req contents do not directly come from
4344 		 * an application and are either generated in kernel or
4345 		 * from user input that was already verified.
4346 		 */
4347 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4348 		optp = (char *)(mp->b_rptr +
4349 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4350 		optlen = (int)
4351 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4352 	}
4353 
4354 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4355 		ipha_t *ipha = (ipha_t *)iphdr;
4356 
4357 		/* packet is IPv4 */
4358 		if (tcp->tcp_family == AF_INET) {
4359 			sin = sin_null;
4360 			sin.sin_addr.s_addr = ipha->ipha_src;
4361 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4362 			sin.sin_family = AF_INET;
4363 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4364 			    (int)sizeof (sin_t), optp, optlen);
4365 		} else {
4366 			sin6 = sin6_null;
4367 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4368 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4369 			sin6.sin6_family = AF_INET6;
4370 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4371 			    (int)sizeof (sin6_t), optp, optlen);
4372 
4373 		}
4374 	} else {
4375 		ip6_t	*ip6h = (ip6_t *)iphdr;
4376 
4377 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4378 		ASSERT(tcp->tcp_family == AF_INET6);
4379 		sin6 = sin6_null;
4380 		sin6.sin6_addr = ip6h->ip6_src;
4381 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4382 		sin6.sin6_family = AF_INET6;
4383 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4384 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4385 		    (int)sizeof (sin6_t), optp, optlen);
4386 	}
4387 
4388 	if (!mp)
4389 		return (B_FALSE);
4390 
4391 	mblk_copycred(mp, idmp);
4392 
4393 	if (defermp == NULL) {
4394 		conn_t *connp = tcp->tcp_connp;
4395 		if (IPCL_IS_NONSTR(connp)) {
4396 			cred_t *cr;
4397 			pid_t cpid;
4398 
4399 			cr = msg_getcred(mp, &cpid);
4400 			(*connp->conn_upcalls->su_connected)
4401 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4402 			    cpid);
4403 			freemsg(mp);
4404 		} else {
4405 			putnext(tcp->tcp_rq, mp);
4406 		}
4407 	} else {
4408 		*defermp = mp;
4409 	}
4410 
4411 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4412 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4413 	return (B_TRUE);
4414 }
4415 
4416 /*
4417  * Defense for the SYN attack -
4418  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4419  *    one from the list of droppable eagers. This list is a subset of q0.
4420  *    see comments before the definition of MAKE_DROPPABLE().
4421  * 2. Don't drop a SYN request before its first timeout. This gives every
4422  *    request at least til the first timeout to complete its 3-way handshake.
4423  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4424  *    requests currently on the queue that has timed out. This will be used
4425  *    as an indicator of whether an attack is under way, so that appropriate
4426  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4427  *    either when eager goes into ESTABLISHED, or gets freed up.)
4428  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4429  *    # of timeout drops back to <= q0len/32 => SYN alert off
4430  */
4431 static boolean_t
4432 tcp_drop_q0(tcp_t *tcp)
4433 {
4434 	tcp_t	*eager;
4435 	mblk_t	*mp;
4436 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4437 
4438 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4439 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4440 
4441 	/* Pick oldest eager from the list of droppable eagers */
4442 	eager = tcp->tcp_eager_prev_drop_q0;
4443 
4444 	/* If list is empty. return B_FALSE */
4445 	if (eager == tcp) {
4446 		return (B_FALSE);
4447 	}
4448 
4449 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4450 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4451 		return (B_FALSE);
4452 
4453 	/*
4454 	 * Take this eager out from the list of droppable eagers since we are
4455 	 * going to drop it.
4456 	 */
4457 	MAKE_UNDROPPABLE(eager);
4458 
4459 	if (tcp->tcp_debug) {
4460 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4461 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4462 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4463 		    tcp->tcp_conn_req_cnt_q0,
4464 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4465 	}
4466 
4467 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4468 
4469 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4470 	CONN_INC_REF(eager->tcp_connp);
4471 
4472 	/* Mark the IRE created for this SYN request temporary */
4473 	tcp_ip_ire_mark_advice(eager);
4474 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4475 	    tcp_clean_death_wrapper, eager->tcp_connp,
4476 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4477 
4478 	return (B_TRUE);
4479 }
4480 
4481 int
4482 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4483     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4484 {
4485 	tcp_t 		*ltcp = lconnp->conn_tcp;
4486 	tcp_t		*tcp = connp->conn_tcp;
4487 	mblk_t		*tpi_mp;
4488 	ipha_t		*ipha;
4489 	ip6_t		*ip6h;
4490 	sin6_t 		sin6;
4491 	in6_addr_t 	v6dst;
4492 	int		err;
4493 	int		ifindex = 0;
4494 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4495 
4496 	if (ipvers == IPV4_VERSION) {
4497 		ipha = (ipha_t *)mp->b_rptr;
4498 
4499 		connp->conn_send = ip_output;
4500 		connp->conn_recv = tcp_input;
4501 
4502 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4503 		    &connp->conn_bound_source_v6);
4504 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4505 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4506 
4507 		sin6 = sin6_null;
4508 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4509 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4510 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4511 		sin6.sin6_family = AF_INET6;
4512 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4513 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4514 		if (tcp->tcp_recvdstaddr) {
4515 			sin6_t	sin6d;
4516 
4517 			sin6d = sin6_null;
4518 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4519 			    &sin6d.sin6_addr);
4520 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4521 			sin6d.sin6_family = AF_INET;
4522 			tpi_mp = mi_tpi_extconn_ind(NULL,
4523 			    (char *)&sin6d, sizeof (sin6_t),
4524 			    (char *)&tcp,
4525 			    (t_scalar_t)sizeof (intptr_t),
4526 			    (char *)&sin6d, sizeof (sin6_t),
4527 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4528 		} else {
4529 			tpi_mp = mi_tpi_conn_ind(NULL,
4530 			    (char *)&sin6, sizeof (sin6_t),
4531 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4532 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4533 		}
4534 	} else {
4535 		ip6h = (ip6_t *)mp->b_rptr;
4536 
4537 		connp->conn_send = ip_output_v6;
4538 		connp->conn_recv = tcp_input;
4539 
4540 		connp->conn_bound_source_v6 = ip6h->ip6_dst;
4541 		connp->conn_srcv6 = ip6h->ip6_dst;
4542 		connp->conn_remv6 = ip6h->ip6_src;
4543 
4544 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4545 		ifindex = (int)DB_CKSUMSTUFF(mp);
4546 		DB_CKSUMSTUFF(mp) = 0;
4547 
4548 		sin6 = sin6_null;
4549 		sin6.sin6_addr = ip6h->ip6_src;
4550 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4551 		sin6.sin6_family = AF_INET6;
4552 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4553 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4554 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4555 
4556 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4557 			/* Pass up the scope_id of remote addr */
4558 			sin6.sin6_scope_id = ifindex;
4559 		} else {
4560 			sin6.sin6_scope_id = 0;
4561 		}
4562 		if (tcp->tcp_recvdstaddr) {
4563 			sin6_t	sin6d;
4564 
4565 			sin6d = sin6_null;
4566 			sin6.sin6_addr = ip6h->ip6_dst;
4567 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4568 			sin6d.sin6_family = AF_INET;
4569 			tpi_mp = mi_tpi_extconn_ind(NULL,
4570 			    (char *)&sin6d, sizeof (sin6_t),
4571 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4572 			    (char *)&sin6d, sizeof (sin6_t),
4573 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4574 		} else {
4575 			tpi_mp = mi_tpi_conn_ind(NULL,
4576 			    (char *)&sin6, sizeof (sin6_t),
4577 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4578 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4579 		}
4580 	}
4581 
4582 	if (tpi_mp == NULL)
4583 		return (ENOMEM);
4584 
4585 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4586 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4587 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4588 	connp->conn_fully_bound = B_FALSE;
4589 
4590 	/* Inherit information from the "parent" */
4591 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4592 	tcp->tcp_family = ltcp->tcp_family;
4593 
4594 	tcp->tcp_wq = ltcp->tcp_wq;
4595 	tcp->tcp_rq = ltcp->tcp_rq;
4596 
4597 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4598 	tcp->tcp_detached = B_TRUE;
4599 	SOCK_CONNID_INIT(tcp->tcp_connid);
4600 	if ((err = tcp_init_values(tcp)) != 0) {
4601 		freemsg(tpi_mp);
4602 		return (err);
4603 	}
4604 
4605 	if (ipvers == IPV4_VERSION) {
4606 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4607 			freemsg(tpi_mp);
4608 			return (err);
4609 		}
4610 		ASSERT(tcp->tcp_ipha != NULL);
4611 	} else {
4612 		/* ifindex must be already set */
4613 		ASSERT(ifindex != 0);
4614 
4615 		if (ltcp->tcp_bound_if != 0)
4616 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4617 		else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src))
4618 			tcp->tcp_bound_if = ifindex;
4619 
4620 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4621 		tcp->tcp_recvifindex = 0;
4622 		tcp->tcp_recvhops = 0xffffffffU;
4623 		ASSERT(tcp->tcp_ip6h != NULL);
4624 	}
4625 
4626 	tcp->tcp_lport = ltcp->tcp_lport;
4627 
4628 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4629 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4630 			/*
4631 			 * Listener had options of some sort; eager inherits.
4632 			 * Free up the eager template and allocate one
4633 			 * of the right size.
4634 			 */
4635 			if (tcp->tcp_hdr_grown) {
4636 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4637 			} else {
4638 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4639 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4640 			}
4641 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4642 			    KM_NOSLEEP);
4643 			if (tcp->tcp_iphc == NULL) {
4644 				tcp->tcp_iphc_len = 0;
4645 				freemsg(tpi_mp);
4646 				return (ENOMEM);
4647 			}
4648 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4649 			tcp->tcp_hdr_grown = B_TRUE;
4650 		}
4651 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4652 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4653 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4654 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4655 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4656 
4657 		/*
4658 		 * Copy the IP+TCP header template from listener to eager
4659 		 */
4660 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4661 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4662 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4663 			    IPPROTO_RAW) {
4664 				tcp->tcp_ip6h =
4665 				    (ip6_t *)(tcp->tcp_iphc +
4666 				    sizeof (ip6i_t));
4667 			} else {
4668 				tcp->tcp_ip6h =
4669 				    (ip6_t *)(tcp->tcp_iphc);
4670 			}
4671 			tcp->tcp_ipha = NULL;
4672 		} else {
4673 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4674 			tcp->tcp_ip6h = NULL;
4675 		}
4676 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4677 		    tcp->tcp_ip_hdr_len);
4678 	} else {
4679 		/*
4680 		 * only valid case when ipversion of listener and
4681 		 * eager differ is when listener is IPv6 and
4682 		 * eager is IPv4.
4683 		 * Eager header template has been initialized to the
4684 		 * maximum v4 header sizes, which includes space for
4685 		 * TCP and IP options.
4686 		 */
4687 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4688 		    (tcp->tcp_ipversion == IPV4_VERSION));
4689 		ASSERT(tcp->tcp_iphc_len >=
4690 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4691 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4692 		/* copy IP header fields individually */
4693 		tcp->tcp_ipha->ipha_ttl =
4694 		    ltcp->tcp_ip6h->ip6_hops;
4695 		bcopy(ltcp->tcp_tcph->th_lport,
4696 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4697 	}
4698 
4699 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4700 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4701 	    sizeof (in_port_t));
4702 
4703 	if (ltcp->tcp_lport == 0) {
4704 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4705 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4706 		    sizeof (in_port_t));
4707 	}
4708 
4709 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4710 		ASSERT(ipha != NULL);
4711 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4712 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4713 
4714 		/* Source routing option copyover (reverse it) */
4715 		if (tcps->tcps_rev_src_routes)
4716 			tcp_opt_reverse(tcp, ipha);
4717 	} else {
4718 		ASSERT(ip6h != NULL);
4719 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4720 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4721 	}
4722 
4723 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4724 	ASSERT(!tcp->tcp_tconnind_started);
4725 	/*
4726 	 * If the SYN contains a credential, it's a loopback packet; attach
4727 	 * the credential to the TPI message.
4728 	 */
4729 	mblk_copycred(tpi_mp, idmp);
4730 
4731 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4732 
4733 	/* Inherit the listener's SSL protection state */
4734 
4735 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4736 		kssl_hold_ent(tcp->tcp_kssl_ent);
4737 		tcp->tcp_kssl_pending = B_TRUE;
4738 	}
4739 
4740 	/* Inherit the listener's non-STREAMS flag */
4741 	if (IPCL_IS_NONSTR(lconnp)) {
4742 		connp->conn_flags |= IPCL_NONSTR;
4743 	}
4744 
4745 	return (0);
4746 }
4747 
4748 
4749 int
4750 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4751     tcph_t *tcph, mblk_t *idmp)
4752 {
4753 	tcp_t 		*ltcp = lconnp->conn_tcp;
4754 	tcp_t		*tcp = connp->conn_tcp;
4755 	sin_t		sin;
4756 	mblk_t		*tpi_mp = NULL;
4757 	int		err;
4758 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4759 
4760 	sin = sin_null;
4761 	sin.sin_addr.s_addr = ipha->ipha_src;
4762 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4763 	sin.sin_family = AF_INET;
4764 	if (ltcp->tcp_recvdstaddr) {
4765 		sin_t	sind;
4766 
4767 		sind = sin_null;
4768 		sind.sin_addr.s_addr = ipha->ipha_dst;
4769 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4770 		sind.sin_family = AF_INET;
4771 		tpi_mp = mi_tpi_extconn_ind(NULL,
4772 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4773 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4774 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4775 	} else {
4776 		tpi_mp = mi_tpi_conn_ind(NULL,
4777 		    (char *)&sin, sizeof (sin_t),
4778 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4779 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4780 	}
4781 
4782 	if (tpi_mp == NULL) {
4783 		return (ENOMEM);
4784 	}
4785 
4786 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4787 	connp->conn_send = ip_output;
4788 	connp->conn_recv = tcp_input;
4789 	connp->conn_fully_bound = B_FALSE;
4790 
4791 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4792 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4793 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4794 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4795 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4796 
4797 	/* Inherit information from the "parent" */
4798 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4799 	tcp->tcp_family = ltcp->tcp_family;
4800 	tcp->tcp_wq = ltcp->tcp_wq;
4801 	tcp->tcp_rq = ltcp->tcp_rq;
4802 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4803 	tcp->tcp_detached = B_TRUE;
4804 	SOCK_CONNID_INIT(tcp->tcp_connid);
4805 	if ((err = tcp_init_values(tcp)) != 0) {
4806 		freemsg(tpi_mp);
4807 		return (err);
4808 	}
4809 
4810 	/*
4811 	 * Let's make sure that eager tcp template has enough space to
4812 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4813 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4814 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4815 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4816 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4817 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4818 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4819 	 */
4820 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4821 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4822 
4823 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4824 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4825 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4826 	tcp->tcp_ttl = ltcp->tcp_ttl;
4827 	tcp->tcp_tos = ltcp->tcp_tos;
4828 
4829 	/* Copy the IP+TCP header template from listener to eager */
4830 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4831 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4832 	tcp->tcp_ip6h = NULL;
4833 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4834 	    tcp->tcp_ip_hdr_len);
4835 
4836 	/* Initialize the IP addresses and Ports */
4837 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4838 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4839 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4840 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4841 
4842 	/* Source routing option copyover (reverse it) */
4843 	if (tcps->tcps_rev_src_routes)
4844 		tcp_opt_reverse(tcp, ipha);
4845 
4846 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4847 	ASSERT(!tcp->tcp_tconnind_started);
4848 
4849 	/*
4850 	 * If the SYN contains a credential, it's a loopback packet; attach
4851 	 * the credential to the TPI message.
4852 	 */
4853 	mblk_copycred(tpi_mp, idmp);
4854 
4855 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4856 
4857 	/* Inherit the listener's SSL protection state */
4858 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4859 		kssl_hold_ent(tcp->tcp_kssl_ent);
4860 		tcp->tcp_kssl_pending = B_TRUE;
4861 	}
4862 
4863 	/* Inherit the listener's non-STREAMS flag */
4864 	if (IPCL_IS_NONSTR(lconnp)) {
4865 		connp->conn_flags |= IPCL_NONSTR;
4866 	}
4867 
4868 	return (0);
4869 }
4870 
4871 /*
4872  * sets up conn for ipsec.
4873  * if the first mblk is M_CTL it is consumed and mpp is updated.
4874  * in case of error mpp is freed.
4875  */
4876 conn_t *
4877 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4878 {
4879 	conn_t 		*connp = tcp->tcp_connp;
4880 	conn_t 		*econnp;
4881 	squeue_t 	*new_sqp;
4882 	mblk_t 		*first_mp = *mpp;
4883 	mblk_t		*mp = *mpp;
4884 	boolean_t	mctl_present = B_FALSE;
4885 	uint_t		ipvers;
4886 
4887 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4888 	if (econnp == NULL) {
4889 		freemsg(first_mp);
4890 		return (NULL);
4891 	}
4892 	if (DB_TYPE(mp) == M_CTL) {
4893 		if (mp->b_cont == NULL ||
4894 		    mp->b_cont->b_datap->db_type != M_DATA) {
4895 			freemsg(first_mp);
4896 			return (NULL);
4897 		}
4898 		mp = mp->b_cont;
4899 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4900 			freemsg(first_mp);
4901 			return (NULL);
4902 		}
4903 
4904 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4905 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4906 		mctl_present = B_TRUE;
4907 	} else {
4908 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4909 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4910 	}
4911 
4912 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4913 	DB_CKSUMSTART(mp) = 0;
4914 
4915 	ASSERT(OK_32PTR(mp->b_rptr));
4916 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4917 	if (ipvers == IPV4_VERSION) {
4918 		uint16_t  	*up;
4919 		uint32_t	ports;
4920 		ipha_t		*ipha;
4921 
4922 		ipha = (ipha_t *)mp->b_rptr;
4923 		up = (uint16_t *)((uchar_t *)ipha +
4924 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4925 		ports = *(uint32_t *)up;
4926 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4927 		    ipha->ipha_dst, ipha->ipha_src, ports);
4928 	} else {
4929 		uint16_t  	*up;
4930 		uint32_t	ports;
4931 		uint16_t	ip_hdr_len;
4932 		uint8_t		*nexthdrp;
4933 		ip6_t 		*ip6h;
4934 		tcph_t		*tcph;
4935 
4936 		ip6h = (ip6_t *)mp->b_rptr;
4937 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4938 			ip_hdr_len = IPV6_HDR_LEN;
4939 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4940 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4941 			CONN_DEC_REF(econnp);
4942 			freemsg(first_mp);
4943 			return (NULL);
4944 		}
4945 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4946 		up = (uint16_t *)tcph->th_lport;
4947 		ports = *(uint32_t *)up;
4948 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4949 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4950 	}
4951 
4952 	/*
4953 	 * The caller already ensured that there is a sqp present.
4954 	 */
4955 	econnp->conn_sqp = new_sqp;
4956 	econnp->conn_initial_sqp = new_sqp;
4957 
4958 	if (connp->conn_policy != NULL) {
4959 		ipsec_in_t *ii;
4960 		ii = (ipsec_in_t *)(first_mp->b_rptr);
4961 		ASSERT(ii->ipsec_in_policy == NULL);
4962 		IPPH_REFHOLD(connp->conn_policy);
4963 		ii->ipsec_in_policy = connp->conn_policy;
4964 
4965 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
4966 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
4967 			CONN_DEC_REF(econnp);
4968 			freemsg(first_mp);
4969 			return (NULL);
4970 		}
4971 	}
4972 
4973 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
4974 		CONN_DEC_REF(econnp);
4975 		freemsg(first_mp);
4976 		return (NULL);
4977 	}
4978 
4979 	/*
4980 	 * If we know we have some policy, pass the "IPSEC"
4981 	 * options size TCP uses this adjust the MSS.
4982 	 */
4983 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
4984 	if (mctl_present) {
4985 		freeb(first_mp);
4986 		*mpp = mp;
4987 	}
4988 
4989 	return (econnp);
4990 }
4991 
4992 /*
4993  * tcp_get_conn/tcp_free_conn
4994  *
4995  * tcp_get_conn is used to get a clean tcp connection structure.
4996  * It tries to reuse the connections put on the freelist by the
4997  * time_wait_collector failing which it goes to kmem_cache. This
4998  * way has two benefits compared to just allocating from and
4999  * freeing to kmem_cache.
5000  * 1) The time_wait_collector can free (which includes the cleanup)
5001  * outside the squeue. So when the interrupt comes, we have a clean
5002  * connection sitting in the freelist. Obviously, this buys us
5003  * performance.
5004  *
5005  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5006  * has multiple disadvantages - tying up the squeue during alloc, and the
5007  * fact that IPSec policy initialization has to happen here which
5008  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5009  * But allocating the conn/tcp in IP land is also not the best since
5010  * we can't check the 'q' and 'q0' which are protected by squeue and
5011  * blindly allocate memory which might have to be freed here if we are
5012  * not allowed to accept the connection. By using the freelist and
5013  * putting the conn/tcp back in freelist, we don't pay a penalty for
5014  * allocating memory without checking 'q/q0' and freeing it if we can't
5015  * accept the connection.
5016  *
5017  * Care should be taken to put the conn back in the same squeue's freelist
5018  * from which it was allocated. Best results are obtained if conn is
5019  * allocated from listener's squeue and freed to the same. Time wait
5020  * collector will free up the freelist is the connection ends up sitting
5021  * there for too long.
5022  */
5023 void *
5024 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5025 {
5026 	tcp_t			*tcp = NULL;
5027 	conn_t			*connp = NULL;
5028 	squeue_t		*sqp = (squeue_t *)arg;
5029 	tcp_squeue_priv_t 	*tcp_time_wait;
5030 	netstack_t		*ns;
5031 	mblk_t			*tcp_rsrv_mp = NULL;
5032 
5033 	tcp_time_wait =
5034 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5035 
5036 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5037 	tcp = tcp_time_wait->tcp_free_list;
5038 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5039 	if (tcp != NULL) {
5040 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5041 		tcp_time_wait->tcp_free_list_cnt--;
5042 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5043 		tcp->tcp_time_wait_next = NULL;
5044 		connp = tcp->tcp_connp;
5045 		connp->conn_flags |= IPCL_REUSED;
5046 
5047 		ASSERT(tcp->tcp_tcps == NULL);
5048 		ASSERT(connp->conn_netstack == NULL);
5049 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5050 		ns = tcps->tcps_netstack;
5051 		netstack_hold(ns);
5052 		connp->conn_netstack = ns;
5053 		tcp->tcp_tcps = tcps;
5054 		TCPS_REFHOLD(tcps);
5055 		ipcl_globalhash_insert(connp);
5056 		return ((void *)connp);
5057 	}
5058 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5059 	/*
5060 	 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
5061 	 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
5062 	 */
5063 	tcp_rsrv_mp = allocb(0, BPRI_HI);
5064 	if (tcp_rsrv_mp == NULL)
5065 		return (NULL);
5066 
5067 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5068 	    tcps->tcps_netstack)) == NULL) {
5069 		freeb(tcp_rsrv_mp);
5070 		return (NULL);
5071 	}
5072 
5073 	tcp = connp->conn_tcp;
5074 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
5075 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5076 
5077 	tcp->tcp_tcps = tcps;
5078 	TCPS_REFHOLD(tcps);
5079 
5080 	return ((void *)connp);
5081 }
5082 
5083 /*
5084  * Update the cached label for the given tcp_t.  This should be called once per
5085  * connection, and before any packets are sent or tcp_process_options is
5086  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5087  */
5088 static boolean_t
5089 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5090 {
5091 	conn_t *connp = tcp->tcp_connp;
5092 
5093 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5094 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5095 		int added;
5096 
5097 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5098 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5099 			return (B_FALSE);
5100 
5101 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5102 		if (added == -1)
5103 			return (B_FALSE);
5104 		tcp->tcp_hdr_len += added;
5105 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5106 		tcp->tcp_ip_hdr_len += added;
5107 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5108 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5109 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5110 			    tcp->tcp_hdr_len);
5111 			if (added == -1)
5112 				return (B_FALSE);
5113 			tcp->tcp_hdr_len += added;
5114 			tcp->tcp_tcph = (tcph_t *)
5115 			    ((uchar_t *)tcp->tcp_tcph + added);
5116 			tcp->tcp_ip_hdr_len += added;
5117 		}
5118 	} else {
5119 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5120 
5121 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5122 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5123 			return (B_FALSE);
5124 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5125 		    &tcp->tcp_label_len, optbuf) != 0)
5126 			return (B_FALSE);
5127 		if (tcp_build_hdrs(tcp) != 0)
5128 			return (B_FALSE);
5129 	}
5130 
5131 	connp->conn_ulp_labeled = 1;
5132 
5133 	return (B_TRUE);
5134 }
5135 
5136 /* BEGIN CSTYLED */
5137 /*
5138  *
5139  * The sockfs ACCEPT path:
5140  * =======================
5141  *
5142  * The eager is now established in its own perimeter as soon as SYN is
5143  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5144  * completes the accept processing on the acceptor STREAM. The sending
5145  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5146  * listener but a TLI/XTI listener completes the accept processing
5147  * on the listener perimeter.
5148  *
5149  * Common control flow for 3 way handshake:
5150  * ----------------------------------------
5151  *
5152  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5153  *					-> tcp_conn_request()
5154  *
5155  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5156  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5157  *
5158  * Sockfs ACCEPT Path:
5159  * -------------------
5160  *
5161  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5162  * as STREAM entry point)
5163  *
5164  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5165  *
5166  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5167  * association (we are not behind eager's squeue but sockfs is protecting us
5168  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5169  * is changed to point at tcp_wput().
5170  *
5171  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5172  * listener (done on listener's perimeter).
5173  *
5174  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5175  * accept.
5176  *
5177  * TLI/XTI client ACCEPT path:
5178  * ---------------------------
5179  *
5180  * soaccept() sends T_CONN_RES on the listener STREAM.
5181  *
5182  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5183  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5184  *
5185  * Locks:
5186  * ======
5187  *
5188  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5189  * and listeners->tcp_eager_next_q.
5190  *
5191  * Referencing:
5192  * ============
5193  *
5194  * 1) We start out in tcp_conn_request by eager placing a ref on
5195  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5196  *
5197  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5198  * doing so we place a ref on the eager. This ref is finally dropped at the
5199  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5200  * reference is dropped by the squeue framework.
5201  *
5202  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5203  *
5204  * The reference must be released by the same entity that added the reference
5205  * In the above scheme, the eager is the entity that adds and releases the
5206  * references. Note that tcp_accept_finish executes in the squeue of the eager
5207  * (albeit after it is attached to the acceptor stream). Though 1. executes
5208  * in the listener's squeue, the eager is nascent at this point and the
5209  * reference can be considered to have been added on behalf of the eager.
5210  *
5211  * Eager getting a Reset or listener closing:
5212  * ==========================================
5213  *
5214  * Once the listener and eager are linked, the listener never does the unlink.
5215  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5216  * a message on all eager perimeter. The eager then does the unlink, clears
5217  * any pointers to the listener's queue and drops the reference to the
5218  * listener. The listener waits in tcp_close outside the squeue until its
5219  * refcount has dropped to 1. This ensures that the listener has waited for
5220  * all eagers to clear their association with the listener.
5221  *
5222  * Similarly, if eager decides to go away, it can unlink itself and close.
5223  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5224  * the reference to eager is still valid because of the extra ref we put
5225  * in tcp_send_conn_ind.
5226  *
5227  * Listener can always locate the eager under the protection
5228  * of the listener->tcp_eager_lock, and then do a refhold
5229  * on the eager during the accept processing.
5230  *
5231  * The acceptor stream accesses the eager in the accept processing
5232  * based on the ref placed on eager before sending T_conn_ind.
5233  * The only entity that can negate this refhold is a listener close
5234  * which is mutually exclusive with an active acceptor stream.
5235  *
5236  * Eager's reference on the listener
5237  * ===================================
5238  *
5239  * If the accept happens (even on a closed eager) the eager drops its
5240  * reference on the listener at the start of tcp_accept_finish. If the
5241  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5242  * the reference is dropped in tcp_closei_local. If the listener closes,
5243  * the reference is dropped in tcp_eager_kill. In all cases the reference
5244  * is dropped while executing in the eager's context (squeue).
5245  */
5246 /* END CSTYLED */
5247 
5248 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5249 
5250 /*
5251  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5252  * tcp_rput_data will not see any SYN packets.
5253  */
5254 /* ARGSUSED */
5255 void
5256 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5257 {
5258 	tcph_t		*tcph;
5259 	uint32_t	seg_seq;
5260 	tcp_t		*eager;
5261 	uint_t		ipvers;
5262 	ipha_t		*ipha;
5263 	ip6_t		*ip6h;
5264 	int		err;
5265 	conn_t		*econnp = NULL;
5266 	squeue_t	*new_sqp;
5267 	mblk_t		*mp1;
5268 	uint_t 		ip_hdr_len;
5269 	conn_t		*connp = (conn_t *)arg;
5270 	tcp_t		*tcp = connp->conn_tcp;
5271 	cred_t		*credp;
5272 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5273 	ip_stack_t	*ipst;
5274 
5275 	if (tcp->tcp_state != TCPS_LISTEN)
5276 		goto error2;
5277 
5278 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5279 
5280 	mutex_enter(&tcp->tcp_eager_lock);
5281 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5282 		mutex_exit(&tcp->tcp_eager_lock);
5283 		TCP_STAT(tcps, tcp_listendrop);
5284 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5285 		if (tcp->tcp_debug) {
5286 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5287 			    "tcp_conn_request: listen backlog (max=%d) "
5288 			    "overflow (%d pending) on %s",
5289 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5290 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5291 		}
5292 		goto error2;
5293 	}
5294 
5295 	if (tcp->tcp_conn_req_cnt_q0 >=
5296 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5297 		/*
5298 		 * Q0 is full. Drop a pending half-open req from the queue
5299 		 * to make room for the new SYN req. Also mark the time we
5300 		 * drop a SYN.
5301 		 *
5302 		 * A more aggressive defense against SYN attack will
5303 		 * be to set the "tcp_syn_defense" flag now.
5304 		 */
5305 		TCP_STAT(tcps, tcp_listendropq0);
5306 		tcp->tcp_last_rcv_lbolt = lbolt64;
5307 		if (!tcp_drop_q0(tcp)) {
5308 			mutex_exit(&tcp->tcp_eager_lock);
5309 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5310 			if (tcp->tcp_debug) {
5311 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5312 				    "tcp_conn_request: listen half-open queue "
5313 				    "(max=%d) full (%d pending) on %s",
5314 				    tcps->tcps_conn_req_max_q0,
5315 				    tcp->tcp_conn_req_cnt_q0,
5316 				    tcp_display(tcp, NULL,
5317 				    DISP_PORT_ONLY));
5318 			}
5319 			goto error2;
5320 		}
5321 	}
5322 	mutex_exit(&tcp->tcp_eager_lock);
5323 
5324 	/*
5325 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5326 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5327 	 * link local address.  If IPSec is enabled, db_struioflag has
5328 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5329 	 * otherwise an error case if neither of them is set.
5330 	 */
5331 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5332 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5333 		DB_CKSUMSTART(mp) = 0;
5334 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5335 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5336 		if (econnp == NULL)
5337 			goto error2;
5338 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5339 		econnp->conn_sqp = new_sqp;
5340 		econnp->conn_initial_sqp = new_sqp;
5341 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5342 		/*
5343 		 * mp is updated in tcp_get_ipsec_conn().
5344 		 */
5345 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5346 		if (econnp == NULL) {
5347 			/*
5348 			 * mp freed by tcp_get_ipsec_conn.
5349 			 */
5350 			return;
5351 		}
5352 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5353 	} else {
5354 		goto error2;
5355 	}
5356 
5357 	ASSERT(DB_TYPE(mp) == M_DATA);
5358 
5359 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5360 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5361 	ASSERT(OK_32PTR(mp->b_rptr));
5362 	if (ipvers == IPV4_VERSION) {
5363 		ipha = (ipha_t *)mp->b_rptr;
5364 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5365 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5366 	} else {
5367 		ip6h = (ip6_t *)mp->b_rptr;
5368 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5369 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5370 	}
5371 
5372 	if (tcp->tcp_family == AF_INET) {
5373 		ASSERT(ipvers == IPV4_VERSION);
5374 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5375 	} else {
5376 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5377 	}
5378 
5379 	if (err)
5380 		goto error3;
5381 
5382 	eager = econnp->conn_tcp;
5383 	ASSERT(eager->tcp_ordrel_mp == NULL);
5384 
5385 	if (!IPCL_IS_NONSTR(econnp)) {
5386 		/*
5387 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
5388 		 * at close time, we will always have that to send up.
5389 		 * Otherwise, we need to do special handling in case the
5390 		 * allocation fails at that time.
5391 		 */
5392 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5393 			goto error3;
5394 	}
5395 	/* Inherit various TCP parameters from the listener */
5396 	eager->tcp_naglim = tcp->tcp_naglim;
5397 	eager->tcp_first_timer_threshold = tcp->tcp_first_timer_threshold;
5398 	eager->tcp_second_timer_threshold = tcp->tcp_second_timer_threshold;
5399 
5400 	eager->tcp_first_ctimer_threshold = tcp->tcp_first_ctimer_threshold;
5401 	eager->tcp_second_ctimer_threshold = tcp->tcp_second_ctimer_threshold;
5402 
5403 	/*
5404 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5405 	 * If it does not, the eager's receive window will be set to the
5406 	 * listener's receive window later in this function.
5407 	 */
5408 	eager->tcp_rwnd = 0;
5409 
5410 	/*
5411 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5412 	 * calling tcp_process_options() where tcp_mss_set() is called
5413 	 * to set the initial cwnd.
5414 	 */
5415 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5416 
5417 	/*
5418 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5419 	 * zone id before the accept is completed in tcp_wput_accept().
5420 	 */
5421 	econnp->conn_zoneid = connp->conn_zoneid;
5422 	econnp->conn_allzones = connp->conn_allzones;
5423 
5424 	/* Copy nexthop information from listener to eager */
5425 	if (connp->conn_nexthop_set) {
5426 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5427 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5428 	}
5429 
5430 	/*
5431 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5432 	 * eager is accepted
5433 	 */
5434 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5435 	crhold(credp);
5436 
5437 	ASSERT(econnp->conn_effective_cred == NULL);
5438 	if (is_system_labeled()) {
5439 		cred_t *cr;
5440 		ts_label_t *tsl;
5441 
5442 		/*
5443 		 * If this is an MLP connection or a MAC-Exempt connection
5444 		 * with an unlabeled node, packets are to be
5445 		 * exchanged using the security label of the received
5446 		 * SYN packet instead of the server application's label.
5447 		 */
5448 		if ((cr = msg_getcred(mp, NULL)) != NULL &&
5449 		    (tsl = crgetlabel(cr)) != NULL &&
5450 		    (connp->conn_mlp_type != mlptSingle ||
5451 		    (connp->conn_mac_mode != CONN_MAC_AWARE &&
5452 		    (tsl->tsl_flags & TSLF_UNLABELED)))) {
5453 			if ((econnp->conn_effective_cred =
5454 			    copycred_from_tslabel(econnp->conn_cred,
5455 			    tsl, KM_NOSLEEP)) != NULL) {
5456 				DTRACE_PROBE2(
5457 				    syn_accept_peerlabel,
5458 				    conn_t *, econnp, cred_t *,
5459 				    econnp->conn_effective_cred);
5460 			} else {
5461 				DTRACE_PROBE3(
5462 				    tx__ip__log__error__set__eagercred__tcp,
5463 				    char *,
5464 				    "SYN mp(1) label on eager connp(2) failed",
5465 				    mblk_t *, mp, conn_t *, econnp);
5466 				goto error3;
5467 			}
5468 		} else {
5469 			DTRACE_PROBE2(syn_accept, conn_t *,
5470 			    econnp, cred_t *, econnp->conn_cred)
5471 		}
5472 
5473 		/*
5474 		 * Verify the destination is allowed to receive packets
5475 		 * at the security label of the SYN-ACK we are generating.
5476 		 * tsol_check_dest() may create a new effective cred for
5477 		 * this connection with a modified label or label flags.
5478 		 */
5479 		if (IN6_IS_ADDR_V4MAPPED(&econnp->conn_remv6)) {
5480 			uint32_t dst;
5481 			IN6_V4MAPPED_TO_IPADDR(&econnp->conn_remv6, dst);
5482 			err = tsol_check_dest(CONN_CRED(econnp), &dst,
5483 			    IPV4_VERSION, B_FALSE, &cr);
5484 		} else {
5485 			err = tsol_check_dest(CONN_CRED(econnp),
5486 			    &econnp->conn_remv6, IPV6_VERSION,
5487 			    B_FALSE, &cr);
5488 		}
5489 		if (err != 0)
5490 			goto error3;
5491 		if (cr != NULL) {
5492 			if (econnp->conn_effective_cred != NULL)
5493 				crfree(econnp->conn_effective_cred);
5494 			econnp->conn_effective_cred = cr;
5495 		}
5496 
5497 		/*
5498 		 * Generate the security label to be used in the text of
5499 		 * this connection's outgoing packets.
5500 		 */
5501 		if (!tcp_update_label(eager, CONN_CRED(econnp))) {
5502 			DTRACE_PROBE3(
5503 			    tx__ip__log__error__connrequest__tcp,
5504 			    char *, "eager connp(1) label on SYN mp(2) failed",
5505 			    conn_t *, econnp, mblk_t *, mp);
5506 			goto error3;
5507 		}
5508 	}
5509 
5510 	eager->tcp_hard_binding = B_TRUE;
5511 
5512 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5513 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5514 
5515 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5516 	if (err != 0) {
5517 		tcp_bind_hash_remove(eager);
5518 		goto error3;
5519 	}
5520 
5521 	/*
5522 	 * No need to check for multicast destination since ip will only pass
5523 	 * up multicasts to those that have expressed interest
5524 	 * TODO: what about rejecting broadcasts?
5525 	 * Also check that source is not a multicast or broadcast address.
5526 	 */
5527 	eager->tcp_state = TCPS_SYN_RCVD;
5528 	SOCK_CONNID_BUMP(eager->tcp_connid);
5529 
5530 	/*
5531 	 * There should be no ire in the mp as we are being called after
5532 	 * receiving the SYN.
5533 	 */
5534 	ASSERT(tcp_ire_mp(&mp) == NULL);
5535 
5536 	/*
5537 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5538 	 */
5539 
5540 	if (tcp_adapt_ire(eager, NULL) == 0) {
5541 		/* Undo the bind_hash_insert */
5542 		tcp_bind_hash_remove(eager);
5543 		goto error3;
5544 	}
5545 
5546 	/* Process all TCP options. */
5547 	tcp_process_options(eager, tcph);
5548 
5549 	/* Is the other end ECN capable? */
5550 	if (tcps->tcps_ecn_permitted >= 1 &&
5551 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5552 		eager->tcp_ecn_ok = B_TRUE;
5553 	}
5554 
5555 	/*
5556 	 * listeners tcp_recv_hiwater should be the default window size or a
5557 	 * window size changed via SO_RCVBUF option. First round up the
5558 	 * eager's tcp_rwnd to the nearest MSS. Then find out the window
5559 	 * scale option value if needed. Call tcp_rwnd_set() to finish the
5560 	 * setting.
5561 	 *
5562 	 * Note if there is a rpipe metric associated with the remote host,
5563 	 * we should not inherit receive window size from listener.
5564 	 */
5565 	eager->tcp_rwnd = MSS_ROUNDUP(
5566 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5567 	    eager->tcp_rwnd), eager->tcp_mss);
5568 	if (eager->tcp_snd_ws_ok)
5569 		tcp_set_ws_value(eager);
5570 	/*
5571 	 * Note that this is the only place tcp_rwnd_set() is called for
5572 	 * accepting a connection.  We need to call it here instead of
5573 	 * after the 3-way handshake because we need to tell the other
5574 	 * side our rwnd in the SYN-ACK segment.
5575 	 */
5576 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5577 
5578 	/*
5579 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5580 	 * via soaccept()->soinheritoptions() which essentially applies
5581 	 * all the listener options to the new STREAM. The options that we
5582 	 * need to take care of are:
5583 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5584 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5585 	 * SO_SNDBUF, SO_RCVBUF.
5586 	 *
5587 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5588 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5589 	 *		tcp_maxpsz_set() gets called later from
5590 	 *		tcp_accept_finish(), the option takes effect.
5591 	 *
5592 	 */
5593 	/* Set the TCP options */
5594 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5595 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5596 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5597 	eager->tcp_oobinline = tcp->tcp_oobinline;
5598 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5599 	eager->tcp_broadcast = tcp->tcp_broadcast;
5600 	eager->tcp_useloopback = tcp->tcp_useloopback;
5601 	eager->tcp_dontroute = tcp->tcp_dontroute;
5602 	eager->tcp_debug = tcp->tcp_debug;
5603 	eager->tcp_linger = tcp->tcp_linger;
5604 	eager->tcp_lingertime = tcp->tcp_lingertime;
5605 	if (tcp->tcp_ka_enabled)
5606 		eager->tcp_ka_enabled = 1;
5607 
5608 	ASSERT(eager->tcp_recv_hiwater != 0 &&
5609 	    eager->tcp_recv_hiwater == eager->tcp_rwnd);
5610 
5611 	/* Set the IP options */
5612 	econnp->conn_broadcast = connp->conn_broadcast;
5613 	econnp->conn_loopback = connp->conn_loopback;
5614 	econnp->conn_dontroute = connp->conn_dontroute;
5615 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5616 
5617 	/* Put a ref on the listener for the eager. */
5618 	CONN_INC_REF(connp);
5619 	mutex_enter(&tcp->tcp_eager_lock);
5620 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5621 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5622 	tcp->tcp_eager_next_q0 = eager;
5623 	eager->tcp_eager_prev_q0 = tcp;
5624 
5625 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5626 	eager->tcp_listener = tcp;
5627 	eager->tcp_saved_listener = tcp;
5628 
5629 	/*
5630 	 * Tag this detached tcp vector for later retrieval
5631 	 * by our listener client in tcp_accept().
5632 	 */
5633 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5634 	tcp->tcp_conn_req_cnt_q0++;
5635 	if (++tcp->tcp_conn_req_seqnum == -1) {
5636 		/*
5637 		 * -1 is "special" and defined in TPI as something
5638 		 * that should never be used in T_CONN_IND
5639 		 */
5640 		++tcp->tcp_conn_req_seqnum;
5641 	}
5642 	mutex_exit(&tcp->tcp_eager_lock);
5643 
5644 	if (tcp->tcp_syn_defense) {
5645 		/* Don't drop the SYN that comes from a good IP source */
5646 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5647 		if (addr_cache != NULL && eager->tcp_remote ==
5648 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5649 			eager->tcp_dontdrop = B_TRUE;
5650 		}
5651 	}
5652 
5653 	/*
5654 	 * We need to insert the eager in its own perimeter but as soon
5655 	 * as we do that, we expose the eager to the classifier and
5656 	 * should not touch any field outside the eager's perimeter.
5657 	 * So do all the work necessary before inserting the eager
5658 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5659 	 * will succeed but undo everything if it fails.
5660 	 */
5661 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5662 	eager->tcp_irs = seg_seq;
5663 	eager->tcp_rack = seg_seq;
5664 	eager->tcp_rnxt = seg_seq + 1;
5665 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5666 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5667 	eager->tcp_state = TCPS_SYN_RCVD;
5668 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5669 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5670 	if (mp1 == NULL) {
5671 		/*
5672 		 * Increment the ref count as we are going to
5673 		 * enqueueing an mp in squeue
5674 		 */
5675 		CONN_INC_REF(econnp);
5676 		goto error;
5677 	}
5678 
5679 	/*
5680 	 * Note that in theory this should use the current pid
5681 	 * so that getpeerucred on the client returns the actual listener
5682 	 * that does accept. But accept() hasn't been called yet. We could use
5683 	 * the pid of the process that did bind/listen on the server.
5684 	 * However, with common usage like inetd() the bind/listen can be done
5685 	 * by a different process than the accept().
5686 	 * Hence we do the simple thing of using the open pid here.
5687 	 * Note that db_credp is set later in tcp_send_data().
5688 	 */
5689 	mblk_setcred(mp1, credp, tcp->tcp_cpid);
5690 	eager->tcp_cpid = tcp->tcp_cpid;
5691 	eager->tcp_open_time = lbolt64;
5692 
5693 	/*
5694 	 * We need to start the rto timer. In normal case, we start
5695 	 * the timer after sending the packet on the wire (or at
5696 	 * least believing that packet was sent by waiting for
5697 	 * CALL_IP_WPUT() to return). Since this is the first packet
5698 	 * being sent on the wire for the eager, our initial tcp_rto
5699 	 * is at least tcp_rexmit_interval_min which is a fairly
5700 	 * large value to allow the algorithm to adjust slowly to large
5701 	 * fluctuations of RTT during first few transmissions.
5702 	 *
5703 	 * Starting the timer first and then sending the packet in this
5704 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5705 	 * is of the order of several 100ms and starting the timer
5706 	 * first and then sending the packet will result in difference
5707 	 * of few micro seconds.
5708 	 *
5709 	 * Without this optimization, we are forced to hold the fanout
5710 	 * lock across the ipcl_bind_insert() and sending the packet
5711 	 * so that we don't race against an incoming packet (maybe RST)
5712 	 * for this eager.
5713 	 *
5714 	 * It is necessary to acquire an extra reference on the eager
5715 	 * at this point and hold it until after tcp_send_data() to
5716 	 * ensure against an eager close race.
5717 	 */
5718 
5719 	CONN_INC_REF(eager->tcp_connp);
5720 
5721 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5722 
5723 	/*
5724 	 * Insert the eager in its own perimeter now. We are ready to deal
5725 	 * with any packets on eager.
5726 	 */
5727 	if (eager->tcp_ipversion == IPV4_VERSION) {
5728 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5729 			goto error;
5730 		}
5731 	} else {
5732 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5733 			goto error;
5734 		}
5735 	}
5736 
5737 	/* mark conn as fully-bound */
5738 	econnp->conn_fully_bound = B_TRUE;
5739 
5740 	/* Send the SYN-ACK */
5741 	tcp_send_data(eager, eager->tcp_wq, mp1);
5742 	CONN_DEC_REF(eager->tcp_connp);
5743 	freemsg(mp);
5744 
5745 	return;
5746 error:
5747 	freemsg(mp1);
5748 	eager->tcp_closemp_used = B_TRUE;
5749 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5750 	mp1 = &eager->tcp_closemp;
5751 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5752 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5753 
5754 	/*
5755 	 * If a connection already exists, send the mp to that connections so
5756 	 * that it can be appropriately dealt with.
5757 	 */
5758 	ipst = tcps->tcps_netstack->netstack_ip;
5759 
5760 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5761 		if (!IPCL_IS_CONNECTED(econnp)) {
5762 			/*
5763 			 * Something bad happened. ipcl_conn_insert()
5764 			 * failed because a connection already existed
5765 			 * in connected hash but we can't find it
5766 			 * anymore (someone blew it away). Just
5767 			 * free this message and hopefully remote
5768 			 * will retransmit at which time the SYN can be
5769 			 * treated as a new connection or dealth with
5770 			 * a TH_RST if a connection already exists.
5771 			 */
5772 			CONN_DEC_REF(econnp);
5773 			freemsg(mp);
5774 		} else {
5775 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5776 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5777 		}
5778 	} else {
5779 		/* Nobody wants this packet */
5780 		freemsg(mp);
5781 	}
5782 	return;
5783 error3:
5784 	CONN_DEC_REF(econnp);
5785 error2:
5786 	freemsg(mp);
5787 }
5788 
5789 /*
5790  * In an ideal case of vertical partition in NUMA architecture, its
5791  * beneficial to have the listener and all the incoming connections
5792  * tied to the same squeue. The other constraint is that incoming
5793  * connections should be tied to the squeue attached to interrupted
5794  * CPU for obvious locality reason so this leaves the listener to
5795  * be tied to the same squeue. Our only problem is that when listener
5796  * is binding, the CPU that will get interrupted by the NIC whose
5797  * IP address the listener is binding to is not even known. So
5798  * the code below allows us to change that binding at the time the
5799  * CPU is interrupted by virtue of incoming connection's squeue.
5800  *
5801  * This is usefull only in case of a listener bound to a specific IP
5802  * address. For other kind of listeners, they get bound the
5803  * very first time and there is no attempt to rebind them.
5804  */
5805 void
5806 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5807 {
5808 	conn_t		*connp = (conn_t *)arg;
5809 	squeue_t	*sqp = (squeue_t *)arg2;
5810 	squeue_t	*new_sqp;
5811 	uint32_t	conn_flags;
5812 
5813 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5814 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5815 	} else {
5816 		goto done;
5817 	}
5818 
5819 	if (connp->conn_fanout == NULL)
5820 		goto done;
5821 
5822 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5823 		mutex_enter(&connp->conn_fanout->connf_lock);
5824 		mutex_enter(&connp->conn_lock);
5825 		/*
5826 		 * No one from read or write side can access us now
5827 		 * except for already queued packets on this squeue.
5828 		 * But since we haven't changed the squeue yet, they
5829 		 * can't execute. If they are processed after we have
5830 		 * changed the squeue, they are sent back to the
5831 		 * correct squeue down below.
5832 		 * But a listner close can race with processing of
5833 		 * incoming SYN. If incoming SYN processing changes
5834 		 * the squeue then the listener close which is waiting
5835 		 * to enter the squeue would operate on the wrong
5836 		 * squeue. Hence we don't change the squeue here unless
5837 		 * the refcount is exactly the minimum refcount. The
5838 		 * minimum refcount of 4 is counted as - 1 each for
5839 		 * TCP and IP, 1 for being in the classifier hash, and
5840 		 * 1 for the mblk being processed.
5841 		 */
5842 
5843 		if (connp->conn_ref != 4 ||
5844 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5845 			mutex_exit(&connp->conn_lock);
5846 			mutex_exit(&connp->conn_fanout->connf_lock);
5847 			goto done;
5848 		}
5849 		if (connp->conn_sqp != new_sqp) {
5850 			while (connp->conn_sqp != new_sqp)
5851 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5852 		}
5853 
5854 		do {
5855 			conn_flags = connp->conn_flags;
5856 			conn_flags |= IPCL_FULLY_BOUND;
5857 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5858 			    conn_flags);
5859 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5860 
5861 		mutex_exit(&connp->conn_fanout->connf_lock);
5862 		mutex_exit(&connp->conn_lock);
5863 	}
5864 
5865 done:
5866 	if (connp->conn_sqp != sqp) {
5867 		CONN_INC_REF(connp);
5868 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5869 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5870 	} else {
5871 		tcp_conn_request(connp, mp, sqp);
5872 	}
5873 }
5874 
5875 /*
5876  * Successful connect request processing begins when our client passes
5877  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5878  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5879  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5880  *   upstream <- tcp_rput()		<- IP
5881  * After various error checks are completed, tcp_tpi_connect() lays
5882  * the target address and port into the composite header template,
5883  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5884  * request followed by an IRE request, and passes the three mblk message
5885  * down to IP looking like this:
5886  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5887  * Processing continues in tcp_rput() when we receive the following message:
5888  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5889  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5890  * to fire off the connection request, and then passes the T_OK_ACK mblk
5891  * upstream that we filled in below.  There are, of course, numerous
5892  * error conditions along the way which truncate the processing described
5893  * above.
5894  */
5895 static void
5896 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5897 {
5898 	sin_t		*sin;
5899 	queue_t		*q = tcp->tcp_wq;
5900 	struct T_conn_req	*tcr;
5901 	struct sockaddr	*sa;
5902 	socklen_t	len;
5903 	int		error;
5904 	cred_t		*cr;
5905 	pid_t		cpid;
5906 
5907 	/*
5908 	 * All Solaris components should pass a db_credp
5909 	 * for this TPI message, hence we ASSERT.
5910 	 * But in case there is some other M_PROTO that looks
5911 	 * like a TPI message sent by some other kernel
5912 	 * component, we check and return an error.
5913 	 */
5914 	cr = msg_getcred(mp, &cpid);
5915 	ASSERT(cr != NULL);
5916 	if (cr == NULL) {
5917 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5918 		return;
5919 	}
5920 
5921 	tcr = (struct T_conn_req *)mp->b_rptr;
5922 
5923 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5924 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5925 		tcp_err_ack(tcp, mp, TPROTO, 0);
5926 		return;
5927 	}
5928 
5929 	/*
5930 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5931 	 * will always have that to send up.  Otherwise, we need to do
5932 	 * special handling in case the allocation fails at that time.
5933 	 * If the end point is TPI, the tcp_t can be reused and the
5934 	 * tcp_ordrel_mp may be allocated already.
5935 	 */
5936 	if (tcp->tcp_ordrel_mp == NULL) {
5937 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5938 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5939 			return;
5940 		}
5941 	}
5942 
5943 	/*
5944 	 * Determine packet type based on type of address passed in
5945 	 * the request should contain an IPv4 or IPv6 address.
5946 	 * Make sure that address family matches the type of
5947 	 * family of the the address passed down
5948 	 */
5949 	switch (tcr->DEST_length) {
5950 	default:
5951 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5952 		return;
5953 
5954 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5955 		/*
5956 		 * XXX: The check for valid DEST_length was not there
5957 		 * in earlier releases and some buggy
5958 		 * TLI apps (e.g Sybase) got away with not feeding
5959 		 * in sin_zero part of address.
5960 		 * We allow that bug to keep those buggy apps humming.
5961 		 * Test suites require the check on DEST_length.
5962 		 * We construct a new mblk with valid DEST_length
5963 		 * free the original so the rest of the code does
5964 		 * not have to keep track of this special shorter
5965 		 * length address case.
5966 		 */
5967 		mblk_t *nmp;
5968 		struct T_conn_req *ntcr;
5969 		sin_t *nsin;
5970 
5971 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5972 		    tcr->OPT_length, BPRI_HI);
5973 		if (nmp == NULL) {
5974 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5975 			return;
5976 		}
5977 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5978 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5979 		ntcr->PRIM_type = T_CONN_REQ;
5980 		ntcr->DEST_length = sizeof (sin_t);
5981 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5982 
5983 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5984 		*nsin = sin_null;
5985 		/* Get pointer to shorter address to copy from original mp */
5986 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5987 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5988 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5989 			freemsg(nmp);
5990 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5991 			return;
5992 		}
5993 		nsin->sin_family = sin->sin_family;
5994 		nsin->sin_port = sin->sin_port;
5995 		nsin->sin_addr = sin->sin_addr;
5996 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5997 		nmp->b_wptr = (uchar_t *)&nsin[1];
5998 		if (tcr->OPT_length != 0) {
5999 			ntcr->OPT_length = tcr->OPT_length;
6000 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6001 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6002 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6003 			    tcr->OPT_length);
6004 			nmp->b_wptr += tcr->OPT_length;
6005 		}
6006 		freemsg(mp);	/* original mp freed */
6007 		mp = nmp;	/* re-initialize original variables */
6008 		tcr = ntcr;
6009 	}
6010 	/* FALLTHRU */
6011 
6012 	case sizeof (sin_t):
6013 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6014 		    sizeof (sin_t));
6015 		len = sizeof (sin_t);
6016 		break;
6017 
6018 	case sizeof (sin6_t):
6019 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6020 		    sizeof (sin6_t));
6021 		len = sizeof (sin6_t);
6022 		break;
6023 	}
6024 
6025 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6026 	if (error != 0) {
6027 		tcp_err_ack(tcp, mp, TSYSERR, error);
6028 		return;
6029 	}
6030 
6031 	/*
6032 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6033 	 * should key on their sequence number and cut them loose.
6034 	 */
6035 
6036 	/*
6037 	 * If options passed in, feed it for verification and handling
6038 	 */
6039 	if (tcr->OPT_length != 0) {
6040 		mblk_t	*ok_mp;
6041 		mblk_t	*discon_mp;
6042 		mblk_t  *conn_opts_mp;
6043 		int t_error, sys_error, do_disconnect;
6044 
6045 		conn_opts_mp = NULL;
6046 
6047 		if (tcp_conprim_opt_process(tcp, mp,
6048 		    &do_disconnect, &t_error, &sys_error) < 0) {
6049 			if (do_disconnect) {
6050 				ASSERT(t_error == 0 && sys_error == 0);
6051 				discon_mp = mi_tpi_discon_ind(NULL,
6052 				    ECONNREFUSED, 0);
6053 				if (!discon_mp) {
6054 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6055 					    TSYSERR, ENOMEM);
6056 					return;
6057 				}
6058 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6059 				if (!ok_mp) {
6060 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6061 					    TSYSERR, ENOMEM);
6062 					return;
6063 				}
6064 				qreply(q, ok_mp);
6065 				qreply(q, discon_mp); /* no flush! */
6066 			} else {
6067 				ASSERT(t_error != 0);
6068 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6069 				    sys_error);
6070 			}
6071 			return;
6072 		}
6073 		/*
6074 		 * Success in setting options, the mp option buffer represented
6075 		 * by OPT_length/offset has been potentially modified and
6076 		 * contains results of option processing. We copy it in
6077 		 * another mp to save it for potentially influencing returning
6078 		 * it in T_CONN_CONN.
6079 		 */
6080 		if (tcr->OPT_length != 0) { /* there are resulting options */
6081 			conn_opts_mp = copyb(mp);
6082 			if (!conn_opts_mp) {
6083 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6084 				    TSYSERR, ENOMEM);
6085 				return;
6086 			}
6087 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6088 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6089 			/*
6090 			 * Note:
6091 			 * These resulting option negotiation can include any
6092 			 * end-to-end negotiation options but there no such
6093 			 * thing (yet?) in our TCP/IP.
6094 			 */
6095 		}
6096 	}
6097 
6098 	/* call the non-TPI version */
6099 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
6100 	if (error < 0) {
6101 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6102 	} else if (error > 0) {
6103 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6104 	} else {
6105 		mp = mi_tpi_ok_ack_alloc(mp);
6106 	}
6107 
6108 	/*
6109 	 * Note: Code below is the "failure" case
6110 	 */
6111 	/* return error ack and blow away saved option results if any */
6112 connect_failed:
6113 	if (mp != NULL)
6114 		putnext(tcp->tcp_rq, mp);
6115 	else {
6116 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6117 		    TSYSERR, ENOMEM);
6118 	}
6119 }
6120 
6121 /*
6122  * Handle connect to IPv4 destinations, including connections for AF_INET6
6123  * sockets connecting to IPv4 mapped IPv6 destinations.
6124  */
6125 static int
6126 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6127     uint_t srcid, cred_t *cr, pid_t pid)
6128 {
6129 	tcph_t	*tcph;
6130 	mblk_t	*mp;
6131 	ipaddr_t dstaddr = *dstaddrp;
6132 	int32_t	oldstate;
6133 	uint16_t lport;
6134 	int	error = 0;
6135 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6136 
6137 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6138 
6139 	/* Check for attempt to connect to INADDR_ANY */
6140 	if (dstaddr == INADDR_ANY)  {
6141 		/*
6142 		 * SunOS 4.x and 4.3 BSD allow an application
6143 		 * to connect a TCP socket to INADDR_ANY.
6144 		 * When they do this, the kernel picks the
6145 		 * address of one interface and uses it
6146 		 * instead.  The kernel usually ends up
6147 		 * picking the address of the loopback
6148 		 * interface.  This is an undocumented feature.
6149 		 * However, we provide the same thing here
6150 		 * in order to have source and binary
6151 		 * compatibility with SunOS 4.x.
6152 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6153 		 * generate the T_CONN_CON.
6154 		 */
6155 		dstaddr = htonl(INADDR_LOOPBACK);
6156 		*dstaddrp = dstaddr;
6157 	}
6158 
6159 	/* Handle __sin6_src_id if socket not bound to an IP address */
6160 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6161 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6162 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6163 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6164 		    tcp->tcp_ipha->ipha_src);
6165 	}
6166 
6167 	/*
6168 	 * Don't let an endpoint connect to itself.  Note that
6169 	 * the test here does not catch the case where the
6170 	 * source IP addr was left unspecified by the user. In
6171 	 * this case, the source addr is set in tcp_adapt_ire()
6172 	 * using the reply to the T_BIND message that we send
6173 	 * down to IP here and the check is repeated in tcp_rput_other.
6174 	 */
6175 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6176 	    dstport == tcp->tcp_lport) {
6177 		error = -TBADADDR;
6178 		goto failed;
6179 	}
6180 
6181 	/*
6182 	 * Verify the destination is allowed to receive packets
6183 	 * at the security label of the connection we are initiating.
6184 	 * tsol_check_dest() may create a new effective cred for this
6185 	 * connection with a modified label or label flags.
6186 	 */
6187 	if (is_system_labeled()) {
6188 		ASSERT(tcp->tcp_connp->conn_effective_cred == NULL);
6189 		if ((error = tsol_check_dest(CONN_CRED(tcp->tcp_connp),
6190 		    &dstaddr, IPV4_VERSION, tcp->tcp_connp->conn_mac_mode,
6191 		    &tcp->tcp_connp->conn_effective_cred)) != 0) {
6192 			if (error != EHOSTUNREACH)
6193 				error = -TSYSERR;
6194 			goto failed;
6195 		}
6196 	}
6197 
6198 	tcp->tcp_ipha->ipha_dst = dstaddr;
6199 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6200 
6201 	/*
6202 	 * Massage a source route if any putting the first hop
6203 	 * in iph_dst. Compute a starting value for the checksum which
6204 	 * takes into account that the original iph_dst should be
6205 	 * included in the checksum but that ip will include the
6206 	 * first hop in the source route in the tcp checksum.
6207 	 */
6208 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6209 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6210 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6211 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6212 	if ((int)tcp->tcp_sum < 0)
6213 		tcp->tcp_sum--;
6214 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6215 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6216 	    (tcp->tcp_sum >> 16));
6217 	tcph = tcp->tcp_tcph;
6218 	*(uint16_t *)tcph->th_fport = dstport;
6219 	tcp->tcp_fport = dstport;
6220 
6221 	oldstate = tcp->tcp_state;
6222 	/*
6223 	 * At this point the remote destination address and remote port fields
6224 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6225 	 * have to see which state tcp was in so we can take apropriate action.
6226 	 */
6227 	if (oldstate == TCPS_IDLE) {
6228 		/*
6229 		 * We support a quick connect capability here, allowing
6230 		 * clients to transition directly from IDLE to SYN_SENT
6231 		 * tcp_bindi will pick an unused port, insert the connection
6232 		 * in the bind hash and transition to BOUND state.
6233 		 */
6234 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6235 		    tcp, B_TRUE);
6236 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6237 		    B_FALSE, B_FALSE);
6238 		if (lport == 0) {
6239 			error = -TNOADDR;
6240 			goto failed;
6241 		}
6242 	}
6243 	tcp->tcp_state = TCPS_SYN_SENT;
6244 
6245 	mp = allocb(sizeof (ire_t), BPRI_HI);
6246 	if (mp == NULL) {
6247 		tcp->tcp_state = oldstate;
6248 		error = ENOMEM;
6249 		goto failed;
6250 	}
6251 
6252 	mp->b_wptr += sizeof (ire_t);
6253 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6254 	tcp->tcp_hard_binding = 1;
6255 
6256 	/*
6257 	 * We need to make sure that the conn_recv is set to a non-null
6258 	 * value before we insert the conn_t into the classifier table.
6259 	 * This is to avoid a race with an incoming packet which does
6260 	 * an ipcl_classify().
6261 	 */
6262 	tcp->tcp_connp->conn_recv = tcp_input;
6263 
6264 	if (tcp->tcp_family == AF_INET) {
6265 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6266 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6267 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6268 	} else {
6269 		in6_addr_t v6src;
6270 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6271 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6272 		} else {
6273 			v6src = tcp->tcp_ip6h->ip6_src;
6274 		}
6275 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6276 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6277 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6278 	}
6279 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6280 	tcp->tcp_active_open = 1;
6281 
6282 
6283 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6284 failed:
6285 	/* return error ack and blow away saved option results if any */
6286 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6287 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6288 	return (error);
6289 }
6290 
6291 /*
6292  * Handle connect to IPv6 destinations.
6293  */
6294 static int
6295 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6296     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6297 {
6298 	tcph_t	*tcph;
6299 	mblk_t	*mp;
6300 	ip6_rthdr_t *rth;
6301 	int32_t  oldstate;
6302 	uint16_t lport;
6303 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6304 	int	error = 0;
6305 	conn_t	*connp = tcp->tcp_connp;
6306 
6307 	ASSERT(tcp->tcp_family == AF_INET6);
6308 
6309 	/*
6310 	 * If we're here, it means that the destination address is a native
6311 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6312 	 * reason why it might not be IPv6 is if the socket was bound to an
6313 	 * IPv4-mapped IPv6 address.
6314 	 */
6315 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6316 		return (-TBADADDR);
6317 	}
6318 
6319 	/*
6320 	 * Interpret a zero destination to mean loopback.
6321 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6322 	 * generate the T_CONN_CON.
6323 	 */
6324 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6325 		*dstaddrp = ipv6_loopback;
6326 	}
6327 
6328 	/* Handle __sin6_src_id if socket not bound to an IP address */
6329 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6330 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6331 		    connp->conn_zoneid, tcps->tcps_netstack);
6332 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6333 	}
6334 
6335 	/*
6336 	 * Take care of the scope_id now and add ip6i_t
6337 	 * if ip6i_t is not already allocated through TCP
6338 	 * sticky options. At this point tcp_ip6h does not
6339 	 * have dst info, thus use dstaddrp.
6340 	 */
6341 	if (scope_id != 0 &&
6342 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6343 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6344 		ip6i_t  *ip6i;
6345 
6346 		ipp->ipp_ifindex = scope_id;
6347 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6348 
6349 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6350 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6351 			/* Already allocated */
6352 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6353 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6354 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6355 		} else {
6356 			int reterr;
6357 
6358 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6359 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6360 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6361 			reterr = tcp_build_hdrs(tcp);
6362 			if (reterr != 0)
6363 				goto failed;
6364 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6365 		}
6366 	}
6367 
6368 	/*
6369 	 * Don't let an endpoint connect to itself.  Note that
6370 	 * the test here does not catch the case where the
6371 	 * source IP addr was left unspecified by the user. In
6372 	 * this case, the source addr is set in tcp_adapt_ire()
6373 	 * using the reply to the T_BIND message that we send
6374 	 * down to IP here and the check is repeated in tcp_rput_other.
6375 	 */
6376 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6377 	    (dstport == tcp->tcp_lport)) {
6378 		error = -TBADADDR;
6379 		goto failed;
6380 	}
6381 
6382 	/*
6383 	 * Verify the destination is allowed to receive packets
6384 	 * at the security label of the connection we are initiating.
6385 	 * check_dest may create a new effective cred for this
6386 	 * connection with a modified label or label flags.
6387 	 */
6388 	if (is_system_labeled()) {
6389 		ASSERT(tcp->tcp_connp->conn_effective_cred == NULL);
6390 		if ((error = tsol_check_dest(CONN_CRED(tcp->tcp_connp),
6391 		    dstaddrp, IPV6_VERSION, tcp->tcp_connp->conn_mac_mode,
6392 		    &tcp->tcp_connp->conn_effective_cred)) != 0) {
6393 			if (error != EHOSTUNREACH)
6394 				error = -TSYSERR;
6395 			goto failed;
6396 		}
6397 	}
6398 
6399 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6400 	tcp->tcp_remote_v6 = *dstaddrp;
6401 	tcp->tcp_ip6h->ip6_vcf =
6402 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6403 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6404 
6405 	/*
6406 	 * Massage a routing header (if present) putting the first hop
6407 	 * in ip6_dst. Compute a starting value for the checksum which
6408 	 * takes into account that the original ip6_dst should be
6409 	 * included in the checksum but that ip will include the
6410 	 * first hop in the source route in the tcp checksum.
6411 	 */
6412 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6413 	if (rth != NULL) {
6414 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6415 		    tcps->tcps_netstack);
6416 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6417 		    (tcp->tcp_sum >> 16));
6418 	} else {
6419 		tcp->tcp_sum = 0;
6420 	}
6421 
6422 	tcph = tcp->tcp_tcph;
6423 	*(uint16_t *)tcph->th_fport = dstport;
6424 	tcp->tcp_fport = dstport;
6425 
6426 	oldstate = tcp->tcp_state;
6427 	/*
6428 	 * At this point the remote destination address and remote port fields
6429 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6430 	 * have to see which state tcp was in so we can take apropriate action.
6431 	 */
6432 	if (oldstate == TCPS_IDLE) {
6433 		/*
6434 		 * We support a quick connect capability here, allowing
6435 		 * clients to transition directly from IDLE to SYN_SENT
6436 		 * tcp_bindi will pick an unused port, insert the connection
6437 		 * in the bind hash and transition to BOUND state.
6438 		 */
6439 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6440 		    tcp, B_TRUE);
6441 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6442 		    B_FALSE, B_FALSE);
6443 		if (lport == 0) {
6444 			error = -TNOADDR;
6445 			goto failed;
6446 		}
6447 	}
6448 	tcp->tcp_state = TCPS_SYN_SENT;
6449 
6450 	mp = allocb(sizeof (ire_t), BPRI_HI);
6451 	if (mp != NULL) {
6452 		in6_addr_t v6src;
6453 
6454 		mp->b_wptr += sizeof (ire_t);
6455 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6456 
6457 		tcp->tcp_hard_binding = 1;
6458 
6459 		/*
6460 		 * We need to make sure that the conn_recv is set to a non-null
6461 		 * value before we insert the conn_t into the classifier table.
6462 		 * This is to avoid a race with an incoming packet which does
6463 		 * an ipcl_classify().
6464 		 */
6465 		tcp->tcp_connp->conn_recv = tcp_input;
6466 
6467 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6468 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6469 		} else {
6470 			v6src = tcp->tcp_ip6h->ip6_src;
6471 		}
6472 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6473 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6474 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6475 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6476 		tcp->tcp_active_open = 1;
6477 
6478 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6479 	}
6480 	/* Error case */
6481 	tcp->tcp_state = oldstate;
6482 	error = ENOMEM;
6483 
6484 failed:
6485 	/* return error ack and blow away saved option results if any */
6486 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6487 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6488 	return (error);
6489 }
6490 
6491 /*
6492  * We need a stream q for detached closing tcp connections
6493  * to use.  Our client hereby indicates that this q is the
6494  * one to use.
6495  */
6496 static void
6497 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6498 {
6499 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6500 	queue_t	*q = tcp->tcp_wq;
6501 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6502 
6503 #ifdef NS_DEBUG
6504 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6505 	    tcps->tcps_netstack->netstack_stackid);
6506 #endif
6507 	mp->b_datap->db_type = M_IOCACK;
6508 	iocp->ioc_count = 0;
6509 	mutex_enter(&tcps->tcps_g_q_lock);
6510 	if (tcps->tcps_g_q != NULL) {
6511 		mutex_exit(&tcps->tcps_g_q_lock);
6512 		iocp->ioc_error = EALREADY;
6513 	} else {
6514 		int error = 0;
6515 		conn_t *connp = tcp->tcp_connp;
6516 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6517 
6518 		tcps->tcps_g_q = tcp->tcp_rq;
6519 		mutex_exit(&tcps->tcps_g_q_lock);
6520 		iocp->ioc_error = 0;
6521 		iocp->ioc_rval = 0;
6522 		/*
6523 		 * We are passing tcp_sticky_ipp as NULL
6524 		 * as it is not useful for tcp_default queue
6525 		 *
6526 		 * Set conn_recv just in case.
6527 		 */
6528 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6529 
6530 		ASSERT(connp->conn_af_isv6);
6531 		connp->conn_ulp = IPPROTO_TCP;
6532 
6533 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6534 		    NULL || (connp->conn_mac_mode != CONN_MAC_DEFAULT)) {
6535 			error = -TBADADDR;
6536 		} else {
6537 			connp->conn_srcv6 = ipv6_all_zeros;
6538 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6539 		}
6540 
6541 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6542 	}
6543 	qreply(q, mp);
6544 }
6545 
6546 static int
6547 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6548 {
6549 	tcp_t	*ltcp = NULL;
6550 	conn_t	*connp;
6551 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6552 
6553 	/*
6554 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6555 	 * when the stream is in BOUND state. Do not send a reset,
6556 	 * since the destination IP address is not valid, and it can
6557 	 * be the initialized value of all zeros (broadcast address).
6558 	 *
6559 	 * XXX There won't be any pending bind request to IP.
6560 	 */
6561 	if (tcp->tcp_state <= TCPS_BOUND) {
6562 		if (tcp->tcp_debug) {
6563 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6564 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6565 		}
6566 		return (TOUTSTATE);
6567 	}
6568 
6569 
6570 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6571 
6572 		/*
6573 		 * According to TPI, for non-listeners, ignore seqnum
6574 		 * and disconnect.
6575 		 * Following interpretation of -1 seqnum is historical
6576 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6577 		 * a valid seqnum should not be -1).
6578 		 *
6579 		 *	-1 means disconnect everything
6580 		 *	regardless even on a listener.
6581 		 */
6582 
6583 		int old_state = tcp->tcp_state;
6584 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6585 
6586 		/*
6587 		 * The connection can't be on the tcp_time_wait_head list
6588 		 * since it is not detached.
6589 		 */
6590 		ASSERT(tcp->tcp_time_wait_next == NULL);
6591 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6592 		ASSERT(tcp->tcp_time_wait_expire == 0);
6593 		ltcp = NULL;
6594 		/*
6595 		 * If it used to be a listener, check to make sure no one else
6596 		 * has taken the port before switching back to LISTEN state.
6597 		 */
6598 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6599 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6600 			    tcp->tcp_ipha->ipha_src,
6601 			    tcp->tcp_connp->conn_zoneid, ipst);
6602 			if (connp != NULL)
6603 				ltcp = connp->conn_tcp;
6604 		} else {
6605 			/* Allow tcp_bound_if listeners? */
6606 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6607 			    &tcp->tcp_ip6h->ip6_src, 0,
6608 			    tcp->tcp_connp->conn_zoneid, ipst);
6609 			if (connp != NULL)
6610 				ltcp = connp->conn_tcp;
6611 		}
6612 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6613 			tcp->tcp_state = TCPS_LISTEN;
6614 		} else if (old_state > TCPS_BOUND) {
6615 			tcp->tcp_conn_req_max = 0;
6616 			tcp->tcp_state = TCPS_BOUND;
6617 		}
6618 		if (ltcp != NULL)
6619 			CONN_DEC_REF(ltcp->tcp_connp);
6620 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6621 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6622 		} else if (old_state == TCPS_ESTABLISHED ||
6623 		    old_state == TCPS_CLOSE_WAIT) {
6624 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6625 		}
6626 
6627 		if (tcp->tcp_fused)
6628 			tcp_unfuse(tcp);
6629 
6630 		mutex_enter(&tcp->tcp_eager_lock);
6631 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6632 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6633 			tcp_eager_cleanup(tcp, 0);
6634 		}
6635 		mutex_exit(&tcp->tcp_eager_lock);
6636 
6637 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6638 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6639 
6640 		tcp_reinit(tcp);
6641 
6642 		return (0);
6643 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6644 		return (TBADSEQ);
6645 	}
6646 	return (0);
6647 }
6648 
6649 /*
6650  * Our client hereby directs us to reject the connection request
6651  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6652  * of sending the appropriate RST, not an ICMP error.
6653  */
6654 static void
6655 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6656 {
6657 	t_scalar_t seqnum;
6658 	int	error;
6659 
6660 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6661 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6662 		tcp_err_ack(tcp, mp, TPROTO, 0);
6663 		return;
6664 	}
6665 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6666 	error = tcp_disconnect_common(tcp, seqnum);
6667 	if (error != 0)
6668 		tcp_err_ack(tcp, mp, error, 0);
6669 	else {
6670 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6671 			/* Send M_FLUSH according to TPI */
6672 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6673 		}
6674 		mp = mi_tpi_ok_ack_alloc(mp);
6675 		if (mp)
6676 			putnext(tcp->tcp_rq, mp);
6677 	}
6678 }
6679 
6680 /*
6681  * Diagnostic routine used to return a string associated with the tcp state.
6682  * Note that if the caller does not supply a buffer, it will use an internal
6683  * static string.  This means that if multiple threads call this function at
6684  * the same time, output can be corrupted...  Note also that this function
6685  * does not check the size of the supplied buffer.  The caller has to make
6686  * sure that it is big enough.
6687  */
6688 static char *
6689 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6690 {
6691 	char		buf1[30];
6692 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6693 	char		*buf;
6694 	char		*cp;
6695 	in6_addr_t	local, remote;
6696 	char		local_addrbuf[INET6_ADDRSTRLEN];
6697 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6698 
6699 	if (sup_buf != NULL)
6700 		buf = sup_buf;
6701 	else
6702 		buf = priv_buf;
6703 
6704 	if (tcp == NULL)
6705 		return ("NULL_TCP");
6706 	switch (tcp->tcp_state) {
6707 	case TCPS_CLOSED:
6708 		cp = "TCP_CLOSED";
6709 		break;
6710 	case TCPS_IDLE:
6711 		cp = "TCP_IDLE";
6712 		break;
6713 	case TCPS_BOUND:
6714 		cp = "TCP_BOUND";
6715 		break;
6716 	case TCPS_LISTEN:
6717 		cp = "TCP_LISTEN";
6718 		break;
6719 	case TCPS_SYN_SENT:
6720 		cp = "TCP_SYN_SENT";
6721 		break;
6722 	case TCPS_SYN_RCVD:
6723 		cp = "TCP_SYN_RCVD";
6724 		break;
6725 	case TCPS_ESTABLISHED:
6726 		cp = "TCP_ESTABLISHED";
6727 		break;
6728 	case TCPS_CLOSE_WAIT:
6729 		cp = "TCP_CLOSE_WAIT";
6730 		break;
6731 	case TCPS_FIN_WAIT_1:
6732 		cp = "TCP_FIN_WAIT_1";
6733 		break;
6734 	case TCPS_CLOSING:
6735 		cp = "TCP_CLOSING";
6736 		break;
6737 	case TCPS_LAST_ACK:
6738 		cp = "TCP_LAST_ACK";
6739 		break;
6740 	case TCPS_FIN_WAIT_2:
6741 		cp = "TCP_FIN_WAIT_2";
6742 		break;
6743 	case TCPS_TIME_WAIT:
6744 		cp = "TCP_TIME_WAIT";
6745 		break;
6746 	default:
6747 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6748 		cp = buf1;
6749 		break;
6750 	}
6751 	switch (format) {
6752 	case DISP_ADDR_AND_PORT:
6753 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6754 			/*
6755 			 * Note that we use the remote address in the tcp_b
6756 			 * structure.  This means that it will print out
6757 			 * the real destination address, not the next hop's
6758 			 * address if source routing is used.
6759 			 */
6760 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6761 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6762 
6763 		} else {
6764 			local = tcp->tcp_ip_src_v6;
6765 			remote = tcp->tcp_remote_v6;
6766 		}
6767 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6768 		    sizeof (local_addrbuf));
6769 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6770 		    sizeof (remote_addrbuf));
6771 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6772 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6773 		    ntohs(tcp->tcp_fport), cp);
6774 		break;
6775 	case DISP_PORT_ONLY:
6776 	default:
6777 		(void) mi_sprintf(buf, "[%u, %u] %s",
6778 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6779 		break;
6780 	}
6781 
6782 	return (buf);
6783 }
6784 
6785 /*
6786  * Called via squeue to get on to eager's perimeter. It sends a
6787  * TH_RST if eager is in the fanout table. The listener wants the
6788  * eager to disappear either by means of tcp_eager_blowoff() or
6789  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6790  * called (via squeue) if the eager cannot be inserted in the
6791  * fanout table in tcp_conn_request().
6792  */
6793 /* ARGSUSED */
6794 void
6795 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6796 {
6797 	conn_t	*econnp = (conn_t *)arg;
6798 	tcp_t	*eager = econnp->conn_tcp;
6799 	tcp_t	*listener = eager->tcp_listener;
6800 	tcp_stack_t	*tcps = eager->tcp_tcps;
6801 
6802 	/*
6803 	 * We could be called because listener is closing. Since
6804 	 * the eager is using listener's queue's, its not safe.
6805 	 * Better use the default queue just to send the TH_RST
6806 	 * out.
6807 	 */
6808 	ASSERT(tcps->tcps_g_q != NULL);
6809 	eager->tcp_rq = tcps->tcps_g_q;
6810 	eager->tcp_wq = WR(tcps->tcps_g_q);
6811 
6812 	/*
6813 	 * An eager's conn_fanout will be NULL if it's a duplicate
6814 	 * for an existing 4-tuples in the conn fanout table.
6815 	 * We don't want to send an RST out in such case.
6816 	 */
6817 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6818 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6819 		    eager, eager->tcp_snxt, 0, TH_RST);
6820 	}
6821 
6822 	/* We are here because listener wants this eager gone */
6823 	if (listener != NULL) {
6824 		mutex_enter(&listener->tcp_eager_lock);
6825 		tcp_eager_unlink(eager);
6826 		if (eager->tcp_tconnind_started) {
6827 			/*
6828 			 * The eager has sent a conn_ind up to the
6829 			 * listener but listener decides to close
6830 			 * instead. We need to drop the extra ref
6831 			 * placed on eager in tcp_rput_data() before
6832 			 * sending the conn_ind to listener.
6833 			 */
6834 			CONN_DEC_REF(econnp);
6835 		}
6836 		mutex_exit(&listener->tcp_eager_lock);
6837 		CONN_DEC_REF(listener->tcp_connp);
6838 	}
6839 
6840 	if (eager->tcp_state != TCPS_CLOSED)
6841 		tcp_close_detached(eager);
6842 }
6843 
6844 /*
6845  * Reset any eager connection hanging off this listener marked
6846  * with 'seqnum' and then reclaim it's resources.
6847  */
6848 static boolean_t
6849 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6850 {
6851 	tcp_t	*eager;
6852 	mblk_t 	*mp;
6853 	tcp_stack_t	*tcps = listener->tcp_tcps;
6854 
6855 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6856 	eager = listener;
6857 	mutex_enter(&listener->tcp_eager_lock);
6858 	do {
6859 		eager = eager->tcp_eager_next_q;
6860 		if (eager == NULL) {
6861 			mutex_exit(&listener->tcp_eager_lock);
6862 			return (B_FALSE);
6863 		}
6864 	} while (eager->tcp_conn_req_seqnum != seqnum);
6865 
6866 	if (eager->tcp_closemp_used) {
6867 		mutex_exit(&listener->tcp_eager_lock);
6868 		return (B_TRUE);
6869 	}
6870 	eager->tcp_closemp_used = B_TRUE;
6871 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6872 	CONN_INC_REF(eager->tcp_connp);
6873 	mutex_exit(&listener->tcp_eager_lock);
6874 	mp = &eager->tcp_closemp;
6875 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6876 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6877 	return (B_TRUE);
6878 }
6879 
6880 /*
6881  * Reset any eager connection hanging off this listener
6882  * and then reclaim it's resources.
6883  */
6884 static void
6885 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6886 {
6887 	tcp_t	*eager;
6888 	mblk_t	*mp;
6889 	tcp_stack_t	*tcps = listener->tcp_tcps;
6890 
6891 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6892 
6893 	if (!q0_only) {
6894 		/* First cleanup q */
6895 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6896 		eager = listener->tcp_eager_next_q;
6897 		while (eager != NULL) {
6898 			if (!eager->tcp_closemp_used) {
6899 				eager->tcp_closemp_used = B_TRUE;
6900 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6901 				CONN_INC_REF(eager->tcp_connp);
6902 				mp = &eager->tcp_closemp;
6903 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6904 				    tcp_eager_kill, eager->tcp_connp,
6905 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6906 			}
6907 			eager = eager->tcp_eager_next_q;
6908 		}
6909 	}
6910 	/* Then cleanup q0 */
6911 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6912 	eager = listener->tcp_eager_next_q0;
6913 	while (eager != listener) {
6914 		if (!eager->tcp_closemp_used) {
6915 			eager->tcp_closemp_used = B_TRUE;
6916 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6917 			CONN_INC_REF(eager->tcp_connp);
6918 			mp = &eager->tcp_closemp;
6919 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6920 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6921 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6922 		}
6923 		eager = eager->tcp_eager_next_q0;
6924 	}
6925 }
6926 
6927 /*
6928  * If we are an eager connection hanging off a listener that hasn't
6929  * formally accepted the connection yet, get off his list and blow off
6930  * any data that we have accumulated.
6931  */
6932 static void
6933 tcp_eager_unlink(tcp_t *tcp)
6934 {
6935 	tcp_t	*listener = tcp->tcp_listener;
6936 
6937 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6938 	ASSERT(listener != NULL);
6939 	if (tcp->tcp_eager_next_q0 != NULL) {
6940 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6941 
6942 		/* Remove the eager tcp from q0 */
6943 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6944 		    tcp->tcp_eager_prev_q0;
6945 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6946 		    tcp->tcp_eager_next_q0;
6947 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6948 		listener->tcp_conn_req_cnt_q0--;
6949 
6950 		tcp->tcp_eager_next_q0 = NULL;
6951 		tcp->tcp_eager_prev_q0 = NULL;
6952 
6953 		/*
6954 		 * Take the eager out, if it is in the list of droppable
6955 		 * eagers.
6956 		 */
6957 		MAKE_UNDROPPABLE(tcp);
6958 
6959 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6960 			/* we have timed out before */
6961 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6962 			listener->tcp_syn_rcvd_timeout--;
6963 		}
6964 	} else {
6965 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6966 		tcp_t	*prev = NULL;
6967 
6968 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6969 			if (tcpp[0] == tcp) {
6970 				if (listener->tcp_eager_last_q == tcp) {
6971 					/*
6972 					 * If we are unlinking the last
6973 					 * element on the list, adjust
6974 					 * tail pointer. Set tail pointer
6975 					 * to nil when list is empty.
6976 					 */
6977 					ASSERT(tcp->tcp_eager_next_q == NULL);
6978 					if (listener->tcp_eager_last_q ==
6979 					    listener->tcp_eager_next_q) {
6980 						listener->tcp_eager_last_q =
6981 						    NULL;
6982 					} else {
6983 						/*
6984 						 * We won't get here if there
6985 						 * is only one eager in the
6986 						 * list.
6987 						 */
6988 						ASSERT(prev != NULL);
6989 						listener->tcp_eager_last_q =
6990 						    prev;
6991 					}
6992 				}
6993 				tcpp[0] = tcp->tcp_eager_next_q;
6994 				tcp->tcp_eager_next_q = NULL;
6995 				tcp->tcp_eager_last_q = NULL;
6996 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6997 				listener->tcp_conn_req_cnt_q--;
6998 				break;
6999 			}
7000 			prev = tcpp[0];
7001 		}
7002 	}
7003 	tcp->tcp_listener = NULL;
7004 }
7005 
7006 /* Shorthand to generate and send TPI error acks to our client */
7007 static void
7008 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7009 {
7010 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7011 		putnext(tcp->tcp_rq, mp);
7012 }
7013 
7014 /* Shorthand to generate and send TPI error acks to our client */
7015 static void
7016 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7017     int t_error, int sys_error)
7018 {
7019 	struct T_error_ack	*teackp;
7020 
7021 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7022 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7023 		teackp = (struct T_error_ack *)mp->b_rptr;
7024 		teackp->ERROR_prim = primitive;
7025 		teackp->TLI_error = t_error;
7026 		teackp->UNIX_error = sys_error;
7027 		putnext(tcp->tcp_rq, mp);
7028 	}
7029 }
7030 
7031 /*
7032  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7033  * but instead the code relies on:
7034  * - the fact that the address of the array and its size never changes
7035  * - the atomic assignment of the elements of the array
7036  */
7037 /* ARGSUSED */
7038 static int
7039 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7040 {
7041 	int i;
7042 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7043 
7044 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7045 		if (tcps->tcps_g_epriv_ports[i] != 0)
7046 			(void) mi_mpprintf(mp, "%d ",
7047 			    tcps->tcps_g_epriv_ports[i]);
7048 	}
7049 	return (0);
7050 }
7051 
7052 /*
7053  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7054  * threads from changing it at the same time.
7055  */
7056 /* ARGSUSED */
7057 static int
7058 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7059     cred_t *cr)
7060 {
7061 	long	new_value;
7062 	int	i;
7063 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7064 
7065 	/*
7066 	 * Fail the request if the new value does not lie within the
7067 	 * port number limits.
7068 	 */
7069 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7070 	    new_value <= 0 || new_value >= 65536) {
7071 		return (EINVAL);
7072 	}
7073 
7074 	mutex_enter(&tcps->tcps_epriv_port_lock);
7075 	/* Check if the value is already in the list */
7076 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7077 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7078 			mutex_exit(&tcps->tcps_epriv_port_lock);
7079 			return (EEXIST);
7080 		}
7081 	}
7082 	/* Find an empty slot */
7083 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7084 		if (tcps->tcps_g_epriv_ports[i] == 0)
7085 			break;
7086 	}
7087 	if (i == tcps->tcps_g_num_epriv_ports) {
7088 		mutex_exit(&tcps->tcps_epriv_port_lock);
7089 		return (EOVERFLOW);
7090 	}
7091 	/* Set the new value */
7092 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7093 	mutex_exit(&tcps->tcps_epriv_port_lock);
7094 	return (0);
7095 }
7096 
7097 /*
7098  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7099  * threads from changing it at the same time.
7100  */
7101 /* ARGSUSED */
7102 static int
7103 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7104     cred_t *cr)
7105 {
7106 	long	new_value;
7107 	int	i;
7108 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7109 
7110 	/*
7111 	 * Fail the request if the new value does not lie within the
7112 	 * port number limits.
7113 	 */
7114 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7115 	    new_value >= 65536) {
7116 		return (EINVAL);
7117 	}
7118 
7119 	mutex_enter(&tcps->tcps_epriv_port_lock);
7120 	/* Check that the value is already in the list */
7121 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7122 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7123 			break;
7124 	}
7125 	if (i == tcps->tcps_g_num_epriv_ports) {
7126 		mutex_exit(&tcps->tcps_epriv_port_lock);
7127 		return (ESRCH);
7128 	}
7129 	/* Clear the value */
7130 	tcps->tcps_g_epriv_ports[i] = 0;
7131 	mutex_exit(&tcps->tcps_epriv_port_lock);
7132 	return (0);
7133 }
7134 
7135 /* Return the TPI/TLI equivalent of our current tcp_state */
7136 static int
7137 tcp_tpistate(tcp_t *tcp)
7138 {
7139 	switch (tcp->tcp_state) {
7140 	case TCPS_IDLE:
7141 		return (TS_UNBND);
7142 	case TCPS_LISTEN:
7143 		/*
7144 		 * Return whether there are outstanding T_CONN_IND waiting
7145 		 * for the matching T_CONN_RES. Therefore don't count q0.
7146 		 */
7147 		if (tcp->tcp_conn_req_cnt_q > 0)
7148 			return (TS_WRES_CIND);
7149 		else
7150 			return (TS_IDLE);
7151 	case TCPS_BOUND:
7152 		return (TS_IDLE);
7153 	case TCPS_SYN_SENT:
7154 		return (TS_WCON_CREQ);
7155 	case TCPS_SYN_RCVD:
7156 		/*
7157 		 * Note: assumption: this has to the active open SYN_RCVD.
7158 		 * The passive instance is detached in SYN_RCVD stage of
7159 		 * incoming connection processing so we cannot get request
7160 		 * for T_info_ack on it.
7161 		 */
7162 		return (TS_WACK_CRES);
7163 	case TCPS_ESTABLISHED:
7164 		return (TS_DATA_XFER);
7165 	case TCPS_CLOSE_WAIT:
7166 		return (TS_WREQ_ORDREL);
7167 	case TCPS_FIN_WAIT_1:
7168 		return (TS_WIND_ORDREL);
7169 	case TCPS_FIN_WAIT_2:
7170 		return (TS_WIND_ORDREL);
7171 
7172 	case TCPS_CLOSING:
7173 	case TCPS_LAST_ACK:
7174 	case TCPS_TIME_WAIT:
7175 	case TCPS_CLOSED:
7176 		/*
7177 		 * Following TS_WACK_DREQ7 is a rendition of "not
7178 		 * yet TS_IDLE" TPI state. There is no best match to any
7179 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7180 		 * choose a value chosen that will map to TLI/XTI level
7181 		 * state of TSTATECHNG (state is process of changing) which
7182 		 * captures what this dummy state represents.
7183 		 */
7184 		return (TS_WACK_DREQ7);
7185 	default:
7186 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7187 		    tcp->tcp_state, tcp_display(tcp, NULL,
7188 		    DISP_PORT_ONLY));
7189 		return (TS_UNBND);
7190 	}
7191 }
7192 
7193 static void
7194 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7195 {
7196 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7197 
7198 	if (tcp->tcp_family == AF_INET6)
7199 		*tia = tcp_g_t_info_ack_v6;
7200 	else
7201 		*tia = tcp_g_t_info_ack;
7202 	tia->CURRENT_state = tcp_tpistate(tcp);
7203 	tia->OPT_size = tcp_max_optsize;
7204 	if (tcp->tcp_mss == 0) {
7205 		/* Not yet set - tcp_open does not set mss */
7206 		if (tcp->tcp_ipversion == IPV4_VERSION)
7207 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7208 		else
7209 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7210 	} else {
7211 		tia->TIDU_size = tcp->tcp_mss;
7212 	}
7213 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7214 }
7215 
7216 static void
7217 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7218     t_uscalar_t cap_bits1)
7219 {
7220 	tcap->CAP_bits1 = 0;
7221 
7222 	if (cap_bits1 & TC1_INFO) {
7223 		tcp_copy_info(&tcap->INFO_ack, tcp);
7224 		tcap->CAP_bits1 |= TC1_INFO;
7225 	}
7226 
7227 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7228 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7229 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7230 	}
7231 
7232 }
7233 
7234 /*
7235  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7236  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7237  * tcp_g_t_info_ack.  The current state of the stream is copied from
7238  * tcp_state.
7239  */
7240 static void
7241 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7242 {
7243 	t_uscalar_t		cap_bits1;
7244 	struct T_capability_ack	*tcap;
7245 
7246 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7247 		freemsg(mp);
7248 		return;
7249 	}
7250 
7251 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7252 
7253 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7254 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7255 	if (mp == NULL)
7256 		return;
7257 
7258 	tcap = (struct T_capability_ack *)mp->b_rptr;
7259 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7260 
7261 	putnext(tcp->tcp_rq, mp);
7262 }
7263 
7264 /*
7265  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7266  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7267  * The current state of the stream is copied from tcp_state.
7268  */
7269 static void
7270 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7271 {
7272 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7273 	    T_INFO_ACK);
7274 	if (!mp) {
7275 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7276 		return;
7277 	}
7278 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7279 	putnext(tcp->tcp_rq, mp);
7280 }
7281 
7282 /* Respond to the TPI addr request */
7283 static void
7284 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7285 {
7286 	sin_t	*sin;
7287 	mblk_t	*ackmp;
7288 	struct T_addr_ack *taa;
7289 
7290 	/* Make it large enough for worst case */
7291 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7292 	    2 * sizeof (sin6_t), 1);
7293 	if (ackmp == NULL) {
7294 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7295 		return;
7296 	}
7297 
7298 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7299 		tcp_addr_req_ipv6(tcp, ackmp);
7300 		return;
7301 	}
7302 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7303 
7304 	bzero(taa, sizeof (struct T_addr_ack));
7305 	ackmp->b_wptr = (uchar_t *)&taa[1];
7306 
7307 	taa->PRIM_type = T_ADDR_ACK;
7308 	ackmp->b_datap->db_type = M_PCPROTO;
7309 
7310 	/*
7311 	 * Note: Following code assumes 32 bit alignment of basic
7312 	 * data structures like sin_t and struct T_addr_ack.
7313 	 */
7314 	if (tcp->tcp_state >= TCPS_BOUND) {
7315 		/*
7316 		 * Fill in local address
7317 		 */
7318 		taa->LOCADDR_length = sizeof (sin_t);
7319 		taa->LOCADDR_offset = sizeof (*taa);
7320 
7321 		sin = (sin_t *)&taa[1];
7322 
7323 		/* Fill zeroes and then intialize non-zero fields */
7324 		*sin = sin_null;
7325 
7326 		sin->sin_family = AF_INET;
7327 
7328 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7329 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7330 
7331 		ackmp->b_wptr = (uchar_t *)&sin[1];
7332 
7333 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7334 			/*
7335 			 * Fill in Remote address
7336 			 */
7337 			taa->REMADDR_length = sizeof (sin_t);
7338 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7339 			    taa->LOCADDR_length);
7340 
7341 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7342 			*sin = sin_null;
7343 			sin->sin_family = AF_INET;
7344 			sin->sin_addr.s_addr = tcp->tcp_remote;
7345 			sin->sin_port = tcp->tcp_fport;
7346 
7347 			ackmp->b_wptr = (uchar_t *)&sin[1];
7348 		}
7349 	}
7350 	putnext(tcp->tcp_rq, ackmp);
7351 }
7352 
7353 /* Assumes that tcp_addr_req gets enough space and alignment */
7354 static void
7355 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7356 {
7357 	sin6_t	*sin6;
7358 	struct T_addr_ack *taa;
7359 
7360 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7361 	ASSERT(OK_32PTR(ackmp->b_rptr));
7362 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7363 	    2 * sizeof (sin6_t));
7364 
7365 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7366 
7367 	bzero(taa, sizeof (struct T_addr_ack));
7368 	ackmp->b_wptr = (uchar_t *)&taa[1];
7369 
7370 	taa->PRIM_type = T_ADDR_ACK;
7371 	ackmp->b_datap->db_type = M_PCPROTO;
7372 
7373 	/*
7374 	 * Note: Following code assumes 32 bit alignment of basic
7375 	 * data structures like sin6_t and struct T_addr_ack.
7376 	 */
7377 	if (tcp->tcp_state >= TCPS_BOUND) {
7378 		/*
7379 		 * Fill in local address
7380 		 */
7381 		taa->LOCADDR_length = sizeof (sin6_t);
7382 		taa->LOCADDR_offset = sizeof (*taa);
7383 
7384 		sin6 = (sin6_t *)&taa[1];
7385 		*sin6 = sin6_null;
7386 
7387 		sin6->sin6_family = AF_INET6;
7388 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7389 		sin6->sin6_port = tcp->tcp_lport;
7390 
7391 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7392 
7393 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7394 			/*
7395 			 * Fill in Remote address
7396 			 */
7397 			taa->REMADDR_length = sizeof (sin6_t);
7398 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7399 			    taa->LOCADDR_length);
7400 
7401 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7402 			*sin6 = sin6_null;
7403 			sin6->sin6_family = AF_INET6;
7404 			sin6->sin6_flowinfo =
7405 			    tcp->tcp_ip6h->ip6_vcf &
7406 			    ~IPV6_VERS_AND_FLOW_MASK;
7407 			sin6->sin6_addr = tcp->tcp_remote_v6;
7408 			sin6->sin6_port = tcp->tcp_fport;
7409 
7410 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7411 		}
7412 	}
7413 	putnext(tcp->tcp_rq, ackmp);
7414 }
7415 
7416 /*
7417  * Handle reinitialization of a tcp structure.
7418  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7419  */
7420 static void
7421 tcp_reinit(tcp_t *tcp)
7422 {
7423 	mblk_t	*mp;
7424 	int 	err;
7425 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7426 
7427 	TCP_STAT(tcps, tcp_reinit_calls);
7428 
7429 	/* tcp_reinit should never be called for detached tcp_t's */
7430 	ASSERT(tcp->tcp_listener == NULL);
7431 	ASSERT((tcp->tcp_family == AF_INET &&
7432 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7433 	    (tcp->tcp_family == AF_INET6 &&
7434 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7435 	    tcp->tcp_ipversion == IPV6_VERSION)));
7436 
7437 	/* Cancel outstanding timers */
7438 	tcp_timers_stop(tcp);
7439 
7440 	/*
7441 	 * Reset everything in the state vector, after updating global
7442 	 * MIB data from instance counters.
7443 	 */
7444 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7445 	tcp->tcp_ibsegs = 0;
7446 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7447 	tcp->tcp_obsegs = 0;
7448 
7449 	tcp_close_mpp(&tcp->tcp_xmit_head);
7450 	if (tcp->tcp_snd_zcopy_aware)
7451 		tcp_zcopy_notify(tcp);
7452 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7453 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7454 	mutex_enter(&tcp->tcp_non_sq_lock);
7455 	if (tcp->tcp_flow_stopped &&
7456 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7457 		tcp_clrqfull(tcp);
7458 	}
7459 	mutex_exit(&tcp->tcp_non_sq_lock);
7460 	tcp_close_mpp(&tcp->tcp_reass_head);
7461 	tcp->tcp_reass_tail = NULL;
7462 	if (tcp->tcp_rcv_list != NULL) {
7463 		/* Free b_next chain */
7464 		tcp_close_mpp(&tcp->tcp_rcv_list);
7465 		tcp->tcp_rcv_last_head = NULL;
7466 		tcp->tcp_rcv_last_tail = NULL;
7467 		tcp->tcp_rcv_cnt = 0;
7468 	}
7469 	tcp->tcp_rcv_last_tail = NULL;
7470 
7471 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7472 		freemsg(mp);
7473 		tcp->tcp_urp_mp = NULL;
7474 	}
7475 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7476 		freemsg(mp);
7477 		tcp->tcp_urp_mark_mp = NULL;
7478 	}
7479 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7480 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7481 		freeb(tcp->tcp_fused_sigurg_mp);
7482 		tcp->tcp_fused_sigurg_mp = NULL;
7483 	}
7484 	if (tcp->tcp_ordrel_mp != NULL) {
7485 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7486 		freeb(tcp->tcp_ordrel_mp);
7487 		tcp->tcp_ordrel_mp = NULL;
7488 	}
7489 
7490 	/*
7491 	 * Following is a union with two members which are
7492 	 * identical types and size so the following cleanup
7493 	 * is enough.
7494 	 */
7495 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7496 
7497 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7498 
7499 	/*
7500 	 * The connection can't be on the tcp_time_wait_head list
7501 	 * since it is not detached.
7502 	 */
7503 	ASSERT(tcp->tcp_time_wait_next == NULL);
7504 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7505 	ASSERT(tcp->tcp_time_wait_expire == 0);
7506 
7507 	if (tcp->tcp_kssl_pending) {
7508 		tcp->tcp_kssl_pending = B_FALSE;
7509 
7510 		/* Don't reset if the initialized by bind. */
7511 		if (tcp->tcp_kssl_ent != NULL) {
7512 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7513 			    KSSL_NO_PROXY);
7514 		}
7515 	}
7516 	if (tcp->tcp_kssl_ctx != NULL) {
7517 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7518 		tcp->tcp_kssl_ctx = NULL;
7519 	}
7520 
7521 	/*
7522 	 * Reset/preserve other values
7523 	 */
7524 	tcp_reinit_values(tcp);
7525 	ipcl_hash_remove(tcp->tcp_connp);
7526 	conn_delete_ire(tcp->tcp_connp, NULL);
7527 	tcp_ipsec_cleanup(tcp);
7528 
7529 	if (tcp->tcp_connp->conn_effective_cred != NULL) {
7530 		crfree(tcp->tcp_connp->conn_effective_cred);
7531 		tcp->tcp_connp->conn_effective_cred = NULL;
7532 	}
7533 
7534 	if (tcp->tcp_conn_req_max != 0) {
7535 		/*
7536 		 * This is the case when a TLI program uses the same
7537 		 * transport end point to accept a connection.  This
7538 		 * makes the TCP both a listener and acceptor.  When
7539 		 * this connection is closed, we need to set the state
7540 		 * back to TCPS_LISTEN.  Make sure that the eager list
7541 		 * is reinitialized.
7542 		 *
7543 		 * Note that this stream is still bound to the four
7544 		 * tuples of the previous connection in IP.  If a new
7545 		 * SYN with different foreign address comes in, IP will
7546 		 * not find it and will send it to the global queue.  In
7547 		 * the global queue, TCP will do a tcp_lookup_listener()
7548 		 * to find this stream.  This works because this stream
7549 		 * is only removed from connected hash.
7550 		 *
7551 		 */
7552 		tcp->tcp_state = TCPS_LISTEN;
7553 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7554 		tcp->tcp_eager_next_drop_q0 = tcp;
7555 		tcp->tcp_eager_prev_drop_q0 = tcp;
7556 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7557 		if (tcp->tcp_family == AF_INET6) {
7558 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7559 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7560 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7561 		} else {
7562 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7563 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7564 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7565 		}
7566 	} else {
7567 		tcp->tcp_state = TCPS_BOUND;
7568 	}
7569 
7570 	/*
7571 	 * Initialize to default values
7572 	 * Can't fail since enough header template space already allocated
7573 	 * at open().
7574 	 */
7575 	err = tcp_init_values(tcp);
7576 	ASSERT(err == 0);
7577 	/* Restore state in tcp_tcph */
7578 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7579 	if (tcp->tcp_ipversion == IPV4_VERSION)
7580 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7581 	else
7582 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7583 	/*
7584 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7585 	 * since the lookup funcs can only lookup on tcp_t
7586 	 */
7587 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7588 
7589 	ASSERT(tcp->tcp_ptpbhn != NULL);
7590 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7591 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7592 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7593 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7594 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7595 }
7596 
7597 /*
7598  * Force values to zero that need be zero.
7599  * Do not touch values asociated with the BOUND or LISTEN state
7600  * since the connection will end up in that state after the reinit.
7601  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7602  * structure!
7603  */
7604 static void
7605 tcp_reinit_values(tcp)
7606 	tcp_t *tcp;
7607 {
7608 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7609 
7610 #ifndef	lint
7611 #define	DONTCARE(x)
7612 #define	PRESERVE(x)
7613 #else
7614 #define	DONTCARE(x)	((x) = (x))
7615 #define	PRESERVE(x)	((x) = (x))
7616 #endif	/* lint */
7617 
7618 	PRESERVE(tcp->tcp_bind_hash_port);
7619 	PRESERVE(tcp->tcp_bind_hash);
7620 	PRESERVE(tcp->tcp_ptpbhn);
7621 	PRESERVE(tcp->tcp_acceptor_hash);
7622 	PRESERVE(tcp->tcp_ptpahn);
7623 
7624 	/* Should be ASSERT NULL on these with new code! */
7625 	ASSERT(tcp->tcp_time_wait_next == NULL);
7626 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7627 	ASSERT(tcp->tcp_time_wait_expire == 0);
7628 	PRESERVE(tcp->tcp_state);
7629 	PRESERVE(tcp->tcp_rq);
7630 	PRESERVE(tcp->tcp_wq);
7631 
7632 	ASSERT(tcp->tcp_xmit_head == NULL);
7633 	ASSERT(tcp->tcp_xmit_last == NULL);
7634 	ASSERT(tcp->tcp_unsent == 0);
7635 	ASSERT(tcp->tcp_xmit_tail == NULL);
7636 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7637 
7638 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7639 	tcp->tcp_suna = 0;			/* Displayed in mib */
7640 	tcp->tcp_swnd = 0;
7641 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7642 
7643 	ASSERT(tcp->tcp_ibsegs == 0);
7644 	ASSERT(tcp->tcp_obsegs == 0);
7645 
7646 	if (tcp->tcp_iphc != NULL) {
7647 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7648 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7649 	}
7650 
7651 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7652 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7653 	DONTCARE(tcp->tcp_ipha);
7654 	DONTCARE(tcp->tcp_ip6h);
7655 	DONTCARE(tcp->tcp_ip_hdr_len);
7656 	DONTCARE(tcp->tcp_tcph);
7657 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7658 	tcp->tcp_valid_bits = 0;
7659 
7660 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7661 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7662 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7663 	tcp->tcp_last_rcv_lbolt = 0;
7664 
7665 	tcp->tcp_init_cwnd = 0;
7666 
7667 	tcp->tcp_urp_last_valid = 0;
7668 	tcp->tcp_hard_binding = 0;
7669 	tcp->tcp_hard_bound = 0;
7670 	PRESERVE(tcp->tcp_cred);
7671 	PRESERVE(tcp->tcp_cpid);
7672 	PRESERVE(tcp->tcp_open_time);
7673 	PRESERVE(tcp->tcp_exclbind);
7674 
7675 	tcp->tcp_fin_acked = 0;
7676 	tcp->tcp_fin_rcvd = 0;
7677 	tcp->tcp_fin_sent = 0;
7678 	tcp->tcp_ordrel_done = 0;
7679 
7680 	tcp->tcp_debug = 0;
7681 	tcp->tcp_dontroute = 0;
7682 	tcp->tcp_broadcast = 0;
7683 
7684 	tcp->tcp_useloopback = 0;
7685 	tcp->tcp_reuseaddr = 0;
7686 	tcp->tcp_oobinline = 0;
7687 	tcp->tcp_dgram_errind = 0;
7688 
7689 	tcp->tcp_detached = 0;
7690 	tcp->tcp_bind_pending = 0;
7691 	tcp->tcp_unbind_pending = 0;
7692 
7693 	tcp->tcp_snd_ws_ok = B_FALSE;
7694 	tcp->tcp_snd_ts_ok = B_FALSE;
7695 	tcp->tcp_linger = 0;
7696 	tcp->tcp_ka_enabled = 0;
7697 	tcp->tcp_zero_win_probe = 0;
7698 
7699 	tcp->tcp_loopback = 0;
7700 	tcp->tcp_refuse = 0;
7701 	tcp->tcp_localnet = 0;
7702 	tcp->tcp_syn_defense = 0;
7703 	tcp->tcp_set_timer = 0;
7704 
7705 	tcp->tcp_active_open = 0;
7706 	tcp->tcp_rexmit = B_FALSE;
7707 	tcp->tcp_xmit_zc_clean = B_FALSE;
7708 
7709 	tcp->tcp_snd_sack_ok = B_FALSE;
7710 	PRESERVE(tcp->tcp_recvdstaddr);
7711 	tcp->tcp_hwcksum = B_FALSE;
7712 
7713 	tcp->tcp_ire_ill_check_done = B_FALSE;
7714 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7715 
7716 	tcp->tcp_mdt = B_FALSE;
7717 	tcp->tcp_mdt_hdr_head = 0;
7718 	tcp->tcp_mdt_hdr_tail = 0;
7719 
7720 	tcp->tcp_conn_def_q0 = 0;
7721 	tcp->tcp_ip_forward_progress = B_FALSE;
7722 	tcp->tcp_anon_priv_bind = 0;
7723 	tcp->tcp_ecn_ok = B_FALSE;
7724 
7725 	tcp->tcp_cwr = B_FALSE;
7726 	tcp->tcp_ecn_echo_on = B_FALSE;
7727 	tcp->tcp_is_wnd_shrnk = B_FALSE;
7728 
7729 	if (tcp->tcp_sack_info != NULL) {
7730 		if (tcp->tcp_notsack_list != NULL) {
7731 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
7732 			    tcp);
7733 		}
7734 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7735 		tcp->tcp_sack_info = NULL;
7736 	}
7737 
7738 	tcp->tcp_rcv_ws = 0;
7739 	tcp->tcp_snd_ws = 0;
7740 	tcp->tcp_ts_recent = 0;
7741 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7742 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7743 	tcp->tcp_if_mtu = 0;
7744 
7745 	ASSERT(tcp->tcp_reass_head == NULL);
7746 	ASSERT(tcp->tcp_reass_tail == NULL);
7747 
7748 	tcp->tcp_cwnd_cnt = 0;
7749 
7750 	ASSERT(tcp->tcp_rcv_list == NULL);
7751 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7752 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7753 	ASSERT(tcp->tcp_rcv_cnt == 0);
7754 
7755 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7756 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7757 	tcp->tcp_csuna = 0;
7758 
7759 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7760 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7761 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7762 	tcp->tcp_rtt_update = 0;
7763 
7764 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7765 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7766 
7767 	tcp->tcp_rack = 0;			/* Displayed in mib */
7768 	tcp->tcp_rack_cnt = 0;
7769 	tcp->tcp_rack_cur_max = 0;
7770 	tcp->tcp_rack_abs_max = 0;
7771 
7772 	tcp->tcp_max_swnd = 0;
7773 
7774 	ASSERT(tcp->tcp_listener == NULL);
7775 
7776 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7777 
7778 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7779 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7780 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7781 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7782 
7783 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7784 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7785 	PRESERVE(tcp->tcp_conn_req_max);
7786 	PRESERVE(tcp->tcp_conn_req_seqnum);
7787 
7788 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7789 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7790 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7791 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7792 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7793 
7794 	tcp->tcp_lingertime = 0;
7795 
7796 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7797 	ASSERT(tcp->tcp_urp_mp == NULL);
7798 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7799 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7800 
7801 	ASSERT(tcp->tcp_eager_next_q == NULL);
7802 	ASSERT(tcp->tcp_eager_last_q == NULL);
7803 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7804 	    tcp->tcp_eager_prev_q0 == NULL) ||
7805 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7806 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7807 
7808 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7809 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7810 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7811 
7812 	tcp->tcp_client_errno = 0;
7813 
7814 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7815 
7816 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7817 
7818 	PRESERVE(tcp->tcp_bound_source_v6);
7819 	tcp->tcp_last_sent_len = 0;
7820 	tcp->tcp_dupack_cnt = 0;
7821 
7822 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7823 	PRESERVE(tcp->tcp_lport);
7824 
7825 	PRESERVE(tcp->tcp_acceptor_lockp);
7826 
7827 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7828 	PRESERVE(tcp->tcp_acceptor_id);
7829 	DONTCARE(tcp->tcp_ipsec_overhead);
7830 
7831 	PRESERVE(tcp->tcp_family);
7832 	if (tcp->tcp_family == AF_INET6) {
7833 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7834 	} else {
7835 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7836 	}
7837 	PRESERVE(tcp->tcp_ipversion);		/* Init in tcp_init_values */
7838 
7839 	tcp->tcp_bound_if = 0;
7840 	tcp->tcp_ipv6_recvancillary = 0;
7841 	tcp->tcp_recvifindex = 0;
7842 	tcp->tcp_recvhops = 0;
7843 	tcp->tcp_closed = 0;
7844 	tcp->tcp_cleandeathtag = 0;
7845 	if (tcp->tcp_hopopts != NULL) {
7846 		mi_free(tcp->tcp_hopopts);
7847 		tcp->tcp_hopopts = NULL;
7848 		tcp->tcp_hopoptslen = 0;
7849 	}
7850 	ASSERT(tcp->tcp_hopoptslen == 0);
7851 	if (tcp->tcp_dstopts != NULL) {
7852 		mi_free(tcp->tcp_dstopts);
7853 		tcp->tcp_dstopts = NULL;
7854 		tcp->tcp_dstoptslen = 0;
7855 	}
7856 	ASSERT(tcp->tcp_dstoptslen == 0);
7857 	if (tcp->tcp_rtdstopts != NULL) {
7858 		mi_free(tcp->tcp_rtdstopts);
7859 		tcp->tcp_rtdstopts = NULL;
7860 		tcp->tcp_rtdstoptslen = 0;
7861 	}
7862 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7863 	if (tcp->tcp_rthdr != NULL) {
7864 		mi_free(tcp->tcp_rthdr);
7865 		tcp->tcp_rthdr = NULL;
7866 		tcp->tcp_rthdrlen = 0;
7867 	}
7868 	ASSERT(tcp->tcp_rthdrlen == 0);
7869 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7870 
7871 	/* Reset fusion-related fields */
7872 	tcp->tcp_fused = B_FALSE;
7873 	tcp->tcp_unfusable = B_FALSE;
7874 	tcp->tcp_fused_sigurg = B_FALSE;
7875 	tcp->tcp_loopback_peer = NULL;
7876 
7877 	tcp->tcp_lso = B_FALSE;
7878 
7879 	tcp->tcp_in_ack_unsent = 0;
7880 	tcp->tcp_cork = B_FALSE;
7881 	tcp->tcp_tconnind_started = B_FALSE;
7882 
7883 	PRESERVE(tcp->tcp_squeue_bytes);
7884 
7885 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7886 	ASSERT(!tcp->tcp_kssl_pending);
7887 	PRESERVE(tcp->tcp_kssl_ent);
7888 
7889 	tcp->tcp_closemp_used = B_FALSE;
7890 
7891 	PRESERVE(tcp->tcp_rsrv_mp);
7892 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7893 
7894 #ifdef DEBUG
7895 	DONTCARE(tcp->tcmp_stk[0]);
7896 #endif
7897 
7898 	PRESERVE(tcp->tcp_connid);
7899 
7900 
7901 #undef	DONTCARE
7902 #undef	PRESERVE
7903 }
7904 
7905 /*
7906  * Allocate necessary resources and initialize state vector.
7907  * Guaranteed not to fail so that when an error is returned,
7908  * the caller doesn't need to do any additional cleanup.
7909  */
7910 int
7911 tcp_init(tcp_t *tcp, queue_t *q)
7912 {
7913 	int	err;
7914 
7915 	tcp->tcp_rq = q;
7916 	tcp->tcp_wq = WR(q);
7917 	tcp->tcp_state = TCPS_IDLE;
7918 	if ((err = tcp_init_values(tcp)) != 0)
7919 		tcp_timers_stop(tcp);
7920 	return (err);
7921 }
7922 
7923 static int
7924 tcp_init_values(tcp_t *tcp)
7925 {
7926 	int	err;
7927 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7928 
7929 	ASSERT((tcp->tcp_family == AF_INET &&
7930 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7931 	    (tcp->tcp_family == AF_INET6 &&
7932 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7933 	    tcp->tcp_ipversion == IPV6_VERSION)));
7934 
7935 	/*
7936 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7937 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7938 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7939 	 * during first few transmissions of a connection as seen in slow
7940 	 * links.
7941 	 */
7942 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7943 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7944 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7945 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7946 	    tcps->tcps_conn_grace_period;
7947 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7948 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7949 	tcp->tcp_timer_backoff = 0;
7950 	tcp->tcp_ms_we_have_waited = 0;
7951 	tcp->tcp_last_recv_time = lbolt;
7952 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7953 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7954 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7955 
7956 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7957 
7958 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7959 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7960 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7961 	/*
7962 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7963 	 * passive open.
7964 	 */
7965 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7966 
7967 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7968 
7969 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7970 
7971 	tcp->tcp_mdt_hdr_head = 0;
7972 	tcp->tcp_mdt_hdr_tail = 0;
7973 
7974 	/* Reset fusion-related fields */
7975 	tcp->tcp_fused = B_FALSE;
7976 	tcp->tcp_unfusable = B_FALSE;
7977 	tcp->tcp_fused_sigurg = B_FALSE;
7978 	tcp->tcp_loopback_peer = NULL;
7979 
7980 	/* Initialize the header template */
7981 	if (tcp->tcp_family == AF_INET) {
7982 		err = tcp_header_init_ipv4(tcp);
7983 	} else {
7984 		err = tcp_header_init_ipv6(tcp);
7985 	}
7986 	if (err)
7987 		return (err);
7988 
7989 	/*
7990 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7991 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7992 	 */
7993 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7994 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7995 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
7996 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7997 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7998 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7999 
8000 	tcp->tcp_cork = B_FALSE;
8001 	/*
8002 	 * Init the tcp_debug option.  This value determines whether TCP
8003 	 * calls strlog() to print out debug messages.  Doing this
8004 	 * initialization here means that this value is not inherited thru
8005 	 * tcp_reinit().
8006 	 */
8007 	tcp->tcp_debug = tcps->tcps_dbg;
8008 
8009 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8010 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8011 
8012 	return (0);
8013 }
8014 
8015 /*
8016  * Initialize the IPv4 header. Loses any record of any IP options.
8017  */
8018 static int
8019 tcp_header_init_ipv4(tcp_t *tcp)
8020 {
8021 	tcph_t		*tcph;
8022 	uint32_t	sum;
8023 	conn_t		*connp;
8024 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8025 
8026 	/*
8027 	 * This is a simple initialization. If there's
8028 	 * already a template, it should never be too small,
8029 	 * so reuse it.  Otherwise, allocate space for the new one.
8030 	 */
8031 	if (tcp->tcp_iphc == NULL) {
8032 		ASSERT(tcp->tcp_iphc_len == 0);
8033 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8034 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8035 		if (tcp->tcp_iphc == NULL) {
8036 			tcp->tcp_iphc_len = 0;
8037 			return (ENOMEM);
8038 		}
8039 	}
8040 
8041 	/* options are gone; may need a new label */
8042 	connp = tcp->tcp_connp;
8043 	connp->conn_mlp_type = mlptSingle;
8044 	connp->conn_ulp_labeled = !is_system_labeled();
8045 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8046 
8047 	/*
8048 	 * tcp_do_get{sock,peer}name constructs the sockaddr from the
8049 	 * ip header, and decides which header to use based on ip version.
8050 	 * That operation happens outside the squeue, so we hold the lock
8051 	 * here to ensure that the ip version and header remain consistent.
8052 	 */
8053 	mutex_enter(&connp->conn_lock);
8054 	tcp->tcp_ipversion = IPV4_VERSION;
8055 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8056 	tcp->tcp_ip6h = NULL;
8057 	mutex_exit(&connp->conn_lock);
8058 
8059 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8060 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8061 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8062 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8063 	tcp->tcp_ipha->ipha_version_and_hdr_length
8064 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8065 	tcp->tcp_ipha->ipha_ident = 0;
8066 
8067 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8068 	tcp->tcp_tos = 0;
8069 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8070 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8071 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8072 
8073 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8074 	tcp->tcp_tcph = tcph;
8075 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8076 	/*
8077 	 * IP wants our header length in the checksum field to
8078 	 * allow it to perform a single pseudo-header+checksum
8079 	 * calculation on behalf of TCP.
8080 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8081 	 */
8082 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8083 	sum = (sum >> 16) + (sum & 0xFFFF);
8084 	U16_TO_ABE16(sum, tcph->th_sum);
8085 	return (0);
8086 }
8087 
8088 /*
8089  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8090  */
8091 static int
8092 tcp_header_init_ipv6(tcp_t *tcp)
8093 {
8094 	tcph_t	*tcph;
8095 	uint32_t	sum;
8096 	conn_t	*connp;
8097 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8098 
8099 	/*
8100 	 * This is a simple initialization. If there's
8101 	 * already a template, it should never be too small,
8102 	 * so reuse it. Otherwise, allocate space for the new one.
8103 	 * Ensure that there is enough space to "downgrade" the tcp_t
8104 	 * to an IPv4 tcp_t. This requires having space for a full load
8105 	 * of IPv4 options, as well as a full load of TCP options
8106 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8107 	 * than a v6 header and a TCP header with a full load of TCP options
8108 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8109 	 * We want to avoid reallocation in the "downgraded" case when
8110 	 * processing outbound IPv4 options.
8111 	 */
8112 	if (tcp->tcp_iphc == NULL) {
8113 		ASSERT(tcp->tcp_iphc_len == 0);
8114 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8115 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8116 		if (tcp->tcp_iphc == NULL) {
8117 			tcp->tcp_iphc_len = 0;
8118 			return (ENOMEM);
8119 		}
8120 	}
8121 
8122 	/* options are gone; may need a new label */
8123 	connp = tcp->tcp_connp;
8124 	connp->conn_mlp_type = mlptSingle;
8125 	connp->conn_ulp_labeled = !is_system_labeled();
8126 
8127 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8128 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8129 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8130 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8131 
8132 	/*
8133 	 * tcp_do_get{sock,peer}name constructs the sockaddr from the
8134 	 * ip header, and decides which header to use based on ip version.
8135 	 * That operation happens outside the squeue, so we hold the lock
8136 	 * here to ensure that the ip version and header remain consistent.
8137 	 */
8138 	mutex_enter(&connp->conn_lock);
8139 	tcp->tcp_ipversion = IPV6_VERSION;
8140 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8141 	tcp->tcp_ipha = NULL;
8142 	mutex_exit(&connp->conn_lock);
8143 
8144 	/* Initialize the header template */
8145 
8146 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8147 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8148 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8149 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8150 
8151 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8152 	tcp->tcp_tcph = tcph;
8153 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8154 	/*
8155 	 * IP wants our header length in the checksum field to
8156 	 * allow it to perform a single psuedo-header+checksum
8157 	 * calculation on behalf of TCP.
8158 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8159 	 */
8160 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8161 	sum = (sum >> 16) + (sum & 0xFFFF);
8162 	U16_TO_ABE16(sum, tcph->th_sum);
8163 	return (0);
8164 }
8165 
8166 /* At minimum we need 8 bytes in the TCP header for the lookup */
8167 #define	ICMP_MIN_TCP_HDR	8
8168 
8169 /*
8170  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8171  * passed up by IP. The message is always received on the correct tcp_t.
8172  * Assumes that IP has pulled up everything up to and including the ICMP header.
8173  */
8174 void
8175 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8176 {
8177 	icmph_t *icmph;
8178 	ipha_t	*ipha;
8179 	int	iph_hdr_length;
8180 	tcph_t	*tcph;
8181 	boolean_t ipsec_mctl = B_FALSE;
8182 	boolean_t secure;
8183 	mblk_t *first_mp = mp;
8184 	int32_t new_mss;
8185 	uint32_t ratio;
8186 	size_t mp_size = MBLKL(mp);
8187 	uint32_t seg_seq;
8188 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8189 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8190 
8191 	/* Assume IP provides aligned packets - otherwise toss */
8192 	if (!OK_32PTR(mp->b_rptr)) {
8193 		freemsg(mp);
8194 		return;
8195 	}
8196 
8197 	/*
8198 	 * Since ICMP errors are normal data marked with M_CTL when sent
8199 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8200 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8201 	 */
8202 	if ((mp_size == sizeof (ipsec_info_t)) &&
8203 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8204 		ASSERT(mp->b_cont != NULL);
8205 		mp = mp->b_cont;
8206 		/* IP should have done this */
8207 		ASSERT(OK_32PTR(mp->b_rptr));
8208 		mp_size = MBLKL(mp);
8209 		ipsec_mctl = B_TRUE;
8210 	}
8211 
8212 	/*
8213 	 * Verify that we have a complete outer IP header. If not, drop it.
8214 	 */
8215 	if (mp_size < sizeof (ipha_t)) {
8216 noticmpv4:
8217 		freemsg(first_mp);
8218 		return;
8219 	}
8220 
8221 	ipha = (ipha_t *)mp->b_rptr;
8222 	/*
8223 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8224 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8225 	 */
8226 	switch (IPH_HDR_VERSION(ipha)) {
8227 	case IPV6_VERSION:
8228 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8229 		return;
8230 	case IPV4_VERSION:
8231 		break;
8232 	default:
8233 		goto noticmpv4;
8234 	}
8235 
8236 	/* Skip past the outer IP and ICMP headers */
8237 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8238 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8239 	/*
8240 	 * If we don't have the correct outer IP header length or if the ULP
8241 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8242 	 * send it upstream.
8243 	 */
8244 	if (iph_hdr_length < sizeof (ipha_t) ||
8245 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8246 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8247 		goto noticmpv4;
8248 	}
8249 	ipha = (ipha_t *)&icmph[1];
8250 
8251 	/* Skip past the inner IP and find the ULP header */
8252 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8253 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8254 	/*
8255 	 * If we don't have the correct inner IP header length or if the ULP
8256 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8257 	 * bytes of TCP header, drop it.
8258 	 */
8259 	if (iph_hdr_length < sizeof (ipha_t) ||
8260 	    ipha->ipha_protocol != IPPROTO_TCP ||
8261 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8262 		goto noticmpv4;
8263 	}
8264 
8265 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8266 		if (ipsec_mctl) {
8267 			secure = ipsec_in_is_secure(first_mp);
8268 		} else {
8269 			secure = B_FALSE;
8270 		}
8271 		if (secure) {
8272 			/*
8273 			 * If we are willing to accept this in clear
8274 			 * we don't have to verify policy.
8275 			 */
8276 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8277 				if (!tcp_check_policy(tcp, first_mp,
8278 				    ipha, NULL, secure, ipsec_mctl)) {
8279 					/*
8280 					 * tcp_check_policy called
8281 					 * ip_drop_packet() on failure.
8282 					 */
8283 					return;
8284 				}
8285 			}
8286 		}
8287 	} else if (ipsec_mctl) {
8288 		/*
8289 		 * This is a hard_bound connection. IP has already
8290 		 * verified policy. We don't have to do it again.
8291 		 */
8292 		freeb(first_mp);
8293 		first_mp = mp;
8294 		ipsec_mctl = B_FALSE;
8295 	}
8296 
8297 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8298 	/*
8299 	 * TCP SHOULD check that the TCP sequence number contained in
8300 	 * payload of the ICMP error message is within the range
8301 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8302 	 */
8303 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8304 		/*
8305 		 * The ICMP message is bogus, just drop it.  But if this is
8306 		 * an ICMP too big message, IP has already changed
8307 		 * the ire_max_frag to the bogus value.  We need to change
8308 		 * it back.
8309 		 */
8310 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8311 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8312 			conn_t *connp = tcp->tcp_connp;
8313 			ire_t *ire;
8314 			int flag;
8315 
8316 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8317 				flag = tcp->tcp_ipha->
8318 				    ipha_fragment_offset_and_flags;
8319 			} else {
8320 				flag = 0;
8321 			}
8322 			mutex_enter(&connp->conn_lock);
8323 			if ((ire = connp->conn_ire_cache) != NULL) {
8324 				mutex_enter(&ire->ire_lock);
8325 				mutex_exit(&connp->conn_lock);
8326 				ire->ire_max_frag = tcp->tcp_if_mtu;
8327 				ire->ire_frag_flag |= flag;
8328 				mutex_exit(&ire->ire_lock);
8329 			} else {
8330 				mutex_exit(&connp->conn_lock);
8331 			}
8332 		}
8333 		goto noticmpv4;
8334 	}
8335 
8336 	switch (icmph->icmph_type) {
8337 	case ICMP_DEST_UNREACHABLE:
8338 		switch (icmph->icmph_code) {
8339 		case ICMP_FRAGMENTATION_NEEDED:
8340 			/*
8341 			 * Reduce the MSS based on the new MTU.  This will
8342 			 * eliminate any fragmentation locally.
8343 			 * N.B.  There may well be some funny side-effects on
8344 			 * the local send policy and the remote receive policy.
8345 			 * Pending further research, we provide
8346 			 * tcp_ignore_path_mtu just in case this proves
8347 			 * disastrous somewhere.
8348 			 *
8349 			 * After updating the MSS, retransmit part of the
8350 			 * dropped segment using the new mss by calling
8351 			 * tcp_wput_data().  Need to adjust all those
8352 			 * params to make sure tcp_wput_data() work properly.
8353 			 */
8354 			if (tcps->tcps_ignore_path_mtu ||
8355 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8356 				break;
8357 
8358 			/*
8359 			 * Decrease the MSS by time stamp options
8360 			 * IP options and IPSEC options. tcp_hdr_len
8361 			 * includes time stamp option and IP option
8362 			 * length.  Note that new_mss may be negative
8363 			 * if tcp_ipsec_overhead is large and the
8364 			 * icmph_du_mtu is the minimum value, which is 68.
8365 			 */
8366 			new_mss = ntohs(icmph->icmph_du_mtu) -
8367 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8368 
8369 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8370 			    new_mss);
8371 
8372 			/*
8373 			 * Only update the MSS if the new one is
8374 			 * smaller than the previous one.  This is
8375 			 * to avoid problems when getting multiple
8376 			 * ICMP errors for the same MTU.
8377 			 */
8378 			if (new_mss >= tcp->tcp_mss)
8379 				break;
8380 
8381 			/*
8382 			 * Note that we are using the template header's DF
8383 			 * bit in the fast path sending.  So we need to compare
8384 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8385 			 * And stop doing IPv4 PMTUd if new_mss is less than
8386 			 * MAX(tcps_mss_min, ip_pmtu_min).
8387 			 */
8388 			if (new_mss < tcps->tcps_mss_min ||
8389 			    new_mss < ipst->ips_ip_pmtu_min) {
8390 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8391 				    0;
8392 			}
8393 
8394 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8395 			ASSERT(ratio >= 1);
8396 			tcp_mss_set(tcp, new_mss, B_TRUE);
8397 
8398 			/*
8399 			 * Make sure we have something to
8400 			 * send.
8401 			 */
8402 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8403 			    (tcp->tcp_xmit_head != NULL)) {
8404 				/*
8405 				 * Shrink tcp_cwnd in
8406 				 * proportion to the old MSS/new MSS.
8407 				 */
8408 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8409 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8410 				    (tcp->tcp_unsent == 0)) {
8411 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8412 				} else {
8413 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8414 				}
8415 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8416 				tcp->tcp_rexmit = B_TRUE;
8417 				tcp->tcp_dupack_cnt = 0;
8418 				tcp->tcp_snd_burst = TCP_CWND_SS;
8419 				tcp_ss_rexmit(tcp);
8420 			}
8421 			break;
8422 		case ICMP_PORT_UNREACHABLE:
8423 		case ICMP_PROTOCOL_UNREACHABLE:
8424 			switch (tcp->tcp_state) {
8425 			case TCPS_SYN_SENT:
8426 			case TCPS_SYN_RCVD:
8427 				/*
8428 				 * ICMP can snipe away incipient
8429 				 * TCP connections as long as
8430 				 * seq number is same as initial
8431 				 * send seq number.
8432 				 */
8433 				if (seg_seq == tcp->tcp_iss) {
8434 					(void) tcp_clean_death(tcp,
8435 					    ECONNREFUSED, 6);
8436 				}
8437 				break;
8438 			}
8439 			break;
8440 		case ICMP_HOST_UNREACHABLE:
8441 		case ICMP_NET_UNREACHABLE:
8442 			/* Record the error in case we finally time out. */
8443 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8444 				tcp->tcp_client_errno = EHOSTUNREACH;
8445 			else
8446 				tcp->tcp_client_errno = ENETUNREACH;
8447 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8448 				if (tcp->tcp_listener != NULL &&
8449 				    tcp->tcp_listener->tcp_syn_defense) {
8450 					/*
8451 					 * Ditch the half-open connection if we
8452 					 * suspect a SYN attack is under way.
8453 					 */
8454 					tcp_ip_ire_mark_advice(tcp);
8455 					(void) tcp_clean_death(tcp,
8456 					    tcp->tcp_client_errno, 7);
8457 				}
8458 			}
8459 			break;
8460 		default:
8461 			break;
8462 		}
8463 		break;
8464 	case ICMP_SOURCE_QUENCH: {
8465 		/*
8466 		 * use a global boolean to control
8467 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8468 		 * The default is false.
8469 		 */
8470 		if (tcp_icmp_source_quench) {
8471 			/*
8472 			 * Reduce the sending rate as if we got a
8473 			 * retransmit timeout
8474 			 */
8475 			uint32_t npkt;
8476 
8477 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8478 			    tcp->tcp_mss;
8479 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8480 			tcp->tcp_cwnd = tcp->tcp_mss;
8481 			tcp->tcp_cwnd_cnt = 0;
8482 		}
8483 		break;
8484 	}
8485 	}
8486 	freemsg(first_mp);
8487 }
8488 
8489 /*
8490  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8491  * error messages passed up by IP.
8492  * Assumes that IP has pulled up all the extension headers as well
8493  * as the ICMPv6 header.
8494  */
8495 static void
8496 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8497 {
8498 	icmp6_t *icmp6;
8499 	ip6_t	*ip6h;
8500 	uint16_t	iph_hdr_length;
8501 	tcpha_t	*tcpha;
8502 	uint8_t	*nexthdrp;
8503 	uint32_t new_mss;
8504 	uint32_t ratio;
8505 	boolean_t secure;
8506 	mblk_t *first_mp = mp;
8507 	size_t mp_size;
8508 	uint32_t seg_seq;
8509 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8510 
8511 	/*
8512 	 * The caller has determined if this is an IPSEC_IN packet and
8513 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8514 	 */
8515 	if (ipsec_mctl)
8516 		mp = mp->b_cont;
8517 
8518 	mp_size = MBLKL(mp);
8519 
8520 	/*
8521 	 * Verify that we have a complete IP header. If not, send it upstream.
8522 	 */
8523 	if (mp_size < sizeof (ip6_t)) {
8524 noticmpv6:
8525 		freemsg(first_mp);
8526 		return;
8527 	}
8528 
8529 	/*
8530 	 * Verify this is an ICMPV6 packet, else send it upstream.
8531 	 */
8532 	ip6h = (ip6_t *)mp->b_rptr;
8533 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8534 		iph_hdr_length = IPV6_HDR_LEN;
8535 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8536 	    &nexthdrp) ||
8537 	    *nexthdrp != IPPROTO_ICMPV6) {
8538 		goto noticmpv6;
8539 	}
8540 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8541 	ip6h = (ip6_t *)&icmp6[1];
8542 	/*
8543 	 * Verify if we have a complete ICMP and inner IP header.
8544 	 */
8545 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8546 		goto noticmpv6;
8547 
8548 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8549 		goto noticmpv6;
8550 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8551 	/*
8552 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8553 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8554 	 * packet.
8555 	 */
8556 	if ((*nexthdrp != IPPROTO_TCP) ||
8557 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8558 		goto noticmpv6;
8559 	}
8560 
8561 	/*
8562 	 * ICMP errors come on the right queue or come on
8563 	 * listener/global queue for detached connections and
8564 	 * get switched to the right queue. If it comes on the
8565 	 * right queue, policy check has already been done by IP
8566 	 * and thus free the first_mp without verifying the policy.
8567 	 * If it has come for a non-hard bound connection, we need
8568 	 * to verify policy as IP may not have done it.
8569 	 */
8570 	if (!tcp->tcp_hard_bound) {
8571 		if (ipsec_mctl) {
8572 			secure = ipsec_in_is_secure(first_mp);
8573 		} else {
8574 			secure = B_FALSE;
8575 		}
8576 		if (secure) {
8577 			/*
8578 			 * If we are willing to accept this in clear
8579 			 * we don't have to verify policy.
8580 			 */
8581 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8582 				if (!tcp_check_policy(tcp, first_mp,
8583 				    NULL, ip6h, secure, ipsec_mctl)) {
8584 					/*
8585 					 * tcp_check_policy called
8586 					 * ip_drop_packet() on failure.
8587 					 */
8588 					return;
8589 				}
8590 			}
8591 		}
8592 	} else if (ipsec_mctl) {
8593 		/*
8594 		 * This is a hard_bound connection. IP has already
8595 		 * verified policy. We don't have to do it again.
8596 		 */
8597 		freeb(first_mp);
8598 		first_mp = mp;
8599 		ipsec_mctl = B_FALSE;
8600 	}
8601 
8602 	seg_seq = ntohl(tcpha->tha_seq);
8603 	/*
8604 	 * TCP SHOULD check that the TCP sequence number contained in
8605 	 * payload of the ICMP error message is within the range
8606 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8607 	 */
8608 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8609 		/*
8610 		 * If the ICMP message is bogus, should we kill the
8611 		 * connection, or should we just drop the bogus ICMP
8612 		 * message? It would probably make more sense to just
8613 		 * drop the message so that if this one managed to get
8614 		 * in, the real connection should not suffer.
8615 		 */
8616 		goto noticmpv6;
8617 	}
8618 
8619 	switch (icmp6->icmp6_type) {
8620 	case ICMP6_PACKET_TOO_BIG:
8621 		/*
8622 		 * Reduce the MSS based on the new MTU.  This will
8623 		 * eliminate any fragmentation locally.
8624 		 * N.B.  There may well be some funny side-effects on
8625 		 * the local send policy and the remote receive policy.
8626 		 * Pending further research, we provide
8627 		 * tcp_ignore_path_mtu just in case this proves
8628 		 * disastrous somewhere.
8629 		 *
8630 		 * After updating the MSS, retransmit part of the
8631 		 * dropped segment using the new mss by calling
8632 		 * tcp_wput_data().  Need to adjust all those
8633 		 * params to make sure tcp_wput_data() work properly.
8634 		 */
8635 		if (tcps->tcps_ignore_path_mtu)
8636 			break;
8637 
8638 		/*
8639 		 * Decrease the MSS by time stamp options
8640 		 * IP options and IPSEC options. tcp_hdr_len
8641 		 * includes time stamp option and IP option
8642 		 * length.
8643 		 */
8644 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8645 		    tcp->tcp_ipsec_overhead;
8646 
8647 		/*
8648 		 * Only update the MSS if the new one is
8649 		 * smaller than the previous one.  This is
8650 		 * to avoid problems when getting multiple
8651 		 * ICMP errors for the same MTU.
8652 		 */
8653 		if (new_mss >= tcp->tcp_mss)
8654 			break;
8655 
8656 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8657 		ASSERT(ratio >= 1);
8658 		tcp_mss_set(tcp, new_mss, B_TRUE);
8659 
8660 		/*
8661 		 * Make sure we have something to
8662 		 * send.
8663 		 */
8664 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8665 		    (tcp->tcp_xmit_head != NULL)) {
8666 			/*
8667 			 * Shrink tcp_cwnd in
8668 			 * proportion to the old MSS/new MSS.
8669 			 */
8670 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8671 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8672 			    (tcp->tcp_unsent == 0)) {
8673 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8674 			} else {
8675 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8676 			}
8677 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8678 			tcp->tcp_rexmit = B_TRUE;
8679 			tcp->tcp_dupack_cnt = 0;
8680 			tcp->tcp_snd_burst = TCP_CWND_SS;
8681 			tcp_ss_rexmit(tcp);
8682 		}
8683 		break;
8684 
8685 	case ICMP6_DST_UNREACH:
8686 		switch (icmp6->icmp6_code) {
8687 		case ICMP6_DST_UNREACH_NOPORT:
8688 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8689 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8690 			    (seg_seq == tcp->tcp_iss)) {
8691 				(void) tcp_clean_death(tcp,
8692 				    ECONNREFUSED, 8);
8693 			}
8694 			break;
8695 
8696 		case ICMP6_DST_UNREACH_ADMIN:
8697 		case ICMP6_DST_UNREACH_NOROUTE:
8698 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8699 		case ICMP6_DST_UNREACH_ADDR:
8700 			/* Record the error in case we finally time out. */
8701 			tcp->tcp_client_errno = EHOSTUNREACH;
8702 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8703 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8704 			    (seg_seq == tcp->tcp_iss)) {
8705 				if (tcp->tcp_listener != NULL &&
8706 				    tcp->tcp_listener->tcp_syn_defense) {
8707 					/*
8708 					 * Ditch the half-open connection if we
8709 					 * suspect a SYN attack is under way.
8710 					 */
8711 					tcp_ip_ire_mark_advice(tcp);
8712 					(void) tcp_clean_death(tcp,
8713 					    tcp->tcp_client_errno, 9);
8714 				}
8715 			}
8716 
8717 
8718 			break;
8719 		default:
8720 			break;
8721 		}
8722 		break;
8723 
8724 	case ICMP6_PARAM_PROB:
8725 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8726 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8727 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8728 		    (uchar_t *)nexthdrp) {
8729 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8730 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8731 				(void) tcp_clean_death(tcp,
8732 				    ECONNREFUSED, 10);
8733 			}
8734 			break;
8735 		}
8736 		break;
8737 
8738 	case ICMP6_TIME_EXCEEDED:
8739 	default:
8740 		break;
8741 	}
8742 	freemsg(first_mp);
8743 }
8744 
8745 /*
8746  * Notify IP that we are having trouble with this connection.  IP should
8747  * blow the IRE away and start over.
8748  */
8749 static void
8750 tcp_ip_notify(tcp_t *tcp)
8751 {
8752 	struct iocblk	*iocp;
8753 	ipid_t	*ipid;
8754 	mblk_t	*mp;
8755 
8756 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8757 	if (tcp->tcp_ipversion == IPV6_VERSION)
8758 		return;
8759 
8760 	mp = mkiocb(IP_IOCTL);
8761 	if (mp == NULL)
8762 		return;
8763 
8764 	iocp = (struct iocblk *)mp->b_rptr;
8765 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8766 
8767 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8768 	if (!mp->b_cont) {
8769 		freeb(mp);
8770 		return;
8771 	}
8772 
8773 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8774 	mp->b_cont->b_wptr += iocp->ioc_count;
8775 	bzero(ipid, sizeof (*ipid));
8776 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8777 	ipid->ipid_ire_type = IRE_CACHE;
8778 	ipid->ipid_addr_offset = sizeof (ipid_t);
8779 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8780 	/*
8781 	 * Note: in the case of source routing we want to blow away the
8782 	 * route to the first source route hop.
8783 	 */
8784 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8785 	    sizeof (tcp->tcp_ipha->ipha_dst));
8786 
8787 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8788 }
8789 
8790 /* Unlink and return any mblk that looks like it contains an ire */
8791 static mblk_t *
8792 tcp_ire_mp(mblk_t **mpp)
8793 {
8794 	mblk_t 	*mp = *mpp;
8795 	mblk_t	*prev_mp = NULL;
8796 
8797 	for (;;) {
8798 		switch (DB_TYPE(mp)) {
8799 		case IRE_DB_TYPE:
8800 		case IRE_DB_REQ_TYPE:
8801 			if (mp == *mpp) {
8802 				*mpp = mp->b_cont;
8803 			} else {
8804 				prev_mp->b_cont = mp->b_cont;
8805 			}
8806 			mp->b_cont = NULL;
8807 			return (mp);
8808 		default:
8809 			break;
8810 		}
8811 		prev_mp = mp;
8812 		mp = mp->b_cont;
8813 		if (mp == NULL)
8814 			break;
8815 	}
8816 	return (mp);
8817 }
8818 
8819 /*
8820  * Timer callback routine for keepalive probe.  We do a fake resend of
8821  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8822  * check to see if we have heard anything from the other end for the last
8823  * RTO period.  If we have, set the timer to expire for another
8824  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8825  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8826  * the timeout if we have not heard from the other side.  If for more than
8827  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8828  * kill the connection unless the keepalive abort threshold is 0.  In
8829  * that case, we will probe "forever."
8830  */
8831 static void
8832 tcp_keepalive_killer(void *arg)
8833 {
8834 	mblk_t	*mp;
8835 	conn_t	*connp = (conn_t *)arg;
8836 	tcp_t  	*tcp = connp->conn_tcp;
8837 	int32_t	firetime;
8838 	int32_t	idletime;
8839 	int32_t	ka_intrvl;
8840 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8841 
8842 	tcp->tcp_ka_tid = 0;
8843 
8844 	if (tcp->tcp_fused)
8845 		return;
8846 
8847 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8848 	ka_intrvl = tcp->tcp_ka_interval;
8849 
8850 	/*
8851 	 * Keepalive probe should only be sent if the application has not
8852 	 * done a close on the connection.
8853 	 */
8854 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8855 		return;
8856 	}
8857 	/* Timer fired too early, restart it. */
8858 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8859 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8860 		    MSEC_TO_TICK(ka_intrvl));
8861 		return;
8862 	}
8863 
8864 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8865 	/*
8866 	 * If we have not heard from the other side for a long
8867 	 * time, kill the connection unless the keepalive abort
8868 	 * threshold is 0.  In that case, we will probe "forever."
8869 	 */
8870 	if (tcp->tcp_ka_abort_thres != 0 &&
8871 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8872 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8873 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8874 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8875 		return;
8876 	}
8877 
8878 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8879 	    idletime >= ka_intrvl) {
8880 		/* Fake resend of last ACKed byte. */
8881 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8882 
8883 		if (mp1 != NULL) {
8884 			*mp1->b_wptr++ = '\0';
8885 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8886 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8887 			freeb(mp1);
8888 			/*
8889 			 * if allocation failed, fall through to start the
8890 			 * timer back.
8891 			 */
8892 			if (mp != NULL) {
8893 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8894 				BUMP_MIB(&tcps->tcps_mib,
8895 				    tcpTimKeepaliveProbe);
8896 				if (tcp->tcp_ka_last_intrvl != 0) {
8897 					int max;
8898 					/*
8899 					 * We should probe again at least
8900 					 * in ka_intrvl, but not more than
8901 					 * tcp_rexmit_interval_max.
8902 					 */
8903 					max = tcps->tcps_rexmit_interval_max;
8904 					firetime = MIN(ka_intrvl - 1,
8905 					    tcp->tcp_ka_last_intrvl << 1);
8906 					if (firetime > max)
8907 						firetime = max;
8908 				} else {
8909 					firetime = tcp->tcp_rto;
8910 				}
8911 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8912 				    tcp_keepalive_killer,
8913 				    MSEC_TO_TICK(firetime));
8914 				tcp->tcp_ka_last_intrvl = firetime;
8915 				return;
8916 			}
8917 		}
8918 	} else {
8919 		tcp->tcp_ka_last_intrvl = 0;
8920 	}
8921 
8922 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8923 	if ((firetime = ka_intrvl - idletime) < 0) {
8924 		firetime = ka_intrvl;
8925 	}
8926 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8927 	    MSEC_TO_TICK(firetime));
8928 }
8929 
8930 int
8931 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8932 {
8933 	queue_t	*q = tcp->tcp_rq;
8934 	int32_t	mss = tcp->tcp_mss;
8935 	int	maxpsz;
8936 	conn_t	*connp = tcp->tcp_connp;
8937 
8938 	if (TCP_IS_DETACHED(tcp))
8939 		return (mss);
8940 	if (tcp->tcp_fused) {
8941 		maxpsz = tcp_fuse_maxpsz(tcp);
8942 		mss = INFPSZ;
8943 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8944 		/*
8945 		 * Set the sd_qn_maxpsz according to the socket send buffer
8946 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8947 		 * instruct the stream head to copyin user data into contiguous
8948 		 * kernel-allocated buffers without breaking it up into smaller
8949 		 * chunks.  We round up the buffer size to the nearest SMSS.
8950 		 */
8951 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8952 		if (tcp->tcp_kssl_ctx == NULL)
8953 			mss = INFPSZ;
8954 		else
8955 			mss = SSL3_MAX_RECORD_LEN;
8956 	} else {
8957 		/*
8958 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8959 		 * (and a multiple of the mss).  This instructs the stream
8960 		 * head to break down larger than SMSS writes into SMSS-
8961 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8962 		 */
8963 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8964 		maxpsz = tcp->tcp_maxpsz * mss;
8965 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8966 			maxpsz = tcp->tcp_xmit_hiwater/2;
8967 			/* Round up to nearest mss */
8968 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8969 		}
8970 	}
8971 
8972 	(void) proto_set_maxpsz(q, connp, maxpsz);
8973 	if (!(IPCL_IS_NONSTR(connp))) {
8974 		/* XXX do it in set_maxpsz()? */
8975 		tcp->tcp_wq->q_maxpsz = maxpsz;
8976 	}
8977 
8978 	if (set_maxblk)
8979 		(void) proto_set_tx_maxblk(q, connp, mss);
8980 	return (mss);
8981 }
8982 
8983 /*
8984  * Extract option values from a tcp header.  We put any found values into the
8985  * tcpopt struct and return a bitmask saying which options were found.
8986  */
8987 static int
8988 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8989 {
8990 	uchar_t		*endp;
8991 	int		len;
8992 	uint32_t	mss;
8993 	uchar_t		*up = (uchar_t *)tcph;
8994 	int		found = 0;
8995 	int32_t		sack_len;
8996 	tcp_seq		sack_begin, sack_end;
8997 	tcp_t		*tcp;
8998 
8999 	endp = up + TCP_HDR_LENGTH(tcph);
9000 	up += TCP_MIN_HEADER_LENGTH;
9001 	while (up < endp) {
9002 		len = endp - up;
9003 		switch (*up) {
9004 		case TCPOPT_EOL:
9005 			break;
9006 
9007 		case TCPOPT_NOP:
9008 			up++;
9009 			continue;
9010 
9011 		case TCPOPT_MAXSEG:
9012 			if (len < TCPOPT_MAXSEG_LEN ||
9013 			    up[1] != TCPOPT_MAXSEG_LEN)
9014 				break;
9015 
9016 			mss = BE16_TO_U16(up+2);
9017 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9018 			tcpopt->tcp_opt_mss = mss;
9019 			found |= TCP_OPT_MSS_PRESENT;
9020 
9021 			up += TCPOPT_MAXSEG_LEN;
9022 			continue;
9023 
9024 		case TCPOPT_WSCALE:
9025 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9026 				break;
9027 
9028 			if (up[2] > TCP_MAX_WINSHIFT)
9029 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9030 			else
9031 				tcpopt->tcp_opt_wscale = up[2];
9032 			found |= TCP_OPT_WSCALE_PRESENT;
9033 
9034 			up += TCPOPT_WS_LEN;
9035 			continue;
9036 
9037 		case TCPOPT_SACK_PERMITTED:
9038 			if (len < TCPOPT_SACK_OK_LEN ||
9039 			    up[1] != TCPOPT_SACK_OK_LEN)
9040 				break;
9041 			found |= TCP_OPT_SACK_OK_PRESENT;
9042 			up += TCPOPT_SACK_OK_LEN;
9043 			continue;
9044 
9045 		case TCPOPT_SACK:
9046 			if (len <= 2 || up[1] <= 2 || len < up[1])
9047 				break;
9048 
9049 			/* If TCP is not interested in SACK blks... */
9050 			if ((tcp = tcpopt->tcp) == NULL) {
9051 				up += up[1];
9052 				continue;
9053 			}
9054 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9055 			up += TCPOPT_HEADER_LEN;
9056 
9057 			/*
9058 			 * If the list is empty, allocate one and assume
9059 			 * nothing is sack'ed.
9060 			 */
9061 			ASSERT(tcp->tcp_sack_info != NULL);
9062 			if (tcp->tcp_notsack_list == NULL) {
9063 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9064 				    tcp->tcp_suna, tcp->tcp_snxt,
9065 				    &(tcp->tcp_num_notsack_blk),
9066 				    &(tcp->tcp_cnt_notsack_list));
9067 
9068 				/*
9069 				 * Make sure tcp_notsack_list is not NULL.
9070 				 * This happens when kmem_alloc(KM_NOSLEEP)
9071 				 * returns NULL.
9072 				 */
9073 				if (tcp->tcp_notsack_list == NULL) {
9074 					up += sack_len;
9075 					continue;
9076 				}
9077 				tcp->tcp_fack = tcp->tcp_suna;
9078 			}
9079 
9080 			while (sack_len > 0) {
9081 				if (up + 8 > endp) {
9082 					up = endp;
9083 					break;
9084 				}
9085 				sack_begin = BE32_TO_U32(up);
9086 				up += 4;
9087 				sack_end = BE32_TO_U32(up);
9088 				up += 4;
9089 				sack_len -= 8;
9090 				/*
9091 				 * Bounds checking.  Make sure the SACK
9092 				 * info is within tcp_suna and tcp_snxt.
9093 				 * If this SACK blk is out of bound, ignore
9094 				 * it but continue to parse the following
9095 				 * blks.
9096 				 */
9097 				if (SEQ_LEQ(sack_end, sack_begin) ||
9098 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9099 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9100 					continue;
9101 				}
9102 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9103 				    sack_begin, sack_end,
9104 				    &(tcp->tcp_num_notsack_blk),
9105 				    &(tcp->tcp_cnt_notsack_list));
9106 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9107 					tcp->tcp_fack = sack_end;
9108 				}
9109 			}
9110 			found |= TCP_OPT_SACK_PRESENT;
9111 			continue;
9112 
9113 		case TCPOPT_TSTAMP:
9114 			if (len < TCPOPT_TSTAMP_LEN ||
9115 			    up[1] != TCPOPT_TSTAMP_LEN)
9116 				break;
9117 
9118 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9119 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9120 
9121 			found |= TCP_OPT_TSTAMP_PRESENT;
9122 
9123 			up += TCPOPT_TSTAMP_LEN;
9124 			continue;
9125 
9126 		default:
9127 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9128 				break;
9129 			up += up[1];
9130 			continue;
9131 		}
9132 		break;
9133 	}
9134 	return (found);
9135 }
9136 
9137 /*
9138  * Set the mss associated with a particular tcp based on its current value,
9139  * and a new one passed in. Observe minimums and maximums, and reset
9140  * other state variables that we want to view as multiples of mss.
9141  *
9142  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9143  * highwater marks etc. need to be initialized or adjusted.
9144  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9145  *    packet arrives.
9146  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9147  *    ICMP6_PACKET_TOO_BIG arrives.
9148  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9149  *    to increase the MSS to use the extra bytes available.
9150  *
9151  * Callers except tcp_paws_check() ensure that they only reduce mss.
9152  */
9153 static void
9154 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9155 {
9156 	uint32_t	mss_max;
9157 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9158 
9159 	if (tcp->tcp_ipversion == IPV4_VERSION)
9160 		mss_max = tcps->tcps_mss_max_ipv4;
9161 	else
9162 		mss_max = tcps->tcps_mss_max_ipv6;
9163 
9164 	if (mss < tcps->tcps_mss_min)
9165 		mss = tcps->tcps_mss_min;
9166 	if (mss > mss_max)
9167 		mss = mss_max;
9168 	/*
9169 	 * Unless naglim has been set by our client to
9170 	 * a non-mss value, force naglim to track mss.
9171 	 * This can help to aggregate small writes.
9172 	 */
9173 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9174 		tcp->tcp_naglim = mss;
9175 	/*
9176 	 * TCP should be able to buffer at least 4 MSS data for obvious
9177 	 * performance reason.
9178 	 */
9179 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9180 		tcp->tcp_xmit_hiwater = mss << 2;
9181 
9182 	/*
9183 	 * Set the xmit_lowater to at least twice of MSS.
9184 	 */
9185 	if ((mss << 1) > tcp->tcp_xmit_lowater)
9186 		tcp->tcp_xmit_lowater = mss << 1;
9187 
9188 	if (do_ss) {
9189 		/*
9190 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9191 		 * changing due to a reduction in MTU, presumably as a
9192 		 * result of a new path component, reset cwnd to its
9193 		 * "initial" value, as a multiple of the new mss.
9194 		 */
9195 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9196 	} else {
9197 		/*
9198 		 * Called by tcp_paws_check(), the mss increased
9199 		 * marginally to allow use of space previously taken
9200 		 * by the timestamp option. It would be inappropriate
9201 		 * to apply slow start or tcp_init_cwnd values to
9202 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9203 		 */
9204 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9205 		tcp->tcp_cwnd_cnt = 0;
9206 	}
9207 	tcp->tcp_mss = mss;
9208 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9209 }
9210 
9211 /* For /dev/tcp aka AF_INET open */
9212 static int
9213 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9214 {
9215 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9216 }
9217 
9218 /* For /dev/tcp6 aka AF_INET6 open */
9219 static int
9220 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9221 {
9222 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9223 }
9224 
9225 static conn_t *
9226 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9227     boolean_t issocket, int *errorp)
9228 {
9229 	tcp_t		*tcp = NULL;
9230 	conn_t		*connp;
9231 	int		err;
9232 	zoneid_t	zoneid;
9233 	tcp_stack_t	*tcps;
9234 	squeue_t	*sqp;
9235 
9236 	ASSERT(errorp != NULL);
9237 	/*
9238 	 * Find the proper zoneid and netstack.
9239 	 */
9240 	/*
9241 	 * Special case for install: miniroot needs to be able to
9242 	 * access files via NFS as though it were always in the
9243 	 * global zone.
9244 	 */
9245 	if (credp == kcred && nfs_global_client_only != 0) {
9246 		zoneid = GLOBAL_ZONEID;
9247 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9248 		    netstack_tcp;
9249 		ASSERT(tcps != NULL);
9250 	} else {
9251 		netstack_t *ns;
9252 
9253 		ns = netstack_find_by_cred(credp);
9254 		ASSERT(ns != NULL);
9255 		tcps = ns->netstack_tcp;
9256 		ASSERT(tcps != NULL);
9257 
9258 		/*
9259 		 * For exclusive stacks we set the zoneid to zero
9260 		 * to make TCP operate as if in the global zone.
9261 		 */
9262 		if (tcps->tcps_netstack->netstack_stackid !=
9263 		    GLOBAL_NETSTACKID)
9264 			zoneid = GLOBAL_ZONEID;
9265 		else
9266 			zoneid = crgetzoneid(credp);
9267 	}
9268 	/*
9269 	 * For stackid zero this is done from strplumb.c, but
9270 	 * non-zero stackids are handled here.
9271 	 */
9272 	if (tcps->tcps_g_q == NULL &&
9273 	    tcps->tcps_netstack->netstack_stackid !=
9274 	    GLOBAL_NETSTACKID) {
9275 		tcp_g_q_setup(tcps);
9276 	}
9277 
9278 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9279 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9280 	/*
9281 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9282 	 * so we drop it by one.
9283 	 */
9284 	netstack_rele(tcps->tcps_netstack);
9285 	if (connp == NULL) {
9286 		*errorp = ENOSR;
9287 		return (NULL);
9288 	}
9289 	connp->conn_sqp = sqp;
9290 	connp->conn_initial_sqp = connp->conn_sqp;
9291 	tcp = connp->conn_tcp;
9292 
9293 	if (isv6) {
9294 		connp->conn_flags |= IPCL_TCP6;
9295 		connp->conn_send = ip_output_v6;
9296 		connp->conn_af_isv6 = B_TRUE;
9297 		connp->conn_pkt_isv6 = B_TRUE;
9298 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9299 		tcp->tcp_ipversion = IPV6_VERSION;
9300 		tcp->tcp_family = AF_INET6;
9301 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9302 	} else {
9303 		connp->conn_flags |= IPCL_TCP4;
9304 		connp->conn_send = ip_output;
9305 		connp->conn_af_isv6 = B_FALSE;
9306 		connp->conn_pkt_isv6 = B_FALSE;
9307 		tcp->tcp_ipversion = IPV4_VERSION;
9308 		tcp->tcp_family = AF_INET;
9309 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9310 	}
9311 
9312 	/*
9313 	 * TCP keeps a copy of cred for cache locality reasons but
9314 	 * we put a reference only once. If connp->conn_cred
9315 	 * becomes invalid, tcp_cred should also be set to NULL.
9316 	 */
9317 	tcp->tcp_cred = connp->conn_cred = credp;
9318 	crhold(connp->conn_cred);
9319 	tcp->tcp_cpid = curproc->p_pid;
9320 	tcp->tcp_open_time = lbolt64;
9321 	connp->conn_zoneid = zoneid;
9322 	connp->conn_mlp_type = mlptSingle;
9323 	connp->conn_ulp_labeled = !is_system_labeled();
9324 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9325 	ASSERT(tcp->tcp_tcps == tcps);
9326 
9327 	/*
9328 	 * If the caller has the process-wide flag set, then default to MAC
9329 	 * exempt mode.  This allows read-down to unlabeled hosts.
9330 	 */
9331 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9332 		connp->conn_mac_mode = CONN_MAC_AWARE;
9333 
9334 	connp->conn_dev = NULL;
9335 	if (issocket) {
9336 		connp->conn_flags |= IPCL_SOCKET;
9337 		tcp->tcp_issocket = 1;
9338 	}
9339 
9340 	/* Non-zero default values */
9341 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9342 
9343 	if (q == NULL) {
9344 		/*
9345 		 * Create a helper stream for non-STREAMS socket.
9346 		 */
9347 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9348 		if (err != 0) {
9349 			ip1dbg(("tcp_create_common: create of IP helper stream "
9350 			    "failed\n"));
9351 			CONN_DEC_REF(connp);
9352 			*errorp = err;
9353 			return (NULL);
9354 		}
9355 		q = connp->conn_rq;
9356 	}
9357 
9358 	SOCK_CONNID_INIT(tcp->tcp_connid);
9359 	err = tcp_init(tcp, q);
9360 	if (err != 0) {
9361 		CONN_DEC_REF(connp);
9362 		*errorp = err;
9363 		return (NULL);
9364 	}
9365 
9366 	return (connp);
9367 }
9368 
9369 static int
9370 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9371     boolean_t isv6)
9372 {
9373 	tcp_t		*tcp = NULL;
9374 	conn_t		*connp = NULL;
9375 	int		err;
9376 	vmem_t		*minor_arena = NULL;
9377 	dev_t		conn_dev;
9378 	boolean_t	issocket;
9379 
9380 	if (q->q_ptr != NULL)
9381 		return (0);
9382 
9383 	if (sflag == MODOPEN)
9384 		return (EINVAL);
9385 
9386 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9387 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9388 		minor_arena = ip_minor_arena_la;
9389 	} else {
9390 		/*
9391 		 * Either minor numbers in the large arena were exhausted
9392 		 * or a non socket application is doing the open.
9393 		 * Try to allocate from the small arena.
9394 		 */
9395 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9396 			return (EBUSY);
9397 		}
9398 		minor_arena = ip_minor_arena_sa;
9399 	}
9400 
9401 	ASSERT(minor_arena != NULL);
9402 
9403 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9404 
9405 	if (flag & SO_FALLBACK) {
9406 		/*
9407 		 * Non streams socket needs a stream to fallback to
9408 		 */
9409 		RD(q)->q_ptr = (void *)conn_dev;
9410 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9411 		WR(q)->q_ptr = (void *)minor_arena;
9412 		qprocson(q);
9413 		return (0);
9414 	} else if (flag & SO_ACCEPTOR) {
9415 		q->q_qinfo = &tcp_acceptor_rinit;
9416 		/*
9417 		 * the conn_dev and minor_arena will be subsequently used by
9418 		 * tcp_wput_accept() and tcp_tpi_close_accept() to figure out
9419 		 * the minor device number for this connection from the q_ptr.
9420 		 */
9421 		RD(q)->q_ptr = (void *)conn_dev;
9422 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9423 		WR(q)->q_ptr = (void *)minor_arena;
9424 		qprocson(q);
9425 		return (0);
9426 	}
9427 
9428 	issocket = flag & SO_SOCKSTR;
9429 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9430 
9431 	if (connp == NULL) {
9432 		inet_minor_free(minor_arena, conn_dev);
9433 		q->q_ptr = WR(q)->q_ptr = NULL;
9434 		return (err);
9435 	}
9436 
9437 	q->q_ptr = WR(q)->q_ptr = connp;
9438 
9439 	connp->conn_dev = conn_dev;
9440 	connp->conn_minor_arena = minor_arena;
9441 
9442 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9443 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9444 
9445 	tcp = connp->conn_tcp;
9446 
9447 	if (issocket) {
9448 		WR(q)->q_qinfo = &tcp_sock_winit;
9449 	} else {
9450 #ifdef  _ILP32
9451 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9452 #else
9453 		tcp->tcp_acceptor_id = conn_dev;
9454 #endif  /* _ILP32 */
9455 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9456 	}
9457 
9458 	/*
9459 	 * Put the ref for TCP. Ref for IP was already put
9460 	 * by ipcl_conn_create. Also Make the conn_t globally
9461 	 * visible to walkers
9462 	 */
9463 	mutex_enter(&connp->conn_lock);
9464 	CONN_INC_REF_LOCKED(connp);
9465 	ASSERT(connp->conn_ref == 2);
9466 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9467 	mutex_exit(&connp->conn_lock);
9468 
9469 	qprocson(q);
9470 	return (0);
9471 }
9472 
9473 /*
9474  * Some TCP options can be "set" by requesting them in the option
9475  * buffer. This is needed for XTI feature test though we do not
9476  * allow it in general. We interpret that this mechanism is more
9477  * applicable to OSI protocols and need not be allowed in general.
9478  * This routine filters out options for which it is not allowed (most)
9479  * and lets through those (few) for which it is. [ The XTI interface
9480  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9481  * ever implemented will have to be allowed here ].
9482  */
9483 static boolean_t
9484 tcp_allow_connopt_set(int level, int name)
9485 {
9486 
9487 	switch (level) {
9488 	case IPPROTO_TCP:
9489 		switch (name) {
9490 		case TCP_NODELAY:
9491 			return (B_TRUE);
9492 		default:
9493 			return (B_FALSE);
9494 		}
9495 		/*NOTREACHED*/
9496 	default:
9497 		return (B_FALSE);
9498 	}
9499 	/*NOTREACHED*/
9500 }
9501 
9502 /*
9503  * this routine gets default values of certain options whose default
9504  * values are maintained by protocol specific code
9505  */
9506 /* ARGSUSED */
9507 int
9508 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9509 {
9510 	int32_t	*i1 = (int32_t *)ptr;
9511 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9512 
9513 	switch (level) {
9514 	case IPPROTO_TCP:
9515 		switch (name) {
9516 		case TCP_NOTIFY_THRESHOLD:
9517 			*i1 = tcps->tcps_ip_notify_interval;
9518 			break;
9519 		case TCP_ABORT_THRESHOLD:
9520 			*i1 = tcps->tcps_ip_abort_interval;
9521 			break;
9522 		case TCP_CONN_NOTIFY_THRESHOLD:
9523 			*i1 = tcps->tcps_ip_notify_cinterval;
9524 			break;
9525 		case TCP_CONN_ABORT_THRESHOLD:
9526 			*i1 = tcps->tcps_ip_abort_cinterval;
9527 			break;
9528 		default:
9529 			return (-1);
9530 		}
9531 		break;
9532 	case IPPROTO_IP:
9533 		switch (name) {
9534 		case IP_TTL:
9535 			*i1 = tcps->tcps_ipv4_ttl;
9536 			break;
9537 		default:
9538 			return (-1);
9539 		}
9540 		break;
9541 	case IPPROTO_IPV6:
9542 		switch (name) {
9543 		case IPV6_UNICAST_HOPS:
9544 			*i1 = tcps->tcps_ipv6_hoplimit;
9545 			break;
9546 		default:
9547 			return (-1);
9548 		}
9549 		break;
9550 	default:
9551 		return (-1);
9552 	}
9553 	return (sizeof (int));
9554 }
9555 
9556 static int
9557 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9558 {
9559 	int		*i1 = (int *)ptr;
9560 	tcp_t		*tcp = connp->conn_tcp;
9561 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9562 
9563 	switch (level) {
9564 	case SOL_SOCKET:
9565 		switch (name) {
9566 		case SO_LINGER:	{
9567 			struct linger *lgr = (struct linger *)ptr;
9568 
9569 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9570 			lgr->l_linger = tcp->tcp_lingertime;
9571 			}
9572 			return (sizeof (struct linger));
9573 		case SO_DEBUG:
9574 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9575 			break;
9576 		case SO_KEEPALIVE:
9577 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9578 			break;
9579 		case SO_DONTROUTE:
9580 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9581 			break;
9582 		case SO_USELOOPBACK:
9583 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9584 			break;
9585 		case SO_BROADCAST:
9586 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9587 			break;
9588 		case SO_REUSEADDR:
9589 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9590 			break;
9591 		case SO_OOBINLINE:
9592 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9593 			break;
9594 		case SO_DGRAM_ERRIND:
9595 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9596 			break;
9597 		case SO_TYPE:
9598 			*i1 = SOCK_STREAM;
9599 			break;
9600 		case SO_SNDBUF:
9601 			*i1 = tcp->tcp_xmit_hiwater;
9602 			break;
9603 		case SO_RCVBUF:
9604 			*i1 = tcp->tcp_recv_hiwater;
9605 			break;
9606 		case SO_SND_COPYAVOID:
9607 			*i1 = tcp->tcp_snd_zcopy_on ?
9608 			    SO_SND_COPYAVOID : 0;
9609 			break;
9610 		case SO_ALLZONES:
9611 			*i1 = connp->conn_allzones ? 1 : 0;
9612 			break;
9613 		case SO_ANON_MLP:
9614 			*i1 = connp->conn_anon_mlp;
9615 			break;
9616 		case SO_MAC_EXEMPT:
9617 			*i1 = (connp->conn_mac_mode == CONN_MAC_AWARE);
9618 			break;
9619 		case SO_MAC_IMPLICIT:
9620 			*i1 = (connp->conn_mac_mode == CONN_MAC_IMPLICIT);
9621 			break;
9622 		case SO_EXCLBIND:
9623 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9624 			break;
9625 		case SO_PROTOTYPE:
9626 			*i1 = IPPROTO_TCP;
9627 			break;
9628 		case SO_DOMAIN:
9629 			*i1 = tcp->tcp_family;
9630 			break;
9631 		case SO_ACCEPTCONN:
9632 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9633 		default:
9634 			return (-1);
9635 		}
9636 		break;
9637 	case IPPROTO_TCP:
9638 		switch (name) {
9639 		case TCP_NODELAY:
9640 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9641 			break;
9642 		case TCP_MAXSEG:
9643 			*i1 = tcp->tcp_mss;
9644 			break;
9645 		case TCP_NOTIFY_THRESHOLD:
9646 			*i1 = (int)tcp->tcp_first_timer_threshold;
9647 			break;
9648 		case TCP_ABORT_THRESHOLD:
9649 			*i1 = tcp->tcp_second_timer_threshold;
9650 			break;
9651 		case TCP_CONN_NOTIFY_THRESHOLD:
9652 			*i1 = tcp->tcp_first_ctimer_threshold;
9653 			break;
9654 		case TCP_CONN_ABORT_THRESHOLD:
9655 			*i1 = tcp->tcp_second_ctimer_threshold;
9656 			break;
9657 		case TCP_RECVDSTADDR:
9658 			*i1 = tcp->tcp_recvdstaddr;
9659 			break;
9660 		case TCP_ANONPRIVBIND:
9661 			*i1 = tcp->tcp_anon_priv_bind;
9662 			break;
9663 		case TCP_EXCLBIND:
9664 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9665 			break;
9666 		case TCP_INIT_CWND:
9667 			*i1 = tcp->tcp_init_cwnd;
9668 			break;
9669 		case TCP_KEEPALIVE_THRESHOLD:
9670 			*i1 = tcp->tcp_ka_interval;
9671 			break;
9672 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9673 			*i1 = tcp->tcp_ka_abort_thres;
9674 			break;
9675 		case TCP_CORK:
9676 			*i1 = tcp->tcp_cork;
9677 			break;
9678 		default:
9679 			return (-1);
9680 		}
9681 		break;
9682 	case IPPROTO_IP:
9683 		if (tcp->tcp_family != AF_INET)
9684 			return (-1);
9685 		switch (name) {
9686 		case IP_OPTIONS:
9687 		case T_IP_OPTIONS: {
9688 			/*
9689 			 * This is compatible with BSD in that in only return
9690 			 * the reverse source route with the final destination
9691 			 * as the last entry. The first 4 bytes of the option
9692 			 * will contain the final destination.
9693 			 */
9694 			int	opt_len;
9695 
9696 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9697 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9698 			ASSERT(opt_len >= 0);
9699 			/* Caller ensures enough space */
9700 			if (opt_len > 0) {
9701 				/*
9702 				 * TODO: Do we have to handle getsockopt on an
9703 				 * initiator as well?
9704 				 */
9705 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9706 			}
9707 			return (0);
9708 			}
9709 		case IP_TOS:
9710 		case T_IP_TOS:
9711 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9712 			break;
9713 		case IP_TTL:
9714 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9715 			break;
9716 		case IP_NEXTHOP:
9717 			/* Handled at IP level */
9718 			return (-EINVAL);
9719 		default:
9720 			return (-1);
9721 		}
9722 		break;
9723 	case IPPROTO_IPV6:
9724 		/*
9725 		 * IPPROTO_IPV6 options are only supported for sockets
9726 		 * that are using IPv6 on the wire.
9727 		 */
9728 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9729 			return (-1);
9730 		}
9731 		switch (name) {
9732 		case IPV6_UNICAST_HOPS:
9733 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9734 			break;	/* goto sizeof (int) option return */
9735 		case IPV6_BOUND_IF:
9736 			/* Zero if not set */
9737 			*i1 = tcp->tcp_bound_if;
9738 			break;	/* goto sizeof (int) option return */
9739 		case IPV6_RECVPKTINFO:
9740 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9741 				*i1 = 1;
9742 			else
9743 				*i1 = 0;
9744 			break;	/* goto sizeof (int) option return */
9745 		case IPV6_RECVTCLASS:
9746 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9747 				*i1 = 1;
9748 			else
9749 				*i1 = 0;
9750 			break;	/* goto sizeof (int) option return */
9751 		case IPV6_RECVHOPLIMIT:
9752 			if (tcp->tcp_ipv6_recvancillary &
9753 			    TCP_IPV6_RECVHOPLIMIT)
9754 				*i1 = 1;
9755 			else
9756 				*i1 = 0;
9757 			break;	/* goto sizeof (int) option return */
9758 		case IPV6_RECVHOPOPTS:
9759 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9760 				*i1 = 1;
9761 			else
9762 				*i1 = 0;
9763 			break;	/* goto sizeof (int) option return */
9764 		case IPV6_RECVDSTOPTS:
9765 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9766 				*i1 = 1;
9767 			else
9768 				*i1 = 0;
9769 			break;	/* goto sizeof (int) option return */
9770 		case _OLD_IPV6_RECVDSTOPTS:
9771 			if (tcp->tcp_ipv6_recvancillary &
9772 			    TCP_OLD_IPV6_RECVDSTOPTS)
9773 				*i1 = 1;
9774 			else
9775 				*i1 = 0;
9776 			break;	/* goto sizeof (int) option return */
9777 		case IPV6_RECVRTHDR:
9778 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9779 				*i1 = 1;
9780 			else
9781 				*i1 = 0;
9782 			break;	/* goto sizeof (int) option return */
9783 		case IPV6_RECVRTHDRDSTOPTS:
9784 			if (tcp->tcp_ipv6_recvancillary &
9785 			    TCP_IPV6_RECVRTDSTOPTS)
9786 				*i1 = 1;
9787 			else
9788 				*i1 = 0;
9789 			break;	/* goto sizeof (int) option return */
9790 		case IPV6_PKTINFO: {
9791 			/* XXX assumes that caller has room for max size! */
9792 			struct in6_pktinfo *pkti;
9793 
9794 			pkti = (struct in6_pktinfo *)ptr;
9795 			if (ipp->ipp_fields & IPPF_IFINDEX)
9796 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9797 			else
9798 				pkti->ipi6_ifindex = 0;
9799 			if (ipp->ipp_fields & IPPF_ADDR)
9800 				pkti->ipi6_addr = ipp->ipp_addr;
9801 			else
9802 				pkti->ipi6_addr = ipv6_all_zeros;
9803 			return (sizeof (struct in6_pktinfo));
9804 		}
9805 		case IPV6_TCLASS:
9806 			if (ipp->ipp_fields & IPPF_TCLASS)
9807 				*i1 = ipp->ipp_tclass;
9808 			else
9809 				*i1 = IPV6_FLOW_TCLASS(
9810 				    IPV6_DEFAULT_VERS_AND_FLOW);
9811 			break;	/* goto sizeof (int) option return */
9812 		case IPV6_NEXTHOP: {
9813 			sin6_t *sin6 = (sin6_t *)ptr;
9814 
9815 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9816 				return (0);
9817 			*sin6 = sin6_null;
9818 			sin6->sin6_family = AF_INET6;
9819 			sin6->sin6_addr = ipp->ipp_nexthop;
9820 			return (sizeof (sin6_t));
9821 		}
9822 		case IPV6_HOPOPTS:
9823 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9824 				return (0);
9825 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9826 				return (0);
9827 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9828 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9829 			if (tcp->tcp_label_len > 0) {
9830 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9831 				ptr[1] = (ipp->ipp_hopoptslen -
9832 				    tcp->tcp_label_len + 7) / 8 - 1;
9833 			}
9834 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9835 		case IPV6_RTHDRDSTOPTS:
9836 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9837 				return (0);
9838 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9839 			return (ipp->ipp_rtdstoptslen);
9840 		case IPV6_RTHDR:
9841 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9842 				return (0);
9843 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9844 			return (ipp->ipp_rthdrlen);
9845 		case IPV6_DSTOPTS:
9846 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9847 				return (0);
9848 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9849 			return (ipp->ipp_dstoptslen);
9850 		case IPV6_SRC_PREFERENCES:
9851 			return (ip6_get_src_preferences(connp,
9852 			    (uint32_t *)ptr));
9853 		case IPV6_PATHMTU: {
9854 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9855 
9856 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9857 				return (-1);
9858 
9859 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9860 			    connp->conn_fport, mtuinfo,
9861 			    connp->conn_netstack));
9862 		}
9863 		default:
9864 			return (-1);
9865 		}
9866 		break;
9867 	default:
9868 		return (-1);
9869 	}
9870 	return (sizeof (int));
9871 }
9872 
9873 /*
9874  * TCP routine to get the values of options.
9875  */
9876 int
9877 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9878 {
9879 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9880 }
9881 
9882 /* returns UNIX error, the optlen is a value-result arg */
9883 int
9884 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9885     void *optvalp, socklen_t *optlen, cred_t *cr)
9886 {
9887 	conn_t		*connp = (conn_t *)proto_handle;
9888 	squeue_t	*sqp = connp->conn_sqp;
9889 	int		error;
9890 	t_uscalar_t	max_optbuf_len;
9891 	void		*optvalp_buf;
9892 	int		len;
9893 
9894 	ASSERT(connp->conn_upper_handle != NULL);
9895 
9896 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9897 	    tcp_opt_obj.odb_opt_des_arr,
9898 	    tcp_opt_obj.odb_opt_arr_cnt,
9899 	    tcp_opt_obj.odb_topmost_tpiprovider,
9900 	    B_FALSE, B_TRUE, cr);
9901 	if (error != 0) {
9902 		if (error < 0) {
9903 			error = proto_tlitosyserr(-error);
9904 		}
9905 		return (error);
9906 	}
9907 
9908 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9909 
9910 	error = squeue_synch_enter(sqp, connp, NULL);
9911 	if (error == ENOMEM) {
9912 		return (ENOMEM);
9913 	}
9914 
9915 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9916 	squeue_synch_exit(sqp, connp);
9917 
9918 	if (len < 0) {
9919 		/*
9920 		 * Pass on to IP
9921 		 */
9922 		kmem_free(optvalp_buf, max_optbuf_len);
9923 		return (ip_get_options(connp, level, option_name,
9924 		    optvalp, optlen, cr));
9925 	} else {
9926 		/*
9927 		 * update optlen and copy option value
9928 		 */
9929 		t_uscalar_t size = MIN(len, *optlen);
9930 		bcopy(optvalp_buf, optvalp, size);
9931 		bcopy(&size, optlen, sizeof (size));
9932 
9933 		kmem_free(optvalp_buf, max_optbuf_len);
9934 		return (0);
9935 	}
9936 }
9937 
9938 /*
9939  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9940  * Parameters are assumed to be verified by the caller.
9941  */
9942 /* ARGSUSED */
9943 int
9944 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9945     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9946     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9947 {
9948 	tcp_t	*tcp = connp->conn_tcp;
9949 	int	*i1 = (int *)invalp;
9950 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9951 	boolean_t checkonly;
9952 	int	reterr;
9953 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9954 
9955 	switch (optset_context) {
9956 	case SETFN_OPTCOM_CHECKONLY:
9957 		checkonly = B_TRUE;
9958 		/*
9959 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9960 		 * inlen != 0 implies value supplied and
9961 		 * 	we have to "pretend" to set it.
9962 		 * inlen == 0 implies that there is no
9963 		 * 	value part in T_CHECK request and just validation
9964 		 * done elsewhere should be enough, we just return here.
9965 		 */
9966 		if (inlen == 0) {
9967 			*outlenp = 0;
9968 			return (0);
9969 		}
9970 		break;
9971 	case SETFN_OPTCOM_NEGOTIATE:
9972 		checkonly = B_FALSE;
9973 		break;
9974 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9975 	case SETFN_CONN_NEGOTIATE:
9976 		checkonly = B_FALSE;
9977 		/*
9978 		 * Negotiating local and "association-related" options
9979 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9980 		 * primitives is allowed by XTI, but we choose
9981 		 * to not implement this style negotiation for Internet
9982 		 * protocols (We interpret it is a must for OSI world but
9983 		 * optional for Internet protocols) for all options.
9984 		 * [ Will do only for the few options that enable test
9985 		 * suites that our XTI implementation of this feature
9986 		 * works for transports that do allow it ]
9987 		 */
9988 		if (!tcp_allow_connopt_set(level, name)) {
9989 			*outlenp = 0;
9990 			return (EINVAL);
9991 		}
9992 		break;
9993 	default:
9994 		/*
9995 		 * We should never get here
9996 		 */
9997 		*outlenp = 0;
9998 		return (EINVAL);
9999 	}
10000 
10001 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10002 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10003 
10004 	/*
10005 	 * For TCP, we should have no ancillary data sent down
10006 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10007 	 * has to be zero.
10008 	 */
10009 	ASSERT(thisdg_attrs == NULL);
10010 
10011 	/*
10012 	 * For fixed length options, no sanity check
10013 	 * of passed in length is done. It is assumed *_optcom_req()
10014 	 * routines do the right thing.
10015 	 */
10016 	switch (level) {
10017 	case SOL_SOCKET:
10018 		switch (name) {
10019 		case SO_LINGER: {
10020 			struct linger *lgr = (struct linger *)invalp;
10021 
10022 			if (!checkonly) {
10023 				if (lgr->l_onoff) {
10024 					tcp->tcp_linger = 1;
10025 					tcp->tcp_lingertime = lgr->l_linger;
10026 				} else {
10027 					tcp->tcp_linger = 0;
10028 					tcp->tcp_lingertime = 0;
10029 				}
10030 				/* struct copy */
10031 				*(struct linger *)outvalp = *lgr;
10032 			} else {
10033 				if (!lgr->l_onoff) {
10034 					((struct linger *)
10035 					    outvalp)->l_onoff = 0;
10036 					((struct linger *)
10037 					    outvalp)->l_linger = 0;
10038 				} else {
10039 					/* struct copy */
10040 					*(struct linger *)outvalp = *lgr;
10041 				}
10042 			}
10043 			*outlenp = sizeof (struct linger);
10044 			return (0);
10045 		}
10046 		case SO_DEBUG:
10047 			if (!checkonly)
10048 				tcp->tcp_debug = onoff;
10049 			break;
10050 		case SO_KEEPALIVE:
10051 			if (checkonly) {
10052 				/* check only case */
10053 				break;
10054 			}
10055 
10056 			if (!onoff) {
10057 				if (tcp->tcp_ka_enabled) {
10058 					if (tcp->tcp_ka_tid != 0) {
10059 						(void) TCP_TIMER_CANCEL(tcp,
10060 						    tcp->tcp_ka_tid);
10061 						tcp->tcp_ka_tid = 0;
10062 					}
10063 					tcp->tcp_ka_enabled = 0;
10064 				}
10065 				break;
10066 			}
10067 			if (!tcp->tcp_ka_enabled) {
10068 				/* Crank up the keepalive timer */
10069 				tcp->tcp_ka_last_intrvl = 0;
10070 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10071 				    tcp_keepalive_killer,
10072 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10073 				tcp->tcp_ka_enabled = 1;
10074 			}
10075 			break;
10076 		case SO_DONTROUTE:
10077 			/*
10078 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10079 			 * only of interest to IP.  We track them here only so
10080 			 * that we can report their current value.
10081 			 */
10082 			if (!checkonly) {
10083 				tcp->tcp_dontroute = onoff;
10084 				tcp->tcp_connp->conn_dontroute = onoff;
10085 			}
10086 			break;
10087 		case SO_USELOOPBACK:
10088 			if (!checkonly) {
10089 				tcp->tcp_useloopback = onoff;
10090 				tcp->tcp_connp->conn_loopback = onoff;
10091 			}
10092 			break;
10093 		case SO_BROADCAST:
10094 			if (!checkonly) {
10095 				tcp->tcp_broadcast = onoff;
10096 				tcp->tcp_connp->conn_broadcast = onoff;
10097 			}
10098 			break;
10099 		case SO_REUSEADDR:
10100 			if (!checkonly) {
10101 				tcp->tcp_reuseaddr = onoff;
10102 				tcp->tcp_connp->conn_reuseaddr = onoff;
10103 			}
10104 			break;
10105 		case SO_OOBINLINE:
10106 			if (!checkonly) {
10107 				tcp->tcp_oobinline = onoff;
10108 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10109 					proto_set_rx_oob_opt(connp, onoff);
10110 			}
10111 			break;
10112 		case SO_DGRAM_ERRIND:
10113 			if (!checkonly)
10114 				tcp->tcp_dgram_errind = onoff;
10115 			break;
10116 		case SO_SNDBUF: {
10117 			if (*i1 > tcps->tcps_max_buf) {
10118 				*outlenp = 0;
10119 				return (ENOBUFS);
10120 			}
10121 			if (checkonly)
10122 				break;
10123 
10124 			tcp->tcp_xmit_hiwater = *i1;
10125 			if (tcps->tcps_snd_lowat_fraction != 0)
10126 				tcp->tcp_xmit_lowater =
10127 				    tcp->tcp_xmit_hiwater /
10128 				    tcps->tcps_snd_lowat_fraction;
10129 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10130 			/*
10131 			 * If we are flow-controlled, recheck the condition.
10132 			 * There are apps that increase SO_SNDBUF size when
10133 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10134 			 * control condition to be lifted right away.
10135 			 */
10136 			mutex_enter(&tcp->tcp_non_sq_lock);
10137 			if (tcp->tcp_flow_stopped &&
10138 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10139 				tcp_clrqfull(tcp);
10140 			}
10141 			mutex_exit(&tcp->tcp_non_sq_lock);
10142 			break;
10143 		}
10144 		case SO_RCVBUF:
10145 			if (*i1 > tcps->tcps_max_buf) {
10146 				*outlenp = 0;
10147 				return (ENOBUFS);
10148 			}
10149 			/* Silently ignore zero */
10150 			if (!checkonly && *i1 != 0) {
10151 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10152 				(void) tcp_rwnd_set(tcp, *i1);
10153 			}
10154 			/*
10155 			 * XXX should we return the rwnd here
10156 			 * and tcp_opt_get ?
10157 			 */
10158 			break;
10159 		case SO_SND_COPYAVOID:
10160 			if (!checkonly) {
10161 				/* we only allow enable at most once for now */
10162 				if (tcp->tcp_loopback ||
10163 				    (tcp->tcp_kssl_ctx != NULL) ||
10164 				    (!tcp->tcp_snd_zcopy_aware &&
10165 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10166 					*outlenp = 0;
10167 					return (EOPNOTSUPP);
10168 				}
10169 				tcp->tcp_snd_zcopy_aware = 1;
10170 			}
10171 			break;
10172 		case SO_RCVTIMEO:
10173 		case SO_SNDTIMEO:
10174 			/*
10175 			 * Pass these two options in order for third part
10176 			 * protocol usage. Here just return directly.
10177 			 */
10178 			return (0);
10179 		case SO_ALLZONES:
10180 			/* Pass option along to IP level for handling */
10181 			return (-EINVAL);
10182 		case SO_ANON_MLP:
10183 			/* Pass option along to IP level for handling */
10184 			return (-EINVAL);
10185 		case SO_MAC_EXEMPT:
10186 			/* Pass option along to IP level for handling */
10187 			return (-EINVAL);
10188 		case SO_EXCLBIND:
10189 			if (!checkonly)
10190 				tcp->tcp_exclbind = onoff;
10191 			break;
10192 		default:
10193 			*outlenp = 0;
10194 			return (EINVAL);
10195 		}
10196 		break;
10197 	case IPPROTO_TCP:
10198 		switch (name) {
10199 		case TCP_NODELAY:
10200 			if (!checkonly)
10201 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10202 			break;
10203 		case TCP_NOTIFY_THRESHOLD:
10204 			if (!checkonly)
10205 				tcp->tcp_first_timer_threshold = *i1;
10206 			break;
10207 		case TCP_ABORT_THRESHOLD:
10208 			if (!checkonly)
10209 				tcp->tcp_second_timer_threshold = *i1;
10210 			break;
10211 		case TCP_CONN_NOTIFY_THRESHOLD:
10212 			if (!checkonly)
10213 				tcp->tcp_first_ctimer_threshold = *i1;
10214 			break;
10215 		case TCP_CONN_ABORT_THRESHOLD:
10216 			if (!checkonly)
10217 				tcp->tcp_second_ctimer_threshold = *i1;
10218 			break;
10219 		case TCP_RECVDSTADDR:
10220 			if (tcp->tcp_state > TCPS_LISTEN)
10221 				return (EOPNOTSUPP);
10222 			if (!checkonly)
10223 				tcp->tcp_recvdstaddr = onoff;
10224 			break;
10225 		case TCP_ANONPRIVBIND:
10226 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10227 			    IPPROTO_TCP)) != 0) {
10228 				*outlenp = 0;
10229 				return (reterr);
10230 			}
10231 			if (!checkonly) {
10232 				tcp->tcp_anon_priv_bind = onoff;
10233 			}
10234 			break;
10235 		case TCP_EXCLBIND:
10236 			if (!checkonly)
10237 				tcp->tcp_exclbind = onoff;
10238 			break;	/* goto sizeof (int) option return */
10239 		case TCP_INIT_CWND: {
10240 			uint32_t init_cwnd = *((uint32_t *)invalp);
10241 
10242 			if (checkonly)
10243 				break;
10244 
10245 			/*
10246 			 * Only allow socket with network configuration
10247 			 * privilege to set the initial cwnd to be larger
10248 			 * than allowed by RFC 3390.
10249 			 */
10250 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10251 				tcp->tcp_init_cwnd = init_cwnd;
10252 				break;
10253 			}
10254 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10255 				*outlenp = 0;
10256 				return (reterr);
10257 			}
10258 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10259 				*outlenp = 0;
10260 				return (EINVAL);
10261 			}
10262 			tcp->tcp_init_cwnd = init_cwnd;
10263 			break;
10264 		}
10265 		case TCP_KEEPALIVE_THRESHOLD:
10266 			if (checkonly)
10267 				break;
10268 
10269 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10270 			    *i1 > tcps->tcps_keepalive_interval_high) {
10271 				*outlenp = 0;
10272 				return (EINVAL);
10273 			}
10274 			if (*i1 != tcp->tcp_ka_interval) {
10275 				tcp->tcp_ka_interval = *i1;
10276 				/*
10277 				 * Check if we need to restart the
10278 				 * keepalive timer.
10279 				 */
10280 				if (tcp->tcp_ka_tid != 0) {
10281 					ASSERT(tcp->tcp_ka_enabled);
10282 					(void) TCP_TIMER_CANCEL(tcp,
10283 					    tcp->tcp_ka_tid);
10284 					tcp->tcp_ka_last_intrvl = 0;
10285 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10286 					    tcp_keepalive_killer,
10287 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10288 				}
10289 			}
10290 			break;
10291 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10292 			if (!checkonly) {
10293 				if (*i1 <
10294 				    tcps->tcps_keepalive_abort_interval_low ||
10295 				    *i1 >
10296 				    tcps->tcps_keepalive_abort_interval_high) {
10297 					*outlenp = 0;
10298 					return (EINVAL);
10299 				}
10300 				tcp->tcp_ka_abort_thres = *i1;
10301 			}
10302 			break;
10303 		case TCP_CORK:
10304 			if (!checkonly) {
10305 				/*
10306 				 * if tcp->tcp_cork was set and is now
10307 				 * being unset, we have to make sure that
10308 				 * the remaining data gets sent out. Also
10309 				 * unset tcp->tcp_cork so that tcp_wput_data()
10310 				 * can send data even if it is less than mss
10311 				 */
10312 				if (tcp->tcp_cork && onoff == 0 &&
10313 				    tcp->tcp_unsent > 0) {
10314 					tcp->tcp_cork = B_FALSE;
10315 					tcp_wput_data(tcp, NULL, B_FALSE);
10316 				}
10317 				tcp->tcp_cork = onoff;
10318 			}
10319 			break;
10320 		default:
10321 			*outlenp = 0;
10322 			return (EINVAL);
10323 		}
10324 		break;
10325 	case IPPROTO_IP:
10326 		if (tcp->tcp_family != AF_INET) {
10327 			*outlenp = 0;
10328 			return (ENOPROTOOPT);
10329 		}
10330 		switch (name) {
10331 		case IP_OPTIONS:
10332 		case T_IP_OPTIONS:
10333 			reterr = tcp_opt_set_header(tcp, checkonly,
10334 			    invalp, inlen);
10335 			if (reterr) {
10336 				*outlenp = 0;
10337 				return (reterr);
10338 			}
10339 			/* OK return - copy input buffer into output buffer */
10340 			if (invalp != outvalp) {
10341 				/* don't trust bcopy for identical src/dst */
10342 				bcopy(invalp, outvalp, inlen);
10343 			}
10344 			*outlenp = inlen;
10345 			return (0);
10346 		case IP_TOS:
10347 		case T_IP_TOS:
10348 			if (!checkonly) {
10349 				tcp->tcp_ipha->ipha_type_of_service =
10350 				    (uchar_t)*i1;
10351 				tcp->tcp_tos = (uchar_t)*i1;
10352 			}
10353 			break;
10354 		case IP_TTL:
10355 			if (!checkonly) {
10356 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10357 				tcp->tcp_ttl = (uchar_t)*i1;
10358 			}
10359 			break;
10360 		case IP_BOUND_IF:
10361 		case IP_NEXTHOP:
10362 			/* Handled at the IP level */
10363 			return (-EINVAL);
10364 		case IP_SEC_OPT:
10365 			/*
10366 			 * We should not allow policy setting after
10367 			 * we start listening for connections.
10368 			 */
10369 			if (tcp->tcp_state == TCPS_LISTEN) {
10370 				return (EINVAL);
10371 			} else {
10372 				/* Handled at the IP level */
10373 				return (-EINVAL);
10374 			}
10375 		default:
10376 			*outlenp = 0;
10377 			return (EINVAL);
10378 		}
10379 		break;
10380 	case IPPROTO_IPV6: {
10381 		ip6_pkt_t		*ipp;
10382 
10383 		/*
10384 		 * IPPROTO_IPV6 options are only supported for sockets
10385 		 * that are using IPv6 on the wire.
10386 		 */
10387 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10388 			*outlenp = 0;
10389 			return (ENOPROTOOPT);
10390 		}
10391 		/*
10392 		 * Only sticky options; no ancillary data
10393 		 */
10394 		ipp = &tcp->tcp_sticky_ipp;
10395 
10396 		switch (name) {
10397 		case IPV6_UNICAST_HOPS:
10398 			/* -1 means use default */
10399 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10400 				*outlenp = 0;
10401 				return (EINVAL);
10402 			}
10403 			if (!checkonly) {
10404 				if (*i1 == -1) {
10405 					tcp->tcp_ip6h->ip6_hops =
10406 					    ipp->ipp_unicast_hops =
10407 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10408 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10409 					/* Pass modified value to IP. */
10410 					*i1 = tcp->tcp_ip6h->ip6_hops;
10411 				} else {
10412 					tcp->tcp_ip6h->ip6_hops =
10413 					    ipp->ipp_unicast_hops =
10414 					    (uint8_t)*i1;
10415 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10416 				}
10417 				reterr = tcp_build_hdrs(tcp);
10418 				if (reterr != 0)
10419 					return (reterr);
10420 			}
10421 			break;
10422 		case IPV6_BOUND_IF:
10423 			if (!checkonly) {
10424 				tcp->tcp_bound_if = *i1;
10425 				PASS_OPT_TO_IP(connp);
10426 			}
10427 			break;
10428 		/*
10429 		 * Set boolean switches for ancillary data delivery
10430 		 */
10431 		case IPV6_RECVPKTINFO:
10432 			if (!checkonly) {
10433 				if (onoff)
10434 					tcp->tcp_ipv6_recvancillary |=
10435 					    TCP_IPV6_RECVPKTINFO;
10436 				else
10437 					tcp->tcp_ipv6_recvancillary &=
10438 					    ~TCP_IPV6_RECVPKTINFO;
10439 				/* Force it to be sent up with the next msg */
10440 				tcp->tcp_recvifindex = 0;
10441 				PASS_OPT_TO_IP(connp);
10442 			}
10443 			break;
10444 		case IPV6_RECVTCLASS:
10445 			if (!checkonly) {
10446 				if (onoff)
10447 					tcp->tcp_ipv6_recvancillary |=
10448 					    TCP_IPV6_RECVTCLASS;
10449 				else
10450 					tcp->tcp_ipv6_recvancillary &=
10451 					    ~TCP_IPV6_RECVTCLASS;
10452 				PASS_OPT_TO_IP(connp);
10453 			}
10454 			break;
10455 		case IPV6_RECVHOPLIMIT:
10456 			if (!checkonly) {
10457 				if (onoff)
10458 					tcp->tcp_ipv6_recvancillary |=
10459 					    TCP_IPV6_RECVHOPLIMIT;
10460 				else
10461 					tcp->tcp_ipv6_recvancillary &=
10462 					    ~TCP_IPV6_RECVHOPLIMIT;
10463 				/* Force it to be sent up with the next msg */
10464 				tcp->tcp_recvhops = 0xffffffffU;
10465 				PASS_OPT_TO_IP(connp);
10466 			}
10467 			break;
10468 		case IPV6_RECVHOPOPTS:
10469 			if (!checkonly) {
10470 				if (onoff)
10471 					tcp->tcp_ipv6_recvancillary |=
10472 					    TCP_IPV6_RECVHOPOPTS;
10473 				else
10474 					tcp->tcp_ipv6_recvancillary &=
10475 					    ~TCP_IPV6_RECVHOPOPTS;
10476 				PASS_OPT_TO_IP(connp);
10477 			}
10478 			break;
10479 		case IPV6_RECVDSTOPTS:
10480 			if (!checkonly) {
10481 				if (onoff)
10482 					tcp->tcp_ipv6_recvancillary |=
10483 					    TCP_IPV6_RECVDSTOPTS;
10484 				else
10485 					tcp->tcp_ipv6_recvancillary &=
10486 					    ~TCP_IPV6_RECVDSTOPTS;
10487 				PASS_OPT_TO_IP(connp);
10488 			}
10489 			break;
10490 		case _OLD_IPV6_RECVDSTOPTS:
10491 			if (!checkonly) {
10492 				if (onoff)
10493 					tcp->tcp_ipv6_recvancillary |=
10494 					    TCP_OLD_IPV6_RECVDSTOPTS;
10495 				else
10496 					tcp->tcp_ipv6_recvancillary &=
10497 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10498 			}
10499 			break;
10500 		case IPV6_RECVRTHDR:
10501 			if (!checkonly) {
10502 				if (onoff)
10503 					tcp->tcp_ipv6_recvancillary |=
10504 					    TCP_IPV6_RECVRTHDR;
10505 				else
10506 					tcp->tcp_ipv6_recvancillary &=
10507 					    ~TCP_IPV6_RECVRTHDR;
10508 				PASS_OPT_TO_IP(connp);
10509 			}
10510 			break;
10511 		case IPV6_RECVRTHDRDSTOPTS:
10512 			if (!checkonly) {
10513 				if (onoff)
10514 					tcp->tcp_ipv6_recvancillary |=
10515 					    TCP_IPV6_RECVRTDSTOPTS;
10516 				else
10517 					tcp->tcp_ipv6_recvancillary &=
10518 					    ~TCP_IPV6_RECVRTDSTOPTS;
10519 				PASS_OPT_TO_IP(connp);
10520 			}
10521 			break;
10522 		case IPV6_PKTINFO:
10523 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10524 				return (EINVAL);
10525 			if (checkonly)
10526 				break;
10527 
10528 			if (inlen == 0) {
10529 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10530 			} else {
10531 				struct in6_pktinfo *pkti;
10532 
10533 				pkti = (struct in6_pktinfo *)invalp;
10534 				/*
10535 				 * RFC 3542 states that ipi6_addr must be
10536 				 * the unspecified address when setting the
10537 				 * IPV6_PKTINFO sticky socket option on a
10538 				 * TCP socket.
10539 				 */
10540 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10541 					return (EINVAL);
10542 				/*
10543 				 * IP will validate the source address and
10544 				 * interface index.
10545 				 */
10546 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10547 					reterr = ip_set_options(tcp->tcp_connp,
10548 					    level, name, invalp, inlen, cr);
10549 				} else {
10550 					reterr = ip6_set_pktinfo(cr,
10551 					    tcp->tcp_connp, pkti);
10552 				}
10553 				if (reterr != 0)
10554 					return (reterr);
10555 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10556 				ipp->ipp_addr = pkti->ipi6_addr;
10557 				if (ipp->ipp_ifindex != 0)
10558 					ipp->ipp_fields |= IPPF_IFINDEX;
10559 				else
10560 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10561 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10562 					ipp->ipp_fields |= IPPF_ADDR;
10563 				else
10564 					ipp->ipp_fields &= ~IPPF_ADDR;
10565 			}
10566 			reterr = tcp_build_hdrs(tcp);
10567 			if (reterr != 0)
10568 				return (reterr);
10569 			break;
10570 		case IPV6_TCLASS:
10571 			if (inlen != 0 && inlen != sizeof (int))
10572 				return (EINVAL);
10573 			if (checkonly)
10574 				break;
10575 
10576 			if (inlen == 0) {
10577 				ipp->ipp_fields &= ~IPPF_TCLASS;
10578 			} else {
10579 				if (*i1 > 255 || *i1 < -1)
10580 					return (EINVAL);
10581 				if (*i1 == -1) {
10582 					ipp->ipp_tclass = 0;
10583 					*i1 = 0;
10584 				} else {
10585 					ipp->ipp_tclass = *i1;
10586 				}
10587 				ipp->ipp_fields |= IPPF_TCLASS;
10588 			}
10589 			reterr = tcp_build_hdrs(tcp);
10590 			if (reterr != 0)
10591 				return (reterr);
10592 			break;
10593 		case IPV6_NEXTHOP:
10594 			/*
10595 			 * IP will verify that the nexthop is reachable
10596 			 * and fail for sticky options.
10597 			 */
10598 			if (inlen != 0 && inlen != sizeof (sin6_t))
10599 				return (EINVAL);
10600 			if (checkonly)
10601 				break;
10602 
10603 			if (inlen == 0) {
10604 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10605 			} else {
10606 				sin6_t *sin6 = (sin6_t *)invalp;
10607 
10608 				if (sin6->sin6_family != AF_INET6)
10609 					return (EAFNOSUPPORT);
10610 				if (IN6_IS_ADDR_V4MAPPED(
10611 				    &sin6->sin6_addr))
10612 					return (EADDRNOTAVAIL);
10613 				ipp->ipp_nexthop = sin6->sin6_addr;
10614 				if (!IN6_IS_ADDR_UNSPECIFIED(
10615 				    &ipp->ipp_nexthop))
10616 					ipp->ipp_fields |= IPPF_NEXTHOP;
10617 				else
10618 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10619 			}
10620 			reterr = tcp_build_hdrs(tcp);
10621 			if (reterr != 0)
10622 				return (reterr);
10623 			PASS_OPT_TO_IP(connp);
10624 			break;
10625 		case IPV6_HOPOPTS: {
10626 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10627 
10628 			/*
10629 			 * Sanity checks - minimum size, size a multiple of
10630 			 * eight bytes, and matching size passed in.
10631 			 */
10632 			if (inlen != 0 &&
10633 			    inlen != (8 * (hopts->ip6h_len + 1)))
10634 				return (EINVAL);
10635 
10636 			if (checkonly)
10637 				break;
10638 
10639 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10640 			    (uchar_t **)&ipp->ipp_hopopts,
10641 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10642 			if (reterr != 0)
10643 				return (reterr);
10644 			if (ipp->ipp_hopoptslen == 0)
10645 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10646 			else
10647 				ipp->ipp_fields |= IPPF_HOPOPTS;
10648 			reterr = tcp_build_hdrs(tcp);
10649 			if (reterr != 0)
10650 				return (reterr);
10651 			break;
10652 		}
10653 		case IPV6_RTHDRDSTOPTS: {
10654 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10655 
10656 			/*
10657 			 * Sanity checks - minimum size, size a multiple of
10658 			 * eight bytes, and matching size passed in.
10659 			 */
10660 			if (inlen != 0 &&
10661 			    inlen != (8 * (dopts->ip6d_len + 1)))
10662 				return (EINVAL);
10663 
10664 			if (checkonly)
10665 				break;
10666 
10667 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10668 			    (uchar_t **)&ipp->ipp_rtdstopts,
10669 			    &ipp->ipp_rtdstoptslen, 0);
10670 			if (reterr != 0)
10671 				return (reterr);
10672 			if (ipp->ipp_rtdstoptslen == 0)
10673 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10674 			else
10675 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10676 			reterr = tcp_build_hdrs(tcp);
10677 			if (reterr != 0)
10678 				return (reterr);
10679 			break;
10680 		}
10681 		case IPV6_DSTOPTS: {
10682 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10683 
10684 			/*
10685 			 * Sanity checks - minimum size, size a multiple of
10686 			 * eight bytes, and matching size passed in.
10687 			 */
10688 			if (inlen != 0 &&
10689 			    inlen != (8 * (dopts->ip6d_len + 1)))
10690 				return (EINVAL);
10691 
10692 			if (checkonly)
10693 				break;
10694 
10695 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10696 			    (uchar_t **)&ipp->ipp_dstopts,
10697 			    &ipp->ipp_dstoptslen, 0);
10698 			if (reterr != 0)
10699 				return (reterr);
10700 			if (ipp->ipp_dstoptslen == 0)
10701 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10702 			else
10703 				ipp->ipp_fields |= IPPF_DSTOPTS;
10704 			reterr = tcp_build_hdrs(tcp);
10705 			if (reterr != 0)
10706 				return (reterr);
10707 			break;
10708 		}
10709 		case IPV6_RTHDR: {
10710 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10711 
10712 			/*
10713 			 * Sanity checks - minimum size, size a multiple of
10714 			 * eight bytes, and matching size passed in.
10715 			 */
10716 			if (inlen != 0 &&
10717 			    inlen != (8 * (rt->ip6r_len + 1)))
10718 				return (EINVAL);
10719 
10720 			if (checkonly)
10721 				break;
10722 
10723 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10724 			    (uchar_t **)&ipp->ipp_rthdr,
10725 			    &ipp->ipp_rthdrlen, 0);
10726 			if (reterr != 0)
10727 				return (reterr);
10728 			if (ipp->ipp_rthdrlen == 0)
10729 				ipp->ipp_fields &= ~IPPF_RTHDR;
10730 			else
10731 				ipp->ipp_fields |= IPPF_RTHDR;
10732 			reterr = tcp_build_hdrs(tcp);
10733 			if (reterr != 0)
10734 				return (reterr);
10735 			break;
10736 		}
10737 		case IPV6_V6ONLY:
10738 			if (!checkonly) {
10739 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10740 			}
10741 			break;
10742 		case IPV6_USE_MIN_MTU:
10743 			if (inlen != sizeof (int))
10744 				return (EINVAL);
10745 
10746 			if (*i1 < -1 || *i1 > 1)
10747 				return (EINVAL);
10748 
10749 			if (checkonly)
10750 				break;
10751 
10752 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10753 			ipp->ipp_use_min_mtu = *i1;
10754 			break;
10755 		case IPV6_SEC_OPT:
10756 			/*
10757 			 * We should not allow policy setting after
10758 			 * we start listening for connections.
10759 			 */
10760 			if (tcp->tcp_state == TCPS_LISTEN) {
10761 				return (EINVAL);
10762 			} else {
10763 				/* Handled at the IP level */
10764 				return (-EINVAL);
10765 			}
10766 		case IPV6_SRC_PREFERENCES:
10767 			if (inlen != sizeof (uint32_t))
10768 				return (EINVAL);
10769 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10770 			    *(uint32_t *)invalp);
10771 			if (reterr != 0) {
10772 				*outlenp = 0;
10773 				return (reterr);
10774 			}
10775 			break;
10776 		default:
10777 			*outlenp = 0;
10778 			return (EINVAL);
10779 		}
10780 		break;
10781 	}		/* end IPPROTO_IPV6 */
10782 	default:
10783 		*outlenp = 0;
10784 		return (EINVAL);
10785 	}
10786 	/*
10787 	 * Common case of OK return with outval same as inval
10788 	 */
10789 	if (invalp != outvalp) {
10790 		/* don't trust bcopy for identical src/dst */
10791 		(void) bcopy(invalp, outvalp, inlen);
10792 	}
10793 	*outlenp = inlen;
10794 	return (0);
10795 }
10796 
10797 /* ARGSUSED */
10798 int
10799 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10800     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10801     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10802 {
10803 	conn_t	*connp =  Q_TO_CONN(q);
10804 
10805 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10806 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10807 }
10808 
10809 int
10810 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10811     const void *optvalp, socklen_t optlen, cred_t *cr)
10812 {
10813 	conn_t		*connp = (conn_t *)proto_handle;
10814 	squeue_t	*sqp = connp->conn_sqp;
10815 	int		error;
10816 
10817 	ASSERT(connp->conn_upper_handle != NULL);
10818 	/*
10819 	 * Entering the squeue synchronously can result in a context switch,
10820 	 * which can cause a rather sever performance degradation. So we try to
10821 	 * handle whatever options we can without entering the squeue.
10822 	 */
10823 	if (level == IPPROTO_TCP) {
10824 		switch (option_name) {
10825 		case TCP_NODELAY:
10826 			if (optlen != sizeof (int32_t))
10827 				return (EINVAL);
10828 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10829 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10830 			    connp->conn_tcp->tcp_mss;
10831 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10832 			return (0);
10833 		default:
10834 			break;
10835 		}
10836 	}
10837 
10838 	error = squeue_synch_enter(sqp, connp, NULL);
10839 	if (error == ENOMEM) {
10840 		return (ENOMEM);
10841 	}
10842 
10843 	error = proto_opt_check(level, option_name, optlen, NULL,
10844 	    tcp_opt_obj.odb_opt_des_arr,
10845 	    tcp_opt_obj.odb_opt_arr_cnt,
10846 	    tcp_opt_obj.odb_topmost_tpiprovider,
10847 	    B_TRUE, B_FALSE, cr);
10848 
10849 	if (error != 0) {
10850 		if (error < 0) {
10851 			error = proto_tlitosyserr(-error);
10852 		}
10853 		squeue_synch_exit(sqp, connp);
10854 		return (error);
10855 	}
10856 
10857 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10858 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10859 	    NULL, cr, NULL);
10860 	squeue_synch_exit(sqp, connp);
10861 
10862 	if (error < 0) {
10863 		/*
10864 		 * Pass on to ip
10865 		 */
10866 		error = ip_set_options(connp, level, option_name, optvalp,
10867 		    optlen, cr);
10868 	}
10869 	return (error);
10870 }
10871 
10872 /*
10873  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10874  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10875  * headers, and the maximum size tcp header (to avoid reallocation
10876  * on the fly for additional tcp options).
10877  * Returns failure if can't allocate memory.
10878  */
10879 static int
10880 tcp_build_hdrs(tcp_t *tcp)
10881 {
10882 	char	*hdrs;
10883 	uint_t	hdrs_len;
10884 	ip6i_t	*ip6i;
10885 	char	buf[TCP_MAX_HDR_LENGTH];
10886 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10887 	in6_addr_t src, dst;
10888 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10889 	conn_t *connp = tcp->tcp_connp;
10890 
10891 	/*
10892 	 * save the existing tcp header and source/dest IP addresses
10893 	 */
10894 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10895 	src = tcp->tcp_ip6h->ip6_src;
10896 	dst = tcp->tcp_ip6h->ip6_dst;
10897 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10898 	ASSERT(hdrs_len != 0);
10899 	if (hdrs_len > tcp->tcp_iphc_len) {
10900 		/* Need to reallocate */
10901 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10902 		if (hdrs == NULL)
10903 			return (ENOMEM);
10904 		if (tcp->tcp_iphc != NULL) {
10905 			if (tcp->tcp_hdr_grown) {
10906 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10907 			} else {
10908 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10909 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10910 			}
10911 			tcp->tcp_iphc_len = 0;
10912 		}
10913 		ASSERT(tcp->tcp_iphc_len == 0);
10914 		tcp->tcp_iphc = hdrs;
10915 		tcp->tcp_iphc_len = hdrs_len;
10916 		tcp->tcp_hdr_grown = B_TRUE;
10917 	}
10918 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10919 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10920 
10921 	/* Set header fields not in ipp */
10922 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10923 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10924 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10925 	} else {
10926 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10927 	}
10928 	/*
10929 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10930 	 *
10931 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10932 	 */
10933 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10934 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10935 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10936 
10937 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10938 
10939 	tcp->tcp_ip6h->ip6_src = src;
10940 	tcp->tcp_ip6h->ip6_dst = dst;
10941 
10942 	/*
10943 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10944 	 * the default value for TCP.
10945 	 */
10946 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10947 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10948 
10949 	/*
10950 	 * If we're setting extension headers after a connection
10951 	 * has been established, and if we have a routing header
10952 	 * among the extension headers, call ip_massage_options_v6 to
10953 	 * manipulate the routing header/ip6_dst set the checksum
10954 	 * difference in the tcp header template.
10955 	 * (This happens in tcp_connect_ipv6 if the routing header
10956 	 * is set prior to the connect.)
10957 	 * Set the tcp_sum to zero first in case we've cleared a
10958 	 * routing header or don't have one at all.
10959 	 */
10960 	tcp->tcp_sum = 0;
10961 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10962 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10963 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10964 		    (uint8_t *)tcp->tcp_tcph);
10965 		if (rth != NULL) {
10966 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10967 			    rth, tcps->tcps_netstack);
10968 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10969 			    (tcp->tcp_sum >> 16));
10970 		}
10971 	}
10972 
10973 	/* Try to get everything in a single mblk */
10974 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10975 	    hdrs_len + tcps->tcps_wroff_xtra);
10976 	return (0);
10977 }
10978 
10979 /*
10980  * Transfer any source route option from ipha to buf/dst in reversed form.
10981  */
10982 static int
10983 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10984 {
10985 	ipoptp_t	opts;
10986 	uchar_t		*opt;
10987 	uint8_t		optval;
10988 	uint8_t		optlen;
10989 	uint32_t	len = 0;
10990 
10991 	for (optval = ipoptp_first(&opts, ipha);
10992 	    optval != IPOPT_EOL;
10993 	    optval = ipoptp_next(&opts)) {
10994 		opt = opts.ipoptp_cur;
10995 		optlen = opts.ipoptp_len;
10996 		switch (optval) {
10997 			int	off1, off2;
10998 		case IPOPT_SSRR:
10999 		case IPOPT_LSRR:
11000 
11001 			/* Reverse source route */
11002 			/*
11003 			 * First entry should be the next to last one in the
11004 			 * current source route (the last entry is our
11005 			 * address.)
11006 			 * The last entry should be the final destination.
11007 			 */
11008 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11009 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11010 			off1 = IPOPT_MINOFF_SR - 1;
11011 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11012 			if (off2 < 0) {
11013 				/* No entries in source route */
11014 				break;
11015 			}
11016 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11017 			/*
11018 			 * Note: use src since ipha has not had its src
11019 			 * and dst reversed (it is in the state it was
11020 			 * received.
11021 			 */
11022 			bcopy(&ipha->ipha_src, buf + off2,
11023 			    IP_ADDR_LEN);
11024 			off2 -= IP_ADDR_LEN;
11025 
11026 			while (off2 > 0) {
11027 				bcopy(opt + off2, buf + off1,
11028 				    IP_ADDR_LEN);
11029 				off1 += IP_ADDR_LEN;
11030 				off2 -= IP_ADDR_LEN;
11031 			}
11032 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11033 			buf += optlen;
11034 			len += optlen;
11035 			break;
11036 		}
11037 	}
11038 done:
11039 	/* Pad the resulting options */
11040 	while (len & 0x3) {
11041 		*buf++ = IPOPT_EOL;
11042 		len++;
11043 	}
11044 	return (len);
11045 }
11046 
11047 
11048 /*
11049  * Extract and revert a source route from ipha (if any)
11050  * and then update the relevant fields in both tcp_t and the standard header.
11051  */
11052 static void
11053 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11054 {
11055 	char	buf[TCP_MAX_HDR_LENGTH];
11056 	uint_t	tcph_len;
11057 	int	len;
11058 
11059 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11060 	len = IPH_HDR_LENGTH(ipha);
11061 	if (len == IP_SIMPLE_HDR_LENGTH)
11062 		/* Nothing to do */
11063 		return;
11064 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11065 	    (len & 0x3))
11066 		return;
11067 
11068 	tcph_len = tcp->tcp_tcp_hdr_len;
11069 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11070 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11071 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11072 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11073 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11074 	len += IP_SIMPLE_HDR_LENGTH;
11075 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11076 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11077 	if ((int)tcp->tcp_sum < 0)
11078 		tcp->tcp_sum--;
11079 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11080 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11081 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11082 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11083 	tcp->tcp_ip_hdr_len = len;
11084 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11085 	    (IP_VERSION << 4) | (len >> 2);
11086 	len += tcph_len;
11087 	tcp->tcp_hdr_len = len;
11088 }
11089 
11090 /*
11091  * Copy the standard header into its new location,
11092  * lay in the new options and then update the relevant
11093  * fields in both tcp_t and the standard header.
11094  */
11095 static int
11096 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11097 {
11098 	uint_t	tcph_len;
11099 	uint8_t	*ip_optp;
11100 	tcph_t	*new_tcph;
11101 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11102 	conn_t	*connp = tcp->tcp_connp;
11103 
11104 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11105 		return (EINVAL);
11106 
11107 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11108 		return (EINVAL);
11109 
11110 	if (checkonly) {
11111 		/*
11112 		 * do not really set, just pretend to - T_CHECK
11113 		 */
11114 		return (0);
11115 	}
11116 
11117 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11118 	if (tcp->tcp_label_len > 0) {
11119 		int padlen;
11120 		uint8_t opt;
11121 
11122 		/* convert list termination to no-ops */
11123 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11124 		ip_optp += ip_optp[IPOPT_OLEN];
11125 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11126 		while (--padlen >= 0)
11127 			*ip_optp++ = opt;
11128 	}
11129 	tcph_len = tcp->tcp_tcp_hdr_len;
11130 	new_tcph = (tcph_t *)(ip_optp + len);
11131 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11132 	tcp->tcp_tcph = new_tcph;
11133 	bcopy(ptr, ip_optp, len);
11134 
11135 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11136 
11137 	tcp->tcp_ip_hdr_len = len;
11138 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11139 	    (IP_VERSION << 4) | (len >> 2);
11140 	tcp->tcp_hdr_len = len + tcph_len;
11141 	if (!TCP_IS_DETACHED(tcp)) {
11142 		/* Always allocate room for all options. */
11143 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11144 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11145 	}
11146 	return (0);
11147 }
11148 
11149 /* Get callback routine passed to nd_load by tcp_param_register */
11150 /* ARGSUSED */
11151 static int
11152 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11153 {
11154 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11155 
11156 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11157 	return (0);
11158 }
11159 
11160 /*
11161  * Walk through the param array specified registering each element with the
11162  * named dispatch handler.
11163  */
11164 static boolean_t
11165 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11166 {
11167 	for (; cnt-- > 0; tcppa++) {
11168 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11169 			if (!nd_load(ndp, tcppa->tcp_param_name,
11170 			    tcp_param_get, tcp_param_set,
11171 			    (caddr_t)tcppa)) {
11172 				nd_free(ndp);
11173 				return (B_FALSE);
11174 			}
11175 		}
11176 	}
11177 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11178 	    KM_SLEEP);
11179 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11180 	    sizeof (tcpparam_t));
11181 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11182 	    tcp_param_get, tcp_param_set_aligned,
11183 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11184 		nd_free(ndp);
11185 		return (B_FALSE);
11186 	}
11187 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11188 	    KM_SLEEP);
11189 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11190 	    sizeof (tcpparam_t));
11191 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11192 	    tcp_param_get, tcp_param_set_aligned,
11193 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11194 		nd_free(ndp);
11195 		return (B_FALSE);
11196 	}
11197 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11198 	    KM_SLEEP);
11199 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11200 	    sizeof (tcpparam_t));
11201 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11202 	    tcp_param_get, tcp_param_set_aligned,
11203 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11204 		nd_free(ndp);
11205 		return (B_FALSE);
11206 	}
11207 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11208 	    KM_SLEEP);
11209 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11210 	    sizeof (tcpparam_t));
11211 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11212 	    tcp_param_get, tcp_param_set_aligned,
11213 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11214 		nd_free(ndp);
11215 		return (B_FALSE);
11216 	}
11217 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11218 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11219 		nd_free(ndp);
11220 		return (B_FALSE);
11221 	}
11222 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11223 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11224 		nd_free(ndp);
11225 		return (B_FALSE);
11226 	}
11227 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11228 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11229 		nd_free(ndp);
11230 		return (B_FALSE);
11231 	}
11232 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11233 	    tcp_1948_phrase_set, NULL)) {
11234 		nd_free(ndp);
11235 		return (B_FALSE);
11236 	}
11237 	/*
11238 	 * Dummy ndd variables - only to convey obsolescence information
11239 	 * through printing of their name (no get or set routines)
11240 	 * XXX Remove in future releases ?
11241 	 */
11242 	if (!nd_load(ndp,
11243 	    "tcp_close_wait_interval(obsoleted - "
11244 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11245 		nd_free(ndp);
11246 		return (B_FALSE);
11247 	}
11248 	return (B_TRUE);
11249 }
11250 
11251 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11252 /* ARGSUSED */
11253 static int
11254 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11255     cred_t *cr)
11256 {
11257 	long new_value;
11258 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11259 
11260 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11261 	    new_value < tcppa->tcp_param_min ||
11262 	    new_value > tcppa->tcp_param_max) {
11263 		return (EINVAL);
11264 	}
11265 	/*
11266 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11267 	 * round it up.  For future 64 bit requirement, we actually make it
11268 	 * a multiple of 8.
11269 	 */
11270 	if (new_value & 0x7) {
11271 		new_value = (new_value & ~0x7) + 0x8;
11272 	}
11273 	tcppa->tcp_param_val = new_value;
11274 	return (0);
11275 }
11276 
11277 /* Set callback routine passed to nd_load by tcp_param_register */
11278 /* ARGSUSED */
11279 static int
11280 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11281 {
11282 	long	new_value;
11283 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11284 
11285 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11286 	    new_value < tcppa->tcp_param_min ||
11287 	    new_value > tcppa->tcp_param_max) {
11288 		return (EINVAL);
11289 	}
11290 	tcppa->tcp_param_val = new_value;
11291 	return (0);
11292 }
11293 
11294 /*
11295  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11296  * is filled, return as much as we can.  The message passed in may be
11297  * multi-part, chained using b_cont.  "start" is the starting sequence
11298  * number for this piece.
11299  */
11300 static mblk_t *
11301 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11302 {
11303 	uint32_t	end;
11304 	mblk_t		*mp1;
11305 	mblk_t		*mp2;
11306 	mblk_t		*next_mp;
11307 	uint32_t	u1;
11308 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11309 
11310 	/* Walk through all the new pieces. */
11311 	do {
11312 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11313 		    (uintptr_t)INT_MAX);
11314 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11315 		next_mp = mp->b_cont;
11316 		if (start == end) {
11317 			/* Empty.  Blast it. */
11318 			freeb(mp);
11319 			continue;
11320 		}
11321 		mp->b_cont = NULL;
11322 		TCP_REASS_SET_SEQ(mp, start);
11323 		TCP_REASS_SET_END(mp, end);
11324 		mp1 = tcp->tcp_reass_tail;
11325 		if (!mp1) {
11326 			tcp->tcp_reass_tail = mp;
11327 			tcp->tcp_reass_head = mp;
11328 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11329 			UPDATE_MIB(&tcps->tcps_mib,
11330 			    tcpInDataUnorderBytes, end - start);
11331 			continue;
11332 		}
11333 		/* New stuff completely beyond tail? */
11334 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11335 			/* Link it on end. */
11336 			mp1->b_cont = mp;
11337 			tcp->tcp_reass_tail = mp;
11338 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11339 			UPDATE_MIB(&tcps->tcps_mib,
11340 			    tcpInDataUnorderBytes, end - start);
11341 			continue;
11342 		}
11343 		mp1 = tcp->tcp_reass_head;
11344 		u1 = TCP_REASS_SEQ(mp1);
11345 		/* New stuff at the front? */
11346 		if (SEQ_LT(start, u1)) {
11347 			/* Yes... Check for overlap. */
11348 			mp->b_cont = mp1;
11349 			tcp->tcp_reass_head = mp;
11350 			tcp_reass_elim_overlap(tcp, mp);
11351 			continue;
11352 		}
11353 		/*
11354 		 * The new piece fits somewhere between the head and tail.
11355 		 * We find our slot, where mp1 precedes us and mp2 trails.
11356 		 */
11357 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11358 			u1 = TCP_REASS_SEQ(mp2);
11359 			if (SEQ_LEQ(start, u1))
11360 				break;
11361 		}
11362 		/* Link ourselves in */
11363 		mp->b_cont = mp2;
11364 		mp1->b_cont = mp;
11365 
11366 		/* Trim overlap with following mblk(s) first */
11367 		tcp_reass_elim_overlap(tcp, mp);
11368 
11369 		/* Trim overlap with preceding mblk */
11370 		tcp_reass_elim_overlap(tcp, mp1);
11371 
11372 	} while (start = end, mp = next_mp);
11373 	mp1 = tcp->tcp_reass_head;
11374 	/* Anything ready to go? */
11375 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11376 		return (NULL);
11377 	/* Eat what we can off the queue */
11378 	for (;;) {
11379 		mp = mp1->b_cont;
11380 		end = TCP_REASS_END(mp1);
11381 		TCP_REASS_SET_SEQ(mp1, 0);
11382 		TCP_REASS_SET_END(mp1, 0);
11383 		if (!mp) {
11384 			tcp->tcp_reass_tail = NULL;
11385 			break;
11386 		}
11387 		if (end != TCP_REASS_SEQ(mp)) {
11388 			mp1->b_cont = NULL;
11389 			break;
11390 		}
11391 		mp1 = mp;
11392 	}
11393 	mp1 = tcp->tcp_reass_head;
11394 	tcp->tcp_reass_head = mp;
11395 	return (mp1);
11396 }
11397 
11398 /* Eliminate any overlap that mp may have over later mblks */
11399 static void
11400 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11401 {
11402 	uint32_t	end;
11403 	mblk_t		*mp1;
11404 	uint32_t	u1;
11405 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11406 
11407 	end = TCP_REASS_END(mp);
11408 	while ((mp1 = mp->b_cont) != NULL) {
11409 		u1 = TCP_REASS_SEQ(mp1);
11410 		if (!SEQ_GT(end, u1))
11411 			break;
11412 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11413 			mp->b_wptr -= end - u1;
11414 			TCP_REASS_SET_END(mp, u1);
11415 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11416 			UPDATE_MIB(&tcps->tcps_mib,
11417 			    tcpInDataPartDupBytes, end - u1);
11418 			break;
11419 		}
11420 		mp->b_cont = mp1->b_cont;
11421 		TCP_REASS_SET_SEQ(mp1, 0);
11422 		TCP_REASS_SET_END(mp1, 0);
11423 		freeb(mp1);
11424 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11425 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11426 	}
11427 	if (!mp1)
11428 		tcp->tcp_reass_tail = mp;
11429 }
11430 
11431 static uint_t
11432 tcp_rwnd_reopen(tcp_t *tcp)
11433 {
11434 	uint_t ret = 0;
11435 	uint_t thwin;
11436 
11437 	/* Learn the latest rwnd information that we sent to the other side. */
11438 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11439 	    << tcp->tcp_rcv_ws;
11440 	/* This is peer's calculated send window (our receive window). */
11441 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11442 	/*
11443 	 * Increase the receive window to max.  But we need to do receiver
11444 	 * SWS avoidance.  This means that we need to check the increase of
11445 	 * of receive window is at least 1 MSS.
11446 	 */
11447 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11448 		/*
11449 		 * If the window that the other side knows is less than max
11450 		 * deferred acks segments, send an update immediately.
11451 		 */
11452 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11453 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11454 			ret = TH_ACK_NEEDED;
11455 		}
11456 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11457 	}
11458 	return (ret);
11459 }
11460 
11461 /*
11462  * Send up all messages queued on tcp_rcv_list.
11463  */
11464 static uint_t
11465 tcp_rcv_drain(tcp_t *tcp)
11466 {
11467 	mblk_t *mp;
11468 	uint_t ret = 0;
11469 #ifdef DEBUG
11470 	uint_t cnt = 0;
11471 #endif
11472 	queue_t	*q = tcp->tcp_rq;
11473 
11474 	/* Can't drain on an eager connection */
11475 	if (tcp->tcp_listener != NULL)
11476 		return (ret);
11477 
11478 	/* Can't be a non-STREAMS connection */
11479 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
11480 
11481 	/* No need for the push timer now. */
11482 	if (tcp->tcp_push_tid != 0) {
11483 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11484 		tcp->tcp_push_tid = 0;
11485 	}
11486 
11487 	/*
11488 	 * Handle two cases here: we are currently fused or we were
11489 	 * previously fused and have some urgent data to be delivered
11490 	 * upstream.  The latter happens because we either ran out of
11491 	 * memory or were detached and therefore sending the SIGURG was
11492 	 * deferred until this point.  In either case we pass control
11493 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11494 	 * some work.
11495 	 */
11496 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11497 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11498 		    tcp->tcp_fused_sigurg_mp != NULL);
11499 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11500 		    &tcp->tcp_fused_sigurg_mp))
11501 			return (ret);
11502 	}
11503 
11504 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11505 		tcp->tcp_rcv_list = mp->b_next;
11506 		mp->b_next = NULL;
11507 #ifdef DEBUG
11508 		cnt += msgdsize(mp);
11509 #endif
11510 		/* Does this need SSL processing first? */
11511 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11512 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11513 			    mblk_t *, mp);
11514 			tcp_kssl_input(tcp, mp);
11515 			continue;
11516 		}
11517 		putnext(q, mp);
11518 	}
11519 #ifdef DEBUG
11520 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11521 #endif
11522 	tcp->tcp_rcv_last_head = NULL;
11523 	tcp->tcp_rcv_last_tail = NULL;
11524 	tcp->tcp_rcv_cnt = 0;
11525 
11526 	if (canputnext(q))
11527 		return (tcp_rwnd_reopen(tcp));
11528 
11529 	return (ret);
11530 }
11531 
11532 /*
11533  * Queue data on tcp_rcv_list which is a b_next chain.
11534  * tcp_rcv_last_head/tail is the last element of this chain.
11535  * Each element of the chain is a b_cont chain.
11536  *
11537  * M_DATA messages are added to the current element.
11538  * Other messages are added as new (b_next) elements.
11539  */
11540 void
11541 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11542 {
11543 	ASSERT(seg_len == msgdsize(mp));
11544 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11545 
11546 	if (tcp->tcp_rcv_list == NULL) {
11547 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11548 		tcp->tcp_rcv_list = mp;
11549 		tcp->tcp_rcv_last_head = mp;
11550 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11551 		tcp->tcp_rcv_last_tail->b_cont = mp;
11552 	} else {
11553 		tcp->tcp_rcv_last_head->b_next = mp;
11554 		tcp->tcp_rcv_last_head = mp;
11555 	}
11556 
11557 	while (mp->b_cont)
11558 		mp = mp->b_cont;
11559 
11560 	tcp->tcp_rcv_last_tail = mp;
11561 	tcp->tcp_rcv_cnt += seg_len;
11562 	tcp->tcp_rwnd -= seg_len;
11563 }
11564 
11565 /*
11566  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11567  *
11568  * This is the default entry function into TCP on the read side. TCP is
11569  * always entered via squeue i.e. using squeue's for mutual exclusion.
11570  * When classifier does a lookup to find the tcp, it also puts a reference
11571  * on the conn structure associated so the tcp is guaranteed to exist
11572  * when we come here. We still need to check the state because it might
11573  * as well has been closed. The squeue processing function i.e. squeue_enter,
11574  * is responsible for doing the CONN_DEC_REF.
11575  *
11576  * Apart from the default entry point, IP also sends packets directly to
11577  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11578  * connections.
11579  */
11580 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11581 void
11582 tcp_input(void *arg, mblk_t *mp, void *arg2)
11583 {
11584 	conn_t	*connp = (conn_t *)arg;
11585 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11586 
11587 	/* arg2 is the sqp */
11588 	ASSERT(arg2 != NULL);
11589 	ASSERT(mp != NULL);
11590 
11591 	/*
11592 	 * Don't accept any input on a closed tcp as this TCP logically does
11593 	 * not exist on the system. Don't proceed further with this TCP.
11594 	 * For eg. this packet could trigger another close of this tcp
11595 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11596 	 * tcp_clean_death / tcp_closei_local must be called at most once
11597 	 * on a TCP. In this case we need to refeed the packet into the
11598 	 * classifier and figure out where the packet should go. Need to
11599 	 * preserve the recv_ill somehow. Until we figure that out, for
11600 	 * now just drop the packet if we can't classify the packet.
11601 	 */
11602 	if (tcp->tcp_state == TCPS_CLOSED ||
11603 	    tcp->tcp_state == TCPS_BOUND) {
11604 		conn_t	*new_connp;
11605 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11606 
11607 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11608 		if (new_connp != NULL) {
11609 			tcp_reinput(new_connp, mp, arg2);
11610 			return;
11611 		}
11612 		/* We failed to classify. For now just drop the packet */
11613 		freemsg(mp);
11614 		return;
11615 	}
11616 
11617 	if (DB_TYPE(mp) != M_DATA) {
11618 		tcp_rput_common(tcp, mp);
11619 		return;
11620 	}
11621 
11622 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11623 		squeue_t	*final_sqp;
11624 
11625 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11626 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11627 		DB_CKSUMSTART(mp) = 0;
11628 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11629 		    connp->conn_final_sqp == NULL &&
11630 		    tcp_outbound_squeue_switch) {
11631 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11632 			connp->conn_final_sqp = final_sqp;
11633 			if (connp->conn_final_sqp != connp->conn_sqp) {
11634 				CONN_INC_REF(connp);
11635 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11636 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11637 				    tcp_rput_data, connp, ip_squeue_flag,
11638 				    SQTAG_CONNECT_FINISH);
11639 				return;
11640 			}
11641 		}
11642 	}
11643 	tcp_rput_data(connp, mp, arg2);
11644 }
11645 
11646 /*
11647  * The read side put procedure.
11648  * The packets passed up by ip are assume to be aligned according to
11649  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11650  */
11651 static void
11652 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11653 {
11654 	/*
11655 	 * tcp_rput_data() does not expect M_CTL except for the case
11656 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11657 	 * type. Need to make sure that any other M_CTLs don't make
11658 	 * it to tcp_rput_data since it is not expecting any and doesn't
11659 	 * check for it.
11660 	 */
11661 	if (DB_TYPE(mp) == M_CTL) {
11662 		switch (*(uint32_t *)(mp->b_rptr)) {
11663 		case TCP_IOC_ABORT_CONN:
11664 			/*
11665 			 * Handle connection abort request.
11666 			 */
11667 			tcp_ioctl_abort_handler(tcp, mp);
11668 			return;
11669 		case IPSEC_IN:
11670 			/*
11671 			 * Only secure icmp arrive in TCP and they
11672 			 * don't go through data path.
11673 			 */
11674 			tcp_icmp_error(tcp, mp);
11675 			return;
11676 		case IN_PKTINFO:
11677 			/*
11678 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11679 			 * sockets that are receiving IPv4 traffic. tcp
11680 			 */
11681 			ASSERT(tcp->tcp_family == AF_INET6);
11682 			ASSERT(tcp->tcp_ipv6_recvancillary &
11683 			    TCP_IPV6_RECVPKTINFO);
11684 			tcp_rput_data(tcp->tcp_connp, mp,
11685 			    tcp->tcp_connp->conn_sqp);
11686 			return;
11687 		case MDT_IOC_INFO_UPDATE:
11688 			/*
11689 			 * Handle Multidata information update; the
11690 			 * following routine will free the message.
11691 			 */
11692 			if (tcp->tcp_connp->conn_mdt_ok) {
11693 				tcp_mdt_update(tcp,
11694 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11695 				    B_FALSE);
11696 			}
11697 			freemsg(mp);
11698 			return;
11699 		case LSO_IOC_INFO_UPDATE:
11700 			/*
11701 			 * Handle LSO information update; the following
11702 			 * routine will free the message.
11703 			 */
11704 			if (tcp->tcp_connp->conn_lso_ok) {
11705 				tcp_lso_update(tcp,
11706 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11707 			}
11708 			freemsg(mp);
11709 			return;
11710 		default:
11711 			/*
11712 			 * tcp_icmp_err() will process the M_CTL packets.
11713 			 * Non-ICMP packets, if any, will be discarded in
11714 			 * tcp_icmp_err(). We will process the ICMP packet
11715 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11716 			 * incoming ICMP packet may result in changing
11717 			 * the tcp_mss, which we would need if we have
11718 			 * packets to retransmit.
11719 			 */
11720 			tcp_icmp_error(tcp, mp);
11721 			return;
11722 		}
11723 	}
11724 
11725 	/* No point processing the message if tcp is already closed */
11726 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11727 		freemsg(mp);
11728 		return;
11729 	}
11730 
11731 	tcp_rput_other(tcp, mp);
11732 }
11733 
11734 
11735 /* The minimum of smoothed mean deviation in RTO calculation. */
11736 #define	TCP_SD_MIN	400
11737 
11738 /*
11739  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11740  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11741  * are the same as those in Appendix A.2 of that paper.
11742  *
11743  * m = new measurement
11744  * sa = smoothed RTT average (8 * average estimates).
11745  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11746  */
11747 static void
11748 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11749 {
11750 	long m = TICK_TO_MSEC(rtt);
11751 	clock_t sa = tcp->tcp_rtt_sa;
11752 	clock_t sv = tcp->tcp_rtt_sd;
11753 	clock_t rto;
11754 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11755 
11756 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11757 	tcp->tcp_rtt_update++;
11758 
11759 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11760 	if (sa != 0) {
11761 		/*
11762 		 * Update average estimator:
11763 		 *	new rtt = 7/8 old rtt + 1/8 Error
11764 		 */
11765 
11766 		/* m is now Error in estimate. */
11767 		m -= sa >> 3;
11768 		if ((sa += m) <= 0) {
11769 			/*
11770 			 * Don't allow the smoothed average to be negative.
11771 			 * We use 0 to denote reinitialization of the
11772 			 * variables.
11773 			 */
11774 			sa = 1;
11775 		}
11776 
11777 		/*
11778 		 * Update deviation estimator:
11779 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11780 		 */
11781 		if (m < 0)
11782 			m = -m;
11783 		m -= sv >> 2;
11784 		sv += m;
11785 	} else {
11786 		/*
11787 		 * This follows BSD's implementation.  So the reinitialized
11788 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11789 		 * link is bandwidth dominated, doubling the window size
11790 		 * during slow start means doubling the RTT.  We want to be
11791 		 * more conservative when we reinitialize our estimates.  3
11792 		 * is just a convenient number.
11793 		 */
11794 		sa = m << 3;
11795 		sv = m << 1;
11796 	}
11797 	if (sv < TCP_SD_MIN) {
11798 		/*
11799 		 * We do not know that if sa captures the delay ACK
11800 		 * effect as in a long train of segments, a receiver
11801 		 * does not delay its ACKs.  So set the minimum of sv
11802 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11803 		 * of BSD DATO.  That means the minimum of mean
11804 		 * deviation is 100 ms.
11805 		 *
11806 		 */
11807 		sv = TCP_SD_MIN;
11808 	}
11809 	tcp->tcp_rtt_sa = sa;
11810 	tcp->tcp_rtt_sd = sv;
11811 	/*
11812 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11813 	 *
11814 	 * Add tcp_rexmit_interval extra in case of extreme environment
11815 	 * where the algorithm fails to work.  The default value of
11816 	 * tcp_rexmit_interval_extra should be 0.
11817 	 *
11818 	 * As we use a finer grained clock than BSD and update
11819 	 * RTO for every ACKs, add in another .25 of RTT to the
11820 	 * deviation of RTO to accomodate burstiness of 1/4 of
11821 	 * window size.
11822 	 */
11823 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11824 
11825 	if (rto > tcps->tcps_rexmit_interval_max) {
11826 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11827 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11828 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11829 	} else {
11830 		tcp->tcp_rto = rto;
11831 	}
11832 
11833 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11834 	tcp->tcp_timer_backoff = 0;
11835 }
11836 
11837 /*
11838  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11839  * send queue which starts at the given sequence number. If the given
11840  * sequence number is equal to last valid sequence number (tcp_snxt), the
11841  * returned mblk is the last valid mblk, and off is set to the length of
11842  * that mblk.
11843  *
11844  * send queue which starts at the given seq. no.
11845  *
11846  * Parameters:
11847  *	tcp_t *tcp: the tcp instance pointer.
11848  *	uint32_t seq: the starting seq. no of the requested segment.
11849  *	int32_t *off: after the execution, *off will be the offset to
11850  *		the returned mblk which points to the requested seq no.
11851  *		It is the caller's responsibility to send in a non-null off.
11852  *
11853  * Return:
11854  *	A mblk_t pointer pointing to the requested segment in send queue.
11855  */
11856 static mblk_t *
11857 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11858 {
11859 	int32_t	cnt;
11860 	mblk_t	*mp;
11861 
11862 	/* Defensive coding.  Make sure we don't send incorrect data. */
11863 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
11864 		return (NULL);
11865 
11866 	cnt = seq - tcp->tcp_suna;
11867 	mp = tcp->tcp_xmit_head;
11868 	while (cnt > 0 && mp != NULL) {
11869 		cnt -= mp->b_wptr - mp->b_rptr;
11870 		if (cnt <= 0) {
11871 			cnt += mp->b_wptr - mp->b_rptr;
11872 			break;
11873 		}
11874 		mp = mp->b_cont;
11875 	}
11876 	ASSERT(mp != NULL);
11877 	*off = cnt;
11878 	return (mp);
11879 }
11880 
11881 /*
11882  * This function handles all retransmissions if SACK is enabled for this
11883  * connection.  First it calculates how many segments can be retransmitted
11884  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11885  * segments.  A segment is eligible if sack_cnt for that segment is greater
11886  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11887  * all eligible segments, it checks to see if TCP can send some new segments
11888  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11889  *
11890  * Parameters:
11891  *	tcp_t *tcp: the tcp structure of the connection.
11892  *	uint_t *flags: in return, appropriate value will be set for
11893  *	tcp_rput_data().
11894  */
11895 static void
11896 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11897 {
11898 	notsack_blk_t	*notsack_blk;
11899 	int32_t		usable_swnd;
11900 	int32_t		mss;
11901 	uint32_t	seg_len;
11902 	mblk_t		*xmit_mp;
11903 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11904 
11905 	ASSERT(tcp->tcp_sack_info != NULL);
11906 	ASSERT(tcp->tcp_notsack_list != NULL);
11907 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11908 
11909 	/* Defensive coding in case there is a bug... */
11910 	if (tcp->tcp_notsack_list == NULL) {
11911 		return;
11912 	}
11913 	notsack_blk = tcp->tcp_notsack_list;
11914 	mss = tcp->tcp_mss;
11915 
11916 	/*
11917 	 * Limit the num of outstanding data in the network to be
11918 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11919 	 */
11920 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11921 
11922 	/* At least retransmit 1 MSS of data. */
11923 	if (usable_swnd <= 0) {
11924 		usable_swnd = mss;
11925 	}
11926 
11927 	/* Make sure no new RTT samples will be taken. */
11928 	tcp->tcp_csuna = tcp->tcp_snxt;
11929 
11930 	notsack_blk = tcp->tcp_notsack_list;
11931 	while (usable_swnd > 0) {
11932 		mblk_t		*snxt_mp, *tmp_mp;
11933 		tcp_seq		begin = tcp->tcp_sack_snxt;
11934 		tcp_seq		end;
11935 		int32_t		off;
11936 
11937 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11938 			if (SEQ_GT(notsack_blk->end, begin) &&
11939 			    (notsack_blk->sack_cnt >=
11940 			    tcps->tcps_dupack_fast_retransmit)) {
11941 				end = notsack_blk->end;
11942 				if (SEQ_LT(begin, notsack_blk->begin)) {
11943 					begin = notsack_blk->begin;
11944 				}
11945 				break;
11946 			}
11947 		}
11948 		/*
11949 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11950 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11951 		 * set to tcp_cwnd_ssthresh.
11952 		 */
11953 		if (notsack_blk == NULL) {
11954 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11955 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11956 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11957 				ASSERT(tcp->tcp_cwnd > 0);
11958 				return;
11959 			} else {
11960 				usable_swnd = usable_swnd / mss;
11961 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11962 				    MAX(usable_swnd * mss, mss);
11963 				*flags |= TH_XMIT_NEEDED;
11964 				return;
11965 			}
11966 		}
11967 
11968 		/*
11969 		 * Note that we may send more than usable_swnd allows here
11970 		 * because of round off, but no more than 1 MSS of data.
11971 		 */
11972 		seg_len = end - begin;
11973 		if (seg_len > mss)
11974 			seg_len = mss;
11975 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11976 		ASSERT(snxt_mp != NULL);
11977 		/* This should not happen.  Defensive coding again... */
11978 		if (snxt_mp == NULL) {
11979 			return;
11980 		}
11981 
11982 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11983 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11984 		if (xmit_mp == NULL)
11985 			return;
11986 
11987 		usable_swnd -= seg_len;
11988 		tcp->tcp_pipe += seg_len;
11989 		tcp->tcp_sack_snxt = begin + seg_len;
11990 
11991 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11992 
11993 		/*
11994 		 * Update the send timestamp to avoid false retransmission.
11995 		 */
11996 		snxt_mp->b_prev = (mblk_t *)lbolt;
11997 
11998 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
11999 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12000 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12001 		/*
12002 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12003 		 * This happens when new data sent during fast recovery is
12004 		 * also lost.  If TCP retransmits those new data, it needs
12005 		 * to extend SACK recover phase to avoid starting another
12006 		 * fast retransmit/recovery unnecessarily.
12007 		 */
12008 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12009 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12010 		}
12011 	}
12012 }
12013 
12014 /*
12015  * This function handles policy checking at TCP level for non-hard_bound/
12016  * detached connections.
12017  */
12018 static boolean_t
12019 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12020     boolean_t secure, boolean_t mctl_present)
12021 {
12022 	ipsec_latch_t *ipl = NULL;
12023 	ipsec_action_t *act = NULL;
12024 	mblk_t *data_mp;
12025 	ipsec_in_t *ii;
12026 	const char *reason;
12027 	kstat_named_t *counter;
12028 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12029 	ipsec_stack_t	*ipss;
12030 	ip_stack_t	*ipst;
12031 
12032 	ASSERT(mctl_present || !secure);
12033 
12034 	ASSERT((ipha == NULL && ip6h != NULL) ||
12035 	    (ip6h == NULL && ipha != NULL));
12036 
12037 	/*
12038 	 * We don't necessarily have an ipsec_in_act action to verify
12039 	 * policy because of assymetrical policy where we have only
12040 	 * outbound policy and no inbound policy (possible with global
12041 	 * policy).
12042 	 */
12043 	if (!secure) {
12044 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12045 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12046 			return (B_TRUE);
12047 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12048 		    "tcp_check_policy", ipha, ip6h, secure,
12049 		    tcps->tcps_netstack);
12050 		ipss = tcps->tcps_netstack->netstack_ipsec;
12051 
12052 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12053 		    DROPPER(ipss, ipds_tcp_clear),
12054 		    &tcps->tcps_dropper);
12055 		return (B_FALSE);
12056 	}
12057 
12058 	/*
12059 	 * We have a secure packet.
12060 	 */
12061 	if (act == NULL) {
12062 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12063 		    "tcp_check_policy", ipha, ip6h, secure,
12064 		    tcps->tcps_netstack);
12065 		ipss = tcps->tcps_netstack->netstack_ipsec;
12066 
12067 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12068 		    DROPPER(ipss, ipds_tcp_secure),
12069 		    &tcps->tcps_dropper);
12070 		return (B_FALSE);
12071 	}
12072 
12073 	/*
12074 	 * XXX This whole routine is currently incorrect.  ipl should
12075 	 * be set to the latch pointer, but is currently not set, so
12076 	 * we initialize it to NULL to avoid picking up random garbage.
12077 	 */
12078 	if (ipl == NULL)
12079 		return (B_TRUE);
12080 
12081 	data_mp = first_mp->b_cont;
12082 
12083 	ii = (ipsec_in_t *)first_mp->b_rptr;
12084 
12085 	ipst = tcps->tcps_netstack->netstack_ip;
12086 
12087 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12088 	    &counter, tcp->tcp_connp)) {
12089 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12090 		return (B_TRUE);
12091 	}
12092 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12093 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12094 	    reason);
12095 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12096 
12097 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12098 	    &tcps->tcps_dropper);
12099 	return (B_FALSE);
12100 }
12101 
12102 /*
12103  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12104  * retransmission after a timeout.
12105  *
12106  * To limit the number of duplicate segments, we limit the number of segment
12107  * to be sent in one time to tcp_snd_burst, the burst variable.
12108  */
12109 static void
12110 tcp_ss_rexmit(tcp_t *tcp)
12111 {
12112 	uint32_t	snxt;
12113 	uint32_t	smax;
12114 	int32_t		win;
12115 	int32_t		mss;
12116 	int32_t		off;
12117 	int32_t		burst = tcp->tcp_snd_burst;
12118 	mblk_t		*snxt_mp;
12119 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12120 
12121 	/*
12122 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12123 	 * all unack'ed segments.
12124 	 */
12125 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12126 		smax = tcp->tcp_rexmit_max;
12127 		snxt = tcp->tcp_rexmit_nxt;
12128 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12129 			snxt = tcp->tcp_suna;
12130 		}
12131 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12132 		win -= snxt - tcp->tcp_suna;
12133 		mss = tcp->tcp_mss;
12134 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12135 
12136 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12137 		    (burst > 0) && (snxt_mp != NULL)) {
12138 			mblk_t	*xmit_mp;
12139 			mblk_t	*old_snxt_mp = snxt_mp;
12140 			uint32_t cnt = mss;
12141 
12142 			if (win < cnt) {
12143 				cnt = win;
12144 			}
12145 			if (SEQ_GT(snxt + cnt, smax)) {
12146 				cnt = smax - snxt;
12147 			}
12148 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12149 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12150 			if (xmit_mp == NULL)
12151 				return;
12152 
12153 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12154 
12155 			snxt += cnt;
12156 			win -= cnt;
12157 			/*
12158 			 * Update the send timestamp to avoid false
12159 			 * retransmission.
12160 			 */
12161 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12162 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12163 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12164 
12165 			tcp->tcp_rexmit_nxt = snxt;
12166 			burst--;
12167 		}
12168 		/*
12169 		 * If we have transmitted all we have at the time
12170 		 * we started the retranmission, we can leave
12171 		 * the rest of the job to tcp_wput_data().  But we
12172 		 * need to check the send window first.  If the
12173 		 * win is not 0, go on with tcp_wput_data().
12174 		 */
12175 		if (SEQ_LT(snxt, smax) || win == 0) {
12176 			return;
12177 		}
12178 	}
12179 	/* Only call tcp_wput_data() if there is data to be sent. */
12180 	if (tcp->tcp_unsent) {
12181 		tcp_wput_data(tcp, NULL, B_FALSE);
12182 	}
12183 }
12184 
12185 /*
12186  * Process all TCP option in SYN segment.  Note that this function should
12187  * be called after tcp_adapt_ire() is called so that the necessary info
12188  * from IRE is already set in the tcp structure.
12189  *
12190  * This function sets up the correct tcp_mss value according to the
12191  * MSS option value and our header size.  It also sets up the window scale
12192  * and timestamp values, and initialize SACK info blocks.  But it does not
12193  * change receive window size after setting the tcp_mss value.  The caller
12194  * should do the appropriate change.
12195  */
12196 void
12197 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12198 {
12199 	int options;
12200 	tcp_opt_t tcpopt;
12201 	uint32_t mss_max;
12202 	char *tmp_tcph;
12203 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12204 
12205 	tcpopt.tcp = NULL;
12206 	options = tcp_parse_options(tcph, &tcpopt);
12207 
12208 	/*
12209 	 * Process MSS option.  Note that MSS option value does not account
12210 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12211 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12212 	 * IPv6.
12213 	 */
12214 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12215 		if (tcp->tcp_ipversion == IPV4_VERSION)
12216 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12217 		else
12218 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12219 	} else {
12220 		if (tcp->tcp_ipversion == IPV4_VERSION)
12221 			mss_max = tcps->tcps_mss_max_ipv4;
12222 		else
12223 			mss_max = tcps->tcps_mss_max_ipv6;
12224 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12225 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12226 		else if (tcpopt.tcp_opt_mss > mss_max)
12227 			tcpopt.tcp_opt_mss = mss_max;
12228 	}
12229 
12230 	/* Process Window Scale option. */
12231 	if (options & TCP_OPT_WSCALE_PRESENT) {
12232 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12233 		tcp->tcp_snd_ws_ok = B_TRUE;
12234 	} else {
12235 		tcp->tcp_snd_ws = B_FALSE;
12236 		tcp->tcp_snd_ws_ok = B_FALSE;
12237 		tcp->tcp_rcv_ws = B_FALSE;
12238 	}
12239 
12240 	/* Process Timestamp option. */
12241 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12242 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12243 		tmp_tcph = (char *)tcp->tcp_tcph;
12244 
12245 		tcp->tcp_snd_ts_ok = B_TRUE;
12246 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12247 		tcp->tcp_last_rcv_lbolt = lbolt64;
12248 		ASSERT(OK_32PTR(tmp_tcph));
12249 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12250 
12251 		/* Fill in our template header with basic timestamp option. */
12252 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12253 		tmp_tcph[0] = TCPOPT_NOP;
12254 		tmp_tcph[1] = TCPOPT_NOP;
12255 		tmp_tcph[2] = TCPOPT_TSTAMP;
12256 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12257 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12258 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12259 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12260 	} else {
12261 		tcp->tcp_snd_ts_ok = B_FALSE;
12262 	}
12263 
12264 	/*
12265 	 * Process SACK options.  If SACK is enabled for this connection,
12266 	 * then allocate the SACK info structure.  Note the following ways
12267 	 * when tcp_snd_sack_ok is set to true.
12268 	 *
12269 	 * For active connection: in tcp_adapt_ire() called in
12270 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12271 	 * is checked.
12272 	 *
12273 	 * For passive connection: in tcp_adapt_ire() called in
12274 	 * tcp_accept_comm().
12275 	 *
12276 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12277 	 * That check makes sure that if we did not send a SACK OK option,
12278 	 * we will not enable SACK for this connection even though the other
12279 	 * side sends us SACK OK option.  For active connection, the SACK
12280 	 * info structure has already been allocated.  So we need to free
12281 	 * it if SACK is disabled.
12282 	 */
12283 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12284 	    (tcp->tcp_snd_sack_ok ||
12285 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12286 		/* This should be true only in the passive case. */
12287 		if (tcp->tcp_sack_info == NULL) {
12288 			ASSERT(TCP_IS_DETACHED(tcp));
12289 			tcp->tcp_sack_info =
12290 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12291 		}
12292 		if (tcp->tcp_sack_info == NULL) {
12293 			tcp->tcp_snd_sack_ok = B_FALSE;
12294 		} else {
12295 			tcp->tcp_snd_sack_ok = B_TRUE;
12296 			if (tcp->tcp_snd_ts_ok) {
12297 				tcp->tcp_max_sack_blk = 3;
12298 			} else {
12299 				tcp->tcp_max_sack_blk = 4;
12300 			}
12301 		}
12302 	} else {
12303 		/*
12304 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12305 		 * no SACK info will be used for this
12306 		 * connection.  This assumes that SACK usage
12307 		 * permission is negotiated.  This may need
12308 		 * to be changed once this is clarified.
12309 		 */
12310 		if (tcp->tcp_sack_info != NULL) {
12311 			ASSERT(tcp->tcp_notsack_list == NULL);
12312 			kmem_cache_free(tcp_sack_info_cache,
12313 			    tcp->tcp_sack_info);
12314 			tcp->tcp_sack_info = NULL;
12315 		}
12316 		tcp->tcp_snd_sack_ok = B_FALSE;
12317 	}
12318 
12319 	/*
12320 	 * Now we know the exact TCP/IP header length, subtract
12321 	 * that from tcp_mss to get our side's MSS.
12322 	 */
12323 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12324 	/*
12325 	 * Here we assume that the other side's header size will be equal to
12326 	 * our header size.  We calculate the real MSS accordingly.  Need to
12327 	 * take into additional stuffs IPsec puts in.
12328 	 *
12329 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12330 	 */
12331 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12332 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12333 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12334 
12335 	/*
12336 	 * Set MSS to the smaller one of both ends of the connection.
12337 	 * We should not have called tcp_mss_set() before, but our
12338 	 * side of the MSS should have been set to a proper value
12339 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12340 	 * STREAM head parameters properly.
12341 	 *
12342 	 * If we have a larger-than-16-bit window but the other side
12343 	 * didn't want to do window scale, tcp_rwnd_set() will take
12344 	 * care of that.
12345 	 */
12346 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12347 }
12348 
12349 /*
12350  * Sends the T_CONN_IND to the listener. The caller calls this
12351  * functions via squeue to get inside the listener's perimeter
12352  * once the 3 way hand shake is done a T_CONN_IND needs to be
12353  * sent. As an optimization, the caller can call this directly
12354  * if listener's perimeter is same as eager's.
12355  */
12356 /* ARGSUSED */
12357 void
12358 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12359 {
12360 	conn_t			*lconnp = (conn_t *)arg;
12361 	tcp_t			*listener = lconnp->conn_tcp;
12362 	tcp_t			*tcp;
12363 	struct T_conn_ind	*conn_ind;
12364 	ipaddr_t 		*addr_cache;
12365 	boolean_t		need_send_conn_ind = B_FALSE;
12366 	tcp_stack_t		*tcps = listener->tcp_tcps;
12367 
12368 	/* retrieve the eager */
12369 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12370 	ASSERT(conn_ind->OPT_offset != 0 &&
12371 	    conn_ind->OPT_length == sizeof (intptr_t));
12372 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12373 	    conn_ind->OPT_length);
12374 
12375 	/*
12376 	 * TLI/XTI applications will get confused by
12377 	 * sending eager as an option since it violates
12378 	 * the option semantics. So remove the eager as
12379 	 * option since TLI/XTI app doesn't need it anyway.
12380 	 */
12381 	if (!TCP_IS_SOCKET(listener)) {
12382 		conn_ind->OPT_length = 0;
12383 		conn_ind->OPT_offset = 0;
12384 	}
12385 	if (listener->tcp_state != TCPS_LISTEN) {
12386 		/*
12387 		 * If listener has closed, it would have caused a
12388 		 * a cleanup/blowoff to happen for the eager. We
12389 		 * just need to return.
12390 		 */
12391 		freemsg(mp);
12392 		return;
12393 	}
12394 
12395 
12396 	/*
12397 	 * if the conn_req_q is full defer passing up the
12398 	 * T_CONN_IND until space is availabe after t_accept()
12399 	 * processing
12400 	 */
12401 	mutex_enter(&listener->tcp_eager_lock);
12402 
12403 	/*
12404 	 * Take the eager out, if it is in the list of droppable eagers
12405 	 * as we are here because the 3W handshake is over.
12406 	 */
12407 	MAKE_UNDROPPABLE(tcp);
12408 
12409 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12410 		tcp_t *tail;
12411 
12412 		/*
12413 		 * The eager already has an extra ref put in tcp_rput_data
12414 		 * so that it stays till accept comes back even though it
12415 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12416 		 */
12417 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12418 		listener->tcp_conn_req_cnt_q0--;
12419 		listener->tcp_conn_req_cnt_q++;
12420 
12421 		/* Move from SYN_RCVD to ESTABLISHED list  */
12422 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12423 		    tcp->tcp_eager_prev_q0;
12424 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12425 		    tcp->tcp_eager_next_q0;
12426 		tcp->tcp_eager_prev_q0 = NULL;
12427 		tcp->tcp_eager_next_q0 = NULL;
12428 
12429 		/*
12430 		 * Insert at end of the queue because sockfs
12431 		 * sends down T_CONN_RES in chronological
12432 		 * order. Leaving the older conn indications
12433 		 * at front of the queue helps reducing search
12434 		 * time.
12435 		 */
12436 		tail = listener->tcp_eager_last_q;
12437 		if (tail != NULL)
12438 			tail->tcp_eager_next_q = tcp;
12439 		else
12440 			listener->tcp_eager_next_q = tcp;
12441 		listener->tcp_eager_last_q = tcp;
12442 		tcp->tcp_eager_next_q = NULL;
12443 		/*
12444 		 * Delay sending up the T_conn_ind until we are
12445 		 * done with the eager. Once we have have sent up
12446 		 * the T_conn_ind, the accept can potentially complete
12447 		 * any time and release the refhold we have on the eager.
12448 		 */
12449 		need_send_conn_ind = B_TRUE;
12450 	} else {
12451 		/*
12452 		 * Defer connection on q0 and set deferred
12453 		 * connection bit true
12454 		 */
12455 		tcp->tcp_conn_def_q0 = B_TRUE;
12456 
12457 		/* take tcp out of q0 ... */
12458 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12459 		    tcp->tcp_eager_next_q0;
12460 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12461 		    tcp->tcp_eager_prev_q0;
12462 
12463 		/* ... and place it at the end of q0 */
12464 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12465 		tcp->tcp_eager_next_q0 = listener;
12466 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12467 		listener->tcp_eager_prev_q0 = tcp;
12468 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12469 	}
12470 
12471 	/* we have timed out before */
12472 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12473 		tcp->tcp_syn_rcvd_timeout = 0;
12474 		listener->tcp_syn_rcvd_timeout--;
12475 		if (listener->tcp_syn_defense &&
12476 		    listener->tcp_syn_rcvd_timeout <=
12477 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12478 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12479 		    listener->tcp_last_rcv_lbolt)) {
12480 			/*
12481 			 * Turn off the defense mode if we
12482 			 * believe the SYN attack is over.
12483 			 */
12484 			listener->tcp_syn_defense = B_FALSE;
12485 			if (listener->tcp_ip_addr_cache) {
12486 				kmem_free((void *)listener->tcp_ip_addr_cache,
12487 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12488 				listener->tcp_ip_addr_cache = NULL;
12489 			}
12490 		}
12491 	}
12492 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12493 	if (addr_cache != NULL) {
12494 		/*
12495 		 * We have finished a 3-way handshake with this
12496 		 * remote host. This proves the IP addr is good.
12497 		 * Cache it!
12498 		 */
12499 		addr_cache[IP_ADDR_CACHE_HASH(
12500 		    tcp->tcp_remote)] = tcp->tcp_remote;
12501 	}
12502 	mutex_exit(&listener->tcp_eager_lock);
12503 	if (need_send_conn_ind)
12504 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12505 }
12506 
12507 /*
12508  * Send the newconn notification to ulp. The eager is blown off if the
12509  * notification fails.
12510  */
12511 static void
12512 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12513 {
12514 	if (IPCL_IS_NONSTR(lconnp)) {
12515 		cred_t	*cr;
12516 		pid_t	cpid;
12517 
12518 		cr = msg_getcred(mp, &cpid);
12519 
12520 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12521 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12522 		    lconnp->conn_tcp);
12523 
12524 		/* Keep the message around in case of a fallback to TPI */
12525 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12526 
12527 		/*
12528 		 * Notify the ULP about the newconn. It is guaranteed that no
12529 		 * tcp_accept() call will be made for the eager if the
12530 		 * notification fails, so it's safe to blow it off in that
12531 		 * case.
12532 		 *
12533 		 * The upper handle will be assigned when tcp_accept() is
12534 		 * called.
12535 		 */
12536 		if ((*lconnp->conn_upcalls->su_newconn)
12537 		    (lconnp->conn_upper_handle,
12538 		    (sock_lower_handle_t)econnp,
12539 		    &sock_tcp_downcalls, cr, cpid,
12540 		    &econnp->conn_upcalls) == NULL) {
12541 			/* Failed to allocate a socket */
12542 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12543 			    tcpEstabResets);
12544 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12545 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12546 		}
12547 	} else {
12548 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12549 	}
12550 }
12551 
12552 mblk_t *
12553 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12554     uint_t *ifindexp, ip6_pkt_t *ippp)
12555 {
12556 	ip_pktinfo_t	*pinfo;
12557 	ip6_t		*ip6h;
12558 	uchar_t		*rptr;
12559 	mblk_t		*first_mp = mp;
12560 	boolean_t	mctl_present = B_FALSE;
12561 	uint_t 		ifindex = 0;
12562 	ip6_pkt_t	ipp;
12563 	uint_t		ipvers;
12564 	uint_t		ip_hdr_len;
12565 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12566 
12567 	rptr = mp->b_rptr;
12568 	ASSERT(OK_32PTR(rptr));
12569 	ASSERT(tcp != NULL);
12570 	ipp.ipp_fields = 0;
12571 
12572 	switch DB_TYPE(mp) {
12573 	case M_CTL:
12574 		mp = mp->b_cont;
12575 		if (mp == NULL) {
12576 			freemsg(first_mp);
12577 			return (NULL);
12578 		}
12579 		if (DB_TYPE(mp) != M_DATA) {
12580 			freemsg(first_mp);
12581 			return (NULL);
12582 		}
12583 		mctl_present = B_TRUE;
12584 		break;
12585 	case M_DATA:
12586 		break;
12587 	default:
12588 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12589 		freemsg(mp);
12590 		return (NULL);
12591 	}
12592 	ipvers = IPH_HDR_VERSION(rptr);
12593 	if (ipvers == IPV4_VERSION) {
12594 		if (tcp == NULL) {
12595 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12596 			goto done;
12597 		}
12598 
12599 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12600 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12601 
12602 		/*
12603 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12604 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12605 		 */
12606 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12607 		    mctl_present) {
12608 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12609 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12610 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12611 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12612 				ipp.ipp_fields |= IPPF_IFINDEX;
12613 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12614 				ifindex = pinfo->ip_pkt_ifindex;
12615 			}
12616 			freeb(first_mp);
12617 			mctl_present = B_FALSE;
12618 		}
12619 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12620 	} else {
12621 		ip6h = (ip6_t *)rptr;
12622 
12623 		ASSERT(ipvers == IPV6_VERSION);
12624 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12625 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12626 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12627 
12628 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12629 			uint8_t	nexthdrp;
12630 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12631 
12632 			/* Look for ifindex information */
12633 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12634 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12635 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12636 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12637 					freemsg(first_mp);
12638 					return (NULL);
12639 				}
12640 
12641 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12642 					ASSERT(ip6i->ip6i_ifindex != 0);
12643 					ipp.ipp_fields |= IPPF_IFINDEX;
12644 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12645 					ifindex = ip6i->ip6i_ifindex;
12646 				}
12647 				rptr = (uchar_t *)&ip6i[1];
12648 				mp->b_rptr = rptr;
12649 				if (rptr == mp->b_wptr) {
12650 					mblk_t *mp1;
12651 					mp1 = mp->b_cont;
12652 					freeb(mp);
12653 					mp = mp1;
12654 					rptr = mp->b_rptr;
12655 				}
12656 				if (MBLKL(mp) < IPV6_HDR_LEN +
12657 				    sizeof (tcph_t)) {
12658 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12659 					freemsg(first_mp);
12660 					return (NULL);
12661 				}
12662 				ip6h = (ip6_t *)rptr;
12663 			}
12664 
12665 			/*
12666 			 * Find any potentially interesting extension headers
12667 			 * as well as the length of the IPv6 + extension
12668 			 * headers.
12669 			 */
12670 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12671 			/* Verify if this is a TCP packet */
12672 			if (nexthdrp != IPPROTO_TCP) {
12673 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12674 				freemsg(first_mp);
12675 				return (NULL);
12676 			}
12677 		} else {
12678 			ip_hdr_len = IPV6_HDR_LEN;
12679 		}
12680 	}
12681 
12682 done:
12683 	if (ipversp != NULL)
12684 		*ipversp = ipvers;
12685 	if (ip_hdr_lenp != NULL)
12686 		*ip_hdr_lenp = ip_hdr_len;
12687 	if (ippp != NULL)
12688 		*ippp = ipp;
12689 	if (ifindexp != NULL)
12690 		*ifindexp = ifindex;
12691 	if (mctl_present) {
12692 		freeb(first_mp);
12693 	}
12694 	return (mp);
12695 }
12696 
12697 /*
12698  * Handle M_DATA messages from IP. Its called directly from IP via
12699  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12700  * in this path.
12701  *
12702  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12703  * v4 and v6), we are called through tcp_input() and a M_CTL can
12704  * be present for options but tcp_find_pktinfo() deals with it. We
12705  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12706  *
12707  * The first argument is always the connp/tcp to which the mp belongs.
12708  * There are no exceptions to this rule. The caller has already put
12709  * a reference on this connp/tcp and once tcp_rput_data() returns,
12710  * the squeue will do the refrele.
12711  *
12712  * The TH_SYN for the listener directly go to tcp_conn_request via
12713  * squeue.
12714  *
12715  * sqp: NULL = recursive, sqp != NULL means called from squeue
12716  */
12717 void
12718 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12719 {
12720 	int32_t		bytes_acked;
12721 	int32_t		gap;
12722 	mblk_t		*mp1;
12723 	uint_t		flags;
12724 	uint32_t	new_swnd = 0;
12725 	uchar_t		*iphdr;
12726 	uchar_t		*rptr;
12727 	int32_t		rgap;
12728 	uint32_t	seg_ack;
12729 	int		seg_len;
12730 	uint_t		ip_hdr_len;
12731 	uint32_t	seg_seq;
12732 	tcph_t		*tcph;
12733 	int		urp;
12734 	tcp_opt_t	tcpopt;
12735 	uint_t		ipvers;
12736 	ip6_pkt_t	ipp;
12737 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12738 	uint32_t	cwnd;
12739 	uint32_t	add;
12740 	int		npkt;
12741 	int		mss;
12742 	conn_t		*connp = (conn_t *)arg;
12743 	squeue_t	*sqp = (squeue_t *)arg2;
12744 	tcp_t		*tcp = connp->conn_tcp;
12745 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12746 
12747 	/*
12748 	 * RST from fused tcp loopback peer should trigger an unfuse.
12749 	 */
12750 	if (tcp->tcp_fused) {
12751 		TCP_STAT(tcps, tcp_fusion_aborted);
12752 		tcp_unfuse(tcp);
12753 	}
12754 
12755 	iphdr = mp->b_rptr;
12756 	rptr = mp->b_rptr;
12757 	ASSERT(OK_32PTR(rptr));
12758 
12759 	/*
12760 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12761 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12762 	 * necessary information.
12763 	 */
12764 	if (IPCL_IS_TCP4(connp)) {
12765 		ipvers = IPV4_VERSION;
12766 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12767 	} else {
12768 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12769 		    NULL, &ipp);
12770 		if (mp == NULL) {
12771 			TCP_STAT(tcps, tcp_rput_v6_error);
12772 			return;
12773 		}
12774 		iphdr = mp->b_rptr;
12775 		rptr = mp->b_rptr;
12776 	}
12777 	ASSERT(DB_TYPE(mp) == M_DATA);
12778 	ASSERT(mp->b_next == NULL);
12779 
12780 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12781 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12782 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12783 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12784 	seg_len = (int)(mp->b_wptr - rptr) -
12785 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12786 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12787 		do {
12788 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12789 			    (uintptr_t)INT_MAX);
12790 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12791 		} while ((mp1 = mp1->b_cont) != NULL &&
12792 		    mp1->b_datap->db_type == M_DATA);
12793 	}
12794 
12795 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12796 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12797 		    seg_len, tcph);
12798 		return;
12799 	}
12800 
12801 	if (sqp != NULL) {
12802 		/*
12803 		 * This is the correct place to update tcp_last_recv_time. Note
12804 		 * that it is also updated for tcp structure that belongs to
12805 		 * global and listener queues which do not really need updating.
12806 		 * But that should not cause any harm.  And it is updated for
12807 		 * all kinds of incoming segments, not only for data segments.
12808 		 */
12809 		tcp->tcp_last_recv_time = lbolt;
12810 	}
12811 
12812 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12813 
12814 	BUMP_LOCAL(tcp->tcp_ibsegs);
12815 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12816 
12817 	if ((flags & TH_URG) && sqp != NULL) {
12818 		/*
12819 		 * TCP can't handle urgent pointers that arrive before
12820 		 * the connection has been accept()ed since it can't
12821 		 * buffer OOB data.  Discard segment if this happens.
12822 		 *
12823 		 * We can't just rely on a non-null tcp_listener to indicate
12824 		 * that the accept() has completed since unlinking of the
12825 		 * eager and completion of the accept are not atomic.
12826 		 * tcp_detached, when it is not set (B_FALSE) indicates
12827 		 * that the accept() has completed.
12828 		 *
12829 		 * Nor can it reassemble urgent pointers, so discard
12830 		 * if it's not the next segment expected.
12831 		 *
12832 		 * Otherwise, collapse chain into one mblk (discard if
12833 		 * that fails).  This makes sure the headers, retransmitted
12834 		 * data, and new data all are in the same mblk.
12835 		 */
12836 		ASSERT(mp != NULL);
12837 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12838 			freemsg(mp);
12839 			return;
12840 		}
12841 		/* Update pointers into message */
12842 		iphdr = rptr = mp->b_rptr;
12843 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12844 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12845 			/*
12846 			 * Since we can't handle any data with this urgent
12847 			 * pointer that is out of sequence, we expunge
12848 			 * the data.  This allows us to still register
12849 			 * the urgent mark and generate the M_PCSIG,
12850 			 * which we can do.
12851 			 */
12852 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12853 			seg_len = 0;
12854 		}
12855 	}
12856 
12857 	switch (tcp->tcp_state) {
12858 	case TCPS_SYN_SENT:
12859 		if (flags & TH_ACK) {
12860 			/*
12861 			 * Note that our stack cannot send data before a
12862 			 * connection is established, therefore the
12863 			 * following check is valid.  Otherwise, it has
12864 			 * to be changed.
12865 			 */
12866 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12867 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12868 				freemsg(mp);
12869 				if (flags & TH_RST)
12870 					return;
12871 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12872 				    tcp, seg_ack, 0, TH_RST);
12873 				return;
12874 			}
12875 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12876 		}
12877 		if (flags & TH_RST) {
12878 			freemsg(mp);
12879 			if (flags & TH_ACK)
12880 				(void) tcp_clean_death(tcp,
12881 				    ECONNREFUSED, 13);
12882 			return;
12883 		}
12884 		if (!(flags & TH_SYN)) {
12885 			freemsg(mp);
12886 			return;
12887 		}
12888 
12889 		/* Process all TCP options. */
12890 		tcp_process_options(tcp, tcph);
12891 		/*
12892 		 * The following changes our rwnd to be a multiple of the
12893 		 * MIN(peer MSS, our MSS) for performance reason.
12894 		 */
12895 		(void) tcp_rwnd_set(tcp,
12896 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
12897 
12898 		/* Is the other end ECN capable? */
12899 		if (tcp->tcp_ecn_ok) {
12900 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12901 				tcp->tcp_ecn_ok = B_FALSE;
12902 			}
12903 		}
12904 		/*
12905 		 * Clear ECN flags because it may interfere with later
12906 		 * processing.
12907 		 */
12908 		flags &= ~(TH_ECE|TH_CWR);
12909 
12910 		tcp->tcp_irs = seg_seq;
12911 		tcp->tcp_rack = seg_seq;
12912 		tcp->tcp_rnxt = seg_seq + 1;
12913 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12914 		if (!TCP_IS_DETACHED(tcp)) {
12915 			/* Allocate room for SACK options if needed. */
12916 			if (tcp->tcp_snd_sack_ok) {
12917 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12918 				    tcp->tcp_hdr_len +
12919 				    TCPOPT_MAX_SACK_LEN +
12920 				    (tcp->tcp_loopback ? 0 :
12921 				    tcps->tcps_wroff_xtra));
12922 			} else {
12923 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12924 				    tcp->tcp_hdr_len +
12925 				    (tcp->tcp_loopback ? 0 :
12926 				    tcps->tcps_wroff_xtra));
12927 			}
12928 		}
12929 		if (flags & TH_ACK) {
12930 			/*
12931 			 * If we can't get the confirmation upstream, pretend
12932 			 * we didn't even see this one.
12933 			 *
12934 			 * XXX: how can we pretend we didn't see it if we
12935 			 * have updated rnxt et. al.
12936 			 *
12937 			 * For loopback we defer sending up the T_CONN_CON
12938 			 * until after some checks below.
12939 			 */
12940 			mp1 = NULL;
12941 			/*
12942 			 * tcp_sendmsg() checks tcp_state without entering
12943 			 * the squeue so tcp_state should be updated before
12944 			 * sending up connection confirmation
12945 			 */
12946 			tcp->tcp_state = TCPS_ESTABLISHED;
12947 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12948 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12949 				tcp->tcp_state = TCPS_SYN_SENT;
12950 				freemsg(mp);
12951 				return;
12952 			}
12953 			/* SYN was acked - making progress */
12954 			if (tcp->tcp_ipversion == IPV6_VERSION)
12955 				tcp->tcp_ip_forward_progress = B_TRUE;
12956 
12957 			/* One for the SYN */
12958 			tcp->tcp_suna = tcp->tcp_iss + 1;
12959 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12960 
12961 			/*
12962 			 * If SYN was retransmitted, need to reset all
12963 			 * retransmission info.  This is because this
12964 			 * segment will be treated as a dup ACK.
12965 			 */
12966 			if (tcp->tcp_rexmit) {
12967 				tcp->tcp_rexmit = B_FALSE;
12968 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12969 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12970 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12971 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12972 				tcp->tcp_ms_we_have_waited = 0;
12973 
12974 				/*
12975 				 * Set tcp_cwnd back to 1 MSS, per
12976 				 * recommendation from
12977 				 * draft-floyd-incr-init-win-01.txt,
12978 				 * Increasing TCP's Initial Window.
12979 				 */
12980 				tcp->tcp_cwnd = tcp->tcp_mss;
12981 			}
12982 
12983 			tcp->tcp_swl1 = seg_seq;
12984 			tcp->tcp_swl2 = seg_ack;
12985 
12986 			new_swnd = BE16_TO_U16(tcph->th_win);
12987 			tcp->tcp_swnd = new_swnd;
12988 			if (new_swnd > tcp->tcp_max_swnd)
12989 				tcp->tcp_max_swnd = new_swnd;
12990 
12991 			/*
12992 			 * Always send the three-way handshake ack immediately
12993 			 * in order to make the connection complete as soon as
12994 			 * possible on the accepting host.
12995 			 */
12996 			flags |= TH_ACK_NEEDED;
12997 
12998 			/*
12999 			 * Special case for loopback.  At this point we have
13000 			 * received SYN-ACK from the remote endpoint.  In
13001 			 * order to ensure that both endpoints reach the
13002 			 * fused state prior to any data exchange, the final
13003 			 * ACK needs to be sent before we indicate T_CONN_CON
13004 			 * to the module upstream.
13005 			 */
13006 			if (tcp->tcp_loopback) {
13007 				mblk_t *ack_mp;
13008 
13009 				ASSERT(!tcp->tcp_unfusable);
13010 				ASSERT(mp1 != NULL);
13011 				/*
13012 				 * For loopback, we always get a pure SYN-ACK
13013 				 * and only need to send back the final ACK
13014 				 * with no data (this is because the other
13015 				 * tcp is ours and we don't do T/TCP).  This
13016 				 * final ACK triggers the passive side to
13017 				 * perform fusion in ESTABLISHED state.
13018 				 */
13019 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13020 					if (tcp->tcp_ack_tid != 0) {
13021 						(void) TCP_TIMER_CANCEL(tcp,
13022 						    tcp->tcp_ack_tid);
13023 						tcp->tcp_ack_tid = 0;
13024 					}
13025 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13026 					BUMP_LOCAL(tcp->tcp_obsegs);
13027 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13028 
13029 					if (!IPCL_IS_NONSTR(connp)) {
13030 						/* Send up T_CONN_CON */
13031 						putnext(tcp->tcp_rq, mp1);
13032 					} else {
13033 						cred_t	*cr;
13034 						pid_t	cpid;
13035 
13036 						cr = msg_getcred(mp1, &cpid);
13037 						(*connp->conn_upcalls->
13038 						    su_connected)
13039 						    (connp->conn_upper_handle,
13040 						    tcp->tcp_connid, cr, cpid);
13041 						freemsg(mp1);
13042 					}
13043 
13044 					freemsg(mp);
13045 					return;
13046 				}
13047 				/*
13048 				 * Forget fusion; we need to handle more
13049 				 * complex cases below.  Send the deferred
13050 				 * T_CONN_CON message upstream and proceed
13051 				 * as usual.  Mark this tcp as not capable
13052 				 * of fusion.
13053 				 */
13054 				TCP_STAT(tcps, tcp_fusion_unfusable);
13055 				tcp->tcp_unfusable = B_TRUE;
13056 				if (!IPCL_IS_NONSTR(connp)) {
13057 					putnext(tcp->tcp_rq, mp1);
13058 				} else {
13059 					cred_t	*cr;
13060 					pid_t	cpid;
13061 
13062 					cr = msg_getcred(mp1, &cpid);
13063 					(*connp->conn_upcalls->su_connected)
13064 					    (connp->conn_upper_handle,
13065 					    tcp->tcp_connid, cr, cpid);
13066 					freemsg(mp1);
13067 				}
13068 			}
13069 
13070 			/*
13071 			 * Check to see if there is data to be sent.  If
13072 			 * yes, set the transmit flag.  Then check to see
13073 			 * if received data processing needs to be done.
13074 			 * If not, go straight to xmit_check.  This short
13075 			 * cut is OK as we don't support T/TCP.
13076 			 */
13077 			if (tcp->tcp_unsent)
13078 				flags |= TH_XMIT_NEEDED;
13079 
13080 			if (seg_len == 0 && !(flags & TH_URG)) {
13081 				freemsg(mp);
13082 				goto xmit_check;
13083 			}
13084 
13085 			flags &= ~TH_SYN;
13086 			seg_seq++;
13087 			break;
13088 		}
13089 		tcp->tcp_state = TCPS_SYN_RCVD;
13090 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13091 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13092 		if (mp1) {
13093 			/*
13094 			 * See comment in tcp_conn_request() for why we use
13095 			 * the open() time pid here.
13096 			 */
13097 			DB_CPID(mp1) = tcp->tcp_cpid;
13098 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13099 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13100 		}
13101 		freemsg(mp);
13102 		return;
13103 	case TCPS_SYN_RCVD:
13104 		if (flags & TH_ACK) {
13105 			/*
13106 			 * In this state, a SYN|ACK packet is either bogus
13107 			 * because the other side must be ACKing our SYN which
13108 			 * indicates it has seen the ACK for their SYN and
13109 			 * shouldn't retransmit it or we're crossing SYNs
13110 			 * on active open.
13111 			 */
13112 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13113 				freemsg(mp);
13114 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13115 				    tcp, seg_ack, 0, TH_RST);
13116 				return;
13117 			}
13118 			/*
13119 			 * NOTE: RFC 793 pg. 72 says this should be
13120 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13121 			 * but that would mean we have an ack that ignored
13122 			 * our SYN.
13123 			 */
13124 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13125 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13126 				freemsg(mp);
13127 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13128 				    tcp, seg_ack, 0, TH_RST);
13129 				return;
13130 			}
13131 		}
13132 		break;
13133 	case TCPS_LISTEN:
13134 		/*
13135 		 * Only a TLI listener can come through this path when a
13136 		 * acceptor is going back to be a listener and a packet
13137 		 * for the acceptor hits the classifier. For a socket
13138 		 * listener, this can never happen because a listener
13139 		 * can never accept connection on itself and hence a
13140 		 * socket acceptor can not go back to being a listener.
13141 		 */
13142 		ASSERT(!TCP_IS_SOCKET(tcp));
13143 		/*FALLTHRU*/
13144 	case TCPS_CLOSED:
13145 	case TCPS_BOUND: {
13146 		conn_t	*new_connp;
13147 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13148 
13149 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13150 		if (new_connp != NULL) {
13151 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13152 			return;
13153 		}
13154 		/* We failed to classify. For now just drop the packet */
13155 		freemsg(mp);
13156 		return;
13157 	}
13158 	case TCPS_IDLE:
13159 		/*
13160 		 * Handle the case where the tcp_clean_death() has happened
13161 		 * on a connection (application hasn't closed yet) but a packet
13162 		 * was already queued on squeue before tcp_clean_death()
13163 		 * was processed. Calling tcp_clean_death() twice on same
13164 		 * connection can result in weird behaviour.
13165 		 */
13166 		freemsg(mp);
13167 		return;
13168 	default:
13169 		break;
13170 	}
13171 
13172 	/*
13173 	 * Already on the correct queue/perimeter.
13174 	 * If this is a detached connection and not an eager
13175 	 * connection hanging off a listener then new data
13176 	 * (past the FIN) will cause a reset.
13177 	 * We do a special check here where it
13178 	 * is out of the main line, rather than check
13179 	 * if we are detached every time we see new
13180 	 * data down below.
13181 	 */
13182 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13183 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13184 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13185 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13186 
13187 		freemsg(mp);
13188 		/*
13189 		 * This could be an SSL closure alert. We're detached so just
13190 		 * acknowledge it this last time.
13191 		 */
13192 		if (tcp->tcp_kssl_ctx != NULL) {
13193 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13194 			tcp->tcp_kssl_ctx = NULL;
13195 
13196 			tcp->tcp_rnxt += seg_len;
13197 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13198 			flags |= TH_ACK_NEEDED;
13199 			goto ack_check;
13200 		}
13201 
13202 		tcp_xmit_ctl("new data when detached", tcp,
13203 		    tcp->tcp_snxt, 0, TH_RST);
13204 		(void) tcp_clean_death(tcp, EPROTO, 12);
13205 		return;
13206 	}
13207 
13208 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13209 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13210 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13211 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13212 
13213 	if (tcp->tcp_snd_ts_ok) {
13214 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13215 			/*
13216 			 * This segment is not acceptable.
13217 			 * Drop it and send back an ACK.
13218 			 */
13219 			freemsg(mp);
13220 			flags |= TH_ACK_NEEDED;
13221 			goto ack_check;
13222 		}
13223 	} else if (tcp->tcp_snd_sack_ok) {
13224 		ASSERT(tcp->tcp_sack_info != NULL);
13225 		tcpopt.tcp = tcp;
13226 		/*
13227 		 * SACK info in already updated in tcp_parse_options.  Ignore
13228 		 * all other TCP options...
13229 		 */
13230 		(void) tcp_parse_options(tcph, &tcpopt);
13231 	}
13232 try_again:;
13233 	mss = tcp->tcp_mss;
13234 	gap = seg_seq - tcp->tcp_rnxt;
13235 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13236 	/*
13237 	 * gap is the amount of sequence space between what we expect to see
13238 	 * and what we got for seg_seq.  A positive value for gap means
13239 	 * something got lost.  A negative value means we got some old stuff.
13240 	 */
13241 	if (gap < 0) {
13242 		/* Old stuff present.  Is the SYN in there? */
13243 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13244 		    (seg_len != 0)) {
13245 			flags &= ~TH_SYN;
13246 			seg_seq++;
13247 			urp--;
13248 			/* Recompute the gaps after noting the SYN. */
13249 			goto try_again;
13250 		}
13251 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13252 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13253 		    (seg_len > -gap ? -gap : seg_len));
13254 		/* Remove the old stuff from seg_len. */
13255 		seg_len += gap;
13256 		/*
13257 		 * Anything left?
13258 		 * Make sure to check for unack'd FIN when rest of data
13259 		 * has been previously ack'd.
13260 		 */
13261 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13262 			/*
13263 			 * Resets are only valid if they lie within our offered
13264 			 * window.  If the RST bit is set, we just ignore this
13265 			 * segment.
13266 			 */
13267 			if (flags & TH_RST) {
13268 				freemsg(mp);
13269 				return;
13270 			}
13271 
13272 			/*
13273 			 * The arriving of dup data packets indicate that we
13274 			 * may have postponed an ack for too long, or the other
13275 			 * side's RTT estimate is out of shape. Start acking
13276 			 * more often.
13277 			 */
13278 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13279 			    tcp->tcp_rack_cnt >= 1 &&
13280 			    tcp->tcp_rack_abs_max > 2) {
13281 				tcp->tcp_rack_abs_max--;
13282 			}
13283 			tcp->tcp_rack_cur_max = 1;
13284 
13285 			/*
13286 			 * This segment is "unacceptable".  None of its
13287 			 * sequence space lies within our advertized window.
13288 			 *
13289 			 * Adjust seg_len to the original value for tracing.
13290 			 */
13291 			seg_len -= gap;
13292 			if (tcp->tcp_debug) {
13293 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13294 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13295 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13296 				    "seg_len %d, rnxt %u, snxt %u, %s",
13297 				    gap, rgap, flags, seg_seq, seg_ack,
13298 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13299 				    tcp_display(tcp, NULL,
13300 				    DISP_ADDR_AND_PORT));
13301 			}
13302 
13303 			/*
13304 			 * Arrange to send an ACK in response to the
13305 			 * unacceptable segment per RFC 793 page 69. There
13306 			 * is only one small difference between ours and the
13307 			 * acceptability test in the RFC - we accept ACK-only
13308 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13309 			 * will be generated.
13310 			 *
13311 			 * Note that we have to ACK an ACK-only packet at least
13312 			 * for stacks that send 0-length keep-alives with
13313 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13314 			 * section 4.2.3.6. As long as we don't ever generate
13315 			 * an unacceptable packet in response to an incoming
13316 			 * packet that is unacceptable, it should not cause
13317 			 * "ACK wars".
13318 			 */
13319 			flags |=  TH_ACK_NEEDED;
13320 
13321 			/*
13322 			 * Continue processing this segment in order to use the
13323 			 * ACK information it contains, but skip all other
13324 			 * sequence-number processing.	Processing the ACK
13325 			 * information is necessary in order to
13326 			 * re-synchronize connections that may have lost
13327 			 * synchronization.
13328 			 *
13329 			 * We clear seg_len and flag fields related to
13330 			 * sequence number processing as they are not
13331 			 * to be trusted for an unacceptable segment.
13332 			 */
13333 			seg_len = 0;
13334 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13335 			goto process_ack;
13336 		}
13337 
13338 		/* Fix seg_seq, and chew the gap off the front. */
13339 		seg_seq = tcp->tcp_rnxt;
13340 		urp += gap;
13341 		do {
13342 			mblk_t	*mp2;
13343 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13344 			    (uintptr_t)UINT_MAX);
13345 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13346 			if (gap > 0) {
13347 				mp->b_rptr = mp->b_wptr - gap;
13348 				break;
13349 			}
13350 			mp2 = mp;
13351 			mp = mp->b_cont;
13352 			freeb(mp2);
13353 		} while (gap < 0);
13354 		/*
13355 		 * If the urgent data has already been acknowledged, we
13356 		 * should ignore TH_URG below
13357 		 */
13358 		if (urp < 0)
13359 			flags &= ~TH_URG;
13360 	}
13361 	/*
13362 	 * rgap is the amount of stuff received out of window.  A negative
13363 	 * value is the amount out of window.
13364 	 */
13365 	if (rgap < 0) {
13366 		mblk_t	*mp2;
13367 
13368 		if (tcp->tcp_rwnd == 0) {
13369 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13370 		} else {
13371 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13372 			UPDATE_MIB(&tcps->tcps_mib,
13373 			    tcpInDataPastWinBytes, -rgap);
13374 		}
13375 
13376 		/*
13377 		 * seg_len does not include the FIN, so if more than
13378 		 * just the FIN is out of window, we act like we don't
13379 		 * see it.  (If just the FIN is out of window, rgap
13380 		 * will be zero and we will go ahead and acknowledge
13381 		 * the FIN.)
13382 		 */
13383 		flags &= ~TH_FIN;
13384 
13385 		/* Fix seg_len and make sure there is something left. */
13386 		seg_len += rgap;
13387 		if (seg_len <= 0) {
13388 			/*
13389 			 * Resets are only valid if they lie within our offered
13390 			 * window.  If the RST bit is set, we just ignore this
13391 			 * segment.
13392 			 */
13393 			if (flags & TH_RST) {
13394 				freemsg(mp);
13395 				return;
13396 			}
13397 
13398 			/* Per RFC 793, we need to send back an ACK. */
13399 			flags |= TH_ACK_NEEDED;
13400 
13401 			/*
13402 			 * Send SIGURG as soon as possible i.e. even
13403 			 * if the TH_URG was delivered in a window probe
13404 			 * packet (which will be unacceptable).
13405 			 *
13406 			 * We generate a signal if none has been generated
13407 			 * for this connection or if this is a new urgent
13408 			 * byte. Also send a zero-length "unmarked" message
13409 			 * to inform SIOCATMARK that this is not the mark.
13410 			 *
13411 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13412 			 * is sent up. This plus the check for old data
13413 			 * (gap >= 0) handles the wraparound of the sequence
13414 			 * number space without having to always track the
13415 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13416 			 * this max in its rcv_up variable).
13417 			 *
13418 			 * This prevents duplicate SIGURGS due to a "late"
13419 			 * zero-window probe when the T_EXDATA_IND has already
13420 			 * been sent up.
13421 			 */
13422 			if ((flags & TH_URG) &&
13423 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13424 			    tcp->tcp_urp_last))) {
13425 				if (IPCL_IS_NONSTR(connp)) {
13426 					if (!TCP_IS_DETACHED(tcp)) {
13427 						(*connp->conn_upcalls->
13428 						    su_signal_oob)
13429 						    (connp->conn_upper_handle,
13430 						    urp);
13431 					}
13432 				} else {
13433 					mp1 = allocb(0, BPRI_MED);
13434 					if (mp1 == NULL) {
13435 						freemsg(mp);
13436 						return;
13437 					}
13438 					if (!TCP_IS_DETACHED(tcp) &&
13439 					    !putnextctl1(tcp->tcp_rq,
13440 					    M_PCSIG, SIGURG)) {
13441 						/* Try again on the rexmit. */
13442 						freemsg(mp1);
13443 						freemsg(mp);
13444 						return;
13445 					}
13446 					/*
13447 					 * If the next byte would be the mark
13448 					 * then mark with MARKNEXT else mark
13449 					 * with NOTMARKNEXT.
13450 					 */
13451 					if (gap == 0 && urp == 0)
13452 						mp1->b_flag |= MSGMARKNEXT;
13453 					else
13454 						mp1->b_flag |= MSGNOTMARKNEXT;
13455 					freemsg(tcp->tcp_urp_mark_mp);
13456 					tcp->tcp_urp_mark_mp = mp1;
13457 					flags |= TH_SEND_URP_MARK;
13458 				}
13459 				tcp->tcp_urp_last_valid = B_TRUE;
13460 				tcp->tcp_urp_last = urp + seg_seq;
13461 			}
13462 			/*
13463 			 * If this is a zero window probe, continue to
13464 			 * process the ACK part.  But we need to set seg_len
13465 			 * to 0 to avoid data processing.  Otherwise just
13466 			 * drop the segment and send back an ACK.
13467 			 */
13468 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13469 				flags &= ~(TH_SYN | TH_URG);
13470 				seg_len = 0;
13471 				goto process_ack;
13472 			} else {
13473 				freemsg(mp);
13474 				goto ack_check;
13475 			}
13476 		}
13477 		/* Pitch out of window stuff off the end. */
13478 		rgap = seg_len;
13479 		mp2 = mp;
13480 		do {
13481 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13482 			    (uintptr_t)INT_MAX);
13483 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13484 			if (rgap < 0) {
13485 				mp2->b_wptr += rgap;
13486 				if ((mp1 = mp2->b_cont) != NULL) {
13487 					mp2->b_cont = NULL;
13488 					freemsg(mp1);
13489 				}
13490 				break;
13491 			}
13492 		} while ((mp2 = mp2->b_cont) != NULL);
13493 	}
13494 ok:;
13495 	/*
13496 	 * TCP should check ECN info for segments inside the window only.
13497 	 * Therefore the check should be done here.
13498 	 */
13499 	if (tcp->tcp_ecn_ok) {
13500 		if (flags & TH_CWR) {
13501 			tcp->tcp_ecn_echo_on = B_FALSE;
13502 		}
13503 		/*
13504 		 * Note that both ECN_CE and CWR can be set in the
13505 		 * same segment.  In this case, we once again turn
13506 		 * on ECN_ECHO.
13507 		 */
13508 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13509 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13510 
13511 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13512 				tcp->tcp_ecn_echo_on = B_TRUE;
13513 			}
13514 		} else {
13515 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13516 
13517 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13518 			    htonl(IPH_ECN_CE << 20)) {
13519 				tcp->tcp_ecn_echo_on = B_TRUE;
13520 			}
13521 		}
13522 	}
13523 
13524 	/*
13525 	 * Check whether we can update tcp_ts_recent.  This test is
13526 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13527 	 * Extensions for High Performance: An Update", Internet Draft.
13528 	 */
13529 	if (tcp->tcp_snd_ts_ok &&
13530 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13531 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13532 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13533 		tcp->tcp_last_rcv_lbolt = lbolt64;
13534 	}
13535 
13536 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13537 		/*
13538 		 * FIN in an out of order segment.  We record this in
13539 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13540 		 * Clear the FIN so that any check on FIN flag will fail.
13541 		 * Remember that FIN also counts in the sequence number
13542 		 * space.  So we need to ack out of order FIN only segments.
13543 		 */
13544 		if (flags & TH_FIN) {
13545 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13546 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13547 			flags &= ~TH_FIN;
13548 			flags |= TH_ACK_NEEDED;
13549 		}
13550 		if (seg_len > 0) {
13551 			/* Fill in the SACK blk list. */
13552 			if (tcp->tcp_snd_sack_ok) {
13553 				ASSERT(tcp->tcp_sack_info != NULL);
13554 				tcp_sack_insert(tcp->tcp_sack_list,
13555 				    seg_seq, seg_seq + seg_len,
13556 				    &(tcp->tcp_num_sack_blk));
13557 			}
13558 
13559 			/*
13560 			 * Attempt reassembly and see if we have something
13561 			 * ready to go.
13562 			 */
13563 			mp = tcp_reass(tcp, mp, seg_seq);
13564 			/* Always ack out of order packets */
13565 			flags |= TH_ACK_NEEDED | TH_PUSH;
13566 			if (mp) {
13567 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13568 				    (uintptr_t)INT_MAX);
13569 				seg_len = mp->b_cont ? msgdsize(mp) :
13570 				    (int)(mp->b_wptr - mp->b_rptr);
13571 				seg_seq = tcp->tcp_rnxt;
13572 				/*
13573 				 * A gap is filled and the seq num and len
13574 				 * of the gap match that of a previously
13575 				 * received FIN, put the FIN flag back in.
13576 				 */
13577 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13578 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13579 					flags |= TH_FIN;
13580 					tcp->tcp_valid_bits &=
13581 					    ~TCP_OFO_FIN_VALID;
13582 				}
13583 			} else {
13584 				/*
13585 				 * Keep going even with NULL mp.
13586 				 * There may be a useful ACK or something else
13587 				 * we don't want to miss.
13588 				 *
13589 				 * But TCP should not perform fast retransmit
13590 				 * because of the ack number.  TCP uses
13591 				 * seg_len == 0 to determine if it is a pure
13592 				 * ACK.  And this is not a pure ACK.
13593 				 */
13594 				seg_len = 0;
13595 				ofo_seg = B_TRUE;
13596 			}
13597 		}
13598 	} else if (seg_len > 0) {
13599 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13600 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13601 		/*
13602 		 * If an out of order FIN was received before, and the seq
13603 		 * num and len of the new segment match that of the FIN,
13604 		 * put the FIN flag back in.
13605 		 */
13606 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13607 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13608 			flags |= TH_FIN;
13609 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13610 		}
13611 	}
13612 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13613 	if (flags & TH_RST) {
13614 		freemsg(mp);
13615 		switch (tcp->tcp_state) {
13616 		case TCPS_SYN_RCVD:
13617 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13618 			break;
13619 		case TCPS_ESTABLISHED:
13620 		case TCPS_FIN_WAIT_1:
13621 		case TCPS_FIN_WAIT_2:
13622 		case TCPS_CLOSE_WAIT:
13623 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13624 			break;
13625 		case TCPS_CLOSING:
13626 		case TCPS_LAST_ACK:
13627 			(void) tcp_clean_death(tcp, 0, 16);
13628 			break;
13629 		default:
13630 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13631 			(void) tcp_clean_death(tcp, ENXIO, 17);
13632 			break;
13633 		}
13634 		return;
13635 	}
13636 	if (flags & TH_SYN) {
13637 		/*
13638 		 * See RFC 793, Page 71
13639 		 *
13640 		 * The seq number must be in the window as it should
13641 		 * be "fixed" above.  If it is outside window, it should
13642 		 * be already rejected.  Note that we allow seg_seq to be
13643 		 * rnxt + rwnd because we want to accept 0 window probe.
13644 		 */
13645 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13646 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13647 		freemsg(mp);
13648 		/*
13649 		 * If the ACK flag is not set, just use our snxt as the
13650 		 * seq number of the RST segment.
13651 		 */
13652 		if (!(flags & TH_ACK)) {
13653 			seg_ack = tcp->tcp_snxt;
13654 		}
13655 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13656 		    TH_RST|TH_ACK);
13657 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13658 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13659 		return;
13660 	}
13661 	/*
13662 	 * urp could be -1 when the urp field in the packet is 0
13663 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13664 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13665 	 */
13666 	if (flags & TH_URG && urp >= 0) {
13667 		if (!tcp->tcp_urp_last_valid ||
13668 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13669 			/*
13670 			 * Non-STREAMS sockets handle the urgent data a litte
13671 			 * differently from STREAMS based sockets. There is no
13672 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
13673 			 * flags to keep SIOCATMARK happy. Instead a
13674 			 * su_signal_oob upcall is made to update the mark.
13675 			 * Neither is a T_EXDATA_IND mblk needed to be
13676 			 * prepended to the urgent data. The urgent data is
13677 			 * delivered using the su_recv upcall, where we set
13678 			 * the MSG_OOB flag to indicate that it is urg data.
13679 			 *
13680 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
13681 			 * are used by non-STREAMS sockets.
13682 			 */
13683 			if (IPCL_IS_NONSTR(connp)) {
13684 				if (!TCP_IS_DETACHED(tcp)) {
13685 					(*connp->conn_upcalls->su_signal_oob)
13686 					    (connp->conn_upper_handle, urp);
13687 				}
13688 			} else {
13689 				/*
13690 				 * If we haven't generated the signal yet for
13691 				 * this urgent pointer value, do it now.  Also,
13692 				 * send up a zero-length M_DATA indicating
13693 				 * whether or not this is the mark. The latter
13694 				 * is not needed when a T_EXDATA_IND is sent up.
13695 				 * However, if there are allocation failures
13696 				 * this code relies on the sender retransmitting
13697 				 * and the socket code for determining the mark
13698 				 * should not block waiting for the peer to
13699 				 * transmit. Thus, for simplicity we always
13700 				 * send up the mark indication.
13701 				 */
13702 				mp1 = allocb(0, BPRI_MED);
13703 				if (mp1 == NULL) {
13704 					freemsg(mp);
13705 					return;
13706 				}
13707 				if (!TCP_IS_DETACHED(tcp) &&
13708 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13709 				    SIGURG)) {
13710 					/* Try again on the rexmit. */
13711 					freemsg(mp1);
13712 					freemsg(mp);
13713 					return;
13714 				}
13715 				/*
13716 				 * Mark with NOTMARKNEXT for now.
13717 				 * The code below will change this to MARKNEXT
13718 				 * if we are at the mark.
13719 				 *
13720 				 * If there are allocation failures (e.g. in
13721 				 * dupmsg below) the next time tcp_rput_data
13722 				 * sees the urgent segment it will send up the
13723 				 * MSGMARKNEXT message.
13724 				 */
13725 				mp1->b_flag |= MSGNOTMARKNEXT;
13726 				freemsg(tcp->tcp_urp_mark_mp);
13727 				tcp->tcp_urp_mark_mp = mp1;
13728 				flags |= TH_SEND_URP_MARK;
13729 #ifdef DEBUG
13730 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13731 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13732 				    "last %x, %s",
13733 				    seg_seq, urp, tcp->tcp_urp_last,
13734 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13735 #endif /* DEBUG */
13736 			}
13737 			tcp->tcp_urp_last_valid = B_TRUE;
13738 			tcp->tcp_urp_last = urp + seg_seq;
13739 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13740 			/*
13741 			 * An allocation failure prevented the previous
13742 			 * tcp_rput_data from sending up the allocated
13743 			 * MSG*MARKNEXT message - send it up this time
13744 			 * around.
13745 			 */
13746 			flags |= TH_SEND_URP_MARK;
13747 		}
13748 
13749 		/*
13750 		 * If the urgent byte is in this segment, make sure that it is
13751 		 * all by itself.  This makes it much easier to deal with the
13752 		 * possibility of an allocation failure on the T_exdata_ind.
13753 		 * Note that seg_len is the number of bytes in the segment, and
13754 		 * urp is the offset into the segment of the urgent byte.
13755 		 * urp < seg_len means that the urgent byte is in this segment.
13756 		 */
13757 		if (urp < seg_len) {
13758 			if (seg_len != 1) {
13759 				uint32_t  tmp_rnxt;
13760 				/*
13761 				 * Break it up and feed it back in.
13762 				 * Re-attach the IP header.
13763 				 */
13764 				mp->b_rptr = iphdr;
13765 				if (urp > 0) {
13766 					/*
13767 					 * There is stuff before the urgent
13768 					 * byte.
13769 					 */
13770 					mp1 = dupmsg(mp);
13771 					if (!mp1) {
13772 						/*
13773 						 * Trim from urgent byte on.
13774 						 * The rest will come back.
13775 						 */
13776 						(void) adjmsg(mp,
13777 						    urp - seg_len);
13778 						tcp_rput_data(connp,
13779 						    mp, NULL);
13780 						return;
13781 					}
13782 					(void) adjmsg(mp1, urp - seg_len);
13783 					/* Feed this piece back in. */
13784 					tmp_rnxt = tcp->tcp_rnxt;
13785 					tcp_rput_data(connp, mp1, NULL);
13786 					/*
13787 					 * If the data passed back in was not
13788 					 * processed (ie: bad ACK) sending
13789 					 * the remainder back in will cause a
13790 					 * loop. In this case, drop the
13791 					 * packet and let the sender try
13792 					 * sending a good packet.
13793 					 */
13794 					if (tmp_rnxt == tcp->tcp_rnxt) {
13795 						freemsg(mp);
13796 						return;
13797 					}
13798 				}
13799 				if (urp != seg_len - 1) {
13800 					uint32_t  tmp_rnxt;
13801 					/*
13802 					 * There is stuff after the urgent
13803 					 * byte.
13804 					 */
13805 					mp1 = dupmsg(mp);
13806 					if (!mp1) {
13807 						/*
13808 						 * Trim everything beyond the
13809 						 * urgent byte.  The rest will
13810 						 * come back.
13811 						 */
13812 						(void) adjmsg(mp,
13813 						    urp + 1 - seg_len);
13814 						tcp_rput_data(connp,
13815 						    mp, NULL);
13816 						return;
13817 					}
13818 					(void) adjmsg(mp1, urp + 1 - seg_len);
13819 					tmp_rnxt = tcp->tcp_rnxt;
13820 					tcp_rput_data(connp, mp1, NULL);
13821 					/*
13822 					 * If the data passed back in was not
13823 					 * processed (ie: bad ACK) sending
13824 					 * the remainder back in will cause a
13825 					 * loop. In this case, drop the
13826 					 * packet and let the sender try
13827 					 * sending a good packet.
13828 					 */
13829 					if (tmp_rnxt == tcp->tcp_rnxt) {
13830 						freemsg(mp);
13831 						return;
13832 					}
13833 				}
13834 				tcp_rput_data(connp, mp, NULL);
13835 				return;
13836 			}
13837 			/*
13838 			 * This segment contains only the urgent byte.  We
13839 			 * have to allocate the T_exdata_ind, if we can.
13840 			 */
13841 			if (IPCL_IS_NONSTR(connp)) {
13842 				int error;
13843 
13844 				(*connp->conn_upcalls->su_recv)
13845 				    (connp->conn_upper_handle, mp, seg_len,
13846 				    MSG_OOB, &error, NULL);
13847 				/*
13848 				 * We should never be in middle of a
13849 				 * fallback, the squeue guarantees that.
13850 				 */
13851 				ASSERT(error != EOPNOTSUPP);
13852 				mp = NULL;
13853 				goto update_ack;
13854 			} else if (!tcp->tcp_urp_mp) {
13855 				struct T_exdata_ind *tei;
13856 				mp1 = allocb(sizeof (struct T_exdata_ind),
13857 				    BPRI_MED);
13858 				if (!mp1) {
13859 					/*
13860 					 * Sigh... It'll be back.
13861 					 * Generate any MSG*MARK message now.
13862 					 */
13863 					freemsg(mp);
13864 					seg_len = 0;
13865 					if (flags & TH_SEND_URP_MARK) {
13866 
13867 
13868 						ASSERT(tcp->tcp_urp_mark_mp);
13869 						tcp->tcp_urp_mark_mp->b_flag &=
13870 						    ~MSGNOTMARKNEXT;
13871 						tcp->tcp_urp_mark_mp->b_flag |=
13872 						    MSGMARKNEXT;
13873 					}
13874 					goto ack_check;
13875 				}
13876 				mp1->b_datap->db_type = M_PROTO;
13877 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13878 				tei->PRIM_type = T_EXDATA_IND;
13879 				tei->MORE_flag = 0;
13880 				mp1->b_wptr = (uchar_t *)&tei[1];
13881 				tcp->tcp_urp_mp = mp1;
13882 #ifdef DEBUG
13883 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13884 				    "tcp_rput: allocated exdata_ind %s",
13885 				    tcp_display(tcp, NULL,
13886 				    DISP_PORT_ONLY));
13887 #endif /* DEBUG */
13888 				/*
13889 				 * There is no need to send a separate MSG*MARK
13890 				 * message since the T_EXDATA_IND will be sent
13891 				 * now.
13892 				 */
13893 				flags &= ~TH_SEND_URP_MARK;
13894 				freemsg(tcp->tcp_urp_mark_mp);
13895 				tcp->tcp_urp_mark_mp = NULL;
13896 			}
13897 			/*
13898 			 * Now we are all set.  On the next putnext upstream,
13899 			 * tcp_urp_mp will be non-NULL and will get prepended
13900 			 * to what has to be this piece containing the urgent
13901 			 * byte.  If for any reason we abort this segment below,
13902 			 * if it comes back, we will have this ready, or it
13903 			 * will get blown off in close.
13904 			 */
13905 		} else if (urp == seg_len) {
13906 			/*
13907 			 * The urgent byte is the next byte after this sequence
13908 			 * number. If this endpoint is non-STREAMS, then there
13909 			 * is nothing to do here since the socket has already
13910 			 * been notified about the urg pointer by the
13911 			 * su_signal_oob call above.
13912 			 *
13913 			 * In case of STREAMS, some more work might be needed.
13914 			 * If there is data it is marked with MSGMARKNEXT and
13915 			 * and any tcp_urp_mark_mp is discarded since it is not
13916 			 * needed. Otherwise, if the code above just allocated
13917 			 * a zero-length tcp_urp_mark_mp message, that message
13918 			 * is tagged with MSGMARKNEXT. Sending up these
13919 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
13920 			 * even though the T_EXDATA_IND will not be sent up
13921 			 * until the urgent byte arrives.
13922 			 */
13923 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
13924 				if (seg_len != 0) {
13925 					flags |= TH_MARKNEXT_NEEDED;
13926 					freemsg(tcp->tcp_urp_mark_mp);
13927 					tcp->tcp_urp_mark_mp = NULL;
13928 					flags &= ~TH_SEND_URP_MARK;
13929 				} else if (tcp->tcp_urp_mark_mp != NULL) {
13930 					flags |= TH_SEND_URP_MARK;
13931 					tcp->tcp_urp_mark_mp->b_flag &=
13932 					    ~MSGNOTMARKNEXT;
13933 					tcp->tcp_urp_mark_mp->b_flag |=
13934 					    MSGMARKNEXT;
13935 				}
13936 			}
13937 #ifdef DEBUG
13938 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13939 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13940 			    seg_len, flags,
13941 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13942 #endif /* DEBUG */
13943 		}
13944 #ifdef DEBUG
13945 		else {
13946 			/* Data left until we hit mark */
13947 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13948 			    "tcp_rput: URP %d bytes left, %s",
13949 			    urp - seg_len, tcp_display(tcp, NULL,
13950 			    DISP_PORT_ONLY));
13951 		}
13952 #endif /* DEBUG */
13953 	}
13954 
13955 process_ack:
13956 	if (!(flags & TH_ACK)) {
13957 		freemsg(mp);
13958 		goto xmit_check;
13959 	}
13960 	}
13961 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13962 
13963 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13964 		tcp->tcp_ip_forward_progress = B_TRUE;
13965 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13966 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13967 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13968 			/* 3-way handshake complete - pass up the T_CONN_IND */
13969 			tcp_t	*listener = tcp->tcp_listener;
13970 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13971 
13972 			tcp->tcp_tconnind_started = B_TRUE;
13973 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13974 			/*
13975 			 * We are here means eager is fine but it can
13976 			 * get a TH_RST at any point between now and till
13977 			 * accept completes and disappear. We need to
13978 			 * ensure that reference to eager is valid after
13979 			 * we get out of eager's perimeter. So we do
13980 			 * an extra refhold.
13981 			 */
13982 			CONN_INC_REF(connp);
13983 
13984 			/*
13985 			 * The listener also exists because of the refhold
13986 			 * done in tcp_conn_request. Its possible that it
13987 			 * might have closed. We will check that once we
13988 			 * get inside listeners context.
13989 			 */
13990 			CONN_INC_REF(listener->tcp_connp);
13991 			if (listener->tcp_connp->conn_sqp ==
13992 			    connp->conn_sqp) {
13993 				/*
13994 				 * We optimize by not calling an SQUEUE_ENTER
13995 				 * on the listener since we know that the
13996 				 * listener and eager squeues are the same.
13997 				 * We are able to make this check safely only
13998 				 * because neither the eager nor the listener
13999 				 * can change its squeue. Only an active connect
14000 				 * can change its squeue
14001 				 */
14002 				tcp_send_conn_ind(listener->tcp_connp, mp,
14003 				    listener->tcp_connp->conn_sqp);
14004 				CONN_DEC_REF(listener->tcp_connp);
14005 			} else if (!tcp->tcp_loopback) {
14006 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14007 				    mp, tcp_send_conn_ind,
14008 				    listener->tcp_connp, SQ_FILL,
14009 				    SQTAG_TCP_CONN_IND);
14010 			} else {
14011 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14012 				    mp, tcp_send_conn_ind,
14013 				    listener->tcp_connp, SQ_PROCESS,
14014 				    SQTAG_TCP_CONN_IND);
14015 			}
14016 		}
14017 
14018 		/*
14019 		 * We are seeing the final ack in the three way
14020 		 * hand shake of a active open'ed connection
14021 		 * so we must send up a T_CONN_CON
14022 		 *
14023 		 * tcp_sendmsg() checks tcp_state without entering
14024 		 * the squeue so tcp_state should be updated before
14025 		 * sending up connection confirmation.
14026 		 */
14027 		tcp->tcp_state = TCPS_ESTABLISHED;
14028 		if (tcp->tcp_active_open) {
14029 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14030 				freemsg(mp);
14031 				tcp->tcp_state = TCPS_SYN_RCVD;
14032 				return;
14033 			}
14034 			/*
14035 			 * Don't fuse the loopback endpoints for
14036 			 * simultaneous active opens.
14037 			 */
14038 			if (tcp->tcp_loopback) {
14039 				TCP_STAT(tcps, tcp_fusion_unfusable);
14040 				tcp->tcp_unfusable = B_TRUE;
14041 			}
14042 		}
14043 
14044 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14045 		bytes_acked--;
14046 		/* SYN was acked - making progress */
14047 		if (tcp->tcp_ipversion == IPV6_VERSION)
14048 			tcp->tcp_ip_forward_progress = B_TRUE;
14049 
14050 		/*
14051 		 * If SYN was retransmitted, need to reset all
14052 		 * retransmission info as this segment will be
14053 		 * treated as a dup ACK.
14054 		 */
14055 		if (tcp->tcp_rexmit) {
14056 			tcp->tcp_rexmit = B_FALSE;
14057 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14058 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14059 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14060 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14061 			tcp->tcp_ms_we_have_waited = 0;
14062 			tcp->tcp_cwnd = mss;
14063 		}
14064 
14065 		/*
14066 		 * We set the send window to zero here.
14067 		 * This is needed if there is data to be
14068 		 * processed already on the queue.
14069 		 * Later (at swnd_update label), the
14070 		 * "new_swnd > tcp_swnd" condition is satisfied
14071 		 * the XMIT_NEEDED flag is set in the current
14072 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14073 		 * called if there is already data on queue in
14074 		 * this state.
14075 		 */
14076 		tcp->tcp_swnd = 0;
14077 
14078 		if (new_swnd > tcp->tcp_max_swnd)
14079 			tcp->tcp_max_swnd = new_swnd;
14080 		tcp->tcp_swl1 = seg_seq;
14081 		tcp->tcp_swl2 = seg_ack;
14082 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14083 
14084 		/* Fuse when both sides are in ESTABLISHED state */
14085 		if (tcp->tcp_loopback && do_tcp_fusion)
14086 			tcp_fuse(tcp, iphdr, tcph);
14087 
14088 	}
14089 	/* This code follows 4.4BSD-Lite2 mostly. */
14090 	if (bytes_acked < 0)
14091 		goto est;
14092 
14093 	/*
14094 	 * If TCP is ECN capable and the congestion experience bit is
14095 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14096 	 * done once per window (or more loosely, per RTT).
14097 	 */
14098 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14099 		tcp->tcp_cwr = B_FALSE;
14100 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14101 		if (!tcp->tcp_cwr) {
14102 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14103 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14104 			tcp->tcp_cwnd = npkt * mss;
14105 			/*
14106 			 * If the cwnd is 0, use the timer to clock out
14107 			 * new segments.  This is required by the ECN spec.
14108 			 */
14109 			if (npkt == 0) {
14110 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14111 				/*
14112 				 * This makes sure that when the ACK comes
14113 				 * back, we will increase tcp_cwnd by 1 MSS.
14114 				 */
14115 				tcp->tcp_cwnd_cnt = 0;
14116 			}
14117 			tcp->tcp_cwr = B_TRUE;
14118 			/*
14119 			 * This marks the end of the current window of in
14120 			 * flight data.  That is why we don't use
14121 			 * tcp_suna + tcp_swnd.  Only data in flight can
14122 			 * provide ECN info.
14123 			 */
14124 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14125 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14126 		}
14127 	}
14128 
14129 	mp1 = tcp->tcp_xmit_head;
14130 	if (bytes_acked == 0) {
14131 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14132 			int dupack_cnt;
14133 
14134 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14135 			/*
14136 			 * Fast retransmit.  When we have seen exactly three
14137 			 * identical ACKs while we have unacked data
14138 			 * outstanding we take it as a hint that our peer
14139 			 * dropped something.
14140 			 *
14141 			 * If TCP is retransmitting, don't do fast retransmit.
14142 			 */
14143 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14144 			    ! tcp->tcp_rexmit) {
14145 				/* Do Limited Transmit */
14146 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14147 				    tcps->tcps_dupack_fast_retransmit) {
14148 					/*
14149 					 * RFC 3042
14150 					 *
14151 					 * What we need to do is temporarily
14152 					 * increase tcp_cwnd so that new
14153 					 * data can be sent if it is allowed
14154 					 * by the receive window (tcp_rwnd).
14155 					 * tcp_wput_data() will take care of
14156 					 * the rest.
14157 					 *
14158 					 * If the connection is SACK capable,
14159 					 * only do limited xmit when there
14160 					 * is SACK info.
14161 					 *
14162 					 * Note how tcp_cwnd is incremented.
14163 					 * The first dup ACK will increase
14164 					 * it by 1 MSS.  The second dup ACK
14165 					 * will increase it by 2 MSS.  This
14166 					 * means that only 1 new segment will
14167 					 * be sent for each dup ACK.
14168 					 */
14169 					if (tcp->tcp_unsent > 0 &&
14170 					    (!tcp->tcp_snd_sack_ok ||
14171 					    (tcp->tcp_snd_sack_ok &&
14172 					    tcp->tcp_notsack_list != NULL))) {
14173 						tcp->tcp_cwnd += mss <<
14174 						    (tcp->tcp_dupack_cnt - 1);
14175 						flags |= TH_LIMIT_XMIT;
14176 					}
14177 				} else if (dupack_cnt ==
14178 				    tcps->tcps_dupack_fast_retransmit) {
14179 
14180 				/*
14181 				 * If we have reduced tcp_ssthresh
14182 				 * because of ECN, do not reduce it again
14183 				 * unless it is already one window of data
14184 				 * away.  After one window of data, tcp_cwr
14185 				 * should then be cleared.  Note that
14186 				 * for non ECN capable connection, tcp_cwr
14187 				 * should always be false.
14188 				 *
14189 				 * Adjust cwnd since the duplicate
14190 				 * ack indicates that a packet was
14191 				 * dropped (due to congestion.)
14192 				 */
14193 				if (!tcp->tcp_cwr) {
14194 					npkt = ((tcp->tcp_snxt -
14195 					    tcp->tcp_suna) >> 1) / mss;
14196 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14197 					    mss;
14198 					tcp->tcp_cwnd = (npkt +
14199 					    tcp->tcp_dupack_cnt) * mss;
14200 				}
14201 				if (tcp->tcp_ecn_ok) {
14202 					tcp->tcp_cwr = B_TRUE;
14203 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14204 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14205 				}
14206 
14207 				/*
14208 				 * We do Hoe's algorithm.  Refer to her
14209 				 * paper "Improving the Start-up Behavior
14210 				 * of a Congestion Control Scheme for TCP,"
14211 				 * appeared in SIGCOMM'96.
14212 				 *
14213 				 * Save highest seq no we have sent so far.
14214 				 * Be careful about the invisible FIN byte.
14215 				 */
14216 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14217 				    (tcp->tcp_unsent == 0)) {
14218 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14219 				} else {
14220 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14221 				}
14222 
14223 				/*
14224 				 * Do not allow bursty traffic during.
14225 				 * fast recovery.  Refer to Fall and Floyd's
14226 				 * paper "Simulation-based Comparisons of
14227 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14228 				 * This is a best current practise.
14229 				 */
14230 				tcp->tcp_snd_burst = TCP_CWND_SS;
14231 
14232 				/*
14233 				 * For SACK:
14234 				 * Calculate tcp_pipe, which is the
14235 				 * estimated number of bytes in
14236 				 * network.
14237 				 *
14238 				 * tcp_fack is the highest sack'ed seq num
14239 				 * TCP has received.
14240 				 *
14241 				 * tcp_pipe is explained in the above quoted
14242 				 * Fall and Floyd's paper.  tcp_fack is
14243 				 * explained in Mathis and Mahdavi's
14244 				 * "Forward Acknowledgment: Refining TCP
14245 				 * Congestion Control" in SIGCOMM '96.
14246 				 */
14247 				if (tcp->tcp_snd_sack_ok) {
14248 					ASSERT(tcp->tcp_sack_info != NULL);
14249 					if (tcp->tcp_notsack_list != NULL) {
14250 						tcp->tcp_pipe = tcp->tcp_snxt -
14251 						    tcp->tcp_fack;
14252 						tcp->tcp_sack_snxt = seg_ack;
14253 						flags |= TH_NEED_SACK_REXMIT;
14254 					} else {
14255 						/*
14256 						 * Always initialize tcp_pipe
14257 						 * even though we don't have
14258 						 * any SACK info.  If later
14259 						 * we get SACK info and
14260 						 * tcp_pipe is not initialized,
14261 						 * funny things will happen.
14262 						 */
14263 						tcp->tcp_pipe =
14264 						    tcp->tcp_cwnd_ssthresh;
14265 					}
14266 				} else {
14267 					flags |= TH_REXMIT_NEEDED;
14268 				} /* tcp_snd_sack_ok */
14269 
14270 				} else {
14271 					/*
14272 					 * Here we perform congestion
14273 					 * avoidance, but NOT slow start.
14274 					 * This is known as the Fast
14275 					 * Recovery Algorithm.
14276 					 */
14277 					if (tcp->tcp_snd_sack_ok &&
14278 					    tcp->tcp_notsack_list != NULL) {
14279 						flags |= TH_NEED_SACK_REXMIT;
14280 						tcp->tcp_pipe -= mss;
14281 						if (tcp->tcp_pipe < 0)
14282 							tcp->tcp_pipe = 0;
14283 					} else {
14284 					/*
14285 					 * We know that one more packet has
14286 					 * left the pipe thus we can update
14287 					 * cwnd.
14288 					 */
14289 					cwnd = tcp->tcp_cwnd + mss;
14290 					if (cwnd > tcp->tcp_cwnd_max)
14291 						cwnd = tcp->tcp_cwnd_max;
14292 					tcp->tcp_cwnd = cwnd;
14293 					if (tcp->tcp_unsent > 0)
14294 						flags |= TH_XMIT_NEEDED;
14295 					}
14296 				}
14297 			}
14298 		} else if (tcp->tcp_zero_win_probe) {
14299 			/*
14300 			 * If the window has opened, need to arrange
14301 			 * to send additional data.
14302 			 */
14303 			if (new_swnd != 0) {
14304 				/* tcp_suna != tcp_snxt */
14305 				/* Packet contains a window update */
14306 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14307 				tcp->tcp_zero_win_probe = 0;
14308 				tcp->tcp_timer_backoff = 0;
14309 				tcp->tcp_ms_we_have_waited = 0;
14310 
14311 				/*
14312 				 * Transmit starting with tcp_suna since
14313 				 * the one byte probe is not ack'ed.
14314 				 * If TCP has sent more than one identical
14315 				 * probe, tcp_rexmit will be set.  That means
14316 				 * tcp_ss_rexmit() will send out the one
14317 				 * byte along with new data.  Otherwise,
14318 				 * fake the retransmission.
14319 				 */
14320 				flags |= TH_XMIT_NEEDED;
14321 				if (!tcp->tcp_rexmit) {
14322 					tcp->tcp_rexmit = B_TRUE;
14323 					tcp->tcp_dupack_cnt = 0;
14324 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14325 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14326 				}
14327 			}
14328 		}
14329 		goto swnd_update;
14330 	}
14331 
14332 	/*
14333 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14334 	 * If the ACK value acks something that we have not yet sent, it might
14335 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14336 	 * other side.
14337 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14338 	 * state is handled above, so we can always just drop the segment and
14339 	 * send an ACK here.
14340 	 *
14341 	 * In the case where the peer shrinks the window, we see the new window
14342 	 * update, but all the data sent previously is queued up by the peer.
14343 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
14344 	 * number, which was already sent, and within window, is recorded.
14345 	 * tcp_snxt is then updated.
14346 	 *
14347 	 * If the window has previously shrunk, and an ACK for data not yet
14348 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
14349 	 * the ACK is for data within the window at the time the window was
14350 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
14351 	 * the sequence number ACK'ed.
14352 	 *
14353 	 * If the ACK covers all the data sent at the time the window was
14354 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
14355 	 *
14356 	 * Should we send ACKs in response to ACK only segments?
14357 	 */
14358 
14359 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14360 		if ((tcp->tcp_is_wnd_shrnk) &&
14361 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
14362 			uint32_t data_acked_ahead_snxt;
14363 
14364 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
14365 			tcp_update_xmit_tail(tcp, seg_ack);
14366 			tcp->tcp_unsent -= data_acked_ahead_snxt;
14367 		} else {
14368 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14369 			/* drop the received segment */
14370 			freemsg(mp);
14371 
14372 			/*
14373 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14374 			 * greater than 0, check if the number of such
14375 			 * bogus ACks is greater than that count.  If yes,
14376 			 * don't send back any ACK.  This prevents TCP from
14377 			 * getting into an ACK storm if somehow an attacker
14378 			 * successfully spoofs an acceptable segment to our
14379 			 * peer.
14380 			 */
14381 			if (tcp_drop_ack_unsent_cnt > 0 &&
14382 			    ++tcp->tcp_in_ack_unsent >
14383 			    tcp_drop_ack_unsent_cnt) {
14384 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14385 				return;
14386 			}
14387 			mp = tcp_ack_mp(tcp);
14388 			if (mp != NULL) {
14389 				BUMP_LOCAL(tcp->tcp_obsegs);
14390 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14391 				tcp_send_data(tcp, tcp->tcp_wq, mp);
14392 			}
14393 			return;
14394 		}
14395 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
14396 	    tcp->tcp_snxt_shrunk)) {
14397 			tcp->tcp_is_wnd_shrnk = B_FALSE;
14398 	}
14399 
14400 	/*
14401 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14402 	 * blocks that are covered by this ACK.
14403 	 */
14404 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14405 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14406 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14407 	}
14408 
14409 	/*
14410 	 * If we got an ACK after fast retransmit, check to see
14411 	 * if it is a partial ACK.  If it is not and the congestion
14412 	 * window was inflated to account for the other side's
14413 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14414 	 */
14415 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14416 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14417 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14418 			tcp->tcp_dupack_cnt = 0;
14419 			/*
14420 			 * Restore the orig tcp_cwnd_ssthresh after
14421 			 * fast retransmit phase.
14422 			 */
14423 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14424 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14425 			}
14426 			tcp->tcp_rexmit_max = seg_ack;
14427 			tcp->tcp_cwnd_cnt = 0;
14428 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14429 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14430 
14431 			/*
14432 			 * Remove all notsack info to avoid confusion with
14433 			 * the next fast retrasnmit/recovery phase.
14434 			 */
14435 			if (tcp->tcp_snd_sack_ok &&
14436 			    tcp->tcp_notsack_list != NULL) {
14437 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
14438 				    tcp);
14439 			}
14440 		} else {
14441 			if (tcp->tcp_snd_sack_ok &&
14442 			    tcp->tcp_notsack_list != NULL) {
14443 				flags |= TH_NEED_SACK_REXMIT;
14444 				tcp->tcp_pipe -= mss;
14445 				if (tcp->tcp_pipe < 0)
14446 					tcp->tcp_pipe = 0;
14447 			} else {
14448 				/*
14449 				 * Hoe's algorithm:
14450 				 *
14451 				 * Retransmit the unack'ed segment and
14452 				 * restart fast recovery.  Note that we
14453 				 * need to scale back tcp_cwnd to the
14454 				 * original value when we started fast
14455 				 * recovery.  This is to prevent overly
14456 				 * aggressive behaviour in sending new
14457 				 * segments.
14458 				 */
14459 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14460 				    tcps->tcps_dupack_fast_retransmit * mss;
14461 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14462 				flags |= TH_REXMIT_NEEDED;
14463 			}
14464 		}
14465 	} else {
14466 		tcp->tcp_dupack_cnt = 0;
14467 		if (tcp->tcp_rexmit) {
14468 			/*
14469 			 * TCP is retranmitting.  If the ACK ack's all
14470 			 * outstanding data, update tcp_rexmit_max and
14471 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14472 			 * to the correct value.
14473 			 *
14474 			 * Note that SEQ_LEQ() is used.  This is to avoid
14475 			 * unnecessary fast retransmit caused by dup ACKs
14476 			 * received when TCP does slow start retransmission
14477 			 * after a time out.  During this phase, TCP may
14478 			 * send out segments which are already received.
14479 			 * This causes dup ACKs to be sent back.
14480 			 */
14481 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14482 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14483 					tcp->tcp_rexmit_nxt = seg_ack;
14484 				}
14485 				if (seg_ack != tcp->tcp_rexmit_max) {
14486 					flags |= TH_XMIT_NEEDED;
14487 				}
14488 			} else {
14489 				tcp->tcp_rexmit = B_FALSE;
14490 				tcp->tcp_xmit_zc_clean = B_FALSE;
14491 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14492 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14493 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14494 			}
14495 			tcp->tcp_ms_we_have_waited = 0;
14496 		}
14497 	}
14498 
14499 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14500 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14501 	tcp->tcp_suna = seg_ack;
14502 	if (tcp->tcp_zero_win_probe != 0) {
14503 		tcp->tcp_zero_win_probe = 0;
14504 		tcp->tcp_timer_backoff = 0;
14505 	}
14506 
14507 	/*
14508 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14509 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14510 	 * will not reach here.
14511 	 */
14512 	if (mp1 == NULL) {
14513 		goto fin_acked;
14514 	}
14515 
14516 	/*
14517 	 * Update the congestion window.
14518 	 *
14519 	 * If TCP is not ECN capable or TCP is ECN capable but the
14520 	 * congestion experience bit is not set, increase the tcp_cwnd as
14521 	 * usual.
14522 	 */
14523 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14524 		cwnd = tcp->tcp_cwnd;
14525 		add = mss;
14526 
14527 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14528 			/*
14529 			 * This is to prevent an increase of less than 1 MSS of
14530 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14531 			 * may send out tinygrams in order to preserve mblk
14532 			 * boundaries.
14533 			 *
14534 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14535 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14536 			 * increased by 1 MSS for every RTTs.
14537 			 */
14538 			if (tcp->tcp_cwnd_cnt <= 0) {
14539 				tcp->tcp_cwnd_cnt = cwnd + add;
14540 			} else {
14541 				tcp->tcp_cwnd_cnt -= add;
14542 				add = 0;
14543 			}
14544 		}
14545 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14546 	}
14547 
14548 	/* See if the latest urgent data has been acknowledged */
14549 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14550 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14551 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14552 
14553 	/* Can we update the RTT estimates? */
14554 	if (tcp->tcp_snd_ts_ok) {
14555 		/* Ignore zero timestamp echo-reply. */
14556 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14557 			tcp_set_rto(tcp, (int32_t)lbolt -
14558 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14559 		}
14560 
14561 		/* If needed, restart the timer. */
14562 		if (tcp->tcp_set_timer == 1) {
14563 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14564 			tcp->tcp_set_timer = 0;
14565 		}
14566 		/*
14567 		 * Update tcp_csuna in case the other side stops sending
14568 		 * us timestamps.
14569 		 */
14570 		tcp->tcp_csuna = tcp->tcp_snxt;
14571 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14572 		/*
14573 		 * An ACK sequence we haven't seen before, so get the RTT
14574 		 * and update the RTO. But first check if the timestamp is
14575 		 * valid to use.
14576 		 */
14577 		if ((mp1->b_next != NULL) &&
14578 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14579 			tcp_set_rto(tcp, (int32_t)lbolt -
14580 			    (int32_t)(intptr_t)mp1->b_prev);
14581 		else
14582 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14583 
14584 		/* Remeber the last sequence to be ACKed */
14585 		tcp->tcp_csuna = seg_ack;
14586 		if (tcp->tcp_set_timer == 1) {
14587 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14588 			tcp->tcp_set_timer = 0;
14589 		}
14590 	} else {
14591 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14592 	}
14593 
14594 	/* Eat acknowledged bytes off the xmit queue. */
14595 	for (;;) {
14596 		mblk_t	*mp2;
14597 		uchar_t	*wptr;
14598 
14599 		wptr = mp1->b_wptr;
14600 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14601 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14602 		if (bytes_acked < 0) {
14603 			mp1->b_rptr = wptr + bytes_acked;
14604 			/*
14605 			 * Set a new timestamp if all the bytes timed by the
14606 			 * old timestamp have been ack'ed.
14607 			 */
14608 			if (SEQ_GT(seg_ack,
14609 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14610 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14611 				mp1->b_next = NULL;
14612 			}
14613 			break;
14614 		}
14615 		mp1->b_next = NULL;
14616 		mp1->b_prev = NULL;
14617 		mp2 = mp1;
14618 		mp1 = mp1->b_cont;
14619 
14620 		/*
14621 		 * This notification is required for some zero-copy
14622 		 * clients to maintain a copy semantic. After the data
14623 		 * is ack'ed, client is safe to modify or reuse the buffer.
14624 		 */
14625 		if (tcp->tcp_snd_zcopy_aware &&
14626 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14627 			tcp_zcopy_notify(tcp);
14628 		freeb(mp2);
14629 		if (bytes_acked == 0) {
14630 			if (mp1 == NULL) {
14631 				/* Everything is ack'ed, clear the tail. */
14632 				tcp->tcp_xmit_tail = NULL;
14633 				/*
14634 				 * Cancel the timer unless we are still
14635 				 * waiting for an ACK for the FIN packet.
14636 				 */
14637 				if (tcp->tcp_timer_tid != 0 &&
14638 				    tcp->tcp_snxt == tcp->tcp_suna) {
14639 					(void) TCP_TIMER_CANCEL(tcp,
14640 					    tcp->tcp_timer_tid);
14641 					tcp->tcp_timer_tid = 0;
14642 				}
14643 				goto pre_swnd_update;
14644 			}
14645 			if (mp2 != tcp->tcp_xmit_tail)
14646 				break;
14647 			tcp->tcp_xmit_tail = mp1;
14648 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14649 			    (uintptr_t)INT_MAX);
14650 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14651 			    mp1->b_rptr);
14652 			break;
14653 		}
14654 		if (mp1 == NULL) {
14655 			/*
14656 			 * More was acked but there is nothing more
14657 			 * outstanding.  This means that the FIN was
14658 			 * just acked or that we're talking to a clown.
14659 			 */
14660 fin_acked:
14661 			ASSERT(tcp->tcp_fin_sent);
14662 			tcp->tcp_xmit_tail = NULL;
14663 			if (tcp->tcp_fin_sent) {
14664 				/* FIN was acked - making progress */
14665 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14666 				    !tcp->tcp_fin_acked)
14667 					tcp->tcp_ip_forward_progress = B_TRUE;
14668 				tcp->tcp_fin_acked = B_TRUE;
14669 				if (tcp->tcp_linger_tid != 0 &&
14670 				    TCP_TIMER_CANCEL(tcp,
14671 				    tcp->tcp_linger_tid) >= 0) {
14672 					tcp_stop_lingering(tcp);
14673 					freemsg(mp);
14674 					mp = NULL;
14675 				}
14676 			} else {
14677 				/*
14678 				 * We should never get here because
14679 				 * we have already checked that the
14680 				 * number of bytes ack'ed should be
14681 				 * smaller than or equal to what we
14682 				 * have sent so far (it is the
14683 				 * acceptability check of the ACK).
14684 				 * We can only get here if the send
14685 				 * queue is corrupted.
14686 				 *
14687 				 * Terminate the connection and
14688 				 * panic the system.  It is better
14689 				 * for us to panic instead of
14690 				 * continuing to avoid other disaster.
14691 				 */
14692 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14693 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14694 				panic("Memory corruption "
14695 				    "detected for connection %s.",
14696 				    tcp_display(tcp, NULL,
14697 				    DISP_ADDR_AND_PORT));
14698 				/*NOTREACHED*/
14699 			}
14700 			goto pre_swnd_update;
14701 		}
14702 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14703 	}
14704 	if (tcp->tcp_unsent) {
14705 		flags |= TH_XMIT_NEEDED;
14706 	}
14707 pre_swnd_update:
14708 	tcp->tcp_xmit_head = mp1;
14709 swnd_update:
14710 	/*
14711 	 * The following check is different from most other implementations.
14712 	 * For bi-directional transfer, when segments are dropped, the
14713 	 * "normal" check will not accept a window update in those
14714 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14715 	 * segments which are outside receiver's window.  As TCP accepts
14716 	 * the ack in those retransmitted segments, if the window update in
14717 	 * the same segment is not accepted, TCP will incorrectly calculates
14718 	 * that it can send more segments.  This can create a deadlock
14719 	 * with the receiver if its window becomes zero.
14720 	 */
14721 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14722 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14723 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14724 		/*
14725 		 * The criteria for update is:
14726 		 *
14727 		 * 1. the segment acknowledges some data.  Or
14728 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14729 		 * 3. the segment is not old and the advertised window is
14730 		 * larger than the previous advertised window.
14731 		 */
14732 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14733 			flags |= TH_XMIT_NEEDED;
14734 		tcp->tcp_swnd = new_swnd;
14735 		if (new_swnd > tcp->tcp_max_swnd)
14736 			tcp->tcp_max_swnd = new_swnd;
14737 		tcp->tcp_swl1 = seg_seq;
14738 		tcp->tcp_swl2 = seg_ack;
14739 	}
14740 est:
14741 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14742 
14743 		switch (tcp->tcp_state) {
14744 		case TCPS_FIN_WAIT_1:
14745 			if (tcp->tcp_fin_acked) {
14746 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14747 				/*
14748 				 * We implement the non-standard BSD/SunOS
14749 				 * FIN_WAIT_2 flushing algorithm.
14750 				 * If there is no user attached to this
14751 				 * TCP endpoint, then this TCP struct
14752 				 * could hang around forever in FIN_WAIT_2
14753 				 * state if the peer forgets to send us
14754 				 * a FIN.  To prevent this, we wait only
14755 				 * 2*MSL (a convenient time value) for
14756 				 * the FIN to arrive.  If it doesn't show up,
14757 				 * we flush the TCP endpoint.  This algorithm,
14758 				 * though a violation of RFC-793, has worked
14759 				 * for over 10 years in BSD systems.
14760 				 * Note: SunOS 4.x waits 675 seconds before
14761 				 * flushing the FIN_WAIT_2 connection.
14762 				 */
14763 				TCP_TIMER_RESTART(tcp,
14764 				    tcps->tcps_fin_wait_2_flush_interval);
14765 			}
14766 			break;
14767 		case TCPS_FIN_WAIT_2:
14768 			break;	/* Shutdown hook? */
14769 		case TCPS_LAST_ACK:
14770 			freemsg(mp);
14771 			if (tcp->tcp_fin_acked) {
14772 				(void) tcp_clean_death(tcp, 0, 19);
14773 				return;
14774 			}
14775 			goto xmit_check;
14776 		case TCPS_CLOSING:
14777 			if (tcp->tcp_fin_acked) {
14778 				tcp->tcp_state = TCPS_TIME_WAIT;
14779 				/*
14780 				 * Unconditionally clear the exclusive binding
14781 				 * bit so this TIME-WAIT connection won't
14782 				 * interfere with new ones.
14783 				 */
14784 				tcp->tcp_exclbind = 0;
14785 				if (!TCP_IS_DETACHED(tcp)) {
14786 					TCP_TIMER_RESTART(tcp,
14787 					    tcps->tcps_time_wait_interval);
14788 				} else {
14789 					tcp_time_wait_append(tcp);
14790 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14791 				}
14792 			}
14793 			/*FALLTHRU*/
14794 		case TCPS_CLOSE_WAIT:
14795 			freemsg(mp);
14796 			goto xmit_check;
14797 		default:
14798 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14799 			break;
14800 		}
14801 	}
14802 	if (flags & TH_FIN) {
14803 		/* Make sure we ack the fin */
14804 		flags |= TH_ACK_NEEDED;
14805 		if (!tcp->tcp_fin_rcvd) {
14806 			tcp->tcp_fin_rcvd = B_TRUE;
14807 			tcp->tcp_rnxt++;
14808 			tcph = tcp->tcp_tcph;
14809 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14810 
14811 			/*
14812 			 * Generate the ordrel_ind at the end unless we
14813 			 * are an eager guy.
14814 			 * In the eager case tcp_rsrv will do this when run
14815 			 * after tcp_accept is done.
14816 			 */
14817 			if (tcp->tcp_listener == NULL &&
14818 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14819 				flags |= TH_ORDREL_NEEDED;
14820 			switch (tcp->tcp_state) {
14821 			case TCPS_SYN_RCVD:
14822 			case TCPS_ESTABLISHED:
14823 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14824 				/* Keepalive? */
14825 				break;
14826 			case TCPS_FIN_WAIT_1:
14827 				if (!tcp->tcp_fin_acked) {
14828 					tcp->tcp_state = TCPS_CLOSING;
14829 					break;
14830 				}
14831 				/* FALLTHRU */
14832 			case TCPS_FIN_WAIT_2:
14833 				tcp->tcp_state = TCPS_TIME_WAIT;
14834 				/*
14835 				 * Unconditionally clear the exclusive binding
14836 				 * bit so this TIME-WAIT connection won't
14837 				 * interfere with new ones.
14838 				 */
14839 				tcp->tcp_exclbind = 0;
14840 				if (!TCP_IS_DETACHED(tcp)) {
14841 					TCP_TIMER_RESTART(tcp,
14842 					    tcps->tcps_time_wait_interval);
14843 				} else {
14844 					tcp_time_wait_append(tcp);
14845 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14846 				}
14847 				if (seg_len) {
14848 					/*
14849 					 * implies data piggybacked on FIN.
14850 					 * break to handle data.
14851 					 */
14852 					break;
14853 				}
14854 				freemsg(mp);
14855 				goto ack_check;
14856 			}
14857 		}
14858 	}
14859 	if (mp == NULL)
14860 		goto xmit_check;
14861 	if (seg_len == 0) {
14862 		freemsg(mp);
14863 		goto xmit_check;
14864 	}
14865 	if (mp->b_rptr == mp->b_wptr) {
14866 		/*
14867 		 * The header has been consumed, so we remove the
14868 		 * zero-length mblk here.
14869 		 */
14870 		mp1 = mp;
14871 		mp = mp->b_cont;
14872 		freeb(mp1);
14873 	}
14874 update_ack:
14875 	tcph = tcp->tcp_tcph;
14876 	tcp->tcp_rack_cnt++;
14877 	{
14878 		uint32_t cur_max;
14879 
14880 		cur_max = tcp->tcp_rack_cur_max;
14881 		if (tcp->tcp_rack_cnt >= cur_max) {
14882 			/*
14883 			 * We have more unacked data than we should - send
14884 			 * an ACK now.
14885 			 */
14886 			flags |= TH_ACK_NEEDED;
14887 			cur_max++;
14888 			if (cur_max > tcp->tcp_rack_abs_max)
14889 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14890 			else
14891 				tcp->tcp_rack_cur_max = cur_max;
14892 		} else if (TCP_IS_DETACHED(tcp)) {
14893 			/* We don't have an ACK timer for detached TCP. */
14894 			flags |= TH_ACK_NEEDED;
14895 		} else if (seg_len < mss) {
14896 			/*
14897 			 * If we get a segment that is less than an mss, and we
14898 			 * already have unacknowledged data, and the amount
14899 			 * unacknowledged is not a multiple of mss, then we
14900 			 * better generate an ACK now.  Otherwise, this may be
14901 			 * the tail piece of a transaction, and we would rather
14902 			 * wait for the response.
14903 			 */
14904 			uint32_t udif;
14905 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14906 			    (uintptr_t)INT_MAX);
14907 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14908 			if (udif && (udif % mss))
14909 				flags |= TH_ACK_NEEDED;
14910 			else
14911 				flags |= TH_ACK_TIMER_NEEDED;
14912 		} else {
14913 			/* Start delayed ack timer */
14914 			flags |= TH_ACK_TIMER_NEEDED;
14915 		}
14916 	}
14917 	tcp->tcp_rnxt += seg_len;
14918 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14919 
14920 	if (mp == NULL)
14921 		goto xmit_check;
14922 
14923 	/* Update SACK list */
14924 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14925 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14926 		    &(tcp->tcp_num_sack_blk));
14927 	}
14928 
14929 	if (tcp->tcp_urp_mp) {
14930 		tcp->tcp_urp_mp->b_cont = mp;
14931 		mp = tcp->tcp_urp_mp;
14932 		tcp->tcp_urp_mp = NULL;
14933 		/* Ready for a new signal. */
14934 		tcp->tcp_urp_last_valid = B_FALSE;
14935 #ifdef DEBUG
14936 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14937 		    "tcp_rput: sending exdata_ind %s",
14938 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14939 #endif /* DEBUG */
14940 	}
14941 
14942 	/*
14943 	 * Check for ancillary data changes compared to last segment.
14944 	 */
14945 	if (tcp->tcp_ipv6_recvancillary != 0) {
14946 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14947 		ASSERT(mp != NULL);
14948 	}
14949 
14950 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14951 		/*
14952 		 * Side queue inbound data until the accept happens.
14953 		 * tcp_accept/tcp_rput drains this when the accept happens.
14954 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14955 		 * T_EXDATA_IND) it is queued on b_next.
14956 		 * XXX Make urgent data use this. Requires:
14957 		 *	Removing tcp_listener check for TH_URG
14958 		 *	Making M_PCPROTO and MARK messages skip the eager case
14959 		 */
14960 
14961 		if (tcp->tcp_kssl_pending) {
14962 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
14963 			    mblk_t *, mp);
14964 			tcp_kssl_input(tcp, mp);
14965 		} else {
14966 			tcp_rcv_enqueue(tcp, mp, seg_len);
14967 		}
14968 	} else if (IPCL_IS_NONSTR(connp)) {
14969 		/*
14970 		 * Non-STREAMS socket
14971 		 *
14972 		 * Note that no KSSL processing is done here, because
14973 		 * KSSL is not supported for non-STREAMS sockets.
14974 		 */
14975 		boolean_t push = flags & (TH_PUSH|TH_FIN);
14976 		int error;
14977 
14978 		if ((*connp->conn_upcalls->su_recv)(
14979 		    connp->conn_upper_handle,
14980 		    mp, seg_len, 0, &error, &push) <= 0) {
14981 			/*
14982 			 * We should never be in middle of a
14983 			 * fallback, the squeue guarantees that.
14984 			 */
14985 			ASSERT(error != EOPNOTSUPP);
14986 			if (error == ENOSPC)
14987 				tcp->tcp_rwnd -= seg_len;
14988 		} else if (push) {
14989 			/* PUSH bit set and sockfs is not flow controlled */
14990 			flags |= tcp_rwnd_reopen(tcp);
14991 		}
14992 	} else {
14993 		/* STREAMS socket */
14994 		if (mp->b_datap->db_type != M_DATA ||
14995 		    (flags & TH_MARKNEXT_NEEDED)) {
14996 			if (tcp->tcp_rcv_list != NULL) {
14997 				flags |= tcp_rcv_drain(tcp);
14998 			}
14999 			ASSERT(tcp->tcp_rcv_list == NULL ||
15000 			    tcp->tcp_fused_sigurg);
15001 
15002 			if (flags & TH_MARKNEXT_NEEDED) {
15003 #ifdef DEBUG
15004 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15005 				    "tcp_rput: sending MSGMARKNEXT %s",
15006 				    tcp_display(tcp, NULL,
15007 				    DISP_PORT_ONLY));
15008 #endif /* DEBUG */
15009 				mp->b_flag |= MSGMARKNEXT;
15010 				flags &= ~TH_MARKNEXT_NEEDED;
15011 			}
15012 
15013 			/* Does this need SSL processing first? */
15014 			if ((tcp->tcp_kssl_ctx != NULL) &&
15015 			    (DB_TYPE(mp) == M_DATA)) {
15016 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15017 				    mblk_t *, mp);
15018 				tcp_kssl_input(tcp, mp);
15019 			} else {
15020 				putnext(tcp->tcp_rq, mp);
15021 				if (!canputnext(tcp->tcp_rq))
15022 					tcp->tcp_rwnd -= seg_len;
15023 			}
15024 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15025 		    (DB_TYPE(mp) == M_DATA)) {
15026 			/* Does this need SSL processing first? */
15027 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15028 			tcp_kssl_input(tcp, mp);
15029 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15030 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15031 			if (tcp->tcp_rcv_list != NULL) {
15032 				/*
15033 				 * Enqueue the new segment first and then
15034 				 * call tcp_rcv_drain() to send all data
15035 				 * up.  The other way to do this is to
15036 				 * send all queued data up and then call
15037 				 * putnext() to send the new segment up.
15038 				 * This way can remove the else part later
15039 				 * on.
15040 				 *
15041 				 * We don't do this to avoid one more call to
15042 				 * canputnext() as tcp_rcv_drain() needs to
15043 				 * call canputnext().
15044 				 */
15045 				tcp_rcv_enqueue(tcp, mp, seg_len);
15046 				flags |= tcp_rcv_drain(tcp);
15047 			} else {
15048 				putnext(tcp->tcp_rq, mp);
15049 				if (!canputnext(tcp->tcp_rq))
15050 					tcp->tcp_rwnd -= seg_len;
15051 			}
15052 		} else {
15053 			/*
15054 			 * Enqueue all packets when processing an mblk
15055 			 * from the co queue and also enqueue normal packets.
15056 			 */
15057 			tcp_rcv_enqueue(tcp, mp, seg_len);
15058 		}
15059 		/*
15060 		 * Make sure the timer is running if we have data waiting
15061 		 * for a push bit. This provides resiliency against
15062 		 * implementations that do not correctly generate push bits.
15063 		 */
15064 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
15065 			/*
15066 			 * The connection may be closed at this point, so don't
15067 			 * do anything for a detached tcp.
15068 			 */
15069 			if (!TCP_IS_DETACHED(tcp))
15070 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15071 				    tcp_push_timer,
15072 				    MSEC_TO_TICK(
15073 				    tcps->tcps_push_timer_interval));
15074 		}
15075 	}
15076 
15077 xmit_check:
15078 	/* Is there anything left to do? */
15079 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15080 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15081 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15082 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15083 		goto done;
15084 
15085 	/* Any transmit work to do and a non-zero window? */
15086 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15087 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15088 		if (flags & TH_REXMIT_NEEDED) {
15089 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15090 
15091 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15092 			if (snd_size > mss)
15093 				snd_size = mss;
15094 			if (snd_size > tcp->tcp_swnd)
15095 				snd_size = tcp->tcp_swnd;
15096 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15097 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15098 			    B_TRUE);
15099 
15100 			if (mp1 != NULL) {
15101 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15102 				tcp->tcp_csuna = tcp->tcp_snxt;
15103 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15104 				UPDATE_MIB(&tcps->tcps_mib,
15105 				    tcpRetransBytes, snd_size);
15106 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15107 			}
15108 		}
15109 		if (flags & TH_NEED_SACK_REXMIT) {
15110 			tcp_sack_rxmit(tcp, &flags);
15111 		}
15112 		/*
15113 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15114 		 * out new segment.  Note that tcp_rexmit should not be
15115 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15116 		 */
15117 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15118 			if (!tcp->tcp_rexmit) {
15119 				tcp_wput_data(tcp, NULL, B_FALSE);
15120 			} else {
15121 				tcp_ss_rexmit(tcp);
15122 			}
15123 		}
15124 		/*
15125 		 * Adjust tcp_cwnd back to normal value after sending
15126 		 * new data segments.
15127 		 */
15128 		if (flags & TH_LIMIT_XMIT) {
15129 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15130 			/*
15131 			 * This will restart the timer.  Restarting the
15132 			 * timer is used to avoid a timeout before the
15133 			 * limited transmitted segment's ACK gets back.
15134 			 */
15135 			if (tcp->tcp_xmit_head != NULL)
15136 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15137 		}
15138 
15139 		/* Anything more to do? */
15140 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15141 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15142 			goto done;
15143 	}
15144 ack_check:
15145 	if (flags & TH_SEND_URP_MARK) {
15146 		ASSERT(tcp->tcp_urp_mark_mp);
15147 		ASSERT(!IPCL_IS_NONSTR(connp));
15148 		/*
15149 		 * Send up any queued data and then send the mark message
15150 		 */
15151 		if (tcp->tcp_rcv_list != NULL) {
15152 			flags |= tcp_rcv_drain(tcp);
15153 
15154 		}
15155 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15156 		mp1 = tcp->tcp_urp_mark_mp;
15157 		tcp->tcp_urp_mark_mp = NULL;
15158 		putnext(tcp->tcp_rq, mp1);
15159 #ifdef DEBUG
15160 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15161 		    "tcp_rput: sending zero-length %s %s",
15162 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15163 		    "MSGNOTMARKNEXT"),
15164 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15165 #endif /* DEBUG */
15166 		flags &= ~TH_SEND_URP_MARK;
15167 	}
15168 	if (flags & TH_ACK_NEEDED) {
15169 		/*
15170 		 * Time to send an ack for some reason.
15171 		 */
15172 		mp1 = tcp_ack_mp(tcp);
15173 
15174 		if (mp1 != NULL) {
15175 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15176 			BUMP_LOCAL(tcp->tcp_obsegs);
15177 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15178 		}
15179 		if (tcp->tcp_ack_tid != 0) {
15180 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15181 			tcp->tcp_ack_tid = 0;
15182 		}
15183 	}
15184 	if (flags & TH_ACK_TIMER_NEEDED) {
15185 		/*
15186 		 * Arrange for deferred ACK or push wait timeout.
15187 		 * Start timer if it is not already running.
15188 		 */
15189 		if (tcp->tcp_ack_tid == 0) {
15190 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15191 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15192 			    (clock_t)tcps->tcps_local_dack_interval :
15193 			    (clock_t)tcps->tcps_deferred_ack_interval));
15194 		}
15195 	}
15196 	if (flags & TH_ORDREL_NEEDED) {
15197 		/*
15198 		 * Send up the ordrel_ind unless we are an eager guy.
15199 		 * In the eager case tcp_rsrv will do this when run
15200 		 * after tcp_accept is done.
15201 		 */
15202 		ASSERT(tcp->tcp_listener == NULL);
15203 
15204 		if (IPCL_IS_NONSTR(connp)) {
15205 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15206 			tcp->tcp_ordrel_done = B_TRUE;
15207 			(*connp->conn_upcalls->su_opctl)
15208 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15209 			goto done;
15210 		}
15211 
15212 		if (tcp->tcp_rcv_list != NULL) {
15213 			/*
15214 			 * Push any mblk(s) enqueued from co processing.
15215 			 */
15216 			flags |= tcp_rcv_drain(tcp);
15217 		}
15218 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15219 
15220 		mp1 = tcp->tcp_ordrel_mp;
15221 		tcp->tcp_ordrel_mp = NULL;
15222 		tcp->tcp_ordrel_done = B_TRUE;
15223 		putnext(tcp->tcp_rq, mp1);
15224 	}
15225 done:
15226 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15227 }
15228 
15229 /*
15230  * This routine adjusts next-to-send sequence number variables, in the
15231  * case where the reciever has shrunk it's window.
15232  */
15233 static void
15234 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
15235 {
15236 	mblk_t *xmit_tail;
15237 	int32_t offset;
15238 
15239 	tcp->tcp_snxt = snxt;
15240 
15241 	/* Get the mblk, and the offset in it, as per the shrunk window */
15242 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
15243 	ASSERT(xmit_tail != NULL);
15244 	tcp->tcp_xmit_tail = xmit_tail;
15245 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
15246 	    xmit_tail->b_rptr - offset;
15247 }
15248 
15249 /*
15250  * This function does PAWS protection check. Returns B_TRUE if the
15251  * segment passes the PAWS test, else returns B_FALSE.
15252  */
15253 boolean_t
15254 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15255 {
15256 	uint8_t	flags;
15257 	int	options;
15258 	uint8_t *up;
15259 
15260 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15261 	/*
15262 	 * If timestamp option is aligned nicely, get values inline,
15263 	 * otherwise call general routine to parse.  Only do that
15264 	 * if timestamp is the only option.
15265 	 */
15266 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15267 	    TCPOPT_REAL_TS_LEN &&
15268 	    OK_32PTR((up = ((uint8_t *)tcph) +
15269 	    TCP_MIN_HEADER_LENGTH)) &&
15270 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15271 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15272 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15273 
15274 		options = TCP_OPT_TSTAMP_PRESENT;
15275 	} else {
15276 		if (tcp->tcp_snd_sack_ok) {
15277 			tcpoptp->tcp = tcp;
15278 		} else {
15279 			tcpoptp->tcp = NULL;
15280 		}
15281 		options = tcp_parse_options(tcph, tcpoptp);
15282 	}
15283 
15284 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15285 		/*
15286 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15287 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15288 		 */
15289 		if ((flags & TH_RST) == 0 &&
15290 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15291 		    tcp->tcp_ts_recent)) {
15292 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15293 			    PAWS_TIMEOUT)) {
15294 				/* This segment is not acceptable. */
15295 				return (B_FALSE);
15296 			} else {
15297 				/*
15298 				 * Connection has been idle for
15299 				 * too long.  Reset the timestamp
15300 				 * and assume the segment is valid.
15301 				 */
15302 				tcp->tcp_ts_recent =
15303 				    tcpoptp->tcp_opt_ts_val;
15304 			}
15305 		}
15306 	} else {
15307 		/*
15308 		 * If we don't get a timestamp on every packet, we
15309 		 * figure we can't really trust 'em, so we stop sending
15310 		 * and parsing them.
15311 		 */
15312 		tcp->tcp_snd_ts_ok = B_FALSE;
15313 
15314 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15315 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15316 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15317 		/*
15318 		 * Adjust the tcp_mss accordingly. We also need to
15319 		 * adjust tcp_cwnd here in accordance with the new mss.
15320 		 * But we avoid doing a slow start here so as to not
15321 		 * to lose on the transfer rate built up so far.
15322 		 */
15323 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15324 		if (tcp->tcp_snd_sack_ok) {
15325 			ASSERT(tcp->tcp_sack_info != NULL);
15326 			tcp->tcp_max_sack_blk = 4;
15327 		}
15328 	}
15329 	return (B_TRUE);
15330 }
15331 
15332 /*
15333  * Attach ancillary data to a received TCP segments for the
15334  * ancillary pieces requested by the application that are
15335  * different than they were in the previous data segment.
15336  *
15337  * Save the "current" values once memory allocation is ok so that
15338  * when memory allocation fails we can just wait for the next data segment.
15339  */
15340 static mblk_t *
15341 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15342 {
15343 	struct T_optdata_ind *todi;
15344 	int optlen;
15345 	uchar_t *optptr;
15346 	struct T_opthdr *toh;
15347 	uint_t addflag;	/* Which pieces to add */
15348 	mblk_t *mp1;
15349 
15350 	optlen = 0;
15351 	addflag = 0;
15352 	/* If app asked for pktinfo and the index has changed ... */
15353 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15354 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15355 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15356 		optlen += sizeof (struct T_opthdr) +
15357 		    sizeof (struct in6_pktinfo);
15358 		addflag |= TCP_IPV6_RECVPKTINFO;
15359 	}
15360 	/* If app asked for hoplimit and it has changed ... */
15361 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15362 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15363 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15364 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15365 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15366 	}
15367 	/* If app asked for tclass and it has changed ... */
15368 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15369 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15370 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15371 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15372 		addflag |= TCP_IPV6_RECVTCLASS;
15373 	}
15374 	/*
15375 	 * If app asked for hopbyhop headers and it has changed ...
15376 	 * For security labels, note that (1) security labels can't change on
15377 	 * a connected socket at all, (2) we're connected to at most one peer,
15378 	 * (3) if anything changes, then it must be some other extra option.
15379 	 */
15380 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15381 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15382 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15383 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15384 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15385 		    tcp->tcp_label_len;
15386 		addflag |= TCP_IPV6_RECVHOPOPTS;
15387 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15388 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15389 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15390 			return (mp);
15391 	}
15392 	/* If app asked for dst headers before routing headers ... */
15393 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15394 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15395 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15396 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15397 		optlen += sizeof (struct T_opthdr) +
15398 		    ipp->ipp_rtdstoptslen;
15399 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15400 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15401 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15402 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15403 			return (mp);
15404 	}
15405 	/* If app asked for routing headers and it has changed ... */
15406 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15407 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15408 	    (ipp->ipp_fields & IPPF_RTHDR),
15409 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15410 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15411 		addflag |= TCP_IPV6_RECVRTHDR;
15412 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15413 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15414 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15415 			return (mp);
15416 	}
15417 	/* If app asked for dest headers and it has changed ... */
15418 	if ((tcp->tcp_ipv6_recvancillary &
15419 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15420 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15421 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15422 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15423 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15424 		addflag |= TCP_IPV6_RECVDSTOPTS;
15425 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15426 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15427 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15428 			return (mp);
15429 	}
15430 
15431 	if (optlen == 0) {
15432 		/* Nothing to add */
15433 		return (mp);
15434 	}
15435 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15436 	if (mp1 == NULL) {
15437 		/*
15438 		 * Defer sending ancillary data until the next TCP segment
15439 		 * arrives.
15440 		 */
15441 		return (mp);
15442 	}
15443 	mp1->b_cont = mp;
15444 	mp = mp1;
15445 	mp->b_wptr += sizeof (*todi) + optlen;
15446 	mp->b_datap->db_type = M_PROTO;
15447 	todi = (struct T_optdata_ind *)mp->b_rptr;
15448 	todi->PRIM_type = T_OPTDATA_IND;
15449 	todi->DATA_flag = 1;	/* MORE data */
15450 	todi->OPT_length = optlen;
15451 	todi->OPT_offset = sizeof (*todi);
15452 	optptr = (uchar_t *)&todi[1];
15453 	/*
15454 	 * If app asked for pktinfo and the index has changed ...
15455 	 * Note that the local address never changes for the connection.
15456 	 */
15457 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15458 		struct in6_pktinfo *pkti;
15459 
15460 		toh = (struct T_opthdr *)optptr;
15461 		toh->level = IPPROTO_IPV6;
15462 		toh->name = IPV6_PKTINFO;
15463 		toh->len = sizeof (*toh) + sizeof (*pkti);
15464 		toh->status = 0;
15465 		optptr += sizeof (*toh);
15466 		pkti = (struct in6_pktinfo *)optptr;
15467 		if (tcp->tcp_ipversion == IPV6_VERSION)
15468 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15469 		else
15470 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15471 			    &pkti->ipi6_addr);
15472 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15473 		optptr += sizeof (*pkti);
15474 		ASSERT(OK_32PTR(optptr));
15475 		/* Save as "last" value */
15476 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15477 	}
15478 	/* If app asked for hoplimit and it has changed ... */
15479 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15480 		toh = (struct T_opthdr *)optptr;
15481 		toh->level = IPPROTO_IPV6;
15482 		toh->name = IPV6_HOPLIMIT;
15483 		toh->len = sizeof (*toh) + sizeof (uint_t);
15484 		toh->status = 0;
15485 		optptr += sizeof (*toh);
15486 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15487 		optptr += sizeof (uint_t);
15488 		ASSERT(OK_32PTR(optptr));
15489 		/* Save as "last" value */
15490 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15491 	}
15492 	/* If app asked for tclass and it has changed ... */
15493 	if (addflag & TCP_IPV6_RECVTCLASS) {
15494 		toh = (struct T_opthdr *)optptr;
15495 		toh->level = IPPROTO_IPV6;
15496 		toh->name = IPV6_TCLASS;
15497 		toh->len = sizeof (*toh) + sizeof (uint_t);
15498 		toh->status = 0;
15499 		optptr += sizeof (*toh);
15500 		*(uint_t *)optptr = ipp->ipp_tclass;
15501 		optptr += sizeof (uint_t);
15502 		ASSERT(OK_32PTR(optptr));
15503 		/* Save as "last" value */
15504 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15505 	}
15506 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15507 		toh = (struct T_opthdr *)optptr;
15508 		toh->level = IPPROTO_IPV6;
15509 		toh->name = IPV6_HOPOPTS;
15510 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15511 		    tcp->tcp_label_len;
15512 		toh->status = 0;
15513 		optptr += sizeof (*toh);
15514 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15515 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15516 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15517 		ASSERT(OK_32PTR(optptr));
15518 		/* Save as last value */
15519 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15520 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15521 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15522 	}
15523 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15524 		toh = (struct T_opthdr *)optptr;
15525 		toh->level = IPPROTO_IPV6;
15526 		toh->name = IPV6_RTHDRDSTOPTS;
15527 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15528 		toh->status = 0;
15529 		optptr += sizeof (*toh);
15530 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15531 		optptr += ipp->ipp_rtdstoptslen;
15532 		ASSERT(OK_32PTR(optptr));
15533 		/* Save as last value */
15534 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15535 		    &tcp->tcp_rtdstoptslen,
15536 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15537 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15538 	}
15539 	if (addflag & TCP_IPV6_RECVRTHDR) {
15540 		toh = (struct T_opthdr *)optptr;
15541 		toh->level = IPPROTO_IPV6;
15542 		toh->name = IPV6_RTHDR;
15543 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15544 		toh->status = 0;
15545 		optptr += sizeof (*toh);
15546 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15547 		optptr += ipp->ipp_rthdrlen;
15548 		ASSERT(OK_32PTR(optptr));
15549 		/* Save as last value */
15550 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15551 		    (ipp->ipp_fields & IPPF_RTHDR),
15552 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15553 	}
15554 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15555 		toh = (struct T_opthdr *)optptr;
15556 		toh->level = IPPROTO_IPV6;
15557 		toh->name = IPV6_DSTOPTS;
15558 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15559 		toh->status = 0;
15560 		optptr += sizeof (*toh);
15561 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15562 		optptr += ipp->ipp_dstoptslen;
15563 		ASSERT(OK_32PTR(optptr));
15564 		/* Save as last value */
15565 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15566 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15567 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15568 	}
15569 	ASSERT(optptr == mp->b_wptr);
15570 	return (mp);
15571 }
15572 
15573 /*
15574  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15575  * messages.
15576  */
15577 void
15578 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15579 {
15580 	uchar_t	*rptr = mp->b_rptr;
15581 	queue_t	*q = tcp->tcp_rq;
15582 	struct T_error_ack *tea;
15583 
15584 	switch (mp->b_datap->db_type) {
15585 	case M_PROTO:
15586 	case M_PCPROTO:
15587 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15588 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15589 			break;
15590 		tea = (struct T_error_ack *)rptr;
15591 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15592 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15593 		    tea->ERROR_prim != T_BIND_REQ);
15594 		switch (tea->PRIM_type) {
15595 		case T_ERROR_ACK:
15596 			if (tcp->tcp_debug) {
15597 				(void) strlog(TCP_MOD_ID, 0, 1,
15598 				    SL_TRACE|SL_ERROR,
15599 				    "tcp_rput_other: case T_ERROR_ACK, "
15600 				    "ERROR_prim == %d",
15601 				    tea->ERROR_prim);
15602 			}
15603 			switch (tea->ERROR_prim) {
15604 			case T_SVR4_OPTMGMT_REQ:
15605 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15606 					/* T_OPTMGMT_REQ generated by TCP */
15607 					printf("T_SVR4_OPTMGMT_REQ failed "
15608 					    "%d/%d - dropped (cnt %d)\n",
15609 					    tea->TLI_error, tea->UNIX_error,
15610 					    tcp->tcp_drop_opt_ack_cnt);
15611 					freemsg(mp);
15612 					tcp->tcp_drop_opt_ack_cnt--;
15613 					return;
15614 				}
15615 				break;
15616 			}
15617 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15618 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15619 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15620 				    "- dropped (cnt %d)\n",
15621 				    tea->TLI_error, tea->UNIX_error,
15622 				    tcp->tcp_drop_opt_ack_cnt);
15623 				freemsg(mp);
15624 				tcp->tcp_drop_opt_ack_cnt--;
15625 				return;
15626 			}
15627 			break;
15628 		case T_OPTMGMT_ACK:
15629 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15630 				/* T_OPTMGMT_REQ generated by TCP */
15631 				freemsg(mp);
15632 				tcp->tcp_drop_opt_ack_cnt--;
15633 				return;
15634 			}
15635 			break;
15636 		default:
15637 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15638 			break;
15639 		}
15640 		break;
15641 	case M_FLUSH:
15642 		if (*rptr & FLUSHR)
15643 			flushq(q, FLUSHDATA);
15644 		break;
15645 	default:
15646 		/* M_CTL will be directly sent to tcp_icmp_error() */
15647 		ASSERT(DB_TYPE(mp) != M_CTL);
15648 		break;
15649 	}
15650 	/*
15651 	 * Make sure we set this bit before sending the ACK for
15652 	 * bind. Otherwise accept could possibly run and free
15653 	 * this tcp struct.
15654 	 */
15655 	ASSERT(q != NULL);
15656 	putnext(q, mp);
15657 }
15658 
15659 /* ARGSUSED */
15660 static void
15661 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15662 {
15663 	conn_t	*connp = (conn_t *)arg;
15664 	tcp_t	*tcp = connp->conn_tcp;
15665 	queue_t	*q = tcp->tcp_rq;
15666 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15667 
15668 	ASSERT(!IPCL_IS_NONSTR(connp));
15669 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15670 	tcp->tcp_rsrv_mp = mp;
15671 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15672 
15673 	TCP_STAT(tcps, tcp_rsrv_calls);
15674 
15675 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15676 		return;
15677 	}
15678 
15679 	if (tcp->tcp_fused) {
15680 		tcp_fuse_backenable(tcp);
15681 		return;
15682 	}
15683 
15684 	if (canputnext(q)) {
15685 		/* Not flow-controlled, open rwnd */
15686 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
15687 
15688 		/*
15689 		 * Send back a window update immediately if TCP is above
15690 		 * ESTABLISHED state and the increase of the rcv window
15691 		 * that the other side knows is at least 1 MSS after flow
15692 		 * control is lifted.
15693 		 */
15694 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15695 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
15696 			tcp_xmit_ctl(NULL, tcp,
15697 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15698 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15699 		}
15700 	}
15701 }
15702 
15703 /*
15704  * The read side service routine is called mostly when we get back-enabled as a
15705  * result of flow control relief.  Since we don't actually queue anything in
15706  * TCP, we have no data to send out of here.  What we do is clear the receive
15707  * window, and send out a window update.
15708  */
15709 static void
15710 tcp_rsrv(queue_t *q)
15711 {
15712 	conn_t		*connp = Q_TO_CONN(q);
15713 	tcp_t		*tcp = connp->conn_tcp;
15714 	mblk_t		*mp;
15715 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15716 
15717 	/* No code does a putq on the read side */
15718 	ASSERT(q->q_first == NULL);
15719 
15720 	/* Nothing to do for the default queue */
15721 	if (q == tcps->tcps_g_q) {
15722 		return;
15723 	}
15724 
15725 	/*
15726 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15727 	 * been run.  So just return.
15728 	 */
15729 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15730 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15731 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15732 		return;
15733 	}
15734 	tcp->tcp_rsrv_mp = NULL;
15735 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15736 
15737 	CONN_INC_REF(connp);
15738 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15739 	    SQ_PROCESS, SQTAG_TCP_RSRV);
15740 }
15741 
15742 /*
15743  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15744  * We do not allow the receive window to shrink.  After setting rwnd,
15745  * set the flow control hiwat of the stream.
15746  *
15747  * This function is called in 2 cases:
15748  *
15749  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15750  *    connection (passive open) and in tcp_rput_data() for active connect.
15751  *    This is called after tcp_mss_set() when the desired MSS value is known.
15752  *    This makes sure that our window size is a mutiple of the other side's
15753  *    MSS.
15754  * 2) Handling SO_RCVBUF option.
15755  *
15756  * It is ASSUMED that the requested size is a multiple of the current MSS.
15757  *
15758  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15759  * user requests so.
15760  */
15761 int
15762 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15763 {
15764 	uint32_t	mss = tcp->tcp_mss;
15765 	uint32_t	old_max_rwnd;
15766 	uint32_t	max_transmittable_rwnd;
15767 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15768 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15769 
15770 	/*
15771 	 * Insist on a receive window that is at least
15772 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15773 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15774 	 * and delayed acknowledgement.
15775 	 */
15776 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
15777 
15778 	if (tcp->tcp_fused) {
15779 		size_t sth_hiwat;
15780 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15781 
15782 		ASSERT(peer_tcp != NULL);
15783 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15784 		if (!tcp_detached) {
15785 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15786 			    sth_hiwat);
15787 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
15788 		}
15789 
15790 		/*
15791 		 * In the fusion case, the maxpsz stream head value of
15792 		 * our peer is set according to its send buffer size
15793 		 * and our receive buffer size; since the latter may
15794 		 * have changed we need to update the peer's maxpsz.
15795 		 */
15796 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15797 		return (sth_hiwat);
15798 	}
15799 
15800 	if (tcp_detached) {
15801 		old_max_rwnd = tcp->tcp_rwnd;
15802 	} else {
15803 		old_max_rwnd = tcp->tcp_recv_hiwater;
15804 	}
15805 
15806 
15807 	/*
15808 	 * If window size info has already been exchanged, TCP should not
15809 	 * shrink the window.  Shrinking window is doable if done carefully.
15810 	 * We may add that support later.  But so far there is not a real
15811 	 * need to do that.
15812 	 */
15813 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15814 		/* MSS may have changed, do a round up again. */
15815 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15816 	}
15817 
15818 	/*
15819 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15820 	 * can be applied even before the window scale option is decided.
15821 	 */
15822 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15823 	if (rwnd > max_transmittable_rwnd) {
15824 		rwnd = max_transmittable_rwnd -
15825 		    (max_transmittable_rwnd % mss);
15826 		if (rwnd < mss)
15827 			rwnd = max_transmittable_rwnd;
15828 		/*
15829 		 * If we're over the limit we may have to back down tcp_rwnd.
15830 		 * The increment below won't work for us. So we set all three
15831 		 * here and the increment below will have no effect.
15832 		 */
15833 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15834 	}
15835 	if (tcp->tcp_localnet) {
15836 		tcp->tcp_rack_abs_max =
15837 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
15838 	} else {
15839 		/*
15840 		 * For a remote host on a different subnet (through a router),
15841 		 * we ack every other packet to be conforming to RFC1122.
15842 		 * tcp_deferred_acks_max is default to 2.
15843 		 */
15844 		tcp->tcp_rack_abs_max =
15845 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
15846 	}
15847 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15848 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15849 	else
15850 		tcp->tcp_rack_cur_max = 0;
15851 	/*
15852 	 * Increment the current rwnd by the amount the maximum grew (we
15853 	 * can not overwrite it since we might be in the middle of a
15854 	 * connection.)
15855 	 */
15856 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15857 	tcp->tcp_recv_hiwater = rwnd;
15858 
15859 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15860 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15861 		tcp->tcp_cwnd_max = rwnd;
15862 
15863 	if (tcp_detached)
15864 		return (rwnd);
15865 
15866 	tcp_set_recv_threshold(tcp, rwnd >> 3);
15867 
15868 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp, rwnd);
15869 	return (rwnd);
15870 }
15871 
15872 /*
15873  * Return SNMP stuff in buffer in mpdata.
15874  */
15875 mblk_t *
15876 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15877 {
15878 	mblk_t			*mpdata;
15879 	mblk_t			*mp_conn_ctl = NULL;
15880 	mblk_t			*mp_conn_tail;
15881 	mblk_t			*mp_attr_ctl = NULL;
15882 	mblk_t			*mp_attr_tail;
15883 	mblk_t			*mp6_conn_ctl = NULL;
15884 	mblk_t			*mp6_conn_tail;
15885 	mblk_t			*mp6_attr_ctl = NULL;
15886 	mblk_t			*mp6_attr_tail;
15887 	struct opthdr		*optp;
15888 	mib2_tcpConnEntry_t	tce;
15889 	mib2_tcp6ConnEntry_t	tce6;
15890 	mib2_transportMLPEntry_t mlp;
15891 	connf_t			*connfp;
15892 	int			i;
15893 	boolean_t 		ispriv;
15894 	zoneid_t 		zoneid;
15895 	int			v4_conn_idx;
15896 	int			v6_conn_idx;
15897 	conn_t			*connp = Q_TO_CONN(q);
15898 	tcp_stack_t		*tcps;
15899 	ip_stack_t		*ipst;
15900 	mblk_t			*mp2ctl;
15901 
15902 	/*
15903 	 * make a copy of the original message
15904 	 */
15905 	mp2ctl = copymsg(mpctl);
15906 
15907 	if (mpctl == NULL ||
15908 	    (mpdata = mpctl->b_cont) == NULL ||
15909 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15910 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
15911 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
15912 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
15913 		freemsg(mp_conn_ctl);
15914 		freemsg(mp_attr_ctl);
15915 		freemsg(mp6_conn_ctl);
15916 		freemsg(mp6_attr_ctl);
15917 		freemsg(mpctl);
15918 		freemsg(mp2ctl);
15919 		return (NULL);
15920 	}
15921 
15922 	ipst = connp->conn_netstack->netstack_ip;
15923 	tcps = connp->conn_netstack->netstack_tcp;
15924 
15925 	/* build table of connections -- need count in fixed part */
15926 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
15927 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
15928 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
15929 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
15930 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
15931 
15932 	ispriv =
15933 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15934 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15935 
15936 	v4_conn_idx = v6_conn_idx = 0;
15937 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
15938 
15939 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15940 		ipst = tcps->tcps_netstack->netstack_ip;
15941 
15942 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
15943 
15944 		connp = NULL;
15945 
15946 		while ((connp =
15947 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15948 			tcp_t *tcp;
15949 			boolean_t needattr;
15950 
15951 			if (connp->conn_zoneid != zoneid)
15952 				continue;	/* not in this zone */
15953 
15954 			tcp = connp->conn_tcp;
15955 			UPDATE_MIB(&tcps->tcps_mib,
15956 			    tcpHCInSegs, tcp->tcp_ibsegs);
15957 			tcp->tcp_ibsegs = 0;
15958 			UPDATE_MIB(&tcps->tcps_mib,
15959 			    tcpHCOutSegs, tcp->tcp_obsegs);
15960 			tcp->tcp_obsegs = 0;
15961 
15962 			tce6.tcp6ConnState = tce.tcpConnState =
15963 			    tcp_snmp_state(tcp);
15964 			if (tce.tcpConnState == MIB2_TCP_established ||
15965 			    tce.tcpConnState == MIB2_TCP_closeWait)
15966 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
15967 
15968 			needattr = B_FALSE;
15969 			bzero(&mlp, sizeof (mlp));
15970 			if (connp->conn_mlp_type != mlptSingle) {
15971 				if (connp->conn_mlp_type == mlptShared ||
15972 				    connp->conn_mlp_type == mlptBoth)
15973 					mlp.tme_flags |= MIB2_TMEF_SHARED;
15974 				if (connp->conn_mlp_type == mlptPrivate ||
15975 				    connp->conn_mlp_type == mlptBoth)
15976 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
15977 				needattr = B_TRUE;
15978 			}
15979 			if (connp->conn_anon_mlp) {
15980 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
15981 				needattr = B_TRUE;
15982 			}
15983 			switch (connp->conn_mac_mode) {
15984 			case CONN_MAC_DEFAULT:
15985 				break;
15986 			case CONN_MAC_AWARE:
15987 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
15988 				needattr = B_TRUE;
15989 				break;
15990 			case CONN_MAC_IMPLICIT:
15991 				mlp.tme_flags |= MIB2_TMEF_MACIMPLICIT;
15992 				needattr = B_TRUE;
15993 				break;
15994 			}
15995 			if (connp->conn_fully_bound &&
15996 			    connp->conn_effective_cred != NULL) {
15997 				ts_label_t *tsl;
15998 
15999 				tsl = crgetlabel(connp->conn_effective_cred);
16000 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
16001 				mlp.tme_doi = label2doi(tsl);
16002 				mlp.tme_label = *label2bslabel(tsl);
16003 				needattr = B_TRUE;
16004 			}
16005 
16006 			/* Create a message to report on IPv6 entries */
16007 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16008 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16009 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16010 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16011 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16012 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16013 			/* Don't want just anybody seeing these... */
16014 			if (ispriv) {
16015 				tce6.tcp6ConnEntryInfo.ce_snxt =
16016 				    tcp->tcp_snxt;
16017 				tce6.tcp6ConnEntryInfo.ce_suna =
16018 				    tcp->tcp_suna;
16019 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16020 				    tcp->tcp_rnxt;
16021 				tce6.tcp6ConnEntryInfo.ce_rack =
16022 				    tcp->tcp_rack;
16023 			} else {
16024 				/*
16025 				 * Netstat, unfortunately, uses this to
16026 				 * get send/receive queue sizes.  How to fix?
16027 				 * Why not compute the difference only?
16028 				 */
16029 				tce6.tcp6ConnEntryInfo.ce_snxt =
16030 				    tcp->tcp_snxt - tcp->tcp_suna;
16031 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16032 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16033 				    tcp->tcp_rnxt - tcp->tcp_rack;
16034 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16035 			}
16036 
16037 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16038 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16039 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16040 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16041 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16042 
16043 			tce6.tcp6ConnCreationProcess =
16044 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16045 			    tcp->tcp_cpid;
16046 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16047 
16048 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16049 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16050 
16051 			mlp.tme_connidx = v6_conn_idx++;
16052 			if (needattr)
16053 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16054 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16055 			}
16056 			/*
16057 			 * Create an IPv4 table entry for IPv4 entries and also
16058 			 * for IPv6 entries which are bound to in6addr_any
16059 			 * but don't have IPV6_V6ONLY set.
16060 			 * (i.e. anything an IPv4 peer could connect to)
16061 			 */
16062 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16063 			    (tcp->tcp_state <= TCPS_LISTEN &&
16064 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16065 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16066 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16067 					tce.tcpConnRemAddress = INADDR_ANY;
16068 					tce.tcpConnLocalAddress = INADDR_ANY;
16069 				} else {
16070 					tce.tcpConnRemAddress =
16071 					    tcp->tcp_remote;
16072 					tce.tcpConnLocalAddress =
16073 					    tcp->tcp_ip_src;
16074 				}
16075 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16076 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16077 				/* Don't want just anybody seeing these... */
16078 				if (ispriv) {
16079 					tce.tcpConnEntryInfo.ce_snxt =
16080 					    tcp->tcp_snxt;
16081 					tce.tcpConnEntryInfo.ce_suna =
16082 					    tcp->tcp_suna;
16083 					tce.tcpConnEntryInfo.ce_rnxt =
16084 					    tcp->tcp_rnxt;
16085 					tce.tcpConnEntryInfo.ce_rack =
16086 					    tcp->tcp_rack;
16087 				} else {
16088 					/*
16089 					 * Netstat, unfortunately, uses this to
16090 					 * get send/receive queue sizes.  How
16091 					 * to fix?
16092 					 * Why not compute the difference only?
16093 					 */
16094 					tce.tcpConnEntryInfo.ce_snxt =
16095 					    tcp->tcp_snxt - tcp->tcp_suna;
16096 					tce.tcpConnEntryInfo.ce_suna = 0;
16097 					tce.tcpConnEntryInfo.ce_rnxt =
16098 					    tcp->tcp_rnxt - tcp->tcp_rack;
16099 					tce.tcpConnEntryInfo.ce_rack = 0;
16100 				}
16101 
16102 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16103 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16104 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16105 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16106 				tce.tcpConnEntryInfo.ce_state =
16107 				    tcp->tcp_state;
16108 
16109 				tce.tcpConnCreationProcess =
16110 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16111 				    tcp->tcp_cpid;
16112 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16113 
16114 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16115 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16116 
16117 				mlp.tme_connidx = v4_conn_idx++;
16118 				if (needattr)
16119 					(void) snmp_append_data2(
16120 					    mp_attr_ctl->b_cont,
16121 					    &mp_attr_tail, (char *)&mlp,
16122 					    sizeof (mlp));
16123 			}
16124 		}
16125 	}
16126 
16127 	/* fixed length structure for IPv4 and IPv6 counters */
16128 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16129 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16130 	    sizeof (mib2_tcp6ConnEntry_t));
16131 	/* synchronize 32- and 64-bit counters */
16132 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16133 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16134 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16135 	optp->level = MIB2_TCP;
16136 	optp->name = 0;
16137 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16138 	    sizeof (tcps->tcps_mib));
16139 	optp->len = msgdsize(mpdata);
16140 	qreply(q, mpctl);
16141 
16142 	/* table of connections... */
16143 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16144 	    sizeof (struct T_optmgmt_ack)];
16145 	optp->level = MIB2_TCP;
16146 	optp->name = MIB2_TCP_CONN;
16147 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16148 	qreply(q, mp_conn_ctl);
16149 
16150 	/* table of MLP attributes... */
16151 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16152 	    sizeof (struct T_optmgmt_ack)];
16153 	optp->level = MIB2_TCP;
16154 	optp->name = EXPER_XPORT_MLP;
16155 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16156 	if (optp->len == 0)
16157 		freemsg(mp_attr_ctl);
16158 	else
16159 		qreply(q, mp_attr_ctl);
16160 
16161 	/* table of IPv6 connections... */
16162 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16163 	    sizeof (struct T_optmgmt_ack)];
16164 	optp->level = MIB2_TCP6;
16165 	optp->name = MIB2_TCP6_CONN;
16166 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16167 	qreply(q, mp6_conn_ctl);
16168 
16169 	/* table of IPv6 MLP attributes... */
16170 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16171 	    sizeof (struct T_optmgmt_ack)];
16172 	optp->level = MIB2_TCP6;
16173 	optp->name = EXPER_XPORT_MLP;
16174 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16175 	if (optp->len == 0)
16176 		freemsg(mp6_attr_ctl);
16177 	else
16178 		qreply(q, mp6_attr_ctl);
16179 	return (mp2ctl);
16180 }
16181 
16182 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16183 /* ARGSUSED */
16184 int
16185 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16186 {
16187 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16188 
16189 	switch (level) {
16190 	case MIB2_TCP:
16191 		switch (name) {
16192 		case 13:
16193 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16194 				return (0);
16195 			/* TODO: delete entry defined by tce */
16196 			return (1);
16197 		default:
16198 			return (0);
16199 		}
16200 	default:
16201 		return (1);
16202 	}
16203 }
16204 
16205 /* Translate TCP state to MIB2 TCP state. */
16206 static int
16207 tcp_snmp_state(tcp_t *tcp)
16208 {
16209 	if (tcp == NULL)
16210 		return (0);
16211 
16212 	switch (tcp->tcp_state) {
16213 	case TCPS_CLOSED:
16214 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16215 	case TCPS_BOUND:
16216 		return (MIB2_TCP_closed);
16217 	case TCPS_LISTEN:
16218 		return (MIB2_TCP_listen);
16219 	case TCPS_SYN_SENT:
16220 		return (MIB2_TCP_synSent);
16221 	case TCPS_SYN_RCVD:
16222 		return (MIB2_TCP_synReceived);
16223 	case TCPS_ESTABLISHED:
16224 		return (MIB2_TCP_established);
16225 	case TCPS_CLOSE_WAIT:
16226 		return (MIB2_TCP_closeWait);
16227 	case TCPS_FIN_WAIT_1:
16228 		return (MIB2_TCP_finWait1);
16229 	case TCPS_CLOSING:
16230 		return (MIB2_TCP_closing);
16231 	case TCPS_LAST_ACK:
16232 		return (MIB2_TCP_lastAck);
16233 	case TCPS_FIN_WAIT_2:
16234 		return (MIB2_TCP_finWait2);
16235 	case TCPS_TIME_WAIT:
16236 		return (MIB2_TCP_timeWait);
16237 	default:
16238 		return (0);
16239 	}
16240 }
16241 
16242 /*
16243  * tcp_timer is the timer service routine.  It handles the retransmission,
16244  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16245  * from the state of the tcp instance what kind of action needs to be done
16246  * at the time it is called.
16247  */
16248 static void
16249 tcp_timer(void *arg)
16250 {
16251 	mblk_t		*mp;
16252 	clock_t		first_threshold;
16253 	clock_t		second_threshold;
16254 	clock_t		ms;
16255 	uint32_t	mss;
16256 	conn_t		*connp = (conn_t *)arg;
16257 	tcp_t		*tcp = connp->conn_tcp;
16258 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16259 
16260 	tcp->tcp_timer_tid = 0;
16261 
16262 	if (tcp->tcp_fused)
16263 		return;
16264 
16265 	first_threshold =  tcp->tcp_first_timer_threshold;
16266 	second_threshold = tcp->tcp_second_timer_threshold;
16267 	switch (tcp->tcp_state) {
16268 	case TCPS_IDLE:
16269 	case TCPS_BOUND:
16270 	case TCPS_LISTEN:
16271 		return;
16272 	case TCPS_SYN_RCVD: {
16273 		tcp_t	*listener = tcp->tcp_listener;
16274 
16275 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16276 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16277 			/* it's our first timeout */
16278 			tcp->tcp_syn_rcvd_timeout = 1;
16279 			mutex_enter(&listener->tcp_eager_lock);
16280 			listener->tcp_syn_rcvd_timeout++;
16281 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16282 				/*
16283 				 * Make this eager available for drop if we
16284 				 * need to drop one to accomodate a new
16285 				 * incoming SYN request.
16286 				 */
16287 				MAKE_DROPPABLE(listener, tcp);
16288 			}
16289 			if (!listener->tcp_syn_defense &&
16290 			    (listener->tcp_syn_rcvd_timeout >
16291 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16292 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16293 				/* We may be under attack. Put on a defense. */
16294 				listener->tcp_syn_defense = B_TRUE;
16295 				cmn_err(CE_WARN, "High TCP connect timeout "
16296 				    "rate! System (port %d) may be under a "
16297 				    "SYN flood attack!",
16298 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16299 
16300 				listener->tcp_ip_addr_cache = kmem_zalloc(
16301 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16302 				    KM_NOSLEEP);
16303 			}
16304 			mutex_exit(&listener->tcp_eager_lock);
16305 		} else if (listener != NULL) {
16306 			mutex_enter(&listener->tcp_eager_lock);
16307 			tcp->tcp_syn_rcvd_timeout++;
16308 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16309 			    !tcp->tcp_closemp_used) {
16310 				/*
16311 				 * This is our second timeout. Put the tcp in
16312 				 * the list of droppable eagers to allow it to
16313 				 * be dropped, if needed. We don't check
16314 				 * whether tcp_dontdrop is set or not to
16315 				 * protect ourselve from a SYN attack where a
16316 				 * remote host can spoof itself as one of the
16317 				 * good IP source and continue to hold
16318 				 * resources too long.
16319 				 */
16320 				MAKE_DROPPABLE(listener, tcp);
16321 			}
16322 			mutex_exit(&listener->tcp_eager_lock);
16323 		}
16324 	}
16325 		/* FALLTHRU */
16326 	case TCPS_SYN_SENT:
16327 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16328 		second_threshold = tcp->tcp_second_ctimer_threshold;
16329 		break;
16330 	case TCPS_ESTABLISHED:
16331 	case TCPS_FIN_WAIT_1:
16332 	case TCPS_CLOSING:
16333 	case TCPS_CLOSE_WAIT:
16334 	case TCPS_LAST_ACK:
16335 		/* If we have data to rexmit */
16336 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16337 			clock_t	time_to_wait;
16338 
16339 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16340 			if (!tcp->tcp_xmit_head)
16341 				break;
16342 			time_to_wait = lbolt -
16343 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16344 			time_to_wait = tcp->tcp_rto -
16345 			    TICK_TO_MSEC(time_to_wait);
16346 			/*
16347 			 * If the timer fires too early, 1 clock tick earlier,
16348 			 * restart the timer.
16349 			 */
16350 			if (time_to_wait > msec_per_tick) {
16351 				TCP_STAT(tcps, tcp_timer_fire_early);
16352 				TCP_TIMER_RESTART(tcp, time_to_wait);
16353 				return;
16354 			}
16355 			/*
16356 			 * When we probe zero windows, we force the swnd open.
16357 			 * If our peer acks with a closed window swnd will be
16358 			 * set to zero by tcp_rput(). As long as we are
16359 			 * receiving acks tcp_rput will
16360 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16361 			 * first and second interval actions.  NOTE: the timer
16362 			 * interval is allowed to continue its exponential
16363 			 * backoff.
16364 			 */
16365 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16366 				if (tcp->tcp_debug) {
16367 					(void) strlog(TCP_MOD_ID, 0, 1,
16368 					    SL_TRACE, "tcp_timer: zero win");
16369 				}
16370 			} else {
16371 				/*
16372 				 * After retransmission, we need to do
16373 				 * slow start.  Set the ssthresh to one
16374 				 * half of current effective window and
16375 				 * cwnd to one MSS.  Also reset
16376 				 * tcp_cwnd_cnt.
16377 				 *
16378 				 * Note that if tcp_ssthresh is reduced because
16379 				 * of ECN, do not reduce it again unless it is
16380 				 * already one window of data away (tcp_cwr
16381 				 * should then be cleared) or this is a
16382 				 * timeout for a retransmitted segment.
16383 				 */
16384 				uint32_t npkt;
16385 
16386 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16387 					npkt = ((tcp->tcp_timer_backoff ?
16388 					    tcp->tcp_cwnd_ssthresh :
16389 					    tcp->tcp_snxt -
16390 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16391 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16392 					    tcp->tcp_mss;
16393 				}
16394 				tcp->tcp_cwnd = tcp->tcp_mss;
16395 				tcp->tcp_cwnd_cnt = 0;
16396 				if (tcp->tcp_ecn_ok) {
16397 					tcp->tcp_cwr = B_TRUE;
16398 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16399 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16400 				}
16401 			}
16402 			break;
16403 		}
16404 		/*
16405 		 * We have something to send yet we cannot send.  The
16406 		 * reason can be:
16407 		 *
16408 		 * 1. Zero send window: we need to do zero window probe.
16409 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16410 		 * segments.
16411 		 * 3. SWS avoidance: receiver may have shrunk window,
16412 		 * reset our knowledge.
16413 		 *
16414 		 * Note that condition 2 can happen with either 1 or
16415 		 * 3.  But 1 and 3 are exclusive.
16416 		 */
16417 		if (tcp->tcp_unsent != 0) {
16418 			if (tcp->tcp_cwnd == 0) {
16419 				/*
16420 				 * Set tcp_cwnd to 1 MSS so that a
16421 				 * new segment can be sent out.  We
16422 				 * are "clocking out" new data when
16423 				 * the network is really congested.
16424 				 */
16425 				ASSERT(tcp->tcp_ecn_ok);
16426 				tcp->tcp_cwnd = tcp->tcp_mss;
16427 			}
16428 			if (tcp->tcp_swnd == 0) {
16429 				/* Extend window for zero window probe */
16430 				tcp->tcp_swnd++;
16431 				tcp->tcp_zero_win_probe = B_TRUE;
16432 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
16433 			} else {
16434 				/*
16435 				 * Handle timeout from sender SWS avoidance.
16436 				 * Reset our knowledge of the max send window
16437 				 * since the receiver might have reduced its
16438 				 * receive buffer.  Avoid setting tcp_max_swnd
16439 				 * to one since that will essentially disable
16440 				 * the SWS checks.
16441 				 *
16442 				 * Note that since we don't have a SWS
16443 				 * state variable, if the timeout is set
16444 				 * for ECN but not for SWS, this
16445 				 * code will also be executed.  This is
16446 				 * fine as tcp_max_swnd is updated
16447 				 * constantly and it will not affect
16448 				 * anything.
16449 				 */
16450 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16451 			}
16452 			tcp_wput_data(tcp, NULL, B_FALSE);
16453 			return;
16454 		}
16455 		/* Is there a FIN that needs to be to re retransmitted? */
16456 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16457 		    !tcp->tcp_fin_acked)
16458 			break;
16459 		/* Nothing to do, return without restarting timer. */
16460 		TCP_STAT(tcps, tcp_timer_fire_miss);
16461 		return;
16462 	case TCPS_FIN_WAIT_2:
16463 		/*
16464 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16465 		 * We waited some time for for peer's FIN, but it hasn't
16466 		 * arrived.  We flush the connection now to avoid
16467 		 * case where the peer has rebooted.
16468 		 */
16469 		if (TCP_IS_DETACHED(tcp)) {
16470 			(void) tcp_clean_death(tcp, 0, 23);
16471 		} else {
16472 			TCP_TIMER_RESTART(tcp,
16473 			    tcps->tcps_fin_wait_2_flush_interval);
16474 		}
16475 		return;
16476 	case TCPS_TIME_WAIT:
16477 		(void) tcp_clean_death(tcp, 0, 24);
16478 		return;
16479 	default:
16480 		if (tcp->tcp_debug) {
16481 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16482 			    "tcp_timer: strange state (%d) %s",
16483 			    tcp->tcp_state, tcp_display(tcp, NULL,
16484 			    DISP_PORT_ONLY));
16485 		}
16486 		return;
16487 	}
16488 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16489 		/*
16490 		 * For zero window probe, we need to send indefinitely,
16491 		 * unless we have not heard from the other side for some
16492 		 * time...
16493 		 */
16494 		if ((tcp->tcp_zero_win_probe == 0) ||
16495 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16496 		    second_threshold)) {
16497 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
16498 			/*
16499 			 * If TCP is in SYN_RCVD state, send back a
16500 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16501 			 * should be zero in TCPS_SYN_RCVD state.
16502 			 */
16503 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16504 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16505 				    "in SYN_RCVD",
16506 				    tcp, tcp->tcp_snxt,
16507 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16508 			}
16509 			(void) tcp_clean_death(tcp,
16510 			    tcp->tcp_client_errno ?
16511 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16512 			return;
16513 		} else {
16514 			/*
16515 			 * Set tcp_ms_we_have_waited to second_threshold
16516 			 * so that in next timeout, we will do the above
16517 			 * check (lbolt - tcp_last_recv_time).  This is
16518 			 * also to avoid overflow.
16519 			 *
16520 			 * We don't need to decrement tcp_timer_backoff
16521 			 * to avoid overflow because it will be decremented
16522 			 * later if new timeout value is greater than
16523 			 * tcp_rexmit_interval_max.  In the case when
16524 			 * tcp_rexmit_interval_max is greater than
16525 			 * second_threshold, it means that we will wait
16526 			 * longer than second_threshold to send the next
16527 			 * window probe.
16528 			 */
16529 			tcp->tcp_ms_we_have_waited = second_threshold;
16530 		}
16531 	} else if (ms > first_threshold) {
16532 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16533 		    tcp->tcp_xmit_head != NULL) {
16534 			tcp->tcp_xmit_head =
16535 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16536 		}
16537 		/*
16538 		 * We have been retransmitting for too long...  The RTT
16539 		 * we calculated is probably incorrect.  Reinitialize it.
16540 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16541 		 * tcp_rtt_update so that we won't accidentally cache a
16542 		 * bad value.  But only do this if this is not a zero
16543 		 * window probe.
16544 		 */
16545 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16546 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16547 			    (tcp->tcp_rtt_sa >> 5);
16548 			tcp->tcp_rtt_sa = 0;
16549 			tcp_ip_notify(tcp);
16550 			tcp->tcp_rtt_update = 0;
16551 		}
16552 	}
16553 	tcp->tcp_timer_backoff++;
16554 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16555 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16556 	    tcps->tcps_rexmit_interval_min) {
16557 		/*
16558 		 * This means the original RTO is tcp_rexmit_interval_min.
16559 		 * So we will use tcp_rexmit_interval_min as the RTO value
16560 		 * and do the backoff.
16561 		 */
16562 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
16563 	} else {
16564 		ms <<= tcp->tcp_timer_backoff;
16565 	}
16566 	if (ms > tcps->tcps_rexmit_interval_max) {
16567 		ms = tcps->tcps_rexmit_interval_max;
16568 		/*
16569 		 * ms is at max, decrement tcp_timer_backoff to avoid
16570 		 * overflow.
16571 		 */
16572 		tcp->tcp_timer_backoff--;
16573 	}
16574 	tcp->tcp_ms_we_have_waited += ms;
16575 	if (tcp->tcp_zero_win_probe == 0) {
16576 		tcp->tcp_rto = ms;
16577 	}
16578 	TCP_TIMER_RESTART(tcp, ms);
16579 	/*
16580 	 * This is after a timeout and tcp_rto is backed off.  Set
16581 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16582 	 * restart the timer with a correct value.
16583 	 */
16584 	tcp->tcp_set_timer = 1;
16585 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16586 	if (mss > tcp->tcp_mss)
16587 		mss = tcp->tcp_mss;
16588 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16589 		mss = tcp->tcp_swnd;
16590 
16591 	if ((mp = tcp->tcp_xmit_head) != NULL)
16592 		mp->b_prev = (mblk_t *)lbolt;
16593 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16594 	    B_TRUE);
16595 
16596 	/*
16597 	 * When slow start after retransmission begins, start with
16598 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16599 	 * start phase.  tcp_snd_burst controls how many segments
16600 	 * can be sent because of an ack.
16601 	 */
16602 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16603 	tcp->tcp_snd_burst = TCP_CWND_SS;
16604 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16605 	    (tcp->tcp_unsent == 0)) {
16606 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16607 	} else {
16608 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16609 	}
16610 	tcp->tcp_rexmit = B_TRUE;
16611 	tcp->tcp_dupack_cnt = 0;
16612 
16613 	/*
16614 	 * Remove all rexmit SACK blk to start from fresh.
16615 	 */
16616 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
16617 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
16618 	if (mp == NULL) {
16619 		return;
16620 	}
16621 	/*
16622 	 * Attach credentials to retransmitted initial SYNs.
16623 	 * In theory we should use the credentials from the connect()
16624 	 * call to ensure that getpeerucred() on the peer will be correct.
16625 	 * But we assume that SYN's are not dropped for loopback connections.
16626 	 */
16627 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16628 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp), tcp->tcp_cpid);
16629 	}
16630 
16631 	tcp->tcp_csuna = tcp->tcp_snxt;
16632 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
16633 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
16634 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16635 
16636 }
16637 
16638 static int
16639 tcp_do_unbind(conn_t *connp)
16640 {
16641 	tcp_t *tcp = connp->conn_tcp;
16642 	int error = 0;
16643 
16644 	switch (tcp->tcp_state) {
16645 	case TCPS_BOUND:
16646 	case TCPS_LISTEN:
16647 		break;
16648 	default:
16649 		return (-TOUTSTATE);
16650 	}
16651 
16652 	/*
16653 	 * Need to clean up all the eagers since after the unbind, segments
16654 	 * will no longer be delivered to this listener stream.
16655 	 */
16656 	mutex_enter(&tcp->tcp_eager_lock);
16657 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16658 		tcp_eager_cleanup(tcp, 0);
16659 	}
16660 	mutex_exit(&tcp->tcp_eager_lock);
16661 
16662 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16663 		tcp->tcp_ipha->ipha_src = 0;
16664 	} else {
16665 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16666 	}
16667 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16668 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16669 	tcp_bind_hash_remove(tcp);
16670 	tcp->tcp_state = TCPS_IDLE;
16671 	tcp->tcp_mdt = B_FALSE;
16672 
16673 	connp = tcp->tcp_connp;
16674 	connp->conn_mdt_ok = B_FALSE;
16675 	ipcl_hash_remove(connp);
16676 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16677 
16678 	return (error);
16679 }
16680 
16681 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16682 static void
16683 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
16684 {
16685 	int error = tcp_do_unbind(tcp->tcp_connp);
16686 
16687 	if (error > 0) {
16688 		tcp_err_ack(tcp, mp, TSYSERR, error);
16689 	} else if (error < 0) {
16690 		tcp_err_ack(tcp, mp, -error, 0);
16691 	} else {
16692 		/* Send M_FLUSH according to TPI */
16693 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16694 
16695 		mp = mi_tpi_ok_ack_alloc(mp);
16696 		putnext(tcp->tcp_rq, mp);
16697 	}
16698 }
16699 
16700 /*
16701  * Don't let port fall into the privileged range.
16702  * Since the extra privileged ports can be arbitrary we also
16703  * ensure that we exclude those from consideration.
16704  * tcp_g_epriv_ports is not sorted thus we loop over it until
16705  * there are no changes.
16706  *
16707  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16708  * but instead the code relies on:
16709  * - the fact that the address of the array and its size never changes
16710  * - the atomic assignment of the elements of the array
16711  *
16712  * Returns 0 if there are no more ports available.
16713  *
16714  * TS note: skip multilevel ports.
16715  */
16716 static in_port_t
16717 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16718 {
16719 	int i;
16720 	boolean_t restart = B_FALSE;
16721 	tcp_stack_t *tcps = tcp->tcp_tcps;
16722 
16723 	if (random && tcp_random_anon_port != 0) {
16724 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16725 		    sizeof (in_port_t));
16726 		/*
16727 		 * Unless changed by a sys admin, the smallest anon port
16728 		 * is 32768 and the largest anon port is 65535.  It is
16729 		 * very likely (50%) for the random port to be smaller
16730 		 * than the smallest anon port.  When that happens,
16731 		 * add port % (anon port range) to the smallest anon
16732 		 * port to get the random port.  It should fall into the
16733 		 * valid anon port range.
16734 		 */
16735 		if (port < tcps->tcps_smallest_anon_port) {
16736 			port = tcps->tcps_smallest_anon_port +
16737 			    port % (tcps->tcps_largest_anon_port -
16738 			    tcps->tcps_smallest_anon_port);
16739 		}
16740 	}
16741 
16742 retry:
16743 	if (port < tcps->tcps_smallest_anon_port)
16744 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16745 
16746 	if (port > tcps->tcps_largest_anon_port) {
16747 		if (restart)
16748 			return (0);
16749 		restart = B_TRUE;
16750 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16751 	}
16752 
16753 	if (port < tcps->tcps_smallest_nonpriv_port)
16754 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
16755 
16756 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
16757 		if (port == tcps->tcps_g_epriv_ports[i]) {
16758 			port++;
16759 			/*
16760 			 * Make sure whether the port is in the
16761 			 * valid range.
16762 			 */
16763 			goto retry;
16764 		}
16765 	}
16766 	if (is_system_labeled() &&
16767 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
16768 	    IPPROTO_TCP, B_TRUE)) != 0) {
16769 		port = i;
16770 		goto retry;
16771 	}
16772 	return (port);
16773 }
16774 
16775 /*
16776  * Return the next anonymous port in the privileged port range for
16777  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16778  * downwards.  This is the same behavior as documented in the userland
16779  * library call rresvport(3N).
16780  *
16781  * TS note: skip multilevel ports.
16782  */
16783 static in_port_t
16784 tcp_get_next_priv_port(const tcp_t *tcp)
16785 {
16786 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16787 	in_port_t nextport;
16788 	boolean_t restart = B_FALSE;
16789 	tcp_stack_t *tcps = tcp->tcp_tcps;
16790 retry:
16791 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
16792 	    next_priv_port >= IPPORT_RESERVED) {
16793 		next_priv_port = IPPORT_RESERVED - 1;
16794 		if (restart)
16795 			return (0);
16796 		restart = B_TRUE;
16797 	}
16798 	if (is_system_labeled() &&
16799 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
16800 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
16801 		next_priv_port = nextport;
16802 		goto retry;
16803 	}
16804 	return (next_priv_port--);
16805 }
16806 
16807 /* The write side r/w procedure. */
16808 
16809 #if CCS_STATS
16810 struct {
16811 	struct {
16812 		int64_t count, bytes;
16813 	} tot, hit;
16814 } wrw_stats;
16815 #endif
16816 
16817 /*
16818  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16819  * messages.
16820  */
16821 /* ARGSUSED */
16822 static void
16823 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16824 {
16825 	conn_t	*connp = (conn_t *)arg;
16826 	tcp_t	*tcp = connp->conn_tcp;
16827 	queue_t	*q = tcp->tcp_wq;
16828 
16829 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16830 	/*
16831 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16832 	 * Once the close starts, streamhead and sockfs will not let any data
16833 	 * packets come down (close ensures that there are no threads using the
16834 	 * queue and no new threads will come down) but since qprocsoff()
16835 	 * hasn't happened yet, a M_FLUSH or some non data message might
16836 	 * get reflected back (in response to our own FLUSHRW) and get
16837 	 * processed after tcp_close() is done. The conn would still be valid
16838 	 * because a ref would have added but we need to check the state
16839 	 * before actually processing the packet.
16840 	 */
16841 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16842 		freemsg(mp);
16843 		return;
16844 	}
16845 
16846 	switch (DB_TYPE(mp)) {
16847 	case M_IOCDATA:
16848 		tcp_wput_iocdata(tcp, mp);
16849 		break;
16850 	case M_FLUSH:
16851 		tcp_wput_flush(tcp, mp);
16852 		break;
16853 	default:
16854 		CALL_IP_WPUT(connp, q, mp);
16855 		break;
16856 	}
16857 }
16858 
16859 /*
16860  * The TCP fast path write put procedure.
16861  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16862  */
16863 /* ARGSUSED */
16864 void
16865 tcp_output(void *arg, mblk_t *mp, void *arg2)
16866 {
16867 	int		len;
16868 	int		hdrlen;
16869 	int		plen;
16870 	mblk_t		*mp1;
16871 	uchar_t		*rptr;
16872 	uint32_t	snxt;
16873 	tcph_t		*tcph;
16874 	struct datab	*db;
16875 	uint32_t	suna;
16876 	uint32_t	mss;
16877 	ipaddr_t	*dst;
16878 	ipaddr_t	*src;
16879 	uint32_t	sum;
16880 	int		usable;
16881 	conn_t		*connp = (conn_t *)arg;
16882 	tcp_t		*tcp = connp->conn_tcp;
16883 	uint32_t	msize;
16884 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16885 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
16886 
16887 	/*
16888 	 * Try and ASSERT the minimum possible references on the
16889 	 * conn early enough. Since we are executing on write side,
16890 	 * the connection is obviously not detached and that means
16891 	 * there is a ref each for TCP and IP. Since we are behind
16892 	 * the squeue, the minimum references needed are 3. If the
16893 	 * conn is in classifier hash list, there should be an
16894 	 * extra ref for that (we check both the possibilities).
16895 	 */
16896 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16897 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16898 
16899 	ASSERT(DB_TYPE(mp) == M_DATA);
16900 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
16901 
16902 	mutex_enter(&tcp->tcp_non_sq_lock);
16903 	tcp->tcp_squeue_bytes -= msize;
16904 	mutex_exit(&tcp->tcp_non_sq_lock);
16905 
16906 	/* Check to see if this connection wants to be re-fused. */
16907 	if (tcp->tcp_refuse) {
16908 		if (tcp->tcp_ipversion == IPV4_VERSION &&
16909 		    !ipst->ips_ip4_observe.he_interested) {
16910 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
16911 			    &tcp->tcp_saved_tcph);
16912 		} else if (tcp->tcp_ipversion == IPV6_VERSION &&
16913 		    !ipst->ips_ip6_observe.he_interested) {
16914 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
16915 			    &tcp->tcp_saved_tcph);
16916 		}
16917 	}
16918 	/* Bypass tcp protocol for fused tcp loopback */
16919 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
16920 		return;
16921 
16922 	mss = tcp->tcp_mss;
16923 	if (tcp->tcp_xmit_zc_clean)
16924 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16925 
16926 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16927 	len = (int)(mp->b_wptr - mp->b_rptr);
16928 
16929 	/*
16930 	 * Criteria for fast path:
16931 	 *
16932 	 *   1. no unsent data
16933 	 *   2. single mblk in request
16934 	 *   3. connection established
16935 	 *   4. data in mblk
16936 	 *   5. len <= mss
16937 	 *   6. no tcp_valid bits
16938 	 */
16939 	if ((tcp->tcp_unsent != 0) ||
16940 	    (tcp->tcp_cork) ||
16941 	    (mp->b_cont != NULL) ||
16942 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16943 	    (len == 0) ||
16944 	    (len > mss) ||
16945 	    (tcp->tcp_valid_bits != 0)) {
16946 		tcp_wput_data(tcp, mp, B_FALSE);
16947 		return;
16948 	}
16949 
16950 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16951 	ASSERT(tcp->tcp_fin_sent == 0);
16952 
16953 	/* queue new packet onto retransmission queue */
16954 	if (tcp->tcp_xmit_head == NULL) {
16955 		tcp->tcp_xmit_head = mp;
16956 	} else {
16957 		tcp->tcp_xmit_last->b_cont = mp;
16958 	}
16959 	tcp->tcp_xmit_last = mp;
16960 	tcp->tcp_xmit_tail = mp;
16961 
16962 	/* find out how much we can send */
16963 	/* BEGIN CSTYLED */
16964 	/*
16965 	 *    un-acked	   usable
16966 	 *  |--------------|-----------------|
16967 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
16968 	 */
16969 	/* END CSTYLED */
16970 
16971 	/* start sending from tcp_snxt */
16972 	snxt = tcp->tcp_snxt;
16973 
16974 	/*
16975 	 * Check to see if this connection has been idled for some
16976 	 * time and no ACK is expected.  If it is, we need to slow
16977 	 * start again to get back the connection's "self-clock" as
16978 	 * described in VJ's paper.
16979 	 *
16980 	 * Refer to the comment in tcp_mss_set() for the calculation
16981 	 * of tcp_cwnd after idle.
16982 	 */
16983 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16984 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16985 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
16986 	}
16987 
16988 	usable = tcp->tcp_swnd;		/* tcp window size */
16989 	if (usable > tcp->tcp_cwnd)
16990 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16991 	usable -= snxt;		/* subtract stuff already sent */
16992 	suna = tcp->tcp_suna;
16993 	usable += suna;
16994 	/* usable can be < 0 if the congestion window is smaller */
16995 	if (len > usable) {
16996 		/* Can't send complete M_DATA in one shot */
16997 		goto slow;
16998 	}
16999 
17000 	mutex_enter(&tcp->tcp_non_sq_lock);
17001 	if (tcp->tcp_flow_stopped &&
17002 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17003 		tcp_clrqfull(tcp);
17004 	}
17005 	mutex_exit(&tcp->tcp_non_sq_lock);
17006 
17007 	/*
17008 	 * determine if anything to send (Nagle).
17009 	 *
17010 	 *   1. len < tcp_mss (i.e. small)
17011 	 *   2. unacknowledged data present
17012 	 *   3. len < nagle limit
17013 	 *   4. last packet sent < nagle limit (previous packet sent)
17014 	 */
17015 	if ((len < mss) && (snxt != suna) &&
17016 	    (len < (int)tcp->tcp_naglim) &&
17017 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17018 		/*
17019 		 * This was the first unsent packet and normally
17020 		 * mss < xmit_hiwater so there is no need to worry
17021 		 * about flow control. The next packet will go
17022 		 * through the flow control check in tcp_wput_data().
17023 		 */
17024 		/* leftover work from above */
17025 		tcp->tcp_unsent = len;
17026 		tcp->tcp_xmit_tail_unsent = len;
17027 
17028 		return;
17029 	}
17030 
17031 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17032 
17033 	if (snxt == suna) {
17034 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17035 	}
17036 
17037 	/* we have always sent something */
17038 	tcp->tcp_rack_cnt = 0;
17039 
17040 	tcp->tcp_snxt = snxt + len;
17041 	tcp->tcp_rack = tcp->tcp_rnxt;
17042 
17043 	if ((mp1 = dupb(mp)) == 0)
17044 		goto no_memory;
17045 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17046 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17047 
17048 	/* adjust tcp header information */
17049 	tcph = tcp->tcp_tcph;
17050 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17051 
17052 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17053 	sum = (sum >> 16) + (sum & 0xFFFF);
17054 	U16_TO_ABE16(sum, tcph->th_sum);
17055 
17056 	U32_TO_ABE32(snxt, tcph->th_seq);
17057 
17058 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17059 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17060 	BUMP_LOCAL(tcp->tcp_obsegs);
17061 
17062 	/* Update the latest receive window size in TCP header. */
17063 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17064 	    tcph->th_win);
17065 
17066 	tcp->tcp_last_sent_len = (ushort_t)len;
17067 
17068 	plen = len + tcp->tcp_hdr_len;
17069 
17070 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17071 		tcp->tcp_ipha->ipha_length = htons(plen);
17072 	} else {
17073 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17074 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17075 	}
17076 
17077 	/* see if we need to allocate a mblk for the headers */
17078 	hdrlen = tcp->tcp_hdr_len;
17079 	rptr = mp1->b_rptr - hdrlen;
17080 	db = mp1->b_datap;
17081 	if ((db->db_ref != 2) || rptr < db->db_base ||
17082 	    (!OK_32PTR(rptr))) {
17083 		/* NOTE: we assume allocb returns an OK_32PTR */
17084 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17085 		    tcps->tcps_wroff_xtra, BPRI_MED);
17086 		if (!mp) {
17087 			freemsg(mp1);
17088 			goto no_memory;
17089 		}
17090 		mp->b_cont = mp1;
17091 		mp1 = mp;
17092 		/* Leave room for Link Level header */
17093 		/* hdrlen = tcp->tcp_hdr_len; */
17094 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17095 		mp1->b_wptr = &rptr[hdrlen];
17096 	}
17097 	mp1->b_rptr = rptr;
17098 
17099 	/* Fill in the timestamp option. */
17100 	if (tcp->tcp_snd_ts_ok) {
17101 		U32_TO_BE32((uint32_t)lbolt,
17102 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17103 		U32_TO_BE32(tcp->tcp_ts_recent,
17104 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17105 	} else {
17106 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17107 	}
17108 
17109 	/* copy header into outgoing packet */
17110 	dst = (ipaddr_t *)rptr;
17111 	src = (ipaddr_t *)tcp->tcp_iphc;
17112 	dst[0] = src[0];
17113 	dst[1] = src[1];
17114 	dst[2] = src[2];
17115 	dst[3] = src[3];
17116 	dst[4] = src[4];
17117 	dst[5] = src[5];
17118 	dst[6] = src[6];
17119 	dst[7] = src[7];
17120 	dst[8] = src[8];
17121 	dst[9] = src[9];
17122 	if (hdrlen -= 40) {
17123 		hdrlen >>= 2;
17124 		dst += 10;
17125 		src += 10;
17126 		do {
17127 			*dst++ = *src++;
17128 		} while (--hdrlen);
17129 	}
17130 
17131 	/*
17132 	 * Set the ECN info in the TCP header.  Note that this
17133 	 * is not the template header.
17134 	 */
17135 	if (tcp->tcp_ecn_ok) {
17136 		SET_ECT(tcp, rptr);
17137 
17138 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17139 		if (tcp->tcp_ecn_echo_on)
17140 			tcph->th_flags[0] |= TH_ECE;
17141 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17142 			tcph->th_flags[0] |= TH_CWR;
17143 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17144 		}
17145 	}
17146 
17147 	if (tcp->tcp_ip_forward_progress) {
17148 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17149 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17150 		tcp->tcp_ip_forward_progress = B_FALSE;
17151 	}
17152 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17153 	return;
17154 
17155 	/*
17156 	 * If we ran out of memory, we pretend to have sent the packet
17157 	 * and that it was lost on the wire.
17158 	 */
17159 no_memory:
17160 	return;
17161 
17162 slow:
17163 	/* leftover work from above */
17164 	tcp->tcp_unsent = len;
17165 	tcp->tcp_xmit_tail_unsent = len;
17166 	tcp_wput_data(tcp, NULL, B_FALSE);
17167 }
17168 
17169 /* ARGSUSED */
17170 void
17171 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17172 {
17173 	conn_t			*connp = (conn_t *)arg;
17174 	tcp_t			*tcp = connp->conn_tcp;
17175 	queue_t			*q = tcp->tcp_rq;
17176 	struct tcp_options	*tcpopt;
17177 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17178 
17179 	/* socket options */
17180 	uint_t 			sopp_flags;
17181 	ssize_t			sopp_rxhiwat;
17182 	ssize_t			sopp_maxblk;
17183 	ushort_t		sopp_wroff;
17184 	ushort_t		sopp_tail;
17185 	ushort_t		sopp_copyopt;
17186 
17187 	tcpopt = (struct tcp_options *)mp->b_rptr;
17188 
17189 	/*
17190 	 * Drop the eager's ref on the listener, that was placed when
17191 	 * this eager began life in tcp_conn_request.
17192 	 */
17193 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17194 	if (IPCL_IS_NONSTR(connp)) {
17195 		/* Safe to free conn_ind message */
17196 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17197 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17198 	}
17199 
17200 	tcp->tcp_detached = B_FALSE;
17201 
17202 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17203 		/*
17204 		 * Someone blewoff the eager before we could finish
17205 		 * the accept.
17206 		 *
17207 		 * The only reason eager exists it because we put in
17208 		 * a ref on it when conn ind went up. We need to send
17209 		 * a disconnect indication up while the last reference
17210 		 * on the eager will be dropped by the squeue when we
17211 		 * return.
17212 		 */
17213 		ASSERT(tcp->tcp_listener == NULL);
17214 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17215 			if (IPCL_IS_NONSTR(connp)) {
17216 				ASSERT(tcp->tcp_issocket);
17217 				(*connp->conn_upcalls->su_disconnected)(
17218 				    connp->conn_upper_handle, tcp->tcp_connid,
17219 				    ECONNREFUSED);
17220 				freemsg(mp);
17221 			} else {
17222 				struct	T_discon_ind	*tdi;
17223 
17224 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17225 				/*
17226 				 * Let us reuse the incoming mblk to avoid
17227 				 * memory allocation failure problems. We know
17228 				 * that the size of the incoming mblk i.e.
17229 				 * stroptions is greater than sizeof
17230 				 * T_discon_ind. So the reallocb below can't
17231 				 * fail.
17232 				 */
17233 				freemsg(mp->b_cont);
17234 				mp->b_cont = NULL;
17235 				ASSERT(DB_REF(mp) == 1);
17236 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17237 				    B_FALSE);
17238 				ASSERT(mp != NULL);
17239 				DB_TYPE(mp) = M_PROTO;
17240 				((union T_primitives *)mp->b_rptr)->type =
17241 				    T_DISCON_IND;
17242 				tdi = (struct T_discon_ind *)mp->b_rptr;
17243 				if (tcp->tcp_issocket) {
17244 					tdi->DISCON_reason = ECONNREFUSED;
17245 					tdi->SEQ_number = 0;
17246 				} else {
17247 					tdi->DISCON_reason = ENOPROTOOPT;
17248 					tdi->SEQ_number =
17249 					    tcp->tcp_conn_req_seqnum;
17250 				}
17251 				mp->b_wptr = mp->b_rptr +
17252 				    sizeof (struct T_discon_ind);
17253 				putnext(q, mp);
17254 				return;
17255 			}
17256 		}
17257 		if (tcp->tcp_hard_binding) {
17258 			tcp->tcp_hard_binding = B_FALSE;
17259 			tcp->tcp_hard_bound = B_TRUE;
17260 		}
17261 		return;
17262 	}
17263 
17264 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17265 		int boundif = tcpopt->to_boundif;
17266 		uint_t len = sizeof (int);
17267 
17268 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17269 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17270 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17271 	}
17272 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17273 		uint_t on = 1;
17274 		uint_t len = sizeof (uint_t);
17275 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17276 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17277 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17278 	}
17279 
17280 	/*
17281 	 * Set max window size (tcp_recv_hiwater) of the acceptor.
17282 	 */
17283 	if (tcp->tcp_rcv_list == NULL) {
17284 		/*
17285 		 * Recv queue is empty, tcp_rwnd should not have changed.
17286 		 * That means it should be equal to the listener's tcp_rwnd.
17287 		 */
17288 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17289 	} else {
17290 #ifdef DEBUG
17291 		mblk_t *tmp;
17292 		mblk_t	*mp1;
17293 		uint_t	cnt = 0;
17294 
17295 		mp1 = tcp->tcp_rcv_list;
17296 		while ((tmp = mp1) != NULL) {
17297 			mp1 = tmp->b_next;
17298 			cnt += msgdsize(tmp);
17299 		}
17300 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17301 #endif
17302 		/* There is some data, add them back to get the max. */
17303 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17304 	}
17305 	/*
17306 	 * This is the first time we run on the correct
17307 	 * queue after tcp_accept. So fix all the q parameters
17308 	 * here.
17309 	 */
17310 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17311 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17312 
17313 	sopp_rxhiwat = tcp->tcp_fused ?
17314 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17315 	    tcp->tcp_recv_hiwater;
17316 
17317 	/*
17318 	 * Determine what write offset value to use depending on SACK and
17319 	 * whether the endpoint is fused or not.
17320 	 */
17321 	if (tcp->tcp_fused) {
17322 		ASSERT(tcp->tcp_loopback);
17323 		ASSERT(tcp->tcp_loopback_peer != NULL);
17324 		/*
17325 		 * For fused tcp loopback, set the stream head's write
17326 		 * offset value to zero since we won't be needing any room
17327 		 * for TCP/IP headers.  This would also improve performance
17328 		 * since it would reduce the amount of work done by kmem.
17329 		 * Non-fused tcp loopback case is handled separately below.
17330 		 */
17331 		sopp_wroff = 0;
17332 		/*
17333 		 * Update the peer's transmit parameters according to
17334 		 * our recently calculated high water mark value.
17335 		 */
17336 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17337 	} else if (tcp->tcp_snd_sack_ok) {
17338 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17339 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17340 	} else {
17341 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17342 		    tcps->tcps_wroff_xtra);
17343 	}
17344 
17345 	/*
17346 	 * If this is endpoint is handling SSL, then reserve extra
17347 	 * offset and space at the end.
17348 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17349 	 * overriding the previous setting. The extra cost of signing and
17350 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17351 	 * instead of a single contiguous one by the stream head
17352 	 * largely outweighs the statistical reduction of ACKs, when
17353 	 * applicable. The peer will also save on decryption and verification
17354 	 * costs.
17355 	 */
17356 	if (tcp->tcp_kssl_ctx != NULL) {
17357 		sopp_wroff += SSL3_WROFFSET;
17358 
17359 		sopp_flags |= SOCKOPT_TAIL;
17360 		sopp_tail = SSL3_MAX_TAIL_LEN;
17361 
17362 		sopp_flags |= SOCKOPT_ZCOPY;
17363 		sopp_copyopt = ZCVMUNSAFE;
17364 
17365 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
17366 	}
17367 
17368 	/* Send the options up */
17369 	if (IPCL_IS_NONSTR(connp)) {
17370 		struct sock_proto_props sopp;
17371 
17372 		sopp.sopp_flags = sopp_flags;
17373 		sopp.sopp_wroff = sopp_wroff;
17374 		sopp.sopp_maxblk = sopp_maxblk;
17375 		sopp.sopp_rxhiwat = sopp_rxhiwat;
17376 		if (sopp_flags & SOCKOPT_TAIL) {
17377 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17378 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
17379 			sopp.sopp_tail = sopp_tail;
17380 			sopp.sopp_zcopyflag = sopp_copyopt;
17381 		}
17382 		if (tcp->tcp_loopback) {
17383 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
17384 			sopp.sopp_loopback = B_TRUE;
17385 		}
17386 		(*connp->conn_upcalls->su_set_proto_props)
17387 		    (connp->conn_upper_handle, &sopp);
17388 	} else {
17389 		struct stroptions *stropt;
17390 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17391 		if (stropt_mp == NULL) {
17392 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
17393 			return;
17394 		}
17395 		DB_TYPE(stropt_mp) = M_SETOPTS;
17396 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17397 		stropt_mp->b_wptr += sizeof (struct stroptions);
17398 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
17399 		stropt->so_hiwat = sopp_rxhiwat;
17400 		stropt->so_wroff = sopp_wroff;
17401 		stropt->so_maxblk = sopp_maxblk;
17402 
17403 		if (sopp_flags & SOCKOPT_TAIL) {
17404 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17405 
17406 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
17407 			stropt->so_tail = sopp_tail;
17408 			stropt->so_copyopt = sopp_copyopt;
17409 		}
17410 
17411 		/* Send the options up */
17412 		putnext(q, stropt_mp);
17413 	}
17414 
17415 	freemsg(mp);
17416 	/*
17417 	 * Pass up any data and/or a fin that has been received.
17418 	 *
17419 	 * Adjust receive window in case it had decreased
17420 	 * (because there is data <=> tcp_rcv_list != NULL)
17421 	 * while the connection was detached. Note that
17422 	 * in case the eager was flow-controlled, w/o this
17423 	 * code, the rwnd may never open up again!
17424 	 */
17425 	if (tcp->tcp_rcv_list != NULL) {
17426 		if (IPCL_IS_NONSTR(connp)) {
17427 			mblk_t *mp;
17428 			int space_left;
17429 			int error;
17430 			boolean_t push = B_TRUE;
17431 
17432 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
17433 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
17434 			    &push) >= 0) {
17435 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17436 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17437 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17438 					tcp_xmit_ctl(NULL,
17439 					    tcp, (tcp->tcp_swnd == 0) ?
17440 					    tcp->tcp_suna : tcp->tcp_snxt,
17441 					    tcp->tcp_rnxt, TH_ACK);
17442 				}
17443 			}
17444 			while ((mp = tcp->tcp_rcv_list) != NULL) {
17445 				push = B_TRUE;
17446 				tcp->tcp_rcv_list = mp->b_next;
17447 				mp->b_next = NULL;
17448 				space_left = (*connp->conn_upcalls->su_recv)
17449 				    (connp->conn_upper_handle, mp, msgdsize(mp),
17450 				    0, &error, &push);
17451 				if (space_left < 0) {
17452 					/*
17453 					 * We should never be in middle of a
17454 					 * fallback, the squeue guarantees that.
17455 					 */
17456 					ASSERT(error != EOPNOTSUPP);
17457 				}
17458 			}
17459 			tcp->tcp_rcv_last_head = NULL;
17460 			tcp->tcp_rcv_last_tail = NULL;
17461 			tcp->tcp_rcv_cnt = 0;
17462 		} else {
17463 			/* We drain directly in case of fused tcp loopback */
17464 
17465 			if (!tcp->tcp_fused && canputnext(q)) {
17466 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17467 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17468 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17469 					tcp_xmit_ctl(NULL,
17470 					    tcp, (tcp->tcp_swnd == 0) ?
17471 					    tcp->tcp_suna : tcp->tcp_snxt,
17472 					    tcp->tcp_rnxt, TH_ACK);
17473 				}
17474 			}
17475 
17476 			(void) tcp_rcv_drain(tcp);
17477 		}
17478 
17479 		/*
17480 		 * For fused tcp loopback, back-enable peer endpoint
17481 		 * if it's currently flow-controlled.
17482 		 */
17483 		if (tcp->tcp_fused) {
17484 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17485 
17486 			ASSERT(peer_tcp != NULL);
17487 			ASSERT(peer_tcp->tcp_fused);
17488 
17489 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
17490 			if (peer_tcp->tcp_flow_stopped) {
17491 				tcp_clrqfull(peer_tcp);
17492 				TCP_STAT(tcps, tcp_fusion_backenabled);
17493 			}
17494 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17495 		}
17496 	}
17497 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17498 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17499 		tcp->tcp_ordrel_done = B_TRUE;
17500 		if (IPCL_IS_NONSTR(connp)) {
17501 			ASSERT(tcp->tcp_ordrel_mp == NULL);
17502 			(*connp->conn_upcalls->su_opctl)(
17503 			    connp->conn_upper_handle,
17504 			    SOCK_OPCTL_SHUT_RECV, 0);
17505 		} else {
17506 			mp = tcp->tcp_ordrel_mp;
17507 			tcp->tcp_ordrel_mp = NULL;
17508 			putnext(q, mp);
17509 		}
17510 	}
17511 	if (tcp->tcp_hard_binding) {
17512 		tcp->tcp_hard_binding = B_FALSE;
17513 		tcp->tcp_hard_bound = B_TRUE;
17514 	}
17515 
17516 	if (tcp->tcp_ka_enabled) {
17517 		tcp->tcp_ka_last_intrvl = 0;
17518 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17519 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17520 	}
17521 
17522 	/*
17523 	 * At this point, eager is fully established and will
17524 	 * have the following references -
17525 	 *
17526 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17527 	 * 1 reference for the squeue which will be dropped by the squeue as
17528 	 *	soon as this function returns.
17529 	 * There will be 1 additonal reference for being in classifier
17530 	 *	hash list provided something bad hasn't happened.
17531 	 */
17532 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17533 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17534 }
17535 
17536 /*
17537  * The function called through squeue to get behind listener's perimeter to
17538  * send a deffered conn_ind.
17539  */
17540 /* ARGSUSED */
17541 void
17542 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17543 {
17544 	conn_t	*connp = (conn_t *)arg;
17545 	tcp_t *listener = connp->conn_tcp;
17546 	struct T_conn_ind *conn_ind;
17547 	tcp_t *tcp;
17548 
17549 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
17550 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17551 	    conn_ind->OPT_length);
17552 
17553 	if (listener->tcp_state != TCPS_LISTEN) {
17554 		/*
17555 		 * If listener has closed, it would have caused a
17556 		 * a cleanup/blowoff to happen for the eager, so
17557 		 * we don't need to do anything more.
17558 		 */
17559 		freemsg(mp);
17560 		return;
17561 	}
17562 
17563 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
17564 }
17565 
17566 /* ARGSUSED */
17567 static int
17568 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
17569 {
17570 	tcp_t *listener, *eager;
17571 	mblk_t *opt_mp;
17572 	struct tcp_options *tcpopt;
17573 
17574 	listener = lconnp->conn_tcp;
17575 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17576 	eager = econnp->conn_tcp;
17577 	ASSERT(eager->tcp_listener != NULL);
17578 
17579 	ASSERT(eager->tcp_rq != NULL);
17580 
17581 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
17582 	if (opt_mp == NULL) {
17583 		return (-TPROTO);
17584 	}
17585 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
17586 	eager->tcp_issocket = B_TRUE;
17587 
17588 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17589 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17590 	ASSERT(econnp->conn_netstack ==
17591 	    listener->tcp_connp->conn_netstack);
17592 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
17593 
17594 	/* Put the ref for IP */
17595 	CONN_INC_REF(econnp);
17596 
17597 	/*
17598 	 * We should have minimum of 3 references on the conn
17599 	 * at this point. One each for TCP and IP and one for
17600 	 * the T_conn_ind that was sent up when the 3-way handshake
17601 	 * completed. In the normal case we would also have another
17602 	 * reference (making a total of 4) for the conn being in the
17603 	 * classifier hash list. However the eager could have received
17604 	 * an RST subsequently and tcp_closei_local could have removed
17605 	 * the eager from the classifier hash list, hence we can't
17606 	 * assert that reference.
17607 	 */
17608 	ASSERT(econnp->conn_ref >= 3);
17609 
17610 	opt_mp->b_datap->db_type = M_SETOPTS;
17611 	opt_mp->b_wptr += sizeof (struct tcp_options);
17612 
17613 	/*
17614 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17615 	 * from listener to acceptor.
17616 	 */
17617 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
17618 	tcpopt->to_flags = 0;
17619 
17620 	if (listener->tcp_bound_if != 0) {
17621 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
17622 		tcpopt->to_boundif = listener->tcp_bound_if;
17623 	}
17624 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17625 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
17626 	}
17627 
17628 	mutex_enter(&listener->tcp_eager_lock);
17629 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17630 
17631 		tcp_t *tail;
17632 		tcp_t *tcp;
17633 		mblk_t *mp1;
17634 
17635 		tcp = listener->tcp_eager_prev_q0;
17636 		/*
17637 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
17638 		 * deferred T_conn_ind queue. We need to get to the head
17639 		 * of the queue in order to send up T_conn_ind the same
17640 		 * order as how the 3WHS is completed.
17641 		 */
17642 		while (tcp != listener) {
17643 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17644 			    !tcp->tcp_kssl_pending)
17645 				break;
17646 			else
17647 				tcp = tcp->tcp_eager_prev_q0;
17648 		}
17649 		/* None of the pending eagers can be sent up now */
17650 		if (tcp == listener)
17651 			goto no_more_eagers;
17652 
17653 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17654 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17655 		/* Move from q0 to q */
17656 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17657 		listener->tcp_conn_req_cnt_q0--;
17658 		listener->tcp_conn_req_cnt_q++;
17659 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17660 		    tcp->tcp_eager_prev_q0;
17661 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17662 		    tcp->tcp_eager_next_q0;
17663 		tcp->tcp_eager_prev_q0 = NULL;
17664 		tcp->tcp_eager_next_q0 = NULL;
17665 		tcp->tcp_conn_def_q0 = B_FALSE;
17666 
17667 		/* Make sure the tcp isn't in the list of droppables */
17668 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
17669 		    tcp->tcp_eager_prev_drop_q0 == NULL);
17670 
17671 		/*
17672 		 * Insert at end of the queue because sockfs sends
17673 		 * down T_CONN_RES in chronological order. Leaving
17674 		 * the older conn indications at front of the queue
17675 		 * helps reducing search time.
17676 		 */
17677 		tail = listener->tcp_eager_last_q;
17678 		if (tail != NULL) {
17679 			tail->tcp_eager_next_q = tcp;
17680 		} else {
17681 			listener->tcp_eager_next_q = tcp;
17682 		}
17683 		listener->tcp_eager_last_q = tcp;
17684 		tcp->tcp_eager_next_q = NULL;
17685 
17686 		/* Need to get inside the listener perimeter */
17687 		CONN_INC_REF(listener->tcp_connp);
17688 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
17689 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
17690 		    SQTAG_TCP_SEND_PENDING);
17691 	}
17692 no_more_eagers:
17693 	tcp_eager_unlink(eager);
17694 	mutex_exit(&listener->tcp_eager_lock);
17695 
17696 	/*
17697 	 * At this point, the eager is detached from the listener
17698 	 * but we still have an extra refs on eager (apart from the
17699 	 * usual tcp references). The ref was placed in tcp_rput_data
17700 	 * before sending the conn_ind in tcp_send_conn_ind.
17701 	 * The ref will be dropped in tcp_accept_finish().
17702 	 */
17703 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
17704 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
17705 	return (0);
17706 }
17707 
17708 int
17709 tcp_accept(sock_lower_handle_t lproto_handle,
17710     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
17711     cred_t *cr)
17712 {
17713 	conn_t *lconnp, *econnp;
17714 	tcp_t *listener, *eager;
17715 	tcp_stack_t	*tcps;
17716 
17717 	lconnp = (conn_t *)lproto_handle;
17718 	listener = lconnp->conn_tcp;
17719 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17720 	econnp = (conn_t *)eproto_handle;
17721 	eager = econnp->conn_tcp;
17722 	ASSERT(eager->tcp_listener != NULL);
17723 	tcps = eager->tcp_tcps;
17724 
17725 	/*
17726 	 * It is OK to manipulate these fields outside the eager's squeue
17727 	 * because they will not start being used until tcp_accept_finish
17728 	 * has been called.
17729 	 */
17730 	ASSERT(lconnp->conn_upper_handle != NULL);
17731 	ASSERT(econnp->conn_upper_handle == NULL);
17732 	econnp->conn_upper_handle = sock_handle;
17733 	econnp->conn_upcalls = lconnp->conn_upcalls;
17734 	ASSERT(IPCL_IS_NONSTR(econnp));
17735 	/*
17736 	 * Create helper stream if it is a non-TPI TCP connection.
17737 	 */
17738 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
17739 		ip1dbg(("tcp_accept: create of IP helper stream"
17740 		    " failed\n"));
17741 		return (EPROTO);
17742 	}
17743 	eager->tcp_rq = econnp->conn_rq;
17744 	eager->tcp_wq = econnp->conn_wq;
17745 
17746 	ASSERT(eager->tcp_rq != NULL);
17747 
17748 	return (tcp_accept_common(lconnp, econnp, cr));
17749 }
17750 
17751 
17752 /*
17753  * This is the STREAMS entry point for T_CONN_RES coming down on
17754  * Acceptor STREAM when  sockfs listener does accept processing.
17755  * Read the block comment on top of tcp_conn_request().
17756  */
17757 void
17758 tcp_tpi_accept(queue_t *q, mblk_t *mp)
17759 {
17760 	queue_t *rq = RD(q);
17761 	struct T_conn_res *conn_res;
17762 	tcp_t *eager;
17763 	tcp_t *listener;
17764 	struct T_ok_ack *ok;
17765 	t_scalar_t PRIM_type;
17766 	conn_t *econnp;
17767 	cred_t *cr;
17768 
17769 	ASSERT(DB_TYPE(mp) == M_PROTO);
17770 
17771 	/*
17772 	 * All Solaris components should pass a db_credp
17773 	 * for this TPI message, hence we ASSERT.
17774 	 * But in case there is some other M_PROTO that looks
17775 	 * like a TPI message sent by some other kernel
17776 	 * component, we check and return an error.
17777 	 */
17778 	cr = msg_getcred(mp, NULL);
17779 	ASSERT(cr != NULL);
17780 	if (cr == NULL) {
17781 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
17782 		if (mp != NULL)
17783 			putnext(rq, mp);
17784 		return;
17785 	}
17786 	conn_res = (struct T_conn_res *)mp->b_rptr;
17787 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17788 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17789 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17790 		if (mp != NULL)
17791 			putnext(rq, mp);
17792 		return;
17793 	}
17794 	switch (conn_res->PRIM_type) {
17795 	case O_T_CONN_RES:
17796 	case T_CONN_RES:
17797 		/*
17798 		 * We pass up an err ack if allocb fails. This will
17799 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17800 		 * tcp_eager_blowoff to be called. sockfs will then call
17801 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17802 		 * we need to do the allocb up here because we have to
17803 		 * make sure rq->q_qinfo->qi_qclose still points to the
17804 		 * correct function (tcp_tpi_close_accept) in case allocb
17805 		 * fails.
17806 		 */
17807 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17808 		    &eager, conn_res->OPT_length);
17809 		PRIM_type = conn_res->PRIM_type;
17810 		mp->b_datap->db_type = M_PCPROTO;
17811 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17812 		ok = (struct T_ok_ack *)mp->b_rptr;
17813 		ok->PRIM_type = T_OK_ACK;
17814 		ok->CORRECT_prim = PRIM_type;
17815 		econnp = eager->tcp_connp;
17816 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
17817 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
17818 		eager->tcp_rq = rq;
17819 		eager->tcp_wq = q;
17820 		rq->q_ptr = econnp;
17821 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
17822 		q->q_ptr = econnp;
17823 		q->q_qinfo = &tcp_winit;
17824 		listener = eager->tcp_listener;
17825 
17826 		if (tcp_accept_common(listener->tcp_connp,
17827 		    econnp, cr) < 0) {
17828 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17829 			if (mp != NULL)
17830 				putnext(rq, mp);
17831 			return;
17832 		}
17833 
17834 		/*
17835 		 * Send the new local address also up to sockfs. There
17836 		 * should already be enough space in the mp that came
17837 		 * down from soaccept().
17838 		 */
17839 		if (eager->tcp_family == AF_INET) {
17840 			sin_t *sin;
17841 
17842 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17843 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17844 			sin = (sin_t *)mp->b_wptr;
17845 			mp->b_wptr += sizeof (sin_t);
17846 			sin->sin_family = AF_INET;
17847 			sin->sin_port = eager->tcp_lport;
17848 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17849 		} else {
17850 			sin6_t *sin6;
17851 
17852 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17853 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17854 			sin6 = (sin6_t *)mp->b_wptr;
17855 			mp->b_wptr += sizeof (sin6_t);
17856 			sin6->sin6_family = AF_INET6;
17857 			sin6->sin6_port = eager->tcp_lport;
17858 			if (eager->tcp_ipversion == IPV4_VERSION) {
17859 				sin6->sin6_flowinfo = 0;
17860 				IN6_IPADDR_TO_V4MAPPED(
17861 				    eager->tcp_ipha->ipha_src,
17862 				    &sin6->sin6_addr);
17863 			} else {
17864 				ASSERT(eager->tcp_ip6h != NULL);
17865 				sin6->sin6_flowinfo =
17866 				    eager->tcp_ip6h->ip6_vcf &
17867 				    ~IPV6_VERS_AND_FLOW_MASK;
17868 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17869 			}
17870 			sin6->sin6_scope_id = 0;
17871 			sin6->__sin6_src_id = 0;
17872 		}
17873 
17874 		putnext(rq, mp);
17875 		return;
17876 	default:
17877 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17878 		if (mp != NULL)
17879 			putnext(rq, mp);
17880 		return;
17881 	}
17882 }
17883 
17884 static int
17885 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17886 {
17887 	sin_t *sin = (sin_t *)sa;
17888 	sin6_t *sin6 = (sin6_t *)sa;
17889 
17890 	switch (tcp->tcp_family) {
17891 	case AF_INET:
17892 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17893 
17894 		if (*salenp < sizeof (sin_t))
17895 			return (EINVAL);
17896 
17897 		*sin = sin_null;
17898 		sin->sin_family = AF_INET;
17899 		if (tcp->tcp_state >= TCPS_BOUND) {
17900 			sin->sin_port = tcp->tcp_lport;
17901 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
17902 		}
17903 		*salenp = sizeof (sin_t);
17904 		break;
17905 
17906 	case AF_INET6:
17907 		if (*salenp < sizeof (sin6_t))
17908 			return (EINVAL);
17909 
17910 		*sin6 = sin6_null;
17911 		sin6->sin6_family = AF_INET6;
17912 		if (tcp->tcp_state >= TCPS_BOUND) {
17913 			sin6->sin6_port = tcp->tcp_lport;
17914 			mutex_enter(&tcp->tcp_connp->conn_lock);
17915 			if (tcp->tcp_ipversion == IPV4_VERSION) {
17916 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
17917 				    &sin6->sin6_addr);
17918 			} else {
17919 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
17920 			}
17921 			mutex_exit(&tcp->tcp_connp->conn_lock);
17922 		}
17923 		*salenp = sizeof (sin6_t);
17924 		break;
17925 	}
17926 
17927 	return (0);
17928 }
17929 
17930 static int
17931 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17932 {
17933 	sin_t *sin = (sin_t *)sa;
17934 	sin6_t *sin6 = (sin6_t *)sa;
17935 
17936 	if (tcp->tcp_state < TCPS_SYN_RCVD)
17937 		return (ENOTCONN);
17938 
17939 	switch (tcp->tcp_family) {
17940 	case AF_INET:
17941 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17942 
17943 		if (*salenp < sizeof (sin_t))
17944 			return (EINVAL);
17945 
17946 		*sin = sin_null;
17947 		sin->sin_family = AF_INET;
17948 		sin->sin_port = tcp->tcp_fport;
17949 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
17950 		    sin->sin_addr.s_addr);
17951 		*salenp = sizeof (sin_t);
17952 		break;
17953 
17954 	case AF_INET6:
17955 		if (*salenp < sizeof (sin6_t))
17956 			return (EINVAL);
17957 
17958 		*sin6 = sin6_null;
17959 		sin6->sin6_family = AF_INET6;
17960 		sin6->sin6_port = tcp->tcp_fport;
17961 		sin6->sin6_addr = tcp->tcp_remote_v6;
17962 		mutex_enter(&tcp->tcp_connp->conn_lock);
17963 		if (tcp->tcp_ipversion == IPV6_VERSION) {
17964 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
17965 			    ~IPV6_VERS_AND_FLOW_MASK;
17966 		}
17967 		mutex_exit(&tcp->tcp_connp->conn_lock);
17968 		*salenp = sizeof (sin6_t);
17969 		break;
17970 	}
17971 
17972 	return (0);
17973 }
17974 
17975 /*
17976  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
17977  */
17978 static void
17979 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
17980 {
17981 	void	*data;
17982 	mblk_t	*datamp = mp->b_cont;
17983 	tcp_t	*tcp = Q_TO_TCP(q);
17984 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
17985 
17986 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
17987 		cmdp->cb_error = EPROTO;
17988 		qreply(q, mp);
17989 		return;
17990 	}
17991 
17992 	data = datamp->b_rptr;
17993 
17994 	switch (cmdp->cb_cmd) {
17995 	case TI_GETPEERNAME:
17996 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
17997 		break;
17998 	case TI_GETMYNAME:
17999 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
18000 		break;
18001 	default:
18002 		cmdp->cb_error = EINVAL;
18003 		break;
18004 	}
18005 
18006 	qreply(q, mp);
18007 }
18008 
18009 void
18010 tcp_wput(queue_t *q, mblk_t *mp)
18011 {
18012 	conn_t	*connp = Q_TO_CONN(q);
18013 	tcp_t	*tcp;
18014 	void (*output_proc)();
18015 	t_scalar_t type;
18016 	uchar_t *rptr;
18017 	struct iocblk	*iocp;
18018 	size_t size;
18019 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18020 
18021 	ASSERT(connp->conn_ref >= 2);
18022 
18023 	switch (DB_TYPE(mp)) {
18024 	case M_DATA:
18025 		tcp = connp->conn_tcp;
18026 		ASSERT(tcp != NULL);
18027 
18028 		size = msgdsize(mp);
18029 
18030 		mutex_enter(&tcp->tcp_non_sq_lock);
18031 		tcp->tcp_squeue_bytes += size;
18032 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18033 			tcp_setqfull(tcp);
18034 		}
18035 		mutex_exit(&tcp->tcp_non_sq_lock);
18036 
18037 		CONN_INC_REF(connp);
18038 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18039 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18040 		return;
18041 
18042 	case M_CMD:
18043 		tcp_wput_cmdblk(q, mp);
18044 		return;
18045 
18046 	case M_PROTO:
18047 	case M_PCPROTO:
18048 		/*
18049 		 * if it is a snmp message, don't get behind the squeue
18050 		 */
18051 		tcp = connp->conn_tcp;
18052 		rptr = mp->b_rptr;
18053 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18054 			type = ((union T_primitives *)rptr)->type;
18055 		} else {
18056 			if (tcp->tcp_debug) {
18057 				(void) strlog(TCP_MOD_ID, 0, 1,
18058 				    SL_ERROR|SL_TRACE,
18059 				    "tcp_wput_proto, dropping one...");
18060 			}
18061 			freemsg(mp);
18062 			return;
18063 		}
18064 		if (type == T_SVR4_OPTMGMT_REQ) {
18065 			/*
18066 			 * All Solaris components should pass a db_credp
18067 			 * for this TPI message, hence we ASSERT.
18068 			 * But in case there is some other M_PROTO that looks
18069 			 * like a TPI message sent by some other kernel
18070 			 * component, we check and return an error.
18071 			 */
18072 			cred_t	*cr = msg_getcred(mp, NULL);
18073 
18074 			ASSERT(cr != NULL);
18075 			if (cr == NULL) {
18076 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18077 				return;
18078 			}
18079 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18080 			    cr)) {
18081 				/*
18082 				 * This was a SNMP request
18083 				 */
18084 				return;
18085 			} else {
18086 				output_proc = tcp_wput_proto;
18087 			}
18088 		} else {
18089 			output_proc = tcp_wput_proto;
18090 		}
18091 		break;
18092 	case M_IOCTL:
18093 		/*
18094 		 * Most ioctls can be processed right away without going via
18095 		 * squeues - process them right here. Those that do require
18096 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18097 		 * are processed by tcp_wput_ioctl().
18098 		 */
18099 		iocp = (struct iocblk *)mp->b_rptr;
18100 		tcp = connp->conn_tcp;
18101 
18102 		switch (iocp->ioc_cmd) {
18103 		case TCP_IOC_ABORT_CONN:
18104 			tcp_ioctl_abort_conn(q, mp);
18105 			return;
18106 		case TI_GETPEERNAME:
18107 		case TI_GETMYNAME:
18108 			mi_copyin(q, mp, NULL,
18109 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18110 			return;
18111 		case ND_SET:
18112 			/* nd_getset does the necessary checks */
18113 		case ND_GET:
18114 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18115 				CALL_IP_WPUT(connp, q, mp);
18116 				return;
18117 			}
18118 			qreply(q, mp);
18119 			return;
18120 		case TCP_IOC_DEFAULT_Q:
18121 			/*
18122 			 * Wants to be the default wq. Check the credentials
18123 			 * first, the rest is executed via squeue.
18124 			 */
18125 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18126 				iocp->ioc_error = EPERM;
18127 				iocp->ioc_count = 0;
18128 				mp->b_datap->db_type = M_IOCACK;
18129 				qreply(q, mp);
18130 				return;
18131 			}
18132 			output_proc = tcp_wput_ioctl;
18133 			break;
18134 		default:
18135 			output_proc = tcp_wput_ioctl;
18136 			break;
18137 		}
18138 		break;
18139 	default:
18140 		output_proc = tcp_wput_nondata;
18141 		break;
18142 	}
18143 
18144 	CONN_INC_REF(connp);
18145 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18146 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18147 }
18148 
18149 /*
18150  * Initial STREAMS write side put() procedure for sockets. It tries to
18151  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18152  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18153  * are handled by tcp_wput() as usual.
18154  *
18155  * All further messages will also be handled by tcp_wput() because we cannot
18156  * be sure that the above short cut is safe later.
18157  */
18158 static void
18159 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18160 {
18161 	conn_t			*connp = Q_TO_CONN(wq);
18162 	tcp_t			*tcp = connp->conn_tcp;
18163 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18164 
18165 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18166 	wq->q_qinfo = &tcp_winit;
18167 
18168 	ASSERT(IPCL_IS_TCP(connp));
18169 	ASSERT(TCP_IS_SOCKET(tcp));
18170 
18171 	if (DB_TYPE(mp) == M_PCPROTO &&
18172 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18173 	    car->PRIM_type == T_CAPABILITY_REQ) {
18174 		tcp_capability_req(tcp, mp);
18175 		return;
18176 	}
18177 
18178 	tcp_wput(wq, mp);
18179 }
18180 
18181 /* ARGSUSED */
18182 static void
18183 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18184 {
18185 #ifdef DEBUG
18186 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18187 #endif
18188 	freemsg(mp);
18189 }
18190 
18191 static boolean_t
18192 tcp_zcopy_check(tcp_t *tcp)
18193 {
18194 	conn_t	*connp = tcp->tcp_connp;
18195 	ire_t	*ire;
18196 	boolean_t	zc_enabled = B_FALSE;
18197 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18198 
18199 	if (do_tcpzcopy == 2)
18200 		zc_enabled = B_TRUE;
18201 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18202 	    IPCL_IS_CONNECTED(connp) &&
18203 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18204 	    connp->conn_dontroute == 0 &&
18205 	    !connp->conn_nexthop_set &&
18206 	    connp->conn_outgoing_ill == NULL &&
18207 	    do_tcpzcopy == 1) {
18208 		/*
18209 		 * the checks above  closely resemble the fast path checks
18210 		 * in tcp_send_data().
18211 		 */
18212 		mutex_enter(&connp->conn_lock);
18213 		ire = connp->conn_ire_cache;
18214 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18215 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18216 			IRE_REFHOLD(ire);
18217 			if (ire->ire_stq != NULL) {
18218 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18219 
18220 				zc_enabled = ill && (ill->ill_capabilities &
18221 				    ILL_CAPAB_ZEROCOPY) &&
18222 				    (ill->ill_zerocopy_capab->
18223 				    ill_zerocopy_flags != 0);
18224 			}
18225 			IRE_REFRELE(ire);
18226 		}
18227 		mutex_exit(&connp->conn_lock);
18228 	}
18229 	tcp->tcp_snd_zcopy_on = zc_enabled;
18230 	if (!TCP_IS_DETACHED(tcp)) {
18231 		if (zc_enabled) {
18232 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18233 			    ZCVMSAFE);
18234 			TCP_STAT(tcps, tcp_zcopy_on);
18235 		} else {
18236 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18237 			    ZCVMUNSAFE);
18238 			TCP_STAT(tcps, tcp_zcopy_off);
18239 		}
18240 	}
18241 	return (zc_enabled);
18242 }
18243 
18244 static mblk_t *
18245 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18246 {
18247 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18248 
18249 	if (do_tcpzcopy == 2)
18250 		return (bp);
18251 	else if (tcp->tcp_snd_zcopy_on) {
18252 		tcp->tcp_snd_zcopy_on = B_FALSE;
18253 		if (!TCP_IS_DETACHED(tcp)) {
18254 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18255 			    ZCVMUNSAFE);
18256 			TCP_STAT(tcps, tcp_zcopy_disable);
18257 		}
18258 	}
18259 	return (tcp_zcopy_backoff(tcp, bp, 0));
18260 }
18261 
18262 /*
18263  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18264  * the original desballoca'ed segmapped mblk.
18265  */
18266 static mblk_t *
18267 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18268 {
18269 	mblk_t *head, *tail, *nbp;
18270 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18271 
18272 	if (IS_VMLOANED_MBLK(bp)) {
18273 		TCP_STAT(tcps, tcp_zcopy_backoff);
18274 		if ((head = copyb(bp)) == NULL) {
18275 			/* fail to backoff; leave it for the next backoff */
18276 			tcp->tcp_xmit_zc_clean = B_FALSE;
18277 			return (bp);
18278 		}
18279 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18280 			if (fix_xmitlist)
18281 				tcp_zcopy_notify(tcp);
18282 			else
18283 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18284 		}
18285 		nbp = bp->b_cont;
18286 		if (fix_xmitlist) {
18287 			head->b_prev = bp->b_prev;
18288 			head->b_next = bp->b_next;
18289 			if (tcp->tcp_xmit_tail == bp)
18290 				tcp->tcp_xmit_tail = head;
18291 		}
18292 		bp->b_next = NULL;
18293 		bp->b_prev = NULL;
18294 		freeb(bp);
18295 	} else {
18296 		head = bp;
18297 		nbp = bp->b_cont;
18298 	}
18299 	tail = head;
18300 	while (nbp) {
18301 		if (IS_VMLOANED_MBLK(nbp)) {
18302 			TCP_STAT(tcps, tcp_zcopy_backoff);
18303 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18304 				tcp->tcp_xmit_zc_clean = B_FALSE;
18305 				tail->b_cont = nbp;
18306 				return (head);
18307 			}
18308 			tail = tail->b_cont;
18309 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18310 				if (fix_xmitlist)
18311 					tcp_zcopy_notify(tcp);
18312 				else
18313 					tail->b_datap->db_struioflag |=
18314 					    STRUIO_ZCNOTIFY;
18315 			}
18316 			bp = nbp;
18317 			nbp = nbp->b_cont;
18318 			if (fix_xmitlist) {
18319 				tail->b_prev = bp->b_prev;
18320 				tail->b_next = bp->b_next;
18321 				if (tcp->tcp_xmit_tail == bp)
18322 					tcp->tcp_xmit_tail = tail;
18323 			}
18324 			bp->b_next = NULL;
18325 			bp->b_prev = NULL;
18326 			freeb(bp);
18327 		} else {
18328 			tail->b_cont = nbp;
18329 			tail = nbp;
18330 			nbp = nbp->b_cont;
18331 		}
18332 	}
18333 	if (fix_xmitlist) {
18334 		tcp->tcp_xmit_last = tail;
18335 		tcp->tcp_xmit_zc_clean = B_TRUE;
18336 	}
18337 	return (head);
18338 }
18339 
18340 static void
18341 tcp_zcopy_notify(tcp_t *tcp)
18342 {
18343 	struct stdata	*stp;
18344 	conn_t *connp;
18345 
18346 	if (tcp->tcp_detached)
18347 		return;
18348 	connp = tcp->tcp_connp;
18349 	if (IPCL_IS_NONSTR(connp)) {
18350 		(*connp->conn_upcalls->su_zcopy_notify)
18351 		    (connp->conn_upper_handle);
18352 		return;
18353 	}
18354 	stp = STREAM(tcp->tcp_rq);
18355 	mutex_enter(&stp->sd_lock);
18356 	stp->sd_flag |= STZCNOTIFY;
18357 	cv_broadcast(&stp->sd_zcopy_wait);
18358 	mutex_exit(&stp->sd_lock);
18359 }
18360 
18361 static boolean_t
18362 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18363 {
18364 	ire_t	*ire;
18365 	conn_t	*connp = tcp->tcp_connp;
18366 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18367 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18368 
18369 	mutex_enter(&connp->conn_lock);
18370 	ire = connp->conn_ire_cache;
18371 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18372 
18373 	if ((ire != NULL) &&
18374 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18375 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18376 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18377 		IRE_REFHOLD(ire);
18378 		mutex_exit(&connp->conn_lock);
18379 	} else {
18380 		boolean_t cached = B_FALSE;
18381 		ts_label_t *tsl;
18382 
18383 		/* force a recheck later on */
18384 		tcp->tcp_ire_ill_check_done = B_FALSE;
18385 
18386 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18387 		connp->conn_ire_cache = NULL;
18388 		mutex_exit(&connp->conn_lock);
18389 
18390 		if (ire != NULL)
18391 			IRE_REFRELE_NOTR(ire);
18392 
18393 		tsl = crgetlabel(CONN_CRED(connp));
18394 		ire = (dst ?
18395 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18396 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18397 		    connp->conn_zoneid, tsl, ipst));
18398 
18399 		if (ire == NULL) {
18400 			TCP_STAT(tcps, tcp_ire_null);
18401 			return (B_FALSE);
18402 		}
18403 
18404 		IRE_REFHOLD_NOTR(ire);
18405 
18406 		mutex_enter(&connp->conn_lock);
18407 		if (CONN_CACHE_IRE(connp)) {
18408 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18409 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18410 				TCP_CHECK_IREINFO(tcp, ire);
18411 				connp->conn_ire_cache = ire;
18412 				cached = B_TRUE;
18413 			}
18414 			rw_exit(&ire->ire_bucket->irb_lock);
18415 		}
18416 		mutex_exit(&connp->conn_lock);
18417 
18418 		/*
18419 		 * We can continue to use the ire but since it was
18420 		 * not cached, we should drop the extra reference.
18421 		 */
18422 		if (!cached)
18423 			IRE_REFRELE_NOTR(ire);
18424 
18425 		/*
18426 		 * Rampart note: no need to select a new label here, since
18427 		 * labels are not allowed to change during the life of a TCP
18428 		 * connection.
18429 		 */
18430 	}
18431 
18432 	*irep = ire;
18433 
18434 	return (B_TRUE);
18435 }
18436 
18437 /*
18438  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18439  *
18440  * 0 = success;
18441  * 1 = failed to find ire and ill.
18442  */
18443 static boolean_t
18444 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18445 {
18446 	ipha_t		*ipha;
18447 	ipaddr_t	dst;
18448 	ire_t		*ire;
18449 	ill_t		*ill;
18450 	mblk_t		*ire_fp_mp;
18451 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18452 
18453 	if (mp != NULL)
18454 		ipha = (ipha_t *)mp->b_rptr;
18455 	else
18456 		ipha = tcp->tcp_ipha;
18457 	dst = ipha->ipha_dst;
18458 
18459 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18460 		return (B_FALSE);
18461 
18462 	if ((ire->ire_flags & RTF_MULTIRT) ||
18463 	    (ire->ire_stq == NULL) ||
18464 	    (ire->ire_nce == NULL) ||
18465 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18466 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18467 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18468 		TCP_STAT(tcps, tcp_ip_ire_send);
18469 		IRE_REFRELE(ire);
18470 		return (B_FALSE);
18471 	}
18472 
18473 	ill = ire_to_ill(ire);
18474 	ASSERT(ill != NULL);
18475 
18476 	if (!tcp->tcp_ire_ill_check_done) {
18477 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18478 		tcp->tcp_ire_ill_check_done = B_TRUE;
18479 	}
18480 
18481 	*irep = ire;
18482 	*illp = ill;
18483 
18484 	return (B_TRUE);
18485 }
18486 
18487 static void
18488 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18489 {
18490 	ipha_t		*ipha;
18491 	ipaddr_t	src;
18492 	ipaddr_t	dst;
18493 	uint32_t	cksum;
18494 	ire_t		*ire;
18495 	uint16_t	*up;
18496 	ill_t		*ill;
18497 	conn_t		*connp = tcp->tcp_connp;
18498 	uint32_t	hcksum_txflags = 0;
18499 	mblk_t		*ire_fp_mp;
18500 	uint_t		ire_fp_mp_len;
18501 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18502 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18503 	cred_t		*cr;
18504 	pid_t		cpid;
18505 
18506 	ASSERT(DB_TYPE(mp) == M_DATA);
18507 
18508 	/*
18509 	 * Here we need to handle the overloading of the cred_t for
18510 	 * both getpeerucred and TX.
18511 	 * If this is a SYN then the caller already set db_credp so
18512 	 * that getpeerucred will work. But if TX is in use we might have
18513 	 * a conn_effective_cred which is different, and we need to use that
18514 	 * cred to make TX use the correct label and label dependent route.
18515 	 */
18516 	if (is_system_labeled()) {
18517 		cr = msg_getcred(mp, &cpid);
18518 		if (cr == NULL || connp->conn_effective_cred != NULL)
18519 			mblk_setcred(mp, CONN_CRED(connp), cpid);
18520 	}
18521 
18522 	ipha = (ipha_t *)mp->b_rptr;
18523 	src = ipha->ipha_src;
18524 	dst = ipha->ipha_dst;
18525 
18526 	ASSERT(q != NULL);
18527 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
18528 
18529 	/*
18530 	 * Drop off fast path for IPv6 and also if options are present or
18531 	 * we need to resolve a TS label.
18532 	 */
18533 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18534 	    !IPCL_IS_CONNECTED(connp) ||
18535 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18536 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18537 	    !connp->conn_ulp_labeled ||
18538 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18539 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18540 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18541 		if (tcp->tcp_snd_zcopy_aware)
18542 			mp = tcp_zcopy_disable(tcp, mp);
18543 		TCP_STAT(tcps, tcp_ip_send);
18544 		CALL_IP_WPUT(connp, q, mp);
18545 		return;
18546 	}
18547 
18548 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18549 		if (tcp->tcp_snd_zcopy_aware)
18550 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18551 		CALL_IP_WPUT(connp, q, mp);
18552 		return;
18553 	}
18554 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18555 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18556 
18557 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18558 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18559 #ifndef _BIG_ENDIAN
18560 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18561 #endif
18562 
18563 	/*
18564 	 * Check to see if we need to re-enable LSO/MDT for this connection
18565 	 * because it was previously disabled due to changes in the ill;
18566 	 * note that by doing it here, this re-enabling only applies when
18567 	 * the packet is not dispatched through CALL_IP_WPUT().
18568 	 *
18569 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18570 	 * case, since that's how we ended up here.  For IPv6, we do the
18571 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18572 	 */
18573 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18574 		/*
18575 		 * Restore LSO for this connection, so that next time around
18576 		 * it is eligible to go through tcp_lsosend() path again.
18577 		 */
18578 		TCP_STAT(tcps, tcp_lso_enabled);
18579 		tcp->tcp_lso = B_TRUE;
18580 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18581 		    "interface %s\n", (void *)connp, ill->ill_name));
18582 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18583 		/*
18584 		 * Restore MDT for this connection, so that next time around
18585 		 * it is eligible to go through tcp_multisend() path again.
18586 		 */
18587 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18588 		tcp->tcp_mdt = B_TRUE;
18589 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18590 		    "interface %s\n", (void *)connp, ill->ill_name));
18591 	}
18592 
18593 	if (tcp->tcp_snd_zcopy_aware) {
18594 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18595 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18596 			mp = tcp_zcopy_disable(tcp, mp);
18597 		/*
18598 		 * we shouldn't need to reset ipha as the mp containing
18599 		 * ipha should never be a zero-copy mp.
18600 		 */
18601 	}
18602 
18603 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18604 		ASSERT(ill->ill_hcksum_capab != NULL);
18605 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18606 	}
18607 
18608 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18609 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18610 
18611 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18612 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18613 
18614 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18615 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18616 
18617 	/* Software checksum? */
18618 	if (DB_CKSUMFLAGS(mp) == 0) {
18619 		TCP_STAT(tcps, tcp_out_sw_cksum);
18620 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18621 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18622 	}
18623 
18624 	/* Calculate IP header checksum if hardware isn't capable */
18625 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18626 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18627 		    ((uint16_t *)ipha)[4]);
18628 	}
18629 
18630 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18631 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18632 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18633 
18634 	UPDATE_OB_PKT_COUNT(ire);
18635 	ire->ire_last_used_time = lbolt;
18636 
18637 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18638 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18639 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18640 	    ntohs(ipha->ipha_length));
18641 
18642 	DTRACE_PROBE4(ip4__physical__out__start,
18643 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
18644 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
18645 	    ipst->ips_ipv4firewall_physical_out,
18646 	    NULL, ill, ipha, mp, mp, 0, ipst);
18647 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18648 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
18649 
18650 	if (mp != NULL) {
18651 		if (ipst->ips_ip4_observe.he_interested) {
18652 			zoneid_t szone;
18653 
18654 			/*
18655 			 * Both of these functions expect b_rptr to be
18656 			 * where the IP header starts, so advance past the
18657 			 * link layer header if present.
18658 			 */
18659 			mp->b_rptr += ire_fp_mp_len;
18660 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
18661 			    ipst, ALL_ZONES);
18662 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
18663 			    ALL_ZONES, ill, ipst);
18664 			mp->b_rptr -= ire_fp_mp_len;
18665 		}
18666 
18667 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
18668 	}
18669 
18670 	IRE_REFRELE(ire);
18671 }
18672 
18673 /*
18674  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18675  * if the receiver shrinks the window, i.e. moves the right window to the
18676  * left, the we should not send new data, but should retransmit normally the
18677  * old unacked data between suna and suna + swnd. We might has sent data
18678  * that is now outside the new window, pretend that we didn't send  it.
18679  */
18680 static void
18681 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18682 {
18683 	uint32_t	snxt = tcp->tcp_snxt;
18684 
18685 	ASSERT(shrunk_count > 0);
18686 
18687 	if (!tcp->tcp_is_wnd_shrnk) {
18688 		tcp->tcp_snxt_shrunk = snxt;
18689 		tcp->tcp_is_wnd_shrnk = B_TRUE;
18690 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
18691 		tcp->tcp_snxt_shrunk = snxt;
18692 	}
18693 
18694 	/* Pretend we didn't send the data outside the window */
18695 	snxt -= shrunk_count;
18696 
18697 	/* Reset all the values per the now shrunk window */
18698 	tcp_update_xmit_tail(tcp, snxt);
18699 	tcp->tcp_unsent += shrunk_count;
18700 
18701 	/*
18702 	 * If the SACK option is set, delete the entire list of
18703 	 * notsack'ed blocks.
18704 	 */
18705 	if (tcp->tcp_sack_info != NULL) {
18706 		if (tcp->tcp_notsack_list != NULL)
18707 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
18708 	}
18709 
18710 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18711 		/*
18712 		 * Make sure the timer is running so that we will probe a zero
18713 		 * window.
18714 		 */
18715 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18716 }
18717 
18718 
18719 /*
18720  * The TCP normal data output path.
18721  * NOTE: the logic of the fast path is duplicated from this function.
18722  */
18723 static void
18724 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18725 {
18726 	int		len;
18727 	mblk_t		*local_time;
18728 	mblk_t		*mp1;
18729 	uint32_t	snxt;
18730 	int		tail_unsent;
18731 	int		tcpstate;
18732 	int		usable = 0;
18733 	mblk_t		*xmit_tail;
18734 	queue_t		*q = tcp->tcp_wq;
18735 	int32_t		mss;
18736 	int32_t		num_sack_blk = 0;
18737 	int32_t		tcp_hdr_len;
18738 	int32_t		tcp_tcp_hdr_len;
18739 	int		mdt_thres;
18740 	int		rc;
18741 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18742 	ip_stack_t	*ipst;
18743 
18744 	tcpstate = tcp->tcp_state;
18745 	if (mp == NULL) {
18746 		/*
18747 		 * tcp_wput_data() with NULL mp should only be called when
18748 		 * there is unsent data.
18749 		 */
18750 		ASSERT(tcp->tcp_unsent > 0);
18751 		/* Really tacky... but we need this for detached closes. */
18752 		len = tcp->tcp_unsent;
18753 		goto data_null;
18754 	}
18755 
18756 #if CCS_STATS
18757 	wrw_stats.tot.count++;
18758 	wrw_stats.tot.bytes += msgdsize(mp);
18759 #endif
18760 	ASSERT(mp->b_datap->db_type == M_DATA);
18761 	/*
18762 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18763 	 * or before a connection attempt has begun.
18764 	 */
18765 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18766 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18767 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18768 #ifdef DEBUG
18769 			cmn_err(CE_WARN,
18770 			    "tcp_wput_data: data after ordrel, %s",
18771 			    tcp_display(tcp, NULL,
18772 			    DISP_ADDR_AND_PORT));
18773 #else
18774 			if (tcp->tcp_debug) {
18775 				(void) strlog(TCP_MOD_ID, 0, 1,
18776 				    SL_TRACE|SL_ERROR,
18777 				    "tcp_wput_data: data after ordrel, %s\n",
18778 				    tcp_display(tcp, NULL,
18779 				    DISP_ADDR_AND_PORT));
18780 			}
18781 #endif /* DEBUG */
18782 		}
18783 		if (tcp->tcp_snd_zcopy_aware &&
18784 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18785 			tcp_zcopy_notify(tcp);
18786 		freemsg(mp);
18787 		mutex_enter(&tcp->tcp_non_sq_lock);
18788 		if (tcp->tcp_flow_stopped &&
18789 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18790 			tcp_clrqfull(tcp);
18791 		}
18792 		mutex_exit(&tcp->tcp_non_sq_lock);
18793 		return;
18794 	}
18795 
18796 	/* Strip empties */
18797 	for (;;) {
18798 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18799 		    (uintptr_t)INT_MAX);
18800 		len = (int)(mp->b_wptr - mp->b_rptr);
18801 		if (len > 0)
18802 			break;
18803 		mp1 = mp;
18804 		mp = mp->b_cont;
18805 		freeb(mp1);
18806 		if (!mp) {
18807 			return;
18808 		}
18809 	}
18810 
18811 	/* If we are the first on the list ... */
18812 	if (tcp->tcp_xmit_head == NULL) {
18813 		tcp->tcp_xmit_head = mp;
18814 		tcp->tcp_xmit_tail = mp;
18815 		tcp->tcp_xmit_tail_unsent = len;
18816 	} else {
18817 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18818 		struct datab *dp;
18819 
18820 		mp1 = tcp->tcp_xmit_last;
18821 		if (len < tcp_tx_pull_len &&
18822 		    (dp = mp1->b_datap)->db_ref == 1 &&
18823 		    dp->db_lim - mp1->b_wptr >= len) {
18824 			ASSERT(len > 0);
18825 			ASSERT(!mp1->b_cont);
18826 			if (len == 1) {
18827 				*mp1->b_wptr++ = *mp->b_rptr;
18828 			} else {
18829 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18830 				mp1->b_wptr += len;
18831 			}
18832 			if (mp1 == tcp->tcp_xmit_tail)
18833 				tcp->tcp_xmit_tail_unsent += len;
18834 			mp1->b_cont = mp->b_cont;
18835 			if (tcp->tcp_snd_zcopy_aware &&
18836 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18837 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18838 			freeb(mp);
18839 			mp = mp1;
18840 		} else {
18841 			tcp->tcp_xmit_last->b_cont = mp;
18842 		}
18843 		len += tcp->tcp_unsent;
18844 	}
18845 
18846 	/* Tack on however many more positive length mblks we have */
18847 	if ((mp1 = mp->b_cont) != NULL) {
18848 		do {
18849 			int tlen;
18850 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18851 			    (uintptr_t)INT_MAX);
18852 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18853 			if (tlen <= 0) {
18854 				mp->b_cont = mp1->b_cont;
18855 				freeb(mp1);
18856 			} else {
18857 				len += tlen;
18858 				mp = mp1;
18859 			}
18860 		} while ((mp1 = mp->b_cont) != NULL);
18861 	}
18862 	tcp->tcp_xmit_last = mp;
18863 	tcp->tcp_unsent = len;
18864 
18865 	if (urgent)
18866 		usable = 1;
18867 
18868 data_null:
18869 	snxt = tcp->tcp_snxt;
18870 	xmit_tail = tcp->tcp_xmit_tail;
18871 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18872 
18873 	/*
18874 	 * Note that tcp_mss has been adjusted to take into account the
18875 	 * timestamp option if applicable.  Because SACK options do not
18876 	 * appear in every TCP segments and they are of variable lengths,
18877 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18878 	 * the actual segment length when we need to send a segment which
18879 	 * includes SACK options.
18880 	 */
18881 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18882 		int32_t	opt_len;
18883 
18884 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18885 		    tcp->tcp_num_sack_blk);
18886 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18887 		    2 + TCPOPT_HEADER_LEN;
18888 		mss = tcp->tcp_mss - opt_len;
18889 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18890 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18891 	} else {
18892 		mss = tcp->tcp_mss;
18893 		tcp_hdr_len = tcp->tcp_hdr_len;
18894 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18895 	}
18896 
18897 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18898 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18899 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18900 	}
18901 	if (tcpstate == TCPS_SYN_RCVD) {
18902 		/*
18903 		 * The three-way connection establishment handshake is not
18904 		 * complete yet. We want to queue the data for transmission
18905 		 * after entering ESTABLISHED state (RFC793). A jump to
18906 		 * "done" label effectively leaves data on the queue.
18907 		 */
18908 		goto done;
18909 	} else {
18910 		int usable_r;
18911 
18912 		/*
18913 		 * In the special case when cwnd is zero, which can only
18914 		 * happen if the connection is ECN capable, return now.
18915 		 * New segments is sent using tcp_timer().  The timer
18916 		 * is set in tcp_rput_data().
18917 		 */
18918 		if (tcp->tcp_cwnd == 0) {
18919 			/*
18920 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18921 			 * finished.
18922 			 */
18923 			ASSERT(tcp->tcp_ecn_ok ||
18924 			    tcp->tcp_state < TCPS_ESTABLISHED);
18925 			return;
18926 		}
18927 
18928 		/* NOTE: trouble if xmitting while SYN not acked? */
18929 		usable_r = snxt - tcp->tcp_suna;
18930 		usable_r = tcp->tcp_swnd - usable_r;
18931 
18932 		/*
18933 		 * Check if the receiver has shrunk the window.  If
18934 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18935 		 * cannot be set as there is unsent data, so FIN cannot
18936 		 * be sent out.  Otherwise, we need to take into account
18937 		 * of FIN as it consumes an "invisible" sequence number.
18938 		 */
18939 		ASSERT(tcp->tcp_fin_sent == 0);
18940 		if (usable_r < 0) {
18941 			/*
18942 			 * The receiver has shrunk the window and we have sent
18943 			 * -usable_r date beyond the window, re-adjust.
18944 			 *
18945 			 * If TCP window scaling is enabled, there can be
18946 			 * round down error as the advertised receive window
18947 			 * is actually right shifted n bits.  This means that
18948 			 * the lower n bits info is wiped out.  It will look
18949 			 * like the window is shrunk.  Do a check here to
18950 			 * see if the shrunk amount is actually within the
18951 			 * error in window calculation.  If it is, just
18952 			 * return.  Note that this check is inside the
18953 			 * shrunk window check.  This makes sure that even
18954 			 * though tcp_process_shrunk_swnd() is not called,
18955 			 * we will stop further processing.
18956 			 */
18957 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18958 				tcp_process_shrunk_swnd(tcp, -usable_r);
18959 			}
18960 			return;
18961 		}
18962 
18963 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18964 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18965 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18966 
18967 		/* usable = MIN(usable, unsent) */
18968 		if (usable_r > len)
18969 			usable_r = len;
18970 
18971 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18972 		if (usable_r > 0) {
18973 			usable = usable_r;
18974 		} else {
18975 			/* Bypass all other unnecessary processing. */
18976 			goto done;
18977 		}
18978 	}
18979 
18980 	local_time = (mblk_t *)lbolt;
18981 
18982 	/*
18983 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18984 	 * BSD.  This is more in line with the true intent of Nagle.
18985 	 *
18986 	 * The conditions are:
18987 	 * 1. The amount of unsent data (or amount of data which can be
18988 	 *    sent, whichever is smaller) is less than Nagle limit.
18989 	 * 2. The last sent size is also less than Nagle limit.
18990 	 * 3. There is unack'ed data.
18991 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18992 	 *    Nagle algorithm.  This reduces the probability that urgent
18993 	 *    bytes get "merged" together.
18994 	 * 5. The app has not closed the connection.  This eliminates the
18995 	 *    wait time of the receiving side waiting for the last piece of
18996 	 *    (small) data.
18997 	 *
18998 	 * If all are satisified, exit without sending anything.  Note
18999 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19000 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19001 	 * 4095).
19002 	 */
19003 	if (usable < (int)tcp->tcp_naglim &&
19004 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19005 	    snxt != tcp->tcp_suna &&
19006 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19007 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19008 		goto done;
19009 	}
19010 
19011 	/*
19012 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
19013 	 * is set, then we have to force TCP not to send partial segment
19014 	 * (smaller than MSS bytes). We are calculating the usable now
19015 	 * based on full mss and will save the rest of remaining data for
19016 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
19017 	 * something to do zero window probe.
19018 	 */
19019 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
19020 		if (usable < mss)
19021 			goto done;
19022 		usable = (usable / mss) * mss;
19023 	}
19024 
19025 	/* Update the latest receive window size in TCP header. */
19026 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19027 	    tcp->tcp_tcph->th_win);
19028 
19029 	/*
19030 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19031 	 *
19032 	 * 1. Simple TCP/IP{v4,v6} (no options).
19033 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19034 	 * 3. If the TCP connection is in ESTABLISHED state.
19035 	 * 4. The TCP is not detached.
19036 	 *
19037 	 * If any of the above conditions have changed during the
19038 	 * connection, stop using LSO/MDT and restore the stream head
19039 	 * parameters accordingly.
19040 	 */
19041 	ipst = tcps->tcps_netstack->netstack_ip;
19042 
19043 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19044 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19045 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19046 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19047 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19048 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19049 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19050 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19051 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19052 		if (tcp->tcp_lso) {
19053 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19054 			tcp->tcp_lso = B_FALSE;
19055 		} else {
19056 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19057 			tcp->tcp_mdt = B_FALSE;
19058 		}
19059 
19060 		/* Anything other than detached is considered pathological */
19061 		if (!TCP_IS_DETACHED(tcp)) {
19062 			if (tcp->tcp_lso)
19063 				TCP_STAT(tcps, tcp_lso_disabled);
19064 			else
19065 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19066 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19067 		}
19068 	}
19069 
19070 	/* Use MDT if sendable amount is greater than the threshold */
19071 	if (tcp->tcp_mdt &&
19072 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19073 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19074 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19075 	    (tcp->tcp_valid_bits == 0 ||
19076 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19077 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19078 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19079 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19080 		    local_time, mdt_thres);
19081 	} else {
19082 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19083 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19084 		    local_time, INT_MAX);
19085 	}
19086 
19087 	/* Pretend that all we were trying to send really got sent */
19088 	if (rc < 0 && tail_unsent < 0) {
19089 		do {
19090 			xmit_tail = xmit_tail->b_cont;
19091 			xmit_tail->b_prev = local_time;
19092 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19093 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19094 			tail_unsent += (int)(xmit_tail->b_wptr -
19095 			    xmit_tail->b_rptr);
19096 		} while (tail_unsent < 0);
19097 	}
19098 done:;
19099 	tcp->tcp_xmit_tail = xmit_tail;
19100 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19101 	len = tcp->tcp_snxt - snxt;
19102 	if (len) {
19103 		/*
19104 		 * If new data was sent, need to update the notsack
19105 		 * list, which is, afterall, data blocks that have
19106 		 * not been sack'ed by the receiver.  New data is
19107 		 * not sack'ed.
19108 		 */
19109 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19110 			/* len is a negative value. */
19111 			tcp->tcp_pipe -= len;
19112 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19113 			    tcp->tcp_snxt, snxt,
19114 			    &(tcp->tcp_num_notsack_blk),
19115 			    &(tcp->tcp_cnt_notsack_list));
19116 		}
19117 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19118 		tcp->tcp_rack = tcp->tcp_rnxt;
19119 		tcp->tcp_rack_cnt = 0;
19120 		if ((snxt + len) == tcp->tcp_suna) {
19121 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19122 		}
19123 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19124 		/*
19125 		 * Didn't send anything. Make sure the timer is running
19126 		 * so that we will probe a zero window.
19127 		 */
19128 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19129 	}
19130 	/* Note that len is the amount we just sent but with a negative sign */
19131 	tcp->tcp_unsent += len;
19132 	mutex_enter(&tcp->tcp_non_sq_lock);
19133 	if (tcp->tcp_flow_stopped) {
19134 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19135 			tcp_clrqfull(tcp);
19136 		}
19137 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19138 		tcp_setqfull(tcp);
19139 	}
19140 	mutex_exit(&tcp->tcp_non_sq_lock);
19141 }
19142 
19143 /*
19144  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19145  * outgoing TCP header with the template header, as well as other
19146  * options such as time-stamp, ECN and/or SACK.
19147  */
19148 static void
19149 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19150 {
19151 	tcph_t *tcp_tmpl, *tcp_h;
19152 	uint32_t *dst, *src;
19153 	int hdrlen;
19154 
19155 	ASSERT(OK_32PTR(rptr));
19156 
19157 	/* Template header */
19158 	tcp_tmpl = tcp->tcp_tcph;
19159 
19160 	/* Header of outgoing packet */
19161 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19162 
19163 	/* dst and src are opaque 32-bit fields, used for copying */
19164 	dst = (uint32_t *)rptr;
19165 	src = (uint32_t *)tcp->tcp_iphc;
19166 	hdrlen = tcp->tcp_hdr_len;
19167 
19168 	/* Fill time-stamp option if needed */
19169 	if (tcp->tcp_snd_ts_ok) {
19170 		U32_TO_BE32((uint32_t)now,
19171 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19172 		U32_TO_BE32(tcp->tcp_ts_recent,
19173 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19174 	} else {
19175 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19176 	}
19177 
19178 	/*
19179 	 * Copy the template header; is this really more efficient than
19180 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19181 	 * but perhaps not for other scenarios.
19182 	 */
19183 	dst[0] = src[0];
19184 	dst[1] = src[1];
19185 	dst[2] = src[2];
19186 	dst[3] = src[3];
19187 	dst[4] = src[4];
19188 	dst[5] = src[5];
19189 	dst[6] = src[6];
19190 	dst[7] = src[7];
19191 	dst[8] = src[8];
19192 	dst[9] = src[9];
19193 	if (hdrlen -= 40) {
19194 		hdrlen >>= 2;
19195 		dst += 10;
19196 		src += 10;
19197 		do {
19198 			*dst++ = *src++;
19199 		} while (--hdrlen);
19200 	}
19201 
19202 	/*
19203 	 * Set the ECN info in the TCP header if it is not a zero
19204 	 * window probe.  Zero window probe is only sent in
19205 	 * tcp_wput_data() and tcp_timer().
19206 	 */
19207 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19208 		SET_ECT(tcp, rptr);
19209 
19210 		if (tcp->tcp_ecn_echo_on)
19211 			tcp_h->th_flags[0] |= TH_ECE;
19212 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19213 			tcp_h->th_flags[0] |= TH_CWR;
19214 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19215 		}
19216 	}
19217 
19218 	/* Fill in SACK options */
19219 	if (num_sack_blk > 0) {
19220 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19221 		sack_blk_t *tmp;
19222 		int32_t	i;
19223 
19224 		wptr[0] = TCPOPT_NOP;
19225 		wptr[1] = TCPOPT_NOP;
19226 		wptr[2] = TCPOPT_SACK;
19227 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19228 		    sizeof (sack_blk_t);
19229 		wptr += TCPOPT_REAL_SACK_LEN;
19230 
19231 		tmp = tcp->tcp_sack_list;
19232 		for (i = 0; i < num_sack_blk; i++) {
19233 			U32_TO_BE32(tmp[i].begin, wptr);
19234 			wptr += sizeof (tcp_seq);
19235 			U32_TO_BE32(tmp[i].end, wptr);
19236 			wptr += sizeof (tcp_seq);
19237 		}
19238 		tcp_h->th_offset_and_rsrvd[0] +=
19239 		    ((num_sack_blk * 2 + 1) << 4);
19240 	}
19241 }
19242 
19243 /*
19244  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19245  * the destination address and SAP attribute, and if necessary, the
19246  * hardware checksum offload attribute to a Multidata message.
19247  */
19248 static int
19249 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19250     const uint32_t start, const uint32_t stuff, const uint32_t end,
19251     const uint32_t flags, tcp_stack_t *tcps)
19252 {
19253 	/* Add global destination address & SAP attribute */
19254 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19255 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19256 		    "destination address+SAP\n"));
19257 
19258 		if (dlmp != NULL)
19259 			TCP_STAT(tcps, tcp_mdt_allocfail);
19260 		return (-1);
19261 	}
19262 
19263 	/* Add global hwcksum attribute */
19264 	if (hwcksum &&
19265 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19266 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19267 		    "checksum attribute\n"));
19268 
19269 		TCP_STAT(tcps, tcp_mdt_allocfail);
19270 		return (-1);
19271 	}
19272 
19273 	return (0);
19274 }
19275 
19276 /*
19277  * Smaller and private version of pdescinfo_t used specifically for TCP,
19278  * which allows for only two payload spans per packet.
19279  */
19280 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19281 
19282 /*
19283  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19284  * scheme, and returns one the following:
19285  *
19286  * -1 = failed allocation.
19287  *  0 = success; burst count reached, or usable send window is too small,
19288  *      and that we'd rather wait until later before sending again.
19289  */
19290 static int
19291 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19292     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19293     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19294     const int mdt_thres)
19295 {
19296 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19297 	multidata_t	*mmd;
19298 	uint_t		obsegs, obbytes, hdr_frag_sz;
19299 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19300 	int		num_burst_seg, max_pld;
19301 	pdesc_t		*pkt;
19302 	tcp_pdescinfo_t	tcp_pkt_info;
19303 	pdescinfo_t	*pkt_info;
19304 	int		pbuf_idx, pbuf_idx_nxt;
19305 	int		seg_len, len, spill, af;
19306 	boolean_t	add_buffer, zcopy, clusterwide;
19307 	boolean_t	rconfirm = B_FALSE;
19308 	boolean_t	done = B_FALSE;
19309 	uint32_t	cksum;
19310 	uint32_t	hwcksum_flags;
19311 	ire_t		*ire = NULL;
19312 	ill_t		*ill;
19313 	ipha_t		*ipha;
19314 	ip6_t		*ip6h;
19315 	ipaddr_t	src, dst;
19316 	ill_zerocopy_capab_t *zc_cap = NULL;
19317 	uint16_t	*up;
19318 	int		err;
19319 	conn_t		*connp;
19320 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19321 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19322 	int		usable_mmd, tail_unsent_mmd;
19323 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19324 	mblk_t		*xmit_tail_mmd;
19325 	netstackid_t	stack_id;
19326 
19327 #ifdef	_BIG_ENDIAN
19328 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19329 #else
19330 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19331 #endif
19332 
19333 #define	PREP_NEW_MULTIDATA() {			\
19334 	mmd = NULL;				\
19335 	md_mp = md_hbuf = NULL;			\
19336 	cur_hdr_off = 0;			\
19337 	max_pld = tcp->tcp_mdt_max_pld;		\
19338 	pbuf_idx = pbuf_idx_nxt = -1;		\
19339 	add_buffer = B_TRUE;			\
19340 	zcopy = B_FALSE;			\
19341 }
19342 
19343 #define	PREP_NEW_PBUF() {			\
19344 	md_pbuf = md_pbuf_nxt = NULL;		\
19345 	pbuf_idx = pbuf_idx_nxt = -1;		\
19346 	cur_pld_off = 0;			\
19347 	first_snxt = *snxt;			\
19348 	ASSERT(*tail_unsent > 0);		\
19349 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19350 }
19351 
19352 	ASSERT(mdt_thres >= mss);
19353 	ASSERT(*usable > 0 && *usable > mdt_thres);
19354 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19355 	ASSERT(!TCP_IS_DETACHED(tcp));
19356 	ASSERT(tcp->tcp_valid_bits == 0 ||
19357 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19358 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19359 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19360 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19361 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19362 
19363 	connp = tcp->tcp_connp;
19364 	ASSERT(connp != NULL);
19365 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19366 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19367 
19368 	stack_id = connp->conn_netstack->netstack_stackid;
19369 
19370 	usable_mmd = tail_unsent_mmd = 0;
19371 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
19372 	xmit_tail_mmd = NULL;
19373 	/*
19374 	 * Note that tcp will only declare at most 2 payload spans per
19375 	 * packet, which is much lower than the maximum allowable number
19376 	 * of packet spans per Multidata.  For this reason, we use the
19377 	 * privately declared and smaller descriptor info structure, in
19378 	 * order to save some stack space.
19379 	 */
19380 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19381 
19382 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19383 	if (af == AF_INET) {
19384 		dst = tcp->tcp_ipha->ipha_dst;
19385 		src = tcp->tcp_ipha->ipha_src;
19386 		ASSERT(!CLASSD(dst));
19387 	}
19388 	ASSERT(af == AF_INET ||
19389 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19390 
19391 	obsegs = obbytes = 0;
19392 	num_burst_seg = tcp->tcp_snd_burst;
19393 	md_mp_head = NULL;
19394 	PREP_NEW_MULTIDATA();
19395 
19396 	/*
19397 	 * Before we go on further, make sure there is an IRE that we can
19398 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19399 	 * in proceeding any further, and we should just hand everything
19400 	 * off to the legacy path.
19401 	 */
19402 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19403 		goto legacy_send_no_md;
19404 
19405 	ASSERT(ire != NULL);
19406 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19407 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19408 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19409 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19410 	/*
19411 	 * If we do support loopback for MDT (which requires modifications
19412 	 * to the receiving paths), the following assertions should go away,
19413 	 * and we would be sending the Multidata to loopback conn later on.
19414 	 */
19415 	ASSERT(!IRE_IS_LOCAL(ire));
19416 	ASSERT(ire->ire_stq != NULL);
19417 
19418 	ill = ire_to_ill(ire);
19419 	ASSERT(ill != NULL);
19420 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19421 
19422 	if (!tcp->tcp_ire_ill_check_done) {
19423 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19424 		tcp->tcp_ire_ill_check_done = B_TRUE;
19425 	}
19426 
19427 	/*
19428 	 * If the underlying interface conditions have changed, or if the
19429 	 * new interface does not support MDT, go back to legacy path.
19430 	 */
19431 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19432 		/* don't go through this path anymore for this connection */
19433 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19434 		tcp->tcp_mdt = B_FALSE;
19435 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19436 		    "interface %s\n", (void *)connp, ill->ill_name));
19437 		/* IRE will be released prior to returning */
19438 		goto legacy_send_no_md;
19439 	}
19440 
19441 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19442 		zc_cap = ill->ill_zerocopy_capab;
19443 
19444 	/*
19445 	 * Check if we can take tcp fast-path. Note that "incomplete"
19446 	 * ire's (where the link-layer for next hop is not resolved
19447 	 * or where the fast-path header in nce_fp_mp is not available
19448 	 * yet) are sent down the legacy (slow) path.
19449 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19450 	 */
19451 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19452 		/* IRE will be released prior to returning */
19453 		goto legacy_send_no_md;
19454 	}
19455 
19456 	/* go to legacy path if interface doesn't support zerocopy */
19457 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19458 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19459 		/* IRE will be released prior to returning */
19460 		goto legacy_send_no_md;
19461 	}
19462 
19463 	/* does the interface support hardware checksum offload? */
19464 	hwcksum_flags = 0;
19465 	if (ILL_HCKSUM_CAPABLE(ill) &&
19466 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19467 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19468 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19469 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19470 		    HCKSUM_IPHDRCKSUM)
19471 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19472 
19473 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19474 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19475 			hwcksum_flags |= HCK_FULLCKSUM;
19476 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19477 		    HCKSUM_INET_PARTIAL)
19478 			hwcksum_flags |= HCK_PARTIALCKSUM;
19479 	}
19480 
19481 	/*
19482 	 * Each header fragment consists of the leading extra space,
19483 	 * followed by the TCP/IP header, and the trailing extra space.
19484 	 * We make sure that each header fragment begins on a 32-bit
19485 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19486 	 * aligned in tcp_mdt_update).
19487 	 */
19488 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19489 	    tcp->tcp_mdt_hdr_tail), 4);
19490 
19491 	/* are we starting from the beginning of data block? */
19492 	if (*tail_unsent == 0) {
19493 		*xmit_tail = (*xmit_tail)->b_cont;
19494 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19495 		*tail_unsent = (int)MBLKL(*xmit_tail);
19496 	}
19497 
19498 	/*
19499 	 * Here we create one or more Multidata messages, each made up of
19500 	 * one header buffer and up to N payload buffers.  This entire
19501 	 * operation is done within two loops:
19502 	 *
19503 	 * The outer loop mostly deals with creating the Multidata message,
19504 	 * as well as the header buffer that gets added to it.  It also
19505 	 * links the Multidata messages together such that all of them can
19506 	 * be sent down to the lower layer in a single putnext call; this
19507 	 * linking behavior depends on the tcp_mdt_chain tunable.
19508 	 *
19509 	 * The inner loop takes an existing Multidata message, and adds
19510 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19511 	 * packetizes those buffers by filling up the corresponding header
19512 	 * buffer fragments with the proper IP and TCP headers, and by
19513 	 * describing the layout of each packet in the packet descriptors
19514 	 * that get added to the Multidata.
19515 	 */
19516 	do {
19517 		/*
19518 		 * If usable send window is too small, or data blocks in
19519 		 * transmit list are smaller than our threshold (i.e. app
19520 		 * performs large writes followed by small ones), we hand
19521 		 * off the control over to the legacy path.  Note that we'll
19522 		 * get back the control once it encounters a large block.
19523 		 */
19524 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19525 		    (*xmit_tail)->b_cont != NULL &&
19526 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19527 			/* send down what we've got so far */
19528 			if (md_mp_head != NULL) {
19529 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19530 				    obsegs, obbytes, &rconfirm);
19531 			}
19532 			/*
19533 			 * Pass control over to tcp_send(), but tell it to
19534 			 * return to us once a large-size transmission is
19535 			 * possible.
19536 			 */
19537 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19538 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19539 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19540 			    tail_unsent, xmit_tail, local_time,
19541 			    mdt_thres)) <= 0) {
19542 				/* burst count reached, or alloc failed */
19543 				IRE_REFRELE(ire);
19544 				return (err);
19545 			}
19546 
19547 			/* tcp_send() may have sent everything, so check */
19548 			if (*usable <= 0) {
19549 				IRE_REFRELE(ire);
19550 				return (0);
19551 			}
19552 
19553 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19554 			/*
19555 			 * We may have delivered the Multidata, so make sure
19556 			 * to re-initialize before the next round.
19557 			 */
19558 			md_mp_head = NULL;
19559 			obsegs = obbytes = 0;
19560 			num_burst_seg = tcp->tcp_snd_burst;
19561 			PREP_NEW_MULTIDATA();
19562 
19563 			/* are we starting from the beginning of data block? */
19564 			if (*tail_unsent == 0) {
19565 				*xmit_tail = (*xmit_tail)->b_cont;
19566 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19567 				    (uintptr_t)INT_MAX);
19568 				*tail_unsent = (int)MBLKL(*xmit_tail);
19569 			}
19570 		}
19571 		/*
19572 		 * Record current values for parameters we may need to pass
19573 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
19574 		 * each iteration of the outer loop (each multidata message
19575 		 * creation). If we have a failure in the inner loop, we send
19576 		 * any complete multidata messages we have before reverting
19577 		 * to using the traditional non-md path.
19578 		 */
19579 		snxt_mmd = *snxt;
19580 		usable_mmd = *usable;
19581 		xmit_tail_mmd = *xmit_tail;
19582 		tail_unsent_mmd = *tail_unsent;
19583 		obsegs_mmd = obsegs;
19584 		obbytes_mmd = obbytes;
19585 
19586 		/*
19587 		 * max_pld limits the number of mblks in tcp's transmit
19588 		 * queue that can be added to a Multidata message.  Once
19589 		 * this counter reaches zero, no more additional mblks
19590 		 * can be added to it.  What happens afterwards depends
19591 		 * on whether or not we are set to chain the Multidata
19592 		 * messages.  If we are to link them together, reset
19593 		 * max_pld to its original value (tcp_mdt_max_pld) and
19594 		 * prepare to create a new Multidata message which will
19595 		 * get linked to md_mp_head.  Else, leave it alone and
19596 		 * let the inner loop break on its own.
19597 		 */
19598 		if (tcp_mdt_chain && max_pld == 0)
19599 			PREP_NEW_MULTIDATA();
19600 
19601 		/* adding a payload buffer; re-initialize values */
19602 		if (add_buffer)
19603 			PREP_NEW_PBUF();
19604 
19605 		/*
19606 		 * If we don't have a Multidata, either because we just
19607 		 * (re)entered this outer loop, or after we branched off
19608 		 * to tcp_send above, setup the Multidata and header
19609 		 * buffer to be used.
19610 		 */
19611 		if (md_mp == NULL) {
19612 			int md_hbuflen;
19613 			uint32_t start, stuff;
19614 
19615 			/*
19616 			 * Calculate Multidata header buffer size large enough
19617 			 * to hold all of the headers that can possibly be
19618 			 * sent at this moment.  We'd rather over-estimate
19619 			 * the size than running out of space; this is okay
19620 			 * since this buffer is small anyway.
19621 			 */
19622 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19623 
19624 			/*
19625 			 * Start and stuff offset for partial hardware
19626 			 * checksum offload; these are currently for IPv4.
19627 			 * For full checksum offload, they are set to zero.
19628 			 */
19629 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19630 				if (af == AF_INET) {
19631 					start = IP_SIMPLE_HDR_LENGTH;
19632 					stuff = IP_SIMPLE_HDR_LENGTH +
19633 					    TCP_CHECKSUM_OFFSET;
19634 				} else {
19635 					start = IPV6_HDR_LEN;
19636 					stuff = IPV6_HDR_LEN +
19637 					    TCP_CHECKSUM_OFFSET;
19638 				}
19639 			} else {
19640 				start = stuff = 0;
19641 			}
19642 
19643 			/*
19644 			 * Create the header buffer, Multidata, as well as
19645 			 * any necessary attributes (destination address,
19646 			 * SAP and hardware checksum offload) that should
19647 			 * be associated with the Multidata message.
19648 			 */
19649 			ASSERT(cur_hdr_off == 0);
19650 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19651 			    ((md_hbuf->b_wptr += md_hbuflen),
19652 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19653 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19654 			    /* fastpath mblk */
19655 			    ire->ire_nce->nce_res_mp,
19656 			    /* hardware checksum enabled */
19657 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19658 			    /* hardware checksum offsets */
19659 			    start, stuff, 0,
19660 			    /* hardware checksum flag */
19661 			    hwcksum_flags, tcps) != 0)) {
19662 legacy_send:
19663 				/*
19664 				 * We arrive here from a failure within the
19665 				 * inner (packetizer) loop or we fail one of
19666 				 * the conditionals above. We restore the
19667 				 * previously checkpointed values for:
19668 				 *    xmit_tail
19669 				 *    usable
19670 				 *    tail_unsent
19671 				 *    snxt
19672 				 *    obbytes
19673 				 *    obsegs
19674 				 * We should then be able to dispatch any
19675 				 * complete multidata before reverting to the
19676 				 * traditional path with consistent parameters
19677 				 * (the inner loop updates these as it
19678 				 * iterates).
19679 				 */
19680 				*xmit_tail = xmit_tail_mmd;
19681 				*usable = usable_mmd;
19682 				*tail_unsent = tail_unsent_mmd;
19683 				*snxt = snxt_mmd;
19684 				obbytes = obbytes_mmd;
19685 				obsegs = obsegs_mmd;
19686 				if (md_mp != NULL) {
19687 					/* Unlink message from the chain */
19688 					if (md_mp_head != NULL) {
19689 						err = (intptr_t)rmvb(md_mp_head,
19690 						    md_mp);
19691 						/*
19692 						 * We can't assert that rmvb
19693 						 * did not return -1, since we
19694 						 * may get here before linkb
19695 						 * happens.  We do, however,
19696 						 * check if we just removed the
19697 						 * only element in the list.
19698 						 */
19699 						if (err == 0)
19700 							md_mp_head = NULL;
19701 					}
19702 					/* md_hbuf gets freed automatically */
19703 					TCP_STAT(tcps, tcp_mdt_discarded);
19704 					freeb(md_mp);
19705 				} else {
19706 					/* Either allocb or mmd_alloc failed */
19707 					TCP_STAT(tcps, tcp_mdt_allocfail);
19708 					if (md_hbuf != NULL)
19709 						freeb(md_hbuf);
19710 				}
19711 
19712 				/* send down what we've got so far */
19713 				if (md_mp_head != NULL) {
19714 					tcp_multisend_data(tcp, ire, ill,
19715 					    md_mp_head, obsegs, obbytes,
19716 					    &rconfirm);
19717 				}
19718 legacy_send_no_md:
19719 				if (ire != NULL)
19720 					IRE_REFRELE(ire);
19721 				/*
19722 				 * Too bad; let the legacy path handle this.
19723 				 * We specify INT_MAX for the threshold, since
19724 				 * we gave up with the Multidata processings
19725 				 * and let the old path have it all.
19726 				 */
19727 				TCP_STAT(tcps, tcp_mdt_legacy_all);
19728 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19729 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19730 				    snxt, tail_unsent, xmit_tail, local_time,
19731 				    INT_MAX));
19732 			}
19733 
19734 			/* link to any existing ones, if applicable */
19735 			TCP_STAT(tcps, tcp_mdt_allocd);
19736 			if (md_mp_head == NULL) {
19737 				md_mp_head = md_mp;
19738 			} else if (tcp_mdt_chain) {
19739 				TCP_STAT(tcps, tcp_mdt_linked);
19740 				linkb(md_mp_head, md_mp);
19741 			}
19742 		}
19743 
19744 		ASSERT(md_mp_head != NULL);
19745 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19746 		ASSERT(md_mp != NULL && mmd != NULL);
19747 		ASSERT(md_hbuf != NULL);
19748 
19749 		/*
19750 		 * Packetize the transmittable portion of the data block;
19751 		 * each data block is essentially added to the Multidata
19752 		 * as a payload buffer.  We also deal with adding more
19753 		 * than one payload buffers, which happens when the remaining
19754 		 * packetized portion of the current payload buffer is less
19755 		 * than MSS, while the next data block in transmit queue
19756 		 * has enough data to make up for one.  This "spillover"
19757 		 * case essentially creates a split-packet, where portions
19758 		 * of the packet's payload fragments may span across two
19759 		 * virtually discontiguous address blocks.
19760 		 */
19761 		seg_len = mss;
19762 		do {
19763 			len = seg_len;
19764 
19765 			/* one must remain NULL for DTRACE_IP_FASTPATH */
19766 			ipha = NULL;
19767 			ip6h = NULL;
19768 
19769 			ASSERT(len > 0);
19770 			ASSERT(max_pld >= 0);
19771 			ASSERT(!add_buffer || cur_pld_off == 0);
19772 
19773 			/*
19774 			 * First time around for this payload buffer; note
19775 			 * in the case of a spillover, the following has
19776 			 * been done prior to adding the split-packet
19777 			 * descriptor to Multidata, and we don't want to
19778 			 * repeat the process.
19779 			 */
19780 			if (add_buffer) {
19781 				ASSERT(mmd != NULL);
19782 				ASSERT(md_pbuf == NULL);
19783 				ASSERT(md_pbuf_nxt == NULL);
19784 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19785 
19786 				/*
19787 				 * Have we reached the limit?  We'd get to
19788 				 * this case when we're not chaining the
19789 				 * Multidata messages together, and since
19790 				 * we're done, terminate this loop.
19791 				 */
19792 				if (max_pld == 0)
19793 					break; /* done */
19794 
19795 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19796 					TCP_STAT(tcps, tcp_mdt_allocfail);
19797 					goto legacy_send; /* out_of_mem */
19798 				}
19799 
19800 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19801 				    zc_cap != NULL) {
19802 					if (!ip_md_zcopy_attr(mmd, NULL,
19803 					    zc_cap->ill_zerocopy_flags)) {
19804 						freeb(md_pbuf);
19805 						TCP_STAT(tcps,
19806 						    tcp_mdt_allocfail);
19807 						/* out_of_mem */
19808 						goto legacy_send;
19809 					}
19810 					zcopy = B_TRUE;
19811 				}
19812 
19813 				md_pbuf->b_rptr += base_pld_off;
19814 
19815 				/*
19816 				 * Add a payload buffer to the Multidata; this
19817 				 * operation must not fail, or otherwise our
19818 				 * logic in this routine is broken.  There
19819 				 * is no memory allocation done by the
19820 				 * routine, so any returned failure simply
19821 				 * tells us that we've done something wrong.
19822 				 *
19823 				 * A failure tells us that either we're adding
19824 				 * the same payload buffer more than once, or
19825 				 * we're trying to add more buffers than
19826 				 * allowed (max_pld calculation is wrong).
19827 				 * None of the above cases should happen, and
19828 				 * we panic because either there's horrible
19829 				 * heap corruption, and/or programming mistake.
19830 				 */
19831 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19832 				if (pbuf_idx < 0) {
19833 					cmn_err(CE_PANIC, "tcp_multisend: "
19834 					    "payload buffer logic error "
19835 					    "detected for tcp %p mmd %p "
19836 					    "pbuf %p (%d)\n",
19837 					    (void *)tcp, (void *)mmd,
19838 					    (void *)md_pbuf, pbuf_idx);
19839 				}
19840 
19841 				ASSERT(max_pld > 0);
19842 				--max_pld;
19843 				add_buffer = B_FALSE;
19844 			}
19845 
19846 			ASSERT(md_mp_head != NULL);
19847 			ASSERT(md_pbuf != NULL);
19848 			ASSERT(md_pbuf_nxt == NULL);
19849 			ASSERT(pbuf_idx != -1);
19850 			ASSERT(pbuf_idx_nxt == -1);
19851 			ASSERT(*usable > 0);
19852 
19853 			/*
19854 			 * We spillover to the next payload buffer only
19855 			 * if all of the following is true:
19856 			 *
19857 			 *   1. There is not enough data on the current
19858 			 *	payload buffer to make up `len',
19859 			 *   2. We are allowed to send `len',
19860 			 *   3. The next payload buffer length is large
19861 			 *	enough to accomodate `spill'.
19862 			 */
19863 			if ((spill = len - *tail_unsent) > 0 &&
19864 			    *usable >= len &&
19865 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19866 			    max_pld > 0) {
19867 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19868 				if (md_pbuf_nxt == NULL) {
19869 					TCP_STAT(tcps, tcp_mdt_allocfail);
19870 					goto legacy_send; /* out_of_mem */
19871 				}
19872 
19873 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19874 				    zc_cap != NULL) {
19875 					if (!ip_md_zcopy_attr(mmd, NULL,
19876 					    zc_cap->ill_zerocopy_flags)) {
19877 						freeb(md_pbuf_nxt);
19878 						TCP_STAT(tcps,
19879 						    tcp_mdt_allocfail);
19880 						/* out_of_mem */
19881 						goto legacy_send;
19882 					}
19883 					zcopy = B_TRUE;
19884 				}
19885 
19886 				/*
19887 				 * See comments above on the first call to
19888 				 * mmd_addpldbuf for explanation on the panic.
19889 				 */
19890 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19891 				if (pbuf_idx_nxt < 0) {
19892 					panic("tcp_multisend: "
19893 					    "next payload buffer logic error "
19894 					    "detected for tcp %p mmd %p "
19895 					    "pbuf %p (%d)\n",
19896 					    (void *)tcp, (void *)mmd,
19897 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19898 				}
19899 
19900 				ASSERT(max_pld > 0);
19901 				--max_pld;
19902 			} else if (spill > 0) {
19903 				/*
19904 				 * If there's a spillover, but the following
19905 				 * xmit_tail couldn't give us enough octets
19906 				 * to reach "len", then stop the current
19907 				 * Multidata creation and let the legacy
19908 				 * tcp_send() path take over.  We don't want
19909 				 * to send the tiny segment as part of this
19910 				 * Multidata for performance reasons; instead,
19911 				 * we let the legacy path deal with grouping
19912 				 * it with the subsequent small mblks.
19913 				 */
19914 				if (*usable >= len &&
19915 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19916 					max_pld = 0;
19917 					break;	/* done */
19918 				}
19919 
19920 				/*
19921 				 * We can't spillover, and we are near
19922 				 * the end of the current payload buffer,
19923 				 * so send what's left.
19924 				 */
19925 				ASSERT(*tail_unsent > 0);
19926 				len = *tail_unsent;
19927 			}
19928 
19929 			/* tail_unsent is negated if there is a spillover */
19930 			*tail_unsent -= len;
19931 			*usable -= len;
19932 			ASSERT(*usable >= 0);
19933 
19934 			if (*usable < mss)
19935 				seg_len = *usable;
19936 			/*
19937 			 * Sender SWS avoidance; see comments in tcp_send();
19938 			 * everything else is the same, except that we only
19939 			 * do this here if there is no more data to be sent
19940 			 * following the current xmit_tail.  We don't check
19941 			 * for 1-byte urgent data because we shouldn't get
19942 			 * here if TCP_URG_VALID is set.
19943 			 */
19944 			if (*usable > 0 && *usable < mss &&
19945 			    ((md_pbuf_nxt == NULL &&
19946 			    (*xmit_tail)->b_cont == NULL) ||
19947 			    (md_pbuf_nxt != NULL &&
19948 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19949 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19950 			    (tcp->tcp_unsent -
19951 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19952 			    !tcp->tcp_zero_win_probe) {
19953 				if ((*snxt + len) == tcp->tcp_snxt &&
19954 				    (*snxt + len) == tcp->tcp_suna) {
19955 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19956 				}
19957 				done = B_TRUE;
19958 			}
19959 
19960 			/*
19961 			 * Prime pump for IP's checksumming on our behalf;
19962 			 * include the adjustment for a source route if any.
19963 			 * Do this only for software/partial hardware checksum
19964 			 * offload, as this field gets zeroed out later for
19965 			 * the full hardware checksum offload case.
19966 			 */
19967 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19968 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19969 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19970 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19971 			}
19972 
19973 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19974 			*snxt += len;
19975 
19976 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19977 			/*
19978 			 * We set the PUSH bit only if TCP has no more buffered
19979 			 * data to be transmitted (or if sender SWS avoidance
19980 			 * takes place), as opposed to setting it for every
19981 			 * last packet in the burst.
19982 			 */
19983 			if (done ||
19984 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19985 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19986 
19987 			/*
19988 			 * Set FIN bit if this is our last segment; snxt
19989 			 * already includes its length, and it will not
19990 			 * be adjusted after this point.
19991 			 */
19992 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19993 			    *snxt == tcp->tcp_fss) {
19994 				if (!tcp->tcp_fin_acked) {
19995 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19996 					BUMP_MIB(&tcps->tcps_mib,
19997 					    tcpOutControl);
19998 				}
19999 				if (!tcp->tcp_fin_sent) {
20000 					tcp->tcp_fin_sent = B_TRUE;
20001 					/*
20002 					 * tcp state must be ESTABLISHED
20003 					 * in order for us to get here in
20004 					 * the first place.
20005 					 */
20006 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20007 
20008 					/*
20009 					 * Upon returning from this routine,
20010 					 * tcp_wput_data() will set tcp_snxt
20011 					 * to be equal to snxt + tcp_fin_sent.
20012 					 * This is essentially the same as
20013 					 * setting it to tcp_fss + 1.
20014 					 */
20015 				}
20016 			}
20017 
20018 			tcp->tcp_last_sent_len = (ushort_t)len;
20019 
20020 			len += tcp_hdr_len;
20021 			if (tcp->tcp_ipversion == IPV4_VERSION)
20022 				tcp->tcp_ipha->ipha_length = htons(len);
20023 			else
20024 				tcp->tcp_ip6h->ip6_plen = htons(len -
20025 				    ((char *)&tcp->tcp_ip6h[1] -
20026 				    tcp->tcp_iphc));
20027 
20028 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20029 
20030 			/* setup header fragment */
20031 			PDESC_HDR_ADD(pkt_info,
20032 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20033 			    tcp->tcp_mdt_hdr_head,		/* head room */
20034 			    tcp_hdr_len,			/* len */
20035 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20036 
20037 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20038 			    hdr_frag_sz);
20039 			ASSERT(MBLKIN(md_hbuf,
20040 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20041 			    PDESC_HDRSIZE(pkt_info)));
20042 
20043 			/* setup first payload fragment */
20044 			PDESC_PLD_INIT(pkt_info);
20045 			PDESC_PLD_SPAN_ADD(pkt_info,
20046 			    pbuf_idx,				/* index */
20047 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20048 			    tcp->tcp_last_sent_len);		/* len */
20049 
20050 			/* create a split-packet in case of a spillover */
20051 			if (md_pbuf_nxt != NULL) {
20052 				ASSERT(spill > 0);
20053 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20054 				ASSERT(!add_buffer);
20055 
20056 				md_pbuf = md_pbuf_nxt;
20057 				md_pbuf_nxt = NULL;
20058 				pbuf_idx = pbuf_idx_nxt;
20059 				pbuf_idx_nxt = -1;
20060 				cur_pld_off = spill;
20061 
20062 				/* trim out first payload fragment */
20063 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20064 
20065 				/* setup second payload fragment */
20066 				PDESC_PLD_SPAN_ADD(pkt_info,
20067 				    pbuf_idx,			/* index */
20068 				    md_pbuf->b_rptr,		/* start */
20069 				    spill);			/* len */
20070 
20071 				if ((*xmit_tail)->b_next == NULL) {
20072 					/*
20073 					 * Store the lbolt used for RTT
20074 					 * estimation. We can only record one
20075 					 * timestamp per mblk so we do it when
20076 					 * we reach the end of the payload
20077 					 * buffer.  Also we only take a new
20078 					 * timestamp sample when the previous
20079 					 * timed data from the same mblk has
20080 					 * been ack'ed.
20081 					 */
20082 					(*xmit_tail)->b_prev = local_time;
20083 					(*xmit_tail)->b_next =
20084 					    (mblk_t *)(uintptr_t)first_snxt;
20085 				}
20086 
20087 				first_snxt = *snxt - spill;
20088 
20089 				/*
20090 				 * Advance xmit_tail; usable could be 0 by
20091 				 * the time we got here, but we made sure
20092 				 * above that we would only spillover to
20093 				 * the next data block if usable includes
20094 				 * the spilled-over amount prior to the
20095 				 * subtraction.  Therefore, we are sure
20096 				 * that xmit_tail->b_cont can't be NULL.
20097 				 */
20098 				ASSERT((*xmit_tail)->b_cont != NULL);
20099 				*xmit_tail = (*xmit_tail)->b_cont;
20100 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20101 				    (uintptr_t)INT_MAX);
20102 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20103 			} else {
20104 				cur_pld_off += tcp->tcp_last_sent_len;
20105 			}
20106 
20107 			/*
20108 			 * Fill in the header using the template header, and
20109 			 * add options such as time-stamp, ECN and/or SACK,
20110 			 * as needed.
20111 			 */
20112 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20113 			    (clock_t)local_time, num_sack_blk);
20114 
20115 			/* take care of some IP header businesses */
20116 			if (af == AF_INET) {
20117 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20118 
20119 				ASSERT(OK_32PTR((uchar_t *)ipha));
20120 				ASSERT(PDESC_HDRL(pkt_info) >=
20121 				    IP_SIMPLE_HDR_LENGTH);
20122 				ASSERT(ipha->ipha_version_and_hdr_length ==
20123 				    IP_SIMPLE_HDR_VERSION);
20124 
20125 				/*
20126 				 * Assign ident value for current packet; see
20127 				 * related comments in ip_wput_ire() about the
20128 				 * contract private interface with clustering
20129 				 * group.
20130 				 */
20131 				clusterwide = B_FALSE;
20132 				if (cl_inet_ipident != NULL) {
20133 					ASSERT(cl_inet_isclusterwide != NULL);
20134 					if ((*cl_inet_isclusterwide)(stack_id,
20135 					    IPPROTO_IP, AF_INET,
20136 					    (uint8_t *)(uintptr_t)src, NULL)) {
20137 						ipha->ipha_ident =
20138 						    (*cl_inet_ipident)(stack_id,
20139 						    IPPROTO_IP, AF_INET,
20140 						    (uint8_t *)(uintptr_t)src,
20141 						    (uint8_t *)(uintptr_t)dst,
20142 						    NULL);
20143 						clusterwide = B_TRUE;
20144 					}
20145 				}
20146 
20147 				if (!clusterwide) {
20148 					ipha->ipha_ident = (uint16_t)
20149 					    atomic_add_32_nv(
20150 						&ire->ire_ident, 1);
20151 				}
20152 #ifndef _BIG_ENDIAN
20153 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20154 				    (ipha->ipha_ident >> 8);
20155 #endif
20156 			} else {
20157 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20158 
20159 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20160 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20161 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20162 				ASSERT(PDESC_HDRL(pkt_info) >=
20163 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20164 				    TCP_CHECKSUM_SIZE));
20165 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20166 
20167 				if (tcp->tcp_ip_forward_progress) {
20168 					rconfirm = B_TRUE;
20169 					tcp->tcp_ip_forward_progress = B_FALSE;
20170 				}
20171 			}
20172 
20173 			/* at least one payload span, and at most two */
20174 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20175 
20176 			/* add the packet descriptor to Multidata */
20177 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20178 			    KM_NOSLEEP)) == NULL) {
20179 				/*
20180 				 * Any failure other than ENOMEM indicates
20181 				 * that we have passed in invalid pkt_info
20182 				 * or parameters to mmd_addpdesc, which must
20183 				 * not happen.
20184 				 *
20185 				 * EINVAL is a result of failure on boundary
20186 				 * checks against the pkt_info contents.  It
20187 				 * should not happen, and we panic because
20188 				 * either there's horrible heap corruption,
20189 				 * and/or programming mistake.
20190 				 */
20191 				if (err != ENOMEM) {
20192 					cmn_err(CE_PANIC, "tcp_multisend: "
20193 					    "pdesc logic error detected for "
20194 					    "tcp %p mmd %p pinfo %p (%d)\n",
20195 					    (void *)tcp, (void *)mmd,
20196 					    (void *)pkt_info, err);
20197 				}
20198 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20199 				goto legacy_send; /* out_of_mem */
20200 			}
20201 			ASSERT(pkt != NULL);
20202 
20203 			/* calculate IP header and TCP checksums */
20204 			if (af == AF_INET) {
20205 				/* calculate pseudo-header checksum */
20206 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20207 				    (src >> 16) + (src & 0xFFFF);
20208 
20209 				/* offset for TCP header checksum */
20210 				up = IPH_TCPH_CHECKSUMP(ipha,
20211 				    IP_SIMPLE_HDR_LENGTH);
20212 			} else {
20213 				up = (uint16_t *)&ip6h->ip6_src;
20214 
20215 				/* calculate pseudo-header checksum */
20216 				cksum = up[0] + up[1] + up[2] + up[3] +
20217 				    up[4] + up[5] + up[6] + up[7] +
20218 				    up[8] + up[9] + up[10] + up[11] +
20219 				    up[12] + up[13] + up[14] + up[15];
20220 
20221 				/* Fold the initial sum */
20222 				cksum = (cksum & 0xffff) + (cksum >> 16);
20223 
20224 				up = (uint16_t *)(((uchar_t *)ip6h) +
20225 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20226 			}
20227 
20228 			if (hwcksum_flags & HCK_FULLCKSUM) {
20229 				/* clear checksum field for hardware */
20230 				*up = 0;
20231 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20232 				uint32_t sum;
20233 
20234 				/* pseudo-header checksumming */
20235 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20236 				sum = (sum & 0xFFFF) + (sum >> 16);
20237 				*up = (sum & 0xFFFF) + (sum >> 16);
20238 			} else {
20239 				/* software checksumming */
20240 				TCP_STAT(tcps, tcp_out_sw_cksum);
20241 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20242 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20243 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20244 				    cksum + IP_TCP_CSUM_COMP);
20245 				if (*up == 0)
20246 					*up = 0xFFFF;
20247 			}
20248 
20249 			/* IPv4 header checksum */
20250 			if (af == AF_INET) {
20251 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20252 					ipha->ipha_hdr_checksum = 0;
20253 				} else {
20254 					IP_HDR_CKSUM(ipha, cksum,
20255 					    ((uint32_t *)ipha)[0],
20256 					    ((uint16_t *)ipha)[4]);
20257 				}
20258 			}
20259 
20260 			if (af == AF_INET &&
20261 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20262 			    af == AF_INET6 &&
20263 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20264 				mblk_t	*mp, *mp1;
20265 				uchar_t	*hdr_rptr, *hdr_wptr;
20266 				uchar_t	*pld_rptr, *pld_wptr;
20267 
20268 				/*
20269 				 * We reconstruct a pseudo packet for the hooks
20270 				 * framework using mmd_transform_link().
20271 				 * If it is a split packet we pullup the
20272 				 * payload. FW_HOOKS expects a pkt comprising
20273 				 * of two mblks: a header and the payload.
20274 				 */
20275 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20276 					TCP_STAT(tcps, tcp_mdt_allocfail);
20277 					goto legacy_send;
20278 				}
20279 
20280 				if (pkt_info->pld_cnt > 1) {
20281 					/* split payload, more than one pld */
20282 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20283 					    NULL) {
20284 						freemsg(mp);
20285 						TCP_STAT(tcps,
20286 						    tcp_mdt_allocfail);
20287 						goto legacy_send;
20288 					}
20289 					freemsg(mp->b_cont);
20290 					mp->b_cont = mp1;
20291 				} else {
20292 					mp1 = mp->b_cont;
20293 				}
20294 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20295 
20296 				/*
20297 				 * Remember the message offsets. This is so we
20298 				 * can detect changes when we return from the
20299 				 * FW_HOOKS callbacks.
20300 				 */
20301 				hdr_rptr = mp->b_rptr;
20302 				hdr_wptr = mp->b_wptr;
20303 				pld_rptr = mp->b_cont->b_rptr;
20304 				pld_wptr = mp->b_cont->b_wptr;
20305 
20306 				if (af == AF_INET) {
20307 					DTRACE_PROBE4(
20308 					    ip4__physical__out__start,
20309 					    ill_t *, NULL,
20310 					    ill_t *, ill,
20311 					    ipha_t *, ipha,
20312 					    mblk_t *, mp);
20313 					FW_HOOKS(
20314 					    ipst->ips_ip4_physical_out_event,
20315 					    ipst->ips_ipv4firewall_physical_out,
20316 					    NULL, ill, ipha, mp, mp, 0, ipst);
20317 					DTRACE_PROBE1(
20318 					    ip4__physical__out__end,
20319 					    mblk_t *, mp);
20320 				} else {
20321 					DTRACE_PROBE4(
20322 					    ip6__physical__out_start,
20323 					    ill_t *, NULL,
20324 					    ill_t *, ill,
20325 					    ip6_t *, ip6h,
20326 					    mblk_t *, mp);
20327 					FW_HOOKS6(
20328 					    ipst->ips_ip6_physical_out_event,
20329 					    ipst->ips_ipv6firewall_physical_out,
20330 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20331 					DTRACE_PROBE1(
20332 					    ip6__physical__out__end,
20333 					    mblk_t *, mp);
20334 				}
20335 
20336 				if (mp == NULL ||
20337 				    (mp1 = mp->b_cont) == NULL ||
20338 				    mp->b_rptr != hdr_rptr ||
20339 				    mp->b_wptr != hdr_wptr ||
20340 				    mp1->b_rptr != pld_rptr ||
20341 				    mp1->b_wptr != pld_wptr ||
20342 				    mp1->b_cont != NULL) {
20343 					/*
20344 					 * We abandon multidata processing and
20345 					 * return to the normal path, either
20346 					 * when a packet is blocked, or when
20347 					 * the boundaries of header buffer or
20348 					 * payload buffer have been changed by
20349 					 * FW_HOOKS[6].
20350 					 */
20351 					if (mp != NULL)
20352 						freemsg(mp);
20353 					goto legacy_send;
20354 				}
20355 				/* Finished with the pseudo packet */
20356 				freemsg(mp);
20357 			}
20358 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
20359 			    ill, ipha, ip6h);
20360 			/* advance header offset */
20361 			cur_hdr_off += hdr_frag_sz;
20362 
20363 			obbytes += tcp->tcp_last_sent_len;
20364 			++obsegs;
20365 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20366 		    *tail_unsent > 0);
20367 
20368 		if ((*xmit_tail)->b_next == NULL) {
20369 			/*
20370 			 * Store the lbolt used for RTT estimation. We can only
20371 			 * record one timestamp per mblk so we do it when we
20372 			 * reach the end of the payload buffer. Also we only
20373 			 * take a new timestamp sample when the previous timed
20374 			 * data from the same mblk has been ack'ed.
20375 			 */
20376 			(*xmit_tail)->b_prev = local_time;
20377 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20378 		}
20379 
20380 		ASSERT(*tail_unsent >= 0);
20381 		if (*tail_unsent > 0) {
20382 			/*
20383 			 * We got here because we broke out of the above
20384 			 * loop due to of one of the following cases:
20385 			 *
20386 			 *   1. len < adjusted MSS (i.e. small),
20387 			 *   2. Sender SWS avoidance,
20388 			 *   3. max_pld is zero.
20389 			 *
20390 			 * We are done for this Multidata, so trim our
20391 			 * last payload buffer (if any) accordingly.
20392 			 */
20393 			if (md_pbuf != NULL)
20394 				md_pbuf->b_wptr -= *tail_unsent;
20395 		} else if (*usable > 0) {
20396 			*xmit_tail = (*xmit_tail)->b_cont;
20397 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20398 			    (uintptr_t)INT_MAX);
20399 			*tail_unsent = (int)MBLKL(*xmit_tail);
20400 			add_buffer = B_TRUE;
20401 		}
20402 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20403 	    (tcp_mdt_chain || max_pld > 0));
20404 
20405 	if (md_mp_head != NULL) {
20406 		/* send everything down */
20407 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20408 		    &rconfirm);
20409 	}
20410 
20411 #undef PREP_NEW_MULTIDATA
20412 #undef PREP_NEW_PBUF
20413 #undef IPVER
20414 
20415 	IRE_REFRELE(ire);
20416 	return (0);
20417 }
20418 
20419 /*
20420  * A wrapper function for sending one or more Multidata messages down to
20421  * the module below ip; this routine does not release the reference of the
20422  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20423  */
20424 static void
20425 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20426     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20427 {
20428 	uint64_t delta;
20429 	nce_t *nce;
20430 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20431 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20432 
20433 	ASSERT(ire != NULL && ill != NULL);
20434 	ASSERT(ire->ire_stq != NULL);
20435 	ASSERT(md_mp_head != NULL);
20436 	ASSERT(rconfirm != NULL);
20437 
20438 	/* adjust MIBs and IRE timestamp */
20439 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
20440 	tcp->tcp_obsegs += obsegs;
20441 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20442 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20443 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20444 
20445 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20446 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20447 	} else {
20448 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20449 	}
20450 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20451 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20452 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20453 
20454 	ire->ire_ob_pkt_count += obsegs;
20455 	if (ire->ire_ipif != NULL)
20456 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20457 	ire->ire_last_used_time = lbolt;
20458 
20459 	if ((tcp->tcp_ipversion == IPV4_VERSION &&
20460 	    ipst->ips_ip4_observe.he_interested) ||
20461 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20462 	    ipst->ips_ip6_observe.he_interested)) {
20463 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
20464 		pdesc_t *dl_pkt;
20465 		pdescinfo_t pinfo;
20466 		mblk_t *nmp;
20467 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
20468 
20469 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
20470 		    (dl_pkt != NULL);
20471 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
20472 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
20473 				continue;
20474 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
20475 			    ALL_ZONES, ill, ipst);
20476 			freemsg(nmp);
20477 		}
20478 	}
20479 
20480 	/* send it down */
20481 	putnext(ire->ire_stq, md_mp_head);
20482 
20483 	/* we're done for TCP/IPv4 */
20484 	if (tcp->tcp_ipversion == IPV4_VERSION)
20485 		return;
20486 
20487 	nce = ire->ire_nce;
20488 
20489 	ASSERT(nce != NULL);
20490 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20491 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20492 
20493 	/* reachability confirmation? */
20494 	if (*rconfirm) {
20495 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20496 		if (nce->nce_state != ND_REACHABLE) {
20497 			mutex_enter(&nce->nce_lock);
20498 			nce->nce_state = ND_REACHABLE;
20499 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20500 			mutex_exit(&nce->nce_lock);
20501 			(void) untimeout(nce->nce_timeout_id);
20502 			if (ip_debug > 2) {
20503 				/* ip1dbg */
20504 				pr_addr_dbg("tcp_multisend_data: state "
20505 				    "for %s changed to REACHABLE\n",
20506 				    AF_INET6, &ire->ire_addr_v6);
20507 			}
20508 		}
20509 		/* reset transport reachability confirmation */
20510 		*rconfirm = B_FALSE;
20511 	}
20512 
20513 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20514 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20515 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20516 
20517 	if (delta > (uint64_t)ill->ill_reachable_time) {
20518 		mutex_enter(&nce->nce_lock);
20519 		switch (nce->nce_state) {
20520 		case ND_REACHABLE:
20521 		case ND_STALE:
20522 			/*
20523 			 * ND_REACHABLE is identical to ND_STALE in this
20524 			 * specific case. If reachable time has expired for
20525 			 * this neighbor (delta is greater than reachable
20526 			 * time), conceptually, the neighbor cache is no
20527 			 * longer in REACHABLE state, but already in STALE
20528 			 * state.  So the correct transition here is to
20529 			 * ND_DELAY.
20530 			 */
20531 			nce->nce_state = ND_DELAY;
20532 			mutex_exit(&nce->nce_lock);
20533 			NDP_RESTART_TIMER(nce,
20534 			    ipst->ips_delay_first_probe_time);
20535 			if (ip_debug > 3) {
20536 				/* ip2dbg */
20537 				pr_addr_dbg("tcp_multisend_data: state "
20538 				    "for %s changed to DELAY\n",
20539 				    AF_INET6, &ire->ire_addr_v6);
20540 			}
20541 			break;
20542 		case ND_DELAY:
20543 		case ND_PROBE:
20544 			mutex_exit(&nce->nce_lock);
20545 			/* Timers have already started */
20546 			break;
20547 		case ND_UNREACHABLE:
20548 			/*
20549 			 * ndp timer has detected that this nce is
20550 			 * unreachable and initiated deleting this nce
20551 			 * and all its associated IREs. This is a race
20552 			 * where we found the ire before it was deleted
20553 			 * and have just sent out a packet using this
20554 			 * unreachable nce.
20555 			 */
20556 			mutex_exit(&nce->nce_lock);
20557 			break;
20558 		default:
20559 			ASSERT(0);
20560 		}
20561 	}
20562 }
20563 
20564 /*
20565  * Derived from tcp_send_data().
20566  */
20567 static void
20568 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20569     int num_lso_seg)
20570 {
20571 	ipha_t		*ipha;
20572 	mblk_t		*ire_fp_mp;
20573 	uint_t		ire_fp_mp_len;
20574 	uint32_t	hcksum_txflags = 0;
20575 	ipaddr_t	src;
20576 	ipaddr_t	dst;
20577 	uint32_t	cksum;
20578 	uint16_t	*up;
20579 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20580 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20581 
20582 	ASSERT(DB_TYPE(mp) == M_DATA);
20583 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20584 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20585 	ASSERT(tcp->tcp_connp != NULL);
20586 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20587 
20588 	ipha = (ipha_t *)mp->b_rptr;
20589 	src = ipha->ipha_src;
20590 	dst = ipha->ipha_dst;
20591 
20592 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
20593 
20594 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20595 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20596 	    num_lso_seg);
20597 #ifndef _BIG_ENDIAN
20598 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20599 #endif
20600 	if (tcp->tcp_snd_zcopy_aware) {
20601 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20602 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20603 			mp = tcp_zcopy_disable(tcp, mp);
20604 	}
20605 
20606 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20607 		ASSERT(ill->ill_hcksum_capab != NULL);
20608 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20609 	}
20610 
20611 	/*
20612 	 * Since the TCP checksum should be recalculated by h/w, we can just
20613 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20614 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20615 	 * The partial pseudo-header excludes TCP length, that was calculated
20616 	 * in tcp_send(), so to zero *up before further processing.
20617 	 */
20618 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20619 
20620 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20621 	*up = 0;
20622 
20623 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20624 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20625 
20626 	/*
20627 	 * Append LSO flags and mss to the mp.
20628 	 */
20629 	lso_info_set(mp, mss, HW_LSO);
20630 
20631 	ipha->ipha_fragment_offset_and_flags |=
20632 	    (uint32_t)htons(ire->ire_frag_flag);
20633 
20634 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20635 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20636 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20637 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20638 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20639 
20640 	UPDATE_OB_PKT_COUNT(ire);
20641 	ire->ire_last_used_time = lbolt;
20642 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20643 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20644 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20645 	    ntohs(ipha->ipha_length));
20646 
20647 	DTRACE_PROBE4(ip4__physical__out__start,
20648 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
20649 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
20650 	    ipst->ips_ipv4firewall_physical_out, NULL,
20651 	    ill, ipha, mp, mp, 0, ipst);
20652 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20653 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
20654 
20655 	if (mp != NULL) {
20656 		if (ipst->ips_ip4_observe.he_interested) {
20657 			zoneid_t szone;
20658 
20659 			if (ire_fp_mp_len != 0)
20660 				mp->b_rptr += ire_fp_mp_len;
20661 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
20662 			    ipst, ALL_ZONES);
20663 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
20664 			    ALL_ZONES, ill, ipst);
20665 			if (ire_fp_mp_len != 0)
20666 				mp->b_rptr -= ire_fp_mp_len;
20667 		}
20668 
20669 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
20670 	}
20671 }
20672 
20673 /*
20674  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20675  * scheme, and returns one of the following:
20676  *
20677  * -1 = failed allocation.
20678  *  0 = success; burst count reached, or usable send window is too small,
20679  *      and that we'd rather wait until later before sending again.
20680  *  1 = success; we are called from tcp_multisend(), and both usable send
20681  *      window and tail_unsent are greater than the MDT threshold, and thus
20682  *      Multidata Transmit should be used instead.
20683  */
20684 static int
20685 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20686     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20687     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20688     const int mdt_thres)
20689 {
20690 	int num_burst_seg = tcp->tcp_snd_burst;
20691 	ire_t		*ire = NULL;
20692 	ill_t		*ill = NULL;
20693 	mblk_t		*ire_fp_mp = NULL;
20694 	uint_t		ire_fp_mp_len = 0;
20695 	int		num_lso_seg = 1;
20696 	uint_t		lso_usable;
20697 	boolean_t	do_lso_send = B_FALSE;
20698 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20699 
20700 	/*
20701 	 * Check LSO capability before any further work. And the similar check
20702 	 * need to be done in for(;;) loop.
20703 	 * LSO will be deployed when therer is more than one mss of available
20704 	 * data and a burst transmission is allowed.
20705 	 */
20706 	if (tcp->tcp_lso &&
20707 	    (tcp->tcp_valid_bits == 0 ||
20708 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20709 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20710 		/*
20711 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20712 		 * Double check LSO usability before going further, since the
20713 		 * underlying interface could have been changed. In case of any
20714 		 * change of LSO capability, set tcp_ire_ill_check_done to
20715 		 * B_FALSE to force to check the ILL with the next send.
20716 		 */
20717 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
20718 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
20719 			/*
20720 			 * Enable LSO with this transmission.
20721 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
20722 			 * IRE_REFRELE(ire) should be called before return.
20723 			 */
20724 			do_lso_send = B_TRUE;
20725 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
20726 			ire_fp_mp_len = MBLKL(ire_fp_mp);
20727 			/* Round up to multiple of 4 */
20728 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
20729 		} else {
20730 			tcp->tcp_lso = B_FALSE;
20731 			tcp->tcp_ire_ill_check_done = B_FALSE;
20732 			do_lso_send = B_FALSE;
20733 			ill = NULL;
20734 		}
20735 	}
20736 
20737 	for (;;) {
20738 		struct datab	*db;
20739 		tcph_t		*tcph;
20740 		uint32_t	sum;
20741 		mblk_t		*mp, *mp1;
20742 		uchar_t		*rptr;
20743 		int		len;
20744 
20745 		/*
20746 		 * If we're called by tcp_multisend(), and the amount of
20747 		 * sendable data as well as the size of current xmit_tail
20748 		 * is beyond the MDT threshold, return to the caller and
20749 		 * let the large data transmit be done using MDT.
20750 		 */
20751 		if (*usable > 0 && *usable > mdt_thres &&
20752 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20753 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20754 			ASSERT(tcp->tcp_mdt);
20755 			return (1);	/* success; do large send */
20756 		}
20757 
20758 		if (num_burst_seg == 0)
20759 			break;		/* success; burst count reached */
20760 
20761 		/*
20762 		 * Calculate the maximum payload length we can send in *one*
20763 		 * time.
20764 		 */
20765 		if (do_lso_send) {
20766 			/*
20767 			 * Check whether need to do LSO any more.
20768 			 */
20769 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20770 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
20771 				lso_usable = MIN(lso_usable,
20772 				    num_burst_seg * mss);
20773 
20774 				num_lso_seg = lso_usable / mss;
20775 				if (lso_usable % mss) {
20776 					num_lso_seg++;
20777 					tcp->tcp_last_sent_len = (ushort_t)
20778 					    (lso_usable % mss);
20779 				} else {
20780 					tcp->tcp_last_sent_len = (ushort_t)mss;
20781 				}
20782 			} else {
20783 				do_lso_send = B_FALSE;
20784 				num_lso_seg = 1;
20785 				lso_usable = mss;
20786 			}
20787 		}
20788 
20789 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
20790 
20791 		/*
20792 		 * Adjust num_burst_seg here.
20793 		 */
20794 		num_burst_seg -= num_lso_seg;
20795 
20796 		len = mss;
20797 		if (len > *usable) {
20798 			ASSERT(do_lso_send == B_FALSE);
20799 
20800 			len = *usable;
20801 			if (len <= 0) {
20802 				/* Terminate the loop */
20803 				break;	/* success; too small */
20804 			}
20805 			/*
20806 			 * Sender silly-window avoidance.
20807 			 * Ignore this if we are going to send a
20808 			 * zero window probe out.
20809 			 *
20810 			 * TODO: force data into microscopic window?
20811 			 *	==> (!pushed || (unsent > usable))
20812 			 */
20813 			if (len < (tcp->tcp_max_swnd >> 1) &&
20814 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20815 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20816 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20817 				/*
20818 				 * If the retransmit timer is not running
20819 				 * we start it so that we will retransmit
20820 				 * in the case when the the receiver has
20821 				 * decremented the window.
20822 				 */
20823 				if (*snxt == tcp->tcp_snxt &&
20824 				    *snxt == tcp->tcp_suna) {
20825 					/*
20826 					 * We are not supposed to send
20827 					 * anything.  So let's wait a little
20828 					 * bit longer before breaking SWS
20829 					 * avoidance.
20830 					 *
20831 					 * What should the value be?
20832 					 * Suggestion: MAX(init rexmit time,
20833 					 * tcp->tcp_rto)
20834 					 */
20835 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20836 				}
20837 				break;	/* success; too small */
20838 			}
20839 		}
20840 
20841 		tcph = tcp->tcp_tcph;
20842 
20843 		/*
20844 		 * The reason to adjust len here is that we need to set flags
20845 		 * and calculate checksum.
20846 		 */
20847 		if (do_lso_send)
20848 			len = lso_usable;
20849 
20850 		*usable -= len; /* Approximate - can be adjusted later */
20851 		if (*usable > 0)
20852 			tcph->th_flags[0] = TH_ACK;
20853 		else
20854 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20855 
20856 		/*
20857 		 * Prime pump for IP's checksumming on our behalf
20858 		 * Include the adjustment for a source route if any.
20859 		 */
20860 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20861 		sum = (sum >> 16) + (sum & 0xFFFF);
20862 		U16_TO_ABE16(sum, tcph->th_sum);
20863 
20864 		U32_TO_ABE32(*snxt, tcph->th_seq);
20865 
20866 		/*
20867 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20868 		 * set.  For the case when TCP_FSS_VALID is the only valid
20869 		 * bit (normal active close), branch off only when we think
20870 		 * that the FIN flag needs to be set.  Note for this case,
20871 		 * that (snxt + len) may not reflect the actual seg_len,
20872 		 * as len may be further reduced in tcp_xmit_mp().  If len
20873 		 * gets modified, we will end up here again.
20874 		 */
20875 		if (tcp->tcp_valid_bits != 0 &&
20876 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20877 		    ((*snxt + len) == tcp->tcp_fss))) {
20878 			uchar_t		*prev_rptr;
20879 			uint32_t	prev_snxt = tcp->tcp_snxt;
20880 
20881 			if (*tail_unsent == 0) {
20882 				ASSERT((*xmit_tail)->b_cont != NULL);
20883 				*xmit_tail = (*xmit_tail)->b_cont;
20884 				prev_rptr = (*xmit_tail)->b_rptr;
20885 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20886 				    (*xmit_tail)->b_rptr);
20887 			} else {
20888 				prev_rptr = (*xmit_tail)->b_rptr;
20889 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20890 				    *tail_unsent;
20891 			}
20892 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20893 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20894 			/* Restore tcp_snxt so we get amount sent right. */
20895 			tcp->tcp_snxt = prev_snxt;
20896 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20897 				/*
20898 				 * If the previous timestamp is still in use,
20899 				 * don't stomp on it.
20900 				 */
20901 				if ((*xmit_tail)->b_next == NULL) {
20902 					(*xmit_tail)->b_prev = local_time;
20903 					(*xmit_tail)->b_next =
20904 					    (mblk_t *)(uintptr_t)(*snxt);
20905 				}
20906 			} else
20907 				(*xmit_tail)->b_rptr = prev_rptr;
20908 
20909 			if (mp == NULL) {
20910 				if (ire != NULL)
20911 					IRE_REFRELE(ire);
20912 				return (-1);
20913 			}
20914 			mp1 = mp->b_cont;
20915 
20916 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
20917 				tcp->tcp_last_sent_len = (ushort_t)len;
20918 			while (mp1->b_cont) {
20919 				*xmit_tail = (*xmit_tail)->b_cont;
20920 				(*xmit_tail)->b_prev = local_time;
20921 				(*xmit_tail)->b_next =
20922 				    (mblk_t *)(uintptr_t)(*snxt);
20923 				mp1 = mp1->b_cont;
20924 			}
20925 			*snxt += len;
20926 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20927 			BUMP_LOCAL(tcp->tcp_obsegs);
20928 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20929 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20930 			tcp_send_data(tcp, q, mp);
20931 			continue;
20932 		}
20933 
20934 		*snxt += len;	/* Adjust later if we don't send all of len */
20935 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20936 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20937 
20938 		if (*tail_unsent) {
20939 			/* Are the bytes above us in flight? */
20940 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20941 			if (rptr != (*xmit_tail)->b_rptr) {
20942 				*tail_unsent -= len;
20943 				if (len <= mss) /* LSO is unusable */
20944 					tcp->tcp_last_sent_len = (ushort_t)len;
20945 				len += tcp_hdr_len;
20946 				if (tcp->tcp_ipversion == IPV4_VERSION)
20947 					tcp->tcp_ipha->ipha_length = htons(len);
20948 				else
20949 					tcp->tcp_ip6h->ip6_plen =
20950 					    htons(len -
20951 					    ((char *)&tcp->tcp_ip6h[1] -
20952 					    tcp->tcp_iphc));
20953 				mp = dupb(*xmit_tail);
20954 				if (mp == NULL) {
20955 					if (ire != NULL)
20956 						IRE_REFRELE(ire);
20957 					return (-1);	/* out_of_mem */
20958 				}
20959 				mp->b_rptr = rptr;
20960 				/*
20961 				 * If the old timestamp is no longer in use,
20962 				 * sample a new timestamp now.
20963 				 */
20964 				if ((*xmit_tail)->b_next == NULL) {
20965 					(*xmit_tail)->b_prev = local_time;
20966 					(*xmit_tail)->b_next =
20967 					    (mblk_t *)(uintptr_t)(*snxt-len);
20968 				}
20969 				goto must_alloc;
20970 			}
20971 		} else {
20972 			*xmit_tail = (*xmit_tail)->b_cont;
20973 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20974 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20975 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20976 			    (*xmit_tail)->b_rptr);
20977 		}
20978 
20979 		(*xmit_tail)->b_prev = local_time;
20980 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20981 
20982 		*tail_unsent -= len;
20983 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
20984 			tcp->tcp_last_sent_len = (ushort_t)len;
20985 
20986 		len += tcp_hdr_len;
20987 		if (tcp->tcp_ipversion == IPV4_VERSION)
20988 			tcp->tcp_ipha->ipha_length = htons(len);
20989 		else
20990 			tcp->tcp_ip6h->ip6_plen = htons(len -
20991 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20992 
20993 		mp = dupb(*xmit_tail);
20994 		if (mp == NULL) {
20995 			if (ire != NULL)
20996 				IRE_REFRELE(ire);
20997 			return (-1);	/* out_of_mem */
20998 		}
20999 
21000 		len = tcp_hdr_len;
21001 		/*
21002 		 * There are four reasons to allocate a new hdr mblk:
21003 		 *  1) The bytes above us are in use by another packet
21004 		 *  2) We don't have good alignment
21005 		 *  3) The mblk is being shared
21006 		 *  4) We don't have enough room for a header
21007 		 */
21008 		rptr = mp->b_rptr - len;
21009 		if (!OK_32PTR(rptr) ||
21010 		    ((db = mp->b_datap), db->db_ref != 2) ||
21011 		    rptr < db->db_base + ire_fp_mp_len) {
21012 			/* NOTE: we assume allocb returns an OK_32PTR */
21013 
21014 		must_alloc:;
21015 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21016 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21017 			if (mp1 == NULL) {
21018 				freemsg(mp);
21019 				if (ire != NULL)
21020 					IRE_REFRELE(ire);
21021 				return (-1);	/* out_of_mem */
21022 			}
21023 			mp1->b_cont = mp;
21024 			mp = mp1;
21025 			/* Leave room for Link Level header */
21026 			len = tcp_hdr_len;
21027 			rptr =
21028 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21029 			mp->b_wptr = &rptr[len];
21030 		}
21031 
21032 		/*
21033 		 * Fill in the header using the template header, and add
21034 		 * options such as time-stamp, ECN and/or SACK, as needed.
21035 		 */
21036 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21037 
21038 		mp->b_rptr = rptr;
21039 
21040 		if (*tail_unsent) {
21041 			int spill = *tail_unsent;
21042 
21043 			mp1 = mp->b_cont;
21044 			if (mp1 == NULL)
21045 				mp1 = mp;
21046 
21047 			/*
21048 			 * If we're a little short, tack on more mblks until
21049 			 * there is no more spillover.
21050 			 */
21051 			while (spill < 0) {
21052 				mblk_t *nmp;
21053 				int nmpsz;
21054 
21055 				nmp = (*xmit_tail)->b_cont;
21056 				nmpsz = MBLKL(nmp);
21057 
21058 				/*
21059 				 * Excess data in mblk; can we split it?
21060 				 * If MDT is enabled for the connection,
21061 				 * keep on splitting as this is a transient
21062 				 * send path.
21063 				 */
21064 				if (!do_lso_send && !tcp->tcp_mdt &&
21065 				    (spill + nmpsz > 0)) {
21066 					/*
21067 					 * Don't split if stream head was
21068 					 * told to break up larger writes
21069 					 * into smaller ones.
21070 					 */
21071 					if (tcp->tcp_maxpsz > 0)
21072 						break;
21073 
21074 					/*
21075 					 * Next mblk is less than SMSS/2
21076 					 * rounded up to nearest 64-byte;
21077 					 * let it get sent as part of the
21078 					 * next segment.
21079 					 */
21080 					if (tcp->tcp_localnet &&
21081 					    !tcp->tcp_cork &&
21082 					    (nmpsz < roundup((mss >> 1), 64)))
21083 						break;
21084 				}
21085 
21086 				*xmit_tail = nmp;
21087 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21088 				/* Stash for rtt use later */
21089 				(*xmit_tail)->b_prev = local_time;
21090 				(*xmit_tail)->b_next =
21091 				    (mblk_t *)(uintptr_t)(*snxt - len);
21092 				mp1->b_cont = dupb(*xmit_tail);
21093 				mp1 = mp1->b_cont;
21094 
21095 				spill += nmpsz;
21096 				if (mp1 == NULL) {
21097 					*tail_unsent = spill;
21098 					freemsg(mp);
21099 					if (ire != NULL)
21100 						IRE_REFRELE(ire);
21101 					return (-1);	/* out_of_mem */
21102 				}
21103 			}
21104 
21105 			/* Trim back any surplus on the last mblk */
21106 			if (spill >= 0) {
21107 				mp1->b_wptr -= spill;
21108 				*tail_unsent = spill;
21109 			} else {
21110 				/*
21111 				 * We did not send everything we could in
21112 				 * order to remain within the b_cont limit.
21113 				 */
21114 				*usable -= spill;
21115 				*snxt += spill;
21116 				tcp->tcp_last_sent_len += spill;
21117 				UPDATE_MIB(&tcps->tcps_mib,
21118 				    tcpOutDataBytes, spill);
21119 				/*
21120 				 * Adjust the checksum
21121 				 */
21122 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21123 				sum += spill;
21124 				sum = (sum >> 16) + (sum & 0xFFFF);
21125 				U16_TO_ABE16(sum, tcph->th_sum);
21126 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21127 					sum = ntohs(
21128 					    ((ipha_t *)rptr)->ipha_length) +
21129 					    spill;
21130 					((ipha_t *)rptr)->ipha_length =
21131 					    htons(sum);
21132 				} else {
21133 					sum = ntohs(
21134 					    ((ip6_t *)rptr)->ip6_plen) +
21135 					    spill;
21136 					((ip6_t *)rptr)->ip6_plen =
21137 					    htons(sum);
21138 				}
21139 				*tail_unsent = 0;
21140 			}
21141 		}
21142 		if (tcp->tcp_ip_forward_progress) {
21143 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21144 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21145 			tcp->tcp_ip_forward_progress = B_FALSE;
21146 		}
21147 
21148 		if (do_lso_send) {
21149 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21150 			    num_lso_seg);
21151 			tcp->tcp_obsegs += num_lso_seg;
21152 
21153 			TCP_STAT(tcps, tcp_lso_times);
21154 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21155 		} else {
21156 			tcp_send_data(tcp, q, mp);
21157 			BUMP_LOCAL(tcp->tcp_obsegs);
21158 		}
21159 	}
21160 
21161 	if (ire != NULL)
21162 		IRE_REFRELE(ire);
21163 	return (0);
21164 }
21165 
21166 /* Unlink and return any mblk that looks like it contains a MDT info */
21167 static mblk_t *
21168 tcp_mdt_info_mp(mblk_t *mp)
21169 {
21170 	mblk_t	*prev_mp;
21171 
21172 	for (;;) {
21173 		prev_mp = mp;
21174 		/* no more to process? */
21175 		if ((mp = mp->b_cont) == NULL)
21176 			break;
21177 
21178 		switch (DB_TYPE(mp)) {
21179 		case M_CTL:
21180 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21181 				continue;
21182 			ASSERT(prev_mp != NULL);
21183 			prev_mp->b_cont = mp->b_cont;
21184 			mp->b_cont = NULL;
21185 			return (mp);
21186 		default:
21187 			break;
21188 		}
21189 	}
21190 	return (mp);
21191 }
21192 
21193 /* MDT info update routine, called when IP notifies us about MDT */
21194 static void
21195 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21196 {
21197 	boolean_t prev_state;
21198 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21199 
21200 	/*
21201 	 * IP is telling us to abort MDT on this connection?  We know
21202 	 * this because the capability is only turned off when IP
21203 	 * encounters some pathological cases, e.g. link-layer change
21204 	 * where the new driver doesn't support MDT, or in situation
21205 	 * where MDT usage on the link-layer has been switched off.
21206 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21207 	 * if the link-layer doesn't support MDT, and if it does, it
21208 	 * will indicate that the feature is to be turned on.
21209 	 */
21210 	prev_state = tcp->tcp_mdt;
21211 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21212 	if (!tcp->tcp_mdt && !first) {
21213 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21214 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21215 		    (void *)tcp->tcp_connp));
21216 	}
21217 
21218 	/*
21219 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21220 	 * so disable MDT otherwise.  The checks are done here
21221 	 * and in tcp_wput_data().
21222 	 */
21223 	if (tcp->tcp_mdt &&
21224 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21225 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21226 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21227 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21228 		tcp->tcp_mdt = B_FALSE;
21229 
21230 	if (tcp->tcp_mdt) {
21231 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21232 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21233 			    "version (%d), expected version is %d",
21234 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21235 			tcp->tcp_mdt = B_FALSE;
21236 			return;
21237 		}
21238 
21239 		/*
21240 		 * We need the driver to be able to handle at least three
21241 		 * spans per packet in order for tcp MDT to be utilized.
21242 		 * The first is for the header portion, while the rest are
21243 		 * needed to handle a packet that straddles across two
21244 		 * virtually non-contiguous buffers; a typical tcp packet
21245 		 * therefore consists of only two spans.  Note that we take
21246 		 * a zero as "don't care".
21247 		 */
21248 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21249 		    mdt_capab->ill_mdt_span_limit < 3) {
21250 			tcp->tcp_mdt = B_FALSE;
21251 			return;
21252 		}
21253 
21254 		/* a zero means driver wants default value */
21255 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21256 		    tcps->tcps_mdt_max_pbufs);
21257 		if (tcp->tcp_mdt_max_pld == 0)
21258 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21259 
21260 		/* ensure 32-bit alignment */
21261 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21262 		    mdt_capab->ill_mdt_hdr_head), 4);
21263 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21264 		    mdt_capab->ill_mdt_hdr_tail), 4);
21265 
21266 		if (!first && !prev_state) {
21267 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21268 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21269 			    (void *)tcp->tcp_connp));
21270 		}
21271 	}
21272 }
21273 
21274 /* Unlink and return any mblk that looks like it contains a LSO info */
21275 static mblk_t *
21276 tcp_lso_info_mp(mblk_t *mp)
21277 {
21278 	mblk_t	*prev_mp;
21279 
21280 	for (;;) {
21281 		prev_mp = mp;
21282 		/* no more to process? */
21283 		if ((mp = mp->b_cont) == NULL)
21284 			break;
21285 
21286 		switch (DB_TYPE(mp)) {
21287 		case M_CTL:
21288 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21289 				continue;
21290 			ASSERT(prev_mp != NULL);
21291 			prev_mp->b_cont = mp->b_cont;
21292 			mp->b_cont = NULL;
21293 			return (mp);
21294 		default:
21295 			break;
21296 		}
21297 	}
21298 
21299 	return (mp);
21300 }
21301 
21302 /* LSO info update routine, called when IP notifies us about LSO */
21303 static void
21304 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21305 {
21306 	tcp_stack_t *tcps = tcp->tcp_tcps;
21307 
21308 	/*
21309 	 * IP is telling us to abort LSO on this connection?  We know
21310 	 * this because the capability is only turned off when IP
21311 	 * encounters some pathological cases, e.g. link-layer change
21312 	 * where the new NIC/driver doesn't support LSO, or in situation
21313 	 * where LSO usage on the link-layer has been switched off.
21314 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21315 	 * if the link-layer doesn't support LSO, and if it does, it
21316 	 * will indicate that the feature is to be turned on.
21317 	 */
21318 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21319 	TCP_STAT(tcps, tcp_lso_enabled);
21320 
21321 	/*
21322 	 * We currently only support LSO on simple TCP/IPv4,
21323 	 * so disable LSO otherwise.  The checks are done here
21324 	 * and in tcp_wput_data().
21325 	 */
21326 	if (tcp->tcp_lso &&
21327 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21328 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21329 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21330 		tcp->tcp_lso = B_FALSE;
21331 		TCP_STAT(tcps, tcp_lso_disabled);
21332 	} else {
21333 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21334 		    lso_capab->ill_lso_max);
21335 	}
21336 }
21337 
21338 static void
21339 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21340 {
21341 	conn_t *connp = tcp->tcp_connp;
21342 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21343 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21344 
21345 	ASSERT(ire != NULL);
21346 
21347 	/*
21348 	 * We may be in the fastpath here, and although we essentially do
21349 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21350 	 * we try to keep things as brief as possible.  After all, these
21351 	 * are only best-effort checks, and we do more thorough ones prior
21352 	 * to calling tcp_send()/tcp_multisend().
21353 	 */
21354 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21355 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21356 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21357 	    !(ire->ire_flags & RTF_MULTIRT) &&
21358 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21359 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21360 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21361 			/* Cache the result */
21362 			connp->conn_lso_ok = B_TRUE;
21363 
21364 			ASSERT(ill->ill_lso_capab != NULL);
21365 			if (!ill->ill_lso_capab->ill_lso_on) {
21366 				ill->ill_lso_capab->ill_lso_on = 1;
21367 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21368 				    "LSO for interface %s\n", (void *)connp,
21369 				    ill->ill_name));
21370 			}
21371 			tcp_lso_update(tcp, ill->ill_lso_capab);
21372 		} else if (ipst->ips_ip_multidata_outbound &&
21373 		    ILL_MDT_CAPABLE(ill)) {
21374 			/* Cache the result */
21375 			connp->conn_mdt_ok = B_TRUE;
21376 
21377 			ASSERT(ill->ill_mdt_capab != NULL);
21378 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21379 				ill->ill_mdt_capab->ill_mdt_on = 1;
21380 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21381 				    "MDT for interface %s\n", (void *)connp,
21382 				    ill->ill_name));
21383 			}
21384 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21385 		}
21386 	}
21387 
21388 	/*
21389 	 * The goal is to reduce the number of generated tcp segments by
21390 	 * setting the maxpsz multiplier to 0; this will have an affect on
21391 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21392 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21393 	 * of outbound segments and incoming ACKs, thus allowing for better
21394 	 * network and system performance.  In contrast the legacy behavior
21395 	 * may result in sending less than SMSS size, because the last mblk
21396 	 * for some packets may have more data than needed to make up SMSS,
21397 	 * and the legacy code refused to "split" it.
21398 	 *
21399 	 * We apply the new behavior on following situations:
21400 	 *
21401 	 *   1) Loopback connections,
21402 	 *   2) Connections in which the remote peer is not on local subnet,
21403 	 *   3) Local subnet connections over the bge interface (see below).
21404 	 *
21405 	 * Ideally, we would like this behavior to apply for interfaces other
21406 	 * than bge.  However, doing so would negatively impact drivers which
21407 	 * perform dynamic mapping and unmapping of DMA resources, which are
21408 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21409 	 * packet will be generated by tcp).  The bge driver does not suffer
21410 	 * from this, as it copies the mblks into pre-mapped buffers, and
21411 	 * therefore does not require more I/O resources than before.
21412 	 *
21413 	 * Otherwise, this behavior is present on all network interfaces when
21414 	 * the destination endpoint is non-local, since reducing the number
21415 	 * of packets in general is good for the network.
21416 	 *
21417 	 * TODO We need to remove this hard-coded conditional for bge once
21418 	 *	a better "self-tuning" mechanism, or a way to comprehend
21419 	 *	the driver transmit strategy is devised.  Until the solution
21420 	 *	is found and well understood, we live with this hack.
21421 	 */
21422 	if (!tcp_static_maxpsz &&
21423 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21424 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21425 		/* override the default value */
21426 		tcp->tcp_maxpsz = 0;
21427 
21428 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21429 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21430 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21431 	}
21432 
21433 	/* set the stream head parameters accordingly */
21434 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21435 }
21436 
21437 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21438 static void
21439 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21440 {
21441 	uchar_t	fval = *mp->b_rptr;
21442 	mblk_t	*tail;
21443 	queue_t	*q = tcp->tcp_wq;
21444 
21445 	/* TODO: How should flush interact with urgent data? */
21446 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21447 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21448 		/*
21449 		 * Flush only data that has not yet been put on the wire.  If
21450 		 * we flush data that we have already transmitted, life, as we
21451 		 * know it, may come to an end.
21452 		 */
21453 		tail = tcp->tcp_xmit_tail;
21454 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21455 		tcp->tcp_xmit_tail_unsent = 0;
21456 		tcp->tcp_unsent = 0;
21457 		if (tail->b_wptr != tail->b_rptr)
21458 			tail = tail->b_cont;
21459 		if (tail) {
21460 			mblk_t **excess = &tcp->tcp_xmit_head;
21461 			for (;;) {
21462 				mblk_t *mp1 = *excess;
21463 				if (mp1 == tail)
21464 					break;
21465 				tcp->tcp_xmit_tail = mp1;
21466 				tcp->tcp_xmit_last = mp1;
21467 				excess = &mp1->b_cont;
21468 			}
21469 			*excess = NULL;
21470 			tcp_close_mpp(&tail);
21471 			if (tcp->tcp_snd_zcopy_aware)
21472 				tcp_zcopy_notify(tcp);
21473 		}
21474 		/*
21475 		 * We have no unsent data, so unsent must be less than
21476 		 * tcp_xmit_lowater, so re-enable flow.
21477 		 */
21478 		mutex_enter(&tcp->tcp_non_sq_lock);
21479 		if (tcp->tcp_flow_stopped) {
21480 			tcp_clrqfull(tcp);
21481 		}
21482 		mutex_exit(&tcp->tcp_non_sq_lock);
21483 	}
21484 	/*
21485 	 * TODO: you can't just flush these, you have to increase rwnd for one
21486 	 * thing.  For another, how should urgent data interact?
21487 	 */
21488 	if (fval & FLUSHR) {
21489 		*mp->b_rptr = fval & ~FLUSHW;
21490 		/* XXX */
21491 		qreply(q, mp);
21492 		return;
21493 	}
21494 	freemsg(mp);
21495 }
21496 
21497 /*
21498  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21499  * messages.
21500  */
21501 static void
21502 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21503 {
21504 	mblk_t	*mp1;
21505 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
21506 	STRUCT_HANDLE(strbuf, sb);
21507 	queue_t *q = tcp->tcp_wq;
21508 	int	error;
21509 	uint_t	addrlen;
21510 
21511 	/* Make sure it is one of ours. */
21512 	switch (iocp->ioc_cmd) {
21513 	case TI_GETMYNAME:
21514 	case TI_GETPEERNAME:
21515 		break;
21516 	default:
21517 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21518 		return;
21519 	}
21520 	switch (mi_copy_state(q, mp, &mp1)) {
21521 	case -1:
21522 		return;
21523 	case MI_COPY_CASE(MI_COPY_IN, 1):
21524 		break;
21525 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21526 		/* Copy out the strbuf. */
21527 		mi_copyout(q, mp);
21528 		return;
21529 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21530 		/* All done. */
21531 		mi_copy_done(q, mp, 0);
21532 		return;
21533 	default:
21534 		mi_copy_done(q, mp, EPROTO);
21535 		return;
21536 	}
21537 	/* Check alignment of the strbuf */
21538 	if (!OK_32PTR(mp1->b_rptr)) {
21539 		mi_copy_done(q, mp, EINVAL);
21540 		return;
21541 	}
21542 
21543 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
21544 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21545 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21546 		mi_copy_done(q, mp, EINVAL);
21547 		return;
21548 	}
21549 
21550 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21551 	if (mp1 == NULL)
21552 		return;
21553 
21554 	switch (iocp->ioc_cmd) {
21555 	case TI_GETMYNAME:
21556 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
21557 		break;
21558 	case TI_GETPEERNAME:
21559 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
21560 		break;
21561 	}
21562 
21563 	if (error != 0) {
21564 		mi_copy_done(q, mp, error);
21565 	} else {
21566 		mp1->b_wptr += addrlen;
21567 		STRUCT_FSET(sb, len, addrlen);
21568 
21569 		/* Copy out the address */
21570 		mi_copyout(q, mp);
21571 	}
21572 }
21573 
21574 static void
21575 tcp_use_pure_tpi(tcp_t *tcp)
21576 {
21577 #ifdef	_ILP32
21578 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
21579 #else
21580 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21581 #endif
21582 	/*
21583 	 * Insert this socket into the acceptor hash.
21584 	 * We might need it for T_CONN_RES message
21585 	 */
21586 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21587 
21588 	tcp->tcp_issocket = B_FALSE;
21589 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
21590 }
21591 
21592 /*
21593  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21594  * messages.
21595  */
21596 /* ARGSUSED */
21597 static void
21598 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21599 {
21600 	conn_t 	*connp = (conn_t *)arg;
21601 	tcp_t	*tcp = connp->conn_tcp;
21602 	queue_t	*q = tcp->tcp_wq;
21603 	struct iocblk	*iocp;
21604 
21605 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21606 	/*
21607 	 * Try and ASSERT the minimum possible references on the
21608 	 * conn early enough. Since we are executing on write side,
21609 	 * the connection is obviously not detached and that means
21610 	 * there is a ref each for TCP and IP. Since we are behind
21611 	 * the squeue, the minimum references needed are 3. If the
21612 	 * conn is in classifier hash list, there should be an
21613 	 * extra ref for that (we check both the possibilities).
21614 	 */
21615 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21616 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21617 
21618 	iocp = (struct iocblk *)mp->b_rptr;
21619 	switch (iocp->ioc_cmd) {
21620 	case TCP_IOC_DEFAULT_Q:
21621 		/* Wants to be the default wq. */
21622 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21623 			iocp->ioc_error = EPERM;
21624 			iocp->ioc_count = 0;
21625 			mp->b_datap->db_type = M_IOCACK;
21626 			qreply(q, mp);
21627 			return;
21628 		}
21629 		tcp_def_q_set(tcp, mp);
21630 		return;
21631 	case _SIOCSOCKFALLBACK:
21632 		/*
21633 		 * Either sockmod is about to be popped and the socket
21634 		 * would now be treated as a plain stream, or a module
21635 		 * is about to be pushed so we could no longer use read-
21636 		 * side synchronous streams for fused loopback tcp.
21637 		 * Drain any queued data and disable direct sockfs
21638 		 * interface from now on.
21639 		 */
21640 		if (!tcp->tcp_issocket) {
21641 			DB_TYPE(mp) = M_IOCNAK;
21642 			iocp->ioc_error = EINVAL;
21643 		} else {
21644 			tcp_use_pure_tpi(tcp);
21645 			DB_TYPE(mp) = M_IOCACK;
21646 			iocp->ioc_error = 0;
21647 		}
21648 		iocp->ioc_count = 0;
21649 		iocp->ioc_rval = 0;
21650 		qreply(q, mp);
21651 		return;
21652 	}
21653 	CALL_IP_WPUT(connp, q, mp);
21654 }
21655 
21656 /*
21657  * This routine is called by tcp_wput() to handle all TPI requests.
21658  */
21659 /* ARGSUSED */
21660 static void
21661 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21662 {
21663 	conn_t 	*connp = (conn_t *)arg;
21664 	tcp_t	*tcp = connp->conn_tcp;
21665 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21666 	uchar_t *rptr;
21667 	t_scalar_t type;
21668 	cred_t *cr;
21669 
21670 	/*
21671 	 * Try and ASSERT the minimum possible references on the
21672 	 * conn early enough. Since we are executing on write side,
21673 	 * the connection is obviously not detached and that means
21674 	 * there is a ref each for TCP and IP. Since we are behind
21675 	 * the squeue, the minimum references needed are 3. If the
21676 	 * conn is in classifier hash list, there should be an
21677 	 * extra ref for that (we check both the possibilities).
21678 	 */
21679 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21680 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21681 
21682 	rptr = mp->b_rptr;
21683 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21684 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21685 		type = ((union T_primitives *)rptr)->type;
21686 		if (type == T_EXDATA_REQ) {
21687 			tcp_output_urgent(connp, mp, arg2);
21688 		} else if (type != T_DATA_REQ) {
21689 			goto non_urgent_data;
21690 		} else {
21691 			/* TODO: options, flags, ... from user */
21692 			/* Set length to zero for reclamation below */
21693 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21694 			freeb(mp);
21695 		}
21696 		return;
21697 	} else {
21698 		if (tcp->tcp_debug) {
21699 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21700 			    "tcp_wput_proto, dropping one...");
21701 		}
21702 		freemsg(mp);
21703 		return;
21704 	}
21705 
21706 non_urgent_data:
21707 
21708 	switch ((int)tprim->type) {
21709 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21710 		/*
21711 		 * save the kssl_ent_t from the next block, and convert this
21712 		 * back to a normal bind_req.
21713 		 */
21714 		if (mp->b_cont != NULL) {
21715 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21716 
21717 			if (tcp->tcp_kssl_ent != NULL) {
21718 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21719 				    KSSL_NO_PROXY);
21720 				tcp->tcp_kssl_ent = NULL;
21721 			}
21722 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21723 			    sizeof (kssl_ent_t));
21724 			kssl_hold_ent(tcp->tcp_kssl_ent);
21725 			freemsg(mp->b_cont);
21726 			mp->b_cont = NULL;
21727 		}
21728 		tprim->type = T_BIND_REQ;
21729 
21730 	/* FALLTHROUGH */
21731 	case O_T_BIND_REQ:	/* bind request */
21732 	case T_BIND_REQ:	/* new semantics bind request */
21733 		tcp_tpi_bind(tcp, mp);
21734 		break;
21735 	case T_UNBIND_REQ:	/* unbind request */
21736 		tcp_tpi_unbind(tcp, mp);
21737 		break;
21738 	case O_T_CONN_RES:	/* old connection response XXX */
21739 	case T_CONN_RES:	/* connection response */
21740 		tcp_tli_accept(tcp, mp);
21741 		break;
21742 	case T_CONN_REQ:	/* connection request */
21743 		tcp_tpi_connect(tcp, mp);
21744 		break;
21745 	case T_DISCON_REQ:	/* disconnect request */
21746 		tcp_disconnect(tcp, mp);
21747 		break;
21748 	case T_CAPABILITY_REQ:
21749 		tcp_capability_req(tcp, mp);	/* capability request */
21750 		break;
21751 	case T_INFO_REQ:	/* information request */
21752 		tcp_info_req(tcp, mp);
21753 		break;
21754 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21755 	case T_OPTMGMT_REQ:
21756 		/*
21757 		 * Note:  no support for snmpcom_req() through new
21758 		 * T_OPTMGMT_REQ. See comments in ip.c
21759 		 */
21760 
21761 		/*
21762 		 * All Solaris components should pass a db_credp
21763 		 * for this TPI message, hence we ASSERT.
21764 		 * But in case there is some other M_PROTO that looks
21765 		 * like a TPI message sent by some other kernel
21766 		 * component, we check and return an error.
21767 		 */
21768 		cr = msg_getcred(mp, NULL);
21769 		ASSERT(cr != NULL);
21770 		if (cr == NULL) {
21771 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
21772 			return;
21773 		}
21774 		/*
21775 		 * If EINPROGRESS is returned, the request has been queued
21776 		 * for subsequent processing by ip_restart_optmgmt(), which
21777 		 * will do the CONN_DEC_REF().
21778 		 */
21779 		CONN_INC_REF(connp);
21780 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
21781 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21782 			    B_TRUE) != EINPROGRESS) {
21783 				CONN_DEC_REF(connp);
21784 			}
21785 		} else {
21786 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21787 			    B_TRUE) != EINPROGRESS) {
21788 				CONN_DEC_REF(connp);
21789 			}
21790 		}
21791 		break;
21792 
21793 	case T_UNITDATA_REQ:	/* unitdata request */
21794 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21795 		break;
21796 	case T_ORDREL_REQ:	/* orderly release req */
21797 		freemsg(mp);
21798 
21799 		if (tcp->tcp_fused)
21800 			tcp_unfuse(tcp);
21801 
21802 		if (tcp_xmit_end(tcp) != 0) {
21803 			/*
21804 			 * We were crossing FINs and got a reset from
21805 			 * the other side. Just ignore it.
21806 			 */
21807 			if (tcp->tcp_debug) {
21808 				(void) strlog(TCP_MOD_ID, 0, 1,
21809 				    SL_ERROR|SL_TRACE,
21810 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21811 				    "state %s",
21812 				    tcp_display(tcp, NULL,
21813 				    DISP_ADDR_AND_PORT));
21814 			}
21815 		}
21816 		break;
21817 	case T_ADDR_REQ:
21818 		tcp_addr_req(tcp, mp);
21819 		break;
21820 	default:
21821 		if (tcp->tcp_debug) {
21822 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21823 			    "tcp_wput_proto, bogus TPI msg, type %d",
21824 			    tprim->type);
21825 		}
21826 		/*
21827 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21828 		 * to recover.
21829 		 */
21830 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21831 		break;
21832 	}
21833 }
21834 
21835 /*
21836  * The TCP write service routine should never be called...
21837  */
21838 /* ARGSUSED */
21839 static void
21840 tcp_wsrv(queue_t *q)
21841 {
21842 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
21843 
21844 	TCP_STAT(tcps, tcp_wsrv_called);
21845 }
21846 
21847 /* Non overlapping byte exchanger */
21848 static void
21849 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21850 {
21851 	uchar_t	uch;
21852 
21853 	while (len-- > 0) {
21854 		uch = a[len];
21855 		a[len] = b[len];
21856 		b[len] = uch;
21857 	}
21858 }
21859 
21860 /*
21861  * Send out a control packet on the tcp connection specified.  This routine
21862  * is typically called where we need a simple ACK or RST generated.
21863  */
21864 static void
21865 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21866 {
21867 	uchar_t		*rptr;
21868 	tcph_t		*tcph;
21869 	ipha_t		*ipha = NULL;
21870 	ip6_t		*ip6h = NULL;
21871 	uint32_t	sum;
21872 	int		tcp_hdr_len;
21873 	int		tcp_ip_hdr_len;
21874 	mblk_t		*mp;
21875 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21876 
21877 	/*
21878 	 * Save sum for use in source route later.
21879 	 */
21880 	ASSERT(tcp != NULL);
21881 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21882 	tcp_hdr_len = tcp->tcp_hdr_len;
21883 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21884 
21885 	/* If a text string is passed in with the request, pass it to strlog. */
21886 	if (str != NULL && tcp->tcp_debug) {
21887 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21888 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21889 		    str, seq, ack, ctl);
21890 	}
21891 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
21892 	    BPRI_MED);
21893 	if (mp == NULL) {
21894 		return;
21895 	}
21896 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
21897 	mp->b_rptr = rptr;
21898 	mp->b_wptr = &rptr[tcp_hdr_len];
21899 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21900 
21901 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21902 		ipha = (ipha_t *)rptr;
21903 		ipha->ipha_length = htons(tcp_hdr_len);
21904 	} else {
21905 		ip6h = (ip6_t *)rptr;
21906 		ASSERT(tcp != NULL);
21907 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21908 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21909 	}
21910 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21911 	tcph->th_flags[0] = (uint8_t)ctl;
21912 	if (ctl & TH_RST) {
21913 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
21914 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
21915 		/*
21916 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21917 		 */
21918 		if (tcp->tcp_snd_ts_ok &&
21919 		    tcp->tcp_state > TCPS_SYN_SENT) {
21920 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21921 			*(mp->b_wptr) = TCPOPT_EOL;
21922 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21923 				ipha->ipha_length = htons(tcp_hdr_len -
21924 				    TCPOPT_REAL_TS_LEN);
21925 			} else {
21926 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21927 				    TCPOPT_REAL_TS_LEN);
21928 			}
21929 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21930 			sum -= TCPOPT_REAL_TS_LEN;
21931 		}
21932 	}
21933 	if (ctl & TH_ACK) {
21934 		if (tcp->tcp_snd_ts_ok) {
21935 			U32_TO_BE32(lbolt,
21936 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21937 			U32_TO_BE32(tcp->tcp_ts_recent,
21938 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21939 		}
21940 
21941 		/* Update the latest receive window size in TCP header. */
21942 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21943 		    tcph->th_win);
21944 		tcp->tcp_rack = ack;
21945 		tcp->tcp_rack_cnt = 0;
21946 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
21947 	}
21948 	BUMP_LOCAL(tcp->tcp_obsegs);
21949 	U32_TO_BE32(seq, tcph->th_seq);
21950 	U32_TO_BE32(ack, tcph->th_ack);
21951 	/*
21952 	 * Include the adjustment for a source route if any.
21953 	 */
21954 	sum = (sum >> 16) + (sum & 0xFFFF);
21955 	U16_TO_BE16(sum, tcph->th_sum);
21956 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21957 }
21958 
21959 /*
21960  * If this routine returns B_TRUE, TCP can generate a RST in response
21961  * to a segment.  If it returns B_FALSE, TCP should not respond.
21962  */
21963 static boolean_t
21964 tcp_send_rst_chk(tcp_stack_t *tcps)
21965 {
21966 	clock_t	now;
21967 
21968 	/*
21969 	 * TCP needs to protect itself from generating too many RSTs.
21970 	 * This can be a DoS attack by sending us random segments
21971 	 * soliciting RSTs.
21972 	 *
21973 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21974 	 * in each 1 second interval.  In this way, TCP still generate
21975 	 * RSTs in normal cases but when under attack, the impact is
21976 	 * limited.
21977 	 */
21978 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
21979 		now = lbolt;
21980 		/* lbolt can wrap around. */
21981 		if ((tcps->tcps_last_rst_intrvl > now) ||
21982 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
21983 		    1*SECONDS)) {
21984 			tcps->tcps_last_rst_intrvl = now;
21985 			tcps->tcps_rst_cnt = 1;
21986 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
21987 			return (B_FALSE);
21988 		}
21989 	}
21990 	return (B_TRUE);
21991 }
21992 
21993 /*
21994  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21995  */
21996 static void
21997 tcp_ip_ire_mark_advice(tcp_t *tcp)
21998 {
21999 	mblk_t *mp;
22000 	ipic_t *ipic;
22001 
22002 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22003 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22004 		    &ipic);
22005 	} else {
22006 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22007 		    &ipic);
22008 	}
22009 	if (mp == NULL)
22010 		return;
22011 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22012 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22013 }
22014 
22015 /*
22016  * Return an IP advice ioctl mblk and set ipic to be the pointer
22017  * to the advice structure.
22018  */
22019 static mblk_t *
22020 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22021 {
22022 	struct iocblk *ioc;
22023 	mblk_t *mp, *mp1;
22024 
22025 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22026 	if (mp == NULL)
22027 		return (NULL);
22028 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22029 	*ipic = (ipic_t *)mp->b_rptr;
22030 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22031 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22032 
22033 	bcopy(addr, *ipic + 1, addr_len);
22034 
22035 	(*ipic)->ipic_addr_length = addr_len;
22036 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22037 
22038 	mp1 = mkiocb(IP_IOCTL);
22039 	if (mp1 == NULL) {
22040 		freemsg(mp);
22041 		return (NULL);
22042 	}
22043 	mp1->b_cont = mp;
22044 	ioc = (struct iocblk *)mp1->b_rptr;
22045 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22046 
22047 	return (mp1);
22048 }
22049 
22050 /*
22051  * Generate a reset based on an inbound packet, connp is set by caller
22052  * when RST is in response to an unexpected inbound packet for which
22053  * there is active tcp state in the system.
22054  *
22055  * IPSEC NOTE : Try to send the reply with the same protection as it came
22056  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22057  * the packet will go out at the same level of protection as it came in by
22058  * converting the IPSEC_IN to IPSEC_OUT.
22059  */
22060 static void
22061 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22062     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22063     tcp_stack_t *tcps, conn_t *connp)
22064 {
22065 	ipha_t		*ipha = NULL;
22066 	ip6_t		*ip6h = NULL;
22067 	ushort_t	len;
22068 	tcph_t		*tcph;
22069 	int		i;
22070 	mblk_t		*ipsec_mp;
22071 	boolean_t	mctl_present;
22072 	ipic_t		*ipic;
22073 	ipaddr_t	v4addr;
22074 	in6_addr_t	v6addr;
22075 	int		addr_len;
22076 	void		*addr;
22077 	queue_t		*q = tcps->tcps_g_q;
22078 	tcp_t		*tcp;
22079 	cred_t		*cr;
22080 	pid_t		pid;
22081 	mblk_t		*nmp;
22082 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22083 
22084 	if (tcps->tcps_g_q == NULL) {
22085 		/*
22086 		 * For non-zero stackids the default queue isn't created
22087 		 * until the first open, thus there can be a need to send
22088 		 * a reset before then. But we can't do that, hence we just
22089 		 * drop the packet. Later during boot, when the default queue
22090 		 * has been setup, a retransmitted packet from the peer
22091 		 * will result in a reset.
22092 		 */
22093 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22094 		    GLOBAL_NETSTACKID);
22095 		freemsg(mp);
22096 		return;
22097 	}
22098 
22099 	if (connp != NULL)
22100 		tcp = connp->conn_tcp;
22101 	else
22102 		tcp = Q_TO_TCP(q);
22103 
22104 	if (!tcp_send_rst_chk(tcps)) {
22105 		tcps->tcps_rst_unsent++;
22106 		freemsg(mp);
22107 		return;
22108 	}
22109 
22110 	if (mp->b_datap->db_type == M_CTL) {
22111 		ipsec_mp = mp;
22112 		mp = mp->b_cont;
22113 		mctl_present = B_TRUE;
22114 	} else {
22115 		ipsec_mp = mp;
22116 		mctl_present = B_FALSE;
22117 	}
22118 
22119 	if (str && q && tcps->tcps_dbg) {
22120 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22121 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22122 		    "flags 0x%x",
22123 		    str, seq, ack, ctl);
22124 	}
22125 	if (mp->b_datap->db_ref != 1) {
22126 		mblk_t *mp1 = copyb(mp);
22127 		freemsg(mp);
22128 		mp = mp1;
22129 		if (!mp) {
22130 			if (mctl_present)
22131 				freeb(ipsec_mp);
22132 			return;
22133 		} else {
22134 			if (mctl_present) {
22135 				ipsec_mp->b_cont = mp;
22136 			} else {
22137 				ipsec_mp = mp;
22138 			}
22139 		}
22140 	} else if (mp->b_cont) {
22141 		freemsg(mp->b_cont);
22142 		mp->b_cont = NULL;
22143 	}
22144 	/*
22145 	 * We skip reversing source route here.
22146 	 * (for now we replace all IP options with EOL)
22147 	 */
22148 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22149 		ipha = (ipha_t *)mp->b_rptr;
22150 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22151 			mp->b_rptr[i] = IPOPT_EOL;
22152 		/*
22153 		 * Make sure that src address isn't flagrantly invalid.
22154 		 * Not all broadcast address checking for the src address
22155 		 * is possible, since we don't know the netmask of the src
22156 		 * addr.  No check for destination address is done, since
22157 		 * IP will not pass up a packet with a broadcast dest
22158 		 * address to TCP.  Similar checks are done below for IPv6.
22159 		 */
22160 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22161 		    CLASSD(ipha->ipha_src)) {
22162 			freemsg(ipsec_mp);
22163 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22164 			return;
22165 		}
22166 	} else {
22167 		ip6h = (ip6_t *)mp->b_rptr;
22168 
22169 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22170 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22171 			freemsg(ipsec_mp);
22172 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22173 			return;
22174 		}
22175 
22176 		/* Remove any extension headers assuming partial overlay */
22177 		if (ip_hdr_len > IPV6_HDR_LEN) {
22178 			uint8_t *to;
22179 
22180 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22181 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22182 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22183 			ip_hdr_len = IPV6_HDR_LEN;
22184 			ip6h = (ip6_t *)mp->b_rptr;
22185 			ip6h->ip6_nxt = IPPROTO_TCP;
22186 		}
22187 	}
22188 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22189 	if (tcph->th_flags[0] & TH_RST) {
22190 		freemsg(ipsec_mp);
22191 		return;
22192 	}
22193 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22194 	len = ip_hdr_len + sizeof (tcph_t);
22195 	mp->b_wptr = &mp->b_rptr[len];
22196 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22197 		ipha->ipha_length = htons(len);
22198 		/* Swap addresses */
22199 		v4addr = ipha->ipha_src;
22200 		ipha->ipha_src = ipha->ipha_dst;
22201 		ipha->ipha_dst = v4addr;
22202 		ipha->ipha_ident = 0;
22203 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22204 		addr_len = IP_ADDR_LEN;
22205 		addr = &v4addr;
22206 	} else {
22207 		/* No ip6i_t in this case */
22208 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22209 		/* Swap addresses */
22210 		v6addr = ip6h->ip6_src;
22211 		ip6h->ip6_src = ip6h->ip6_dst;
22212 		ip6h->ip6_dst = v6addr;
22213 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22214 		addr_len = IPV6_ADDR_LEN;
22215 		addr = &v6addr;
22216 	}
22217 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22218 	U32_TO_BE32(ack, tcph->th_ack);
22219 	U32_TO_BE32(seq, tcph->th_seq);
22220 	U16_TO_BE16(0, tcph->th_win);
22221 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22222 	tcph->th_flags[0] = (uint8_t)ctl;
22223 	if (ctl & TH_RST) {
22224 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22225 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22226 	}
22227 
22228 	/* IP trusts us to set up labels when required. */
22229 	if (is_system_labeled() && (cr = msg_getcred(mp, &pid)) != NULL &&
22230 	    crgetlabel(cr) != NULL) {
22231 		int err;
22232 
22233 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22234 			err = tsol_check_label(cr, &mp,
22235 			    tcp->tcp_connp->conn_mac_mode,
22236 			    tcps->tcps_netstack->netstack_ip, pid);
22237 		else
22238 			err = tsol_check_label_v6(cr, &mp,
22239 			    tcp->tcp_connp->conn_mac_mode,
22240 			    tcps->tcps_netstack->netstack_ip, pid);
22241 		if (mctl_present)
22242 			ipsec_mp->b_cont = mp;
22243 		else
22244 			ipsec_mp = mp;
22245 		if (err != 0) {
22246 			freemsg(ipsec_mp);
22247 			return;
22248 		}
22249 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22250 			ipha = (ipha_t *)mp->b_rptr;
22251 		} else {
22252 			ip6h = (ip6_t *)mp->b_rptr;
22253 		}
22254 	}
22255 
22256 	if (mctl_present) {
22257 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22258 
22259 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22260 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h, zoneid)) {
22261 			return;
22262 		}
22263 	}
22264 	if (zoneid == ALL_ZONES)
22265 		zoneid = GLOBAL_ZONEID;
22266 
22267 	/* Add the zoneid so ip_output routes it properly */
22268 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22269 		freemsg(ipsec_mp);
22270 		return;
22271 	}
22272 	ipsec_mp = nmp;
22273 
22274 	/*
22275 	 * NOTE:  one might consider tracing a TCP packet here, but
22276 	 * this function has no active TCP state and no tcp structure
22277 	 * that has a trace buffer.  If we traced here, we would have
22278 	 * to keep a local trace buffer in tcp_record_trace().
22279 	 *
22280 	 * TSol note: The mblk that contains the incoming packet was
22281 	 * reused by tcp_xmit_listener_reset, so it already contains
22282 	 * the right credentials and we don't need to call mblk_setcred.
22283 	 * Also the conn's cred is not right since it is associated
22284 	 * with tcps_g_q.
22285 	 */
22286 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22287 
22288 	/*
22289 	 * Tell IP to mark the IRE used for this destination temporary.
22290 	 * This way, we can limit our exposure to DoS attack because IP
22291 	 * creates an IRE for each destination.  If there are too many,
22292 	 * the time to do any routing lookup will be extremely long.  And
22293 	 * the lookup can be in interrupt context.
22294 	 *
22295 	 * Note that in normal circumstances, this marking should not
22296 	 * affect anything.  It would be nice if only 1 message is
22297 	 * needed to inform IP that the IRE created for this RST should
22298 	 * not be added to the cache table.  But there is currently
22299 	 * not such communication mechanism between TCP and IP.  So
22300 	 * the best we can do now is to send the advice ioctl to IP
22301 	 * to mark the IRE temporary.
22302 	 */
22303 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22304 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22305 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22306 	}
22307 }
22308 
22309 /*
22310  * Initiate closedown sequence on an active connection.  (May be called as
22311  * writer.)  Return value zero for OK return, non-zero for error return.
22312  */
22313 static int
22314 tcp_xmit_end(tcp_t *tcp)
22315 {
22316 	ipic_t	*ipic;
22317 	mblk_t	*mp;
22318 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22319 
22320 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22321 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22322 		/*
22323 		 * Invalid state, only states TCPS_SYN_RCVD,
22324 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22325 		 */
22326 		return (-1);
22327 	}
22328 
22329 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22330 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22331 	/*
22332 	 * If there is nothing more unsent, send the FIN now.
22333 	 * Otherwise, it will go out with the last segment.
22334 	 */
22335 	if (tcp->tcp_unsent == 0) {
22336 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22337 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22338 
22339 		if (mp) {
22340 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22341 		} else {
22342 			/*
22343 			 * Couldn't allocate msg.  Pretend we got it out.
22344 			 * Wait for rexmit timeout.
22345 			 */
22346 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22347 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22348 		}
22349 
22350 		/*
22351 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22352 		 * changed.
22353 		 */
22354 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22355 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22356 		}
22357 	} else {
22358 		/*
22359 		 * If tcp->tcp_cork is set, then the data will not get sent,
22360 		 * so we have to check that and unset it first.
22361 		 */
22362 		if (tcp->tcp_cork)
22363 			tcp->tcp_cork = B_FALSE;
22364 		tcp_wput_data(tcp, NULL, B_FALSE);
22365 	}
22366 
22367 	/*
22368 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22369 	 * is 0, don't update the cache.
22370 	 */
22371 	if (tcps->tcps_rtt_updates == 0 ||
22372 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22373 		return (0);
22374 
22375 	/*
22376 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22377 	 * different from the destination.
22378 	 */
22379 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22380 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22381 			return (0);
22382 		}
22383 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22384 		    &ipic);
22385 	} else {
22386 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22387 		    &tcp->tcp_ip6h->ip6_dst))) {
22388 			return (0);
22389 		}
22390 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22391 		    &ipic);
22392 	}
22393 
22394 	/* Record route attributes in the IRE for use by future connections. */
22395 	if (mp == NULL)
22396 		return (0);
22397 
22398 	/*
22399 	 * We do not have a good algorithm to update ssthresh at this time.
22400 	 * So don't do any update.
22401 	 */
22402 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22403 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22404 
22405 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22406 
22407 	return (0);
22408 }
22409 
22410 /* ARGSUSED */
22411 void
22412 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
22413 {
22414 	conn_t *connp = (conn_t *)arg;
22415 	mblk_t *mp1;
22416 	tcp_t *tcp = connp->conn_tcp;
22417 	tcp_xmit_reset_event_t *eventp;
22418 
22419 	ASSERT(mp->b_datap->db_type == M_PROTO &&
22420 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
22421 
22422 	if (tcp->tcp_state != TCPS_LISTEN) {
22423 		freemsg(mp);
22424 		return;
22425 	}
22426 
22427 	mp1 = mp->b_cont;
22428 	mp->b_cont = NULL;
22429 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
22430 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
22431 	    connp->conn_netstack);
22432 
22433 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
22434 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
22435 	freemsg(mp);
22436 }
22437 
22438 /*
22439  * Generate a "no listener here" RST in response to an "unknown" segment.
22440  * connp is set by caller when RST is in response to an unexpected
22441  * inbound packet for which there is active tcp state in the system.
22442  * Note that we are reusing the incoming mp to construct the outgoing RST.
22443  */
22444 void
22445 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22446     tcp_stack_t *tcps, conn_t *connp)
22447 {
22448 	uchar_t		*rptr;
22449 	uint32_t	seg_len;
22450 	tcph_t		*tcph;
22451 	uint32_t	seg_seq;
22452 	uint32_t	seg_ack;
22453 	uint_t		flags;
22454 	mblk_t		*ipsec_mp;
22455 	ipha_t 		*ipha;
22456 	ip6_t 		*ip6h;
22457 	boolean_t	mctl_present = B_FALSE;
22458 	boolean_t	check = B_TRUE;
22459 	boolean_t	policy_present;
22460 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22461 
22462 	TCP_STAT(tcps, tcp_no_listener);
22463 
22464 	ipsec_mp = mp;
22465 
22466 	if (mp->b_datap->db_type == M_CTL) {
22467 		ipsec_in_t *ii;
22468 
22469 		mctl_present = B_TRUE;
22470 		mp = mp->b_cont;
22471 
22472 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22473 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22474 		if (ii->ipsec_in_dont_check) {
22475 			check = B_FALSE;
22476 			if (!ii->ipsec_in_secure) {
22477 				freeb(ipsec_mp);
22478 				mctl_present = B_FALSE;
22479 				ipsec_mp = mp;
22480 			}
22481 		}
22482 	}
22483 
22484 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22485 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22486 		ipha = (ipha_t *)mp->b_rptr;
22487 		ip6h = NULL;
22488 	} else {
22489 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22490 		ipha = NULL;
22491 		ip6h = (ip6_t *)mp->b_rptr;
22492 	}
22493 
22494 	if (check && policy_present) {
22495 		/*
22496 		 * The conn_t parameter is NULL because we already know
22497 		 * nobody's home.
22498 		 */
22499 		ipsec_mp = ipsec_check_global_policy(
22500 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22501 		    tcps->tcps_netstack);
22502 		if (ipsec_mp == NULL)
22503 			return;
22504 	}
22505 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22506 		DTRACE_PROBE2(
22507 		    tx__ip__log__error__nolistener__tcp,
22508 		    char *, "Could not reply with RST to mp(1)",
22509 		    mblk_t *, mp);
22510 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22511 		freemsg(ipsec_mp);
22512 		return;
22513 	}
22514 
22515 	rptr = mp->b_rptr;
22516 
22517 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22518 	seg_seq = BE32_TO_U32(tcph->th_seq);
22519 	seg_ack = BE32_TO_U32(tcph->th_ack);
22520 	flags = tcph->th_flags[0];
22521 
22522 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22523 	if (flags & TH_RST) {
22524 		freemsg(ipsec_mp);
22525 	} else if (flags & TH_ACK) {
22526 		tcp_xmit_early_reset("no tcp, reset",
22527 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22528 		    connp);
22529 	} else {
22530 		if (flags & TH_SYN) {
22531 			seg_len++;
22532 		} else {
22533 			/*
22534 			 * Here we violate the RFC.  Note that a normal
22535 			 * TCP will never send a segment without the ACK
22536 			 * flag, except for RST or SYN segment.  This
22537 			 * segment is neither.  Just drop it on the
22538 			 * floor.
22539 			 */
22540 			freemsg(ipsec_mp);
22541 			tcps->tcps_rst_unsent++;
22542 			return;
22543 		}
22544 
22545 		tcp_xmit_early_reset("no tcp, reset/ack",
22546 		    ipsec_mp, 0, seg_seq + seg_len,
22547 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22548 	}
22549 }
22550 
22551 /*
22552  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22553  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22554  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22555  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22556  * otherwise it will dup partial mblks.)
22557  * Otherwise, an appropriate ACK packet will be generated.  This
22558  * routine is not usually called to send new data for the first time.  It
22559  * is mostly called out of the timer for retransmits, and to generate ACKs.
22560  *
22561  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22562  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22563  * of the original mblk chain will be returned in *offset and *end_mp.
22564  */
22565 mblk_t *
22566 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22567     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22568     boolean_t rexmit)
22569 {
22570 	int	data_length;
22571 	int32_t	off = 0;
22572 	uint_t	flags;
22573 	mblk_t	*mp1;
22574 	mblk_t	*mp2;
22575 	uchar_t	*rptr;
22576 	tcph_t	*tcph;
22577 	int32_t	num_sack_blk = 0;
22578 	int32_t	sack_opt_len = 0;
22579 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22580 
22581 	/* Allocate for our maximum TCP header + link-level */
22582 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22583 	    tcps->tcps_wroff_xtra, BPRI_MED);
22584 	if (!mp1)
22585 		return (NULL);
22586 	data_length = 0;
22587 
22588 	/*
22589 	 * Note that tcp_mss has been adjusted to take into account the
22590 	 * timestamp option if applicable.  Because SACK options do not
22591 	 * appear in every TCP segments and they are of variable lengths,
22592 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22593 	 * the actual segment length when we need to send a segment which
22594 	 * includes SACK options.
22595 	 */
22596 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22597 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22598 		    tcp->tcp_num_sack_blk);
22599 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22600 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22601 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22602 			max_to_send -= sack_opt_len;
22603 	}
22604 
22605 	if (offset != NULL) {
22606 		off = *offset;
22607 		/* We use offset as an indicator that end_mp is not NULL. */
22608 		*end_mp = NULL;
22609 	}
22610 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22611 		/* This could be faster with cooperation from downstream */
22612 		if (mp2 != mp1 && !sendall &&
22613 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22614 		    max_to_send)
22615 			/*
22616 			 * Don't send the next mblk since the whole mblk
22617 			 * does not fit.
22618 			 */
22619 			break;
22620 		mp2->b_cont = dupb(mp);
22621 		mp2 = mp2->b_cont;
22622 		if (!mp2) {
22623 			freemsg(mp1);
22624 			return (NULL);
22625 		}
22626 		mp2->b_rptr += off;
22627 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22628 		    (uintptr_t)INT_MAX);
22629 
22630 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22631 		if (data_length > max_to_send) {
22632 			mp2->b_wptr -= data_length - max_to_send;
22633 			data_length = max_to_send;
22634 			off = mp2->b_wptr - mp->b_rptr;
22635 			break;
22636 		} else {
22637 			off = 0;
22638 		}
22639 	}
22640 	if (offset != NULL) {
22641 		*offset = off;
22642 		*end_mp = mp;
22643 	}
22644 	if (seg_len != NULL) {
22645 		*seg_len = data_length;
22646 	}
22647 
22648 	/* Update the latest receive window size in TCP header. */
22649 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22650 	    tcp->tcp_tcph->th_win);
22651 
22652 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22653 	mp1->b_rptr = rptr;
22654 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22655 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22656 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22657 	U32_TO_ABE32(seq, tcph->th_seq);
22658 
22659 	/*
22660 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22661 	 * that this function was called from tcp_wput_data. Thus, when called
22662 	 * to retransmit data the setting of the PUSH bit may appear some
22663 	 * what random in that it might get set when it should not. This
22664 	 * should not pose any performance issues.
22665 	 */
22666 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22667 	    tcp->tcp_unsent == data_length)) {
22668 		flags = TH_ACK | TH_PUSH;
22669 	} else {
22670 		flags = TH_ACK;
22671 	}
22672 
22673 	if (tcp->tcp_ecn_ok) {
22674 		if (tcp->tcp_ecn_echo_on)
22675 			flags |= TH_ECE;
22676 
22677 		/*
22678 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22679 		 * There is no TCP flow control for non-data segments, and
22680 		 * only data segment is transmitted reliably.
22681 		 */
22682 		if (data_length > 0 && !rexmit) {
22683 			SET_ECT(tcp, rptr);
22684 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22685 				flags |= TH_CWR;
22686 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22687 			}
22688 		}
22689 	}
22690 
22691 	if (tcp->tcp_valid_bits) {
22692 		uint32_t u1;
22693 
22694 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22695 		    seq == tcp->tcp_iss) {
22696 			uchar_t	*wptr;
22697 
22698 			/*
22699 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22700 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22701 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22702 			 * our SYN is not ack'ed but the app closes this
22703 			 * TCP connection.
22704 			 */
22705 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22706 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22707 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22708 
22709 			/*
22710 			 * Tack on the MSS option.  It is always needed
22711 			 * for both active and passive open.
22712 			 *
22713 			 * MSS option value should be interface MTU - MIN
22714 			 * TCP/IP header according to RFC 793 as it means
22715 			 * the maximum segment size TCP can receive.  But
22716 			 * to get around some broken middle boxes/end hosts
22717 			 * out there, we allow the option value to be the
22718 			 * same as the MSS option size on the peer side.
22719 			 * In this way, the other side will not send
22720 			 * anything larger than they can receive.
22721 			 *
22722 			 * Note that for SYN_SENT state, the ndd param
22723 			 * tcp_use_smss_as_mss_opt has no effect as we
22724 			 * don't know the peer's MSS option value. So
22725 			 * the only case we need to take care of is in
22726 			 * SYN_RCVD state, which is done later.
22727 			 */
22728 			wptr = mp1->b_wptr;
22729 			wptr[0] = TCPOPT_MAXSEG;
22730 			wptr[1] = TCPOPT_MAXSEG_LEN;
22731 			wptr += 2;
22732 			u1 = tcp->tcp_if_mtu -
22733 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22734 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22735 			    TCP_MIN_HEADER_LENGTH;
22736 			U16_TO_BE16(u1, wptr);
22737 			mp1->b_wptr = wptr + 2;
22738 			/* Update the offset to cover the additional word */
22739 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22740 
22741 			/*
22742 			 * Note that the following way of filling in
22743 			 * TCP options are not optimal.  Some NOPs can
22744 			 * be saved.  But there is no need at this time
22745 			 * to optimize it.  When it is needed, we will
22746 			 * do it.
22747 			 */
22748 			switch (tcp->tcp_state) {
22749 			case TCPS_SYN_SENT:
22750 				flags = TH_SYN;
22751 
22752 				if (tcp->tcp_snd_ts_ok) {
22753 					uint32_t llbolt = (uint32_t)lbolt;
22754 
22755 					wptr = mp1->b_wptr;
22756 					wptr[0] = TCPOPT_NOP;
22757 					wptr[1] = TCPOPT_NOP;
22758 					wptr[2] = TCPOPT_TSTAMP;
22759 					wptr[3] = TCPOPT_TSTAMP_LEN;
22760 					wptr += 4;
22761 					U32_TO_BE32(llbolt, wptr);
22762 					wptr += 4;
22763 					ASSERT(tcp->tcp_ts_recent == 0);
22764 					U32_TO_BE32(0L, wptr);
22765 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22766 					tcph->th_offset_and_rsrvd[0] +=
22767 					    (3 << 4);
22768 				}
22769 
22770 				/*
22771 				 * Set up all the bits to tell other side
22772 				 * we are ECN capable.
22773 				 */
22774 				if (tcp->tcp_ecn_ok) {
22775 					flags |= (TH_ECE | TH_CWR);
22776 				}
22777 				break;
22778 			case TCPS_SYN_RCVD:
22779 				flags |= TH_SYN;
22780 
22781 				/*
22782 				 * Reset the MSS option value to be SMSS
22783 				 * We should probably add back the bytes
22784 				 * for timestamp option and IPsec.  We
22785 				 * don't do that as this is a workaround
22786 				 * for broken middle boxes/end hosts, it
22787 				 * is better for us to be more cautious.
22788 				 * They may not take these things into
22789 				 * account in their SMSS calculation.  Thus
22790 				 * the peer's calculated SMSS may be smaller
22791 				 * than what it can be.  This should be OK.
22792 				 */
22793 				if (tcps->tcps_use_smss_as_mss_opt) {
22794 					u1 = tcp->tcp_mss;
22795 					U16_TO_BE16(u1, wptr);
22796 				}
22797 
22798 				/*
22799 				 * If the other side is ECN capable, reply
22800 				 * that we are also ECN capable.
22801 				 */
22802 				if (tcp->tcp_ecn_ok)
22803 					flags |= TH_ECE;
22804 				break;
22805 			default:
22806 				/*
22807 				 * The above ASSERT() makes sure that this
22808 				 * must be FIN-WAIT-1 state.  Our SYN has
22809 				 * not been ack'ed so retransmit it.
22810 				 */
22811 				flags |= TH_SYN;
22812 				break;
22813 			}
22814 
22815 			if (tcp->tcp_snd_ws_ok) {
22816 				wptr = mp1->b_wptr;
22817 				wptr[0] =  TCPOPT_NOP;
22818 				wptr[1] =  TCPOPT_WSCALE;
22819 				wptr[2] =  TCPOPT_WS_LEN;
22820 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22821 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22822 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22823 			}
22824 
22825 			if (tcp->tcp_snd_sack_ok) {
22826 				wptr = mp1->b_wptr;
22827 				wptr[0] = TCPOPT_NOP;
22828 				wptr[1] = TCPOPT_NOP;
22829 				wptr[2] = TCPOPT_SACK_PERMITTED;
22830 				wptr[3] = TCPOPT_SACK_OK_LEN;
22831 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22832 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22833 			}
22834 
22835 			/* allocb() of adequate mblk assures space */
22836 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22837 			    (uintptr_t)INT_MAX);
22838 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22839 			/*
22840 			 * Get IP set to checksum on our behalf
22841 			 * Include the adjustment for a source route if any.
22842 			 */
22843 			u1 += tcp->tcp_sum;
22844 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22845 			U16_TO_BE16(u1, tcph->th_sum);
22846 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22847 		}
22848 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22849 		    (seq + data_length) == tcp->tcp_fss) {
22850 			if (!tcp->tcp_fin_acked) {
22851 				flags |= TH_FIN;
22852 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22853 			}
22854 			if (!tcp->tcp_fin_sent) {
22855 				tcp->tcp_fin_sent = B_TRUE;
22856 				switch (tcp->tcp_state) {
22857 				case TCPS_SYN_RCVD:
22858 				case TCPS_ESTABLISHED:
22859 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22860 					break;
22861 				case TCPS_CLOSE_WAIT:
22862 					tcp->tcp_state = TCPS_LAST_ACK;
22863 					break;
22864 				}
22865 				if (tcp->tcp_suna == tcp->tcp_snxt)
22866 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22867 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22868 			}
22869 		}
22870 		/*
22871 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22872 		 * is smaller than seq, u1 will become a very huge value.
22873 		 * So the comparison will fail.  Also note that tcp_urp
22874 		 * should be positive, see RFC 793 page 17.
22875 		 */
22876 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22877 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22878 		    u1 < (uint32_t)(64 * 1024)) {
22879 			flags |= TH_URG;
22880 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
22881 			U32_TO_ABE16(u1, tcph->th_urp);
22882 		}
22883 	}
22884 	tcph->th_flags[0] = (uchar_t)flags;
22885 	tcp->tcp_rack = tcp->tcp_rnxt;
22886 	tcp->tcp_rack_cnt = 0;
22887 
22888 	if (tcp->tcp_snd_ts_ok) {
22889 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22890 			uint32_t llbolt = (uint32_t)lbolt;
22891 
22892 			U32_TO_BE32(llbolt,
22893 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22894 			U32_TO_BE32(tcp->tcp_ts_recent,
22895 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22896 		}
22897 	}
22898 
22899 	if (num_sack_blk > 0) {
22900 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22901 		sack_blk_t *tmp;
22902 		int32_t	i;
22903 
22904 		wptr[0] = TCPOPT_NOP;
22905 		wptr[1] = TCPOPT_NOP;
22906 		wptr[2] = TCPOPT_SACK;
22907 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22908 		    sizeof (sack_blk_t);
22909 		wptr += TCPOPT_REAL_SACK_LEN;
22910 
22911 		tmp = tcp->tcp_sack_list;
22912 		for (i = 0; i < num_sack_blk; i++) {
22913 			U32_TO_BE32(tmp[i].begin, wptr);
22914 			wptr += sizeof (tcp_seq);
22915 			U32_TO_BE32(tmp[i].end, wptr);
22916 			wptr += sizeof (tcp_seq);
22917 		}
22918 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22919 	}
22920 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22921 	data_length += (int)(mp1->b_wptr - rptr);
22922 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22923 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22924 	} else {
22925 		ip6_t *ip6 = (ip6_t *)(rptr +
22926 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22927 		    sizeof (ip6i_t) : 0));
22928 
22929 		ip6->ip6_plen = htons(data_length -
22930 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22931 	}
22932 
22933 	/*
22934 	 * Prime pump for IP
22935 	 * Include the adjustment for a source route if any.
22936 	 */
22937 	data_length -= tcp->tcp_ip_hdr_len;
22938 	data_length += tcp->tcp_sum;
22939 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22940 	U16_TO_ABE16(data_length, tcph->th_sum);
22941 	if (tcp->tcp_ip_forward_progress) {
22942 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22943 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22944 		tcp->tcp_ip_forward_progress = B_FALSE;
22945 	}
22946 	return (mp1);
22947 }
22948 
22949 /* This function handles the push timeout. */
22950 void
22951 tcp_push_timer(void *arg)
22952 {
22953 	conn_t	*connp = (conn_t *)arg;
22954 	tcp_t *tcp = connp->conn_tcp;
22955 
22956 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
22957 
22958 	ASSERT(tcp->tcp_listener == NULL);
22959 
22960 	ASSERT(!IPCL_IS_NONSTR(connp));
22961 
22962 	tcp->tcp_push_tid = 0;
22963 
22964 	if (tcp->tcp_rcv_list != NULL &&
22965 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
22966 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22967 }
22968 
22969 /*
22970  * This function handles delayed ACK timeout.
22971  */
22972 static void
22973 tcp_ack_timer(void *arg)
22974 {
22975 	conn_t	*connp = (conn_t *)arg;
22976 	tcp_t *tcp = connp->conn_tcp;
22977 	mblk_t *mp;
22978 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22979 
22980 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
22981 
22982 	tcp->tcp_ack_tid = 0;
22983 
22984 	if (tcp->tcp_fused)
22985 		return;
22986 
22987 	/*
22988 	 * Do not send ACK if there is no outstanding unack'ed data.
22989 	 */
22990 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22991 		return;
22992 	}
22993 
22994 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22995 		/*
22996 		 * Make sure we don't allow deferred ACKs to result in
22997 		 * timer-based ACKing.  If we have held off an ACK
22998 		 * when there was more than an mss here, and the timer
22999 		 * goes off, we have to worry about the possibility
23000 		 * that the sender isn't doing slow-start, or is out
23001 		 * of step with us for some other reason.  We fall
23002 		 * permanently back in the direction of
23003 		 * ACK-every-other-packet as suggested in RFC 1122.
23004 		 */
23005 		if (tcp->tcp_rack_abs_max > 2)
23006 			tcp->tcp_rack_abs_max--;
23007 		tcp->tcp_rack_cur_max = 2;
23008 	}
23009 	mp = tcp_ack_mp(tcp);
23010 
23011 	if (mp != NULL) {
23012 		BUMP_LOCAL(tcp->tcp_obsegs);
23013 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23014 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23015 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23016 	}
23017 }
23018 
23019 
23020 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23021 static mblk_t *
23022 tcp_ack_mp(tcp_t *tcp)
23023 {
23024 	uint32_t	seq_no;
23025 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23026 
23027 	/*
23028 	 * There are a few cases to be considered while setting the sequence no.
23029 	 * Essentially, we can come here while processing an unacceptable pkt
23030 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23031 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23032 	 * If we are here for a zero window probe, stick with suna. In all
23033 	 * other cases, we check if suna + swnd encompasses snxt and set
23034 	 * the sequence number to snxt, if so. If snxt falls outside the
23035 	 * window (the receiver probably shrunk its window), we will go with
23036 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23037 	 * receiver.
23038 	 */
23039 	if (tcp->tcp_zero_win_probe) {
23040 		seq_no = tcp->tcp_suna;
23041 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23042 		ASSERT(tcp->tcp_swnd == 0);
23043 		seq_no = tcp->tcp_snxt;
23044 	} else {
23045 		seq_no = SEQ_GT(tcp->tcp_snxt,
23046 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23047 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23048 	}
23049 
23050 	if (tcp->tcp_valid_bits) {
23051 		/*
23052 		 * For the complex case where we have to send some
23053 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23054 		 */
23055 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23056 		    NULL, B_FALSE));
23057 	} else {
23058 		/* Generate a simple ACK */
23059 		int	data_length;
23060 		uchar_t	*rptr;
23061 		tcph_t	*tcph;
23062 		mblk_t	*mp1;
23063 		int32_t	tcp_hdr_len;
23064 		int32_t	tcp_tcp_hdr_len;
23065 		int32_t	num_sack_blk = 0;
23066 		int32_t sack_opt_len;
23067 
23068 		/*
23069 		 * Allocate space for TCP + IP headers
23070 		 * and link-level header
23071 		 */
23072 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23073 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23074 			    tcp->tcp_num_sack_blk);
23075 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23076 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23077 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23078 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23079 		} else {
23080 			tcp_hdr_len = tcp->tcp_hdr_len;
23081 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23082 		}
23083 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23084 		if (!mp1)
23085 			return (NULL);
23086 
23087 		/* Update the latest receive window size in TCP header. */
23088 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23089 		    tcp->tcp_tcph->th_win);
23090 		/* copy in prototype TCP + IP header */
23091 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23092 		mp1->b_rptr = rptr;
23093 		mp1->b_wptr = rptr + tcp_hdr_len;
23094 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23095 
23096 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23097 
23098 		/* Set the TCP sequence number. */
23099 		U32_TO_ABE32(seq_no, tcph->th_seq);
23100 
23101 		/* Set up the TCP flag field. */
23102 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23103 		if (tcp->tcp_ecn_echo_on)
23104 			tcph->th_flags[0] |= TH_ECE;
23105 
23106 		tcp->tcp_rack = tcp->tcp_rnxt;
23107 		tcp->tcp_rack_cnt = 0;
23108 
23109 		/* fill in timestamp option if in use */
23110 		if (tcp->tcp_snd_ts_ok) {
23111 			uint32_t llbolt = (uint32_t)lbolt;
23112 
23113 			U32_TO_BE32(llbolt,
23114 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23115 			U32_TO_BE32(tcp->tcp_ts_recent,
23116 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23117 		}
23118 
23119 		/* Fill in SACK options */
23120 		if (num_sack_blk > 0) {
23121 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23122 			sack_blk_t *tmp;
23123 			int32_t	i;
23124 
23125 			wptr[0] = TCPOPT_NOP;
23126 			wptr[1] = TCPOPT_NOP;
23127 			wptr[2] = TCPOPT_SACK;
23128 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23129 			    sizeof (sack_blk_t);
23130 			wptr += TCPOPT_REAL_SACK_LEN;
23131 
23132 			tmp = tcp->tcp_sack_list;
23133 			for (i = 0; i < num_sack_blk; i++) {
23134 				U32_TO_BE32(tmp[i].begin, wptr);
23135 				wptr += sizeof (tcp_seq);
23136 				U32_TO_BE32(tmp[i].end, wptr);
23137 				wptr += sizeof (tcp_seq);
23138 			}
23139 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23140 			    << 4);
23141 		}
23142 
23143 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23144 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23145 		} else {
23146 			/* Check for ip6i_t header in sticky hdrs */
23147 			ip6_t *ip6 = (ip6_t *)(rptr +
23148 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23149 			    sizeof (ip6i_t) : 0));
23150 
23151 			ip6->ip6_plen = htons(tcp_hdr_len -
23152 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23153 		}
23154 
23155 		/*
23156 		 * Prime pump for checksum calculation in IP.  Include the
23157 		 * adjustment for a source route if any.
23158 		 */
23159 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23160 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23161 		U16_TO_ABE16(data_length, tcph->th_sum);
23162 
23163 		if (tcp->tcp_ip_forward_progress) {
23164 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23165 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23166 			tcp->tcp_ip_forward_progress = B_FALSE;
23167 		}
23168 		return (mp1);
23169 	}
23170 }
23171 
23172 /*
23173  * Hash list insertion routine for tcp_t structures. Each hash bucket
23174  * contains a list of tcp_t entries, and each entry is bound to a unique
23175  * port. If there are multiple tcp_t's that are bound to the same port, then
23176  * one of them will be linked into the hash bucket list, and the rest will
23177  * hang off of that one entry. For each port, entries bound to a specific IP
23178  * address will be inserted before those those bound to INADDR_ANY.
23179  */
23180 static void
23181 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23182 {
23183 	tcp_t	**tcpp;
23184 	tcp_t	*tcpnext;
23185 	tcp_t	*tcphash;
23186 
23187 	if (tcp->tcp_ptpbhn != NULL) {
23188 		ASSERT(!caller_holds_lock);
23189 		tcp_bind_hash_remove(tcp);
23190 	}
23191 	tcpp = &tbf->tf_tcp;
23192 	if (!caller_holds_lock) {
23193 		mutex_enter(&tbf->tf_lock);
23194 	} else {
23195 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23196 	}
23197 	tcphash = tcpp[0];
23198 	tcpnext = NULL;
23199 	if (tcphash != NULL) {
23200 		/* Look for an entry using the same port */
23201 		while ((tcphash = tcpp[0]) != NULL &&
23202 		    tcp->tcp_lport != tcphash->tcp_lport)
23203 			tcpp = &(tcphash->tcp_bind_hash);
23204 
23205 		/* The port was not found, just add to the end */
23206 		if (tcphash == NULL)
23207 			goto insert;
23208 
23209 		/*
23210 		 * OK, there already exists an entry bound to the
23211 		 * same port.
23212 		 *
23213 		 * If the new tcp bound to the INADDR_ANY address
23214 		 * and the first one in the list is not bound to
23215 		 * INADDR_ANY we skip all entries until we find the
23216 		 * first one bound to INADDR_ANY.
23217 		 * This makes sure that applications binding to a
23218 		 * specific address get preference over those binding to
23219 		 * INADDR_ANY.
23220 		 */
23221 		tcpnext = tcphash;
23222 		tcphash = NULL;
23223 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23224 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23225 			while ((tcpnext = tcpp[0]) != NULL &&
23226 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23227 				tcpp = &(tcpnext->tcp_bind_hash_port);
23228 
23229 			if (tcpnext) {
23230 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23231 				tcphash = tcpnext->tcp_bind_hash;
23232 				if (tcphash != NULL) {
23233 					tcphash->tcp_ptpbhn =
23234 					    &(tcp->tcp_bind_hash);
23235 					tcpnext->tcp_bind_hash = NULL;
23236 				}
23237 			}
23238 		} else {
23239 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23240 			tcphash = tcpnext->tcp_bind_hash;
23241 			if (tcphash != NULL) {
23242 				tcphash->tcp_ptpbhn =
23243 				    &(tcp->tcp_bind_hash);
23244 				tcpnext->tcp_bind_hash = NULL;
23245 			}
23246 		}
23247 	}
23248 insert:
23249 	tcp->tcp_bind_hash_port = tcpnext;
23250 	tcp->tcp_bind_hash = tcphash;
23251 	tcp->tcp_ptpbhn = tcpp;
23252 	tcpp[0] = tcp;
23253 	if (!caller_holds_lock)
23254 		mutex_exit(&tbf->tf_lock);
23255 }
23256 
23257 /*
23258  * Hash list removal routine for tcp_t structures.
23259  */
23260 static void
23261 tcp_bind_hash_remove(tcp_t *tcp)
23262 {
23263 	tcp_t	*tcpnext;
23264 	kmutex_t *lockp;
23265 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23266 
23267 	if (tcp->tcp_ptpbhn == NULL)
23268 		return;
23269 
23270 	/*
23271 	 * Extract the lock pointer in case there are concurrent
23272 	 * hash_remove's for this instance.
23273 	 */
23274 	ASSERT(tcp->tcp_lport != 0);
23275 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23276 
23277 	ASSERT(lockp != NULL);
23278 	mutex_enter(lockp);
23279 	if (tcp->tcp_ptpbhn) {
23280 		tcpnext = tcp->tcp_bind_hash_port;
23281 		if (tcpnext != NULL) {
23282 			tcp->tcp_bind_hash_port = NULL;
23283 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23284 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23285 			if (tcpnext->tcp_bind_hash != NULL) {
23286 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23287 				    &(tcpnext->tcp_bind_hash);
23288 				tcp->tcp_bind_hash = NULL;
23289 			}
23290 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23291 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23292 			tcp->tcp_bind_hash = NULL;
23293 		}
23294 		*tcp->tcp_ptpbhn = tcpnext;
23295 		tcp->tcp_ptpbhn = NULL;
23296 	}
23297 	mutex_exit(lockp);
23298 }
23299 
23300 
23301 /*
23302  * Hash list lookup routine for tcp_t structures.
23303  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23304  */
23305 static tcp_t *
23306 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23307 {
23308 	tf_t	*tf;
23309 	tcp_t	*tcp;
23310 
23311 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23312 	mutex_enter(&tf->tf_lock);
23313 	for (tcp = tf->tf_tcp; tcp != NULL;
23314 	    tcp = tcp->tcp_acceptor_hash) {
23315 		if (tcp->tcp_acceptor_id == id) {
23316 			CONN_INC_REF(tcp->tcp_connp);
23317 			mutex_exit(&tf->tf_lock);
23318 			return (tcp);
23319 		}
23320 	}
23321 	mutex_exit(&tf->tf_lock);
23322 	return (NULL);
23323 }
23324 
23325 
23326 /*
23327  * Hash list insertion routine for tcp_t structures.
23328  */
23329 void
23330 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23331 {
23332 	tf_t	*tf;
23333 	tcp_t	**tcpp;
23334 	tcp_t	*tcpnext;
23335 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23336 
23337 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23338 
23339 	if (tcp->tcp_ptpahn != NULL)
23340 		tcp_acceptor_hash_remove(tcp);
23341 	tcpp = &tf->tf_tcp;
23342 	mutex_enter(&tf->tf_lock);
23343 	tcpnext = tcpp[0];
23344 	if (tcpnext)
23345 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23346 	tcp->tcp_acceptor_hash = tcpnext;
23347 	tcp->tcp_ptpahn = tcpp;
23348 	tcpp[0] = tcp;
23349 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23350 	mutex_exit(&tf->tf_lock);
23351 }
23352 
23353 /*
23354  * Hash list removal routine for tcp_t structures.
23355  */
23356 static void
23357 tcp_acceptor_hash_remove(tcp_t *tcp)
23358 {
23359 	tcp_t	*tcpnext;
23360 	kmutex_t *lockp;
23361 
23362 	/*
23363 	 * Extract the lock pointer in case there are concurrent
23364 	 * hash_remove's for this instance.
23365 	 */
23366 	lockp = tcp->tcp_acceptor_lockp;
23367 
23368 	if (tcp->tcp_ptpahn == NULL)
23369 		return;
23370 
23371 	ASSERT(lockp != NULL);
23372 	mutex_enter(lockp);
23373 	if (tcp->tcp_ptpahn) {
23374 		tcpnext = tcp->tcp_acceptor_hash;
23375 		if (tcpnext) {
23376 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23377 			tcp->tcp_acceptor_hash = NULL;
23378 		}
23379 		*tcp->tcp_ptpahn = tcpnext;
23380 		tcp->tcp_ptpahn = NULL;
23381 	}
23382 	mutex_exit(lockp);
23383 	tcp->tcp_acceptor_lockp = NULL;
23384 }
23385 
23386 /*
23387  * Type three generator adapted from the random() function in 4.4 BSD:
23388  */
23389 
23390 /*
23391  * Copyright (c) 1983, 1993
23392  *	The Regents of the University of California.  All rights reserved.
23393  *
23394  * Redistribution and use in source and binary forms, with or without
23395  * modification, are permitted provided that the following conditions
23396  * are met:
23397  * 1. Redistributions of source code must retain the above copyright
23398  *    notice, this list of conditions and the following disclaimer.
23399  * 2. Redistributions in binary form must reproduce the above copyright
23400  *    notice, this list of conditions and the following disclaimer in the
23401  *    documentation and/or other materials provided with the distribution.
23402  * 3. All advertising materials mentioning features or use of this software
23403  *    must display the following acknowledgement:
23404  *	This product includes software developed by the University of
23405  *	California, Berkeley and its contributors.
23406  * 4. Neither the name of the University nor the names of its contributors
23407  *    may be used to endorse or promote products derived from this software
23408  *    without specific prior written permission.
23409  *
23410  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23411  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23412  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23413  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23414  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23415  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23416  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23417  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23418  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23419  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23420  * SUCH DAMAGE.
23421  */
23422 
23423 /* Type 3 -- x**31 + x**3 + 1 */
23424 #define	DEG_3		31
23425 #define	SEP_3		3
23426 
23427 
23428 /* Protected by tcp_random_lock */
23429 static int tcp_randtbl[DEG_3 + 1];
23430 
23431 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23432 static int *tcp_random_rptr = &tcp_randtbl[1];
23433 
23434 static int *tcp_random_state = &tcp_randtbl[1];
23435 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23436 
23437 kmutex_t tcp_random_lock;
23438 
23439 void
23440 tcp_random_init(void)
23441 {
23442 	int i;
23443 	hrtime_t hrt;
23444 	time_t wallclock;
23445 	uint64_t result;
23446 
23447 	/*
23448 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23449 	 * a longlong, which may contain resolution down to nanoseconds.
23450 	 * The current time will either be a 32-bit or a 64-bit quantity.
23451 	 * XOR the two together in a 64-bit result variable.
23452 	 * Convert the result to a 32-bit value by multiplying the high-order
23453 	 * 32-bits by the low-order 32-bits.
23454 	 */
23455 
23456 	hrt = gethrtime();
23457 	(void) drv_getparm(TIME, &wallclock);
23458 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23459 	mutex_enter(&tcp_random_lock);
23460 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23461 	    (result & 0xffffffff);
23462 
23463 	for (i = 1; i < DEG_3; i++)
23464 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23465 		    + 12345;
23466 	tcp_random_fptr = &tcp_random_state[SEP_3];
23467 	tcp_random_rptr = &tcp_random_state[0];
23468 	mutex_exit(&tcp_random_lock);
23469 	for (i = 0; i < 10 * DEG_3; i++)
23470 		(void) tcp_random();
23471 }
23472 
23473 /*
23474  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23475  * This range is selected to be approximately centered on TCP_ISS / 2,
23476  * and easy to compute. We get this value by generating a 32-bit random
23477  * number, selecting out the high-order 17 bits, and then adding one so
23478  * that we never return zero.
23479  */
23480 int
23481 tcp_random(void)
23482 {
23483 	int i;
23484 
23485 	mutex_enter(&tcp_random_lock);
23486 	*tcp_random_fptr += *tcp_random_rptr;
23487 
23488 	/*
23489 	 * The high-order bits are more random than the low-order bits,
23490 	 * so we select out the high-order 17 bits and add one so that
23491 	 * we never return zero.
23492 	 */
23493 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23494 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23495 		tcp_random_fptr = tcp_random_state;
23496 		++tcp_random_rptr;
23497 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23498 		tcp_random_rptr = tcp_random_state;
23499 
23500 	mutex_exit(&tcp_random_lock);
23501 	return (i);
23502 }
23503 
23504 static int
23505 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23506     int *t_errorp, int *sys_errorp)
23507 {
23508 	int error;
23509 	int is_absreq_failure;
23510 	t_scalar_t *opt_lenp;
23511 	t_scalar_t opt_offset;
23512 	int prim_type;
23513 	struct T_conn_req *tcreqp;
23514 	struct T_conn_res *tcresp;
23515 	cred_t *cr;
23516 
23517 	/*
23518 	 * All Solaris components should pass a db_credp
23519 	 * for this TPI message, hence we ASSERT.
23520 	 * But in case there is some other M_PROTO that looks
23521 	 * like a TPI message sent by some other kernel
23522 	 * component, we check and return an error.
23523 	 */
23524 	cr = msg_getcred(mp, NULL);
23525 	ASSERT(cr != NULL);
23526 	if (cr == NULL)
23527 		return (-1);
23528 
23529 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23530 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23531 	    prim_type == T_CONN_RES);
23532 
23533 	switch (prim_type) {
23534 	case T_CONN_REQ:
23535 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23536 		opt_offset = tcreqp->OPT_offset;
23537 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23538 		break;
23539 	case O_T_CONN_RES:
23540 	case T_CONN_RES:
23541 		tcresp = (struct T_conn_res *)mp->b_rptr;
23542 		opt_offset = tcresp->OPT_offset;
23543 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23544 		break;
23545 	}
23546 
23547 	*t_errorp = 0;
23548 	*sys_errorp = 0;
23549 	*do_disconnectp = 0;
23550 
23551 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23552 	    opt_offset, cr, &tcp_opt_obj,
23553 	    NULL, &is_absreq_failure);
23554 
23555 	switch (error) {
23556 	case  0:		/* no error */
23557 		ASSERT(is_absreq_failure == 0);
23558 		return (0);
23559 	case ENOPROTOOPT:
23560 		*t_errorp = TBADOPT;
23561 		break;
23562 	case EACCES:
23563 		*t_errorp = TACCES;
23564 		break;
23565 	default:
23566 		*t_errorp = TSYSERR; *sys_errorp = error;
23567 		break;
23568 	}
23569 	if (is_absreq_failure != 0) {
23570 		/*
23571 		 * The connection request should get the local ack
23572 		 * T_OK_ACK and then a T_DISCON_IND.
23573 		 */
23574 		*do_disconnectp = 1;
23575 	}
23576 	return (-1);
23577 }
23578 
23579 /*
23580  * Split this function out so that if the secret changes, I'm okay.
23581  *
23582  * Initialize the tcp_iss_cookie and tcp_iss_key.
23583  */
23584 
23585 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23586 
23587 static void
23588 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
23589 {
23590 	struct {
23591 		int32_t current_time;
23592 		uint32_t randnum;
23593 		uint16_t pad;
23594 		uint8_t ether[6];
23595 		uint8_t passwd[PASSWD_SIZE];
23596 	} tcp_iss_cookie;
23597 	time_t t;
23598 
23599 	/*
23600 	 * Start with the current absolute time.
23601 	 */
23602 	(void) drv_getparm(TIME, &t);
23603 	tcp_iss_cookie.current_time = t;
23604 
23605 	/*
23606 	 * XXX - Need a more random number per RFC 1750, not this crap.
23607 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23608 	 */
23609 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23610 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23611 
23612 	/*
23613 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23614 	 * as a good template.
23615 	 */
23616 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23617 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23618 
23619 	/*
23620 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23621 	 */
23622 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23623 
23624 	/*
23625 	 * See 4010593 if this section becomes a problem again,
23626 	 * but the local ethernet address is useful here.
23627 	 */
23628 	(void) localetheraddr(NULL,
23629 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23630 
23631 	/*
23632 	 * Hash 'em all together.  The MD5Final is called per-connection.
23633 	 */
23634 	mutex_enter(&tcps->tcps_iss_key_lock);
23635 	MD5Init(&tcps->tcps_iss_key);
23636 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
23637 	    sizeof (tcp_iss_cookie));
23638 	mutex_exit(&tcps->tcps_iss_key_lock);
23639 }
23640 
23641 /*
23642  * Set the RFC 1948 pass phrase
23643  */
23644 /* ARGSUSED */
23645 static int
23646 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23647     cred_t *cr)
23648 {
23649 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23650 
23651 	/*
23652 	 * Basically, value contains a new pass phrase.  Pass it along!
23653 	 */
23654 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
23655 	return (0);
23656 }
23657 
23658 /* ARGSUSED */
23659 static int
23660 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23661 {
23662 	bzero(buf, sizeof (tcp_sack_info_t));
23663 	return (0);
23664 }
23665 
23666 /* ARGSUSED */
23667 static int
23668 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23669 {
23670 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23671 	return (0);
23672 }
23673 
23674 /*
23675  * Make sure we wait until the default queue is setup, yet allow
23676  * tcp_g_q_create() to open a TCP stream.
23677  * We need to allow tcp_g_q_create() do do an open
23678  * of tcp, hence we compare curhread.
23679  * All others have to wait until the tcps_g_q has been
23680  * setup.
23681  */
23682 void
23683 tcp_g_q_setup(tcp_stack_t *tcps)
23684 {
23685 	mutex_enter(&tcps->tcps_g_q_lock);
23686 	if (tcps->tcps_g_q != NULL) {
23687 		mutex_exit(&tcps->tcps_g_q_lock);
23688 		return;
23689 	}
23690 	if (tcps->tcps_g_q_creator == NULL) {
23691 		/* This thread will set it up */
23692 		tcps->tcps_g_q_creator = curthread;
23693 		mutex_exit(&tcps->tcps_g_q_lock);
23694 		tcp_g_q_create(tcps);
23695 		mutex_enter(&tcps->tcps_g_q_lock);
23696 		ASSERT(tcps->tcps_g_q_creator == curthread);
23697 		tcps->tcps_g_q_creator = NULL;
23698 		cv_signal(&tcps->tcps_g_q_cv);
23699 		ASSERT(tcps->tcps_g_q != NULL);
23700 		mutex_exit(&tcps->tcps_g_q_lock);
23701 		return;
23702 	}
23703 	/* Everybody but the creator has to wait */
23704 	if (tcps->tcps_g_q_creator != curthread) {
23705 		while (tcps->tcps_g_q == NULL)
23706 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
23707 	}
23708 	mutex_exit(&tcps->tcps_g_q_lock);
23709 }
23710 
23711 #define	IP	"ip"
23712 
23713 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
23714 
23715 /*
23716  * Create a default tcp queue here instead of in strplumb
23717  */
23718 void
23719 tcp_g_q_create(tcp_stack_t *tcps)
23720 {
23721 	int error;
23722 	ldi_handle_t	lh = NULL;
23723 	ldi_ident_t	li = NULL;
23724 	int		rval;
23725 	cred_t		*cr;
23726 	major_t IP_MAJ;
23727 
23728 #ifdef NS_DEBUG
23729 	(void) printf("tcp_g_q_create()\n");
23730 #endif
23731 
23732 	IP_MAJ = ddi_name_to_major(IP);
23733 
23734 	ASSERT(tcps->tcps_g_q_creator == curthread);
23735 
23736 	error = ldi_ident_from_major(IP_MAJ, &li);
23737 	if (error) {
23738 #ifdef DEBUG
23739 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
23740 		    error);
23741 #endif
23742 		return;
23743 	}
23744 
23745 	cr = zone_get_kcred(netstackid_to_zoneid(
23746 	    tcps->tcps_netstack->netstack_stackid));
23747 	ASSERT(cr != NULL);
23748 	/*
23749 	 * We set the tcp default queue to IPv6 because IPv4 falls
23750 	 * back to IPv6 when it can't find a client, but
23751 	 * IPv6 does not fall back to IPv4.
23752 	 */
23753 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
23754 	if (error) {
23755 #ifdef DEBUG
23756 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
23757 		    error);
23758 #endif
23759 		goto out;
23760 	}
23761 
23762 	/*
23763 	 * This ioctl causes the tcp framework to cache a pointer to
23764 	 * this stream, so we don't want to close the stream after
23765 	 * this operation.
23766 	 * Use the kernel credentials that are for the zone we're in.
23767 	 */
23768 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
23769 	    (intptr_t)0, FKIOCTL, cr, &rval);
23770 	if (error) {
23771 #ifdef DEBUG
23772 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
23773 		    "error %d\n", error);
23774 #endif
23775 		goto out;
23776 	}
23777 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
23778 	lh = NULL;
23779 out:
23780 	/* Close layered handles */
23781 	if (li)
23782 		ldi_ident_release(li);
23783 	/* Keep cred around until _inactive needs it */
23784 	tcps->tcps_g_q_cr = cr;
23785 }
23786 
23787 /*
23788  * We keep tcp_g_q set until all other tcp_t's in the zone
23789  * has gone away, and then when tcp_g_q_inactive() is called
23790  * we clear it.
23791  */
23792 void
23793 tcp_g_q_destroy(tcp_stack_t *tcps)
23794 {
23795 #ifdef NS_DEBUG
23796 	(void) printf("tcp_g_q_destroy()for stack %d\n",
23797 	    tcps->tcps_netstack->netstack_stackid);
23798 #endif
23799 
23800 	if (tcps->tcps_g_q == NULL) {
23801 		return;	/* Nothing to cleanup */
23802 	}
23803 	/*
23804 	 * Drop reference corresponding to the default queue.
23805 	 * This reference was added from tcp_open when the default queue
23806 	 * was created, hence we compensate for this extra drop in
23807 	 * tcp_g_q_close. If the refcnt drops to zero here it means
23808 	 * the default queue was the last one to be open, in which
23809 	 * case, then tcp_g_q_inactive will be
23810 	 * called as a result of the refrele.
23811 	 */
23812 	TCPS_REFRELE(tcps);
23813 }
23814 
23815 /*
23816  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23817  * Run by tcp_q_q_inactive using a taskq.
23818  */
23819 static void
23820 tcp_g_q_close(void *arg)
23821 {
23822 	tcp_stack_t *tcps = arg;
23823 	int error;
23824 	ldi_handle_t	lh = NULL;
23825 	ldi_ident_t	li = NULL;
23826 	cred_t		*cr;
23827 	major_t IP_MAJ;
23828 
23829 	IP_MAJ = ddi_name_to_major(IP);
23830 
23831 #ifdef NS_DEBUG
23832 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
23833 	    tcps->tcps_netstack->netstack_stackid,
23834 	    tcps->tcps_netstack->netstack_refcnt);
23835 #endif
23836 	lh = tcps->tcps_g_q_lh;
23837 	if (lh == NULL)
23838 		return;	/* Nothing to cleanup */
23839 
23840 	ASSERT(tcps->tcps_refcnt == 1);
23841 	ASSERT(tcps->tcps_g_q != NULL);
23842 
23843 	error = ldi_ident_from_major(IP_MAJ, &li);
23844 	if (error) {
23845 #ifdef DEBUG
23846 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
23847 		    error);
23848 #endif
23849 		return;
23850 	}
23851 
23852 	cr = tcps->tcps_g_q_cr;
23853 	tcps->tcps_g_q_cr = NULL;
23854 	ASSERT(cr != NULL);
23855 
23856 	/*
23857 	 * Make sure we can break the recursion when tcp_close decrements
23858 	 * the reference count causing g_q_inactive to be called again.
23859 	 */
23860 	tcps->tcps_g_q_lh = NULL;
23861 
23862 	/* close the default queue */
23863 	(void) ldi_close(lh, FREAD|FWRITE, cr);
23864 	/*
23865 	 * At this point in time tcps and the rest of netstack_t might
23866 	 * have been deleted.
23867 	 */
23868 	tcps = NULL;
23869 
23870 	/* Close layered handles */
23871 	ldi_ident_release(li);
23872 	crfree(cr);
23873 }
23874 
23875 /*
23876  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23877  *
23878  * Have to ensure that the ldi routines are not used by an
23879  * interrupt thread by using a taskq.
23880  */
23881 void
23882 tcp_g_q_inactive(tcp_stack_t *tcps)
23883 {
23884 	if (tcps->tcps_g_q_lh == NULL)
23885 		return;	/* Nothing to cleanup */
23886 
23887 	ASSERT(tcps->tcps_refcnt == 0);
23888 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
23889 
23890 	if (servicing_interrupt()) {
23891 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
23892 		    (void *) tcps, TQ_SLEEP);
23893 	} else {
23894 		tcp_g_q_close(tcps);
23895 	}
23896 }
23897 
23898 /*
23899  * Called by IP when IP is loaded into the kernel
23900  */
23901 void
23902 tcp_ddi_g_init(void)
23903 {
23904 	tcp_timercache = kmem_cache_create("tcp_timercache",
23905 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23906 	    NULL, NULL, NULL, NULL, NULL, 0);
23907 
23908 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23909 	    sizeof (tcp_sack_info_t), 0,
23910 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23911 
23912 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23913 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23914 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23915 
23916 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23917 
23918 	/* Initialize the random number generator */
23919 	tcp_random_init();
23920 
23921 	/* A single callback independently of how many netstacks we have */
23922 	ip_squeue_init(tcp_squeue_add);
23923 
23924 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
23925 
23926 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
23927 	    TASKQ_PREPOPULATE);
23928 
23929 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
23930 
23931 	/*
23932 	 * We want to be informed each time a stack is created or
23933 	 * destroyed in the kernel, so we can maintain the
23934 	 * set of tcp_stack_t's.
23935 	 */
23936 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
23937 	    tcp_stack_fini);
23938 }
23939 
23940 
23941 #define	INET_NAME	"ip"
23942 
23943 /*
23944  * Initialize the TCP stack instance.
23945  */
23946 static void *
23947 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
23948 {
23949 	tcp_stack_t	*tcps;
23950 	tcpparam_t	*pa;
23951 	int		i;
23952 	int		error = 0;
23953 	major_t		major;
23954 
23955 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
23956 	tcps->tcps_netstack = ns;
23957 
23958 	/* Initialize locks */
23959 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23960 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
23961 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23962 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23963 
23964 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
23965 	tcps->tcps_g_epriv_ports[0] = 2049;
23966 	tcps->tcps_g_epriv_ports[1] = 4045;
23967 	tcps->tcps_min_anonpriv_port = 512;
23968 
23969 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
23970 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
23971 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
23972 	    TCP_FANOUT_SIZE, KM_SLEEP);
23973 
23974 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
23975 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
23976 		    MUTEX_DEFAULT, NULL);
23977 	}
23978 
23979 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
23980 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
23981 		    MUTEX_DEFAULT, NULL);
23982 	}
23983 
23984 	/* TCP's IPsec code calls the packet dropper. */
23985 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
23986 
23987 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
23988 	tcps->tcps_params = pa;
23989 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
23990 
23991 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
23992 	    A_CNT(lcl_tcp_param_arr), tcps);
23993 
23994 	/*
23995 	 * Note: To really walk the device tree you need the devinfo
23996 	 * pointer to your device which is only available after probe/attach.
23997 	 * The following is safe only because it uses ddi_root_node()
23998 	 */
23999 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24000 	    tcp_opt_obj.odb_opt_arr_cnt);
24001 
24002 	/*
24003 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24004 	 * by the boot scripts.
24005 	 *
24006 	 * Use NULL name, as the name is caught by the new lockstats.
24007 	 *
24008 	 * Initialize with some random, non-guessable string, like the global
24009 	 * T_INFO_ACK.
24010 	 */
24011 
24012 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24013 	    sizeof (tcp_g_t_info_ack), tcps);
24014 
24015 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24016 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24017 
24018 	major = mod_name_to_major(INET_NAME);
24019 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24020 	ASSERT(error == 0);
24021 	return (tcps);
24022 }
24023 
24024 /*
24025  * Called when the IP module is about to be unloaded.
24026  */
24027 void
24028 tcp_ddi_g_destroy(void)
24029 {
24030 	tcp_g_kstat_fini(tcp_g_kstat);
24031 	tcp_g_kstat = NULL;
24032 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24033 
24034 	mutex_destroy(&tcp_random_lock);
24035 
24036 	kmem_cache_destroy(tcp_timercache);
24037 	kmem_cache_destroy(tcp_sack_info_cache);
24038 	kmem_cache_destroy(tcp_iphc_cache);
24039 
24040 	netstack_unregister(NS_TCP);
24041 	taskq_destroy(tcp_taskq);
24042 }
24043 
24044 /*
24045  * Shut down the TCP stack instance.
24046  */
24047 /* ARGSUSED */
24048 static void
24049 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24050 {
24051 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24052 
24053 	tcp_g_q_destroy(tcps);
24054 }
24055 
24056 /*
24057  * Free the TCP stack instance.
24058  */
24059 static void
24060 tcp_stack_fini(netstackid_t stackid, void *arg)
24061 {
24062 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24063 	int i;
24064 
24065 	nd_free(&tcps->tcps_g_nd);
24066 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24067 	tcps->tcps_params = NULL;
24068 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24069 	tcps->tcps_wroff_xtra_param = NULL;
24070 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24071 	tcps->tcps_mdt_head_param = NULL;
24072 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24073 	tcps->tcps_mdt_tail_param = NULL;
24074 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24075 	tcps->tcps_mdt_max_pbufs_param = NULL;
24076 
24077 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24078 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24079 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24080 	}
24081 
24082 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24083 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24084 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24085 	}
24086 
24087 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24088 	tcps->tcps_bind_fanout = NULL;
24089 
24090 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24091 	tcps->tcps_acceptor_fanout = NULL;
24092 
24093 	mutex_destroy(&tcps->tcps_iss_key_lock);
24094 	mutex_destroy(&tcps->tcps_g_q_lock);
24095 	cv_destroy(&tcps->tcps_g_q_cv);
24096 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24097 
24098 	ip_drop_unregister(&tcps->tcps_dropper);
24099 
24100 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24101 	tcps->tcps_kstat = NULL;
24102 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24103 
24104 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24105 	tcps->tcps_mibkp = NULL;
24106 
24107 	ldi_ident_release(tcps->tcps_ldi_ident);
24108 	kmem_free(tcps, sizeof (*tcps));
24109 }
24110 
24111 /*
24112  * Generate ISS, taking into account NDD changes may happen halfway through.
24113  * (If the iss is not zero, set it.)
24114  */
24115 
24116 static void
24117 tcp_iss_init(tcp_t *tcp)
24118 {
24119 	MD5_CTX context;
24120 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24121 	uint32_t answer[4];
24122 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24123 
24124 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24125 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24126 	switch (tcps->tcps_strong_iss) {
24127 	case 2:
24128 		mutex_enter(&tcps->tcps_iss_key_lock);
24129 		context = tcps->tcps_iss_key;
24130 		mutex_exit(&tcps->tcps_iss_key_lock);
24131 		arg.ports = tcp->tcp_ports;
24132 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24133 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24134 			    &arg.src);
24135 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24136 			    &arg.dst);
24137 		} else {
24138 			arg.src = tcp->tcp_ip6h->ip6_src;
24139 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24140 		}
24141 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24142 		MD5Final((uchar_t *)answer, &context);
24143 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24144 		/*
24145 		 * Now that we've hashed into a unique per-connection sequence
24146 		 * space, add a random increment per strong_iss == 1.  So I
24147 		 * guess we'll have to...
24148 		 */
24149 		/* FALLTHRU */
24150 	case 1:
24151 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24152 		break;
24153 	default:
24154 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24155 		break;
24156 	}
24157 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24158 	tcp->tcp_fss = tcp->tcp_iss - 1;
24159 	tcp->tcp_suna = tcp->tcp_iss;
24160 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24161 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24162 	tcp->tcp_csuna = tcp->tcp_snxt;
24163 }
24164 
24165 /*
24166  * Exported routine for extracting active tcp connection status.
24167  *
24168  * This is used by the Solaris Cluster Networking software to
24169  * gather a list of connections that need to be forwarded to
24170  * specific nodes in the cluster when configuration changes occur.
24171  *
24172  * The callback is invoked for each tcp_t structure from all netstacks,
24173  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24174  * from the netstack with the specified stack_id. Returning
24175  * non-zero from the callback routine terminates the search.
24176  */
24177 int
24178 cl_tcp_walk_list(netstackid_t stack_id,
24179     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24180 {
24181 	netstack_handle_t nh;
24182 	netstack_t *ns;
24183 	int ret = 0;
24184 
24185 	if (stack_id >= 0) {
24186 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24187 			return (EINVAL);
24188 
24189 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24190 		    ns->netstack_tcp);
24191 		netstack_rele(ns);
24192 		return (ret);
24193 	}
24194 
24195 	netstack_next_init(&nh);
24196 	while ((ns = netstack_next(&nh)) != NULL) {
24197 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24198 		    ns->netstack_tcp);
24199 		netstack_rele(ns);
24200 	}
24201 	netstack_next_fini(&nh);
24202 	return (ret);
24203 }
24204 
24205 static int
24206 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
24207     tcp_stack_t *tcps)
24208 {
24209 	tcp_t *tcp;
24210 	cl_tcp_info_t	cl_tcpi;
24211 	connf_t	*connfp;
24212 	conn_t	*connp;
24213 	int	i;
24214 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24215 
24216 	ASSERT(callback != NULL);
24217 
24218 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24219 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
24220 		connp = NULL;
24221 
24222 		while ((connp =
24223 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24224 
24225 			tcp = connp->conn_tcp;
24226 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24227 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24228 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24229 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24230 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24231 			/*
24232 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24233 			 * addresses. They are copied implicitly below as
24234 			 * mapped addresses.
24235 			 */
24236 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24237 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24238 				cl_tcpi.cl_tcpi_faddr =
24239 				    tcp->tcp_ipha->ipha_dst;
24240 			} else {
24241 				cl_tcpi.cl_tcpi_faddr_v6 =
24242 				    tcp->tcp_ip6h->ip6_dst;
24243 			}
24244 
24245 			/*
24246 			 * If the callback returns non-zero
24247 			 * we terminate the traversal.
24248 			 */
24249 			if ((*callback)(&cl_tcpi, arg) != 0) {
24250 				CONN_DEC_REF(tcp->tcp_connp);
24251 				return (1);
24252 			}
24253 		}
24254 	}
24255 
24256 	return (0);
24257 }
24258 
24259 /*
24260  * Macros used for accessing the different types of sockaddr
24261  * structures inside a tcp_ioc_abort_conn_t.
24262  */
24263 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24264 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24265 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24266 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24267 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24268 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24269 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24270 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24271 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24272 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24273 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24274 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24275 
24276 /*
24277  * Return the correct error code to mimic the behavior
24278  * of a connection reset.
24279  */
24280 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24281 		switch ((state)) {		\
24282 		case TCPS_SYN_SENT:		\
24283 		case TCPS_SYN_RCVD:		\
24284 			(err) = ECONNREFUSED;	\
24285 			break;			\
24286 		case TCPS_ESTABLISHED:		\
24287 		case TCPS_FIN_WAIT_1:		\
24288 		case TCPS_FIN_WAIT_2:		\
24289 		case TCPS_CLOSE_WAIT:		\
24290 			(err) = ECONNRESET;	\
24291 			break;			\
24292 		case TCPS_CLOSING:		\
24293 		case TCPS_LAST_ACK:		\
24294 		case TCPS_TIME_WAIT:		\
24295 			(err) = 0;		\
24296 			break;			\
24297 		default:			\
24298 			(err) = ENXIO;		\
24299 		}				\
24300 	}
24301 
24302 /*
24303  * Check if a tcp structure matches the info in acp.
24304  */
24305 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24306 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24307 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24308 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24309 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24310 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24311 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24312 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24313 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24314 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24315 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24316 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24317 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24318 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24319 	&(tcp)->tcp_ip_src_v6)) &&				\
24320 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24321 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24322 	&(tcp)->tcp_remote_v6)) &&				\
24323 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24324 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24325 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24326 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24327 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24328 	(acp)->ac_end >= (tcp)->tcp_state))
24329 
24330 #define	TCP_AC_MATCH(acp, tcp)					\
24331 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24332 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24333 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24334 
24335 /*
24336  * Build a message containing a tcp_ioc_abort_conn_t structure
24337  * which is filled in with information from acp and tp.
24338  */
24339 static mblk_t *
24340 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24341 {
24342 	mblk_t *mp;
24343 	tcp_ioc_abort_conn_t *tacp;
24344 
24345 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24346 	if (mp == NULL)
24347 		return (NULL);
24348 
24349 	mp->b_datap->db_type = M_CTL;
24350 
24351 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24352 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24353 	    sizeof (uint32_t));
24354 
24355 	tacp->ac_start = acp->ac_start;
24356 	tacp->ac_end = acp->ac_end;
24357 	tacp->ac_zoneid = acp->ac_zoneid;
24358 
24359 	if (acp->ac_local.ss_family == AF_INET) {
24360 		tacp->ac_local.ss_family = AF_INET;
24361 		tacp->ac_remote.ss_family = AF_INET;
24362 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24363 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24364 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24365 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24366 	} else {
24367 		tacp->ac_local.ss_family = AF_INET6;
24368 		tacp->ac_remote.ss_family = AF_INET6;
24369 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24370 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24371 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24372 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24373 	}
24374 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24375 	return (mp);
24376 }
24377 
24378 /*
24379  * Print a tcp_ioc_abort_conn_t structure.
24380  */
24381 static void
24382 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24383 {
24384 	char lbuf[128];
24385 	char rbuf[128];
24386 	sa_family_t af;
24387 	in_port_t lport, rport;
24388 	ushort_t logflags;
24389 
24390 	af = acp->ac_local.ss_family;
24391 
24392 	if (af == AF_INET) {
24393 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24394 		    lbuf, 128);
24395 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24396 		    rbuf, 128);
24397 		lport = ntohs(TCP_AC_V4LPORT(acp));
24398 		rport = ntohs(TCP_AC_V4RPORT(acp));
24399 	} else {
24400 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24401 		    lbuf, 128);
24402 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24403 		    rbuf, 128);
24404 		lport = ntohs(TCP_AC_V6LPORT(acp));
24405 		rport = ntohs(TCP_AC_V6RPORT(acp));
24406 	}
24407 
24408 	logflags = SL_TRACE | SL_NOTE;
24409 	/*
24410 	 * Don't print this message to the console if the operation was done
24411 	 * to a non-global zone.
24412 	 */
24413 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24414 		logflags |= SL_CONSOLE;
24415 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24416 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24417 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24418 	    acp->ac_start, acp->ac_end);
24419 }
24420 
24421 /*
24422  * Called inside tcp_rput when a message built using
24423  * tcp_ioctl_abort_build_msg is put into a queue.
24424  * Note that when we get here there is no wildcard in acp any more.
24425  */
24426 static void
24427 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24428 {
24429 	tcp_ioc_abort_conn_t *acp;
24430 
24431 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24432 	if (tcp->tcp_state <= acp->ac_end) {
24433 		/*
24434 		 * If we get here, we are already on the correct
24435 		 * squeue. This ioctl follows the following path
24436 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24437 		 * ->tcp_ioctl_abort->squeue_enter (if on a
24438 		 * different squeue)
24439 		 */
24440 		int errcode;
24441 
24442 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24443 		(void) tcp_clean_death(tcp, errcode, 26);
24444 	}
24445 	freemsg(mp);
24446 }
24447 
24448 /*
24449  * Abort all matching connections on a hash chain.
24450  */
24451 static int
24452 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24453     boolean_t exact, tcp_stack_t *tcps)
24454 {
24455 	int nmatch, err = 0;
24456 	tcp_t *tcp;
24457 	MBLKP mp, last, listhead = NULL;
24458 	conn_t	*tconnp;
24459 	connf_t	*connfp;
24460 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24461 
24462 	connfp = &ipst->ips_ipcl_conn_fanout[index];
24463 
24464 startover:
24465 	nmatch = 0;
24466 
24467 	mutex_enter(&connfp->connf_lock);
24468 	for (tconnp = connfp->connf_head; tconnp != NULL;
24469 	    tconnp = tconnp->conn_next) {
24470 		tcp = tconnp->conn_tcp;
24471 		if (TCP_AC_MATCH(acp, tcp)) {
24472 			CONN_INC_REF(tcp->tcp_connp);
24473 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24474 			if (mp == NULL) {
24475 				err = ENOMEM;
24476 				CONN_DEC_REF(tcp->tcp_connp);
24477 				break;
24478 			}
24479 			mp->b_prev = (mblk_t *)tcp;
24480 
24481 			if (listhead == NULL) {
24482 				listhead = mp;
24483 				last = mp;
24484 			} else {
24485 				last->b_next = mp;
24486 				last = mp;
24487 			}
24488 			nmatch++;
24489 			if (exact)
24490 				break;
24491 		}
24492 
24493 		/* Avoid holding lock for too long. */
24494 		if (nmatch >= 500)
24495 			break;
24496 	}
24497 	mutex_exit(&connfp->connf_lock);
24498 
24499 	/* Pass mp into the correct tcp */
24500 	while ((mp = listhead) != NULL) {
24501 		listhead = listhead->b_next;
24502 		tcp = (tcp_t *)mp->b_prev;
24503 		mp->b_next = mp->b_prev = NULL;
24504 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
24505 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
24506 	}
24507 
24508 	*count += nmatch;
24509 	if (nmatch >= 500 && err == 0)
24510 		goto startover;
24511 	return (err);
24512 }
24513 
24514 /*
24515  * Abort all connections that matches the attributes specified in acp.
24516  */
24517 static int
24518 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
24519 {
24520 	sa_family_t af;
24521 	uint32_t  ports;
24522 	uint16_t *pports;
24523 	int err = 0, count = 0;
24524 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24525 	int index = -1;
24526 	ushort_t logflags;
24527 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24528 
24529 	af = acp->ac_local.ss_family;
24530 
24531 	if (af == AF_INET) {
24532 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24533 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24534 			pports = (uint16_t *)&ports;
24535 			pports[1] = TCP_AC_V4LPORT(acp);
24536 			pports[0] = TCP_AC_V4RPORT(acp);
24537 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24538 		}
24539 	} else {
24540 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24541 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24542 			pports = (uint16_t *)&ports;
24543 			pports[1] = TCP_AC_V6LPORT(acp);
24544 			pports[0] = TCP_AC_V6RPORT(acp);
24545 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24546 		}
24547 	}
24548 
24549 	/*
24550 	 * For cases where remote addr, local port, and remote port are non-
24551 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24552 	 */
24553 	if (index != -1) {
24554 		err = tcp_ioctl_abort_bucket(acp, index,
24555 		    &count, exact, tcps);
24556 	} else {
24557 		/*
24558 		 * loop through all entries for wildcard case
24559 		 */
24560 		for (index = 0;
24561 		    index < ipst->ips_ipcl_conn_fanout_size;
24562 		    index++) {
24563 			err = tcp_ioctl_abort_bucket(acp, index,
24564 			    &count, exact, tcps);
24565 			if (err != 0)
24566 				break;
24567 		}
24568 	}
24569 
24570 	logflags = SL_TRACE | SL_NOTE;
24571 	/*
24572 	 * Don't print this message to the console if the operation was done
24573 	 * to a non-global zone.
24574 	 */
24575 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24576 		logflags |= SL_CONSOLE;
24577 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24578 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24579 	if (err == 0 && count == 0)
24580 		err = ENOENT;
24581 	return (err);
24582 }
24583 
24584 /*
24585  * Process the TCP_IOC_ABORT_CONN ioctl request.
24586  */
24587 static void
24588 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24589 {
24590 	int	err;
24591 	IOCP    iocp;
24592 	MBLKP   mp1;
24593 	sa_family_t laf, raf;
24594 	tcp_ioc_abort_conn_t *acp;
24595 	zone_t		*zptr;
24596 	conn_t		*connp = Q_TO_CONN(q);
24597 	zoneid_t	zoneid = connp->conn_zoneid;
24598 	tcp_t		*tcp = connp->conn_tcp;
24599 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24600 
24601 	iocp = (IOCP)mp->b_rptr;
24602 
24603 	if ((mp1 = mp->b_cont) == NULL ||
24604 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24605 		err = EINVAL;
24606 		goto out;
24607 	}
24608 
24609 	/* check permissions */
24610 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
24611 		err = EPERM;
24612 		goto out;
24613 	}
24614 
24615 	if (mp1->b_cont != NULL) {
24616 		freemsg(mp1->b_cont);
24617 		mp1->b_cont = NULL;
24618 	}
24619 
24620 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24621 	laf = acp->ac_local.ss_family;
24622 	raf = acp->ac_remote.ss_family;
24623 
24624 	/* check that a zone with the supplied zoneid exists */
24625 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24626 		zptr = zone_find_by_id(zoneid);
24627 		if (zptr != NULL) {
24628 			zone_rele(zptr);
24629 		} else {
24630 			err = EINVAL;
24631 			goto out;
24632 		}
24633 	}
24634 
24635 	/*
24636 	 * For exclusive stacks we set the zoneid to zero
24637 	 * to make TCP operate as if in the global zone.
24638 	 */
24639 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
24640 		acp->ac_zoneid = GLOBAL_ZONEID;
24641 
24642 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24643 	    acp->ac_start > acp->ac_end || laf != raf ||
24644 	    (laf != AF_INET && laf != AF_INET6)) {
24645 		err = EINVAL;
24646 		goto out;
24647 	}
24648 
24649 	tcp_ioctl_abort_dump(acp);
24650 	err = tcp_ioctl_abort(acp, tcps);
24651 
24652 out:
24653 	if (mp1 != NULL) {
24654 		freemsg(mp1);
24655 		mp->b_cont = NULL;
24656 	}
24657 
24658 	if (err != 0)
24659 		miocnak(q, mp, 0, err);
24660 	else
24661 		miocack(q, mp, 0, 0);
24662 }
24663 
24664 /*
24665  * tcp_time_wait_processing() handles processing of incoming packets when
24666  * the tcp is in the TIME_WAIT state.
24667  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24668  * on the time wait list.
24669  */
24670 void
24671 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24672     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24673 {
24674 	int32_t		bytes_acked;
24675 	int32_t		gap;
24676 	int32_t		rgap;
24677 	tcp_opt_t	tcpopt;
24678 	uint_t		flags;
24679 	uint32_t	new_swnd = 0;
24680 	conn_t		*connp;
24681 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24682 
24683 	BUMP_LOCAL(tcp->tcp_ibsegs);
24684 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
24685 
24686 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24687 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24688 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24689 	if (tcp->tcp_snd_ts_ok) {
24690 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24691 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24692 			    tcp->tcp_rnxt, TH_ACK);
24693 			goto done;
24694 		}
24695 	}
24696 	gap = seg_seq - tcp->tcp_rnxt;
24697 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24698 	if (gap < 0) {
24699 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
24700 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
24701 		    (seg_len > -gap ? -gap : seg_len));
24702 		seg_len += gap;
24703 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24704 			if (flags & TH_RST) {
24705 				goto done;
24706 			}
24707 			if ((flags & TH_FIN) && seg_len == -1) {
24708 				/*
24709 				 * When TCP receives a duplicate FIN in
24710 				 * TIME_WAIT state, restart the 2 MSL timer.
24711 				 * See page 73 in RFC 793. Make sure this TCP
24712 				 * is already on the TIME_WAIT list. If not,
24713 				 * just restart the timer.
24714 				 */
24715 				if (TCP_IS_DETACHED(tcp)) {
24716 					if (tcp_time_wait_remove(tcp, NULL) ==
24717 					    B_TRUE) {
24718 						tcp_time_wait_append(tcp);
24719 						TCP_DBGSTAT(tcps,
24720 						    tcp_rput_time_wait);
24721 					}
24722 				} else {
24723 					ASSERT(tcp != NULL);
24724 					TCP_TIMER_RESTART(tcp,
24725 					    tcps->tcps_time_wait_interval);
24726 				}
24727 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24728 				    tcp->tcp_rnxt, TH_ACK);
24729 				goto done;
24730 			}
24731 			flags |=  TH_ACK_NEEDED;
24732 			seg_len = 0;
24733 			goto process_ack;
24734 		}
24735 
24736 		/* Fix seg_seq, and chew the gap off the front. */
24737 		seg_seq = tcp->tcp_rnxt;
24738 	}
24739 
24740 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24741 		/*
24742 		 * Make sure that when we accept the connection, pick
24743 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24744 		 * old connection.
24745 		 *
24746 		 * The next ISS generated is equal to tcp_iss_incr_extra
24747 		 * + ISS_INCR/2 + other components depending on the
24748 		 * value of tcp_strong_iss.  We pre-calculate the new
24749 		 * ISS here and compare with tcp_snxt to determine if
24750 		 * we need to make adjustment to tcp_iss_incr_extra.
24751 		 *
24752 		 * The above calculation is ugly and is a
24753 		 * waste of CPU cycles...
24754 		 */
24755 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
24756 		int32_t adj;
24757 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24758 
24759 		switch (tcps->tcps_strong_iss) {
24760 		case 2: {
24761 			/* Add time and MD5 components. */
24762 			uint32_t answer[4];
24763 			struct {
24764 				uint32_t ports;
24765 				in6_addr_t src;
24766 				in6_addr_t dst;
24767 			} arg;
24768 			MD5_CTX context;
24769 
24770 			mutex_enter(&tcps->tcps_iss_key_lock);
24771 			context = tcps->tcps_iss_key;
24772 			mutex_exit(&tcps->tcps_iss_key_lock);
24773 			arg.ports = tcp->tcp_ports;
24774 			/* We use MAPPED addresses in tcp_iss_init */
24775 			arg.src = tcp->tcp_ip_src_v6;
24776 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24777 				IN6_IPADDR_TO_V4MAPPED(
24778 				    tcp->tcp_ipha->ipha_dst,
24779 				    &arg.dst);
24780 			} else {
24781 				arg.dst =
24782 				    tcp->tcp_ip6h->ip6_dst;
24783 			}
24784 			MD5Update(&context, (uchar_t *)&arg,
24785 			    sizeof (arg));
24786 			MD5Final((uchar_t *)answer, &context);
24787 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24788 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24789 			break;
24790 		}
24791 		case 1:
24792 			/* Add time component and min random (i.e. 1). */
24793 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24794 			break;
24795 		default:
24796 			/* Add only time component. */
24797 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24798 			break;
24799 		}
24800 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24801 			/*
24802 			 * New ISS not guaranteed to be ISS_INCR/2
24803 			 * ahead of the current tcp_snxt, so add the
24804 			 * difference to tcp_iss_incr_extra.
24805 			 */
24806 			tcps->tcps_iss_incr_extra += adj;
24807 		}
24808 		/*
24809 		 * If tcp_clean_death() can not perform the task now,
24810 		 * drop the SYN packet and let the other side re-xmit.
24811 		 * Otherwise pass the SYN packet back in, since the
24812 		 * old tcp state has been cleaned up or freed.
24813 		 */
24814 		if (tcp_clean_death(tcp, 0, 27) == -1)
24815 			goto done;
24816 		/*
24817 		 * We will come back to tcp_rput_data
24818 		 * on the global queue. Packets destined
24819 		 * for the global queue will be checked
24820 		 * with global policy. But the policy for
24821 		 * this packet has already been checked as
24822 		 * this was destined for the detached
24823 		 * connection. We need to bypass policy
24824 		 * check this time by attaching a dummy
24825 		 * ipsec_in with ipsec_in_dont_check set.
24826 		 */
24827 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
24828 		if (connp != NULL) {
24829 			TCP_STAT(tcps, tcp_time_wait_syn_success);
24830 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24831 			return;
24832 		}
24833 		goto done;
24834 	}
24835 
24836 	/*
24837 	 * rgap is the amount of stuff received out of window.  A negative
24838 	 * value is the amount out of window.
24839 	 */
24840 	if (rgap < 0) {
24841 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
24842 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
24843 		/* Fix seg_len and make sure there is something left. */
24844 		seg_len += rgap;
24845 		if (seg_len <= 0) {
24846 			if (flags & TH_RST) {
24847 				goto done;
24848 			}
24849 			flags |=  TH_ACK_NEEDED;
24850 			seg_len = 0;
24851 			goto process_ack;
24852 		}
24853 	}
24854 	/*
24855 	 * Check whether we can update tcp_ts_recent.  This test is
24856 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24857 	 * Extensions for High Performance: An Update", Internet Draft.
24858 	 */
24859 	if (tcp->tcp_snd_ts_ok &&
24860 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24861 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24862 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24863 		tcp->tcp_last_rcv_lbolt = lbolt64;
24864 	}
24865 
24866 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24867 		/* Always ack out of order packets */
24868 		flags |= TH_ACK_NEEDED;
24869 		seg_len = 0;
24870 	} else if (seg_len > 0) {
24871 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
24872 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
24873 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
24874 	}
24875 	if (flags & TH_RST) {
24876 		(void) tcp_clean_death(tcp, 0, 28);
24877 		goto done;
24878 	}
24879 	if (flags & TH_SYN) {
24880 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24881 		    TH_RST|TH_ACK);
24882 		/*
24883 		 * Do not delete the TCP structure if it is in
24884 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24885 		 */
24886 		goto done;
24887 	}
24888 process_ack:
24889 	if (flags & TH_ACK) {
24890 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24891 		if (bytes_acked <= 0) {
24892 			if (bytes_acked == 0 && seg_len == 0 &&
24893 			    new_swnd == tcp->tcp_swnd)
24894 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
24895 		} else {
24896 			/* Acks something not sent */
24897 			flags |= TH_ACK_NEEDED;
24898 		}
24899 	}
24900 	if (flags & TH_ACK_NEEDED) {
24901 		/*
24902 		 * Time to send an ack for some reason.
24903 		 */
24904 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24905 		    tcp->tcp_rnxt, TH_ACK);
24906 	}
24907 done:
24908 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24909 		DB_CKSUMSTART(mp) = 0;
24910 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24911 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
24912 	}
24913 	freemsg(mp);
24914 }
24915 
24916 /*
24917  * TCP Timers Implementation.
24918  */
24919 timeout_id_t
24920 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24921 {
24922 	mblk_t *mp;
24923 	tcp_timer_t *tcpt;
24924 	tcp_t *tcp = connp->conn_tcp;
24925 
24926 	ASSERT(connp->conn_sqp != NULL);
24927 
24928 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
24929 
24930 	if (tcp->tcp_timercache == NULL) {
24931 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24932 	} else {
24933 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
24934 		mp = tcp->tcp_timercache;
24935 		tcp->tcp_timercache = mp->b_next;
24936 		mp->b_next = NULL;
24937 		ASSERT(mp->b_wptr == NULL);
24938 	}
24939 
24940 	CONN_INC_REF(connp);
24941 	tcpt = (tcp_timer_t *)mp->b_rptr;
24942 	tcpt->connp = connp;
24943 	tcpt->tcpt_proc = f;
24944 	/*
24945 	 * TCP timers are normal timeouts. Plus, they do not require more than
24946 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
24947 	 * rounding up the expiration to the next resolution boundary, we can
24948 	 * batch timers in the callout subsystem to make TCP timers more
24949 	 * efficient. The roundup also protects short timers from expiring too
24950 	 * early before they have a chance to be cancelled.
24951 	 */
24952 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
24953 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
24954 
24955 	return ((timeout_id_t)mp);
24956 }
24957 
24958 static void
24959 tcp_timer_callback(void *arg)
24960 {
24961 	mblk_t *mp = (mblk_t *)arg;
24962 	tcp_timer_t *tcpt;
24963 	conn_t	*connp;
24964 
24965 	tcpt = (tcp_timer_t *)mp->b_rptr;
24966 	connp = tcpt->connp;
24967 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
24968 	    SQ_FILL, SQTAG_TCP_TIMER);
24969 }
24970 
24971 static void
24972 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24973 {
24974 	tcp_timer_t *tcpt;
24975 	conn_t *connp = (conn_t *)arg;
24976 	tcp_t *tcp = connp->conn_tcp;
24977 
24978 	tcpt = (tcp_timer_t *)mp->b_rptr;
24979 	ASSERT(connp == tcpt->connp);
24980 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24981 
24982 	/*
24983 	 * If the TCP has reached the closed state, don't proceed any
24984 	 * further. This TCP logically does not exist on the system.
24985 	 * tcpt_proc could for example access queues, that have already
24986 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24987 	 */
24988 	if (tcp->tcp_state != TCPS_CLOSED) {
24989 		(*tcpt->tcpt_proc)(connp);
24990 	} else {
24991 		tcp->tcp_timer_tid = 0;
24992 	}
24993 	tcp_timer_free(connp->conn_tcp, mp);
24994 }
24995 
24996 /*
24997  * There is potential race with untimeout and the handler firing at the same
24998  * time. The mblock may be freed by the handler while we are trying to use
24999  * it. But since both should execute on the same squeue, this race should not
25000  * occur.
25001  */
25002 clock_t
25003 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25004 {
25005 	mblk_t	*mp = (mblk_t *)id;
25006 	tcp_timer_t *tcpt;
25007 	clock_t delta;
25008 
25009 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25010 
25011 	if (mp == NULL)
25012 		return (-1);
25013 
25014 	tcpt = (tcp_timer_t *)mp->b_rptr;
25015 	ASSERT(tcpt->connp == connp);
25016 
25017 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25018 
25019 	if (delta >= 0) {
25020 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
25021 		tcp_timer_free(connp->conn_tcp, mp);
25022 		CONN_DEC_REF(connp);
25023 	}
25024 
25025 	return (delta);
25026 }
25027 
25028 /*
25029  * Allocate space for the timer event. The allocation looks like mblk, but it is
25030  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25031  *
25032  * Dealing with failures: If we can't allocate from the timer cache we try
25033  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25034  * points to b_rptr.
25035  * If we can't allocate anything using allocb_tryhard(), we perform a last
25036  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25037  * save the actual allocation size in b_datap.
25038  */
25039 mblk_t *
25040 tcp_timermp_alloc(int kmflags)
25041 {
25042 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25043 	    kmflags & ~KM_PANIC);
25044 
25045 	if (mp != NULL) {
25046 		mp->b_next = mp->b_prev = NULL;
25047 		mp->b_rptr = (uchar_t *)(&mp[1]);
25048 		mp->b_wptr = NULL;
25049 		mp->b_datap = NULL;
25050 		mp->b_queue = NULL;
25051 		mp->b_cont = NULL;
25052 	} else if (kmflags & KM_PANIC) {
25053 		/*
25054 		 * Failed to allocate memory for the timer. Try allocating from
25055 		 * dblock caches.
25056 		 */
25057 		/* ipclassifier calls this from a constructor - hence no tcps */
25058 		TCP_G_STAT(tcp_timermp_allocfail);
25059 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25060 		if (mp == NULL) {
25061 			size_t size = 0;
25062 			/*
25063 			 * Memory is really low. Try tryhard allocation.
25064 			 *
25065 			 * ipclassifier calls this from a constructor -
25066 			 * hence no tcps
25067 			 */
25068 			TCP_G_STAT(tcp_timermp_allocdblfail);
25069 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25070 			    sizeof (tcp_timer_t), &size, kmflags);
25071 			mp->b_rptr = (uchar_t *)(&mp[1]);
25072 			mp->b_next = mp->b_prev = NULL;
25073 			mp->b_wptr = (uchar_t *)-1;
25074 			mp->b_datap = (dblk_t *)size;
25075 			mp->b_queue = NULL;
25076 			mp->b_cont = NULL;
25077 		}
25078 		ASSERT(mp->b_wptr != NULL);
25079 	}
25080 	/* ipclassifier calls this from a constructor - hence no tcps */
25081 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25082 
25083 	return (mp);
25084 }
25085 
25086 /*
25087  * Free per-tcp timer cache.
25088  * It can only contain entries from tcp_timercache.
25089  */
25090 void
25091 tcp_timermp_free(tcp_t *tcp)
25092 {
25093 	mblk_t *mp;
25094 
25095 	while ((mp = tcp->tcp_timercache) != NULL) {
25096 		ASSERT(mp->b_wptr == NULL);
25097 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25098 		kmem_cache_free(tcp_timercache, mp);
25099 	}
25100 }
25101 
25102 /*
25103  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25104  * events there already (currently at most two events are cached).
25105  * If the event is not allocated from the timer cache, free it right away.
25106  */
25107 static void
25108 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25109 {
25110 	mblk_t *mp1 = tcp->tcp_timercache;
25111 
25112 	if (mp->b_wptr != NULL) {
25113 		/*
25114 		 * This allocation is not from a timer cache, free it right
25115 		 * away.
25116 		 */
25117 		if (mp->b_wptr != (uchar_t *)-1)
25118 			freeb(mp);
25119 		else
25120 			kmem_free(mp, (size_t)mp->b_datap);
25121 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25122 		/* Cache this timer block for future allocations */
25123 		mp->b_rptr = (uchar_t *)(&mp[1]);
25124 		mp->b_next = mp1;
25125 		tcp->tcp_timercache = mp;
25126 	} else {
25127 		kmem_cache_free(tcp_timercache, mp);
25128 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25129 	}
25130 }
25131 
25132 /*
25133  * End of TCP Timers implementation.
25134  */
25135 
25136 /*
25137  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25138  * on the specified backing STREAMS q. Note, the caller may make the
25139  * decision to call based on the tcp_t.tcp_flow_stopped value which
25140  * when check outside the q's lock is only an advisory check ...
25141  */
25142 void
25143 tcp_setqfull(tcp_t *tcp)
25144 {
25145 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25146 	conn_t	*connp = tcp->tcp_connp;
25147 
25148 	if (tcp->tcp_closed)
25149 		return;
25150 
25151 	if (IPCL_IS_NONSTR(connp)) {
25152 		(*connp->conn_upcalls->su_txq_full)
25153 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25154 		tcp->tcp_flow_stopped = B_TRUE;
25155 	} else {
25156 		queue_t *q = tcp->tcp_wq;
25157 
25158 		if (!(q->q_flag & QFULL)) {
25159 			mutex_enter(QLOCK(q));
25160 			if (!(q->q_flag & QFULL)) {
25161 				/* still need to set QFULL */
25162 				q->q_flag |= QFULL;
25163 				tcp->tcp_flow_stopped = B_TRUE;
25164 				mutex_exit(QLOCK(q));
25165 				TCP_STAT(tcps, tcp_flwctl_on);
25166 			} else {
25167 				mutex_exit(QLOCK(q));
25168 			}
25169 		}
25170 	}
25171 }
25172 
25173 void
25174 tcp_clrqfull(tcp_t *tcp)
25175 {
25176 	conn_t  *connp = tcp->tcp_connp;
25177 
25178 	if (tcp->tcp_closed)
25179 		return;
25180 
25181 	if (IPCL_IS_NONSTR(connp)) {
25182 		(*connp->conn_upcalls->su_txq_full)
25183 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25184 		tcp->tcp_flow_stopped = B_FALSE;
25185 	} else {
25186 		queue_t *q = tcp->tcp_wq;
25187 
25188 		if (q->q_flag & QFULL) {
25189 			mutex_enter(QLOCK(q));
25190 			if (q->q_flag & QFULL) {
25191 				q->q_flag &= ~QFULL;
25192 				tcp->tcp_flow_stopped = B_FALSE;
25193 				mutex_exit(QLOCK(q));
25194 				if (q->q_flag & QWANTW)
25195 					qbackenable(q, 0);
25196 			} else {
25197 				mutex_exit(QLOCK(q));
25198 			}
25199 		}
25200 	}
25201 }
25202 
25203 /*
25204  * kstats related to squeues i.e. not per IP instance
25205  */
25206 static void *
25207 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
25208 {
25209 	kstat_t *ksp;
25210 
25211 	tcp_g_stat_t template = {
25212 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
25213 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
25214 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
25215 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
25216 	};
25217 
25218 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
25219 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25220 	    KSTAT_FLAG_VIRTUAL);
25221 
25222 	if (ksp == NULL)
25223 		return (NULL);
25224 
25225 	bcopy(&template, tcp_g_statp, sizeof (template));
25226 	ksp->ks_data = (void *)tcp_g_statp;
25227 
25228 	kstat_install(ksp);
25229 	return (ksp);
25230 }
25231 
25232 static void
25233 tcp_g_kstat_fini(kstat_t *ksp)
25234 {
25235 	if (ksp != NULL) {
25236 		kstat_delete(ksp);
25237 	}
25238 }
25239 
25240 
25241 static void *
25242 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
25243 {
25244 	kstat_t *ksp;
25245 
25246 	tcp_stat_t template = {
25247 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
25248 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
25249 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
25250 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
25251 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
25252 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
25253 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
25254 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
25255 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
25256 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
25257 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
25258 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
25259 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
25260 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
25261 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
25262 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
25263 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
25264 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
25265 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
25266 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
25267 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
25268 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
25269 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
25270 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
25271 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
25272 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
25273 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
25274 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
25275 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
25276 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
25277 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
25278 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
25279 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
25280 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
25281 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
25282 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
25283 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
25284 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
25285 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
25286 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
25287 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
25288 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
25289 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
25290 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
25291 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
25292 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
25293 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
25294 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
25295 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
25296 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
25297 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
25298 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
25299 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
25300 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
25301 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
25302 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
25303 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
25304 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
25305 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
25306 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
25307 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
25308 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
25309 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
25310 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
25311 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
25312 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
25313 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
25314 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
25315 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
25316 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
25317 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
25318 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
25319 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
25320 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
25321 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
25322 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
25323 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
25324 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
25325 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
25326 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
25327 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
25328 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
25329 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
25330 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
25331 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
25332 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
25333 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
25334 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
25335 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
25336 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
25337 	};
25338 
25339 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
25340 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25341 	    KSTAT_FLAG_VIRTUAL, stackid);
25342 
25343 	if (ksp == NULL)
25344 		return (NULL);
25345 
25346 	bcopy(&template, tcps_statisticsp, sizeof (template));
25347 	ksp->ks_data = (void *)tcps_statisticsp;
25348 	ksp->ks_private = (void *)(uintptr_t)stackid;
25349 
25350 	kstat_install(ksp);
25351 	return (ksp);
25352 }
25353 
25354 static void
25355 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
25356 {
25357 	if (ksp != NULL) {
25358 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25359 		kstat_delete_netstack(ksp, stackid);
25360 	}
25361 }
25362 
25363 /*
25364  * TCP Kstats implementation
25365  */
25366 static void *
25367 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
25368 {
25369 	kstat_t	*ksp;
25370 
25371 	tcp_named_kstat_t template = {
25372 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25373 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25374 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25375 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25376 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25377 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25378 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25379 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25380 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25381 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25382 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25383 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25384 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25385 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25386 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25387 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25388 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25389 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25390 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25391 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25392 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25393 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25394 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25395 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25396 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25397 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25398 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25399 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25400 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25401 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25402 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25403 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25404 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25405 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25406 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25407 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25408 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25409 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25410 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25411 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25412 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25413 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25414 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25415 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25416 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25417 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25418 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25419 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25420 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25421 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25422 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25423 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25424 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25425 	};
25426 
25427 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
25428 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
25429 
25430 	if (ksp == NULL)
25431 		return (NULL);
25432 
25433 	template.rtoAlgorithm.value.ui32 = 4;
25434 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
25435 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
25436 	template.maxConn.value.i32 = -1;
25437 
25438 	bcopy(&template, ksp->ks_data, sizeof (template));
25439 	ksp->ks_update = tcp_kstat_update;
25440 	ksp->ks_private = (void *)(uintptr_t)stackid;
25441 
25442 	kstat_install(ksp);
25443 	return (ksp);
25444 }
25445 
25446 static void
25447 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
25448 {
25449 	if (ksp != NULL) {
25450 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25451 		kstat_delete_netstack(ksp, stackid);
25452 	}
25453 }
25454 
25455 static int
25456 tcp_kstat_update(kstat_t *kp, int rw)
25457 {
25458 	tcp_named_kstat_t *tcpkp;
25459 	tcp_t		*tcp;
25460 	connf_t		*connfp;
25461 	conn_t		*connp;
25462 	int 		i;
25463 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
25464 	netstack_t	*ns;
25465 	tcp_stack_t	*tcps;
25466 	ip_stack_t	*ipst;
25467 
25468 	if ((kp == NULL) || (kp->ks_data == NULL))
25469 		return (EIO);
25470 
25471 	if (rw == KSTAT_WRITE)
25472 		return (EACCES);
25473 
25474 	ns = netstack_find_by_stackid(stackid);
25475 	if (ns == NULL)
25476 		return (-1);
25477 	tcps = ns->netstack_tcp;
25478 	if (tcps == NULL) {
25479 		netstack_rele(ns);
25480 		return (-1);
25481 	}
25482 
25483 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25484 
25485 	tcpkp->currEstab.value.ui32 = 0;
25486 
25487 	ipst = ns->netstack_ip;
25488 
25489 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25490 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25491 		connp = NULL;
25492 		while ((connp =
25493 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25494 			tcp = connp->conn_tcp;
25495 			switch (tcp_snmp_state(tcp)) {
25496 			case MIB2_TCP_established:
25497 			case MIB2_TCP_closeWait:
25498 				tcpkp->currEstab.value.ui32++;
25499 				break;
25500 			}
25501 		}
25502 	}
25503 
25504 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
25505 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
25506 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
25507 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
25508 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
25509 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
25510 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
25511 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
25512 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
25513 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
25514 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
25515 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
25516 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
25517 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
25518 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
25519 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
25520 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
25521 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
25522 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
25523 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
25524 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
25525 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
25526 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
25527 	tcpkp->inDataInorderSegs.value.ui32 =
25528 	    tcps->tcps_mib.tcpInDataInorderSegs;
25529 	tcpkp->inDataInorderBytes.value.ui32 =
25530 	    tcps->tcps_mib.tcpInDataInorderBytes;
25531 	tcpkp->inDataUnorderSegs.value.ui32 =
25532 	    tcps->tcps_mib.tcpInDataUnorderSegs;
25533 	tcpkp->inDataUnorderBytes.value.ui32 =
25534 	    tcps->tcps_mib.tcpInDataUnorderBytes;
25535 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
25536 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
25537 	tcpkp->inDataPartDupSegs.value.ui32 =
25538 	    tcps->tcps_mib.tcpInDataPartDupSegs;
25539 	tcpkp->inDataPartDupBytes.value.ui32 =
25540 	    tcps->tcps_mib.tcpInDataPartDupBytes;
25541 	tcpkp->inDataPastWinSegs.value.ui32 =
25542 	    tcps->tcps_mib.tcpInDataPastWinSegs;
25543 	tcpkp->inDataPastWinBytes.value.ui32 =
25544 	    tcps->tcps_mib.tcpInDataPastWinBytes;
25545 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
25546 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
25547 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
25548 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
25549 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
25550 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
25551 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
25552 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
25553 	tcpkp->timKeepaliveProbe.value.ui32 =
25554 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
25555 	tcpkp->timKeepaliveDrop.value.ui32 =
25556 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
25557 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
25558 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
25559 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
25560 	tcpkp->outSackRetransSegs.value.ui32 =
25561 	    tcps->tcps_mib.tcpOutSackRetransSegs;
25562 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
25563 
25564 	netstack_rele(ns);
25565 	return (0);
25566 }
25567 
25568 void
25569 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25570 {
25571 	uint16_t	hdr_len;
25572 	ipha_t		*ipha;
25573 	uint8_t		*nexthdrp;
25574 	tcph_t		*tcph;
25575 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
25576 
25577 	/* Already has an eager */
25578 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25579 		TCP_STAT(tcps, tcp_reinput_syn);
25580 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25581 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
25582 		return;
25583 	}
25584 
25585 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25586 	case IPV4_VERSION:
25587 		ipha = (ipha_t *)mp->b_rptr;
25588 		hdr_len = IPH_HDR_LENGTH(ipha);
25589 		break;
25590 	case IPV6_VERSION:
25591 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25592 		    &hdr_len, &nexthdrp)) {
25593 			CONN_DEC_REF(connp);
25594 			freemsg(mp);
25595 			return;
25596 		}
25597 		break;
25598 	}
25599 
25600 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25601 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25602 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25603 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25604 	}
25605 
25606 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25607 	    SQ_FILL, SQTAG_TCP_REINPUT);
25608 }
25609 
25610 static int
25611 tcp_squeue_switch(int val)
25612 {
25613 	int rval = SQ_FILL;
25614 
25615 	switch (val) {
25616 	case 1:
25617 		rval = SQ_NODRAIN;
25618 		break;
25619 	case 2:
25620 		rval = SQ_PROCESS;
25621 		break;
25622 	default:
25623 		break;
25624 	}
25625 	return (rval);
25626 }
25627 
25628 /*
25629  * This is called once for each squeue - globally for all stack
25630  * instances.
25631  */
25632 static void
25633 tcp_squeue_add(squeue_t *sqp)
25634 {
25635 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25636 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
25637 
25638 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25639 	tcp_time_wait->tcp_time_wait_tid =
25640 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
25641 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
25642 	    CALLOUT_FLAG_ROUNDUP);
25643 	if (tcp_free_list_max_cnt == 0) {
25644 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25645 		    max_ncpus : boot_max_ncpus);
25646 
25647 		/*
25648 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25649 		 */
25650 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25651 		    (tcp_ncpus * sizeof (tcp_t) * 100);
25652 	}
25653 	tcp_time_wait->tcp_free_list_cnt = 0;
25654 }
25655 
25656 static int
25657 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
25658 {
25659 	mblk_t	*ire_mp = NULL;
25660 	mblk_t	*syn_mp;
25661 	mblk_t	*mdti;
25662 	mblk_t	*lsoi;
25663 	int	retval;
25664 	tcph_t	*tcph;
25665 	cred_t	*ecr;
25666 	ts_label_t	*tsl;
25667 	uint32_t	mss;
25668 	conn_t	*connp = tcp->tcp_connp;
25669 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25670 
25671 	if (error == 0) {
25672 		/*
25673 		 * Adapt Multidata information, if any.  The
25674 		 * following tcp_mdt_update routine will free
25675 		 * the message.
25676 		 */
25677 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
25678 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
25679 			    b_rptr)->mdt_capab, B_TRUE);
25680 			freemsg(mdti);
25681 		}
25682 
25683 		/*
25684 		 * Check to update LSO information with tcp, and
25685 		 * tcp_lso_update routine will free the message.
25686 		 */
25687 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
25688 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
25689 			    b_rptr)->lso_capab);
25690 			freemsg(lsoi);
25691 		}
25692 
25693 		/* Get the IRE, if we had requested for it */
25694 		if (mp != NULL)
25695 			ire_mp = tcp_ire_mp(&mp);
25696 
25697 		if (tcp->tcp_hard_binding) {
25698 			tcp->tcp_hard_binding = B_FALSE;
25699 			tcp->tcp_hard_bound = B_TRUE;
25700 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
25701 			if (retval != 0) {
25702 				error = EADDRINUSE;
25703 				goto bind_failed;
25704 			}
25705 		} else {
25706 			if (ire_mp != NULL)
25707 				freeb(ire_mp);
25708 			goto after_syn_sent;
25709 		}
25710 
25711 		retval = tcp_adapt_ire(tcp, ire_mp);
25712 		if (ire_mp != NULL)
25713 			freeb(ire_mp);
25714 		if (retval == 0) {
25715 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
25716 			    ENETUNREACH : EADDRNOTAVAIL);
25717 			goto ipcl_rm;
25718 		}
25719 		/*
25720 		 * Don't let an endpoint connect to itself.
25721 		 * Also checked in tcp_connect() but that
25722 		 * check can't handle the case when the
25723 		 * local IP address is INADDR_ANY.
25724 		 */
25725 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25726 			if ((tcp->tcp_ipha->ipha_dst ==
25727 			    tcp->tcp_ipha->ipha_src) &&
25728 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25729 			    tcp->tcp_tcph->th_fport))) {
25730 				error = EADDRNOTAVAIL;
25731 				goto ipcl_rm;
25732 			}
25733 		} else {
25734 			if (IN6_ARE_ADDR_EQUAL(
25735 			    &tcp->tcp_ip6h->ip6_dst,
25736 			    &tcp->tcp_ip6h->ip6_src) &&
25737 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25738 			    tcp->tcp_tcph->th_fport))) {
25739 				error = EADDRNOTAVAIL;
25740 				goto ipcl_rm;
25741 			}
25742 		}
25743 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
25744 		/*
25745 		 * This should not be possible!  Just for
25746 		 * defensive coding...
25747 		 */
25748 		if (tcp->tcp_state != TCPS_SYN_SENT)
25749 			goto after_syn_sent;
25750 
25751 		if (is_system_labeled() &&
25752 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
25753 			error = EHOSTUNREACH;
25754 			goto ipcl_rm;
25755 		}
25756 
25757 		/*
25758 		 * tcp_adapt_ire() does not adjust
25759 		 * for TCP/IP header length.
25760 		 */
25761 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
25762 
25763 		/*
25764 		 * Just make sure our rwnd is at
25765 		 * least tcp_recv_hiwat_mss * MSS
25766 		 * large, and round up to the nearest
25767 		 * MSS.
25768 		 *
25769 		 * We do the round up here because
25770 		 * we need to get the interface
25771 		 * MTU first before we can do the
25772 		 * round up.
25773 		 */
25774 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
25775 		    tcps->tcps_recv_hiwat_minmss * mss);
25776 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
25777 		tcp_set_ws_value(tcp);
25778 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
25779 		    tcp->tcp_tcph->th_win);
25780 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
25781 			tcp->tcp_snd_ws_ok = B_TRUE;
25782 
25783 		/*
25784 		 * Set tcp_snd_ts_ok to true
25785 		 * so that tcp_xmit_mp will
25786 		 * include the timestamp
25787 		 * option in the SYN segment.
25788 		 */
25789 		if (tcps->tcps_tstamp_always ||
25790 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
25791 			tcp->tcp_snd_ts_ok = B_TRUE;
25792 		}
25793 
25794 		/*
25795 		 * tcp_snd_sack_ok can be set in
25796 		 * tcp_adapt_ire() if the sack metric
25797 		 * is set.  So check it here also.
25798 		 */
25799 		if (tcps->tcps_sack_permitted == 2 ||
25800 		    tcp->tcp_snd_sack_ok) {
25801 			if (tcp->tcp_sack_info == NULL) {
25802 				tcp->tcp_sack_info =
25803 				    kmem_cache_alloc(tcp_sack_info_cache,
25804 				    KM_SLEEP);
25805 			}
25806 			tcp->tcp_snd_sack_ok = B_TRUE;
25807 		}
25808 
25809 		/*
25810 		 * Should we use ECN?  Note that the current
25811 		 * default value (SunOS 5.9) of tcp_ecn_permitted
25812 		 * is 1.  The reason for doing this is that there
25813 		 * are equipments out there that will drop ECN
25814 		 * enabled IP packets.  Setting it to 1 avoids
25815 		 * compatibility problems.
25816 		 */
25817 		if (tcps->tcps_ecn_permitted == 2)
25818 			tcp->tcp_ecn_ok = B_TRUE;
25819 
25820 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
25821 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
25822 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
25823 		if (syn_mp) {
25824 			/*
25825 			 * cr contains the cred from the thread calling
25826 			 * connect().
25827 			 *
25828 			 * If no thread cred is available, use the
25829 			 * socket creator's cred instead. If still no
25830 			 * cred, drop the request rather than risk a
25831 			 * panic on production systems.
25832 			 */
25833 			if (cr == NULL) {
25834 				cr = CONN_CRED(connp);
25835 				pid = tcp->tcp_cpid;
25836 				ASSERT(cr != NULL);
25837 				if (cr != NULL) {
25838 					mblk_setcred(syn_mp, cr, pid);
25839 				} else {
25840 					error = ECONNABORTED;
25841 					goto ipcl_rm;
25842 				}
25843 
25844 			/*
25845 			 * If an effective security label exists for
25846 			 * the connection, create a copy of the thread's
25847 			 * cred but with the effective label attached.
25848 			 */
25849 			} else if (is_system_labeled() &&
25850 			    connp->conn_effective_cred != NULL &&
25851 			    (tsl = crgetlabel(connp->
25852 			    conn_effective_cred)) != NULL) {
25853 				if ((ecr = copycred_from_tslabel(cr,
25854 				    tsl, KM_NOSLEEP)) == NULL) {
25855 					error = ENOMEM;
25856 					goto ipcl_rm;
25857 				}
25858 				mblk_setcred(syn_mp, ecr, pid);
25859 				crfree(ecr);
25860 
25861 			/*
25862 			 * Default to using the thread's cred unchanged.
25863 			 */
25864 			} else {
25865 				mblk_setcred(syn_mp, cr, pid);
25866 			}
25867 
25868 			/*
25869 			 * We must bump the generation before sending the syn
25870 			 * to ensure that we use the right generation in case
25871 			 * this thread issues a "connected" up call.
25872 			 */
25873 			SOCK_CONNID_BUMP(tcp->tcp_connid);
25874 
25875 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
25876 		}
25877 	after_syn_sent:
25878 		if (mp != NULL) {
25879 			ASSERT(mp->b_cont == NULL);
25880 			freeb(mp);
25881 		}
25882 		return (error);
25883 	} else {
25884 		/* error */
25885 		if (tcp->tcp_debug) {
25886 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
25887 			    "tcp_post_ip_bind: error == %d", error);
25888 		}
25889 		if (mp != NULL) {
25890 			freeb(mp);
25891 		}
25892 	}
25893 
25894 ipcl_rm:
25895 	/*
25896 	 * Need to unbind with classifier since we were just
25897 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
25898 	 */
25899 	tcp->tcp_hard_bound = B_FALSE;
25900 	tcp->tcp_hard_binding = B_FALSE;
25901 
25902 	ipcl_hash_remove(connp);
25903 
25904 bind_failed:
25905 	tcp->tcp_state = TCPS_IDLE;
25906 	if (tcp->tcp_ipversion == IPV4_VERSION)
25907 		tcp->tcp_ipha->ipha_src = 0;
25908 	else
25909 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
25910 	/*
25911 	 * Copy of the src addr. in tcp_t is needed since
25912 	 * the lookup funcs. can only look at tcp_t
25913 	 */
25914 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
25915 
25916 	tcph = tcp->tcp_tcph;
25917 	tcph->th_lport[0] = 0;
25918 	tcph->th_lport[1] = 0;
25919 	tcp_bind_hash_remove(tcp);
25920 	bzero(&connp->u_port, sizeof (connp->u_port));
25921 	/* blow away saved option results if any */
25922 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
25923 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
25924 
25925 	conn_delete_ire(tcp->tcp_connp, NULL);
25926 
25927 	return (error);
25928 }
25929 
25930 static int
25931 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
25932     boolean_t bind_to_req_port_only, cred_t *cr)
25933 {
25934 	in_port_t	mlp_port;
25935 	mlp_type_t 	addrtype, mlptype;
25936 	boolean_t	user_specified;
25937 	in_port_t	allocated_port;
25938 	in_port_t	requested_port = *requested_port_ptr;
25939 	conn_t		*connp;
25940 	zone_t		*zone;
25941 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25942 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
25943 
25944 	/*
25945 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
25946 	 */
25947 	if (cr == NULL)
25948 		cr = tcp->tcp_cred;
25949 	/*
25950 	 * Get a valid port (within the anonymous range and should not
25951 	 * be a privileged one) to use if the user has not given a port.
25952 	 * If multiple threads are here, they may all start with
25953 	 * with the same initial port. But, it should be fine as long as
25954 	 * tcp_bindi will ensure that no two threads will be assigned
25955 	 * the same port.
25956 	 *
25957 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
25958 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
25959 	 * unless TCP_ANONPRIVBIND option is set.
25960 	 */
25961 	mlptype = mlptSingle;
25962 	mlp_port = requested_port;
25963 	if (requested_port == 0) {
25964 		requested_port = tcp->tcp_anon_priv_bind ?
25965 		    tcp_get_next_priv_port(tcp) :
25966 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
25967 		    tcp, B_TRUE);
25968 		if (requested_port == 0) {
25969 			return (-TNOADDR);
25970 		}
25971 		user_specified = B_FALSE;
25972 
25973 		/*
25974 		 * If the user went through one of the RPC interfaces to create
25975 		 * this socket and RPC is MLP in this zone, then give him an
25976 		 * anonymous MLP.
25977 		 */
25978 		connp = tcp->tcp_connp;
25979 		if (connp->conn_anon_mlp && is_system_labeled()) {
25980 			zone = crgetzone(cr);
25981 			addrtype = tsol_mlp_addr_type(
25982 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
25983 			    IPV6_VERSION, &v6addr,
25984 			    tcps->tcps_netstack->netstack_ip);
25985 			if (addrtype == mlptSingle) {
25986 				return (-TNOADDR);
25987 			}
25988 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25989 			    PMAPPORT, addrtype);
25990 			mlp_port = PMAPPORT;
25991 		}
25992 	} else {
25993 		int i;
25994 		boolean_t priv = B_FALSE;
25995 
25996 		/*
25997 		 * If the requested_port is in the well-known privileged range,
25998 		 * verify that the stream was opened by a privileged user.
25999 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
26000 		 * but instead the code relies on:
26001 		 * - the fact that the address of the array and its size never
26002 		 *   changes
26003 		 * - the atomic assignment of the elements of the array
26004 		 */
26005 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26006 			priv = B_TRUE;
26007 		} else {
26008 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26009 				if (requested_port ==
26010 				    tcps->tcps_g_epriv_ports[i]) {
26011 					priv = B_TRUE;
26012 					break;
26013 				}
26014 			}
26015 		}
26016 		if (priv) {
26017 			if (secpolicy_net_privaddr(cr, requested_port,
26018 			    IPPROTO_TCP) != 0) {
26019 				if (tcp->tcp_debug) {
26020 					(void) strlog(TCP_MOD_ID, 0, 1,
26021 					    SL_ERROR|SL_TRACE,
26022 					    "tcp_bind: no priv for port %d",
26023 					    requested_port);
26024 				}
26025 				return (-TACCES);
26026 			}
26027 		}
26028 		user_specified = B_TRUE;
26029 
26030 		connp = tcp->tcp_connp;
26031 		if (is_system_labeled()) {
26032 			zone = crgetzone(cr);
26033 			addrtype = tsol_mlp_addr_type(
26034 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
26035 			    IPV6_VERSION, &v6addr,
26036 			    tcps->tcps_netstack->netstack_ip);
26037 			if (addrtype == mlptSingle) {
26038 				return (-TNOADDR);
26039 			}
26040 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26041 			    requested_port, addrtype);
26042 		}
26043 	}
26044 
26045 	if (mlptype != mlptSingle) {
26046 		if (secpolicy_net_bindmlp(cr) != 0) {
26047 			if (tcp->tcp_debug) {
26048 				(void) strlog(TCP_MOD_ID, 0, 1,
26049 				    SL_ERROR|SL_TRACE,
26050 				    "tcp_bind: no priv for multilevel port %d",
26051 				    requested_port);
26052 			}
26053 			return (-TACCES);
26054 		}
26055 
26056 		/*
26057 		 * If we're specifically binding a shared IP address and the
26058 		 * port is MLP on shared addresses, then check to see if this
26059 		 * zone actually owns the MLP.  Reject if not.
26060 		 */
26061 		if (mlptype == mlptShared && addrtype == mlptShared) {
26062 			/*
26063 			 * No need to handle exclusive-stack zones since
26064 			 * ALL_ZONES only applies to the shared stack.
26065 			 */
26066 			zoneid_t mlpzone;
26067 
26068 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26069 			    htons(mlp_port));
26070 			if (connp->conn_zoneid != mlpzone) {
26071 				if (tcp->tcp_debug) {
26072 					(void) strlog(TCP_MOD_ID, 0, 1,
26073 					    SL_ERROR|SL_TRACE,
26074 					    "tcp_bind: attempt to bind port "
26075 					    "%d on shared addr in zone %d "
26076 					    "(should be %d)",
26077 					    mlp_port, connp->conn_zoneid,
26078 					    mlpzone);
26079 				}
26080 				return (-TACCES);
26081 			}
26082 		}
26083 
26084 		if (!user_specified) {
26085 			int err;
26086 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26087 			    requested_port, B_TRUE);
26088 			if (err != 0) {
26089 				if (tcp->tcp_debug) {
26090 					(void) strlog(TCP_MOD_ID, 0, 1,
26091 					    SL_ERROR|SL_TRACE,
26092 					    "tcp_bind: cannot establish anon "
26093 					    "MLP for port %d",
26094 					    requested_port);
26095 				}
26096 				return (err);
26097 			}
26098 			connp->conn_anon_port = B_TRUE;
26099 		}
26100 		connp->conn_mlp_type = mlptype;
26101 	}
26102 
26103 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26104 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26105 
26106 	if (allocated_port == 0) {
26107 		connp->conn_mlp_type = mlptSingle;
26108 		if (connp->conn_anon_port) {
26109 			connp->conn_anon_port = B_FALSE;
26110 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26111 			    requested_port, B_FALSE);
26112 		}
26113 		if (bind_to_req_port_only) {
26114 			if (tcp->tcp_debug) {
26115 				(void) strlog(TCP_MOD_ID, 0, 1,
26116 				    SL_ERROR|SL_TRACE,
26117 				    "tcp_bind: requested addr busy");
26118 			}
26119 			return (-TADDRBUSY);
26120 		} else {
26121 			/* If we are out of ports, fail the bind. */
26122 			if (tcp->tcp_debug) {
26123 				(void) strlog(TCP_MOD_ID, 0, 1,
26124 				    SL_ERROR|SL_TRACE,
26125 				    "tcp_bind: out of ports?");
26126 			}
26127 			return (-TNOADDR);
26128 		}
26129 	}
26130 
26131 	/* Pass the allocated port back */
26132 	*requested_port_ptr = allocated_port;
26133 	return (0);
26134 }
26135 
26136 static int
26137 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26138     boolean_t bind_to_req_port_only)
26139 {
26140 	tcp_t	*tcp = connp->conn_tcp;
26141 	sin_t	*sin;
26142 	sin6_t  *sin6;
26143 	in_port_t requested_port;
26144 	ipaddr_t	v4addr;
26145 	in6_addr_t	v6addr;
26146 	uint_t	ipversion;
26147 	int	error = 0;
26148 
26149 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26150 
26151 	if (tcp->tcp_state == TCPS_BOUND) {
26152 		return (0);
26153 	} else if (tcp->tcp_state > TCPS_BOUND) {
26154 		if (tcp->tcp_debug) {
26155 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26156 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26157 		}
26158 		return (-TOUTSTATE);
26159 	}
26160 
26161 	ASSERT(sa != NULL && len != 0);
26162 
26163 	if (!OK_32PTR((char *)sa)) {
26164 		if (tcp->tcp_debug) {
26165 			(void) strlog(TCP_MOD_ID, 0, 1,
26166 			    SL_ERROR|SL_TRACE,
26167 			    "tcp_bind: bad address parameter, "
26168 			    "address %p, len %d",
26169 			    (void *)sa, len);
26170 		}
26171 		return (-TPROTO);
26172 	}
26173 
26174 	switch (len) {
26175 	case sizeof (sin_t):	/* Complete IPv4 address */
26176 		sin = (sin_t *)sa;
26177 		/*
26178 		 * With sockets sockfs will accept bogus sin_family in
26179 		 * bind() and replace it with the family used in the socket
26180 		 * call.
26181 		 */
26182 		if (sin->sin_family != AF_INET ||
26183 		    tcp->tcp_family != AF_INET) {
26184 			return (EAFNOSUPPORT);
26185 		}
26186 		requested_port = ntohs(sin->sin_port);
26187 		ipversion = IPV4_VERSION;
26188 		v4addr = sin->sin_addr.s_addr;
26189 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26190 		break;
26191 
26192 	case sizeof (sin6_t): /* Complete IPv6 address */
26193 		sin6 = (sin6_t *)sa;
26194 		if (sin6->sin6_family != AF_INET6 ||
26195 		    tcp->tcp_family != AF_INET6) {
26196 			return (EAFNOSUPPORT);
26197 		}
26198 		requested_port = ntohs(sin6->sin6_port);
26199 		ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26200 		    IPV4_VERSION : IPV6_VERSION;
26201 		v6addr = sin6->sin6_addr;
26202 		break;
26203 
26204 	default:
26205 		if (tcp->tcp_debug) {
26206 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26207 			    "tcp_bind: bad address length, %d", len);
26208 		}
26209 		return (EAFNOSUPPORT);
26210 		/* return (-TBADADDR); */
26211 	}
26212 
26213 	tcp->tcp_bound_source_v6 = v6addr;
26214 
26215 	/* Check for change in ipversion */
26216 	if (tcp->tcp_ipversion != ipversion) {
26217 		ASSERT(tcp->tcp_family == AF_INET6);
26218 		error = (ipversion == IPV6_VERSION) ?
26219 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26220 		if (error) {
26221 			return (ENOMEM);
26222 		}
26223 	}
26224 
26225 	/*
26226 	 * Initialize family specific fields. Copy of the src addr.
26227 	 * in tcp_t is needed for the lookup funcs.
26228 	 */
26229 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26230 		tcp->tcp_ip6h->ip6_src = v6addr;
26231 	} else {
26232 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
26233 	}
26234 	tcp->tcp_ip_src_v6 = v6addr;
26235 
26236 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
26237 
26238 	error = tcp_bind_select_lport(tcp, &requested_port,
26239 	    bind_to_req_port_only, cr);
26240 
26241 	return (error);
26242 }
26243 
26244 /*
26245  * Return unix error is tli error is TSYSERR, otherwise return a negative
26246  * tli error.
26247  */
26248 int
26249 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26250     boolean_t bind_to_req_port_only)
26251 {
26252 	int error;
26253 	tcp_t *tcp = connp->conn_tcp;
26254 
26255 	if (tcp->tcp_state >= TCPS_BOUND) {
26256 		if (tcp->tcp_debug) {
26257 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26258 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26259 		}
26260 		return (-TOUTSTATE);
26261 	}
26262 
26263 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
26264 	if (error != 0)
26265 		return (error);
26266 
26267 	ASSERT(tcp->tcp_state == TCPS_BOUND);
26268 
26269 	tcp->tcp_conn_req_max = 0;
26270 
26271 	if (tcp->tcp_family == AF_INET6) {
26272 		ASSERT(tcp->tcp_connp->conn_af_isv6);
26273 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
26274 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
26275 	} else {
26276 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
26277 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
26278 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
26279 	}
26280 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
26281 }
26282 
26283 int
26284 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
26285     socklen_t len, cred_t *cr)
26286 {
26287 	int 		error;
26288 	conn_t		*connp = (conn_t *)proto_handle;
26289 	squeue_t	*sqp = connp->conn_sqp;
26290 
26291 	/* All Solaris components should pass a cred for this operation. */
26292 	ASSERT(cr != NULL);
26293 
26294 	ASSERT(sqp != NULL);
26295 	ASSERT(connp->conn_upper_handle != NULL);
26296 
26297 	error = squeue_synch_enter(sqp, connp, NULL);
26298 	if (error != 0) {
26299 		/* failed to enter */
26300 		return (ENOSR);
26301 	}
26302 
26303 	/* binding to a NULL address really means unbind */
26304 	if (sa == NULL) {
26305 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
26306 			error = tcp_do_unbind(connp);
26307 		else
26308 			error = EINVAL;
26309 	} else {
26310 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
26311 	}
26312 
26313 	squeue_synch_exit(sqp, connp);
26314 
26315 	if (error < 0) {
26316 		if (error == -TOUTSTATE)
26317 			error = EINVAL;
26318 		else
26319 			error = proto_tlitosyserr(-error);
26320 	}
26321 
26322 	return (error);
26323 }
26324 
26325 /*
26326  * If the return value from this function is positive, it's a UNIX error.
26327  * Otherwise, if it's negative, then the absolute value is a TLI error.
26328  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
26329  */
26330 int
26331 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
26332     cred_t *cr, pid_t pid)
26333 {
26334 	tcp_t		*tcp = connp->conn_tcp;
26335 	sin_t		*sin = (sin_t *)sa;
26336 	sin6_t		*sin6 = (sin6_t *)sa;
26337 	ipaddr_t	*dstaddrp;
26338 	in_port_t	dstport;
26339 	uint_t		srcid;
26340 	int		error = 0;
26341 
26342 	switch (len) {
26343 	default:
26344 		/*
26345 		 * Should never happen
26346 		 */
26347 		return (EINVAL);
26348 
26349 	case sizeof (sin_t):
26350 		sin = (sin_t *)sa;
26351 		if (sin->sin_port == 0) {
26352 			return (-TBADADDR);
26353 		}
26354 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
26355 			return (EAFNOSUPPORT);
26356 		}
26357 		break;
26358 
26359 	case sizeof (sin6_t):
26360 		sin6 = (sin6_t *)sa;
26361 		if (sin6->sin6_port == 0) {
26362 			return (-TBADADDR);
26363 		}
26364 		break;
26365 	}
26366 	/*
26367 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
26368 	 * make sure that the template IP header in the tcp structure is an
26369 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
26370 	 * need to this before we call tcp_bindi() so that the port lookup
26371 	 * code will look for ports in the correct port space (IPv4 and
26372 	 * IPv6 have separate port spaces).
26373 	 */
26374 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
26375 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26376 		int err = 0;
26377 
26378 		err = tcp_header_init_ipv4(tcp);
26379 			if (err != 0) {
26380 				error = ENOMEM;
26381 				goto connect_failed;
26382 			}
26383 		if (tcp->tcp_lport != 0)
26384 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
26385 	}
26386 
26387 	switch (tcp->tcp_state) {
26388 	case TCPS_LISTEN:
26389 		/*
26390 		 * Listening sockets are not allowed to issue connect().
26391 		 */
26392 		if (IPCL_IS_NONSTR(connp))
26393 			return (EOPNOTSUPP);
26394 		/* FALLTHRU */
26395 	case TCPS_IDLE:
26396 		/*
26397 		 * We support quick connect, refer to comments in
26398 		 * tcp_connect_*()
26399 		 */
26400 		/* FALLTHRU */
26401 	case TCPS_BOUND:
26402 		if (tcp->tcp_family == AF_INET6) {
26403 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26404 				return (tcp_connect_ipv6(tcp,
26405 				    &sin6->sin6_addr,
26406 				    sin6->sin6_port, sin6->sin6_flowinfo,
26407 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
26408 				    cr, pid));
26409 			}
26410 			/*
26411 			 * Destination adress is mapped IPv6 address.
26412 			 * Source bound address should be unspecified or
26413 			 * IPv6 mapped address as well.
26414 			 */
26415 			if (!IN6_IS_ADDR_UNSPECIFIED(
26416 			    &tcp->tcp_bound_source_v6) &&
26417 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
26418 				return (EADDRNOTAVAIL);
26419 			}
26420 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
26421 			dstport = sin6->sin6_port;
26422 			srcid = sin6->__sin6_src_id;
26423 		} else {
26424 			dstaddrp = &sin->sin_addr.s_addr;
26425 			dstport = sin->sin_port;
26426 			srcid = 0;
26427 		}
26428 
26429 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
26430 		    pid);
26431 		break;
26432 	default:
26433 		return (-TOUTSTATE);
26434 	}
26435 	/*
26436 	 * Note: Code below is the "failure" case
26437 	 */
26438 connect_failed:
26439 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26440 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26441 	return (error);
26442 }
26443 
26444 int
26445 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
26446     socklen_t len, sock_connid_t *id, cred_t *cr)
26447 {
26448 	conn_t		*connp = (conn_t *)proto_handle;
26449 	tcp_t		*tcp = connp->conn_tcp;
26450 	squeue_t	*sqp = connp->conn_sqp;
26451 	int		error;
26452 
26453 	ASSERT(connp->conn_upper_handle != NULL);
26454 
26455 	/* All Solaris components should pass a cred for this operation. */
26456 	ASSERT(cr != NULL);
26457 
26458 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
26459 	if (error != 0) {
26460 		return (error);
26461 	}
26462 
26463 	error = squeue_synch_enter(sqp, connp, NULL);
26464 	if (error != 0) {
26465 		/* failed to enter */
26466 		return (ENOSR);
26467 	}
26468 
26469 	/*
26470 	 * TCP supports quick connect, so no need to do an implicit bind
26471 	 */
26472 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
26473 	if (error == 0) {
26474 		*id = connp->conn_tcp->tcp_connid;
26475 	} else if (error < 0) {
26476 		if (error == -TOUTSTATE) {
26477 			switch (connp->conn_tcp->tcp_state) {
26478 			case TCPS_SYN_SENT:
26479 				error = EALREADY;
26480 				break;
26481 			case TCPS_ESTABLISHED:
26482 				error = EISCONN;
26483 				break;
26484 			case TCPS_LISTEN:
26485 				error = EOPNOTSUPP;
26486 				break;
26487 			default:
26488 				error = EINVAL;
26489 				break;
26490 			}
26491 		} else {
26492 			error = proto_tlitosyserr(-error);
26493 		}
26494 	}
26495 
26496 	if (tcp->tcp_loopback) {
26497 		struct sock_proto_props sopp;
26498 
26499 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
26500 		sopp.sopp_loopback = B_TRUE;
26501 
26502 		(*connp->conn_upcalls->su_set_proto_props)(
26503 		    connp->conn_upper_handle, &sopp);
26504 	}
26505 done:
26506 	squeue_synch_exit(sqp, connp);
26507 
26508 	return ((error == 0) ? EINPROGRESS : error);
26509 }
26510 
26511 /* ARGSUSED */
26512 sock_lower_handle_t
26513 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
26514     uint_t *smodep, int *errorp, int flags, cred_t *credp)
26515 {
26516 	conn_t		*connp;
26517 	boolean_t	isv6 = family == AF_INET6;
26518 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
26519 	    (proto != 0 && proto != IPPROTO_TCP)) {
26520 		*errorp = EPROTONOSUPPORT;
26521 		return (NULL);
26522 	}
26523 
26524 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
26525 	if (connp == NULL) {
26526 		return (NULL);
26527 	}
26528 
26529 	/*
26530 	 * Put the ref for TCP. Ref for IP was already put
26531 	 * by ipcl_conn_create. Also Make the conn_t globally
26532 	 * visible to walkers
26533 	 */
26534 	mutex_enter(&connp->conn_lock);
26535 	CONN_INC_REF_LOCKED(connp);
26536 	ASSERT(connp->conn_ref == 2);
26537 	connp->conn_state_flags &= ~CONN_INCIPIENT;
26538 
26539 	connp->conn_flags |= IPCL_NONSTR;
26540 	mutex_exit(&connp->conn_lock);
26541 
26542 	ASSERT(errorp != NULL);
26543 	*errorp = 0;
26544 	*sock_downcalls = &sock_tcp_downcalls;
26545 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
26546 	    SM_SENDFILESUPP;
26547 
26548 	return ((sock_lower_handle_t)connp);
26549 }
26550 
26551 /* ARGSUSED */
26552 void
26553 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
26554     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
26555 {
26556 	conn_t *connp = (conn_t *)proto_handle;
26557 	struct sock_proto_props sopp;
26558 
26559 	ASSERT(connp->conn_upper_handle == NULL);
26560 
26561 	/* All Solaris components should pass a cred for this operation. */
26562 	ASSERT(cr != NULL);
26563 
26564 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
26565 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
26566 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
26567 
26568 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
26569 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
26570 	sopp.sopp_maxpsz = INFPSZ;
26571 	sopp.sopp_maxblk = INFPSZ;
26572 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
26573 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
26574 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
26575 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
26576 	    tcp_rinfo.mi_minpsz;
26577 
26578 	connp->conn_upcalls = sock_upcalls;
26579 	connp->conn_upper_handle = sock_handle;
26580 
26581 	ASSERT(connp->conn_tcp->tcp_recv_hiwater != 0 &&
26582 	    connp->conn_tcp->tcp_recv_hiwater == connp->conn_tcp->tcp_rwnd);
26583 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
26584 }
26585 
26586 /* ARGSUSED */
26587 int
26588 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
26589 {
26590 	conn_t *connp = (conn_t *)proto_handle;
26591 
26592 	ASSERT(connp->conn_upper_handle != NULL);
26593 
26594 	/* All Solaris components should pass a cred for this operation. */
26595 	ASSERT(cr != NULL);
26596 
26597 	tcp_close_common(connp, flags);
26598 
26599 	ip_free_helper_stream(connp);
26600 
26601 	/*
26602 	 * Drop IP's reference on the conn. This is the last reference
26603 	 * on the connp if the state was less than established. If the
26604 	 * connection has gone into timewait state, then we will have
26605 	 * one ref for the TCP and one more ref (total of two) for the
26606 	 * classifier connected hash list (a timewait connections stays
26607 	 * in connected hash till closed).
26608 	 *
26609 	 * We can't assert the references because there might be other
26610 	 * transient reference places because of some walkers or queued
26611 	 * packets in squeue for the timewait state.
26612 	 */
26613 	CONN_DEC_REF(connp);
26614 	return (0);
26615 }
26616 
26617 /* ARGSUSED */
26618 int
26619 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
26620     cred_t *cr)
26621 {
26622 	tcp_t		*tcp;
26623 	uint32_t	msize;
26624 	conn_t *connp = (conn_t *)proto_handle;
26625 	int32_t		tcpstate;
26626 
26627 	/* All Solaris components should pass a cred for this operation. */
26628 	ASSERT(cr != NULL);
26629 
26630 	ASSERT(connp->conn_ref >= 2);
26631 	ASSERT(connp->conn_upper_handle != NULL);
26632 
26633 	if (msg->msg_controllen != 0) {
26634 		freemsg(mp);
26635 		return (EOPNOTSUPP);
26636 	}
26637 
26638 	switch (DB_TYPE(mp)) {
26639 	case M_DATA:
26640 		tcp = connp->conn_tcp;
26641 		ASSERT(tcp != NULL);
26642 
26643 		tcpstate = tcp->tcp_state;
26644 		if (tcpstate < TCPS_ESTABLISHED) {
26645 			freemsg(mp);
26646 			/*
26647 			 * We return ENOTCONN if the endpoint is trying to
26648 			 * connect or has never been connected, and EPIPE if it
26649 			 * has been disconnected. The connection id helps us
26650 			 * distinguish between the last two cases.
26651 			 */
26652 			return ((tcpstate == TCPS_SYN_SENT) ? ENOTCONN :
26653 			    ((tcp->tcp_connid > 0) ? EPIPE : ENOTCONN));
26654 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
26655 			freemsg(mp);
26656 			return (EPIPE);
26657 		}
26658 
26659 		msize = msgdsize(mp);
26660 
26661 		mutex_enter(&tcp->tcp_non_sq_lock);
26662 		tcp->tcp_squeue_bytes += msize;
26663 		/*
26664 		 * Squeue Flow Control
26665 		 */
26666 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
26667 			tcp_setqfull(tcp);
26668 		}
26669 		mutex_exit(&tcp->tcp_non_sq_lock);
26670 
26671 		/*
26672 		 * The application may pass in an address in the msghdr, but
26673 		 * we ignore the address on connection-oriented sockets.
26674 		 * Just like BSD this code does not generate an error for
26675 		 * TCP (a CONNREQUIRED socket) when sending to an address
26676 		 * passed in with sendto/sendmsg. Instead the data is
26677 		 * delivered on the connection as if no address had been
26678 		 * supplied.
26679 		 */
26680 		CONN_INC_REF(connp);
26681 
26682 		if (msg->msg_flags & MSG_OOB) {
26683 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
26684 			    tcp_output_urgent, connp, tcp_squeue_flag,
26685 			    SQTAG_TCP_OUTPUT);
26686 		} else {
26687 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
26688 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
26689 		}
26690 
26691 		return (0);
26692 
26693 	default:
26694 		ASSERT(0);
26695 	}
26696 
26697 	freemsg(mp);
26698 	return (0);
26699 }
26700 
26701 /* ARGSUSED */
26702 void
26703 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
26704 {
26705 	int len;
26706 	uint32_t msize;
26707 	conn_t *connp = (conn_t *)arg;
26708 	tcp_t *tcp = connp->conn_tcp;
26709 
26710 	msize = msgdsize(mp);
26711 
26712 	len = msize - 1;
26713 	if (len < 0) {
26714 		freemsg(mp);
26715 		return;
26716 	}
26717 
26718 	/*
26719 	 * Try to force urgent data out on the wire. Even if we have unsent
26720 	 * data this will at least send the urgent flag.
26721 	 * XXX does not handle more flag correctly.
26722 	 */
26723 	len += tcp->tcp_unsent;
26724 	len += tcp->tcp_snxt;
26725 	tcp->tcp_urg = len;
26726 	tcp->tcp_valid_bits |= TCP_URG_VALID;
26727 
26728 	/* Bypass tcp protocol for fused tcp loopback */
26729 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
26730 		return;
26731 
26732 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
26733 	if (DB_TYPE(mp) != M_DATA) {
26734 		mblk_t *mp1 = mp;
26735 		ASSERT(!IPCL_IS_NONSTR(connp));
26736 		mp = mp->b_cont;
26737 		freeb(mp1);
26738 	}
26739 	tcp_wput_data(tcp, mp, B_TRUE);
26740 }
26741 
26742 /* ARGSUSED */
26743 int
26744 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26745     socklen_t *addrlenp, cred_t *cr)
26746 {
26747 	conn_t	*connp = (conn_t *)proto_handle;
26748 	tcp_t	*tcp = connp->conn_tcp;
26749 
26750 	ASSERT(connp->conn_upper_handle != NULL);
26751 	/* All Solaris components should pass a cred for this operation. */
26752 	ASSERT(cr != NULL);
26753 
26754 	ASSERT(tcp != NULL);
26755 
26756 	return (tcp_do_getpeername(tcp, addr, addrlenp));
26757 }
26758 
26759 /* ARGSUSED */
26760 int
26761 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26762     socklen_t *addrlenp, cred_t *cr)
26763 {
26764 	conn_t	*connp = (conn_t *)proto_handle;
26765 	tcp_t	*tcp = connp->conn_tcp;
26766 
26767 	/* All Solaris components should pass a cred for this operation. */
26768 	ASSERT(cr != NULL);
26769 
26770 	ASSERT(connp->conn_upper_handle != NULL);
26771 
26772 	return (tcp_do_getsockname(tcp, addr, addrlenp));
26773 }
26774 
26775 /*
26776  * tcp_fallback
26777  *
26778  * A direct socket is falling back to using STREAMS. The queue
26779  * that is being passed down was created using tcp_open() with
26780  * the SO_FALLBACK flag set. As a result, the queue is not
26781  * associated with a conn, and the q_ptrs instead contain the
26782  * dev and minor area that should be used.
26783  *
26784  * The 'issocket' flag indicates whether the FireEngine
26785  * optimizations should be used. The common case would be that
26786  * optimizations are enabled, and they might be subsequently
26787  * disabled using the _SIOCSOCKFALLBACK ioctl.
26788  */
26789 
26790 /*
26791  * An active connection is falling back to TPI. Gather all the information
26792  * required by the STREAM head and TPI sonode and send it up.
26793  */
26794 void
26795 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
26796     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
26797 {
26798 	conn_t			*connp = tcp->tcp_connp;
26799 	struct stroptions	*stropt;
26800 	struct T_capability_ack tca;
26801 	struct sockaddr_in6	laddr, faddr;
26802 	socklen_t 		laddrlen, faddrlen;
26803 	short			opts;
26804 	int			error;
26805 	mblk_t			*mp;
26806 
26807 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
26808 	connp->conn_minor_arena = WR(q)->q_ptr;
26809 
26810 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
26811 
26812 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
26813 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
26814 
26815 	WR(q)->q_qinfo = &tcp_sock_winit;
26816 
26817 	if (!issocket)
26818 		tcp_use_pure_tpi(tcp);
26819 
26820 	/*
26821 	 * free the helper stream
26822 	 */
26823 	ip_free_helper_stream(connp);
26824 
26825 	/*
26826 	 * Notify the STREAM head about options
26827 	 */
26828 	DB_TYPE(stropt_mp) = M_SETOPTS;
26829 	stropt = (struct stroptions *)stropt_mp->b_rptr;
26830 	stropt_mp->b_wptr += sizeof (struct stroptions);
26831 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
26832 
26833 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
26834 	    tcp->tcp_tcps->tcps_wroff_xtra);
26835 	if (tcp->tcp_snd_sack_ok)
26836 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
26837 	stropt->so_hiwat = tcp->tcp_recv_hiwater;
26838 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
26839 
26840 	putnext(RD(q), stropt_mp);
26841 
26842 	/*
26843 	 * Collect the information needed to sync with the sonode
26844 	 */
26845 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
26846 
26847 	laddrlen = faddrlen = sizeof (sin6_t);
26848 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
26849 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
26850 	if (error != 0)
26851 		faddrlen = 0;
26852 
26853 	opts = 0;
26854 	if (tcp->tcp_oobinline)
26855 		opts |= SO_OOBINLINE;
26856 	if (tcp->tcp_dontroute)
26857 		opts |= SO_DONTROUTE;
26858 
26859 	/*
26860 	 * Notify the socket that the protocol is now quiescent,
26861 	 * and it's therefore safe move data from the socket
26862 	 * to the stream head.
26863 	 */
26864 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
26865 	    (struct sockaddr *)&laddr, laddrlen,
26866 	    (struct sockaddr *)&faddr, faddrlen, opts);
26867 
26868 	while ((mp = tcp->tcp_rcv_list) != NULL) {
26869 		tcp->tcp_rcv_list = mp->b_next;
26870 		mp->b_next = NULL;
26871 		putnext(q, mp);
26872 	}
26873 	tcp->tcp_rcv_last_head = NULL;
26874 	tcp->tcp_rcv_last_tail = NULL;
26875 	tcp->tcp_rcv_cnt = 0;
26876 }
26877 
26878 /*
26879  * An eager is falling back to TPI. All we have to do is send
26880  * up a T_CONN_IND.
26881  */
26882 void
26883 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
26884 {
26885 	tcp_t *listener = eager->tcp_listener;
26886 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
26887 
26888 	ASSERT(listener != NULL);
26889 	ASSERT(mp != NULL);
26890 
26891 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
26892 
26893 	/*
26894 	 * TLI/XTI applications will get confused by
26895 	 * sending eager as an option since it violates
26896 	 * the option semantics. So remove the eager as
26897 	 * option since TLI/XTI app doesn't need it anyway.
26898 	 */
26899 	if (!direct_sockfs) {
26900 		struct T_conn_ind *conn_ind;
26901 
26902 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
26903 		conn_ind->OPT_length = 0;
26904 		conn_ind->OPT_offset = 0;
26905 	}
26906 
26907 	/*
26908 	 * Sockfs guarantees that the listener will not be closed
26909 	 * during fallback. So we can safely use the listener's queue.
26910 	 */
26911 	putnext(listener->tcp_rq, mp);
26912 }
26913 
26914 int
26915 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
26916     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
26917 {
26918 	tcp_t			*tcp;
26919 	conn_t 			*connp = (conn_t *)proto_handle;
26920 	int			error;
26921 	mblk_t			*stropt_mp;
26922 	mblk_t			*ordrel_mp;
26923 
26924 	tcp = connp->conn_tcp;
26925 
26926 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
26927 	    NULL);
26928 
26929 	/* Pre-allocate the T_ordrel_ind mblk. */
26930 	ASSERT(tcp->tcp_ordrel_mp == NULL);
26931 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
26932 	    STR_NOSIG, NULL);
26933 	ordrel_mp->b_datap->db_type = M_PROTO;
26934 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
26935 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
26936 
26937 	/*
26938 	 * Enter the squeue so that no new packets can come in
26939 	 */
26940 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
26941 	if (error != 0) {
26942 		/* failed to enter, free all the pre-allocated messages. */
26943 		freeb(stropt_mp);
26944 		freeb(ordrel_mp);
26945 		/*
26946 		 * We cannot process the eager, so at least send out a
26947 		 * RST so the peer can reconnect.
26948 		 */
26949 		if (tcp->tcp_listener != NULL) {
26950 			(void) tcp_eager_blowoff(tcp->tcp_listener,
26951 			    tcp->tcp_conn_req_seqnum);
26952 		}
26953 		return (ENOMEM);
26954 	}
26955 
26956 	/*
26957 	 * Both endpoints must be of the same type (either STREAMS or
26958 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
26959 	 * we have to unfuse.
26960 	 */
26961 	if (tcp->tcp_fused)
26962 		tcp_unfuse(tcp);
26963 
26964 	/*
26965 	 * No longer a direct socket
26966 	 */
26967 	connp->conn_flags &= ~IPCL_NONSTR;
26968 	tcp->tcp_ordrel_mp = ordrel_mp;
26969 
26970 	if (tcp->tcp_listener != NULL) {
26971 		/* The eager will deal with opts when accept() is called */
26972 		freeb(stropt_mp);
26973 		tcp_fallback_eager(tcp, direct_sockfs);
26974 	} else {
26975 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
26976 		    quiesced_cb);
26977 	}
26978 
26979 	/*
26980 	 * There should be atleast two ref's (IP + TCP)
26981 	 */
26982 	ASSERT(connp->conn_ref >= 2);
26983 	squeue_synch_exit(connp->conn_sqp, connp);
26984 
26985 	return (0);
26986 }
26987 
26988 /* ARGSUSED */
26989 static void
26990 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
26991 {
26992 	conn_t 	*connp = (conn_t *)arg;
26993 	tcp_t	*tcp = connp->conn_tcp;
26994 
26995 	freemsg(mp);
26996 
26997 	if (tcp->tcp_fused)
26998 		tcp_unfuse(tcp);
26999 
27000 	if (tcp_xmit_end(tcp) != 0) {
27001 		/*
27002 		 * We were crossing FINs and got a reset from
27003 		 * the other side. Just ignore it.
27004 		 */
27005 		if (tcp->tcp_debug) {
27006 			(void) strlog(TCP_MOD_ID, 0, 1,
27007 			    SL_ERROR|SL_TRACE,
27008 			    "tcp_shutdown_output() out of state %s",
27009 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27010 		}
27011 	}
27012 }
27013 
27014 /* ARGSUSED */
27015 int
27016 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27017 {
27018 	conn_t  *connp = (conn_t *)proto_handle;
27019 	tcp_t   *tcp = connp->conn_tcp;
27020 
27021 	ASSERT(connp->conn_upper_handle != NULL);
27022 
27023 	/* All Solaris components should pass a cred for this operation. */
27024 	ASSERT(cr != NULL);
27025 
27026 	/*
27027 	 * X/Open requires that we check the connected state.
27028 	 */
27029 	if (tcp->tcp_state < TCPS_SYN_SENT)
27030 		return (ENOTCONN);
27031 
27032 	/* shutdown the send side */
27033 	if (how != SHUT_RD) {
27034 		mblk_t *bp;
27035 
27036 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27037 		CONN_INC_REF(connp);
27038 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27039 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27040 
27041 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27042 		    SOCK_OPCTL_SHUT_SEND, 0);
27043 	}
27044 
27045 	/* shutdown the recv side */
27046 	if (how != SHUT_WR)
27047 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27048 		    SOCK_OPCTL_SHUT_RECV, 0);
27049 
27050 	return (0);
27051 }
27052 
27053 /*
27054  * SOP_LISTEN() calls into tcp_listen().
27055  */
27056 /* ARGSUSED */
27057 int
27058 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27059 {
27060 	conn_t	*connp = (conn_t *)proto_handle;
27061 	int 	error;
27062 	squeue_t *sqp = connp->conn_sqp;
27063 
27064 	ASSERT(connp->conn_upper_handle != NULL);
27065 
27066 	/* All Solaris components should pass a cred for this operation. */
27067 	ASSERT(cr != NULL);
27068 
27069 	error = squeue_synch_enter(sqp, connp, NULL);
27070 	if (error != 0) {
27071 		/* failed to enter */
27072 		return (ENOBUFS);
27073 	}
27074 
27075 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
27076 	if (error == 0) {
27077 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27078 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27079 	} else if (error < 0) {
27080 		if (error == -TOUTSTATE)
27081 			error = EINVAL;
27082 		else
27083 			error = proto_tlitosyserr(-error);
27084 	}
27085 	squeue_synch_exit(sqp, connp);
27086 	return (error);
27087 }
27088 
27089 static int
27090 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
27091     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
27092 {
27093 	tcp_t		*tcp = connp->conn_tcp;
27094 	int		error = 0;
27095 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27096 
27097 	/* All Solaris components should pass a cred for this operation. */
27098 	ASSERT(cr != NULL);
27099 
27100 	if (tcp->tcp_state >= TCPS_BOUND) {
27101 		if ((tcp->tcp_state == TCPS_BOUND ||
27102 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27103 			/*
27104 			 * Handle listen() increasing backlog.
27105 			 * This is more "liberal" then what the TPI spec
27106 			 * requires but is needed to avoid a t_unbind
27107 			 * when handling listen() since the port number
27108 			 * might be "stolen" between the unbind and bind.
27109 			 */
27110 			goto do_listen;
27111 		}
27112 		if (tcp->tcp_debug) {
27113 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27114 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27115 		}
27116 		return (-TOUTSTATE);
27117 	} else {
27118 		if (sa == NULL) {
27119 			sin6_t	addr;
27120 			sin_t *sin;
27121 			sin6_t *sin6;
27122 
27123 			ASSERT(IPCL_IS_NONSTR(connp));
27124 
27125 			/* Do an implicit bind: Request for a generic port. */
27126 			if (tcp->tcp_family == AF_INET) {
27127 				len = sizeof (sin_t);
27128 				sin = (sin_t *)&addr;
27129 				*sin = sin_null;
27130 				sin->sin_family = AF_INET;
27131 			} else {
27132 				ASSERT(tcp->tcp_family == AF_INET6);
27133 				len = sizeof (sin6_t);
27134 				sin6 = (sin6_t *)&addr;
27135 				*sin6 = sin6_null;
27136 				sin6->sin6_family = AF_INET6;
27137 			}
27138 			sa = (struct sockaddr *)&addr;
27139 		}
27140 
27141 		error = tcp_bind_check(connp, sa, len, cr,
27142 		    bind_to_req_port_only);
27143 		if (error)
27144 			return (error);
27145 		/* Fall through and do the fanout insertion */
27146 	}
27147 
27148 do_listen:
27149 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27150 	tcp->tcp_conn_req_max = backlog;
27151 	if (tcp->tcp_conn_req_max) {
27152 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27153 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27154 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27155 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27156 		/*
27157 		 * If this is a listener, do not reset the eager list
27158 		 * and other stuffs.  Note that we don't check if the
27159 		 * existing eager list meets the new tcp_conn_req_max
27160 		 * requirement.
27161 		 */
27162 		if (tcp->tcp_state != TCPS_LISTEN) {
27163 			tcp->tcp_state = TCPS_LISTEN;
27164 			/* Initialize the chain. Don't need the eager_lock */
27165 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27166 			tcp->tcp_eager_next_drop_q0 = tcp;
27167 			tcp->tcp_eager_prev_drop_q0 = tcp;
27168 			tcp->tcp_second_ctimer_threshold =
27169 			    tcps->tcps_ip_abort_linterval;
27170 		}
27171 	}
27172 
27173 	/*
27174 	 * We can call ip_bind directly, the processing continues
27175 	 * in tcp_post_ip_bind().
27176 	 *
27177 	 * We need to make sure that the conn_recv is set to a non-null
27178 	 * value before we insert the conn into the classifier table.
27179 	 * This is to avoid a race with an incoming packet which does an
27180 	 * ipcl_classify().
27181 	 */
27182 	connp->conn_recv = tcp_conn_request;
27183 	if (tcp->tcp_family == AF_INET) {
27184 		error = ip_proto_bind_laddr_v4(connp, NULL,
27185 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27186 	} else {
27187 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27188 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27189 	}
27190 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27191 }
27192 
27193 void
27194 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27195 {
27196 	conn_t  *connp = (conn_t *)proto_handle;
27197 	tcp_t	*tcp = connp->conn_tcp;
27198 	mblk_t *mp;
27199 	int error;
27200 
27201 	ASSERT(connp->conn_upper_handle != NULL);
27202 
27203 	/*
27204 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
27205 	 * is currently running.
27206 	 */
27207 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27208 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
27209 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
27210 		return;
27211 	}
27212 	tcp->tcp_rsrv_mp = NULL;
27213 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27214 
27215 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
27216 	ASSERT(error == 0);
27217 
27218 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27219 	tcp->tcp_rsrv_mp = mp;
27220 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27221 
27222 	if (tcp->tcp_fused) {
27223 		tcp_fuse_backenable(tcp);
27224 	} else {
27225 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27226 		/*
27227 		 * Send back a window update immediately if TCP is above
27228 		 * ESTABLISHED state and the increase of the rcv window
27229 		 * that the other side knows is at least 1 MSS after flow
27230 		 * control is lifted.
27231 		 */
27232 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27233 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
27234 			tcp_xmit_ctl(NULL, tcp,
27235 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27236 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27237 		}
27238 	}
27239 
27240 	squeue_synch_exit(connp->conn_sqp, connp);
27241 }
27242 
27243 /* ARGSUSED */
27244 int
27245 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27246     int mode, int32_t *rvalp, cred_t *cr)
27247 {
27248 	conn_t  	*connp = (conn_t *)proto_handle;
27249 	int		error;
27250 
27251 	ASSERT(connp->conn_upper_handle != NULL);
27252 
27253 	/* All Solaris components should pass a cred for this operation. */
27254 	ASSERT(cr != NULL);
27255 
27256 	switch (cmd) {
27257 		case ND_SET:
27258 		case ND_GET:
27259 		case TCP_IOC_DEFAULT_Q:
27260 		case _SIOCSOCKFALLBACK:
27261 		case TCP_IOC_ABORT_CONN:
27262 		case TI_GETPEERNAME:
27263 		case TI_GETMYNAME:
27264 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27265 			    cmd));
27266 			error = EINVAL;
27267 			break;
27268 		default:
27269 			/*
27270 			 * Pass on to IP using helper stream
27271 			 */
27272 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
27273 			    cmd, arg, mode, cr, rvalp);
27274 			break;
27275 	}
27276 	return (error);
27277 }
27278 
27279 sock_downcalls_t sock_tcp_downcalls = {
27280 	tcp_activate,
27281 	tcp_accept,
27282 	tcp_bind,
27283 	tcp_listen,
27284 	tcp_connect,
27285 	tcp_getpeername,
27286 	tcp_getsockname,
27287 	tcp_getsockopt,
27288 	tcp_setsockopt,
27289 	tcp_sendmsg,
27290 	NULL,
27291 	NULL,
27292 	NULL,
27293 	tcp_shutdown,
27294 	tcp_clr_flowctrl,
27295 	tcp_ioctl,
27296 	tcp_close,
27297 };
27298