xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 5ad1f010a7b934be6e0dd6c13198af62791824be)
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_exempt = B_FALSE;
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 	zoneid_t zoneid = connp->conn_zoneid;
3123 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3124 
3125 	/*
3126 	 * Lookup for free addresses is done in a loop and "loopmax"
3127 	 * influences how long we spin in the loop
3128 	 */
3129 	if (bind_to_req_port_only) {
3130 		/*
3131 		 * If the requested port is busy, don't bother to look
3132 		 * for a new one. Setting loop maximum count to 1 has
3133 		 * that effect.
3134 		 */
3135 		loopmax = 1;
3136 	} else {
3137 		/*
3138 		 * If the requested port is busy, look for a free one
3139 		 * in the anonymous port range.
3140 		 * Set loopmax appropriately so that one does not look
3141 		 * forever in the case all of the anonymous ports are in use.
3142 		 */
3143 		if (tcp->tcp_anon_priv_bind) {
3144 			/*
3145 			 * loopmax =
3146 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3147 			 */
3148 			loopmax = IPPORT_RESERVED -
3149 			    tcps->tcps_min_anonpriv_port;
3150 		} else {
3151 			loopmax = (tcps->tcps_largest_anon_port -
3152 			    tcps->tcps_smallest_anon_port + 1);
3153 		}
3154 	}
3155 	do {
3156 		uint16_t	lport;
3157 		tf_t		*tbf;
3158 		tcp_t		*ltcp;
3159 		conn_t		*lconnp;
3160 
3161 		lport = htons(port);
3162 
3163 		/*
3164 		 * Ensure that the tcp_t is not currently in the bind hash.
3165 		 * Hold the lock on the hash bucket to ensure that
3166 		 * the duplicate check plus the insertion is an atomic
3167 		 * operation.
3168 		 *
3169 		 * This function does an inline lookup on the bind hash list
3170 		 * Make sure that we access only members of tcp_t
3171 		 * and that we don't look at tcp_tcp, since we are not
3172 		 * doing a CONN_INC_REF.
3173 		 */
3174 		tcp_bind_hash_remove(tcp);
3175 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3176 		mutex_enter(&tbf->tf_lock);
3177 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3178 		    ltcp = ltcp->tcp_bind_hash) {
3179 			if (lport == ltcp->tcp_lport)
3180 				break;
3181 		}
3182 
3183 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3184 			boolean_t not_socket;
3185 			boolean_t exclbind;
3186 
3187 			lconnp = ltcp->tcp_connp;
3188 
3189 			/*
3190 			 * On a labeled system, we must treat bindings to ports
3191 			 * on shared IP addresses by sockets with MAC exemption
3192 			 * privilege as being in all zones, as there's
3193 			 * otherwise no way to identify the right receiver.
3194 			 */
3195 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3196 			    IPCL_ZONE_MATCH(connp,
3197 			    ltcp->tcp_connp->conn_zoneid)) &&
3198 			    !lconnp->conn_mac_exempt &&
3199 			    !connp->conn_mac_exempt)
3200 				continue;
3201 
3202 			/*
3203 			 * If TCP_EXCLBIND is set for either the bound or
3204 			 * binding endpoint, the semantics of bind
3205 			 * is changed according to the following.
3206 			 *
3207 			 * spec = specified address (v4 or v6)
3208 			 * unspec = unspecified address (v4 or v6)
3209 			 * A = specified addresses are different for endpoints
3210 			 *
3211 			 * bound	bind to		allowed
3212 			 * -------------------------------------
3213 			 * unspec	unspec		no
3214 			 * unspec	spec		no
3215 			 * spec		unspec		no
3216 			 * spec		spec		yes if A
3217 			 *
3218 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3219 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3220 			 *
3221 			 * Note:
3222 			 *
3223 			 * 1. Because of TLI semantics, an endpoint can go
3224 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3225 			 * TCPS_BOUND, depending on whether it is originally
3226 			 * a listener or not.  That is why we need to check
3227 			 * for states greater than or equal to TCPS_BOUND
3228 			 * here.
3229 			 *
3230 			 * 2. Ideally, we should only check for state equals
3231 			 * to TCPS_LISTEN. And the following check should be
3232 			 * added.
3233 			 *
3234 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3235 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3236 			 *		...
3237 			 * }
3238 			 *
3239 			 * The semantics will be changed to this.  If the
3240 			 * endpoint on the list is in state not equal to
3241 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3242 			 * set, let the bind succeed.
3243 			 *
3244 			 * Because of (1), we cannot do that for TLI
3245 			 * endpoints.  But we can do that for socket endpoints.
3246 			 * If in future, we can change this going back
3247 			 * semantics, we can use the above check for TLI also.
3248 			 */
3249 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3250 			    TCP_IS_SOCKET(tcp));
3251 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3252 
3253 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3254 			    (exclbind && (not_socket ||
3255 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3256 				if (V6_OR_V4_INADDR_ANY(
3257 				    ltcp->tcp_bound_source_v6) ||
3258 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3259 				    IN6_ARE_ADDR_EQUAL(laddr,
3260 				    &ltcp->tcp_bound_source_v6)) {
3261 					break;
3262 				}
3263 				continue;
3264 			}
3265 
3266 			/*
3267 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3268 			 * have disjoint port number spaces, if *_EXCLBIND
3269 			 * is not set and only if the application binds to a
3270 			 * specific port. We use the same autoassigned port
3271 			 * number space for IPv4 and IPv6 sockets.
3272 			 */
3273 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3274 			    bind_to_req_port_only)
3275 				continue;
3276 
3277 			/*
3278 			 * Ideally, we should make sure that the source
3279 			 * address, remote address, and remote port in the
3280 			 * four tuple for this tcp-connection is unique.
3281 			 * However, trying to find out the local source
3282 			 * address would require too much code duplication
3283 			 * with IP, since IP needs needs to have that code
3284 			 * to support userland TCP implementations.
3285 			 */
3286 			if (quick_connect &&
3287 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3288 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3289 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3290 			    &ltcp->tcp_remote_v6)))
3291 				continue;
3292 
3293 			if (!reuseaddr) {
3294 				/*
3295 				 * No socket option SO_REUSEADDR.
3296 				 * If existing port is bound to
3297 				 * a non-wildcard IP address
3298 				 * and the requesting stream is
3299 				 * bound to a distinct
3300 				 * different IP addresses
3301 				 * (non-wildcard, also), keep
3302 				 * going.
3303 				 */
3304 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3305 				    !V6_OR_V4_INADDR_ANY(
3306 				    ltcp->tcp_bound_source_v6) &&
3307 				    !IN6_ARE_ADDR_EQUAL(laddr,
3308 				    &ltcp->tcp_bound_source_v6))
3309 					continue;
3310 				if (ltcp->tcp_state >= TCPS_BOUND) {
3311 					/*
3312 					 * This port is being used and
3313 					 * its state is >= TCPS_BOUND,
3314 					 * so we can't bind to it.
3315 					 */
3316 					break;
3317 				}
3318 			} else {
3319 				/*
3320 				 * socket option SO_REUSEADDR is set on the
3321 				 * binding tcp_t.
3322 				 *
3323 				 * If two streams are bound to
3324 				 * same IP address or both addr
3325 				 * and bound source are wildcards
3326 				 * (INADDR_ANY), we want to stop
3327 				 * searching.
3328 				 * We have found a match of IP source
3329 				 * address and source port, which is
3330 				 * refused regardless of the
3331 				 * SO_REUSEADDR setting, so we break.
3332 				 */
3333 				if (IN6_ARE_ADDR_EQUAL(laddr,
3334 				    &ltcp->tcp_bound_source_v6) &&
3335 				    (ltcp->tcp_state == TCPS_LISTEN ||
3336 				    ltcp->tcp_state == TCPS_BOUND))
3337 					break;
3338 			}
3339 		}
3340 		if (ltcp != NULL) {
3341 			/* The port number is busy */
3342 			mutex_exit(&tbf->tf_lock);
3343 		} else {
3344 			/*
3345 			 * This port is ours. Insert in fanout and mark as
3346 			 * bound to prevent others from getting the port
3347 			 * number.
3348 			 */
3349 			tcp->tcp_state = TCPS_BOUND;
3350 			tcp->tcp_lport = htons(port);
3351 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3352 
3353 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3354 			    tcp->tcp_lport)] == tbf);
3355 			tcp_bind_hash_insert(tbf, tcp, 1);
3356 
3357 			mutex_exit(&tbf->tf_lock);
3358 
3359 			/*
3360 			 * We don't want tcp_next_port_to_try to "inherit"
3361 			 * a port number supplied by the user in a bind.
3362 			 */
3363 			if (user_specified)
3364 				return (port);
3365 
3366 			/*
3367 			 * This is the only place where tcp_next_port_to_try
3368 			 * is updated. After the update, it may or may not
3369 			 * be in the valid range.
3370 			 */
3371 			if (!tcp->tcp_anon_priv_bind)
3372 				tcps->tcps_next_port_to_try = port + 1;
3373 			return (port);
3374 		}
3375 
3376 		if (tcp->tcp_anon_priv_bind) {
3377 			port = tcp_get_next_priv_port(tcp);
3378 		} else {
3379 			if (count == 0 && user_specified) {
3380 				/*
3381 				 * We may have to return an anonymous port. So
3382 				 * get one to start with.
3383 				 */
3384 				port =
3385 				    tcp_update_next_port(
3386 				    tcps->tcps_next_port_to_try,
3387 				    tcp, B_TRUE);
3388 				user_specified = B_FALSE;
3389 			} else {
3390 				port = tcp_update_next_port(port + 1, tcp,
3391 				    B_FALSE);
3392 			}
3393 		}
3394 		if (port == 0)
3395 			break;
3396 
3397 		/*
3398 		 * Don't let this loop run forever in the case where
3399 		 * all of the anonymous ports are in use.
3400 		 */
3401 	} while (++count < loopmax);
3402 	return (0);
3403 }
3404 
3405 /*
3406  * tcp_clean_death / tcp_close_detached must not be called more than once
3407  * on a tcp. Thus every function that potentially calls tcp_clean_death
3408  * must check for the tcp state before calling tcp_clean_death.
3409  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3410  * tcp_timer_handler, all check for the tcp state.
3411  */
3412 /* ARGSUSED */
3413 void
3414 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3415 {
3416 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3417 
3418 	freemsg(mp);
3419 	if (tcp->tcp_state > TCPS_BOUND)
3420 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3421 		    ETIMEDOUT, 5);
3422 }
3423 
3424 /*
3425  * We are dying for some reason.  Try to do it gracefully.  (May be called
3426  * as writer.)
3427  *
3428  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3429  * done by a service procedure).
3430  * TBD - Should the return value distinguish between the tcp_t being
3431  * freed and it being reinitialized?
3432  */
3433 static int
3434 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3435 {
3436 	mblk_t	*mp;
3437 	queue_t	*q;
3438 	conn_t	*connp = tcp->tcp_connp;
3439 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3440 
3441 	TCP_CLD_STAT(tag);
3442 
3443 #if TCP_TAG_CLEAN_DEATH
3444 	tcp->tcp_cleandeathtag = tag;
3445 #endif
3446 
3447 	if (tcp->tcp_fused)
3448 		tcp_unfuse(tcp);
3449 
3450 	if (tcp->tcp_linger_tid != 0 &&
3451 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3452 		tcp_stop_lingering(tcp);
3453 	}
3454 
3455 	ASSERT(tcp != NULL);
3456 	ASSERT((tcp->tcp_family == AF_INET &&
3457 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3458 	    (tcp->tcp_family == AF_INET6 &&
3459 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3460 	    tcp->tcp_ipversion == IPV6_VERSION)));
3461 
3462 	if (TCP_IS_DETACHED(tcp)) {
3463 		if (tcp->tcp_hard_binding) {
3464 			/*
3465 			 * Its an eager that we are dealing with. We close the
3466 			 * eager but in case a conn_ind has already gone to the
3467 			 * listener, let tcp_accept_finish() send a discon_ind
3468 			 * to the listener and drop the last reference. If the
3469 			 * listener doesn't even know about the eager i.e. the
3470 			 * conn_ind hasn't gone up, blow away the eager and drop
3471 			 * the last reference as well. If the conn_ind has gone
3472 			 * up, state should be BOUND. tcp_accept_finish
3473 			 * will figure out that the connection has received a
3474 			 * RST and will send a DISCON_IND to the application.
3475 			 */
3476 			tcp_closei_local(tcp);
3477 			if (!tcp->tcp_tconnind_started) {
3478 				CONN_DEC_REF(connp);
3479 			} else {
3480 				tcp->tcp_state = TCPS_BOUND;
3481 			}
3482 		} else {
3483 			tcp_close_detached(tcp);
3484 		}
3485 		return (0);
3486 	}
3487 
3488 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3489 
3490 	q = tcp->tcp_rq;
3491 
3492 	/* Trash all inbound data */
3493 	if (!IPCL_IS_NONSTR(connp)) {
3494 		ASSERT(q != NULL);
3495 		flushq(q, FLUSHALL);
3496 	}
3497 
3498 	/*
3499 	 * If we are at least part way open and there is error
3500 	 * (err==0 implies no error)
3501 	 * notify our client by a T_DISCON_IND.
3502 	 */
3503 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3504 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3505 		    !TCP_IS_SOCKET(tcp)) {
3506 			/*
3507 			 * Send M_FLUSH according to TPI. Because sockets will
3508 			 * (and must) ignore FLUSHR we do that only for TPI
3509 			 * endpoints and sockets in STREAMS mode.
3510 			 */
3511 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3512 		}
3513 		if (tcp->tcp_debug) {
3514 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3515 			    "tcp_clean_death: discon err %d", err);
3516 		}
3517 		if (IPCL_IS_NONSTR(connp)) {
3518 			/* Direct socket, use upcall */
3519 			(*connp->conn_upcalls->su_disconnected)(
3520 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3521 		} else {
3522 			mp = mi_tpi_discon_ind(NULL, err, 0);
3523 			if (mp != NULL) {
3524 				putnext(q, mp);
3525 			} else {
3526 				if (tcp->tcp_debug) {
3527 					(void) strlog(TCP_MOD_ID, 0, 1,
3528 					    SL_ERROR|SL_TRACE,
3529 					    "tcp_clean_death, sending M_ERROR");
3530 				}
3531 				(void) putnextctl1(q, M_ERROR, EPROTO);
3532 			}
3533 		}
3534 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3535 			/* SYN_SENT or SYN_RCVD */
3536 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3537 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3538 			/* ESTABLISHED or CLOSE_WAIT */
3539 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3540 		}
3541 	}
3542 
3543 	tcp_reinit(tcp);
3544 	if (IPCL_IS_NONSTR(connp))
3545 		(void) tcp_do_unbind(connp);
3546 
3547 	return (-1);
3548 }
3549 
3550 /*
3551  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3552  * to expire, stop the wait and finish the close.
3553  */
3554 static void
3555 tcp_stop_lingering(tcp_t *tcp)
3556 {
3557 	clock_t	delta = 0;
3558 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3559 
3560 	tcp->tcp_linger_tid = 0;
3561 	if (tcp->tcp_state > TCPS_LISTEN) {
3562 		tcp_acceptor_hash_remove(tcp);
3563 		mutex_enter(&tcp->tcp_non_sq_lock);
3564 		if (tcp->tcp_flow_stopped) {
3565 			tcp_clrqfull(tcp);
3566 		}
3567 		mutex_exit(&tcp->tcp_non_sq_lock);
3568 
3569 		if (tcp->tcp_timer_tid != 0) {
3570 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3571 			tcp->tcp_timer_tid = 0;
3572 		}
3573 		/*
3574 		 * Need to cancel those timers which will not be used when
3575 		 * TCP is detached.  This has to be done before the tcp_wq
3576 		 * is set to the global queue.
3577 		 */
3578 		tcp_timers_stop(tcp);
3579 
3580 		tcp->tcp_detached = B_TRUE;
3581 		ASSERT(tcps->tcps_g_q != NULL);
3582 		tcp->tcp_rq = tcps->tcps_g_q;
3583 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3584 
3585 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3586 			tcp_time_wait_append(tcp);
3587 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3588 			goto finish;
3589 		}
3590 
3591 		/*
3592 		 * If delta is zero the timer event wasn't executed and was
3593 		 * successfully canceled. In this case we need to restart it
3594 		 * with the minimal delta possible.
3595 		 */
3596 		if (delta >= 0) {
3597 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3598 			    delta ? delta : 1);
3599 		}
3600 	} else {
3601 		tcp_closei_local(tcp);
3602 		CONN_DEC_REF(tcp->tcp_connp);
3603 	}
3604 finish:
3605 	/* Signal closing thread that it can complete close */
3606 	mutex_enter(&tcp->tcp_closelock);
3607 	tcp->tcp_detached = B_TRUE;
3608 	ASSERT(tcps->tcps_g_q != NULL);
3609 
3610 	tcp->tcp_rq = tcps->tcps_g_q;
3611 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3612 
3613 	tcp->tcp_closed = 1;
3614 	cv_signal(&tcp->tcp_closecv);
3615 	mutex_exit(&tcp->tcp_closelock);
3616 }
3617 
3618 /*
3619  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3620  * expires.
3621  */
3622 static void
3623 tcp_close_linger_timeout(void *arg)
3624 {
3625 	conn_t	*connp = (conn_t *)arg;
3626 	tcp_t 	*tcp = connp->conn_tcp;
3627 
3628 	tcp->tcp_client_errno = ETIMEDOUT;
3629 	tcp_stop_lingering(tcp);
3630 }
3631 
3632 static void
3633 tcp_close_common(conn_t *connp, int flags)
3634 {
3635 	tcp_t		*tcp = connp->conn_tcp;
3636 	mblk_t 		*mp = &tcp->tcp_closemp;
3637 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3638 	mblk_t		*bp;
3639 
3640 	ASSERT(connp->conn_ref >= 2);
3641 
3642 	/*
3643 	 * Mark the conn as closing. ill_pending_mp_add will not
3644 	 * add any mp to the pending mp list, after this conn has
3645 	 * started closing. Same for sq_pending_mp_add
3646 	 */
3647 	mutex_enter(&connp->conn_lock);
3648 	connp->conn_state_flags |= CONN_CLOSING;
3649 	if (connp->conn_oper_pending_ill != NULL)
3650 		conn_ioctl_cleanup_reqd = B_TRUE;
3651 	CONN_INC_REF_LOCKED(connp);
3652 	mutex_exit(&connp->conn_lock);
3653 	tcp->tcp_closeflags = (uint8_t)flags;
3654 	ASSERT(connp->conn_ref >= 3);
3655 
3656 	/*
3657 	 * tcp_closemp_used is used below without any protection of a lock
3658 	 * as we don't expect any one else to use it concurrently at this
3659 	 * point otherwise it would be a major defect.
3660 	 */
3661 
3662 	if (mp->b_prev == NULL)
3663 		tcp->tcp_closemp_used = B_TRUE;
3664 	else
3665 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3666 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3667 
3668 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3669 
3670 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3671 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3672 
3673 	mutex_enter(&tcp->tcp_closelock);
3674 	while (!tcp->tcp_closed) {
3675 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3676 			/*
3677 			 * The cv_wait_sig() was interrupted. We now do the
3678 			 * following:
3679 			 *
3680 			 * 1) If the endpoint was lingering, we allow this
3681 			 * to be interrupted by cancelling the linger timeout
3682 			 * and closing normally.
3683 			 *
3684 			 * 2) Revert to calling cv_wait()
3685 			 *
3686 			 * We revert to using cv_wait() to avoid an
3687 			 * infinite loop which can occur if the calling
3688 			 * thread is higher priority than the squeue worker
3689 			 * thread and is bound to the same cpu.
3690 			 */
3691 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3692 				mutex_exit(&tcp->tcp_closelock);
3693 				/* Entering squeue, bump ref count. */
3694 				CONN_INC_REF(connp);
3695 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3696 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3697 				    tcp_linger_interrupted, connp,
3698 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3699 				mutex_enter(&tcp->tcp_closelock);
3700 			}
3701 			break;
3702 		}
3703 	}
3704 	while (!tcp->tcp_closed)
3705 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3706 	mutex_exit(&tcp->tcp_closelock);
3707 
3708 	/*
3709 	 * In the case of listener streams that have eagers in the q or q0
3710 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3711 	 * tcp_wq of the eagers point to our queues. By waiting for the
3712 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3713 	 * up their queue pointers and also dropped their references to us.
3714 	 */
3715 	if (tcp->tcp_wait_for_eagers) {
3716 		mutex_enter(&connp->conn_lock);
3717 		while (connp->conn_ref != 1) {
3718 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3719 		}
3720 		mutex_exit(&connp->conn_lock);
3721 	}
3722 	/*
3723 	 * ioctl cleanup. The mp is queued in the
3724 	 * ill_pending_mp or in the sq_pending_mp.
3725 	 */
3726 	if (conn_ioctl_cleanup_reqd)
3727 		conn_ioctl_cleanup(connp);
3728 
3729 	tcp->tcp_cpid = -1;
3730 }
3731 
3732 static int
3733 tcp_tpi_close(queue_t *q, int flags)
3734 {
3735 	conn_t		*connp;
3736 
3737 	ASSERT(WR(q)->q_next == NULL);
3738 
3739 	if (flags & SO_FALLBACK) {
3740 		/*
3741 		 * stream is being closed while in fallback
3742 		 * simply free the resources that were allocated
3743 		 */
3744 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3745 		qprocsoff(q);
3746 		goto done;
3747 	}
3748 
3749 	connp = Q_TO_CONN(q);
3750 	/*
3751 	 * We are being closed as /dev/tcp or /dev/tcp6.
3752 	 */
3753 	tcp_close_common(connp, flags);
3754 
3755 	qprocsoff(q);
3756 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3757 
3758 	/*
3759 	 * Drop IP's reference on the conn. This is the last reference
3760 	 * on the connp if the state was less than established. If the
3761 	 * connection has gone into timewait state, then we will have
3762 	 * one ref for the TCP and one more ref (total of two) for the
3763 	 * classifier connected hash list (a timewait connections stays
3764 	 * in connected hash till closed).
3765 	 *
3766 	 * We can't assert the references because there might be other
3767 	 * transient reference places because of some walkers or queued
3768 	 * packets in squeue for the timewait state.
3769 	 */
3770 	CONN_DEC_REF(connp);
3771 done:
3772 	q->q_ptr = WR(q)->q_ptr = NULL;
3773 	return (0);
3774 }
3775 
3776 static int
3777 tcp_tpi_close_accept(queue_t *q)
3778 {
3779 	vmem_t	*minor_arena;
3780 	dev_t	conn_dev;
3781 
3782 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3783 
3784 	/*
3785 	 * We had opened an acceptor STREAM for sockfs which is
3786 	 * now being closed due to some error.
3787 	 */
3788 	qprocsoff(q);
3789 
3790 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3791 	conn_dev = (dev_t)RD(q)->q_ptr;
3792 	ASSERT(minor_arena != NULL);
3793 	ASSERT(conn_dev != 0);
3794 	inet_minor_free(minor_arena, conn_dev);
3795 	q->q_ptr = WR(q)->q_ptr = NULL;
3796 	return (0);
3797 }
3798 
3799 /*
3800  * Called by tcp_close() routine via squeue when lingering is
3801  * interrupted by a signal.
3802  */
3803 
3804 /* ARGSUSED */
3805 static void
3806 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3807 {
3808 	conn_t	*connp = (conn_t *)arg;
3809 	tcp_t	*tcp = connp->conn_tcp;
3810 
3811 	freeb(mp);
3812 	if (tcp->tcp_linger_tid != 0 &&
3813 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3814 		tcp_stop_lingering(tcp);
3815 		tcp->tcp_client_errno = EINTR;
3816 	}
3817 }
3818 
3819 /*
3820  * Called by streams close routine via squeues when our client blows off her
3821  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3822  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3823  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3824  * acked.
3825  *
3826  * NOTE: tcp_close potentially returns error when lingering.
3827  * However, the stream head currently does not pass these errors
3828  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3829  * errors to the application (from tsleep()) and not errors
3830  * like ECONNRESET caused by receiving a reset packet.
3831  */
3832 
3833 /* ARGSUSED */
3834 static void
3835 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3836 {
3837 	char	*msg;
3838 	conn_t	*connp = (conn_t *)arg;
3839 	tcp_t	*tcp = connp->conn_tcp;
3840 	clock_t	delta = 0;
3841 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3842 
3843 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3844 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3845 
3846 	mutex_enter(&tcp->tcp_eager_lock);
3847 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3848 		/* Cleanup for listener */
3849 		tcp_eager_cleanup(tcp, 0);
3850 		tcp->tcp_wait_for_eagers = 1;
3851 	}
3852 	mutex_exit(&tcp->tcp_eager_lock);
3853 
3854 	connp->conn_mdt_ok = B_FALSE;
3855 	tcp->tcp_mdt = B_FALSE;
3856 
3857 	connp->conn_lso_ok = B_FALSE;
3858 	tcp->tcp_lso = B_FALSE;
3859 
3860 	msg = NULL;
3861 	switch (tcp->tcp_state) {
3862 	case TCPS_CLOSED:
3863 	case TCPS_IDLE:
3864 	case TCPS_BOUND:
3865 	case TCPS_LISTEN:
3866 		break;
3867 	case TCPS_SYN_SENT:
3868 		msg = "tcp_close, during connect";
3869 		break;
3870 	case TCPS_SYN_RCVD:
3871 		/*
3872 		 * Close during the connect 3-way handshake
3873 		 * but here there may or may not be pending data
3874 		 * already on queue. Process almost same as in
3875 		 * the ESTABLISHED state.
3876 		 */
3877 		/* FALLTHRU */
3878 	default:
3879 		if (tcp->tcp_fused)
3880 			tcp_unfuse(tcp);
3881 
3882 		/*
3883 		 * If SO_LINGER has set a zero linger time, abort the
3884 		 * connection with a reset.
3885 		 */
3886 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3887 			msg = "tcp_close, zero lingertime";
3888 			break;
3889 		}
3890 
3891 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3892 		/*
3893 		 * Abort connection if there is unread data queued.
3894 		 */
3895 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3896 			msg = "tcp_close, unread data";
3897 			break;
3898 		}
3899 		/*
3900 		 * tcp_hard_bound is now cleared thus all packets go through
3901 		 * tcp_lookup. This fact is used by tcp_detach below.
3902 		 *
3903 		 * We have done a qwait() above which could have possibly
3904 		 * drained more messages in turn causing transition to a
3905 		 * different state. Check whether we have to do the rest
3906 		 * of the processing or not.
3907 		 */
3908 		if (tcp->tcp_state <= TCPS_LISTEN)
3909 			break;
3910 
3911 		/*
3912 		 * Transmit the FIN before detaching the tcp_t.
3913 		 * After tcp_detach returns this queue/perimeter
3914 		 * no longer owns the tcp_t thus others can modify it.
3915 		 */
3916 		(void) tcp_xmit_end(tcp);
3917 
3918 		/*
3919 		 * If lingering on close then wait until the fin is acked,
3920 		 * the SO_LINGER time passes, or a reset is sent/received.
3921 		 */
3922 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3923 		    !(tcp->tcp_fin_acked) &&
3924 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3925 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3926 				tcp->tcp_client_errno = EWOULDBLOCK;
3927 			} else if (tcp->tcp_client_errno == 0) {
3928 
3929 				ASSERT(tcp->tcp_linger_tid == 0);
3930 
3931 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3932 				    tcp_close_linger_timeout,
3933 				    tcp->tcp_lingertime * hz);
3934 
3935 				/* tcp_close_linger_timeout will finish close */
3936 				if (tcp->tcp_linger_tid == 0)
3937 					tcp->tcp_client_errno = ENOSR;
3938 				else
3939 					return;
3940 			}
3941 
3942 			/*
3943 			 * Check if we need to detach or just close
3944 			 * the instance.
3945 			 */
3946 			if (tcp->tcp_state <= TCPS_LISTEN)
3947 				break;
3948 		}
3949 
3950 		/*
3951 		 * Make sure that no other thread will access the tcp_rq of
3952 		 * this instance (through lookups etc.) as tcp_rq will go
3953 		 * away shortly.
3954 		 */
3955 		tcp_acceptor_hash_remove(tcp);
3956 
3957 		mutex_enter(&tcp->tcp_non_sq_lock);
3958 		if (tcp->tcp_flow_stopped) {
3959 			tcp_clrqfull(tcp);
3960 		}
3961 		mutex_exit(&tcp->tcp_non_sq_lock);
3962 
3963 		if (tcp->tcp_timer_tid != 0) {
3964 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3965 			tcp->tcp_timer_tid = 0;
3966 		}
3967 		/*
3968 		 * Need to cancel those timers which will not be used when
3969 		 * TCP is detached.  This has to be done before the tcp_wq
3970 		 * is set to the global queue.
3971 		 */
3972 		tcp_timers_stop(tcp);
3973 
3974 		tcp->tcp_detached = B_TRUE;
3975 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3976 			tcp_time_wait_append(tcp);
3977 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3978 			ASSERT(connp->conn_ref >= 3);
3979 			goto finish;
3980 		}
3981 
3982 		/*
3983 		 * If delta is zero the timer event wasn't executed and was
3984 		 * successfully canceled. In this case we need to restart it
3985 		 * with the minimal delta possible.
3986 		 */
3987 		if (delta >= 0)
3988 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3989 			    delta ? delta : 1);
3990 
3991 		ASSERT(connp->conn_ref >= 3);
3992 		goto finish;
3993 	}
3994 
3995 	/* Detach did not complete. Still need to remove q from stream. */
3996 	if (msg) {
3997 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3998 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3999 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4000 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4001 		    tcp->tcp_state == TCPS_SYN_RCVD)
4002 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4003 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4004 	}
4005 
4006 	tcp_closei_local(tcp);
4007 	CONN_DEC_REF(connp);
4008 	ASSERT(connp->conn_ref >= 2);
4009 
4010 finish:
4011 	/*
4012 	 * Although packets are always processed on the correct
4013 	 * tcp's perimeter and access is serialized via squeue's,
4014 	 * IP still needs a queue when sending packets in time_wait
4015 	 * state so use WR(tcps_g_q) till ip_output() can be
4016 	 * changed to deal with just connp. For read side, we
4017 	 * could have set tcp_rq to NULL but there are some cases
4018 	 * in tcp_rput_data() from early days of this code which
4019 	 * do a putnext without checking if tcp is closed. Those
4020 	 * need to be identified before both tcp_rq and tcp_wq
4021 	 * can be set to NULL and tcps_g_q can disappear forever.
4022 	 */
4023 	mutex_enter(&tcp->tcp_closelock);
4024 	/*
4025 	 * Don't change the queues in the case of a listener that has
4026 	 * eagers in its q or q0. It could surprise the eagers.
4027 	 * Instead wait for the eagers outside the squeue.
4028 	 */
4029 	if (!tcp->tcp_wait_for_eagers) {
4030 		tcp->tcp_detached = B_TRUE;
4031 		/*
4032 		 * When default queue is closing we set tcps_g_q to NULL
4033 		 * after the close is done.
4034 		 */
4035 		ASSERT(tcps->tcps_g_q != NULL);
4036 		tcp->tcp_rq = tcps->tcps_g_q;
4037 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4038 	}
4039 
4040 	/* Signal tcp_close() to finish closing. */
4041 	tcp->tcp_closed = 1;
4042 	cv_signal(&tcp->tcp_closecv);
4043 	mutex_exit(&tcp->tcp_closelock);
4044 }
4045 
4046 /*
4047  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4048  * Some stream heads get upset if they see these later on as anything but NULL.
4049  */
4050 static void
4051 tcp_close_mpp(mblk_t **mpp)
4052 {
4053 	mblk_t	*mp;
4054 
4055 	if ((mp = *mpp) != NULL) {
4056 		do {
4057 			mp->b_next = NULL;
4058 			mp->b_prev = NULL;
4059 		} while ((mp = mp->b_cont) != NULL);
4060 
4061 		mp = *mpp;
4062 		*mpp = NULL;
4063 		freemsg(mp);
4064 	}
4065 }
4066 
4067 /* Do detached close. */
4068 static void
4069 tcp_close_detached(tcp_t *tcp)
4070 {
4071 	if (tcp->tcp_fused)
4072 		tcp_unfuse(tcp);
4073 
4074 	/*
4075 	 * Clustering code serializes TCP disconnect callbacks and
4076 	 * cluster tcp list walks by blocking a TCP disconnect callback
4077 	 * if a cluster tcp list walk is in progress. This ensures
4078 	 * accurate accounting of TCPs in the cluster code even though
4079 	 * the TCP list walk itself is not atomic.
4080 	 */
4081 	tcp_closei_local(tcp);
4082 	CONN_DEC_REF(tcp->tcp_connp);
4083 }
4084 
4085 /*
4086  * Stop all TCP timers, and free the timer mblks if requested.
4087  */
4088 void
4089 tcp_timers_stop(tcp_t *tcp)
4090 {
4091 	if (tcp->tcp_timer_tid != 0) {
4092 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4093 		tcp->tcp_timer_tid = 0;
4094 	}
4095 	if (tcp->tcp_ka_tid != 0) {
4096 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4097 		tcp->tcp_ka_tid = 0;
4098 	}
4099 	if (tcp->tcp_ack_tid != 0) {
4100 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4101 		tcp->tcp_ack_tid = 0;
4102 	}
4103 	if (tcp->tcp_push_tid != 0) {
4104 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4105 		tcp->tcp_push_tid = 0;
4106 	}
4107 }
4108 
4109 /*
4110  * The tcp_t is going away. Remove it from all lists and set it
4111  * to TCPS_CLOSED. The freeing up of memory is deferred until
4112  * tcp_inactive. This is needed since a thread in tcp_rput might have
4113  * done a CONN_INC_REF on this structure before it was removed from the
4114  * hashes.
4115  */
4116 static void
4117 tcp_closei_local(tcp_t *tcp)
4118 {
4119 	ire_t 	*ire;
4120 	conn_t	*connp = tcp->tcp_connp;
4121 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4122 
4123 	if (!TCP_IS_SOCKET(tcp))
4124 		tcp_acceptor_hash_remove(tcp);
4125 
4126 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4127 	tcp->tcp_ibsegs = 0;
4128 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4129 	tcp->tcp_obsegs = 0;
4130 
4131 	/*
4132 	 * If we are an eager connection hanging off a listener that
4133 	 * hasn't formally accepted the connection yet, get off his
4134 	 * list and blow off any data that we have accumulated.
4135 	 */
4136 	if (tcp->tcp_listener != NULL) {
4137 		tcp_t	*listener = tcp->tcp_listener;
4138 		mutex_enter(&listener->tcp_eager_lock);
4139 		/*
4140 		 * tcp_tconnind_started == B_TRUE means that the
4141 		 * conn_ind has already gone to listener. At
4142 		 * this point, eager will be closed but we
4143 		 * leave it in listeners eager list so that
4144 		 * if listener decides to close without doing
4145 		 * accept, we can clean this up. In tcp_wput_accept
4146 		 * we take care of the case of accept on closed
4147 		 * eager.
4148 		 */
4149 		if (!tcp->tcp_tconnind_started) {
4150 			tcp_eager_unlink(tcp);
4151 			mutex_exit(&listener->tcp_eager_lock);
4152 			/*
4153 			 * We don't want to have any pointers to the
4154 			 * listener queue, after we have released our
4155 			 * reference on the listener
4156 			 */
4157 			ASSERT(tcps->tcps_g_q != NULL);
4158 			tcp->tcp_rq = tcps->tcps_g_q;
4159 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4160 			CONN_DEC_REF(listener->tcp_connp);
4161 		} else {
4162 			mutex_exit(&listener->tcp_eager_lock);
4163 		}
4164 	}
4165 
4166 	/* Stop all the timers */
4167 	tcp_timers_stop(tcp);
4168 
4169 	if (tcp->tcp_state == TCPS_LISTEN) {
4170 		if (tcp->tcp_ip_addr_cache) {
4171 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4172 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4173 			tcp->tcp_ip_addr_cache = NULL;
4174 		}
4175 	}
4176 	mutex_enter(&tcp->tcp_non_sq_lock);
4177 	if (tcp->tcp_flow_stopped)
4178 		tcp_clrqfull(tcp);
4179 	mutex_exit(&tcp->tcp_non_sq_lock);
4180 
4181 	tcp_bind_hash_remove(tcp);
4182 	/*
4183 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4184 	 * is trying to remove this tcp from the time wait list, we will
4185 	 * block in tcp_time_wait_remove while trying to acquire the
4186 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4187 	 * requires the ipcl_hash_remove to be ordered after the
4188 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4189 	 */
4190 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4191 		(void) tcp_time_wait_remove(tcp, NULL);
4192 	CL_INET_DISCONNECT(connp, tcp);
4193 	ipcl_hash_remove(connp);
4194 
4195 	/*
4196 	 * Delete the cached ire in conn_ire_cache and also mark
4197 	 * the conn as CONDEMNED
4198 	 */
4199 	mutex_enter(&connp->conn_lock);
4200 	connp->conn_state_flags |= CONN_CONDEMNED;
4201 	ire = connp->conn_ire_cache;
4202 	connp->conn_ire_cache = NULL;
4203 	mutex_exit(&connp->conn_lock);
4204 	if (ire != NULL)
4205 		IRE_REFRELE_NOTR(ire);
4206 
4207 	/* Need to cleanup any pending ioctls */
4208 	ASSERT(tcp->tcp_time_wait_next == NULL);
4209 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4210 	ASSERT(tcp->tcp_time_wait_expire == 0);
4211 	tcp->tcp_state = TCPS_CLOSED;
4212 
4213 	/* Release any SSL context */
4214 	if (tcp->tcp_kssl_ent != NULL) {
4215 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4216 		tcp->tcp_kssl_ent = NULL;
4217 	}
4218 	if (tcp->tcp_kssl_ctx != NULL) {
4219 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4220 		tcp->tcp_kssl_ctx = NULL;
4221 	}
4222 	tcp->tcp_kssl_pending = B_FALSE;
4223 
4224 	tcp_ipsec_cleanup(tcp);
4225 }
4226 
4227 /*
4228  * tcp is dying (called from ipcl_conn_destroy and error cases).
4229  * Free the tcp_t in either case.
4230  */
4231 void
4232 tcp_free(tcp_t *tcp)
4233 {
4234 	mblk_t	*mp;
4235 	ip6_pkt_t	*ipp;
4236 
4237 	ASSERT(tcp != NULL);
4238 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4239 
4240 	tcp->tcp_rq = NULL;
4241 	tcp->tcp_wq = NULL;
4242 
4243 	tcp_close_mpp(&tcp->tcp_xmit_head);
4244 	tcp_close_mpp(&tcp->tcp_reass_head);
4245 	if (tcp->tcp_rcv_list != NULL) {
4246 		/* Free b_next chain */
4247 		tcp_close_mpp(&tcp->tcp_rcv_list);
4248 	}
4249 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4250 		freemsg(mp);
4251 	}
4252 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4253 		freemsg(mp);
4254 	}
4255 
4256 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4257 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4258 		freeb(tcp->tcp_fused_sigurg_mp);
4259 		tcp->tcp_fused_sigurg_mp = NULL;
4260 	}
4261 
4262 	if (tcp->tcp_ordrel_mp != NULL) {
4263 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4264 		freeb(tcp->tcp_ordrel_mp);
4265 		tcp->tcp_ordrel_mp = NULL;
4266 	}
4267 
4268 	if (tcp->tcp_sack_info != NULL) {
4269 		if (tcp->tcp_notsack_list != NULL) {
4270 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
4271 			    tcp);
4272 		}
4273 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4274 	}
4275 
4276 	if (tcp->tcp_hopopts != NULL) {
4277 		mi_free(tcp->tcp_hopopts);
4278 		tcp->tcp_hopopts = NULL;
4279 		tcp->tcp_hopoptslen = 0;
4280 	}
4281 	ASSERT(tcp->tcp_hopoptslen == 0);
4282 	if (tcp->tcp_dstopts != NULL) {
4283 		mi_free(tcp->tcp_dstopts);
4284 		tcp->tcp_dstopts = NULL;
4285 		tcp->tcp_dstoptslen = 0;
4286 	}
4287 	ASSERT(tcp->tcp_dstoptslen == 0);
4288 	if (tcp->tcp_rtdstopts != NULL) {
4289 		mi_free(tcp->tcp_rtdstopts);
4290 		tcp->tcp_rtdstopts = NULL;
4291 		tcp->tcp_rtdstoptslen = 0;
4292 	}
4293 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4294 	if (tcp->tcp_rthdr != NULL) {
4295 		mi_free(tcp->tcp_rthdr);
4296 		tcp->tcp_rthdr = NULL;
4297 		tcp->tcp_rthdrlen = 0;
4298 	}
4299 	ASSERT(tcp->tcp_rthdrlen == 0);
4300 
4301 	ipp = &tcp->tcp_sticky_ipp;
4302 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4303 	    IPPF_RTHDR))
4304 		ip6_pkt_free(ipp);
4305 
4306 	/*
4307 	 * Free memory associated with the tcp/ip header template.
4308 	 */
4309 
4310 	if (tcp->tcp_iphc != NULL)
4311 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4312 
4313 	/*
4314 	 * Following is really a blowing away a union.
4315 	 * It happens to have exactly two members of identical size
4316 	 * the following code is enough.
4317 	 */
4318 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4319 }
4320 
4321 
4322 /*
4323  * Put a connection confirmation message upstream built from the
4324  * address information within 'iph' and 'tcph'.  Report our success or failure.
4325  */
4326 static boolean_t
4327 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4328     mblk_t **defermp)
4329 {
4330 	sin_t	sin;
4331 	sin6_t	sin6;
4332 	mblk_t	*mp;
4333 	char	*optp = NULL;
4334 	int	optlen = 0;
4335 
4336 	if (defermp != NULL)
4337 		*defermp = NULL;
4338 
4339 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4340 		/*
4341 		 * Return in T_CONN_CON results of option negotiation through
4342 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4343 		 * negotiation, then what is received from remote end needs
4344 		 * to be taken into account but there is no such thing (yet?)
4345 		 * in our TCP/IP.
4346 		 * Note: We do not use mi_offset_param() here as
4347 		 * tcp_opts_conn_req contents do not directly come from
4348 		 * an application and are either generated in kernel or
4349 		 * from user input that was already verified.
4350 		 */
4351 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4352 		optp = (char *)(mp->b_rptr +
4353 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4354 		optlen = (int)
4355 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4356 	}
4357 
4358 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4359 		ipha_t *ipha = (ipha_t *)iphdr;
4360 
4361 		/* packet is IPv4 */
4362 		if (tcp->tcp_family == AF_INET) {
4363 			sin = sin_null;
4364 			sin.sin_addr.s_addr = ipha->ipha_src;
4365 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4366 			sin.sin_family = AF_INET;
4367 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4368 			    (int)sizeof (sin_t), optp, optlen);
4369 		} else {
4370 			sin6 = sin6_null;
4371 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4372 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4373 			sin6.sin6_family = AF_INET6;
4374 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4375 			    (int)sizeof (sin6_t), optp, optlen);
4376 
4377 		}
4378 	} else {
4379 		ip6_t	*ip6h = (ip6_t *)iphdr;
4380 
4381 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4382 		ASSERT(tcp->tcp_family == AF_INET6);
4383 		sin6 = sin6_null;
4384 		sin6.sin6_addr = ip6h->ip6_src;
4385 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4386 		sin6.sin6_family = AF_INET6;
4387 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4388 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4389 		    (int)sizeof (sin6_t), optp, optlen);
4390 	}
4391 
4392 	if (!mp)
4393 		return (B_FALSE);
4394 
4395 	mblk_copycred(mp, idmp);
4396 
4397 	if (defermp == NULL) {
4398 		conn_t *connp = tcp->tcp_connp;
4399 		if (IPCL_IS_NONSTR(connp)) {
4400 			cred_t *cr;
4401 			pid_t cpid;
4402 
4403 			cr = msg_getcred(mp, &cpid);
4404 			(*connp->conn_upcalls->su_connected)
4405 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4406 			    cpid);
4407 			freemsg(mp);
4408 		} else {
4409 			putnext(tcp->tcp_rq, mp);
4410 		}
4411 	} else {
4412 		*defermp = mp;
4413 	}
4414 
4415 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4416 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4417 	return (B_TRUE);
4418 }
4419 
4420 /*
4421  * Defense for the SYN attack -
4422  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4423  *    one from the list of droppable eagers. This list is a subset of q0.
4424  *    see comments before the definition of MAKE_DROPPABLE().
4425  * 2. Don't drop a SYN request before its first timeout. This gives every
4426  *    request at least til the first timeout to complete its 3-way handshake.
4427  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4428  *    requests currently on the queue that has timed out. This will be used
4429  *    as an indicator of whether an attack is under way, so that appropriate
4430  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4431  *    either when eager goes into ESTABLISHED, or gets freed up.)
4432  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4433  *    # of timeout drops back to <= q0len/32 => SYN alert off
4434  */
4435 static boolean_t
4436 tcp_drop_q0(tcp_t *tcp)
4437 {
4438 	tcp_t	*eager;
4439 	mblk_t	*mp;
4440 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4441 
4442 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4443 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4444 
4445 	/* Pick oldest eager from the list of droppable eagers */
4446 	eager = tcp->tcp_eager_prev_drop_q0;
4447 
4448 	/* If list is empty. return B_FALSE */
4449 	if (eager == tcp) {
4450 		return (B_FALSE);
4451 	}
4452 
4453 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4454 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4455 		return (B_FALSE);
4456 
4457 	/*
4458 	 * Take this eager out from the list of droppable eagers since we are
4459 	 * going to drop it.
4460 	 */
4461 	MAKE_UNDROPPABLE(eager);
4462 
4463 	if (tcp->tcp_debug) {
4464 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4465 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4466 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4467 		    tcp->tcp_conn_req_cnt_q0,
4468 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4469 	}
4470 
4471 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4472 
4473 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4474 	CONN_INC_REF(eager->tcp_connp);
4475 
4476 	/* Mark the IRE created for this SYN request temporary */
4477 	tcp_ip_ire_mark_advice(eager);
4478 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4479 	    tcp_clean_death_wrapper, eager->tcp_connp,
4480 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4481 
4482 	return (B_TRUE);
4483 }
4484 
4485 int
4486 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4487     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4488 {
4489 	tcp_t 		*ltcp = lconnp->conn_tcp;
4490 	tcp_t		*tcp = connp->conn_tcp;
4491 	mblk_t		*tpi_mp;
4492 	ipha_t		*ipha;
4493 	ip6_t		*ip6h;
4494 	sin6_t 		sin6;
4495 	in6_addr_t 	v6dst;
4496 	int		err;
4497 	int		ifindex = 0;
4498 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4499 
4500 	if (ipvers == IPV4_VERSION) {
4501 		ipha = (ipha_t *)mp->b_rptr;
4502 
4503 		connp->conn_send = ip_output;
4504 		connp->conn_recv = tcp_input;
4505 
4506 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4507 		    &connp->conn_bound_source_v6);
4508 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4509 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4510 
4511 		sin6 = sin6_null;
4512 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4513 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4514 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4515 		sin6.sin6_family = AF_INET6;
4516 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4517 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4518 		if (tcp->tcp_recvdstaddr) {
4519 			sin6_t	sin6d;
4520 
4521 			sin6d = sin6_null;
4522 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4523 			    &sin6d.sin6_addr);
4524 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4525 			sin6d.sin6_family = AF_INET;
4526 			tpi_mp = mi_tpi_extconn_ind(NULL,
4527 			    (char *)&sin6d, sizeof (sin6_t),
4528 			    (char *)&tcp,
4529 			    (t_scalar_t)sizeof (intptr_t),
4530 			    (char *)&sin6d, sizeof (sin6_t),
4531 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4532 		} else {
4533 			tpi_mp = mi_tpi_conn_ind(NULL,
4534 			    (char *)&sin6, sizeof (sin6_t),
4535 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4536 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4537 		}
4538 	} else {
4539 		ip6h = (ip6_t *)mp->b_rptr;
4540 
4541 		connp->conn_send = ip_output_v6;
4542 		connp->conn_recv = tcp_input;
4543 
4544 		connp->conn_bound_source_v6 = ip6h->ip6_dst;
4545 		connp->conn_srcv6 = ip6h->ip6_dst;
4546 		connp->conn_remv6 = ip6h->ip6_src;
4547 
4548 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4549 		ifindex = (int)DB_CKSUMSTUFF(mp);
4550 		DB_CKSUMSTUFF(mp) = 0;
4551 
4552 		sin6 = sin6_null;
4553 		sin6.sin6_addr = ip6h->ip6_src;
4554 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4555 		sin6.sin6_family = AF_INET6;
4556 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4557 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4558 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4559 
4560 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4561 			/* Pass up the scope_id of remote addr */
4562 			sin6.sin6_scope_id = ifindex;
4563 		} else {
4564 			sin6.sin6_scope_id = 0;
4565 		}
4566 		if (tcp->tcp_recvdstaddr) {
4567 			sin6_t	sin6d;
4568 
4569 			sin6d = sin6_null;
4570 			sin6.sin6_addr = ip6h->ip6_dst;
4571 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4572 			sin6d.sin6_family = AF_INET;
4573 			tpi_mp = mi_tpi_extconn_ind(NULL,
4574 			    (char *)&sin6d, sizeof (sin6_t),
4575 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4576 			    (char *)&sin6d, sizeof (sin6_t),
4577 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4578 		} else {
4579 			tpi_mp = mi_tpi_conn_ind(NULL,
4580 			    (char *)&sin6, sizeof (sin6_t),
4581 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4582 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4583 		}
4584 	}
4585 
4586 	if (tpi_mp == NULL)
4587 		return (ENOMEM);
4588 
4589 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4590 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4591 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4592 	connp->conn_fully_bound = B_FALSE;
4593 
4594 	/* Inherit information from the "parent" */
4595 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4596 	tcp->tcp_family = ltcp->tcp_family;
4597 
4598 	tcp->tcp_wq = ltcp->tcp_wq;
4599 	tcp->tcp_rq = ltcp->tcp_rq;
4600 
4601 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4602 	tcp->tcp_detached = B_TRUE;
4603 	SOCK_CONNID_INIT(tcp->tcp_connid);
4604 	if ((err = tcp_init_values(tcp)) != 0) {
4605 		freemsg(tpi_mp);
4606 		return (err);
4607 	}
4608 
4609 	if (ipvers == IPV4_VERSION) {
4610 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4611 			freemsg(tpi_mp);
4612 			return (err);
4613 		}
4614 		ASSERT(tcp->tcp_ipha != NULL);
4615 	} else {
4616 		/* ifindex must be already set */
4617 		ASSERT(ifindex != 0);
4618 
4619 		if (ltcp->tcp_bound_if != 0)
4620 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4621 		else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src))
4622 			tcp->tcp_bound_if = ifindex;
4623 
4624 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4625 		tcp->tcp_recvifindex = 0;
4626 		tcp->tcp_recvhops = 0xffffffffU;
4627 		ASSERT(tcp->tcp_ip6h != NULL);
4628 	}
4629 
4630 	tcp->tcp_lport = ltcp->tcp_lport;
4631 
4632 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4633 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4634 			/*
4635 			 * Listener had options of some sort; eager inherits.
4636 			 * Free up the eager template and allocate one
4637 			 * of the right size.
4638 			 */
4639 			if (tcp->tcp_hdr_grown) {
4640 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4641 			} else {
4642 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4643 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4644 			}
4645 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4646 			    KM_NOSLEEP);
4647 			if (tcp->tcp_iphc == NULL) {
4648 				tcp->tcp_iphc_len = 0;
4649 				freemsg(tpi_mp);
4650 				return (ENOMEM);
4651 			}
4652 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4653 			tcp->tcp_hdr_grown = B_TRUE;
4654 		}
4655 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4656 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4657 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4658 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4659 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4660 
4661 		/*
4662 		 * Copy the IP+TCP header template from listener to eager
4663 		 */
4664 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4665 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4666 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4667 			    IPPROTO_RAW) {
4668 				tcp->tcp_ip6h =
4669 				    (ip6_t *)(tcp->tcp_iphc +
4670 				    sizeof (ip6i_t));
4671 			} else {
4672 				tcp->tcp_ip6h =
4673 				    (ip6_t *)(tcp->tcp_iphc);
4674 			}
4675 			tcp->tcp_ipha = NULL;
4676 		} else {
4677 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4678 			tcp->tcp_ip6h = NULL;
4679 		}
4680 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4681 		    tcp->tcp_ip_hdr_len);
4682 	} else {
4683 		/*
4684 		 * only valid case when ipversion of listener and
4685 		 * eager differ is when listener is IPv6 and
4686 		 * eager is IPv4.
4687 		 * Eager header template has been initialized to the
4688 		 * maximum v4 header sizes, which includes space for
4689 		 * TCP and IP options.
4690 		 */
4691 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4692 		    (tcp->tcp_ipversion == IPV4_VERSION));
4693 		ASSERT(tcp->tcp_iphc_len >=
4694 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4695 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4696 		/* copy IP header fields individually */
4697 		tcp->tcp_ipha->ipha_ttl =
4698 		    ltcp->tcp_ip6h->ip6_hops;
4699 		bcopy(ltcp->tcp_tcph->th_lport,
4700 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4701 	}
4702 
4703 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4704 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4705 	    sizeof (in_port_t));
4706 
4707 	if (ltcp->tcp_lport == 0) {
4708 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4709 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4710 		    sizeof (in_port_t));
4711 	}
4712 
4713 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4714 		ASSERT(ipha != NULL);
4715 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4716 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4717 
4718 		/* Source routing option copyover (reverse it) */
4719 		if (tcps->tcps_rev_src_routes)
4720 			tcp_opt_reverse(tcp, ipha);
4721 	} else {
4722 		ASSERT(ip6h != NULL);
4723 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4724 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4725 	}
4726 
4727 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4728 	ASSERT(!tcp->tcp_tconnind_started);
4729 	/*
4730 	 * If the SYN contains a credential, it's a loopback packet; attach
4731 	 * the credential to the TPI message.
4732 	 */
4733 	mblk_copycred(tpi_mp, idmp);
4734 
4735 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4736 
4737 	/* Inherit the listener's SSL protection state */
4738 
4739 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4740 		kssl_hold_ent(tcp->tcp_kssl_ent);
4741 		tcp->tcp_kssl_pending = B_TRUE;
4742 	}
4743 
4744 	/* Inherit the listener's non-STREAMS flag */
4745 	if (IPCL_IS_NONSTR(lconnp)) {
4746 		connp->conn_flags |= IPCL_NONSTR;
4747 	}
4748 
4749 	return (0);
4750 }
4751 
4752 
4753 int
4754 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4755     tcph_t *tcph, mblk_t *idmp)
4756 {
4757 	tcp_t 		*ltcp = lconnp->conn_tcp;
4758 	tcp_t		*tcp = connp->conn_tcp;
4759 	sin_t		sin;
4760 	mblk_t		*tpi_mp = NULL;
4761 	int		err;
4762 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4763 
4764 	sin = sin_null;
4765 	sin.sin_addr.s_addr = ipha->ipha_src;
4766 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4767 	sin.sin_family = AF_INET;
4768 	if (ltcp->tcp_recvdstaddr) {
4769 		sin_t	sind;
4770 
4771 		sind = sin_null;
4772 		sind.sin_addr.s_addr = ipha->ipha_dst;
4773 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4774 		sind.sin_family = AF_INET;
4775 		tpi_mp = mi_tpi_extconn_ind(NULL,
4776 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4777 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4778 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4779 	} else {
4780 		tpi_mp = mi_tpi_conn_ind(NULL,
4781 		    (char *)&sin, sizeof (sin_t),
4782 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4783 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4784 	}
4785 
4786 	if (tpi_mp == NULL) {
4787 		return (ENOMEM);
4788 	}
4789 
4790 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4791 	connp->conn_send = ip_output;
4792 	connp->conn_recv = tcp_input;
4793 	connp->conn_fully_bound = B_FALSE;
4794 
4795 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4796 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4797 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4798 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4799 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4800 
4801 	/* Inherit information from the "parent" */
4802 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4803 	tcp->tcp_family = ltcp->tcp_family;
4804 	tcp->tcp_wq = ltcp->tcp_wq;
4805 	tcp->tcp_rq = ltcp->tcp_rq;
4806 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4807 	tcp->tcp_detached = B_TRUE;
4808 	SOCK_CONNID_INIT(tcp->tcp_connid);
4809 	if ((err = tcp_init_values(tcp)) != 0) {
4810 		freemsg(tpi_mp);
4811 		return (err);
4812 	}
4813 
4814 	/*
4815 	 * Let's make sure that eager tcp template has enough space to
4816 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4817 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4818 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4819 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4820 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4821 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4822 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4823 	 */
4824 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4825 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4826 
4827 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4828 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4829 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4830 	tcp->tcp_ttl = ltcp->tcp_ttl;
4831 	tcp->tcp_tos = ltcp->tcp_tos;
4832 
4833 	/* Copy the IP+TCP header template from listener to eager */
4834 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4835 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4836 	tcp->tcp_ip6h = NULL;
4837 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4838 	    tcp->tcp_ip_hdr_len);
4839 
4840 	/* Initialize the IP addresses and Ports */
4841 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4842 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4843 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4844 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4845 
4846 	/* Source routing option copyover (reverse it) */
4847 	if (tcps->tcps_rev_src_routes)
4848 		tcp_opt_reverse(tcp, ipha);
4849 
4850 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4851 	ASSERT(!tcp->tcp_tconnind_started);
4852 
4853 	/*
4854 	 * If the SYN contains a credential, it's a loopback packet; attach
4855 	 * the credential to the TPI message.
4856 	 */
4857 	mblk_copycred(tpi_mp, idmp);
4858 
4859 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4860 
4861 	/* Inherit the listener's SSL protection state */
4862 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4863 		kssl_hold_ent(tcp->tcp_kssl_ent);
4864 		tcp->tcp_kssl_pending = B_TRUE;
4865 	}
4866 
4867 	/* Inherit the listener's non-STREAMS flag */
4868 	if (IPCL_IS_NONSTR(lconnp)) {
4869 		connp->conn_flags |= IPCL_NONSTR;
4870 	}
4871 
4872 	return (0);
4873 }
4874 
4875 /*
4876  * sets up conn for ipsec.
4877  * if the first mblk is M_CTL it is consumed and mpp is updated.
4878  * in case of error mpp is freed.
4879  */
4880 conn_t *
4881 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4882 {
4883 	conn_t 		*connp = tcp->tcp_connp;
4884 	conn_t 		*econnp;
4885 	squeue_t 	*new_sqp;
4886 	mblk_t 		*first_mp = *mpp;
4887 	mblk_t		*mp = *mpp;
4888 	boolean_t	mctl_present = B_FALSE;
4889 	uint_t		ipvers;
4890 
4891 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4892 	if (econnp == NULL) {
4893 		freemsg(first_mp);
4894 		return (NULL);
4895 	}
4896 	if (DB_TYPE(mp) == M_CTL) {
4897 		if (mp->b_cont == NULL ||
4898 		    mp->b_cont->b_datap->db_type != M_DATA) {
4899 			freemsg(first_mp);
4900 			return (NULL);
4901 		}
4902 		mp = mp->b_cont;
4903 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4904 			freemsg(first_mp);
4905 			return (NULL);
4906 		}
4907 
4908 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4909 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4910 		mctl_present = B_TRUE;
4911 	} else {
4912 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4913 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4914 	}
4915 
4916 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4917 	DB_CKSUMSTART(mp) = 0;
4918 
4919 	ASSERT(OK_32PTR(mp->b_rptr));
4920 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4921 	if (ipvers == IPV4_VERSION) {
4922 		uint16_t  	*up;
4923 		uint32_t	ports;
4924 		ipha_t		*ipha;
4925 
4926 		ipha = (ipha_t *)mp->b_rptr;
4927 		up = (uint16_t *)((uchar_t *)ipha +
4928 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4929 		ports = *(uint32_t *)up;
4930 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4931 		    ipha->ipha_dst, ipha->ipha_src, ports);
4932 	} else {
4933 		uint16_t  	*up;
4934 		uint32_t	ports;
4935 		uint16_t	ip_hdr_len;
4936 		uint8_t		*nexthdrp;
4937 		ip6_t 		*ip6h;
4938 		tcph_t		*tcph;
4939 
4940 		ip6h = (ip6_t *)mp->b_rptr;
4941 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4942 			ip_hdr_len = IPV6_HDR_LEN;
4943 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4944 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4945 			CONN_DEC_REF(econnp);
4946 			freemsg(first_mp);
4947 			return (NULL);
4948 		}
4949 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4950 		up = (uint16_t *)tcph->th_lport;
4951 		ports = *(uint32_t *)up;
4952 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4953 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4954 	}
4955 
4956 	/*
4957 	 * The caller already ensured that there is a sqp present.
4958 	 */
4959 	econnp->conn_sqp = new_sqp;
4960 	econnp->conn_initial_sqp = new_sqp;
4961 
4962 	if (connp->conn_policy != NULL) {
4963 		ipsec_in_t *ii;
4964 		ii = (ipsec_in_t *)(first_mp->b_rptr);
4965 		ASSERT(ii->ipsec_in_policy == NULL);
4966 		IPPH_REFHOLD(connp->conn_policy);
4967 		ii->ipsec_in_policy = connp->conn_policy;
4968 
4969 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
4970 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
4971 			CONN_DEC_REF(econnp);
4972 			freemsg(first_mp);
4973 			return (NULL);
4974 		}
4975 	}
4976 
4977 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
4978 		CONN_DEC_REF(econnp);
4979 		freemsg(first_mp);
4980 		return (NULL);
4981 	}
4982 
4983 	/*
4984 	 * If we know we have some policy, pass the "IPSEC"
4985 	 * options size TCP uses this adjust the MSS.
4986 	 */
4987 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
4988 	if (mctl_present) {
4989 		freeb(first_mp);
4990 		*mpp = mp;
4991 	}
4992 
4993 	return (econnp);
4994 }
4995 
4996 /*
4997  * tcp_get_conn/tcp_free_conn
4998  *
4999  * tcp_get_conn is used to get a clean tcp connection structure.
5000  * It tries to reuse the connections put on the freelist by the
5001  * time_wait_collector failing which it goes to kmem_cache. This
5002  * way has two benefits compared to just allocating from and
5003  * freeing to kmem_cache.
5004  * 1) The time_wait_collector can free (which includes the cleanup)
5005  * outside the squeue. So when the interrupt comes, we have a clean
5006  * connection sitting in the freelist. Obviously, this buys us
5007  * performance.
5008  *
5009  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5010  * has multiple disadvantages - tying up the squeue during alloc, and the
5011  * fact that IPSec policy initialization has to happen here which
5012  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5013  * But allocating the conn/tcp in IP land is also not the best since
5014  * we can't check the 'q' and 'q0' which are protected by squeue and
5015  * blindly allocate memory which might have to be freed here if we are
5016  * not allowed to accept the connection. By using the freelist and
5017  * putting the conn/tcp back in freelist, we don't pay a penalty for
5018  * allocating memory without checking 'q/q0' and freeing it if we can't
5019  * accept the connection.
5020  *
5021  * Care should be taken to put the conn back in the same squeue's freelist
5022  * from which it was allocated. Best results are obtained if conn is
5023  * allocated from listener's squeue and freed to the same. Time wait
5024  * collector will free up the freelist is the connection ends up sitting
5025  * there for too long.
5026  */
5027 void *
5028 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5029 {
5030 	tcp_t			*tcp = NULL;
5031 	conn_t			*connp = NULL;
5032 	squeue_t		*sqp = (squeue_t *)arg;
5033 	tcp_squeue_priv_t 	*tcp_time_wait;
5034 	netstack_t		*ns;
5035 	mblk_t			*tcp_rsrv_mp = NULL;
5036 
5037 	tcp_time_wait =
5038 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5039 
5040 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5041 	tcp = tcp_time_wait->tcp_free_list;
5042 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5043 	if (tcp != NULL) {
5044 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5045 		tcp_time_wait->tcp_free_list_cnt--;
5046 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5047 		tcp->tcp_time_wait_next = NULL;
5048 		connp = tcp->tcp_connp;
5049 		connp->conn_flags |= IPCL_REUSED;
5050 
5051 		ASSERT(tcp->tcp_tcps == NULL);
5052 		ASSERT(connp->conn_netstack == NULL);
5053 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5054 		ns = tcps->tcps_netstack;
5055 		netstack_hold(ns);
5056 		connp->conn_netstack = ns;
5057 		tcp->tcp_tcps = tcps;
5058 		TCPS_REFHOLD(tcps);
5059 		ipcl_globalhash_insert(connp);
5060 		return ((void *)connp);
5061 	}
5062 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5063 	/*
5064 	 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
5065 	 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
5066 	 */
5067 	tcp_rsrv_mp = allocb(0, BPRI_HI);
5068 	if (tcp_rsrv_mp == NULL)
5069 		return (NULL);
5070 
5071 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5072 	    tcps->tcps_netstack)) == NULL) {
5073 		freeb(tcp_rsrv_mp);
5074 		return (NULL);
5075 	}
5076 
5077 	tcp = connp->conn_tcp;
5078 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
5079 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5080 
5081 	tcp->tcp_tcps = tcps;
5082 	TCPS_REFHOLD(tcps);
5083 
5084 	return ((void *)connp);
5085 }
5086 
5087 /*
5088  * Update the cached label for the given tcp_t.  This should be called once per
5089  * connection, and before any packets are sent or tcp_process_options is
5090  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5091  */
5092 static boolean_t
5093 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5094 {
5095 	conn_t *connp = tcp->tcp_connp;
5096 
5097 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5098 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5099 		int added;
5100 
5101 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5102 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5103 			return (B_FALSE);
5104 
5105 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5106 		if (added == -1)
5107 			return (B_FALSE);
5108 		tcp->tcp_hdr_len += added;
5109 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5110 		tcp->tcp_ip_hdr_len += added;
5111 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5112 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5113 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5114 			    tcp->tcp_hdr_len);
5115 			if (added == -1)
5116 				return (B_FALSE);
5117 			tcp->tcp_hdr_len += added;
5118 			tcp->tcp_tcph = (tcph_t *)
5119 			    ((uchar_t *)tcp->tcp_tcph + added);
5120 			tcp->tcp_ip_hdr_len += added;
5121 		}
5122 	} else {
5123 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5124 
5125 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5126 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5127 			return (B_FALSE);
5128 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5129 		    &tcp->tcp_label_len, optbuf) != 0)
5130 			return (B_FALSE);
5131 		if (tcp_build_hdrs(tcp) != 0)
5132 			return (B_FALSE);
5133 	}
5134 
5135 	connp->conn_ulp_labeled = 1;
5136 
5137 	return (B_TRUE);
5138 }
5139 
5140 /* BEGIN CSTYLED */
5141 /*
5142  *
5143  * The sockfs ACCEPT path:
5144  * =======================
5145  *
5146  * The eager is now established in its own perimeter as soon as SYN is
5147  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5148  * completes the accept processing on the acceptor STREAM. The sending
5149  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5150  * listener but a TLI/XTI listener completes the accept processing
5151  * on the listener perimeter.
5152  *
5153  * Common control flow for 3 way handshake:
5154  * ----------------------------------------
5155  *
5156  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5157  *					-> tcp_conn_request()
5158  *
5159  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5160  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5161  *
5162  * Sockfs ACCEPT Path:
5163  * -------------------
5164  *
5165  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5166  * as STREAM entry point)
5167  *
5168  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5169  *
5170  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5171  * association (we are not behind eager's squeue but sockfs is protecting us
5172  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5173  * is changed to point at tcp_wput().
5174  *
5175  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5176  * listener (done on listener's perimeter).
5177  *
5178  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5179  * accept.
5180  *
5181  * TLI/XTI client ACCEPT path:
5182  * ---------------------------
5183  *
5184  * soaccept() sends T_CONN_RES on the listener STREAM.
5185  *
5186  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5187  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5188  *
5189  * Locks:
5190  * ======
5191  *
5192  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5193  * and listeners->tcp_eager_next_q.
5194  *
5195  * Referencing:
5196  * ============
5197  *
5198  * 1) We start out in tcp_conn_request by eager placing a ref on
5199  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5200  *
5201  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5202  * doing so we place a ref on the eager. This ref is finally dropped at the
5203  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5204  * reference is dropped by the squeue framework.
5205  *
5206  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5207  *
5208  * The reference must be released by the same entity that added the reference
5209  * In the above scheme, the eager is the entity that adds and releases the
5210  * references. Note that tcp_accept_finish executes in the squeue of the eager
5211  * (albeit after it is attached to the acceptor stream). Though 1. executes
5212  * in the listener's squeue, the eager is nascent at this point and the
5213  * reference can be considered to have been added on behalf of the eager.
5214  *
5215  * Eager getting a Reset or listener closing:
5216  * ==========================================
5217  *
5218  * Once the listener and eager are linked, the listener never does the unlink.
5219  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5220  * a message on all eager perimeter. The eager then does the unlink, clears
5221  * any pointers to the listener's queue and drops the reference to the
5222  * listener. The listener waits in tcp_close outside the squeue until its
5223  * refcount has dropped to 1. This ensures that the listener has waited for
5224  * all eagers to clear their association with the listener.
5225  *
5226  * Similarly, if eager decides to go away, it can unlink itself and close.
5227  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5228  * the reference to eager is still valid because of the extra ref we put
5229  * in tcp_send_conn_ind.
5230  *
5231  * Listener can always locate the eager under the protection
5232  * of the listener->tcp_eager_lock, and then do a refhold
5233  * on the eager during the accept processing.
5234  *
5235  * The acceptor stream accesses the eager in the accept processing
5236  * based on the ref placed on eager before sending T_conn_ind.
5237  * The only entity that can negate this refhold is a listener close
5238  * which is mutually exclusive with an active acceptor stream.
5239  *
5240  * Eager's reference on the listener
5241  * ===================================
5242  *
5243  * If the accept happens (even on a closed eager) the eager drops its
5244  * reference on the listener at the start of tcp_accept_finish. If the
5245  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5246  * the reference is dropped in tcp_closei_local. If the listener closes,
5247  * the reference is dropped in tcp_eager_kill. In all cases the reference
5248  * is dropped while executing in the eager's context (squeue).
5249  */
5250 /* END CSTYLED */
5251 
5252 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5253 
5254 /*
5255  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5256  * tcp_rput_data will not see any SYN packets.
5257  */
5258 /* ARGSUSED */
5259 void
5260 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5261 {
5262 	tcph_t		*tcph;
5263 	uint32_t	seg_seq;
5264 	tcp_t		*eager;
5265 	uint_t		ipvers;
5266 	ipha_t		*ipha;
5267 	ip6_t		*ip6h;
5268 	int		err;
5269 	conn_t		*econnp = NULL;
5270 	squeue_t	*new_sqp;
5271 	mblk_t		*mp1;
5272 	uint_t 		ip_hdr_len;
5273 	conn_t		*connp = (conn_t *)arg;
5274 	tcp_t		*tcp = connp->conn_tcp;
5275 	cred_t		*credp;
5276 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5277 	ip_stack_t	*ipst;
5278 
5279 	if (tcp->tcp_state != TCPS_LISTEN)
5280 		goto error2;
5281 
5282 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5283 
5284 	mutex_enter(&tcp->tcp_eager_lock);
5285 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5286 		mutex_exit(&tcp->tcp_eager_lock);
5287 		TCP_STAT(tcps, tcp_listendrop);
5288 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5289 		if (tcp->tcp_debug) {
5290 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5291 			    "tcp_conn_request: listen backlog (max=%d) "
5292 			    "overflow (%d pending) on %s",
5293 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5294 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5295 		}
5296 		goto error2;
5297 	}
5298 
5299 	if (tcp->tcp_conn_req_cnt_q0 >=
5300 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5301 		/*
5302 		 * Q0 is full. Drop a pending half-open req from the queue
5303 		 * to make room for the new SYN req. Also mark the time we
5304 		 * drop a SYN.
5305 		 *
5306 		 * A more aggressive defense against SYN attack will
5307 		 * be to set the "tcp_syn_defense" flag now.
5308 		 */
5309 		TCP_STAT(tcps, tcp_listendropq0);
5310 		tcp->tcp_last_rcv_lbolt = lbolt64;
5311 		if (!tcp_drop_q0(tcp)) {
5312 			mutex_exit(&tcp->tcp_eager_lock);
5313 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5314 			if (tcp->tcp_debug) {
5315 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5316 				    "tcp_conn_request: listen half-open queue "
5317 				    "(max=%d) full (%d pending) on %s",
5318 				    tcps->tcps_conn_req_max_q0,
5319 				    tcp->tcp_conn_req_cnt_q0,
5320 				    tcp_display(tcp, NULL,
5321 				    DISP_PORT_ONLY));
5322 			}
5323 			goto error2;
5324 		}
5325 	}
5326 	mutex_exit(&tcp->tcp_eager_lock);
5327 
5328 	/*
5329 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5330 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5331 	 * link local address.  If IPSec is enabled, db_struioflag has
5332 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5333 	 * otherwise an error case if neither of them is set.
5334 	 */
5335 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5336 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5337 		DB_CKSUMSTART(mp) = 0;
5338 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5339 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5340 		if (econnp == NULL)
5341 			goto error2;
5342 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5343 		econnp->conn_sqp = new_sqp;
5344 		econnp->conn_initial_sqp = new_sqp;
5345 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5346 		/*
5347 		 * mp is updated in tcp_get_ipsec_conn().
5348 		 */
5349 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5350 		if (econnp == NULL) {
5351 			/*
5352 			 * mp freed by tcp_get_ipsec_conn.
5353 			 */
5354 			return;
5355 		}
5356 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5357 	} else {
5358 		goto error2;
5359 	}
5360 
5361 	ASSERT(DB_TYPE(mp) == M_DATA);
5362 
5363 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5364 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5365 	ASSERT(OK_32PTR(mp->b_rptr));
5366 	if (ipvers == IPV4_VERSION) {
5367 		ipha = (ipha_t *)mp->b_rptr;
5368 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5369 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5370 	} else {
5371 		ip6h = (ip6_t *)mp->b_rptr;
5372 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5373 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5374 	}
5375 
5376 	if (tcp->tcp_family == AF_INET) {
5377 		ASSERT(ipvers == IPV4_VERSION);
5378 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5379 	} else {
5380 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5381 	}
5382 
5383 	if (err)
5384 		goto error3;
5385 
5386 	eager = econnp->conn_tcp;
5387 	ASSERT(eager->tcp_ordrel_mp == NULL);
5388 
5389 	if (!IPCL_IS_NONSTR(econnp)) {
5390 		/*
5391 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
5392 		 * at close time, we will always have that to send up.
5393 		 * Otherwise, we need to do special handling in case the
5394 		 * allocation fails at that time.
5395 		 */
5396 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5397 			goto error3;
5398 	}
5399 	/* Inherit various TCP parameters from the listener */
5400 	eager->tcp_naglim = tcp->tcp_naglim;
5401 	eager->tcp_first_timer_threshold = tcp->tcp_first_timer_threshold;
5402 	eager->tcp_second_timer_threshold = tcp->tcp_second_timer_threshold;
5403 
5404 	eager->tcp_first_ctimer_threshold = tcp->tcp_first_ctimer_threshold;
5405 	eager->tcp_second_ctimer_threshold = tcp->tcp_second_ctimer_threshold;
5406 
5407 	/*
5408 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5409 	 * If it does not, the eager's receive window will be set to the
5410 	 * listener's receive window later in this function.
5411 	 */
5412 	eager->tcp_rwnd = 0;
5413 
5414 	/*
5415 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5416 	 * calling tcp_process_options() where tcp_mss_set() is called
5417 	 * to set the initial cwnd.
5418 	 */
5419 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5420 
5421 	/*
5422 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5423 	 * zone id before the accept is completed in tcp_wput_accept().
5424 	 */
5425 	econnp->conn_zoneid = connp->conn_zoneid;
5426 	econnp->conn_allzones = connp->conn_allzones;
5427 
5428 	/* Copy nexthop information from listener to eager */
5429 	if (connp->conn_nexthop_set) {
5430 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5431 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5432 	}
5433 
5434 	/*
5435 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5436 	 * eager is accepted
5437 	 */
5438 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5439 	crhold(credp);
5440 
5441 	ASSERT(econnp->conn_effective_cred == NULL);
5442 	if (is_system_labeled()) {
5443 		cred_t *cr;
5444 		ts_label_t *tsl;
5445 
5446 		/*
5447 		 * If this is an MLP connection or a MAC-Exempt connection
5448 		 * with an unlabeled node, packets are to be
5449 		 * exchanged using the security label of the received
5450 		 * SYN packet instead of the server application's label.
5451 		 */
5452 		if ((cr = msg_getcred(mp, NULL)) != NULL &&
5453 		    (tsl = crgetlabel(cr)) != NULL &&
5454 		    (connp->conn_mlp_type != mlptSingle ||
5455 		    (connp->conn_mac_exempt == B_TRUE &&
5456 		    (tsl->tsl_flags & TSLF_UNLABELED)))) {
5457 			if ((econnp->conn_effective_cred =
5458 			    copycred_from_tslabel(econnp->conn_cred,
5459 			    tsl, KM_NOSLEEP)) != NULL) {
5460 				DTRACE_PROBE2(
5461 				    syn_accept_peerlabel,
5462 				    conn_t *, econnp, cred_t *,
5463 				    econnp->conn_effective_cred);
5464 			} else {
5465 				DTRACE_PROBE3(
5466 				    tx__ip__log__error__set__eagercred__tcp,
5467 				    char *,
5468 				    "SYN mp(1) label on eager connp(2) failed",
5469 				    mblk_t *, mp, conn_t *, econnp);
5470 				goto error3;
5471 			}
5472 		} else {
5473 			DTRACE_PROBE2(syn_accept, conn_t *,
5474 			    econnp, cred_t *, econnp->conn_cred)
5475 		}
5476 
5477 		/*
5478 		 * Verify the destination is allowed to receive packets
5479 		 * at the security label of the SYN-ACK we are generating.
5480 		 * tsol_check_dest() may create a new effective cred for
5481 		 * this connection with a modified label or label flags.
5482 		 */
5483 		if (IN6_IS_ADDR_V4MAPPED(&econnp->conn_remv6)) {
5484 			uint32_t dst;
5485 			IN6_V4MAPPED_TO_IPADDR(&econnp->conn_remv6, dst);
5486 			err = tsol_check_dest(CONN_CRED(econnp), &dst,
5487 			    IPV4_VERSION, B_FALSE, &cr);
5488 		} else {
5489 			err = tsol_check_dest(CONN_CRED(econnp),
5490 			    &econnp->conn_remv6, IPV6_VERSION,
5491 			    B_FALSE, &cr);
5492 		}
5493 		if (err != 0)
5494 			goto error3;
5495 		if (cr != NULL) {
5496 			if (econnp->conn_effective_cred != NULL)
5497 				crfree(econnp->conn_effective_cred);
5498 			econnp->conn_effective_cred = cr;
5499 		}
5500 
5501 		/*
5502 		 * Generate the security label to be used in the text of
5503 		 * this connection's outgoing packets.
5504 		 */
5505 		if (!tcp_update_label(eager, CONN_CRED(econnp))) {
5506 			DTRACE_PROBE3(
5507 			    tx__ip__log__error__connrequest__tcp,
5508 			    char *, "eager connp(1) label on SYN mp(2) failed",
5509 			    conn_t *, econnp, mblk_t *, mp);
5510 			goto error3;
5511 		}
5512 	}
5513 
5514 	eager->tcp_hard_binding = B_TRUE;
5515 
5516 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5517 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5518 
5519 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5520 	if (err != 0) {
5521 		tcp_bind_hash_remove(eager);
5522 		goto error3;
5523 	}
5524 
5525 	/*
5526 	 * No need to check for multicast destination since ip will only pass
5527 	 * up multicasts to those that have expressed interest
5528 	 * TODO: what about rejecting broadcasts?
5529 	 * Also check that source is not a multicast or broadcast address.
5530 	 */
5531 	eager->tcp_state = TCPS_SYN_RCVD;
5532 
5533 
5534 	/*
5535 	 * There should be no ire in the mp as we are being called after
5536 	 * receiving the SYN.
5537 	 */
5538 	ASSERT(tcp_ire_mp(&mp) == NULL);
5539 
5540 	/*
5541 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5542 	 */
5543 
5544 	if (tcp_adapt_ire(eager, NULL) == 0) {
5545 		/* Undo the bind_hash_insert */
5546 		tcp_bind_hash_remove(eager);
5547 		goto error3;
5548 	}
5549 
5550 	/* Process all TCP options. */
5551 	tcp_process_options(eager, tcph);
5552 
5553 	/* Is the other end ECN capable? */
5554 	if (tcps->tcps_ecn_permitted >= 1 &&
5555 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5556 		eager->tcp_ecn_ok = B_TRUE;
5557 	}
5558 
5559 	/*
5560 	 * listeners tcp_recv_hiwater should be the default window size or a
5561 	 * window size changed via SO_RCVBUF option. First round up the
5562 	 * eager's tcp_rwnd to the nearest MSS. Then find out the window
5563 	 * scale option value if needed. Call tcp_rwnd_set() to finish the
5564 	 * setting.
5565 	 *
5566 	 * Note if there is a rpipe metric associated with the remote host,
5567 	 * we should not inherit receive window size from listener.
5568 	 */
5569 	eager->tcp_rwnd = MSS_ROUNDUP(
5570 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5571 	    eager->tcp_rwnd), eager->tcp_mss);
5572 	if (eager->tcp_snd_ws_ok)
5573 		tcp_set_ws_value(eager);
5574 	/*
5575 	 * Note that this is the only place tcp_rwnd_set() is called for
5576 	 * accepting a connection.  We need to call it here instead of
5577 	 * after the 3-way handshake because we need to tell the other
5578 	 * side our rwnd in the SYN-ACK segment.
5579 	 */
5580 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5581 
5582 	/*
5583 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5584 	 * via soaccept()->soinheritoptions() which essentially applies
5585 	 * all the listener options to the new STREAM. The options that we
5586 	 * need to take care of are:
5587 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5588 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5589 	 * SO_SNDBUF, SO_RCVBUF.
5590 	 *
5591 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5592 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5593 	 *		tcp_maxpsz_set() gets called later from
5594 	 *		tcp_accept_finish(), the option takes effect.
5595 	 *
5596 	 */
5597 	/* Set the TCP options */
5598 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5599 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5600 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5601 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5602 	eager->tcp_oobinline = tcp->tcp_oobinline;
5603 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5604 	eager->tcp_broadcast = tcp->tcp_broadcast;
5605 	eager->tcp_useloopback = tcp->tcp_useloopback;
5606 	eager->tcp_dontroute = tcp->tcp_dontroute;
5607 	eager->tcp_debug = tcp->tcp_debug;
5608 	eager->tcp_linger = tcp->tcp_linger;
5609 	eager->tcp_lingertime = tcp->tcp_lingertime;
5610 	if (tcp->tcp_ka_enabled)
5611 		eager->tcp_ka_enabled = 1;
5612 
5613 	/* Set the IP options */
5614 	econnp->conn_broadcast = connp->conn_broadcast;
5615 	econnp->conn_loopback = connp->conn_loopback;
5616 	econnp->conn_dontroute = connp->conn_dontroute;
5617 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5618 
5619 	/* Put a ref on the listener for the eager. */
5620 	CONN_INC_REF(connp);
5621 	mutex_enter(&tcp->tcp_eager_lock);
5622 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5623 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5624 	tcp->tcp_eager_next_q0 = eager;
5625 	eager->tcp_eager_prev_q0 = tcp;
5626 
5627 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5628 	eager->tcp_listener = tcp;
5629 	eager->tcp_saved_listener = tcp;
5630 
5631 	/*
5632 	 * Tag this detached tcp vector for later retrieval
5633 	 * by our listener client in tcp_accept().
5634 	 */
5635 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5636 	tcp->tcp_conn_req_cnt_q0++;
5637 	if (++tcp->tcp_conn_req_seqnum == -1) {
5638 		/*
5639 		 * -1 is "special" and defined in TPI as something
5640 		 * that should never be used in T_CONN_IND
5641 		 */
5642 		++tcp->tcp_conn_req_seqnum;
5643 	}
5644 	mutex_exit(&tcp->tcp_eager_lock);
5645 
5646 	if (tcp->tcp_syn_defense) {
5647 		/* Don't drop the SYN that comes from a good IP source */
5648 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5649 		if (addr_cache != NULL && eager->tcp_remote ==
5650 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5651 			eager->tcp_dontdrop = B_TRUE;
5652 		}
5653 	}
5654 
5655 	/*
5656 	 * We need to insert the eager in its own perimeter but as soon
5657 	 * as we do that, we expose the eager to the classifier and
5658 	 * should not touch any field outside the eager's perimeter.
5659 	 * So do all the work necessary before inserting the eager
5660 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5661 	 * will succeed but undo everything if it fails.
5662 	 */
5663 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5664 	eager->tcp_irs = seg_seq;
5665 	eager->tcp_rack = seg_seq;
5666 	eager->tcp_rnxt = seg_seq + 1;
5667 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5668 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5669 	eager->tcp_state = TCPS_SYN_RCVD;
5670 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5671 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5672 	if (mp1 == NULL) {
5673 		/*
5674 		 * Increment the ref count as we are going to
5675 		 * enqueueing an mp in squeue
5676 		 */
5677 		CONN_INC_REF(econnp);
5678 		goto error;
5679 	}
5680 
5681 	/*
5682 	 * Note that in theory this should use the current pid
5683 	 * so that getpeerucred on the client returns the actual listener
5684 	 * that does accept. But accept() hasn't been called yet. We could use
5685 	 * the pid of the process that did bind/listen on the server.
5686 	 * However, with common usage like inetd() the bind/listen can be done
5687 	 * by a different process than the accept().
5688 	 * Hence we do the simple thing of using the open pid here.
5689 	 * Note that db_credp is set later in tcp_send_data().
5690 	 */
5691 	mblk_setcred(mp1, credp, tcp->tcp_cpid);
5692 	eager->tcp_cpid = tcp->tcp_cpid;
5693 	eager->tcp_open_time = lbolt64;
5694 
5695 	/*
5696 	 * We need to start the rto timer. In normal case, we start
5697 	 * the timer after sending the packet on the wire (or at
5698 	 * least believing that packet was sent by waiting for
5699 	 * CALL_IP_WPUT() to return). Since this is the first packet
5700 	 * being sent on the wire for the eager, our initial tcp_rto
5701 	 * is at least tcp_rexmit_interval_min which is a fairly
5702 	 * large value to allow the algorithm to adjust slowly to large
5703 	 * fluctuations of RTT during first few transmissions.
5704 	 *
5705 	 * Starting the timer first and then sending the packet in this
5706 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5707 	 * is of the order of several 100ms and starting the timer
5708 	 * first and then sending the packet will result in difference
5709 	 * of few micro seconds.
5710 	 *
5711 	 * Without this optimization, we are forced to hold the fanout
5712 	 * lock across the ipcl_bind_insert() and sending the packet
5713 	 * so that we don't race against an incoming packet (maybe RST)
5714 	 * for this eager.
5715 	 *
5716 	 * It is necessary to acquire an extra reference on the eager
5717 	 * at this point and hold it until after tcp_send_data() to
5718 	 * ensure against an eager close race.
5719 	 */
5720 
5721 	CONN_INC_REF(eager->tcp_connp);
5722 
5723 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5724 
5725 	/*
5726 	 * Insert the eager in its own perimeter now. We are ready to deal
5727 	 * with any packets on eager.
5728 	 */
5729 	if (eager->tcp_ipversion == IPV4_VERSION) {
5730 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5731 			goto error;
5732 		}
5733 	} else {
5734 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5735 			goto error;
5736 		}
5737 	}
5738 
5739 	/* mark conn as fully-bound */
5740 	econnp->conn_fully_bound = B_TRUE;
5741 
5742 	/* Send the SYN-ACK */
5743 	tcp_send_data(eager, eager->tcp_wq, mp1);
5744 	CONN_DEC_REF(eager->tcp_connp);
5745 	freemsg(mp);
5746 
5747 	return;
5748 error:
5749 	freemsg(mp1);
5750 	eager->tcp_closemp_used = B_TRUE;
5751 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5752 	mp1 = &eager->tcp_closemp;
5753 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5754 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5755 
5756 	/*
5757 	 * If a connection already exists, send the mp to that connections so
5758 	 * that it can be appropriately dealt with.
5759 	 */
5760 	ipst = tcps->tcps_netstack->netstack_ip;
5761 
5762 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5763 		if (!IPCL_IS_CONNECTED(econnp)) {
5764 			/*
5765 			 * Something bad happened. ipcl_conn_insert()
5766 			 * failed because a connection already existed
5767 			 * in connected hash but we can't find it
5768 			 * anymore (someone blew it away). Just
5769 			 * free this message and hopefully remote
5770 			 * will retransmit at which time the SYN can be
5771 			 * treated as a new connection or dealth with
5772 			 * a TH_RST if a connection already exists.
5773 			 */
5774 			CONN_DEC_REF(econnp);
5775 			freemsg(mp);
5776 		} else {
5777 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5778 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5779 		}
5780 	} else {
5781 		/* Nobody wants this packet */
5782 		freemsg(mp);
5783 	}
5784 	return;
5785 error3:
5786 	CONN_DEC_REF(econnp);
5787 error2:
5788 	freemsg(mp);
5789 }
5790 
5791 /*
5792  * In an ideal case of vertical partition in NUMA architecture, its
5793  * beneficial to have the listener and all the incoming connections
5794  * tied to the same squeue. The other constraint is that incoming
5795  * connections should be tied to the squeue attached to interrupted
5796  * CPU for obvious locality reason so this leaves the listener to
5797  * be tied to the same squeue. Our only problem is that when listener
5798  * is binding, the CPU that will get interrupted by the NIC whose
5799  * IP address the listener is binding to is not even known. So
5800  * the code below allows us to change that binding at the time the
5801  * CPU is interrupted by virtue of incoming connection's squeue.
5802  *
5803  * This is usefull only in case of a listener bound to a specific IP
5804  * address. For other kind of listeners, they get bound the
5805  * very first time and there is no attempt to rebind them.
5806  */
5807 void
5808 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5809 {
5810 	conn_t		*connp = (conn_t *)arg;
5811 	squeue_t	*sqp = (squeue_t *)arg2;
5812 	squeue_t	*new_sqp;
5813 	uint32_t	conn_flags;
5814 
5815 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5816 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5817 	} else {
5818 		goto done;
5819 	}
5820 
5821 	if (connp->conn_fanout == NULL)
5822 		goto done;
5823 
5824 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5825 		mutex_enter(&connp->conn_fanout->connf_lock);
5826 		mutex_enter(&connp->conn_lock);
5827 		/*
5828 		 * No one from read or write side can access us now
5829 		 * except for already queued packets on this squeue.
5830 		 * But since we haven't changed the squeue yet, they
5831 		 * can't execute. If they are processed after we have
5832 		 * changed the squeue, they are sent back to the
5833 		 * correct squeue down below.
5834 		 * But a listner close can race with processing of
5835 		 * incoming SYN. If incoming SYN processing changes
5836 		 * the squeue then the listener close which is waiting
5837 		 * to enter the squeue would operate on the wrong
5838 		 * squeue. Hence we don't change the squeue here unless
5839 		 * the refcount is exactly the minimum refcount. The
5840 		 * minimum refcount of 4 is counted as - 1 each for
5841 		 * TCP and IP, 1 for being in the classifier hash, and
5842 		 * 1 for the mblk being processed.
5843 		 */
5844 
5845 		if (connp->conn_ref != 4 ||
5846 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5847 			mutex_exit(&connp->conn_lock);
5848 			mutex_exit(&connp->conn_fanout->connf_lock);
5849 			goto done;
5850 		}
5851 		if (connp->conn_sqp != new_sqp) {
5852 			while (connp->conn_sqp != new_sqp)
5853 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5854 		}
5855 
5856 		do {
5857 			conn_flags = connp->conn_flags;
5858 			conn_flags |= IPCL_FULLY_BOUND;
5859 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5860 			    conn_flags);
5861 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5862 
5863 		mutex_exit(&connp->conn_fanout->connf_lock);
5864 		mutex_exit(&connp->conn_lock);
5865 	}
5866 
5867 done:
5868 	if (connp->conn_sqp != sqp) {
5869 		CONN_INC_REF(connp);
5870 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5871 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5872 	} else {
5873 		tcp_conn_request(connp, mp, sqp);
5874 	}
5875 }
5876 
5877 /*
5878  * Successful connect request processing begins when our client passes
5879  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5880  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5881  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5882  *   upstream <- tcp_rput()		<- IP
5883  * After various error checks are completed, tcp_tpi_connect() lays
5884  * the target address and port into the composite header template,
5885  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5886  * request followed by an IRE request, and passes the three mblk message
5887  * down to IP looking like this:
5888  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5889  * Processing continues in tcp_rput() when we receive the following message:
5890  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5891  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5892  * to fire off the connection request, and then passes the T_OK_ACK mblk
5893  * upstream that we filled in below.  There are, of course, numerous
5894  * error conditions along the way which truncate the processing described
5895  * above.
5896  */
5897 static void
5898 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5899 {
5900 	sin_t		*sin;
5901 	queue_t		*q = tcp->tcp_wq;
5902 	struct T_conn_req	*tcr;
5903 	struct sockaddr	*sa;
5904 	socklen_t	len;
5905 	int		error;
5906 	cred_t		*cr;
5907 	pid_t		cpid;
5908 
5909 	/*
5910 	 * All Solaris components should pass a db_credp
5911 	 * for this TPI message, hence we ASSERT.
5912 	 * But in case there is some other M_PROTO that looks
5913 	 * like a TPI message sent by some other kernel
5914 	 * component, we check and return an error.
5915 	 */
5916 	cr = msg_getcred(mp, &cpid);
5917 	ASSERT(cr != NULL);
5918 	if (cr == NULL) {
5919 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5920 		return;
5921 	}
5922 
5923 	tcr = (struct T_conn_req *)mp->b_rptr;
5924 
5925 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5926 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5927 		tcp_err_ack(tcp, mp, TPROTO, 0);
5928 		return;
5929 	}
5930 
5931 	/*
5932 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5933 	 * will always have that to send up.  Otherwise, we need to do
5934 	 * special handling in case the allocation fails at that time.
5935 	 * If the end point is TPI, the tcp_t can be reused and the
5936 	 * tcp_ordrel_mp may be allocated already.
5937 	 */
5938 	if (tcp->tcp_ordrel_mp == NULL) {
5939 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5940 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5941 			return;
5942 		}
5943 	}
5944 
5945 	/*
5946 	 * Determine packet type based on type of address passed in
5947 	 * the request should contain an IPv4 or IPv6 address.
5948 	 * Make sure that address family matches the type of
5949 	 * family of the the address passed down
5950 	 */
5951 	switch (tcr->DEST_length) {
5952 	default:
5953 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5954 		return;
5955 
5956 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5957 		/*
5958 		 * XXX: The check for valid DEST_length was not there
5959 		 * in earlier releases and some buggy
5960 		 * TLI apps (e.g Sybase) got away with not feeding
5961 		 * in sin_zero part of address.
5962 		 * We allow that bug to keep those buggy apps humming.
5963 		 * Test suites require the check on DEST_length.
5964 		 * We construct a new mblk with valid DEST_length
5965 		 * free the original so the rest of the code does
5966 		 * not have to keep track of this special shorter
5967 		 * length address case.
5968 		 */
5969 		mblk_t *nmp;
5970 		struct T_conn_req *ntcr;
5971 		sin_t *nsin;
5972 
5973 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5974 		    tcr->OPT_length, BPRI_HI);
5975 		if (nmp == NULL) {
5976 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5977 			return;
5978 		}
5979 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5980 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5981 		ntcr->PRIM_type = T_CONN_REQ;
5982 		ntcr->DEST_length = sizeof (sin_t);
5983 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5984 
5985 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5986 		*nsin = sin_null;
5987 		/* Get pointer to shorter address to copy from original mp */
5988 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5989 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5990 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5991 			freemsg(nmp);
5992 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5993 			return;
5994 		}
5995 		nsin->sin_family = sin->sin_family;
5996 		nsin->sin_port = sin->sin_port;
5997 		nsin->sin_addr = sin->sin_addr;
5998 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5999 		nmp->b_wptr = (uchar_t *)&nsin[1];
6000 		if (tcr->OPT_length != 0) {
6001 			ntcr->OPT_length = tcr->OPT_length;
6002 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6003 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6004 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6005 			    tcr->OPT_length);
6006 			nmp->b_wptr += tcr->OPT_length;
6007 		}
6008 		freemsg(mp);	/* original mp freed */
6009 		mp = nmp;	/* re-initialize original variables */
6010 		tcr = ntcr;
6011 	}
6012 	/* FALLTHRU */
6013 
6014 	case sizeof (sin_t):
6015 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6016 		    sizeof (sin_t));
6017 		len = sizeof (sin_t);
6018 		break;
6019 
6020 	case sizeof (sin6_t):
6021 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6022 		    sizeof (sin6_t));
6023 		len = sizeof (sin6_t);
6024 		break;
6025 	}
6026 
6027 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6028 	if (error != 0) {
6029 		tcp_err_ack(tcp, mp, TSYSERR, error);
6030 		return;
6031 	}
6032 
6033 	/*
6034 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6035 	 * should key on their sequence number and cut them loose.
6036 	 */
6037 
6038 	/*
6039 	 * If options passed in, feed it for verification and handling
6040 	 */
6041 	if (tcr->OPT_length != 0) {
6042 		mblk_t	*ok_mp;
6043 		mblk_t	*discon_mp;
6044 		mblk_t  *conn_opts_mp;
6045 		int t_error, sys_error, do_disconnect;
6046 
6047 		conn_opts_mp = NULL;
6048 
6049 		if (tcp_conprim_opt_process(tcp, mp,
6050 		    &do_disconnect, &t_error, &sys_error) < 0) {
6051 			if (do_disconnect) {
6052 				ASSERT(t_error == 0 && sys_error == 0);
6053 				discon_mp = mi_tpi_discon_ind(NULL,
6054 				    ECONNREFUSED, 0);
6055 				if (!discon_mp) {
6056 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6057 					    TSYSERR, ENOMEM);
6058 					return;
6059 				}
6060 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6061 				if (!ok_mp) {
6062 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6063 					    TSYSERR, ENOMEM);
6064 					return;
6065 				}
6066 				qreply(q, ok_mp);
6067 				qreply(q, discon_mp); /* no flush! */
6068 			} else {
6069 				ASSERT(t_error != 0);
6070 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6071 				    sys_error);
6072 			}
6073 			return;
6074 		}
6075 		/*
6076 		 * Success in setting options, the mp option buffer represented
6077 		 * by OPT_length/offset has been potentially modified and
6078 		 * contains results of option processing. We copy it in
6079 		 * another mp to save it for potentially influencing returning
6080 		 * it in T_CONN_CONN.
6081 		 */
6082 		if (tcr->OPT_length != 0) { /* there are resulting options */
6083 			conn_opts_mp = copyb(mp);
6084 			if (!conn_opts_mp) {
6085 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6086 				    TSYSERR, ENOMEM);
6087 				return;
6088 			}
6089 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6090 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6091 			/*
6092 			 * Note:
6093 			 * These resulting option negotiation can include any
6094 			 * end-to-end negotiation options but there no such
6095 			 * thing (yet?) in our TCP/IP.
6096 			 */
6097 		}
6098 	}
6099 
6100 	/* call the non-TPI version */
6101 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
6102 	if (error < 0) {
6103 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6104 	} else if (error > 0) {
6105 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6106 	} else {
6107 		mp = mi_tpi_ok_ack_alloc(mp);
6108 	}
6109 
6110 	/*
6111 	 * Note: Code below is the "failure" case
6112 	 */
6113 	/* return error ack and blow away saved option results if any */
6114 connect_failed:
6115 	if (mp != NULL)
6116 		putnext(tcp->tcp_rq, mp);
6117 	else {
6118 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6119 		    TSYSERR, ENOMEM);
6120 	}
6121 }
6122 
6123 /*
6124  * Handle connect to IPv4 destinations, including connections for AF_INET6
6125  * sockets connecting to IPv4 mapped IPv6 destinations.
6126  */
6127 static int
6128 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6129     uint_t srcid, cred_t *cr, pid_t pid)
6130 {
6131 	tcph_t	*tcph;
6132 	mblk_t	*mp;
6133 	ipaddr_t dstaddr = *dstaddrp;
6134 	int32_t	oldstate;
6135 	uint16_t lport;
6136 	int	error = 0;
6137 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6138 
6139 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6140 
6141 	/* Check for attempt to connect to INADDR_ANY */
6142 	if (dstaddr == INADDR_ANY)  {
6143 		/*
6144 		 * SunOS 4.x and 4.3 BSD allow an application
6145 		 * to connect a TCP socket to INADDR_ANY.
6146 		 * When they do this, the kernel picks the
6147 		 * address of one interface and uses it
6148 		 * instead.  The kernel usually ends up
6149 		 * picking the address of the loopback
6150 		 * interface.  This is an undocumented feature.
6151 		 * However, we provide the same thing here
6152 		 * in order to have source and binary
6153 		 * compatibility with SunOS 4.x.
6154 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6155 		 * generate the T_CONN_CON.
6156 		 */
6157 		dstaddr = htonl(INADDR_LOOPBACK);
6158 		*dstaddrp = dstaddr;
6159 	}
6160 
6161 	/* Handle __sin6_src_id if socket not bound to an IP address */
6162 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6163 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6164 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6165 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6166 		    tcp->tcp_ipha->ipha_src);
6167 	}
6168 
6169 	/*
6170 	 * Don't let an endpoint connect to itself.  Note that
6171 	 * the test here does not catch the case where the
6172 	 * source IP addr was left unspecified by the user. In
6173 	 * this case, the source addr is set in tcp_adapt_ire()
6174 	 * using the reply to the T_BIND message that we send
6175 	 * down to IP here and the check is repeated in tcp_rput_other.
6176 	 */
6177 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6178 	    dstport == tcp->tcp_lport) {
6179 		error = -TBADADDR;
6180 		goto failed;
6181 	}
6182 
6183 	/*
6184 	 * Verify the destination is allowed to receive packets
6185 	 * at the security label of the connection we are initiating.
6186 	 * tsol_check_dest() may create a new effective cred for this
6187 	 * connection with a modified label or label flags.
6188 	 */
6189 	if (is_system_labeled()) {
6190 		ASSERT(tcp->tcp_connp->conn_effective_cred == NULL);
6191 		if ((error = tsol_check_dest(CONN_CRED(tcp->tcp_connp),
6192 		    &dstaddr, IPV4_VERSION, tcp->tcp_connp->conn_mac_exempt,
6193 		    &tcp->tcp_connp->conn_effective_cred)) != 0) {
6194 			if (error != EHOSTUNREACH)
6195 				error = -TSYSERR;
6196 			goto failed;
6197 		}
6198 	}
6199 
6200 	tcp->tcp_ipha->ipha_dst = dstaddr;
6201 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6202 
6203 	/*
6204 	 * Massage a source route if any putting the first hop
6205 	 * in iph_dst. Compute a starting value for the checksum which
6206 	 * takes into account that the original iph_dst should be
6207 	 * included in the checksum but that ip will include the
6208 	 * first hop in the source route in the tcp checksum.
6209 	 */
6210 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6211 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6212 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6213 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6214 	if ((int)tcp->tcp_sum < 0)
6215 		tcp->tcp_sum--;
6216 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6217 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6218 	    (tcp->tcp_sum >> 16));
6219 	tcph = tcp->tcp_tcph;
6220 	*(uint16_t *)tcph->th_fport = dstport;
6221 	tcp->tcp_fport = dstport;
6222 
6223 	oldstate = tcp->tcp_state;
6224 	/*
6225 	 * At this point the remote destination address and remote port fields
6226 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6227 	 * have to see which state tcp was in so we can take apropriate action.
6228 	 */
6229 	if (oldstate == TCPS_IDLE) {
6230 		/*
6231 		 * We support a quick connect capability here, allowing
6232 		 * clients to transition directly from IDLE to SYN_SENT
6233 		 * tcp_bindi will pick an unused port, insert the connection
6234 		 * in the bind hash and transition to BOUND state.
6235 		 */
6236 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6237 		    tcp, B_TRUE);
6238 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6239 		    B_FALSE, B_FALSE);
6240 		if (lport == 0) {
6241 			error = -TNOADDR;
6242 			goto failed;
6243 		}
6244 	}
6245 	tcp->tcp_state = TCPS_SYN_SENT;
6246 
6247 	mp = allocb(sizeof (ire_t), BPRI_HI);
6248 	if (mp == NULL) {
6249 		tcp->tcp_state = oldstate;
6250 		error = ENOMEM;
6251 		goto failed;
6252 	}
6253 
6254 	mp->b_wptr += sizeof (ire_t);
6255 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6256 	tcp->tcp_hard_binding = 1;
6257 
6258 	/*
6259 	 * We need to make sure that the conn_recv is set to a non-null
6260 	 * value before we insert the conn_t into the classifier table.
6261 	 * This is to avoid a race with an incoming packet which does
6262 	 * an ipcl_classify().
6263 	 */
6264 	tcp->tcp_connp->conn_recv = tcp_input;
6265 
6266 	if (tcp->tcp_family == AF_INET) {
6267 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6268 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6269 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6270 	} else {
6271 		in6_addr_t v6src;
6272 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6273 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6274 		} else {
6275 			v6src = tcp->tcp_ip6h->ip6_src;
6276 		}
6277 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6278 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6279 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6280 	}
6281 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6282 	tcp->tcp_active_open = 1;
6283 
6284 
6285 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6286 failed:
6287 	/* return error ack and blow away saved option results if any */
6288 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6289 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6290 	return (error);
6291 }
6292 
6293 /*
6294  * Handle connect to IPv6 destinations.
6295  */
6296 static int
6297 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6298     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6299 {
6300 	tcph_t	*tcph;
6301 	mblk_t	*mp;
6302 	ip6_rthdr_t *rth;
6303 	int32_t  oldstate;
6304 	uint16_t lport;
6305 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6306 	int	error = 0;
6307 	conn_t	*connp = tcp->tcp_connp;
6308 
6309 	ASSERT(tcp->tcp_family == AF_INET6);
6310 
6311 	/*
6312 	 * If we're here, it means that the destination address is a native
6313 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6314 	 * reason why it might not be IPv6 is if the socket was bound to an
6315 	 * IPv4-mapped IPv6 address.
6316 	 */
6317 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6318 		return (-TBADADDR);
6319 	}
6320 
6321 	/*
6322 	 * Interpret a zero destination to mean loopback.
6323 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6324 	 * generate the T_CONN_CON.
6325 	 */
6326 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6327 		*dstaddrp = ipv6_loopback;
6328 	}
6329 
6330 	/* Handle __sin6_src_id if socket not bound to an IP address */
6331 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6332 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6333 		    connp->conn_zoneid, tcps->tcps_netstack);
6334 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6335 	}
6336 
6337 	/*
6338 	 * Take care of the scope_id now and add ip6i_t
6339 	 * if ip6i_t is not already allocated through TCP
6340 	 * sticky options. At this point tcp_ip6h does not
6341 	 * have dst info, thus use dstaddrp.
6342 	 */
6343 	if (scope_id != 0 &&
6344 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6345 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6346 		ip6i_t  *ip6i;
6347 
6348 		ipp->ipp_ifindex = scope_id;
6349 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6350 
6351 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6352 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6353 			/* Already allocated */
6354 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6355 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6356 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6357 		} else {
6358 			int reterr;
6359 
6360 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6361 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6362 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6363 			reterr = tcp_build_hdrs(tcp);
6364 			if (reterr != 0)
6365 				goto failed;
6366 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6367 		}
6368 	}
6369 
6370 	/*
6371 	 * Don't let an endpoint connect to itself.  Note that
6372 	 * the test here does not catch the case where the
6373 	 * source IP addr was left unspecified by the user. In
6374 	 * this case, the source addr is set in tcp_adapt_ire()
6375 	 * using the reply to the T_BIND message that we send
6376 	 * down to IP here and the check is repeated in tcp_rput_other.
6377 	 */
6378 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6379 	    (dstport == tcp->tcp_lport)) {
6380 		error = -TBADADDR;
6381 		goto failed;
6382 	}
6383 
6384 	/*
6385 	 * Verify the destination is allowed to receive packets
6386 	 * at the security label of the connection we are initiating.
6387 	 * check_dest may create a new effective cred for this
6388 	 * connection with a modified label or label flags.
6389 	 */
6390 	if (is_system_labeled()) {
6391 		ASSERT(tcp->tcp_connp->conn_effective_cred == NULL);
6392 		if ((error = tsol_check_dest(CONN_CRED(tcp->tcp_connp),
6393 		    dstaddrp, IPV6_VERSION, tcp->tcp_connp->conn_mac_exempt,
6394 		    &tcp->tcp_connp->conn_effective_cred)) != 0) {
6395 			if (error != EHOSTUNREACH)
6396 				error = -TSYSERR;
6397 			goto failed;
6398 		}
6399 	}
6400 
6401 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6402 	tcp->tcp_remote_v6 = *dstaddrp;
6403 	tcp->tcp_ip6h->ip6_vcf =
6404 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6405 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6406 
6407 	/*
6408 	 * Massage a routing header (if present) putting the first hop
6409 	 * in ip6_dst. Compute a starting value for the checksum which
6410 	 * takes into account that the original ip6_dst should be
6411 	 * included in the checksum but that ip will include the
6412 	 * first hop in the source route in the tcp checksum.
6413 	 */
6414 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6415 	if (rth != NULL) {
6416 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6417 		    tcps->tcps_netstack);
6418 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6419 		    (tcp->tcp_sum >> 16));
6420 	} else {
6421 		tcp->tcp_sum = 0;
6422 	}
6423 
6424 	tcph = tcp->tcp_tcph;
6425 	*(uint16_t *)tcph->th_fport = dstport;
6426 	tcp->tcp_fport = dstport;
6427 
6428 	oldstate = tcp->tcp_state;
6429 	/*
6430 	 * At this point the remote destination address and remote port fields
6431 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6432 	 * have to see which state tcp was in so we can take apropriate action.
6433 	 */
6434 	if (oldstate == TCPS_IDLE) {
6435 		/*
6436 		 * We support a quick connect capability here, allowing
6437 		 * clients to transition directly from IDLE to SYN_SENT
6438 		 * tcp_bindi will pick an unused port, insert the connection
6439 		 * in the bind hash and transition to BOUND state.
6440 		 */
6441 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6442 		    tcp, B_TRUE);
6443 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6444 		    B_FALSE, B_FALSE);
6445 		if (lport == 0) {
6446 			error = -TNOADDR;
6447 			goto failed;
6448 		}
6449 	}
6450 	tcp->tcp_state = TCPS_SYN_SENT;
6451 
6452 	mp = allocb(sizeof (ire_t), BPRI_HI);
6453 	if (mp != NULL) {
6454 		in6_addr_t v6src;
6455 
6456 		mp->b_wptr += sizeof (ire_t);
6457 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6458 
6459 		tcp->tcp_hard_binding = 1;
6460 
6461 		/*
6462 		 * We need to make sure that the conn_recv is set to a non-null
6463 		 * value before we insert the conn_t into the classifier table.
6464 		 * This is to avoid a race with an incoming packet which does
6465 		 * an ipcl_classify().
6466 		 */
6467 		tcp->tcp_connp->conn_recv = tcp_input;
6468 
6469 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6470 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6471 		} else {
6472 			v6src = tcp->tcp_ip6h->ip6_src;
6473 		}
6474 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6475 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6476 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6477 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6478 		tcp->tcp_active_open = 1;
6479 
6480 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6481 	}
6482 	/* Error case */
6483 	tcp->tcp_state = oldstate;
6484 	error = ENOMEM;
6485 
6486 failed:
6487 	/* return error ack and blow away saved option results if any */
6488 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6489 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6490 	return (error);
6491 }
6492 
6493 /*
6494  * We need a stream q for detached closing tcp connections
6495  * to use.  Our client hereby indicates that this q is the
6496  * one to use.
6497  */
6498 static void
6499 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6500 {
6501 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6502 	queue_t	*q = tcp->tcp_wq;
6503 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6504 
6505 #ifdef NS_DEBUG
6506 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6507 	    tcps->tcps_netstack->netstack_stackid);
6508 #endif
6509 	mp->b_datap->db_type = M_IOCACK;
6510 	iocp->ioc_count = 0;
6511 	mutex_enter(&tcps->tcps_g_q_lock);
6512 	if (tcps->tcps_g_q != NULL) {
6513 		mutex_exit(&tcps->tcps_g_q_lock);
6514 		iocp->ioc_error = EALREADY;
6515 	} else {
6516 		int error = 0;
6517 		conn_t *connp = tcp->tcp_connp;
6518 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6519 
6520 		tcps->tcps_g_q = tcp->tcp_rq;
6521 		mutex_exit(&tcps->tcps_g_q_lock);
6522 		iocp->ioc_error = 0;
6523 		iocp->ioc_rval = 0;
6524 		/*
6525 		 * We are passing tcp_sticky_ipp as NULL
6526 		 * as it is not useful for tcp_default queue
6527 		 *
6528 		 * Set conn_recv just in case.
6529 		 */
6530 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6531 
6532 		ASSERT(connp->conn_af_isv6);
6533 		connp->conn_ulp = IPPROTO_TCP;
6534 
6535 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6536 		    NULL || connp->conn_mac_exempt) {
6537 			error = -TBADADDR;
6538 		} else {
6539 			connp->conn_srcv6 = ipv6_all_zeros;
6540 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6541 		}
6542 
6543 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6544 	}
6545 	qreply(q, mp);
6546 }
6547 
6548 static int
6549 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6550 {
6551 	tcp_t	*ltcp = NULL;
6552 	conn_t	*connp;
6553 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6554 
6555 	/*
6556 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6557 	 * when the stream is in BOUND state. Do not send a reset,
6558 	 * since the destination IP address is not valid, and it can
6559 	 * be the initialized value of all zeros (broadcast address).
6560 	 *
6561 	 * XXX There won't be any pending bind request to IP.
6562 	 */
6563 	if (tcp->tcp_state <= TCPS_BOUND) {
6564 		if (tcp->tcp_debug) {
6565 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6566 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6567 		}
6568 		return (TOUTSTATE);
6569 	}
6570 
6571 
6572 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6573 
6574 		/*
6575 		 * According to TPI, for non-listeners, ignore seqnum
6576 		 * and disconnect.
6577 		 * Following interpretation of -1 seqnum is historical
6578 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6579 		 * a valid seqnum should not be -1).
6580 		 *
6581 		 *	-1 means disconnect everything
6582 		 *	regardless even on a listener.
6583 		 */
6584 
6585 		int old_state = tcp->tcp_state;
6586 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6587 
6588 		/*
6589 		 * The connection can't be on the tcp_time_wait_head list
6590 		 * since it is not detached.
6591 		 */
6592 		ASSERT(tcp->tcp_time_wait_next == NULL);
6593 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6594 		ASSERT(tcp->tcp_time_wait_expire == 0);
6595 		ltcp = NULL;
6596 		/*
6597 		 * If it used to be a listener, check to make sure no one else
6598 		 * has taken the port before switching back to LISTEN state.
6599 		 */
6600 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6601 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6602 			    tcp->tcp_ipha->ipha_src,
6603 			    tcp->tcp_connp->conn_zoneid, ipst);
6604 			if (connp != NULL)
6605 				ltcp = connp->conn_tcp;
6606 		} else {
6607 			/* Allow tcp_bound_if listeners? */
6608 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6609 			    &tcp->tcp_ip6h->ip6_src, 0,
6610 			    tcp->tcp_connp->conn_zoneid, ipst);
6611 			if (connp != NULL)
6612 				ltcp = connp->conn_tcp;
6613 		}
6614 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6615 			tcp->tcp_state = TCPS_LISTEN;
6616 		} else if (old_state > TCPS_BOUND) {
6617 			tcp->tcp_conn_req_max = 0;
6618 			tcp->tcp_state = TCPS_BOUND;
6619 		}
6620 		if (ltcp != NULL)
6621 			CONN_DEC_REF(ltcp->tcp_connp);
6622 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6623 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6624 		} else if (old_state == TCPS_ESTABLISHED ||
6625 		    old_state == TCPS_CLOSE_WAIT) {
6626 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6627 		}
6628 
6629 		if (tcp->tcp_fused)
6630 			tcp_unfuse(tcp);
6631 
6632 		mutex_enter(&tcp->tcp_eager_lock);
6633 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6634 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6635 			tcp_eager_cleanup(tcp, 0);
6636 		}
6637 		mutex_exit(&tcp->tcp_eager_lock);
6638 
6639 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6640 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6641 
6642 		tcp_reinit(tcp);
6643 
6644 		return (0);
6645 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6646 		return (TBADSEQ);
6647 	}
6648 	return (0);
6649 }
6650 
6651 /*
6652  * Our client hereby directs us to reject the connection request
6653  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6654  * of sending the appropriate RST, not an ICMP error.
6655  */
6656 static void
6657 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6658 {
6659 	t_scalar_t seqnum;
6660 	int	error;
6661 
6662 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6663 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6664 		tcp_err_ack(tcp, mp, TPROTO, 0);
6665 		return;
6666 	}
6667 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6668 	error = tcp_disconnect_common(tcp, seqnum);
6669 	if (error != 0)
6670 		tcp_err_ack(tcp, mp, error, 0);
6671 	else {
6672 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6673 			/* Send M_FLUSH according to TPI */
6674 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6675 		}
6676 		mp = mi_tpi_ok_ack_alloc(mp);
6677 		if (mp)
6678 			putnext(tcp->tcp_rq, mp);
6679 	}
6680 }
6681 
6682 /*
6683  * Diagnostic routine used to return a string associated with the tcp state.
6684  * Note that if the caller does not supply a buffer, it will use an internal
6685  * static string.  This means that if multiple threads call this function at
6686  * the same time, output can be corrupted...  Note also that this function
6687  * does not check the size of the supplied buffer.  The caller has to make
6688  * sure that it is big enough.
6689  */
6690 static char *
6691 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6692 {
6693 	char		buf1[30];
6694 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6695 	char		*buf;
6696 	char		*cp;
6697 	in6_addr_t	local, remote;
6698 	char		local_addrbuf[INET6_ADDRSTRLEN];
6699 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6700 
6701 	if (sup_buf != NULL)
6702 		buf = sup_buf;
6703 	else
6704 		buf = priv_buf;
6705 
6706 	if (tcp == NULL)
6707 		return ("NULL_TCP");
6708 	switch (tcp->tcp_state) {
6709 	case TCPS_CLOSED:
6710 		cp = "TCP_CLOSED";
6711 		break;
6712 	case TCPS_IDLE:
6713 		cp = "TCP_IDLE";
6714 		break;
6715 	case TCPS_BOUND:
6716 		cp = "TCP_BOUND";
6717 		break;
6718 	case TCPS_LISTEN:
6719 		cp = "TCP_LISTEN";
6720 		break;
6721 	case TCPS_SYN_SENT:
6722 		cp = "TCP_SYN_SENT";
6723 		break;
6724 	case TCPS_SYN_RCVD:
6725 		cp = "TCP_SYN_RCVD";
6726 		break;
6727 	case TCPS_ESTABLISHED:
6728 		cp = "TCP_ESTABLISHED";
6729 		break;
6730 	case TCPS_CLOSE_WAIT:
6731 		cp = "TCP_CLOSE_WAIT";
6732 		break;
6733 	case TCPS_FIN_WAIT_1:
6734 		cp = "TCP_FIN_WAIT_1";
6735 		break;
6736 	case TCPS_CLOSING:
6737 		cp = "TCP_CLOSING";
6738 		break;
6739 	case TCPS_LAST_ACK:
6740 		cp = "TCP_LAST_ACK";
6741 		break;
6742 	case TCPS_FIN_WAIT_2:
6743 		cp = "TCP_FIN_WAIT_2";
6744 		break;
6745 	case TCPS_TIME_WAIT:
6746 		cp = "TCP_TIME_WAIT";
6747 		break;
6748 	default:
6749 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6750 		cp = buf1;
6751 		break;
6752 	}
6753 	switch (format) {
6754 	case DISP_ADDR_AND_PORT:
6755 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6756 			/*
6757 			 * Note that we use the remote address in the tcp_b
6758 			 * structure.  This means that it will print out
6759 			 * the real destination address, not the next hop's
6760 			 * address if source routing is used.
6761 			 */
6762 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6763 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6764 
6765 		} else {
6766 			local = tcp->tcp_ip_src_v6;
6767 			remote = tcp->tcp_remote_v6;
6768 		}
6769 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6770 		    sizeof (local_addrbuf));
6771 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6772 		    sizeof (remote_addrbuf));
6773 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6774 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6775 		    ntohs(tcp->tcp_fport), cp);
6776 		break;
6777 	case DISP_PORT_ONLY:
6778 	default:
6779 		(void) mi_sprintf(buf, "[%u, %u] %s",
6780 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6781 		break;
6782 	}
6783 
6784 	return (buf);
6785 }
6786 
6787 /*
6788  * Called via squeue to get on to eager's perimeter. It sends a
6789  * TH_RST if eager is in the fanout table. The listener wants the
6790  * eager to disappear either by means of tcp_eager_blowoff() or
6791  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6792  * called (via squeue) if the eager cannot be inserted in the
6793  * fanout table in tcp_conn_request().
6794  */
6795 /* ARGSUSED */
6796 void
6797 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6798 {
6799 	conn_t	*econnp = (conn_t *)arg;
6800 	tcp_t	*eager = econnp->conn_tcp;
6801 	tcp_t	*listener = eager->tcp_listener;
6802 	tcp_stack_t	*tcps = eager->tcp_tcps;
6803 
6804 	/*
6805 	 * We could be called because listener is closing. Since
6806 	 * the eager is using listener's queue's, its not safe.
6807 	 * Better use the default queue just to send the TH_RST
6808 	 * out.
6809 	 */
6810 	ASSERT(tcps->tcps_g_q != NULL);
6811 	eager->tcp_rq = tcps->tcps_g_q;
6812 	eager->tcp_wq = WR(tcps->tcps_g_q);
6813 
6814 	/*
6815 	 * An eager's conn_fanout will be NULL if it's a duplicate
6816 	 * for an existing 4-tuples in the conn fanout table.
6817 	 * We don't want to send an RST out in such case.
6818 	 */
6819 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6820 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6821 		    eager, eager->tcp_snxt, 0, TH_RST);
6822 	}
6823 
6824 	/* We are here because listener wants this eager gone */
6825 	if (listener != NULL) {
6826 		mutex_enter(&listener->tcp_eager_lock);
6827 		tcp_eager_unlink(eager);
6828 		if (eager->tcp_tconnind_started) {
6829 			/*
6830 			 * The eager has sent a conn_ind up to the
6831 			 * listener but listener decides to close
6832 			 * instead. We need to drop the extra ref
6833 			 * placed on eager in tcp_rput_data() before
6834 			 * sending the conn_ind to listener.
6835 			 */
6836 			CONN_DEC_REF(econnp);
6837 		}
6838 		mutex_exit(&listener->tcp_eager_lock);
6839 		CONN_DEC_REF(listener->tcp_connp);
6840 	}
6841 
6842 	if (eager->tcp_state != TCPS_CLOSED)
6843 		tcp_close_detached(eager);
6844 }
6845 
6846 /*
6847  * Reset any eager connection hanging off this listener marked
6848  * with 'seqnum' and then reclaim it's resources.
6849  */
6850 static boolean_t
6851 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6852 {
6853 	tcp_t	*eager;
6854 	mblk_t 	*mp;
6855 	tcp_stack_t	*tcps = listener->tcp_tcps;
6856 
6857 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6858 	eager = listener;
6859 	mutex_enter(&listener->tcp_eager_lock);
6860 	do {
6861 		eager = eager->tcp_eager_next_q;
6862 		if (eager == NULL) {
6863 			mutex_exit(&listener->tcp_eager_lock);
6864 			return (B_FALSE);
6865 		}
6866 	} while (eager->tcp_conn_req_seqnum != seqnum);
6867 
6868 	if (eager->tcp_closemp_used) {
6869 		mutex_exit(&listener->tcp_eager_lock);
6870 		return (B_TRUE);
6871 	}
6872 	eager->tcp_closemp_used = B_TRUE;
6873 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6874 	CONN_INC_REF(eager->tcp_connp);
6875 	mutex_exit(&listener->tcp_eager_lock);
6876 	mp = &eager->tcp_closemp;
6877 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6878 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6879 	return (B_TRUE);
6880 }
6881 
6882 /*
6883  * Reset any eager connection hanging off this listener
6884  * and then reclaim it's resources.
6885  */
6886 static void
6887 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6888 {
6889 	tcp_t	*eager;
6890 	mblk_t	*mp;
6891 	tcp_stack_t	*tcps = listener->tcp_tcps;
6892 
6893 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6894 
6895 	if (!q0_only) {
6896 		/* First cleanup q */
6897 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6898 		eager = listener->tcp_eager_next_q;
6899 		while (eager != NULL) {
6900 			if (!eager->tcp_closemp_used) {
6901 				eager->tcp_closemp_used = B_TRUE;
6902 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6903 				CONN_INC_REF(eager->tcp_connp);
6904 				mp = &eager->tcp_closemp;
6905 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6906 				    tcp_eager_kill, eager->tcp_connp,
6907 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6908 			}
6909 			eager = eager->tcp_eager_next_q;
6910 		}
6911 	}
6912 	/* Then cleanup q0 */
6913 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6914 	eager = listener->tcp_eager_next_q0;
6915 	while (eager != listener) {
6916 		if (!eager->tcp_closemp_used) {
6917 			eager->tcp_closemp_used = B_TRUE;
6918 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6919 			CONN_INC_REF(eager->tcp_connp);
6920 			mp = &eager->tcp_closemp;
6921 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6922 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6923 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6924 		}
6925 		eager = eager->tcp_eager_next_q0;
6926 	}
6927 }
6928 
6929 /*
6930  * If we are an eager connection hanging off a listener that hasn't
6931  * formally accepted the connection yet, get off his list and blow off
6932  * any data that we have accumulated.
6933  */
6934 static void
6935 tcp_eager_unlink(tcp_t *tcp)
6936 {
6937 	tcp_t	*listener = tcp->tcp_listener;
6938 
6939 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6940 	ASSERT(listener != NULL);
6941 	if (tcp->tcp_eager_next_q0 != NULL) {
6942 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6943 
6944 		/* Remove the eager tcp from q0 */
6945 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6946 		    tcp->tcp_eager_prev_q0;
6947 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6948 		    tcp->tcp_eager_next_q0;
6949 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6950 		listener->tcp_conn_req_cnt_q0--;
6951 
6952 		tcp->tcp_eager_next_q0 = NULL;
6953 		tcp->tcp_eager_prev_q0 = NULL;
6954 
6955 		/*
6956 		 * Take the eager out, if it is in the list of droppable
6957 		 * eagers.
6958 		 */
6959 		MAKE_UNDROPPABLE(tcp);
6960 
6961 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6962 			/* we have timed out before */
6963 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6964 			listener->tcp_syn_rcvd_timeout--;
6965 		}
6966 	} else {
6967 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6968 		tcp_t	*prev = NULL;
6969 
6970 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6971 			if (tcpp[0] == tcp) {
6972 				if (listener->tcp_eager_last_q == tcp) {
6973 					/*
6974 					 * If we are unlinking the last
6975 					 * element on the list, adjust
6976 					 * tail pointer. Set tail pointer
6977 					 * to nil when list is empty.
6978 					 */
6979 					ASSERT(tcp->tcp_eager_next_q == NULL);
6980 					if (listener->tcp_eager_last_q ==
6981 					    listener->tcp_eager_next_q) {
6982 						listener->tcp_eager_last_q =
6983 						    NULL;
6984 					} else {
6985 						/*
6986 						 * We won't get here if there
6987 						 * is only one eager in the
6988 						 * list.
6989 						 */
6990 						ASSERT(prev != NULL);
6991 						listener->tcp_eager_last_q =
6992 						    prev;
6993 					}
6994 				}
6995 				tcpp[0] = tcp->tcp_eager_next_q;
6996 				tcp->tcp_eager_next_q = NULL;
6997 				tcp->tcp_eager_last_q = NULL;
6998 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6999 				listener->tcp_conn_req_cnt_q--;
7000 				break;
7001 			}
7002 			prev = tcpp[0];
7003 		}
7004 	}
7005 	tcp->tcp_listener = NULL;
7006 }
7007 
7008 /* Shorthand to generate and send TPI error acks to our client */
7009 static void
7010 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7011 {
7012 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7013 		putnext(tcp->tcp_rq, mp);
7014 }
7015 
7016 /* Shorthand to generate and send TPI error acks to our client */
7017 static void
7018 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7019     int t_error, int sys_error)
7020 {
7021 	struct T_error_ack	*teackp;
7022 
7023 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7024 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7025 		teackp = (struct T_error_ack *)mp->b_rptr;
7026 		teackp->ERROR_prim = primitive;
7027 		teackp->TLI_error = t_error;
7028 		teackp->UNIX_error = sys_error;
7029 		putnext(tcp->tcp_rq, mp);
7030 	}
7031 }
7032 
7033 /*
7034  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7035  * but instead the code relies on:
7036  * - the fact that the address of the array and its size never changes
7037  * - the atomic assignment of the elements of the array
7038  */
7039 /* ARGSUSED */
7040 static int
7041 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7042 {
7043 	int i;
7044 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7045 
7046 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7047 		if (tcps->tcps_g_epriv_ports[i] != 0)
7048 			(void) mi_mpprintf(mp, "%d ",
7049 			    tcps->tcps_g_epriv_ports[i]);
7050 	}
7051 	return (0);
7052 }
7053 
7054 /*
7055  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7056  * threads from changing it at the same time.
7057  */
7058 /* ARGSUSED */
7059 static int
7060 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7061     cred_t *cr)
7062 {
7063 	long	new_value;
7064 	int	i;
7065 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7066 
7067 	/*
7068 	 * Fail the request if the new value does not lie within the
7069 	 * port number limits.
7070 	 */
7071 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7072 	    new_value <= 0 || new_value >= 65536) {
7073 		return (EINVAL);
7074 	}
7075 
7076 	mutex_enter(&tcps->tcps_epriv_port_lock);
7077 	/* Check if the value is already in the list */
7078 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7079 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7080 			mutex_exit(&tcps->tcps_epriv_port_lock);
7081 			return (EEXIST);
7082 		}
7083 	}
7084 	/* Find an empty slot */
7085 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7086 		if (tcps->tcps_g_epriv_ports[i] == 0)
7087 			break;
7088 	}
7089 	if (i == tcps->tcps_g_num_epriv_ports) {
7090 		mutex_exit(&tcps->tcps_epriv_port_lock);
7091 		return (EOVERFLOW);
7092 	}
7093 	/* Set the new value */
7094 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7095 	mutex_exit(&tcps->tcps_epriv_port_lock);
7096 	return (0);
7097 }
7098 
7099 /*
7100  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7101  * threads from changing it at the same time.
7102  */
7103 /* ARGSUSED */
7104 static int
7105 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7106     cred_t *cr)
7107 {
7108 	long	new_value;
7109 	int	i;
7110 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7111 
7112 	/*
7113 	 * Fail the request if the new value does not lie within the
7114 	 * port number limits.
7115 	 */
7116 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7117 	    new_value >= 65536) {
7118 		return (EINVAL);
7119 	}
7120 
7121 	mutex_enter(&tcps->tcps_epriv_port_lock);
7122 	/* Check that the value is already in the list */
7123 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7124 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7125 			break;
7126 	}
7127 	if (i == tcps->tcps_g_num_epriv_ports) {
7128 		mutex_exit(&tcps->tcps_epriv_port_lock);
7129 		return (ESRCH);
7130 	}
7131 	/* Clear the value */
7132 	tcps->tcps_g_epriv_ports[i] = 0;
7133 	mutex_exit(&tcps->tcps_epriv_port_lock);
7134 	return (0);
7135 }
7136 
7137 /* Return the TPI/TLI equivalent of our current tcp_state */
7138 static int
7139 tcp_tpistate(tcp_t *tcp)
7140 {
7141 	switch (tcp->tcp_state) {
7142 	case TCPS_IDLE:
7143 		return (TS_UNBND);
7144 	case TCPS_LISTEN:
7145 		/*
7146 		 * Return whether there are outstanding T_CONN_IND waiting
7147 		 * for the matching T_CONN_RES. Therefore don't count q0.
7148 		 */
7149 		if (tcp->tcp_conn_req_cnt_q > 0)
7150 			return (TS_WRES_CIND);
7151 		else
7152 			return (TS_IDLE);
7153 	case TCPS_BOUND:
7154 		return (TS_IDLE);
7155 	case TCPS_SYN_SENT:
7156 		return (TS_WCON_CREQ);
7157 	case TCPS_SYN_RCVD:
7158 		/*
7159 		 * Note: assumption: this has to the active open SYN_RCVD.
7160 		 * The passive instance is detached in SYN_RCVD stage of
7161 		 * incoming connection processing so we cannot get request
7162 		 * for T_info_ack on it.
7163 		 */
7164 		return (TS_WACK_CRES);
7165 	case TCPS_ESTABLISHED:
7166 		return (TS_DATA_XFER);
7167 	case TCPS_CLOSE_WAIT:
7168 		return (TS_WREQ_ORDREL);
7169 	case TCPS_FIN_WAIT_1:
7170 		return (TS_WIND_ORDREL);
7171 	case TCPS_FIN_WAIT_2:
7172 		return (TS_WIND_ORDREL);
7173 
7174 	case TCPS_CLOSING:
7175 	case TCPS_LAST_ACK:
7176 	case TCPS_TIME_WAIT:
7177 	case TCPS_CLOSED:
7178 		/*
7179 		 * Following TS_WACK_DREQ7 is a rendition of "not
7180 		 * yet TS_IDLE" TPI state. There is no best match to any
7181 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7182 		 * choose a value chosen that will map to TLI/XTI level
7183 		 * state of TSTATECHNG (state is process of changing) which
7184 		 * captures what this dummy state represents.
7185 		 */
7186 		return (TS_WACK_DREQ7);
7187 	default:
7188 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7189 		    tcp->tcp_state, tcp_display(tcp, NULL,
7190 		    DISP_PORT_ONLY));
7191 		return (TS_UNBND);
7192 	}
7193 }
7194 
7195 static void
7196 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7197 {
7198 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7199 
7200 	if (tcp->tcp_family == AF_INET6)
7201 		*tia = tcp_g_t_info_ack_v6;
7202 	else
7203 		*tia = tcp_g_t_info_ack;
7204 	tia->CURRENT_state = tcp_tpistate(tcp);
7205 	tia->OPT_size = tcp_max_optsize;
7206 	if (tcp->tcp_mss == 0) {
7207 		/* Not yet set - tcp_open does not set mss */
7208 		if (tcp->tcp_ipversion == IPV4_VERSION)
7209 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7210 		else
7211 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7212 	} else {
7213 		tia->TIDU_size = tcp->tcp_mss;
7214 	}
7215 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7216 }
7217 
7218 static void
7219 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7220     t_uscalar_t cap_bits1)
7221 {
7222 	tcap->CAP_bits1 = 0;
7223 
7224 	if (cap_bits1 & TC1_INFO) {
7225 		tcp_copy_info(&tcap->INFO_ack, tcp);
7226 		tcap->CAP_bits1 |= TC1_INFO;
7227 	}
7228 
7229 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7230 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7231 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7232 	}
7233 
7234 }
7235 
7236 /*
7237  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7238  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7239  * tcp_g_t_info_ack.  The current state of the stream is copied from
7240  * tcp_state.
7241  */
7242 static void
7243 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7244 {
7245 	t_uscalar_t		cap_bits1;
7246 	struct T_capability_ack	*tcap;
7247 
7248 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7249 		freemsg(mp);
7250 		return;
7251 	}
7252 
7253 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7254 
7255 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7256 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7257 	if (mp == NULL)
7258 		return;
7259 
7260 	tcap = (struct T_capability_ack *)mp->b_rptr;
7261 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7262 
7263 	putnext(tcp->tcp_rq, mp);
7264 }
7265 
7266 /*
7267  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7268  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7269  * The current state of the stream is copied from tcp_state.
7270  */
7271 static void
7272 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7273 {
7274 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7275 	    T_INFO_ACK);
7276 	if (!mp) {
7277 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7278 		return;
7279 	}
7280 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7281 	putnext(tcp->tcp_rq, mp);
7282 }
7283 
7284 /* Respond to the TPI addr request */
7285 static void
7286 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7287 {
7288 	sin_t	*sin;
7289 	mblk_t	*ackmp;
7290 	struct T_addr_ack *taa;
7291 
7292 	/* Make it large enough for worst case */
7293 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7294 	    2 * sizeof (sin6_t), 1);
7295 	if (ackmp == NULL) {
7296 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7297 		return;
7298 	}
7299 
7300 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7301 		tcp_addr_req_ipv6(tcp, ackmp);
7302 		return;
7303 	}
7304 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7305 
7306 	bzero(taa, sizeof (struct T_addr_ack));
7307 	ackmp->b_wptr = (uchar_t *)&taa[1];
7308 
7309 	taa->PRIM_type = T_ADDR_ACK;
7310 	ackmp->b_datap->db_type = M_PCPROTO;
7311 
7312 	/*
7313 	 * Note: Following code assumes 32 bit alignment of basic
7314 	 * data structures like sin_t and struct T_addr_ack.
7315 	 */
7316 	if (tcp->tcp_state >= TCPS_BOUND) {
7317 		/*
7318 		 * Fill in local address
7319 		 */
7320 		taa->LOCADDR_length = sizeof (sin_t);
7321 		taa->LOCADDR_offset = sizeof (*taa);
7322 
7323 		sin = (sin_t *)&taa[1];
7324 
7325 		/* Fill zeroes and then intialize non-zero fields */
7326 		*sin = sin_null;
7327 
7328 		sin->sin_family = AF_INET;
7329 
7330 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7331 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7332 
7333 		ackmp->b_wptr = (uchar_t *)&sin[1];
7334 
7335 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7336 			/*
7337 			 * Fill in Remote address
7338 			 */
7339 			taa->REMADDR_length = sizeof (sin_t);
7340 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7341 			    taa->LOCADDR_length);
7342 
7343 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7344 			*sin = sin_null;
7345 			sin->sin_family = AF_INET;
7346 			sin->sin_addr.s_addr = tcp->tcp_remote;
7347 			sin->sin_port = tcp->tcp_fport;
7348 
7349 			ackmp->b_wptr = (uchar_t *)&sin[1];
7350 		}
7351 	}
7352 	putnext(tcp->tcp_rq, ackmp);
7353 }
7354 
7355 /* Assumes that tcp_addr_req gets enough space and alignment */
7356 static void
7357 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7358 {
7359 	sin6_t	*sin6;
7360 	struct T_addr_ack *taa;
7361 
7362 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7363 	ASSERT(OK_32PTR(ackmp->b_rptr));
7364 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7365 	    2 * sizeof (sin6_t));
7366 
7367 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7368 
7369 	bzero(taa, sizeof (struct T_addr_ack));
7370 	ackmp->b_wptr = (uchar_t *)&taa[1];
7371 
7372 	taa->PRIM_type = T_ADDR_ACK;
7373 	ackmp->b_datap->db_type = M_PCPROTO;
7374 
7375 	/*
7376 	 * Note: Following code assumes 32 bit alignment of basic
7377 	 * data structures like sin6_t and struct T_addr_ack.
7378 	 */
7379 	if (tcp->tcp_state >= TCPS_BOUND) {
7380 		/*
7381 		 * Fill in local address
7382 		 */
7383 		taa->LOCADDR_length = sizeof (sin6_t);
7384 		taa->LOCADDR_offset = sizeof (*taa);
7385 
7386 		sin6 = (sin6_t *)&taa[1];
7387 		*sin6 = sin6_null;
7388 
7389 		sin6->sin6_family = AF_INET6;
7390 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7391 		sin6->sin6_port = tcp->tcp_lport;
7392 
7393 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7394 
7395 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7396 			/*
7397 			 * Fill in Remote address
7398 			 */
7399 			taa->REMADDR_length = sizeof (sin6_t);
7400 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7401 			    taa->LOCADDR_length);
7402 
7403 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7404 			*sin6 = sin6_null;
7405 			sin6->sin6_family = AF_INET6;
7406 			sin6->sin6_flowinfo =
7407 			    tcp->tcp_ip6h->ip6_vcf &
7408 			    ~IPV6_VERS_AND_FLOW_MASK;
7409 			sin6->sin6_addr = tcp->tcp_remote_v6;
7410 			sin6->sin6_port = tcp->tcp_fport;
7411 
7412 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7413 		}
7414 	}
7415 	putnext(tcp->tcp_rq, ackmp);
7416 }
7417 
7418 /*
7419  * Handle reinitialization of a tcp structure.
7420  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7421  */
7422 static void
7423 tcp_reinit(tcp_t *tcp)
7424 {
7425 	mblk_t	*mp;
7426 	int 	err;
7427 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7428 
7429 	TCP_STAT(tcps, tcp_reinit_calls);
7430 
7431 	/* tcp_reinit should never be called for detached tcp_t's */
7432 	ASSERT(tcp->tcp_listener == NULL);
7433 	ASSERT((tcp->tcp_family == AF_INET &&
7434 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7435 	    (tcp->tcp_family == AF_INET6 &&
7436 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7437 	    tcp->tcp_ipversion == IPV6_VERSION)));
7438 
7439 	/* Cancel outstanding timers */
7440 	tcp_timers_stop(tcp);
7441 
7442 	/*
7443 	 * Reset everything in the state vector, after updating global
7444 	 * MIB data from instance counters.
7445 	 */
7446 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7447 	tcp->tcp_ibsegs = 0;
7448 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7449 	tcp->tcp_obsegs = 0;
7450 
7451 	tcp_close_mpp(&tcp->tcp_xmit_head);
7452 	if (tcp->tcp_snd_zcopy_aware)
7453 		tcp_zcopy_notify(tcp);
7454 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7455 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7456 	mutex_enter(&tcp->tcp_non_sq_lock);
7457 	if (tcp->tcp_flow_stopped &&
7458 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7459 		tcp_clrqfull(tcp);
7460 	}
7461 	mutex_exit(&tcp->tcp_non_sq_lock);
7462 	tcp_close_mpp(&tcp->tcp_reass_head);
7463 	tcp->tcp_reass_tail = NULL;
7464 	if (tcp->tcp_rcv_list != NULL) {
7465 		/* Free b_next chain */
7466 		tcp_close_mpp(&tcp->tcp_rcv_list);
7467 		tcp->tcp_rcv_last_head = NULL;
7468 		tcp->tcp_rcv_last_tail = NULL;
7469 		tcp->tcp_rcv_cnt = 0;
7470 	}
7471 	tcp->tcp_rcv_last_tail = NULL;
7472 
7473 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7474 		freemsg(mp);
7475 		tcp->tcp_urp_mp = NULL;
7476 	}
7477 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7478 		freemsg(mp);
7479 		tcp->tcp_urp_mark_mp = NULL;
7480 	}
7481 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7482 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7483 		freeb(tcp->tcp_fused_sigurg_mp);
7484 		tcp->tcp_fused_sigurg_mp = NULL;
7485 	}
7486 	if (tcp->tcp_ordrel_mp != NULL) {
7487 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7488 		freeb(tcp->tcp_ordrel_mp);
7489 		tcp->tcp_ordrel_mp = NULL;
7490 	}
7491 
7492 	/*
7493 	 * Following is a union with two members which are
7494 	 * identical types and size so the following cleanup
7495 	 * is enough.
7496 	 */
7497 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7498 
7499 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7500 
7501 	/*
7502 	 * The connection can't be on the tcp_time_wait_head list
7503 	 * since it is not detached.
7504 	 */
7505 	ASSERT(tcp->tcp_time_wait_next == NULL);
7506 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7507 	ASSERT(tcp->tcp_time_wait_expire == 0);
7508 
7509 	if (tcp->tcp_kssl_pending) {
7510 		tcp->tcp_kssl_pending = B_FALSE;
7511 
7512 		/* Don't reset if the initialized by bind. */
7513 		if (tcp->tcp_kssl_ent != NULL) {
7514 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7515 			    KSSL_NO_PROXY);
7516 		}
7517 	}
7518 	if (tcp->tcp_kssl_ctx != NULL) {
7519 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7520 		tcp->tcp_kssl_ctx = NULL;
7521 	}
7522 
7523 	/*
7524 	 * Reset/preserve other values
7525 	 */
7526 	tcp_reinit_values(tcp);
7527 	ipcl_hash_remove(tcp->tcp_connp);
7528 	conn_delete_ire(tcp->tcp_connp, NULL);
7529 	tcp_ipsec_cleanup(tcp);
7530 
7531 	if (tcp->tcp_connp->conn_effective_cred != NULL) {
7532 		crfree(tcp->tcp_connp->conn_effective_cred);
7533 		tcp->tcp_connp->conn_effective_cred = NULL;
7534 	}
7535 
7536 	if (tcp->tcp_conn_req_max != 0) {
7537 		/*
7538 		 * This is the case when a TLI program uses the same
7539 		 * transport end point to accept a connection.  This
7540 		 * makes the TCP both a listener and acceptor.  When
7541 		 * this connection is closed, we need to set the state
7542 		 * back to TCPS_LISTEN.  Make sure that the eager list
7543 		 * is reinitialized.
7544 		 *
7545 		 * Note that this stream is still bound to the four
7546 		 * tuples of the previous connection in IP.  If a new
7547 		 * SYN with different foreign address comes in, IP will
7548 		 * not find it and will send it to the global queue.  In
7549 		 * the global queue, TCP will do a tcp_lookup_listener()
7550 		 * to find this stream.  This works because this stream
7551 		 * is only removed from connected hash.
7552 		 *
7553 		 */
7554 		tcp->tcp_state = TCPS_LISTEN;
7555 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7556 		tcp->tcp_eager_next_drop_q0 = tcp;
7557 		tcp->tcp_eager_prev_drop_q0 = tcp;
7558 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7559 		if (tcp->tcp_family == AF_INET6) {
7560 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7561 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7562 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7563 		} else {
7564 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7565 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7566 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7567 		}
7568 	} else {
7569 		tcp->tcp_state = TCPS_BOUND;
7570 	}
7571 
7572 	/*
7573 	 * Initialize to default values
7574 	 * Can't fail since enough header template space already allocated
7575 	 * at open().
7576 	 */
7577 	err = tcp_init_values(tcp);
7578 	ASSERT(err == 0);
7579 	/* Restore state in tcp_tcph */
7580 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7581 	if (tcp->tcp_ipversion == IPV4_VERSION)
7582 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7583 	else
7584 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7585 	/*
7586 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7587 	 * since the lookup funcs can only lookup on tcp_t
7588 	 */
7589 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7590 
7591 	ASSERT(tcp->tcp_ptpbhn != NULL);
7592 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7593 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7594 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7595 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7596 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7597 }
7598 
7599 /*
7600  * Force values to zero that need be zero.
7601  * Do not touch values asociated with the BOUND or LISTEN state
7602  * since the connection will end up in that state after the reinit.
7603  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7604  * structure!
7605  */
7606 static void
7607 tcp_reinit_values(tcp)
7608 	tcp_t *tcp;
7609 {
7610 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7611 
7612 #ifndef	lint
7613 #define	DONTCARE(x)
7614 #define	PRESERVE(x)
7615 #else
7616 #define	DONTCARE(x)	((x) = (x))
7617 #define	PRESERVE(x)	((x) = (x))
7618 #endif	/* lint */
7619 
7620 	PRESERVE(tcp->tcp_bind_hash_port);
7621 	PRESERVE(tcp->tcp_bind_hash);
7622 	PRESERVE(tcp->tcp_ptpbhn);
7623 	PRESERVE(tcp->tcp_acceptor_hash);
7624 	PRESERVE(tcp->tcp_ptpahn);
7625 
7626 	/* Should be ASSERT NULL on these with new code! */
7627 	ASSERT(tcp->tcp_time_wait_next == NULL);
7628 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7629 	ASSERT(tcp->tcp_time_wait_expire == 0);
7630 	PRESERVE(tcp->tcp_state);
7631 	PRESERVE(tcp->tcp_rq);
7632 	PRESERVE(tcp->tcp_wq);
7633 
7634 	ASSERT(tcp->tcp_xmit_head == NULL);
7635 	ASSERT(tcp->tcp_xmit_last == NULL);
7636 	ASSERT(tcp->tcp_unsent == 0);
7637 	ASSERT(tcp->tcp_xmit_tail == NULL);
7638 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7639 
7640 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7641 	tcp->tcp_suna = 0;			/* Displayed in mib */
7642 	tcp->tcp_swnd = 0;
7643 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7644 
7645 	ASSERT(tcp->tcp_ibsegs == 0);
7646 	ASSERT(tcp->tcp_obsegs == 0);
7647 
7648 	if (tcp->tcp_iphc != NULL) {
7649 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7650 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7651 	}
7652 
7653 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7654 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7655 	DONTCARE(tcp->tcp_ipha);
7656 	DONTCARE(tcp->tcp_ip6h);
7657 	DONTCARE(tcp->tcp_ip_hdr_len);
7658 	DONTCARE(tcp->tcp_tcph);
7659 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7660 	tcp->tcp_valid_bits = 0;
7661 
7662 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7663 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7664 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7665 	tcp->tcp_last_rcv_lbolt = 0;
7666 
7667 	tcp->tcp_init_cwnd = 0;
7668 
7669 	tcp->tcp_urp_last_valid = 0;
7670 	tcp->tcp_hard_binding = 0;
7671 	tcp->tcp_hard_bound = 0;
7672 	PRESERVE(tcp->tcp_cred);
7673 	PRESERVE(tcp->tcp_cpid);
7674 	PRESERVE(tcp->tcp_open_time);
7675 	PRESERVE(tcp->tcp_exclbind);
7676 
7677 	tcp->tcp_fin_acked = 0;
7678 	tcp->tcp_fin_rcvd = 0;
7679 	tcp->tcp_fin_sent = 0;
7680 	tcp->tcp_ordrel_done = 0;
7681 
7682 	tcp->tcp_debug = 0;
7683 	tcp->tcp_dontroute = 0;
7684 	tcp->tcp_broadcast = 0;
7685 
7686 	tcp->tcp_useloopback = 0;
7687 	tcp->tcp_reuseaddr = 0;
7688 	tcp->tcp_oobinline = 0;
7689 	tcp->tcp_dgram_errind = 0;
7690 
7691 	tcp->tcp_detached = 0;
7692 	tcp->tcp_bind_pending = 0;
7693 	tcp->tcp_unbind_pending = 0;
7694 
7695 	tcp->tcp_snd_ws_ok = B_FALSE;
7696 	tcp->tcp_snd_ts_ok = B_FALSE;
7697 	tcp->tcp_linger = 0;
7698 	tcp->tcp_ka_enabled = 0;
7699 	tcp->tcp_zero_win_probe = 0;
7700 
7701 	tcp->tcp_loopback = 0;
7702 	tcp->tcp_refuse = 0;
7703 	tcp->tcp_localnet = 0;
7704 	tcp->tcp_syn_defense = 0;
7705 	tcp->tcp_set_timer = 0;
7706 
7707 	tcp->tcp_active_open = 0;
7708 	tcp->tcp_rexmit = B_FALSE;
7709 	tcp->tcp_xmit_zc_clean = B_FALSE;
7710 
7711 	tcp->tcp_snd_sack_ok = B_FALSE;
7712 	PRESERVE(tcp->tcp_recvdstaddr);
7713 	tcp->tcp_hwcksum = B_FALSE;
7714 
7715 	tcp->tcp_ire_ill_check_done = B_FALSE;
7716 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7717 
7718 	tcp->tcp_mdt = B_FALSE;
7719 	tcp->tcp_mdt_hdr_head = 0;
7720 	tcp->tcp_mdt_hdr_tail = 0;
7721 
7722 	tcp->tcp_conn_def_q0 = 0;
7723 	tcp->tcp_ip_forward_progress = B_FALSE;
7724 	tcp->tcp_anon_priv_bind = 0;
7725 	tcp->tcp_ecn_ok = B_FALSE;
7726 
7727 	tcp->tcp_cwr = B_FALSE;
7728 	tcp->tcp_ecn_echo_on = B_FALSE;
7729 	tcp->tcp_is_wnd_shrnk = B_FALSE;
7730 
7731 	if (tcp->tcp_sack_info != NULL) {
7732 		if (tcp->tcp_notsack_list != NULL) {
7733 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
7734 			    tcp);
7735 		}
7736 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7737 		tcp->tcp_sack_info = NULL;
7738 	}
7739 
7740 	tcp->tcp_rcv_ws = 0;
7741 	tcp->tcp_snd_ws = 0;
7742 	tcp->tcp_ts_recent = 0;
7743 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7744 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7745 	tcp->tcp_if_mtu = 0;
7746 
7747 	ASSERT(tcp->tcp_reass_head == NULL);
7748 	ASSERT(tcp->tcp_reass_tail == NULL);
7749 
7750 	tcp->tcp_cwnd_cnt = 0;
7751 
7752 	ASSERT(tcp->tcp_rcv_list == NULL);
7753 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7754 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7755 	ASSERT(tcp->tcp_rcv_cnt == 0);
7756 
7757 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7758 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7759 	tcp->tcp_csuna = 0;
7760 
7761 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7762 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7763 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7764 	tcp->tcp_rtt_update = 0;
7765 
7766 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7767 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7768 
7769 	tcp->tcp_rack = 0;			/* Displayed in mib */
7770 	tcp->tcp_rack_cnt = 0;
7771 	tcp->tcp_rack_cur_max = 0;
7772 	tcp->tcp_rack_abs_max = 0;
7773 
7774 	tcp->tcp_max_swnd = 0;
7775 
7776 	ASSERT(tcp->tcp_listener == NULL);
7777 
7778 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7779 
7780 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7781 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7782 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7783 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7784 
7785 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7786 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7787 	PRESERVE(tcp->tcp_conn_req_max);
7788 	PRESERVE(tcp->tcp_conn_req_seqnum);
7789 
7790 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7791 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7792 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7793 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7794 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7795 
7796 	tcp->tcp_lingertime = 0;
7797 
7798 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7799 	ASSERT(tcp->tcp_urp_mp == NULL);
7800 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7801 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7802 
7803 	ASSERT(tcp->tcp_eager_next_q == NULL);
7804 	ASSERT(tcp->tcp_eager_last_q == NULL);
7805 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7806 	    tcp->tcp_eager_prev_q0 == NULL) ||
7807 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7808 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7809 
7810 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7811 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7812 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7813 
7814 	tcp->tcp_client_errno = 0;
7815 
7816 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7817 
7818 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7819 
7820 	PRESERVE(tcp->tcp_bound_source_v6);
7821 	tcp->tcp_last_sent_len = 0;
7822 	tcp->tcp_dupack_cnt = 0;
7823 
7824 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7825 	PRESERVE(tcp->tcp_lport);
7826 
7827 	PRESERVE(tcp->tcp_acceptor_lockp);
7828 
7829 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7830 	PRESERVE(tcp->tcp_acceptor_id);
7831 	DONTCARE(tcp->tcp_ipsec_overhead);
7832 
7833 	PRESERVE(tcp->tcp_family);
7834 	if (tcp->tcp_family == AF_INET6) {
7835 		tcp->tcp_ipversion = IPV6_VERSION;
7836 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7837 	} else {
7838 		tcp->tcp_ipversion = IPV4_VERSION;
7839 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7840 	}
7841 
7842 	tcp->tcp_bound_if = 0;
7843 	tcp->tcp_ipv6_recvancillary = 0;
7844 	tcp->tcp_recvifindex = 0;
7845 	tcp->tcp_recvhops = 0;
7846 	tcp->tcp_closed = 0;
7847 	tcp->tcp_cleandeathtag = 0;
7848 	if (tcp->tcp_hopopts != NULL) {
7849 		mi_free(tcp->tcp_hopopts);
7850 		tcp->tcp_hopopts = NULL;
7851 		tcp->tcp_hopoptslen = 0;
7852 	}
7853 	ASSERT(tcp->tcp_hopoptslen == 0);
7854 	if (tcp->tcp_dstopts != NULL) {
7855 		mi_free(tcp->tcp_dstopts);
7856 		tcp->tcp_dstopts = NULL;
7857 		tcp->tcp_dstoptslen = 0;
7858 	}
7859 	ASSERT(tcp->tcp_dstoptslen == 0);
7860 	if (tcp->tcp_rtdstopts != NULL) {
7861 		mi_free(tcp->tcp_rtdstopts);
7862 		tcp->tcp_rtdstopts = NULL;
7863 		tcp->tcp_rtdstoptslen = 0;
7864 	}
7865 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7866 	if (tcp->tcp_rthdr != NULL) {
7867 		mi_free(tcp->tcp_rthdr);
7868 		tcp->tcp_rthdr = NULL;
7869 		tcp->tcp_rthdrlen = 0;
7870 	}
7871 	ASSERT(tcp->tcp_rthdrlen == 0);
7872 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7873 
7874 	/* Reset fusion-related fields */
7875 	tcp->tcp_fused = B_FALSE;
7876 	tcp->tcp_unfusable = B_FALSE;
7877 	tcp->tcp_fused_sigurg = B_FALSE;
7878 	tcp->tcp_loopback_peer = NULL;
7879 	tcp->tcp_recv_hiwater = 0;
7880 
7881 	tcp->tcp_lso = B_FALSE;
7882 
7883 	tcp->tcp_in_ack_unsent = 0;
7884 	tcp->tcp_cork = B_FALSE;
7885 	tcp->tcp_tconnind_started = B_FALSE;
7886 
7887 	PRESERVE(tcp->tcp_squeue_bytes);
7888 
7889 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7890 	ASSERT(!tcp->tcp_kssl_pending);
7891 	PRESERVE(tcp->tcp_kssl_ent);
7892 
7893 	tcp->tcp_closemp_used = B_FALSE;
7894 
7895 	PRESERVE(tcp->tcp_rsrv_mp);
7896 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7897 
7898 #ifdef DEBUG
7899 	DONTCARE(tcp->tcmp_stk[0]);
7900 #endif
7901 
7902 	PRESERVE(tcp->tcp_connid);
7903 
7904 
7905 #undef	DONTCARE
7906 #undef	PRESERVE
7907 }
7908 
7909 /*
7910  * Allocate necessary resources and initialize state vector.
7911  * Guaranteed not to fail so that when an error is returned,
7912  * the caller doesn't need to do any additional cleanup.
7913  */
7914 int
7915 tcp_init(tcp_t *tcp, queue_t *q)
7916 {
7917 	int	err;
7918 
7919 	tcp->tcp_rq = q;
7920 	tcp->tcp_wq = WR(q);
7921 	tcp->tcp_state = TCPS_IDLE;
7922 	if ((err = tcp_init_values(tcp)) != 0)
7923 		tcp_timers_stop(tcp);
7924 	return (err);
7925 }
7926 
7927 static int
7928 tcp_init_values(tcp_t *tcp)
7929 {
7930 	int	err;
7931 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7932 
7933 	ASSERT((tcp->tcp_family == AF_INET &&
7934 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7935 	    (tcp->tcp_family == AF_INET6 &&
7936 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7937 	    tcp->tcp_ipversion == IPV6_VERSION)));
7938 
7939 	/*
7940 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7941 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7942 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7943 	 * during first few transmissions of a connection as seen in slow
7944 	 * links.
7945 	 */
7946 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7947 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7948 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7949 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7950 	    tcps->tcps_conn_grace_period;
7951 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7952 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7953 	tcp->tcp_timer_backoff = 0;
7954 	tcp->tcp_ms_we_have_waited = 0;
7955 	tcp->tcp_last_recv_time = lbolt;
7956 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7957 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7958 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7959 
7960 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7961 
7962 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7963 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7964 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7965 	/*
7966 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7967 	 * passive open.
7968 	 */
7969 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7970 
7971 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7972 
7973 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7974 
7975 	tcp->tcp_mdt_hdr_head = 0;
7976 	tcp->tcp_mdt_hdr_tail = 0;
7977 
7978 	/* Reset fusion-related fields */
7979 	tcp->tcp_fused = B_FALSE;
7980 	tcp->tcp_unfusable = B_FALSE;
7981 	tcp->tcp_fused_sigurg = B_FALSE;
7982 	tcp->tcp_loopback_peer = NULL;
7983 	tcp->tcp_recv_hiwater = 0;
7984 
7985 	/* Initialize the header template */
7986 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7987 		err = tcp_header_init_ipv4(tcp);
7988 	} else {
7989 		err = tcp_header_init_ipv6(tcp);
7990 	}
7991 	if (err)
7992 		return (err);
7993 
7994 	/*
7995 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7996 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7997 	 */
7998 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7999 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8000 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8001 
8002 	tcp->tcp_cork = B_FALSE;
8003 	/*
8004 	 * Init the tcp_debug option.  This value determines whether TCP
8005 	 * calls strlog() to print out debug messages.  Doing this
8006 	 * initialization here means that this value is not inherited thru
8007 	 * tcp_reinit().
8008 	 */
8009 	tcp->tcp_debug = tcps->tcps_dbg;
8010 
8011 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8012 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8013 
8014 	return (0);
8015 }
8016 
8017 /*
8018  * Initialize the IPv4 header. Loses any record of any IP options.
8019  */
8020 static int
8021 tcp_header_init_ipv4(tcp_t *tcp)
8022 {
8023 	tcph_t		*tcph;
8024 	uint32_t	sum;
8025 	conn_t		*connp;
8026 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8027 
8028 	/*
8029 	 * This is a simple initialization. If there's
8030 	 * already a template, it should never be too small,
8031 	 * so reuse it.  Otherwise, allocate space for the new one.
8032 	 */
8033 	if (tcp->tcp_iphc == NULL) {
8034 		ASSERT(tcp->tcp_iphc_len == 0);
8035 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8036 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8037 		if (tcp->tcp_iphc == NULL) {
8038 			tcp->tcp_iphc_len = 0;
8039 			return (ENOMEM);
8040 		}
8041 	}
8042 
8043 	/* options are gone; may need a new label */
8044 	connp = tcp->tcp_connp;
8045 	connp->conn_mlp_type = mlptSingle;
8046 	connp->conn_ulp_labeled = !is_system_labeled();
8047 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8048 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8049 	tcp->tcp_ip6h = NULL;
8050 	tcp->tcp_ipversion = IPV4_VERSION;
8051 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8052 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8053 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8054 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8055 	tcp->tcp_ipha->ipha_version_and_hdr_length
8056 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8057 	tcp->tcp_ipha->ipha_ident = 0;
8058 
8059 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8060 	tcp->tcp_tos = 0;
8061 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8062 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8063 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8064 
8065 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8066 	tcp->tcp_tcph = tcph;
8067 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8068 	/*
8069 	 * IP wants our header length in the checksum field to
8070 	 * allow it to perform a single pseudo-header+checksum
8071 	 * calculation on behalf of TCP.
8072 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8073 	 */
8074 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8075 	sum = (sum >> 16) + (sum & 0xFFFF);
8076 	U16_TO_ABE16(sum, tcph->th_sum);
8077 	return (0);
8078 }
8079 
8080 /*
8081  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8082  */
8083 static int
8084 tcp_header_init_ipv6(tcp_t *tcp)
8085 {
8086 	tcph_t	*tcph;
8087 	uint32_t	sum;
8088 	conn_t	*connp;
8089 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8090 
8091 	/*
8092 	 * This is a simple initialization. If there's
8093 	 * already a template, it should never be too small,
8094 	 * so reuse it. Otherwise, allocate space for the new one.
8095 	 * Ensure that there is enough space to "downgrade" the tcp_t
8096 	 * to an IPv4 tcp_t. This requires having space for a full load
8097 	 * of IPv4 options, as well as a full load of TCP options
8098 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8099 	 * than a v6 header and a TCP header with a full load of TCP options
8100 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8101 	 * We want to avoid reallocation in the "downgraded" case when
8102 	 * processing outbound IPv4 options.
8103 	 */
8104 	if (tcp->tcp_iphc == NULL) {
8105 		ASSERT(tcp->tcp_iphc_len == 0);
8106 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8107 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8108 		if (tcp->tcp_iphc == NULL) {
8109 			tcp->tcp_iphc_len = 0;
8110 			return (ENOMEM);
8111 		}
8112 	}
8113 
8114 	/* options are gone; may need a new label */
8115 	connp = tcp->tcp_connp;
8116 	connp->conn_mlp_type = mlptSingle;
8117 	connp->conn_ulp_labeled = !is_system_labeled();
8118 
8119 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8120 	tcp->tcp_ipversion = IPV6_VERSION;
8121 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8122 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8123 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8124 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8125 	tcp->tcp_ipha = NULL;
8126 
8127 	/* Initialize the header template */
8128 
8129 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8130 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8131 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8132 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8133 
8134 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8135 	tcp->tcp_tcph = tcph;
8136 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8137 	/*
8138 	 * IP wants our header length in the checksum field to
8139 	 * allow it to perform a single psuedo-header+checksum
8140 	 * calculation on behalf of TCP.
8141 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8142 	 */
8143 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8144 	sum = (sum >> 16) + (sum & 0xFFFF);
8145 	U16_TO_ABE16(sum, tcph->th_sum);
8146 	return (0);
8147 }
8148 
8149 /* At minimum we need 8 bytes in the TCP header for the lookup */
8150 #define	ICMP_MIN_TCP_HDR	8
8151 
8152 /*
8153  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8154  * passed up by IP. The message is always received on the correct tcp_t.
8155  * Assumes that IP has pulled up everything up to and including the ICMP header.
8156  */
8157 void
8158 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8159 {
8160 	icmph_t *icmph;
8161 	ipha_t	*ipha;
8162 	int	iph_hdr_length;
8163 	tcph_t	*tcph;
8164 	boolean_t ipsec_mctl = B_FALSE;
8165 	boolean_t secure;
8166 	mblk_t *first_mp = mp;
8167 	int32_t new_mss;
8168 	uint32_t ratio;
8169 	size_t mp_size = MBLKL(mp);
8170 	uint32_t seg_seq;
8171 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8172 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8173 
8174 	/* Assume IP provides aligned packets - otherwise toss */
8175 	if (!OK_32PTR(mp->b_rptr)) {
8176 		freemsg(mp);
8177 		return;
8178 	}
8179 
8180 	/*
8181 	 * Since ICMP errors are normal data marked with M_CTL when sent
8182 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8183 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8184 	 */
8185 	if ((mp_size == sizeof (ipsec_info_t)) &&
8186 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8187 		ASSERT(mp->b_cont != NULL);
8188 		mp = mp->b_cont;
8189 		/* IP should have done this */
8190 		ASSERT(OK_32PTR(mp->b_rptr));
8191 		mp_size = MBLKL(mp);
8192 		ipsec_mctl = B_TRUE;
8193 	}
8194 
8195 	/*
8196 	 * Verify that we have a complete outer IP header. If not, drop it.
8197 	 */
8198 	if (mp_size < sizeof (ipha_t)) {
8199 noticmpv4:
8200 		freemsg(first_mp);
8201 		return;
8202 	}
8203 
8204 	ipha = (ipha_t *)mp->b_rptr;
8205 	/*
8206 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8207 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8208 	 */
8209 	switch (IPH_HDR_VERSION(ipha)) {
8210 	case IPV6_VERSION:
8211 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8212 		return;
8213 	case IPV4_VERSION:
8214 		break;
8215 	default:
8216 		goto noticmpv4;
8217 	}
8218 
8219 	/* Skip past the outer IP and ICMP headers */
8220 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8221 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8222 	/*
8223 	 * If we don't have the correct outer IP header length or if the ULP
8224 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8225 	 * send it upstream.
8226 	 */
8227 	if (iph_hdr_length < sizeof (ipha_t) ||
8228 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8229 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8230 		goto noticmpv4;
8231 	}
8232 	ipha = (ipha_t *)&icmph[1];
8233 
8234 	/* Skip past the inner IP and find the ULP header */
8235 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8236 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8237 	/*
8238 	 * If we don't have the correct inner IP header length or if the ULP
8239 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8240 	 * bytes of TCP header, drop it.
8241 	 */
8242 	if (iph_hdr_length < sizeof (ipha_t) ||
8243 	    ipha->ipha_protocol != IPPROTO_TCP ||
8244 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8245 		goto noticmpv4;
8246 	}
8247 
8248 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8249 		if (ipsec_mctl) {
8250 			secure = ipsec_in_is_secure(first_mp);
8251 		} else {
8252 			secure = B_FALSE;
8253 		}
8254 		if (secure) {
8255 			/*
8256 			 * If we are willing to accept this in clear
8257 			 * we don't have to verify policy.
8258 			 */
8259 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8260 				if (!tcp_check_policy(tcp, first_mp,
8261 				    ipha, NULL, secure, ipsec_mctl)) {
8262 					/*
8263 					 * tcp_check_policy called
8264 					 * ip_drop_packet() on failure.
8265 					 */
8266 					return;
8267 				}
8268 			}
8269 		}
8270 	} else if (ipsec_mctl) {
8271 		/*
8272 		 * This is a hard_bound connection. IP has already
8273 		 * verified policy. We don't have to do it again.
8274 		 */
8275 		freeb(first_mp);
8276 		first_mp = mp;
8277 		ipsec_mctl = B_FALSE;
8278 	}
8279 
8280 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8281 	/*
8282 	 * TCP SHOULD check that the TCP sequence number contained in
8283 	 * payload of the ICMP error message is within the range
8284 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8285 	 */
8286 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8287 		/*
8288 		 * The ICMP message is bogus, just drop it.  But if this is
8289 		 * an ICMP too big message, IP has already changed
8290 		 * the ire_max_frag to the bogus value.  We need to change
8291 		 * it back.
8292 		 */
8293 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8294 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8295 			conn_t *connp = tcp->tcp_connp;
8296 			ire_t *ire;
8297 			int flag;
8298 
8299 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8300 				flag = tcp->tcp_ipha->
8301 				    ipha_fragment_offset_and_flags;
8302 			} else {
8303 				flag = 0;
8304 			}
8305 			mutex_enter(&connp->conn_lock);
8306 			if ((ire = connp->conn_ire_cache) != NULL) {
8307 				mutex_enter(&ire->ire_lock);
8308 				mutex_exit(&connp->conn_lock);
8309 				ire->ire_max_frag = tcp->tcp_if_mtu;
8310 				ire->ire_frag_flag |= flag;
8311 				mutex_exit(&ire->ire_lock);
8312 			} else {
8313 				mutex_exit(&connp->conn_lock);
8314 			}
8315 		}
8316 		goto noticmpv4;
8317 	}
8318 
8319 	switch (icmph->icmph_type) {
8320 	case ICMP_DEST_UNREACHABLE:
8321 		switch (icmph->icmph_code) {
8322 		case ICMP_FRAGMENTATION_NEEDED:
8323 			/*
8324 			 * Reduce the MSS based on the new MTU.  This will
8325 			 * eliminate any fragmentation locally.
8326 			 * N.B.  There may well be some funny side-effects on
8327 			 * the local send policy and the remote receive policy.
8328 			 * Pending further research, we provide
8329 			 * tcp_ignore_path_mtu just in case this proves
8330 			 * disastrous somewhere.
8331 			 *
8332 			 * After updating the MSS, retransmit part of the
8333 			 * dropped segment using the new mss by calling
8334 			 * tcp_wput_data().  Need to adjust all those
8335 			 * params to make sure tcp_wput_data() work properly.
8336 			 */
8337 			if (tcps->tcps_ignore_path_mtu ||
8338 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8339 				break;
8340 
8341 			/*
8342 			 * Decrease the MSS by time stamp options
8343 			 * IP options and IPSEC options. tcp_hdr_len
8344 			 * includes time stamp option and IP option
8345 			 * length.  Note that new_mss may be negative
8346 			 * if tcp_ipsec_overhead is large and the
8347 			 * icmph_du_mtu is the minimum value, which is 68.
8348 			 */
8349 			new_mss = ntohs(icmph->icmph_du_mtu) -
8350 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8351 
8352 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8353 			    new_mss);
8354 
8355 			/*
8356 			 * Only update the MSS if the new one is
8357 			 * smaller than the previous one.  This is
8358 			 * to avoid problems when getting multiple
8359 			 * ICMP errors for the same MTU.
8360 			 */
8361 			if (new_mss >= tcp->tcp_mss)
8362 				break;
8363 
8364 			/*
8365 			 * Note that we are using the template header's DF
8366 			 * bit in the fast path sending.  So we need to compare
8367 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8368 			 * And stop doing IPv4 PMTUd if new_mss is less than
8369 			 * MAX(tcps_mss_min, ip_pmtu_min).
8370 			 */
8371 			if (new_mss < tcps->tcps_mss_min ||
8372 			    new_mss < ipst->ips_ip_pmtu_min) {
8373 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8374 				    0;
8375 			}
8376 
8377 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8378 			ASSERT(ratio >= 1);
8379 			tcp_mss_set(tcp, new_mss, B_TRUE);
8380 
8381 			/*
8382 			 * Make sure we have something to
8383 			 * send.
8384 			 */
8385 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8386 			    (tcp->tcp_xmit_head != NULL)) {
8387 				/*
8388 				 * Shrink tcp_cwnd in
8389 				 * proportion to the old MSS/new MSS.
8390 				 */
8391 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8392 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8393 				    (tcp->tcp_unsent == 0)) {
8394 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8395 				} else {
8396 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8397 				}
8398 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8399 				tcp->tcp_rexmit = B_TRUE;
8400 				tcp->tcp_dupack_cnt = 0;
8401 				tcp->tcp_snd_burst = TCP_CWND_SS;
8402 				tcp_ss_rexmit(tcp);
8403 			}
8404 			break;
8405 		case ICMP_PORT_UNREACHABLE:
8406 		case ICMP_PROTOCOL_UNREACHABLE:
8407 			switch (tcp->tcp_state) {
8408 			case TCPS_SYN_SENT:
8409 			case TCPS_SYN_RCVD:
8410 				/*
8411 				 * ICMP can snipe away incipient
8412 				 * TCP connections as long as
8413 				 * seq number is same as initial
8414 				 * send seq number.
8415 				 */
8416 				if (seg_seq == tcp->tcp_iss) {
8417 					(void) tcp_clean_death(tcp,
8418 					    ECONNREFUSED, 6);
8419 				}
8420 				break;
8421 			}
8422 			break;
8423 		case ICMP_HOST_UNREACHABLE:
8424 		case ICMP_NET_UNREACHABLE:
8425 			/* Record the error in case we finally time out. */
8426 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8427 				tcp->tcp_client_errno = EHOSTUNREACH;
8428 			else
8429 				tcp->tcp_client_errno = ENETUNREACH;
8430 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8431 				if (tcp->tcp_listener != NULL &&
8432 				    tcp->tcp_listener->tcp_syn_defense) {
8433 					/*
8434 					 * Ditch the half-open connection if we
8435 					 * suspect a SYN attack is under way.
8436 					 */
8437 					tcp_ip_ire_mark_advice(tcp);
8438 					(void) tcp_clean_death(tcp,
8439 					    tcp->tcp_client_errno, 7);
8440 				}
8441 			}
8442 			break;
8443 		default:
8444 			break;
8445 		}
8446 		break;
8447 	case ICMP_SOURCE_QUENCH: {
8448 		/*
8449 		 * use a global boolean to control
8450 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8451 		 * The default is false.
8452 		 */
8453 		if (tcp_icmp_source_quench) {
8454 			/*
8455 			 * Reduce the sending rate as if we got a
8456 			 * retransmit timeout
8457 			 */
8458 			uint32_t npkt;
8459 
8460 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8461 			    tcp->tcp_mss;
8462 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8463 			tcp->tcp_cwnd = tcp->tcp_mss;
8464 			tcp->tcp_cwnd_cnt = 0;
8465 		}
8466 		break;
8467 	}
8468 	}
8469 	freemsg(first_mp);
8470 }
8471 
8472 /*
8473  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8474  * error messages passed up by IP.
8475  * Assumes that IP has pulled up all the extension headers as well
8476  * as the ICMPv6 header.
8477  */
8478 static void
8479 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8480 {
8481 	icmp6_t *icmp6;
8482 	ip6_t	*ip6h;
8483 	uint16_t	iph_hdr_length;
8484 	tcpha_t	*tcpha;
8485 	uint8_t	*nexthdrp;
8486 	uint32_t new_mss;
8487 	uint32_t ratio;
8488 	boolean_t secure;
8489 	mblk_t *first_mp = mp;
8490 	size_t mp_size;
8491 	uint32_t seg_seq;
8492 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8493 
8494 	/*
8495 	 * The caller has determined if this is an IPSEC_IN packet and
8496 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8497 	 */
8498 	if (ipsec_mctl)
8499 		mp = mp->b_cont;
8500 
8501 	mp_size = MBLKL(mp);
8502 
8503 	/*
8504 	 * Verify that we have a complete IP header. If not, send it upstream.
8505 	 */
8506 	if (mp_size < sizeof (ip6_t)) {
8507 noticmpv6:
8508 		freemsg(first_mp);
8509 		return;
8510 	}
8511 
8512 	/*
8513 	 * Verify this is an ICMPV6 packet, else send it upstream.
8514 	 */
8515 	ip6h = (ip6_t *)mp->b_rptr;
8516 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8517 		iph_hdr_length = IPV6_HDR_LEN;
8518 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8519 	    &nexthdrp) ||
8520 	    *nexthdrp != IPPROTO_ICMPV6) {
8521 		goto noticmpv6;
8522 	}
8523 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8524 	ip6h = (ip6_t *)&icmp6[1];
8525 	/*
8526 	 * Verify if we have a complete ICMP and inner IP header.
8527 	 */
8528 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8529 		goto noticmpv6;
8530 
8531 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8532 		goto noticmpv6;
8533 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8534 	/*
8535 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8536 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8537 	 * packet.
8538 	 */
8539 	if ((*nexthdrp != IPPROTO_TCP) ||
8540 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8541 		goto noticmpv6;
8542 	}
8543 
8544 	/*
8545 	 * ICMP errors come on the right queue or come on
8546 	 * listener/global queue for detached connections and
8547 	 * get switched to the right queue. If it comes on the
8548 	 * right queue, policy check has already been done by IP
8549 	 * and thus free the first_mp without verifying the policy.
8550 	 * If it has come for a non-hard bound connection, we need
8551 	 * to verify policy as IP may not have done it.
8552 	 */
8553 	if (!tcp->tcp_hard_bound) {
8554 		if (ipsec_mctl) {
8555 			secure = ipsec_in_is_secure(first_mp);
8556 		} else {
8557 			secure = B_FALSE;
8558 		}
8559 		if (secure) {
8560 			/*
8561 			 * If we are willing to accept this in clear
8562 			 * we don't have to verify policy.
8563 			 */
8564 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8565 				if (!tcp_check_policy(tcp, first_mp,
8566 				    NULL, ip6h, secure, ipsec_mctl)) {
8567 					/*
8568 					 * tcp_check_policy called
8569 					 * ip_drop_packet() on failure.
8570 					 */
8571 					return;
8572 				}
8573 			}
8574 		}
8575 	} else if (ipsec_mctl) {
8576 		/*
8577 		 * This is a hard_bound connection. IP has already
8578 		 * verified policy. We don't have to do it again.
8579 		 */
8580 		freeb(first_mp);
8581 		first_mp = mp;
8582 		ipsec_mctl = B_FALSE;
8583 	}
8584 
8585 	seg_seq = ntohl(tcpha->tha_seq);
8586 	/*
8587 	 * TCP SHOULD check that the TCP sequence number contained in
8588 	 * payload of the ICMP error message is within the range
8589 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8590 	 */
8591 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8592 		/*
8593 		 * If the ICMP message is bogus, should we kill the
8594 		 * connection, or should we just drop the bogus ICMP
8595 		 * message? It would probably make more sense to just
8596 		 * drop the message so that if this one managed to get
8597 		 * in, the real connection should not suffer.
8598 		 */
8599 		goto noticmpv6;
8600 	}
8601 
8602 	switch (icmp6->icmp6_type) {
8603 	case ICMP6_PACKET_TOO_BIG:
8604 		/*
8605 		 * Reduce the MSS based on the new MTU.  This will
8606 		 * eliminate any fragmentation locally.
8607 		 * N.B.  There may well be some funny side-effects on
8608 		 * the local send policy and the remote receive policy.
8609 		 * Pending further research, we provide
8610 		 * tcp_ignore_path_mtu just in case this proves
8611 		 * disastrous somewhere.
8612 		 *
8613 		 * After updating the MSS, retransmit part of the
8614 		 * dropped segment using the new mss by calling
8615 		 * tcp_wput_data().  Need to adjust all those
8616 		 * params to make sure tcp_wput_data() work properly.
8617 		 */
8618 		if (tcps->tcps_ignore_path_mtu)
8619 			break;
8620 
8621 		/*
8622 		 * Decrease the MSS by time stamp options
8623 		 * IP options and IPSEC options. tcp_hdr_len
8624 		 * includes time stamp option and IP option
8625 		 * length.
8626 		 */
8627 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8628 		    tcp->tcp_ipsec_overhead;
8629 
8630 		/*
8631 		 * Only update the MSS if the new one is
8632 		 * smaller than the previous one.  This is
8633 		 * to avoid problems when getting multiple
8634 		 * ICMP errors for the same MTU.
8635 		 */
8636 		if (new_mss >= tcp->tcp_mss)
8637 			break;
8638 
8639 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8640 		ASSERT(ratio >= 1);
8641 		tcp_mss_set(tcp, new_mss, B_TRUE);
8642 
8643 		/*
8644 		 * Make sure we have something to
8645 		 * send.
8646 		 */
8647 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8648 		    (tcp->tcp_xmit_head != NULL)) {
8649 			/*
8650 			 * Shrink tcp_cwnd in
8651 			 * proportion to the old MSS/new MSS.
8652 			 */
8653 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8654 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8655 			    (tcp->tcp_unsent == 0)) {
8656 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8657 			} else {
8658 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8659 			}
8660 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8661 			tcp->tcp_rexmit = B_TRUE;
8662 			tcp->tcp_dupack_cnt = 0;
8663 			tcp->tcp_snd_burst = TCP_CWND_SS;
8664 			tcp_ss_rexmit(tcp);
8665 		}
8666 		break;
8667 
8668 	case ICMP6_DST_UNREACH:
8669 		switch (icmp6->icmp6_code) {
8670 		case ICMP6_DST_UNREACH_NOPORT:
8671 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8672 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8673 			    (seg_seq == tcp->tcp_iss)) {
8674 				(void) tcp_clean_death(tcp,
8675 				    ECONNREFUSED, 8);
8676 			}
8677 			break;
8678 
8679 		case ICMP6_DST_UNREACH_ADMIN:
8680 		case ICMP6_DST_UNREACH_NOROUTE:
8681 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8682 		case ICMP6_DST_UNREACH_ADDR:
8683 			/* Record the error in case we finally time out. */
8684 			tcp->tcp_client_errno = EHOSTUNREACH;
8685 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8686 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8687 			    (seg_seq == tcp->tcp_iss)) {
8688 				if (tcp->tcp_listener != NULL &&
8689 				    tcp->tcp_listener->tcp_syn_defense) {
8690 					/*
8691 					 * Ditch the half-open connection if we
8692 					 * suspect a SYN attack is under way.
8693 					 */
8694 					tcp_ip_ire_mark_advice(tcp);
8695 					(void) tcp_clean_death(tcp,
8696 					    tcp->tcp_client_errno, 9);
8697 				}
8698 			}
8699 
8700 
8701 			break;
8702 		default:
8703 			break;
8704 		}
8705 		break;
8706 
8707 	case ICMP6_PARAM_PROB:
8708 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8709 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8710 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8711 		    (uchar_t *)nexthdrp) {
8712 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8713 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8714 				(void) tcp_clean_death(tcp,
8715 				    ECONNREFUSED, 10);
8716 			}
8717 			break;
8718 		}
8719 		break;
8720 
8721 	case ICMP6_TIME_EXCEEDED:
8722 	default:
8723 		break;
8724 	}
8725 	freemsg(first_mp);
8726 }
8727 
8728 /*
8729  * Notify IP that we are having trouble with this connection.  IP should
8730  * blow the IRE away and start over.
8731  */
8732 static void
8733 tcp_ip_notify(tcp_t *tcp)
8734 {
8735 	struct iocblk	*iocp;
8736 	ipid_t	*ipid;
8737 	mblk_t	*mp;
8738 
8739 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8740 	if (tcp->tcp_ipversion == IPV6_VERSION)
8741 		return;
8742 
8743 	mp = mkiocb(IP_IOCTL);
8744 	if (mp == NULL)
8745 		return;
8746 
8747 	iocp = (struct iocblk *)mp->b_rptr;
8748 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8749 
8750 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8751 	if (!mp->b_cont) {
8752 		freeb(mp);
8753 		return;
8754 	}
8755 
8756 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8757 	mp->b_cont->b_wptr += iocp->ioc_count;
8758 	bzero(ipid, sizeof (*ipid));
8759 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8760 	ipid->ipid_ire_type = IRE_CACHE;
8761 	ipid->ipid_addr_offset = sizeof (ipid_t);
8762 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8763 	/*
8764 	 * Note: in the case of source routing we want to blow away the
8765 	 * route to the first source route hop.
8766 	 */
8767 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8768 	    sizeof (tcp->tcp_ipha->ipha_dst));
8769 
8770 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8771 }
8772 
8773 /* Unlink and return any mblk that looks like it contains an ire */
8774 static mblk_t *
8775 tcp_ire_mp(mblk_t **mpp)
8776 {
8777 	mblk_t 	*mp = *mpp;
8778 	mblk_t	*prev_mp = NULL;
8779 
8780 	for (;;) {
8781 		switch (DB_TYPE(mp)) {
8782 		case IRE_DB_TYPE:
8783 		case IRE_DB_REQ_TYPE:
8784 			if (mp == *mpp) {
8785 				*mpp = mp->b_cont;
8786 			} else {
8787 				prev_mp->b_cont = mp->b_cont;
8788 			}
8789 			mp->b_cont = NULL;
8790 			return (mp);
8791 		default:
8792 			break;
8793 		}
8794 		prev_mp = mp;
8795 		mp = mp->b_cont;
8796 		if (mp == NULL)
8797 			break;
8798 	}
8799 	return (mp);
8800 }
8801 
8802 /*
8803  * Timer callback routine for keepalive probe.  We do a fake resend of
8804  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8805  * check to see if we have heard anything from the other end for the last
8806  * RTO period.  If we have, set the timer to expire for another
8807  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8808  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8809  * the timeout if we have not heard from the other side.  If for more than
8810  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8811  * kill the connection unless the keepalive abort threshold is 0.  In
8812  * that case, we will probe "forever."
8813  */
8814 static void
8815 tcp_keepalive_killer(void *arg)
8816 {
8817 	mblk_t	*mp;
8818 	conn_t	*connp = (conn_t *)arg;
8819 	tcp_t  	*tcp = connp->conn_tcp;
8820 	int32_t	firetime;
8821 	int32_t	idletime;
8822 	int32_t	ka_intrvl;
8823 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8824 
8825 	tcp->tcp_ka_tid = 0;
8826 
8827 	if (tcp->tcp_fused)
8828 		return;
8829 
8830 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8831 	ka_intrvl = tcp->tcp_ka_interval;
8832 
8833 	/*
8834 	 * Keepalive probe should only be sent if the application has not
8835 	 * done a close on the connection.
8836 	 */
8837 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8838 		return;
8839 	}
8840 	/* Timer fired too early, restart it. */
8841 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8842 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8843 		    MSEC_TO_TICK(ka_intrvl));
8844 		return;
8845 	}
8846 
8847 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8848 	/*
8849 	 * If we have not heard from the other side for a long
8850 	 * time, kill the connection unless the keepalive abort
8851 	 * threshold is 0.  In that case, we will probe "forever."
8852 	 */
8853 	if (tcp->tcp_ka_abort_thres != 0 &&
8854 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8855 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8856 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8857 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8858 		return;
8859 	}
8860 
8861 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8862 	    idletime >= ka_intrvl) {
8863 		/* Fake resend of last ACKed byte. */
8864 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8865 
8866 		if (mp1 != NULL) {
8867 			*mp1->b_wptr++ = '\0';
8868 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8869 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8870 			freeb(mp1);
8871 			/*
8872 			 * if allocation failed, fall through to start the
8873 			 * timer back.
8874 			 */
8875 			if (mp != NULL) {
8876 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8877 				BUMP_MIB(&tcps->tcps_mib,
8878 				    tcpTimKeepaliveProbe);
8879 				if (tcp->tcp_ka_last_intrvl != 0) {
8880 					int max;
8881 					/*
8882 					 * We should probe again at least
8883 					 * in ka_intrvl, but not more than
8884 					 * tcp_rexmit_interval_max.
8885 					 */
8886 					max = tcps->tcps_rexmit_interval_max;
8887 					firetime = MIN(ka_intrvl - 1,
8888 					    tcp->tcp_ka_last_intrvl << 1);
8889 					if (firetime > max)
8890 						firetime = max;
8891 				} else {
8892 					firetime = tcp->tcp_rto;
8893 				}
8894 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8895 				    tcp_keepalive_killer,
8896 				    MSEC_TO_TICK(firetime));
8897 				tcp->tcp_ka_last_intrvl = firetime;
8898 				return;
8899 			}
8900 		}
8901 	} else {
8902 		tcp->tcp_ka_last_intrvl = 0;
8903 	}
8904 
8905 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8906 	if ((firetime = ka_intrvl - idletime) < 0) {
8907 		firetime = ka_intrvl;
8908 	}
8909 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8910 	    MSEC_TO_TICK(firetime));
8911 }
8912 
8913 int
8914 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8915 {
8916 	queue_t	*q = tcp->tcp_rq;
8917 	int32_t	mss = tcp->tcp_mss;
8918 	int	maxpsz;
8919 	conn_t	*connp = tcp->tcp_connp;
8920 
8921 	if (TCP_IS_DETACHED(tcp))
8922 		return (mss);
8923 	if (tcp->tcp_fused) {
8924 		maxpsz = tcp_fuse_maxpsz(tcp);
8925 		mss = INFPSZ;
8926 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8927 		/*
8928 		 * Set the sd_qn_maxpsz according to the socket send buffer
8929 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8930 		 * instruct the stream head to copyin user data into contiguous
8931 		 * kernel-allocated buffers without breaking it up into smaller
8932 		 * chunks.  We round up the buffer size to the nearest SMSS.
8933 		 */
8934 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8935 		if (tcp->tcp_kssl_ctx == NULL)
8936 			mss = INFPSZ;
8937 		else
8938 			mss = SSL3_MAX_RECORD_LEN;
8939 	} else {
8940 		/*
8941 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8942 		 * (and a multiple of the mss).  This instructs the stream
8943 		 * head to break down larger than SMSS writes into SMSS-
8944 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8945 		 */
8946 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8947 		maxpsz = tcp->tcp_maxpsz * mss;
8948 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8949 			maxpsz = tcp->tcp_xmit_hiwater/2;
8950 			/* Round up to nearest mss */
8951 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8952 		}
8953 	}
8954 
8955 	(void) proto_set_maxpsz(q, connp, maxpsz);
8956 	if (!(IPCL_IS_NONSTR(connp))) {
8957 		/* XXX do it in set_maxpsz()? */
8958 		tcp->tcp_wq->q_maxpsz = maxpsz;
8959 	}
8960 
8961 	if (set_maxblk)
8962 		(void) proto_set_tx_maxblk(q, connp, mss);
8963 	return (mss);
8964 }
8965 
8966 /*
8967  * Extract option values from a tcp header.  We put any found values into the
8968  * tcpopt struct and return a bitmask saying which options were found.
8969  */
8970 static int
8971 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8972 {
8973 	uchar_t		*endp;
8974 	int		len;
8975 	uint32_t	mss;
8976 	uchar_t		*up = (uchar_t *)tcph;
8977 	int		found = 0;
8978 	int32_t		sack_len;
8979 	tcp_seq		sack_begin, sack_end;
8980 	tcp_t		*tcp;
8981 
8982 	endp = up + TCP_HDR_LENGTH(tcph);
8983 	up += TCP_MIN_HEADER_LENGTH;
8984 	while (up < endp) {
8985 		len = endp - up;
8986 		switch (*up) {
8987 		case TCPOPT_EOL:
8988 			break;
8989 
8990 		case TCPOPT_NOP:
8991 			up++;
8992 			continue;
8993 
8994 		case TCPOPT_MAXSEG:
8995 			if (len < TCPOPT_MAXSEG_LEN ||
8996 			    up[1] != TCPOPT_MAXSEG_LEN)
8997 				break;
8998 
8999 			mss = BE16_TO_U16(up+2);
9000 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9001 			tcpopt->tcp_opt_mss = mss;
9002 			found |= TCP_OPT_MSS_PRESENT;
9003 
9004 			up += TCPOPT_MAXSEG_LEN;
9005 			continue;
9006 
9007 		case TCPOPT_WSCALE:
9008 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9009 				break;
9010 
9011 			if (up[2] > TCP_MAX_WINSHIFT)
9012 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9013 			else
9014 				tcpopt->tcp_opt_wscale = up[2];
9015 			found |= TCP_OPT_WSCALE_PRESENT;
9016 
9017 			up += TCPOPT_WS_LEN;
9018 			continue;
9019 
9020 		case TCPOPT_SACK_PERMITTED:
9021 			if (len < TCPOPT_SACK_OK_LEN ||
9022 			    up[1] != TCPOPT_SACK_OK_LEN)
9023 				break;
9024 			found |= TCP_OPT_SACK_OK_PRESENT;
9025 			up += TCPOPT_SACK_OK_LEN;
9026 			continue;
9027 
9028 		case TCPOPT_SACK:
9029 			if (len <= 2 || up[1] <= 2 || len < up[1])
9030 				break;
9031 
9032 			/* If TCP is not interested in SACK blks... */
9033 			if ((tcp = tcpopt->tcp) == NULL) {
9034 				up += up[1];
9035 				continue;
9036 			}
9037 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9038 			up += TCPOPT_HEADER_LEN;
9039 
9040 			/*
9041 			 * If the list is empty, allocate one and assume
9042 			 * nothing is sack'ed.
9043 			 */
9044 			ASSERT(tcp->tcp_sack_info != NULL);
9045 			if (tcp->tcp_notsack_list == NULL) {
9046 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9047 				    tcp->tcp_suna, tcp->tcp_snxt,
9048 				    &(tcp->tcp_num_notsack_blk),
9049 				    &(tcp->tcp_cnt_notsack_list));
9050 
9051 				/*
9052 				 * Make sure tcp_notsack_list is not NULL.
9053 				 * This happens when kmem_alloc(KM_NOSLEEP)
9054 				 * returns NULL.
9055 				 */
9056 				if (tcp->tcp_notsack_list == NULL) {
9057 					up += sack_len;
9058 					continue;
9059 				}
9060 				tcp->tcp_fack = tcp->tcp_suna;
9061 			}
9062 
9063 			while (sack_len > 0) {
9064 				if (up + 8 > endp) {
9065 					up = endp;
9066 					break;
9067 				}
9068 				sack_begin = BE32_TO_U32(up);
9069 				up += 4;
9070 				sack_end = BE32_TO_U32(up);
9071 				up += 4;
9072 				sack_len -= 8;
9073 				/*
9074 				 * Bounds checking.  Make sure the SACK
9075 				 * info is within tcp_suna and tcp_snxt.
9076 				 * If this SACK blk is out of bound, ignore
9077 				 * it but continue to parse the following
9078 				 * blks.
9079 				 */
9080 				if (SEQ_LEQ(sack_end, sack_begin) ||
9081 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9082 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9083 					continue;
9084 				}
9085 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9086 				    sack_begin, sack_end,
9087 				    &(tcp->tcp_num_notsack_blk),
9088 				    &(tcp->tcp_cnt_notsack_list));
9089 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9090 					tcp->tcp_fack = sack_end;
9091 				}
9092 			}
9093 			found |= TCP_OPT_SACK_PRESENT;
9094 			continue;
9095 
9096 		case TCPOPT_TSTAMP:
9097 			if (len < TCPOPT_TSTAMP_LEN ||
9098 			    up[1] != TCPOPT_TSTAMP_LEN)
9099 				break;
9100 
9101 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9102 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9103 
9104 			found |= TCP_OPT_TSTAMP_PRESENT;
9105 
9106 			up += TCPOPT_TSTAMP_LEN;
9107 			continue;
9108 
9109 		default:
9110 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9111 				break;
9112 			up += up[1];
9113 			continue;
9114 		}
9115 		break;
9116 	}
9117 	return (found);
9118 }
9119 
9120 /*
9121  * Set the mss associated with a particular tcp based on its current value,
9122  * and a new one passed in. Observe minimums and maximums, and reset
9123  * other state variables that we want to view as multiples of mss.
9124  *
9125  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9126  * highwater marks etc. need to be initialized or adjusted.
9127  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9128  *    packet arrives.
9129  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9130  *    ICMP6_PACKET_TOO_BIG arrives.
9131  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9132  *    to increase the MSS to use the extra bytes available.
9133  *
9134  * Callers except tcp_paws_check() ensure that they only reduce mss.
9135  */
9136 static void
9137 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9138 {
9139 	uint32_t	mss_max;
9140 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9141 
9142 	if (tcp->tcp_ipversion == IPV4_VERSION)
9143 		mss_max = tcps->tcps_mss_max_ipv4;
9144 	else
9145 		mss_max = tcps->tcps_mss_max_ipv6;
9146 
9147 	if (mss < tcps->tcps_mss_min)
9148 		mss = tcps->tcps_mss_min;
9149 	if (mss > mss_max)
9150 		mss = mss_max;
9151 	/*
9152 	 * Unless naglim has been set by our client to
9153 	 * a non-mss value, force naglim to track mss.
9154 	 * This can help to aggregate small writes.
9155 	 */
9156 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9157 		tcp->tcp_naglim = mss;
9158 	/*
9159 	 * TCP should be able to buffer at least 4 MSS data for obvious
9160 	 * performance reason.
9161 	 */
9162 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9163 		tcp->tcp_xmit_hiwater = mss << 2;
9164 
9165 	/*
9166 	 * Set the xmit_lowater to at least twice of MSS.
9167 	 */
9168 	if ((mss << 1) > tcp->tcp_xmit_lowater)
9169 		tcp->tcp_xmit_lowater = mss << 1;
9170 
9171 	if (do_ss) {
9172 		/*
9173 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9174 		 * changing due to a reduction in MTU, presumably as a
9175 		 * result of a new path component, reset cwnd to its
9176 		 * "initial" value, as a multiple of the new mss.
9177 		 */
9178 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9179 	} else {
9180 		/*
9181 		 * Called by tcp_paws_check(), the mss increased
9182 		 * marginally to allow use of space previously taken
9183 		 * by the timestamp option. It would be inappropriate
9184 		 * to apply slow start or tcp_init_cwnd values to
9185 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9186 		 */
9187 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9188 		tcp->tcp_cwnd_cnt = 0;
9189 	}
9190 	tcp->tcp_mss = mss;
9191 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9192 }
9193 
9194 /* For /dev/tcp aka AF_INET open */
9195 static int
9196 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9197 {
9198 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9199 }
9200 
9201 /* For /dev/tcp6 aka AF_INET6 open */
9202 static int
9203 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9204 {
9205 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9206 }
9207 
9208 static conn_t *
9209 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9210     boolean_t issocket, int *errorp)
9211 {
9212 	tcp_t		*tcp = NULL;
9213 	conn_t		*connp;
9214 	int		err;
9215 	zoneid_t	zoneid;
9216 	tcp_stack_t	*tcps;
9217 	squeue_t	*sqp;
9218 
9219 	ASSERT(errorp != NULL);
9220 	/*
9221 	 * Find the proper zoneid and netstack.
9222 	 */
9223 	/*
9224 	 * Special case for install: miniroot needs to be able to
9225 	 * access files via NFS as though it were always in the
9226 	 * global zone.
9227 	 */
9228 	if (credp == kcred && nfs_global_client_only != 0) {
9229 		zoneid = GLOBAL_ZONEID;
9230 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9231 		    netstack_tcp;
9232 		ASSERT(tcps != NULL);
9233 	} else {
9234 		netstack_t *ns;
9235 
9236 		ns = netstack_find_by_cred(credp);
9237 		ASSERT(ns != NULL);
9238 		tcps = ns->netstack_tcp;
9239 		ASSERT(tcps != NULL);
9240 
9241 		/*
9242 		 * For exclusive stacks we set the zoneid to zero
9243 		 * to make TCP operate as if in the global zone.
9244 		 */
9245 		if (tcps->tcps_netstack->netstack_stackid !=
9246 		    GLOBAL_NETSTACKID)
9247 			zoneid = GLOBAL_ZONEID;
9248 		else
9249 			zoneid = crgetzoneid(credp);
9250 	}
9251 	/*
9252 	 * For stackid zero this is done from strplumb.c, but
9253 	 * non-zero stackids are handled here.
9254 	 */
9255 	if (tcps->tcps_g_q == NULL &&
9256 	    tcps->tcps_netstack->netstack_stackid !=
9257 	    GLOBAL_NETSTACKID) {
9258 		tcp_g_q_setup(tcps);
9259 	}
9260 
9261 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9262 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9263 	/*
9264 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9265 	 * so we drop it by one.
9266 	 */
9267 	netstack_rele(tcps->tcps_netstack);
9268 	if (connp == NULL) {
9269 		*errorp = ENOSR;
9270 		return (NULL);
9271 	}
9272 	connp->conn_sqp = sqp;
9273 	connp->conn_initial_sqp = connp->conn_sqp;
9274 	tcp = connp->conn_tcp;
9275 
9276 	if (isv6) {
9277 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9278 		connp->conn_send = ip_output_v6;
9279 		connp->conn_af_isv6 = B_TRUE;
9280 		connp->conn_pkt_isv6 = B_TRUE;
9281 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9282 		tcp->tcp_ipversion = IPV6_VERSION;
9283 		tcp->tcp_family = AF_INET6;
9284 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9285 	} else {
9286 		connp->conn_flags |= IPCL_TCP4;
9287 		connp->conn_send = ip_output;
9288 		connp->conn_af_isv6 = B_FALSE;
9289 		connp->conn_pkt_isv6 = B_FALSE;
9290 		tcp->tcp_ipversion = IPV4_VERSION;
9291 		tcp->tcp_family = AF_INET;
9292 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9293 	}
9294 
9295 	/*
9296 	 * TCP keeps a copy of cred for cache locality reasons but
9297 	 * we put a reference only once. If connp->conn_cred
9298 	 * becomes invalid, tcp_cred should also be set to NULL.
9299 	 */
9300 	tcp->tcp_cred = connp->conn_cred = credp;
9301 	crhold(connp->conn_cred);
9302 	tcp->tcp_cpid = curproc->p_pid;
9303 	tcp->tcp_open_time = lbolt64;
9304 	connp->conn_zoneid = zoneid;
9305 	connp->conn_mlp_type = mlptSingle;
9306 	connp->conn_ulp_labeled = !is_system_labeled();
9307 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9308 	ASSERT(tcp->tcp_tcps == tcps);
9309 
9310 	/*
9311 	 * If the caller has the process-wide flag set, then default to MAC
9312 	 * exempt mode.  This allows read-down to unlabeled hosts.
9313 	 */
9314 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9315 		connp->conn_mac_exempt = B_TRUE;
9316 
9317 	connp->conn_dev = NULL;
9318 	if (issocket) {
9319 		connp->conn_flags |= IPCL_SOCKET;
9320 		tcp->tcp_issocket = 1;
9321 	}
9322 
9323 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9324 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9325 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9326 
9327 	/* Non-zero default values */
9328 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9329 
9330 	if (q == NULL) {
9331 		/*
9332 		 * Create a helper stream for non-STREAMS socket.
9333 		 */
9334 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9335 		if (err != 0) {
9336 			ip1dbg(("tcp_create_common: create of IP helper stream "
9337 			    "failed\n"));
9338 			CONN_DEC_REF(connp);
9339 			*errorp = err;
9340 			return (NULL);
9341 		}
9342 		q = connp->conn_rq;
9343 	}
9344 
9345 	SOCK_CONNID_INIT(tcp->tcp_connid);
9346 	err = tcp_init(tcp, q);
9347 	if (err != 0) {
9348 		CONN_DEC_REF(connp);
9349 		*errorp = err;
9350 		return (NULL);
9351 	}
9352 
9353 	return (connp);
9354 }
9355 
9356 static int
9357 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9358     boolean_t isv6)
9359 {
9360 	tcp_t		*tcp = NULL;
9361 	conn_t		*connp = NULL;
9362 	int		err;
9363 	vmem_t		*minor_arena = NULL;
9364 	dev_t		conn_dev;
9365 	boolean_t	issocket;
9366 
9367 	if (q->q_ptr != NULL)
9368 		return (0);
9369 
9370 	if (sflag == MODOPEN)
9371 		return (EINVAL);
9372 
9373 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9374 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9375 		minor_arena = ip_minor_arena_la;
9376 	} else {
9377 		/*
9378 		 * Either minor numbers in the large arena were exhausted
9379 		 * or a non socket application is doing the open.
9380 		 * Try to allocate from the small arena.
9381 		 */
9382 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9383 			return (EBUSY);
9384 		}
9385 		minor_arena = ip_minor_arena_sa;
9386 	}
9387 
9388 	ASSERT(minor_arena != NULL);
9389 
9390 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9391 
9392 	if (flag & SO_FALLBACK) {
9393 		/*
9394 		 * Non streams socket needs a stream to fallback to
9395 		 */
9396 		RD(q)->q_ptr = (void *)conn_dev;
9397 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9398 		WR(q)->q_ptr = (void *)minor_arena;
9399 		qprocson(q);
9400 		return (0);
9401 	} else if (flag & SO_ACCEPTOR) {
9402 		q->q_qinfo = &tcp_acceptor_rinit;
9403 		/*
9404 		 * the conn_dev and minor_arena will be subsequently used by
9405 		 * tcp_wput_accept() and tcp_tpi_close_accept() to figure out
9406 		 * the minor device number for this connection from the q_ptr.
9407 		 */
9408 		RD(q)->q_ptr = (void *)conn_dev;
9409 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9410 		WR(q)->q_ptr = (void *)minor_arena;
9411 		qprocson(q);
9412 		return (0);
9413 	}
9414 
9415 	issocket = flag & SO_SOCKSTR;
9416 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9417 
9418 	if (connp == NULL) {
9419 		inet_minor_free(minor_arena, conn_dev);
9420 		q->q_ptr = WR(q)->q_ptr = NULL;
9421 		return (err);
9422 	}
9423 
9424 	q->q_ptr = WR(q)->q_ptr = connp;
9425 
9426 	connp->conn_dev = conn_dev;
9427 	connp->conn_minor_arena = minor_arena;
9428 
9429 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9430 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9431 
9432 	tcp = connp->conn_tcp;
9433 
9434 	if (issocket) {
9435 		WR(q)->q_qinfo = &tcp_sock_winit;
9436 	} else {
9437 #ifdef  _ILP32
9438 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9439 #else
9440 		tcp->tcp_acceptor_id = conn_dev;
9441 #endif  /* _ILP32 */
9442 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9443 	}
9444 
9445 	/*
9446 	 * Put the ref for TCP. Ref for IP was already put
9447 	 * by ipcl_conn_create. Also Make the conn_t globally
9448 	 * visible to walkers
9449 	 */
9450 	mutex_enter(&connp->conn_lock);
9451 	CONN_INC_REF_LOCKED(connp);
9452 	ASSERT(connp->conn_ref == 2);
9453 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9454 	mutex_exit(&connp->conn_lock);
9455 
9456 	qprocson(q);
9457 	return (0);
9458 }
9459 
9460 /*
9461  * Some TCP options can be "set" by requesting them in the option
9462  * buffer. This is needed for XTI feature test though we do not
9463  * allow it in general. We interpret that this mechanism is more
9464  * applicable to OSI protocols and need not be allowed in general.
9465  * This routine filters out options for which it is not allowed (most)
9466  * and lets through those (few) for which it is. [ The XTI interface
9467  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9468  * ever implemented will have to be allowed here ].
9469  */
9470 static boolean_t
9471 tcp_allow_connopt_set(int level, int name)
9472 {
9473 
9474 	switch (level) {
9475 	case IPPROTO_TCP:
9476 		switch (name) {
9477 		case TCP_NODELAY:
9478 			return (B_TRUE);
9479 		default:
9480 			return (B_FALSE);
9481 		}
9482 		/*NOTREACHED*/
9483 	default:
9484 		return (B_FALSE);
9485 	}
9486 	/*NOTREACHED*/
9487 }
9488 
9489 /*
9490  * this routine gets default values of certain options whose default
9491  * values are maintained by protocol specific code
9492  */
9493 /* ARGSUSED */
9494 int
9495 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9496 {
9497 	int32_t	*i1 = (int32_t *)ptr;
9498 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9499 
9500 	switch (level) {
9501 	case IPPROTO_TCP:
9502 		switch (name) {
9503 		case TCP_NOTIFY_THRESHOLD:
9504 			*i1 = tcps->tcps_ip_notify_interval;
9505 			break;
9506 		case TCP_ABORT_THRESHOLD:
9507 			*i1 = tcps->tcps_ip_abort_interval;
9508 			break;
9509 		case TCP_CONN_NOTIFY_THRESHOLD:
9510 			*i1 = tcps->tcps_ip_notify_cinterval;
9511 			break;
9512 		case TCP_CONN_ABORT_THRESHOLD:
9513 			*i1 = tcps->tcps_ip_abort_cinterval;
9514 			break;
9515 		default:
9516 			return (-1);
9517 		}
9518 		break;
9519 	case IPPROTO_IP:
9520 		switch (name) {
9521 		case IP_TTL:
9522 			*i1 = tcps->tcps_ipv4_ttl;
9523 			break;
9524 		default:
9525 			return (-1);
9526 		}
9527 		break;
9528 	case IPPROTO_IPV6:
9529 		switch (name) {
9530 		case IPV6_UNICAST_HOPS:
9531 			*i1 = tcps->tcps_ipv6_hoplimit;
9532 			break;
9533 		default:
9534 			return (-1);
9535 		}
9536 		break;
9537 	default:
9538 		return (-1);
9539 	}
9540 	return (sizeof (int));
9541 }
9542 
9543 static int
9544 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9545 {
9546 	int		*i1 = (int *)ptr;
9547 	tcp_t		*tcp = connp->conn_tcp;
9548 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9549 
9550 	switch (level) {
9551 	case SOL_SOCKET:
9552 		switch (name) {
9553 		case SO_LINGER:	{
9554 			struct linger *lgr = (struct linger *)ptr;
9555 
9556 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9557 			lgr->l_linger = tcp->tcp_lingertime;
9558 			}
9559 			return (sizeof (struct linger));
9560 		case SO_DEBUG:
9561 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9562 			break;
9563 		case SO_KEEPALIVE:
9564 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9565 			break;
9566 		case SO_DONTROUTE:
9567 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9568 			break;
9569 		case SO_USELOOPBACK:
9570 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9571 			break;
9572 		case SO_BROADCAST:
9573 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9574 			break;
9575 		case SO_REUSEADDR:
9576 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9577 			break;
9578 		case SO_OOBINLINE:
9579 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9580 			break;
9581 		case SO_DGRAM_ERRIND:
9582 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9583 			break;
9584 		case SO_TYPE:
9585 			*i1 = SOCK_STREAM;
9586 			break;
9587 		case SO_SNDBUF:
9588 			*i1 = tcp->tcp_xmit_hiwater;
9589 			break;
9590 		case SO_RCVBUF:
9591 			*i1 = tcp->tcp_recv_hiwater;
9592 			break;
9593 		case SO_SND_COPYAVOID:
9594 			*i1 = tcp->tcp_snd_zcopy_on ?
9595 			    SO_SND_COPYAVOID : 0;
9596 			break;
9597 		case SO_ALLZONES:
9598 			*i1 = connp->conn_allzones ? 1 : 0;
9599 			break;
9600 		case SO_ANON_MLP:
9601 			*i1 = connp->conn_anon_mlp;
9602 			break;
9603 		case SO_MAC_EXEMPT:
9604 			*i1 = connp->conn_mac_exempt;
9605 			break;
9606 		case SO_EXCLBIND:
9607 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9608 			break;
9609 		case SO_PROTOTYPE:
9610 			*i1 = IPPROTO_TCP;
9611 			break;
9612 		case SO_DOMAIN:
9613 			*i1 = tcp->tcp_family;
9614 			break;
9615 		case SO_ACCEPTCONN:
9616 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9617 		default:
9618 			return (-1);
9619 		}
9620 		break;
9621 	case IPPROTO_TCP:
9622 		switch (name) {
9623 		case TCP_NODELAY:
9624 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9625 			break;
9626 		case TCP_MAXSEG:
9627 			*i1 = tcp->tcp_mss;
9628 			break;
9629 		case TCP_NOTIFY_THRESHOLD:
9630 			*i1 = (int)tcp->tcp_first_timer_threshold;
9631 			break;
9632 		case TCP_ABORT_THRESHOLD:
9633 			*i1 = tcp->tcp_second_timer_threshold;
9634 			break;
9635 		case TCP_CONN_NOTIFY_THRESHOLD:
9636 			*i1 = tcp->tcp_first_ctimer_threshold;
9637 			break;
9638 		case TCP_CONN_ABORT_THRESHOLD:
9639 			*i1 = tcp->tcp_second_ctimer_threshold;
9640 			break;
9641 		case TCP_RECVDSTADDR:
9642 			*i1 = tcp->tcp_recvdstaddr;
9643 			break;
9644 		case TCP_ANONPRIVBIND:
9645 			*i1 = tcp->tcp_anon_priv_bind;
9646 			break;
9647 		case TCP_EXCLBIND:
9648 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9649 			break;
9650 		case TCP_INIT_CWND:
9651 			*i1 = tcp->tcp_init_cwnd;
9652 			break;
9653 		case TCP_KEEPALIVE_THRESHOLD:
9654 			*i1 = tcp->tcp_ka_interval;
9655 			break;
9656 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9657 			*i1 = tcp->tcp_ka_abort_thres;
9658 			break;
9659 		case TCP_CORK:
9660 			*i1 = tcp->tcp_cork;
9661 			break;
9662 		default:
9663 			return (-1);
9664 		}
9665 		break;
9666 	case IPPROTO_IP:
9667 		if (tcp->tcp_family != AF_INET)
9668 			return (-1);
9669 		switch (name) {
9670 		case IP_OPTIONS:
9671 		case T_IP_OPTIONS: {
9672 			/*
9673 			 * This is compatible with BSD in that in only return
9674 			 * the reverse source route with the final destination
9675 			 * as the last entry. The first 4 bytes of the option
9676 			 * will contain the final destination.
9677 			 */
9678 			int	opt_len;
9679 
9680 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9681 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9682 			ASSERT(opt_len >= 0);
9683 			/* Caller ensures enough space */
9684 			if (opt_len > 0) {
9685 				/*
9686 				 * TODO: Do we have to handle getsockopt on an
9687 				 * initiator as well?
9688 				 */
9689 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9690 			}
9691 			return (0);
9692 			}
9693 		case IP_TOS:
9694 		case T_IP_TOS:
9695 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9696 			break;
9697 		case IP_TTL:
9698 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9699 			break;
9700 		case IP_NEXTHOP:
9701 			/* Handled at IP level */
9702 			return (-EINVAL);
9703 		default:
9704 			return (-1);
9705 		}
9706 		break;
9707 	case IPPROTO_IPV6:
9708 		/*
9709 		 * IPPROTO_IPV6 options are only supported for sockets
9710 		 * that are using IPv6 on the wire.
9711 		 */
9712 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9713 			return (-1);
9714 		}
9715 		switch (name) {
9716 		case IPV6_UNICAST_HOPS:
9717 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9718 			break;	/* goto sizeof (int) option return */
9719 		case IPV6_BOUND_IF:
9720 			/* Zero if not set */
9721 			*i1 = tcp->tcp_bound_if;
9722 			break;	/* goto sizeof (int) option return */
9723 		case IPV6_RECVPKTINFO:
9724 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9725 				*i1 = 1;
9726 			else
9727 				*i1 = 0;
9728 			break;	/* goto sizeof (int) option return */
9729 		case IPV6_RECVTCLASS:
9730 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9731 				*i1 = 1;
9732 			else
9733 				*i1 = 0;
9734 			break;	/* goto sizeof (int) option return */
9735 		case IPV6_RECVHOPLIMIT:
9736 			if (tcp->tcp_ipv6_recvancillary &
9737 			    TCP_IPV6_RECVHOPLIMIT)
9738 				*i1 = 1;
9739 			else
9740 				*i1 = 0;
9741 			break;	/* goto sizeof (int) option return */
9742 		case IPV6_RECVHOPOPTS:
9743 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9744 				*i1 = 1;
9745 			else
9746 				*i1 = 0;
9747 			break;	/* goto sizeof (int) option return */
9748 		case IPV6_RECVDSTOPTS:
9749 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9750 				*i1 = 1;
9751 			else
9752 				*i1 = 0;
9753 			break;	/* goto sizeof (int) option return */
9754 		case _OLD_IPV6_RECVDSTOPTS:
9755 			if (tcp->tcp_ipv6_recvancillary &
9756 			    TCP_OLD_IPV6_RECVDSTOPTS)
9757 				*i1 = 1;
9758 			else
9759 				*i1 = 0;
9760 			break;	/* goto sizeof (int) option return */
9761 		case IPV6_RECVRTHDR:
9762 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9763 				*i1 = 1;
9764 			else
9765 				*i1 = 0;
9766 			break;	/* goto sizeof (int) option return */
9767 		case IPV6_RECVRTHDRDSTOPTS:
9768 			if (tcp->tcp_ipv6_recvancillary &
9769 			    TCP_IPV6_RECVRTDSTOPTS)
9770 				*i1 = 1;
9771 			else
9772 				*i1 = 0;
9773 			break;	/* goto sizeof (int) option return */
9774 		case IPV6_PKTINFO: {
9775 			/* XXX assumes that caller has room for max size! */
9776 			struct in6_pktinfo *pkti;
9777 
9778 			pkti = (struct in6_pktinfo *)ptr;
9779 			if (ipp->ipp_fields & IPPF_IFINDEX)
9780 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9781 			else
9782 				pkti->ipi6_ifindex = 0;
9783 			if (ipp->ipp_fields & IPPF_ADDR)
9784 				pkti->ipi6_addr = ipp->ipp_addr;
9785 			else
9786 				pkti->ipi6_addr = ipv6_all_zeros;
9787 			return (sizeof (struct in6_pktinfo));
9788 		}
9789 		case IPV6_TCLASS:
9790 			if (ipp->ipp_fields & IPPF_TCLASS)
9791 				*i1 = ipp->ipp_tclass;
9792 			else
9793 				*i1 = IPV6_FLOW_TCLASS(
9794 				    IPV6_DEFAULT_VERS_AND_FLOW);
9795 			break;	/* goto sizeof (int) option return */
9796 		case IPV6_NEXTHOP: {
9797 			sin6_t *sin6 = (sin6_t *)ptr;
9798 
9799 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9800 				return (0);
9801 			*sin6 = sin6_null;
9802 			sin6->sin6_family = AF_INET6;
9803 			sin6->sin6_addr = ipp->ipp_nexthop;
9804 			return (sizeof (sin6_t));
9805 		}
9806 		case IPV6_HOPOPTS:
9807 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9808 				return (0);
9809 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9810 				return (0);
9811 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9812 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9813 			if (tcp->tcp_label_len > 0) {
9814 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9815 				ptr[1] = (ipp->ipp_hopoptslen -
9816 				    tcp->tcp_label_len + 7) / 8 - 1;
9817 			}
9818 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9819 		case IPV6_RTHDRDSTOPTS:
9820 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9821 				return (0);
9822 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9823 			return (ipp->ipp_rtdstoptslen);
9824 		case IPV6_RTHDR:
9825 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9826 				return (0);
9827 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9828 			return (ipp->ipp_rthdrlen);
9829 		case IPV6_DSTOPTS:
9830 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9831 				return (0);
9832 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9833 			return (ipp->ipp_dstoptslen);
9834 		case IPV6_SRC_PREFERENCES:
9835 			return (ip6_get_src_preferences(connp,
9836 			    (uint32_t *)ptr));
9837 		case IPV6_PATHMTU: {
9838 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9839 
9840 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9841 				return (-1);
9842 
9843 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9844 			    connp->conn_fport, mtuinfo,
9845 			    connp->conn_netstack));
9846 		}
9847 		default:
9848 			return (-1);
9849 		}
9850 		break;
9851 	default:
9852 		return (-1);
9853 	}
9854 	return (sizeof (int));
9855 }
9856 
9857 /*
9858  * TCP routine to get the values of options.
9859  */
9860 int
9861 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9862 {
9863 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9864 }
9865 
9866 /* returns UNIX error, the optlen is a value-result arg */
9867 int
9868 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9869     void *optvalp, socklen_t *optlen, cred_t *cr)
9870 {
9871 	conn_t		*connp = (conn_t *)proto_handle;
9872 	squeue_t	*sqp = connp->conn_sqp;
9873 	int		error;
9874 	t_uscalar_t	max_optbuf_len;
9875 	void		*optvalp_buf;
9876 	int		len;
9877 
9878 	ASSERT(connp->conn_upper_handle != NULL);
9879 
9880 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9881 	    tcp_opt_obj.odb_opt_des_arr,
9882 	    tcp_opt_obj.odb_opt_arr_cnt,
9883 	    tcp_opt_obj.odb_topmost_tpiprovider,
9884 	    B_FALSE, B_TRUE, cr);
9885 	if (error != 0) {
9886 		if (error < 0) {
9887 			error = proto_tlitosyserr(-error);
9888 		}
9889 		return (error);
9890 	}
9891 
9892 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9893 
9894 	error = squeue_synch_enter(sqp, connp, NULL);
9895 	if (error == ENOMEM) {
9896 		return (ENOMEM);
9897 	}
9898 
9899 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9900 	squeue_synch_exit(sqp, connp);
9901 
9902 	if (len < 0) {
9903 		/*
9904 		 * Pass on to IP
9905 		 */
9906 		kmem_free(optvalp_buf, max_optbuf_len);
9907 		return (ip_get_options(connp, level, option_name,
9908 		    optvalp, optlen, cr));
9909 	} else {
9910 		/*
9911 		 * update optlen and copy option value
9912 		 */
9913 		t_uscalar_t size = MIN(len, *optlen);
9914 		bcopy(optvalp_buf, optvalp, size);
9915 		bcopy(&size, optlen, sizeof (size));
9916 
9917 		kmem_free(optvalp_buf, max_optbuf_len);
9918 		return (0);
9919 	}
9920 }
9921 
9922 /*
9923  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9924  * Parameters are assumed to be verified by the caller.
9925  */
9926 /* ARGSUSED */
9927 int
9928 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9929     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9930     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9931 {
9932 	tcp_t	*tcp = connp->conn_tcp;
9933 	int	*i1 = (int *)invalp;
9934 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9935 	boolean_t checkonly;
9936 	int	reterr;
9937 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9938 
9939 	switch (optset_context) {
9940 	case SETFN_OPTCOM_CHECKONLY:
9941 		checkonly = B_TRUE;
9942 		/*
9943 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9944 		 * inlen != 0 implies value supplied and
9945 		 * 	we have to "pretend" to set it.
9946 		 * inlen == 0 implies that there is no
9947 		 * 	value part in T_CHECK request and just validation
9948 		 * done elsewhere should be enough, we just return here.
9949 		 */
9950 		if (inlen == 0) {
9951 			*outlenp = 0;
9952 			return (0);
9953 		}
9954 		break;
9955 	case SETFN_OPTCOM_NEGOTIATE:
9956 		checkonly = B_FALSE;
9957 		break;
9958 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9959 	case SETFN_CONN_NEGOTIATE:
9960 		checkonly = B_FALSE;
9961 		/*
9962 		 * Negotiating local and "association-related" options
9963 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9964 		 * primitives is allowed by XTI, but we choose
9965 		 * to not implement this style negotiation for Internet
9966 		 * protocols (We interpret it is a must for OSI world but
9967 		 * optional for Internet protocols) for all options.
9968 		 * [ Will do only for the few options that enable test
9969 		 * suites that our XTI implementation of this feature
9970 		 * works for transports that do allow it ]
9971 		 */
9972 		if (!tcp_allow_connopt_set(level, name)) {
9973 			*outlenp = 0;
9974 			return (EINVAL);
9975 		}
9976 		break;
9977 	default:
9978 		/*
9979 		 * We should never get here
9980 		 */
9981 		*outlenp = 0;
9982 		return (EINVAL);
9983 	}
9984 
9985 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9986 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9987 
9988 	/*
9989 	 * For TCP, we should have no ancillary data sent down
9990 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9991 	 * has to be zero.
9992 	 */
9993 	ASSERT(thisdg_attrs == NULL);
9994 
9995 	/*
9996 	 * For fixed length options, no sanity check
9997 	 * of passed in length is done. It is assumed *_optcom_req()
9998 	 * routines do the right thing.
9999 	 */
10000 	switch (level) {
10001 	case SOL_SOCKET:
10002 		switch (name) {
10003 		case SO_LINGER: {
10004 			struct linger *lgr = (struct linger *)invalp;
10005 
10006 			if (!checkonly) {
10007 				if (lgr->l_onoff) {
10008 					tcp->tcp_linger = 1;
10009 					tcp->tcp_lingertime = lgr->l_linger;
10010 				} else {
10011 					tcp->tcp_linger = 0;
10012 					tcp->tcp_lingertime = 0;
10013 				}
10014 				/* struct copy */
10015 				*(struct linger *)outvalp = *lgr;
10016 			} else {
10017 				if (!lgr->l_onoff) {
10018 					((struct linger *)
10019 					    outvalp)->l_onoff = 0;
10020 					((struct linger *)
10021 					    outvalp)->l_linger = 0;
10022 				} else {
10023 					/* struct copy */
10024 					*(struct linger *)outvalp = *lgr;
10025 				}
10026 			}
10027 			*outlenp = sizeof (struct linger);
10028 			return (0);
10029 		}
10030 		case SO_DEBUG:
10031 			if (!checkonly)
10032 				tcp->tcp_debug = onoff;
10033 			break;
10034 		case SO_KEEPALIVE:
10035 			if (checkonly) {
10036 				/* check only case */
10037 				break;
10038 			}
10039 
10040 			if (!onoff) {
10041 				if (tcp->tcp_ka_enabled) {
10042 					if (tcp->tcp_ka_tid != 0) {
10043 						(void) TCP_TIMER_CANCEL(tcp,
10044 						    tcp->tcp_ka_tid);
10045 						tcp->tcp_ka_tid = 0;
10046 					}
10047 					tcp->tcp_ka_enabled = 0;
10048 				}
10049 				break;
10050 			}
10051 			if (!tcp->tcp_ka_enabled) {
10052 				/* Crank up the keepalive timer */
10053 				tcp->tcp_ka_last_intrvl = 0;
10054 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10055 				    tcp_keepalive_killer,
10056 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10057 				tcp->tcp_ka_enabled = 1;
10058 			}
10059 			break;
10060 		case SO_DONTROUTE:
10061 			/*
10062 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10063 			 * only of interest to IP.  We track them here only so
10064 			 * that we can report their current value.
10065 			 */
10066 			if (!checkonly) {
10067 				tcp->tcp_dontroute = onoff;
10068 				tcp->tcp_connp->conn_dontroute = onoff;
10069 			}
10070 			break;
10071 		case SO_USELOOPBACK:
10072 			if (!checkonly) {
10073 				tcp->tcp_useloopback = onoff;
10074 				tcp->tcp_connp->conn_loopback = onoff;
10075 			}
10076 			break;
10077 		case SO_BROADCAST:
10078 			if (!checkonly) {
10079 				tcp->tcp_broadcast = onoff;
10080 				tcp->tcp_connp->conn_broadcast = onoff;
10081 			}
10082 			break;
10083 		case SO_REUSEADDR:
10084 			if (!checkonly) {
10085 				tcp->tcp_reuseaddr = onoff;
10086 				tcp->tcp_connp->conn_reuseaddr = onoff;
10087 			}
10088 			break;
10089 		case SO_OOBINLINE:
10090 			if (!checkonly) {
10091 				tcp->tcp_oobinline = onoff;
10092 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10093 					proto_set_rx_oob_opt(connp, onoff);
10094 			}
10095 			break;
10096 		case SO_DGRAM_ERRIND:
10097 			if (!checkonly)
10098 				tcp->tcp_dgram_errind = onoff;
10099 			break;
10100 		case SO_SNDBUF: {
10101 			if (*i1 > tcps->tcps_max_buf) {
10102 				*outlenp = 0;
10103 				return (ENOBUFS);
10104 			}
10105 			if (checkonly)
10106 				break;
10107 
10108 			tcp->tcp_xmit_hiwater = *i1;
10109 			if (tcps->tcps_snd_lowat_fraction != 0)
10110 				tcp->tcp_xmit_lowater =
10111 				    tcp->tcp_xmit_hiwater /
10112 				    tcps->tcps_snd_lowat_fraction;
10113 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10114 			/*
10115 			 * If we are flow-controlled, recheck the condition.
10116 			 * There are apps that increase SO_SNDBUF size when
10117 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10118 			 * control condition to be lifted right away.
10119 			 */
10120 			mutex_enter(&tcp->tcp_non_sq_lock);
10121 			if (tcp->tcp_flow_stopped &&
10122 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10123 				tcp_clrqfull(tcp);
10124 			}
10125 			mutex_exit(&tcp->tcp_non_sq_lock);
10126 			break;
10127 		}
10128 		case SO_RCVBUF:
10129 			if (*i1 > tcps->tcps_max_buf) {
10130 				*outlenp = 0;
10131 				return (ENOBUFS);
10132 			}
10133 			/* Silently ignore zero */
10134 			if (!checkonly && *i1 != 0) {
10135 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10136 				(void) tcp_rwnd_set(tcp, *i1);
10137 			}
10138 			/*
10139 			 * XXX should we return the rwnd here
10140 			 * and tcp_opt_get ?
10141 			 */
10142 			break;
10143 		case SO_SND_COPYAVOID:
10144 			if (!checkonly) {
10145 				/* we only allow enable at most once for now */
10146 				if (tcp->tcp_loopback ||
10147 				    (tcp->tcp_kssl_ctx != NULL) ||
10148 				    (!tcp->tcp_snd_zcopy_aware &&
10149 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10150 					*outlenp = 0;
10151 					return (EOPNOTSUPP);
10152 				}
10153 				tcp->tcp_snd_zcopy_aware = 1;
10154 			}
10155 			break;
10156 		case SO_RCVTIMEO:
10157 		case SO_SNDTIMEO:
10158 			/*
10159 			 * Pass these two options in order for third part
10160 			 * protocol usage. Here just return directly.
10161 			 */
10162 			return (0);
10163 		case SO_ALLZONES:
10164 			/* Pass option along to IP level for handling */
10165 			return (-EINVAL);
10166 		case SO_ANON_MLP:
10167 			/* Pass option along to IP level for handling */
10168 			return (-EINVAL);
10169 		case SO_MAC_EXEMPT:
10170 			/* Pass option along to IP level for handling */
10171 			return (-EINVAL);
10172 		case SO_EXCLBIND:
10173 			if (!checkonly)
10174 				tcp->tcp_exclbind = onoff;
10175 			break;
10176 		default:
10177 			*outlenp = 0;
10178 			return (EINVAL);
10179 		}
10180 		break;
10181 	case IPPROTO_TCP:
10182 		switch (name) {
10183 		case TCP_NODELAY:
10184 			if (!checkonly)
10185 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10186 			break;
10187 		case TCP_NOTIFY_THRESHOLD:
10188 			if (!checkonly)
10189 				tcp->tcp_first_timer_threshold = *i1;
10190 			break;
10191 		case TCP_ABORT_THRESHOLD:
10192 			if (!checkonly)
10193 				tcp->tcp_second_timer_threshold = *i1;
10194 			break;
10195 		case TCP_CONN_NOTIFY_THRESHOLD:
10196 			if (!checkonly)
10197 				tcp->tcp_first_ctimer_threshold = *i1;
10198 			break;
10199 		case TCP_CONN_ABORT_THRESHOLD:
10200 			if (!checkonly)
10201 				tcp->tcp_second_ctimer_threshold = *i1;
10202 			break;
10203 		case TCP_RECVDSTADDR:
10204 			if (tcp->tcp_state > TCPS_LISTEN)
10205 				return (EOPNOTSUPP);
10206 			if (!checkonly)
10207 				tcp->tcp_recvdstaddr = onoff;
10208 			break;
10209 		case TCP_ANONPRIVBIND:
10210 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10211 			    IPPROTO_TCP)) != 0) {
10212 				*outlenp = 0;
10213 				return (reterr);
10214 			}
10215 			if (!checkonly) {
10216 				tcp->tcp_anon_priv_bind = onoff;
10217 			}
10218 			break;
10219 		case TCP_EXCLBIND:
10220 			if (!checkonly)
10221 				tcp->tcp_exclbind = onoff;
10222 			break;	/* goto sizeof (int) option return */
10223 		case TCP_INIT_CWND: {
10224 			uint32_t init_cwnd = *((uint32_t *)invalp);
10225 
10226 			if (checkonly)
10227 				break;
10228 
10229 			/*
10230 			 * Only allow socket with network configuration
10231 			 * privilege to set the initial cwnd to be larger
10232 			 * than allowed by RFC 3390.
10233 			 */
10234 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10235 				tcp->tcp_init_cwnd = init_cwnd;
10236 				break;
10237 			}
10238 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10239 				*outlenp = 0;
10240 				return (reterr);
10241 			}
10242 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10243 				*outlenp = 0;
10244 				return (EINVAL);
10245 			}
10246 			tcp->tcp_init_cwnd = init_cwnd;
10247 			break;
10248 		}
10249 		case TCP_KEEPALIVE_THRESHOLD:
10250 			if (checkonly)
10251 				break;
10252 
10253 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10254 			    *i1 > tcps->tcps_keepalive_interval_high) {
10255 				*outlenp = 0;
10256 				return (EINVAL);
10257 			}
10258 			if (*i1 != tcp->tcp_ka_interval) {
10259 				tcp->tcp_ka_interval = *i1;
10260 				/*
10261 				 * Check if we need to restart the
10262 				 * keepalive timer.
10263 				 */
10264 				if (tcp->tcp_ka_tid != 0) {
10265 					ASSERT(tcp->tcp_ka_enabled);
10266 					(void) TCP_TIMER_CANCEL(tcp,
10267 					    tcp->tcp_ka_tid);
10268 					tcp->tcp_ka_last_intrvl = 0;
10269 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10270 					    tcp_keepalive_killer,
10271 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10272 				}
10273 			}
10274 			break;
10275 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10276 			if (!checkonly) {
10277 				if (*i1 <
10278 				    tcps->tcps_keepalive_abort_interval_low ||
10279 				    *i1 >
10280 				    tcps->tcps_keepalive_abort_interval_high) {
10281 					*outlenp = 0;
10282 					return (EINVAL);
10283 				}
10284 				tcp->tcp_ka_abort_thres = *i1;
10285 			}
10286 			break;
10287 		case TCP_CORK:
10288 			if (!checkonly) {
10289 				/*
10290 				 * if tcp->tcp_cork was set and is now
10291 				 * being unset, we have to make sure that
10292 				 * the remaining data gets sent out. Also
10293 				 * unset tcp->tcp_cork so that tcp_wput_data()
10294 				 * can send data even if it is less than mss
10295 				 */
10296 				if (tcp->tcp_cork && onoff == 0 &&
10297 				    tcp->tcp_unsent > 0) {
10298 					tcp->tcp_cork = B_FALSE;
10299 					tcp_wput_data(tcp, NULL, B_FALSE);
10300 				}
10301 				tcp->tcp_cork = onoff;
10302 			}
10303 			break;
10304 		default:
10305 			*outlenp = 0;
10306 			return (EINVAL);
10307 		}
10308 		break;
10309 	case IPPROTO_IP:
10310 		if (tcp->tcp_family != AF_INET) {
10311 			*outlenp = 0;
10312 			return (ENOPROTOOPT);
10313 		}
10314 		switch (name) {
10315 		case IP_OPTIONS:
10316 		case T_IP_OPTIONS:
10317 			reterr = tcp_opt_set_header(tcp, checkonly,
10318 			    invalp, inlen);
10319 			if (reterr) {
10320 				*outlenp = 0;
10321 				return (reterr);
10322 			}
10323 			/* OK return - copy input buffer into output buffer */
10324 			if (invalp != outvalp) {
10325 				/* don't trust bcopy for identical src/dst */
10326 				bcopy(invalp, outvalp, inlen);
10327 			}
10328 			*outlenp = inlen;
10329 			return (0);
10330 		case IP_TOS:
10331 		case T_IP_TOS:
10332 			if (!checkonly) {
10333 				tcp->tcp_ipha->ipha_type_of_service =
10334 				    (uchar_t)*i1;
10335 				tcp->tcp_tos = (uchar_t)*i1;
10336 			}
10337 			break;
10338 		case IP_TTL:
10339 			if (!checkonly) {
10340 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10341 				tcp->tcp_ttl = (uchar_t)*i1;
10342 			}
10343 			break;
10344 		case IP_BOUND_IF:
10345 		case IP_NEXTHOP:
10346 			/* Handled at the IP level */
10347 			return (-EINVAL);
10348 		case IP_SEC_OPT:
10349 			/*
10350 			 * We should not allow policy setting after
10351 			 * we start listening for connections.
10352 			 */
10353 			if (tcp->tcp_state == TCPS_LISTEN) {
10354 				return (EINVAL);
10355 			} else {
10356 				/* Handled at the IP level */
10357 				return (-EINVAL);
10358 			}
10359 		default:
10360 			*outlenp = 0;
10361 			return (EINVAL);
10362 		}
10363 		break;
10364 	case IPPROTO_IPV6: {
10365 		ip6_pkt_t		*ipp;
10366 
10367 		/*
10368 		 * IPPROTO_IPV6 options are only supported for sockets
10369 		 * that are using IPv6 on the wire.
10370 		 */
10371 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10372 			*outlenp = 0;
10373 			return (ENOPROTOOPT);
10374 		}
10375 		/*
10376 		 * Only sticky options; no ancillary data
10377 		 */
10378 		ipp = &tcp->tcp_sticky_ipp;
10379 
10380 		switch (name) {
10381 		case IPV6_UNICAST_HOPS:
10382 			/* -1 means use default */
10383 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10384 				*outlenp = 0;
10385 				return (EINVAL);
10386 			}
10387 			if (!checkonly) {
10388 				if (*i1 == -1) {
10389 					tcp->tcp_ip6h->ip6_hops =
10390 					    ipp->ipp_unicast_hops =
10391 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10392 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10393 					/* Pass modified value to IP. */
10394 					*i1 = tcp->tcp_ip6h->ip6_hops;
10395 				} else {
10396 					tcp->tcp_ip6h->ip6_hops =
10397 					    ipp->ipp_unicast_hops =
10398 					    (uint8_t)*i1;
10399 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10400 				}
10401 				reterr = tcp_build_hdrs(tcp);
10402 				if (reterr != 0)
10403 					return (reterr);
10404 			}
10405 			break;
10406 		case IPV6_BOUND_IF:
10407 			if (!checkonly) {
10408 				tcp->tcp_bound_if = *i1;
10409 				PASS_OPT_TO_IP(connp);
10410 			}
10411 			break;
10412 		/*
10413 		 * Set boolean switches for ancillary data delivery
10414 		 */
10415 		case IPV6_RECVPKTINFO:
10416 			if (!checkonly) {
10417 				if (onoff)
10418 					tcp->tcp_ipv6_recvancillary |=
10419 					    TCP_IPV6_RECVPKTINFO;
10420 				else
10421 					tcp->tcp_ipv6_recvancillary &=
10422 					    ~TCP_IPV6_RECVPKTINFO;
10423 				/* Force it to be sent up with the next msg */
10424 				tcp->tcp_recvifindex = 0;
10425 				PASS_OPT_TO_IP(connp);
10426 			}
10427 			break;
10428 		case IPV6_RECVTCLASS:
10429 			if (!checkonly) {
10430 				if (onoff)
10431 					tcp->tcp_ipv6_recvancillary |=
10432 					    TCP_IPV6_RECVTCLASS;
10433 				else
10434 					tcp->tcp_ipv6_recvancillary &=
10435 					    ~TCP_IPV6_RECVTCLASS;
10436 				PASS_OPT_TO_IP(connp);
10437 			}
10438 			break;
10439 		case IPV6_RECVHOPLIMIT:
10440 			if (!checkonly) {
10441 				if (onoff)
10442 					tcp->tcp_ipv6_recvancillary |=
10443 					    TCP_IPV6_RECVHOPLIMIT;
10444 				else
10445 					tcp->tcp_ipv6_recvancillary &=
10446 					    ~TCP_IPV6_RECVHOPLIMIT;
10447 				/* Force it to be sent up with the next msg */
10448 				tcp->tcp_recvhops = 0xffffffffU;
10449 				PASS_OPT_TO_IP(connp);
10450 			}
10451 			break;
10452 		case IPV6_RECVHOPOPTS:
10453 			if (!checkonly) {
10454 				if (onoff)
10455 					tcp->tcp_ipv6_recvancillary |=
10456 					    TCP_IPV6_RECVHOPOPTS;
10457 				else
10458 					tcp->tcp_ipv6_recvancillary &=
10459 					    ~TCP_IPV6_RECVHOPOPTS;
10460 				PASS_OPT_TO_IP(connp);
10461 			}
10462 			break;
10463 		case IPV6_RECVDSTOPTS:
10464 			if (!checkonly) {
10465 				if (onoff)
10466 					tcp->tcp_ipv6_recvancillary |=
10467 					    TCP_IPV6_RECVDSTOPTS;
10468 				else
10469 					tcp->tcp_ipv6_recvancillary &=
10470 					    ~TCP_IPV6_RECVDSTOPTS;
10471 				PASS_OPT_TO_IP(connp);
10472 			}
10473 			break;
10474 		case _OLD_IPV6_RECVDSTOPTS:
10475 			if (!checkonly) {
10476 				if (onoff)
10477 					tcp->tcp_ipv6_recvancillary |=
10478 					    TCP_OLD_IPV6_RECVDSTOPTS;
10479 				else
10480 					tcp->tcp_ipv6_recvancillary &=
10481 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10482 			}
10483 			break;
10484 		case IPV6_RECVRTHDR:
10485 			if (!checkonly) {
10486 				if (onoff)
10487 					tcp->tcp_ipv6_recvancillary |=
10488 					    TCP_IPV6_RECVRTHDR;
10489 				else
10490 					tcp->tcp_ipv6_recvancillary &=
10491 					    ~TCP_IPV6_RECVRTHDR;
10492 				PASS_OPT_TO_IP(connp);
10493 			}
10494 			break;
10495 		case IPV6_RECVRTHDRDSTOPTS:
10496 			if (!checkonly) {
10497 				if (onoff)
10498 					tcp->tcp_ipv6_recvancillary |=
10499 					    TCP_IPV6_RECVRTDSTOPTS;
10500 				else
10501 					tcp->tcp_ipv6_recvancillary &=
10502 					    ~TCP_IPV6_RECVRTDSTOPTS;
10503 				PASS_OPT_TO_IP(connp);
10504 			}
10505 			break;
10506 		case IPV6_PKTINFO:
10507 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10508 				return (EINVAL);
10509 			if (checkonly)
10510 				break;
10511 
10512 			if (inlen == 0) {
10513 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10514 			} else {
10515 				struct in6_pktinfo *pkti;
10516 
10517 				pkti = (struct in6_pktinfo *)invalp;
10518 				/*
10519 				 * RFC 3542 states that ipi6_addr must be
10520 				 * the unspecified address when setting the
10521 				 * IPV6_PKTINFO sticky socket option on a
10522 				 * TCP socket.
10523 				 */
10524 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10525 					return (EINVAL);
10526 				/*
10527 				 * IP will validate the source address and
10528 				 * interface index.
10529 				 */
10530 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10531 					reterr = ip_set_options(tcp->tcp_connp,
10532 					    level, name, invalp, inlen, cr);
10533 				} else {
10534 					reterr = ip6_set_pktinfo(cr,
10535 					    tcp->tcp_connp, pkti);
10536 				}
10537 				if (reterr != 0)
10538 					return (reterr);
10539 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10540 				ipp->ipp_addr = pkti->ipi6_addr;
10541 				if (ipp->ipp_ifindex != 0)
10542 					ipp->ipp_fields |= IPPF_IFINDEX;
10543 				else
10544 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10545 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10546 					ipp->ipp_fields |= IPPF_ADDR;
10547 				else
10548 					ipp->ipp_fields &= ~IPPF_ADDR;
10549 			}
10550 			reterr = tcp_build_hdrs(tcp);
10551 			if (reterr != 0)
10552 				return (reterr);
10553 			break;
10554 		case IPV6_TCLASS:
10555 			if (inlen != 0 && inlen != sizeof (int))
10556 				return (EINVAL);
10557 			if (checkonly)
10558 				break;
10559 
10560 			if (inlen == 0) {
10561 				ipp->ipp_fields &= ~IPPF_TCLASS;
10562 			} else {
10563 				if (*i1 > 255 || *i1 < -1)
10564 					return (EINVAL);
10565 				if (*i1 == -1) {
10566 					ipp->ipp_tclass = 0;
10567 					*i1 = 0;
10568 				} else {
10569 					ipp->ipp_tclass = *i1;
10570 				}
10571 				ipp->ipp_fields |= IPPF_TCLASS;
10572 			}
10573 			reterr = tcp_build_hdrs(tcp);
10574 			if (reterr != 0)
10575 				return (reterr);
10576 			break;
10577 		case IPV6_NEXTHOP:
10578 			/*
10579 			 * IP will verify that the nexthop is reachable
10580 			 * and fail for sticky options.
10581 			 */
10582 			if (inlen != 0 && inlen != sizeof (sin6_t))
10583 				return (EINVAL);
10584 			if (checkonly)
10585 				break;
10586 
10587 			if (inlen == 0) {
10588 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10589 			} else {
10590 				sin6_t *sin6 = (sin6_t *)invalp;
10591 
10592 				if (sin6->sin6_family != AF_INET6)
10593 					return (EAFNOSUPPORT);
10594 				if (IN6_IS_ADDR_V4MAPPED(
10595 				    &sin6->sin6_addr))
10596 					return (EADDRNOTAVAIL);
10597 				ipp->ipp_nexthop = sin6->sin6_addr;
10598 				if (!IN6_IS_ADDR_UNSPECIFIED(
10599 				    &ipp->ipp_nexthop))
10600 					ipp->ipp_fields |= IPPF_NEXTHOP;
10601 				else
10602 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10603 			}
10604 			reterr = tcp_build_hdrs(tcp);
10605 			if (reterr != 0)
10606 				return (reterr);
10607 			PASS_OPT_TO_IP(connp);
10608 			break;
10609 		case IPV6_HOPOPTS: {
10610 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10611 
10612 			/*
10613 			 * Sanity checks - minimum size, size a multiple of
10614 			 * eight bytes, and matching size passed in.
10615 			 */
10616 			if (inlen != 0 &&
10617 			    inlen != (8 * (hopts->ip6h_len + 1)))
10618 				return (EINVAL);
10619 
10620 			if (checkonly)
10621 				break;
10622 
10623 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10624 			    (uchar_t **)&ipp->ipp_hopopts,
10625 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10626 			if (reterr != 0)
10627 				return (reterr);
10628 			if (ipp->ipp_hopoptslen == 0)
10629 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10630 			else
10631 				ipp->ipp_fields |= IPPF_HOPOPTS;
10632 			reterr = tcp_build_hdrs(tcp);
10633 			if (reterr != 0)
10634 				return (reterr);
10635 			break;
10636 		}
10637 		case IPV6_RTHDRDSTOPTS: {
10638 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10639 
10640 			/*
10641 			 * Sanity checks - minimum size, size a multiple of
10642 			 * eight bytes, and matching size passed in.
10643 			 */
10644 			if (inlen != 0 &&
10645 			    inlen != (8 * (dopts->ip6d_len + 1)))
10646 				return (EINVAL);
10647 
10648 			if (checkonly)
10649 				break;
10650 
10651 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10652 			    (uchar_t **)&ipp->ipp_rtdstopts,
10653 			    &ipp->ipp_rtdstoptslen, 0);
10654 			if (reterr != 0)
10655 				return (reterr);
10656 			if (ipp->ipp_rtdstoptslen == 0)
10657 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10658 			else
10659 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10660 			reterr = tcp_build_hdrs(tcp);
10661 			if (reterr != 0)
10662 				return (reterr);
10663 			break;
10664 		}
10665 		case IPV6_DSTOPTS: {
10666 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10667 
10668 			/*
10669 			 * Sanity checks - minimum size, size a multiple of
10670 			 * eight bytes, and matching size passed in.
10671 			 */
10672 			if (inlen != 0 &&
10673 			    inlen != (8 * (dopts->ip6d_len + 1)))
10674 				return (EINVAL);
10675 
10676 			if (checkonly)
10677 				break;
10678 
10679 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10680 			    (uchar_t **)&ipp->ipp_dstopts,
10681 			    &ipp->ipp_dstoptslen, 0);
10682 			if (reterr != 0)
10683 				return (reterr);
10684 			if (ipp->ipp_dstoptslen == 0)
10685 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10686 			else
10687 				ipp->ipp_fields |= IPPF_DSTOPTS;
10688 			reterr = tcp_build_hdrs(tcp);
10689 			if (reterr != 0)
10690 				return (reterr);
10691 			break;
10692 		}
10693 		case IPV6_RTHDR: {
10694 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10695 
10696 			/*
10697 			 * Sanity checks - minimum size, size a multiple of
10698 			 * eight bytes, and matching size passed in.
10699 			 */
10700 			if (inlen != 0 &&
10701 			    inlen != (8 * (rt->ip6r_len + 1)))
10702 				return (EINVAL);
10703 
10704 			if (checkonly)
10705 				break;
10706 
10707 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10708 			    (uchar_t **)&ipp->ipp_rthdr,
10709 			    &ipp->ipp_rthdrlen, 0);
10710 			if (reterr != 0)
10711 				return (reterr);
10712 			if (ipp->ipp_rthdrlen == 0)
10713 				ipp->ipp_fields &= ~IPPF_RTHDR;
10714 			else
10715 				ipp->ipp_fields |= IPPF_RTHDR;
10716 			reterr = tcp_build_hdrs(tcp);
10717 			if (reterr != 0)
10718 				return (reterr);
10719 			break;
10720 		}
10721 		case IPV6_V6ONLY:
10722 			if (!checkonly) {
10723 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10724 			}
10725 			break;
10726 		case IPV6_USE_MIN_MTU:
10727 			if (inlen != sizeof (int))
10728 				return (EINVAL);
10729 
10730 			if (*i1 < -1 || *i1 > 1)
10731 				return (EINVAL);
10732 
10733 			if (checkonly)
10734 				break;
10735 
10736 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10737 			ipp->ipp_use_min_mtu = *i1;
10738 			break;
10739 		case IPV6_SEC_OPT:
10740 			/*
10741 			 * We should not allow policy setting after
10742 			 * we start listening for connections.
10743 			 */
10744 			if (tcp->tcp_state == TCPS_LISTEN) {
10745 				return (EINVAL);
10746 			} else {
10747 				/* Handled at the IP level */
10748 				return (-EINVAL);
10749 			}
10750 		case IPV6_SRC_PREFERENCES:
10751 			if (inlen != sizeof (uint32_t))
10752 				return (EINVAL);
10753 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10754 			    *(uint32_t *)invalp);
10755 			if (reterr != 0) {
10756 				*outlenp = 0;
10757 				return (reterr);
10758 			}
10759 			break;
10760 		default:
10761 			*outlenp = 0;
10762 			return (EINVAL);
10763 		}
10764 		break;
10765 	}		/* end IPPROTO_IPV6 */
10766 	default:
10767 		*outlenp = 0;
10768 		return (EINVAL);
10769 	}
10770 	/*
10771 	 * Common case of OK return with outval same as inval
10772 	 */
10773 	if (invalp != outvalp) {
10774 		/* don't trust bcopy for identical src/dst */
10775 		(void) bcopy(invalp, outvalp, inlen);
10776 	}
10777 	*outlenp = inlen;
10778 	return (0);
10779 }
10780 
10781 /* ARGSUSED */
10782 int
10783 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10784     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10785     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10786 {
10787 	conn_t	*connp =  Q_TO_CONN(q);
10788 
10789 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10790 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10791 }
10792 
10793 int
10794 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10795     const void *optvalp, socklen_t optlen, cred_t *cr)
10796 {
10797 	conn_t		*connp = (conn_t *)proto_handle;
10798 	squeue_t	*sqp = connp->conn_sqp;
10799 	int		error;
10800 
10801 	ASSERT(connp->conn_upper_handle != NULL);
10802 	/*
10803 	 * Entering the squeue synchronously can result in a context switch,
10804 	 * which can cause a rather sever performance degradation. So we try to
10805 	 * handle whatever options we can without entering the squeue.
10806 	 */
10807 	if (level == IPPROTO_TCP) {
10808 		switch (option_name) {
10809 		case TCP_NODELAY:
10810 			if (optlen != sizeof (int32_t))
10811 				return (EINVAL);
10812 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10813 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10814 			    connp->conn_tcp->tcp_mss;
10815 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10816 			return (0);
10817 		default:
10818 			break;
10819 		}
10820 	}
10821 
10822 	error = squeue_synch_enter(sqp, connp, NULL);
10823 	if (error == ENOMEM) {
10824 		return (ENOMEM);
10825 	}
10826 
10827 	error = proto_opt_check(level, option_name, optlen, NULL,
10828 	    tcp_opt_obj.odb_opt_des_arr,
10829 	    tcp_opt_obj.odb_opt_arr_cnt,
10830 	    tcp_opt_obj.odb_topmost_tpiprovider,
10831 	    B_TRUE, B_FALSE, cr);
10832 
10833 	if (error != 0) {
10834 		if (error < 0) {
10835 			error = proto_tlitosyserr(-error);
10836 		}
10837 		squeue_synch_exit(sqp, connp);
10838 		return (error);
10839 	}
10840 
10841 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10842 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10843 	    NULL, cr, NULL);
10844 	squeue_synch_exit(sqp, connp);
10845 
10846 	if (error < 0) {
10847 		/*
10848 		 * Pass on to ip
10849 		 */
10850 		error = ip_set_options(connp, level, option_name, optvalp,
10851 		    optlen, cr);
10852 	}
10853 	return (error);
10854 }
10855 
10856 /*
10857  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10858  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10859  * headers, and the maximum size tcp header (to avoid reallocation
10860  * on the fly for additional tcp options).
10861  * Returns failure if can't allocate memory.
10862  */
10863 static int
10864 tcp_build_hdrs(tcp_t *tcp)
10865 {
10866 	char	*hdrs;
10867 	uint_t	hdrs_len;
10868 	ip6i_t	*ip6i;
10869 	char	buf[TCP_MAX_HDR_LENGTH];
10870 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10871 	in6_addr_t src, dst;
10872 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10873 	conn_t *connp = tcp->tcp_connp;
10874 
10875 	/*
10876 	 * save the existing tcp header and source/dest IP addresses
10877 	 */
10878 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10879 	src = tcp->tcp_ip6h->ip6_src;
10880 	dst = tcp->tcp_ip6h->ip6_dst;
10881 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10882 	ASSERT(hdrs_len != 0);
10883 	if (hdrs_len > tcp->tcp_iphc_len) {
10884 		/* Need to reallocate */
10885 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10886 		if (hdrs == NULL)
10887 			return (ENOMEM);
10888 		if (tcp->tcp_iphc != NULL) {
10889 			if (tcp->tcp_hdr_grown) {
10890 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10891 			} else {
10892 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10893 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10894 			}
10895 			tcp->tcp_iphc_len = 0;
10896 		}
10897 		ASSERT(tcp->tcp_iphc_len == 0);
10898 		tcp->tcp_iphc = hdrs;
10899 		tcp->tcp_iphc_len = hdrs_len;
10900 		tcp->tcp_hdr_grown = B_TRUE;
10901 	}
10902 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10903 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10904 
10905 	/* Set header fields not in ipp */
10906 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10907 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10908 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10909 	} else {
10910 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10911 	}
10912 	/*
10913 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10914 	 *
10915 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10916 	 */
10917 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10918 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10919 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10920 
10921 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10922 
10923 	tcp->tcp_ip6h->ip6_src = src;
10924 	tcp->tcp_ip6h->ip6_dst = dst;
10925 
10926 	/*
10927 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10928 	 * the default value for TCP.
10929 	 */
10930 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10931 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10932 
10933 	/*
10934 	 * If we're setting extension headers after a connection
10935 	 * has been established, and if we have a routing header
10936 	 * among the extension headers, call ip_massage_options_v6 to
10937 	 * manipulate the routing header/ip6_dst set the checksum
10938 	 * difference in the tcp header template.
10939 	 * (This happens in tcp_connect_ipv6 if the routing header
10940 	 * is set prior to the connect.)
10941 	 * Set the tcp_sum to zero first in case we've cleared a
10942 	 * routing header or don't have one at all.
10943 	 */
10944 	tcp->tcp_sum = 0;
10945 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10946 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10947 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10948 		    (uint8_t *)tcp->tcp_tcph);
10949 		if (rth != NULL) {
10950 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10951 			    rth, tcps->tcps_netstack);
10952 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10953 			    (tcp->tcp_sum >> 16));
10954 		}
10955 	}
10956 
10957 	/* Try to get everything in a single mblk */
10958 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10959 	    hdrs_len + tcps->tcps_wroff_xtra);
10960 	return (0);
10961 }
10962 
10963 /*
10964  * Transfer any source route option from ipha to buf/dst in reversed form.
10965  */
10966 static int
10967 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10968 {
10969 	ipoptp_t	opts;
10970 	uchar_t		*opt;
10971 	uint8_t		optval;
10972 	uint8_t		optlen;
10973 	uint32_t	len = 0;
10974 
10975 	for (optval = ipoptp_first(&opts, ipha);
10976 	    optval != IPOPT_EOL;
10977 	    optval = ipoptp_next(&opts)) {
10978 		opt = opts.ipoptp_cur;
10979 		optlen = opts.ipoptp_len;
10980 		switch (optval) {
10981 			int	off1, off2;
10982 		case IPOPT_SSRR:
10983 		case IPOPT_LSRR:
10984 
10985 			/* Reverse source route */
10986 			/*
10987 			 * First entry should be the next to last one in the
10988 			 * current source route (the last entry is our
10989 			 * address.)
10990 			 * The last entry should be the final destination.
10991 			 */
10992 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10993 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10994 			off1 = IPOPT_MINOFF_SR - 1;
10995 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10996 			if (off2 < 0) {
10997 				/* No entries in source route */
10998 				break;
10999 			}
11000 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11001 			/*
11002 			 * Note: use src since ipha has not had its src
11003 			 * and dst reversed (it is in the state it was
11004 			 * received.
11005 			 */
11006 			bcopy(&ipha->ipha_src, buf + off2,
11007 			    IP_ADDR_LEN);
11008 			off2 -= IP_ADDR_LEN;
11009 
11010 			while (off2 > 0) {
11011 				bcopy(opt + off2, buf + off1,
11012 				    IP_ADDR_LEN);
11013 				off1 += IP_ADDR_LEN;
11014 				off2 -= IP_ADDR_LEN;
11015 			}
11016 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11017 			buf += optlen;
11018 			len += optlen;
11019 			break;
11020 		}
11021 	}
11022 done:
11023 	/* Pad the resulting options */
11024 	while (len & 0x3) {
11025 		*buf++ = IPOPT_EOL;
11026 		len++;
11027 	}
11028 	return (len);
11029 }
11030 
11031 
11032 /*
11033  * Extract and revert a source route from ipha (if any)
11034  * and then update the relevant fields in both tcp_t and the standard header.
11035  */
11036 static void
11037 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11038 {
11039 	char	buf[TCP_MAX_HDR_LENGTH];
11040 	uint_t	tcph_len;
11041 	int	len;
11042 
11043 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11044 	len = IPH_HDR_LENGTH(ipha);
11045 	if (len == IP_SIMPLE_HDR_LENGTH)
11046 		/* Nothing to do */
11047 		return;
11048 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11049 	    (len & 0x3))
11050 		return;
11051 
11052 	tcph_len = tcp->tcp_tcp_hdr_len;
11053 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11054 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11055 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11056 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11057 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11058 	len += IP_SIMPLE_HDR_LENGTH;
11059 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11060 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11061 	if ((int)tcp->tcp_sum < 0)
11062 		tcp->tcp_sum--;
11063 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11064 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11065 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11066 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11067 	tcp->tcp_ip_hdr_len = len;
11068 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11069 	    (IP_VERSION << 4) | (len >> 2);
11070 	len += tcph_len;
11071 	tcp->tcp_hdr_len = len;
11072 }
11073 
11074 /*
11075  * Copy the standard header into its new location,
11076  * lay in the new options and then update the relevant
11077  * fields in both tcp_t and the standard header.
11078  */
11079 static int
11080 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11081 {
11082 	uint_t	tcph_len;
11083 	uint8_t	*ip_optp;
11084 	tcph_t	*new_tcph;
11085 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11086 	conn_t	*connp = tcp->tcp_connp;
11087 
11088 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11089 		return (EINVAL);
11090 
11091 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11092 		return (EINVAL);
11093 
11094 	if (checkonly) {
11095 		/*
11096 		 * do not really set, just pretend to - T_CHECK
11097 		 */
11098 		return (0);
11099 	}
11100 
11101 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11102 	if (tcp->tcp_label_len > 0) {
11103 		int padlen;
11104 		uint8_t opt;
11105 
11106 		/* convert list termination to no-ops */
11107 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11108 		ip_optp += ip_optp[IPOPT_OLEN];
11109 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11110 		while (--padlen >= 0)
11111 			*ip_optp++ = opt;
11112 	}
11113 	tcph_len = tcp->tcp_tcp_hdr_len;
11114 	new_tcph = (tcph_t *)(ip_optp + len);
11115 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11116 	tcp->tcp_tcph = new_tcph;
11117 	bcopy(ptr, ip_optp, len);
11118 
11119 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11120 
11121 	tcp->tcp_ip_hdr_len = len;
11122 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11123 	    (IP_VERSION << 4) | (len >> 2);
11124 	tcp->tcp_hdr_len = len + tcph_len;
11125 	if (!TCP_IS_DETACHED(tcp)) {
11126 		/* Always allocate room for all options. */
11127 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11128 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11129 	}
11130 	return (0);
11131 }
11132 
11133 /* Get callback routine passed to nd_load by tcp_param_register */
11134 /* ARGSUSED */
11135 static int
11136 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11137 {
11138 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11139 
11140 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11141 	return (0);
11142 }
11143 
11144 /*
11145  * Walk through the param array specified registering each element with the
11146  * named dispatch handler.
11147  */
11148 static boolean_t
11149 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11150 {
11151 	for (; cnt-- > 0; tcppa++) {
11152 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11153 			if (!nd_load(ndp, tcppa->tcp_param_name,
11154 			    tcp_param_get, tcp_param_set,
11155 			    (caddr_t)tcppa)) {
11156 				nd_free(ndp);
11157 				return (B_FALSE);
11158 			}
11159 		}
11160 	}
11161 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11162 	    KM_SLEEP);
11163 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11164 	    sizeof (tcpparam_t));
11165 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11166 	    tcp_param_get, tcp_param_set_aligned,
11167 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11168 		nd_free(ndp);
11169 		return (B_FALSE);
11170 	}
11171 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11172 	    KM_SLEEP);
11173 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11174 	    sizeof (tcpparam_t));
11175 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11176 	    tcp_param_get, tcp_param_set_aligned,
11177 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11178 		nd_free(ndp);
11179 		return (B_FALSE);
11180 	}
11181 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11182 	    KM_SLEEP);
11183 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11184 	    sizeof (tcpparam_t));
11185 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11186 	    tcp_param_get, tcp_param_set_aligned,
11187 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11188 		nd_free(ndp);
11189 		return (B_FALSE);
11190 	}
11191 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11192 	    KM_SLEEP);
11193 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11194 	    sizeof (tcpparam_t));
11195 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11196 	    tcp_param_get, tcp_param_set_aligned,
11197 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11198 		nd_free(ndp);
11199 		return (B_FALSE);
11200 	}
11201 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11202 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11203 		nd_free(ndp);
11204 		return (B_FALSE);
11205 	}
11206 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11207 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11208 		nd_free(ndp);
11209 		return (B_FALSE);
11210 	}
11211 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11212 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11213 		nd_free(ndp);
11214 		return (B_FALSE);
11215 	}
11216 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11217 	    tcp_1948_phrase_set, NULL)) {
11218 		nd_free(ndp);
11219 		return (B_FALSE);
11220 	}
11221 	/*
11222 	 * Dummy ndd variables - only to convey obsolescence information
11223 	 * through printing of their name (no get or set routines)
11224 	 * XXX Remove in future releases ?
11225 	 */
11226 	if (!nd_load(ndp,
11227 	    "tcp_close_wait_interval(obsoleted - "
11228 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11229 		nd_free(ndp);
11230 		return (B_FALSE);
11231 	}
11232 	return (B_TRUE);
11233 }
11234 
11235 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11236 /* ARGSUSED */
11237 static int
11238 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11239     cred_t *cr)
11240 {
11241 	long new_value;
11242 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11243 
11244 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11245 	    new_value < tcppa->tcp_param_min ||
11246 	    new_value > tcppa->tcp_param_max) {
11247 		return (EINVAL);
11248 	}
11249 	/*
11250 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11251 	 * round it up.  For future 64 bit requirement, we actually make it
11252 	 * a multiple of 8.
11253 	 */
11254 	if (new_value & 0x7) {
11255 		new_value = (new_value & ~0x7) + 0x8;
11256 	}
11257 	tcppa->tcp_param_val = new_value;
11258 	return (0);
11259 }
11260 
11261 /* Set callback routine passed to nd_load by tcp_param_register */
11262 /* ARGSUSED */
11263 static int
11264 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11265 {
11266 	long	new_value;
11267 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11268 
11269 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11270 	    new_value < tcppa->tcp_param_min ||
11271 	    new_value > tcppa->tcp_param_max) {
11272 		return (EINVAL);
11273 	}
11274 	tcppa->tcp_param_val = new_value;
11275 	return (0);
11276 }
11277 
11278 /*
11279  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11280  * is filled, return as much as we can.  The message passed in may be
11281  * multi-part, chained using b_cont.  "start" is the starting sequence
11282  * number for this piece.
11283  */
11284 static mblk_t *
11285 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11286 {
11287 	uint32_t	end;
11288 	mblk_t		*mp1;
11289 	mblk_t		*mp2;
11290 	mblk_t		*next_mp;
11291 	uint32_t	u1;
11292 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11293 
11294 	/* Walk through all the new pieces. */
11295 	do {
11296 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11297 		    (uintptr_t)INT_MAX);
11298 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11299 		next_mp = mp->b_cont;
11300 		if (start == end) {
11301 			/* Empty.  Blast it. */
11302 			freeb(mp);
11303 			continue;
11304 		}
11305 		mp->b_cont = NULL;
11306 		TCP_REASS_SET_SEQ(mp, start);
11307 		TCP_REASS_SET_END(mp, end);
11308 		mp1 = tcp->tcp_reass_tail;
11309 		if (!mp1) {
11310 			tcp->tcp_reass_tail = mp;
11311 			tcp->tcp_reass_head = mp;
11312 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11313 			UPDATE_MIB(&tcps->tcps_mib,
11314 			    tcpInDataUnorderBytes, end - start);
11315 			continue;
11316 		}
11317 		/* New stuff completely beyond tail? */
11318 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11319 			/* Link it on end. */
11320 			mp1->b_cont = mp;
11321 			tcp->tcp_reass_tail = mp;
11322 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11323 			UPDATE_MIB(&tcps->tcps_mib,
11324 			    tcpInDataUnorderBytes, end - start);
11325 			continue;
11326 		}
11327 		mp1 = tcp->tcp_reass_head;
11328 		u1 = TCP_REASS_SEQ(mp1);
11329 		/* New stuff at the front? */
11330 		if (SEQ_LT(start, u1)) {
11331 			/* Yes... Check for overlap. */
11332 			mp->b_cont = mp1;
11333 			tcp->tcp_reass_head = mp;
11334 			tcp_reass_elim_overlap(tcp, mp);
11335 			continue;
11336 		}
11337 		/*
11338 		 * The new piece fits somewhere between the head and tail.
11339 		 * We find our slot, where mp1 precedes us and mp2 trails.
11340 		 */
11341 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11342 			u1 = TCP_REASS_SEQ(mp2);
11343 			if (SEQ_LEQ(start, u1))
11344 				break;
11345 		}
11346 		/* Link ourselves in */
11347 		mp->b_cont = mp2;
11348 		mp1->b_cont = mp;
11349 
11350 		/* Trim overlap with following mblk(s) first */
11351 		tcp_reass_elim_overlap(tcp, mp);
11352 
11353 		/* Trim overlap with preceding mblk */
11354 		tcp_reass_elim_overlap(tcp, mp1);
11355 
11356 	} while (start = end, mp = next_mp);
11357 	mp1 = tcp->tcp_reass_head;
11358 	/* Anything ready to go? */
11359 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11360 		return (NULL);
11361 	/* Eat what we can off the queue */
11362 	for (;;) {
11363 		mp = mp1->b_cont;
11364 		end = TCP_REASS_END(mp1);
11365 		TCP_REASS_SET_SEQ(mp1, 0);
11366 		TCP_REASS_SET_END(mp1, 0);
11367 		if (!mp) {
11368 			tcp->tcp_reass_tail = NULL;
11369 			break;
11370 		}
11371 		if (end != TCP_REASS_SEQ(mp)) {
11372 			mp1->b_cont = NULL;
11373 			break;
11374 		}
11375 		mp1 = mp;
11376 	}
11377 	mp1 = tcp->tcp_reass_head;
11378 	tcp->tcp_reass_head = mp;
11379 	return (mp1);
11380 }
11381 
11382 /* Eliminate any overlap that mp may have over later mblks */
11383 static void
11384 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11385 {
11386 	uint32_t	end;
11387 	mblk_t		*mp1;
11388 	uint32_t	u1;
11389 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11390 
11391 	end = TCP_REASS_END(mp);
11392 	while ((mp1 = mp->b_cont) != NULL) {
11393 		u1 = TCP_REASS_SEQ(mp1);
11394 		if (!SEQ_GT(end, u1))
11395 			break;
11396 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11397 			mp->b_wptr -= end - u1;
11398 			TCP_REASS_SET_END(mp, u1);
11399 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11400 			UPDATE_MIB(&tcps->tcps_mib,
11401 			    tcpInDataPartDupBytes, end - u1);
11402 			break;
11403 		}
11404 		mp->b_cont = mp1->b_cont;
11405 		TCP_REASS_SET_SEQ(mp1, 0);
11406 		TCP_REASS_SET_END(mp1, 0);
11407 		freeb(mp1);
11408 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11409 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11410 	}
11411 	if (!mp1)
11412 		tcp->tcp_reass_tail = mp;
11413 }
11414 
11415 static uint_t
11416 tcp_rwnd_reopen(tcp_t *tcp)
11417 {
11418 	uint_t ret = 0;
11419 	uint_t thwin;
11420 
11421 	/* Learn the latest rwnd information that we sent to the other side. */
11422 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11423 	    << tcp->tcp_rcv_ws;
11424 	/* This is peer's calculated send window (our receive window). */
11425 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11426 	/*
11427 	 * Increase the receive window to max.  But we need to do receiver
11428 	 * SWS avoidance.  This means that we need to check the increase of
11429 	 * of receive window is at least 1 MSS.
11430 	 */
11431 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11432 		/*
11433 		 * If the window that the other side knows is less than max
11434 		 * deferred acks segments, send an update immediately.
11435 		 */
11436 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11437 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11438 			ret = TH_ACK_NEEDED;
11439 		}
11440 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11441 	}
11442 	return (ret);
11443 }
11444 
11445 /*
11446  * Send up all messages queued on tcp_rcv_list.
11447  */
11448 static uint_t
11449 tcp_rcv_drain(tcp_t *tcp)
11450 {
11451 	mblk_t *mp;
11452 	uint_t ret = 0;
11453 #ifdef DEBUG
11454 	uint_t cnt = 0;
11455 #endif
11456 	queue_t	*q = tcp->tcp_rq;
11457 
11458 	/* Can't drain on an eager connection */
11459 	if (tcp->tcp_listener != NULL)
11460 		return (ret);
11461 
11462 	/* Can't be a non-STREAMS connection */
11463 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
11464 
11465 	/* No need for the push timer now. */
11466 	if (tcp->tcp_push_tid != 0) {
11467 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11468 		tcp->tcp_push_tid = 0;
11469 	}
11470 
11471 	/*
11472 	 * Handle two cases here: we are currently fused or we were
11473 	 * previously fused and have some urgent data to be delivered
11474 	 * upstream.  The latter happens because we either ran out of
11475 	 * memory or were detached and therefore sending the SIGURG was
11476 	 * deferred until this point.  In either case we pass control
11477 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11478 	 * some work.
11479 	 */
11480 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11481 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11482 		    tcp->tcp_fused_sigurg_mp != NULL);
11483 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11484 		    &tcp->tcp_fused_sigurg_mp))
11485 			return (ret);
11486 	}
11487 
11488 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11489 		tcp->tcp_rcv_list = mp->b_next;
11490 		mp->b_next = NULL;
11491 #ifdef DEBUG
11492 		cnt += msgdsize(mp);
11493 #endif
11494 		/* Does this need SSL processing first? */
11495 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11496 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11497 			    mblk_t *, mp);
11498 			tcp_kssl_input(tcp, mp);
11499 			continue;
11500 		}
11501 		putnext(q, mp);
11502 	}
11503 #ifdef DEBUG
11504 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11505 #endif
11506 	tcp->tcp_rcv_last_head = NULL;
11507 	tcp->tcp_rcv_last_tail = NULL;
11508 	tcp->tcp_rcv_cnt = 0;
11509 
11510 	if (canputnext(q))
11511 		return (tcp_rwnd_reopen(tcp));
11512 
11513 	return (ret);
11514 }
11515 
11516 /*
11517  * Queue data on tcp_rcv_list which is a b_next chain.
11518  * tcp_rcv_last_head/tail is the last element of this chain.
11519  * Each element of the chain is a b_cont chain.
11520  *
11521  * M_DATA messages are added to the current element.
11522  * Other messages are added as new (b_next) elements.
11523  */
11524 void
11525 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11526 {
11527 	ASSERT(seg_len == msgdsize(mp));
11528 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11529 
11530 	if (tcp->tcp_rcv_list == NULL) {
11531 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11532 		tcp->tcp_rcv_list = mp;
11533 		tcp->tcp_rcv_last_head = mp;
11534 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11535 		tcp->tcp_rcv_last_tail->b_cont = mp;
11536 	} else {
11537 		tcp->tcp_rcv_last_head->b_next = mp;
11538 		tcp->tcp_rcv_last_head = mp;
11539 	}
11540 
11541 	while (mp->b_cont)
11542 		mp = mp->b_cont;
11543 
11544 	tcp->tcp_rcv_last_tail = mp;
11545 	tcp->tcp_rcv_cnt += seg_len;
11546 	tcp->tcp_rwnd -= seg_len;
11547 }
11548 
11549 /*
11550  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11551  *
11552  * This is the default entry function into TCP on the read side. TCP is
11553  * always entered via squeue i.e. using squeue's for mutual exclusion.
11554  * When classifier does a lookup to find the tcp, it also puts a reference
11555  * on the conn structure associated so the tcp is guaranteed to exist
11556  * when we come here. We still need to check the state because it might
11557  * as well has been closed. The squeue processing function i.e. squeue_enter,
11558  * is responsible for doing the CONN_DEC_REF.
11559  *
11560  * Apart from the default entry point, IP also sends packets directly to
11561  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11562  * connections.
11563  */
11564 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11565 void
11566 tcp_input(void *arg, mblk_t *mp, void *arg2)
11567 {
11568 	conn_t	*connp = (conn_t *)arg;
11569 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11570 
11571 	/* arg2 is the sqp */
11572 	ASSERT(arg2 != NULL);
11573 	ASSERT(mp != NULL);
11574 
11575 	/*
11576 	 * Don't accept any input on a closed tcp as this TCP logically does
11577 	 * not exist on the system. Don't proceed further with this TCP.
11578 	 * For eg. this packet could trigger another close of this tcp
11579 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11580 	 * tcp_clean_death / tcp_closei_local must be called at most once
11581 	 * on a TCP. In this case we need to refeed the packet into the
11582 	 * classifier and figure out where the packet should go. Need to
11583 	 * preserve the recv_ill somehow. Until we figure that out, for
11584 	 * now just drop the packet if we can't classify the packet.
11585 	 */
11586 	if (tcp->tcp_state == TCPS_CLOSED ||
11587 	    tcp->tcp_state == TCPS_BOUND) {
11588 		conn_t	*new_connp;
11589 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11590 
11591 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11592 		if (new_connp != NULL) {
11593 			tcp_reinput(new_connp, mp, arg2);
11594 			return;
11595 		}
11596 		/* We failed to classify. For now just drop the packet */
11597 		freemsg(mp);
11598 		return;
11599 	}
11600 
11601 	if (DB_TYPE(mp) != M_DATA) {
11602 		tcp_rput_common(tcp, mp);
11603 		return;
11604 	}
11605 
11606 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11607 		squeue_t	*final_sqp;
11608 
11609 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11610 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11611 		DB_CKSUMSTART(mp) = 0;
11612 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11613 		    connp->conn_final_sqp == NULL &&
11614 		    tcp_outbound_squeue_switch) {
11615 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11616 			connp->conn_final_sqp = final_sqp;
11617 			if (connp->conn_final_sqp != connp->conn_sqp) {
11618 				CONN_INC_REF(connp);
11619 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11620 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11621 				    tcp_rput_data, connp, ip_squeue_flag,
11622 				    SQTAG_CONNECT_FINISH);
11623 				return;
11624 			}
11625 		}
11626 	}
11627 	tcp_rput_data(connp, mp, arg2);
11628 }
11629 
11630 /*
11631  * The read side put procedure.
11632  * The packets passed up by ip are assume to be aligned according to
11633  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11634  */
11635 static void
11636 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11637 {
11638 	/*
11639 	 * tcp_rput_data() does not expect M_CTL except for the case
11640 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11641 	 * type. Need to make sure that any other M_CTLs don't make
11642 	 * it to tcp_rput_data since it is not expecting any and doesn't
11643 	 * check for it.
11644 	 */
11645 	if (DB_TYPE(mp) == M_CTL) {
11646 		switch (*(uint32_t *)(mp->b_rptr)) {
11647 		case TCP_IOC_ABORT_CONN:
11648 			/*
11649 			 * Handle connection abort request.
11650 			 */
11651 			tcp_ioctl_abort_handler(tcp, mp);
11652 			return;
11653 		case IPSEC_IN:
11654 			/*
11655 			 * Only secure icmp arrive in TCP and they
11656 			 * don't go through data path.
11657 			 */
11658 			tcp_icmp_error(tcp, mp);
11659 			return;
11660 		case IN_PKTINFO:
11661 			/*
11662 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11663 			 * sockets that are receiving IPv4 traffic. tcp
11664 			 */
11665 			ASSERT(tcp->tcp_family == AF_INET6);
11666 			ASSERT(tcp->tcp_ipv6_recvancillary &
11667 			    TCP_IPV6_RECVPKTINFO);
11668 			tcp_rput_data(tcp->tcp_connp, mp,
11669 			    tcp->tcp_connp->conn_sqp);
11670 			return;
11671 		case MDT_IOC_INFO_UPDATE:
11672 			/*
11673 			 * Handle Multidata information update; the
11674 			 * following routine will free the message.
11675 			 */
11676 			if (tcp->tcp_connp->conn_mdt_ok) {
11677 				tcp_mdt_update(tcp,
11678 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11679 				    B_FALSE);
11680 			}
11681 			freemsg(mp);
11682 			return;
11683 		case LSO_IOC_INFO_UPDATE:
11684 			/*
11685 			 * Handle LSO information update; the following
11686 			 * routine will free the message.
11687 			 */
11688 			if (tcp->tcp_connp->conn_lso_ok) {
11689 				tcp_lso_update(tcp,
11690 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11691 			}
11692 			freemsg(mp);
11693 			return;
11694 		default:
11695 			/*
11696 			 * tcp_icmp_err() will process the M_CTL packets.
11697 			 * Non-ICMP packets, if any, will be discarded in
11698 			 * tcp_icmp_err(). We will process the ICMP packet
11699 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11700 			 * incoming ICMP packet may result in changing
11701 			 * the tcp_mss, which we would need if we have
11702 			 * packets to retransmit.
11703 			 */
11704 			tcp_icmp_error(tcp, mp);
11705 			return;
11706 		}
11707 	}
11708 
11709 	/* No point processing the message if tcp is already closed */
11710 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11711 		freemsg(mp);
11712 		return;
11713 	}
11714 
11715 	tcp_rput_other(tcp, mp);
11716 }
11717 
11718 
11719 /* The minimum of smoothed mean deviation in RTO calculation. */
11720 #define	TCP_SD_MIN	400
11721 
11722 /*
11723  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11724  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11725  * are the same as those in Appendix A.2 of that paper.
11726  *
11727  * m = new measurement
11728  * sa = smoothed RTT average (8 * average estimates).
11729  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11730  */
11731 static void
11732 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11733 {
11734 	long m = TICK_TO_MSEC(rtt);
11735 	clock_t sa = tcp->tcp_rtt_sa;
11736 	clock_t sv = tcp->tcp_rtt_sd;
11737 	clock_t rto;
11738 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11739 
11740 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11741 	tcp->tcp_rtt_update++;
11742 
11743 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11744 	if (sa != 0) {
11745 		/*
11746 		 * Update average estimator:
11747 		 *	new rtt = 7/8 old rtt + 1/8 Error
11748 		 */
11749 
11750 		/* m is now Error in estimate. */
11751 		m -= sa >> 3;
11752 		if ((sa += m) <= 0) {
11753 			/*
11754 			 * Don't allow the smoothed average to be negative.
11755 			 * We use 0 to denote reinitialization of the
11756 			 * variables.
11757 			 */
11758 			sa = 1;
11759 		}
11760 
11761 		/*
11762 		 * Update deviation estimator:
11763 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11764 		 */
11765 		if (m < 0)
11766 			m = -m;
11767 		m -= sv >> 2;
11768 		sv += m;
11769 	} else {
11770 		/*
11771 		 * This follows BSD's implementation.  So the reinitialized
11772 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11773 		 * link is bandwidth dominated, doubling the window size
11774 		 * during slow start means doubling the RTT.  We want to be
11775 		 * more conservative when we reinitialize our estimates.  3
11776 		 * is just a convenient number.
11777 		 */
11778 		sa = m << 3;
11779 		sv = m << 1;
11780 	}
11781 	if (sv < TCP_SD_MIN) {
11782 		/*
11783 		 * We do not know that if sa captures the delay ACK
11784 		 * effect as in a long train of segments, a receiver
11785 		 * does not delay its ACKs.  So set the minimum of sv
11786 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11787 		 * of BSD DATO.  That means the minimum of mean
11788 		 * deviation is 100 ms.
11789 		 *
11790 		 */
11791 		sv = TCP_SD_MIN;
11792 	}
11793 	tcp->tcp_rtt_sa = sa;
11794 	tcp->tcp_rtt_sd = sv;
11795 	/*
11796 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11797 	 *
11798 	 * Add tcp_rexmit_interval extra in case of extreme environment
11799 	 * where the algorithm fails to work.  The default value of
11800 	 * tcp_rexmit_interval_extra should be 0.
11801 	 *
11802 	 * As we use a finer grained clock than BSD and update
11803 	 * RTO for every ACKs, add in another .25 of RTT to the
11804 	 * deviation of RTO to accomodate burstiness of 1/4 of
11805 	 * window size.
11806 	 */
11807 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11808 
11809 	if (rto > tcps->tcps_rexmit_interval_max) {
11810 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11811 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11812 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11813 	} else {
11814 		tcp->tcp_rto = rto;
11815 	}
11816 
11817 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11818 	tcp->tcp_timer_backoff = 0;
11819 }
11820 
11821 /*
11822  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11823  * send queue which starts at the given sequence number. If the given
11824  * sequence number is equal to last valid sequence number (tcp_snxt), the
11825  * returned mblk is the last valid mblk, and off is set to the length of
11826  * that mblk.
11827  *
11828  * send queue which starts at the given seq. no.
11829  *
11830  * Parameters:
11831  *	tcp_t *tcp: the tcp instance pointer.
11832  *	uint32_t seq: the starting seq. no of the requested segment.
11833  *	int32_t *off: after the execution, *off will be the offset to
11834  *		the returned mblk which points to the requested seq no.
11835  *		It is the caller's responsibility to send in a non-null off.
11836  *
11837  * Return:
11838  *	A mblk_t pointer pointing to the requested segment in send queue.
11839  */
11840 static mblk_t *
11841 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11842 {
11843 	int32_t	cnt;
11844 	mblk_t	*mp;
11845 
11846 	/* Defensive coding.  Make sure we don't send incorrect data. */
11847 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
11848 		return (NULL);
11849 
11850 	cnt = seq - tcp->tcp_suna;
11851 	mp = tcp->tcp_xmit_head;
11852 	while (cnt > 0 && mp != NULL) {
11853 		cnt -= mp->b_wptr - mp->b_rptr;
11854 		if (cnt <= 0) {
11855 			cnt += mp->b_wptr - mp->b_rptr;
11856 			break;
11857 		}
11858 		mp = mp->b_cont;
11859 	}
11860 	ASSERT(mp != NULL);
11861 	*off = cnt;
11862 	return (mp);
11863 }
11864 
11865 /*
11866  * This function handles all retransmissions if SACK is enabled for this
11867  * connection.  First it calculates how many segments can be retransmitted
11868  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11869  * segments.  A segment is eligible if sack_cnt for that segment is greater
11870  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11871  * all eligible segments, it checks to see if TCP can send some new segments
11872  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11873  *
11874  * Parameters:
11875  *	tcp_t *tcp: the tcp structure of the connection.
11876  *	uint_t *flags: in return, appropriate value will be set for
11877  *	tcp_rput_data().
11878  */
11879 static void
11880 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11881 {
11882 	notsack_blk_t	*notsack_blk;
11883 	int32_t		usable_swnd;
11884 	int32_t		mss;
11885 	uint32_t	seg_len;
11886 	mblk_t		*xmit_mp;
11887 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11888 
11889 	ASSERT(tcp->tcp_sack_info != NULL);
11890 	ASSERT(tcp->tcp_notsack_list != NULL);
11891 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11892 
11893 	/* Defensive coding in case there is a bug... */
11894 	if (tcp->tcp_notsack_list == NULL) {
11895 		return;
11896 	}
11897 	notsack_blk = tcp->tcp_notsack_list;
11898 	mss = tcp->tcp_mss;
11899 
11900 	/*
11901 	 * Limit the num of outstanding data in the network to be
11902 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11903 	 */
11904 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11905 
11906 	/* At least retransmit 1 MSS of data. */
11907 	if (usable_swnd <= 0) {
11908 		usable_swnd = mss;
11909 	}
11910 
11911 	/* Make sure no new RTT samples will be taken. */
11912 	tcp->tcp_csuna = tcp->tcp_snxt;
11913 
11914 	notsack_blk = tcp->tcp_notsack_list;
11915 	while (usable_swnd > 0) {
11916 		mblk_t		*snxt_mp, *tmp_mp;
11917 		tcp_seq		begin = tcp->tcp_sack_snxt;
11918 		tcp_seq		end;
11919 		int32_t		off;
11920 
11921 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11922 			if (SEQ_GT(notsack_blk->end, begin) &&
11923 			    (notsack_blk->sack_cnt >=
11924 			    tcps->tcps_dupack_fast_retransmit)) {
11925 				end = notsack_blk->end;
11926 				if (SEQ_LT(begin, notsack_blk->begin)) {
11927 					begin = notsack_blk->begin;
11928 				}
11929 				break;
11930 			}
11931 		}
11932 		/*
11933 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11934 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11935 		 * set to tcp_cwnd_ssthresh.
11936 		 */
11937 		if (notsack_blk == NULL) {
11938 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11939 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11940 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11941 				ASSERT(tcp->tcp_cwnd > 0);
11942 				return;
11943 			} else {
11944 				usable_swnd = usable_swnd / mss;
11945 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11946 				    MAX(usable_swnd * mss, mss);
11947 				*flags |= TH_XMIT_NEEDED;
11948 				return;
11949 			}
11950 		}
11951 
11952 		/*
11953 		 * Note that we may send more than usable_swnd allows here
11954 		 * because of round off, but no more than 1 MSS of data.
11955 		 */
11956 		seg_len = end - begin;
11957 		if (seg_len > mss)
11958 			seg_len = mss;
11959 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11960 		ASSERT(snxt_mp != NULL);
11961 		/* This should not happen.  Defensive coding again... */
11962 		if (snxt_mp == NULL) {
11963 			return;
11964 		}
11965 
11966 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11967 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11968 		if (xmit_mp == NULL)
11969 			return;
11970 
11971 		usable_swnd -= seg_len;
11972 		tcp->tcp_pipe += seg_len;
11973 		tcp->tcp_sack_snxt = begin + seg_len;
11974 
11975 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11976 
11977 		/*
11978 		 * Update the send timestamp to avoid false retransmission.
11979 		 */
11980 		snxt_mp->b_prev = (mblk_t *)lbolt;
11981 
11982 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
11983 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
11984 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
11985 		/*
11986 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11987 		 * This happens when new data sent during fast recovery is
11988 		 * also lost.  If TCP retransmits those new data, it needs
11989 		 * to extend SACK recover phase to avoid starting another
11990 		 * fast retransmit/recovery unnecessarily.
11991 		 */
11992 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11993 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11994 		}
11995 	}
11996 }
11997 
11998 /*
11999  * This function handles policy checking at TCP level for non-hard_bound/
12000  * detached connections.
12001  */
12002 static boolean_t
12003 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12004     boolean_t secure, boolean_t mctl_present)
12005 {
12006 	ipsec_latch_t *ipl = NULL;
12007 	ipsec_action_t *act = NULL;
12008 	mblk_t *data_mp;
12009 	ipsec_in_t *ii;
12010 	const char *reason;
12011 	kstat_named_t *counter;
12012 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12013 	ipsec_stack_t	*ipss;
12014 	ip_stack_t	*ipst;
12015 
12016 	ASSERT(mctl_present || !secure);
12017 
12018 	ASSERT((ipha == NULL && ip6h != NULL) ||
12019 	    (ip6h == NULL && ipha != NULL));
12020 
12021 	/*
12022 	 * We don't necessarily have an ipsec_in_act action to verify
12023 	 * policy because of assymetrical policy where we have only
12024 	 * outbound policy and no inbound policy (possible with global
12025 	 * policy).
12026 	 */
12027 	if (!secure) {
12028 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12029 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12030 			return (B_TRUE);
12031 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12032 		    "tcp_check_policy", ipha, ip6h, secure,
12033 		    tcps->tcps_netstack);
12034 		ipss = tcps->tcps_netstack->netstack_ipsec;
12035 
12036 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12037 		    DROPPER(ipss, ipds_tcp_clear),
12038 		    &tcps->tcps_dropper);
12039 		return (B_FALSE);
12040 	}
12041 
12042 	/*
12043 	 * We have a secure packet.
12044 	 */
12045 	if (act == NULL) {
12046 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12047 		    "tcp_check_policy", ipha, ip6h, secure,
12048 		    tcps->tcps_netstack);
12049 		ipss = tcps->tcps_netstack->netstack_ipsec;
12050 
12051 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12052 		    DROPPER(ipss, ipds_tcp_secure),
12053 		    &tcps->tcps_dropper);
12054 		return (B_FALSE);
12055 	}
12056 
12057 	/*
12058 	 * XXX This whole routine is currently incorrect.  ipl should
12059 	 * be set to the latch pointer, but is currently not set, so
12060 	 * we initialize it to NULL to avoid picking up random garbage.
12061 	 */
12062 	if (ipl == NULL)
12063 		return (B_TRUE);
12064 
12065 	data_mp = first_mp->b_cont;
12066 
12067 	ii = (ipsec_in_t *)first_mp->b_rptr;
12068 
12069 	ipst = tcps->tcps_netstack->netstack_ip;
12070 
12071 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12072 	    &counter, tcp->tcp_connp)) {
12073 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12074 		return (B_TRUE);
12075 	}
12076 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12077 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12078 	    reason);
12079 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12080 
12081 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12082 	    &tcps->tcps_dropper);
12083 	return (B_FALSE);
12084 }
12085 
12086 /*
12087  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12088  * retransmission after a timeout.
12089  *
12090  * To limit the number of duplicate segments, we limit the number of segment
12091  * to be sent in one time to tcp_snd_burst, the burst variable.
12092  */
12093 static void
12094 tcp_ss_rexmit(tcp_t *tcp)
12095 {
12096 	uint32_t	snxt;
12097 	uint32_t	smax;
12098 	int32_t		win;
12099 	int32_t		mss;
12100 	int32_t		off;
12101 	int32_t		burst = tcp->tcp_snd_burst;
12102 	mblk_t		*snxt_mp;
12103 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12104 
12105 	/*
12106 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12107 	 * all unack'ed segments.
12108 	 */
12109 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12110 		smax = tcp->tcp_rexmit_max;
12111 		snxt = tcp->tcp_rexmit_nxt;
12112 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12113 			snxt = tcp->tcp_suna;
12114 		}
12115 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12116 		win -= snxt - tcp->tcp_suna;
12117 		mss = tcp->tcp_mss;
12118 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12119 
12120 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12121 		    (burst > 0) && (snxt_mp != NULL)) {
12122 			mblk_t	*xmit_mp;
12123 			mblk_t	*old_snxt_mp = snxt_mp;
12124 			uint32_t cnt = mss;
12125 
12126 			if (win < cnt) {
12127 				cnt = win;
12128 			}
12129 			if (SEQ_GT(snxt + cnt, smax)) {
12130 				cnt = smax - snxt;
12131 			}
12132 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12133 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12134 			if (xmit_mp == NULL)
12135 				return;
12136 
12137 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12138 
12139 			snxt += cnt;
12140 			win -= cnt;
12141 			/*
12142 			 * Update the send timestamp to avoid false
12143 			 * retransmission.
12144 			 */
12145 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12146 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12147 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12148 
12149 			tcp->tcp_rexmit_nxt = snxt;
12150 			burst--;
12151 		}
12152 		/*
12153 		 * If we have transmitted all we have at the time
12154 		 * we started the retranmission, we can leave
12155 		 * the rest of the job to tcp_wput_data().  But we
12156 		 * need to check the send window first.  If the
12157 		 * win is not 0, go on with tcp_wput_data().
12158 		 */
12159 		if (SEQ_LT(snxt, smax) || win == 0) {
12160 			return;
12161 		}
12162 	}
12163 	/* Only call tcp_wput_data() if there is data to be sent. */
12164 	if (tcp->tcp_unsent) {
12165 		tcp_wput_data(tcp, NULL, B_FALSE);
12166 	}
12167 }
12168 
12169 /*
12170  * Process all TCP option in SYN segment.  Note that this function should
12171  * be called after tcp_adapt_ire() is called so that the necessary info
12172  * from IRE is already set in the tcp structure.
12173  *
12174  * This function sets up the correct tcp_mss value according to the
12175  * MSS option value and our header size.  It also sets up the window scale
12176  * and timestamp values, and initialize SACK info blocks.  But it does not
12177  * change receive window size after setting the tcp_mss value.  The caller
12178  * should do the appropriate change.
12179  */
12180 void
12181 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12182 {
12183 	int options;
12184 	tcp_opt_t tcpopt;
12185 	uint32_t mss_max;
12186 	char *tmp_tcph;
12187 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12188 
12189 	tcpopt.tcp = NULL;
12190 	options = tcp_parse_options(tcph, &tcpopt);
12191 
12192 	/*
12193 	 * Process MSS option.  Note that MSS option value does not account
12194 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12195 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12196 	 * IPv6.
12197 	 */
12198 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12199 		if (tcp->tcp_ipversion == IPV4_VERSION)
12200 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12201 		else
12202 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12203 	} else {
12204 		if (tcp->tcp_ipversion == IPV4_VERSION)
12205 			mss_max = tcps->tcps_mss_max_ipv4;
12206 		else
12207 			mss_max = tcps->tcps_mss_max_ipv6;
12208 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12209 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12210 		else if (tcpopt.tcp_opt_mss > mss_max)
12211 			tcpopt.tcp_opt_mss = mss_max;
12212 	}
12213 
12214 	/* Process Window Scale option. */
12215 	if (options & TCP_OPT_WSCALE_PRESENT) {
12216 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12217 		tcp->tcp_snd_ws_ok = B_TRUE;
12218 	} else {
12219 		tcp->tcp_snd_ws = B_FALSE;
12220 		tcp->tcp_snd_ws_ok = B_FALSE;
12221 		tcp->tcp_rcv_ws = B_FALSE;
12222 	}
12223 
12224 	/* Process Timestamp option. */
12225 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12226 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12227 		tmp_tcph = (char *)tcp->tcp_tcph;
12228 
12229 		tcp->tcp_snd_ts_ok = B_TRUE;
12230 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12231 		tcp->tcp_last_rcv_lbolt = lbolt64;
12232 		ASSERT(OK_32PTR(tmp_tcph));
12233 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12234 
12235 		/* Fill in our template header with basic timestamp option. */
12236 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12237 		tmp_tcph[0] = TCPOPT_NOP;
12238 		tmp_tcph[1] = TCPOPT_NOP;
12239 		tmp_tcph[2] = TCPOPT_TSTAMP;
12240 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12241 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12242 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12243 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12244 	} else {
12245 		tcp->tcp_snd_ts_ok = B_FALSE;
12246 	}
12247 
12248 	/*
12249 	 * Process SACK options.  If SACK is enabled for this connection,
12250 	 * then allocate the SACK info structure.  Note the following ways
12251 	 * when tcp_snd_sack_ok is set to true.
12252 	 *
12253 	 * For active connection: in tcp_adapt_ire() called in
12254 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12255 	 * is checked.
12256 	 *
12257 	 * For passive connection: in tcp_adapt_ire() called in
12258 	 * tcp_accept_comm().
12259 	 *
12260 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12261 	 * That check makes sure that if we did not send a SACK OK option,
12262 	 * we will not enable SACK for this connection even though the other
12263 	 * side sends us SACK OK option.  For active connection, the SACK
12264 	 * info structure has already been allocated.  So we need to free
12265 	 * it if SACK is disabled.
12266 	 */
12267 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12268 	    (tcp->tcp_snd_sack_ok ||
12269 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12270 		/* This should be true only in the passive case. */
12271 		if (tcp->tcp_sack_info == NULL) {
12272 			ASSERT(TCP_IS_DETACHED(tcp));
12273 			tcp->tcp_sack_info =
12274 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12275 		}
12276 		if (tcp->tcp_sack_info == NULL) {
12277 			tcp->tcp_snd_sack_ok = B_FALSE;
12278 		} else {
12279 			tcp->tcp_snd_sack_ok = B_TRUE;
12280 			if (tcp->tcp_snd_ts_ok) {
12281 				tcp->tcp_max_sack_blk = 3;
12282 			} else {
12283 				tcp->tcp_max_sack_blk = 4;
12284 			}
12285 		}
12286 	} else {
12287 		/*
12288 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12289 		 * no SACK info will be used for this
12290 		 * connection.  This assumes that SACK usage
12291 		 * permission is negotiated.  This may need
12292 		 * to be changed once this is clarified.
12293 		 */
12294 		if (tcp->tcp_sack_info != NULL) {
12295 			ASSERT(tcp->tcp_notsack_list == NULL);
12296 			kmem_cache_free(tcp_sack_info_cache,
12297 			    tcp->tcp_sack_info);
12298 			tcp->tcp_sack_info = NULL;
12299 		}
12300 		tcp->tcp_snd_sack_ok = B_FALSE;
12301 	}
12302 
12303 	/*
12304 	 * Now we know the exact TCP/IP header length, subtract
12305 	 * that from tcp_mss to get our side's MSS.
12306 	 */
12307 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12308 	/*
12309 	 * Here we assume that the other side's header size will be equal to
12310 	 * our header size.  We calculate the real MSS accordingly.  Need to
12311 	 * take into additional stuffs IPsec puts in.
12312 	 *
12313 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12314 	 */
12315 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12316 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12317 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12318 
12319 	/*
12320 	 * Set MSS to the smaller one of both ends of the connection.
12321 	 * We should not have called tcp_mss_set() before, but our
12322 	 * side of the MSS should have been set to a proper value
12323 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12324 	 * STREAM head parameters properly.
12325 	 *
12326 	 * If we have a larger-than-16-bit window but the other side
12327 	 * didn't want to do window scale, tcp_rwnd_set() will take
12328 	 * care of that.
12329 	 */
12330 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12331 }
12332 
12333 /*
12334  * Sends the T_CONN_IND to the listener. The caller calls this
12335  * functions via squeue to get inside the listener's perimeter
12336  * once the 3 way hand shake is done a T_CONN_IND needs to be
12337  * sent. As an optimization, the caller can call this directly
12338  * if listener's perimeter is same as eager's.
12339  */
12340 /* ARGSUSED */
12341 void
12342 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12343 {
12344 	conn_t			*lconnp = (conn_t *)arg;
12345 	tcp_t			*listener = lconnp->conn_tcp;
12346 	tcp_t			*tcp;
12347 	struct T_conn_ind	*conn_ind;
12348 	ipaddr_t 		*addr_cache;
12349 	boolean_t		need_send_conn_ind = B_FALSE;
12350 	tcp_stack_t		*tcps = listener->tcp_tcps;
12351 
12352 	/* retrieve the eager */
12353 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12354 	ASSERT(conn_ind->OPT_offset != 0 &&
12355 	    conn_ind->OPT_length == sizeof (intptr_t));
12356 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12357 	    conn_ind->OPT_length);
12358 
12359 	/*
12360 	 * TLI/XTI applications will get confused by
12361 	 * sending eager as an option since it violates
12362 	 * the option semantics. So remove the eager as
12363 	 * option since TLI/XTI app doesn't need it anyway.
12364 	 */
12365 	if (!TCP_IS_SOCKET(listener)) {
12366 		conn_ind->OPT_length = 0;
12367 		conn_ind->OPT_offset = 0;
12368 	}
12369 	if (listener->tcp_state != TCPS_LISTEN) {
12370 		/*
12371 		 * If listener has closed, it would have caused a
12372 		 * a cleanup/blowoff to happen for the eager. We
12373 		 * just need to return.
12374 		 */
12375 		freemsg(mp);
12376 		return;
12377 	}
12378 
12379 
12380 	/*
12381 	 * if the conn_req_q is full defer passing up the
12382 	 * T_CONN_IND until space is availabe after t_accept()
12383 	 * processing
12384 	 */
12385 	mutex_enter(&listener->tcp_eager_lock);
12386 
12387 	/*
12388 	 * Take the eager out, if it is in the list of droppable eagers
12389 	 * as we are here because the 3W handshake is over.
12390 	 */
12391 	MAKE_UNDROPPABLE(tcp);
12392 
12393 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12394 		tcp_t *tail;
12395 
12396 		/*
12397 		 * The eager already has an extra ref put in tcp_rput_data
12398 		 * so that it stays till accept comes back even though it
12399 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12400 		 */
12401 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12402 		listener->tcp_conn_req_cnt_q0--;
12403 		listener->tcp_conn_req_cnt_q++;
12404 
12405 		/* Move from SYN_RCVD to ESTABLISHED list  */
12406 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12407 		    tcp->tcp_eager_prev_q0;
12408 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12409 		    tcp->tcp_eager_next_q0;
12410 		tcp->tcp_eager_prev_q0 = NULL;
12411 		tcp->tcp_eager_next_q0 = NULL;
12412 
12413 		/*
12414 		 * Insert at end of the queue because sockfs
12415 		 * sends down T_CONN_RES in chronological
12416 		 * order. Leaving the older conn indications
12417 		 * at front of the queue helps reducing search
12418 		 * time.
12419 		 */
12420 		tail = listener->tcp_eager_last_q;
12421 		if (tail != NULL)
12422 			tail->tcp_eager_next_q = tcp;
12423 		else
12424 			listener->tcp_eager_next_q = tcp;
12425 		listener->tcp_eager_last_q = tcp;
12426 		tcp->tcp_eager_next_q = NULL;
12427 		/*
12428 		 * Delay sending up the T_conn_ind until we are
12429 		 * done with the eager. Once we have have sent up
12430 		 * the T_conn_ind, the accept can potentially complete
12431 		 * any time and release the refhold we have on the eager.
12432 		 */
12433 		need_send_conn_ind = B_TRUE;
12434 	} else {
12435 		/*
12436 		 * Defer connection on q0 and set deferred
12437 		 * connection bit true
12438 		 */
12439 		tcp->tcp_conn_def_q0 = B_TRUE;
12440 
12441 		/* take tcp out of q0 ... */
12442 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12443 		    tcp->tcp_eager_next_q0;
12444 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12445 		    tcp->tcp_eager_prev_q0;
12446 
12447 		/* ... and place it at the end of q0 */
12448 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12449 		tcp->tcp_eager_next_q0 = listener;
12450 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12451 		listener->tcp_eager_prev_q0 = tcp;
12452 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12453 	}
12454 
12455 	/* we have timed out before */
12456 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12457 		tcp->tcp_syn_rcvd_timeout = 0;
12458 		listener->tcp_syn_rcvd_timeout--;
12459 		if (listener->tcp_syn_defense &&
12460 		    listener->tcp_syn_rcvd_timeout <=
12461 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12462 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12463 		    listener->tcp_last_rcv_lbolt)) {
12464 			/*
12465 			 * Turn off the defense mode if we
12466 			 * believe the SYN attack is over.
12467 			 */
12468 			listener->tcp_syn_defense = B_FALSE;
12469 			if (listener->tcp_ip_addr_cache) {
12470 				kmem_free((void *)listener->tcp_ip_addr_cache,
12471 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12472 				listener->tcp_ip_addr_cache = NULL;
12473 			}
12474 		}
12475 	}
12476 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12477 	if (addr_cache != NULL) {
12478 		/*
12479 		 * We have finished a 3-way handshake with this
12480 		 * remote host. This proves the IP addr is good.
12481 		 * Cache it!
12482 		 */
12483 		addr_cache[IP_ADDR_CACHE_HASH(
12484 		    tcp->tcp_remote)] = tcp->tcp_remote;
12485 	}
12486 	mutex_exit(&listener->tcp_eager_lock);
12487 	if (need_send_conn_ind)
12488 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12489 }
12490 
12491 /*
12492  * Send the newconn notification to ulp. The eager is blown off if the
12493  * notification fails.
12494  */
12495 static void
12496 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12497 {
12498 	if (IPCL_IS_NONSTR(lconnp)) {
12499 		cred_t	*cr;
12500 		pid_t	cpid;
12501 
12502 		cr = msg_getcred(mp, &cpid);
12503 
12504 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12505 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12506 		    lconnp->conn_tcp);
12507 
12508 		/* Keep the message around in case of a fallback to TPI */
12509 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12510 
12511 		/*
12512 		 * Notify the ULP about the newconn. It is guaranteed that no
12513 		 * tcp_accept() call will be made for the eager if the
12514 		 * notification fails, so it's safe to blow it off in that
12515 		 * case.
12516 		 *
12517 		 * The upper handle will be assigned when tcp_accept() is
12518 		 * called.
12519 		 */
12520 		if ((*lconnp->conn_upcalls->su_newconn)
12521 		    (lconnp->conn_upper_handle,
12522 		    (sock_lower_handle_t)econnp,
12523 		    &sock_tcp_downcalls, cr, cpid,
12524 		    &econnp->conn_upcalls) == NULL) {
12525 			/* Failed to allocate a socket */
12526 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12527 			    tcpEstabResets);
12528 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12529 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12530 		}
12531 	} else {
12532 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12533 	}
12534 }
12535 
12536 mblk_t *
12537 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12538     uint_t *ifindexp, ip6_pkt_t *ippp)
12539 {
12540 	ip_pktinfo_t	*pinfo;
12541 	ip6_t		*ip6h;
12542 	uchar_t		*rptr;
12543 	mblk_t		*first_mp = mp;
12544 	boolean_t	mctl_present = B_FALSE;
12545 	uint_t 		ifindex = 0;
12546 	ip6_pkt_t	ipp;
12547 	uint_t		ipvers;
12548 	uint_t		ip_hdr_len;
12549 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12550 
12551 	rptr = mp->b_rptr;
12552 	ASSERT(OK_32PTR(rptr));
12553 	ASSERT(tcp != NULL);
12554 	ipp.ipp_fields = 0;
12555 
12556 	switch DB_TYPE(mp) {
12557 	case M_CTL:
12558 		mp = mp->b_cont;
12559 		if (mp == NULL) {
12560 			freemsg(first_mp);
12561 			return (NULL);
12562 		}
12563 		if (DB_TYPE(mp) != M_DATA) {
12564 			freemsg(first_mp);
12565 			return (NULL);
12566 		}
12567 		mctl_present = B_TRUE;
12568 		break;
12569 	case M_DATA:
12570 		break;
12571 	default:
12572 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12573 		freemsg(mp);
12574 		return (NULL);
12575 	}
12576 	ipvers = IPH_HDR_VERSION(rptr);
12577 	if (ipvers == IPV4_VERSION) {
12578 		if (tcp == NULL) {
12579 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12580 			goto done;
12581 		}
12582 
12583 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12584 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12585 
12586 		/*
12587 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12588 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12589 		 */
12590 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12591 		    mctl_present) {
12592 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12593 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12594 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12595 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12596 				ipp.ipp_fields |= IPPF_IFINDEX;
12597 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12598 				ifindex = pinfo->ip_pkt_ifindex;
12599 			}
12600 			freeb(first_mp);
12601 			mctl_present = B_FALSE;
12602 		}
12603 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12604 	} else {
12605 		ip6h = (ip6_t *)rptr;
12606 
12607 		ASSERT(ipvers == IPV6_VERSION);
12608 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12609 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12610 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12611 
12612 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12613 			uint8_t	nexthdrp;
12614 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12615 
12616 			/* Look for ifindex information */
12617 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12618 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12619 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12620 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12621 					freemsg(first_mp);
12622 					return (NULL);
12623 				}
12624 
12625 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12626 					ASSERT(ip6i->ip6i_ifindex != 0);
12627 					ipp.ipp_fields |= IPPF_IFINDEX;
12628 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12629 					ifindex = ip6i->ip6i_ifindex;
12630 				}
12631 				rptr = (uchar_t *)&ip6i[1];
12632 				mp->b_rptr = rptr;
12633 				if (rptr == mp->b_wptr) {
12634 					mblk_t *mp1;
12635 					mp1 = mp->b_cont;
12636 					freeb(mp);
12637 					mp = mp1;
12638 					rptr = mp->b_rptr;
12639 				}
12640 				if (MBLKL(mp) < IPV6_HDR_LEN +
12641 				    sizeof (tcph_t)) {
12642 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12643 					freemsg(first_mp);
12644 					return (NULL);
12645 				}
12646 				ip6h = (ip6_t *)rptr;
12647 			}
12648 
12649 			/*
12650 			 * Find any potentially interesting extension headers
12651 			 * as well as the length of the IPv6 + extension
12652 			 * headers.
12653 			 */
12654 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12655 			/* Verify if this is a TCP packet */
12656 			if (nexthdrp != IPPROTO_TCP) {
12657 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12658 				freemsg(first_mp);
12659 				return (NULL);
12660 			}
12661 		} else {
12662 			ip_hdr_len = IPV6_HDR_LEN;
12663 		}
12664 	}
12665 
12666 done:
12667 	if (ipversp != NULL)
12668 		*ipversp = ipvers;
12669 	if (ip_hdr_lenp != NULL)
12670 		*ip_hdr_lenp = ip_hdr_len;
12671 	if (ippp != NULL)
12672 		*ippp = ipp;
12673 	if (ifindexp != NULL)
12674 		*ifindexp = ifindex;
12675 	if (mctl_present) {
12676 		freeb(first_mp);
12677 	}
12678 	return (mp);
12679 }
12680 
12681 /*
12682  * Handle M_DATA messages from IP. Its called directly from IP via
12683  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12684  * in this path.
12685  *
12686  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12687  * v4 and v6), we are called through tcp_input() and a M_CTL can
12688  * be present for options but tcp_find_pktinfo() deals with it. We
12689  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12690  *
12691  * The first argument is always the connp/tcp to which the mp belongs.
12692  * There are no exceptions to this rule. The caller has already put
12693  * a reference on this connp/tcp and once tcp_rput_data() returns,
12694  * the squeue will do the refrele.
12695  *
12696  * The TH_SYN for the listener directly go to tcp_conn_request via
12697  * squeue.
12698  *
12699  * sqp: NULL = recursive, sqp != NULL means called from squeue
12700  */
12701 void
12702 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12703 {
12704 	int32_t		bytes_acked;
12705 	int32_t		gap;
12706 	mblk_t		*mp1;
12707 	uint_t		flags;
12708 	uint32_t	new_swnd = 0;
12709 	uchar_t		*iphdr;
12710 	uchar_t		*rptr;
12711 	int32_t		rgap;
12712 	uint32_t	seg_ack;
12713 	int		seg_len;
12714 	uint_t		ip_hdr_len;
12715 	uint32_t	seg_seq;
12716 	tcph_t		*tcph;
12717 	int		urp;
12718 	tcp_opt_t	tcpopt;
12719 	uint_t		ipvers;
12720 	ip6_pkt_t	ipp;
12721 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12722 	uint32_t	cwnd;
12723 	uint32_t	add;
12724 	int		npkt;
12725 	int		mss;
12726 	conn_t		*connp = (conn_t *)arg;
12727 	squeue_t	*sqp = (squeue_t *)arg2;
12728 	tcp_t		*tcp = connp->conn_tcp;
12729 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12730 
12731 	/*
12732 	 * RST from fused tcp loopback peer should trigger an unfuse.
12733 	 */
12734 	if (tcp->tcp_fused) {
12735 		TCP_STAT(tcps, tcp_fusion_aborted);
12736 		tcp_unfuse(tcp);
12737 	}
12738 
12739 	iphdr = mp->b_rptr;
12740 	rptr = mp->b_rptr;
12741 	ASSERT(OK_32PTR(rptr));
12742 
12743 	/*
12744 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12745 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12746 	 * necessary information.
12747 	 */
12748 	if (IPCL_IS_TCP4(connp)) {
12749 		ipvers = IPV4_VERSION;
12750 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12751 	} else {
12752 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12753 		    NULL, &ipp);
12754 		if (mp == NULL) {
12755 			TCP_STAT(tcps, tcp_rput_v6_error);
12756 			return;
12757 		}
12758 		iphdr = mp->b_rptr;
12759 		rptr = mp->b_rptr;
12760 	}
12761 	ASSERT(DB_TYPE(mp) == M_DATA);
12762 	ASSERT(mp->b_next == NULL);
12763 
12764 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12765 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12766 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12767 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12768 	seg_len = (int)(mp->b_wptr - rptr) -
12769 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12770 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12771 		do {
12772 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12773 			    (uintptr_t)INT_MAX);
12774 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12775 		} while ((mp1 = mp1->b_cont) != NULL &&
12776 		    mp1->b_datap->db_type == M_DATA);
12777 	}
12778 
12779 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12780 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12781 		    seg_len, tcph);
12782 		return;
12783 	}
12784 
12785 	if (sqp != NULL) {
12786 		/*
12787 		 * This is the correct place to update tcp_last_recv_time. Note
12788 		 * that it is also updated for tcp structure that belongs to
12789 		 * global and listener queues which do not really need updating.
12790 		 * But that should not cause any harm.  And it is updated for
12791 		 * all kinds of incoming segments, not only for data segments.
12792 		 */
12793 		tcp->tcp_last_recv_time = lbolt;
12794 	}
12795 
12796 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12797 
12798 	BUMP_LOCAL(tcp->tcp_ibsegs);
12799 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12800 
12801 	if ((flags & TH_URG) && sqp != NULL) {
12802 		/*
12803 		 * TCP can't handle urgent pointers that arrive before
12804 		 * the connection has been accept()ed since it can't
12805 		 * buffer OOB data.  Discard segment if this happens.
12806 		 *
12807 		 * We can't just rely on a non-null tcp_listener to indicate
12808 		 * that the accept() has completed since unlinking of the
12809 		 * eager and completion of the accept are not atomic.
12810 		 * tcp_detached, when it is not set (B_FALSE) indicates
12811 		 * that the accept() has completed.
12812 		 *
12813 		 * Nor can it reassemble urgent pointers, so discard
12814 		 * if it's not the next segment expected.
12815 		 *
12816 		 * Otherwise, collapse chain into one mblk (discard if
12817 		 * that fails).  This makes sure the headers, retransmitted
12818 		 * data, and new data all are in the same mblk.
12819 		 */
12820 		ASSERT(mp != NULL);
12821 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12822 			freemsg(mp);
12823 			return;
12824 		}
12825 		/* Update pointers into message */
12826 		iphdr = rptr = mp->b_rptr;
12827 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12828 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12829 			/*
12830 			 * Since we can't handle any data with this urgent
12831 			 * pointer that is out of sequence, we expunge
12832 			 * the data.  This allows us to still register
12833 			 * the urgent mark and generate the M_PCSIG,
12834 			 * which we can do.
12835 			 */
12836 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12837 			seg_len = 0;
12838 		}
12839 	}
12840 
12841 	switch (tcp->tcp_state) {
12842 	case TCPS_SYN_SENT:
12843 		if (flags & TH_ACK) {
12844 			/*
12845 			 * Note that our stack cannot send data before a
12846 			 * connection is established, therefore the
12847 			 * following check is valid.  Otherwise, it has
12848 			 * to be changed.
12849 			 */
12850 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12851 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12852 				freemsg(mp);
12853 				if (flags & TH_RST)
12854 					return;
12855 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12856 				    tcp, seg_ack, 0, TH_RST);
12857 				return;
12858 			}
12859 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12860 		}
12861 		if (flags & TH_RST) {
12862 			freemsg(mp);
12863 			if (flags & TH_ACK)
12864 				(void) tcp_clean_death(tcp,
12865 				    ECONNREFUSED, 13);
12866 			return;
12867 		}
12868 		if (!(flags & TH_SYN)) {
12869 			freemsg(mp);
12870 			return;
12871 		}
12872 
12873 		/* Process all TCP options. */
12874 		tcp_process_options(tcp, tcph);
12875 		/*
12876 		 * The following changes our rwnd to be a multiple of the
12877 		 * MIN(peer MSS, our MSS) for performance reason.
12878 		 */
12879 		(void) tcp_rwnd_set(tcp,
12880 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
12881 
12882 		/* Is the other end ECN capable? */
12883 		if (tcp->tcp_ecn_ok) {
12884 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12885 				tcp->tcp_ecn_ok = B_FALSE;
12886 			}
12887 		}
12888 		/*
12889 		 * Clear ECN flags because it may interfere with later
12890 		 * processing.
12891 		 */
12892 		flags &= ~(TH_ECE|TH_CWR);
12893 
12894 		tcp->tcp_irs = seg_seq;
12895 		tcp->tcp_rack = seg_seq;
12896 		tcp->tcp_rnxt = seg_seq + 1;
12897 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12898 		if (!TCP_IS_DETACHED(tcp)) {
12899 			/* Allocate room for SACK options if needed. */
12900 			if (tcp->tcp_snd_sack_ok) {
12901 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12902 				    tcp->tcp_hdr_len +
12903 				    TCPOPT_MAX_SACK_LEN +
12904 				    (tcp->tcp_loopback ? 0 :
12905 				    tcps->tcps_wroff_xtra));
12906 			} else {
12907 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12908 				    tcp->tcp_hdr_len +
12909 				    (tcp->tcp_loopback ? 0 :
12910 				    tcps->tcps_wroff_xtra));
12911 			}
12912 		}
12913 		if (flags & TH_ACK) {
12914 			/*
12915 			 * If we can't get the confirmation upstream, pretend
12916 			 * we didn't even see this one.
12917 			 *
12918 			 * XXX: how can we pretend we didn't see it if we
12919 			 * have updated rnxt et. al.
12920 			 *
12921 			 * For loopback we defer sending up the T_CONN_CON
12922 			 * until after some checks below.
12923 			 */
12924 			mp1 = NULL;
12925 			/*
12926 			 * tcp_sendmsg() checks tcp_state without entering
12927 			 * the squeue so tcp_state should be updated before
12928 			 * sending up connection confirmation
12929 			 */
12930 			tcp->tcp_state = TCPS_ESTABLISHED;
12931 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12932 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12933 				tcp->tcp_state = TCPS_SYN_SENT;
12934 				freemsg(mp);
12935 				return;
12936 			}
12937 			/* SYN was acked - making progress */
12938 			if (tcp->tcp_ipversion == IPV6_VERSION)
12939 				tcp->tcp_ip_forward_progress = B_TRUE;
12940 
12941 			/* One for the SYN */
12942 			tcp->tcp_suna = tcp->tcp_iss + 1;
12943 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12944 
12945 			/*
12946 			 * If SYN was retransmitted, need to reset all
12947 			 * retransmission info.  This is because this
12948 			 * segment will be treated as a dup ACK.
12949 			 */
12950 			if (tcp->tcp_rexmit) {
12951 				tcp->tcp_rexmit = B_FALSE;
12952 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12953 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12954 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12955 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12956 				tcp->tcp_ms_we_have_waited = 0;
12957 
12958 				/*
12959 				 * Set tcp_cwnd back to 1 MSS, per
12960 				 * recommendation from
12961 				 * draft-floyd-incr-init-win-01.txt,
12962 				 * Increasing TCP's Initial Window.
12963 				 */
12964 				tcp->tcp_cwnd = tcp->tcp_mss;
12965 			}
12966 
12967 			tcp->tcp_swl1 = seg_seq;
12968 			tcp->tcp_swl2 = seg_ack;
12969 
12970 			new_swnd = BE16_TO_U16(tcph->th_win);
12971 			tcp->tcp_swnd = new_swnd;
12972 			if (new_swnd > tcp->tcp_max_swnd)
12973 				tcp->tcp_max_swnd = new_swnd;
12974 
12975 			/*
12976 			 * Always send the three-way handshake ack immediately
12977 			 * in order to make the connection complete as soon as
12978 			 * possible on the accepting host.
12979 			 */
12980 			flags |= TH_ACK_NEEDED;
12981 
12982 			/*
12983 			 * Special case for loopback.  At this point we have
12984 			 * received SYN-ACK from the remote endpoint.  In
12985 			 * order to ensure that both endpoints reach the
12986 			 * fused state prior to any data exchange, the final
12987 			 * ACK needs to be sent before we indicate T_CONN_CON
12988 			 * to the module upstream.
12989 			 */
12990 			if (tcp->tcp_loopback) {
12991 				mblk_t *ack_mp;
12992 
12993 				ASSERT(!tcp->tcp_unfusable);
12994 				ASSERT(mp1 != NULL);
12995 				/*
12996 				 * For loopback, we always get a pure SYN-ACK
12997 				 * and only need to send back the final ACK
12998 				 * with no data (this is because the other
12999 				 * tcp is ours and we don't do T/TCP).  This
13000 				 * final ACK triggers the passive side to
13001 				 * perform fusion in ESTABLISHED state.
13002 				 */
13003 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13004 					if (tcp->tcp_ack_tid != 0) {
13005 						(void) TCP_TIMER_CANCEL(tcp,
13006 						    tcp->tcp_ack_tid);
13007 						tcp->tcp_ack_tid = 0;
13008 					}
13009 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13010 					BUMP_LOCAL(tcp->tcp_obsegs);
13011 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13012 
13013 					if (!IPCL_IS_NONSTR(connp)) {
13014 						/* Send up T_CONN_CON */
13015 						putnext(tcp->tcp_rq, mp1);
13016 					} else {
13017 						cred_t	*cr;
13018 						pid_t	cpid;
13019 
13020 						cr = msg_getcred(mp1, &cpid);
13021 						(*connp->conn_upcalls->
13022 						    su_connected)
13023 						    (connp->conn_upper_handle,
13024 						    tcp->tcp_connid, cr, cpid);
13025 						freemsg(mp1);
13026 					}
13027 
13028 					freemsg(mp);
13029 					return;
13030 				}
13031 				/*
13032 				 * Forget fusion; we need to handle more
13033 				 * complex cases below.  Send the deferred
13034 				 * T_CONN_CON message upstream and proceed
13035 				 * as usual.  Mark this tcp as not capable
13036 				 * of fusion.
13037 				 */
13038 				TCP_STAT(tcps, tcp_fusion_unfusable);
13039 				tcp->tcp_unfusable = B_TRUE;
13040 				if (!IPCL_IS_NONSTR(connp)) {
13041 					putnext(tcp->tcp_rq, mp1);
13042 				} else {
13043 					cred_t	*cr;
13044 					pid_t	cpid;
13045 
13046 					cr = msg_getcred(mp1, &cpid);
13047 					(*connp->conn_upcalls->su_connected)
13048 					    (connp->conn_upper_handle,
13049 					    tcp->tcp_connid, cr, cpid);
13050 					freemsg(mp1);
13051 				}
13052 			}
13053 
13054 			/*
13055 			 * Check to see if there is data to be sent.  If
13056 			 * yes, set the transmit flag.  Then check to see
13057 			 * if received data processing needs to be done.
13058 			 * If not, go straight to xmit_check.  This short
13059 			 * cut is OK as we don't support T/TCP.
13060 			 */
13061 			if (tcp->tcp_unsent)
13062 				flags |= TH_XMIT_NEEDED;
13063 
13064 			if (seg_len == 0 && !(flags & TH_URG)) {
13065 				freemsg(mp);
13066 				goto xmit_check;
13067 			}
13068 
13069 			flags &= ~TH_SYN;
13070 			seg_seq++;
13071 			break;
13072 		}
13073 		tcp->tcp_state = TCPS_SYN_RCVD;
13074 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13075 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13076 		if (mp1) {
13077 			/*
13078 			 * See comment in tcp_conn_request() for why we use
13079 			 * the open() time pid here.
13080 			 */
13081 			DB_CPID(mp1) = tcp->tcp_cpid;
13082 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13083 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13084 		}
13085 		freemsg(mp);
13086 		return;
13087 	case TCPS_SYN_RCVD:
13088 		if (flags & TH_ACK) {
13089 			/*
13090 			 * In this state, a SYN|ACK packet is either bogus
13091 			 * because the other side must be ACKing our SYN which
13092 			 * indicates it has seen the ACK for their SYN and
13093 			 * shouldn't retransmit it or we're crossing SYNs
13094 			 * on active open.
13095 			 */
13096 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13097 				freemsg(mp);
13098 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13099 				    tcp, seg_ack, 0, TH_RST);
13100 				return;
13101 			}
13102 			/*
13103 			 * NOTE: RFC 793 pg. 72 says this should be
13104 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13105 			 * but that would mean we have an ack that ignored
13106 			 * our SYN.
13107 			 */
13108 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13109 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13110 				freemsg(mp);
13111 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13112 				    tcp, seg_ack, 0, TH_RST);
13113 				return;
13114 			}
13115 		}
13116 		break;
13117 	case TCPS_LISTEN:
13118 		/*
13119 		 * Only a TLI listener can come through this path when a
13120 		 * acceptor is going back to be a listener and a packet
13121 		 * for the acceptor hits the classifier. For a socket
13122 		 * listener, this can never happen because a listener
13123 		 * can never accept connection on itself and hence a
13124 		 * socket acceptor can not go back to being a listener.
13125 		 */
13126 		ASSERT(!TCP_IS_SOCKET(tcp));
13127 		/*FALLTHRU*/
13128 	case TCPS_CLOSED:
13129 	case TCPS_BOUND: {
13130 		conn_t	*new_connp;
13131 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13132 
13133 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13134 		if (new_connp != NULL) {
13135 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13136 			return;
13137 		}
13138 		/* We failed to classify. For now just drop the packet */
13139 		freemsg(mp);
13140 		return;
13141 	}
13142 	case TCPS_IDLE:
13143 		/*
13144 		 * Handle the case where the tcp_clean_death() has happened
13145 		 * on a connection (application hasn't closed yet) but a packet
13146 		 * was already queued on squeue before tcp_clean_death()
13147 		 * was processed. Calling tcp_clean_death() twice on same
13148 		 * connection can result in weird behaviour.
13149 		 */
13150 		freemsg(mp);
13151 		return;
13152 	default:
13153 		break;
13154 	}
13155 
13156 	/*
13157 	 * Already on the correct queue/perimeter.
13158 	 * If this is a detached connection and not an eager
13159 	 * connection hanging off a listener then new data
13160 	 * (past the FIN) will cause a reset.
13161 	 * We do a special check here where it
13162 	 * is out of the main line, rather than check
13163 	 * if we are detached every time we see new
13164 	 * data down below.
13165 	 */
13166 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13167 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13168 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13169 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13170 
13171 		freemsg(mp);
13172 		/*
13173 		 * This could be an SSL closure alert. We're detached so just
13174 		 * acknowledge it this last time.
13175 		 */
13176 		if (tcp->tcp_kssl_ctx != NULL) {
13177 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13178 			tcp->tcp_kssl_ctx = NULL;
13179 
13180 			tcp->tcp_rnxt += seg_len;
13181 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13182 			flags |= TH_ACK_NEEDED;
13183 			goto ack_check;
13184 		}
13185 
13186 		tcp_xmit_ctl("new data when detached", tcp,
13187 		    tcp->tcp_snxt, 0, TH_RST);
13188 		(void) tcp_clean_death(tcp, EPROTO, 12);
13189 		return;
13190 	}
13191 
13192 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13193 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13194 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13195 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13196 
13197 	if (tcp->tcp_snd_ts_ok) {
13198 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13199 			/*
13200 			 * This segment is not acceptable.
13201 			 * Drop it and send back an ACK.
13202 			 */
13203 			freemsg(mp);
13204 			flags |= TH_ACK_NEEDED;
13205 			goto ack_check;
13206 		}
13207 	} else if (tcp->tcp_snd_sack_ok) {
13208 		ASSERT(tcp->tcp_sack_info != NULL);
13209 		tcpopt.tcp = tcp;
13210 		/*
13211 		 * SACK info in already updated in tcp_parse_options.  Ignore
13212 		 * all other TCP options...
13213 		 */
13214 		(void) tcp_parse_options(tcph, &tcpopt);
13215 	}
13216 try_again:;
13217 	mss = tcp->tcp_mss;
13218 	gap = seg_seq - tcp->tcp_rnxt;
13219 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13220 	/*
13221 	 * gap is the amount of sequence space between what we expect to see
13222 	 * and what we got for seg_seq.  A positive value for gap means
13223 	 * something got lost.  A negative value means we got some old stuff.
13224 	 */
13225 	if (gap < 0) {
13226 		/* Old stuff present.  Is the SYN in there? */
13227 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13228 		    (seg_len != 0)) {
13229 			flags &= ~TH_SYN;
13230 			seg_seq++;
13231 			urp--;
13232 			/* Recompute the gaps after noting the SYN. */
13233 			goto try_again;
13234 		}
13235 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13236 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13237 		    (seg_len > -gap ? -gap : seg_len));
13238 		/* Remove the old stuff from seg_len. */
13239 		seg_len += gap;
13240 		/*
13241 		 * Anything left?
13242 		 * Make sure to check for unack'd FIN when rest of data
13243 		 * has been previously ack'd.
13244 		 */
13245 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13246 			/*
13247 			 * Resets are only valid if they lie within our offered
13248 			 * window.  If the RST bit is set, we just ignore this
13249 			 * segment.
13250 			 */
13251 			if (flags & TH_RST) {
13252 				freemsg(mp);
13253 				return;
13254 			}
13255 
13256 			/*
13257 			 * The arriving of dup data packets indicate that we
13258 			 * may have postponed an ack for too long, or the other
13259 			 * side's RTT estimate is out of shape. Start acking
13260 			 * more often.
13261 			 */
13262 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13263 			    tcp->tcp_rack_cnt >= 1 &&
13264 			    tcp->tcp_rack_abs_max > 2) {
13265 				tcp->tcp_rack_abs_max--;
13266 			}
13267 			tcp->tcp_rack_cur_max = 1;
13268 
13269 			/*
13270 			 * This segment is "unacceptable".  None of its
13271 			 * sequence space lies within our advertized window.
13272 			 *
13273 			 * Adjust seg_len to the original value for tracing.
13274 			 */
13275 			seg_len -= gap;
13276 			if (tcp->tcp_debug) {
13277 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13278 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13279 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13280 				    "seg_len %d, rnxt %u, snxt %u, %s",
13281 				    gap, rgap, flags, seg_seq, seg_ack,
13282 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13283 				    tcp_display(tcp, NULL,
13284 				    DISP_ADDR_AND_PORT));
13285 			}
13286 
13287 			/*
13288 			 * Arrange to send an ACK in response to the
13289 			 * unacceptable segment per RFC 793 page 69. There
13290 			 * is only one small difference between ours and the
13291 			 * acceptability test in the RFC - we accept ACK-only
13292 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13293 			 * will be generated.
13294 			 *
13295 			 * Note that we have to ACK an ACK-only packet at least
13296 			 * for stacks that send 0-length keep-alives with
13297 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13298 			 * section 4.2.3.6. As long as we don't ever generate
13299 			 * an unacceptable packet in response to an incoming
13300 			 * packet that is unacceptable, it should not cause
13301 			 * "ACK wars".
13302 			 */
13303 			flags |=  TH_ACK_NEEDED;
13304 
13305 			/*
13306 			 * Continue processing this segment in order to use the
13307 			 * ACK information it contains, but skip all other
13308 			 * sequence-number processing.	Processing the ACK
13309 			 * information is necessary in order to
13310 			 * re-synchronize connections that may have lost
13311 			 * synchronization.
13312 			 *
13313 			 * We clear seg_len and flag fields related to
13314 			 * sequence number processing as they are not
13315 			 * to be trusted for an unacceptable segment.
13316 			 */
13317 			seg_len = 0;
13318 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13319 			goto process_ack;
13320 		}
13321 
13322 		/* Fix seg_seq, and chew the gap off the front. */
13323 		seg_seq = tcp->tcp_rnxt;
13324 		urp += gap;
13325 		do {
13326 			mblk_t	*mp2;
13327 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13328 			    (uintptr_t)UINT_MAX);
13329 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13330 			if (gap > 0) {
13331 				mp->b_rptr = mp->b_wptr - gap;
13332 				break;
13333 			}
13334 			mp2 = mp;
13335 			mp = mp->b_cont;
13336 			freeb(mp2);
13337 		} while (gap < 0);
13338 		/*
13339 		 * If the urgent data has already been acknowledged, we
13340 		 * should ignore TH_URG below
13341 		 */
13342 		if (urp < 0)
13343 			flags &= ~TH_URG;
13344 	}
13345 	/*
13346 	 * rgap is the amount of stuff received out of window.  A negative
13347 	 * value is the amount out of window.
13348 	 */
13349 	if (rgap < 0) {
13350 		mblk_t	*mp2;
13351 
13352 		if (tcp->tcp_rwnd == 0) {
13353 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13354 		} else {
13355 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13356 			UPDATE_MIB(&tcps->tcps_mib,
13357 			    tcpInDataPastWinBytes, -rgap);
13358 		}
13359 
13360 		/*
13361 		 * seg_len does not include the FIN, so if more than
13362 		 * just the FIN is out of window, we act like we don't
13363 		 * see it.  (If just the FIN is out of window, rgap
13364 		 * will be zero and we will go ahead and acknowledge
13365 		 * the FIN.)
13366 		 */
13367 		flags &= ~TH_FIN;
13368 
13369 		/* Fix seg_len and make sure there is something left. */
13370 		seg_len += rgap;
13371 		if (seg_len <= 0) {
13372 			/*
13373 			 * Resets are only valid if they lie within our offered
13374 			 * window.  If the RST bit is set, we just ignore this
13375 			 * segment.
13376 			 */
13377 			if (flags & TH_RST) {
13378 				freemsg(mp);
13379 				return;
13380 			}
13381 
13382 			/* Per RFC 793, we need to send back an ACK. */
13383 			flags |= TH_ACK_NEEDED;
13384 
13385 			/*
13386 			 * Send SIGURG as soon as possible i.e. even
13387 			 * if the TH_URG was delivered in a window probe
13388 			 * packet (which will be unacceptable).
13389 			 *
13390 			 * We generate a signal if none has been generated
13391 			 * for this connection or if this is a new urgent
13392 			 * byte. Also send a zero-length "unmarked" message
13393 			 * to inform SIOCATMARK that this is not the mark.
13394 			 *
13395 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13396 			 * is sent up. This plus the check for old data
13397 			 * (gap >= 0) handles the wraparound of the sequence
13398 			 * number space without having to always track the
13399 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13400 			 * this max in its rcv_up variable).
13401 			 *
13402 			 * This prevents duplicate SIGURGS due to a "late"
13403 			 * zero-window probe when the T_EXDATA_IND has already
13404 			 * been sent up.
13405 			 */
13406 			if ((flags & TH_URG) &&
13407 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13408 			    tcp->tcp_urp_last))) {
13409 				if (IPCL_IS_NONSTR(connp)) {
13410 					if (!TCP_IS_DETACHED(tcp)) {
13411 						(*connp->conn_upcalls->
13412 						    su_signal_oob)
13413 						    (connp->conn_upper_handle,
13414 						    urp);
13415 					}
13416 				} else {
13417 					mp1 = allocb(0, BPRI_MED);
13418 					if (mp1 == NULL) {
13419 						freemsg(mp);
13420 						return;
13421 					}
13422 					if (!TCP_IS_DETACHED(tcp) &&
13423 					    !putnextctl1(tcp->tcp_rq,
13424 					    M_PCSIG, SIGURG)) {
13425 						/* Try again on the rexmit. */
13426 						freemsg(mp1);
13427 						freemsg(mp);
13428 						return;
13429 					}
13430 					/*
13431 					 * If the next byte would be the mark
13432 					 * then mark with MARKNEXT else mark
13433 					 * with NOTMARKNEXT.
13434 					 */
13435 					if (gap == 0 && urp == 0)
13436 						mp1->b_flag |= MSGMARKNEXT;
13437 					else
13438 						mp1->b_flag |= MSGNOTMARKNEXT;
13439 					freemsg(tcp->tcp_urp_mark_mp);
13440 					tcp->tcp_urp_mark_mp = mp1;
13441 					flags |= TH_SEND_URP_MARK;
13442 				}
13443 				tcp->tcp_urp_last_valid = B_TRUE;
13444 				tcp->tcp_urp_last = urp + seg_seq;
13445 			}
13446 			/*
13447 			 * If this is a zero window probe, continue to
13448 			 * process the ACK part.  But we need to set seg_len
13449 			 * to 0 to avoid data processing.  Otherwise just
13450 			 * drop the segment and send back an ACK.
13451 			 */
13452 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13453 				flags &= ~(TH_SYN | TH_URG);
13454 				seg_len = 0;
13455 				goto process_ack;
13456 			} else {
13457 				freemsg(mp);
13458 				goto ack_check;
13459 			}
13460 		}
13461 		/* Pitch out of window stuff off the end. */
13462 		rgap = seg_len;
13463 		mp2 = mp;
13464 		do {
13465 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13466 			    (uintptr_t)INT_MAX);
13467 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13468 			if (rgap < 0) {
13469 				mp2->b_wptr += rgap;
13470 				if ((mp1 = mp2->b_cont) != NULL) {
13471 					mp2->b_cont = NULL;
13472 					freemsg(mp1);
13473 				}
13474 				break;
13475 			}
13476 		} while ((mp2 = mp2->b_cont) != NULL);
13477 	}
13478 ok:;
13479 	/*
13480 	 * TCP should check ECN info for segments inside the window only.
13481 	 * Therefore the check should be done here.
13482 	 */
13483 	if (tcp->tcp_ecn_ok) {
13484 		if (flags & TH_CWR) {
13485 			tcp->tcp_ecn_echo_on = B_FALSE;
13486 		}
13487 		/*
13488 		 * Note that both ECN_CE and CWR can be set in the
13489 		 * same segment.  In this case, we once again turn
13490 		 * on ECN_ECHO.
13491 		 */
13492 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13493 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13494 
13495 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13496 				tcp->tcp_ecn_echo_on = B_TRUE;
13497 			}
13498 		} else {
13499 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13500 
13501 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13502 			    htonl(IPH_ECN_CE << 20)) {
13503 				tcp->tcp_ecn_echo_on = B_TRUE;
13504 			}
13505 		}
13506 	}
13507 
13508 	/*
13509 	 * Check whether we can update tcp_ts_recent.  This test is
13510 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13511 	 * Extensions for High Performance: An Update", Internet Draft.
13512 	 */
13513 	if (tcp->tcp_snd_ts_ok &&
13514 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13515 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13516 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13517 		tcp->tcp_last_rcv_lbolt = lbolt64;
13518 	}
13519 
13520 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13521 		/*
13522 		 * FIN in an out of order segment.  We record this in
13523 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13524 		 * Clear the FIN so that any check on FIN flag will fail.
13525 		 * Remember that FIN also counts in the sequence number
13526 		 * space.  So we need to ack out of order FIN only segments.
13527 		 */
13528 		if (flags & TH_FIN) {
13529 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13530 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13531 			flags &= ~TH_FIN;
13532 			flags |= TH_ACK_NEEDED;
13533 		}
13534 		if (seg_len > 0) {
13535 			/* Fill in the SACK blk list. */
13536 			if (tcp->tcp_snd_sack_ok) {
13537 				ASSERT(tcp->tcp_sack_info != NULL);
13538 				tcp_sack_insert(tcp->tcp_sack_list,
13539 				    seg_seq, seg_seq + seg_len,
13540 				    &(tcp->tcp_num_sack_blk));
13541 			}
13542 
13543 			/*
13544 			 * Attempt reassembly and see if we have something
13545 			 * ready to go.
13546 			 */
13547 			mp = tcp_reass(tcp, mp, seg_seq);
13548 			/* Always ack out of order packets */
13549 			flags |= TH_ACK_NEEDED | TH_PUSH;
13550 			if (mp) {
13551 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13552 				    (uintptr_t)INT_MAX);
13553 				seg_len = mp->b_cont ? msgdsize(mp) :
13554 				    (int)(mp->b_wptr - mp->b_rptr);
13555 				seg_seq = tcp->tcp_rnxt;
13556 				/*
13557 				 * A gap is filled and the seq num and len
13558 				 * of the gap match that of a previously
13559 				 * received FIN, put the FIN flag back in.
13560 				 */
13561 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13562 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13563 					flags |= TH_FIN;
13564 					tcp->tcp_valid_bits &=
13565 					    ~TCP_OFO_FIN_VALID;
13566 				}
13567 			} else {
13568 				/*
13569 				 * Keep going even with NULL mp.
13570 				 * There may be a useful ACK or something else
13571 				 * we don't want to miss.
13572 				 *
13573 				 * But TCP should not perform fast retransmit
13574 				 * because of the ack number.  TCP uses
13575 				 * seg_len == 0 to determine if it is a pure
13576 				 * ACK.  And this is not a pure ACK.
13577 				 */
13578 				seg_len = 0;
13579 				ofo_seg = B_TRUE;
13580 			}
13581 		}
13582 	} else if (seg_len > 0) {
13583 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13584 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13585 		/*
13586 		 * If an out of order FIN was received before, and the seq
13587 		 * num and len of the new segment match that of the FIN,
13588 		 * put the FIN flag back in.
13589 		 */
13590 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13591 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13592 			flags |= TH_FIN;
13593 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13594 		}
13595 	}
13596 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13597 	if (flags & TH_RST) {
13598 		freemsg(mp);
13599 		switch (tcp->tcp_state) {
13600 		case TCPS_SYN_RCVD:
13601 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13602 			break;
13603 		case TCPS_ESTABLISHED:
13604 		case TCPS_FIN_WAIT_1:
13605 		case TCPS_FIN_WAIT_2:
13606 		case TCPS_CLOSE_WAIT:
13607 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13608 			break;
13609 		case TCPS_CLOSING:
13610 		case TCPS_LAST_ACK:
13611 			(void) tcp_clean_death(tcp, 0, 16);
13612 			break;
13613 		default:
13614 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13615 			(void) tcp_clean_death(tcp, ENXIO, 17);
13616 			break;
13617 		}
13618 		return;
13619 	}
13620 	if (flags & TH_SYN) {
13621 		/*
13622 		 * See RFC 793, Page 71
13623 		 *
13624 		 * The seq number must be in the window as it should
13625 		 * be "fixed" above.  If it is outside window, it should
13626 		 * be already rejected.  Note that we allow seg_seq to be
13627 		 * rnxt + rwnd because we want to accept 0 window probe.
13628 		 */
13629 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13630 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13631 		freemsg(mp);
13632 		/*
13633 		 * If the ACK flag is not set, just use our snxt as the
13634 		 * seq number of the RST segment.
13635 		 */
13636 		if (!(flags & TH_ACK)) {
13637 			seg_ack = tcp->tcp_snxt;
13638 		}
13639 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13640 		    TH_RST|TH_ACK);
13641 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13642 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13643 		return;
13644 	}
13645 	/*
13646 	 * urp could be -1 when the urp field in the packet is 0
13647 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13648 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13649 	 */
13650 	if (flags & TH_URG && urp >= 0) {
13651 		if (!tcp->tcp_urp_last_valid ||
13652 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13653 			/*
13654 			 * Non-STREAMS sockets handle the urgent data a litte
13655 			 * differently from STREAMS based sockets. There is no
13656 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
13657 			 * flags to keep SIOCATMARK happy. Instead a
13658 			 * su_signal_oob upcall is made to update the mark.
13659 			 * Neither is a T_EXDATA_IND mblk needed to be
13660 			 * prepended to the urgent data. The urgent data is
13661 			 * delivered using the su_recv upcall, where we set
13662 			 * the MSG_OOB flag to indicate that it is urg data.
13663 			 *
13664 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
13665 			 * are used by non-STREAMS sockets.
13666 			 */
13667 			if (IPCL_IS_NONSTR(connp)) {
13668 				if (!TCP_IS_DETACHED(tcp)) {
13669 					(*connp->conn_upcalls->su_signal_oob)
13670 					    (connp->conn_upper_handle, urp);
13671 				}
13672 			} else {
13673 				/*
13674 				 * If we haven't generated the signal yet for
13675 				 * this urgent pointer value, do it now.  Also,
13676 				 * send up a zero-length M_DATA indicating
13677 				 * whether or not this is the mark. The latter
13678 				 * is not needed when a T_EXDATA_IND is sent up.
13679 				 * However, if there are allocation failures
13680 				 * this code relies on the sender retransmitting
13681 				 * and the socket code for determining the mark
13682 				 * should not block waiting for the peer to
13683 				 * transmit. Thus, for simplicity we always
13684 				 * send up the mark indication.
13685 				 */
13686 				mp1 = allocb(0, BPRI_MED);
13687 				if (mp1 == NULL) {
13688 					freemsg(mp);
13689 					return;
13690 				}
13691 				if (!TCP_IS_DETACHED(tcp) &&
13692 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13693 				    SIGURG)) {
13694 					/* Try again on the rexmit. */
13695 					freemsg(mp1);
13696 					freemsg(mp);
13697 					return;
13698 				}
13699 				/*
13700 				 * Mark with NOTMARKNEXT for now.
13701 				 * The code below will change this to MARKNEXT
13702 				 * if we are at the mark.
13703 				 *
13704 				 * If there are allocation failures (e.g. in
13705 				 * dupmsg below) the next time tcp_rput_data
13706 				 * sees the urgent segment it will send up the
13707 				 * MSGMARKNEXT message.
13708 				 */
13709 				mp1->b_flag |= MSGNOTMARKNEXT;
13710 				freemsg(tcp->tcp_urp_mark_mp);
13711 				tcp->tcp_urp_mark_mp = mp1;
13712 				flags |= TH_SEND_URP_MARK;
13713 #ifdef DEBUG
13714 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13715 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13716 				    "last %x, %s",
13717 				    seg_seq, urp, tcp->tcp_urp_last,
13718 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13719 #endif /* DEBUG */
13720 			}
13721 			tcp->tcp_urp_last_valid = B_TRUE;
13722 			tcp->tcp_urp_last = urp + seg_seq;
13723 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13724 			/*
13725 			 * An allocation failure prevented the previous
13726 			 * tcp_rput_data from sending up the allocated
13727 			 * MSG*MARKNEXT message - send it up this time
13728 			 * around.
13729 			 */
13730 			flags |= TH_SEND_URP_MARK;
13731 		}
13732 
13733 		/*
13734 		 * If the urgent byte is in this segment, make sure that it is
13735 		 * all by itself.  This makes it much easier to deal with the
13736 		 * possibility of an allocation failure on the T_exdata_ind.
13737 		 * Note that seg_len is the number of bytes in the segment, and
13738 		 * urp is the offset into the segment of the urgent byte.
13739 		 * urp < seg_len means that the urgent byte is in this segment.
13740 		 */
13741 		if (urp < seg_len) {
13742 			if (seg_len != 1) {
13743 				uint32_t  tmp_rnxt;
13744 				/*
13745 				 * Break it up and feed it back in.
13746 				 * Re-attach the IP header.
13747 				 */
13748 				mp->b_rptr = iphdr;
13749 				if (urp > 0) {
13750 					/*
13751 					 * There is stuff before the urgent
13752 					 * byte.
13753 					 */
13754 					mp1 = dupmsg(mp);
13755 					if (!mp1) {
13756 						/*
13757 						 * Trim from urgent byte on.
13758 						 * The rest will come back.
13759 						 */
13760 						(void) adjmsg(mp,
13761 						    urp - seg_len);
13762 						tcp_rput_data(connp,
13763 						    mp, NULL);
13764 						return;
13765 					}
13766 					(void) adjmsg(mp1, urp - seg_len);
13767 					/* Feed this piece back in. */
13768 					tmp_rnxt = tcp->tcp_rnxt;
13769 					tcp_rput_data(connp, mp1, NULL);
13770 					/*
13771 					 * If the data passed back in was not
13772 					 * processed (ie: bad ACK) sending
13773 					 * the remainder back in will cause a
13774 					 * loop. In this case, drop the
13775 					 * packet and let the sender try
13776 					 * sending a good packet.
13777 					 */
13778 					if (tmp_rnxt == tcp->tcp_rnxt) {
13779 						freemsg(mp);
13780 						return;
13781 					}
13782 				}
13783 				if (urp != seg_len - 1) {
13784 					uint32_t  tmp_rnxt;
13785 					/*
13786 					 * There is stuff after the urgent
13787 					 * byte.
13788 					 */
13789 					mp1 = dupmsg(mp);
13790 					if (!mp1) {
13791 						/*
13792 						 * Trim everything beyond the
13793 						 * urgent byte.  The rest will
13794 						 * come back.
13795 						 */
13796 						(void) adjmsg(mp,
13797 						    urp + 1 - seg_len);
13798 						tcp_rput_data(connp,
13799 						    mp, NULL);
13800 						return;
13801 					}
13802 					(void) adjmsg(mp1, urp + 1 - seg_len);
13803 					tmp_rnxt = tcp->tcp_rnxt;
13804 					tcp_rput_data(connp, mp1, NULL);
13805 					/*
13806 					 * If the data passed back in was not
13807 					 * processed (ie: bad ACK) sending
13808 					 * the remainder back in will cause a
13809 					 * loop. In this case, drop the
13810 					 * packet and let the sender try
13811 					 * sending a good packet.
13812 					 */
13813 					if (tmp_rnxt == tcp->tcp_rnxt) {
13814 						freemsg(mp);
13815 						return;
13816 					}
13817 				}
13818 				tcp_rput_data(connp, mp, NULL);
13819 				return;
13820 			}
13821 			/*
13822 			 * This segment contains only the urgent byte.  We
13823 			 * have to allocate the T_exdata_ind, if we can.
13824 			 */
13825 			if (IPCL_IS_NONSTR(connp)) {
13826 				int error;
13827 
13828 				(*connp->conn_upcalls->su_recv)
13829 				    (connp->conn_upper_handle, mp, seg_len,
13830 				    MSG_OOB, &error, NULL);
13831 				/*
13832 				 * We should never be in middle of a
13833 				 * fallback, the squeue guarantees that.
13834 				 */
13835 				ASSERT(error != EOPNOTSUPP);
13836 				mp = NULL;
13837 				goto update_ack;
13838 			} else if (!tcp->tcp_urp_mp) {
13839 				struct T_exdata_ind *tei;
13840 				mp1 = allocb(sizeof (struct T_exdata_ind),
13841 				    BPRI_MED);
13842 				if (!mp1) {
13843 					/*
13844 					 * Sigh... It'll be back.
13845 					 * Generate any MSG*MARK message now.
13846 					 */
13847 					freemsg(mp);
13848 					seg_len = 0;
13849 					if (flags & TH_SEND_URP_MARK) {
13850 
13851 
13852 						ASSERT(tcp->tcp_urp_mark_mp);
13853 						tcp->tcp_urp_mark_mp->b_flag &=
13854 						    ~MSGNOTMARKNEXT;
13855 						tcp->tcp_urp_mark_mp->b_flag |=
13856 						    MSGMARKNEXT;
13857 					}
13858 					goto ack_check;
13859 				}
13860 				mp1->b_datap->db_type = M_PROTO;
13861 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13862 				tei->PRIM_type = T_EXDATA_IND;
13863 				tei->MORE_flag = 0;
13864 				mp1->b_wptr = (uchar_t *)&tei[1];
13865 				tcp->tcp_urp_mp = mp1;
13866 #ifdef DEBUG
13867 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13868 				    "tcp_rput: allocated exdata_ind %s",
13869 				    tcp_display(tcp, NULL,
13870 				    DISP_PORT_ONLY));
13871 #endif /* DEBUG */
13872 				/*
13873 				 * There is no need to send a separate MSG*MARK
13874 				 * message since the T_EXDATA_IND will be sent
13875 				 * now.
13876 				 */
13877 				flags &= ~TH_SEND_URP_MARK;
13878 				freemsg(tcp->tcp_urp_mark_mp);
13879 				tcp->tcp_urp_mark_mp = NULL;
13880 			}
13881 			/*
13882 			 * Now we are all set.  On the next putnext upstream,
13883 			 * tcp_urp_mp will be non-NULL and will get prepended
13884 			 * to what has to be this piece containing the urgent
13885 			 * byte.  If for any reason we abort this segment below,
13886 			 * if it comes back, we will have this ready, or it
13887 			 * will get blown off in close.
13888 			 */
13889 		} else if (urp == seg_len) {
13890 			/*
13891 			 * The urgent byte is the next byte after this sequence
13892 			 * number. If this endpoint is non-STREAMS, then there
13893 			 * is nothing to do here since the socket has already
13894 			 * been notified about the urg pointer by the
13895 			 * su_signal_oob call above.
13896 			 *
13897 			 * In case of STREAMS, some more work might be needed.
13898 			 * If there is data it is marked with MSGMARKNEXT and
13899 			 * and any tcp_urp_mark_mp is discarded since it is not
13900 			 * needed. Otherwise, if the code above just allocated
13901 			 * a zero-length tcp_urp_mark_mp message, that message
13902 			 * is tagged with MSGMARKNEXT. Sending up these
13903 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
13904 			 * even though the T_EXDATA_IND will not be sent up
13905 			 * until the urgent byte arrives.
13906 			 */
13907 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
13908 				if (seg_len != 0) {
13909 					flags |= TH_MARKNEXT_NEEDED;
13910 					freemsg(tcp->tcp_urp_mark_mp);
13911 					tcp->tcp_urp_mark_mp = NULL;
13912 					flags &= ~TH_SEND_URP_MARK;
13913 				} else if (tcp->tcp_urp_mark_mp != NULL) {
13914 					flags |= TH_SEND_URP_MARK;
13915 					tcp->tcp_urp_mark_mp->b_flag &=
13916 					    ~MSGNOTMARKNEXT;
13917 					tcp->tcp_urp_mark_mp->b_flag |=
13918 					    MSGMARKNEXT;
13919 				}
13920 			}
13921 #ifdef DEBUG
13922 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13923 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13924 			    seg_len, flags,
13925 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13926 #endif /* DEBUG */
13927 		}
13928 #ifdef DEBUG
13929 		else {
13930 			/* Data left until we hit mark */
13931 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13932 			    "tcp_rput: URP %d bytes left, %s",
13933 			    urp - seg_len, tcp_display(tcp, NULL,
13934 			    DISP_PORT_ONLY));
13935 		}
13936 #endif /* DEBUG */
13937 	}
13938 
13939 process_ack:
13940 	if (!(flags & TH_ACK)) {
13941 		freemsg(mp);
13942 		goto xmit_check;
13943 	}
13944 	}
13945 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13946 
13947 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13948 		tcp->tcp_ip_forward_progress = B_TRUE;
13949 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13950 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13951 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13952 			/* 3-way handshake complete - pass up the T_CONN_IND */
13953 			tcp_t	*listener = tcp->tcp_listener;
13954 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13955 
13956 			tcp->tcp_tconnind_started = B_TRUE;
13957 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13958 			/*
13959 			 * We are here means eager is fine but it can
13960 			 * get a TH_RST at any point between now and till
13961 			 * accept completes and disappear. We need to
13962 			 * ensure that reference to eager is valid after
13963 			 * we get out of eager's perimeter. So we do
13964 			 * an extra refhold.
13965 			 */
13966 			CONN_INC_REF(connp);
13967 
13968 			/*
13969 			 * The listener also exists because of the refhold
13970 			 * done in tcp_conn_request. Its possible that it
13971 			 * might have closed. We will check that once we
13972 			 * get inside listeners context.
13973 			 */
13974 			CONN_INC_REF(listener->tcp_connp);
13975 			if (listener->tcp_connp->conn_sqp ==
13976 			    connp->conn_sqp) {
13977 				/*
13978 				 * We optimize by not calling an SQUEUE_ENTER
13979 				 * on the listener since we know that the
13980 				 * listener and eager squeues are the same.
13981 				 * We are able to make this check safely only
13982 				 * because neither the eager nor the listener
13983 				 * can change its squeue. Only an active connect
13984 				 * can change its squeue
13985 				 */
13986 				tcp_send_conn_ind(listener->tcp_connp, mp,
13987 				    listener->tcp_connp->conn_sqp);
13988 				CONN_DEC_REF(listener->tcp_connp);
13989 			} else if (!tcp->tcp_loopback) {
13990 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
13991 				    mp, tcp_send_conn_ind,
13992 				    listener->tcp_connp, SQ_FILL,
13993 				    SQTAG_TCP_CONN_IND);
13994 			} else {
13995 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
13996 				    mp, tcp_send_conn_ind,
13997 				    listener->tcp_connp, SQ_PROCESS,
13998 				    SQTAG_TCP_CONN_IND);
13999 			}
14000 		}
14001 
14002 		/*
14003 		 * We are seeing the final ack in the three way
14004 		 * hand shake of a active open'ed connection
14005 		 * so we must send up a T_CONN_CON
14006 		 *
14007 		 * tcp_sendmsg() checks tcp_state without entering
14008 		 * the squeue so tcp_state should be updated before
14009 		 * sending up connection confirmation.
14010 		 */
14011 		tcp->tcp_state = TCPS_ESTABLISHED;
14012 		if (tcp->tcp_active_open) {
14013 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14014 				freemsg(mp);
14015 				tcp->tcp_state = TCPS_SYN_RCVD;
14016 				return;
14017 			}
14018 			/*
14019 			 * Don't fuse the loopback endpoints for
14020 			 * simultaneous active opens.
14021 			 */
14022 			if (tcp->tcp_loopback) {
14023 				TCP_STAT(tcps, tcp_fusion_unfusable);
14024 				tcp->tcp_unfusable = B_TRUE;
14025 			}
14026 		}
14027 
14028 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14029 		bytes_acked--;
14030 		/* SYN was acked - making progress */
14031 		if (tcp->tcp_ipversion == IPV6_VERSION)
14032 			tcp->tcp_ip_forward_progress = B_TRUE;
14033 
14034 		/*
14035 		 * If SYN was retransmitted, need to reset all
14036 		 * retransmission info as this segment will be
14037 		 * treated as a dup ACK.
14038 		 */
14039 		if (tcp->tcp_rexmit) {
14040 			tcp->tcp_rexmit = B_FALSE;
14041 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14042 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14043 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14044 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14045 			tcp->tcp_ms_we_have_waited = 0;
14046 			tcp->tcp_cwnd = mss;
14047 		}
14048 
14049 		/*
14050 		 * We set the send window to zero here.
14051 		 * This is needed if there is data to be
14052 		 * processed already on the queue.
14053 		 * Later (at swnd_update label), the
14054 		 * "new_swnd > tcp_swnd" condition is satisfied
14055 		 * the XMIT_NEEDED flag is set in the current
14056 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14057 		 * called if there is already data on queue in
14058 		 * this state.
14059 		 */
14060 		tcp->tcp_swnd = 0;
14061 
14062 		if (new_swnd > tcp->tcp_max_swnd)
14063 			tcp->tcp_max_swnd = new_swnd;
14064 		tcp->tcp_swl1 = seg_seq;
14065 		tcp->tcp_swl2 = seg_ack;
14066 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14067 
14068 		/* Fuse when both sides are in ESTABLISHED state */
14069 		if (tcp->tcp_loopback && do_tcp_fusion)
14070 			tcp_fuse(tcp, iphdr, tcph);
14071 
14072 	}
14073 	/* This code follows 4.4BSD-Lite2 mostly. */
14074 	if (bytes_acked < 0)
14075 		goto est;
14076 
14077 	/*
14078 	 * If TCP is ECN capable and the congestion experience bit is
14079 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14080 	 * done once per window (or more loosely, per RTT).
14081 	 */
14082 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14083 		tcp->tcp_cwr = B_FALSE;
14084 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14085 		if (!tcp->tcp_cwr) {
14086 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14087 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14088 			tcp->tcp_cwnd = npkt * mss;
14089 			/*
14090 			 * If the cwnd is 0, use the timer to clock out
14091 			 * new segments.  This is required by the ECN spec.
14092 			 */
14093 			if (npkt == 0) {
14094 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14095 				/*
14096 				 * This makes sure that when the ACK comes
14097 				 * back, we will increase tcp_cwnd by 1 MSS.
14098 				 */
14099 				tcp->tcp_cwnd_cnt = 0;
14100 			}
14101 			tcp->tcp_cwr = B_TRUE;
14102 			/*
14103 			 * This marks the end of the current window of in
14104 			 * flight data.  That is why we don't use
14105 			 * tcp_suna + tcp_swnd.  Only data in flight can
14106 			 * provide ECN info.
14107 			 */
14108 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14109 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14110 		}
14111 	}
14112 
14113 	mp1 = tcp->tcp_xmit_head;
14114 	if (bytes_acked == 0) {
14115 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14116 			int dupack_cnt;
14117 
14118 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14119 			/*
14120 			 * Fast retransmit.  When we have seen exactly three
14121 			 * identical ACKs while we have unacked data
14122 			 * outstanding we take it as a hint that our peer
14123 			 * dropped something.
14124 			 *
14125 			 * If TCP is retransmitting, don't do fast retransmit.
14126 			 */
14127 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14128 			    ! tcp->tcp_rexmit) {
14129 				/* Do Limited Transmit */
14130 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14131 				    tcps->tcps_dupack_fast_retransmit) {
14132 					/*
14133 					 * RFC 3042
14134 					 *
14135 					 * What we need to do is temporarily
14136 					 * increase tcp_cwnd so that new
14137 					 * data can be sent if it is allowed
14138 					 * by the receive window (tcp_rwnd).
14139 					 * tcp_wput_data() will take care of
14140 					 * the rest.
14141 					 *
14142 					 * If the connection is SACK capable,
14143 					 * only do limited xmit when there
14144 					 * is SACK info.
14145 					 *
14146 					 * Note how tcp_cwnd is incremented.
14147 					 * The first dup ACK will increase
14148 					 * it by 1 MSS.  The second dup ACK
14149 					 * will increase it by 2 MSS.  This
14150 					 * means that only 1 new segment will
14151 					 * be sent for each dup ACK.
14152 					 */
14153 					if (tcp->tcp_unsent > 0 &&
14154 					    (!tcp->tcp_snd_sack_ok ||
14155 					    (tcp->tcp_snd_sack_ok &&
14156 					    tcp->tcp_notsack_list != NULL))) {
14157 						tcp->tcp_cwnd += mss <<
14158 						    (tcp->tcp_dupack_cnt - 1);
14159 						flags |= TH_LIMIT_XMIT;
14160 					}
14161 				} else if (dupack_cnt ==
14162 				    tcps->tcps_dupack_fast_retransmit) {
14163 
14164 				/*
14165 				 * If we have reduced tcp_ssthresh
14166 				 * because of ECN, do not reduce it again
14167 				 * unless it is already one window of data
14168 				 * away.  After one window of data, tcp_cwr
14169 				 * should then be cleared.  Note that
14170 				 * for non ECN capable connection, tcp_cwr
14171 				 * should always be false.
14172 				 *
14173 				 * Adjust cwnd since the duplicate
14174 				 * ack indicates that a packet was
14175 				 * dropped (due to congestion.)
14176 				 */
14177 				if (!tcp->tcp_cwr) {
14178 					npkt = ((tcp->tcp_snxt -
14179 					    tcp->tcp_suna) >> 1) / mss;
14180 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14181 					    mss;
14182 					tcp->tcp_cwnd = (npkt +
14183 					    tcp->tcp_dupack_cnt) * mss;
14184 				}
14185 				if (tcp->tcp_ecn_ok) {
14186 					tcp->tcp_cwr = B_TRUE;
14187 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14188 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14189 				}
14190 
14191 				/*
14192 				 * We do Hoe's algorithm.  Refer to her
14193 				 * paper "Improving the Start-up Behavior
14194 				 * of a Congestion Control Scheme for TCP,"
14195 				 * appeared in SIGCOMM'96.
14196 				 *
14197 				 * Save highest seq no we have sent so far.
14198 				 * Be careful about the invisible FIN byte.
14199 				 */
14200 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14201 				    (tcp->tcp_unsent == 0)) {
14202 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14203 				} else {
14204 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14205 				}
14206 
14207 				/*
14208 				 * Do not allow bursty traffic during.
14209 				 * fast recovery.  Refer to Fall and Floyd's
14210 				 * paper "Simulation-based Comparisons of
14211 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14212 				 * This is a best current practise.
14213 				 */
14214 				tcp->tcp_snd_burst = TCP_CWND_SS;
14215 
14216 				/*
14217 				 * For SACK:
14218 				 * Calculate tcp_pipe, which is the
14219 				 * estimated number of bytes in
14220 				 * network.
14221 				 *
14222 				 * tcp_fack is the highest sack'ed seq num
14223 				 * TCP has received.
14224 				 *
14225 				 * tcp_pipe is explained in the above quoted
14226 				 * Fall and Floyd's paper.  tcp_fack is
14227 				 * explained in Mathis and Mahdavi's
14228 				 * "Forward Acknowledgment: Refining TCP
14229 				 * Congestion Control" in SIGCOMM '96.
14230 				 */
14231 				if (tcp->tcp_snd_sack_ok) {
14232 					ASSERT(tcp->tcp_sack_info != NULL);
14233 					if (tcp->tcp_notsack_list != NULL) {
14234 						tcp->tcp_pipe = tcp->tcp_snxt -
14235 						    tcp->tcp_fack;
14236 						tcp->tcp_sack_snxt = seg_ack;
14237 						flags |= TH_NEED_SACK_REXMIT;
14238 					} else {
14239 						/*
14240 						 * Always initialize tcp_pipe
14241 						 * even though we don't have
14242 						 * any SACK info.  If later
14243 						 * we get SACK info and
14244 						 * tcp_pipe is not initialized,
14245 						 * funny things will happen.
14246 						 */
14247 						tcp->tcp_pipe =
14248 						    tcp->tcp_cwnd_ssthresh;
14249 					}
14250 				} else {
14251 					flags |= TH_REXMIT_NEEDED;
14252 				} /* tcp_snd_sack_ok */
14253 
14254 				} else {
14255 					/*
14256 					 * Here we perform congestion
14257 					 * avoidance, but NOT slow start.
14258 					 * This is known as the Fast
14259 					 * Recovery Algorithm.
14260 					 */
14261 					if (tcp->tcp_snd_sack_ok &&
14262 					    tcp->tcp_notsack_list != NULL) {
14263 						flags |= TH_NEED_SACK_REXMIT;
14264 						tcp->tcp_pipe -= mss;
14265 						if (tcp->tcp_pipe < 0)
14266 							tcp->tcp_pipe = 0;
14267 					} else {
14268 					/*
14269 					 * We know that one more packet has
14270 					 * left the pipe thus we can update
14271 					 * cwnd.
14272 					 */
14273 					cwnd = tcp->tcp_cwnd + mss;
14274 					if (cwnd > tcp->tcp_cwnd_max)
14275 						cwnd = tcp->tcp_cwnd_max;
14276 					tcp->tcp_cwnd = cwnd;
14277 					if (tcp->tcp_unsent > 0)
14278 						flags |= TH_XMIT_NEEDED;
14279 					}
14280 				}
14281 			}
14282 		} else if (tcp->tcp_zero_win_probe) {
14283 			/*
14284 			 * If the window has opened, need to arrange
14285 			 * to send additional data.
14286 			 */
14287 			if (new_swnd != 0) {
14288 				/* tcp_suna != tcp_snxt */
14289 				/* Packet contains a window update */
14290 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14291 				tcp->tcp_zero_win_probe = 0;
14292 				tcp->tcp_timer_backoff = 0;
14293 				tcp->tcp_ms_we_have_waited = 0;
14294 
14295 				/*
14296 				 * Transmit starting with tcp_suna since
14297 				 * the one byte probe is not ack'ed.
14298 				 * If TCP has sent more than one identical
14299 				 * probe, tcp_rexmit will be set.  That means
14300 				 * tcp_ss_rexmit() will send out the one
14301 				 * byte along with new data.  Otherwise,
14302 				 * fake the retransmission.
14303 				 */
14304 				flags |= TH_XMIT_NEEDED;
14305 				if (!tcp->tcp_rexmit) {
14306 					tcp->tcp_rexmit = B_TRUE;
14307 					tcp->tcp_dupack_cnt = 0;
14308 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14309 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14310 				}
14311 			}
14312 		}
14313 		goto swnd_update;
14314 	}
14315 
14316 	/*
14317 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14318 	 * If the ACK value acks something that we have not yet sent, it might
14319 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14320 	 * other side.
14321 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14322 	 * state is handled above, so we can always just drop the segment and
14323 	 * send an ACK here.
14324 	 *
14325 	 * In the case where the peer shrinks the window, we see the new window
14326 	 * update, but all the data sent previously is queued up by the peer.
14327 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
14328 	 * number, which was already sent, and within window, is recorded.
14329 	 * tcp_snxt is then updated.
14330 	 *
14331 	 * If the window has previously shrunk, and an ACK for data not yet
14332 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
14333 	 * the ACK is for data within the window at the time the window was
14334 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
14335 	 * the sequence number ACK'ed.
14336 	 *
14337 	 * If the ACK covers all the data sent at the time the window was
14338 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
14339 	 *
14340 	 * Should we send ACKs in response to ACK only segments?
14341 	 */
14342 
14343 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14344 		if ((tcp->tcp_is_wnd_shrnk) &&
14345 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
14346 			uint32_t data_acked_ahead_snxt;
14347 
14348 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
14349 			tcp_update_xmit_tail(tcp, seg_ack);
14350 			tcp->tcp_unsent -= data_acked_ahead_snxt;
14351 		} else {
14352 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14353 			/* drop the received segment */
14354 			freemsg(mp);
14355 
14356 			/*
14357 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14358 			 * greater than 0, check if the number of such
14359 			 * bogus ACks is greater than that count.  If yes,
14360 			 * don't send back any ACK.  This prevents TCP from
14361 			 * getting into an ACK storm if somehow an attacker
14362 			 * successfully spoofs an acceptable segment to our
14363 			 * peer.
14364 			 */
14365 			if (tcp_drop_ack_unsent_cnt > 0 &&
14366 			    ++tcp->tcp_in_ack_unsent >
14367 			    tcp_drop_ack_unsent_cnt) {
14368 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14369 				return;
14370 			}
14371 			mp = tcp_ack_mp(tcp);
14372 			if (mp != NULL) {
14373 				BUMP_LOCAL(tcp->tcp_obsegs);
14374 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14375 				tcp_send_data(tcp, tcp->tcp_wq, mp);
14376 			}
14377 			return;
14378 		}
14379 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
14380 	    tcp->tcp_snxt_shrunk)) {
14381 			tcp->tcp_is_wnd_shrnk = B_FALSE;
14382 	}
14383 
14384 	/*
14385 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14386 	 * blocks that are covered by this ACK.
14387 	 */
14388 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14389 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14390 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14391 	}
14392 
14393 	/*
14394 	 * If we got an ACK after fast retransmit, check to see
14395 	 * if it is a partial ACK.  If it is not and the congestion
14396 	 * window was inflated to account for the other side's
14397 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14398 	 */
14399 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14400 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14401 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14402 			tcp->tcp_dupack_cnt = 0;
14403 			/*
14404 			 * Restore the orig tcp_cwnd_ssthresh after
14405 			 * fast retransmit phase.
14406 			 */
14407 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14408 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14409 			}
14410 			tcp->tcp_rexmit_max = seg_ack;
14411 			tcp->tcp_cwnd_cnt = 0;
14412 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14413 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14414 
14415 			/*
14416 			 * Remove all notsack info to avoid confusion with
14417 			 * the next fast retrasnmit/recovery phase.
14418 			 */
14419 			if (tcp->tcp_snd_sack_ok &&
14420 			    tcp->tcp_notsack_list != NULL) {
14421 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
14422 				    tcp);
14423 			}
14424 		} else {
14425 			if (tcp->tcp_snd_sack_ok &&
14426 			    tcp->tcp_notsack_list != NULL) {
14427 				flags |= TH_NEED_SACK_REXMIT;
14428 				tcp->tcp_pipe -= mss;
14429 				if (tcp->tcp_pipe < 0)
14430 					tcp->tcp_pipe = 0;
14431 			} else {
14432 				/*
14433 				 * Hoe's algorithm:
14434 				 *
14435 				 * Retransmit the unack'ed segment and
14436 				 * restart fast recovery.  Note that we
14437 				 * need to scale back tcp_cwnd to the
14438 				 * original value when we started fast
14439 				 * recovery.  This is to prevent overly
14440 				 * aggressive behaviour in sending new
14441 				 * segments.
14442 				 */
14443 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14444 				    tcps->tcps_dupack_fast_retransmit * mss;
14445 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14446 				flags |= TH_REXMIT_NEEDED;
14447 			}
14448 		}
14449 	} else {
14450 		tcp->tcp_dupack_cnt = 0;
14451 		if (tcp->tcp_rexmit) {
14452 			/*
14453 			 * TCP is retranmitting.  If the ACK ack's all
14454 			 * outstanding data, update tcp_rexmit_max and
14455 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14456 			 * to the correct value.
14457 			 *
14458 			 * Note that SEQ_LEQ() is used.  This is to avoid
14459 			 * unnecessary fast retransmit caused by dup ACKs
14460 			 * received when TCP does slow start retransmission
14461 			 * after a time out.  During this phase, TCP may
14462 			 * send out segments which are already received.
14463 			 * This causes dup ACKs to be sent back.
14464 			 */
14465 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14466 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14467 					tcp->tcp_rexmit_nxt = seg_ack;
14468 				}
14469 				if (seg_ack != tcp->tcp_rexmit_max) {
14470 					flags |= TH_XMIT_NEEDED;
14471 				}
14472 			} else {
14473 				tcp->tcp_rexmit = B_FALSE;
14474 				tcp->tcp_xmit_zc_clean = B_FALSE;
14475 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14476 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14477 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14478 			}
14479 			tcp->tcp_ms_we_have_waited = 0;
14480 		}
14481 	}
14482 
14483 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14484 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14485 	tcp->tcp_suna = seg_ack;
14486 	if (tcp->tcp_zero_win_probe != 0) {
14487 		tcp->tcp_zero_win_probe = 0;
14488 		tcp->tcp_timer_backoff = 0;
14489 	}
14490 
14491 	/*
14492 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14493 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14494 	 * will not reach here.
14495 	 */
14496 	if (mp1 == NULL) {
14497 		goto fin_acked;
14498 	}
14499 
14500 	/*
14501 	 * Update the congestion window.
14502 	 *
14503 	 * If TCP is not ECN capable or TCP is ECN capable but the
14504 	 * congestion experience bit is not set, increase the tcp_cwnd as
14505 	 * usual.
14506 	 */
14507 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14508 		cwnd = tcp->tcp_cwnd;
14509 		add = mss;
14510 
14511 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14512 			/*
14513 			 * This is to prevent an increase of less than 1 MSS of
14514 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14515 			 * may send out tinygrams in order to preserve mblk
14516 			 * boundaries.
14517 			 *
14518 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14519 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14520 			 * increased by 1 MSS for every RTTs.
14521 			 */
14522 			if (tcp->tcp_cwnd_cnt <= 0) {
14523 				tcp->tcp_cwnd_cnt = cwnd + add;
14524 			} else {
14525 				tcp->tcp_cwnd_cnt -= add;
14526 				add = 0;
14527 			}
14528 		}
14529 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14530 	}
14531 
14532 	/* See if the latest urgent data has been acknowledged */
14533 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14534 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14535 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14536 
14537 	/* Can we update the RTT estimates? */
14538 	if (tcp->tcp_snd_ts_ok) {
14539 		/* Ignore zero timestamp echo-reply. */
14540 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14541 			tcp_set_rto(tcp, (int32_t)lbolt -
14542 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14543 		}
14544 
14545 		/* If needed, restart the timer. */
14546 		if (tcp->tcp_set_timer == 1) {
14547 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14548 			tcp->tcp_set_timer = 0;
14549 		}
14550 		/*
14551 		 * Update tcp_csuna in case the other side stops sending
14552 		 * us timestamps.
14553 		 */
14554 		tcp->tcp_csuna = tcp->tcp_snxt;
14555 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14556 		/*
14557 		 * An ACK sequence we haven't seen before, so get the RTT
14558 		 * and update the RTO. But first check if the timestamp is
14559 		 * valid to use.
14560 		 */
14561 		if ((mp1->b_next != NULL) &&
14562 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14563 			tcp_set_rto(tcp, (int32_t)lbolt -
14564 			    (int32_t)(intptr_t)mp1->b_prev);
14565 		else
14566 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14567 
14568 		/* Remeber the last sequence to be ACKed */
14569 		tcp->tcp_csuna = seg_ack;
14570 		if (tcp->tcp_set_timer == 1) {
14571 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14572 			tcp->tcp_set_timer = 0;
14573 		}
14574 	} else {
14575 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14576 	}
14577 
14578 	/* Eat acknowledged bytes off the xmit queue. */
14579 	for (;;) {
14580 		mblk_t	*mp2;
14581 		uchar_t	*wptr;
14582 
14583 		wptr = mp1->b_wptr;
14584 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14585 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14586 		if (bytes_acked < 0) {
14587 			mp1->b_rptr = wptr + bytes_acked;
14588 			/*
14589 			 * Set a new timestamp if all the bytes timed by the
14590 			 * old timestamp have been ack'ed.
14591 			 */
14592 			if (SEQ_GT(seg_ack,
14593 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14594 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14595 				mp1->b_next = NULL;
14596 			}
14597 			break;
14598 		}
14599 		mp1->b_next = NULL;
14600 		mp1->b_prev = NULL;
14601 		mp2 = mp1;
14602 		mp1 = mp1->b_cont;
14603 
14604 		/*
14605 		 * This notification is required for some zero-copy
14606 		 * clients to maintain a copy semantic. After the data
14607 		 * is ack'ed, client is safe to modify or reuse the buffer.
14608 		 */
14609 		if (tcp->tcp_snd_zcopy_aware &&
14610 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14611 			tcp_zcopy_notify(tcp);
14612 		freeb(mp2);
14613 		if (bytes_acked == 0) {
14614 			if (mp1 == NULL) {
14615 				/* Everything is ack'ed, clear the tail. */
14616 				tcp->tcp_xmit_tail = NULL;
14617 				/*
14618 				 * Cancel the timer unless we are still
14619 				 * waiting for an ACK for the FIN packet.
14620 				 */
14621 				if (tcp->tcp_timer_tid != 0 &&
14622 				    tcp->tcp_snxt == tcp->tcp_suna) {
14623 					(void) TCP_TIMER_CANCEL(tcp,
14624 					    tcp->tcp_timer_tid);
14625 					tcp->tcp_timer_tid = 0;
14626 				}
14627 				goto pre_swnd_update;
14628 			}
14629 			if (mp2 != tcp->tcp_xmit_tail)
14630 				break;
14631 			tcp->tcp_xmit_tail = mp1;
14632 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14633 			    (uintptr_t)INT_MAX);
14634 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14635 			    mp1->b_rptr);
14636 			break;
14637 		}
14638 		if (mp1 == NULL) {
14639 			/*
14640 			 * More was acked but there is nothing more
14641 			 * outstanding.  This means that the FIN was
14642 			 * just acked or that we're talking to a clown.
14643 			 */
14644 fin_acked:
14645 			ASSERT(tcp->tcp_fin_sent);
14646 			tcp->tcp_xmit_tail = NULL;
14647 			if (tcp->tcp_fin_sent) {
14648 				/* FIN was acked - making progress */
14649 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14650 				    !tcp->tcp_fin_acked)
14651 					tcp->tcp_ip_forward_progress = B_TRUE;
14652 				tcp->tcp_fin_acked = B_TRUE;
14653 				if (tcp->tcp_linger_tid != 0 &&
14654 				    TCP_TIMER_CANCEL(tcp,
14655 				    tcp->tcp_linger_tid) >= 0) {
14656 					tcp_stop_lingering(tcp);
14657 					freemsg(mp);
14658 					mp = NULL;
14659 				}
14660 			} else {
14661 				/*
14662 				 * We should never get here because
14663 				 * we have already checked that the
14664 				 * number of bytes ack'ed should be
14665 				 * smaller than or equal to what we
14666 				 * have sent so far (it is the
14667 				 * acceptability check of the ACK).
14668 				 * We can only get here if the send
14669 				 * queue is corrupted.
14670 				 *
14671 				 * Terminate the connection and
14672 				 * panic the system.  It is better
14673 				 * for us to panic instead of
14674 				 * continuing to avoid other disaster.
14675 				 */
14676 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14677 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14678 				panic("Memory corruption "
14679 				    "detected for connection %s.",
14680 				    tcp_display(tcp, NULL,
14681 				    DISP_ADDR_AND_PORT));
14682 				/*NOTREACHED*/
14683 			}
14684 			goto pre_swnd_update;
14685 		}
14686 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14687 	}
14688 	if (tcp->tcp_unsent) {
14689 		flags |= TH_XMIT_NEEDED;
14690 	}
14691 pre_swnd_update:
14692 	tcp->tcp_xmit_head = mp1;
14693 swnd_update:
14694 	/*
14695 	 * The following check is different from most other implementations.
14696 	 * For bi-directional transfer, when segments are dropped, the
14697 	 * "normal" check will not accept a window update in those
14698 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14699 	 * segments which are outside receiver's window.  As TCP accepts
14700 	 * the ack in those retransmitted segments, if the window update in
14701 	 * the same segment is not accepted, TCP will incorrectly calculates
14702 	 * that it can send more segments.  This can create a deadlock
14703 	 * with the receiver if its window becomes zero.
14704 	 */
14705 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14706 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14707 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14708 		/*
14709 		 * The criteria for update is:
14710 		 *
14711 		 * 1. the segment acknowledges some data.  Or
14712 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14713 		 * 3. the segment is not old and the advertised window is
14714 		 * larger than the previous advertised window.
14715 		 */
14716 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14717 			flags |= TH_XMIT_NEEDED;
14718 		tcp->tcp_swnd = new_swnd;
14719 		if (new_swnd > tcp->tcp_max_swnd)
14720 			tcp->tcp_max_swnd = new_swnd;
14721 		tcp->tcp_swl1 = seg_seq;
14722 		tcp->tcp_swl2 = seg_ack;
14723 	}
14724 est:
14725 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14726 
14727 		switch (tcp->tcp_state) {
14728 		case TCPS_FIN_WAIT_1:
14729 			if (tcp->tcp_fin_acked) {
14730 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14731 				/*
14732 				 * We implement the non-standard BSD/SunOS
14733 				 * FIN_WAIT_2 flushing algorithm.
14734 				 * If there is no user attached to this
14735 				 * TCP endpoint, then this TCP struct
14736 				 * could hang around forever in FIN_WAIT_2
14737 				 * state if the peer forgets to send us
14738 				 * a FIN.  To prevent this, we wait only
14739 				 * 2*MSL (a convenient time value) for
14740 				 * the FIN to arrive.  If it doesn't show up,
14741 				 * we flush the TCP endpoint.  This algorithm,
14742 				 * though a violation of RFC-793, has worked
14743 				 * for over 10 years in BSD systems.
14744 				 * Note: SunOS 4.x waits 675 seconds before
14745 				 * flushing the FIN_WAIT_2 connection.
14746 				 */
14747 				TCP_TIMER_RESTART(tcp,
14748 				    tcps->tcps_fin_wait_2_flush_interval);
14749 			}
14750 			break;
14751 		case TCPS_FIN_WAIT_2:
14752 			break;	/* Shutdown hook? */
14753 		case TCPS_LAST_ACK:
14754 			freemsg(mp);
14755 			if (tcp->tcp_fin_acked) {
14756 				(void) tcp_clean_death(tcp, 0, 19);
14757 				return;
14758 			}
14759 			goto xmit_check;
14760 		case TCPS_CLOSING:
14761 			if (tcp->tcp_fin_acked) {
14762 				tcp->tcp_state = TCPS_TIME_WAIT;
14763 				/*
14764 				 * Unconditionally clear the exclusive binding
14765 				 * bit so this TIME-WAIT connection won't
14766 				 * interfere with new ones.
14767 				 */
14768 				tcp->tcp_exclbind = 0;
14769 				if (!TCP_IS_DETACHED(tcp)) {
14770 					TCP_TIMER_RESTART(tcp,
14771 					    tcps->tcps_time_wait_interval);
14772 				} else {
14773 					tcp_time_wait_append(tcp);
14774 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14775 				}
14776 			}
14777 			/*FALLTHRU*/
14778 		case TCPS_CLOSE_WAIT:
14779 			freemsg(mp);
14780 			goto xmit_check;
14781 		default:
14782 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14783 			break;
14784 		}
14785 	}
14786 	if (flags & TH_FIN) {
14787 		/* Make sure we ack the fin */
14788 		flags |= TH_ACK_NEEDED;
14789 		if (!tcp->tcp_fin_rcvd) {
14790 			tcp->tcp_fin_rcvd = B_TRUE;
14791 			tcp->tcp_rnxt++;
14792 			tcph = tcp->tcp_tcph;
14793 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14794 
14795 			/*
14796 			 * Generate the ordrel_ind at the end unless we
14797 			 * are an eager guy.
14798 			 * In the eager case tcp_rsrv will do this when run
14799 			 * after tcp_accept is done.
14800 			 */
14801 			if (tcp->tcp_listener == NULL &&
14802 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14803 				flags |= TH_ORDREL_NEEDED;
14804 			switch (tcp->tcp_state) {
14805 			case TCPS_SYN_RCVD:
14806 			case TCPS_ESTABLISHED:
14807 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14808 				/* Keepalive? */
14809 				break;
14810 			case TCPS_FIN_WAIT_1:
14811 				if (!tcp->tcp_fin_acked) {
14812 					tcp->tcp_state = TCPS_CLOSING;
14813 					break;
14814 				}
14815 				/* FALLTHRU */
14816 			case TCPS_FIN_WAIT_2:
14817 				tcp->tcp_state = TCPS_TIME_WAIT;
14818 				/*
14819 				 * Unconditionally clear the exclusive binding
14820 				 * bit so this TIME-WAIT connection won't
14821 				 * interfere with new ones.
14822 				 */
14823 				tcp->tcp_exclbind = 0;
14824 				if (!TCP_IS_DETACHED(tcp)) {
14825 					TCP_TIMER_RESTART(tcp,
14826 					    tcps->tcps_time_wait_interval);
14827 				} else {
14828 					tcp_time_wait_append(tcp);
14829 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14830 				}
14831 				if (seg_len) {
14832 					/*
14833 					 * implies data piggybacked on FIN.
14834 					 * break to handle data.
14835 					 */
14836 					break;
14837 				}
14838 				freemsg(mp);
14839 				goto ack_check;
14840 			}
14841 		}
14842 	}
14843 	if (mp == NULL)
14844 		goto xmit_check;
14845 	if (seg_len == 0) {
14846 		freemsg(mp);
14847 		goto xmit_check;
14848 	}
14849 	if (mp->b_rptr == mp->b_wptr) {
14850 		/*
14851 		 * The header has been consumed, so we remove the
14852 		 * zero-length mblk here.
14853 		 */
14854 		mp1 = mp;
14855 		mp = mp->b_cont;
14856 		freeb(mp1);
14857 	}
14858 update_ack:
14859 	tcph = tcp->tcp_tcph;
14860 	tcp->tcp_rack_cnt++;
14861 	{
14862 		uint32_t cur_max;
14863 
14864 		cur_max = tcp->tcp_rack_cur_max;
14865 		if (tcp->tcp_rack_cnt >= cur_max) {
14866 			/*
14867 			 * We have more unacked data than we should - send
14868 			 * an ACK now.
14869 			 */
14870 			flags |= TH_ACK_NEEDED;
14871 			cur_max++;
14872 			if (cur_max > tcp->tcp_rack_abs_max)
14873 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14874 			else
14875 				tcp->tcp_rack_cur_max = cur_max;
14876 		} else if (TCP_IS_DETACHED(tcp)) {
14877 			/* We don't have an ACK timer for detached TCP. */
14878 			flags |= TH_ACK_NEEDED;
14879 		} else if (seg_len < mss) {
14880 			/*
14881 			 * If we get a segment that is less than an mss, and we
14882 			 * already have unacknowledged data, and the amount
14883 			 * unacknowledged is not a multiple of mss, then we
14884 			 * better generate an ACK now.  Otherwise, this may be
14885 			 * the tail piece of a transaction, and we would rather
14886 			 * wait for the response.
14887 			 */
14888 			uint32_t udif;
14889 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14890 			    (uintptr_t)INT_MAX);
14891 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14892 			if (udif && (udif % mss))
14893 				flags |= TH_ACK_NEEDED;
14894 			else
14895 				flags |= TH_ACK_TIMER_NEEDED;
14896 		} else {
14897 			/* Start delayed ack timer */
14898 			flags |= TH_ACK_TIMER_NEEDED;
14899 		}
14900 	}
14901 	tcp->tcp_rnxt += seg_len;
14902 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14903 
14904 	if (mp == NULL)
14905 		goto xmit_check;
14906 
14907 	/* Update SACK list */
14908 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14909 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14910 		    &(tcp->tcp_num_sack_blk));
14911 	}
14912 
14913 	if (tcp->tcp_urp_mp) {
14914 		tcp->tcp_urp_mp->b_cont = mp;
14915 		mp = tcp->tcp_urp_mp;
14916 		tcp->tcp_urp_mp = NULL;
14917 		/* Ready for a new signal. */
14918 		tcp->tcp_urp_last_valid = B_FALSE;
14919 #ifdef DEBUG
14920 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14921 		    "tcp_rput: sending exdata_ind %s",
14922 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14923 #endif /* DEBUG */
14924 	}
14925 
14926 	/*
14927 	 * Check for ancillary data changes compared to last segment.
14928 	 */
14929 	if (tcp->tcp_ipv6_recvancillary != 0) {
14930 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14931 		ASSERT(mp != NULL);
14932 	}
14933 
14934 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14935 		/*
14936 		 * Side queue inbound data until the accept happens.
14937 		 * tcp_accept/tcp_rput drains this when the accept happens.
14938 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14939 		 * T_EXDATA_IND) it is queued on b_next.
14940 		 * XXX Make urgent data use this. Requires:
14941 		 *	Removing tcp_listener check for TH_URG
14942 		 *	Making M_PCPROTO and MARK messages skip the eager case
14943 		 */
14944 
14945 		if (tcp->tcp_kssl_pending) {
14946 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
14947 			    mblk_t *, mp);
14948 			tcp_kssl_input(tcp, mp);
14949 		} else {
14950 			tcp_rcv_enqueue(tcp, mp, seg_len);
14951 		}
14952 	} else if (IPCL_IS_NONSTR(connp)) {
14953 		/*
14954 		 * Non-STREAMS socket
14955 		 *
14956 		 * Note that no KSSL processing is done here, because
14957 		 * KSSL is not supported for non-STREAMS sockets.
14958 		 */
14959 		boolean_t push = flags & (TH_PUSH|TH_FIN);
14960 		int error;
14961 
14962 		if ((*connp->conn_upcalls->su_recv)(
14963 		    connp->conn_upper_handle,
14964 		    mp, seg_len, 0, &error, &push) <= 0) {
14965 			/*
14966 			 * We should never be in middle of a
14967 			 * fallback, the squeue guarantees that.
14968 			 */
14969 			ASSERT(error != EOPNOTSUPP);
14970 			if (error == ENOSPC)
14971 				tcp->tcp_rwnd -= seg_len;
14972 		} else if (push) {
14973 			/* PUSH bit set and sockfs is not flow controlled */
14974 			flags |= tcp_rwnd_reopen(tcp);
14975 		}
14976 	} else {
14977 		/* STREAMS socket */
14978 		if (mp->b_datap->db_type != M_DATA ||
14979 		    (flags & TH_MARKNEXT_NEEDED)) {
14980 			if (tcp->tcp_rcv_list != NULL) {
14981 				flags |= tcp_rcv_drain(tcp);
14982 			}
14983 			ASSERT(tcp->tcp_rcv_list == NULL ||
14984 			    tcp->tcp_fused_sigurg);
14985 
14986 			if (flags & TH_MARKNEXT_NEEDED) {
14987 #ifdef DEBUG
14988 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14989 				    "tcp_rput: sending MSGMARKNEXT %s",
14990 				    tcp_display(tcp, NULL,
14991 				    DISP_PORT_ONLY));
14992 #endif /* DEBUG */
14993 				mp->b_flag |= MSGMARKNEXT;
14994 				flags &= ~TH_MARKNEXT_NEEDED;
14995 			}
14996 
14997 			/* Does this need SSL processing first? */
14998 			if ((tcp->tcp_kssl_ctx != NULL) &&
14999 			    (DB_TYPE(mp) == M_DATA)) {
15000 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15001 				    mblk_t *, mp);
15002 				tcp_kssl_input(tcp, mp);
15003 			} else {
15004 				putnext(tcp->tcp_rq, mp);
15005 				if (!canputnext(tcp->tcp_rq))
15006 					tcp->tcp_rwnd -= seg_len;
15007 			}
15008 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15009 		    (DB_TYPE(mp) == M_DATA)) {
15010 			/* Does this need SSL processing first? */
15011 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15012 			tcp_kssl_input(tcp, mp);
15013 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15014 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15015 			if (tcp->tcp_rcv_list != NULL) {
15016 				/*
15017 				 * Enqueue the new segment first and then
15018 				 * call tcp_rcv_drain() to send all data
15019 				 * up.  The other way to do this is to
15020 				 * send all queued data up and then call
15021 				 * putnext() to send the new segment up.
15022 				 * This way can remove the else part later
15023 				 * on.
15024 				 *
15025 				 * We don't do this to avoid one more call to
15026 				 * canputnext() as tcp_rcv_drain() needs to
15027 				 * call canputnext().
15028 				 */
15029 				tcp_rcv_enqueue(tcp, mp, seg_len);
15030 				flags |= tcp_rcv_drain(tcp);
15031 			} else {
15032 				putnext(tcp->tcp_rq, mp);
15033 				if (!canputnext(tcp->tcp_rq))
15034 					tcp->tcp_rwnd -= seg_len;
15035 			}
15036 		} else {
15037 			/*
15038 			 * Enqueue all packets when processing an mblk
15039 			 * from the co queue and also enqueue normal packets.
15040 			 */
15041 			tcp_rcv_enqueue(tcp, mp, seg_len);
15042 		}
15043 		/*
15044 		 * Make sure the timer is running if we have data waiting
15045 		 * for a push bit. This provides resiliency against
15046 		 * implementations that do not correctly generate push bits.
15047 		 */
15048 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
15049 			/*
15050 			 * The connection may be closed at this point, so don't
15051 			 * do anything for a detached tcp.
15052 			 */
15053 			if (!TCP_IS_DETACHED(tcp))
15054 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15055 				    tcp_push_timer,
15056 				    MSEC_TO_TICK(
15057 				    tcps->tcps_push_timer_interval));
15058 		}
15059 	}
15060 
15061 xmit_check:
15062 	/* Is there anything left to do? */
15063 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15064 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15065 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15066 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15067 		goto done;
15068 
15069 	/* Any transmit work to do and a non-zero window? */
15070 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15071 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15072 		if (flags & TH_REXMIT_NEEDED) {
15073 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15074 
15075 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15076 			if (snd_size > mss)
15077 				snd_size = mss;
15078 			if (snd_size > tcp->tcp_swnd)
15079 				snd_size = tcp->tcp_swnd;
15080 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15081 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15082 			    B_TRUE);
15083 
15084 			if (mp1 != NULL) {
15085 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15086 				tcp->tcp_csuna = tcp->tcp_snxt;
15087 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15088 				UPDATE_MIB(&tcps->tcps_mib,
15089 				    tcpRetransBytes, snd_size);
15090 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15091 			}
15092 		}
15093 		if (flags & TH_NEED_SACK_REXMIT) {
15094 			tcp_sack_rxmit(tcp, &flags);
15095 		}
15096 		/*
15097 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15098 		 * out new segment.  Note that tcp_rexmit should not be
15099 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15100 		 */
15101 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15102 			if (!tcp->tcp_rexmit) {
15103 				tcp_wput_data(tcp, NULL, B_FALSE);
15104 			} else {
15105 				tcp_ss_rexmit(tcp);
15106 			}
15107 		}
15108 		/*
15109 		 * Adjust tcp_cwnd back to normal value after sending
15110 		 * new data segments.
15111 		 */
15112 		if (flags & TH_LIMIT_XMIT) {
15113 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15114 			/*
15115 			 * This will restart the timer.  Restarting the
15116 			 * timer is used to avoid a timeout before the
15117 			 * limited transmitted segment's ACK gets back.
15118 			 */
15119 			if (tcp->tcp_xmit_head != NULL)
15120 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15121 		}
15122 
15123 		/* Anything more to do? */
15124 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15125 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15126 			goto done;
15127 	}
15128 ack_check:
15129 	if (flags & TH_SEND_URP_MARK) {
15130 		ASSERT(tcp->tcp_urp_mark_mp);
15131 		ASSERT(!IPCL_IS_NONSTR(connp));
15132 		/*
15133 		 * Send up any queued data and then send the mark message
15134 		 */
15135 		if (tcp->tcp_rcv_list != NULL) {
15136 			flags |= tcp_rcv_drain(tcp);
15137 
15138 		}
15139 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15140 		mp1 = tcp->tcp_urp_mark_mp;
15141 		tcp->tcp_urp_mark_mp = NULL;
15142 		putnext(tcp->tcp_rq, mp1);
15143 #ifdef DEBUG
15144 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15145 		    "tcp_rput: sending zero-length %s %s",
15146 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15147 		    "MSGNOTMARKNEXT"),
15148 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15149 #endif /* DEBUG */
15150 		flags &= ~TH_SEND_URP_MARK;
15151 	}
15152 	if (flags & TH_ACK_NEEDED) {
15153 		/*
15154 		 * Time to send an ack for some reason.
15155 		 */
15156 		mp1 = tcp_ack_mp(tcp);
15157 
15158 		if (mp1 != NULL) {
15159 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15160 			BUMP_LOCAL(tcp->tcp_obsegs);
15161 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15162 		}
15163 		if (tcp->tcp_ack_tid != 0) {
15164 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15165 			tcp->tcp_ack_tid = 0;
15166 		}
15167 	}
15168 	if (flags & TH_ACK_TIMER_NEEDED) {
15169 		/*
15170 		 * Arrange for deferred ACK or push wait timeout.
15171 		 * Start timer if it is not already running.
15172 		 */
15173 		if (tcp->tcp_ack_tid == 0) {
15174 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15175 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15176 			    (clock_t)tcps->tcps_local_dack_interval :
15177 			    (clock_t)tcps->tcps_deferred_ack_interval));
15178 		}
15179 	}
15180 	if (flags & TH_ORDREL_NEEDED) {
15181 		/*
15182 		 * Send up the ordrel_ind unless we are an eager guy.
15183 		 * In the eager case tcp_rsrv will do this when run
15184 		 * after tcp_accept is done.
15185 		 */
15186 		ASSERT(tcp->tcp_listener == NULL);
15187 
15188 		if (IPCL_IS_NONSTR(connp)) {
15189 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15190 			tcp->tcp_ordrel_done = B_TRUE;
15191 			(*connp->conn_upcalls->su_opctl)
15192 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15193 			goto done;
15194 		}
15195 
15196 		if (tcp->tcp_rcv_list != NULL) {
15197 			/*
15198 			 * Push any mblk(s) enqueued from co processing.
15199 			 */
15200 			flags |= tcp_rcv_drain(tcp);
15201 		}
15202 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15203 
15204 		mp1 = tcp->tcp_ordrel_mp;
15205 		tcp->tcp_ordrel_mp = NULL;
15206 		tcp->tcp_ordrel_done = B_TRUE;
15207 		putnext(tcp->tcp_rq, mp1);
15208 	}
15209 done:
15210 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15211 }
15212 
15213 /*
15214  * This routine adjusts next-to-send sequence number variables, in the
15215  * case where the reciever has shrunk it's window.
15216  */
15217 static void
15218 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
15219 {
15220 	mblk_t *xmit_tail;
15221 	int32_t offset;
15222 
15223 	tcp->tcp_snxt = snxt;
15224 
15225 	/* Get the mblk, and the offset in it, as per the shrunk window */
15226 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
15227 	ASSERT(xmit_tail != NULL);
15228 	tcp->tcp_xmit_tail = xmit_tail;
15229 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
15230 	    xmit_tail->b_rptr - offset;
15231 }
15232 
15233 /*
15234  * This function does PAWS protection check. Returns B_TRUE if the
15235  * segment passes the PAWS test, else returns B_FALSE.
15236  */
15237 boolean_t
15238 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15239 {
15240 	uint8_t	flags;
15241 	int	options;
15242 	uint8_t *up;
15243 
15244 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15245 	/*
15246 	 * If timestamp option is aligned nicely, get values inline,
15247 	 * otherwise call general routine to parse.  Only do that
15248 	 * if timestamp is the only option.
15249 	 */
15250 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15251 	    TCPOPT_REAL_TS_LEN &&
15252 	    OK_32PTR((up = ((uint8_t *)tcph) +
15253 	    TCP_MIN_HEADER_LENGTH)) &&
15254 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15255 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15256 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15257 
15258 		options = TCP_OPT_TSTAMP_PRESENT;
15259 	} else {
15260 		if (tcp->tcp_snd_sack_ok) {
15261 			tcpoptp->tcp = tcp;
15262 		} else {
15263 			tcpoptp->tcp = NULL;
15264 		}
15265 		options = tcp_parse_options(tcph, tcpoptp);
15266 	}
15267 
15268 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15269 		/*
15270 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15271 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15272 		 */
15273 		if ((flags & TH_RST) == 0 &&
15274 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15275 		    tcp->tcp_ts_recent)) {
15276 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15277 			    PAWS_TIMEOUT)) {
15278 				/* This segment is not acceptable. */
15279 				return (B_FALSE);
15280 			} else {
15281 				/*
15282 				 * Connection has been idle for
15283 				 * too long.  Reset the timestamp
15284 				 * and assume the segment is valid.
15285 				 */
15286 				tcp->tcp_ts_recent =
15287 				    tcpoptp->tcp_opt_ts_val;
15288 			}
15289 		}
15290 	} else {
15291 		/*
15292 		 * If we don't get a timestamp on every packet, we
15293 		 * figure we can't really trust 'em, so we stop sending
15294 		 * and parsing them.
15295 		 */
15296 		tcp->tcp_snd_ts_ok = B_FALSE;
15297 
15298 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15299 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15300 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15301 		/*
15302 		 * Adjust the tcp_mss accordingly. We also need to
15303 		 * adjust tcp_cwnd here in accordance with the new mss.
15304 		 * But we avoid doing a slow start here so as to not
15305 		 * to lose on the transfer rate built up so far.
15306 		 */
15307 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15308 		if (tcp->tcp_snd_sack_ok) {
15309 			ASSERT(tcp->tcp_sack_info != NULL);
15310 			tcp->tcp_max_sack_blk = 4;
15311 		}
15312 	}
15313 	return (B_TRUE);
15314 }
15315 
15316 /*
15317  * Attach ancillary data to a received TCP segments for the
15318  * ancillary pieces requested by the application that are
15319  * different than they were in the previous data segment.
15320  *
15321  * Save the "current" values once memory allocation is ok so that
15322  * when memory allocation fails we can just wait for the next data segment.
15323  */
15324 static mblk_t *
15325 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15326 {
15327 	struct T_optdata_ind *todi;
15328 	int optlen;
15329 	uchar_t *optptr;
15330 	struct T_opthdr *toh;
15331 	uint_t addflag;	/* Which pieces to add */
15332 	mblk_t *mp1;
15333 
15334 	optlen = 0;
15335 	addflag = 0;
15336 	/* If app asked for pktinfo and the index has changed ... */
15337 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15338 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15339 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15340 		optlen += sizeof (struct T_opthdr) +
15341 		    sizeof (struct in6_pktinfo);
15342 		addflag |= TCP_IPV6_RECVPKTINFO;
15343 	}
15344 	/* If app asked for hoplimit and it has changed ... */
15345 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15346 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15347 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15348 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15349 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15350 	}
15351 	/* If app asked for tclass and it has changed ... */
15352 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15353 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15354 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15355 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15356 		addflag |= TCP_IPV6_RECVTCLASS;
15357 	}
15358 	/*
15359 	 * If app asked for hopbyhop headers and it has changed ...
15360 	 * For security labels, note that (1) security labels can't change on
15361 	 * a connected socket at all, (2) we're connected to at most one peer,
15362 	 * (3) if anything changes, then it must be some other extra option.
15363 	 */
15364 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15365 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15366 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15367 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15368 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15369 		    tcp->tcp_label_len;
15370 		addflag |= TCP_IPV6_RECVHOPOPTS;
15371 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15372 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15373 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15374 			return (mp);
15375 	}
15376 	/* If app asked for dst headers before routing headers ... */
15377 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15378 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15379 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15380 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15381 		optlen += sizeof (struct T_opthdr) +
15382 		    ipp->ipp_rtdstoptslen;
15383 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15384 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15385 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15386 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15387 			return (mp);
15388 	}
15389 	/* If app asked for routing headers and it has changed ... */
15390 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15391 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15392 	    (ipp->ipp_fields & IPPF_RTHDR),
15393 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15394 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15395 		addflag |= TCP_IPV6_RECVRTHDR;
15396 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15397 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15398 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15399 			return (mp);
15400 	}
15401 	/* If app asked for dest headers and it has changed ... */
15402 	if ((tcp->tcp_ipv6_recvancillary &
15403 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15404 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15405 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15406 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15407 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15408 		addflag |= TCP_IPV6_RECVDSTOPTS;
15409 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15410 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15411 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15412 			return (mp);
15413 	}
15414 
15415 	if (optlen == 0) {
15416 		/* Nothing to add */
15417 		return (mp);
15418 	}
15419 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15420 	if (mp1 == NULL) {
15421 		/*
15422 		 * Defer sending ancillary data until the next TCP segment
15423 		 * arrives.
15424 		 */
15425 		return (mp);
15426 	}
15427 	mp1->b_cont = mp;
15428 	mp = mp1;
15429 	mp->b_wptr += sizeof (*todi) + optlen;
15430 	mp->b_datap->db_type = M_PROTO;
15431 	todi = (struct T_optdata_ind *)mp->b_rptr;
15432 	todi->PRIM_type = T_OPTDATA_IND;
15433 	todi->DATA_flag = 1;	/* MORE data */
15434 	todi->OPT_length = optlen;
15435 	todi->OPT_offset = sizeof (*todi);
15436 	optptr = (uchar_t *)&todi[1];
15437 	/*
15438 	 * If app asked for pktinfo and the index has changed ...
15439 	 * Note that the local address never changes for the connection.
15440 	 */
15441 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15442 		struct in6_pktinfo *pkti;
15443 
15444 		toh = (struct T_opthdr *)optptr;
15445 		toh->level = IPPROTO_IPV6;
15446 		toh->name = IPV6_PKTINFO;
15447 		toh->len = sizeof (*toh) + sizeof (*pkti);
15448 		toh->status = 0;
15449 		optptr += sizeof (*toh);
15450 		pkti = (struct in6_pktinfo *)optptr;
15451 		if (tcp->tcp_ipversion == IPV6_VERSION)
15452 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15453 		else
15454 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15455 			    &pkti->ipi6_addr);
15456 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15457 		optptr += sizeof (*pkti);
15458 		ASSERT(OK_32PTR(optptr));
15459 		/* Save as "last" value */
15460 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15461 	}
15462 	/* If app asked for hoplimit and it has changed ... */
15463 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15464 		toh = (struct T_opthdr *)optptr;
15465 		toh->level = IPPROTO_IPV6;
15466 		toh->name = IPV6_HOPLIMIT;
15467 		toh->len = sizeof (*toh) + sizeof (uint_t);
15468 		toh->status = 0;
15469 		optptr += sizeof (*toh);
15470 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15471 		optptr += sizeof (uint_t);
15472 		ASSERT(OK_32PTR(optptr));
15473 		/* Save as "last" value */
15474 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15475 	}
15476 	/* If app asked for tclass and it has changed ... */
15477 	if (addflag & TCP_IPV6_RECVTCLASS) {
15478 		toh = (struct T_opthdr *)optptr;
15479 		toh->level = IPPROTO_IPV6;
15480 		toh->name = IPV6_TCLASS;
15481 		toh->len = sizeof (*toh) + sizeof (uint_t);
15482 		toh->status = 0;
15483 		optptr += sizeof (*toh);
15484 		*(uint_t *)optptr = ipp->ipp_tclass;
15485 		optptr += sizeof (uint_t);
15486 		ASSERT(OK_32PTR(optptr));
15487 		/* Save as "last" value */
15488 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15489 	}
15490 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15491 		toh = (struct T_opthdr *)optptr;
15492 		toh->level = IPPROTO_IPV6;
15493 		toh->name = IPV6_HOPOPTS;
15494 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15495 		    tcp->tcp_label_len;
15496 		toh->status = 0;
15497 		optptr += sizeof (*toh);
15498 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15499 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15500 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15501 		ASSERT(OK_32PTR(optptr));
15502 		/* Save as last value */
15503 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15504 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15505 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15506 	}
15507 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15508 		toh = (struct T_opthdr *)optptr;
15509 		toh->level = IPPROTO_IPV6;
15510 		toh->name = IPV6_RTHDRDSTOPTS;
15511 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15512 		toh->status = 0;
15513 		optptr += sizeof (*toh);
15514 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15515 		optptr += ipp->ipp_rtdstoptslen;
15516 		ASSERT(OK_32PTR(optptr));
15517 		/* Save as last value */
15518 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15519 		    &tcp->tcp_rtdstoptslen,
15520 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15521 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15522 	}
15523 	if (addflag & TCP_IPV6_RECVRTHDR) {
15524 		toh = (struct T_opthdr *)optptr;
15525 		toh->level = IPPROTO_IPV6;
15526 		toh->name = IPV6_RTHDR;
15527 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15528 		toh->status = 0;
15529 		optptr += sizeof (*toh);
15530 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15531 		optptr += ipp->ipp_rthdrlen;
15532 		ASSERT(OK_32PTR(optptr));
15533 		/* Save as last value */
15534 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15535 		    (ipp->ipp_fields & IPPF_RTHDR),
15536 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15537 	}
15538 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15539 		toh = (struct T_opthdr *)optptr;
15540 		toh->level = IPPROTO_IPV6;
15541 		toh->name = IPV6_DSTOPTS;
15542 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15543 		toh->status = 0;
15544 		optptr += sizeof (*toh);
15545 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15546 		optptr += ipp->ipp_dstoptslen;
15547 		ASSERT(OK_32PTR(optptr));
15548 		/* Save as last value */
15549 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15550 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15551 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15552 	}
15553 	ASSERT(optptr == mp->b_wptr);
15554 	return (mp);
15555 }
15556 
15557 /*
15558  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15559  * messages.
15560  */
15561 void
15562 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15563 {
15564 	uchar_t	*rptr = mp->b_rptr;
15565 	queue_t	*q = tcp->tcp_rq;
15566 	struct T_error_ack *tea;
15567 
15568 	switch (mp->b_datap->db_type) {
15569 	case M_PROTO:
15570 	case M_PCPROTO:
15571 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15572 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15573 			break;
15574 		tea = (struct T_error_ack *)rptr;
15575 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15576 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15577 		    tea->ERROR_prim != T_BIND_REQ);
15578 		switch (tea->PRIM_type) {
15579 		case T_ERROR_ACK:
15580 			if (tcp->tcp_debug) {
15581 				(void) strlog(TCP_MOD_ID, 0, 1,
15582 				    SL_TRACE|SL_ERROR,
15583 				    "tcp_rput_other: case T_ERROR_ACK, "
15584 				    "ERROR_prim == %d",
15585 				    tea->ERROR_prim);
15586 			}
15587 			switch (tea->ERROR_prim) {
15588 			case T_SVR4_OPTMGMT_REQ:
15589 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15590 					/* T_OPTMGMT_REQ generated by TCP */
15591 					printf("T_SVR4_OPTMGMT_REQ failed "
15592 					    "%d/%d - dropped (cnt %d)\n",
15593 					    tea->TLI_error, tea->UNIX_error,
15594 					    tcp->tcp_drop_opt_ack_cnt);
15595 					freemsg(mp);
15596 					tcp->tcp_drop_opt_ack_cnt--;
15597 					return;
15598 				}
15599 				break;
15600 			}
15601 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15602 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15603 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15604 				    "- dropped (cnt %d)\n",
15605 				    tea->TLI_error, tea->UNIX_error,
15606 				    tcp->tcp_drop_opt_ack_cnt);
15607 				freemsg(mp);
15608 				tcp->tcp_drop_opt_ack_cnt--;
15609 				return;
15610 			}
15611 			break;
15612 		case T_OPTMGMT_ACK:
15613 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15614 				/* T_OPTMGMT_REQ generated by TCP */
15615 				freemsg(mp);
15616 				tcp->tcp_drop_opt_ack_cnt--;
15617 				return;
15618 			}
15619 			break;
15620 		default:
15621 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15622 			break;
15623 		}
15624 		break;
15625 	case M_FLUSH:
15626 		if (*rptr & FLUSHR)
15627 			flushq(q, FLUSHDATA);
15628 		break;
15629 	default:
15630 		/* M_CTL will be directly sent to tcp_icmp_error() */
15631 		ASSERT(DB_TYPE(mp) != M_CTL);
15632 		break;
15633 	}
15634 	/*
15635 	 * Make sure we set this bit before sending the ACK for
15636 	 * bind. Otherwise accept could possibly run and free
15637 	 * this tcp struct.
15638 	 */
15639 	ASSERT(q != NULL);
15640 	putnext(q, mp);
15641 }
15642 
15643 /* ARGSUSED */
15644 static void
15645 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15646 {
15647 	conn_t	*connp = (conn_t *)arg;
15648 	tcp_t	*tcp = connp->conn_tcp;
15649 	queue_t	*q = tcp->tcp_rq;
15650 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15651 
15652 	ASSERT(!IPCL_IS_NONSTR(connp));
15653 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15654 	tcp->tcp_rsrv_mp = mp;
15655 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15656 
15657 	TCP_STAT(tcps, tcp_rsrv_calls);
15658 
15659 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15660 		return;
15661 	}
15662 
15663 	if (tcp->tcp_fused) {
15664 		tcp_fuse_backenable(tcp);
15665 		return;
15666 	}
15667 
15668 	if (canputnext(q)) {
15669 		/* Not flow-controlled, open rwnd */
15670 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
15671 
15672 		/*
15673 		 * Send back a window update immediately if TCP is above
15674 		 * ESTABLISHED state and the increase of the rcv window
15675 		 * that the other side knows is at least 1 MSS after flow
15676 		 * control is lifted.
15677 		 */
15678 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15679 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
15680 			tcp_xmit_ctl(NULL, tcp,
15681 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15682 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15683 		}
15684 	}
15685 }
15686 
15687 /*
15688  * The read side service routine is called mostly when we get back-enabled as a
15689  * result of flow control relief.  Since we don't actually queue anything in
15690  * TCP, we have no data to send out of here.  What we do is clear the receive
15691  * window, and send out a window update.
15692  */
15693 static void
15694 tcp_rsrv(queue_t *q)
15695 {
15696 	conn_t		*connp = Q_TO_CONN(q);
15697 	tcp_t		*tcp = connp->conn_tcp;
15698 	mblk_t		*mp;
15699 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15700 
15701 	/* No code does a putq on the read side */
15702 	ASSERT(q->q_first == NULL);
15703 
15704 	/* Nothing to do for the default queue */
15705 	if (q == tcps->tcps_g_q) {
15706 		return;
15707 	}
15708 
15709 	/*
15710 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15711 	 * been run.  So just return.
15712 	 */
15713 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15714 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15715 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15716 		return;
15717 	}
15718 	tcp->tcp_rsrv_mp = NULL;
15719 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15720 
15721 	CONN_INC_REF(connp);
15722 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15723 	    SQ_PROCESS, SQTAG_TCP_RSRV);
15724 }
15725 
15726 /*
15727  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15728  * We do not allow the receive window to shrink.  After setting rwnd,
15729  * set the flow control hiwat of the stream.
15730  *
15731  * This function is called in 2 cases:
15732  *
15733  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15734  *    connection (passive open) and in tcp_rput_data() for active connect.
15735  *    This is called after tcp_mss_set() when the desired MSS value is known.
15736  *    This makes sure that our window size is a mutiple of the other side's
15737  *    MSS.
15738  * 2) Handling SO_RCVBUF option.
15739  *
15740  * It is ASSUMED that the requested size is a multiple of the current MSS.
15741  *
15742  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15743  * user requests so.
15744  */
15745 int
15746 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15747 {
15748 	uint32_t	mss = tcp->tcp_mss;
15749 	uint32_t	old_max_rwnd;
15750 	uint32_t	max_transmittable_rwnd;
15751 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15752 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15753 
15754 	if (tcp->tcp_fused) {
15755 		size_t sth_hiwat;
15756 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15757 
15758 		ASSERT(peer_tcp != NULL);
15759 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15760 		if (!tcp_detached) {
15761 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15762 			    sth_hiwat);
15763 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
15764 		}
15765 
15766 		/*
15767 		 * In the fusion case, the maxpsz stream head value of
15768 		 * our peer is set according to its send buffer size
15769 		 * and our receive buffer size; since the latter may
15770 		 * have changed we need to update the peer's maxpsz.
15771 		 */
15772 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15773 		return (sth_hiwat);
15774 	}
15775 
15776 	if (tcp_detached) {
15777 		old_max_rwnd = tcp->tcp_rwnd;
15778 	} else {
15779 		old_max_rwnd = tcp->tcp_recv_hiwater;
15780 	}
15781 
15782 	/*
15783 	 * Insist on a receive window that is at least
15784 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15785 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15786 	 * and delayed acknowledgement.
15787 	 */
15788 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
15789 
15790 	/*
15791 	 * If window size info has already been exchanged, TCP should not
15792 	 * shrink the window.  Shrinking window is doable if done carefully.
15793 	 * We may add that support later.  But so far there is not a real
15794 	 * need to do that.
15795 	 */
15796 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15797 		/* MSS may have changed, do a round up again. */
15798 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15799 	}
15800 
15801 	/*
15802 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15803 	 * can be applied even before the window scale option is decided.
15804 	 */
15805 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15806 	if (rwnd > max_transmittable_rwnd) {
15807 		rwnd = max_transmittable_rwnd -
15808 		    (max_transmittable_rwnd % mss);
15809 		if (rwnd < mss)
15810 			rwnd = max_transmittable_rwnd;
15811 		/*
15812 		 * If we're over the limit we may have to back down tcp_rwnd.
15813 		 * The increment below won't work for us. So we set all three
15814 		 * here and the increment below will have no effect.
15815 		 */
15816 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15817 	}
15818 	if (tcp->tcp_localnet) {
15819 		tcp->tcp_rack_abs_max =
15820 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
15821 	} else {
15822 		/*
15823 		 * For a remote host on a different subnet (through a router),
15824 		 * we ack every other packet to be conforming to RFC1122.
15825 		 * tcp_deferred_acks_max is default to 2.
15826 		 */
15827 		tcp->tcp_rack_abs_max =
15828 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
15829 	}
15830 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15831 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15832 	else
15833 		tcp->tcp_rack_cur_max = 0;
15834 	/*
15835 	 * Increment the current rwnd by the amount the maximum grew (we
15836 	 * can not overwrite it since we might be in the middle of a
15837 	 * connection.)
15838 	 */
15839 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15840 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15841 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15842 		tcp->tcp_cwnd_max = rwnd;
15843 
15844 	if (tcp_detached)
15845 		return (rwnd);
15846 
15847 	tcp_set_recv_threshold(tcp, rwnd >> 3);
15848 
15849 	tcp->tcp_recv_hiwater = rwnd;
15850 
15851 	/*
15852 	 * Set the STREAM head high water mark. This doesn't have to be
15853 	 * here, since we are simply using default values, but we would
15854 	 * prefer to choose these values algorithmically, with a likely
15855 	 * relationship to rwnd.
15856 	 */
15857 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15858 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
15859 	return (rwnd);
15860 }
15861 
15862 /*
15863  * Return SNMP stuff in buffer in mpdata.
15864  */
15865 mblk_t *
15866 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15867 {
15868 	mblk_t			*mpdata;
15869 	mblk_t			*mp_conn_ctl = NULL;
15870 	mblk_t			*mp_conn_tail;
15871 	mblk_t			*mp_attr_ctl = NULL;
15872 	mblk_t			*mp_attr_tail;
15873 	mblk_t			*mp6_conn_ctl = NULL;
15874 	mblk_t			*mp6_conn_tail;
15875 	mblk_t			*mp6_attr_ctl = NULL;
15876 	mblk_t			*mp6_attr_tail;
15877 	struct opthdr		*optp;
15878 	mib2_tcpConnEntry_t	tce;
15879 	mib2_tcp6ConnEntry_t	tce6;
15880 	mib2_transportMLPEntry_t mlp;
15881 	connf_t			*connfp;
15882 	int			i;
15883 	boolean_t 		ispriv;
15884 	zoneid_t 		zoneid;
15885 	int			v4_conn_idx;
15886 	int			v6_conn_idx;
15887 	conn_t			*connp = Q_TO_CONN(q);
15888 	tcp_stack_t		*tcps;
15889 	ip_stack_t		*ipst;
15890 	mblk_t			*mp2ctl;
15891 
15892 	/*
15893 	 * make a copy of the original message
15894 	 */
15895 	mp2ctl = copymsg(mpctl);
15896 
15897 	if (mpctl == NULL ||
15898 	    (mpdata = mpctl->b_cont) == NULL ||
15899 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15900 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
15901 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
15902 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
15903 		freemsg(mp_conn_ctl);
15904 		freemsg(mp_attr_ctl);
15905 		freemsg(mp6_conn_ctl);
15906 		freemsg(mp6_attr_ctl);
15907 		freemsg(mpctl);
15908 		freemsg(mp2ctl);
15909 		return (NULL);
15910 	}
15911 
15912 	ipst = connp->conn_netstack->netstack_ip;
15913 	tcps = connp->conn_netstack->netstack_tcp;
15914 
15915 	/* build table of connections -- need count in fixed part */
15916 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
15917 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
15918 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
15919 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
15920 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
15921 
15922 	ispriv =
15923 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15924 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15925 
15926 	v4_conn_idx = v6_conn_idx = 0;
15927 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
15928 
15929 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15930 		ipst = tcps->tcps_netstack->netstack_ip;
15931 
15932 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
15933 
15934 		connp = NULL;
15935 
15936 		while ((connp =
15937 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15938 			tcp_t *tcp;
15939 			boolean_t needattr;
15940 
15941 			if (connp->conn_zoneid != zoneid)
15942 				continue;	/* not in this zone */
15943 
15944 			tcp = connp->conn_tcp;
15945 			UPDATE_MIB(&tcps->tcps_mib,
15946 			    tcpHCInSegs, tcp->tcp_ibsegs);
15947 			tcp->tcp_ibsegs = 0;
15948 			UPDATE_MIB(&tcps->tcps_mib,
15949 			    tcpHCOutSegs, tcp->tcp_obsegs);
15950 			tcp->tcp_obsegs = 0;
15951 
15952 			tce6.tcp6ConnState = tce.tcpConnState =
15953 			    tcp_snmp_state(tcp);
15954 			if (tce.tcpConnState == MIB2_TCP_established ||
15955 			    tce.tcpConnState == MIB2_TCP_closeWait)
15956 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
15957 
15958 			needattr = B_FALSE;
15959 			bzero(&mlp, sizeof (mlp));
15960 			if (connp->conn_mlp_type != mlptSingle) {
15961 				if (connp->conn_mlp_type == mlptShared ||
15962 				    connp->conn_mlp_type == mlptBoth)
15963 					mlp.tme_flags |= MIB2_TMEF_SHARED;
15964 				if (connp->conn_mlp_type == mlptPrivate ||
15965 				    connp->conn_mlp_type == mlptBoth)
15966 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
15967 				needattr = B_TRUE;
15968 			}
15969 			if (connp->conn_anon_mlp) {
15970 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
15971 				needattr = B_TRUE;
15972 			}
15973 			if (connp->conn_mac_exempt) {
15974 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
15975 				needattr = B_TRUE;
15976 			}
15977 			if (connp->conn_fully_bound &&
15978 			    connp->conn_effective_cred != NULL) {
15979 				ts_label_t *tsl;
15980 
15981 				tsl = crgetlabel(connp->conn_effective_cred);
15982 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
15983 				mlp.tme_doi = label2doi(tsl);
15984 				mlp.tme_label = *label2bslabel(tsl);
15985 				needattr = B_TRUE;
15986 			}
15987 
15988 			/* Create a message to report on IPv6 entries */
15989 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15990 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15991 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15992 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15993 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15994 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15995 			/* Don't want just anybody seeing these... */
15996 			if (ispriv) {
15997 				tce6.tcp6ConnEntryInfo.ce_snxt =
15998 				    tcp->tcp_snxt;
15999 				tce6.tcp6ConnEntryInfo.ce_suna =
16000 				    tcp->tcp_suna;
16001 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16002 				    tcp->tcp_rnxt;
16003 				tce6.tcp6ConnEntryInfo.ce_rack =
16004 				    tcp->tcp_rack;
16005 			} else {
16006 				/*
16007 				 * Netstat, unfortunately, uses this to
16008 				 * get send/receive queue sizes.  How to fix?
16009 				 * Why not compute the difference only?
16010 				 */
16011 				tce6.tcp6ConnEntryInfo.ce_snxt =
16012 				    tcp->tcp_snxt - tcp->tcp_suna;
16013 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16014 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16015 				    tcp->tcp_rnxt - tcp->tcp_rack;
16016 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16017 			}
16018 
16019 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16020 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16021 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16022 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16023 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16024 
16025 			tce6.tcp6ConnCreationProcess =
16026 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16027 			    tcp->tcp_cpid;
16028 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16029 
16030 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16031 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16032 
16033 			mlp.tme_connidx = v6_conn_idx++;
16034 			if (needattr)
16035 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16036 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16037 			}
16038 			/*
16039 			 * Create an IPv4 table entry for IPv4 entries and also
16040 			 * for IPv6 entries which are bound to in6addr_any
16041 			 * but don't have IPV6_V6ONLY set.
16042 			 * (i.e. anything an IPv4 peer could connect to)
16043 			 */
16044 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16045 			    (tcp->tcp_state <= TCPS_LISTEN &&
16046 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16047 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16048 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16049 					tce.tcpConnRemAddress = INADDR_ANY;
16050 					tce.tcpConnLocalAddress = INADDR_ANY;
16051 				} else {
16052 					tce.tcpConnRemAddress =
16053 					    tcp->tcp_remote;
16054 					tce.tcpConnLocalAddress =
16055 					    tcp->tcp_ip_src;
16056 				}
16057 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16058 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16059 				/* Don't want just anybody seeing these... */
16060 				if (ispriv) {
16061 					tce.tcpConnEntryInfo.ce_snxt =
16062 					    tcp->tcp_snxt;
16063 					tce.tcpConnEntryInfo.ce_suna =
16064 					    tcp->tcp_suna;
16065 					tce.tcpConnEntryInfo.ce_rnxt =
16066 					    tcp->tcp_rnxt;
16067 					tce.tcpConnEntryInfo.ce_rack =
16068 					    tcp->tcp_rack;
16069 				} else {
16070 					/*
16071 					 * Netstat, unfortunately, uses this to
16072 					 * get send/receive queue sizes.  How
16073 					 * to fix?
16074 					 * Why not compute the difference only?
16075 					 */
16076 					tce.tcpConnEntryInfo.ce_snxt =
16077 					    tcp->tcp_snxt - tcp->tcp_suna;
16078 					tce.tcpConnEntryInfo.ce_suna = 0;
16079 					tce.tcpConnEntryInfo.ce_rnxt =
16080 					    tcp->tcp_rnxt - tcp->tcp_rack;
16081 					tce.tcpConnEntryInfo.ce_rack = 0;
16082 				}
16083 
16084 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16085 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16086 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16087 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16088 				tce.tcpConnEntryInfo.ce_state =
16089 				    tcp->tcp_state;
16090 
16091 				tce.tcpConnCreationProcess =
16092 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16093 				    tcp->tcp_cpid;
16094 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16095 
16096 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16097 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16098 
16099 				mlp.tme_connidx = v4_conn_idx++;
16100 				if (needattr)
16101 					(void) snmp_append_data2(
16102 					    mp_attr_ctl->b_cont,
16103 					    &mp_attr_tail, (char *)&mlp,
16104 					    sizeof (mlp));
16105 			}
16106 		}
16107 	}
16108 
16109 	/* fixed length structure for IPv4 and IPv6 counters */
16110 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16111 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16112 	    sizeof (mib2_tcp6ConnEntry_t));
16113 	/* synchronize 32- and 64-bit counters */
16114 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16115 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16116 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16117 	optp->level = MIB2_TCP;
16118 	optp->name = 0;
16119 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16120 	    sizeof (tcps->tcps_mib));
16121 	optp->len = msgdsize(mpdata);
16122 	qreply(q, mpctl);
16123 
16124 	/* table of connections... */
16125 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16126 	    sizeof (struct T_optmgmt_ack)];
16127 	optp->level = MIB2_TCP;
16128 	optp->name = MIB2_TCP_CONN;
16129 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16130 	qreply(q, mp_conn_ctl);
16131 
16132 	/* table of MLP attributes... */
16133 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16134 	    sizeof (struct T_optmgmt_ack)];
16135 	optp->level = MIB2_TCP;
16136 	optp->name = EXPER_XPORT_MLP;
16137 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16138 	if (optp->len == 0)
16139 		freemsg(mp_attr_ctl);
16140 	else
16141 		qreply(q, mp_attr_ctl);
16142 
16143 	/* table of IPv6 connections... */
16144 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16145 	    sizeof (struct T_optmgmt_ack)];
16146 	optp->level = MIB2_TCP6;
16147 	optp->name = MIB2_TCP6_CONN;
16148 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16149 	qreply(q, mp6_conn_ctl);
16150 
16151 	/* table of IPv6 MLP attributes... */
16152 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16153 	    sizeof (struct T_optmgmt_ack)];
16154 	optp->level = MIB2_TCP6;
16155 	optp->name = EXPER_XPORT_MLP;
16156 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16157 	if (optp->len == 0)
16158 		freemsg(mp6_attr_ctl);
16159 	else
16160 		qreply(q, mp6_attr_ctl);
16161 	return (mp2ctl);
16162 }
16163 
16164 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16165 /* ARGSUSED */
16166 int
16167 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16168 {
16169 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16170 
16171 	switch (level) {
16172 	case MIB2_TCP:
16173 		switch (name) {
16174 		case 13:
16175 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16176 				return (0);
16177 			/* TODO: delete entry defined by tce */
16178 			return (1);
16179 		default:
16180 			return (0);
16181 		}
16182 	default:
16183 		return (1);
16184 	}
16185 }
16186 
16187 /* Translate TCP state to MIB2 TCP state. */
16188 static int
16189 tcp_snmp_state(tcp_t *tcp)
16190 {
16191 	if (tcp == NULL)
16192 		return (0);
16193 
16194 	switch (tcp->tcp_state) {
16195 	case TCPS_CLOSED:
16196 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16197 	case TCPS_BOUND:
16198 		return (MIB2_TCP_closed);
16199 	case TCPS_LISTEN:
16200 		return (MIB2_TCP_listen);
16201 	case TCPS_SYN_SENT:
16202 		return (MIB2_TCP_synSent);
16203 	case TCPS_SYN_RCVD:
16204 		return (MIB2_TCP_synReceived);
16205 	case TCPS_ESTABLISHED:
16206 		return (MIB2_TCP_established);
16207 	case TCPS_CLOSE_WAIT:
16208 		return (MIB2_TCP_closeWait);
16209 	case TCPS_FIN_WAIT_1:
16210 		return (MIB2_TCP_finWait1);
16211 	case TCPS_CLOSING:
16212 		return (MIB2_TCP_closing);
16213 	case TCPS_LAST_ACK:
16214 		return (MIB2_TCP_lastAck);
16215 	case TCPS_FIN_WAIT_2:
16216 		return (MIB2_TCP_finWait2);
16217 	case TCPS_TIME_WAIT:
16218 		return (MIB2_TCP_timeWait);
16219 	default:
16220 		return (0);
16221 	}
16222 }
16223 
16224 /*
16225  * tcp_timer is the timer service routine.  It handles the retransmission,
16226  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16227  * from the state of the tcp instance what kind of action needs to be done
16228  * at the time it is called.
16229  */
16230 static void
16231 tcp_timer(void *arg)
16232 {
16233 	mblk_t		*mp;
16234 	clock_t		first_threshold;
16235 	clock_t		second_threshold;
16236 	clock_t		ms;
16237 	uint32_t	mss;
16238 	conn_t		*connp = (conn_t *)arg;
16239 	tcp_t		*tcp = connp->conn_tcp;
16240 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16241 
16242 	tcp->tcp_timer_tid = 0;
16243 
16244 	if (tcp->tcp_fused)
16245 		return;
16246 
16247 	first_threshold =  tcp->tcp_first_timer_threshold;
16248 	second_threshold = tcp->tcp_second_timer_threshold;
16249 	switch (tcp->tcp_state) {
16250 	case TCPS_IDLE:
16251 	case TCPS_BOUND:
16252 	case TCPS_LISTEN:
16253 		return;
16254 	case TCPS_SYN_RCVD: {
16255 		tcp_t	*listener = tcp->tcp_listener;
16256 
16257 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16258 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16259 			/* it's our first timeout */
16260 			tcp->tcp_syn_rcvd_timeout = 1;
16261 			mutex_enter(&listener->tcp_eager_lock);
16262 			listener->tcp_syn_rcvd_timeout++;
16263 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16264 				/*
16265 				 * Make this eager available for drop if we
16266 				 * need to drop one to accomodate a new
16267 				 * incoming SYN request.
16268 				 */
16269 				MAKE_DROPPABLE(listener, tcp);
16270 			}
16271 			if (!listener->tcp_syn_defense &&
16272 			    (listener->tcp_syn_rcvd_timeout >
16273 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16274 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16275 				/* We may be under attack. Put on a defense. */
16276 				listener->tcp_syn_defense = B_TRUE;
16277 				cmn_err(CE_WARN, "High TCP connect timeout "
16278 				    "rate! System (port %d) may be under a "
16279 				    "SYN flood attack!",
16280 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16281 
16282 				listener->tcp_ip_addr_cache = kmem_zalloc(
16283 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16284 				    KM_NOSLEEP);
16285 			}
16286 			mutex_exit(&listener->tcp_eager_lock);
16287 		} else if (listener != NULL) {
16288 			mutex_enter(&listener->tcp_eager_lock);
16289 			tcp->tcp_syn_rcvd_timeout++;
16290 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16291 			    !tcp->tcp_closemp_used) {
16292 				/*
16293 				 * This is our second timeout. Put the tcp in
16294 				 * the list of droppable eagers to allow it to
16295 				 * be dropped, if needed. We don't check
16296 				 * whether tcp_dontdrop is set or not to
16297 				 * protect ourselve from a SYN attack where a
16298 				 * remote host can spoof itself as one of the
16299 				 * good IP source and continue to hold
16300 				 * resources too long.
16301 				 */
16302 				MAKE_DROPPABLE(listener, tcp);
16303 			}
16304 			mutex_exit(&listener->tcp_eager_lock);
16305 		}
16306 	}
16307 		/* FALLTHRU */
16308 	case TCPS_SYN_SENT:
16309 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16310 		second_threshold = tcp->tcp_second_ctimer_threshold;
16311 		break;
16312 	case TCPS_ESTABLISHED:
16313 	case TCPS_FIN_WAIT_1:
16314 	case TCPS_CLOSING:
16315 	case TCPS_CLOSE_WAIT:
16316 	case TCPS_LAST_ACK:
16317 		/* If we have data to rexmit */
16318 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16319 			clock_t	time_to_wait;
16320 
16321 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16322 			if (!tcp->tcp_xmit_head)
16323 				break;
16324 			time_to_wait = lbolt -
16325 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16326 			time_to_wait = tcp->tcp_rto -
16327 			    TICK_TO_MSEC(time_to_wait);
16328 			/*
16329 			 * If the timer fires too early, 1 clock tick earlier,
16330 			 * restart the timer.
16331 			 */
16332 			if (time_to_wait > msec_per_tick) {
16333 				TCP_STAT(tcps, tcp_timer_fire_early);
16334 				TCP_TIMER_RESTART(tcp, time_to_wait);
16335 				return;
16336 			}
16337 			/*
16338 			 * When we probe zero windows, we force the swnd open.
16339 			 * If our peer acks with a closed window swnd will be
16340 			 * set to zero by tcp_rput(). As long as we are
16341 			 * receiving acks tcp_rput will
16342 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16343 			 * first and second interval actions.  NOTE: the timer
16344 			 * interval is allowed to continue its exponential
16345 			 * backoff.
16346 			 */
16347 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16348 				if (tcp->tcp_debug) {
16349 					(void) strlog(TCP_MOD_ID, 0, 1,
16350 					    SL_TRACE, "tcp_timer: zero win");
16351 				}
16352 			} else {
16353 				/*
16354 				 * After retransmission, we need to do
16355 				 * slow start.  Set the ssthresh to one
16356 				 * half of current effective window and
16357 				 * cwnd to one MSS.  Also reset
16358 				 * tcp_cwnd_cnt.
16359 				 *
16360 				 * Note that if tcp_ssthresh is reduced because
16361 				 * of ECN, do not reduce it again unless it is
16362 				 * already one window of data away (tcp_cwr
16363 				 * should then be cleared) or this is a
16364 				 * timeout for a retransmitted segment.
16365 				 */
16366 				uint32_t npkt;
16367 
16368 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16369 					npkt = ((tcp->tcp_timer_backoff ?
16370 					    tcp->tcp_cwnd_ssthresh :
16371 					    tcp->tcp_snxt -
16372 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16373 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16374 					    tcp->tcp_mss;
16375 				}
16376 				tcp->tcp_cwnd = tcp->tcp_mss;
16377 				tcp->tcp_cwnd_cnt = 0;
16378 				if (tcp->tcp_ecn_ok) {
16379 					tcp->tcp_cwr = B_TRUE;
16380 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16381 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16382 				}
16383 			}
16384 			break;
16385 		}
16386 		/*
16387 		 * We have something to send yet we cannot send.  The
16388 		 * reason can be:
16389 		 *
16390 		 * 1. Zero send window: we need to do zero window probe.
16391 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16392 		 * segments.
16393 		 * 3. SWS avoidance: receiver may have shrunk window,
16394 		 * reset our knowledge.
16395 		 *
16396 		 * Note that condition 2 can happen with either 1 or
16397 		 * 3.  But 1 and 3 are exclusive.
16398 		 */
16399 		if (tcp->tcp_unsent != 0) {
16400 			if (tcp->tcp_cwnd == 0) {
16401 				/*
16402 				 * Set tcp_cwnd to 1 MSS so that a
16403 				 * new segment can be sent out.  We
16404 				 * are "clocking out" new data when
16405 				 * the network is really congested.
16406 				 */
16407 				ASSERT(tcp->tcp_ecn_ok);
16408 				tcp->tcp_cwnd = tcp->tcp_mss;
16409 			}
16410 			if (tcp->tcp_swnd == 0) {
16411 				/* Extend window for zero window probe */
16412 				tcp->tcp_swnd++;
16413 				tcp->tcp_zero_win_probe = B_TRUE;
16414 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
16415 			} else {
16416 				/*
16417 				 * Handle timeout from sender SWS avoidance.
16418 				 * Reset our knowledge of the max send window
16419 				 * since the receiver might have reduced its
16420 				 * receive buffer.  Avoid setting tcp_max_swnd
16421 				 * to one since that will essentially disable
16422 				 * the SWS checks.
16423 				 *
16424 				 * Note that since we don't have a SWS
16425 				 * state variable, if the timeout is set
16426 				 * for ECN but not for SWS, this
16427 				 * code will also be executed.  This is
16428 				 * fine as tcp_max_swnd is updated
16429 				 * constantly and it will not affect
16430 				 * anything.
16431 				 */
16432 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16433 			}
16434 			tcp_wput_data(tcp, NULL, B_FALSE);
16435 			return;
16436 		}
16437 		/* Is there a FIN that needs to be to re retransmitted? */
16438 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16439 		    !tcp->tcp_fin_acked)
16440 			break;
16441 		/* Nothing to do, return without restarting timer. */
16442 		TCP_STAT(tcps, tcp_timer_fire_miss);
16443 		return;
16444 	case TCPS_FIN_WAIT_2:
16445 		/*
16446 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16447 		 * We waited some time for for peer's FIN, but it hasn't
16448 		 * arrived.  We flush the connection now to avoid
16449 		 * case where the peer has rebooted.
16450 		 */
16451 		if (TCP_IS_DETACHED(tcp)) {
16452 			(void) tcp_clean_death(tcp, 0, 23);
16453 		} else {
16454 			TCP_TIMER_RESTART(tcp,
16455 			    tcps->tcps_fin_wait_2_flush_interval);
16456 		}
16457 		return;
16458 	case TCPS_TIME_WAIT:
16459 		(void) tcp_clean_death(tcp, 0, 24);
16460 		return;
16461 	default:
16462 		if (tcp->tcp_debug) {
16463 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16464 			    "tcp_timer: strange state (%d) %s",
16465 			    tcp->tcp_state, tcp_display(tcp, NULL,
16466 			    DISP_PORT_ONLY));
16467 		}
16468 		return;
16469 	}
16470 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16471 		/*
16472 		 * For zero window probe, we need to send indefinitely,
16473 		 * unless we have not heard from the other side for some
16474 		 * time...
16475 		 */
16476 		if ((tcp->tcp_zero_win_probe == 0) ||
16477 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16478 		    second_threshold)) {
16479 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
16480 			/*
16481 			 * If TCP is in SYN_RCVD state, send back a
16482 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16483 			 * should be zero in TCPS_SYN_RCVD state.
16484 			 */
16485 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16486 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16487 				    "in SYN_RCVD",
16488 				    tcp, tcp->tcp_snxt,
16489 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16490 			}
16491 			(void) tcp_clean_death(tcp,
16492 			    tcp->tcp_client_errno ?
16493 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16494 			return;
16495 		} else {
16496 			/*
16497 			 * Set tcp_ms_we_have_waited to second_threshold
16498 			 * so that in next timeout, we will do the above
16499 			 * check (lbolt - tcp_last_recv_time).  This is
16500 			 * also to avoid overflow.
16501 			 *
16502 			 * We don't need to decrement tcp_timer_backoff
16503 			 * to avoid overflow because it will be decremented
16504 			 * later if new timeout value is greater than
16505 			 * tcp_rexmit_interval_max.  In the case when
16506 			 * tcp_rexmit_interval_max is greater than
16507 			 * second_threshold, it means that we will wait
16508 			 * longer than second_threshold to send the next
16509 			 * window probe.
16510 			 */
16511 			tcp->tcp_ms_we_have_waited = second_threshold;
16512 		}
16513 	} else if (ms > first_threshold) {
16514 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16515 		    tcp->tcp_xmit_head != NULL) {
16516 			tcp->tcp_xmit_head =
16517 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16518 		}
16519 		/*
16520 		 * We have been retransmitting for too long...  The RTT
16521 		 * we calculated is probably incorrect.  Reinitialize it.
16522 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16523 		 * tcp_rtt_update so that we won't accidentally cache a
16524 		 * bad value.  But only do this if this is not a zero
16525 		 * window probe.
16526 		 */
16527 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16528 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16529 			    (tcp->tcp_rtt_sa >> 5);
16530 			tcp->tcp_rtt_sa = 0;
16531 			tcp_ip_notify(tcp);
16532 			tcp->tcp_rtt_update = 0;
16533 		}
16534 	}
16535 	tcp->tcp_timer_backoff++;
16536 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16537 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16538 	    tcps->tcps_rexmit_interval_min) {
16539 		/*
16540 		 * This means the original RTO is tcp_rexmit_interval_min.
16541 		 * So we will use tcp_rexmit_interval_min as the RTO value
16542 		 * and do the backoff.
16543 		 */
16544 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
16545 	} else {
16546 		ms <<= tcp->tcp_timer_backoff;
16547 	}
16548 	if (ms > tcps->tcps_rexmit_interval_max) {
16549 		ms = tcps->tcps_rexmit_interval_max;
16550 		/*
16551 		 * ms is at max, decrement tcp_timer_backoff to avoid
16552 		 * overflow.
16553 		 */
16554 		tcp->tcp_timer_backoff--;
16555 	}
16556 	tcp->tcp_ms_we_have_waited += ms;
16557 	if (tcp->tcp_zero_win_probe == 0) {
16558 		tcp->tcp_rto = ms;
16559 	}
16560 	TCP_TIMER_RESTART(tcp, ms);
16561 	/*
16562 	 * This is after a timeout and tcp_rto is backed off.  Set
16563 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16564 	 * restart the timer with a correct value.
16565 	 */
16566 	tcp->tcp_set_timer = 1;
16567 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16568 	if (mss > tcp->tcp_mss)
16569 		mss = tcp->tcp_mss;
16570 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16571 		mss = tcp->tcp_swnd;
16572 
16573 	if ((mp = tcp->tcp_xmit_head) != NULL)
16574 		mp->b_prev = (mblk_t *)lbolt;
16575 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16576 	    B_TRUE);
16577 
16578 	/*
16579 	 * When slow start after retransmission begins, start with
16580 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16581 	 * start phase.  tcp_snd_burst controls how many segments
16582 	 * can be sent because of an ack.
16583 	 */
16584 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16585 	tcp->tcp_snd_burst = TCP_CWND_SS;
16586 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16587 	    (tcp->tcp_unsent == 0)) {
16588 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16589 	} else {
16590 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16591 	}
16592 	tcp->tcp_rexmit = B_TRUE;
16593 	tcp->tcp_dupack_cnt = 0;
16594 
16595 	/*
16596 	 * Remove all rexmit SACK blk to start from fresh.
16597 	 */
16598 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
16599 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
16600 	if (mp == NULL) {
16601 		return;
16602 	}
16603 	/*
16604 	 * Attach credentials to retransmitted initial SYNs.
16605 	 * In theory we should use the credentials from the connect()
16606 	 * call to ensure that getpeerucred() on the peer will be correct.
16607 	 * But we assume that SYN's are not dropped for loopback connections.
16608 	 */
16609 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16610 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp), tcp->tcp_cpid);
16611 	}
16612 
16613 	tcp->tcp_csuna = tcp->tcp_snxt;
16614 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
16615 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
16616 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16617 
16618 }
16619 
16620 static int
16621 tcp_do_unbind(conn_t *connp)
16622 {
16623 	tcp_t *tcp = connp->conn_tcp;
16624 	int error = 0;
16625 
16626 	switch (tcp->tcp_state) {
16627 	case TCPS_BOUND:
16628 	case TCPS_LISTEN:
16629 		break;
16630 	default:
16631 		return (-TOUTSTATE);
16632 	}
16633 
16634 	/*
16635 	 * Need to clean up all the eagers since after the unbind, segments
16636 	 * will no longer be delivered to this listener stream.
16637 	 */
16638 	mutex_enter(&tcp->tcp_eager_lock);
16639 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16640 		tcp_eager_cleanup(tcp, 0);
16641 	}
16642 	mutex_exit(&tcp->tcp_eager_lock);
16643 
16644 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16645 		tcp->tcp_ipha->ipha_src = 0;
16646 	} else {
16647 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16648 	}
16649 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16650 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16651 	tcp_bind_hash_remove(tcp);
16652 	tcp->tcp_state = TCPS_IDLE;
16653 	tcp->tcp_mdt = B_FALSE;
16654 
16655 	connp = tcp->tcp_connp;
16656 	connp->conn_mdt_ok = B_FALSE;
16657 	ipcl_hash_remove(connp);
16658 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16659 
16660 	return (error);
16661 }
16662 
16663 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16664 static void
16665 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
16666 {
16667 	int error = tcp_do_unbind(tcp->tcp_connp);
16668 
16669 	if (error > 0) {
16670 		tcp_err_ack(tcp, mp, TSYSERR, error);
16671 	} else if (error < 0) {
16672 		tcp_err_ack(tcp, mp, -error, 0);
16673 	} else {
16674 		/* Send M_FLUSH according to TPI */
16675 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16676 
16677 		mp = mi_tpi_ok_ack_alloc(mp);
16678 		putnext(tcp->tcp_rq, mp);
16679 	}
16680 }
16681 
16682 /*
16683  * Don't let port fall into the privileged range.
16684  * Since the extra privileged ports can be arbitrary we also
16685  * ensure that we exclude those from consideration.
16686  * tcp_g_epriv_ports is not sorted thus we loop over it until
16687  * there are no changes.
16688  *
16689  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16690  * but instead the code relies on:
16691  * - the fact that the address of the array and its size never changes
16692  * - the atomic assignment of the elements of the array
16693  *
16694  * Returns 0 if there are no more ports available.
16695  *
16696  * TS note: skip multilevel ports.
16697  */
16698 static in_port_t
16699 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16700 {
16701 	int i;
16702 	boolean_t restart = B_FALSE;
16703 	tcp_stack_t *tcps = tcp->tcp_tcps;
16704 
16705 	if (random && tcp_random_anon_port != 0) {
16706 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16707 		    sizeof (in_port_t));
16708 		/*
16709 		 * Unless changed by a sys admin, the smallest anon port
16710 		 * is 32768 and the largest anon port is 65535.  It is
16711 		 * very likely (50%) for the random port to be smaller
16712 		 * than the smallest anon port.  When that happens,
16713 		 * add port % (anon port range) to the smallest anon
16714 		 * port to get the random port.  It should fall into the
16715 		 * valid anon port range.
16716 		 */
16717 		if (port < tcps->tcps_smallest_anon_port) {
16718 			port = tcps->tcps_smallest_anon_port +
16719 			    port % (tcps->tcps_largest_anon_port -
16720 			    tcps->tcps_smallest_anon_port);
16721 		}
16722 	}
16723 
16724 retry:
16725 	if (port < tcps->tcps_smallest_anon_port)
16726 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16727 
16728 	if (port > tcps->tcps_largest_anon_port) {
16729 		if (restart)
16730 			return (0);
16731 		restart = B_TRUE;
16732 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16733 	}
16734 
16735 	if (port < tcps->tcps_smallest_nonpriv_port)
16736 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
16737 
16738 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
16739 		if (port == tcps->tcps_g_epriv_ports[i]) {
16740 			port++;
16741 			/*
16742 			 * Make sure whether the port is in the
16743 			 * valid range.
16744 			 */
16745 			goto retry;
16746 		}
16747 	}
16748 	if (is_system_labeled() &&
16749 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
16750 	    IPPROTO_TCP, B_TRUE)) != 0) {
16751 		port = i;
16752 		goto retry;
16753 	}
16754 	return (port);
16755 }
16756 
16757 /*
16758  * Return the next anonymous port in the privileged port range for
16759  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16760  * downwards.  This is the same behavior as documented in the userland
16761  * library call rresvport(3N).
16762  *
16763  * TS note: skip multilevel ports.
16764  */
16765 static in_port_t
16766 tcp_get_next_priv_port(const tcp_t *tcp)
16767 {
16768 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16769 	in_port_t nextport;
16770 	boolean_t restart = B_FALSE;
16771 	tcp_stack_t *tcps = tcp->tcp_tcps;
16772 retry:
16773 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
16774 	    next_priv_port >= IPPORT_RESERVED) {
16775 		next_priv_port = IPPORT_RESERVED - 1;
16776 		if (restart)
16777 			return (0);
16778 		restart = B_TRUE;
16779 	}
16780 	if (is_system_labeled() &&
16781 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
16782 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
16783 		next_priv_port = nextport;
16784 		goto retry;
16785 	}
16786 	return (next_priv_port--);
16787 }
16788 
16789 /* The write side r/w procedure. */
16790 
16791 #if CCS_STATS
16792 struct {
16793 	struct {
16794 		int64_t count, bytes;
16795 	} tot, hit;
16796 } wrw_stats;
16797 #endif
16798 
16799 /*
16800  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16801  * messages.
16802  */
16803 /* ARGSUSED */
16804 static void
16805 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16806 {
16807 	conn_t	*connp = (conn_t *)arg;
16808 	tcp_t	*tcp = connp->conn_tcp;
16809 	queue_t	*q = tcp->tcp_wq;
16810 
16811 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16812 	/*
16813 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16814 	 * Once the close starts, streamhead and sockfs will not let any data
16815 	 * packets come down (close ensures that there are no threads using the
16816 	 * queue and no new threads will come down) but since qprocsoff()
16817 	 * hasn't happened yet, a M_FLUSH or some non data message might
16818 	 * get reflected back (in response to our own FLUSHRW) and get
16819 	 * processed after tcp_close() is done. The conn would still be valid
16820 	 * because a ref would have added but we need to check the state
16821 	 * before actually processing the packet.
16822 	 */
16823 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16824 		freemsg(mp);
16825 		return;
16826 	}
16827 
16828 	switch (DB_TYPE(mp)) {
16829 	case M_IOCDATA:
16830 		tcp_wput_iocdata(tcp, mp);
16831 		break;
16832 	case M_FLUSH:
16833 		tcp_wput_flush(tcp, mp);
16834 		break;
16835 	default:
16836 		CALL_IP_WPUT(connp, q, mp);
16837 		break;
16838 	}
16839 }
16840 
16841 /*
16842  * The TCP fast path write put procedure.
16843  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16844  */
16845 /* ARGSUSED */
16846 void
16847 tcp_output(void *arg, mblk_t *mp, void *arg2)
16848 {
16849 	int		len;
16850 	int		hdrlen;
16851 	int		plen;
16852 	mblk_t		*mp1;
16853 	uchar_t		*rptr;
16854 	uint32_t	snxt;
16855 	tcph_t		*tcph;
16856 	struct datab	*db;
16857 	uint32_t	suna;
16858 	uint32_t	mss;
16859 	ipaddr_t	*dst;
16860 	ipaddr_t	*src;
16861 	uint32_t	sum;
16862 	int		usable;
16863 	conn_t		*connp = (conn_t *)arg;
16864 	tcp_t		*tcp = connp->conn_tcp;
16865 	uint32_t	msize;
16866 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16867 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
16868 
16869 	/*
16870 	 * Try and ASSERT the minimum possible references on the
16871 	 * conn early enough. Since we are executing on write side,
16872 	 * the connection is obviously not detached and that means
16873 	 * there is a ref each for TCP and IP. Since we are behind
16874 	 * the squeue, the minimum references needed are 3. If the
16875 	 * conn is in classifier hash list, there should be an
16876 	 * extra ref for that (we check both the possibilities).
16877 	 */
16878 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16879 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16880 
16881 	ASSERT(DB_TYPE(mp) == M_DATA);
16882 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
16883 
16884 	mutex_enter(&tcp->tcp_non_sq_lock);
16885 	tcp->tcp_squeue_bytes -= msize;
16886 	mutex_exit(&tcp->tcp_non_sq_lock);
16887 
16888 	/* Check to see if this connection wants to be re-fused. */
16889 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
16890 		if (tcp->tcp_ipversion == IPV4_VERSION) {
16891 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
16892 			    &tcp->tcp_saved_tcph);
16893 		} else {
16894 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
16895 			    &tcp->tcp_saved_tcph);
16896 		}
16897 	}
16898 	/* Bypass tcp protocol for fused tcp loopback */
16899 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
16900 		return;
16901 
16902 	mss = tcp->tcp_mss;
16903 	if (tcp->tcp_xmit_zc_clean)
16904 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16905 
16906 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16907 	len = (int)(mp->b_wptr - mp->b_rptr);
16908 
16909 	/*
16910 	 * Criteria for fast path:
16911 	 *
16912 	 *   1. no unsent data
16913 	 *   2. single mblk in request
16914 	 *   3. connection established
16915 	 *   4. data in mblk
16916 	 *   5. len <= mss
16917 	 *   6. no tcp_valid bits
16918 	 */
16919 	if ((tcp->tcp_unsent != 0) ||
16920 	    (tcp->tcp_cork) ||
16921 	    (mp->b_cont != NULL) ||
16922 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16923 	    (len == 0) ||
16924 	    (len > mss) ||
16925 	    (tcp->tcp_valid_bits != 0)) {
16926 		tcp_wput_data(tcp, mp, B_FALSE);
16927 		return;
16928 	}
16929 
16930 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16931 	ASSERT(tcp->tcp_fin_sent == 0);
16932 
16933 	/* queue new packet onto retransmission queue */
16934 	if (tcp->tcp_xmit_head == NULL) {
16935 		tcp->tcp_xmit_head = mp;
16936 	} else {
16937 		tcp->tcp_xmit_last->b_cont = mp;
16938 	}
16939 	tcp->tcp_xmit_last = mp;
16940 	tcp->tcp_xmit_tail = mp;
16941 
16942 	/* find out how much we can send */
16943 	/* BEGIN CSTYLED */
16944 	/*
16945 	 *    un-acked	   usable
16946 	 *  |--------------|-----------------|
16947 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
16948 	 */
16949 	/* END CSTYLED */
16950 
16951 	/* start sending from tcp_snxt */
16952 	snxt = tcp->tcp_snxt;
16953 
16954 	/*
16955 	 * Check to see if this connection has been idled for some
16956 	 * time and no ACK is expected.  If it is, we need to slow
16957 	 * start again to get back the connection's "self-clock" as
16958 	 * described in VJ's paper.
16959 	 *
16960 	 * Refer to the comment in tcp_mss_set() for the calculation
16961 	 * of tcp_cwnd after idle.
16962 	 */
16963 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16964 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16965 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
16966 	}
16967 
16968 	usable = tcp->tcp_swnd;		/* tcp window size */
16969 	if (usable > tcp->tcp_cwnd)
16970 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16971 	usable -= snxt;		/* subtract stuff already sent */
16972 	suna = tcp->tcp_suna;
16973 	usable += suna;
16974 	/* usable can be < 0 if the congestion window is smaller */
16975 	if (len > usable) {
16976 		/* Can't send complete M_DATA in one shot */
16977 		goto slow;
16978 	}
16979 
16980 	mutex_enter(&tcp->tcp_non_sq_lock);
16981 	if (tcp->tcp_flow_stopped &&
16982 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16983 		tcp_clrqfull(tcp);
16984 	}
16985 	mutex_exit(&tcp->tcp_non_sq_lock);
16986 
16987 	/*
16988 	 * determine if anything to send (Nagle).
16989 	 *
16990 	 *   1. len < tcp_mss (i.e. small)
16991 	 *   2. unacknowledged data present
16992 	 *   3. len < nagle limit
16993 	 *   4. last packet sent < nagle limit (previous packet sent)
16994 	 */
16995 	if ((len < mss) && (snxt != suna) &&
16996 	    (len < (int)tcp->tcp_naglim) &&
16997 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
16998 		/*
16999 		 * This was the first unsent packet and normally
17000 		 * mss < xmit_hiwater so there is no need to worry
17001 		 * about flow control. The next packet will go
17002 		 * through the flow control check in tcp_wput_data().
17003 		 */
17004 		/* leftover work from above */
17005 		tcp->tcp_unsent = len;
17006 		tcp->tcp_xmit_tail_unsent = len;
17007 
17008 		return;
17009 	}
17010 
17011 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17012 
17013 	if (snxt == suna) {
17014 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17015 	}
17016 
17017 	/* we have always sent something */
17018 	tcp->tcp_rack_cnt = 0;
17019 
17020 	tcp->tcp_snxt = snxt + len;
17021 	tcp->tcp_rack = tcp->tcp_rnxt;
17022 
17023 	if ((mp1 = dupb(mp)) == 0)
17024 		goto no_memory;
17025 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17026 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17027 
17028 	/* adjust tcp header information */
17029 	tcph = tcp->tcp_tcph;
17030 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17031 
17032 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17033 	sum = (sum >> 16) + (sum & 0xFFFF);
17034 	U16_TO_ABE16(sum, tcph->th_sum);
17035 
17036 	U32_TO_ABE32(snxt, tcph->th_seq);
17037 
17038 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17039 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17040 	BUMP_LOCAL(tcp->tcp_obsegs);
17041 
17042 	/* Update the latest receive window size in TCP header. */
17043 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17044 	    tcph->th_win);
17045 
17046 	tcp->tcp_last_sent_len = (ushort_t)len;
17047 
17048 	plen = len + tcp->tcp_hdr_len;
17049 
17050 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17051 		tcp->tcp_ipha->ipha_length = htons(plen);
17052 	} else {
17053 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17054 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17055 	}
17056 
17057 	/* see if we need to allocate a mblk for the headers */
17058 	hdrlen = tcp->tcp_hdr_len;
17059 	rptr = mp1->b_rptr - hdrlen;
17060 	db = mp1->b_datap;
17061 	if ((db->db_ref != 2) || rptr < db->db_base ||
17062 	    (!OK_32PTR(rptr))) {
17063 		/* NOTE: we assume allocb returns an OK_32PTR */
17064 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17065 		    tcps->tcps_wroff_xtra, BPRI_MED);
17066 		if (!mp) {
17067 			freemsg(mp1);
17068 			goto no_memory;
17069 		}
17070 		mp->b_cont = mp1;
17071 		mp1 = mp;
17072 		/* Leave room for Link Level header */
17073 		/* hdrlen = tcp->tcp_hdr_len; */
17074 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17075 		mp1->b_wptr = &rptr[hdrlen];
17076 	}
17077 	mp1->b_rptr = rptr;
17078 
17079 	/* Fill in the timestamp option. */
17080 	if (tcp->tcp_snd_ts_ok) {
17081 		U32_TO_BE32((uint32_t)lbolt,
17082 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17083 		U32_TO_BE32(tcp->tcp_ts_recent,
17084 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17085 	} else {
17086 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17087 	}
17088 
17089 	/* copy header into outgoing packet */
17090 	dst = (ipaddr_t *)rptr;
17091 	src = (ipaddr_t *)tcp->tcp_iphc;
17092 	dst[0] = src[0];
17093 	dst[1] = src[1];
17094 	dst[2] = src[2];
17095 	dst[3] = src[3];
17096 	dst[4] = src[4];
17097 	dst[5] = src[5];
17098 	dst[6] = src[6];
17099 	dst[7] = src[7];
17100 	dst[8] = src[8];
17101 	dst[9] = src[9];
17102 	if (hdrlen -= 40) {
17103 		hdrlen >>= 2;
17104 		dst += 10;
17105 		src += 10;
17106 		do {
17107 			*dst++ = *src++;
17108 		} while (--hdrlen);
17109 	}
17110 
17111 	/*
17112 	 * Set the ECN info in the TCP header.  Note that this
17113 	 * is not the template header.
17114 	 */
17115 	if (tcp->tcp_ecn_ok) {
17116 		SET_ECT(tcp, rptr);
17117 
17118 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17119 		if (tcp->tcp_ecn_echo_on)
17120 			tcph->th_flags[0] |= TH_ECE;
17121 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17122 			tcph->th_flags[0] |= TH_CWR;
17123 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17124 		}
17125 	}
17126 
17127 	if (tcp->tcp_ip_forward_progress) {
17128 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17129 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17130 		tcp->tcp_ip_forward_progress = B_FALSE;
17131 	}
17132 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17133 	return;
17134 
17135 	/*
17136 	 * If we ran out of memory, we pretend to have sent the packet
17137 	 * and that it was lost on the wire.
17138 	 */
17139 no_memory:
17140 	return;
17141 
17142 slow:
17143 	/* leftover work from above */
17144 	tcp->tcp_unsent = len;
17145 	tcp->tcp_xmit_tail_unsent = len;
17146 	tcp_wput_data(tcp, NULL, B_FALSE);
17147 }
17148 
17149 /* ARGSUSED */
17150 void
17151 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17152 {
17153 	conn_t			*connp = (conn_t *)arg;
17154 	tcp_t			*tcp = connp->conn_tcp;
17155 	queue_t			*q = tcp->tcp_rq;
17156 	struct tcp_options	*tcpopt;
17157 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17158 
17159 	/* socket options */
17160 	uint_t 			sopp_flags;
17161 	ssize_t			sopp_rxhiwat;
17162 	ssize_t			sopp_maxblk;
17163 	ushort_t		sopp_wroff;
17164 	ushort_t		sopp_tail;
17165 	ushort_t		sopp_copyopt;
17166 
17167 	tcpopt = (struct tcp_options *)mp->b_rptr;
17168 
17169 	/*
17170 	 * Drop the eager's ref on the listener, that was placed when
17171 	 * this eager began life in tcp_conn_request.
17172 	 */
17173 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17174 	if (IPCL_IS_NONSTR(connp)) {
17175 		/* Safe to free conn_ind message */
17176 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17177 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17178 	}
17179 
17180 	tcp->tcp_detached = B_FALSE;
17181 
17182 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17183 		/*
17184 		 * Someone blewoff the eager before we could finish
17185 		 * the accept.
17186 		 *
17187 		 * The only reason eager exists it because we put in
17188 		 * a ref on it when conn ind went up. We need to send
17189 		 * a disconnect indication up while the last reference
17190 		 * on the eager will be dropped by the squeue when we
17191 		 * return.
17192 		 */
17193 		ASSERT(tcp->tcp_listener == NULL);
17194 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17195 			if (IPCL_IS_NONSTR(connp)) {
17196 				ASSERT(tcp->tcp_issocket);
17197 				(*connp->conn_upcalls->su_disconnected)(
17198 				    connp->conn_upper_handle, tcp->tcp_connid,
17199 				    ECONNREFUSED);
17200 				freemsg(mp);
17201 			} else {
17202 				struct	T_discon_ind	*tdi;
17203 
17204 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17205 				/*
17206 				 * Let us reuse the incoming mblk to avoid
17207 				 * memory allocation failure problems. We know
17208 				 * that the size of the incoming mblk i.e.
17209 				 * stroptions is greater than sizeof
17210 				 * T_discon_ind. So the reallocb below can't
17211 				 * fail.
17212 				 */
17213 				freemsg(mp->b_cont);
17214 				mp->b_cont = NULL;
17215 				ASSERT(DB_REF(mp) == 1);
17216 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17217 				    B_FALSE);
17218 				ASSERT(mp != NULL);
17219 				DB_TYPE(mp) = M_PROTO;
17220 				((union T_primitives *)mp->b_rptr)->type =
17221 				    T_DISCON_IND;
17222 				tdi = (struct T_discon_ind *)mp->b_rptr;
17223 				if (tcp->tcp_issocket) {
17224 					tdi->DISCON_reason = ECONNREFUSED;
17225 					tdi->SEQ_number = 0;
17226 				} else {
17227 					tdi->DISCON_reason = ENOPROTOOPT;
17228 					tdi->SEQ_number =
17229 					    tcp->tcp_conn_req_seqnum;
17230 				}
17231 				mp->b_wptr = mp->b_rptr +
17232 				    sizeof (struct T_discon_ind);
17233 				putnext(q, mp);
17234 				return;
17235 			}
17236 		}
17237 		if (tcp->tcp_hard_binding) {
17238 			tcp->tcp_hard_binding = B_FALSE;
17239 			tcp->tcp_hard_bound = B_TRUE;
17240 		}
17241 		return;
17242 	}
17243 
17244 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17245 		int boundif = tcpopt->to_boundif;
17246 		uint_t len = sizeof (int);
17247 
17248 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17249 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17250 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17251 	}
17252 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17253 		uint_t on = 1;
17254 		uint_t len = sizeof (uint_t);
17255 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17256 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17257 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17258 	}
17259 
17260 	/*
17261 	 * Set max window size (tcp_recv_hiwater) of the acceptor.
17262 	 */
17263 	if (tcp->tcp_rcv_list == NULL) {
17264 		/*
17265 		 * Recv queue is empty, tcp_rwnd should not have changed.
17266 		 * That means it should be equal to the listener's tcp_rwnd.
17267 		 */
17268 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17269 	} else {
17270 #ifdef DEBUG
17271 		mblk_t *tmp;
17272 		mblk_t	*mp1;
17273 		uint_t	cnt = 0;
17274 
17275 		mp1 = tcp->tcp_rcv_list;
17276 		while ((tmp = mp1) != NULL) {
17277 			mp1 = tmp->b_next;
17278 			cnt += msgdsize(tmp);
17279 		}
17280 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17281 #endif
17282 		/* There is some data, add them back to get the max. */
17283 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17284 	}
17285 	/*
17286 	 * This is the first time we run on the correct
17287 	 * queue after tcp_accept. So fix all the q parameters
17288 	 * here.
17289 	 */
17290 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17291 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17292 
17293 	sopp_rxhiwat = tcp->tcp_fused ?
17294 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17295 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
17296 
17297 	/*
17298 	 * Determine what write offset value to use depending on SACK and
17299 	 * whether the endpoint is fused or not.
17300 	 */
17301 	if (tcp->tcp_fused) {
17302 		ASSERT(tcp->tcp_loopback);
17303 		ASSERT(tcp->tcp_loopback_peer != NULL);
17304 		/*
17305 		 * For fused tcp loopback, set the stream head's write
17306 		 * offset value to zero since we won't be needing any room
17307 		 * for TCP/IP headers.  This would also improve performance
17308 		 * since it would reduce the amount of work done by kmem.
17309 		 * Non-fused tcp loopback case is handled separately below.
17310 		 */
17311 		sopp_wroff = 0;
17312 		/*
17313 		 * Update the peer's transmit parameters according to
17314 		 * our recently calculated high water mark value.
17315 		 */
17316 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17317 	} else if (tcp->tcp_snd_sack_ok) {
17318 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17319 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17320 	} else {
17321 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17322 		    tcps->tcps_wroff_xtra);
17323 	}
17324 
17325 	/*
17326 	 * If this is endpoint is handling SSL, then reserve extra
17327 	 * offset and space at the end.
17328 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17329 	 * overriding the previous setting. The extra cost of signing and
17330 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17331 	 * instead of a single contiguous one by the stream head
17332 	 * largely outweighs the statistical reduction of ACKs, when
17333 	 * applicable. The peer will also save on decryption and verification
17334 	 * costs.
17335 	 */
17336 	if (tcp->tcp_kssl_ctx != NULL) {
17337 		sopp_wroff += SSL3_WROFFSET;
17338 
17339 		sopp_flags |= SOCKOPT_TAIL;
17340 		sopp_tail = SSL3_MAX_TAIL_LEN;
17341 
17342 		sopp_flags |= SOCKOPT_ZCOPY;
17343 		sopp_copyopt = ZCVMUNSAFE;
17344 
17345 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
17346 	}
17347 
17348 	/* Send the options up */
17349 	if (IPCL_IS_NONSTR(connp)) {
17350 		struct sock_proto_props sopp;
17351 
17352 		sopp.sopp_flags = sopp_flags;
17353 		sopp.sopp_wroff = sopp_wroff;
17354 		sopp.sopp_maxblk = sopp_maxblk;
17355 		sopp.sopp_rxhiwat = sopp_rxhiwat;
17356 		if (sopp_flags & SOCKOPT_TAIL) {
17357 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17358 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
17359 			sopp.sopp_tail = sopp_tail;
17360 			sopp.sopp_zcopyflag = sopp_copyopt;
17361 		}
17362 		if (tcp->tcp_loopback) {
17363 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
17364 			sopp.sopp_loopback = B_TRUE;
17365 		}
17366 		(*connp->conn_upcalls->su_set_proto_props)
17367 		    (connp->conn_upper_handle, &sopp);
17368 	} else {
17369 		struct stroptions *stropt;
17370 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17371 		if (stropt_mp == NULL) {
17372 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
17373 			return;
17374 		}
17375 		DB_TYPE(stropt_mp) = M_SETOPTS;
17376 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17377 		stropt_mp->b_wptr += sizeof (struct stroptions);
17378 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
17379 		stropt->so_hiwat = sopp_rxhiwat;
17380 		stropt->so_wroff = sopp_wroff;
17381 		stropt->so_maxblk = sopp_maxblk;
17382 
17383 		if (sopp_flags & SOCKOPT_TAIL) {
17384 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17385 
17386 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
17387 			stropt->so_tail = sopp_tail;
17388 			stropt->so_copyopt = sopp_copyopt;
17389 		}
17390 
17391 		/* Send the options up */
17392 		putnext(q, stropt_mp);
17393 	}
17394 
17395 	freemsg(mp);
17396 	/*
17397 	 * Pass up any data and/or a fin that has been received.
17398 	 *
17399 	 * Adjust receive window in case it had decreased
17400 	 * (because there is data <=> tcp_rcv_list != NULL)
17401 	 * while the connection was detached. Note that
17402 	 * in case the eager was flow-controlled, w/o this
17403 	 * code, the rwnd may never open up again!
17404 	 */
17405 	if (tcp->tcp_rcv_list != NULL) {
17406 		if (IPCL_IS_NONSTR(connp)) {
17407 			mblk_t *mp;
17408 			int space_left;
17409 			int error;
17410 			boolean_t push = B_TRUE;
17411 
17412 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
17413 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
17414 			    &push) >= 0) {
17415 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17416 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17417 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17418 					tcp_xmit_ctl(NULL,
17419 					    tcp, (tcp->tcp_swnd == 0) ?
17420 					    tcp->tcp_suna : tcp->tcp_snxt,
17421 					    tcp->tcp_rnxt, TH_ACK);
17422 				}
17423 			}
17424 			while ((mp = tcp->tcp_rcv_list) != NULL) {
17425 				push = B_TRUE;
17426 				tcp->tcp_rcv_list = mp->b_next;
17427 				mp->b_next = NULL;
17428 				space_left = (*connp->conn_upcalls->su_recv)
17429 				    (connp->conn_upper_handle, mp, msgdsize(mp),
17430 				    0, &error, &push);
17431 				if (space_left < 0) {
17432 					/*
17433 					 * We should never be in middle of a
17434 					 * fallback, the squeue guarantees that.
17435 					 */
17436 					ASSERT(error != EOPNOTSUPP);
17437 				}
17438 			}
17439 			tcp->tcp_rcv_last_head = NULL;
17440 			tcp->tcp_rcv_last_tail = NULL;
17441 			tcp->tcp_rcv_cnt = 0;
17442 		} else {
17443 			/* We drain directly in case of fused tcp loopback */
17444 
17445 			if (!tcp->tcp_fused && canputnext(q)) {
17446 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17447 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17448 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17449 					tcp_xmit_ctl(NULL,
17450 					    tcp, (tcp->tcp_swnd == 0) ?
17451 					    tcp->tcp_suna : tcp->tcp_snxt,
17452 					    tcp->tcp_rnxt, TH_ACK);
17453 				}
17454 			}
17455 
17456 			(void) tcp_rcv_drain(tcp);
17457 		}
17458 
17459 		/*
17460 		 * For fused tcp loopback, back-enable peer endpoint
17461 		 * if it's currently flow-controlled.
17462 		 */
17463 		if (tcp->tcp_fused) {
17464 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17465 
17466 			ASSERT(peer_tcp != NULL);
17467 			ASSERT(peer_tcp->tcp_fused);
17468 
17469 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
17470 			if (peer_tcp->tcp_flow_stopped) {
17471 				tcp_clrqfull(peer_tcp);
17472 				TCP_STAT(tcps, tcp_fusion_backenabled);
17473 			}
17474 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17475 		}
17476 	}
17477 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17478 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17479 		tcp->tcp_ordrel_done = B_TRUE;
17480 		if (IPCL_IS_NONSTR(connp)) {
17481 			ASSERT(tcp->tcp_ordrel_mp == NULL);
17482 			(*connp->conn_upcalls->su_opctl)(
17483 			    connp->conn_upper_handle,
17484 			    SOCK_OPCTL_SHUT_RECV, 0);
17485 		} else {
17486 			mp = tcp->tcp_ordrel_mp;
17487 			tcp->tcp_ordrel_mp = NULL;
17488 			putnext(q, mp);
17489 		}
17490 	}
17491 	if (tcp->tcp_hard_binding) {
17492 		tcp->tcp_hard_binding = B_FALSE;
17493 		tcp->tcp_hard_bound = B_TRUE;
17494 	}
17495 
17496 	if (tcp->tcp_ka_enabled) {
17497 		tcp->tcp_ka_last_intrvl = 0;
17498 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17499 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17500 	}
17501 
17502 	/*
17503 	 * At this point, eager is fully established and will
17504 	 * have the following references -
17505 	 *
17506 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17507 	 * 1 reference for the squeue which will be dropped by the squeue as
17508 	 *	soon as this function returns.
17509 	 * There will be 1 additonal reference for being in classifier
17510 	 *	hash list provided something bad hasn't happened.
17511 	 */
17512 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17513 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17514 }
17515 
17516 /*
17517  * The function called through squeue to get behind listener's perimeter to
17518  * send a deffered conn_ind.
17519  */
17520 /* ARGSUSED */
17521 void
17522 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17523 {
17524 	conn_t	*connp = (conn_t *)arg;
17525 	tcp_t *listener = connp->conn_tcp;
17526 	struct T_conn_ind *conn_ind;
17527 	tcp_t *tcp;
17528 
17529 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
17530 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17531 	    conn_ind->OPT_length);
17532 
17533 	if (listener->tcp_state != TCPS_LISTEN) {
17534 		/*
17535 		 * If listener has closed, it would have caused a
17536 		 * a cleanup/blowoff to happen for the eager, so
17537 		 * we don't need to do anything more.
17538 		 */
17539 		freemsg(mp);
17540 		return;
17541 	}
17542 
17543 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
17544 }
17545 
17546 /* ARGSUSED */
17547 static int
17548 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
17549 {
17550 	tcp_t *listener, *eager;
17551 	mblk_t *opt_mp;
17552 	struct tcp_options *tcpopt;
17553 
17554 	listener = lconnp->conn_tcp;
17555 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17556 	eager = econnp->conn_tcp;
17557 	ASSERT(eager->tcp_listener != NULL);
17558 
17559 	ASSERT(eager->tcp_rq != NULL);
17560 
17561 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
17562 	if (opt_mp == NULL) {
17563 		return (-TPROTO);
17564 	}
17565 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
17566 	eager->tcp_issocket = B_TRUE;
17567 
17568 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17569 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17570 	ASSERT(econnp->conn_netstack ==
17571 	    listener->tcp_connp->conn_netstack);
17572 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
17573 
17574 	/* Put the ref for IP */
17575 	CONN_INC_REF(econnp);
17576 
17577 	/*
17578 	 * We should have minimum of 3 references on the conn
17579 	 * at this point. One each for TCP and IP and one for
17580 	 * the T_conn_ind that was sent up when the 3-way handshake
17581 	 * completed. In the normal case we would also have another
17582 	 * reference (making a total of 4) for the conn being in the
17583 	 * classifier hash list. However the eager could have received
17584 	 * an RST subsequently and tcp_closei_local could have removed
17585 	 * the eager from the classifier hash list, hence we can't
17586 	 * assert that reference.
17587 	 */
17588 	ASSERT(econnp->conn_ref >= 3);
17589 
17590 	opt_mp->b_datap->db_type = M_SETOPTS;
17591 	opt_mp->b_wptr += sizeof (struct tcp_options);
17592 
17593 	/*
17594 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17595 	 * from listener to acceptor.
17596 	 */
17597 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
17598 	tcpopt->to_flags = 0;
17599 
17600 	if (listener->tcp_bound_if != 0) {
17601 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
17602 		tcpopt->to_boundif = listener->tcp_bound_if;
17603 	}
17604 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17605 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
17606 	}
17607 
17608 	mutex_enter(&listener->tcp_eager_lock);
17609 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17610 
17611 		tcp_t *tail;
17612 		tcp_t *tcp;
17613 		mblk_t *mp1;
17614 
17615 		tcp = listener->tcp_eager_prev_q0;
17616 		/*
17617 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
17618 		 * deferred T_conn_ind queue. We need to get to the head
17619 		 * of the queue in order to send up T_conn_ind the same
17620 		 * order as how the 3WHS is completed.
17621 		 */
17622 		while (tcp != listener) {
17623 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17624 			    !tcp->tcp_kssl_pending)
17625 				break;
17626 			else
17627 				tcp = tcp->tcp_eager_prev_q0;
17628 		}
17629 		/* None of the pending eagers can be sent up now */
17630 		if (tcp == listener)
17631 			goto no_more_eagers;
17632 
17633 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17634 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17635 		/* Move from q0 to q */
17636 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17637 		listener->tcp_conn_req_cnt_q0--;
17638 		listener->tcp_conn_req_cnt_q++;
17639 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17640 		    tcp->tcp_eager_prev_q0;
17641 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17642 		    tcp->tcp_eager_next_q0;
17643 		tcp->tcp_eager_prev_q0 = NULL;
17644 		tcp->tcp_eager_next_q0 = NULL;
17645 		tcp->tcp_conn_def_q0 = B_FALSE;
17646 
17647 		/* Make sure the tcp isn't in the list of droppables */
17648 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
17649 		    tcp->tcp_eager_prev_drop_q0 == NULL);
17650 
17651 		/*
17652 		 * Insert at end of the queue because sockfs sends
17653 		 * down T_CONN_RES in chronological order. Leaving
17654 		 * the older conn indications at front of the queue
17655 		 * helps reducing search time.
17656 		 */
17657 		tail = listener->tcp_eager_last_q;
17658 		if (tail != NULL) {
17659 			tail->tcp_eager_next_q = tcp;
17660 		} else {
17661 			listener->tcp_eager_next_q = tcp;
17662 		}
17663 		listener->tcp_eager_last_q = tcp;
17664 		tcp->tcp_eager_next_q = NULL;
17665 
17666 		/* Need to get inside the listener perimeter */
17667 		CONN_INC_REF(listener->tcp_connp);
17668 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
17669 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
17670 		    SQTAG_TCP_SEND_PENDING);
17671 	}
17672 no_more_eagers:
17673 	tcp_eager_unlink(eager);
17674 	mutex_exit(&listener->tcp_eager_lock);
17675 
17676 	/*
17677 	 * At this point, the eager is detached from the listener
17678 	 * but we still have an extra refs on eager (apart from the
17679 	 * usual tcp references). The ref was placed in tcp_rput_data
17680 	 * before sending the conn_ind in tcp_send_conn_ind.
17681 	 * The ref will be dropped in tcp_accept_finish().
17682 	 */
17683 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
17684 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
17685 	return (0);
17686 }
17687 
17688 int
17689 tcp_accept(sock_lower_handle_t lproto_handle,
17690     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
17691     cred_t *cr)
17692 {
17693 	conn_t *lconnp, *econnp;
17694 	tcp_t *listener, *eager;
17695 	tcp_stack_t	*tcps;
17696 
17697 	lconnp = (conn_t *)lproto_handle;
17698 	listener = lconnp->conn_tcp;
17699 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17700 	econnp = (conn_t *)eproto_handle;
17701 	eager = econnp->conn_tcp;
17702 	ASSERT(eager->tcp_listener != NULL);
17703 	tcps = eager->tcp_tcps;
17704 
17705 	/*
17706 	 * It is OK to manipulate these fields outside the eager's squeue
17707 	 * because they will not start being used until tcp_accept_finish
17708 	 * has been called.
17709 	 */
17710 	ASSERT(lconnp->conn_upper_handle != NULL);
17711 	ASSERT(econnp->conn_upper_handle == NULL);
17712 	econnp->conn_upper_handle = sock_handle;
17713 	econnp->conn_upcalls = lconnp->conn_upcalls;
17714 	ASSERT(IPCL_IS_NONSTR(econnp));
17715 	/*
17716 	 * Create helper stream if it is a non-TPI TCP connection.
17717 	 */
17718 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
17719 		ip1dbg(("tcp_accept: create of IP helper stream"
17720 		    " failed\n"));
17721 		return (EPROTO);
17722 	}
17723 	eager->tcp_rq = econnp->conn_rq;
17724 	eager->tcp_wq = econnp->conn_wq;
17725 
17726 	ASSERT(eager->tcp_rq != NULL);
17727 
17728 	return (tcp_accept_common(lconnp, econnp, cr));
17729 }
17730 
17731 
17732 /*
17733  * This is the STREAMS entry point for T_CONN_RES coming down on
17734  * Acceptor STREAM when  sockfs listener does accept processing.
17735  * Read the block comment on top of tcp_conn_request().
17736  */
17737 void
17738 tcp_tpi_accept(queue_t *q, mblk_t *mp)
17739 {
17740 	queue_t *rq = RD(q);
17741 	struct T_conn_res *conn_res;
17742 	tcp_t *eager;
17743 	tcp_t *listener;
17744 	struct T_ok_ack *ok;
17745 	t_scalar_t PRIM_type;
17746 	conn_t *econnp;
17747 	cred_t *cr;
17748 
17749 	ASSERT(DB_TYPE(mp) == M_PROTO);
17750 
17751 	/*
17752 	 * All Solaris components should pass a db_credp
17753 	 * for this TPI message, hence we ASSERT.
17754 	 * But in case there is some other M_PROTO that looks
17755 	 * like a TPI message sent by some other kernel
17756 	 * component, we check and return an error.
17757 	 */
17758 	cr = msg_getcred(mp, NULL);
17759 	ASSERT(cr != NULL);
17760 	if (cr == NULL) {
17761 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
17762 		if (mp != NULL)
17763 			putnext(rq, mp);
17764 		return;
17765 	}
17766 	conn_res = (struct T_conn_res *)mp->b_rptr;
17767 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17768 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17769 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17770 		if (mp != NULL)
17771 			putnext(rq, mp);
17772 		return;
17773 	}
17774 	switch (conn_res->PRIM_type) {
17775 	case O_T_CONN_RES:
17776 	case T_CONN_RES:
17777 		/*
17778 		 * We pass up an err ack if allocb fails. This will
17779 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17780 		 * tcp_eager_blowoff to be called. sockfs will then call
17781 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17782 		 * we need to do the allocb up here because we have to
17783 		 * make sure rq->q_qinfo->qi_qclose still points to the
17784 		 * correct function (tcp_tpi_close_accept) in case allocb
17785 		 * fails.
17786 		 */
17787 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17788 		    &eager, conn_res->OPT_length);
17789 		PRIM_type = conn_res->PRIM_type;
17790 		mp->b_datap->db_type = M_PCPROTO;
17791 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17792 		ok = (struct T_ok_ack *)mp->b_rptr;
17793 		ok->PRIM_type = T_OK_ACK;
17794 		ok->CORRECT_prim = PRIM_type;
17795 		econnp = eager->tcp_connp;
17796 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
17797 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
17798 		eager->tcp_rq = rq;
17799 		eager->tcp_wq = q;
17800 		rq->q_ptr = econnp;
17801 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
17802 		q->q_ptr = econnp;
17803 		q->q_qinfo = &tcp_winit;
17804 		listener = eager->tcp_listener;
17805 
17806 		if (tcp_accept_common(listener->tcp_connp,
17807 		    econnp, cr) < 0) {
17808 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17809 			if (mp != NULL)
17810 				putnext(rq, mp);
17811 			return;
17812 		}
17813 
17814 		/*
17815 		 * Send the new local address also up to sockfs. There
17816 		 * should already be enough space in the mp that came
17817 		 * down from soaccept().
17818 		 */
17819 		if (eager->tcp_family == AF_INET) {
17820 			sin_t *sin;
17821 
17822 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17823 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17824 			sin = (sin_t *)mp->b_wptr;
17825 			mp->b_wptr += sizeof (sin_t);
17826 			sin->sin_family = AF_INET;
17827 			sin->sin_port = eager->tcp_lport;
17828 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17829 		} else {
17830 			sin6_t *sin6;
17831 
17832 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17833 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17834 			sin6 = (sin6_t *)mp->b_wptr;
17835 			mp->b_wptr += sizeof (sin6_t);
17836 			sin6->sin6_family = AF_INET6;
17837 			sin6->sin6_port = eager->tcp_lport;
17838 			if (eager->tcp_ipversion == IPV4_VERSION) {
17839 				sin6->sin6_flowinfo = 0;
17840 				IN6_IPADDR_TO_V4MAPPED(
17841 				    eager->tcp_ipha->ipha_src,
17842 				    &sin6->sin6_addr);
17843 			} else {
17844 				ASSERT(eager->tcp_ip6h != NULL);
17845 				sin6->sin6_flowinfo =
17846 				    eager->tcp_ip6h->ip6_vcf &
17847 				    ~IPV6_VERS_AND_FLOW_MASK;
17848 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17849 			}
17850 			sin6->sin6_scope_id = 0;
17851 			sin6->__sin6_src_id = 0;
17852 		}
17853 
17854 		putnext(rq, mp);
17855 		return;
17856 	default:
17857 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17858 		if (mp != NULL)
17859 			putnext(rq, mp);
17860 		return;
17861 	}
17862 }
17863 
17864 static int
17865 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17866 {
17867 	sin_t *sin = (sin_t *)sa;
17868 	sin6_t *sin6 = (sin6_t *)sa;
17869 
17870 	switch (tcp->tcp_family) {
17871 	case AF_INET:
17872 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17873 
17874 		if (*salenp < sizeof (sin_t))
17875 			return (EINVAL);
17876 
17877 		*sin = sin_null;
17878 		sin->sin_family = AF_INET;
17879 		if (tcp->tcp_state >= TCPS_BOUND) {
17880 			sin->sin_port = tcp->tcp_lport;
17881 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
17882 		}
17883 		*salenp = sizeof (sin_t);
17884 		break;
17885 
17886 	case AF_INET6:
17887 		if (*salenp < sizeof (sin6_t))
17888 			return (EINVAL);
17889 
17890 		*sin6 = sin6_null;
17891 		sin6->sin6_family = AF_INET6;
17892 		if (tcp->tcp_state >= TCPS_BOUND) {
17893 			sin6->sin6_port = tcp->tcp_lport;
17894 			if (tcp->tcp_ipversion == IPV4_VERSION) {
17895 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
17896 				    &sin6->sin6_addr);
17897 			} else {
17898 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
17899 			}
17900 		}
17901 		*salenp = sizeof (sin6_t);
17902 		break;
17903 	}
17904 
17905 	return (0);
17906 }
17907 
17908 static int
17909 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17910 {
17911 	sin_t *sin = (sin_t *)sa;
17912 	sin6_t *sin6 = (sin6_t *)sa;
17913 
17914 	if (tcp->tcp_state < TCPS_SYN_RCVD)
17915 		return (ENOTCONN);
17916 
17917 	switch (tcp->tcp_family) {
17918 	case AF_INET:
17919 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17920 
17921 		if (*salenp < sizeof (sin_t))
17922 			return (EINVAL);
17923 
17924 		*sin = sin_null;
17925 		sin->sin_family = AF_INET;
17926 		sin->sin_port = tcp->tcp_fport;
17927 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
17928 		    sin->sin_addr.s_addr);
17929 		*salenp = sizeof (sin_t);
17930 		break;
17931 
17932 	case AF_INET6:
17933 		if (*salenp < sizeof (sin6_t))
17934 			return (EINVAL);
17935 
17936 		*sin6 = sin6_null;
17937 		sin6->sin6_family = AF_INET6;
17938 		sin6->sin6_port = tcp->tcp_fport;
17939 		sin6->sin6_addr = tcp->tcp_remote_v6;
17940 		if (tcp->tcp_ipversion == IPV6_VERSION) {
17941 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
17942 			    ~IPV6_VERS_AND_FLOW_MASK;
17943 		}
17944 		*salenp = sizeof (sin6_t);
17945 		break;
17946 	}
17947 
17948 	return (0);
17949 }
17950 
17951 /*
17952  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
17953  */
17954 static void
17955 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
17956 {
17957 	void	*data;
17958 	mblk_t	*datamp = mp->b_cont;
17959 	tcp_t	*tcp = Q_TO_TCP(q);
17960 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
17961 
17962 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
17963 		cmdp->cb_error = EPROTO;
17964 		qreply(q, mp);
17965 		return;
17966 	}
17967 
17968 	data = datamp->b_rptr;
17969 
17970 	switch (cmdp->cb_cmd) {
17971 	case TI_GETPEERNAME:
17972 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
17973 		break;
17974 	case TI_GETMYNAME:
17975 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
17976 		break;
17977 	default:
17978 		cmdp->cb_error = EINVAL;
17979 		break;
17980 	}
17981 
17982 	qreply(q, mp);
17983 }
17984 
17985 void
17986 tcp_wput(queue_t *q, mblk_t *mp)
17987 {
17988 	conn_t	*connp = Q_TO_CONN(q);
17989 	tcp_t	*tcp;
17990 	void (*output_proc)();
17991 	t_scalar_t type;
17992 	uchar_t *rptr;
17993 	struct iocblk	*iocp;
17994 	size_t size;
17995 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17996 
17997 	ASSERT(connp->conn_ref >= 2);
17998 
17999 	switch (DB_TYPE(mp)) {
18000 	case M_DATA:
18001 		tcp = connp->conn_tcp;
18002 		ASSERT(tcp != NULL);
18003 
18004 		size = msgdsize(mp);
18005 
18006 		mutex_enter(&tcp->tcp_non_sq_lock);
18007 		tcp->tcp_squeue_bytes += size;
18008 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18009 			tcp_setqfull(tcp);
18010 		}
18011 		mutex_exit(&tcp->tcp_non_sq_lock);
18012 
18013 		CONN_INC_REF(connp);
18014 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18015 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18016 		return;
18017 
18018 	case M_CMD:
18019 		tcp_wput_cmdblk(q, mp);
18020 		return;
18021 
18022 	case M_PROTO:
18023 	case M_PCPROTO:
18024 		/*
18025 		 * if it is a snmp message, don't get behind the squeue
18026 		 */
18027 		tcp = connp->conn_tcp;
18028 		rptr = mp->b_rptr;
18029 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18030 			type = ((union T_primitives *)rptr)->type;
18031 		} else {
18032 			if (tcp->tcp_debug) {
18033 				(void) strlog(TCP_MOD_ID, 0, 1,
18034 				    SL_ERROR|SL_TRACE,
18035 				    "tcp_wput_proto, dropping one...");
18036 			}
18037 			freemsg(mp);
18038 			return;
18039 		}
18040 		if (type == T_SVR4_OPTMGMT_REQ) {
18041 			/*
18042 			 * All Solaris components should pass a db_credp
18043 			 * for this TPI message, hence we ASSERT.
18044 			 * But in case there is some other M_PROTO that looks
18045 			 * like a TPI message sent by some other kernel
18046 			 * component, we check and return an error.
18047 			 */
18048 			cred_t	*cr = msg_getcred(mp, NULL);
18049 
18050 			ASSERT(cr != NULL);
18051 			if (cr == NULL) {
18052 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18053 				return;
18054 			}
18055 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18056 			    cr)) {
18057 				/*
18058 				 * This was a SNMP request
18059 				 */
18060 				return;
18061 			} else {
18062 				output_proc = tcp_wput_proto;
18063 			}
18064 		} else {
18065 			output_proc = tcp_wput_proto;
18066 		}
18067 		break;
18068 	case M_IOCTL:
18069 		/*
18070 		 * Most ioctls can be processed right away without going via
18071 		 * squeues - process them right here. Those that do require
18072 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18073 		 * are processed by tcp_wput_ioctl().
18074 		 */
18075 		iocp = (struct iocblk *)mp->b_rptr;
18076 		tcp = connp->conn_tcp;
18077 
18078 		switch (iocp->ioc_cmd) {
18079 		case TCP_IOC_ABORT_CONN:
18080 			tcp_ioctl_abort_conn(q, mp);
18081 			return;
18082 		case TI_GETPEERNAME:
18083 		case TI_GETMYNAME:
18084 			mi_copyin(q, mp, NULL,
18085 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18086 			return;
18087 		case ND_SET:
18088 			/* nd_getset does the necessary checks */
18089 		case ND_GET:
18090 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18091 				CALL_IP_WPUT(connp, q, mp);
18092 				return;
18093 			}
18094 			qreply(q, mp);
18095 			return;
18096 		case TCP_IOC_DEFAULT_Q:
18097 			/*
18098 			 * Wants to be the default wq. Check the credentials
18099 			 * first, the rest is executed via squeue.
18100 			 */
18101 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18102 				iocp->ioc_error = EPERM;
18103 				iocp->ioc_count = 0;
18104 				mp->b_datap->db_type = M_IOCACK;
18105 				qreply(q, mp);
18106 				return;
18107 			}
18108 			output_proc = tcp_wput_ioctl;
18109 			break;
18110 		default:
18111 			output_proc = tcp_wput_ioctl;
18112 			break;
18113 		}
18114 		break;
18115 	default:
18116 		output_proc = tcp_wput_nondata;
18117 		break;
18118 	}
18119 
18120 	CONN_INC_REF(connp);
18121 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18122 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18123 }
18124 
18125 /*
18126  * Initial STREAMS write side put() procedure for sockets. It tries to
18127  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18128  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18129  * are handled by tcp_wput() as usual.
18130  *
18131  * All further messages will also be handled by tcp_wput() because we cannot
18132  * be sure that the above short cut is safe later.
18133  */
18134 static void
18135 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18136 {
18137 	conn_t			*connp = Q_TO_CONN(wq);
18138 	tcp_t			*tcp = connp->conn_tcp;
18139 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18140 
18141 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18142 	wq->q_qinfo = &tcp_winit;
18143 
18144 	ASSERT(IPCL_IS_TCP(connp));
18145 	ASSERT(TCP_IS_SOCKET(tcp));
18146 
18147 	if (DB_TYPE(mp) == M_PCPROTO &&
18148 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18149 	    car->PRIM_type == T_CAPABILITY_REQ) {
18150 		tcp_capability_req(tcp, mp);
18151 		return;
18152 	}
18153 
18154 	tcp_wput(wq, mp);
18155 }
18156 
18157 /* ARGSUSED */
18158 static void
18159 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18160 {
18161 #ifdef DEBUG
18162 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18163 #endif
18164 	freemsg(mp);
18165 }
18166 
18167 static boolean_t
18168 tcp_zcopy_check(tcp_t *tcp)
18169 {
18170 	conn_t	*connp = tcp->tcp_connp;
18171 	ire_t	*ire;
18172 	boolean_t	zc_enabled = B_FALSE;
18173 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18174 
18175 	if (do_tcpzcopy == 2)
18176 		zc_enabled = B_TRUE;
18177 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18178 	    IPCL_IS_CONNECTED(connp) &&
18179 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18180 	    connp->conn_dontroute == 0 &&
18181 	    !connp->conn_nexthop_set &&
18182 	    connp->conn_outgoing_ill == NULL &&
18183 	    do_tcpzcopy == 1) {
18184 		/*
18185 		 * the checks above  closely resemble the fast path checks
18186 		 * in tcp_send_data().
18187 		 */
18188 		mutex_enter(&connp->conn_lock);
18189 		ire = connp->conn_ire_cache;
18190 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18191 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18192 			IRE_REFHOLD(ire);
18193 			if (ire->ire_stq != NULL) {
18194 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18195 
18196 				zc_enabled = ill && (ill->ill_capabilities &
18197 				    ILL_CAPAB_ZEROCOPY) &&
18198 				    (ill->ill_zerocopy_capab->
18199 				    ill_zerocopy_flags != 0);
18200 			}
18201 			IRE_REFRELE(ire);
18202 		}
18203 		mutex_exit(&connp->conn_lock);
18204 	}
18205 	tcp->tcp_snd_zcopy_on = zc_enabled;
18206 	if (!TCP_IS_DETACHED(tcp)) {
18207 		if (zc_enabled) {
18208 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18209 			    ZCVMSAFE);
18210 			TCP_STAT(tcps, tcp_zcopy_on);
18211 		} else {
18212 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18213 			    ZCVMUNSAFE);
18214 			TCP_STAT(tcps, tcp_zcopy_off);
18215 		}
18216 	}
18217 	return (zc_enabled);
18218 }
18219 
18220 static mblk_t *
18221 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18222 {
18223 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18224 
18225 	if (do_tcpzcopy == 2)
18226 		return (bp);
18227 	else if (tcp->tcp_snd_zcopy_on) {
18228 		tcp->tcp_snd_zcopy_on = B_FALSE;
18229 		if (!TCP_IS_DETACHED(tcp)) {
18230 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18231 			    ZCVMUNSAFE);
18232 			TCP_STAT(tcps, tcp_zcopy_disable);
18233 		}
18234 	}
18235 	return (tcp_zcopy_backoff(tcp, bp, 0));
18236 }
18237 
18238 /*
18239  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18240  * the original desballoca'ed segmapped mblk.
18241  */
18242 static mblk_t *
18243 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18244 {
18245 	mblk_t *head, *tail, *nbp;
18246 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18247 
18248 	if (IS_VMLOANED_MBLK(bp)) {
18249 		TCP_STAT(tcps, tcp_zcopy_backoff);
18250 		if ((head = copyb(bp)) == NULL) {
18251 			/* fail to backoff; leave it for the next backoff */
18252 			tcp->tcp_xmit_zc_clean = B_FALSE;
18253 			return (bp);
18254 		}
18255 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18256 			if (fix_xmitlist)
18257 				tcp_zcopy_notify(tcp);
18258 			else
18259 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18260 		}
18261 		nbp = bp->b_cont;
18262 		if (fix_xmitlist) {
18263 			head->b_prev = bp->b_prev;
18264 			head->b_next = bp->b_next;
18265 			if (tcp->tcp_xmit_tail == bp)
18266 				tcp->tcp_xmit_tail = head;
18267 		}
18268 		bp->b_next = NULL;
18269 		bp->b_prev = NULL;
18270 		freeb(bp);
18271 	} else {
18272 		head = bp;
18273 		nbp = bp->b_cont;
18274 	}
18275 	tail = head;
18276 	while (nbp) {
18277 		if (IS_VMLOANED_MBLK(nbp)) {
18278 			TCP_STAT(tcps, tcp_zcopy_backoff);
18279 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18280 				tcp->tcp_xmit_zc_clean = B_FALSE;
18281 				tail->b_cont = nbp;
18282 				return (head);
18283 			}
18284 			tail = tail->b_cont;
18285 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18286 				if (fix_xmitlist)
18287 					tcp_zcopy_notify(tcp);
18288 				else
18289 					tail->b_datap->db_struioflag |=
18290 					    STRUIO_ZCNOTIFY;
18291 			}
18292 			bp = nbp;
18293 			nbp = nbp->b_cont;
18294 			if (fix_xmitlist) {
18295 				tail->b_prev = bp->b_prev;
18296 				tail->b_next = bp->b_next;
18297 				if (tcp->tcp_xmit_tail == bp)
18298 					tcp->tcp_xmit_tail = tail;
18299 			}
18300 			bp->b_next = NULL;
18301 			bp->b_prev = NULL;
18302 			freeb(bp);
18303 		} else {
18304 			tail->b_cont = nbp;
18305 			tail = nbp;
18306 			nbp = nbp->b_cont;
18307 		}
18308 	}
18309 	if (fix_xmitlist) {
18310 		tcp->tcp_xmit_last = tail;
18311 		tcp->tcp_xmit_zc_clean = B_TRUE;
18312 	}
18313 	return (head);
18314 }
18315 
18316 static void
18317 tcp_zcopy_notify(tcp_t *tcp)
18318 {
18319 	struct stdata	*stp;
18320 	conn_t *connp;
18321 
18322 	if (tcp->tcp_detached)
18323 		return;
18324 	connp = tcp->tcp_connp;
18325 	if (IPCL_IS_NONSTR(connp)) {
18326 		(*connp->conn_upcalls->su_zcopy_notify)
18327 		    (connp->conn_upper_handle);
18328 		return;
18329 	}
18330 	stp = STREAM(tcp->tcp_rq);
18331 	mutex_enter(&stp->sd_lock);
18332 	stp->sd_flag |= STZCNOTIFY;
18333 	cv_broadcast(&stp->sd_zcopy_wait);
18334 	mutex_exit(&stp->sd_lock);
18335 }
18336 
18337 static boolean_t
18338 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18339 {
18340 	ire_t	*ire;
18341 	conn_t	*connp = tcp->tcp_connp;
18342 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18343 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18344 
18345 	mutex_enter(&connp->conn_lock);
18346 	ire = connp->conn_ire_cache;
18347 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18348 
18349 	if ((ire != NULL) &&
18350 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18351 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18352 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18353 		IRE_REFHOLD(ire);
18354 		mutex_exit(&connp->conn_lock);
18355 	} else {
18356 		boolean_t cached = B_FALSE;
18357 		ts_label_t *tsl;
18358 
18359 		/* force a recheck later on */
18360 		tcp->tcp_ire_ill_check_done = B_FALSE;
18361 
18362 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18363 		connp->conn_ire_cache = NULL;
18364 		mutex_exit(&connp->conn_lock);
18365 
18366 		if (ire != NULL)
18367 			IRE_REFRELE_NOTR(ire);
18368 
18369 		tsl = crgetlabel(CONN_CRED(connp));
18370 		ire = (dst ?
18371 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18372 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18373 		    connp->conn_zoneid, tsl, ipst));
18374 
18375 		if (ire == NULL) {
18376 			TCP_STAT(tcps, tcp_ire_null);
18377 			return (B_FALSE);
18378 		}
18379 
18380 		IRE_REFHOLD_NOTR(ire);
18381 
18382 		mutex_enter(&connp->conn_lock);
18383 		if (CONN_CACHE_IRE(connp)) {
18384 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18385 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18386 				TCP_CHECK_IREINFO(tcp, ire);
18387 				connp->conn_ire_cache = ire;
18388 				cached = B_TRUE;
18389 			}
18390 			rw_exit(&ire->ire_bucket->irb_lock);
18391 		}
18392 		mutex_exit(&connp->conn_lock);
18393 
18394 		/*
18395 		 * We can continue to use the ire but since it was
18396 		 * not cached, we should drop the extra reference.
18397 		 */
18398 		if (!cached)
18399 			IRE_REFRELE_NOTR(ire);
18400 
18401 		/*
18402 		 * Rampart note: no need to select a new label here, since
18403 		 * labels are not allowed to change during the life of a TCP
18404 		 * connection.
18405 		 */
18406 	}
18407 
18408 	*irep = ire;
18409 
18410 	return (B_TRUE);
18411 }
18412 
18413 /*
18414  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18415  *
18416  * 0 = success;
18417  * 1 = failed to find ire and ill.
18418  */
18419 static boolean_t
18420 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18421 {
18422 	ipha_t		*ipha;
18423 	ipaddr_t	dst;
18424 	ire_t		*ire;
18425 	ill_t		*ill;
18426 	mblk_t		*ire_fp_mp;
18427 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18428 
18429 	if (mp != NULL)
18430 		ipha = (ipha_t *)mp->b_rptr;
18431 	else
18432 		ipha = tcp->tcp_ipha;
18433 	dst = ipha->ipha_dst;
18434 
18435 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18436 		return (B_FALSE);
18437 
18438 	if ((ire->ire_flags & RTF_MULTIRT) ||
18439 	    (ire->ire_stq == NULL) ||
18440 	    (ire->ire_nce == NULL) ||
18441 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18442 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18443 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18444 		TCP_STAT(tcps, tcp_ip_ire_send);
18445 		IRE_REFRELE(ire);
18446 		return (B_FALSE);
18447 	}
18448 
18449 	ill = ire_to_ill(ire);
18450 	ASSERT(ill != NULL);
18451 
18452 	if (!tcp->tcp_ire_ill_check_done) {
18453 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18454 		tcp->tcp_ire_ill_check_done = B_TRUE;
18455 	}
18456 
18457 	*irep = ire;
18458 	*illp = ill;
18459 
18460 	return (B_TRUE);
18461 }
18462 
18463 static void
18464 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18465 {
18466 	ipha_t		*ipha;
18467 	ipaddr_t	src;
18468 	ipaddr_t	dst;
18469 	uint32_t	cksum;
18470 	ire_t		*ire;
18471 	uint16_t	*up;
18472 	ill_t		*ill;
18473 	conn_t		*connp = tcp->tcp_connp;
18474 	uint32_t	hcksum_txflags = 0;
18475 	mblk_t		*ire_fp_mp;
18476 	uint_t		ire_fp_mp_len;
18477 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18478 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18479 	cred_t		*cr;
18480 	pid_t		cpid;
18481 
18482 	ASSERT(DB_TYPE(mp) == M_DATA);
18483 
18484 	/*
18485 	 * Here we need to handle the overloading of the cred_t for
18486 	 * both getpeerucred and TX.
18487 	 * If this is a SYN then the caller already set db_credp so
18488 	 * that getpeerucred will work. But if TX is in use we might have
18489 	 * a conn_effective_cred which is different, and we need to use that
18490 	 * cred to make TX use the correct label and label dependent route.
18491 	 */
18492 	if (is_system_labeled()) {
18493 		cr = msg_getcred(mp, &cpid);
18494 		if (cr == NULL || connp->conn_effective_cred != NULL)
18495 			mblk_setcred(mp, CONN_CRED(connp), cpid);
18496 	}
18497 
18498 	ipha = (ipha_t *)mp->b_rptr;
18499 	src = ipha->ipha_src;
18500 	dst = ipha->ipha_dst;
18501 
18502 	ASSERT(q != NULL);
18503 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
18504 
18505 	/*
18506 	 * Drop off fast path for IPv6 and also if options are present or
18507 	 * we need to resolve a TS label.
18508 	 */
18509 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18510 	    !IPCL_IS_CONNECTED(connp) ||
18511 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18512 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18513 	    !connp->conn_ulp_labeled ||
18514 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18515 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18516 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18517 		if (tcp->tcp_snd_zcopy_aware)
18518 			mp = tcp_zcopy_disable(tcp, mp);
18519 		TCP_STAT(tcps, tcp_ip_send);
18520 		CALL_IP_WPUT(connp, q, mp);
18521 		return;
18522 	}
18523 
18524 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18525 		if (tcp->tcp_snd_zcopy_aware)
18526 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18527 		CALL_IP_WPUT(connp, q, mp);
18528 		return;
18529 	}
18530 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18531 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18532 
18533 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18534 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18535 #ifndef _BIG_ENDIAN
18536 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18537 #endif
18538 
18539 	/*
18540 	 * Check to see if we need to re-enable LSO/MDT for this connection
18541 	 * because it was previously disabled due to changes in the ill;
18542 	 * note that by doing it here, this re-enabling only applies when
18543 	 * the packet is not dispatched through CALL_IP_WPUT().
18544 	 *
18545 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18546 	 * case, since that's how we ended up here.  For IPv6, we do the
18547 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18548 	 */
18549 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18550 		/*
18551 		 * Restore LSO for this connection, so that next time around
18552 		 * it is eligible to go through tcp_lsosend() path again.
18553 		 */
18554 		TCP_STAT(tcps, tcp_lso_enabled);
18555 		tcp->tcp_lso = B_TRUE;
18556 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18557 		    "interface %s\n", (void *)connp, ill->ill_name));
18558 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18559 		/*
18560 		 * Restore MDT for this connection, so that next time around
18561 		 * it is eligible to go through tcp_multisend() path again.
18562 		 */
18563 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18564 		tcp->tcp_mdt = B_TRUE;
18565 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18566 		    "interface %s\n", (void *)connp, ill->ill_name));
18567 	}
18568 
18569 	if (tcp->tcp_snd_zcopy_aware) {
18570 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18571 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18572 			mp = tcp_zcopy_disable(tcp, mp);
18573 		/*
18574 		 * we shouldn't need to reset ipha as the mp containing
18575 		 * ipha should never be a zero-copy mp.
18576 		 */
18577 	}
18578 
18579 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18580 		ASSERT(ill->ill_hcksum_capab != NULL);
18581 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18582 	}
18583 
18584 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18585 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18586 
18587 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18588 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18589 
18590 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18591 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18592 
18593 	/* Software checksum? */
18594 	if (DB_CKSUMFLAGS(mp) == 0) {
18595 		TCP_STAT(tcps, tcp_out_sw_cksum);
18596 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18597 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18598 	}
18599 
18600 	/* Calculate IP header checksum if hardware isn't capable */
18601 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18602 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18603 		    ((uint16_t *)ipha)[4]);
18604 	}
18605 
18606 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18607 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18608 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18609 
18610 	UPDATE_OB_PKT_COUNT(ire);
18611 	ire->ire_last_used_time = lbolt;
18612 
18613 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18614 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18615 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18616 	    ntohs(ipha->ipha_length));
18617 
18618 	DTRACE_PROBE4(ip4__physical__out__start,
18619 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
18620 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
18621 	    ipst->ips_ipv4firewall_physical_out,
18622 	    NULL, ill, ipha, mp, mp, 0, ipst);
18623 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18624 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
18625 
18626 	if (mp != NULL) {
18627 		if (ipst->ips_ipobs_enabled) {
18628 			zoneid_t szone;
18629 
18630 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
18631 			    ipst, ALL_ZONES);
18632 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
18633 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
18634 		}
18635 
18636 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
18637 	}
18638 
18639 	IRE_REFRELE(ire);
18640 }
18641 
18642 /*
18643  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18644  * if the receiver shrinks the window, i.e. moves the right window to the
18645  * left, the we should not send new data, but should retransmit normally the
18646  * old unacked data between suna and suna + swnd. We might has sent data
18647  * that is now outside the new window, pretend that we didn't send  it.
18648  */
18649 static void
18650 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18651 {
18652 	uint32_t	snxt = tcp->tcp_snxt;
18653 
18654 	ASSERT(shrunk_count > 0);
18655 
18656 	if (!tcp->tcp_is_wnd_shrnk) {
18657 		tcp->tcp_snxt_shrunk = snxt;
18658 		tcp->tcp_is_wnd_shrnk = B_TRUE;
18659 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
18660 		tcp->tcp_snxt_shrunk = snxt;
18661 	}
18662 
18663 	/* Pretend we didn't send the data outside the window */
18664 	snxt -= shrunk_count;
18665 
18666 	/* Reset all the values per the now shrunk window */
18667 	tcp_update_xmit_tail(tcp, snxt);
18668 	tcp->tcp_unsent += shrunk_count;
18669 
18670 	/*
18671 	 * If the SACK option is set, delete the entire list of
18672 	 * notsack'ed blocks.
18673 	 */
18674 	if (tcp->tcp_sack_info != NULL) {
18675 		if (tcp->tcp_notsack_list != NULL)
18676 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
18677 	}
18678 
18679 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18680 		/*
18681 		 * Make sure the timer is running so that we will probe a zero
18682 		 * window.
18683 		 */
18684 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18685 }
18686 
18687 
18688 /*
18689  * The TCP normal data output path.
18690  * NOTE: the logic of the fast path is duplicated from this function.
18691  */
18692 static void
18693 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18694 {
18695 	int		len;
18696 	mblk_t		*local_time;
18697 	mblk_t		*mp1;
18698 	uint32_t	snxt;
18699 	int		tail_unsent;
18700 	int		tcpstate;
18701 	int		usable = 0;
18702 	mblk_t		*xmit_tail;
18703 	queue_t		*q = tcp->tcp_wq;
18704 	int32_t		mss;
18705 	int32_t		num_sack_blk = 0;
18706 	int32_t		tcp_hdr_len;
18707 	int32_t		tcp_tcp_hdr_len;
18708 	int		mdt_thres;
18709 	int		rc;
18710 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18711 	ip_stack_t	*ipst;
18712 
18713 	tcpstate = tcp->tcp_state;
18714 	if (mp == NULL) {
18715 		/*
18716 		 * tcp_wput_data() with NULL mp should only be called when
18717 		 * there is unsent data.
18718 		 */
18719 		ASSERT(tcp->tcp_unsent > 0);
18720 		/* Really tacky... but we need this for detached closes. */
18721 		len = tcp->tcp_unsent;
18722 		goto data_null;
18723 	}
18724 
18725 #if CCS_STATS
18726 	wrw_stats.tot.count++;
18727 	wrw_stats.tot.bytes += msgdsize(mp);
18728 #endif
18729 	ASSERT(mp->b_datap->db_type == M_DATA);
18730 	/*
18731 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18732 	 * or before a connection attempt has begun.
18733 	 */
18734 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18735 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18736 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18737 #ifdef DEBUG
18738 			cmn_err(CE_WARN,
18739 			    "tcp_wput_data: data after ordrel, %s",
18740 			    tcp_display(tcp, NULL,
18741 			    DISP_ADDR_AND_PORT));
18742 #else
18743 			if (tcp->tcp_debug) {
18744 				(void) strlog(TCP_MOD_ID, 0, 1,
18745 				    SL_TRACE|SL_ERROR,
18746 				    "tcp_wput_data: data after ordrel, %s\n",
18747 				    tcp_display(tcp, NULL,
18748 				    DISP_ADDR_AND_PORT));
18749 			}
18750 #endif /* DEBUG */
18751 		}
18752 		if (tcp->tcp_snd_zcopy_aware &&
18753 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18754 			tcp_zcopy_notify(tcp);
18755 		freemsg(mp);
18756 		mutex_enter(&tcp->tcp_non_sq_lock);
18757 		if (tcp->tcp_flow_stopped &&
18758 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18759 			tcp_clrqfull(tcp);
18760 		}
18761 		mutex_exit(&tcp->tcp_non_sq_lock);
18762 		return;
18763 	}
18764 
18765 	/* Strip empties */
18766 	for (;;) {
18767 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18768 		    (uintptr_t)INT_MAX);
18769 		len = (int)(mp->b_wptr - mp->b_rptr);
18770 		if (len > 0)
18771 			break;
18772 		mp1 = mp;
18773 		mp = mp->b_cont;
18774 		freeb(mp1);
18775 		if (!mp) {
18776 			return;
18777 		}
18778 	}
18779 
18780 	/* If we are the first on the list ... */
18781 	if (tcp->tcp_xmit_head == NULL) {
18782 		tcp->tcp_xmit_head = mp;
18783 		tcp->tcp_xmit_tail = mp;
18784 		tcp->tcp_xmit_tail_unsent = len;
18785 	} else {
18786 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18787 		struct datab *dp;
18788 
18789 		mp1 = tcp->tcp_xmit_last;
18790 		if (len < tcp_tx_pull_len &&
18791 		    (dp = mp1->b_datap)->db_ref == 1 &&
18792 		    dp->db_lim - mp1->b_wptr >= len) {
18793 			ASSERT(len > 0);
18794 			ASSERT(!mp1->b_cont);
18795 			if (len == 1) {
18796 				*mp1->b_wptr++ = *mp->b_rptr;
18797 			} else {
18798 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18799 				mp1->b_wptr += len;
18800 			}
18801 			if (mp1 == tcp->tcp_xmit_tail)
18802 				tcp->tcp_xmit_tail_unsent += len;
18803 			mp1->b_cont = mp->b_cont;
18804 			if (tcp->tcp_snd_zcopy_aware &&
18805 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18806 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18807 			freeb(mp);
18808 			mp = mp1;
18809 		} else {
18810 			tcp->tcp_xmit_last->b_cont = mp;
18811 		}
18812 		len += tcp->tcp_unsent;
18813 	}
18814 
18815 	/* Tack on however many more positive length mblks we have */
18816 	if ((mp1 = mp->b_cont) != NULL) {
18817 		do {
18818 			int tlen;
18819 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18820 			    (uintptr_t)INT_MAX);
18821 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18822 			if (tlen <= 0) {
18823 				mp->b_cont = mp1->b_cont;
18824 				freeb(mp1);
18825 			} else {
18826 				len += tlen;
18827 				mp = mp1;
18828 			}
18829 		} while ((mp1 = mp->b_cont) != NULL);
18830 	}
18831 	tcp->tcp_xmit_last = mp;
18832 	tcp->tcp_unsent = len;
18833 
18834 	if (urgent)
18835 		usable = 1;
18836 
18837 data_null:
18838 	snxt = tcp->tcp_snxt;
18839 	xmit_tail = tcp->tcp_xmit_tail;
18840 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18841 
18842 	/*
18843 	 * Note that tcp_mss has been adjusted to take into account the
18844 	 * timestamp option if applicable.  Because SACK options do not
18845 	 * appear in every TCP segments and they are of variable lengths,
18846 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18847 	 * the actual segment length when we need to send a segment which
18848 	 * includes SACK options.
18849 	 */
18850 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18851 		int32_t	opt_len;
18852 
18853 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18854 		    tcp->tcp_num_sack_blk);
18855 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18856 		    2 + TCPOPT_HEADER_LEN;
18857 		mss = tcp->tcp_mss - opt_len;
18858 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18859 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18860 	} else {
18861 		mss = tcp->tcp_mss;
18862 		tcp_hdr_len = tcp->tcp_hdr_len;
18863 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18864 	}
18865 
18866 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18867 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18868 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18869 	}
18870 	if (tcpstate == TCPS_SYN_RCVD) {
18871 		/*
18872 		 * The three-way connection establishment handshake is not
18873 		 * complete yet. We want to queue the data for transmission
18874 		 * after entering ESTABLISHED state (RFC793). A jump to
18875 		 * "done" label effectively leaves data on the queue.
18876 		 */
18877 		goto done;
18878 	} else {
18879 		int usable_r;
18880 
18881 		/*
18882 		 * In the special case when cwnd is zero, which can only
18883 		 * happen if the connection is ECN capable, return now.
18884 		 * New segments is sent using tcp_timer().  The timer
18885 		 * is set in tcp_rput_data().
18886 		 */
18887 		if (tcp->tcp_cwnd == 0) {
18888 			/*
18889 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18890 			 * finished.
18891 			 */
18892 			ASSERT(tcp->tcp_ecn_ok ||
18893 			    tcp->tcp_state < TCPS_ESTABLISHED);
18894 			return;
18895 		}
18896 
18897 		/* NOTE: trouble if xmitting while SYN not acked? */
18898 		usable_r = snxt - tcp->tcp_suna;
18899 		usable_r = tcp->tcp_swnd - usable_r;
18900 
18901 		/*
18902 		 * Check if the receiver has shrunk the window.  If
18903 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18904 		 * cannot be set as there is unsent data, so FIN cannot
18905 		 * be sent out.  Otherwise, we need to take into account
18906 		 * of FIN as it consumes an "invisible" sequence number.
18907 		 */
18908 		ASSERT(tcp->tcp_fin_sent == 0);
18909 		if (usable_r < 0) {
18910 			/*
18911 			 * The receiver has shrunk the window and we have sent
18912 			 * -usable_r date beyond the window, re-adjust.
18913 			 *
18914 			 * If TCP window scaling is enabled, there can be
18915 			 * round down error as the advertised receive window
18916 			 * is actually right shifted n bits.  This means that
18917 			 * the lower n bits info is wiped out.  It will look
18918 			 * like the window is shrunk.  Do a check here to
18919 			 * see if the shrunk amount is actually within the
18920 			 * error in window calculation.  If it is, just
18921 			 * return.  Note that this check is inside the
18922 			 * shrunk window check.  This makes sure that even
18923 			 * though tcp_process_shrunk_swnd() is not called,
18924 			 * we will stop further processing.
18925 			 */
18926 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18927 				tcp_process_shrunk_swnd(tcp, -usable_r);
18928 			}
18929 			return;
18930 		}
18931 
18932 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18933 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18934 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18935 
18936 		/* usable = MIN(usable, unsent) */
18937 		if (usable_r > len)
18938 			usable_r = len;
18939 
18940 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18941 		if (usable_r > 0) {
18942 			usable = usable_r;
18943 		} else {
18944 			/* Bypass all other unnecessary processing. */
18945 			goto done;
18946 		}
18947 	}
18948 
18949 	local_time = (mblk_t *)lbolt;
18950 
18951 	/*
18952 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18953 	 * BSD.  This is more in line with the true intent of Nagle.
18954 	 *
18955 	 * The conditions are:
18956 	 * 1. The amount of unsent data (or amount of data which can be
18957 	 *    sent, whichever is smaller) is less than Nagle limit.
18958 	 * 2. The last sent size is also less than Nagle limit.
18959 	 * 3. There is unack'ed data.
18960 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18961 	 *    Nagle algorithm.  This reduces the probability that urgent
18962 	 *    bytes get "merged" together.
18963 	 * 5. The app has not closed the connection.  This eliminates the
18964 	 *    wait time of the receiving side waiting for the last piece of
18965 	 *    (small) data.
18966 	 *
18967 	 * If all are satisified, exit without sending anything.  Note
18968 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18969 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18970 	 * 4095).
18971 	 */
18972 	if (usable < (int)tcp->tcp_naglim &&
18973 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18974 	    snxt != tcp->tcp_suna &&
18975 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18976 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18977 		goto done;
18978 	}
18979 
18980 	/*
18981 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
18982 	 * is set, then we have to force TCP not to send partial segment
18983 	 * (smaller than MSS bytes). We are calculating the usable now
18984 	 * based on full mss and will save the rest of remaining data for
18985 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
18986 	 * something to do zero window probe.
18987 	 */
18988 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
18989 		if (usable < mss)
18990 			goto done;
18991 		usable = (usable / mss) * mss;
18992 	}
18993 
18994 	/* Update the latest receive window size in TCP header. */
18995 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18996 	    tcp->tcp_tcph->th_win);
18997 
18998 	/*
18999 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19000 	 *
19001 	 * 1. Simple TCP/IP{v4,v6} (no options).
19002 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19003 	 * 3. If the TCP connection is in ESTABLISHED state.
19004 	 * 4. The TCP is not detached.
19005 	 *
19006 	 * If any of the above conditions have changed during the
19007 	 * connection, stop using LSO/MDT and restore the stream head
19008 	 * parameters accordingly.
19009 	 */
19010 	ipst = tcps->tcps_netstack->netstack_ip;
19011 
19012 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19013 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19014 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19015 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19016 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19017 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19018 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19019 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19020 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19021 		if (tcp->tcp_lso) {
19022 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19023 			tcp->tcp_lso = B_FALSE;
19024 		} else {
19025 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19026 			tcp->tcp_mdt = B_FALSE;
19027 		}
19028 
19029 		/* Anything other than detached is considered pathological */
19030 		if (!TCP_IS_DETACHED(tcp)) {
19031 			if (tcp->tcp_lso)
19032 				TCP_STAT(tcps, tcp_lso_disabled);
19033 			else
19034 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19035 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19036 		}
19037 	}
19038 
19039 	/* Use MDT if sendable amount is greater than the threshold */
19040 	if (tcp->tcp_mdt &&
19041 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19042 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19043 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19044 	    (tcp->tcp_valid_bits == 0 ||
19045 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19046 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19047 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19048 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19049 		    local_time, mdt_thres);
19050 	} else {
19051 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19052 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19053 		    local_time, INT_MAX);
19054 	}
19055 
19056 	/* Pretend that all we were trying to send really got sent */
19057 	if (rc < 0 && tail_unsent < 0) {
19058 		do {
19059 			xmit_tail = xmit_tail->b_cont;
19060 			xmit_tail->b_prev = local_time;
19061 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19062 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19063 			tail_unsent += (int)(xmit_tail->b_wptr -
19064 			    xmit_tail->b_rptr);
19065 		} while (tail_unsent < 0);
19066 	}
19067 done:;
19068 	tcp->tcp_xmit_tail = xmit_tail;
19069 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19070 	len = tcp->tcp_snxt - snxt;
19071 	if (len) {
19072 		/*
19073 		 * If new data was sent, need to update the notsack
19074 		 * list, which is, afterall, data blocks that have
19075 		 * not been sack'ed by the receiver.  New data is
19076 		 * not sack'ed.
19077 		 */
19078 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19079 			/* len is a negative value. */
19080 			tcp->tcp_pipe -= len;
19081 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19082 			    tcp->tcp_snxt, snxt,
19083 			    &(tcp->tcp_num_notsack_blk),
19084 			    &(tcp->tcp_cnt_notsack_list));
19085 		}
19086 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19087 		tcp->tcp_rack = tcp->tcp_rnxt;
19088 		tcp->tcp_rack_cnt = 0;
19089 		if ((snxt + len) == tcp->tcp_suna) {
19090 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19091 		}
19092 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19093 		/*
19094 		 * Didn't send anything. Make sure the timer is running
19095 		 * so that we will probe a zero window.
19096 		 */
19097 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19098 	}
19099 	/* Note that len is the amount we just sent but with a negative sign */
19100 	tcp->tcp_unsent += len;
19101 	mutex_enter(&tcp->tcp_non_sq_lock);
19102 	if (tcp->tcp_flow_stopped) {
19103 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19104 			tcp_clrqfull(tcp);
19105 		}
19106 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19107 		tcp_setqfull(tcp);
19108 	}
19109 	mutex_exit(&tcp->tcp_non_sq_lock);
19110 }
19111 
19112 /*
19113  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19114  * outgoing TCP header with the template header, as well as other
19115  * options such as time-stamp, ECN and/or SACK.
19116  */
19117 static void
19118 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19119 {
19120 	tcph_t *tcp_tmpl, *tcp_h;
19121 	uint32_t *dst, *src;
19122 	int hdrlen;
19123 
19124 	ASSERT(OK_32PTR(rptr));
19125 
19126 	/* Template header */
19127 	tcp_tmpl = tcp->tcp_tcph;
19128 
19129 	/* Header of outgoing packet */
19130 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19131 
19132 	/* dst and src are opaque 32-bit fields, used for copying */
19133 	dst = (uint32_t *)rptr;
19134 	src = (uint32_t *)tcp->tcp_iphc;
19135 	hdrlen = tcp->tcp_hdr_len;
19136 
19137 	/* Fill time-stamp option if needed */
19138 	if (tcp->tcp_snd_ts_ok) {
19139 		U32_TO_BE32((uint32_t)now,
19140 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19141 		U32_TO_BE32(tcp->tcp_ts_recent,
19142 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19143 	} else {
19144 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19145 	}
19146 
19147 	/*
19148 	 * Copy the template header; is this really more efficient than
19149 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19150 	 * but perhaps not for other scenarios.
19151 	 */
19152 	dst[0] = src[0];
19153 	dst[1] = src[1];
19154 	dst[2] = src[2];
19155 	dst[3] = src[3];
19156 	dst[4] = src[4];
19157 	dst[5] = src[5];
19158 	dst[6] = src[6];
19159 	dst[7] = src[7];
19160 	dst[8] = src[8];
19161 	dst[9] = src[9];
19162 	if (hdrlen -= 40) {
19163 		hdrlen >>= 2;
19164 		dst += 10;
19165 		src += 10;
19166 		do {
19167 			*dst++ = *src++;
19168 		} while (--hdrlen);
19169 	}
19170 
19171 	/*
19172 	 * Set the ECN info in the TCP header if it is not a zero
19173 	 * window probe.  Zero window probe is only sent in
19174 	 * tcp_wput_data() and tcp_timer().
19175 	 */
19176 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19177 		SET_ECT(tcp, rptr);
19178 
19179 		if (tcp->tcp_ecn_echo_on)
19180 			tcp_h->th_flags[0] |= TH_ECE;
19181 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19182 			tcp_h->th_flags[0] |= TH_CWR;
19183 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19184 		}
19185 	}
19186 
19187 	/* Fill in SACK options */
19188 	if (num_sack_blk > 0) {
19189 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19190 		sack_blk_t *tmp;
19191 		int32_t	i;
19192 
19193 		wptr[0] = TCPOPT_NOP;
19194 		wptr[1] = TCPOPT_NOP;
19195 		wptr[2] = TCPOPT_SACK;
19196 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19197 		    sizeof (sack_blk_t);
19198 		wptr += TCPOPT_REAL_SACK_LEN;
19199 
19200 		tmp = tcp->tcp_sack_list;
19201 		for (i = 0; i < num_sack_blk; i++) {
19202 			U32_TO_BE32(tmp[i].begin, wptr);
19203 			wptr += sizeof (tcp_seq);
19204 			U32_TO_BE32(tmp[i].end, wptr);
19205 			wptr += sizeof (tcp_seq);
19206 		}
19207 		tcp_h->th_offset_and_rsrvd[0] +=
19208 		    ((num_sack_blk * 2 + 1) << 4);
19209 	}
19210 }
19211 
19212 /*
19213  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19214  * the destination address and SAP attribute, and if necessary, the
19215  * hardware checksum offload attribute to a Multidata message.
19216  */
19217 static int
19218 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19219     const uint32_t start, const uint32_t stuff, const uint32_t end,
19220     const uint32_t flags, tcp_stack_t *tcps)
19221 {
19222 	/* Add global destination address & SAP attribute */
19223 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19224 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19225 		    "destination address+SAP\n"));
19226 
19227 		if (dlmp != NULL)
19228 			TCP_STAT(tcps, tcp_mdt_allocfail);
19229 		return (-1);
19230 	}
19231 
19232 	/* Add global hwcksum attribute */
19233 	if (hwcksum &&
19234 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19235 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19236 		    "checksum attribute\n"));
19237 
19238 		TCP_STAT(tcps, tcp_mdt_allocfail);
19239 		return (-1);
19240 	}
19241 
19242 	return (0);
19243 }
19244 
19245 /*
19246  * Smaller and private version of pdescinfo_t used specifically for TCP,
19247  * which allows for only two payload spans per packet.
19248  */
19249 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19250 
19251 /*
19252  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19253  * scheme, and returns one the following:
19254  *
19255  * -1 = failed allocation.
19256  *  0 = success; burst count reached, or usable send window is too small,
19257  *      and that we'd rather wait until later before sending again.
19258  */
19259 static int
19260 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19261     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19262     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19263     const int mdt_thres)
19264 {
19265 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19266 	multidata_t	*mmd;
19267 	uint_t		obsegs, obbytes, hdr_frag_sz;
19268 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19269 	int		num_burst_seg, max_pld;
19270 	pdesc_t		*pkt;
19271 	tcp_pdescinfo_t	tcp_pkt_info;
19272 	pdescinfo_t	*pkt_info;
19273 	int		pbuf_idx, pbuf_idx_nxt;
19274 	int		seg_len, len, spill, af;
19275 	boolean_t	add_buffer, zcopy, clusterwide;
19276 	boolean_t	rconfirm = B_FALSE;
19277 	boolean_t	done = B_FALSE;
19278 	uint32_t	cksum;
19279 	uint32_t	hwcksum_flags;
19280 	ire_t		*ire = NULL;
19281 	ill_t		*ill;
19282 	ipha_t		*ipha;
19283 	ip6_t		*ip6h;
19284 	ipaddr_t	src, dst;
19285 	ill_zerocopy_capab_t *zc_cap = NULL;
19286 	uint16_t	*up;
19287 	int		err;
19288 	conn_t		*connp;
19289 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19290 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19291 	int		usable_mmd, tail_unsent_mmd;
19292 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19293 	mblk_t		*xmit_tail_mmd;
19294 	netstackid_t	stack_id;
19295 
19296 #ifdef	_BIG_ENDIAN
19297 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19298 #else
19299 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19300 #endif
19301 
19302 #define	PREP_NEW_MULTIDATA() {			\
19303 	mmd = NULL;				\
19304 	md_mp = md_hbuf = NULL;			\
19305 	cur_hdr_off = 0;			\
19306 	max_pld = tcp->tcp_mdt_max_pld;		\
19307 	pbuf_idx = pbuf_idx_nxt = -1;		\
19308 	add_buffer = B_TRUE;			\
19309 	zcopy = B_FALSE;			\
19310 }
19311 
19312 #define	PREP_NEW_PBUF() {			\
19313 	md_pbuf = md_pbuf_nxt = NULL;		\
19314 	pbuf_idx = pbuf_idx_nxt = -1;		\
19315 	cur_pld_off = 0;			\
19316 	first_snxt = *snxt;			\
19317 	ASSERT(*tail_unsent > 0);		\
19318 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19319 }
19320 
19321 	ASSERT(mdt_thres >= mss);
19322 	ASSERT(*usable > 0 && *usable > mdt_thres);
19323 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19324 	ASSERT(!TCP_IS_DETACHED(tcp));
19325 	ASSERT(tcp->tcp_valid_bits == 0 ||
19326 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19327 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19328 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19329 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19330 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19331 
19332 	connp = tcp->tcp_connp;
19333 	ASSERT(connp != NULL);
19334 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19335 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19336 
19337 	stack_id = connp->conn_netstack->netstack_stackid;
19338 
19339 	usable_mmd = tail_unsent_mmd = 0;
19340 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
19341 	xmit_tail_mmd = NULL;
19342 	/*
19343 	 * Note that tcp will only declare at most 2 payload spans per
19344 	 * packet, which is much lower than the maximum allowable number
19345 	 * of packet spans per Multidata.  For this reason, we use the
19346 	 * privately declared and smaller descriptor info structure, in
19347 	 * order to save some stack space.
19348 	 */
19349 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19350 
19351 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19352 	if (af == AF_INET) {
19353 		dst = tcp->tcp_ipha->ipha_dst;
19354 		src = tcp->tcp_ipha->ipha_src;
19355 		ASSERT(!CLASSD(dst));
19356 	}
19357 	ASSERT(af == AF_INET ||
19358 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19359 
19360 	obsegs = obbytes = 0;
19361 	num_burst_seg = tcp->tcp_snd_burst;
19362 	md_mp_head = NULL;
19363 	PREP_NEW_MULTIDATA();
19364 
19365 	/*
19366 	 * Before we go on further, make sure there is an IRE that we can
19367 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19368 	 * in proceeding any further, and we should just hand everything
19369 	 * off to the legacy path.
19370 	 */
19371 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19372 		goto legacy_send_no_md;
19373 
19374 	ASSERT(ire != NULL);
19375 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19376 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19377 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19378 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19379 	/*
19380 	 * If we do support loopback for MDT (which requires modifications
19381 	 * to the receiving paths), the following assertions should go away,
19382 	 * and we would be sending the Multidata to loopback conn later on.
19383 	 */
19384 	ASSERT(!IRE_IS_LOCAL(ire));
19385 	ASSERT(ire->ire_stq != NULL);
19386 
19387 	ill = ire_to_ill(ire);
19388 	ASSERT(ill != NULL);
19389 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19390 
19391 	if (!tcp->tcp_ire_ill_check_done) {
19392 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19393 		tcp->tcp_ire_ill_check_done = B_TRUE;
19394 	}
19395 
19396 	/*
19397 	 * If the underlying interface conditions have changed, or if the
19398 	 * new interface does not support MDT, go back to legacy path.
19399 	 */
19400 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19401 		/* don't go through this path anymore for this connection */
19402 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19403 		tcp->tcp_mdt = B_FALSE;
19404 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19405 		    "interface %s\n", (void *)connp, ill->ill_name));
19406 		/* IRE will be released prior to returning */
19407 		goto legacy_send_no_md;
19408 	}
19409 
19410 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19411 		zc_cap = ill->ill_zerocopy_capab;
19412 
19413 	/*
19414 	 * Check if we can take tcp fast-path. Note that "incomplete"
19415 	 * ire's (where the link-layer for next hop is not resolved
19416 	 * or where the fast-path header in nce_fp_mp is not available
19417 	 * yet) are sent down the legacy (slow) path.
19418 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19419 	 */
19420 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19421 		/* IRE will be released prior to returning */
19422 		goto legacy_send_no_md;
19423 	}
19424 
19425 	/* go to legacy path if interface doesn't support zerocopy */
19426 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19427 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19428 		/* IRE will be released prior to returning */
19429 		goto legacy_send_no_md;
19430 	}
19431 
19432 	/* does the interface support hardware checksum offload? */
19433 	hwcksum_flags = 0;
19434 	if (ILL_HCKSUM_CAPABLE(ill) &&
19435 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19436 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19437 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19438 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19439 		    HCKSUM_IPHDRCKSUM)
19440 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19441 
19442 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19443 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19444 			hwcksum_flags |= HCK_FULLCKSUM;
19445 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19446 		    HCKSUM_INET_PARTIAL)
19447 			hwcksum_flags |= HCK_PARTIALCKSUM;
19448 	}
19449 
19450 	/*
19451 	 * Each header fragment consists of the leading extra space,
19452 	 * followed by the TCP/IP header, and the trailing extra space.
19453 	 * We make sure that each header fragment begins on a 32-bit
19454 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19455 	 * aligned in tcp_mdt_update).
19456 	 */
19457 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19458 	    tcp->tcp_mdt_hdr_tail), 4);
19459 
19460 	/* are we starting from the beginning of data block? */
19461 	if (*tail_unsent == 0) {
19462 		*xmit_tail = (*xmit_tail)->b_cont;
19463 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19464 		*tail_unsent = (int)MBLKL(*xmit_tail);
19465 	}
19466 
19467 	/*
19468 	 * Here we create one or more Multidata messages, each made up of
19469 	 * one header buffer and up to N payload buffers.  This entire
19470 	 * operation is done within two loops:
19471 	 *
19472 	 * The outer loop mostly deals with creating the Multidata message,
19473 	 * as well as the header buffer that gets added to it.  It also
19474 	 * links the Multidata messages together such that all of them can
19475 	 * be sent down to the lower layer in a single putnext call; this
19476 	 * linking behavior depends on the tcp_mdt_chain tunable.
19477 	 *
19478 	 * The inner loop takes an existing Multidata message, and adds
19479 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19480 	 * packetizes those buffers by filling up the corresponding header
19481 	 * buffer fragments with the proper IP and TCP headers, and by
19482 	 * describing the layout of each packet in the packet descriptors
19483 	 * that get added to the Multidata.
19484 	 */
19485 	do {
19486 		/*
19487 		 * If usable send window is too small, or data blocks in
19488 		 * transmit list are smaller than our threshold (i.e. app
19489 		 * performs large writes followed by small ones), we hand
19490 		 * off the control over to the legacy path.  Note that we'll
19491 		 * get back the control once it encounters a large block.
19492 		 */
19493 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19494 		    (*xmit_tail)->b_cont != NULL &&
19495 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19496 			/* send down what we've got so far */
19497 			if (md_mp_head != NULL) {
19498 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19499 				    obsegs, obbytes, &rconfirm);
19500 			}
19501 			/*
19502 			 * Pass control over to tcp_send(), but tell it to
19503 			 * return to us once a large-size transmission is
19504 			 * possible.
19505 			 */
19506 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19507 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19508 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19509 			    tail_unsent, xmit_tail, local_time,
19510 			    mdt_thres)) <= 0) {
19511 				/* burst count reached, or alloc failed */
19512 				IRE_REFRELE(ire);
19513 				return (err);
19514 			}
19515 
19516 			/* tcp_send() may have sent everything, so check */
19517 			if (*usable <= 0) {
19518 				IRE_REFRELE(ire);
19519 				return (0);
19520 			}
19521 
19522 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19523 			/*
19524 			 * We may have delivered the Multidata, so make sure
19525 			 * to re-initialize before the next round.
19526 			 */
19527 			md_mp_head = NULL;
19528 			obsegs = obbytes = 0;
19529 			num_burst_seg = tcp->tcp_snd_burst;
19530 			PREP_NEW_MULTIDATA();
19531 
19532 			/* are we starting from the beginning of data block? */
19533 			if (*tail_unsent == 0) {
19534 				*xmit_tail = (*xmit_tail)->b_cont;
19535 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19536 				    (uintptr_t)INT_MAX);
19537 				*tail_unsent = (int)MBLKL(*xmit_tail);
19538 			}
19539 		}
19540 		/*
19541 		 * Record current values for parameters we may need to pass
19542 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
19543 		 * each iteration of the outer loop (each multidata message
19544 		 * creation). If we have a failure in the inner loop, we send
19545 		 * any complete multidata messages we have before reverting
19546 		 * to using the traditional non-md path.
19547 		 */
19548 		snxt_mmd = *snxt;
19549 		usable_mmd = *usable;
19550 		xmit_tail_mmd = *xmit_tail;
19551 		tail_unsent_mmd = *tail_unsent;
19552 		obsegs_mmd = obsegs;
19553 		obbytes_mmd = obbytes;
19554 
19555 		/*
19556 		 * max_pld limits the number of mblks in tcp's transmit
19557 		 * queue that can be added to a Multidata message.  Once
19558 		 * this counter reaches zero, no more additional mblks
19559 		 * can be added to it.  What happens afterwards depends
19560 		 * on whether or not we are set to chain the Multidata
19561 		 * messages.  If we are to link them together, reset
19562 		 * max_pld to its original value (tcp_mdt_max_pld) and
19563 		 * prepare to create a new Multidata message which will
19564 		 * get linked to md_mp_head.  Else, leave it alone and
19565 		 * let the inner loop break on its own.
19566 		 */
19567 		if (tcp_mdt_chain && max_pld == 0)
19568 			PREP_NEW_MULTIDATA();
19569 
19570 		/* adding a payload buffer; re-initialize values */
19571 		if (add_buffer)
19572 			PREP_NEW_PBUF();
19573 
19574 		/*
19575 		 * If we don't have a Multidata, either because we just
19576 		 * (re)entered this outer loop, or after we branched off
19577 		 * to tcp_send above, setup the Multidata and header
19578 		 * buffer to be used.
19579 		 */
19580 		if (md_mp == NULL) {
19581 			int md_hbuflen;
19582 			uint32_t start, stuff;
19583 
19584 			/*
19585 			 * Calculate Multidata header buffer size large enough
19586 			 * to hold all of the headers that can possibly be
19587 			 * sent at this moment.  We'd rather over-estimate
19588 			 * the size than running out of space; this is okay
19589 			 * since this buffer is small anyway.
19590 			 */
19591 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19592 
19593 			/*
19594 			 * Start and stuff offset for partial hardware
19595 			 * checksum offload; these are currently for IPv4.
19596 			 * For full checksum offload, they are set to zero.
19597 			 */
19598 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19599 				if (af == AF_INET) {
19600 					start = IP_SIMPLE_HDR_LENGTH;
19601 					stuff = IP_SIMPLE_HDR_LENGTH +
19602 					    TCP_CHECKSUM_OFFSET;
19603 				} else {
19604 					start = IPV6_HDR_LEN;
19605 					stuff = IPV6_HDR_LEN +
19606 					    TCP_CHECKSUM_OFFSET;
19607 				}
19608 			} else {
19609 				start = stuff = 0;
19610 			}
19611 
19612 			/*
19613 			 * Create the header buffer, Multidata, as well as
19614 			 * any necessary attributes (destination address,
19615 			 * SAP and hardware checksum offload) that should
19616 			 * be associated with the Multidata message.
19617 			 */
19618 			ASSERT(cur_hdr_off == 0);
19619 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19620 			    ((md_hbuf->b_wptr += md_hbuflen),
19621 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19622 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19623 			    /* fastpath mblk */
19624 			    ire->ire_nce->nce_res_mp,
19625 			    /* hardware checksum enabled */
19626 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19627 			    /* hardware checksum offsets */
19628 			    start, stuff, 0,
19629 			    /* hardware checksum flag */
19630 			    hwcksum_flags, tcps) != 0)) {
19631 legacy_send:
19632 				/*
19633 				 * We arrive here from a failure within the
19634 				 * inner (packetizer) loop or we fail one of
19635 				 * the conditionals above. We restore the
19636 				 * previously checkpointed values for:
19637 				 *    xmit_tail
19638 				 *    usable
19639 				 *    tail_unsent
19640 				 *    snxt
19641 				 *    obbytes
19642 				 *    obsegs
19643 				 * We should then be able to dispatch any
19644 				 * complete multidata before reverting to the
19645 				 * traditional path with consistent parameters
19646 				 * (the inner loop updates these as it
19647 				 * iterates).
19648 				 */
19649 				*xmit_tail = xmit_tail_mmd;
19650 				*usable = usable_mmd;
19651 				*tail_unsent = tail_unsent_mmd;
19652 				*snxt = snxt_mmd;
19653 				obbytes = obbytes_mmd;
19654 				obsegs = obsegs_mmd;
19655 				if (md_mp != NULL) {
19656 					/* Unlink message from the chain */
19657 					if (md_mp_head != NULL) {
19658 						err = (intptr_t)rmvb(md_mp_head,
19659 						    md_mp);
19660 						/*
19661 						 * We can't assert that rmvb
19662 						 * did not return -1, since we
19663 						 * may get here before linkb
19664 						 * happens.  We do, however,
19665 						 * check if we just removed the
19666 						 * only element in the list.
19667 						 */
19668 						if (err == 0)
19669 							md_mp_head = NULL;
19670 					}
19671 					/* md_hbuf gets freed automatically */
19672 					TCP_STAT(tcps, tcp_mdt_discarded);
19673 					freeb(md_mp);
19674 				} else {
19675 					/* Either allocb or mmd_alloc failed */
19676 					TCP_STAT(tcps, tcp_mdt_allocfail);
19677 					if (md_hbuf != NULL)
19678 						freeb(md_hbuf);
19679 				}
19680 
19681 				/* send down what we've got so far */
19682 				if (md_mp_head != NULL) {
19683 					tcp_multisend_data(tcp, ire, ill,
19684 					    md_mp_head, obsegs, obbytes,
19685 					    &rconfirm);
19686 				}
19687 legacy_send_no_md:
19688 				if (ire != NULL)
19689 					IRE_REFRELE(ire);
19690 				/*
19691 				 * Too bad; let the legacy path handle this.
19692 				 * We specify INT_MAX for the threshold, since
19693 				 * we gave up with the Multidata processings
19694 				 * and let the old path have it all.
19695 				 */
19696 				TCP_STAT(tcps, tcp_mdt_legacy_all);
19697 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19698 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19699 				    snxt, tail_unsent, xmit_tail, local_time,
19700 				    INT_MAX));
19701 			}
19702 
19703 			/* link to any existing ones, if applicable */
19704 			TCP_STAT(tcps, tcp_mdt_allocd);
19705 			if (md_mp_head == NULL) {
19706 				md_mp_head = md_mp;
19707 			} else if (tcp_mdt_chain) {
19708 				TCP_STAT(tcps, tcp_mdt_linked);
19709 				linkb(md_mp_head, md_mp);
19710 			}
19711 		}
19712 
19713 		ASSERT(md_mp_head != NULL);
19714 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19715 		ASSERT(md_mp != NULL && mmd != NULL);
19716 		ASSERT(md_hbuf != NULL);
19717 
19718 		/*
19719 		 * Packetize the transmittable portion of the data block;
19720 		 * each data block is essentially added to the Multidata
19721 		 * as a payload buffer.  We also deal with adding more
19722 		 * than one payload buffers, which happens when the remaining
19723 		 * packetized portion of the current payload buffer is less
19724 		 * than MSS, while the next data block in transmit queue
19725 		 * has enough data to make up for one.  This "spillover"
19726 		 * case essentially creates a split-packet, where portions
19727 		 * of the packet's payload fragments may span across two
19728 		 * virtually discontiguous address blocks.
19729 		 */
19730 		seg_len = mss;
19731 		do {
19732 			len = seg_len;
19733 
19734 			/* one must remain NULL for DTRACE_IP_FASTPATH */
19735 			ipha = NULL;
19736 			ip6h = NULL;
19737 
19738 			ASSERT(len > 0);
19739 			ASSERT(max_pld >= 0);
19740 			ASSERT(!add_buffer || cur_pld_off == 0);
19741 
19742 			/*
19743 			 * First time around for this payload buffer; note
19744 			 * in the case of a spillover, the following has
19745 			 * been done prior to adding the split-packet
19746 			 * descriptor to Multidata, and we don't want to
19747 			 * repeat the process.
19748 			 */
19749 			if (add_buffer) {
19750 				ASSERT(mmd != NULL);
19751 				ASSERT(md_pbuf == NULL);
19752 				ASSERT(md_pbuf_nxt == NULL);
19753 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19754 
19755 				/*
19756 				 * Have we reached the limit?  We'd get to
19757 				 * this case when we're not chaining the
19758 				 * Multidata messages together, and since
19759 				 * we're done, terminate this loop.
19760 				 */
19761 				if (max_pld == 0)
19762 					break; /* done */
19763 
19764 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19765 					TCP_STAT(tcps, tcp_mdt_allocfail);
19766 					goto legacy_send; /* out_of_mem */
19767 				}
19768 
19769 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19770 				    zc_cap != NULL) {
19771 					if (!ip_md_zcopy_attr(mmd, NULL,
19772 					    zc_cap->ill_zerocopy_flags)) {
19773 						freeb(md_pbuf);
19774 						TCP_STAT(tcps,
19775 						    tcp_mdt_allocfail);
19776 						/* out_of_mem */
19777 						goto legacy_send;
19778 					}
19779 					zcopy = B_TRUE;
19780 				}
19781 
19782 				md_pbuf->b_rptr += base_pld_off;
19783 
19784 				/*
19785 				 * Add a payload buffer to the Multidata; this
19786 				 * operation must not fail, or otherwise our
19787 				 * logic in this routine is broken.  There
19788 				 * is no memory allocation done by the
19789 				 * routine, so any returned failure simply
19790 				 * tells us that we've done something wrong.
19791 				 *
19792 				 * A failure tells us that either we're adding
19793 				 * the same payload buffer more than once, or
19794 				 * we're trying to add more buffers than
19795 				 * allowed (max_pld calculation is wrong).
19796 				 * None of the above cases should happen, and
19797 				 * we panic because either there's horrible
19798 				 * heap corruption, and/or programming mistake.
19799 				 */
19800 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19801 				if (pbuf_idx < 0) {
19802 					cmn_err(CE_PANIC, "tcp_multisend: "
19803 					    "payload buffer logic error "
19804 					    "detected for tcp %p mmd %p "
19805 					    "pbuf %p (%d)\n",
19806 					    (void *)tcp, (void *)mmd,
19807 					    (void *)md_pbuf, pbuf_idx);
19808 				}
19809 
19810 				ASSERT(max_pld > 0);
19811 				--max_pld;
19812 				add_buffer = B_FALSE;
19813 			}
19814 
19815 			ASSERT(md_mp_head != NULL);
19816 			ASSERT(md_pbuf != NULL);
19817 			ASSERT(md_pbuf_nxt == NULL);
19818 			ASSERT(pbuf_idx != -1);
19819 			ASSERT(pbuf_idx_nxt == -1);
19820 			ASSERT(*usable > 0);
19821 
19822 			/*
19823 			 * We spillover to the next payload buffer only
19824 			 * if all of the following is true:
19825 			 *
19826 			 *   1. There is not enough data on the current
19827 			 *	payload buffer to make up `len',
19828 			 *   2. We are allowed to send `len',
19829 			 *   3. The next payload buffer length is large
19830 			 *	enough to accomodate `spill'.
19831 			 */
19832 			if ((spill = len - *tail_unsent) > 0 &&
19833 			    *usable >= len &&
19834 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19835 			    max_pld > 0) {
19836 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19837 				if (md_pbuf_nxt == NULL) {
19838 					TCP_STAT(tcps, tcp_mdt_allocfail);
19839 					goto legacy_send; /* out_of_mem */
19840 				}
19841 
19842 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19843 				    zc_cap != NULL) {
19844 					if (!ip_md_zcopy_attr(mmd, NULL,
19845 					    zc_cap->ill_zerocopy_flags)) {
19846 						freeb(md_pbuf_nxt);
19847 						TCP_STAT(tcps,
19848 						    tcp_mdt_allocfail);
19849 						/* out_of_mem */
19850 						goto legacy_send;
19851 					}
19852 					zcopy = B_TRUE;
19853 				}
19854 
19855 				/*
19856 				 * See comments above on the first call to
19857 				 * mmd_addpldbuf for explanation on the panic.
19858 				 */
19859 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19860 				if (pbuf_idx_nxt < 0) {
19861 					panic("tcp_multisend: "
19862 					    "next payload buffer logic error "
19863 					    "detected for tcp %p mmd %p "
19864 					    "pbuf %p (%d)\n",
19865 					    (void *)tcp, (void *)mmd,
19866 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19867 				}
19868 
19869 				ASSERT(max_pld > 0);
19870 				--max_pld;
19871 			} else if (spill > 0) {
19872 				/*
19873 				 * If there's a spillover, but the following
19874 				 * xmit_tail couldn't give us enough octets
19875 				 * to reach "len", then stop the current
19876 				 * Multidata creation and let the legacy
19877 				 * tcp_send() path take over.  We don't want
19878 				 * to send the tiny segment as part of this
19879 				 * Multidata for performance reasons; instead,
19880 				 * we let the legacy path deal with grouping
19881 				 * it with the subsequent small mblks.
19882 				 */
19883 				if (*usable >= len &&
19884 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19885 					max_pld = 0;
19886 					break;	/* done */
19887 				}
19888 
19889 				/*
19890 				 * We can't spillover, and we are near
19891 				 * the end of the current payload buffer,
19892 				 * so send what's left.
19893 				 */
19894 				ASSERT(*tail_unsent > 0);
19895 				len = *tail_unsent;
19896 			}
19897 
19898 			/* tail_unsent is negated if there is a spillover */
19899 			*tail_unsent -= len;
19900 			*usable -= len;
19901 			ASSERT(*usable >= 0);
19902 
19903 			if (*usable < mss)
19904 				seg_len = *usable;
19905 			/*
19906 			 * Sender SWS avoidance; see comments in tcp_send();
19907 			 * everything else is the same, except that we only
19908 			 * do this here if there is no more data to be sent
19909 			 * following the current xmit_tail.  We don't check
19910 			 * for 1-byte urgent data because we shouldn't get
19911 			 * here if TCP_URG_VALID is set.
19912 			 */
19913 			if (*usable > 0 && *usable < mss &&
19914 			    ((md_pbuf_nxt == NULL &&
19915 			    (*xmit_tail)->b_cont == NULL) ||
19916 			    (md_pbuf_nxt != NULL &&
19917 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19918 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19919 			    (tcp->tcp_unsent -
19920 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19921 			    !tcp->tcp_zero_win_probe) {
19922 				if ((*snxt + len) == tcp->tcp_snxt &&
19923 				    (*snxt + len) == tcp->tcp_suna) {
19924 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19925 				}
19926 				done = B_TRUE;
19927 			}
19928 
19929 			/*
19930 			 * Prime pump for IP's checksumming on our behalf;
19931 			 * include the adjustment for a source route if any.
19932 			 * Do this only for software/partial hardware checksum
19933 			 * offload, as this field gets zeroed out later for
19934 			 * the full hardware checksum offload case.
19935 			 */
19936 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19937 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19938 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19939 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19940 			}
19941 
19942 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19943 			*snxt += len;
19944 
19945 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19946 			/*
19947 			 * We set the PUSH bit only if TCP has no more buffered
19948 			 * data to be transmitted (or if sender SWS avoidance
19949 			 * takes place), as opposed to setting it for every
19950 			 * last packet in the burst.
19951 			 */
19952 			if (done ||
19953 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19954 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19955 
19956 			/*
19957 			 * Set FIN bit if this is our last segment; snxt
19958 			 * already includes its length, and it will not
19959 			 * be adjusted after this point.
19960 			 */
19961 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19962 			    *snxt == tcp->tcp_fss) {
19963 				if (!tcp->tcp_fin_acked) {
19964 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19965 					BUMP_MIB(&tcps->tcps_mib,
19966 					    tcpOutControl);
19967 				}
19968 				if (!tcp->tcp_fin_sent) {
19969 					tcp->tcp_fin_sent = B_TRUE;
19970 					/*
19971 					 * tcp state must be ESTABLISHED
19972 					 * in order for us to get here in
19973 					 * the first place.
19974 					 */
19975 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19976 
19977 					/*
19978 					 * Upon returning from this routine,
19979 					 * tcp_wput_data() will set tcp_snxt
19980 					 * to be equal to snxt + tcp_fin_sent.
19981 					 * This is essentially the same as
19982 					 * setting it to tcp_fss + 1.
19983 					 */
19984 				}
19985 			}
19986 
19987 			tcp->tcp_last_sent_len = (ushort_t)len;
19988 
19989 			len += tcp_hdr_len;
19990 			if (tcp->tcp_ipversion == IPV4_VERSION)
19991 				tcp->tcp_ipha->ipha_length = htons(len);
19992 			else
19993 				tcp->tcp_ip6h->ip6_plen = htons(len -
19994 				    ((char *)&tcp->tcp_ip6h[1] -
19995 				    tcp->tcp_iphc));
19996 
19997 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19998 
19999 			/* setup header fragment */
20000 			PDESC_HDR_ADD(pkt_info,
20001 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20002 			    tcp->tcp_mdt_hdr_head,		/* head room */
20003 			    tcp_hdr_len,			/* len */
20004 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20005 
20006 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20007 			    hdr_frag_sz);
20008 			ASSERT(MBLKIN(md_hbuf,
20009 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20010 			    PDESC_HDRSIZE(pkt_info)));
20011 
20012 			/* setup first payload fragment */
20013 			PDESC_PLD_INIT(pkt_info);
20014 			PDESC_PLD_SPAN_ADD(pkt_info,
20015 			    pbuf_idx,				/* index */
20016 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20017 			    tcp->tcp_last_sent_len);		/* len */
20018 
20019 			/* create a split-packet in case of a spillover */
20020 			if (md_pbuf_nxt != NULL) {
20021 				ASSERT(spill > 0);
20022 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20023 				ASSERT(!add_buffer);
20024 
20025 				md_pbuf = md_pbuf_nxt;
20026 				md_pbuf_nxt = NULL;
20027 				pbuf_idx = pbuf_idx_nxt;
20028 				pbuf_idx_nxt = -1;
20029 				cur_pld_off = spill;
20030 
20031 				/* trim out first payload fragment */
20032 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20033 
20034 				/* setup second payload fragment */
20035 				PDESC_PLD_SPAN_ADD(pkt_info,
20036 				    pbuf_idx,			/* index */
20037 				    md_pbuf->b_rptr,		/* start */
20038 				    spill);			/* len */
20039 
20040 				if ((*xmit_tail)->b_next == NULL) {
20041 					/*
20042 					 * Store the lbolt used for RTT
20043 					 * estimation. We can only record one
20044 					 * timestamp per mblk so we do it when
20045 					 * we reach the end of the payload
20046 					 * buffer.  Also we only take a new
20047 					 * timestamp sample when the previous
20048 					 * timed data from the same mblk has
20049 					 * been ack'ed.
20050 					 */
20051 					(*xmit_tail)->b_prev = local_time;
20052 					(*xmit_tail)->b_next =
20053 					    (mblk_t *)(uintptr_t)first_snxt;
20054 				}
20055 
20056 				first_snxt = *snxt - spill;
20057 
20058 				/*
20059 				 * Advance xmit_tail; usable could be 0 by
20060 				 * the time we got here, but we made sure
20061 				 * above that we would only spillover to
20062 				 * the next data block if usable includes
20063 				 * the spilled-over amount prior to the
20064 				 * subtraction.  Therefore, we are sure
20065 				 * that xmit_tail->b_cont can't be NULL.
20066 				 */
20067 				ASSERT((*xmit_tail)->b_cont != NULL);
20068 				*xmit_tail = (*xmit_tail)->b_cont;
20069 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20070 				    (uintptr_t)INT_MAX);
20071 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20072 			} else {
20073 				cur_pld_off += tcp->tcp_last_sent_len;
20074 			}
20075 
20076 			/*
20077 			 * Fill in the header using the template header, and
20078 			 * add options such as time-stamp, ECN and/or SACK,
20079 			 * as needed.
20080 			 */
20081 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20082 			    (clock_t)local_time, num_sack_blk);
20083 
20084 			/* take care of some IP header businesses */
20085 			if (af == AF_INET) {
20086 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20087 
20088 				ASSERT(OK_32PTR((uchar_t *)ipha));
20089 				ASSERT(PDESC_HDRL(pkt_info) >=
20090 				    IP_SIMPLE_HDR_LENGTH);
20091 				ASSERT(ipha->ipha_version_and_hdr_length ==
20092 				    IP_SIMPLE_HDR_VERSION);
20093 
20094 				/*
20095 				 * Assign ident value for current packet; see
20096 				 * related comments in ip_wput_ire() about the
20097 				 * contract private interface with clustering
20098 				 * group.
20099 				 */
20100 				clusterwide = B_FALSE;
20101 				if (cl_inet_ipident != NULL) {
20102 					ASSERT(cl_inet_isclusterwide != NULL);
20103 					if ((*cl_inet_isclusterwide)(stack_id,
20104 					    IPPROTO_IP, AF_INET,
20105 					    (uint8_t *)(uintptr_t)src, NULL)) {
20106 						ipha->ipha_ident =
20107 						    (*cl_inet_ipident)(stack_id,
20108 						    IPPROTO_IP, AF_INET,
20109 						    (uint8_t *)(uintptr_t)src,
20110 						    (uint8_t *)(uintptr_t)dst,
20111 						    NULL);
20112 						clusterwide = B_TRUE;
20113 					}
20114 				}
20115 
20116 				if (!clusterwide) {
20117 					ipha->ipha_ident = (uint16_t)
20118 					    atomic_add_32_nv(
20119 						&ire->ire_ident, 1);
20120 				}
20121 #ifndef _BIG_ENDIAN
20122 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20123 				    (ipha->ipha_ident >> 8);
20124 #endif
20125 			} else {
20126 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20127 
20128 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20129 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20130 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20131 				ASSERT(PDESC_HDRL(pkt_info) >=
20132 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20133 				    TCP_CHECKSUM_SIZE));
20134 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20135 
20136 				if (tcp->tcp_ip_forward_progress) {
20137 					rconfirm = B_TRUE;
20138 					tcp->tcp_ip_forward_progress = B_FALSE;
20139 				}
20140 			}
20141 
20142 			/* at least one payload span, and at most two */
20143 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20144 
20145 			/* add the packet descriptor to Multidata */
20146 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20147 			    KM_NOSLEEP)) == NULL) {
20148 				/*
20149 				 * Any failure other than ENOMEM indicates
20150 				 * that we have passed in invalid pkt_info
20151 				 * or parameters to mmd_addpdesc, which must
20152 				 * not happen.
20153 				 *
20154 				 * EINVAL is a result of failure on boundary
20155 				 * checks against the pkt_info contents.  It
20156 				 * should not happen, and we panic because
20157 				 * either there's horrible heap corruption,
20158 				 * and/or programming mistake.
20159 				 */
20160 				if (err != ENOMEM) {
20161 					cmn_err(CE_PANIC, "tcp_multisend: "
20162 					    "pdesc logic error detected for "
20163 					    "tcp %p mmd %p pinfo %p (%d)\n",
20164 					    (void *)tcp, (void *)mmd,
20165 					    (void *)pkt_info, err);
20166 				}
20167 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20168 				goto legacy_send; /* out_of_mem */
20169 			}
20170 			ASSERT(pkt != NULL);
20171 
20172 			/* calculate IP header and TCP checksums */
20173 			if (af == AF_INET) {
20174 				/* calculate pseudo-header checksum */
20175 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20176 				    (src >> 16) + (src & 0xFFFF);
20177 
20178 				/* offset for TCP header checksum */
20179 				up = IPH_TCPH_CHECKSUMP(ipha,
20180 				    IP_SIMPLE_HDR_LENGTH);
20181 			} else {
20182 				up = (uint16_t *)&ip6h->ip6_src;
20183 
20184 				/* calculate pseudo-header checksum */
20185 				cksum = up[0] + up[1] + up[2] + up[3] +
20186 				    up[4] + up[5] + up[6] + up[7] +
20187 				    up[8] + up[9] + up[10] + up[11] +
20188 				    up[12] + up[13] + up[14] + up[15];
20189 
20190 				/* Fold the initial sum */
20191 				cksum = (cksum & 0xffff) + (cksum >> 16);
20192 
20193 				up = (uint16_t *)(((uchar_t *)ip6h) +
20194 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20195 			}
20196 
20197 			if (hwcksum_flags & HCK_FULLCKSUM) {
20198 				/* clear checksum field for hardware */
20199 				*up = 0;
20200 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20201 				uint32_t sum;
20202 
20203 				/* pseudo-header checksumming */
20204 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20205 				sum = (sum & 0xFFFF) + (sum >> 16);
20206 				*up = (sum & 0xFFFF) + (sum >> 16);
20207 			} else {
20208 				/* software checksumming */
20209 				TCP_STAT(tcps, tcp_out_sw_cksum);
20210 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20211 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20212 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20213 				    cksum + IP_TCP_CSUM_COMP);
20214 				if (*up == 0)
20215 					*up = 0xFFFF;
20216 			}
20217 
20218 			/* IPv4 header checksum */
20219 			if (af == AF_INET) {
20220 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20221 					ipha->ipha_hdr_checksum = 0;
20222 				} else {
20223 					IP_HDR_CKSUM(ipha, cksum,
20224 					    ((uint32_t *)ipha)[0],
20225 					    ((uint16_t *)ipha)[4]);
20226 				}
20227 			}
20228 
20229 			if (af == AF_INET &&
20230 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20231 			    af == AF_INET6 &&
20232 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20233 				mblk_t	*mp, *mp1;
20234 				uchar_t	*hdr_rptr, *hdr_wptr;
20235 				uchar_t	*pld_rptr, *pld_wptr;
20236 
20237 				/*
20238 				 * We reconstruct a pseudo packet for the hooks
20239 				 * framework using mmd_transform_link().
20240 				 * If it is a split packet we pullup the
20241 				 * payload. FW_HOOKS expects a pkt comprising
20242 				 * of two mblks: a header and the payload.
20243 				 */
20244 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20245 					TCP_STAT(tcps, tcp_mdt_allocfail);
20246 					goto legacy_send;
20247 				}
20248 
20249 				if (pkt_info->pld_cnt > 1) {
20250 					/* split payload, more than one pld */
20251 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20252 					    NULL) {
20253 						freemsg(mp);
20254 						TCP_STAT(tcps,
20255 						    tcp_mdt_allocfail);
20256 						goto legacy_send;
20257 					}
20258 					freemsg(mp->b_cont);
20259 					mp->b_cont = mp1;
20260 				} else {
20261 					mp1 = mp->b_cont;
20262 				}
20263 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20264 
20265 				/*
20266 				 * Remember the message offsets. This is so we
20267 				 * can detect changes when we return from the
20268 				 * FW_HOOKS callbacks.
20269 				 */
20270 				hdr_rptr = mp->b_rptr;
20271 				hdr_wptr = mp->b_wptr;
20272 				pld_rptr = mp->b_cont->b_rptr;
20273 				pld_wptr = mp->b_cont->b_wptr;
20274 
20275 				if (af == AF_INET) {
20276 					DTRACE_PROBE4(
20277 					    ip4__physical__out__start,
20278 					    ill_t *, NULL,
20279 					    ill_t *, ill,
20280 					    ipha_t *, ipha,
20281 					    mblk_t *, mp);
20282 					FW_HOOKS(
20283 					    ipst->ips_ip4_physical_out_event,
20284 					    ipst->ips_ipv4firewall_physical_out,
20285 					    NULL, ill, ipha, mp, mp, 0, ipst);
20286 					DTRACE_PROBE1(
20287 					    ip4__physical__out__end,
20288 					    mblk_t *, mp);
20289 				} else {
20290 					DTRACE_PROBE4(
20291 					    ip6__physical__out_start,
20292 					    ill_t *, NULL,
20293 					    ill_t *, ill,
20294 					    ip6_t *, ip6h,
20295 					    mblk_t *, mp);
20296 					FW_HOOKS6(
20297 					    ipst->ips_ip6_physical_out_event,
20298 					    ipst->ips_ipv6firewall_physical_out,
20299 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20300 					DTRACE_PROBE1(
20301 					    ip6__physical__out__end,
20302 					    mblk_t *, mp);
20303 				}
20304 
20305 				if (mp == NULL ||
20306 				    (mp1 = mp->b_cont) == NULL ||
20307 				    mp->b_rptr != hdr_rptr ||
20308 				    mp->b_wptr != hdr_wptr ||
20309 				    mp1->b_rptr != pld_rptr ||
20310 				    mp1->b_wptr != pld_wptr ||
20311 				    mp1->b_cont != NULL) {
20312 					/*
20313 					 * We abandon multidata processing and
20314 					 * return to the normal path, either
20315 					 * when a packet is blocked, or when
20316 					 * the boundaries of header buffer or
20317 					 * payload buffer have been changed by
20318 					 * FW_HOOKS[6].
20319 					 */
20320 					if (mp != NULL)
20321 						freemsg(mp);
20322 					goto legacy_send;
20323 				}
20324 				/* Finished with the pseudo packet */
20325 				freemsg(mp);
20326 			}
20327 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
20328 			    ill, ipha, ip6h);
20329 			/* advance header offset */
20330 			cur_hdr_off += hdr_frag_sz;
20331 
20332 			obbytes += tcp->tcp_last_sent_len;
20333 			++obsegs;
20334 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20335 		    *tail_unsent > 0);
20336 
20337 		if ((*xmit_tail)->b_next == NULL) {
20338 			/*
20339 			 * Store the lbolt used for RTT estimation. We can only
20340 			 * record one timestamp per mblk so we do it when we
20341 			 * reach the end of the payload buffer. Also we only
20342 			 * take a new timestamp sample when the previous timed
20343 			 * data from the same mblk has been ack'ed.
20344 			 */
20345 			(*xmit_tail)->b_prev = local_time;
20346 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20347 		}
20348 
20349 		ASSERT(*tail_unsent >= 0);
20350 		if (*tail_unsent > 0) {
20351 			/*
20352 			 * We got here because we broke out of the above
20353 			 * loop due to of one of the following cases:
20354 			 *
20355 			 *   1. len < adjusted MSS (i.e. small),
20356 			 *   2. Sender SWS avoidance,
20357 			 *   3. max_pld is zero.
20358 			 *
20359 			 * We are done for this Multidata, so trim our
20360 			 * last payload buffer (if any) accordingly.
20361 			 */
20362 			if (md_pbuf != NULL)
20363 				md_pbuf->b_wptr -= *tail_unsent;
20364 		} else if (*usable > 0) {
20365 			*xmit_tail = (*xmit_tail)->b_cont;
20366 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20367 			    (uintptr_t)INT_MAX);
20368 			*tail_unsent = (int)MBLKL(*xmit_tail);
20369 			add_buffer = B_TRUE;
20370 		}
20371 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20372 	    (tcp_mdt_chain || max_pld > 0));
20373 
20374 	if (md_mp_head != NULL) {
20375 		/* send everything down */
20376 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20377 		    &rconfirm);
20378 	}
20379 
20380 #undef PREP_NEW_MULTIDATA
20381 #undef PREP_NEW_PBUF
20382 #undef IPVER
20383 
20384 	IRE_REFRELE(ire);
20385 	return (0);
20386 }
20387 
20388 /*
20389  * A wrapper function for sending one or more Multidata messages down to
20390  * the module below ip; this routine does not release the reference of the
20391  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20392  */
20393 static void
20394 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20395     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20396 {
20397 	uint64_t delta;
20398 	nce_t *nce;
20399 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20400 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20401 
20402 	ASSERT(ire != NULL && ill != NULL);
20403 	ASSERT(ire->ire_stq != NULL);
20404 	ASSERT(md_mp_head != NULL);
20405 	ASSERT(rconfirm != NULL);
20406 
20407 	/* adjust MIBs and IRE timestamp */
20408 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
20409 	tcp->tcp_obsegs += obsegs;
20410 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20411 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20412 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20413 
20414 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20415 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20416 	} else {
20417 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20418 	}
20419 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20420 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20421 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20422 
20423 	ire->ire_ob_pkt_count += obsegs;
20424 	if (ire->ire_ipif != NULL)
20425 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20426 	ire->ire_last_used_time = lbolt;
20427 
20428 	if (ipst->ips_ipobs_enabled) {
20429 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
20430 		pdesc_t *dl_pkt;
20431 		pdescinfo_t pinfo;
20432 		mblk_t *nmp;
20433 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
20434 
20435 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
20436 		    (dl_pkt != NULL);
20437 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
20438 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
20439 				continue;
20440 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
20441 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
20442 			freemsg(nmp);
20443 		}
20444 	}
20445 
20446 	/* send it down */
20447 	putnext(ire->ire_stq, md_mp_head);
20448 
20449 	/* we're done for TCP/IPv4 */
20450 	if (tcp->tcp_ipversion == IPV4_VERSION)
20451 		return;
20452 
20453 	nce = ire->ire_nce;
20454 
20455 	ASSERT(nce != NULL);
20456 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20457 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20458 
20459 	/* reachability confirmation? */
20460 	if (*rconfirm) {
20461 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20462 		if (nce->nce_state != ND_REACHABLE) {
20463 			mutex_enter(&nce->nce_lock);
20464 			nce->nce_state = ND_REACHABLE;
20465 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20466 			mutex_exit(&nce->nce_lock);
20467 			(void) untimeout(nce->nce_timeout_id);
20468 			if (ip_debug > 2) {
20469 				/* ip1dbg */
20470 				pr_addr_dbg("tcp_multisend_data: state "
20471 				    "for %s changed to REACHABLE\n",
20472 				    AF_INET6, &ire->ire_addr_v6);
20473 			}
20474 		}
20475 		/* reset transport reachability confirmation */
20476 		*rconfirm = B_FALSE;
20477 	}
20478 
20479 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20480 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20481 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20482 
20483 	if (delta > (uint64_t)ill->ill_reachable_time) {
20484 		mutex_enter(&nce->nce_lock);
20485 		switch (nce->nce_state) {
20486 		case ND_REACHABLE:
20487 		case ND_STALE:
20488 			/*
20489 			 * ND_REACHABLE is identical to ND_STALE in this
20490 			 * specific case. If reachable time has expired for
20491 			 * this neighbor (delta is greater than reachable
20492 			 * time), conceptually, the neighbor cache is no
20493 			 * longer in REACHABLE state, but already in STALE
20494 			 * state.  So the correct transition here is to
20495 			 * ND_DELAY.
20496 			 */
20497 			nce->nce_state = ND_DELAY;
20498 			mutex_exit(&nce->nce_lock);
20499 			NDP_RESTART_TIMER(nce,
20500 			    ipst->ips_delay_first_probe_time);
20501 			if (ip_debug > 3) {
20502 				/* ip2dbg */
20503 				pr_addr_dbg("tcp_multisend_data: state "
20504 				    "for %s changed to DELAY\n",
20505 				    AF_INET6, &ire->ire_addr_v6);
20506 			}
20507 			break;
20508 		case ND_DELAY:
20509 		case ND_PROBE:
20510 			mutex_exit(&nce->nce_lock);
20511 			/* Timers have already started */
20512 			break;
20513 		case ND_UNREACHABLE:
20514 			/*
20515 			 * ndp timer has detected that this nce is
20516 			 * unreachable and initiated deleting this nce
20517 			 * and all its associated IREs. This is a race
20518 			 * where we found the ire before it was deleted
20519 			 * and have just sent out a packet using this
20520 			 * unreachable nce.
20521 			 */
20522 			mutex_exit(&nce->nce_lock);
20523 			break;
20524 		default:
20525 			ASSERT(0);
20526 		}
20527 	}
20528 }
20529 
20530 /*
20531  * Derived from tcp_send_data().
20532  */
20533 static void
20534 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20535     int num_lso_seg)
20536 {
20537 	ipha_t		*ipha;
20538 	mblk_t		*ire_fp_mp;
20539 	uint_t		ire_fp_mp_len;
20540 	uint32_t	hcksum_txflags = 0;
20541 	ipaddr_t	src;
20542 	ipaddr_t	dst;
20543 	uint32_t	cksum;
20544 	uint16_t	*up;
20545 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20546 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20547 
20548 	ASSERT(DB_TYPE(mp) == M_DATA);
20549 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20550 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20551 	ASSERT(tcp->tcp_connp != NULL);
20552 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20553 
20554 	ipha = (ipha_t *)mp->b_rptr;
20555 	src = ipha->ipha_src;
20556 	dst = ipha->ipha_dst;
20557 
20558 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
20559 
20560 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20561 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20562 	    num_lso_seg);
20563 #ifndef _BIG_ENDIAN
20564 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20565 #endif
20566 	if (tcp->tcp_snd_zcopy_aware) {
20567 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20568 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20569 			mp = tcp_zcopy_disable(tcp, mp);
20570 	}
20571 
20572 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20573 		ASSERT(ill->ill_hcksum_capab != NULL);
20574 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20575 	}
20576 
20577 	/*
20578 	 * Since the TCP checksum should be recalculated by h/w, we can just
20579 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20580 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20581 	 * The partial pseudo-header excludes TCP length, that was calculated
20582 	 * in tcp_send(), so to zero *up before further processing.
20583 	 */
20584 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20585 
20586 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20587 	*up = 0;
20588 
20589 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20590 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20591 
20592 	/*
20593 	 * Append LSO flags and mss to the mp.
20594 	 */
20595 	lso_info_set(mp, mss, HW_LSO);
20596 
20597 	ipha->ipha_fragment_offset_and_flags |=
20598 	    (uint32_t)htons(ire->ire_frag_flag);
20599 
20600 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20601 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20602 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20603 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20604 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20605 
20606 	UPDATE_OB_PKT_COUNT(ire);
20607 	ire->ire_last_used_time = lbolt;
20608 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20609 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20610 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20611 	    ntohs(ipha->ipha_length));
20612 
20613 	DTRACE_PROBE4(ip4__physical__out__start,
20614 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
20615 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
20616 	    ipst->ips_ipv4firewall_physical_out, NULL,
20617 	    ill, ipha, mp, mp, 0, ipst);
20618 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20619 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
20620 
20621 	if (mp != NULL) {
20622 		if (ipst->ips_ipobs_enabled) {
20623 			zoneid_t szone;
20624 
20625 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
20626 			    ipst, ALL_ZONES);
20627 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
20628 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
20629 		}
20630 
20631 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
20632 	}
20633 }
20634 
20635 /*
20636  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20637  * scheme, and returns one of the following:
20638  *
20639  * -1 = failed allocation.
20640  *  0 = success; burst count reached, or usable send window is too small,
20641  *      and that we'd rather wait until later before sending again.
20642  *  1 = success; we are called from tcp_multisend(), and both usable send
20643  *      window and tail_unsent are greater than the MDT threshold, and thus
20644  *      Multidata Transmit should be used instead.
20645  */
20646 static int
20647 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20648     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20649     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20650     const int mdt_thres)
20651 {
20652 	int num_burst_seg = tcp->tcp_snd_burst;
20653 	ire_t		*ire = NULL;
20654 	ill_t		*ill = NULL;
20655 	mblk_t		*ire_fp_mp = NULL;
20656 	uint_t		ire_fp_mp_len = 0;
20657 	int		num_lso_seg = 1;
20658 	uint_t		lso_usable;
20659 	boolean_t	do_lso_send = B_FALSE;
20660 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20661 
20662 	/*
20663 	 * Check LSO capability before any further work. And the similar check
20664 	 * need to be done in for(;;) loop.
20665 	 * LSO will be deployed when therer is more than one mss of available
20666 	 * data and a burst transmission is allowed.
20667 	 */
20668 	if (tcp->tcp_lso &&
20669 	    (tcp->tcp_valid_bits == 0 ||
20670 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20671 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20672 		/*
20673 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20674 		 * Double check LSO usability before going further, since the
20675 		 * underlying interface could have been changed. In case of any
20676 		 * change of LSO capability, set tcp_ire_ill_check_done to
20677 		 * B_FALSE to force to check the ILL with the next send.
20678 		 */
20679 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
20680 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
20681 			/*
20682 			 * Enable LSO with this transmission.
20683 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
20684 			 * IRE_REFRELE(ire) should be called before return.
20685 			 */
20686 			do_lso_send = B_TRUE;
20687 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
20688 			ire_fp_mp_len = MBLKL(ire_fp_mp);
20689 			/* Round up to multiple of 4 */
20690 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
20691 		} else {
20692 			tcp->tcp_lso = B_FALSE;
20693 			tcp->tcp_ire_ill_check_done = B_FALSE;
20694 			do_lso_send = B_FALSE;
20695 			ill = NULL;
20696 		}
20697 	}
20698 
20699 	for (;;) {
20700 		struct datab	*db;
20701 		tcph_t		*tcph;
20702 		uint32_t	sum;
20703 		mblk_t		*mp, *mp1;
20704 		uchar_t		*rptr;
20705 		int		len;
20706 
20707 		/*
20708 		 * If we're called by tcp_multisend(), and the amount of
20709 		 * sendable data as well as the size of current xmit_tail
20710 		 * is beyond the MDT threshold, return to the caller and
20711 		 * let the large data transmit be done using MDT.
20712 		 */
20713 		if (*usable > 0 && *usable > mdt_thres &&
20714 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20715 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20716 			ASSERT(tcp->tcp_mdt);
20717 			return (1);	/* success; do large send */
20718 		}
20719 
20720 		if (num_burst_seg == 0)
20721 			break;		/* success; burst count reached */
20722 
20723 		/*
20724 		 * Calculate the maximum payload length we can send in *one*
20725 		 * time.
20726 		 */
20727 		if (do_lso_send) {
20728 			/*
20729 			 * Check whether need to do LSO any more.
20730 			 */
20731 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20732 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
20733 				lso_usable = MIN(lso_usable,
20734 				    num_burst_seg * mss);
20735 
20736 				num_lso_seg = lso_usable / mss;
20737 				if (lso_usable % mss) {
20738 					num_lso_seg++;
20739 					tcp->tcp_last_sent_len = (ushort_t)
20740 					    (lso_usable % mss);
20741 				} else {
20742 					tcp->tcp_last_sent_len = (ushort_t)mss;
20743 				}
20744 			} else {
20745 				do_lso_send = B_FALSE;
20746 				num_lso_seg = 1;
20747 				lso_usable = mss;
20748 			}
20749 		}
20750 
20751 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
20752 
20753 		/*
20754 		 * Adjust num_burst_seg here.
20755 		 */
20756 		num_burst_seg -= num_lso_seg;
20757 
20758 		len = mss;
20759 		if (len > *usable) {
20760 			ASSERT(do_lso_send == B_FALSE);
20761 
20762 			len = *usable;
20763 			if (len <= 0) {
20764 				/* Terminate the loop */
20765 				break;	/* success; too small */
20766 			}
20767 			/*
20768 			 * Sender silly-window avoidance.
20769 			 * Ignore this if we are going to send a
20770 			 * zero window probe out.
20771 			 *
20772 			 * TODO: force data into microscopic window?
20773 			 *	==> (!pushed || (unsent > usable))
20774 			 */
20775 			if (len < (tcp->tcp_max_swnd >> 1) &&
20776 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20777 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20778 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20779 				/*
20780 				 * If the retransmit timer is not running
20781 				 * we start it so that we will retransmit
20782 				 * in the case when the the receiver has
20783 				 * decremented the window.
20784 				 */
20785 				if (*snxt == tcp->tcp_snxt &&
20786 				    *snxt == tcp->tcp_suna) {
20787 					/*
20788 					 * We are not supposed to send
20789 					 * anything.  So let's wait a little
20790 					 * bit longer before breaking SWS
20791 					 * avoidance.
20792 					 *
20793 					 * What should the value be?
20794 					 * Suggestion: MAX(init rexmit time,
20795 					 * tcp->tcp_rto)
20796 					 */
20797 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20798 				}
20799 				break;	/* success; too small */
20800 			}
20801 		}
20802 
20803 		tcph = tcp->tcp_tcph;
20804 
20805 		/*
20806 		 * The reason to adjust len here is that we need to set flags
20807 		 * and calculate checksum.
20808 		 */
20809 		if (do_lso_send)
20810 			len = lso_usable;
20811 
20812 		*usable -= len; /* Approximate - can be adjusted later */
20813 		if (*usable > 0)
20814 			tcph->th_flags[0] = TH_ACK;
20815 		else
20816 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20817 
20818 		/*
20819 		 * Prime pump for IP's checksumming on our behalf
20820 		 * Include the adjustment for a source route if any.
20821 		 */
20822 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20823 		sum = (sum >> 16) + (sum & 0xFFFF);
20824 		U16_TO_ABE16(sum, tcph->th_sum);
20825 
20826 		U32_TO_ABE32(*snxt, tcph->th_seq);
20827 
20828 		/*
20829 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20830 		 * set.  For the case when TCP_FSS_VALID is the only valid
20831 		 * bit (normal active close), branch off only when we think
20832 		 * that the FIN flag needs to be set.  Note for this case,
20833 		 * that (snxt + len) may not reflect the actual seg_len,
20834 		 * as len may be further reduced in tcp_xmit_mp().  If len
20835 		 * gets modified, we will end up here again.
20836 		 */
20837 		if (tcp->tcp_valid_bits != 0 &&
20838 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20839 		    ((*snxt + len) == tcp->tcp_fss))) {
20840 			uchar_t		*prev_rptr;
20841 			uint32_t	prev_snxt = tcp->tcp_snxt;
20842 
20843 			if (*tail_unsent == 0) {
20844 				ASSERT((*xmit_tail)->b_cont != NULL);
20845 				*xmit_tail = (*xmit_tail)->b_cont;
20846 				prev_rptr = (*xmit_tail)->b_rptr;
20847 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20848 				    (*xmit_tail)->b_rptr);
20849 			} else {
20850 				prev_rptr = (*xmit_tail)->b_rptr;
20851 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20852 				    *tail_unsent;
20853 			}
20854 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20855 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20856 			/* Restore tcp_snxt so we get amount sent right. */
20857 			tcp->tcp_snxt = prev_snxt;
20858 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20859 				/*
20860 				 * If the previous timestamp is still in use,
20861 				 * don't stomp on it.
20862 				 */
20863 				if ((*xmit_tail)->b_next == NULL) {
20864 					(*xmit_tail)->b_prev = local_time;
20865 					(*xmit_tail)->b_next =
20866 					    (mblk_t *)(uintptr_t)(*snxt);
20867 				}
20868 			} else
20869 				(*xmit_tail)->b_rptr = prev_rptr;
20870 
20871 			if (mp == NULL) {
20872 				if (ire != NULL)
20873 					IRE_REFRELE(ire);
20874 				return (-1);
20875 			}
20876 			mp1 = mp->b_cont;
20877 
20878 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
20879 				tcp->tcp_last_sent_len = (ushort_t)len;
20880 			while (mp1->b_cont) {
20881 				*xmit_tail = (*xmit_tail)->b_cont;
20882 				(*xmit_tail)->b_prev = local_time;
20883 				(*xmit_tail)->b_next =
20884 				    (mblk_t *)(uintptr_t)(*snxt);
20885 				mp1 = mp1->b_cont;
20886 			}
20887 			*snxt += len;
20888 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20889 			BUMP_LOCAL(tcp->tcp_obsegs);
20890 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20891 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20892 			tcp_send_data(tcp, q, mp);
20893 			continue;
20894 		}
20895 
20896 		*snxt += len;	/* Adjust later if we don't send all of len */
20897 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20898 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20899 
20900 		if (*tail_unsent) {
20901 			/* Are the bytes above us in flight? */
20902 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20903 			if (rptr != (*xmit_tail)->b_rptr) {
20904 				*tail_unsent -= len;
20905 				if (len <= mss) /* LSO is unusable */
20906 					tcp->tcp_last_sent_len = (ushort_t)len;
20907 				len += tcp_hdr_len;
20908 				if (tcp->tcp_ipversion == IPV4_VERSION)
20909 					tcp->tcp_ipha->ipha_length = htons(len);
20910 				else
20911 					tcp->tcp_ip6h->ip6_plen =
20912 					    htons(len -
20913 					    ((char *)&tcp->tcp_ip6h[1] -
20914 					    tcp->tcp_iphc));
20915 				mp = dupb(*xmit_tail);
20916 				if (mp == NULL) {
20917 					if (ire != NULL)
20918 						IRE_REFRELE(ire);
20919 					return (-1);	/* out_of_mem */
20920 				}
20921 				mp->b_rptr = rptr;
20922 				/*
20923 				 * If the old timestamp is no longer in use,
20924 				 * sample a new timestamp now.
20925 				 */
20926 				if ((*xmit_tail)->b_next == NULL) {
20927 					(*xmit_tail)->b_prev = local_time;
20928 					(*xmit_tail)->b_next =
20929 					    (mblk_t *)(uintptr_t)(*snxt-len);
20930 				}
20931 				goto must_alloc;
20932 			}
20933 		} else {
20934 			*xmit_tail = (*xmit_tail)->b_cont;
20935 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20936 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20937 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20938 			    (*xmit_tail)->b_rptr);
20939 		}
20940 
20941 		(*xmit_tail)->b_prev = local_time;
20942 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20943 
20944 		*tail_unsent -= len;
20945 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
20946 			tcp->tcp_last_sent_len = (ushort_t)len;
20947 
20948 		len += tcp_hdr_len;
20949 		if (tcp->tcp_ipversion == IPV4_VERSION)
20950 			tcp->tcp_ipha->ipha_length = htons(len);
20951 		else
20952 			tcp->tcp_ip6h->ip6_plen = htons(len -
20953 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20954 
20955 		mp = dupb(*xmit_tail);
20956 		if (mp == NULL) {
20957 			if (ire != NULL)
20958 				IRE_REFRELE(ire);
20959 			return (-1);	/* out_of_mem */
20960 		}
20961 
20962 		len = tcp_hdr_len;
20963 		/*
20964 		 * There are four reasons to allocate a new hdr mblk:
20965 		 *  1) The bytes above us are in use by another packet
20966 		 *  2) We don't have good alignment
20967 		 *  3) The mblk is being shared
20968 		 *  4) We don't have enough room for a header
20969 		 */
20970 		rptr = mp->b_rptr - len;
20971 		if (!OK_32PTR(rptr) ||
20972 		    ((db = mp->b_datap), db->db_ref != 2) ||
20973 		    rptr < db->db_base + ire_fp_mp_len) {
20974 			/* NOTE: we assume allocb returns an OK_32PTR */
20975 
20976 		must_alloc:;
20977 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20978 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
20979 			if (mp1 == NULL) {
20980 				freemsg(mp);
20981 				if (ire != NULL)
20982 					IRE_REFRELE(ire);
20983 				return (-1);	/* out_of_mem */
20984 			}
20985 			mp1->b_cont = mp;
20986 			mp = mp1;
20987 			/* Leave room for Link Level header */
20988 			len = tcp_hdr_len;
20989 			rptr =
20990 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
20991 			mp->b_wptr = &rptr[len];
20992 		}
20993 
20994 		/*
20995 		 * Fill in the header using the template header, and add
20996 		 * options such as time-stamp, ECN and/or SACK, as needed.
20997 		 */
20998 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20999 
21000 		mp->b_rptr = rptr;
21001 
21002 		if (*tail_unsent) {
21003 			int spill = *tail_unsent;
21004 
21005 			mp1 = mp->b_cont;
21006 			if (mp1 == NULL)
21007 				mp1 = mp;
21008 
21009 			/*
21010 			 * If we're a little short, tack on more mblks until
21011 			 * there is no more spillover.
21012 			 */
21013 			while (spill < 0) {
21014 				mblk_t *nmp;
21015 				int nmpsz;
21016 
21017 				nmp = (*xmit_tail)->b_cont;
21018 				nmpsz = MBLKL(nmp);
21019 
21020 				/*
21021 				 * Excess data in mblk; can we split it?
21022 				 * If MDT is enabled for the connection,
21023 				 * keep on splitting as this is a transient
21024 				 * send path.
21025 				 */
21026 				if (!do_lso_send && !tcp->tcp_mdt &&
21027 				    (spill + nmpsz > 0)) {
21028 					/*
21029 					 * Don't split if stream head was
21030 					 * told to break up larger writes
21031 					 * into smaller ones.
21032 					 */
21033 					if (tcp->tcp_maxpsz > 0)
21034 						break;
21035 
21036 					/*
21037 					 * Next mblk is less than SMSS/2
21038 					 * rounded up to nearest 64-byte;
21039 					 * let it get sent as part of the
21040 					 * next segment.
21041 					 */
21042 					if (tcp->tcp_localnet &&
21043 					    !tcp->tcp_cork &&
21044 					    (nmpsz < roundup((mss >> 1), 64)))
21045 						break;
21046 				}
21047 
21048 				*xmit_tail = nmp;
21049 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21050 				/* Stash for rtt use later */
21051 				(*xmit_tail)->b_prev = local_time;
21052 				(*xmit_tail)->b_next =
21053 				    (mblk_t *)(uintptr_t)(*snxt - len);
21054 				mp1->b_cont = dupb(*xmit_tail);
21055 				mp1 = mp1->b_cont;
21056 
21057 				spill += nmpsz;
21058 				if (mp1 == NULL) {
21059 					*tail_unsent = spill;
21060 					freemsg(mp);
21061 					if (ire != NULL)
21062 						IRE_REFRELE(ire);
21063 					return (-1);	/* out_of_mem */
21064 				}
21065 			}
21066 
21067 			/* Trim back any surplus on the last mblk */
21068 			if (spill >= 0) {
21069 				mp1->b_wptr -= spill;
21070 				*tail_unsent = spill;
21071 			} else {
21072 				/*
21073 				 * We did not send everything we could in
21074 				 * order to remain within the b_cont limit.
21075 				 */
21076 				*usable -= spill;
21077 				*snxt += spill;
21078 				tcp->tcp_last_sent_len += spill;
21079 				UPDATE_MIB(&tcps->tcps_mib,
21080 				    tcpOutDataBytes, spill);
21081 				/*
21082 				 * Adjust the checksum
21083 				 */
21084 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21085 				sum += spill;
21086 				sum = (sum >> 16) + (sum & 0xFFFF);
21087 				U16_TO_ABE16(sum, tcph->th_sum);
21088 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21089 					sum = ntohs(
21090 					    ((ipha_t *)rptr)->ipha_length) +
21091 					    spill;
21092 					((ipha_t *)rptr)->ipha_length =
21093 					    htons(sum);
21094 				} else {
21095 					sum = ntohs(
21096 					    ((ip6_t *)rptr)->ip6_plen) +
21097 					    spill;
21098 					((ip6_t *)rptr)->ip6_plen =
21099 					    htons(sum);
21100 				}
21101 				*tail_unsent = 0;
21102 			}
21103 		}
21104 		if (tcp->tcp_ip_forward_progress) {
21105 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21106 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21107 			tcp->tcp_ip_forward_progress = B_FALSE;
21108 		}
21109 
21110 		if (do_lso_send) {
21111 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21112 			    num_lso_seg);
21113 			tcp->tcp_obsegs += num_lso_seg;
21114 
21115 			TCP_STAT(tcps, tcp_lso_times);
21116 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21117 		} else {
21118 			tcp_send_data(tcp, q, mp);
21119 			BUMP_LOCAL(tcp->tcp_obsegs);
21120 		}
21121 	}
21122 
21123 	if (ire != NULL)
21124 		IRE_REFRELE(ire);
21125 	return (0);
21126 }
21127 
21128 /* Unlink and return any mblk that looks like it contains a MDT info */
21129 static mblk_t *
21130 tcp_mdt_info_mp(mblk_t *mp)
21131 {
21132 	mblk_t	*prev_mp;
21133 
21134 	for (;;) {
21135 		prev_mp = mp;
21136 		/* no more to process? */
21137 		if ((mp = mp->b_cont) == NULL)
21138 			break;
21139 
21140 		switch (DB_TYPE(mp)) {
21141 		case M_CTL:
21142 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21143 				continue;
21144 			ASSERT(prev_mp != NULL);
21145 			prev_mp->b_cont = mp->b_cont;
21146 			mp->b_cont = NULL;
21147 			return (mp);
21148 		default:
21149 			break;
21150 		}
21151 	}
21152 	return (mp);
21153 }
21154 
21155 /* MDT info update routine, called when IP notifies us about MDT */
21156 static void
21157 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21158 {
21159 	boolean_t prev_state;
21160 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21161 
21162 	/*
21163 	 * IP is telling us to abort MDT on this connection?  We know
21164 	 * this because the capability is only turned off when IP
21165 	 * encounters some pathological cases, e.g. link-layer change
21166 	 * where the new driver doesn't support MDT, or in situation
21167 	 * where MDT usage on the link-layer has been switched off.
21168 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21169 	 * if the link-layer doesn't support MDT, and if it does, it
21170 	 * will indicate that the feature is to be turned on.
21171 	 */
21172 	prev_state = tcp->tcp_mdt;
21173 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21174 	if (!tcp->tcp_mdt && !first) {
21175 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21176 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21177 		    (void *)tcp->tcp_connp));
21178 	}
21179 
21180 	/*
21181 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21182 	 * so disable MDT otherwise.  The checks are done here
21183 	 * and in tcp_wput_data().
21184 	 */
21185 	if (tcp->tcp_mdt &&
21186 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21187 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21188 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21189 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21190 		tcp->tcp_mdt = B_FALSE;
21191 
21192 	if (tcp->tcp_mdt) {
21193 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21194 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21195 			    "version (%d), expected version is %d",
21196 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21197 			tcp->tcp_mdt = B_FALSE;
21198 			return;
21199 		}
21200 
21201 		/*
21202 		 * We need the driver to be able to handle at least three
21203 		 * spans per packet in order for tcp MDT to be utilized.
21204 		 * The first is for the header portion, while the rest are
21205 		 * needed to handle a packet that straddles across two
21206 		 * virtually non-contiguous buffers; a typical tcp packet
21207 		 * therefore consists of only two spans.  Note that we take
21208 		 * a zero as "don't care".
21209 		 */
21210 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21211 		    mdt_capab->ill_mdt_span_limit < 3) {
21212 			tcp->tcp_mdt = B_FALSE;
21213 			return;
21214 		}
21215 
21216 		/* a zero means driver wants default value */
21217 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21218 		    tcps->tcps_mdt_max_pbufs);
21219 		if (tcp->tcp_mdt_max_pld == 0)
21220 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21221 
21222 		/* ensure 32-bit alignment */
21223 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21224 		    mdt_capab->ill_mdt_hdr_head), 4);
21225 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21226 		    mdt_capab->ill_mdt_hdr_tail), 4);
21227 
21228 		if (!first && !prev_state) {
21229 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21230 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21231 			    (void *)tcp->tcp_connp));
21232 		}
21233 	}
21234 }
21235 
21236 /* Unlink and return any mblk that looks like it contains a LSO info */
21237 static mblk_t *
21238 tcp_lso_info_mp(mblk_t *mp)
21239 {
21240 	mblk_t	*prev_mp;
21241 
21242 	for (;;) {
21243 		prev_mp = mp;
21244 		/* no more to process? */
21245 		if ((mp = mp->b_cont) == NULL)
21246 			break;
21247 
21248 		switch (DB_TYPE(mp)) {
21249 		case M_CTL:
21250 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21251 				continue;
21252 			ASSERT(prev_mp != NULL);
21253 			prev_mp->b_cont = mp->b_cont;
21254 			mp->b_cont = NULL;
21255 			return (mp);
21256 		default:
21257 			break;
21258 		}
21259 	}
21260 
21261 	return (mp);
21262 }
21263 
21264 /* LSO info update routine, called when IP notifies us about LSO */
21265 static void
21266 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21267 {
21268 	tcp_stack_t *tcps = tcp->tcp_tcps;
21269 
21270 	/*
21271 	 * IP is telling us to abort LSO on this connection?  We know
21272 	 * this because the capability is only turned off when IP
21273 	 * encounters some pathological cases, e.g. link-layer change
21274 	 * where the new NIC/driver doesn't support LSO, or in situation
21275 	 * where LSO usage on the link-layer has been switched off.
21276 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21277 	 * if the link-layer doesn't support LSO, and if it does, it
21278 	 * will indicate that the feature is to be turned on.
21279 	 */
21280 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21281 	TCP_STAT(tcps, tcp_lso_enabled);
21282 
21283 	/*
21284 	 * We currently only support LSO on simple TCP/IPv4,
21285 	 * so disable LSO otherwise.  The checks are done here
21286 	 * and in tcp_wput_data().
21287 	 */
21288 	if (tcp->tcp_lso &&
21289 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21290 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21291 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21292 		tcp->tcp_lso = B_FALSE;
21293 		TCP_STAT(tcps, tcp_lso_disabled);
21294 	} else {
21295 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21296 		    lso_capab->ill_lso_max);
21297 	}
21298 }
21299 
21300 static void
21301 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21302 {
21303 	conn_t *connp = tcp->tcp_connp;
21304 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21305 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21306 
21307 	ASSERT(ire != NULL);
21308 
21309 	/*
21310 	 * We may be in the fastpath here, and although we essentially do
21311 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21312 	 * we try to keep things as brief as possible.  After all, these
21313 	 * are only best-effort checks, and we do more thorough ones prior
21314 	 * to calling tcp_send()/tcp_multisend().
21315 	 */
21316 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21317 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21318 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21319 	    !(ire->ire_flags & RTF_MULTIRT) &&
21320 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21321 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21322 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21323 			/* Cache the result */
21324 			connp->conn_lso_ok = B_TRUE;
21325 
21326 			ASSERT(ill->ill_lso_capab != NULL);
21327 			if (!ill->ill_lso_capab->ill_lso_on) {
21328 				ill->ill_lso_capab->ill_lso_on = 1;
21329 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21330 				    "LSO for interface %s\n", (void *)connp,
21331 				    ill->ill_name));
21332 			}
21333 			tcp_lso_update(tcp, ill->ill_lso_capab);
21334 		} else if (ipst->ips_ip_multidata_outbound &&
21335 		    ILL_MDT_CAPABLE(ill)) {
21336 			/* Cache the result */
21337 			connp->conn_mdt_ok = B_TRUE;
21338 
21339 			ASSERT(ill->ill_mdt_capab != NULL);
21340 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21341 				ill->ill_mdt_capab->ill_mdt_on = 1;
21342 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21343 				    "MDT for interface %s\n", (void *)connp,
21344 				    ill->ill_name));
21345 			}
21346 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21347 		}
21348 	}
21349 
21350 	/*
21351 	 * The goal is to reduce the number of generated tcp segments by
21352 	 * setting the maxpsz multiplier to 0; this will have an affect on
21353 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21354 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21355 	 * of outbound segments and incoming ACKs, thus allowing for better
21356 	 * network and system performance.  In contrast the legacy behavior
21357 	 * may result in sending less than SMSS size, because the last mblk
21358 	 * for some packets may have more data than needed to make up SMSS,
21359 	 * and the legacy code refused to "split" it.
21360 	 *
21361 	 * We apply the new behavior on following situations:
21362 	 *
21363 	 *   1) Loopback connections,
21364 	 *   2) Connections in which the remote peer is not on local subnet,
21365 	 *   3) Local subnet connections over the bge interface (see below).
21366 	 *
21367 	 * Ideally, we would like this behavior to apply for interfaces other
21368 	 * than bge.  However, doing so would negatively impact drivers which
21369 	 * perform dynamic mapping and unmapping of DMA resources, which are
21370 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21371 	 * packet will be generated by tcp).  The bge driver does not suffer
21372 	 * from this, as it copies the mblks into pre-mapped buffers, and
21373 	 * therefore does not require more I/O resources than before.
21374 	 *
21375 	 * Otherwise, this behavior is present on all network interfaces when
21376 	 * the destination endpoint is non-local, since reducing the number
21377 	 * of packets in general is good for the network.
21378 	 *
21379 	 * TODO We need to remove this hard-coded conditional for bge once
21380 	 *	a better "self-tuning" mechanism, or a way to comprehend
21381 	 *	the driver transmit strategy is devised.  Until the solution
21382 	 *	is found and well understood, we live with this hack.
21383 	 */
21384 	if (!tcp_static_maxpsz &&
21385 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21386 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21387 		/* override the default value */
21388 		tcp->tcp_maxpsz = 0;
21389 
21390 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21391 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21392 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21393 	}
21394 
21395 	/* set the stream head parameters accordingly */
21396 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21397 }
21398 
21399 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21400 static void
21401 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21402 {
21403 	uchar_t	fval = *mp->b_rptr;
21404 	mblk_t	*tail;
21405 	queue_t	*q = tcp->tcp_wq;
21406 
21407 	/* TODO: How should flush interact with urgent data? */
21408 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21409 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21410 		/*
21411 		 * Flush only data that has not yet been put on the wire.  If
21412 		 * we flush data that we have already transmitted, life, as we
21413 		 * know it, may come to an end.
21414 		 */
21415 		tail = tcp->tcp_xmit_tail;
21416 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21417 		tcp->tcp_xmit_tail_unsent = 0;
21418 		tcp->tcp_unsent = 0;
21419 		if (tail->b_wptr != tail->b_rptr)
21420 			tail = tail->b_cont;
21421 		if (tail) {
21422 			mblk_t **excess = &tcp->tcp_xmit_head;
21423 			for (;;) {
21424 				mblk_t *mp1 = *excess;
21425 				if (mp1 == tail)
21426 					break;
21427 				tcp->tcp_xmit_tail = mp1;
21428 				tcp->tcp_xmit_last = mp1;
21429 				excess = &mp1->b_cont;
21430 			}
21431 			*excess = NULL;
21432 			tcp_close_mpp(&tail);
21433 			if (tcp->tcp_snd_zcopy_aware)
21434 				tcp_zcopy_notify(tcp);
21435 		}
21436 		/*
21437 		 * We have no unsent data, so unsent must be less than
21438 		 * tcp_xmit_lowater, so re-enable flow.
21439 		 */
21440 		mutex_enter(&tcp->tcp_non_sq_lock);
21441 		if (tcp->tcp_flow_stopped) {
21442 			tcp_clrqfull(tcp);
21443 		}
21444 		mutex_exit(&tcp->tcp_non_sq_lock);
21445 	}
21446 	/*
21447 	 * TODO: you can't just flush these, you have to increase rwnd for one
21448 	 * thing.  For another, how should urgent data interact?
21449 	 */
21450 	if (fval & FLUSHR) {
21451 		*mp->b_rptr = fval & ~FLUSHW;
21452 		/* XXX */
21453 		qreply(q, mp);
21454 		return;
21455 	}
21456 	freemsg(mp);
21457 }
21458 
21459 /*
21460  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21461  * messages.
21462  */
21463 static void
21464 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21465 {
21466 	mblk_t	*mp1;
21467 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
21468 	STRUCT_HANDLE(strbuf, sb);
21469 	queue_t *q = tcp->tcp_wq;
21470 	int	error;
21471 	uint_t	addrlen;
21472 
21473 	/* Make sure it is one of ours. */
21474 	switch (iocp->ioc_cmd) {
21475 	case TI_GETMYNAME:
21476 	case TI_GETPEERNAME:
21477 		break;
21478 	default:
21479 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21480 		return;
21481 	}
21482 	switch (mi_copy_state(q, mp, &mp1)) {
21483 	case -1:
21484 		return;
21485 	case MI_COPY_CASE(MI_COPY_IN, 1):
21486 		break;
21487 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21488 		/* Copy out the strbuf. */
21489 		mi_copyout(q, mp);
21490 		return;
21491 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21492 		/* All done. */
21493 		mi_copy_done(q, mp, 0);
21494 		return;
21495 	default:
21496 		mi_copy_done(q, mp, EPROTO);
21497 		return;
21498 	}
21499 	/* Check alignment of the strbuf */
21500 	if (!OK_32PTR(mp1->b_rptr)) {
21501 		mi_copy_done(q, mp, EINVAL);
21502 		return;
21503 	}
21504 
21505 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
21506 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21507 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21508 		mi_copy_done(q, mp, EINVAL);
21509 		return;
21510 	}
21511 
21512 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21513 	if (mp1 == NULL)
21514 		return;
21515 
21516 	switch (iocp->ioc_cmd) {
21517 	case TI_GETMYNAME:
21518 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
21519 		break;
21520 	case TI_GETPEERNAME:
21521 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
21522 		break;
21523 	}
21524 
21525 	if (error != 0) {
21526 		mi_copy_done(q, mp, error);
21527 	} else {
21528 		mp1->b_wptr += addrlen;
21529 		STRUCT_FSET(sb, len, addrlen);
21530 
21531 		/* Copy out the address */
21532 		mi_copyout(q, mp);
21533 	}
21534 }
21535 
21536 static void
21537 tcp_use_pure_tpi(tcp_t *tcp)
21538 {
21539 #ifdef	_ILP32
21540 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
21541 #else
21542 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21543 #endif
21544 	/*
21545 	 * Insert this socket into the acceptor hash.
21546 	 * We might need it for T_CONN_RES message
21547 	 */
21548 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21549 
21550 	tcp->tcp_issocket = B_FALSE;
21551 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
21552 }
21553 
21554 /*
21555  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21556  * messages.
21557  */
21558 /* ARGSUSED */
21559 static void
21560 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21561 {
21562 	conn_t 	*connp = (conn_t *)arg;
21563 	tcp_t	*tcp = connp->conn_tcp;
21564 	queue_t	*q = tcp->tcp_wq;
21565 	struct iocblk	*iocp;
21566 
21567 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21568 	/*
21569 	 * Try and ASSERT the minimum possible references on the
21570 	 * conn early enough. Since we are executing on write side,
21571 	 * the connection is obviously not detached and that means
21572 	 * there is a ref each for TCP and IP. Since we are behind
21573 	 * the squeue, the minimum references needed are 3. If the
21574 	 * conn is in classifier hash list, there should be an
21575 	 * extra ref for that (we check both the possibilities).
21576 	 */
21577 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21578 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21579 
21580 	iocp = (struct iocblk *)mp->b_rptr;
21581 	switch (iocp->ioc_cmd) {
21582 	case TCP_IOC_DEFAULT_Q:
21583 		/* Wants to be the default wq. */
21584 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21585 			iocp->ioc_error = EPERM;
21586 			iocp->ioc_count = 0;
21587 			mp->b_datap->db_type = M_IOCACK;
21588 			qreply(q, mp);
21589 			return;
21590 		}
21591 		tcp_def_q_set(tcp, mp);
21592 		return;
21593 	case _SIOCSOCKFALLBACK:
21594 		/*
21595 		 * Either sockmod is about to be popped and the socket
21596 		 * would now be treated as a plain stream, or a module
21597 		 * is about to be pushed so we could no longer use read-
21598 		 * side synchronous streams for fused loopback tcp.
21599 		 * Drain any queued data and disable direct sockfs
21600 		 * interface from now on.
21601 		 */
21602 		if (!tcp->tcp_issocket) {
21603 			DB_TYPE(mp) = M_IOCNAK;
21604 			iocp->ioc_error = EINVAL;
21605 		} else {
21606 			tcp_use_pure_tpi(tcp);
21607 			DB_TYPE(mp) = M_IOCACK;
21608 			iocp->ioc_error = 0;
21609 		}
21610 		iocp->ioc_count = 0;
21611 		iocp->ioc_rval = 0;
21612 		qreply(q, mp);
21613 		return;
21614 	}
21615 	CALL_IP_WPUT(connp, q, mp);
21616 }
21617 
21618 /*
21619  * This routine is called by tcp_wput() to handle all TPI requests.
21620  */
21621 /* ARGSUSED */
21622 static void
21623 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21624 {
21625 	conn_t 	*connp = (conn_t *)arg;
21626 	tcp_t	*tcp = connp->conn_tcp;
21627 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21628 	uchar_t *rptr;
21629 	t_scalar_t type;
21630 	cred_t *cr;
21631 
21632 	/*
21633 	 * Try and ASSERT the minimum possible references on the
21634 	 * conn early enough. Since we are executing on write side,
21635 	 * the connection is obviously not detached and that means
21636 	 * there is a ref each for TCP and IP. Since we are behind
21637 	 * the squeue, the minimum references needed are 3. If the
21638 	 * conn is in classifier hash list, there should be an
21639 	 * extra ref for that (we check both the possibilities).
21640 	 */
21641 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21642 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21643 
21644 	rptr = mp->b_rptr;
21645 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21646 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21647 		type = ((union T_primitives *)rptr)->type;
21648 		if (type == T_EXDATA_REQ) {
21649 			tcp_output_urgent(connp, mp, arg2);
21650 		} else if (type != T_DATA_REQ) {
21651 			goto non_urgent_data;
21652 		} else {
21653 			/* TODO: options, flags, ... from user */
21654 			/* Set length to zero for reclamation below */
21655 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21656 			freeb(mp);
21657 		}
21658 		return;
21659 	} else {
21660 		if (tcp->tcp_debug) {
21661 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21662 			    "tcp_wput_proto, dropping one...");
21663 		}
21664 		freemsg(mp);
21665 		return;
21666 	}
21667 
21668 non_urgent_data:
21669 
21670 	switch ((int)tprim->type) {
21671 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21672 		/*
21673 		 * save the kssl_ent_t from the next block, and convert this
21674 		 * back to a normal bind_req.
21675 		 */
21676 		if (mp->b_cont != NULL) {
21677 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21678 
21679 			if (tcp->tcp_kssl_ent != NULL) {
21680 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21681 				    KSSL_NO_PROXY);
21682 				tcp->tcp_kssl_ent = NULL;
21683 			}
21684 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21685 			    sizeof (kssl_ent_t));
21686 			kssl_hold_ent(tcp->tcp_kssl_ent);
21687 			freemsg(mp->b_cont);
21688 			mp->b_cont = NULL;
21689 		}
21690 		tprim->type = T_BIND_REQ;
21691 
21692 	/* FALLTHROUGH */
21693 	case O_T_BIND_REQ:	/* bind request */
21694 	case T_BIND_REQ:	/* new semantics bind request */
21695 		tcp_tpi_bind(tcp, mp);
21696 		break;
21697 	case T_UNBIND_REQ:	/* unbind request */
21698 		tcp_tpi_unbind(tcp, mp);
21699 		break;
21700 	case O_T_CONN_RES:	/* old connection response XXX */
21701 	case T_CONN_RES:	/* connection response */
21702 		tcp_tli_accept(tcp, mp);
21703 		break;
21704 	case T_CONN_REQ:	/* connection request */
21705 		tcp_tpi_connect(tcp, mp);
21706 		break;
21707 	case T_DISCON_REQ:	/* disconnect request */
21708 		tcp_disconnect(tcp, mp);
21709 		break;
21710 	case T_CAPABILITY_REQ:
21711 		tcp_capability_req(tcp, mp);	/* capability request */
21712 		break;
21713 	case T_INFO_REQ:	/* information request */
21714 		tcp_info_req(tcp, mp);
21715 		break;
21716 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21717 	case T_OPTMGMT_REQ:
21718 		/*
21719 		 * Note:  no support for snmpcom_req() through new
21720 		 * T_OPTMGMT_REQ. See comments in ip.c
21721 		 */
21722 
21723 		/*
21724 		 * All Solaris components should pass a db_credp
21725 		 * for this TPI message, hence we ASSERT.
21726 		 * But in case there is some other M_PROTO that looks
21727 		 * like a TPI message sent by some other kernel
21728 		 * component, we check and return an error.
21729 		 */
21730 		cr = msg_getcred(mp, NULL);
21731 		ASSERT(cr != NULL);
21732 		if (cr == NULL) {
21733 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
21734 			return;
21735 		}
21736 		/*
21737 		 * If EINPROGRESS is returned, the request has been queued
21738 		 * for subsequent processing by ip_restart_optmgmt(), which
21739 		 * will do the CONN_DEC_REF().
21740 		 */
21741 		CONN_INC_REF(connp);
21742 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
21743 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21744 			    B_TRUE) != EINPROGRESS) {
21745 				CONN_DEC_REF(connp);
21746 			}
21747 		} else {
21748 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21749 			    B_TRUE) != EINPROGRESS) {
21750 				CONN_DEC_REF(connp);
21751 			}
21752 		}
21753 		break;
21754 
21755 	case T_UNITDATA_REQ:	/* unitdata request */
21756 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21757 		break;
21758 	case T_ORDREL_REQ:	/* orderly release req */
21759 		freemsg(mp);
21760 
21761 		if (tcp->tcp_fused)
21762 			tcp_unfuse(tcp);
21763 
21764 		if (tcp_xmit_end(tcp) != 0) {
21765 			/*
21766 			 * We were crossing FINs and got a reset from
21767 			 * the other side. Just ignore it.
21768 			 */
21769 			if (tcp->tcp_debug) {
21770 				(void) strlog(TCP_MOD_ID, 0, 1,
21771 				    SL_ERROR|SL_TRACE,
21772 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21773 				    "state %s",
21774 				    tcp_display(tcp, NULL,
21775 				    DISP_ADDR_AND_PORT));
21776 			}
21777 		}
21778 		break;
21779 	case T_ADDR_REQ:
21780 		tcp_addr_req(tcp, mp);
21781 		break;
21782 	default:
21783 		if (tcp->tcp_debug) {
21784 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21785 			    "tcp_wput_proto, bogus TPI msg, type %d",
21786 			    tprim->type);
21787 		}
21788 		/*
21789 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21790 		 * to recover.
21791 		 */
21792 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21793 		break;
21794 	}
21795 }
21796 
21797 /*
21798  * The TCP write service routine should never be called...
21799  */
21800 /* ARGSUSED */
21801 static void
21802 tcp_wsrv(queue_t *q)
21803 {
21804 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
21805 
21806 	TCP_STAT(tcps, tcp_wsrv_called);
21807 }
21808 
21809 /* Non overlapping byte exchanger */
21810 static void
21811 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21812 {
21813 	uchar_t	uch;
21814 
21815 	while (len-- > 0) {
21816 		uch = a[len];
21817 		a[len] = b[len];
21818 		b[len] = uch;
21819 	}
21820 }
21821 
21822 /*
21823  * Send out a control packet on the tcp connection specified.  This routine
21824  * is typically called where we need a simple ACK or RST generated.
21825  */
21826 static void
21827 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21828 {
21829 	uchar_t		*rptr;
21830 	tcph_t		*tcph;
21831 	ipha_t		*ipha = NULL;
21832 	ip6_t		*ip6h = NULL;
21833 	uint32_t	sum;
21834 	int		tcp_hdr_len;
21835 	int		tcp_ip_hdr_len;
21836 	mblk_t		*mp;
21837 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21838 
21839 	/*
21840 	 * Save sum for use in source route later.
21841 	 */
21842 	ASSERT(tcp != NULL);
21843 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21844 	tcp_hdr_len = tcp->tcp_hdr_len;
21845 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21846 
21847 	/* If a text string is passed in with the request, pass it to strlog. */
21848 	if (str != NULL && tcp->tcp_debug) {
21849 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21850 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21851 		    str, seq, ack, ctl);
21852 	}
21853 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
21854 	    BPRI_MED);
21855 	if (mp == NULL) {
21856 		return;
21857 	}
21858 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
21859 	mp->b_rptr = rptr;
21860 	mp->b_wptr = &rptr[tcp_hdr_len];
21861 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21862 
21863 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21864 		ipha = (ipha_t *)rptr;
21865 		ipha->ipha_length = htons(tcp_hdr_len);
21866 	} else {
21867 		ip6h = (ip6_t *)rptr;
21868 		ASSERT(tcp != NULL);
21869 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21870 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21871 	}
21872 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21873 	tcph->th_flags[0] = (uint8_t)ctl;
21874 	if (ctl & TH_RST) {
21875 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
21876 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
21877 		/*
21878 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21879 		 */
21880 		if (tcp->tcp_snd_ts_ok &&
21881 		    tcp->tcp_state > TCPS_SYN_SENT) {
21882 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21883 			*(mp->b_wptr) = TCPOPT_EOL;
21884 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21885 				ipha->ipha_length = htons(tcp_hdr_len -
21886 				    TCPOPT_REAL_TS_LEN);
21887 			} else {
21888 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21889 				    TCPOPT_REAL_TS_LEN);
21890 			}
21891 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21892 			sum -= TCPOPT_REAL_TS_LEN;
21893 		}
21894 	}
21895 	if (ctl & TH_ACK) {
21896 		if (tcp->tcp_snd_ts_ok) {
21897 			U32_TO_BE32(lbolt,
21898 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21899 			U32_TO_BE32(tcp->tcp_ts_recent,
21900 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21901 		}
21902 
21903 		/* Update the latest receive window size in TCP header. */
21904 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21905 		    tcph->th_win);
21906 		tcp->tcp_rack = ack;
21907 		tcp->tcp_rack_cnt = 0;
21908 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
21909 	}
21910 	BUMP_LOCAL(tcp->tcp_obsegs);
21911 	U32_TO_BE32(seq, tcph->th_seq);
21912 	U32_TO_BE32(ack, tcph->th_ack);
21913 	/*
21914 	 * Include the adjustment for a source route if any.
21915 	 */
21916 	sum = (sum >> 16) + (sum & 0xFFFF);
21917 	U16_TO_BE16(sum, tcph->th_sum);
21918 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21919 }
21920 
21921 /*
21922  * If this routine returns B_TRUE, TCP can generate a RST in response
21923  * to a segment.  If it returns B_FALSE, TCP should not respond.
21924  */
21925 static boolean_t
21926 tcp_send_rst_chk(tcp_stack_t *tcps)
21927 {
21928 	clock_t	now;
21929 
21930 	/*
21931 	 * TCP needs to protect itself from generating too many RSTs.
21932 	 * This can be a DoS attack by sending us random segments
21933 	 * soliciting RSTs.
21934 	 *
21935 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21936 	 * in each 1 second interval.  In this way, TCP still generate
21937 	 * RSTs in normal cases but when under attack, the impact is
21938 	 * limited.
21939 	 */
21940 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
21941 		now = lbolt;
21942 		/* lbolt can wrap around. */
21943 		if ((tcps->tcps_last_rst_intrvl > now) ||
21944 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
21945 		    1*SECONDS)) {
21946 			tcps->tcps_last_rst_intrvl = now;
21947 			tcps->tcps_rst_cnt = 1;
21948 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
21949 			return (B_FALSE);
21950 		}
21951 	}
21952 	return (B_TRUE);
21953 }
21954 
21955 /*
21956  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21957  */
21958 static void
21959 tcp_ip_ire_mark_advice(tcp_t *tcp)
21960 {
21961 	mblk_t *mp;
21962 	ipic_t *ipic;
21963 
21964 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21965 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21966 		    &ipic);
21967 	} else {
21968 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21969 		    &ipic);
21970 	}
21971 	if (mp == NULL)
21972 		return;
21973 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21974 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21975 }
21976 
21977 /*
21978  * Return an IP advice ioctl mblk and set ipic to be the pointer
21979  * to the advice structure.
21980  */
21981 static mblk_t *
21982 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21983 {
21984 	struct iocblk *ioc;
21985 	mblk_t *mp, *mp1;
21986 
21987 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21988 	if (mp == NULL)
21989 		return (NULL);
21990 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21991 	*ipic = (ipic_t *)mp->b_rptr;
21992 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21993 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21994 
21995 	bcopy(addr, *ipic + 1, addr_len);
21996 
21997 	(*ipic)->ipic_addr_length = addr_len;
21998 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21999 
22000 	mp1 = mkiocb(IP_IOCTL);
22001 	if (mp1 == NULL) {
22002 		freemsg(mp);
22003 		return (NULL);
22004 	}
22005 	mp1->b_cont = mp;
22006 	ioc = (struct iocblk *)mp1->b_rptr;
22007 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22008 
22009 	return (mp1);
22010 }
22011 
22012 /*
22013  * Generate a reset based on an inbound packet, connp is set by caller
22014  * when RST is in response to an unexpected inbound packet for which
22015  * there is active tcp state in the system.
22016  *
22017  * IPSEC NOTE : Try to send the reply with the same protection as it came
22018  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22019  * the packet will go out at the same level of protection as it came in by
22020  * converting the IPSEC_IN to IPSEC_OUT.
22021  */
22022 static void
22023 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22024     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22025     tcp_stack_t *tcps, conn_t *connp)
22026 {
22027 	ipha_t		*ipha = NULL;
22028 	ip6_t		*ip6h = NULL;
22029 	ushort_t	len;
22030 	tcph_t		*tcph;
22031 	int		i;
22032 	mblk_t		*ipsec_mp;
22033 	boolean_t	mctl_present;
22034 	ipic_t		*ipic;
22035 	ipaddr_t	v4addr;
22036 	in6_addr_t	v6addr;
22037 	int		addr_len;
22038 	void		*addr;
22039 	queue_t		*q = tcps->tcps_g_q;
22040 	tcp_t		*tcp;
22041 	cred_t		*cr;
22042 	pid_t		pid;
22043 	mblk_t		*nmp;
22044 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22045 
22046 	if (tcps->tcps_g_q == NULL) {
22047 		/*
22048 		 * For non-zero stackids the default queue isn't created
22049 		 * until the first open, thus there can be a need to send
22050 		 * a reset before then. But we can't do that, hence we just
22051 		 * drop the packet. Later during boot, when the default queue
22052 		 * has been setup, a retransmitted packet from the peer
22053 		 * will result in a reset.
22054 		 */
22055 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22056 		    GLOBAL_NETSTACKID);
22057 		freemsg(mp);
22058 		return;
22059 	}
22060 
22061 	if (connp != NULL)
22062 		tcp = connp->conn_tcp;
22063 	else
22064 		tcp = Q_TO_TCP(q);
22065 
22066 	if (!tcp_send_rst_chk(tcps)) {
22067 		tcps->tcps_rst_unsent++;
22068 		freemsg(mp);
22069 		return;
22070 	}
22071 
22072 	if (mp->b_datap->db_type == M_CTL) {
22073 		ipsec_mp = mp;
22074 		mp = mp->b_cont;
22075 		mctl_present = B_TRUE;
22076 	} else {
22077 		ipsec_mp = mp;
22078 		mctl_present = B_FALSE;
22079 	}
22080 
22081 	if (str && q && tcps->tcps_dbg) {
22082 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22083 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22084 		    "flags 0x%x",
22085 		    str, seq, ack, ctl);
22086 	}
22087 	if (mp->b_datap->db_ref != 1) {
22088 		mblk_t *mp1 = copyb(mp);
22089 		freemsg(mp);
22090 		mp = mp1;
22091 		if (!mp) {
22092 			if (mctl_present)
22093 				freeb(ipsec_mp);
22094 			return;
22095 		} else {
22096 			if (mctl_present) {
22097 				ipsec_mp->b_cont = mp;
22098 			} else {
22099 				ipsec_mp = mp;
22100 			}
22101 		}
22102 	} else if (mp->b_cont) {
22103 		freemsg(mp->b_cont);
22104 		mp->b_cont = NULL;
22105 	}
22106 	/*
22107 	 * We skip reversing source route here.
22108 	 * (for now we replace all IP options with EOL)
22109 	 */
22110 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22111 		ipha = (ipha_t *)mp->b_rptr;
22112 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22113 			mp->b_rptr[i] = IPOPT_EOL;
22114 		/*
22115 		 * Make sure that src address isn't flagrantly invalid.
22116 		 * Not all broadcast address checking for the src address
22117 		 * is possible, since we don't know the netmask of the src
22118 		 * addr.  No check for destination address is done, since
22119 		 * IP will not pass up a packet with a broadcast dest
22120 		 * address to TCP.  Similar checks are done below for IPv6.
22121 		 */
22122 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22123 		    CLASSD(ipha->ipha_src)) {
22124 			freemsg(ipsec_mp);
22125 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22126 			return;
22127 		}
22128 	} else {
22129 		ip6h = (ip6_t *)mp->b_rptr;
22130 
22131 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22132 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22133 			freemsg(ipsec_mp);
22134 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22135 			return;
22136 		}
22137 
22138 		/* Remove any extension headers assuming partial overlay */
22139 		if (ip_hdr_len > IPV6_HDR_LEN) {
22140 			uint8_t *to;
22141 
22142 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22143 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22144 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22145 			ip_hdr_len = IPV6_HDR_LEN;
22146 			ip6h = (ip6_t *)mp->b_rptr;
22147 			ip6h->ip6_nxt = IPPROTO_TCP;
22148 		}
22149 	}
22150 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22151 	if (tcph->th_flags[0] & TH_RST) {
22152 		freemsg(ipsec_mp);
22153 		return;
22154 	}
22155 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22156 	len = ip_hdr_len + sizeof (tcph_t);
22157 	mp->b_wptr = &mp->b_rptr[len];
22158 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22159 		ipha->ipha_length = htons(len);
22160 		/* Swap addresses */
22161 		v4addr = ipha->ipha_src;
22162 		ipha->ipha_src = ipha->ipha_dst;
22163 		ipha->ipha_dst = v4addr;
22164 		ipha->ipha_ident = 0;
22165 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22166 		addr_len = IP_ADDR_LEN;
22167 		addr = &v4addr;
22168 	} else {
22169 		/* No ip6i_t in this case */
22170 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22171 		/* Swap addresses */
22172 		v6addr = ip6h->ip6_src;
22173 		ip6h->ip6_src = ip6h->ip6_dst;
22174 		ip6h->ip6_dst = v6addr;
22175 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22176 		addr_len = IPV6_ADDR_LEN;
22177 		addr = &v6addr;
22178 	}
22179 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22180 	U32_TO_BE32(ack, tcph->th_ack);
22181 	U32_TO_BE32(seq, tcph->th_seq);
22182 	U16_TO_BE16(0, tcph->th_win);
22183 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22184 	tcph->th_flags[0] = (uint8_t)ctl;
22185 	if (ctl & TH_RST) {
22186 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22187 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22188 	}
22189 
22190 	/* IP trusts us to set up labels when required. */
22191 	if (is_system_labeled() && (cr = msg_getcred(mp, &pid)) != NULL &&
22192 	    crgetlabel(cr) != NULL) {
22193 		int err;
22194 
22195 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22196 			err = tsol_check_label(cr, &mp,
22197 			    tcp->tcp_connp->conn_mac_exempt,
22198 			    tcps->tcps_netstack->netstack_ip, pid);
22199 		else
22200 			err = tsol_check_label_v6(cr, &mp,
22201 			    tcp->tcp_connp->conn_mac_exempt,
22202 			    tcps->tcps_netstack->netstack_ip, pid);
22203 		if (mctl_present)
22204 			ipsec_mp->b_cont = mp;
22205 		else
22206 			ipsec_mp = mp;
22207 		if (err != 0) {
22208 			freemsg(ipsec_mp);
22209 			return;
22210 		}
22211 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22212 			ipha = (ipha_t *)mp->b_rptr;
22213 		} else {
22214 			ip6h = (ip6_t *)mp->b_rptr;
22215 		}
22216 	}
22217 
22218 	if (mctl_present) {
22219 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22220 
22221 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22222 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22223 			return;
22224 		}
22225 	}
22226 	if (zoneid == ALL_ZONES)
22227 		zoneid = GLOBAL_ZONEID;
22228 
22229 	/* Add the zoneid so ip_output routes it properly */
22230 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22231 		freemsg(ipsec_mp);
22232 		return;
22233 	}
22234 	ipsec_mp = nmp;
22235 
22236 	/*
22237 	 * NOTE:  one might consider tracing a TCP packet here, but
22238 	 * this function has no active TCP state and no tcp structure
22239 	 * that has a trace buffer.  If we traced here, we would have
22240 	 * to keep a local trace buffer in tcp_record_trace().
22241 	 *
22242 	 * TSol note: The mblk that contains the incoming packet was
22243 	 * reused by tcp_xmit_listener_reset, so it already contains
22244 	 * the right credentials and we don't need to call mblk_setcred.
22245 	 * Also the conn's cred is not right since it is associated
22246 	 * with tcps_g_q.
22247 	 */
22248 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22249 
22250 	/*
22251 	 * Tell IP to mark the IRE used for this destination temporary.
22252 	 * This way, we can limit our exposure to DoS attack because IP
22253 	 * creates an IRE for each destination.  If there are too many,
22254 	 * the time to do any routing lookup will be extremely long.  And
22255 	 * the lookup can be in interrupt context.
22256 	 *
22257 	 * Note that in normal circumstances, this marking should not
22258 	 * affect anything.  It would be nice if only 1 message is
22259 	 * needed to inform IP that the IRE created for this RST should
22260 	 * not be added to the cache table.  But there is currently
22261 	 * not such communication mechanism between TCP and IP.  So
22262 	 * the best we can do now is to send the advice ioctl to IP
22263 	 * to mark the IRE temporary.
22264 	 */
22265 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22266 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22267 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22268 	}
22269 }
22270 
22271 /*
22272  * Initiate closedown sequence on an active connection.  (May be called as
22273  * writer.)  Return value zero for OK return, non-zero for error return.
22274  */
22275 static int
22276 tcp_xmit_end(tcp_t *tcp)
22277 {
22278 	ipic_t	*ipic;
22279 	mblk_t	*mp;
22280 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22281 
22282 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22283 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22284 		/*
22285 		 * Invalid state, only states TCPS_SYN_RCVD,
22286 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22287 		 */
22288 		return (-1);
22289 	}
22290 
22291 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22292 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22293 	/*
22294 	 * If there is nothing more unsent, send the FIN now.
22295 	 * Otherwise, it will go out with the last segment.
22296 	 */
22297 	if (tcp->tcp_unsent == 0) {
22298 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22299 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22300 
22301 		if (mp) {
22302 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22303 		} else {
22304 			/*
22305 			 * Couldn't allocate msg.  Pretend we got it out.
22306 			 * Wait for rexmit timeout.
22307 			 */
22308 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22309 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22310 		}
22311 
22312 		/*
22313 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22314 		 * changed.
22315 		 */
22316 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22317 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22318 		}
22319 	} else {
22320 		/*
22321 		 * If tcp->tcp_cork is set, then the data will not get sent,
22322 		 * so we have to check that and unset it first.
22323 		 */
22324 		if (tcp->tcp_cork)
22325 			tcp->tcp_cork = B_FALSE;
22326 		tcp_wput_data(tcp, NULL, B_FALSE);
22327 	}
22328 
22329 	/*
22330 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22331 	 * is 0, don't update the cache.
22332 	 */
22333 	if (tcps->tcps_rtt_updates == 0 ||
22334 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22335 		return (0);
22336 
22337 	/*
22338 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22339 	 * different from the destination.
22340 	 */
22341 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22342 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22343 			return (0);
22344 		}
22345 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22346 		    &ipic);
22347 	} else {
22348 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22349 		    &tcp->tcp_ip6h->ip6_dst))) {
22350 			return (0);
22351 		}
22352 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22353 		    &ipic);
22354 	}
22355 
22356 	/* Record route attributes in the IRE for use by future connections. */
22357 	if (mp == NULL)
22358 		return (0);
22359 
22360 	/*
22361 	 * We do not have a good algorithm to update ssthresh at this time.
22362 	 * So don't do any update.
22363 	 */
22364 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22365 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22366 
22367 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22368 
22369 	return (0);
22370 }
22371 
22372 /* ARGSUSED */
22373 void
22374 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
22375 {
22376 	conn_t *connp = (conn_t *)arg;
22377 	mblk_t *mp1;
22378 	tcp_t *tcp = connp->conn_tcp;
22379 	tcp_xmit_reset_event_t *eventp;
22380 
22381 	ASSERT(mp->b_datap->db_type == M_PROTO &&
22382 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
22383 
22384 	if (tcp->tcp_state != TCPS_LISTEN) {
22385 		freemsg(mp);
22386 		return;
22387 	}
22388 
22389 	mp1 = mp->b_cont;
22390 	mp->b_cont = NULL;
22391 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
22392 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
22393 	    connp->conn_netstack);
22394 
22395 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
22396 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
22397 	freemsg(mp);
22398 }
22399 
22400 /*
22401  * Generate a "no listener here" RST in response to an "unknown" segment.
22402  * connp is set by caller when RST is in response to an unexpected
22403  * inbound packet for which there is active tcp state in the system.
22404  * Note that we are reusing the incoming mp to construct the outgoing RST.
22405  */
22406 void
22407 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22408     tcp_stack_t *tcps, conn_t *connp)
22409 {
22410 	uchar_t		*rptr;
22411 	uint32_t	seg_len;
22412 	tcph_t		*tcph;
22413 	uint32_t	seg_seq;
22414 	uint32_t	seg_ack;
22415 	uint_t		flags;
22416 	mblk_t		*ipsec_mp;
22417 	ipha_t 		*ipha;
22418 	ip6_t 		*ip6h;
22419 	boolean_t	mctl_present = B_FALSE;
22420 	boolean_t	check = B_TRUE;
22421 	boolean_t	policy_present;
22422 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22423 
22424 	TCP_STAT(tcps, tcp_no_listener);
22425 
22426 	ipsec_mp = mp;
22427 
22428 	if (mp->b_datap->db_type == M_CTL) {
22429 		ipsec_in_t *ii;
22430 
22431 		mctl_present = B_TRUE;
22432 		mp = mp->b_cont;
22433 
22434 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22435 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22436 		if (ii->ipsec_in_dont_check) {
22437 			check = B_FALSE;
22438 			if (!ii->ipsec_in_secure) {
22439 				freeb(ipsec_mp);
22440 				mctl_present = B_FALSE;
22441 				ipsec_mp = mp;
22442 			}
22443 		}
22444 	}
22445 
22446 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22447 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22448 		ipha = (ipha_t *)mp->b_rptr;
22449 		ip6h = NULL;
22450 	} else {
22451 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22452 		ipha = NULL;
22453 		ip6h = (ip6_t *)mp->b_rptr;
22454 	}
22455 
22456 	if (check && policy_present) {
22457 		/*
22458 		 * The conn_t parameter is NULL because we already know
22459 		 * nobody's home.
22460 		 */
22461 		ipsec_mp = ipsec_check_global_policy(
22462 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22463 		    tcps->tcps_netstack);
22464 		if (ipsec_mp == NULL)
22465 			return;
22466 	}
22467 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22468 		DTRACE_PROBE2(
22469 		    tx__ip__log__error__nolistener__tcp,
22470 		    char *, "Could not reply with RST to mp(1)",
22471 		    mblk_t *, mp);
22472 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22473 		freemsg(ipsec_mp);
22474 		return;
22475 	}
22476 
22477 	rptr = mp->b_rptr;
22478 
22479 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22480 	seg_seq = BE32_TO_U32(tcph->th_seq);
22481 	seg_ack = BE32_TO_U32(tcph->th_ack);
22482 	flags = tcph->th_flags[0];
22483 
22484 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22485 	if (flags & TH_RST) {
22486 		freemsg(ipsec_mp);
22487 	} else if (flags & TH_ACK) {
22488 		tcp_xmit_early_reset("no tcp, reset",
22489 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22490 		    connp);
22491 	} else {
22492 		if (flags & TH_SYN) {
22493 			seg_len++;
22494 		} else {
22495 			/*
22496 			 * Here we violate the RFC.  Note that a normal
22497 			 * TCP will never send a segment without the ACK
22498 			 * flag, except for RST or SYN segment.  This
22499 			 * segment is neither.  Just drop it on the
22500 			 * floor.
22501 			 */
22502 			freemsg(ipsec_mp);
22503 			tcps->tcps_rst_unsent++;
22504 			return;
22505 		}
22506 
22507 		tcp_xmit_early_reset("no tcp, reset/ack",
22508 		    ipsec_mp, 0, seg_seq + seg_len,
22509 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22510 	}
22511 }
22512 
22513 /*
22514  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22515  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22516  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22517  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22518  * otherwise it will dup partial mblks.)
22519  * Otherwise, an appropriate ACK packet will be generated.  This
22520  * routine is not usually called to send new data for the first time.  It
22521  * is mostly called out of the timer for retransmits, and to generate ACKs.
22522  *
22523  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22524  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22525  * of the original mblk chain will be returned in *offset and *end_mp.
22526  */
22527 mblk_t *
22528 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22529     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22530     boolean_t rexmit)
22531 {
22532 	int	data_length;
22533 	int32_t	off = 0;
22534 	uint_t	flags;
22535 	mblk_t	*mp1;
22536 	mblk_t	*mp2;
22537 	uchar_t	*rptr;
22538 	tcph_t	*tcph;
22539 	int32_t	num_sack_blk = 0;
22540 	int32_t	sack_opt_len = 0;
22541 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22542 
22543 	/* Allocate for our maximum TCP header + link-level */
22544 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22545 	    tcps->tcps_wroff_xtra, BPRI_MED);
22546 	if (!mp1)
22547 		return (NULL);
22548 	data_length = 0;
22549 
22550 	/*
22551 	 * Note that tcp_mss has been adjusted to take into account the
22552 	 * timestamp option if applicable.  Because SACK options do not
22553 	 * appear in every TCP segments and they are of variable lengths,
22554 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22555 	 * the actual segment length when we need to send a segment which
22556 	 * includes SACK options.
22557 	 */
22558 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22559 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22560 		    tcp->tcp_num_sack_blk);
22561 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22562 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22563 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22564 			max_to_send -= sack_opt_len;
22565 	}
22566 
22567 	if (offset != NULL) {
22568 		off = *offset;
22569 		/* We use offset as an indicator that end_mp is not NULL. */
22570 		*end_mp = NULL;
22571 	}
22572 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22573 		/* This could be faster with cooperation from downstream */
22574 		if (mp2 != mp1 && !sendall &&
22575 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22576 		    max_to_send)
22577 			/*
22578 			 * Don't send the next mblk since the whole mblk
22579 			 * does not fit.
22580 			 */
22581 			break;
22582 		mp2->b_cont = dupb(mp);
22583 		mp2 = mp2->b_cont;
22584 		if (!mp2) {
22585 			freemsg(mp1);
22586 			return (NULL);
22587 		}
22588 		mp2->b_rptr += off;
22589 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22590 		    (uintptr_t)INT_MAX);
22591 
22592 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22593 		if (data_length > max_to_send) {
22594 			mp2->b_wptr -= data_length - max_to_send;
22595 			data_length = max_to_send;
22596 			off = mp2->b_wptr - mp->b_rptr;
22597 			break;
22598 		} else {
22599 			off = 0;
22600 		}
22601 	}
22602 	if (offset != NULL) {
22603 		*offset = off;
22604 		*end_mp = mp;
22605 	}
22606 	if (seg_len != NULL) {
22607 		*seg_len = data_length;
22608 	}
22609 
22610 	/* Update the latest receive window size in TCP header. */
22611 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22612 	    tcp->tcp_tcph->th_win);
22613 
22614 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22615 	mp1->b_rptr = rptr;
22616 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22617 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22618 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22619 	U32_TO_ABE32(seq, tcph->th_seq);
22620 
22621 	/*
22622 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22623 	 * that this function was called from tcp_wput_data. Thus, when called
22624 	 * to retransmit data the setting of the PUSH bit may appear some
22625 	 * what random in that it might get set when it should not. This
22626 	 * should not pose any performance issues.
22627 	 */
22628 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22629 	    tcp->tcp_unsent == data_length)) {
22630 		flags = TH_ACK | TH_PUSH;
22631 	} else {
22632 		flags = TH_ACK;
22633 	}
22634 
22635 	if (tcp->tcp_ecn_ok) {
22636 		if (tcp->tcp_ecn_echo_on)
22637 			flags |= TH_ECE;
22638 
22639 		/*
22640 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22641 		 * There is no TCP flow control for non-data segments, and
22642 		 * only data segment is transmitted reliably.
22643 		 */
22644 		if (data_length > 0 && !rexmit) {
22645 			SET_ECT(tcp, rptr);
22646 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22647 				flags |= TH_CWR;
22648 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22649 			}
22650 		}
22651 	}
22652 
22653 	if (tcp->tcp_valid_bits) {
22654 		uint32_t u1;
22655 
22656 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22657 		    seq == tcp->tcp_iss) {
22658 			uchar_t	*wptr;
22659 
22660 			/*
22661 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22662 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22663 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22664 			 * our SYN is not ack'ed but the app closes this
22665 			 * TCP connection.
22666 			 */
22667 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22668 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22669 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22670 
22671 			/*
22672 			 * Tack on the MSS option.  It is always needed
22673 			 * for both active and passive open.
22674 			 *
22675 			 * MSS option value should be interface MTU - MIN
22676 			 * TCP/IP header according to RFC 793 as it means
22677 			 * the maximum segment size TCP can receive.  But
22678 			 * to get around some broken middle boxes/end hosts
22679 			 * out there, we allow the option value to be the
22680 			 * same as the MSS option size on the peer side.
22681 			 * In this way, the other side will not send
22682 			 * anything larger than they can receive.
22683 			 *
22684 			 * Note that for SYN_SENT state, the ndd param
22685 			 * tcp_use_smss_as_mss_opt has no effect as we
22686 			 * don't know the peer's MSS option value. So
22687 			 * the only case we need to take care of is in
22688 			 * SYN_RCVD state, which is done later.
22689 			 */
22690 			wptr = mp1->b_wptr;
22691 			wptr[0] = TCPOPT_MAXSEG;
22692 			wptr[1] = TCPOPT_MAXSEG_LEN;
22693 			wptr += 2;
22694 			u1 = tcp->tcp_if_mtu -
22695 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22696 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22697 			    TCP_MIN_HEADER_LENGTH;
22698 			U16_TO_BE16(u1, wptr);
22699 			mp1->b_wptr = wptr + 2;
22700 			/* Update the offset to cover the additional word */
22701 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22702 
22703 			/*
22704 			 * Note that the following way of filling in
22705 			 * TCP options are not optimal.  Some NOPs can
22706 			 * be saved.  But there is no need at this time
22707 			 * to optimize it.  When it is needed, we will
22708 			 * do it.
22709 			 */
22710 			switch (tcp->tcp_state) {
22711 			case TCPS_SYN_SENT:
22712 				flags = TH_SYN;
22713 
22714 				if (tcp->tcp_snd_ts_ok) {
22715 					uint32_t llbolt = (uint32_t)lbolt;
22716 
22717 					wptr = mp1->b_wptr;
22718 					wptr[0] = TCPOPT_NOP;
22719 					wptr[1] = TCPOPT_NOP;
22720 					wptr[2] = TCPOPT_TSTAMP;
22721 					wptr[3] = TCPOPT_TSTAMP_LEN;
22722 					wptr += 4;
22723 					U32_TO_BE32(llbolt, wptr);
22724 					wptr += 4;
22725 					ASSERT(tcp->tcp_ts_recent == 0);
22726 					U32_TO_BE32(0L, wptr);
22727 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22728 					tcph->th_offset_and_rsrvd[0] +=
22729 					    (3 << 4);
22730 				}
22731 
22732 				/*
22733 				 * Set up all the bits to tell other side
22734 				 * we are ECN capable.
22735 				 */
22736 				if (tcp->tcp_ecn_ok) {
22737 					flags |= (TH_ECE | TH_CWR);
22738 				}
22739 				break;
22740 			case TCPS_SYN_RCVD:
22741 				flags |= TH_SYN;
22742 
22743 				/*
22744 				 * Reset the MSS option value to be SMSS
22745 				 * We should probably add back the bytes
22746 				 * for timestamp option and IPsec.  We
22747 				 * don't do that as this is a workaround
22748 				 * for broken middle boxes/end hosts, it
22749 				 * is better for us to be more cautious.
22750 				 * They may not take these things into
22751 				 * account in their SMSS calculation.  Thus
22752 				 * the peer's calculated SMSS may be smaller
22753 				 * than what it can be.  This should be OK.
22754 				 */
22755 				if (tcps->tcps_use_smss_as_mss_opt) {
22756 					u1 = tcp->tcp_mss;
22757 					U16_TO_BE16(u1, wptr);
22758 				}
22759 
22760 				/*
22761 				 * If the other side is ECN capable, reply
22762 				 * that we are also ECN capable.
22763 				 */
22764 				if (tcp->tcp_ecn_ok)
22765 					flags |= TH_ECE;
22766 				break;
22767 			default:
22768 				/*
22769 				 * The above ASSERT() makes sure that this
22770 				 * must be FIN-WAIT-1 state.  Our SYN has
22771 				 * not been ack'ed so retransmit it.
22772 				 */
22773 				flags |= TH_SYN;
22774 				break;
22775 			}
22776 
22777 			if (tcp->tcp_snd_ws_ok) {
22778 				wptr = mp1->b_wptr;
22779 				wptr[0] =  TCPOPT_NOP;
22780 				wptr[1] =  TCPOPT_WSCALE;
22781 				wptr[2] =  TCPOPT_WS_LEN;
22782 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22783 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22784 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22785 			}
22786 
22787 			if (tcp->tcp_snd_sack_ok) {
22788 				wptr = mp1->b_wptr;
22789 				wptr[0] = TCPOPT_NOP;
22790 				wptr[1] = TCPOPT_NOP;
22791 				wptr[2] = TCPOPT_SACK_PERMITTED;
22792 				wptr[3] = TCPOPT_SACK_OK_LEN;
22793 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22794 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22795 			}
22796 
22797 			/* allocb() of adequate mblk assures space */
22798 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22799 			    (uintptr_t)INT_MAX);
22800 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22801 			/*
22802 			 * Get IP set to checksum on our behalf
22803 			 * Include the adjustment for a source route if any.
22804 			 */
22805 			u1 += tcp->tcp_sum;
22806 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22807 			U16_TO_BE16(u1, tcph->th_sum);
22808 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22809 		}
22810 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22811 		    (seq + data_length) == tcp->tcp_fss) {
22812 			if (!tcp->tcp_fin_acked) {
22813 				flags |= TH_FIN;
22814 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22815 			}
22816 			if (!tcp->tcp_fin_sent) {
22817 				tcp->tcp_fin_sent = B_TRUE;
22818 				switch (tcp->tcp_state) {
22819 				case TCPS_SYN_RCVD:
22820 				case TCPS_ESTABLISHED:
22821 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22822 					break;
22823 				case TCPS_CLOSE_WAIT:
22824 					tcp->tcp_state = TCPS_LAST_ACK;
22825 					break;
22826 				}
22827 				if (tcp->tcp_suna == tcp->tcp_snxt)
22828 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22829 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22830 			}
22831 		}
22832 		/*
22833 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22834 		 * is smaller than seq, u1 will become a very huge value.
22835 		 * So the comparison will fail.  Also note that tcp_urp
22836 		 * should be positive, see RFC 793 page 17.
22837 		 */
22838 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22839 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22840 		    u1 < (uint32_t)(64 * 1024)) {
22841 			flags |= TH_URG;
22842 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
22843 			U32_TO_ABE16(u1, tcph->th_urp);
22844 		}
22845 	}
22846 	tcph->th_flags[0] = (uchar_t)flags;
22847 	tcp->tcp_rack = tcp->tcp_rnxt;
22848 	tcp->tcp_rack_cnt = 0;
22849 
22850 	if (tcp->tcp_snd_ts_ok) {
22851 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22852 			uint32_t llbolt = (uint32_t)lbolt;
22853 
22854 			U32_TO_BE32(llbolt,
22855 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22856 			U32_TO_BE32(tcp->tcp_ts_recent,
22857 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22858 		}
22859 	}
22860 
22861 	if (num_sack_blk > 0) {
22862 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22863 		sack_blk_t *tmp;
22864 		int32_t	i;
22865 
22866 		wptr[0] = TCPOPT_NOP;
22867 		wptr[1] = TCPOPT_NOP;
22868 		wptr[2] = TCPOPT_SACK;
22869 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22870 		    sizeof (sack_blk_t);
22871 		wptr += TCPOPT_REAL_SACK_LEN;
22872 
22873 		tmp = tcp->tcp_sack_list;
22874 		for (i = 0; i < num_sack_blk; i++) {
22875 			U32_TO_BE32(tmp[i].begin, wptr);
22876 			wptr += sizeof (tcp_seq);
22877 			U32_TO_BE32(tmp[i].end, wptr);
22878 			wptr += sizeof (tcp_seq);
22879 		}
22880 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22881 	}
22882 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22883 	data_length += (int)(mp1->b_wptr - rptr);
22884 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22885 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22886 	} else {
22887 		ip6_t *ip6 = (ip6_t *)(rptr +
22888 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22889 		    sizeof (ip6i_t) : 0));
22890 
22891 		ip6->ip6_plen = htons(data_length -
22892 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22893 	}
22894 
22895 	/*
22896 	 * Prime pump for IP
22897 	 * Include the adjustment for a source route if any.
22898 	 */
22899 	data_length -= tcp->tcp_ip_hdr_len;
22900 	data_length += tcp->tcp_sum;
22901 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22902 	U16_TO_ABE16(data_length, tcph->th_sum);
22903 	if (tcp->tcp_ip_forward_progress) {
22904 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22905 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22906 		tcp->tcp_ip_forward_progress = B_FALSE;
22907 	}
22908 	return (mp1);
22909 }
22910 
22911 /* This function handles the push timeout. */
22912 void
22913 tcp_push_timer(void *arg)
22914 {
22915 	conn_t	*connp = (conn_t *)arg;
22916 	tcp_t *tcp = connp->conn_tcp;
22917 
22918 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
22919 
22920 	ASSERT(tcp->tcp_listener == NULL);
22921 
22922 	ASSERT(!IPCL_IS_NONSTR(connp));
22923 
22924 	tcp->tcp_push_tid = 0;
22925 
22926 	if (tcp->tcp_rcv_list != NULL &&
22927 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
22928 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22929 }
22930 
22931 /*
22932  * This function handles delayed ACK timeout.
22933  */
22934 static void
22935 tcp_ack_timer(void *arg)
22936 {
22937 	conn_t	*connp = (conn_t *)arg;
22938 	tcp_t *tcp = connp->conn_tcp;
22939 	mblk_t *mp;
22940 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22941 
22942 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
22943 
22944 	tcp->tcp_ack_tid = 0;
22945 
22946 	if (tcp->tcp_fused)
22947 		return;
22948 
22949 	/*
22950 	 * Do not send ACK if there is no outstanding unack'ed data.
22951 	 */
22952 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22953 		return;
22954 	}
22955 
22956 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22957 		/*
22958 		 * Make sure we don't allow deferred ACKs to result in
22959 		 * timer-based ACKing.  If we have held off an ACK
22960 		 * when there was more than an mss here, and the timer
22961 		 * goes off, we have to worry about the possibility
22962 		 * that the sender isn't doing slow-start, or is out
22963 		 * of step with us for some other reason.  We fall
22964 		 * permanently back in the direction of
22965 		 * ACK-every-other-packet as suggested in RFC 1122.
22966 		 */
22967 		if (tcp->tcp_rack_abs_max > 2)
22968 			tcp->tcp_rack_abs_max--;
22969 		tcp->tcp_rack_cur_max = 2;
22970 	}
22971 	mp = tcp_ack_mp(tcp);
22972 
22973 	if (mp != NULL) {
22974 		BUMP_LOCAL(tcp->tcp_obsegs);
22975 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22976 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
22977 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22978 	}
22979 }
22980 
22981 
22982 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22983 static mblk_t *
22984 tcp_ack_mp(tcp_t *tcp)
22985 {
22986 	uint32_t	seq_no;
22987 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22988 
22989 	/*
22990 	 * There are a few cases to be considered while setting the sequence no.
22991 	 * Essentially, we can come here while processing an unacceptable pkt
22992 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
22993 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
22994 	 * If we are here for a zero window probe, stick with suna. In all
22995 	 * other cases, we check if suna + swnd encompasses snxt and set
22996 	 * the sequence number to snxt, if so. If snxt falls outside the
22997 	 * window (the receiver probably shrunk its window), we will go with
22998 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
22999 	 * receiver.
23000 	 */
23001 	if (tcp->tcp_zero_win_probe) {
23002 		seq_no = tcp->tcp_suna;
23003 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23004 		ASSERT(tcp->tcp_swnd == 0);
23005 		seq_no = tcp->tcp_snxt;
23006 	} else {
23007 		seq_no = SEQ_GT(tcp->tcp_snxt,
23008 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23009 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23010 	}
23011 
23012 	if (tcp->tcp_valid_bits) {
23013 		/*
23014 		 * For the complex case where we have to send some
23015 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23016 		 */
23017 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23018 		    NULL, B_FALSE));
23019 	} else {
23020 		/* Generate a simple ACK */
23021 		int	data_length;
23022 		uchar_t	*rptr;
23023 		tcph_t	*tcph;
23024 		mblk_t	*mp1;
23025 		int32_t	tcp_hdr_len;
23026 		int32_t	tcp_tcp_hdr_len;
23027 		int32_t	num_sack_blk = 0;
23028 		int32_t sack_opt_len;
23029 
23030 		/*
23031 		 * Allocate space for TCP + IP headers
23032 		 * and link-level header
23033 		 */
23034 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23035 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23036 			    tcp->tcp_num_sack_blk);
23037 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23038 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23039 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23040 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23041 		} else {
23042 			tcp_hdr_len = tcp->tcp_hdr_len;
23043 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23044 		}
23045 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23046 		if (!mp1)
23047 			return (NULL);
23048 
23049 		/* Update the latest receive window size in TCP header. */
23050 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23051 		    tcp->tcp_tcph->th_win);
23052 		/* copy in prototype TCP + IP header */
23053 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23054 		mp1->b_rptr = rptr;
23055 		mp1->b_wptr = rptr + tcp_hdr_len;
23056 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23057 
23058 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23059 
23060 		/* Set the TCP sequence number. */
23061 		U32_TO_ABE32(seq_no, tcph->th_seq);
23062 
23063 		/* Set up the TCP flag field. */
23064 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23065 		if (tcp->tcp_ecn_echo_on)
23066 			tcph->th_flags[0] |= TH_ECE;
23067 
23068 		tcp->tcp_rack = tcp->tcp_rnxt;
23069 		tcp->tcp_rack_cnt = 0;
23070 
23071 		/* fill in timestamp option if in use */
23072 		if (tcp->tcp_snd_ts_ok) {
23073 			uint32_t llbolt = (uint32_t)lbolt;
23074 
23075 			U32_TO_BE32(llbolt,
23076 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23077 			U32_TO_BE32(tcp->tcp_ts_recent,
23078 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23079 		}
23080 
23081 		/* Fill in SACK options */
23082 		if (num_sack_blk > 0) {
23083 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23084 			sack_blk_t *tmp;
23085 			int32_t	i;
23086 
23087 			wptr[0] = TCPOPT_NOP;
23088 			wptr[1] = TCPOPT_NOP;
23089 			wptr[2] = TCPOPT_SACK;
23090 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23091 			    sizeof (sack_blk_t);
23092 			wptr += TCPOPT_REAL_SACK_LEN;
23093 
23094 			tmp = tcp->tcp_sack_list;
23095 			for (i = 0; i < num_sack_blk; i++) {
23096 				U32_TO_BE32(tmp[i].begin, wptr);
23097 				wptr += sizeof (tcp_seq);
23098 				U32_TO_BE32(tmp[i].end, wptr);
23099 				wptr += sizeof (tcp_seq);
23100 			}
23101 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23102 			    << 4);
23103 		}
23104 
23105 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23106 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23107 		} else {
23108 			/* Check for ip6i_t header in sticky hdrs */
23109 			ip6_t *ip6 = (ip6_t *)(rptr +
23110 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23111 			    sizeof (ip6i_t) : 0));
23112 
23113 			ip6->ip6_plen = htons(tcp_hdr_len -
23114 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23115 		}
23116 
23117 		/*
23118 		 * Prime pump for checksum calculation in IP.  Include the
23119 		 * adjustment for a source route if any.
23120 		 */
23121 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23122 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23123 		U16_TO_ABE16(data_length, tcph->th_sum);
23124 
23125 		if (tcp->tcp_ip_forward_progress) {
23126 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23127 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23128 			tcp->tcp_ip_forward_progress = B_FALSE;
23129 		}
23130 		return (mp1);
23131 	}
23132 }
23133 
23134 /*
23135  * Hash list insertion routine for tcp_t structures. Each hash bucket
23136  * contains a list of tcp_t entries, and each entry is bound to a unique
23137  * port. If there are multiple tcp_t's that are bound to the same port, then
23138  * one of them will be linked into the hash bucket list, and the rest will
23139  * hang off of that one entry. For each port, entries bound to a specific IP
23140  * address will be inserted before those those bound to INADDR_ANY.
23141  */
23142 static void
23143 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23144 {
23145 	tcp_t	**tcpp;
23146 	tcp_t	*tcpnext;
23147 	tcp_t	*tcphash;
23148 
23149 	if (tcp->tcp_ptpbhn != NULL) {
23150 		ASSERT(!caller_holds_lock);
23151 		tcp_bind_hash_remove(tcp);
23152 	}
23153 	tcpp = &tbf->tf_tcp;
23154 	if (!caller_holds_lock) {
23155 		mutex_enter(&tbf->tf_lock);
23156 	} else {
23157 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23158 	}
23159 	tcphash = tcpp[0];
23160 	tcpnext = NULL;
23161 	if (tcphash != NULL) {
23162 		/* Look for an entry using the same port */
23163 		while ((tcphash = tcpp[0]) != NULL &&
23164 		    tcp->tcp_lport != tcphash->tcp_lport)
23165 			tcpp = &(tcphash->tcp_bind_hash);
23166 
23167 		/* The port was not found, just add to the end */
23168 		if (tcphash == NULL)
23169 			goto insert;
23170 
23171 		/*
23172 		 * OK, there already exists an entry bound to the
23173 		 * same port.
23174 		 *
23175 		 * If the new tcp bound to the INADDR_ANY address
23176 		 * and the first one in the list is not bound to
23177 		 * INADDR_ANY we skip all entries until we find the
23178 		 * first one bound to INADDR_ANY.
23179 		 * This makes sure that applications binding to a
23180 		 * specific address get preference over those binding to
23181 		 * INADDR_ANY.
23182 		 */
23183 		tcpnext = tcphash;
23184 		tcphash = NULL;
23185 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23186 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23187 			while ((tcpnext = tcpp[0]) != NULL &&
23188 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23189 				tcpp = &(tcpnext->tcp_bind_hash_port);
23190 
23191 			if (tcpnext) {
23192 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23193 				tcphash = tcpnext->tcp_bind_hash;
23194 				if (tcphash != NULL) {
23195 					tcphash->tcp_ptpbhn =
23196 					    &(tcp->tcp_bind_hash);
23197 					tcpnext->tcp_bind_hash = NULL;
23198 				}
23199 			}
23200 		} else {
23201 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23202 			tcphash = tcpnext->tcp_bind_hash;
23203 			if (tcphash != NULL) {
23204 				tcphash->tcp_ptpbhn =
23205 				    &(tcp->tcp_bind_hash);
23206 				tcpnext->tcp_bind_hash = NULL;
23207 			}
23208 		}
23209 	}
23210 insert:
23211 	tcp->tcp_bind_hash_port = tcpnext;
23212 	tcp->tcp_bind_hash = tcphash;
23213 	tcp->tcp_ptpbhn = tcpp;
23214 	tcpp[0] = tcp;
23215 	if (!caller_holds_lock)
23216 		mutex_exit(&tbf->tf_lock);
23217 }
23218 
23219 /*
23220  * Hash list removal routine for tcp_t structures.
23221  */
23222 static void
23223 tcp_bind_hash_remove(tcp_t *tcp)
23224 {
23225 	tcp_t	*tcpnext;
23226 	kmutex_t *lockp;
23227 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23228 
23229 	if (tcp->tcp_ptpbhn == NULL)
23230 		return;
23231 
23232 	/*
23233 	 * Extract the lock pointer in case there are concurrent
23234 	 * hash_remove's for this instance.
23235 	 */
23236 	ASSERT(tcp->tcp_lport != 0);
23237 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23238 
23239 	ASSERT(lockp != NULL);
23240 	mutex_enter(lockp);
23241 	if (tcp->tcp_ptpbhn) {
23242 		tcpnext = tcp->tcp_bind_hash_port;
23243 		if (tcpnext != NULL) {
23244 			tcp->tcp_bind_hash_port = NULL;
23245 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23246 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23247 			if (tcpnext->tcp_bind_hash != NULL) {
23248 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23249 				    &(tcpnext->tcp_bind_hash);
23250 				tcp->tcp_bind_hash = NULL;
23251 			}
23252 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23253 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23254 			tcp->tcp_bind_hash = NULL;
23255 		}
23256 		*tcp->tcp_ptpbhn = tcpnext;
23257 		tcp->tcp_ptpbhn = NULL;
23258 	}
23259 	mutex_exit(lockp);
23260 }
23261 
23262 
23263 /*
23264  * Hash list lookup routine for tcp_t structures.
23265  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23266  */
23267 static tcp_t *
23268 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23269 {
23270 	tf_t	*tf;
23271 	tcp_t	*tcp;
23272 
23273 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23274 	mutex_enter(&tf->tf_lock);
23275 	for (tcp = tf->tf_tcp; tcp != NULL;
23276 	    tcp = tcp->tcp_acceptor_hash) {
23277 		if (tcp->tcp_acceptor_id == id) {
23278 			CONN_INC_REF(tcp->tcp_connp);
23279 			mutex_exit(&tf->tf_lock);
23280 			return (tcp);
23281 		}
23282 	}
23283 	mutex_exit(&tf->tf_lock);
23284 	return (NULL);
23285 }
23286 
23287 
23288 /*
23289  * Hash list insertion routine for tcp_t structures.
23290  */
23291 void
23292 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23293 {
23294 	tf_t	*tf;
23295 	tcp_t	**tcpp;
23296 	tcp_t	*tcpnext;
23297 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23298 
23299 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23300 
23301 	if (tcp->tcp_ptpahn != NULL)
23302 		tcp_acceptor_hash_remove(tcp);
23303 	tcpp = &tf->tf_tcp;
23304 	mutex_enter(&tf->tf_lock);
23305 	tcpnext = tcpp[0];
23306 	if (tcpnext)
23307 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23308 	tcp->tcp_acceptor_hash = tcpnext;
23309 	tcp->tcp_ptpahn = tcpp;
23310 	tcpp[0] = tcp;
23311 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23312 	mutex_exit(&tf->tf_lock);
23313 }
23314 
23315 /*
23316  * Hash list removal routine for tcp_t structures.
23317  */
23318 static void
23319 tcp_acceptor_hash_remove(tcp_t *tcp)
23320 {
23321 	tcp_t	*tcpnext;
23322 	kmutex_t *lockp;
23323 
23324 	/*
23325 	 * Extract the lock pointer in case there are concurrent
23326 	 * hash_remove's for this instance.
23327 	 */
23328 	lockp = tcp->tcp_acceptor_lockp;
23329 
23330 	if (tcp->tcp_ptpahn == NULL)
23331 		return;
23332 
23333 	ASSERT(lockp != NULL);
23334 	mutex_enter(lockp);
23335 	if (tcp->tcp_ptpahn) {
23336 		tcpnext = tcp->tcp_acceptor_hash;
23337 		if (tcpnext) {
23338 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23339 			tcp->tcp_acceptor_hash = NULL;
23340 		}
23341 		*tcp->tcp_ptpahn = tcpnext;
23342 		tcp->tcp_ptpahn = NULL;
23343 	}
23344 	mutex_exit(lockp);
23345 	tcp->tcp_acceptor_lockp = NULL;
23346 }
23347 
23348 /*
23349  * Type three generator adapted from the random() function in 4.4 BSD:
23350  */
23351 
23352 /*
23353  * Copyright (c) 1983, 1993
23354  *	The Regents of the University of California.  All rights reserved.
23355  *
23356  * Redistribution and use in source and binary forms, with or without
23357  * modification, are permitted provided that the following conditions
23358  * are met:
23359  * 1. Redistributions of source code must retain the above copyright
23360  *    notice, this list of conditions and the following disclaimer.
23361  * 2. Redistributions in binary form must reproduce the above copyright
23362  *    notice, this list of conditions and the following disclaimer in the
23363  *    documentation and/or other materials provided with the distribution.
23364  * 3. All advertising materials mentioning features or use of this software
23365  *    must display the following acknowledgement:
23366  *	This product includes software developed by the University of
23367  *	California, Berkeley and its contributors.
23368  * 4. Neither the name of the University nor the names of its contributors
23369  *    may be used to endorse or promote products derived from this software
23370  *    without specific prior written permission.
23371  *
23372  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23373  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23374  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23375  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23376  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23377  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23378  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23379  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23380  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23381  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23382  * SUCH DAMAGE.
23383  */
23384 
23385 /* Type 3 -- x**31 + x**3 + 1 */
23386 #define	DEG_3		31
23387 #define	SEP_3		3
23388 
23389 
23390 /* Protected by tcp_random_lock */
23391 static int tcp_randtbl[DEG_3 + 1];
23392 
23393 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23394 static int *tcp_random_rptr = &tcp_randtbl[1];
23395 
23396 static int *tcp_random_state = &tcp_randtbl[1];
23397 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23398 
23399 kmutex_t tcp_random_lock;
23400 
23401 void
23402 tcp_random_init(void)
23403 {
23404 	int i;
23405 	hrtime_t hrt;
23406 	time_t wallclock;
23407 	uint64_t result;
23408 
23409 	/*
23410 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23411 	 * a longlong, which may contain resolution down to nanoseconds.
23412 	 * The current time will either be a 32-bit or a 64-bit quantity.
23413 	 * XOR the two together in a 64-bit result variable.
23414 	 * Convert the result to a 32-bit value by multiplying the high-order
23415 	 * 32-bits by the low-order 32-bits.
23416 	 */
23417 
23418 	hrt = gethrtime();
23419 	(void) drv_getparm(TIME, &wallclock);
23420 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23421 	mutex_enter(&tcp_random_lock);
23422 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23423 	    (result & 0xffffffff);
23424 
23425 	for (i = 1; i < DEG_3; i++)
23426 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23427 		    + 12345;
23428 	tcp_random_fptr = &tcp_random_state[SEP_3];
23429 	tcp_random_rptr = &tcp_random_state[0];
23430 	mutex_exit(&tcp_random_lock);
23431 	for (i = 0; i < 10 * DEG_3; i++)
23432 		(void) tcp_random();
23433 }
23434 
23435 /*
23436  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23437  * This range is selected to be approximately centered on TCP_ISS / 2,
23438  * and easy to compute. We get this value by generating a 32-bit random
23439  * number, selecting out the high-order 17 bits, and then adding one so
23440  * that we never return zero.
23441  */
23442 int
23443 tcp_random(void)
23444 {
23445 	int i;
23446 
23447 	mutex_enter(&tcp_random_lock);
23448 	*tcp_random_fptr += *tcp_random_rptr;
23449 
23450 	/*
23451 	 * The high-order bits are more random than the low-order bits,
23452 	 * so we select out the high-order 17 bits and add one so that
23453 	 * we never return zero.
23454 	 */
23455 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23456 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23457 		tcp_random_fptr = tcp_random_state;
23458 		++tcp_random_rptr;
23459 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23460 		tcp_random_rptr = tcp_random_state;
23461 
23462 	mutex_exit(&tcp_random_lock);
23463 	return (i);
23464 }
23465 
23466 static int
23467 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23468     int *t_errorp, int *sys_errorp)
23469 {
23470 	int error;
23471 	int is_absreq_failure;
23472 	t_scalar_t *opt_lenp;
23473 	t_scalar_t opt_offset;
23474 	int prim_type;
23475 	struct T_conn_req *tcreqp;
23476 	struct T_conn_res *tcresp;
23477 	cred_t *cr;
23478 
23479 	/*
23480 	 * All Solaris components should pass a db_credp
23481 	 * for this TPI message, hence we ASSERT.
23482 	 * But in case there is some other M_PROTO that looks
23483 	 * like a TPI message sent by some other kernel
23484 	 * component, we check and return an error.
23485 	 */
23486 	cr = msg_getcred(mp, NULL);
23487 	ASSERT(cr != NULL);
23488 	if (cr == NULL)
23489 		return (-1);
23490 
23491 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23492 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23493 	    prim_type == T_CONN_RES);
23494 
23495 	switch (prim_type) {
23496 	case T_CONN_REQ:
23497 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23498 		opt_offset = tcreqp->OPT_offset;
23499 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23500 		break;
23501 	case O_T_CONN_RES:
23502 	case T_CONN_RES:
23503 		tcresp = (struct T_conn_res *)mp->b_rptr;
23504 		opt_offset = tcresp->OPT_offset;
23505 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23506 		break;
23507 	}
23508 
23509 	*t_errorp = 0;
23510 	*sys_errorp = 0;
23511 	*do_disconnectp = 0;
23512 
23513 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23514 	    opt_offset, cr, &tcp_opt_obj,
23515 	    NULL, &is_absreq_failure);
23516 
23517 	switch (error) {
23518 	case  0:		/* no error */
23519 		ASSERT(is_absreq_failure == 0);
23520 		return (0);
23521 	case ENOPROTOOPT:
23522 		*t_errorp = TBADOPT;
23523 		break;
23524 	case EACCES:
23525 		*t_errorp = TACCES;
23526 		break;
23527 	default:
23528 		*t_errorp = TSYSERR; *sys_errorp = error;
23529 		break;
23530 	}
23531 	if (is_absreq_failure != 0) {
23532 		/*
23533 		 * The connection request should get the local ack
23534 		 * T_OK_ACK and then a T_DISCON_IND.
23535 		 */
23536 		*do_disconnectp = 1;
23537 	}
23538 	return (-1);
23539 }
23540 
23541 /*
23542  * Split this function out so that if the secret changes, I'm okay.
23543  *
23544  * Initialize the tcp_iss_cookie and tcp_iss_key.
23545  */
23546 
23547 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23548 
23549 static void
23550 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
23551 {
23552 	struct {
23553 		int32_t current_time;
23554 		uint32_t randnum;
23555 		uint16_t pad;
23556 		uint8_t ether[6];
23557 		uint8_t passwd[PASSWD_SIZE];
23558 	} tcp_iss_cookie;
23559 	time_t t;
23560 
23561 	/*
23562 	 * Start with the current absolute time.
23563 	 */
23564 	(void) drv_getparm(TIME, &t);
23565 	tcp_iss_cookie.current_time = t;
23566 
23567 	/*
23568 	 * XXX - Need a more random number per RFC 1750, not this crap.
23569 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23570 	 */
23571 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23572 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23573 
23574 	/*
23575 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23576 	 * as a good template.
23577 	 */
23578 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23579 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23580 
23581 	/*
23582 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23583 	 */
23584 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23585 
23586 	/*
23587 	 * See 4010593 if this section becomes a problem again,
23588 	 * but the local ethernet address is useful here.
23589 	 */
23590 	(void) localetheraddr(NULL,
23591 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23592 
23593 	/*
23594 	 * Hash 'em all together.  The MD5Final is called per-connection.
23595 	 */
23596 	mutex_enter(&tcps->tcps_iss_key_lock);
23597 	MD5Init(&tcps->tcps_iss_key);
23598 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
23599 	    sizeof (tcp_iss_cookie));
23600 	mutex_exit(&tcps->tcps_iss_key_lock);
23601 }
23602 
23603 /*
23604  * Set the RFC 1948 pass phrase
23605  */
23606 /* ARGSUSED */
23607 static int
23608 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23609     cred_t *cr)
23610 {
23611 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23612 
23613 	/*
23614 	 * Basically, value contains a new pass phrase.  Pass it along!
23615 	 */
23616 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
23617 	return (0);
23618 }
23619 
23620 /* ARGSUSED */
23621 static int
23622 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23623 {
23624 	bzero(buf, sizeof (tcp_sack_info_t));
23625 	return (0);
23626 }
23627 
23628 /* ARGSUSED */
23629 static int
23630 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23631 {
23632 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23633 	return (0);
23634 }
23635 
23636 /*
23637  * Make sure we wait until the default queue is setup, yet allow
23638  * tcp_g_q_create() to open a TCP stream.
23639  * We need to allow tcp_g_q_create() do do an open
23640  * of tcp, hence we compare curhread.
23641  * All others have to wait until the tcps_g_q has been
23642  * setup.
23643  */
23644 void
23645 tcp_g_q_setup(tcp_stack_t *tcps)
23646 {
23647 	mutex_enter(&tcps->tcps_g_q_lock);
23648 	if (tcps->tcps_g_q != NULL) {
23649 		mutex_exit(&tcps->tcps_g_q_lock);
23650 		return;
23651 	}
23652 	if (tcps->tcps_g_q_creator == NULL) {
23653 		/* This thread will set it up */
23654 		tcps->tcps_g_q_creator = curthread;
23655 		mutex_exit(&tcps->tcps_g_q_lock);
23656 		tcp_g_q_create(tcps);
23657 		mutex_enter(&tcps->tcps_g_q_lock);
23658 		ASSERT(tcps->tcps_g_q_creator == curthread);
23659 		tcps->tcps_g_q_creator = NULL;
23660 		cv_signal(&tcps->tcps_g_q_cv);
23661 		ASSERT(tcps->tcps_g_q != NULL);
23662 		mutex_exit(&tcps->tcps_g_q_lock);
23663 		return;
23664 	}
23665 	/* Everybody but the creator has to wait */
23666 	if (tcps->tcps_g_q_creator != curthread) {
23667 		while (tcps->tcps_g_q == NULL)
23668 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
23669 	}
23670 	mutex_exit(&tcps->tcps_g_q_lock);
23671 }
23672 
23673 #define	IP	"ip"
23674 
23675 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
23676 
23677 /*
23678  * Create a default tcp queue here instead of in strplumb
23679  */
23680 void
23681 tcp_g_q_create(tcp_stack_t *tcps)
23682 {
23683 	int error;
23684 	ldi_handle_t	lh = NULL;
23685 	ldi_ident_t	li = NULL;
23686 	int		rval;
23687 	cred_t		*cr;
23688 	major_t IP_MAJ;
23689 
23690 #ifdef NS_DEBUG
23691 	(void) printf("tcp_g_q_create()\n");
23692 #endif
23693 
23694 	IP_MAJ = ddi_name_to_major(IP);
23695 
23696 	ASSERT(tcps->tcps_g_q_creator == curthread);
23697 
23698 	error = ldi_ident_from_major(IP_MAJ, &li);
23699 	if (error) {
23700 #ifdef DEBUG
23701 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
23702 		    error);
23703 #endif
23704 		return;
23705 	}
23706 
23707 	cr = zone_get_kcred(netstackid_to_zoneid(
23708 	    tcps->tcps_netstack->netstack_stackid));
23709 	ASSERT(cr != NULL);
23710 	/*
23711 	 * We set the tcp default queue to IPv6 because IPv4 falls
23712 	 * back to IPv6 when it can't find a client, but
23713 	 * IPv6 does not fall back to IPv4.
23714 	 */
23715 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
23716 	if (error) {
23717 #ifdef DEBUG
23718 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
23719 		    error);
23720 #endif
23721 		goto out;
23722 	}
23723 
23724 	/*
23725 	 * This ioctl causes the tcp framework to cache a pointer to
23726 	 * this stream, so we don't want to close the stream after
23727 	 * this operation.
23728 	 * Use the kernel credentials that are for the zone we're in.
23729 	 */
23730 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
23731 	    (intptr_t)0, FKIOCTL, cr, &rval);
23732 	if (error) {
23733 #ifdef DEBUG
23734 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
23735 		    "error %d\n", error);
23736 #endif
23737 		goto out;
23738 	}
23739 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
23740 	lh = NULL;
23741 out:
23742 	/* Close layered handles */
23743 	if (li)
23744 		ldi_ident_release(li);
23745 	/* Keep cred around until _inactive needs it */
23746 	tcps->tcps_g_q_cr = cr;
23747 }
23748 
23749 /*
23750  * We keep tcp_g_q set until all other tcp_t's in the zone
23751  * has gone away, and then when tcp_g_q_inactive() is called
23752  * we clear it.
23753  */
23754 void
23755 tcp_g_q_destroy(tcp_stack_t *tcps)
23756 {
23757 #ifdef NS_DEBUG
23758 	(void) printf("tcp_g_q_destroy()for stack %d\n",
23759 	    tcps->tcps_netstack->netstack_stackid);
23760 #endif
23761 
23762 	if (tcps->tcps_g_q == NULL) {
23763 		return;	/* Nothing to cleanup */
23764 	}
23765 	/*
23766 	 * Drop reference corresponding to the default queue.
23767 	 * This reference was added from tcp_open when the default queue
23768 	 * was created, hence we compensate for this extra drop in
23769 	 * tcp_g_q_close. If the refcnt drops to zero here it means
23770 	 * the default queue was the last one to be open, in which
23771 	 * case, then tcp_g_q_inactive will be
23772 	 * called as a result of the refrele.
23773 	 */
23774 	TCPS_REFRELE(tcps);
23775 }
23776 
23777 /*
23778  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23779  * Run by tcp_q_q_inactive using a taskq.
23780  */
23781 static void
23782 tcp_g_q_close(void *arg)
23783 {
23784 	tcp_stack_t *tcps = arg;
23785 	int error;
23786 	ldi_handle_t	lh = NULL;
23787 	ldi_ident_t	li = NULL;
23788 	cred_t		*cr;
23789 	major_t IP_MAJ;
23790 
23791 	IP_MAJ = ddi_name_to_major(IP);
23792 
23793 #ifdef NS_DEBUG
23794 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
23795 	    tcps->tcps_netstack->netstack_stackid,
23796 	    tcps->tcps_netstack->netstack_refcnt);
23797 #endif
23798 	lh = tcps->tcps_g_q_lh;
23799 	if (lh == NULL)
23800 		return;	/* Nothing to cleanup */
23801 
23802 	ASSERT(tcps->tcps_refcnt == 1);
23803 	ASSERT(tcps->tcps_g_q != NULL);
23804 
23805 	error = ldi_ident_from_major(IP_MAJ, &li);
23806 	if (error) {
23807 #ifdef DEBUG
23808 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
23809 		    error);
23810 #endif
23811 		return;
23812 	}
23813 
23814 	cr = tcps->tcps_g_q_cr;
23815 	tcps->tcps_g_q_cr = NULL;
23816 	ASSERT(cr != NULL);
23817 
23818 	/*
23819 	 * Make sure we can break the recursion when tcp_close decrements
23820 	 * the reference count causing g_q_inactive to be called again.
23821 	 */
23822 	tcps->tcps_g_q_lh = NULL;
23823 
23824 	/* close the default queue */
23825 	(void) ldi_close(lh, FREAD|FWRITE, cr);
23826 	/*
23827 	 * At this point in time tcps and the rest of netstack_t might
23828 	 * have been deleted.
23829 	 */
23830 	tcps = NULL;
23831 
23832 	/* Close layered handles */
23833 	ldi_ident_release(li);
23834 	crfree(cr);
23835 }
23836 
23837 /*
23838  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23839  *
23840  * Have to ensure that the ldi routines are not used by an
23841  * interrupt thread by using a taskq.
23842  */
23843 void
23844 tcp_g_q_inactive(tcp_stack_t *tcps)
23845 {
23846 	if (tcps->tcps_g_q_lh == NULL)
23847 		return;	/* Nothing to cleanup */
23848 
23849 	ASSERT(tcps->tcps_refcnt == 0);
23850 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
23851 
23852 	if (servicing_interrupt()) {
23853 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
23854 		    (void *) tcps, TQ_SLEEP);
23855 	} else {
23856 		tcp_g_q_close(tcps);
23857 	}
23858 }
23859 
23860 /*
23861  * Called by IP when IP is loaded into the kernel
23862  */
23863 void
23864 tcp_ddi_g_init(void)
23865 {
23866 	tcp_timercache = kmem_cache_create("tcp_timercache",
23867 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23868 	    NULL, NULL, NULL, NULL, NULL, 0);
23869 
23870 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23871 	    sizeof (tcp_sack_info_t), 0,
23872 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23873 
23874 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23875 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23876 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23877 
23878 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23879 
23880 	/* Initialize the random number generator */
23881 	tcp_random_init();
23882 
23883 	/* A single callback independently of how many netstacks we have */
23884 	ip_squeue_init(tcp_squeue_add);
23885 
23886 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
23887 
23888 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
23889 	    TASKQ_PREPOPULATE);
23890 
23891 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
23892 
23893 	/*
23894 	 * We want to be informed each time a stack is created or
23895 	 * destroyed in the kernel, so we can maintain the
23896 	 * set of tcp_stack_t's.
23897 	 */
23898 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
23899 	    tcp_stack_fini);
23900 }
23901 
23902 
23903 #define	INET_NAME	"ip"
23904 
23905 /*
23906  * Initialize the TCP stack instance.
23907  */
23908 static void *
23909 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
23910 {
23911 	tcp_stack_t	*tcps;
23912 	tcpparam_t	*pa;
23913 	int		i;
23914 	int		error = 0;
23915 	major_t		major;
23916 
23917 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
23918 	tcps->tcps_netstack = ns;
23919 
23920 	/* Initialize locks */
23921 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23922 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
23923 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23924 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23925 
23926 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
23927 	tcps->tcps_g_epriv_ports[0] = 2049;
23928 	tcps->tcps_g_epriv_ports[1] = 4045;
23929 	tcps->tcps_min_anonpriv_port = 512;
23930 
23931 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
23932 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
23933 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
23934 	    TCP_FANOUT_SIZE, KM_SLEEP);
23935 
23936 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
23937 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
23938 		    MUTEX_DEFAULT, NULL);
23939 	}
23940 
23941 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
23942 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
23943 		    MUTEX_DEFAULT, NULL);
23944 	}
23945 
23946 	/* TCP's IPsec code calls the packet dropper. */
23947 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
23948 
23949 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
23950 	tcps->tcps_params = pa;
23951 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
23952 
23953 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
23954 	    A_CNT(lcl_tcp_param_arr), tcps);
23955 
23956 	/*
23957 	 * Note: To really walk the device tree you need the devinfo
23958 	 * pointer to your device which is only available after probe/attach.
23959 	 * The following is safe only because it uses ddi_root_node()
23960 	 */
23961 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23962 	    tcp_opt_obj.odb_opt_arr_cnt);
23963 
23964 	/*
23965 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23966 	 * by the boot scripts.
23967 	 *
23968 	 * Use NULL name, as the name is caught by the new lockstats.
23969 	 *
23970 	 * Initialize with some random, non-guessable string, like the global
23971 	 * T_INFO_ACK.
23972 	 */
23973 
23974 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23975 	    sizeof (tcp_g_t_info_ack), tcps);
23976 
23977 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
23978 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
23979 
23980 	major = mod_name_to_major(INET_NAME);
23981 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
23982 	ASSERT(error == 0);
23983 	return (tcps);
23984 }
23985 
23986 /*
23987  * Called when the IP module is about to be unloaded.
23988  */
23989 void
23990 tcp_ddi_g_destroy(void)
23991 {
23992 	tcp_g_kstat_fini(tcp_g_kstat);
23993 	tcp_g_kstat = NULL;
23994 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
23995 
23996 	mutex_destroy(&tcp_random_lock);
23997 
23998 	kmem_cache_destroy(tcp_timercache);
23999 	kmem_cache_destroy(tcp_sack_info_cache);
24000 	kmem_cache_destroy(tcp_iphc_cache);
24001 
24002 	netstack_unregister(NS_TCP);
24003 	taskq_destroy(tcp_taskq);
24004 }
24005 
24006 /*
24007  * Shut down the TCP stack instance.
24008  */
24009 /* ARGSUSED */
24010 static void
24011 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24012 {
24013 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24014 
24015 	tcp_g_q_destroy(tcps);
24016 }
24017 
24018 /*
24019  * Free the TCP stack instance.
24020  */
24021 static void
24022 tcp_stack_fini(netstackid_t stackid, void *arg)
24023 {
24024 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24025 	int i;
24026 
24027 	nd_free(&tcps->tcps_g_nd);
24028 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24029 	tcps->tcps_params = NULL;
24030 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24031 	tcps->tcps_wroff_xtra_param = NULL;
24032 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24033 	tcps->tcps_mdt_head_param = NULL;
24034 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24035 	tcps->tcps_mdt_tail_param = NULL;
24036 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24037 	tcps->tcps_mdt_max_pbufs_param = NULL;
24038 
24039 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24040 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24041 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24042 	}
24043 
24044 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24045 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24046 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24047 	}
24048 
24049 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24050 	tcps->tcps_bind_fanout = NULL;
24051 
24052 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24053 	tcps->tcps_acceptor_fanout = NULL;
24054 
24055 	mutex_destroy(&tcps->tcps_iss_key_lock);
24056 	mutex_destroy(&tcps->tcps_g_q_lock);
24057 	cv_destroy(&tcps->tcps_g_q_cv);
24058 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24059 
24060 	ip_drop_unregister(&tcps->tcps_dropper);
24061 
24062 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24063 	tcps->tcps_kstat = NULL;
24064 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24065 
24066 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24067 	tcps->tcps_mibkp = NULL;
24068 
24069 	ldi_ident_release(tcps->tcps_ldi_ident);
24070 	kmem_free(tcps, sizeof (*tcps));
24071 }
24072 
24073 /*
24074  * Generate ISS, taking into account NDD changes may happen halfway through.
24075  * (If the iss is not zero, set it.)
24076  */
24077 
24078 static void
24079 tcp_iss_init(tcp_t *tcp)
24080 {
24081 	MD5_CTX context;
24082 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24083 	uint32_t answer[4];
24084 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24085 
24086 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24087 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24088 	switch (tcps->tcps_strong_iss) {
24089 	case 2:
24090 		mutex_enter(&tcps->tcps_iss_key_lock);
24091 		context = tcps->tcps_iss_key;
24092 		mutex_exit(&tcps->tcps_iss_key_lock);
24093 		arg.ports = tcp->tcp_ports;
24094 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24095 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24096 			    &arg.src);
24097 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24098 			    &arg.dst);
24099 		} else {
24100 			arg.src = tcp->tcp_ip6h->ip6_src;
24101 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24102 		}
24103 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24104 		MD5Final((uchar_t *)answer, &context);
24105 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24106 		/*
24107 		 * Now that we've hashed into a unique per-connection sequence
24108 		 * space, add a random increment per strong_iss == 1.  So I
24109 		 * guess we'll have to...
24110 		 */
24111 		/* FALLTHRU */
24112 	case 1:
24113 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24114 		break;
24115 	default:
24116 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24117 		break;
24118 	}
24119 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24120 	tcp->tcp_fss = tcp->tcp_iss - 1;
24121 	tcp->tcp_suna = tcp->tcp_iss;
24122 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24123 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24124 	tcp->tcp_csuna = tcp->tcp_snxt;
24125 }
24126 
24127 /*
24128  * Exported routine for extracting active tcp connection status.
24129  *
24130  * This is used by the Solaris Cluster Networking software to
24131  * gather a list of connections that need to be forwarded to
24132  * specific nodes in the cluster when configuration changes occur.
24133  *
24134  * The callback is invoked for each tcp_t structure from all netstacks,
24135  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24136  * from the netstack with the specified stack_id. Returning
24137  * non-zero from the callback routine terminates the search.
24138  */
24139 int
24140 cl_tcp_walk_list(netstackid_t stack_id,
24141     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24142 {
24143 	netstack_handle_t nh;
24144 	netstack_t *ns;
24145 	int ret = 0;
24146 
24147 	if (stack_id >= 0) {
24148 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24149 			return (EINVAL);
24150 
24151 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24152 		    ns->netstack_tcp);
24153 		netstack_rele(ns);
24154 		return (ret);
24155 	}
24156 
24157 	netstack_next_init(&nh);
24158 	while ((ns = netstack_next(&nh)) != NULL) {
24159 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24160 		    ns->netstack_tcp);
24161 		netstack_rele(ns);
24162 	}
24163 	netstack_next_fini(&nh);
24164 	return (ret);
24165 }
24166 
24167 static int
24168 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
24169     tcp_stack_t *tcps)
24170 {
24171 	tcp_t *tcp;
24172 	cl_tcp_info_t	cl_tcpi;
24173 	connf_t	*connfp;
24174 	conn_t	*connp;
24175 	int	i;
24176 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24177 
24178 	ASSERT(callback != NULL);
24179 
24180 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24181 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
24182 		connp = NULL;
24183 
24184 		while ((connp =
24185 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24186 
24187 			tcp = connp->conn_tcp;
24188 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24189 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24190 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24191 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24192 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24193 			/*
24194 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24195 			 * addresses. They are copied implicitly below as
24196 			 * mapped addresses.
24197 			 */
24198 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24199 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24200 				cl_tcpi.cl_tcpi_faddr =
24201 				    tcp->tcp_ipha->ipha_dst;
24202 			} else {
24203 				cl_tcpi.cl_tcpi_faddr_v6 =
24204 				    tcp->tcp_ip6h->ip6_dst;
24205 			}
24206 
24207 			/*
24208 			 * If the callback returns non-zero
24209 			 * we terminate the traversal.
24210 			 */
24211 			if ((*callback)(&cl_tcpi, arg) != 0) {
24212 				CONN_DEC_REF(tcp->tcp_connp);
24213 				return (1);
24214 			}
24215 		}
24216 	}
24217 
24218 	return (0);
24219 }
24220 
24221 /*
24222  * Macros used for accessing the different types of sockaddr
24223  * structures inside a tcp_ioc_abort_conn_t.
24224  */
24225 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24226 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24227 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24228 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24229 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24230 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24231 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24232 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24233 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24234 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24235 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24236 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24237 
24238 /*
24239  * Return the correct error code to mimic the behavior
24240  * of a connection reset.
24241  */
24242 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24243 		switch ((state)) {		\
24244 		case TCPS_SYN_SENT:		\
24245 		case TCPS_SYN_RCVD:		\
24246 			(err) = ECONNREFUSED;	\
24247 			break;			\
24248 		case TCPS_ESTABLISHED:		\
24249 		case TCPS_FIN_WAIT_1:		\
24250 		case TCPS_FIN_WAIT_2:		\
24251 		case TCPS_CLOSE_WAIT:		\
24252 			(err) = ECONNRESET;	\
24253 			break;			\
24254 		case TCPS_CLOSING:		\
24255 		case TCPS_LAST_ACK:		\
24256 		case TCPS_TIME_WAIT:		\
24257 			(err) = 0;		\
24258 			break;			\
24259 		default:			\
24260 			(err) = ENXIO;		\
24261 		}				\
24262 	}
24263 
24264 /*
24265  * Check if a tcp structure matches the info in acp.
24266  */
24267 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24268 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24269 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24270 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24271 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24272 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24273 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24274 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24275 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24276 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24277 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24278 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24279 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24280 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24281 	&(tcp)->tcp_ip_src_v6)) &&				\
24282 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24283 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24284 	&(tcp)->tcp_remote_v6)) &&				\
24285 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24286 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24287 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24288 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24289 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24290 	(acp)->ac_end >= (tcp)->tcp_state))
24291 
24292 #define	TCP_AC_MATCH(acp, tcp)					\
24293 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24294 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24295 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24296 
24297 /*
24298  * Build a message containing a tcp_ioc_abort_conn_t structure
24299  * which is filled in with information from acp and tp.
24300  */
24301 static mblk_t *
24302 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24303 {
24304 	mblk_t *mp;
24305 	tcp_ioc_abort_conn_t *tacp;
24306 
24307 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24308 	if (mp == NULL)
24309 		return (NULL);
24310 
24311 	mp->b_datap->db_type = M_CTL;
24312 
24313 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24314 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24315 	    sizeof (uint32_t));
24316 
24317 	tacp->ac_start = acp->ac_start;
24318 	tacp->ac_end = acp->ac_end;
24319 	tacp->ac_zoneid = acp->ac_zoneid;
24320 
24321 	if (acp->ac_local.ss_family == AF_INET) {
24322 		tacp->ac_local.ss_family = AF_INET;
24323 		tacp->ac_remote.ss_family = AF_INET;
24324 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24325 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24326 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24327 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24328 	} else {
24329 		tacp->ac_local.ss_family = AF_INET6;
24330 		tacp->ac_remote.ss_family = AF_INET6;
24331 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24332 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24333 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24334 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24335 	}
24336 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24337 	return (mp);
24338 }
24339 
24340 /*
24341  * Print a tcp_ioc_abort_conn_t structure.
24342  */
24343 static void
24344 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24345 {
24346 	char lbuf[128];
24347 	char rbuf[128];
24348 	sa_family_t af;
24349 	in_port_t lport, rport;
24350 	ushort_t logflags;
24351 
24352 	af = acp->ac_local.ss_family;
24353 
24354 	if (af == AF_INET) {
24355 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24356 		    lbuf, 128);
24357 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24358 		    rbuf, 128);
24359 		lport = ntohs(TCP_AC_V4LPORT(acp));
24360 		rport = ntohs(TCP_AC_V4RPORT(acp));
24361 	} else {
24362 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24363 		    lbuf, 128);
24364 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24365 		    rbuf, 128);
24366 		lport = ntohs(TCP_AC_V6LPORT(acp));
24367 		rport = ntohs(TCP_AC_V6RPORT(acp));
24368 	}
24369 
24370 	logflags = SL_TRACE | SL_NOTE;
24371 	/*
24372 	 * Don't print this message to the console if the operation was done
24373 	 * to a non-global zone.
24374 	 */
24375 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24376 		logflags |= SL_CONSOLE;
24377 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24378 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24379 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24380 	    acp->ac_start, acp->ac_end);
24381 }
24382 
24383 /*
24384  * Called inside tcp_rput when a message built using
24385  * tcp_ioctl_abort_build_msg is put into a queue.
24386  * Note that when we get here there is no wildcard in acp any more.
24387  */
24388 static void
24389 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24390 {
24391 	tcp_ioc_abort_conn_t *acp;
24392 
24393 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24394 	if (tcp->tcp_state <= acp->ac_end) {
24395 		/*
24396 		 * If we get here, we are already on the correct
24397 		 * squeue. This ioctl follows the following path
24398 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24399 		 * ->tcp_ioctl_abort->squeue_enter (if on a
24400 		 * different squeue)
24401 		 */
24402 		int errcode;
24403 
24404 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24405 		(void) tcp_clean_death(tcp, errcode, 26);
24406 	}
24407 	freemsg(mp);
24408 }
24409 
24410 /*
24411  * Abort all matching connections on a hash chain.
24412  */
24413 static int
24414 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24415     boolean_t exact, tcp_stack_t *tcps)
24416 {
24417 	int nmatch, err = 0;
24418 	tcp_t *tcp;
24419 	MBLKP mp, last, listhead = NULL;
24420 	conn_t	*tconnp;
24421 	connf_t	*connfp;
24422 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24423 
24424 	connfp = &ipst->ips_ipcl_conn_fanout[index];
24425 
24426 startover:
24427 	nmatch = 0;
24428 
24429 	mutex_enter(&connfp->connf_lock);
24430 	for (tconnp = connfp->connf_head; tconnp != NULL;
24431 	    tconnp = tconnp->conn_next) {
24432 		tcp = tconnp->conn_tcp;
24433 		if (TCP_AC_MATCH(acp, tcp)) {
24434 			CONN_INC_REF(tcp->tcp_connp);
24435 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24436 			if (mp == NULL) {
24437 				err = ENOMEM;
24438 				CONN_DEC_REF(tcp->tcp_connp);
24439 				break;
24440 			}
24441 			mp->b_prev = (mblk_t *)tcp;
24442 
24443 			if (listhead == NULL) {
24444 				listhead = mp;
24445 				last = mp;
24446 			} else {
24447 				last->b_next = mp;
24448 				last = mp;
24449 			}
24450 			nmatch++;
24451 			if (exact)
24452 				break;
24453 		}
24454 
24455 		/* Avoid holding lock for too long. */
24456 		if (nmatch >= 500)
24457 			break;
24458 	}
24459 	mutex_exit(&connfp->connf_lock);
24460 
24461 	/* Pass mp into the correct tcp */
24462 	while ((mp = listhead) != NULL) {
24463 		listhead = listhead->b_next;
24464 		tcp = (tcp_t *)mp->b_prev;
24465 		mp->b_next = mp->b_prev = NULL;
24466 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
24467 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
24468 	}
24469 
24470 	*count += nmatch;
24471 	if (nmatch >= 500 && err == 0)
24472 		goto startover;
24473 	return (err);
24474 }
24475 
24476 /*
24477  * Abort all connections that matches the attributes specified in acp.
24478  */
24479 static int
24480 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
24481 {
24482 	sa_family_t af;
24483 	uint32_t  ports;
24484 	uint16_t *pports;
24485 	int err = 0, count = 0;
24486 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24487 	int index = -1;
24488 	ushort_t logflags;
24489 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24490 
24491 	af = acp->ac_local.ss_family;
24492 
24493 	if (af == AF_INET) {
24494 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24495 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24496 			pports = (uint16_t *)&ports;
24497 			pports[1] = TCP_AC_V4LPORT(acp);
24498 			pports[0] = TCP_AC_V4RPORT(acp);
24499 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24500 		}
24501 	} else {
24502 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24503 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24504 			pports = (uint16_t *)&ports;
24505 			pports[1] = TCP_AC_V6LPORT(acp);
24506 			pports[0] = TCP_AC_V6RPORT(acp);
24507 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24508 		}
24509 	}
24510 
24511 	/*
24512 	 * For cases where remote addr, local port, and remote port are non-
24513 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24514 	 */
24515 	if (index != -1) {
24516 		err = tcp_ioctl_abort_bucket(acp, index,
24517 		    &count, exact, tcps);
24518 	} else {
24519 		/*
24520 		 * loop through all entries for wildcard case
24521 		 */
24522 		for (index = 0;
24523 		    index < ipst->ips_ipcl_conn_fanout_size;
24524 		    index++) {
24525 			err = tcp_ioctl_abort_bucket(acp, index,
24526 			    &count, exact, tcps);
24527 			if (err != 0)
24528 				break;
24529 		}
24530 	}
24531 
24532 	logflags = SL_TRACE | SL_NOTE;
24533 	/*
24534 	 * Don't print this message to the console if the operation was done
24535 	 * to a non-global zone.
24536 	 */
24537 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24538 		logflags |= SL_CONSOLE;
24539 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24540 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24541 	if (err == 0 && count == 0)
24542 		err = ENOENT;
24543 	return (err);
24544 }
24545 
24546 /*
24547  * Process the TCP_IOC_ABORT_CONN ioctl request.
24548  */
24549 static void
24550 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24551 {
24552 	int	err;
24553 	IOCP    iocp;
24554 	MBLKP   mp1;
24555 	sa_family_t laf, raf;
24556 	tcp_ioc_abort_conn_t *acp;
24557 	zone_t		*zptr;
24558 	conn_t		*connp = Q_TO_CONN(q);
24559 	zoneid_t	zoneid = connp->conn_zoneid;
24560 	tcp_t		*tcp = connp->conn_tcp;
24561 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24562 
24563 	iocp = (IOCP)mp->b_rptr;
24564 
24565 	if ((mp1 = mp->b_cont) == NULL ||
24566 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24567 		err = EINVAL;
24568 		goto out;
24569 	}
24570 
24571 	/* check permissions */
24572 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
24573 		err = EPERM;
24574 		goto out;
24575 	}
24576 
24577 	if (mp1->b_cont != NULL) {
24578 		freemsg(mp1->b_cont);
24579 		mp1->b_cont = NULL;
24580 	}
24581 
24582 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24583 	laf = acp->ac_local.ss_family;
24584 	raf = acp->ac_remote.ss_family;
24585 
24586 	/* check that a zone with the supplied zoneid exists */
24587 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24588 		zptr = zone_find_by_id(zoneid);
24589 		if (zptr != NULL) {
24590 			zone_rele(zptr);
24591 		} else {
24592 			err = EINVAL;
24593 			goto out;
24594 		}
24595 	}
24596 
24597 	/*
24598 	 * For exclusive stacks we set the zoneid to zero
24599 	 * to make TCP operate as if in the global zone.
24600 	 */
24601 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
24602 		acp->ac_zoneid = GLOBAL_ZONEID;
24603 
24604 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24605 	    acp->ac_start > acp->ac_end || laf != raf ||
24606 	    (laf != AF_INET && laf != AF_INET6)) {
24607 		err = EINVAL;
24608 		goto out;
24609 	}
24610 
24611 	tcp_ioctl_abort_dump(acp);
24612 	err = tcp_ioctl_abort(acp, tcps);
24613 
24614 out:
24615 	if (mp1 != NULL) {
24616 		freemsg(mp1);
24617 		mp->b_cont = NULL;
24618 	}
24619 
24620 	if (err != 0)
24621 		miocnak(q, mp, 0, err);
24622 	else
24623 		miocack(q, mp, 0, 0);
24624 }
24625 
24626 /*
24627  * tcp_time_wait_processing() handles processing of incoming packets when
24628  * the tcp is in the TIME_WAIT state.
24629  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24630  * on the time wait list.
24631  */
24632 void
24633 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24634     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24635 {
24636 	int32_t		bytes_acked;
24637 	int32_t		gap;
24638 	int32_t		rgap;
24639 	tcp_opt_t	tcpopt;
24640 	uint_t		flags;
24641 	uint32_t	new_swnd = 0;
24642 	conn_t		*connp;
24643 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24644 
24645 	BUMP_LOCAL(tcp->tcp_ibsegs);
24646 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
24647 
24648 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24649 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24650 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24651 	if (tcp->tcp_snd_ts_ok) {
24652 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24653 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24654 			    tcp->tcp_rnxt, TH_ACK);
24655 			goto done;
24656 		}
24657 	}
24658 	gap = seg_seq - tcp->tcp_rnxt;
24659 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24660 	if (gap < 0) {
24661 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
24662 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
24663 		    (seg_len > -gap ? -gap : seg_len));
24664 		seg_len += gap;
24665 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24666 			if (flags & TH_RST) {
24667 				goto done;
24668 			}
24669 			if ((flags & TH_FIN) && seg_len == -1) {
24670 				/*
24671 				 * When TCP receives a duplicate FIN in
24672 				 * TIME_WAIT state, restart the 2 MSL timer.
24673 				 * See page 73 in RFC 793. Make sure this TCP
24674 				 * is already on the TIME_WAIT list. If not,
24675 				 * just restart the timer.
24676 				 */
24677 				if (TCP_IS_DETACHED(tcp)) {
24678 					if (tcp_time_wait_remove(tcp, NULL) ==
24679 					    B_TRUE) {
24680 						tcp_time_wait_append(tcp);
24681 						TCP_DBGSTAT(tcps,
24682 						    tcp_rput_time_wait);
24683 					}
24684 				} else {
24685 					ASSERT(tcp != NULL);
24686 					TCP_TIMER_RESTART(tcp,
24687 					    tcps->tcps_time_wait_interval);
24688 				}
24689 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24690 				    tcp->tcp_rnxt, TH_ACK);
24691 				goto done;
24692 			}
24693 			flags |=  TH_ACK_NEEDED;
24694 			seg_len = 0;
24695 			goto process_ack;
24696 		}
24697 
24698 		/* Fix seg_seq, and chew the gap off the front. */
24699 		seg_seq = tcp->tcp_rnxt;
24700 	}
24701 
24702 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24703 		/*
24704 		 * Make sure that when we accept the connection, pick
24705 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24706 		 * old connection.
24707 		 *
24708 		 * The next ISS generated is equal to tcp_iss_incr_extra
24709 		 * + ISS_INCR/2 + other components depending on the
24710 		 * value of tcp_strong_iss.  We pre-calculate the new
24711 		 * ISS here and compare with tcp_snxt to determine if
24712 		 * we need to make adjustment to tcp_iss_incr_extra.
24713 		 *
24714 		 * The above calculation is ugly and is a
24715 		 * waste of CPU cycles...
24716 		 */
24717 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
24718 		int32_t adj;
24719 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24720 
24721 		switch (tcps->tcps_strong_iss) {
24722 		case 2: {
24723 			/* Add time and MD5 components. */
24724 			uint32_t answer[4];
24725 			struct {
24726 				uint32_t ports;
24727 				in6_addr_t src;
24728 				in6_addr_t dst;
24729 			} arg;
24730 			MD5_CTX context;
24731 
24732 			mutex_enter(&tcps->tcps_iss_key_lock);
24733 			context = tcps->tcps_iss_key;
24734 			mutex_exit(&tcps->tcps_iss_key_lock);
24735 			arg.ports = tcp->tcp_ports;
24736 			/* We use MAPPED addresses in tcp_iss_init */
24737 			arg.src = tcp->tcp_ip_src_v6;
24738 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24739 				IN6_IPADDR_TO_V4MAPPED(
24740 				    tcp->tcp_ipha->ipha_dst,
24741 				    &arg.dst);
24742 			} else {
24743 				arg.dst =
24744 				    tcp->tcp_ip6h->ip6_dst;
24745 			}
24746 			MD5Update(&context, (uchar_t *)&arg,
24747 			    sizeof (arg));
24748 			MD5Final((uchar_t *)answer, &context);
24749 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24750 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24751 			break;
24752 		}
24753 		case 1:
24754 			/* Add time component and min random (i.e. 1). */
24755 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24756 			break;
24757 		default:
24758 			/* Add only time component. */
24759 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24760 			break;
24761 		}
24762 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24763 			/*
24764 			 * New ISS not guaranteed to be ISS_INCR/2
24765 			 * ahead of the current tcp_snxt, so add the
24766 			 * difference to tcp_iss_incr_extra.
24767 			 */
24768 			tcps->tcps_iss_incr_extra += adj;
24769 		}
24770 		/*
24771 		 * If tcp_clean_death() can not perform the task now,
24772 		 * drop the SYN packet and let the other side re-xmit.
24773 		 * Otherwise pass the SYN packet back in, since the
24774 		 * old tcp state has been cleaned up or freed.
24775 		 */
24776 		if (tcp_clean_death(tcp, 0, 27) == -1)
24777 			goto done;
24778 		/*
24779 		 * We will come back to tcp_rput_data
24780 		 * on the global queue. Packets destined
24781 		 * for the global queue will be checked
24782 		 * with global policy. But the policy for
24783 		 * this packet has already been checked as
24784 		 * this was destined for the detached
24785 		 * connection. We need to bypass policy
24786 		 * check this time by attaching a dummy
24787 		 * ipsec_in with ipsec_in_dont_check set.
24788 		 */
24789 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
24790 		if (connp != NULL) {
24791 			TCP_STAT(tcps, tcp_time_wait_syn_success);
24792 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24793 			return;
24794 		}
24795 		goto done;
24796 	}
24797 
24798 	/*
24799 	 * rgap is the amount of stuff received out of window.  A negative
24800 	 * value is the amount out of window.
24801 	 */
24802 	if (rgap < 0) {
24803 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
24804 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
24805 		/* Fix seg_len and make sure there is something left. */
24806 		seg_len += rgap;
24807 		if (seg_len <= 0) {
24808 			if (flags & TH_RST) {
24809 				goto done;
24810 			}
24811 			flags |=  TH_ACK_NEEDED;
24812 			seg_len = 0;
24813 			goto process_ack;
24814 		}
24815 	}
24816 	/*
24817 	 * Check whether we can update tcp_ts_recent.  This test is
24818 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24819 	 * Extensions for High Performance: An Update", Internet Draft.
24820 	 */
24821 	if (tcp->tcp_snd_ts_ok &&
24822 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24823 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24824 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24825 		tcp->tcp_last_rcv_lbolt = lbolt64;
24826 	}
24827 
24828 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24829 		/* Always ack out of order packets */
24830 		flags |= TH_ACK_NEEDED;
24831 		seg_len = 0;
24832 	} else if (seg_len > 0) {
24833 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
24834 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
24835 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
24836 	}
24837 	if (flags & TH_RST) {
24838 		(void) tcp_clean_death(tcp, 0, 28);
24839 		goto done;
24840 	}
24841 	if (flags & TH_SYN) {
24842 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24843 		    TH_RST|TH_ACK);
24844 		/*
24845 		 * Do not delete the TCP structure if it is in
24846 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24847 		 */
24848 		goto done;
24849 	}
24850 process_ack:
24851 	if (flags & TH_ACK) {
24852 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24853 		if (bytes_acked <= 0) {
24854 			if (bytes_acked == 0 && seg_len == 0 &&
24855 			    new_swnd == tcp->tcp_swnd)
24856 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
24857 		} else {
24858 			/* Acks something not sent */
24859 			flags |= TH_ACK_NEEDED;
24860 		}
24861 	}
24862 	if (flags & TH_ACK_NEEDED) {
24863 		/*
24864 		 * Time to send an ack for some reason.
24865 		 */
24866 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24867 		    tcp->tcp_rnxt, TH_ACK);
24868 	}
24869 done:
24870 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24871 		DB_CKSUMSTART(mp) = 0;
24872 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24873 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
24874 	}
24875 	freemsg(mp);
24876 }
24877 
24878 /*
24879  * TCP Timers Implementation.
24880  */
24881 timeout_id_t
24882 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24883 {
24884 	mblk_t *mp;
24885 	tcp_timer_t *tcpt;
24886 	tcp_t *tcp = connp->conn_tcp;
24887 
24888 	ASSERT(connp->conn_sqp != NULL);
24889 
24890 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
24891 
24892 	if (tcp->tcp_timercache == NULL) {
24893 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24894 	} else {
24895 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
24896 		mp = tcp->tcp_timercache;
24897 		tcp->tcp_timercache = mp->b_next;
24898 		mp->b_next = NULL;
24899 		ASSERT(mp->b_wptr == NULL);
24900 	}
24901 
24902 	CONN_INC_REF(connp);
24903 	tcpt = (tcp_timer_t *)mp->b_rptr;
24904 	tcpt->connp = connp;
24905 	tcpt->tcpt_proc = f;
24906 	/*
24907 	 * TCP timers are normal timeouts. Plus, they do not require more than
24908 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
24909 	 * rounding up the expiration to the next resolution boundary, we can
24910 	 * batch timers in the callout subsystem to make TCP timers more
24911 	 * efficient. The roundup also protects short timers from expiring too
24912 	 * early before they have a chance to be cancelled.
24913 	 */
24914 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
24915 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
24916 
24917 	return ((timeout_id_t)mp);
24918 }
24919 
24920 static void
24921 tcp_timer_callback(void *arg)
24922 {
24923 	mblk_t *mp = (mblk_t *)arg;
24924 	tcp_timer_t *tcpt;
24925 	conn_t	*connp;
24926 
24927 	tcpt = (tcp_timer_t *)mp->b_rptr;
24928 	connp = tcpt->connp;
24929 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
24930 	    SQ_FILL, SQTAG_TCP_TIMER);
24931 }
24932 
24933 static void
24934 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24935 {
24936 	tcp_timer_t *tcpt;
24937 	conn_t *connp = (conn_t *)arg;
24938 	tcp_t *tcp = connp->conn_tcp;
24939 
24940 	tcpt = (tcp_timer_t *)mp->b_rptr;
24941 	ASSERT(connp == tcpt->connp);
24942 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24943 
24944 	/*
24945 	 * If the TCP has reached the closed state, don't proceed any
24946 	 * further. This TCP logically does not exist on the system.
24947 	 * tcpt_proc could for example access queues, that have already
24948 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24949 	 */
24950 	if (tcp->tcp_state != TCPS_CLOSED) {
24951 		(*tcpt->tcpt_proc)(connp);
24952 	} else {
24953 		tcp->tcp_timer_tid = 0;
24954 	}
24955 	tcp_timer_free(connp->conn_tcp, mp);
24956 }
24957 
24958 /*
24959  * There is potential race with untimeout and the handler firing at the same
24960  * time. The mblock may be freed by the handler while we are trying to use
24961  * it. But since both should execute on the same squeue, this race should not
24962  * occur.
24963  */
24964 clock_t
24965 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24966 {
24967 	mblk_t	*mp = (mblk_t *)id;
24968 	tcp_timer_t *tcpt;
24969 	clock_t delta;
24970 
24971 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
24972 
24973 	if (mp == NULL)
24974 		return (-1);
24975 
24976 	tcpt = (tcp_timer_t *)mp->b_rptr;
24977 	ASSERT(tcpt->connp == connp);
24978 
24979 	delta = untimeout_default(tcpt->tcpt_tid, 0);
24980 
24981 	if (delta >= 0) {
24982 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
24983 		tcp_timer_free(connp->conn_tcp, mp);
24984 		CONN_DEC_REF(connp);
24985 	}
24986 
24987 	return (delta);
24988 }
24989 
24990 /*
24991  * Allocate space for the timer event. The allocation looks like mblk, but it is
24992  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24993  *
24994  * Dealing with failures: If we can't allocate from the timer cache we try
24995  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24996  * points to b_rptr.
24997  * If we can't allocate anything using allocb_tryhard(), we perform a last
24998  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24999  * save the actual allocation size in b_datap.
25000  */
25001 mblk_t *
25002 tcp_timermp_alloc(int kmflags)
25003 {
25004 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25005 	    kmflags & ~KM_PANIC);
25006 
25007 	if (mp != NULL) {
25008 		mp->b_next = mp->b_prev = NULL;
25009 		mp->b_rptr = (uchar_t *)(&mp[1]);
25010 		mp->b_wptr = NULL;
25011 		mp->b_datap = NULL;
25012 		mp->b_queue = NULL;
25013 		mp->b_cont = NULL;
25014 	} else if (kmflags & KM_PANIC) {
25015 		/*
25016 		 * Failed to allocate memory for the timer. Try allocating from
25017 		 * dblock caches.
25018 		 */
25019 		/* ipclassifier calls this from a constructor - hence no tcps */
25020 		TCP_G_STAT(tcp_timermp_allocfail);
25021 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25022 		if (mp == NULL) {
25023 			size_t size = 0;
25024 			/*
25025 			 * Memory is really low. Try tryhard allocation.
25026 			 *
25027 			 * ipclassifier calls this from a constructor -
25028 			 * hence no tcps
25029 			 */
25030 			TCP_G_STAT(tcp_timermp_allocdblfail);
25031 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25032 			    sizeof (tcp_timer_t), &size, kmflags);
25033 			mp->b_rptr = (uchar_t *)(&mp[1]);
25034 			mp->b_next = mp->b_prev = NULL;
25035 			mp->b_wptr = (uchar_t *)-1;
25036 			mp->b_datap = (dblk_t *)size;
25037 			mp->b_queue = NULL;
25038 			mp->b_cont = NULL;
25039 		}
25040 		ASSERT(mp->b_wptr != NULL);
25041 	}
25042 	/* ipclassifier calls this from a constructor - hence no tcps */
25043 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25044 
25045 	return (mp);
25046 }
25047 
25048 /*
25049  * Free per-tcp timer cache.
25050  * It can only contain entries from tcp_timercache.
25051  */
25052 void
25053 tcp_timermp_free(tcp_t *tcp)
25054 {
25055 	mblk_t *mp;
25056 
25057 	while ((mp = tcp->tcp_timercache) != NULL) {
25058 		ASSERT(mp->b_wptr == NULL);
25059 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25060 		kmem_cache_free(tcp_timercache, mp);
25061 	}
25062 }
25063 
25064 /*
25065  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25066  * events there already (currently at most two events are cached).
25067  * If the event is not allocated from the timer cache, free it right away.
25068  */
25069 static void
25070 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25071 {
25072 	mblk_t *mp1 = tcp->tcp_timercache;
25073 
25074 	if (mp->b_wptr != NULL) {
25075 		/*
25076 		 * This allocation is not from a timer cache, free it right
25077 		 * away.
25078 		 */
25079 		if (mp->b_wptr != (uchar_t *)-1)
25080 			freeb(mp);
25081 		else
25082 			kmem_free(mp, (size_t)mp->b_datap);
25083 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25084 		/* Cache this timer block for future allocations */
25085 		mp->b_rptr = (uchar_t *)(&mp[1]);
25086 		mp->b_next = mp1;
25087 		tcp->tcp_timercache = mp;
25088 	} else {
25089 		kmem_cache_free(tcp_timercache, mp);
25090 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25091 	}
25092 }
25093 
25094 /*
25095  * End of TCP Timers implementation.
25096  */
25097 
25098 /*
25099  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25100  * on the specified backing STREAMS q. Note, the caller may make the
25101  * decision to call based on the tcp_t.tcp_flow_stopped value which
25102  * when check outside the q's lock is only an advisory check ...
25103  */
25104 void
25105 tcp_setqfull(tcp_t *tcp)
25106 {
25107 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25108 	conn_t	*connp = tcp->tcp_connp;
25109 
25110 	if (tcp->tcp_closed)
25111 		return;
25112 
25113 	if (IPCL_IS_NONSTR(connp)) {
25114 		(*connp->conn_upcalls->su_txq_full)
25115 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25116 		tcp->tcp_flow_stopped = B_TRUE;
25117 	} else {
25118 		queue_t *q = tcp->tcp_wq;
25119 
25120 		if (!(q->q_flag & QFULL)) {
25121 			mutex_enter(QLOCK(q));
25122 			if (!(q->q_flag & QFULL)) {
25123 				/* still need to set QFULL */
25124 				q->q_flag |= QFULL;
25125 				tcp->tcp_flow_stopped = B_TRUE;
25126 				mutex_exit(QLOCK(q));
25127 				TCP_STAT(tcps, tcp_flwctl_on);
25128 			} else {
25129 				mutex_exit(QLOCK(q));
25130 			}
25131 		}
25132 	}
25133 }
25134 
25135 void
25136 tcp_clrqfull(tcp_t *tcp)
25137 {
25138 	conn_t  *connp = tcp->tcp_connp;
25139 
25140 	if (tcp->tcp_closed)
25141 		return;
25142 
25143 	if (IPCL_IS_NONSTR(connp)) {
25144 		(*connp->conn_upcalls->su_txq_full)
25145 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25146 		tcp->tcp_flow_stopped = B_FALSE;
25147 	} else {
25148 		queue_t *q = tcp->tcp_wq;
25149 
25150 		if (q->q_flag & QFULL) {
25151 			mutex_enter(QLOCK(q));
25152 			if (q->q_flag & QFULL) {
25153 				q->q_flag &= ~QFULL;
25154 				tcp->tcp_flow_stopped = B_FALSE;
25155 				mutex_exit(QLOCK(q));
25156 				if (q->q_flag & QWANTW)
25157 					qbackenable(q, 0);
25158 			} else {
25159 				mutex_exit(QLOCK(q));
25160 			}
25161 		}
25162 	}
25163 }
25164 
25165 /*
25166  * kstats related to squeues i.e. not per IP instance
25167  */
25168 static void *
25169 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
25170 {
25171 	kstat_t *ksp;
25172 
25173 	tcp_g_stat_t template = {
25174 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
25175 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
25176 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
25177 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
25178 	};
25179 
25180 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
25181 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25182 	    KSTAT_FLAG_VIRTUAL);
25183 
25184 	if (ksp == NULL)
25185 		return (NULL);
25186 
25187 	bcopy(&template, tcp_g_statp, sizeof (template));
25188 	ksp->ks_data = (void *)tcp_g_statp;
25189 
25190 	kstat_install(ksp);
25191 	return (ksp);
25192 }
25193 
25194 static void
25195 tcp_g_kstat_fini(kstat_t *ksp)
25196 {
25197 	if (ksp != NULL) {
25198 		kstat_delete(ksp);
25199 	}
25200 }
25201 
25202 
25203 static void *
25204 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
25205 {
25206 	kstat_t *ksp;
25207 
25208 	tcp_stat_t template = {
25209 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
25210 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
25211 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
25212 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
25213 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
25214 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
25215 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
25216 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
25217 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
25218 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
25219 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
25220 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
25221 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
25222 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
25223 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
25224 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
25225 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
25226 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
25227 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
25228 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
25229 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
25230 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
25231 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
25232 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
25233 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
25234 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
25235 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
25236 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
25237 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
25238 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
25239 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
25240 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
25241 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
25242 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
25243 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
25244 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
25245 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
25246 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
25247 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
25248 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
25249 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
25250 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
25251 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
25252 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
25253 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
25254 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
25255 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
25256 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
25257 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
25258 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
25259 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
25260 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
25261 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
25262 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
25263 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
25264 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
25265 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
25266 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
25267 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
25268 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
25269 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
25270 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
25271 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
25272 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
25273 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
25274 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
25275 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
25276 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
25277 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
25278 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
25279 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
25280 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
25281 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
25282 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
25283 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
25284 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
25285 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
25286 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
25287 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
25288 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
25289 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
25290 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
25291 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
25292 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
25293 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
25294 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
25295 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
25296 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
25297 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
25298 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
25299 	};
25300 
25301 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
25302 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25303 	    KSTAT_FLAG_VIRTUAL, stackid);
25304 
25305 	if (ksp == NULL)
25306 		return (NULL);
25307 
25308 	bcopy(&template, tcps_statisticsp, sizeof (template));
25309 	ksp->ks_data = (void *)tcps_statisticsp;
25310 	ksp->ks_private = (void *)(uintptr_t)stackid;
25311 
25312 	kstat_install(ksp);
25313 	return (ksp);
25314 }
25315 
25316 static void
25317 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
25318 {
25319 	if (ksp != NULL) {
25320 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25321 		kstat_delete_netstack(ksp, stackid);
25322 	}
25323 }
25324 
25325 /*
25326  * TCP Kstats implementation
25327  */
25328 static void *
25329 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
25330 {
25331 	kstat_t	*ksp;
25332 
25333 	tcp_named_kstat_t template = {
25334 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25335 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25336 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25337 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25338 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25339 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25340 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25341 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25342 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25343 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25344 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25345 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25346 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25347 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25348 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25349 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25350 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25351 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25352 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25353 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25354 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25355 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25356 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25357 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25358 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25359 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25360 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25361 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25362 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25363 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25364 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25365 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25366 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25367 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25368 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25369 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25370 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25371 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25372 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25373 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25374 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25375 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25376 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25377 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25378 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25379 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25380 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25381 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25382 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25383 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25384 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25385 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25386 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25387 	};
25388 
25389 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
25390 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
25391 
25392 	if (ksp == NULL)
25393 		return (NULL);
25394 
25395 	template.rtoAlgorithm.value.ui32 = 4;
25396 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
25397 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
25398 	template.maxConn.value.i32 = -1;
25399 
25400 	bcopy(&template, ksp->ks_data, sizeof (template));
25401 	ksp->ks_update = tcp_kstat_update;
25402 	ksp->ks_private = (void *)(uintptr_t)stackid;
25403 
25404 	kstat_install(ksp);
25405 	return (ksp);
25406 }
25407 
25408 static void
25409 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
25410 {
25411 	if (ksp != NULL) {
25412 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25413 		kstat_delete_netstack(ksp, stackid);
25414 	}
25415 }
25416 
25417 static int
25418 tcp_kstat_update(kstat_t *kp, int rw)
25419 {
25420 	tcp_named_kstat_t *tcpkp;
25421 	tcp_t		*tcp;
25422 	connf_t		*connfp;
25423 	conn_t		*connp;
25424 	int 		i;
25425 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
25426 	netstack_t	*ns;
25427 	tcp_stack_t	*tcps;
25428 	ip_stack_t	*ipst;
25429 
25430 	if ((kp == NULL) || (kp->ks_data == NULL))
25431 		return (EIO);
25432 
25433 	if (rw == KSTAT_WRITE)
25434 		return (EACCES);
25435 
25436 	ns = netstack_find_by_stackid(stackid);
25437 	if (ns == NULL)
25438 		return (-1);
25439 	tcps = ns->netstack_tcp;
25440 	if (tcps == NULL) {
25441 		netstack_rele(ns);
25442 		return (-1);
25443 	}
25444 
25445 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25446 
25447 	tcpkp->currEstab.value.ui32 = 0;
25448 
25449 	ipst = ns->netstack_ip;
25450 
25451 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25452 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25453 		connp = NULL;
25454 		while ((connp =
25455 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25456 			tcp = connp->conn_tcp;
25457 			switch (tcp_snmp_state(tcp)) {
25458 			case MIB2_TCP_established:
25459 			case MIB2_TCP_closeWait:
25460 				tcpkp->currEstab.value.ui32++;
25461 				break;
25462 			}
25463 		}
25464 	}
25465 
25466 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
25467 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
25468 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
25469 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
25470 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
25471 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
25472 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
25473 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
25474 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
25475 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
25476 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
25477 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
25478 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
25479 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
25480 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
25481 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
25482 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
25483 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
25484 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
25485 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
25486 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
25487 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
25488 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
25489 	tcpkp->inDataInorderSegs.value.ui32 =
25490 	    tcps->tcps_mib.tcpInDataInorderSegs;
25491 	tcpkp->inDataInorderBytes.value.ui32 =
25492 	    tcps->tcps_mib.tcpInDataInorderBytes;
25493 	tcpkp->inDataUnorderSegs.value.ui32 =
25494 	    tcps->tcps_mib.tcpInDataUnorderSegs;
25495 	tcpkp->inDataUnorderBytes.value.ui32 =
25496 	    tcps->tcps_mib.tcpInDataUnorderBytes;
25497 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
25498 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
25499 	tcpkp->inDataPartDupSegs.value.ui32 =
25500 	    tcps->tcps_mib.tcpInDataPartDupSegs;
25501 	tcpkp->inDataPartDupBytes.value.ui32 =
25502 	    tcps->tcps_mib.tcpInDataPartDupBytes;
25503 	tcpkp->inDataPastWinSegs.value.ui32 =
25504 	    tcps->tcps_mib.tcpInDataPastWinSegs;
25505 	tcpkp->inDataPastWinBytes.value.ui32 =
25506 	    tcps->tcps_mib.tcpInDataPastWinBytes;
25507 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
25508 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
25509 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
25510 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
25511 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
25512 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
25513 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
25514 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
25515 	tcpkp->timKeepaliveProbe.value.ui32 =
25516 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
25517 	tcpkp->timKeepaliveDrop.value.ui32 =
25518 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
25519 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
25520 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
25521 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
25522 	tcpkp->outSackRetransSegs.value.ui32 =
25523 	    tcps->tcps_mib.tcpOutSackRetransSegs;
25524 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
25525 
25526 	netstack_rele(ns);
25527 	return (0);
25528 }
25529 
25530 void
25531 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25532 {
25533 	uint16_t	hdr_len;
25534 	ipha_t		*ipha;
25535 	uint8_t		*nexthdrp;
25536 	tcph_t		*tcph;
25537 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
25538 
25539 	/* Already has an eager */
25540 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25541 		TCP_STAT(tcps, tcp_reinput_syn);
25542 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25543 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
25544 		return;
25545 	}
25546 
25547 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25548 	case IPV4_VERSION:
25549 		ipha = (ipha_t *)mp->b_rptr;
25550 		hdr_len = IPH_HDR_LENGTH(ipha);
25551 		break;
25552 	case IPV6_VERSION:
25553 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25554 		    &hdr_len, &nexthdrp)) {
25555 			CONN_DEC_REF(connp);
25556 			freemsg(mp);
25557 			return;
25558 		}
25559 		break;
25560 	}
25561 
25562 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25563 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25564 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25565 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25566 	}
25567 
25568 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25569 	    SQ_FILL, SQTAG_TCP_REINPUT);
25570 }
25571 
25572 static int
25573 tcp_squeue_switch(int val)
25574 {
25575 	int rval = SQ_FILL;
25576 
25577 	switch (val) {
25578 	case 1:
25579 		rval = SQ_NODRAIN;
25580 		break;
25581 	case 2:
25582 		rval = SQ_PROCESS;
25583 		break;
25584 	default:
25585 		break;
25586 	}
25587 	return (rval);
25588 }
25589 
25590 /*
25591  * This is called once for each squeue - globally for all stack
25592  * instances.
25593  */
25594 static void
25595 tcp_squeue_add(squeue_t *sqp)
25596 {
25597 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25598 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
25599 
25600 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25601 	tcp_time_wait->tcp_time_wait_tid =
25602 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
25603 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
25604 	    CALLOUT_FLAG_ROUNDUP);
25605 	if (tcp_free_list_max_cnt == 0) {
25606 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25607 		    max_ncpus : boot_max_ncpus);
25608 
25609 		/*
25610 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25611 		 */
25612 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25613 		    (tcp_ncpus * sizeof (tcp_t) * 100);
25614 	}
25615 	tcp_time_wait->tcp_free_list_cnt = 0;
25616 }
25617 
25618 static int
25619 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
25620 {
25621 	mblk_t	*ire_mp = NULL;
25622 	mblk_t	*syn_mp;
25623 	mblk_t	*mdti;
25624 	mblk_t	*lsoi;
25625 	int	retval;
25626 	tcph_t	*tcph;
25627 	cred_t	*ecr;
25628 	ts_label_t	*tsl;
25629 	uint32_t	mss;
25630 	conn_t	*connp = tcp->tcp_connp;
25631 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25632 
25633 	if (error == 0) {
25634 		/*
25635 		 * Adapt Multidata information, if any.  The
25636 		 * following tcp_mdt_update routine will free
25637 		 * the message.
25638 		 */
25639 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
25640 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
25641 			    b_rptr)->mdt_capab, B_TRUE);
25642 			freemsg(mdti);
25643 		}
25644 
25645 		/*
25646 		 * Check to update LSO information with tcp, and
25647 		 * tcp_lso_update routine will free the message.
25648 		 */
25649 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
25650 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
25651 			    b_rptr)->lso_capab);
25652 			freemsg(lsoi);
25653 		}
25654 
25655 		/* Get the IRE, if we had requested for it */
25656 		if (mp != NULL)
25657 			ire_mp = tcp_ire_mp(&mp);
25658 
25659 		if (tcp->tcp_hard_binding) {
25660 			tcp->tcp_hard_binding = B_FALSE;
25661 			tcp->tcp_hard_bound = B_TRUE;
25662 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
25663 			if (retval != 0) {
25664 				error = EADDRINUSE;
25665 				goto bind_failed;
25666 			}
25667 		} else {
25668 			if (ire_mp != NULL)
25669 				freeb(ire_mp);
25670 			goto after_syn_sent;
25671 		}
25672 
25673 		retval = tcp_adapt_ire(tcp, ire_mp);
25674 		if (ire_mp != NULL)
25675 			freeb(ire_mp);
25676 		if (retval == 0) {
25677 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
25678 			    ENETUNREACH : EADDRNOTAVAIL);
25679 			goto ipcl_rm;
25680 		}
25681 		/*
25682 		 * Don't let an endpoint connect to itself.
25683 		 * Also checked in tcp_connect() but that
25684 		 * check can't handle the case when the
25685 		 * local IP address is INADDR_ANY.
25686 		 */
25687 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25688 			if ((tcp->tcp_ipha->ipha_dst ==
25689 			    tcp->tcp_ipha->ipha_src) &&
25690 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25691 			    tcp->tcp_tcph->th_fport))) {
25692 				error = EADDRNOTAVAIL;
25693 				goto ipcl_rm;
25694 			}
25695 		} else {
25696 			if (IN6_ARE_ADDR_EQUAL(
25697 			    &tcp->tcp_ip6h->ip6_dst,
25698 			    &tcp->tcp_ip6h->ip6_src) &&
25699 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25700 			    tcp->tcp_tcph->th_fport))) {
25701 				error = EADDRNOTAVAIL;
25702 				goto ipcl_rm;
25703 			}
25704 		}
25705 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
25706 		/*
25707 		 * This should not be possible!  Just for
25708 		 * defensive coding...
25709 		 */
25710 		if (tcp->tcp_state != TCPS_SYN_SENT)
25711 			goto after_syn_sent;
25712 
25713 		if (is_system_labeled() &&
25714 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
25715 			error = EHOSTUNREACH;
25716 			goto ipcl_rm;
25717 		}
25718 
25719 		/*
25720 		 * tcp_adapt_ire() does not adjust
25721 		 * for TCP/IP header length.
25722 		 */
25723 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
25724 
25725 		/*
25726 		 * Just make sure our rwnd is at
25727 		 * least tcp_recv_hiwat_mss * MSS
25728 		 * large, and round up to the nearest
25729 		 * MSS.
25730 		 *
25731 		 * We do the round up here because
25732 		 * we need to get the interface
25733 		 * MTU first before we can do the
25734 		 * round up.
25735 		 */
25736 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
25737 		    tcps->tcps_recv_hiwat_minmss * mss);
25738 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
25739 		tcp_set_ws_value(tcp);
25740 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
25741 		    tcp->tcp_tcph->th_win);
25742 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
25743 			tcp->tcp_snd_ws_ok = B_TRUE;
25744 
25745 		/*
25746 		 * Set tcp_snd_ts_ok to true
25747 		 * so that tcp_xmit_mp will
25748 		 * include the timestamp
25749 		 * option in the SYN segment.
25750 		 */
25751 		if (tcps->tcps_tstamp_always ||
25752 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
25753 			tcp->tcp_snd_ts_ok = B_TRUE;
25754 		}
25755 
25756 		/*
25757 		 * tcp_snd_sack_ok can be set in
25758 		 * tcp_adapt_ire() if the sack metric
25759 		 * is set.  So check it here also.
25760 		 */
25761 		if (tcps->tcps_sack_permitted == 2 ||
25762 		    tcp->tcp_snd_sack_ok) {
25763 			if (tcp->tcp_sack_info == NULL) {
25764 				tcp->tcp_sack_info =
25765 				    kmem_cache_alloc(tcp_sack_info_cache,
25766 				    KM_SLEEP);
25767 			}
25768 			tcp->tcp_snd_sack_ok = B_TRUE;
25769 		}
25770 
25771 		/*
25772 		 * Should we use ECN?  Note that the current
25773 		 * default value (SunOS 5.9) of tcp_ecn_permitted
25774 		 * is 1.  The reason for doing this is that there
25775 		 * are equipments out there that will drop ECN
25776 		 * enabled IP packets.  Setting it to 1 avoids
25777 		 * compatibility problems.
25778 		 */
25779 		if (tcps->tcps_ecn_permitted == 2)
25780 			tcp->tcp_ecn_ok = B_TRUE;
25781 
25782 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
25783 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
25784 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
25785 		if (syn_mp) {
25786 			/*
25787 			 * cr contains the cred from the thread calling
25788 			 * connect().
25789 			 *
25790 			 * If no thread cred is available, use the
25791 			 * socket creator's cred instead. If still no
25792 			 * cred, drop the request rather than risk a
25793 			 * panic on production systems.
25794 			 */
25795 			if (cr == NULL) {
25796 				cr = CONN_CRED(connp);
25797 				pid = tcp->tcp_cpid;
25798 				ASSERT(cr != NULL);
25799 				if (cr != NULL) {
25800 					mblk_setcred(syn_mp, cr, pid);
25801 				} else {
25802 					error = ECONNABORTED;
25803 					goto ipcl_rm;
25804 				}
25805 
25806 			/*
25807 			 * If an effective security label exists for
25808 			 * the connection, create a copy of the thread's
25809 			 * cred but with the effective label attached.
25810 			 */
25811 			} else if (is_system_labeled() &&
25812 			    connp->conn_effective_cred != NULL &&
25813 			    (tsl = crgetlabel(connp->
25814 			    conn_effective_cred)) != NULL) {
25815 				if ((ecr = copycred_from_tslabel(cr,
25816 				    tsl, KM_NOSLEEP)) == NULL) {
25817 					error = ENOMEM;
25818 					goto ipcl_rm;
25819 				}
25820 				mblk_setcred(syn_mp, ecr, pid);
25821 				crfree(ecr);
25822 
25823 			/*
25824 			 * Default to using the thread's cred unchanged.
25825 			 */
25826 			} else {
25827 				mblk_setcred(syn_mp, cr, pid);
25828 			}
25829 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
25830 		}
25831 	after_syn_sent:
25832 		if (mp != NULL) {
25833 			ASSERT(mp->b_cont == NULL);
25834 			freeb(mp);
25835 		}
25836 		return (error);
25837 	} else {
25838 		/* error */
25839 		if (tcp->tcp_debug) {
25840 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
25841 			    "tcp_post_ip_bind: error == %d", error);
25842 		}
25843 		if (mp != NULL) {
25844 			freeb(mp);
25845 		}
25846 	}
25847 
25848 ipcl_rm:
25849 	/*
25850 	 * Need to unbind with classifier since we were just
25851 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
25852 	 */
25853 	tcp->tcp_hard_bound = B_FALSE;
25854 	tcp->tcp_hard_binding = B_FALSE;
25855 
25856 	ipcl_hash_remove(connp);
25857 
25858 bind_failed:
25859 	tcp->tcp_state = TCPS_IDLE;
25860 	if (tcp->tcp_ipversion == IPV4_VERSION)
25861 		tcp->tcp_ipha->ipha_src = 0;
25862 	else
25863 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
25864 	/*
25865 	 * Copy of the src addr. in tcp_t is needed since
25866 	 * the lookup funcs. can only look at tcp_t
25867 	 */
25868 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
25869 
25870 	tcph = tcp->tcp_tcph;
25871 	tcph->th_lport[0] = 0;
25872 	tcph->th_lport[1] = 0;
25873 	tcp_bind_hash_remove(tcp);
25874 	bzero(&connp->u_port, sizeof (connp->u_port));
25875 	/* blow away saved option results if any */
25876 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
25877 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
25878 
25879 	conn_delete_ire(tcp->tcp_connp, NULL);
25880 
25881 	return (error);
25882 }
25883 
25884 static int
25885 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
25886     boolean_t bind_to_req_port_only, cred_t *cr)
25887 {
25888 	in_port_t	mlp_port;
25889 	mlp_type_t 	addrtype, mlptype;
25890 	boolean_t	user_specified;
25891 	in_port_t	allocated_port;
25892 	in_port_t	requested_port = *requested_port_ptr;
25893 	conn_t		*connp;
25894 	zone_t		*zone;
25895 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25896 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
25897 
25898 	/*
25899 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
25900 	 */
25901 	if (cr == NULL)
25902 		cr = tcp->tcp_cred;
25903 	/*
25904 	 * Get a valid port (within the anonymous range and should not
25905 	 * be a privileged one) to use if the user has not given a port.
25906 	 * If multiple threads are here, they may all start with
25907 	 * with the same initial port. But, it should be fine as long as
25908 	 * tcp_bindi will ensure that no two threads will be assigned
25909 	 * the same port.
25910 	 *
25911 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
25912 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
25913 	 * unless TCP_ANONPRIVBIND option is set.
25914 	 */
25915 	mlptype = mlptSingle;
25916 	mlp_port = requested_port;
25917 	if (requested_port == 0) {
25918 		requested_port = tcp->tcp_anon_priv_bind ?
25919 		    tcp_get_next_priv_port(tcp) :
25920 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
25921 		    tcp, B_TRUE);
25922 		if (requested_port == 0) {
25923 			return (-TNOADDR);
25924 		}
25925 		user_specified = B_FALSE;
25926 
25927 		/*
25928 		 * If the user went through one of the RPC interfaces to create
25929 		 * this socket and RPC is MLP in this zone, then give him an
25930 		 * anonymous MLP.
25931 		 */
25932 		connp = tcp->tcp_connp;
25933 		if (connp->conn_anon_mlp && is_system_labeled()) {
25934 			zone = crgetzone(cr);
25935 			addrtype = tsol_mlp_addr_type(
25936 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
25937 			    IPV6_VERSION, &v6addr,
25938 			    tcps->tcps_netstack->netstack_ip);
25939 			if (addrtype == mlptSingle) {
25940 				return (-TNOADDR);
25941 			}
25942 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25943 			    PMAPPORT, addrtype);
25944 			mlp_port = PMAPPORT;
25945 		}
25946 	} else {
25947 		int i;
25948 		boolean_t priv = B_FALSE;
25949 
25950 		/*
25951 		 * If the requested_port is in the well-known privileged range,
25952 		 * verify that the stream was opened by a privileged user.
25953 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
25954 		 * but instead the code relies on:
25955 		 * - the fact that the address of the array and its size never
25956 		 *   changes
25957 		 * - the atomic assignment of the elements of the array
25958 		 */
25959 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
25960 			priv = B_TRUE;
25961 		} else {
25962 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
25963 				if (requested_port ==
25964 				    tcps->tcps_g_epriv_ports[i]) {
25965 					priv = B_TRUE;
25966 					break;
25967 				}
25968 			}
25969 		}
25970 		if (priv) {
25971 			if (secpolicy_net_privaddr(cr, requested_port,
25972 			    IPPROTO_TCP) != 0) {
25973 				if (tcp->tcp_debug) {
25974 					(void) strlog(TCP_MOD_ID, 0, 1,
25975 					    SL_ERROR|SL_TRACE,
25976 					    "tcp_bind: no priv for port %d",
25977 					    requested_port);
25978 				}
25979 				return (-TACCES);
25980 			}
25981 		}
25982 		user_specified = B_TRUE;
25983 
25984 		connp = tcp->tcp_connp;
25985 		if (is_system_labeled()) {
25986 			zone = crgetzone(cr);
25987 			addrtype = tsol_mlp_addr_type(
25988 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
25989 			    IPV6_VERSION, &v6addr,
25990 			    tcps->tcps_netstack->netstack_ip);
25991 			if (addrtype == mlptSingle) {
25992 				return (-TNOADDR);
25993 			}
25994 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25995 			    requested_port, addrtype);
25996 		}
25997 	}
25998 
25999 	if (mlptype != mlptSingle) {
26000 		if (secpolicy_net_bindmlp(cr) != 0) {
26001 			if (tcp->tcp_debug) {
26002 				(void) strlog(TCP_MOD_ID, 0, 1,
26003 				    SL_ERROR|SL_TRACE,
26004 				    "tcp_bind: no priv for multilevel port %d",
26005 				    requested_port);
26006 			}
26007 			return (-TACCES);
26008 		}
26009 
26010 		/*
26011 		 * If we're specifically binding a shared IP address and the
26012 		 * port is MLP on shared addresses, then check to see if this
26013 		 * zone actually owns the MLP.  Reject if not.
26014 		 */
26015 		if (mlptype == mlptShared && addrtype == mlptShared) {
26016 			/*
26017 			 * No need to handle exclusive-stack zones since
26018 			 * ALL_ZONES only applies to the shared stack.
26019 			 */
26020 			zoneid_t mlpzone;
26021 
26022 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26023 			    htons(mlp_port));
26024 			if (connp->conn_zoneid != mlpzone) {
26025 				if (tcp->tcp_debug) {
26026 					(void) strlog(TCP_MOD_ID, 0, 1,
26027 					    SL_ERROR|SL_TRACE,
26028 					    "tcp_bind: attempt to bind port "
26029 					    "%d on shared addr in zone %d "
26030 					    "(should be %d)",
26031 					    mlp_port, connp->conn_zoneid,
26032 					    mlpzone);
26033 				}
26034 				return (-TACCES);
26035 			}
26036 		}
26037 
26038 		if (!user_specified) {
26039 			int err;
26040 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26041 			    requested_port, B_TRUE);
26042 			if (err != 0) {
26043 				if (tcp->tcp_debug) {
26044 					(void) strlog(TCP_MOD_ID, 0, 1,
26045 					    SL_ERROR|SL_TRACE,
26046 					    "tcp_bind: cannot establish anon "
26047 					    "MLP for port %d",
26048 					    requested_port);
26049 				}
26050 				return (err);
26051 			}
26052 			connp->conn_anon_port = B_TRUE;
26053 		}
26054 		connp->conn_mlp_type = mlptype;
26055 	}
26056 
26057 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26058 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26059 
26060 	if (allocated_port == 0) {
26061 		connp->conn_mlp_type = mlptSingle;
26062 		if (connp->conn_anon_port) {
26063 			connp->conn_anon_port = B_FALSE;
26064 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26065 			    requested_port, B_FALSE);
26066 		}
26067 		if (bind_to_req_port_only) {
26068 			if (tcp->tcp_debug) {
26069 				(void) strlog(TCP_MOD_ID, 0, 1,
26070 				    SL_ERROR|SL_TRACE,
26071 				    "tcp_bind: requested addr busy");
26072 			}
26073 			return (-TADDRBUSY);
26074 		} else {
26075 			/* If we are out of ports, fail the bind. */
26076 			if (tcp->tcp_debug) {
26077 				(void) strlog(TCP_MOD_ID, 0, 1,
26078 				    SL_ERROR|SL_TRACE,
26079 				    "tcp_bind: out of ports?");
26080 			}
26081 			return (-TNOADDR);
26082 		}
26083 	}
26084 
26085 	/* Pass the allocated port back */
26086 	*requested_port_ptr = allocated_port;
26087 	return (0);
26088 }
26089 
26090 static int
26091 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26092     boolean_t bind_to_req_port_only)
26093 {
26094 	tcp_t	*tcp = connp->conn_tcp;
26095 	sin_t	*sin;
26096 	sin6_t  *sin6;
26097 	in_port_t requested_port;
26098 	ipaddr_t	v4addr;
26099 	in6_addr_t	v6addr;
26100 	uint_t	origipversion;
26101 	int	error = 0;
26102 
26103 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26104 
26105 	if (tcp->tcp_state == TCPS_BOUND) {
26106 		return (0);
26107 	} else if (tcp->tcp_state > TCPS_BOUND) {
26108 		if (tcp->tcp_debug) {
26109 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26110 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26111 		}
26112 		return (-TOUTSTATE);
26113 	}
26114 	origipversion = tcp->tcp_ipversion;
26115 
26116 	ASSERT(sa != NULL && len != 0);
26117 
26118 	if (!OK_32PTR((char *)sa)) {
26119 		if (tcp->tcp_debug) {
26120 			(void) strlog(TCP_MOD_ID, 0, 1,
26121 			    SL_ERROR|SL_TRACE,
26122 			    "tcp_bind: bad address parameter, "
26123 			    "address %p, len %d",
26124 			    (void *)sa, len);
26125 		}
26126 		return (-TPROTO);
26127 	}
26128 
26129 	switch (len) {
26130 	case sizeof (sin_t):	/* Complete IPv4 address */
26131 		sin = (sin_t *)sa;
26132 		/*
26133 		 * With sockets sockfs will accept bogus sin_family in
26134 		 * bind() and replace it with the family used in the socket
26135 		 * call.
26136 		 */
26137 		if (sin->sin_family != AF_INET ||
26138 		    tcp->tcp_family != AF_INET) {
26139 			return (EAFNOSUPPORT);
26140 		}
26141 		requested_port = ntohs(sin->sin_port);
26142 		tcp->tcp_ipversion = IPV4_VERSION;
26143 		v4addr = sin->sin_addr.s_addr;
26144 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26145 		break;
26146 
26147 	case sizeof (sin6_t): /* Complete IPv6 address */
26148 		sin6 = (sin6_t *)sa;
26149 		if (sin6->sin6_family != AF_INET6 ||
26150 		    tcp->tcp_family != AF_INET6) {
26151 			return (EAFNOSUPPORT);
26152 		}
26153 		requested_port = ntohs(sin6->sin6_port);
26154 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26155 		    IPV4_VERSION : IPV6_VERSION;
26156 		v6addr = sin6->sin6_addr;
26157 		break;
26158 
26159 	default:
26160 		if (tcp->tcp_debug) {
26161 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26162 			    "tcp_bind: bad address length, %d", len);
26163 		}
26164 		return (EAFNOSUPPORT);
26165 		/* return (-TBADADDR); */
26166 	}
26167 
26168 	tcp->tcp_bound_source_v6 = v6addr;
26169 
26170 	/* Check for change in ipversion */
26171 	if (origipversion != tcp->tcp_ipversion) {
26172 		ASSERT(tcp->tcp_family == AF_INET6);
26173 		error = tcp->tcp_ipversion == IPV6_VERSION ?
26174 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26175 		if (error) {
26176 			return (ENOMEM);
26177 		}
26178 	}
26179 
26180 	/*
26181 	 * Initialize family specific fields. Copy of the src addr.
26182 	 * in tcp_t is needed for the lookup funcs.
26183 	 */
26184 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26185 		tcp->tcp_ip6h->ip6_src = v6addr;
26186 	} else {
26187 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
26188 	}
26189 	tcp->tcp_ip_src_v6 = v6addr;
26190 
26191 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
26192 
26193 	error = tcp_bind_select_lport(tcp, &requested_port,
26194 	    bind_to_req_port_only, cr);
26195 
26196 	return (error);
26197 }
26198 
26199 /*
26200  * Return unix error is tli error is TSYSERR, otherwise return a negative
26201  * tli error.
26202  */
26203 int
26204 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26205     boolean_t bind_to_req_port_only)
26206 {
26207 	int error;
26208 	tcp_t *tcp = connp->conn_tcp;
26209 
26210 	if (tcp->tcp_state >= TCPS_BOUND) {
26211 		if (tcp->tcp_debug) {
26212 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26213 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26214 		}
26215 		return (-TOUTSTATE);
26216 	}
26217 
26218 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
26219 	if (error != 0)
26220 		return (error);
26221 
26222 	ASSERT(tcp->tcp_state == TCPS_BOUND);
26223 
26224 	tcp->tcp_conn_req_max = 0;
26225 
26226 	if (tcp->tcp_family == AF_INET6) {
26227 		ASSERT(tcp->tcp_connp->conn_af_isv6);
26228 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
26229 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
26230 	} else {
26231 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
26232 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
26233 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
26234 	}
26235 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
26236 }
26237 
26238 int
26239 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
26240     socklen_t len, cred_t *cr)
26241 {
26242 	int 		error;
26243 	conn_t		*connp = (conn_t *)proto_handle;
26244 	squeue_t	*sqp = connp->conn_sqp;
26245 
26246 	/* All Solaris components should pass a cred for this operation. */
26247 	ASSERT(cr != NULL);
26248 
26249 	ASSERT(sqp != NULL);
26250 	ASSERT(connp->conn_upper_handle != NULL);
26251 
26252 	error = squeue_synch_enter(sqp, connp, NULL);
26253 	if (error != 0) {
26254 		/* failed to enter */
26255 		return (ENOSR);
26256 	}
26257 
26258 	/* binding to a NULL address really means unbind */
26259 	if (sa == NULL) {
26260 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
26261 			error = tcp_do_unbind(connp);
26262 		else
26263 			error = EINVAL;
26264 	} else {
26265 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
26266 	}
26267 
26268 	squeue_synch_exit(sqp, connp);
26269 
26270 	if (error < 0) {
26271 		if (error == -TOUTSTATE)
26272 			error = EINVAL;
26273 		else
26274 			error = proto_tlitosyserr(-error);
26275 	}
26276 
26277 	return (error);
26278 }
26279 
26280 /*
26281  * If the return value from this function is positive, it's a UNIX error.
26282  * Otherwise, if it's negative, then the absolute value is a TLI error.
26283  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
26284  */
26285 int
26286 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
26287     cred_t *cr, pid_t pid)
26288 {
26289 	tcp_t		*tcp = connp->conn_tcp;
26290 	sin_t		*sin = (sin_t *)sa;
26291 	sin6_t		*sin6 = (sin6_t *)sa;
26292 	ipaddr_t	*dstaddrp;
26293 	in_port_t	dstport;
26294 	uint_t		srcid;
26295 	int		error = 0;
26296 
26297 	switch (len) {
26298 	default:
26299 		/*
26300 		 * Should never happen
26301 		 */
26302 		return (EINVAL);
26303 
26304 	case sizeof (sin_t):
26305 		sin = (sin_t *)sa;
26306 		if (sin->sin_port == 0) {
26307 			return (-TBADADDR);
26308 		}
26309 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
26310 			return (EAFNOSUPPORT);
26311 		}
26312 		break;
26313 
26314 	case sizeof (sin6_t):
26315 		sin6 = (sin6_t *)sa;
26316 		if (sin6->sin6_port == 0) {
26317 			return (-TBADADDR);
26318 		}
26319 		break;
26320 	}
26321 	/*
26322 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
26323 	 * make sure that the template IP header in the tcp structure is an
26324 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
26325 	 * need to this before we call tcp_bindi() so that the port lookup
26326 	 * code will look for ports in the correct port space (IPv4 and
26327 	 * IPv6 have separate port spaces).
26328 	 */
26329 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
26330 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26331 		int err = 0;
26332 
26333 		err = tcp_header_init_ipv4(tcp);
26334 			if (err != 0) {
26335 				error = ENOMEM;
26336 				goto connect_failed;
26337 			}
26338 		if (tcp->tcp_lport != 0)
26339 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
26340 	}
26341 
26342 	switch (tcp->tcp_state) {
26343 	case TCPS_LISTEN:
26344 		/*
26345 		 * Listening sockets are not allowed to issue connect().
26346 		 */
26347 		if (IPCL_IS_NONSTR(connp))
26348 			return (EOPNOTSUPP);
26349 		/* FALLTHRU */
26350 	case TCPS_IDLE:
26351 		/*
26352 		 * We support quick connect, refer to comments in
26353 		 * tcp_connect_*()
26354 		 */
26355 		/* FALLTHRU */
26356 	case TCPS_BOUND:
26357 		/*
26358 		 * We must bump the generation before the operation start.
26359 		 * This is done to ensure that any upcall made later on sends
26360 		 * up the right generation to the socket.
26361 		 */
26362 		SOCK_CONNID_BUMP(tcp->tcp_connid);
26363 
26364 		if (tcp->tcp_family == AF_INET6) {
26365 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26366 				return (tcp_connect_ipv6(tcp,
26367 				    &sin6->sin6_addr,
26368 				    sin6->sin6_port, sin6->sin6_flowinfo,
26369 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
26370 				    cr, pid));
26371 			}
26372 			/*
26373 			 * Destination adress is mapped IPv6 address.
26374 			 * Source bound address should be unspecified or
26375 			 * IPv6 mapped address as well.
26376 			 */
26377 			if (!IN6_IS_ADDR_UNSPECIFIED(
26378 			    &tcp->tcp_bound_source_v6) &&
26379 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
26380 				return (EADDRNOTAVAIL);
26381 			}
26382 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
26383 			dstport = sin6->sin6_port;
26384 			srcid = sin6->__sin6_src_id;
26385 		} else {
26386 			dstaddrp = &sin->sin_addr.s_addr;
26387 			dstport = sin->sin_port;
26388 			srcid = 0;
26389 		}
26390 
26391 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
26392 		    pid);
26393 		break;
26394 	default:
26395 		return (-TOUTSTATE);
26396 	}
26397 	/*
26398 	 * Note: Code below is the "failure" case
26399 	 */
26400 connect_failed:
26401 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26402 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26403 	return (error);
26404 }
26405 
26406 int
26407 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
26408     socklen_t len, sock_connid_t *id, cred_t *cr)
26409 {
26410 	conn_t		*connp = (conn_t *)proto_handle;
26411 	tcp_t		*tcp = connp->conn_tcp;
26412 	squeue_t	*sqp = connp->conn_sqp;
26413 	int		error;
26414 
26415 	ASSERT(connp->conn_upper_handle != NULL);
26416 
26417 	/* All Solaris components should pass a cred for this operation. */
26418 	ASSERT(cr != NULL);
26419 
26420 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
26421 	if (error != 0) {
26422 		return (error);
26423 	}
26424 
26425 	error = squeue_synch_enter(sqp, connp, NULL);
26426 	if (error != 0) {
26427 		/* failed to enter */
26428 		return (ENOSR);
26429 	}
26430 
26431 	/*
26432 	 * TCP supports quick connect, so no need to do an implicit bind
26433 	 */
26434 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
26435 	if (error == 0) {
26436 		*id = connp->conn_tcp->tcp_connid;
26437 	} else if (error < 0) {
26438 		if (error == -TOUTSTATE) {
26439 			switch (connp->conn_tcp->tcp_state) {
26440 			case TCPS_SYN_SENT:
26441 				error = EALREADY;
26442 				break;
26443 			case TCPS_ESTABLISHED:
26444 				error = EISCONN;
26445 				break;
26446 			case TCPS_LISTEN:
26447 				error = EOPNOTSUPP;
26448 				break;
26449 			default:
26450 				error = EINVAL;
26451 				break;
26452 			}
26453 		} else {
26454 			error = proto_tlitosyserr(-error);
26455 		}
26456 	}
26457 
26458 	if (tcp->tcp_loopback) {
26459 		struct sock_proto_props sopp;
26460 
26461 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
26462 		sopp.sopp_loopback = B_TRUE;
26463 
26464 		(*connp->conn_upcalls->su_set_proto_props)(
26465 		    connp->conn_upper_handle, &sopp);
26466 	}
26467 done:
26468 	squeue_synch_exit(sqp, connp);
26469 
26470 	return ((error == 0) ? EINPROGRESS : error);
26471 }
26472 
26473 /* ARGSUSED */
26474 sock_lower_handle_t
26475 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
26476     uint_t *smodep, int *errorp, int flags, cred_t *credp)
26477 {
26478 	conn_t		*connp;
26479 	boolean_t	isv6 = family == AF_INET6;
26480 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
26481 	    (proto != 0 && proto != IPPROTO_TCP)) {
26482 		*errorp = EPROTONOSUPPORT;
26483 		return (NULL);
26484 	}
26485 
26486 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
26487 	if (connp == NULL) {
26488 		return (NULL);
26489 	}
26490 
26491 	/*
26492 	 * Put the ref for TCP. Ref for IP was already put
26493 	 * by ipcl_conn_create. Also Make the conn_t globally
26494 	 * visible to walkers
26495 	 */
26496 	mutex_enter(&connp->conn_lock);
26497 	CONN_INC_REF_LOCKED(connp);
26498 	ASSERT(connp->conn_ref == 2);
26499 	connp->conn_state_flags &= ~CONN_INCIPIENT;
26500 
26501 	connp->conn_flags |= IPCL_NONSTR;
26502 	mutex_exit(&connp->conn_lock);
26503 
26504 	ASSERT(errorp != NULL);
26505 	*errorp = 0;
26506 	*sock_downcalls = &sock_tcp_downcalls;
26507 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
26508 	    SM_SENDFILESUPP;
26509 
26510 	return ((sock_lower_handle_t)connp);
26511 }
26512 
26513 /* ARGSUSED */
26514 void
26515 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
26516     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
26517 {
26518 	conn_t *connp = (conn_t *)proto_handle;
26519 	struct sock_proto_props sopp;
26520 
26521 	ASSERT(connp->conn_upper_handle == NULL);
26522 
26523 	/* All Solaris components should pass a cred for this operation. */
26524 	ASSERT(cr != NULL);
26525 
26526 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
26527 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
26528 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
26529 
26530 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
26531 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
26532 	sopp.sopp_maxpsz = INFPSZ;
26533 	sopp.sopp_maxblk = INFPSZ;
26534 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
26535 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
26536 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
26537 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
26538 	    tcp_rinfo.mi_minpsz;
26539 
26540 	connp->conn_upcalls = sock_upcalls;
26541 	connp->conn_upper_handle = sock_handle;
26542 
26543 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
26544 }
26545 
26546 /* ARGSUSED */
26547 int
26548 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
26549 {
26550 	conn_t *connp = (conn_t *)proto_handle;
26551 
26552 	ASSERT(connp->conn_upper_handle != NULL);
26553 
26554 	/* All Solaris components should pass a cred for this operation. */
26555 	ASSERT(cr != NULL);
26556 
26557 	tcp_close_common(connp, flags);
26558 
26559 	ip_free_helper_stream(connp);
26560 
26561 	/*
26562 	 * Drop IP's reference on the conn. This is the last reference
26563 	 * on the connp if the state was less than established. If the
26564 	 * connection has gone into timewait state, then we will have
26565 	 * one ref for the TCP and one more ref (total of two) for the
26566 	 * classifier connected hash list (a timewait connections stays
26567 	 * in connected hash till closed).
26568 	 *
26569 	 * We can't assert the references because there might be other
26570 	 * transient reference places because of some walkers or queued
26571 	 * packets in squeue for the timewait state.
26572 	 */
26573 	CONN_DEC_REF(connp);
26574 	return (0);
26575 }
26576 
26577 /* ARGSUSED */
26578 int
26579 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
26580     cred_t *cr)
26581 {
26582 	tcp_t		*tcp;
26583 	uint32_t	msize;
26584 	conn_t *connp = (conn_t *)proto_handle;
26585 	int32_t		tcpstate;
26586 
26587 	/* All Solaris components should pass a cred for this operation. */
26588 	ASSERT(cr != NULL);
26589 
26590 	ASSERT(connp->conn_ref >= 2);
26591 	ASSERT(connp->conn_upper_handle != NULL);
26592 
26593 	if (msg->msg_controllen != 0) {
26594 		return (EOPNOTSUPP);
26595 
26596 	}
26597 	switch (DB_TYPE(mp)) {
26598 	case M_DATA:
26599 		tcp = connp->conn_tcp;
26600 		ASSERT(tcp != NULL);
26601 
26602 		tcpstate = tcp->tcp_state;
26603 		if (tcpstate < TCPS_ESTABLISHED) {
26604 			freemsg(mp);
26605 			return (ENOTCONN);
26606 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
26607 			freemsg(mp);
26608 			return (EPIPE);
26609 		}
26610 
26611 		msize = msgdsize(mp);
26612 
26613 		mutex_enter(&tcp->tcp_non_sq_lock);
26614 		tcp->tcp_squeue_bytes += msize;
26615 		/*
26616 		 * Squeue Flow Control
26617 		 */
26618 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
26619 			tcp_setqfull(tcp);
26620 		}
26621 		mutex_exit(&tcp->tcp_non_sq_lock);
26622 
26623 		/*
26624 		 * The application may pass in an address in the msghdr, but
26625 		 * we ignore the address on connection-oriented sockets.
26626 		 * Just like BSD this code does not generate an error for
26627 		 * TCP (a CONNREQUIRED socket) when sending to an address
26628 		 * passed in with sendto/sendmsg. Instead the data is
26629 		 * delivered on the connection as if no address had been
26630 		 * supplied.
26631 		 */
26632 		CONN_INC_REF(connp);
26633 
26634 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
26635 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
26636 			    tcp_output_urgent, connp, tcp_squeue_flag,
26637 			    SQTAG_TCP_OUTPUT);
26638 		} else {
26639 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
26640 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
26641 		}
26642 
26643 		return (0);
26644 
26645 	default:
26646 		ASSERT(0);
26647 	}
26648 
26649 	freemsg(mp);
26650 	return (0);
26651 }
26652 
26653 /* ARGSUSED */
26654 void
26655 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
26656 {
26657 	int len;
26658 	uint32_t msize;
26659 	conn_t *connp = (conn_t *)arg;
26660 	tcp_t *tcp = connp->conn_tcp;
26661 
26662 	msize = msgdsize(mp);
26663 
26664 	len = msize - 1;
26665 	if (len < 0) {
26666 		freemsg(mp);
26667 		return;
26668 	}
26669 
26670 	/*
26671 	 * Try to force urgent data out on the wire. Even if we have unsent
26672 	 * data this will at least send the urgent flag.
26673 	 * XXX does not handle more flag correctly.
26674 	 */
26675 	len += tcp->tcp_unsent;
26676 	len += tcp->tcp_snxt;
26677 	tcp->tcp_urg = len;
26678 	tcp->tcp_valid_bits |= TCP_URG_VALID;
26679 
26680 	/* Bypass tcp protocol for fused tcp loopback */
26681 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
26682 		return;
26683 
26684 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
26685 	if (DB_TYPE(mp) != M_DATA) {
26686 		mblk_t *mp1 = mp;
26687 		ASSERT(!IPCL_IS_NONSTR(connp));
26688 		mp = mp->b_cont;
26689 		freeb(mp1);
26690 	}
26691 	tcp_wput_data(tcp, mp, B_TRUE);
26692 }
26693 
26694 /* ARGSUSED */
26695 int
26696 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26697     socklen_t *addrlenp, cred_t *cr)
26698 {
26699 	conn_t	*connp = (conn_t *)proto_handle;
26700 	tcp_t	*tcp = connp->conn_tcp;
26701 
26702 	ASSERT(connp->conn_upper_handle != NULL);
26703 	/* All Solaris components should pass a cred for this operation. */
26704 	ASSERT(cr != NULL);
26705 
26706 	ASSERT(tcp != NULL);
26707 
26708 	return (tcp_do_getpeername(tcp, addr, addrlenp));
26709 }
26710 
26711 /* ARGSUSED */
26712 int
26713 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26714     socklen_t *addrlenp, cred_t *cr)
26715 {
26716 	conn_t	*connp = (conn_t *)proto_handle;
26717 	tcp_t	*tcp = connp->conn_tcp;
26718 
26719 	/* All Solaris components should pass a cred for this operation. */
26720 	ASSERT(cr != NULL);
26721 
26722 	ASSERT(connp->conn_upper_handle != NULL);
26723 
26724 	return (tcp_do_getsockname(tcp, addr, addrlenp));
26725 }
26726 
26727 /*
26728  * tcp_fallback
26729  *
26730  * A direct socket is falling back to using STREAMS. The queue
26731  * that is being passed down was created using tcp_open() with
26732  * the SO_FALLBACK flag set. As a result, the queue is not
26733  * associated with a conn, and the q_ptrs instead contain the
26734  * dev and minor area that should be used.
26735  *
26736  * The 'issocket' flag indicates whether the FireEngine
26737  * optimizations should be used. The common case would be that
26738  * optimizations are enabled, and they might be subsequently
26739  * disabled using the _SIOCSOCKFALLBACK ioctl.
26740  */
26741 
26742 /*
26743  * An active connection is falling back to TPI. Gather all the information
26744  * required by the STREAM head and TPI sonode and send it up.
26745  */
26746 void
26747 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
26748     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
26749 {
26750 	conn_t			*connp = tcp->tcp_connp;
26751 	struct stroptions	*stropt;
26752 	struct T_capability_ack tca;
26753 	struct sockaddr_in6	laddr, faddr;
26754 	socklen_t 		laddrlen, faddrlen;
26755 	short			opts;
26756 	int			error;
26757 	mblk_t			*mp;
26758 
26759 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
26760 	connp->conn_minor_arena = WR(q)->q_ptr;
26761 
26762 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
26763 
26764 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
26765 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
26766 
26767 	WR(q)->q_qinfo = &tcp_sock_winit;
26768 
26769 	if (!issocket)
26770 		tcp_use_pure_tpi(tcp);
26771 
26772 	/*
26773 	 * free the helper stream
26774 	 */
26775 	ip_free_helper_stream(connp);
26776 
26777 	/*
26778 	 * Notify the STREAM head about options
26779 	 */
26780 	DB_TYPE(stropt_mp) = M_SETOPTS;
26781 	stropt = (struct stroptions *)stropt_mp->b_rptr;
26782 	stropt_mp->b_wptr += sizeof (struct stroptions);
26783 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
26784 
26785 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
26786 	    tcp->tcp_tcps->tcps_wroff_xtra);
26787 	if (tcp->tcp_snd_sack_ok)
26788 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
26789 	stropt->so_hiwat = tcp->tcp_recv_hiwater;
26790 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
26791 
26792 	putnext(RD(q), stropt_mp);
26793 
26794 	/*
26795 	 * Collect the information needed to sync with the sonode
26796 	 */
26797 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
26798 
26799 	laddrlen = faddrlen = sizeof (sin6_t);
26800 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
26801 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
26802 	if (error != 0)
26803 		faddrlen = 0;
26804 
26805 	opts = 0;
26806 	if (tcp->tcp_oobinline)
26807 		opts |= SO_OOBINLINE;
26808 	if (tcp->tcp_dontroute)
26809 		opts |= SO_DONTROUTE;
26810 
26811 	/*
26812 	 * Notify the socket that the protocol is now quiescent,
26813 	 * and it's therefore safe move data from the socket
26814 	 * to the stream head.
26815 	 */
26816 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
26817 	    (struct sockaddr *)&laddr, laddrlen,
26818 	    (struct sockaddr *)&faddr, faddrlen, opts);
26819 
26820 	while ((mp = tcp->tcp_rcv_list) != NULL) {
26821 		tcp->tcp_rcv_list = mp->b_next;
26822 		mp->b_next = NULL;
26823 		putnext(q, mp);
26824 	}
26825 	tcp->tcp_rcv_last_head = NULL;
26826 	tcp->tcp_rcv_last_tail = NULL;
26827 	tcp->tcp_rcv_cnt = 0;
26828 }
26829 
26830 /*
26831  * An eager is falling back to TPI. All we have to do is send
26832  * up a T_CONN_IND.
26833  */
26834 void
26835 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
26836 {
26837 	tcp_t *listener = eager->tcp_listener;
26838 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
26839 
26840 	ASSERT(listener != NULL);
26841 	ASSERT(mp != NULL);
26842 
26843 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
26844 
26845 	/*
26846 	 * TLI/XTI applications will get confused by
26847 	 * sending eager as an option since it violates
26848 	 * the option semantics. So remove the eager as
26849 	 * option since TLI/XTI app doesn't need it anyway.
26850 	 */
26851 	if (!direct_sockfs) {
26852 		struct T_conn_ind *conn_ind;
26853 
26854 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
26855 		conn_ind->OPT_length = 0;
26856 		conn_ind->OPT_offset = 0;
26857 	}
26858 
26859 	/*
26860 	 * Sockfs guarantees that the listener will not be closed
26861 	 * during fallback. So we can safely use the listener's queue.
26862 	 */
26863 	putnext(listener->tcp_rq, mp);
26864 }
26865 
26866 int
26867 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
26868     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
26869 {
26870 	tcp_t			*tcp;
26871 	conn_t 			*connp = (conn_t *)proto_handle;
26872 	int			error;
26873 	mblk_t			*stropt_mp;
26874 	mblk_t			*ordrel_mp;
26875 
26876 	tcp = connp->conn_tcp;
26877 
26878 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
26879 	    NULL);
26880 
26881 	/* Pre-allocate the T_ordrel_ind mblk. */
26882 	ASSERT(tcp->tcp_ordrel_mp == NULL);
26883 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
26884 	    STR_NOSIG, NULL);
26885 	ordrel_mp->b_datap->db_type = M_PROTO;
26886 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
26887 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
26888 
26889 	/*
26890 	 * Enter the squeue so that no new packets can come in
26891 	 */
26892 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
26893 	if (error != 0) {
26894 		/* failed to enter, free all the pre-allocated messages. */
26895 		freeb(stropt_mp);
26896 		freeb(ordrel_mp);
26897 		/*
26898 		 * We cannot process the eager, so at least send out a
26899 		 * RST so the peer can reconnect.
26900 		 */
26901 		if (tcp->tcp_listener != NULL) {
26902 			(void) tcp_eager_blowoff(tcp->tcp_listener,
26903 			    tcp->tcp_conn_req_seqnum);
26904 		}
26905 		return (ENOMEM);
26906 	}
26907 
26908 	/*
26909 	 * Both endpoints must be of the same type (either STREAMS or
26910 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
26911 	 * we have to unfuse.
26912 	 */
26913 	if (tcp->tcp_fused)
26914 		tcp_unfuse(tcp);
26915 
26916 	/*
26917 	 * No longer a direct socket
26918 	 */
26919 	connp->conn_flags &= ~IPCL_NONSTR;
26920 	tcp->tcp_ordrel_mp = ordrel_mp;
26921 
26922 	if (tcp->tcp_listener != NULL) {
26923 		/* The eager will deal with opts when accept() is called */
26924 		freeb(stropt_mp);
26925 		tcp_fallback_eager(tcp, direct_sockfs);
26926 	} else {
26927 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
26928 		    quiesced_cb);
26929 	}
26930 
26931 	/*
26932 	 * There should be atleast two ref's (IP + TCP)
26933 	 */
26934 	ASSERT(connp->conn_ref >= 2);
26935 	squeue_synch_exit(connp->conn_sqp, connp);
26936 
26937 	return (0);
26938 }
26939 
26940 /* ARGSUSED */
26941 static void
26942 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
26943 {
26944 	conn_t 	*connp = (conn_t *)arg;
26945 	tcp_t	*tcp = connp->conn_tcp;
26946 
26947 	freemsg(mp);
26948 
26949 	if (tcp->tcp_fused)
26950 		tcp_unfuse(tcp);
26951 
26952 	if (tcp_xmit_end(tcp) != 0) {
26953 		/*
26954 		 * We were crossing FINs and got a reset from
26955 		 * the other side. Just ignore it.
26956 		 */
26957 		if (tcp->tcp_debug) {
26958 			(void) strlog(TCP_MOD_ID, 0, 1,
26959 			    SL_ERROR|SL_TRACE,
26960 			    "tcp_shutdown_output() out of state %s",
26961 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
26962 		}
26963 	}
26964 }
26965 
26966 /* ARGSUSED */
26967 int
26968 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
26969 {
26970 	conn_t  *connp = (conn_t *)proto_handle;
26971 	tcp_t   *tcp = connp->conn_tcp;
26972 
26973 	ASSERT(connp->conn_upper_handle != NULL);
26974 
26975 	/* All Solaris components should pass a cred for this operation. */
26976 	ASSERT(cr != NULL);
26977 
26978 	/*
26979 	 * X/Open requires that we check the connected state.
26980 	 */
26981 	if (tcp->tcp_state < TCPS_SYN_SENT)
26982 		return (ENOTCONN);
26983 
26984 	/* shutdown the send side */
26985 	if (how != SHUT_RD) {
26986 		mblk_t *bp;
26987 
26988 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
26989 		CONN_INC_REF(connp);
26990 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
26991 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
26992 
26993 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
26994 		    SOCK_OPCTL_SHUT_SEND, 0);
26995 	}
26996 
26997 	/* shutdown the recv side */
26998 	if (how != SHUT_WR)
26999 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27000 		    SOCK_OPCTL_SHUT_RECV, 0);
27001 
27002 	return (0);
27003 }
27004 
27005 /*
27006  * SOP_LISTEN() calls into tcp_listen().
27007  */
27008 /* ARGSUSED */
27009 int
27010 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27011 {
27012 	conn_t	*connp = (conn_t *)proto_handle;
27013 	int 	error;
27014 	squeue_t *sqp = connp->conn_sqp;
27015 
27016 	ASSERT(connp->conn_upper_handle != NULL);
27017 
27018 	/* All Solaris components should pass a cred for this operation. */
27019 	ASSERT(cr != NULL);
27020 
27021 	error = squeue_synch_enter(sqp, connp, NULL);
27022 	if (error != 0) {
27023 		/* failed to enter */
27024 		return (ENOBUFS);
27025 	}
27026 
27027 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
27028 	if (error == 0) {
27029 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27030 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27031 	} else if (error < 0) {
27032 		if (error == -TOUTSTATE)
27033 			error = EINVAL;
27034 		else
27035 			error = proto_tlitosyserr(-error);
27036 	}
27037 	squeue_synch_exit(sqp, connp);
27038 	return (error);
27039 }
27040 
27041 static int
27042 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
27043     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
27044 {
27045 	tcp_t		*tcp = connp->conn_tcp;
27046 	int		error = 0;
27047 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27048 
27049 	/* All Solaris components should pass a cred for this operation. */
27050 	ASSERT(cr != NULL);
27051 
27052 	if (tcp->tcp_state >= TCPS_BOUND) {
27053 		if ((tcp->tcp_state == TCPS_BOUND ||
27054 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27055 			/*
27056 			 * Handle listen() increasing backlog.
27057 			 * This is more "liberal" then what the TPI spec
27058 			 * requires but is needed to avoid a t_unbind
27059 			 * when handling listen() since the port number
27060 			 * might be "stolen" between the unbind and bind.
27061 			 */
27062 			goto do_listen;
27063 		}
27064 		if (tcp->tcp_debug) {
27065 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27066 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27067 		}
27068 		return (-TOUTSTATE);
27069 	} else {
27070 		if (sa == NULL) {
27071 			sin6_t	addr;
27072 			sin_t *sin;
27073 			sin6_t *sin6;
27074 
27075 			ASSERT(IPCL_IS_NONSTR(connp));
27076 
27077 			/* Do an implicit bind: Request for a generic port. */
27078 			if (tcp->tcp_family == AF_INET) {
27079 				len = sizeof (sin_t);
27080 				sin = (sin_t *)&addr;
27081 				*sin = sin_null;
27082 				sin->sin_family = AF_INET;
27083 				tcp->tcp_ipversion = IPV4_VERSION;
27084 			} else {
27085 				ASSERT(tcp->tcp_family == AF_INET6);
27086 				len = sizeof (sin6_t);
27087 				sin6 = (sin6_t *)&addr;
27088 				*sin6 = sin6_null;
27089 				sin6->sin6_family = AF_INET6;
27090 				tcp->tcp_ipversion = IPV6_VERSION;
27091 			}
27092 			sa = (struct sockaddr *)&addr;
27093 		}
27094 
27095 		error = tcp_bind_check(connp, sa, len, cr,
27096 		    bind_to_req_port_only);
27097 		if (error)
27098 			return (error);
27099 		/* Fall through and do the fanout insertion */
27100 	}
27101 
27102 do_listen:
27103 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27104 	tcp->tcp_conn_req_max = backlog;
27105 	if (tcp->tcp_conn_req_max) {
27106 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27107 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27108 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27109 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27110 		/*
27111 		 * If this is a listener, do not reset the eager list
27112 		 * and other stuffs.  Note that we don't check if the
27113 		 * existing eager list meets the new tcp_conn_req_max
27114 		 * requirement.
27115 		 */
27116 		if (tcp->tcp_state != TCPS_LISTEN) {
27117 			tcp->tcp_state = TCPS_LISTEN;
27118 			/* Initialize the chain. Don't need the eager_lock */
27119 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27120 			tcp->tcp_eager_next_drop_q0 = tcp;
27121 			tcp->tcp_eager_prev_drop_q0 = tcp;
27122 			tcp->tcp_second_ctimer_threshold =
27123 			    tcps->tcps_ip_abort_linterval;
27124 		}
27125 	}
27126 
27127 	/*
27128 	 * We can call ip_bind directly, the processing continues
27129 	 * in tcp_post_ip_bind().
27130 	 *
27131 	 * We need to make sure that the conn_recv is set to a non-null
27132 	 * value before we insert the conn into the classifier table.
27133 	 * This is to avoid a race with an incoming packet which does an
27134 	 * ipcl_classify().
27135 	 */
27136 	connp->conn_recv = tcp_conn_request;
27137 	if (tcp->tcp_family == AF_INET) {
27138 		error = ip_proto_bind_laddr_v4(connp, NULL,
27139 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27140 	} else {
27141 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27142 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27143 	}
27144 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27145 }
27146 
27147 void
27148 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27149 {
27150 	conn_t  *connp = (conn_t *)proto_handle;
27151 	tcp_t	*tcp = connp->conn_tcp;
27152 	mblk_t *mp;
27153 	int error;
27154 
27155 	ASSERT(connp->conn_upper_handle != NULL);
27156 
27157 	/*
27158 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
27159 	 * is currently running.
27160 	 */
27161 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27162 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
27163 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
27164 		return;
27165 	}
27166 	tcp->tcp_rsrv_mp = NULL;
27167 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27168 
27169 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
27170 	ASSERT(error == 0);
27171 
27172 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27173 	tcp->tcp_rsrv_mp = mp;
27174 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27175 
27176 	if (tcp->tcp_fused) {
27177 		tcp_fuse_backenable(tcp);
27178 	} else {
27179 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27180 		/*
27181 		 * Send back a window update immediately if TCP is above
27182 		 * ESTABLISHED state and the increase of the rcv window
27183 		 * that the other side knows is at least 1 MSS after flow
27184 		 * control is lifted.
27185 		 */
27186 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27187 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
27188 			tcp_xmit_ctl(NULL, tcp,
27189 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27190 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27191 		}
27192 	}
27193 
27194 	squeue_synch_exit(connp->conn_sqp, connp);
27195 }
27196 
27197 /* ARGSUSED */
27198 int
27199 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27200     int mode, int32_t *rvalp, cred_t *cr)
27201 {
27202 	conn_t  	*connp = (conn_t *)proto_handle;
27203 	int		error;
27204 
27205 	ASSERT(connp->conn_upper_handle != NULL);
27206 
27207 	/* All Solaris components should pass a cred for this operation. */
27208 	ASSERT(cr != NULL);
27209 
27210 	switch (cmd) {
27211 		case ND_SET:
27212 		case ND_GET:
27213 		case TCP_IOC_DEFAULT_Q:
27214 		case _SIOCSOCKFALLBACK:
27215 		case TCP_IOC_ABORT_CONN:
27216 		case TI_GETPEERNAME:
27217 		case TI_GETMYNAME:
27218 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27219 			    cmd));
27220 			error = EINVAL;
27221 			break;
27222 		default:
27223 			/*
27224 			 * Pass on to IP using helper stream
27225 			 */
27226 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
27227 			    cmd, arg, mode, cr, rvalp);
27228 			break;
27229 	}
27230 	return (error);
27231 }
27232 
27233 sock_downcalls_t sock_tcp_downcalls = {
27234 	tcp_activate,
27235 	tcp_accept,
27236 	tcp_bind,
27237 	tcp_listen,
27238 	tcp_connect,
27239 	tcp_getpeername,
27240 	tcp_getsockname,
27241 	tcp_getsockopt,
27242 	tcp_setsockopt,
27243 	tcp_sendmsg,
27244 	NULL,
27245 	NULL,
27246 	NULL,
27247 	tcp_shutdown,
27248 	tcp_clr_flowctrl,
27249 	tcp_ioctl,
27250 	tcp_close,
27251 };
27252